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
Rajeshkumar90/ansible-modules-extras
univention/udm_user.py
27
21241
#!/usr/bin/python # -*- coding: UTF-8 -*- # Copyright (c) 2016, Adfinis SyGroup AG # Tobias Rueetschi <tobias.ruetschi@adfinis-sygroup.ch> # # 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 datetime import date import crypt from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.univention_umc import ( umc_module_for_add, umc_module_for_edit, ldap_search, base_dn, ) from dateutil.relativedelta import relativedelta ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: udm_user version_added: "2.2" author: "Tobias Rueetschi (@2-B)" short_description: Manage posix users on a univention corporate server description: - "This module allows to manage posix users on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it." requirements: - Python >= 2.6 options: state: required: false default: "present" choices: [ present, absent ] description: - Whether the user is present or not. username: required: true description: - User name aliases: ['name'] firstname: required: false description: - First name. Required if C(state=present). lastname: required: false description: - Last name. Required if C(state=present). password: required: false default: None description: - Password. Required if C(state=present). birthday: required: false default: None description: - Birthday city: required: false default: None description: - City of users business address. country: required: false default: None description: - Country of users business address. department_number: required: false default: None description: - Department number of users business address. aliases: [ departmentNumber ] description: required: false default: None description: - Description (not gecos) display_name: required: false default: None description: - Display name (not gecos) aliases: [ displayName ] email: required: false default: [''] description: - A list of e-mail addresses. employee_number: required: false default: None description: - Employee number aliases: [ employeeNumber ] employee_type: required: false default: None description: - Employee type aliases: [ employeeType ] gecos: required: false default: None description: - GECOS groups: required: false default: [] description: - "POSIX groups, the LDAP DNs of the groups will be found with the LDAP filter for each group as $GROUP: C((&(objectClass=posixGroup)(cn=$GROUP)))." home_share: required: false default: None description: - "Home NFS share. Must be a LDAP DN, e.g. C(cn=home,cn=shares,ou=school,dc=example,dc=com)." aliases: [ homeShare ] home_share_path: required: false default: None description: - Path to home NFS share, inside the homeShare. aliases: [ homeSharePath ] home_telephone_number: required: false default: [] description: - List of private telephone numbers. aliases: [ homeTelephoneNumber ] homedrive: required: false default: None description: - Windows home drive, e.g. C("H:"). mail_alternative_address: required: false default: [] description: - List of alternative e-mail addresses. aliases: [ mailAlternativeAddress ] mail_home_server: required: false default: None description: - FQDN of mail server aliases: [ mailHomeServer ] mail_primary_address: required: false default: None description: - Primary e-mail address aliases: [ mailPrimaryAddress ] mobile_telephone_number: required: false default: [] description: - Mobile phone number aliases: [ mobileTelephoneNumber ] organisation: required: false default: None description: - Organisation override_pw_history: required: false default: False description: - Override password history aliases: [ overridePWHistory ] override_pw_length: required: false default: False description: - Override password check aliases: [ overridePWLength ] pager_telephonenumber: required: false default: [] description: - List of pager telephone numbers. aliases: [ pagerTelephonenumber ] phone: required: false default: [] description: - List of telephone numbers. postcode: required: false default: None description: - Postal code of users business address. primary_group: required: false default: cn=Domain Users,cn=groups,$LDAP_BASE_DN description: - Primary group. This must be the group LDAP DN. aliases: [ primaryGroup ] profilepath: required: false default: None description: - Windows profile directory pwd_change_next_login: required: false default: None choices: [ '0', '1' ] description: - Change password on next login. aliases: [ pwdChangeNextLogin ] room_number: required: false default: None description: - Room number of users business address. aliases: [ roomNumber ] samba_privileges: required: false default: [] description: - "Samba privilege, like allow printer administration, do domain join." aliases: [ sambaPrivileges ] samba_user_workstations: required: false default: [] description: - Allow the authentication only on this Microsoft Windows host. aliases: [ sambaUserWorkstations ] sambahome: required: false default: None description: - Windows home path, e.g. C('\\\\$FQDN\\$USERNAME'). scriptpath: required: false default: None description: - Windows logon script. secretary: required: false default: [] description: - A list of superiors as LDAP DNs. serviceprovider: required: false default: [''] description: - Enable user for the following service providers. shell: required: false default: '/bin/bash' description: - Login shell street: required: false default: None description: - Street of users business address. title: required: false default: None description: - Title, e.g. C(Prof.). unixhome: required: false default: '/home/$USERNAME' description: - Unix home directory userexpiry: required: false default: Today + 1 year description: - Account expiry date, e.g. C(1999-12-31). position: required: false default: '' description: - "Define the whole position of users object inside the LDAP tree, e.g. C(cn=employee,cn=users,ou=school,dc=example,dc=com)." ou: required: false default: '' description: - "Organizational Unit inside the LDAP Base DN, e.g. C(school) for LDAP OU C(ou=school,dc=example,dc=com)." subpath: required: false default: 'cn=users' description: - "LDAP subpath inside the organizational unit, e.g. C(cn=teachers,cn=users) for LDAP container C(cn=teachers,cn=users,dc=example,dc=com)." ''' EXAMPLES = ''' # Create a user on a UCS - udm_user: name: FooBar password: secure_password firstname: Foo lastname: Bar # Create a user with the DN # C(uid=foo,cn=teachers,cn=users,ou=school,dc=school,dc=example,dc=com) - udm_user: name: foo password: secure_password firstname: Foo lastname: Bar ou: school subpath: 'cn=teachers,cn=users' # or define the position - udm_user: name: foo password: secure_password firstname: Foo lastname: Bar position: 'cn=teachers,cn=users,ou=school,dc=school,dc=example,dc=com' ''' RETURN = '''# ''' def main(): expiry = date.strftime(date.today() + relativedelta(years=1), "%Y-%m-%d") module = AnsibleModule( argument_spec = dict( birthday = dict(default=None, type='str'), city = dict(default=None, type='str'), country = dict(default=None, type='str'), department_number = dict(default=None, type='str', aliases=['departmentNumber']), description = dict(default=None, type='str'), display_name = dict(default=None, type='str', aliases=['displayName']), email = dict(default=[''], type='list'), employee_number = dict(default=None, type='str', aliases=['employeeNumber']), employee_type = dict(default=None, type='str', aliases=['employeeType']), firstname = dict(default=None, type='str'), gecos = dict(default=None, type='str'), groups = dict(default=[], type='list'), home_share = dict(default=None, type='str', aliases=['homeShare']), home_share_path = dict(default=None, type='str', aliases=['homeSharePath']), home_telephone_number = dict(default=[], type='list', aliases=['homeTelephoneNumber']), homedrive = dict(default=None, type='str'), lastname = dict(default=None, type='str'), mail_alternative_address= dict(default=[], type='list', aliases=['mailAlternativeAddress']), mail_home_server = dict(default=None, type='str', aliases=['mailHomeServer']), mail_primary_address = dict(default=None, type='str', aliases=['mailPrimaryAddress']), mobile_telephone_number = dict(default=[], type='list', aliases=['mobileTelephoneNumber']), organisation = dict(default=None, type='str'), overridePWHistory = dict(default=False, type='bool', aliases=['override_pw_history']), overridePWLength = dict(default=False, type='bool', aliases=['override_pw_length']), pager_telephonenumber = dict(default=[], type='list', aliases=['pagerTelephonenumber']), password = dict(default=None, type='str', no_log=True), phone = dict(default=[], type='list'), postcode = dict(default=None, type='str'), primary_group = dict(default=None, type='str', aliases=['primaryGroup']), profilepath = dict(default=None, type='str'), pwd_change_next_login = dict(default=None, type='str', choices=['0', '1'], aliases=['pwdChangeNextLogin']), room_number = dict(default=None, type='str', aliases=['roomNumber']), samba_privileges = dict(default=[], type='list', aliases=['sambaPrivileges']), samba_user_workstations = dict(default=[], type='list', aliases=['sambaUserWorkstations']), sambahome = dict(default=None, type='str'), scriptpath = dict(default=None, type='str'), secretary = dict(default=[], type='list'), serviceprovider = dict(default=[''], type='list'), shell = dict(default='/bin/bash', type='str'), street = dict(default=None, type='str'), title = dict(default=None, type='str'), unixhome = dict(default=None, type='str'), userexpiry = dict(default=expiry, type='str'), username = dict(required=True, aliases=['name'], type='str'), position = dict(default='', type='str'), ou = dict(default='', type='str'), subpath = dict(default='cn=users', type='str'), state = dict(default='present', choices=['present', 'absent'], type='str') ), supports_check_mode=True, required_if = ([ ('state', 'present', ['firstname', 'lastname', 'password']) ]) ) username = module.params['username'] position = module.params['position'] ou = module.params['ou'] subpath = module.params['subpath'] state = module.params['state'] changed = False users = list(ldap_search( '(&(objectClass=posixAccount)(uid={}))'.format(username), attr=['uid'] )) if position != '': container = position else: if ou != '': ou = 'ou={},'.format(ou) if subpath != '': subpath = '{},'.format(subpath) container = '{}{}{}'.format(subpath, ou, base_dn()) user_dn = 'uid={},{}'.format(username, container) exists = bool(len(users)) if state == 'present': try: if not exists: obj = umc_module_for_add('users/user', container) else: obj = umc_module_for_edit('users/user', user_dn) if module.params['displayName'] is None: module.params['displayName'] = '{} {}'.format( module.params['firstname'], module.params['lastname'] ) if module.params['unixhome'] is None: module.params['unixhome'] = '/home/{}'.format( module.params['username'] ) for k in obj.keys(): if (k != 'password' and k != 'groups' and k != 'overridePWHistory' and k in module.params and module.params[k] is not None): obj[k] = module.params[k] # handle some special values obj['e-mail'] = module.params['email'] password = module.params['password'] if obj['password'] is None: obj['password'] = password else: old_password = obj['password'].split('}', 2)[1] if crypt.crypt(password, old_password) != old_password: obj['overridePWHistory'] = module.params['overridePWHistory'] obj['overridePWLength'] = module.params['overridePWLength'] obj['password'] = password diff = obj.diff() if exists: for k in obj.keys(): if obj.hasChanged(k): changed = True else: changed = True if not module.check_mode: if not exists: obj.create() elif changed: obj.modify() except: module.fail_json( msg="Creating/editing user {} in {} failed".format( username, container ) ) try: groups = module.params['groups'] if groups: filter = '(&(objectClass=posixGroup)(|(cn={})))'.format( ')(cn='.join(groups) ) group_dns = list(ldap_search(filter, attr=['dn'])) for dn in group_dns: grp = umc_module_for_edit('groups/group', dn[0]) if user_dn not in grp['users']: grp['users'].append(user_dn) if not module.check_mode: grp.modify() changed = True except: module.fail_json( msg="Adding groups to user {} failed".format(username) ) if state == 'absent' and exists: try: obj = umc_module_for_edit('users/user', user_dn) if not module.check_mode: obj.remove() changed = True except: module.fail_json( msg="Removing user {} failed".format(username) ) module.exit_json( changed=changed, username=username, diff=diff, container=container ) if __name__ == '__main__': main()
gpl-3.0
viniciusgama/blog_gae
django/contrib/markup/tests.py
245
3155
# Quick tests for the markup templatetags (django.contrib.markup) import re from django.template import Template, Context, add_to_builtins from django.utils import unittest from django.utils.html import escape add_to_builtins('django.contrib.markup.templatetags.markup') try: import textile except ImportError: textile = None try: import markdown except ImportError: markdown = None try: import docutils except ImportError: docutils = None class Templates(unittest.TestCase): textile_content = """Paragraph 1 Paragraph 2 with "quotes" and @code@""" markdown_content = """Paragraph 1 ## An h2""" rest_content = """Paragraph 1 Paragraph 2 with a link_ .. _link: http://www.example.com/""" @unittest.skipUnless(textile, 'texttile not installed') def test_textile(self): t = Template("{{ textile_content|textile }}") rendered = t.render(Context({'textile_content':self.textile_content})).strip() self.assertEqual(rendered.replace('\t', ''), """<p>Paragraph 1</p> <p>Paragraph 2 with &#8220;quotes&#8221; and <code>code</code></p>""") @unittest.skipIf(textile, 'texttile is installed') def test_no_textile(self): t = Template("{{ textile_content|textile }}") rendered = t.render(Context({'textile_content':self.textile_content})).strip() self.assertEqual(rendered, escape(self.textile_content)) @unittest.skipUnless(markdown, 'markdown not installed') def test_markdown(self): t = Template("{{ markdown_content|markdown }}") rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() pattern = re.compile("""<p>Paragraph 1\s*</p>\s*<h2>\s*An h2</h2>""") self.assertTrue(pattern.match(rendered)) @unittest.skipIf(markdown, 'markdown is installed') def test_no_markdown(self): t = Template("{{ markdown_content|markdown }}") rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() self.assertEqual(rendered, self.markdown_content) @unittest.skipUnless(docutils, 'docutils not installed') def test_docutils(self): t = Template("{{ rest_content|restructuredtext }}") rendered = t.render(Context({'rest_content':self.rest_content})).strip() # Different versions of docutils return slightly different HTML try: # Docutils v0.4 and earlier self.assertEqual(rendered, """<p>Paragraph 1</p> <p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""") except AssertionError, e: # Docutils from SVN (which will become 0.5) self.assertEqual(rendered, """<p>Paragraph 1</p> <p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""") @unittest.skipIf(docutils, 'docutils is installed') def test_no_docutils(self): t = Template("{{ rest_content|restructuredtext }}") rendered = t.render(Context({'rest_content':self.rest_content})).strip() self.assertEqual(rendered, self.rest_content) if __name__ == '__main__': unittest.main()
bsd-3-clause
benjixx/ansible
lib/ansible/utils/module_docs_fragments/rackspace.py
232
4190
# (c) 2014, Matt Martz <matt@sivel.net> # # 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/>. class ModuleDocFragment(object): # Standard Rackspace only documentation fragment DOCUMENTATION = """ options: api_key: description: - Rackspace API key (overrides I(credentials)) aliases: - password credentials: description: - File to find the Rackspace credentials in (ignored if I(api_key) and I(username) are provided) default: null aliases: - creds_file env: description: - Environment as configured in ~/.pyrax.cfg, see U(https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#pyrax-configuration) version_added: 1.5 region: description: - Region to create an instance in default: DFW username: description: - Rackspace username (overrides I(credentials)) verify_ssl: description: - Whether or not to require SSL validation of API endpoints version_added: 1.5 requirements: - "python >= 2.6" - pyrax notes: - The following environment variables can be used, C(RAX_USERNAME), C(RAX_API_KEY), C(RAX_CREDS_FILE), C(RAX_CREDENTIALS), C(RAX_REGION). - C(RAX_CREDENTIALS) and C(RAX_CREDS_FILE) points to a credentials file appropriate for pyrax. See U(https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating) - C(RAX_USERNAME) and C(RAX_API_KEY) obviate the use of a credentials file - C(RAX_REGION) defines a Rackspace Public Cloud region (DFW, ORD, LON, ...) """ # Documentation fragment including attributes to enable communication # of other OpenStack clouds. Not all rax modules support this. OPENSTACK = """ options: api_key: description: - Rackspace API key (overrides I(credentials)) aliases: - password auth_endpoint: description: - The URI of the authentication service default: https://identity.api.rackspacecloud.com/v2.0/ version_added: 1.5 credentials: description: - File to find the Rackspace credentials in (ignored if I(api_key) and I(username) are provided) default: null aliases: - creds_file env: description: - Environment as configured in ~/.pyrax.cfg, see U(https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#pyrax-configuration) version_added: 1.5 identity_type: description: - Authentication machanism to use, such as rackspace or keystone default: rackspace version_added: 1.5 region: description: - Region to create an instance in default: DFW tenant_id: description: - The tenant ID used for authentication version_added: 1.5 tenant_name: description: - The tenant name used for authentication version_added: 1.5 username: description: - Rackspace username (overrides I(credentials)) verify_ssl: description: - Whether or not to require SSL validation of API endpoints version_added: 1.5 requirements: - "python >= 2.6" - pyrax notes: - The following environment variables can be used, C(RAX_USERNAME), C(RAX_API_KEY), C(RAX_CREDS_FILE), C(RAX_CREDENTIALS), C(RAX_REGION). - C(RAX_CREDENTIALS) and C(RAX_CREDS_FILE) points to a credentials file appropriate for pyrax. See U(https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating) - C(RAX_USERNAME) and C(RAX_API_KEY) obviate the use of a credentials file - C(RAX_REGION) defines a Rackspace Public Cloud region (DFW, ORD, LON, ...) """
gpl-3.0
YihaoLu/statsmodels
statsmodels/compat/tests/test_itercompat.py
33
1222
# -*- coding: utf-8 -*- """ Created on Wed Feb 29 10:34:00 2012 Author: Josef Perktold """ from statsmodels.compat import lrange, zip_longest, combinations from numpy.testing import assert_ def test_zip_longest(): lili = [['a0', 'b0', 'c0', 'd0'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3'], ['a4', 'b4']] transposed = [('a0', 'a1', 'a2', 'a3', 'a4'), ('b0', 'b1', 'b2', 'b3', 'b4'), ('c0', 'c1', 'c2', 'c3', None), ('d0', None, 'd2', 'd3', None)] assert_(list(zip_longest(*lili)) == transposed, '%r not equal %r' % ( zip_longest(*lili), transposed)) def test_combinations(): actual = list(combinations('ABCD', 2)) desired = [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')] assert_(actual == desired, '%r not equal %r' % (actual, desired)) actual = list(combinations(lrange(4), 3)) desired = [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)] assert_(actual == desired, '%r not equal %r' % (actual, desired)) if __name__ == '__main__': test_zip_longest() test_combinations()
bsd-3-clause
cloudera/hue
desktop/core/ext-py/dnspython-1.15.0/dns/rdataclass.py
16
3258
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Rdata Classes. @var _by_text: The rdata class textual name to value mapping @type _by_text: dict @var _by_value: The rdata class value to textual name mapping @type _by_value: dict @var _metaclasses: If an rdataclass is a metaclass, there will be a mapping whose key is the rdatatype value and whose value is True in this dictionary. @type _metaclasses: dict""" import re import dns.exception RESERVED0 = 0 IN = 1 CH = 3 HS = 4 NONE = 254 ANY = 255 _by_text = { 'RESERVED0': RESERVED0, 'IN': IN, 'CH': CH, 'HS': HS, 'NONE': NONE, 'ANY': ANY } # We construct the inverse mapping programmatically to ensure that we # cannot make any mistakes (e.g. omissions, cut-and-paste errors) that # would cause the mapping not to be true inverse. _by_value = dict((y, x) for x, y in _by_text.items()) # Now that we've built the inverse map, we can add class aliases to # the _by_text mapping. _by_text.update({ 'INTERNET': IN, 'CHAOS': CH, 'HESIOD': HS }) _metaclasses = { NONE: True, ANY: True } _unknown_class_pattern = re.compile('CLASS([0-9]+)$', re.I) class UnknownRdataclass(dns.exception.DNSException): """A DNS class is unknown.""" def from_text(text): """Convert text into a DNS rdata class value. @param text: the text @type text: string @rtype: int @raises dns.rdataclass.UnknownRdataclass: the class is unknown @raises ValueError: the rdata class value is not >= 0 and <= 65535 """ value = _by_text.get(text.upper()) if value is None: match = _unknown_class_pattern.match(text) if match is None: raise UnknownRdataclass value = int(match.group(1)) if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 65535") return value def to_text(value): """Convert a DNS rdata class to text. @param value: the rdata class value @type value: int @rtype: string @raises ValueError: the rdata class value is not >= 0 and <= 65535 """ if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 65535") text = _by_value.get(value) if text is None: text = 'CLASS' + repr(value) return text def is_metaclass(rdclass): """True if the class is a metaclass. @param rdclass: the rdata class @type rdclass: int @rtype: bool""" if rdclass in _metaclasses: return True return False
apache-2.0
misgeatgit/opencog
opencog/python/pln_old/examples/temporal/temporal_example.py
28
1863
""" Demo to demonstrate use of temporal reasoning pipeline 1. RelEx and RelEx2Logic process natural language sentences 2. PLN performs inferences using AI on output atoms """ from __future__ import print_function from opencog.atomspace import types, AtomSpace, TruthValue from opencog.scheme_wrapper import load_scm, scheme_eval, scheme_eval_h, __init__ from pln.chainers import Chainer from pln.rules.temporal_rules import create_temporal_rules __author__ = 'Sebastian Ruder' num_steps = 100 print_starting_contents = True coreTypes = "opencog/scm/core_types.scm" utilities = "opencog/scm/utilities.scm" timeLinks = "opencog/spacetime/spacetime_types.scm" data = "tests/python/test_pln/scm_disabled/temporal/temporalToyExample.scm" # data = "opencog/python/pln_old/examples/temporal/temporal-r2l-input.scm" # initialize atomspace atomspace = AtomSpace() __init__(atomspace) for item in [coreTypes, utilities, timeLinks, data]: load_scm(atomspace, item) # initialize chainer chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True, delete_temporary_variables=True) for rule in create_temporal_rules(chainer): chainer.add_rule(rule) if print_starting_contents: print('AtomSpace starting contents:') atomspace.print_list() outputs_produced = 0 for i in range(0, num_steps): result = chainer.forward_step() output = None input = None rule = None if result is not None: atomspace_string = "" (rule, input, output) = result outputs_produced += 1 print("\n----- [Output # {0}] -----".format(outputs_produced)) for j in output: print("-- Output:\n{0}".format(j)) print("-- using production rule: {0}".format(rule.name)) print("\n-- based on this input:\n{0}".format(input))
agpl-3.0
vguerci/Deluge.app
deluge/core/alertmanager.py
4
5064
# # alertmanager.py # # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # # Deluge is free software. # # You may 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. # # deluge 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 deluge. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the file(s), # but you are not obligated to do so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. # """ The AlertManager handles all the libtorrent alerts. This should typically only be used by the Core. Plugins should utilize the `:mod:EventManager` for similar functionality. """ from twisted.internet import reactor import deluge.component as component from deluge._libtorrent import lt from deluge.log import LOG as log class AlertManager(component.Component): def __init__(self): log.debug("AlertManager initialized..") component.Component.__init__(self, "AlertManager", interval=0.05) self.session = component.get("Core").session self.session.set_alert_mask( lt.alert.category_t.error_notification | lt.alert.category_t.port_mapping_notification | lt.alert.category_t.storage_notification | lt.alert.category_t.tracker_notification | lt.alert.category_t.status_notification | lt.alert.category_t.ip_block_notification | lt.alert.category_t.performance_warning) # handlers is a dictionary of lists {"alert_type": [handler1,h2,..]} self.handlers = {} self.delayed_calls = [] def update(self): self.delayed_calls = [dc for dc in self.delayed_calls if dc.active()] self.handle_alerts() def stop(self): for dc in self.delayed_calls: dc.cancel() self.delayed_calls = [] def register_handler(self, alert_type, handler): """ Registers a function that will be called when 'alert_type' is pop'd in handle_alerts. The handler function should look like: handler(alert) Where 'alert' is the actual alert object from libtorrent. :param alert_type: str, this is string representation of the alert name :param handler: func(alert), the function to be called when the alert is raised """ if alert_type not in self.handlers: # There is no entry for this alert type yet, so lets make it with an # empty list. self.handlers[alert_type] = [] # Append the handler to the list in the handlers dictionary self.handlers[alert_type].append(handler) log.debug("Registered handler for alert %s", alert_type) def deregister_handler(self, handler): """ De-registers the `:param:handler` function from all alert types. :param handler: func, the handler function to deregister """ # Iterate through all handlers and remove 'handler' where found for (key, value) in self.handlers.items(): if handler in value: # Handler is in this alert type list value.remove(handler) def handle_alerts(self, wait=False): """ Pops all libtorrent alerts in the session queue and handles them appropriately. :param wait: bool, if True then the handler functions will be run right away and waited to return before processing the next alert """ alert = self.session.pop_alert() # Loop through all alerts in the queue while alert is not None: alert_type = type(alert).__name__ # Display the alert message log.debug("%s: %s", alert_type, alert.message()) # Call any handlers for this alert type if alert_type in self.handlers: for handler in self.handlers[alert_type]: if not wait: self.delayed_calls.append(reactor.callLater(0, handler, alert)) else: handler(alert) alert = self.session.pop_alert()
gpl-3.0
Tuxemon/Tuxemon
tuxemon/event/actions/clear_variable.py
1
1565
# # Tuxemon # Copyright (c) 2020 William Edwards <shadowapex@gmail.com>, # Benjamin Bean <superman2k5@gmail.com> # # This file is part of Tuxemon # # 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/>. # # Contributor(s): # # Adam Chevalier <chevalierAdam2@gmail.com> from __future__ import annotations from tuxemon.event.eventaction import EventAction import logging from typing import NamedTuple, final logger = logging.getLogger(__name__) class ClearVariableActionParameters(NamedTuple): variable: str # noinspection PyAttributeOutsideInit @final class ClearVariableAction(EventAction[ClearVariableActionParameters]): """Clears the value of var from the game. Valid Parameters: string variable_name """ name = "clear_variable" param_class = ClearVariableActionParameters def start(self) -> None: player = self.session.player key = self.parameters.variable player.game_variables.pop(key, None)
gpl-3.0
lijoantony/django-oscar
src/oscar/apps/customer/auth_backends.py
55
2680
import warnings from django.contrib.auth.backends import ModelBackend from django.core.exceptions import ImproperlyConfigured from oscar.apps.customer.utils import normalise_email from oscar.core.compat import get_user_model User = get_user_model() if hasattr(User, 'REQUIRED_FIELDS'): if not (User.USERNAME_FIELD == 'email' or 'email' in User.REQUIRED_FIELDS): raise ImproperlyConfigured( "EmailBackend: Your User model must have an email" " field with blank=False") class EmailBackend(ModelBackend): """ Custom auth backend that uses an email address and password For this to work, the User model must have an 'email' field """ def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if 'username' not in kwargs or kwargs['username'] is None: return None clean_email = normalise_email(kwargs['username']) else: clean_email = normalise_email(email) # Check if we're dealing with an email address if '@' not in clean_email: return None # Since Django doesn't enforce emails to be unique, we look for all # matching users and try to authenticate them all. Note that we # intentionally allow multiple users with the same email address # (has been a requirement in larger system deployments), # we just enforce that they don't share the same password. # We make a case-insensitive match when looking for emails. matching_users = User.objects.filter(email__iexact=clean_email) authenticated_users = [ user for user in matching_users if user.check_password(password)] if len(authenticated_users) == 1: # Happy path return authenticated_users[0] elif len(authenticated_users) > 1: # This is the problem scenario where we have multiple users with # the same email address AND password. We can't safely authenticate # either. raise User.MultipleObjectsReturned( "There are multiple users with the given email address and " "password") return None # Deprecated since Oscar 1.0 because of the spelling. class Emailbackend(EmailBackend): def __init__(self): warnings.warn( "Oscar's auth backend EmailBackend has been renamed in Oscar 1.0 " " and you're using the old name of Emailbackend. Please rename " " all references; most likely in the AUTH_BACKENDS setting.", DeprecationWarning) super(Emailbackend, self).__init__()
bsd-3-clause
littlejo/Libreosteo
winserver.py
1
8114
# This file is part of Libreosteo. # # Libreosteo 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. # # Libreosteo 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 Libreosteo. If not, see <http://www.gnu.org/licenses/>. """ Requires Mark Hammond's pywin32 package. """ # Python stdlib imports import sys import logging import os, os.path if getattr(sys, 'frozen', False): # frozen dir = os.path.dirname(sys.executable) sys.path.append(dir) os.environ['PATH'] = (os.environ['PATH']+";").join(p+";" for p in sys.path) # Win32 service imports import win32serviceutil import win32service, win32api import servicemanager # Third-party imports import cherrypy import patch import server class LibreosteoService(win32serviceutil.ServiceFramework): """Libreosteo NT Service.""" _svc_name_ = "LibreosteoService" _svc_display_name_ = "Libreosteo Service" def log(self, msg): servicemanager.LogInfoMsg(str(msg)) def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) try: self.log("Create the Libreosteo server") config = server.configure() _srvr = server.Server(config) # in practice, you will want to specify a value for # log.error_file below or in your config file. If you # use a config file, be sure to use an absolute path to # it, as you can't be assured what path your service # will run in. self.log("Configure the server") cherrypy.config.update({ 'global':{ 'log.screen': False, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None, 'log.error_file' : os.path.join(_srvr.base_dir, 'libreosteo_error.log'), 'tools.log_tracebacks.on' : True, 'log.access_file' : os.path.join(_srvr.base_dir, 'libreosteo_access.log'), 'server.socket_port': config["server_port"], 'server.socket_host': '0.0.0.0', } }) self.ReportServiceStatus(win32service.SERVICE_RUNNING) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'') ) self.log("Run the service Libreosteo") _srvr.run() except Exception as e: s = str(e); self.log('Exception : %s' % s) self.SvcStop() def SvcStop(self): self.log("Stopping service") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) cherrypy.engine.exit() self.ReportServiceStatus(win32service.SERVICE_STOPPED) # very important for use with py2exe # otherwise the Service Controller never knows that it is stopped ! self.log("Service stopped") if __name__ == '__main__': if getattr(sys, 'frozen', False): # frozen DATA_FOLDER = os.path.dirname(sys.executable) else: # unfrozen DATA_FOLDER = os.path.dirname(os.path.realpath(__file__)) LOG_CONF = { 'version': 1, 'formatters': { 'void': { 'format': '' }, 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': { 'default': { 'level':'INFO', 'class':'logging.handlers.RotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(DATA_FOLDER, 'default.log'), 'maxBytes': 10485760, 'backupCount': 20, 'encoding': 'utf8' }, 'cherrypy_console': { 'level':'INFO', 'class':'logging.handlers.RotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(DATA_FOLDER, 'console.log'), 'maxBytes': 10485760, 'backupCount': 20, 'encoding': 'utf8' }, 'cherrypy_access': { 'level':'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(DATA_FOLDER, 'access.log'), 'maxBytes': 10485760, 'backupCount': 20, 'encoding': 'utf8' }, 'cherrypy_error': { 'level':'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(DATA_FOLDER, 'errors.log'), 'maxBytes': 10485760, 'backupCount': 20, 'encoding': 'utf8' }, }, 'loggers': { 'django.utils.translation': { 'handlers': ['default'], 'level': 'INFO' }, '': { 'handlers': ['default'], 'level': 'INFO' }, 'root': { 'handlers': ['default'], 'level': 'INFO' }, 'db': { 'handlers': ['default'], 'level': 'INFO' , 'propagate': True }, 'cherrypy.access': { 'handlers': ['cherrypy_access'], 'level': 'INFO', 'propagate': True }, 'cherrypy.error': { 'handlers': ['cherrypy_console', 'cherrypy_error'], 'level': 'INFO', 'propagate': True }, 'libreosteoweb.api' : { 'handlers': ['cherrypy_console', 'default'], 'level': 'INFO', 'propagate': True }, 'libreosteo' : { 'handlers': ['cherrypy_console', 'default'], 'level': 'INFO', 'propagate': True }, 'Libreosteo' : { 'handlers': ['cherrypy_console', 'default'], 'level': 'INFO', 'propagate': True }, } } logging.config.dictConfig(LOG_CONF) os.chdir(DATA_FOLDER) logging.info(os.getcwd()) logger = logging.getLogger(__name__) logger.info("Frozen with attribute value %s" % (getattr(sys, 'frozen', False))) if len(sys.argv) == 1: logging.info("Start service") logging.info("Handle starting of the service") try: servicemanager.Initialize() servicemanager.PrepareToHostSingle(LibreosteoService) servicemanager.StartServiceCtrlDispatcher() except Exception as e: logging.exception("Exception when starting service") else: logging.info("Start Controller") logging.info("Handle command line on service manager") try: win32serviceutil.HandleCommandLine(LibreosteoService) except Exception as e: logging.exception("Exception when starting service")
gpl-3.0
blackzw/openwrt_sdk_dev1
staging_dir/host/lib/python2.7/pydoc_data/topics.py
35
407675
# Autogenerated by Sphinx on Thu Feb 23 15:17:35 2012 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\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 is recursively defined as\nfollows.\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\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`` statement in the\n current code block: the name is bound to the object in the current\n local namespace.\n\n * Otherwise: the name is bound to the object in the current global\n namespace.\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 a plain integer. If it is negative, the\n sequence\'s length is added to it. The resulting value must be a\n nonnegative integer less than the sequence\'s length, and the\n sequence is asked to assign the assigned object to its item with\n that index. If the index is out of range, ``IndexError`` is raised\n (assignment to a subscripted sequence cannot add new items to a\n 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* 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 (small) integers. If either\n bound is negative, the sequence\'s length is added to it. The\n resulting bounds are clipped to lie between zero and the sequence\'s\n length, inclusive. Finally, the sequence object is asked to replace\n the slice with the items of the assigned sequence. The length of\n the 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\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 literals and various numeric literals:\n\n literal ::= stringliteral | integer | longinteger\n | floatnumber | imagnumber\n\nEvaluation of a literal yields an object of the given type (string,\ninteger, long integer, floating point number, complex number) with the\ngiven value. The value may be approximated in the case of floating\npoint and imaginary (complex) literals. See section *Literals* for\ndetails.\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 in new-style classes.\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 not simply execute ``self.name = value`` --- this would\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n 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\n\nMore attribute access for new-style classes\n===========================================\n\nThe following methods only apply to new-style classes.\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 for new-style\n classes*.\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. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\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 a new-style object instance, ``a.x`` is transformed\n into the call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a new-style class, ``A.x`` is transformed into the\n call: ``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 both old and new-style classes have a\ndictionary for attribute storage. This wastes space for objects\nhaving very few instance variables. The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition. The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable. Space is saved because *__dict__* is\nnot created for each instance.\n\n__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 new-style class, *__slots__* reserves space for the declared\n variables and prevents the automatic creation of *__dict__* and\n *__weakref__* for each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\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 Changed in version 2.3: Previously, adding ``\'__dict__\'`` to the\n *__slots__* declaration would not enable the assignment of new\n attributes not specifically listed in the sequence of instance\n variable names.\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 Changed in version 2.3: Previously, adding ``\'__weakref__\'`` to the\n *__slots__* declaration would not enable support for weak\n references.\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 ``long``, ``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 Changed in version 2.6: Previously, *__class__* assignment raised an\n error if either new or old class had *__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, e.g., a module, list, or an instance. This\nobject is then asked to produce the attribute whose name is the\nidentifier. If this attribute is not available, the exception\n``AttributeError`` is raised. Otherwise, the type and value of the\nobject produced is determined by the object. Multiple evaluations of\nthe same attribute reference 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 (plain or long) and the other must be a sequence.\nIn the former case, the numbers are converted to a common type and\nthen multiplied together. In the latter case, sequence repetition is\nperformed; a negative 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. Plain or long integer division yields an\ninteger of the same type; the result is that of mathematical division\nwith the \'floor\' function applied to the result. Division by zero\nraises 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 [2].\n\nThe integer division and modulo operators are connected by the\nfollowing identity: ``x == (x/y)*y + (x%y)``. Integer division and\nmodulo are also connected with the built-in function ``divmod()``:\n``divmod(x, y) == (x/y, x%y)``. These identities don\'t hold for\nfloating point numbers; there similar identities hold approximately\nwhere ``x/y`` is replaced by ``floor(x/y)`` or ``floor(x/y) - 1`` [3].\n\nIn addition to performing the modulo operation on numbers, the ``%``\noperator is also overloaded by string and unicode objects to perform\nstring formatting (also known as interpolation). The syntax for string\nformatting is described in the Python Library Reference, section\n*String Formatting Operations*.\n\nDeprecated since version 2.3: The floor division operator, the modulo\noperator, and the ``divmod()`` function are no longer defined for\ncomplex numbers. Instead, convert to a floating point number using\nthe ``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 plain or long integers. The arguments are converted to a common\ntype.\n\nThe ``^`` operator yields the bitwise XOR (exclusive OR) of its\narguments, which must be plain or long integers. The arguments are\nconverted to a common type.\n\nThe ``|`` operator yields the bitwise (inclusive) OR of its arguments,\nwhich must be plain or long integers. The arguments are converted to\na common type.\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 ``func_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`` statement or the built-in ``eval()``\nfunction.\n\nSee *The standard type hierarchy* for more information.\n', 'bltin-ellipsis-object': '\nThe Ellipsis Object\n*******************\n\nThis object is used by extended slice notation (see *Slicings*). It\nsupports no special operations. There is exactly one ellipsis object,\nnamed ``Ellipsis`` (a built-in name).\n\nIt is written as ``Ellipsis``. When in a subscript, it can also be\nwritten as ``...``, for example ``seq[...]``.\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).\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: ``<type '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. (See the ``__nonzero__()`` special method for a way to\nchange this.)\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 [","]\n | expression genexpr_for] ")"\n argument_list ::= positional_arguments ["," keyword_arguments]\n ["," "*" expression] ["," keyword_arguments]\n ["," "**" expression]\n | keyword_arguments ["," "*" expression]\n ["," "**" expression]\n | "*" expression ["," "*" expression] ["," "**" 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 certain class instances\nthemselves are callable; extensions may define additional callable\nobject types). All argument expressions are evaluated before the call\nis attempted. Please refer to section *Function definitions* for the\nsyntax 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. Formal parameters using the syntax ``(sublist)`` cannot be\nused as keyword argument names; the outermost sublist corresponds to a\nsingle unnamed argument slot, and the argument value is assigned to\nthe sublist using the usual tuple assignment rules after all other\nparameter processing is done.\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 ::= "class" classname [inheritance] ":" suite\n inheritance ::= "(" [expression_list] ")"\n classname ::= identifier\n\nA class definition is an executable statement. It first evaluates the\ninheritance list, if present. Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing. The class\'s suite is then executed in a new execution\nframe (see section *Naming and binding*), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.) When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary. The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances. To create instance\nvariables, they can be set in a method with ``self.name = value``.\nBoth class and instance variables are accessible through the notation\n"``self.name``", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results. For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions. The evaluation rules for the decorator\nexpressions are the same as for functions. The result must be a class\nobject, which is then bound to the class name.\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 forms ``<>`` and ``!=`` are equivalent; for consistency with C,\n``!=`` is preferred; where ``!=`` is mentioned below ``<>`` is also\naccepted. The ``<>`` spelling is considered obsolescent.\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,\nobjects of different types *always* compare unequal, and are ordered\nconsistently but arbitrarily. You can control comparison behavior of\nobjects of non-built-in types by defining a ``__cmp__`` method or rich\ncomparison methods like ``__gt__``, described in section *Special\nmethod names*.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the ``in`` and ``not in``\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric equivalents\n (the result of the built-in function ``ord()``) of their characters.\n Unicode and 8-bit strings are fully interoperable in this behavior.\n [4]\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, ``cmp([1,2,x], [1,2,y])`` returns\n the same as ``cmp(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 their sorted\n (key, value) lists compare equal. [5] Outcomes other than equality\n are resolved consistently, but are not otherwise defined. [6]\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\nThe operators ``in`` and ``not in`` test for collection membership.\n``x in s`` evaluates to true if *x* is a member of the collection *s*,\nand false otherwise. ``x not in s`` returns the negation of ``x in\ns``. The collection membership test has traditionally been bound to\nsequences; an object is a member of a collection if the collection is\na sequence and contains an element equal to that object. However, it\nmake sense for many other object types to support membership tests\nwithout being a sequence. In particular, dictionaries (for keys) and\nsets support membership testing.\n\nFor the list and tuple types, ``x in y`` is true if and only if there\nexists an index *i* such that ``x == y[i]`` is true.\n\nFor the Unicode and string types, ``x in y`` is true if and only if\n*x* is a substring of *y*. An equivalent test is ``y.find(x) != -1``.\nNote, *x* and *y* need not be the same type; consequently, ``u\'ab\' in\n\'abc\'`` will return ``True``. Empty strings are always considered to\nbe a substring of any other string, so ``"" in "abc"`` will return\n``True``.\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength ``1``.\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. [7]\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. Function and class\ndefinitions are also syntactically compound 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`` statements 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 | decorated\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, and then the suite is executed. When the items are\nexhausted (which is immediately when the sequence is empty), the suite\nin the ``else`` clause, if present, is executed, and the loop\nterminates.\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\nThe target list is not deleted when the loop is finished, but if the\nsequence is empty, it will not have been assigned to at all by the\nloop. Hint: the built-in function ``range()`` returns a sequence of\nintegers suitable to emulate the effect of Pascal\'s ``for i := a to b\ndo``; e.g., ``range(3)`` returns the list ``[0, 1, 2]``.\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 internal\n counter is used to keep track of which item is used next, and this\n is incremented on each iteration. When this counter has reached the\n length of the sequence the loop terminates. This means that if the\n suite deletes the current (or a previous) item from the sequence,\n the next item will be skipped (since it gets the index of the\n 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\nChanged in version 2.5: In previous versions of Python,\n``try``...``except``...``finally`` did not work. ``try``...``except``\nhad to be nested in ``try``...``finally``.\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, a tuple containing an item compatible with the\nexception, or, in the (deprecated) case of string exceptions, is the\nraised string itself (note that the object identities must match, i.e.\nit must be the same string object, not just a string with the same\nvalue).\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 in that except clause, if present, and the except\nclause\'s suite is executed. All except clauses must have an\nexecutable block. When the end of this block is reached, execution\ncontinues normally after the entire try statement. (This means that\nif two nested handlers exist for the same exception, and the exception\noccurs in the try clause of the inner handler, the outer handler will\nnot handle the exception.)\n\nBefore an except clause\'s suite is executed, details about the\nexception are assigned to three variables in the ``sys`` module:\n``sys.exc_type`` receives the object identifying the exception;\n``sys.exc_value`` receives the exception\'s parameter;\n``sys.exc_traceback`` receives a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. These details are also available through the\n``sys.exc_info()`` function, which returns a tuple ``(exc_type,\nexc_value, exc_traceback)``. Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program. As of Python 1.5, the variables are restored to\ntheir previous values (before the call) when returning from a function\nthat 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\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost. The exception information is not available to the\nprogram during execution 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\nNew in version 2.5.\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\nNote: In Python 2.5, the ``with`` statement is only allowed when the\n ``with_statement`` feature has been enabled. It is always enabled\n in Python 2.6.\n\nChanged in version 2.7: 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 decorated ::= decorators (classdef | funcdef)\n decorators ::= decorator+\n decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite\n dotted_name ::= identifier ("." identifier)*\n parameter_list ::= (defparameter ",")*\n ( "*" identifier [, "**" identifier]\n | "**" identifier\n | defparameter [","] )\n defparameter ::= parameter ["=" expression]\n sublist ::= parameter ("," parameter)* [","]\n parameter ::= identifier | "(" sublist ")"\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 top-level 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 must also have a default value --- this is a syntactic\nrestriction 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.\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.\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\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n classdef ::= "class" classname [inheritance] ":" suite\n inheritance ::= "(" [expression_list] ")"\n classname ::= identifier\n\nA class definition is an executable statement. It first evaluates the\ninheritance list, if present. Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing. The class\'s suite is then executed in a new execution\nframe (see section *Naming and binding*), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.) When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary. The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances. To create instance\nvariables, they can be set in a method with ``self.name = value``.\nBoth class and instance variables are accessible through the notation\n"``self.name``", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results. For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions. The evaluation rules for the decorator\nexpressions are the same as for functions. The result must be a class\nobject, which is then bound to the class name.\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\nNew in version 2.5.\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," the arguments\nare coerced using the coercion rules listed at *Coercion rules*. If\nboth arguments are standard numeric types, the following coercions are\napplied:\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, if either argument is a long integer, the other is\n converted to long integer;\n\n* otherwise, both must be plain integers and no conversion is\n necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator). Extensions can define their own\ncoercions.\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_traceback`` 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.exc_traceback`` or ``sys.last_traceback``. Circular\n references which are garbage are detected when the option cycle\n detector is enabled (it\'s on by default), but can only be cleaned\n up if there are no Python-level ``__del__()`` methods involved.\n Refer to the documentation for the ``gc`` module for more\n information about how ``__del__()`` methods are handled by the\n cycle detector, particularly the description of the ``garbage``\n 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\n See also the *-R* command-line option.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances of that class is 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 the ``str()`` built-in function and by the ``print``\n statement to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n 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 New in version 2.1.\n\n These are the so-called "rich comparison" methods, and are called\n for comparison operators in preference to ``__cmp__()`` below. 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`` and\n ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and\n ``x>=y`` calls ``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.__cmp__(self, other)\n\n Called by comparison operations if rich comparison (see above) is\n not defined. Should return a negative integer if ``self < other``,\n zero if ``self == other``, a positive integer if ``self > other``.\n If no ``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class instances are compared by object identity\n ("address"). See also the description of ``__hash__()`` for some\n important notes on creating *hashable* objects which support custom\n comparison operations and are usable as dictionary keys. (Note: the\n restriction that exceptions are not propagated by ``__cmp__()`` has\n been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1: No longer supported.\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 a ``__cmp__()`` or ``__eq__()`` method\n it should not define a ``__hash__()`` operation either; if it\n defines ``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances will not be usable in hashed collections. If a class\n defines mutable objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it should not implement ``__hash__()``, since\n hashable collection implementations require that a object\'s hash\n value is immutable (if the object\'s hash value changes, it will be\n in the wrong hash bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value returned is no longer appropriate (e.g. by switching\n to a value-based concept of equality instead of the default\n identity based equality) can explicitly flag themselves as being\n unhashable by setting ``__hash__ = None`` in the class definition.\n Doing so means that not only will instances of the class raise an\n appropriate ``TypeError`` when a program attempts to retrieve their\n hash value, but they will also be correctly identified as\n unhashable when checking ``isinstance(obj, collections.Hashable)``\n (unlike classes which define their own ``__hash__()`` to explicitly\n raise ``TypeError``).\n\n Changed in version 2.5: ``__hash__()`` may now also return a long\n integer object; the 32-bit integer is then derived from the hash of\n that object.\n\n Changed in version 2.6: ``__hash__`` may now be set to ``None`` to\n explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth value testing and the built-in operation\n ``bool()``; should return ``False`` or ``True``, or their integer\n equivalents ``0`` or ``1``. When this method is not defined,\n ``__len__()`` is called, if it is defined, and the object is\n considered true if its result is nonzero. If a class defines\n neither ``__len__()`` nor ``__nonzero__()``, all its instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called to implement ``unicode()`` built-in; should return a Unicode\n object. When this method is not defined, string conversion is\n attempted, and the result of string conversion is converted to\n Unicode using the system default encoding.\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\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n python -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 2.4: Restarting post-mortem behavior added.\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 ``c`` 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[, locals]])\n\n Execute the *statement* (given as a string) under debugger control.\n The debugger prompt appears before any code is executed; you can\n set breakpoints and type ``continue``, or you can step through the\n statement using ``step`` or ``next`` (all these commands are\n explained below). The optional *globals* and *locals* arguments\n specify the environment in which the code is executed; by default\n the dictionary of the module ``__main__`` is used. (See the\n explanation of the ``exec`` statement or the ``eval()`` built-in\n function.)\n\npdb.runeval(expression[, globals[, locals]])\n\n Evaluate the *expression* (given as a string) under debugger\n control. When ``runeval()`` returns, it returns the value of the\n expression. Otherwise this function is similar to ``run()``.\n\npdb.runcall(function[, argument, ...])\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])\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)\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 Example call to enable tracing with *skip*:\n\n import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n New in version 2.7: The *skip* argument.\n\n run(statement[, globals[, locals]])\n runeval(expression[, globals[, locals]])\n runcall(function[, argument, ...])\n set_trace()\n\n See the documentation for the functions explained above.\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\nIt is illegal to delete a name from the local namespace if it occurs\nas a free variable in a nested block.\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', '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\nIf ``exec`` is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n``SyntaxError`` unless the exec explicitly specifies the local\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, 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\nExceptions can also be identified by strings, in which case the\n``except`` clause is selected by object identity. An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API. Their\n contents may change from one version of Python to the next without\n warning and should not be relied on by code which will run under\n multiple 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 file read by the\nbuilt-in function ``execfile()`` is a code block. The string argument\npassed to the built-in function ``eval()`` and to the ``exec``\nstatement is a code block. The expression read and evaluated by the\nbuilt-in function ``input()`` 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 generator expressions since\nthey are implemented using a function scope. This means that the\nfollowing 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.\nIf a name is bound at the module level, it is a global variable. (The\nvariables of the module code block are local and global.) If a\nvariable is used in a code block but not defined there, it is a *free\nvariable*.\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, in the\nsecond position of an ``except`` clause header or after ``as`` in a\n``with`` statement. The ``import`` statement of the form ``from ...\nimport *`` binds all names defined in the imported module, except\nthose beginning with an underscore. This form may only be used at the\nmodule 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). It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\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 name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtins namespace, the namespace\nof the module ``__builtin__``. The global namespace is searched\nfirst. If the name is not found there, the builtins namespace is\nsearched. The global statement must precede all uses of the 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``__builtin__`` (note: no \'s\'); when in any other module,\n``__builtins__`` is an alias for the dictionary of the ``__builtin__``\nmodule itself. ``__builtins__`` can be set to a user-created\ndictionary to create a weak 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 ``__builtin__`` (no \'s\') module and modify its attributes\nappropriately.\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\nIf ``exec`` is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n``SyntaxError`` unless the exec explicitly specifies the local\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, 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\nExceptions can also be identified by strings, in which case the\n``except`` clause is selected by object identity. An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API. Their\n contents may change from one version of Python to the next without\n warning and should not be relied on by code which will run under\n multiple 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 of floating point numbers can\nlook like octal integers, but are interpreted using radix 10. For\nexample, ``077e010`` is legal, and denotes the same number as\n``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, and then the suite is executed. When the items are\nexhausted (which is immediately when the sequence is empty), the suite\nin the ``else`` clause, if present, is executed, and the loop\nterminates.\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\nThe target list is not deleted when the loop is finished, but if the\nsequence is empty, it will not have been assigned to at all by the\nloop. Hint: the built-in function ``range()`` returns a sequence of\nintegers suitable to emulate the effect of Pascal\'s ``for i := a to b\ndo``; e.g., ``range(3)`` returns the list ``[0, 1, 2]``.\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 internal\n counter is used to keep track of which item is used next, and this\n is incremented on each iteration. When this counter has reached the\n length of the sequence the loop terminates. This means that if the\n suite deletes the current (or a previous) item from the sequence,\n the next item will be skipped (since it gets the index of the\n 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"\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 2.7: 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\nTwo conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, and ``\'!r\'`` which calls ``repr()``.\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\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 \'}\'>\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 is only valid for integers, and only for binary,\noctal, or hexadecimal output. If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\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 2.7: 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\nIf the *width* field is preceded by a zero (``\'0\'``) character, this\nenables zero-padding. This is equivalent to an *alignment* type of\n``\'=\'`` and a *fill* character of ``\'0\'``.\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\'``. |\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 | The same as ``\'g\'``. |\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\') # 2.7+ 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(object):\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.5\n >>> total = 22\n >>> \'Correct answers: {:.2%}\'.format(points/total)\n \'Correct answers: 88.64%\'\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):\n ... for base in \'dXob\':\n ... print \'{0:{width}{base}}\'.format(num, base=base, width=width),\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 decorated ::= decorators (classdef | funcdef)\n decorators ::= decorator+\n decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite\n dotted_name ::= identifier ("." identifier)*\n parameter_list ::= (defparameter ",")*\n ( "*" identifier [, "**" identifier]\n | "**" identifier\n | defparameter [","] )\n defparameter ::= parameter ["=" expression]\n sublist ::= parameter ("," parameter)* [","]\n parameter ::= identifier | "(" sublist ")"\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 top-level 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 must also have a default value --- this is a syntactic\nrestriction 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.\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.\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', '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 an\n``exec`` statement does not affect the code block *containing* the\n``exec`` statement, and code contained in an ``exec`` statement is\nunaffected by ``global`` statements in the code containing the\n``exec`` statement. The same applies to the ``eval()``,\n``execfile()`` 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 ``__builtin__`` module.\n When not in interactive mode, ``_`` has no special meaning and is\n not 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\n identifier ::= (letter|"_") (letter | digit | "_")*\n letter ::= lowercase | uppercase\n lowercase ::= "a"..."z"\n uppercase ::= "A"..."Z"\n digit ::= "0"..."9"\n\nIdentifiers are unlimited in length. Case is significant.\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 and del from not while\n as elif global or with\n assert else if pass yield\n break except import print\n class exec in raise\n continue finally is return\n def for lambda try\n\nChanged in version 2.4: ``None`` became a constant and is now\nrecognized by the compiler as a name for the built-in object ``None``.\nAlthough it is not a keyword, you cannot assign a different object to\nit.\n\nChanged in version 2.5: Using ``as`` and ``with`` as identifiers\ntriggers a warning. To use them as keywords, enable the\n``with_statement`` future feature .\n\nChanged in version 2.6: ``as`` and ``with`` are full keywords.\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 ``__builtin__`` module.\n When not in interactive mode, ``_`` has no special meaning and is\n not 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\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the ``import`` statement occurs). The\nstatement comes in two forms differing on whether it uses the ``from``\nkeyword. The first form (without ``from``) repeats these steps for\neach identifier in the list. The form with ``from`` performs step (1)\nonce, and then performs step (2) repeatedly.\n\nTo understand how step (1) occurs, one must first understand how\nPython handles hierarchical naming of modules. To help organize\nmodules and provide a hierarchy in naming, Python has a concept of\npackages. A package can contain other packages and modules while\nmodules cannot contain other modules or packages. From a file system\nperspective, packages are directories and modules are files. The\noriginal specification for packages is still available to read,\nalthough minor details have changed since the writing of that\ndocument.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n``sys.modules``, the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import.\n\nIf the module is not found in the cache, then ``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can be found in\n**PEP 302**). The object is a list of *finder* objects which are\nqueried in order as to whether they know how to load the module by\ncalling their ``find_module()`` method with the name of the module. If\nthe module happens to be contained within a package (as denoted by the\nexistence of a dot in the name), then a second argument to\n``find_module()`` is given as the value of the ``__path__`` attribute\nfrom the parent package (everything up to the last dot in the name of\nthe module being imported). If a finder can find the module it returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of the finders on ``sys.meta_path`` are able to find the\nmodule then some implicitly defined finders are queried.\nImplementations of Python vary in what implicit meta path finders are\ndefined. The one they all do define, though, is one that handles\n``sys.path_hooks``, ``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to ``find_module()``,\n``__path__`` on the parent package, is used as the source of paths. If\nthe module is not contained in a package then ``sys.path`` is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n``sys.path_importer_cache`` caches finders for paths and is checked\nfor a finder. If the path does not have a finder cached then\n``sys.path_hooks`` is searched by calling each object in the list with\na single argument of the path, returning a finder or raises\n``ImportError``. If a finder is returned then it is cached in\n``sys.path_importer_cache`` and then used for that path entry. If no\nfinder can be found but the path exists then a value of ``None`` is\nstored in ``sys.path_importer_cache`` to signify that an implicit,\nfile-based finder that handles modules stored as individual files\nshould be used for that path. If the path does not exist then a finder\nwhich always returns *None`* is placed in the cache for the path.\n\nIf no finder can find the module then ``ImportError`` is raised.\nOtherwise some finder returned a loader whose ``load_module()`` method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin ``sys.modules`` (a possibility if the loader is called outside of\nthe import machinery) then it is to use that module for initialization\nand not a new module. But if the module does not exist in\n``sys.modules`` then it is to be added to that dict before\ninitialization begins. If an error occurs during loading of the module\nand it was added to ``sys.modules`` it is to be removed from the dict.\nIf an error occurs but the module was already in ``sys.modules`` it is\nleft in the dict.\n\nThe loader must set several attributes on the module. ``__name__`` is\nto be set to the name of the module. ``__file__`` is to be the "path"\nto the file unless the module is built-in (and thus listed in\n``sys.builtin_module_names``) in which case the attribute is not set.\nIf what is being imported is a package then ``__path__`` is to be set\nto a list of paths to be searched when looking for modules and\npackages contained within the package being imported. ``__package__``\nis optional but should be set to the name of package that contains the\nmodule or package (the empty string is used for module not contained\nin a package). ``__loader__`` is also optional but should be set to\nthe loader object that is loading the module.\n\nIf an error occurs during loading then the loader raises\n``ImportError`` if some other exception is not already being\npropagated. Otherwise the loader returns the module that was loaded\nand initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any. If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound. As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname". If a name is not\nfound, ``ImportError`` is raised. If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\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. If the\nwild card form of import --- ``import *`` --- is used in a function\nand the function contains or is a nested block with free variables,\nthe compiler will 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 2.6 are ``unicode_literals``,\n``print_function``, ``absolute_import``, ``division``, ``generators``,\n``nested_scopes`` and ``with_statement``. ``generators``,\n``with_statement``, ``nested_scopes`` are redundant in Python version\n2.6 and above because they are always enabled.\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 an ``exec`` statement or calls to the built-in\nfunctions ``compile()`` and ``execfile()`` that occur in a module\n``M`` containing a future statement will, by default, use the new\nsyntax or semantics associated with the future statement. This can,\nstarting with Python 2.2 be controlled by optional arguments to\n``compile()`` --- see the documentation of that function for 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 forms ``<>`` and ``!=`` are equivalent; for consistency with C,\n``!=`` is preferred; where ``!=`` is mentioned below ``<>`` is also\naccepted. The ``<>`` spelling is considered obsolescent.\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,\nobjects of different types *always* compare unequal, and are ordered\nconsistently but arbitrarily. You can control comparison behavior of\nobjects of non-built-in types by defining a ``__cmp__`` method or rich\ncomparison methods like ``__gt__``, described in section *Special\nmethod names*.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the ``in`` and ``not in``\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric equivalents\n (the result of the built-in function ``ord()``) of their characters.\n Unicode and 8-bit strings are fully interoperable in this behavior.\n [4]\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, ``cmp([1,2,x], [1,2,y])`` returns\n the same as ``cmp(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 their sorted\n (key, value) lists compare equal. [5] Outcomes other than equality\n are resolved consistently, but are not otherwise defined. [6]\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\nThe operators ``in`` and ``not in`` test for collection membership.\n``x in s`` evaluates to true if *x* is a member of the collection *s*,\nand false otherwise. ``x not in s`` returns the negation of ``x in\ns``. The collection membership test has traditionally been bound to\nsequences; an object is a member of a collection if the collection is\na sequence and contains an element equal to that object. However, it\nmake sense for many other object types to support membership tests\nwithout being a sequence. In particular, dictionaries (for keys) and\nsets support membership testing.\n\nFor the list and tuple types, ``x in y`` is true if and only if there\nexists an index *i* such that ``x == y[i]`` is true.\n\nFor the Unicode and string types, ``x in y`` is true if and only if\n*x* is a substring of *y*. An equivalent test is ``y.find(x) != -1``.\nNote, *x* and *y* need not be the same type; consequently, ``u\'ab\' in\n\'abc\'`` will return ``True``. Empty strings are always considered to\nbe a substring of any other string, so ``"" in "abc"`` will return\n``True``.\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength ``1``.\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. [7]\n', 'integers': '\nInteger and long integer literals\n*********************************\n\nInteger and long integer literals are described by the following\nlexical definitions:\n\n longinteger ::= integer ("l" | "L")\n integer ::= decimalinteger | octinteger | hexinteger | bininteger\n decimalinteger ::= nonzerodigit digit* | "0"\n octinteger ::= "0" ("o" | "O") octdigit+ | "0" octdigit+\n hexinteger ::= "0" ("x" | "X") hexdigit+\n bininteger ::= "0" ("b" | "B") bindigit+\n nonzerodigit ::= "1"..."9"\n octdigit ::= "0"..."7"\n bindigit ::= "0" | "1"\n hexdigit ::= digit | "a"..."f" | "A"..."F"\n\nAlthough both lower case ``\'l\'`` and upper case ``\'L\'`` are allowed as\nsuffix for long integers, it is strongly recommended to always use\n``\'L\'``, since the letter ``\'l\'`` looks too much like the digit\n``\'1\'``.\n\nPlain integer literals that are above the largest representable plain\ninteger (e.g., 2147483647 when using 32-bit arithmetic) are accepted\nas if they were long integers instead. [1] There is no limit for long\ninteger literals apart from what can be stored in available memory.\n\nSome examples of plain integer literals (first row) and long integer\nliterals (second and third rows):\n\n 7 2147483647 0177\n 3L 79228162514264337593543950336L 0377L 0x100000000L\n 79228162514264337593543950336 0xdeadbeef\n', 'lambda': '\nLambdas\n*******\n\n lambda_form ::= "lambda" [parameter_list]: expression\n old_lambda_form ::= "lambda" [parameter_list]: old_expression\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 name(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.\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 | list_comprehension] "]"\n list_comprehension ::= expression list_for\n list_for ::= "for" target_list "in" old_expression_list [list_iter]\n old_expression_list ::= old_expression [("," old_expression)+ [","]]\n old_expression ::= or_test | old_lambda_form\n list_iter ::= list_for | list_if\n list_if ::= "if" old_expression [list_iter]\n\nA list display yields a new list object. Its contents are specified\nby providing either a list of expressions or a list comprehension.\nWhen a comma-separated list of expressions is supplied, its elements\nare evaluated from left to right and placed into the list object in\nthat order. When a list comprehension is supplied, it consists of a\nsingle expression followed by at least one ``for`` clause and zero or\nmore ``for`` or ``if`` clauses. In this case, the elements of the new\nlist are those that would be produced by considering each of the\n``for`` or ``if`` clauses a block, nesting from left to right, and\nevaluating the expression to produce a list element each time the\ninnermost block is reached [1].\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 file read by the\nbuilt-in function ``execfile()`` is a code block. The string argument\npassed to the built-in function ``eval()`` and to the ``exec``\nstatement is a code block. The expression read and evaluated by the\nbuilt-in function ``input()`` 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 generator expressions since\nthey are implemented using a function scope. This means that the\nfollowing 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.\nIf a name is bound at the module level, it is a global variable. (The\nvariables of the module code block are local and global.) If a\nvariable is used in a code block but not defined there, it is a *free\nvariable*.\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, in the\nsecond position of an ``except`` clause header or after ``as`` in a\n``with`` statement. The ``import`` statement of the form ``from ...\nimport *`` binds all names defined in the imported module, except\nthose beginning with an underscore. This form may only be used at the\nmodule 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). It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\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 name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtins namespace, the namespace\nof the module ``__builtin__``. The global namespace is searched\nfirst. If the name is not found there, the builtins namespace is\nsearched. The global statement must precede all uses of the 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``__builtin__`` (note: no 's'); when in any other module,\n``__builtins__`` is an alias for the dictionary of the ``__builtin__``\nmodule itself. ``__builtins__`` can be set to a user-created\ndictionary to create a weak 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 ``__builtin__`` (no 's') module and modify its attributes\nappropriately.\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\nIf ``exec`` is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n``SyntaxError`` unless the exec explicitly specifies the local\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, it is used for both.\n", 'numbers': "\nNumeric literals\n****************\n\nThere are four types of numeric literals: plain integers, long\nintegers, floating point numbers, and imaginary numbers. There are no\ncomplex literals (complex numbers can be formed by adding a real\nnumber and an imaginary 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.__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 (``+``, ``-``, ``*``, ``//``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to evaluate the expression ``x + y``, where *x* is an\n 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__()`` (described below). Note\n that ``__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.__div__(self, other)\nobject.__truediv__(self, other)\n\n The division operator (``/``) is implemented by these methods. The\n ``__truediv__()`` method is used when ``__future__.division`` is in\n effect, otherwise ``__div__()`` is used. If only one of these two\n methods is defined, the object will not support division in the\n alternate context; ``TypeError`` will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(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 (``+``, ``-``, ``*``, ``/``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected (swapped) operands. These functions are only called if\n the left operand does not support the corresponding operation and\n the operands are of different types. [2] For instance, to evaluate\n the expression ``x - y``, where *y* is an instance of a class that\n has an ``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)`` returns *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.__idiv__(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.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``long()``, and ``float()``. Should return a value of\n the appropriate type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to implement the built-in functions ``oct()`` and ``hex()``.\n Should return a string value.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing). Must return\n an integer (int or long).\n\n New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to implement "mixed-mode" numeric arithmetic. Should either\n return a 2-tuple containing *self* and *other* converted to a\n common numeric type, or ``None`` if conversion is impossible. When\n the common type would be the type of ``other``, it is sufficient to\n return ``None``, since the interpreter will also ask the other\n object to attempt a coercion (but sometimes, if the implementation\n of the other type cannot be changed, it is useful to do the\n conversion to the other type here). A return value of\n ``NotImplemented`` is equivalent to returning ``None``.\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 (currently implemented as its address). An\nobject\'s *type* is also unchangeable. [1] An object\'s type determines\nthe operations that the object supports (e.g., "does it have a\nlength?") and also defines the possible values for objects of that\ntype. The ``type()`` function returns an object\'s type (which is an\nobject itself). The *value* of some objects can change. Objects\nwhose value can change are said to be *mutable*; objects whose value\nis unchangeable once they are created are called *immutable*. (The\nvalue of an immutable container object that contains a reference to a\nmutable object can change when the latter\'s value is changed; however\nthe container 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 provides a convenient way to do\nthis.\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': '\nSummary\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+-------------------------------------------------+---------------------------------------+\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| | [8] |\n+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``**`` | Exponentiation [9] |\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:datum...}``, ```expressions...``` | display, dictionary display, string |\n| | conversion |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] In Python 2.3 and later releases, a list comprehension "leaks" the\n control variables of each ``for`` it contains into the containing\n scope. However, this behavior is deprecated, and relying on it\n will not work in Python 3.0\n\n[2] 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[3] If x is very close to an exact integer multiple of y, it\'s\n possible for ``floor(x/y)`` to be one larger than ``(x-x%y)/y``\n due to rounding. In such cases, Python returns the latter result,\n in order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\n close to ``x``.\n\n[4] While comparisons between unicode strings make sense at the byte\n level, they may be counter-intuitive to users. For example, the\n strings ``u"\\u00C7"`` and ``u"\\u0043\\u0327"`` compare differently,\n even 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[5] The implementation computes this efficiently, without constructing\n lists or sorting.\n\n[6] Earlier versions of Python used lexicographic comparison of the\n sorted (key, value) lists, but this was very expensive for the\n common case of comparing for equality. An even earlier version of\n Python compared dictionaries by identity only, but this caused\n surprises because people expected to be able to test a dictionary\n for emptiness by comparing it to ``{}``.\n\n[7] 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[8] The ``%`` operator is also used for string formatting; the same\n precedence applies.\n\n[9] 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. The result type is that of the\narguments after coercion.\n\nWith mixed operand types, the coercion rules for binary arithmetic\noperators apply. For int and long int operands, the result has the\nsame type as the operands (after coercion) unless the second argument\nis negative; in that case, all arguments are converted to float and a\nfloat result is delivered. For example, ``10**2`` returns ``100``, but\n``10**-2`` returns ``0.01``. (This last feature was added in Python\n2.2. In Python 2.1 and before, if both arguments were of integer types\nand the second argument was negative, an exception was raised).\n\nRaising ``0.0`` to a negative power results in a\n``ZeroDivisionError``. Raising a negative number to a fractional power\nresults in a ``ValueError``.\n', 'raise': '\nThe ``raise`` statement\n***********************\n\n raise_stmt ::= "raise" [expression ["," expression ["," 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 ``TypeError`` exception is raised indicating that\nthis is an error (if running under IDLE, a ``Queue.Empty`` exception\nis raised instead).\n\nOtherwise, ``raise`` evaluates the expressions to get three objects,\nusing ``None`` as the value of omitted expressions. The first two\nobjects are used to determine the *type* and *value* of the exception.\n\nIf the first object is an instance, the type of the exception is the\nclass of the instance, the instance itself is the value, and the\nsecond object must be ``None``.\n\nIf the first object is a class, it becomes the type of the exception.\nThe second object is used to determine the exception value: If it is\nan instance of the class, the instance becomes the exception value. If\nthe second object is a tuple, it is used as the argument list for the\nclass constructor; if it is ``None``, an empty argument list is used,\nand any other object is treated as a single argument to the\nconstructor. The instance so created by calling the constructor is\nused as the exception value.\n\nIf a third object is present and not ``None``, it must be a traceback\nobject (see section *The standard type hierarchy*), and it is\nsubstituted instead of the current location as the place where the\nexception occurred. If the third object is present and not a\ntraceback object or ``None``, a ``TypeError`` exception is raised.\nThe three-expression form of ``raise`` is useful to re-raise an\nexception transparently in an except clause, but ``raise`` with no\nexpressions should be preferred if the exception to be re-raised was\nthe most recently active exception in the current scope.\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 is not allowed to\ninclude an ``expression_list``. In that context, a bare ``return``\nindicates that the generator is done and will cause ``StopIteration``\nto be raised.\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. (For backwards compatibility, the method\n``__getslice__()`` (see below) can also be defined to handle simple,\nbut not extended slices.) It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``has_key()``,\n``get()``, ``clear()``, ``setdefault()``, ``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``, ``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for Python's\nstandard dictionary objects. The ``UserDict`` module provides a\n``DictMixin`` class to help create those methods from a base set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``, and\n``keys()``. Mutable sequences should provide methods ``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``, ``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python standard list\nobjects. Finally, sequence types should implement addition (meaning\nconcatenation) and multiplication (meaning repetition) by defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``, ``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they should not\ndefine ``__coerce__()`` or other numerical operators. It is\nrecommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should be equivalent of ``has_key()``;\nfor sequences, 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``iterkeys()``; 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 ``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is considered to be false in a\n Boolean context.\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 ``iterkeys()``.\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\n New in version 2.6.\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 plain or long integers as arguments. The\narguments are converted to a common type. 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,\nn)``. Negative shift counts raise a ``ValueError`` exception.\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 ::= simple_slicing | extended_slicing\n simple_slicing ::= primary "[" short_slice "]"\n extended_slicing ::= primary "[" slice_list "]"\n slice_list ::= slice_item ("," slice_item)* [","]\n slice_item ::= expression | proper_slice | ellipsis\n proper_slice ::= short_slice | long_slice\n short_slice ::= [lower_bound] ":" [upper_bound]\n long_slice ::= short_slice ":" [stride]\n lower_bound ::= expression\n upper_bound ::= expression\n stride ::= expression\n ellipsis ::= "..."\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 nor ellipses). Similarly, when the slice\nlist has exactly one short slice and no trailing comma, the\ninterpretation as a simple slicing takes priority over that as an\nextended slicing.\n\nThe semantics for a simple slicing are as follows. The primary must\nevaluate to a sequence object. The lower and upper bound expressions,\nif present, must evaluate to plain integers; defaults are zero and the\n``sys.maxint``, respectively. If either bound is negative, the\nsequence\'s length is added to it. The slicing now selects all items\nwith index *k* such that ``i <= k < j`` where *i* and *j* are the\nspecified lower and upper bounds. This may be an empty sequence. It\nis not an error if *i* or *j* lie outside the range of valid indexes\n(such items don\'t exist so they aren\'t selected).\n\nThe semantics for an extended slicing are as follows. The primary\nmust evaluate to a mapping object, and it is indexed with a key that\nis constructed 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 an ellipsis slice\nitem is the built-in ``Ellipsis`` object. The conversion of a proper\nslice is a slice object (see section *The standard type hierarchy*)\nwhose ``start``, ``stop`` and ``step`` attributes are the values of\nthe expressions 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\nobject.__methods__\n\n Deprecated since version 2.2: Use the built-in function ``dir()``\n to get a list of an object\'s attributes. This attribute is no\n longer available.\n\nobject.__members__\n\n Deprecated since version 2.2: Use the built-in function ``dir()``\n to get a list of an object\'s attributes. This attribute is no\n longer available.\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\nThe following attributes are only supported by *new-style class*es.\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 new-style class keeps a list of weak references to its\n immediate subclasses. This method returns a list of all those\n references still alive. Example:\n\n >>> int.__subclasses__()\n [<type \'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\n[6] The advantage of leaving the newline on is that returning an empty\n string is then an unambiguous EOF indication. It is also possible\n (in cases where it might matter, for example, if you want to make\n an exact copy of a file while scanning its lines) to tell whether\n the last line of a file ended in a newline or not (yes this\n happens!).\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 ``x.__getitem__(i)`` for\nold-style classes and ``type(x).__getitem__(x, i)`` for new-style\nclasses. Except where mentioned, attempts to execute an operation\nraise an 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_traceback`` 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.exc_traceback`` or ``sys.last_traceback``. Circular\n references which are garbage are detected when the option cycle\n detector is enabled (it\'s on by default), but can only be cleaned\n up if there are no Python-level ``__del__()`` methods involved.\n Refer to the documentation for the ``gc`` module for more\n information about how ``__del__()`` methods are handled by the\n cycle detector, particularly the description of the ``garbage``\n 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\n See also the *-R* command-line option.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances of that class is 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 the ``str()`` built-in function and by the ``print``\n statement to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n 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 New in version 2.1.\n\n These are the so-called "rich comparison" methods, and are called\n for comparison operators in preference to ``__cmp__()`` below. 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`` and\n ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and\n ``x>=y`` calls ``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.__cmp__(self, other)\n\n Called by comparison operations if rich comparison (see above) is\n not defined. Should return a negative integer if ``self < other``,\n zero if ``self == other``, a positive integer if ``self > other``.\n If no ``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class instances are compared by object identity\n ("address"). See also the description of ``__hash__()`` for some\n important notes on creating *hashable* objects which support custom\n comparison operations and are usable as dictionary keys. (Note: the\n restriction that exceptions are not propagated by ``__cmp__()`` has\n been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1: No longer supported.\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 a ``__cmp__()`` or ``__eq__()`` method\n it should not define a ``__hash__()`` operation either; if it\n defines ``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances will not be usable in hashed collections. If a class\n defines mutable objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it should not implement ``__hash__()``, since\n hashable collection implementations require that a object\'s hash\n value is immutable (if the object\'s hash value changes, it will be\n in the wrong hash bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value returned is no longer appropriate (e.g. by switching\n to a value-based concept of equality instead of the default\n identity based equality) can explicitly flag themselves as being\n unhashable by setting ``__hash__ = None`` in the class definition.\n Doing so means that not only will instances of the class raise an\n appropriate ``TypeError`` when a program attempts to retrieve their\n hash value, but they will also be correctly identified as\n unhashable when checking ``isinstance(obj, collections.Hashable)``\n (unlike classes which define their own ``__hash__()`` to explicitly\n raise ``TypeError``).\n\n Changed in version 2.5: ``__hash__()`` may now also return a long\n integer object; the 32-bit integer is then derived from the hash of\n that object.\n\n Changed in version 2.6: ``__hash__`` may now be set to ``None`` to\n explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth value testing and the built-in operation\n ``bool()``; should return ``False`` or ``True``, or their integer\n equivalents ``0`` or ``1``. When this method is not defined,\n ``__len__()`` is called, if it is defined, and the object is\n considered true if its result is nonzero. If a class defines\n neither ``__len__()`` nor ``__nonzero__()``, all its instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called to implement ``unicode()`` built-in; should return a Unicode\n object. When this method is not defined, string conversion is\n attempted, and the result of string conversion is converted to\n Unicode using the system default encoding.\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 in new-style classes.\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 not simply execute ``self.name = value`` --- this would\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n 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\n\nMore attribute access for new-style classes\n-------------------------------------------\n\nThe following methods only apply to new-style classes.\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 for new-style\n classes*.\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. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\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 a new-style object instance, ``a.x`` is transformed\n into the call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a new-style class, ``A.x`` is transformed into the\n call: ``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 both old and new-style classes have a\ndictionary for attribute storage. This wastes space for objects\nhaving very few instance variables. The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition. The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable. Space is saved because *__dict__* is\nnot created for each instance.\n\n__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 new-style class, *__slots__* reserves space for the declared\n variables and prevents the automatic creation of *__dict__* and\n *__weakref__* for each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\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 Changed in version 2.3: Previously, adding ``\'__dict__\'`` to the\n *__slots__* declaration would not enable the assignment of new\n attributes not specifically listed in the sequence of instance\n variable names.\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 Changed in version 2.3: Previously, adding ``\'__weakref__\'`` to the\n *__slots__* declaration would not enable support for weak\n references.\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 ``long``, ``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 Changed in version 2.6: Previously, *__class__* assignment raised an\n error if either new or old class had *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, new-style classes are constructed using ``type()``. A\nclass definition is read into a separate namespace and the value of\nclass name is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if *__metaclass__* is defined then\nthe callable assigned to it will be called instead of ``type()``. This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\n__metaclass__\n\n This variable can be any callable accepting arguments for ``name``,\n ``bases``, and ``dict``. Upon class creation, the callable is used\n instead of the built-in ``type()``.\n\n New in version 2.2.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If ``dict[\'__metaclass__\']`` exists, it is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n used (this looks for a *__class__* attribute first and if not found,\n uses its type).\n\n* Otherwise, if a global variable named __metaclass__ exists, it is\n used.\n\n* Otherwise, the old-style, classic metaclass (types.ClassType) is\n used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\n\nCustomizing instance and subclass checks\n========================================\n\nNew in version 2.6.\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. (For backwards compatibility, the method\n``__getslice__()`` (see below) can also be defined to handle simple,\nbut not extended slices.) It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``has_key()``,\n``get()``, ``clear()``, ``setdefault()``, ``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``, ``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for Python\'s\nstandard dictionary objects. The ``UserDict`` module provides a\n``DictMixin`` class to help create those methods from a base set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``, and\n``keys()``. Mutable sequences should provide methods ``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``, ``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python standard list\nobjects. Finally, sequence types should implement addition (meaning\nconcatenation) and multiplication (meaning repetition) by defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``, ``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they should not\ndefine ``__coerce__()`` or other numerical operators. It is\nrecommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should be equivalent of ``has_key()``;\nfor sequences, 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``iterkeys()``; 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 ``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is considered to be false in a\n Boolean context.\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 ``iterkeys()``.\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\n New in version 2.6.\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\nAdditional methods for emulation of sequence types\n==================================================\n\nThe following optional methods can be defined to further emulate\nsequence objects. Immutable sequences methods should at most only\ndefine ``__getslice__()``; mutable sequences might define all three\nmethods.\n\nobject.__getslice__(self, i, j)\n\n Deprecated since version 2.0: Support slice objects as parameters\n to the ``__getitem__()`` method. (However, built-in types in\n CPython currently still implement ``__getslice__()``. Therefore,\n you have to override it in derived classes when implementing\n slicing.)\n\n Called to implement evaluation of ``self[i:j]``. The returned\n object should be of the same type as *self*. Note that missing *i*\n or *j* in the slice expression are replaced by zero or\n ``sys.maxint``, respectively. If negative indexes are used in the\n slice, the length of the sequence is added to that index. If the\n instance does not implement the ``__len__()`` method, an\n ``AttributeError`` is raised. No guarantee is made that indexes\n adjusted this way are not still negative. Indexes which are\n greater than the length of the sequence are not modified. If no\n ``__getslice__()`` is found, a slice object is created instead, and\n passed to ``__getitem__()`` instead.\n\nobject.__setslice__(self, i, j, sequence)\n\n Called to implement assignment to ``self[i:j]``. Same notes for *i*\n and *j* as for ``__getslice__()``.\n\n This method is deprecated. If no ``__setslice__()`` is found, or\n for extended slicing of the form ``self[i:j:k]``, a slice object is\n created, and passed to ``__setitem__()``, instead of\n ``__setslice__()`` being called.\n\nobject.__delslice__(self, i, j)\n\n Called to implement deletion of ``self[i:j]``. Same notes for *i*\n and *j* as for ``__getslice__()``. This method is deprecated. If no\n ``__delslice__()`` is found, or for extended slicing of the form\n ``self[i:j:k]``, a slice object is created, and passed to\n ``__delitem__()``, instead of ``__delslice__()`` being called.\n\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used, and the slice method is available. For slice\noperations involving extended slice notation, or in absence of the\nslice methods, ``__getitem__()``, ``__setitem__()`` or\n``__delitem__()`` is called with a slice object as argument.\n\nThe following example demonstrate how to make your program or module\ncompatible with earlier versions of Python (assuming that methods\n``__getitem__()``, ``__setitem__()`` and ``__delitem__()`` support\nslice objects as arguments):\n\n class MyClass:\n ...\n def __getitem__(self, index):\n ...\n def __setitem__(self, index, value):\n ...\n def __delitem__(self, index):\n ...\n\n if sys.version_info < (2, 0):\n # They won\'t be defined if version is at least 2.0 final\n\n def __getslice__(self, i, j):\n return self[max(0, i):max(0, j):]\n def __setslice__(self, i, j, seq):\n self[max(0, i):max(0, j):] = seq\n def __delslice__(self, i, j):\n del self[max(0, i):max(0, j):]\n ...\n\nNote the calls to ``max()``; these are necessary because of the\nhandling of negative indices before the ``__*slice__()`` methods are\ncalled. When negative indexes are used, the ``__*item__()`` methods\nreceive them as provided, but the ``__*slice__()`` methods get a\n"cooked" form of the index values. For each negative index value, the\nlength of the sequence is added to the index before calling the method\n(which may still result in a negative index); this is the customary\nhandling of negative indexes by the built-in sequence types, and the\n``__*item__()`` methods are expected to do this as well. However,\nsince they should already be doing that, negative indexes cannot be\npassed in; they must be constrained to the bounds of the sequence\nbefore being passed to the ``__*item__()`` methods. Calling ``max(0,\ni)`` conveniently returns the proper value.\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.__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 (``+``, ``-``, ``*``, ``//``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to evaluate the expression ``x + y``, where *x* is an\n 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__()`` (described below). Note\n that ``__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.__div__(self, other)\nobject.__truediv__(self, other)\n\n The division operator (``/``) is implemented by these methods. The\n ``__truediv__()`` method is used when ``__future__.division`` is in\n effect, otherwise ``__div__()`` is used. If only one of these two\n methods is defined, the object will not support division in the\n alternate context; ``TypeError`` will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(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 (``+``, ``-``, ``*``, ``/``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected (swapped) operands. These functions are only called if\n the left operand does not support the corresponding operation and\n the operands are of different types. [2] For instance, to evaluate\n the expression ``x - y``, where *y* is an instance of a class that\n has an ``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)`` returns *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.__idiv__(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.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``long()``, and ``float()``. Should return a value of\n the appropriate type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to implement the built-in functions ``oct()`` and ``hex()``.\n Should return a string value.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing). Must return\n an integer (int or long).\n\n New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to implement "mixed-mode" numeric arithmetic. Should either\n return a 2-tuple containing *self* and *other* converted to a\n common numeric type, or ``None`` if conversion is impossible. When\n the common type would be the type of ``other``, it is sufficient to\n return ``None``, since the interpreter will also ask the other\n object to attempt a coercion (but sometimes, if the implementation\n of the other type cannot be changed, it is useful to do the\n conversion to the other type here). A return value of\n ``NotImplemented`` is equivalent to returning ``None``.\n\n\nCoercion rules\n==============\n\nThis section used to document the rules for coercion. As the language\nhas evolved, the coercion rules have become hard to document\nprecisely; documenting what one version of one particular\nimplementation does is undesirable. Instead, here are some informal\nguidelines regarding coercion. In Python 3.0, coercion will not be\nsupported.\n\n* If the left operand of a % operator is a string or Unicode object,\n no coercion takes place and the string formatting operation is\n invoked instead.\n\n* It is no longer recommended to define a coercion operation. Mixed-\n mode operations on types that don\'t define coercion pass the\n original arguments to the operation.\n\n* New-style classes (those derived from ``object``) never invoke the\n ``__coerce__()`` method in response to a binary operator; the only\n time ``__coerce__()`` is invoked is when the built-in function\n ``coerce()`` is called.\n\n* For most intents and purposes, an operator that returns\n ``NotImplemented`` is treated the same as one that is not\n implemented at all.\n\n* Below, ``__op__()`` and ``__rop__()`` are used to signify the\n generic method names corresponding to an operator; ``__iop__()`` is\n used for the corresponding in-place operator. For example, for the\n operator \'``+``\', ``__add__()`` and ``__radd__()`` are used for the\n left and right variant of the binary operator, and ``__iadd__()``\n for the in-place variant.\n\n* For objects *x* and *y*, first ``x.__op__(y)`` is tried. If this is\n not implemented or returns ``NotImplemented``, ``y.__rop__(x)`` is\n tried. If this is also not implemented or returns\n ``NotImplemented``, a ``TypeError`` exception is raised. But see\n the following exception:\n\n* Exception to the previous item: if the left operand is an instance\n of a built-in type or a new-style class, and the right operand is an\n instance of a proper subclass of that type or class and overrides\n the base\'s ``__rop__()`` method, the right operand\'s ``__rop__()``\n method is tried *before* the left operand\'s ``__op__()`` method.\n\n This is done so that a subclass can completely override binary\n operators. Otherwise, the left operand\'s ``__op__()`` method would\n always accept the right operand: when an instance of a given class\n is expected, an instance of a subclass of that class is always\n acceptable.\n\n* When either operand type defines a coercion, this coercion is called\n before that type\'s ``__op__()`` or ``__rop__()`` method is called,\n but no sooner. If the coercion returns an object of a different\n type for the operand whose coercion is invoked, part of the process\n is redone using the new object.\n\n* When an in-place operator (like \'``+=``\') is used, if the left\n operand implements ``__iop__()``, it is invoked without any\n coercion. When the operation falls back to ``__op__()`` and/or\n ``__rop__()``, the normal coercion rules apply.\n\n* In ``x + y``, if *x* is a sequence that implements sequence\n concatenation, sequence concatenation is invoked.\n\n* In ``x * y``, if one operand is a sequence that implements sequence\n repetition, and the other is an integer (``int`` or ``long``),\n sequence repetition is invoked.\n\n* Rich comparisons (implemented by methods ``__eq__()`` and so on)\n never use coercion. Three-way comparison (implemented by\n ``__cmp__()``) does use coercion under the same conditions as other\n binary operations use it.\n\n* In the current implementation, the built-in numeric types ``int``,\n ``long``, ``float``, and ``complex`` do not use coercion. All these\n types implement a ``__coerce__()`` method, for use by the built-in\n ``coerce()`` function.\n\n Changed in version 2.7.\n\n\nWith Statement Context Managers\n===============================\n\nNew in version 2.5.\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 for old-style classes\n===========================================\n\nFor old-style classes, special methods are always looked up in exactly\nthe same way as any other method or attribute. This is the case\nregardless of whether the method is being looked up explicitly as in\n``x.__getitem__(i)`` or implicitly as in ``x[i]``.\n\nThis behaviour means that special methods may exhibit different\nbehaviour for different instances of a single old-style class if the\nappropriate special attributes are set differently:\n\n >>> class C:\n ... pass\n ...\n >>> c1 = C()\n >>> c2 = C()\n >>> c1.__len__ = lambda: 5\n >>> c2.__len__ = lambda: 9\n >>> len(c1)\n 5\n >>> len(c2)\n 9\n\n\nSpecial method lookup for new-style classes\n===========================================\n\nFor new-style classes, implicit invocations of special methods are\nonly guaranteed to work correctly if defined on an object\'s type, not\nin the object\'s instance dictionary. That behaviour is the reason why\nthe following code raises an exception (unlike the equivalent example\nwith old-style classes):\n\n >>> class C(object):\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):\n ... __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\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support. Some of them are also available on\n``bytearray`` objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output formatted strings use\ntemplate strings or the ``%`` operator described in the *String\nFormatting Operations* section. Also, see the ``re`` module for string\nfunctions based on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with its first character capitalized\n and the rest lowercased.\n\n For 8-bit strings, this method is locale-dependent.\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\n Changed in version 2.4: Support for the *fillchar* argument.\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.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: 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\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one 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\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\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.\n\n For 8-bit strings, this method is locale-dependent.\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.\n\n For 8-bit strings, this method is locale-dependent.\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.\n\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\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.\n\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n 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\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string with all the cased characters [4]\n converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\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\n Changed in version 2.2.2: Support for the *chars* argument.\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\n New in version 2.5.\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\n Changed in version 2.4: Support for the *fillchar* argument.\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\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\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\n New in version 2.4.\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\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\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, then there is no limit\n 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. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\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\n Changed in version 2.5: Accept tuples as *prefix*.\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\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n 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 For 8-bit strings, this method is locale-dependent.\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\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that can be used to form decimal-radix numbers,\n e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n', 'strings': '\nString literals\n***************\n\nString literals are described by the following lexical definitions:\n\n stringliteral ::= [stringprefix](shortstring | longstring)\n stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"\n | "b" | "B" | "br" | "Br" | "bR" | "BR"\n shortstring ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n longstring ::= "\'\'\'" longstringitem* "\'\'\'"\n | \'"""\' longstringitem* \'"""\'\n shortstringitem ::= shortstringchar | escapeseq\n longstringitem ::= longstringchar | escapeseq\n shortstringchar ::= <any source character except "\\" or newline or the quote>\n longstringchar ::= <any source character except "\\">\n escapeseq ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the ``stringprefix`` and the rest of\nthe string literal. The source character set is defined by the\nencoding declaration; it is ASCII if no encoding declaration is given\nin the source file; see section *Encoding declarations*.\n\nIn plain English: String literals can be enclosed in matching single\nquotes (``\'``) or double quotes (``"``). They can also be enclosed in\nmatching groups of three single or double quotes (these are generally\nreferred to as *triple-quoted strings*). The backslash (``\\``)\ncharacter is used to escape characters that otherwise have a special\nmeaning, such as newline, backslash itself, or the quote character.\nString literals may optionally be prefixed with a letter ``\'r\'`` or\n``\'R\'``; such strings are called *raw strings* and use different rules\nfor interpreting backslash escape sequences. A prefix of ``\'u\'`` or\n``\'U\'`` makes the string a Unicode string. Unicode strings use the\nUnicode character set as defined by the Unicode Consortium and ISO\n10646. Some additional escape sequences, described below, are\navailable in Unicode strings. A prefix of ``\'b\'`` or ``\'B\'`` is\nignored in Python 2; it indicates that the literal should become a\nbytes literal in Python 3 (e.g. when code is automatically converted\nwith 2to3). A ``\'u\'`` or ``\'b\'`` prefix may be followed by an ``\'r\'``\nprefix.\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`` | 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| ``\\N{name}`` | Character named *name* in the | |\n| | Unicode database (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| ``\\r`` | ASCII Carriage Return (CR) | |\n+-------------------+-----------------------------------+---------+\n| ``\\t`` | ASCII Horizontal Tab (TAB) | |\n+-------------------+-----------------------------------+---------+\n| ``\\uxxxx`` | Character with 16-bit hex value | (1) |\n| | *xxxx* (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| ``\\Uxxxxxxxx`` | Character with 32-bit hex value | (2) |\n| | *xxxxxxxx* (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| ``\\v`` | ASCII Vertical Tab (VT) | |\n+-------------------+-----------------------------------+---------+\n| ``\\ooo`` | Character with octal value *ooo* | (3,5) |\n+-------------------+-----------------------------------+---------+\n| ``\\xhh`` | Character with hex value *hh* | (4,5) |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. Individual code units which form parts of a surrogate pair can be\n encoded using this escape sequence.\n\n2. Any Unicode character can be encoded this way, but characters\n outside the Basic Multilingual Plane (BMP) will be encoded using a\n surrogate pair if Python is compiled to use 16-bit code units (the\n default). Individual code units which form parts of a surrogate\n pair can be encoded using this escape sequence.\n\n3. As in Standard C, up to three octal digits are accepted.\n\n4. Unlike in Standard C, exactly two hex digits are required.\n\n5. In a string literal, hexadecimal and octal escapes denote the byte\n with the given value; it is not necessary that the byte encodes a\n character in the source character set. In a Unicode literal, these\n escapes denote a Unicode character with the given value.\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 marked as "(Unicode only)"\nin the table above fall into the category of unrecognized escapes for\nnon-Unicode string literals.\n\nWhen an ``\'r\'`` or ``\'R\'`` prefix is present, a character following a\nbackslash is included in the string without change, and *all\nbackslashes are left in the string*. For example, the string literal\n``r"\\n"`` consists of two characters: a backslash and a lowercase\n``\'n\'``. String quotes can be escaped with a backslash, but the\nbackslash remains in the string; for example, ``r"\\""`` is a valid\nstring literal consisting of two characters: a backslash and a double\nquote; ``r"\\"`` is not a valid string literal (even a raw string\ncannot end in an odd number of backslashes). Specifically, *a raw\nstring cannot end in a single backslash* (since the backslash would\nescape 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\nWhen an ``\'r\'`` or ``\'R\'`` prefix is used in conjunction with a\n``\'u\'`` or ``\'U\'`` prefix, then the ``\\uXXXX`` and ``\\UXXXXXXXX``\nescape sequences are processed while *all other backslashes are left\nin the string*. For example, the string literal ``ur"\\u0062\\n"``\nconsists of three Unicode characters: \'LATIN SMALL LETTER B\', \'REVERSE\nSOLIDUS\', and \'LATIN SMALL LETTER N\'. Backslashes can be escaped with\na preceding backslash; however, both remain in the string. As a\nresult, ``\\uXXXX`` escape sequences are only recognized when there are\nan odd number of backslashes.\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 of a sequence or mapping type.\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 a\nplain integer. If this value is negative, the length of the sequence\nis added to it (so that, e.g., ``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).\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``, ``0L``, ``0.0``,\n ``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 ``__nonzero__()`` or ``__len__()`` method, when that method returns\n the 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\nChanged in version 2.5: In previous versions of Python,\n``try``...``except``...``finally`` did not work. ``try``...``except``\nhad to be nested in ``try``...``finally``.\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, a tuple containing an item compatible with the\nexception, or, in the (deprecated) case of string exceptions, is the\nraised string itself (note that the object identities must match, i.e.\nit must be the same string object, not just a string with the same\nvalue).\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 in that except clause, if present, and the except\nclause\'s suite is executed. All except clauses must have an\nexecutable block. When the end of this block is reached, execution\ncontinues normally after the entire try statement. (This means that\nif two nested handlers exist for the same exception, and the exception\noccurs in the try clause of the inner handler, the outer handler will\nnot handle the exception.)\n\nBefore an except clause\'s suite is executed, details about the\nexception are assigned to three variables in the ``sys`` module:\n``sys.exc_type`` receives the object identifying the exception;\n``sys.exc_value`` receives the exception\'s parameter;\n``sys.exc_traceback`` receives a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. These details are also available through the\n``sys.exc_info()`` function, which returns a tuple ``(exc_type,\nexc_value, exc_traceback)``. Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program. As of Python 1.5, the variables are restored to\ntheir previous values (before the call) when returning from a function\nthat 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\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost. The exception information is not available to the\nprogram during execution 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.).\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 built-in name\n ``Ellipsis``. It is used to indicate the presence of the ``...``\n syntax in a slice. 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 three types of integers:\n\n Plain integers\n These represent numbers in the range -2147483648 through\n 2147483647. (The range may be larger on machines with a\n larger natural word size, but not smaller.) When the result\n of an operation would fall outside this range, the result is\n normally returned as a long integer (in some cases, the\n exception ``OverflowError`` is raised instead). For the\n purpose of shift and mask operations, integers are assumed to\n have a binary, 2\'s complement notation using 32 or more bits,\n and hiding no bits from the user (i.e., all 4294967296\n different bit patterns correspond to different values).\n\n Long integers\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\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 plain\n integers, 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 and the least surprises when\n switching between the plain and long integer domains. Any\n operation, if it yields a result in the plain integer domain,\n will yield the same result in the long integer domain or when\n using mixed operands. The switch between domains is transparent\n to the programmer.\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``\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 The items of a string are characters. There is no separate\n character type; a character is represented by a string of one\n item. Characters represent (at least) 8-bit bytes. The\n built-in functions ``chr()`` and ``ord()`` convert between\n characters and nonnegative integers representing the byte\n values. Bytes with the values 0-127 usually represent the\n corresponding ASCII values, but the interpretation of values\n is up to the program. The string data type is also used to\n represent arrays of bytes, e.g., to hold data read from a\n file.\n\n (On systems whose native character set is not ASCII, strings\n may use EBCDIC in their internal representation, provided the\n functions ``chr()`` and ``ord()`` implement a mapping between\n ASCII and EBCDIC, and string comparison preserves the ASCII\n order. Or perhaps someone can propose a better rule?)\n\n Unicode\n The items of a Unicode object are Unicode code units. A\n Unicode code unit is represented by a Unicode object of one\n item and can hold either a 16-bit or 32-bit value\n representing a Unicode ordinal (the maximum value for the\n ordinal is given in ``sys.maxunicode``, and depends on how\n Python is configured at compile time). Surrogate pairs may\n be present in the Unicode object, and will be reported as two\n separate items. The built-in functions ``unichr()`` and\n ``ord()`` convert between code units and nonnegative integers\n representing the Unicode ordinals as defined in the Unicode\n Standard 3.0. Conversion from and to other encodings are\n possible through the Unicode method ``encode()`` and the\n built-in function ``unicode()``.\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 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.\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``, ``gdbm``, and ``bsddb`` provide\n additional examples of mapping types.\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 | ``func_doc`` | The function\'s documentation | Writable |\n | | string, or ``None`` if | |\n | | unavailable | |\n +-------------------------+---------------------------------+-------------+\n | ``__doc__`` | Another way of spelling | Writable |\n | | ``func_doc`` | |\n +-------------------------+---------------------------------+-------------+\n | ``func_name`` | The function\'s name | Writable |\n +-------------------------+---------------------------------+-------------+\n | ``__name__`` | Another way of spelling | Writable |\n | | ``func_name`` | |\n +-------------------------+---------------------------------+-------------+\n | ``__module__`` | The name of the module the | Writable |\n | | function was defined in, or | |\n | | ``None`` if unavailable. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_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 | ``func_code`` | The code object representing | Writable |\n | | the compiled function body. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_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 | ``func_dict`` | The namespace supporting | Writable |\n | | arbitrary function attributes. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_closure`` | ``None`` or a tuple of cells | Read-only |\n | | that contain bindings for the | |\n | | function\'s free variables. | |\n +-------------------------+---------------------------------+-------------+\n\n Most of the attributes labelled "Writable" check the type of the\n assigned value.\n\n Changed in version 2.4: ``func_name`` is now writable.\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 User-defined methods\n A user-defined method object combines a class, a class instance\n (or ``None``) and any callable object (normally a user-defined\n function).\n\n Special read-only attributes: ``im_self`` is the class instance\n object, ``im_func`` is the function object; ``im_class`` is the\n class of ``im_self`` for bound methods or the class that asked\n for the method for unbound methods; ``__doc__`` is the method\'s\n documentation (same as ``im_func.__doc__``); ``__name__`` is the\n method name (same as ``im_func.__name__``); ``__module__`` is\n the name of the module the method was defined in, or ``None`` if\n unavailable.\n\n Changed in version 2.2: ``im_self`` used to refer to the class\n that defined the method.\n\n Changed in version 2.6: For 3.0 forward-compatibility,\n ``im_func`` is also available as ``__func__``, and ``im_self``\n as ``__self__``.\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, an unbound\n user-defined method object, or a class method object. When the\n attribute is a user-defined method object, a new method object\n is only created if the class from which it is being retrieved is\n the same as, or a derived class of, the class stored in the\n original method object; otherwise, the original method object is\n used as it is.\n\n When a user-defined method object is created by retrieving a\n user-defined function object from a class, its ``im_self``\n attribute is ``None`` and the method object is said to be\n unbound. When one is created by retrieving a user-defined\n function object from a class via one of its instances, its\n ``im_self`` attribute is the instance, and the method object is\n said to be bound. In either case, the new method\'s ``im_class``\n attribute is the class from which the retrieval takes place, and\n its ``im_func`` 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 ``im_func``\n attribute of the new instance is not the original method object\n but its ``im_func`` attribute.\n\n When a user-defined method object is created by retrieving a\n class method object from a class or instance, its ``im_self``\n attribute is the class itself (the same as the ``im_class``\n attribute), and its ``im_func`` attribute is the function object\n underlying the class method.\n\n When an unbound user-defined method object is called, the\n underlying function (``im_func``) is called, with the\n restriction that the first argument must be an instance of the\n proper class (``im_class``) or of a derived class thereof.\n\n When a bound user-defined method object is called, the\n underlying function (``im_func``) is called, inserting the class\n instance (``im_self``) in front of the argument list. For\n instance, when ``C`` is a class which contains a definition for\n a function ``f()``, and ``x`` is an instance of ``C``, calling\n ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``.\n\n When a user-defined method object is derived from a class method\n object, the "class instance" stored in ``im_self`` will actually\n be the class itself, so that calling either ``x.f(1)`` or\n ``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 (unbound or\n bound) method object happens each time the attribute is\n retrieved from the class or instance. In some cases, a fruitful\n optimization is to assign the attribute to a local variable and\n call that local variable. Also notice that this transformation\n only happens for user-defined functions; other callable objects\n (and all non-callable objects) are retrieved without\n transformation. It is also important to note that user-defined\n functions which are attributes of a class instance are not\n converted to bound methods; this *only* happens when the\n function is an attribute 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 ``next()`` method will cause the function to\n execute until it provides a value using the ``yield`` statement.\n When the function executes a ``return`` statement or falls off\n the end, a ``StopIteration`` exception is raised and the\n iterator will have reached the end of the set of values to be\n 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 Class Types\n Class types, or "new-style classes," are callable. These\n objects normally act as factories for new instances of\n themselves, but variations are possible for class types that\n override ``__new__()``. The arguments of the call are passed to\n ``__new__()`` and, in the typical case, to ``__init__()`` to\n initialize the new instance.\n\n Classic Classes\n Class objects are described below. When a class object is\n called, a new class instance (also described below) is created\n and returned. This implies a call to the class\'s ``__init__()``\n method if it has one. Any arguments are passed on to the\n ``__init__()`` method. If there is no ``__init__()`` method,\n the class must be called without arguments.\n\n Class instances\n Class instances are described below. Class instances are\n callable only when the class has a ``__call__()`` method;\n ``x(arguments)`` is a shorthand for ``x.__call__(arguments)``.\n\nModules\n Modules are imported by the ``import`` statement (see section *The\n import statement*). A module object has a namespace implemented by\n a dictionary object (this is the dictionary referenced by the\n func_globals attribute of functions defined in the module).\n Attribute references are translated to lookups in this dictionary,\n e.g., ``m.x`` is equivalent to ``m.__dict__["x"]``. A module object\n does not contain the code object used to initialize the module\n (since it isn\'t 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 is not present for C modules that are\n statically linked into the interpreter; for extension modules\n loaded dynamically from a shared library, it is the pathname of the\n shared library file.\n\nClasses\n Both class types (new-style classes) and class objects (old-\n style/classic classes) are typically created by class definitions\n (see section *Class definitions*). A class has a namespace\n implemented by a dictionary object. Class attribute references are\n translated to lookups in this dictionary, e.g., ``C.x`` is\n translated to ``C.__dict__["x"]`` (although for new-style classes\n in particular there are a number of hooks which allow for other\n means of locating attributes). When the attribute name is not found\n there, the attribute search continues in the base classes. For\n old-style classes, the search is depth-first, left-to-right in the\n order of occurrence in the base class list. New-style classes use\n the more complex C3 method resolution order which behaves correctly\n even in the presence of \'diamond\' inheritance structures where\n there are multiple inheritance paths leading back to a common\n ancestor. Additional details on the C3 MRO used by new-style\n classes can be found in the documentation accompanying the 2.3\n release at http://www.python.org/download/releases/2.3/mro/.\n\n When a class attribute reference (for class ``C``, say) would yield\n a user-defined function object or an unbound user-defined method\n object whose associated class is either ``C`` or one of its base\n classes, it is transformed into an unbound user-defined method\n object whose ``im_class`` attribute is ``C``. When it would yield a\n class method object, it is transformed into a bound user-defined\n method object whose ``im_class`` and ``im_self`` attributes are\n both ``C``. When it would yield a static method object, it is\n transformed into the object wrapped by the static method object.\n See section *Implementing Descriptors* for another way in which\n attributes retrieved from a class may differ from those actually\n contained in its ``__dict__`` (note that only new-style classes\n support descriptors).\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 or an unbound user-defined method object whose\n associated class is the class (call it ``C``) of the instance for\n which the attribute reference was initiated or one of its bases, it\n is transformed into a bound user-defined method object whose\n ``im_class`` attribute is ``C`` and whose ``im_self`` attribute is\n the instance. Static method and class method objects are also\n transformed, as if they had been retrieved from class ``C``; see\n above under "Classes". See section *Implementing Descriptors* for\n another way in which attributes of a class retrieved via its\n instances may differ from the objects actually stored in the\n class\'s ``__dict__``. If no class attribute is found, and the\n object\'s class has a ``__getattr__()`` method, that is called to\n satisfy the 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\nFiles\n A file object represents an open file. File objects are created by\n the ``open()`` built-in function, and also by ``os.popen()``,\n ``os.fdopen()``, and the ``makefile()`` method of socket objects\n (and perhaps by other functions or methods provided by extension\n modules). The objects ``sys.stdin``, ``sys.stdout`` and\n ``sys.stderr`` are initialized to file objects corresponding to the\n interpreter\'s standard input, output and error streams. See *File\n Objects* for complete documentation of file objects.\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_restricted`` is a flag indicating whether the function is\n executing in restricted execution mode; ``f_lasti`` gives the\n precise instruction (this is an index into the bytecode string\n 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_exc_type``, ``f_exc_value``,\n ``f_exc_traceback`` represent the last exception raised in the\n parent frame provided another exception was ever raised in the\n current frame (in all other cases they are None); ``f_lineno``\n is the current line number of the frame --- writing to this from\n within a trace function jumps to the given line (only for the\n bottom-most frame). A debugger can implement a Jump command\n (aka Set Next Statement) 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 ``sys.exc_traceback``,\n and also as the third item of the tuple returned by\n ``sys.exc_info()``. The latter is the preferred interface,\n since it works correctly when the program is using multiple\n threads. When the program contains no suitable handler, the\n stack trace is written (nicely formatted) to the standard error\n stream; if the interpreter is interactive, it is also made\n available to the user as ``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 when *extended slice\n syntax* is used. This is a slice using two colons, or multiple\n slices or ellipses separated by commas, e.g., ``a[i:j:step]``,\n ``a[i:j, k:l]``, or ``a[..., i:j]``. They are also created by\n the built-in ``slice()`` 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 extended slice that the slice\n object would describe if applied to a sequence of *length*\n items. It returns a tuple of three integers; respectively\n these are the *start* and *stop* indices and the *step* or\n stride length of the slice. Missing or out-of-bounds indices\n are handled in a manner consistent with regular slices.\n\n New in version 2.3.\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([arg])\n\n Return a new dictionary initialized from an optional positional\n argument or from a set of keyword arguments. If no arguments are\n given, return a new empty dictionary. If the positional argument\n *arg* is a mapping object, return a dictionary mapping the same\n keys to the same values as does the mapping object. Otherwise the\n positional argument must be a sequence, a container that supports\n iteration, or an iterator object. The elements of the argument\n must each also be of one of those kinds, and each must in turn\n contain exactly two objects. The first is used as a key in the new\n dictionary, and the second as the key\'s value. If a given key is\n seen more than once, the last value associated with it is retained\n in the new dictionary.\n\n If keyword arguments are given, the keywords themselves with their\n associated values are added as items to the dictionary. If a key is\n specified both in the positional argument and as a keyword\n argument, the value associated with the keyword is retained in the\n dictionary. For example, these all return a dictionary equal to\n ``{"one": 1, "two": 2}``:\n\n * ``dict(one=1, two=2)``\n\n * ``dict({\'one\': 1, \'two\': 2})``\n\n * ``dict(zip((\'one\', \'two\'), (1, 2)))``\n\n * ``dict([[\'two\', 2], [\'one\', 1]])``\n\n The first example only works for keys that are valid Python\n identifiers; the others work with any valid keys.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for building a dictionary from\n keyword arguments added.\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 New in version 2.5: If a subclass of dict defines a method\n ``__missing__()``, if the key *key* is not present, the\n ``d[key]`` operation calls that method with the key *key* as\n argument. The ``d[key]`` operation then returns or raises\n whatever is returned or raised by the ``__missing__(key)`` call\n if the key is not present. No other operations or methods invoke\n ``__missing__()``. If ``__missing__()`` is not defined,\n ``KeyError`` is raised. ``__missing__()`` must be a method; it\n cannot be an instance variable. For an example, see\n ``collections.defaultdict``.\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 New in version 2.2.\n\n key not in d\n\n Equivalent to ``not key in d``.\n\n New in version 2.2.\n\n iter(d)\n\n Return an iterator over the keys of the dictionary. This is a\n shortcut for ``iterkeys()``.\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 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 New in version 2.3.\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 has_key(key)\n\n Test for the presence of *key* in the dictionary. ``has_key()``\n is deprecated in favor of ``key in d``.\n\n items()\n\n Return a copy of the dictionary\'s list of ``(key, value)``\n pairs.\n\n **CPython implementation detail:** Keys and values are listed in\n an arbitrary order which is non-random, varies across Python\n implementations, and depends on the dictionary\'s history of\n insertions and deletions.\n\n If ``items()``, ``keys()``, ``values()``, ``iteritems()``,\n ``iterkeys()``, and ``itervalues()`` are called with no\n intervening modifications to the dictionary, the lists will\n directly correspond. This allows the creation of ``(value,\n key)`` pairs using ``zip()``: ``pairs = zip(d.values(),\n d.keys())``. The same relationship holds for the ``iterkeys()``\n and ``itervalues()`` methods: ``pairs = zip(d.itervalues(),\n d.iterkeys())`` provides the same value for ``pairs``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.iteritems()]``.\n\n iteritems()\n\n Return an iterator over the dictionary\'s ``(key, value)`` pairs.\n See the note for ``dict.items()``.\n\n Using ``iteritems()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n iterkeys()\n\n Return an iterator over the dictionary\'s keys. See the note for\n ``dict.items()``.\n\n Using ``iterkeys()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n itervalues()\n\n Return an iterator over the dictionary\'s values. See the note\n for ``dict.items()``.\n\n Using ``itervalues()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n keys()\n\n Return a copy of the dictionary\'s list of keys. See the note\n for ``dict.items()``.\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 New in version 2.3.\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 Changed in version 2.4: Allowed the argument to be an iterable\n of key/value pairs and allowed keyword arguments.\n\n values()\n\n Return a copy of the dictionary\'s list of values. See the note\n for ``dict.items()``.\n\n viewitems()\n\n Return a new view of the dictionary\'s items (``(key, value)``\n pairs). See below for documentation of view objects.\n\n New in version 2.7.\n\n viewkeys()\n\n Return a new view of the dictionary\'s keys. See below for\n documentation of view objects.\n\n New in version 2.7.\n\n viewvalues()\n\n Return a new view of the dictionary\'s values. See below for\n documentation of view objects.\n\n New in version 2.7.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.viewkeys()``, ``dict.viewvalues()`` and\n``dict.viewitems()`` are *view objects*. They provide a dynamic view\non the 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 and\nhashable, then the items view is also set-like. (Values views are not\ntreated as set-like since the entries are generally not unique.) Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n Return the intersection of the dictview and the other object as a\n new set.\n\ndictview | other\n\n Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n Return the difference between the dictview and the other object\n (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n Return the symmetric difference (all elements either in *dictview*\n or *other*, but not in both) of the dictview and the other object\n as a new set.\n\nAn example of dictionary view usage:\n\n >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n >>> keys = dishes.viewkeys()\n >>> values = dishes.viewvalues()\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', '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\nThe implementation adds two special read-only attributes to class\ninstance methods: ``m.im_self`` is the object on which the method\noperates, and ``m.im_func`` is the function implementing the method.\nCalling ``m(arg-1, arg-2, ..., arg-n)`` is completely equivalent to\ncalling ``m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)``.\n\nClass instance methods are either *bound* or *unbound*, referring to\nwhether the method was accessed through an instance or a class,\nrespectively. When a method is unbound, its ``im_self`` attribute\nwill be ``None`` and if called, an explicit ``self`` object must be\npassed as the first argument. In this case, ``self`` must be an\ninstance of the unbound method's class (or a subclass of that class),\notherwise a ``TypeError`` is raised.\n\nLike function objects, methods objects support getting arbitrary\nattributes. However, since method attributes are actually stored on\nthe underlying function object (``meth.im_func``), setting method\nattributes on either bound or unbound methods is disallowed.\nAttempting to set a method attribute results in a ``TypeError`` being\nraised. In order to set a method attribute, you need to explicitly\nset it on the underlying function object:\n\n class C:\n def method(self):\n pass\n\n c = C()\n c.method.im_func.whoami = 'my name is c'\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 --- ``str``, ``unicode``, ``list``, ``tuple``, ``bytearray``, ``buffer``, ``xrange``\n***************************************************************************************************\n\nThere are seven sequence types: strings, Unicode strings, lists,\ntuples, bytearrays, buffers, and xrange objects.\n\nFor other containers see the built in ``dict`` and ``set`` classes,\nand the ``collections`` module.\n\nString literals are written in single or double quotes: ``\'xyzzy\'``,\n``"frobozz"``. See *String literals* for more about string literals.\nUnicode strings are much like strings, but are specified in the syntax\nusing a preceding ``\'u\'`` character: ``u\'abc\'``, ``u"def"``. In\naddition to the functionality described here, there are also string-\nspecific methods described in the *String Methods* section. Lists are\nconstructed with square brackets, separating items with commas: ``[a,\nb, c]``. Tuples are constructed by the comma operator (not within\nsquare brackets), with or without enclosing parentheses, but an empty\ntuple must have the enclosing parentheses, such as ``a, b, c`` or\n``()``. A single item tuple must have a trailing comma, such as\n``(d,)``.\n\nBytearray objects are created with the built-in function\n``bytearray()``.\n\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the built-in function ``buffer()``. They don\'t\nsupport concatenation or repetition.\n\nObjects of type xrange are similar to buffers in that there is no\nspecific syntax to create them, but they are created using the\n``xrange()`` function. They don\'t support slicing, concatenation or\nrepetition, and using ``in``, ``not in``, ``min()`` or ``max()`` on\nthem is inefficient.\n\nMost sequence types support the following operations. The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations. The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable 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* and *j* are\nintegers:\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) |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s`` | *n* shallow copies of *s* | (2) |\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(i)`` | index of the first occurence of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n| ``s.count(i)`` | total number of occurences of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons. In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements. This means that to compare equal, every element must compare\nequal and the two sequences must be of the same type and have the same\nlength. (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string or Unicode string object the ``in`` and ``not\n in`` operations act like a substring test. In Python versions\n before 2.3, *x* had to be a string of length 1. In Python 2.3 and\n beyond, *x* may be a string of any length.\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. **CPython implementation detail:** If *s* and *t* are both strings,\n some Python implementations such as CPython can usually perform an\n in-place optimization for assignments of the form ``s = s + t`` or\n ``s += t``. When applicable, this optimization makes quadratic\n run-time much less likely. This optimization is both version and\n implementation dependent. For performance sensitive code, it is\n preferable to use the ``str.join()`` method which assures\n consistent linear concatenation performance across versions and\n implementations.\n\n Changed in version 2.4: Formerly, string concatenation never\n occurred in-place.\n\n\nString Methods\n==============\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support. Some of them are also available on\n``bytearray`` objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output formatted strings use\ntemplate strings or the ``%`` operator described in the *String\nFormatting Operations* section. Also, see the ``re`` module for string\nfunctions based on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with its first character capitalized\n and the rest lowercased.\n\n For 8-bit strings, this method is locale-dependent.\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\n Changed in version 2.4: Support for the *fillchar* argument.\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.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: 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\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one 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\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\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.\n\n For 8-bit strings, this method is locale-dependent.\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.\n\n For 8-bit strings, this method is locale-dependent.\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.\n\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\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.\n\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n 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\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string with all the cased characters [4]\n converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\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\n Changed in version 2.2.2: Support for the *chars* argument.\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\n New in version 2.5.\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\n Changed in version 2.4: Support for the *fillchar* argument.\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\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\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\n New in version 2.4.\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\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\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, then there is no limit\n 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. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\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\n Changed in version 2.5: Accept tuples as *prefix*.\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\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\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\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n 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 For 8-bit strings, this method is locale-dependent.\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\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that can be used to form decimal-radix numbers,\n e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the\n``%`` operator (modulo). This is also known as the string\n*formatting* or *interpolation* operator. Given ``format % values``\n(where *format* is a string or Unicode object), ``%`` conversion\nspecifications in *format* are replaced with zero or more elements of\n*values*. The effect is similar to the using ``sprintf()`` in the C\nlanguage. If *format* is a Unicode object, or if any of the objects\nbeing converted using the ``%s`` conversion are Unicode objects, the\nresult will also be a Unicode object.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [5] Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n conversion types.\n\n4. Minimum field width (optional). If specified as an ``\'*\'``\n (asterisk), the actual width is read from the next element of the\n tuple in *values*, and the object to convert comes after the\n minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n precision. If specified as ``\'*\'`` (an asterisk), the actual width\n is read from the next element of the tuple in *values*, and the\n value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print \'%(language)s has %(number)03d quote types.\' % \\\n... {"language": "Python", "number": 2}\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag | Meaning |\n+===========+=======================================================================+\n| ``\'#\'`` | The value conversion will use the "alternate form" (where defined |\n| | below). |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'`` | The conversion will be zero padded for numeric values. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'`` | The converted value is left adjusted (overrides the ``\'0\'`` |\n| | conversion if both are given). |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'`` | (a space) A blank should be left before a positive number (or empty |\n| | string) produced by a signed conversion. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'`` | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion |\n| | (overrides a "space" flag). |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion | Meaning | Notes |\n+==============+=======================================================+=========+\n| ``\'d\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'`` | Signed octal value. | (1) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'`` | Obsolete type -- it is identical to ``\'d\'``. | (7) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'`` | Signed hexadecimal (lowercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'`` | Signed hexadecimal (uppercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'`` | Floating point exponential format (lowercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'`` | Floating point exponential format (uppercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'`` | Floating point format. Uses lowercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'`` | Floating point format. Uses uppercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'`` | Single character (accepts integer or single character | |\n| | string). | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'`` | String (converts any Python object using ``repr()``). | (5) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'`` | String (converts any Python object using ``str()``). | (6) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'`` | No argument is converted, results in a ``\'%\'`` | |\n| | character in the result. | |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. The alternate form causes a leading zero (``\'0\'``) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n2. The alternate form causes a leading ``\'0x\'`` or ``\'0X\'`` (depending\n on whether the ``\'x\'`` or ``\'X\'`` format was used) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n point, even if no digits follow it.\n\n The precision determines the number of digits after the decimal\n point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n point, and trailing zeroes are not removed as they would otherwise\n be.\n\n The precision determines the number of significant digits before\n and after the decimal point and defaults to 6.\n\n5. The ``%r`` conversion was added in Python 2.0.\n\n The precision determines the maximal number of characters used.\n\n6. If the object or format provided is a ``unicode`` string, the\n resulting string will also be ``unicode``.\n\n The precision determines the maximal number of characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 2.7: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nXRange Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is commonly used\nfor looping. The advantage of the ``xrange`` type is that an\n``xrange`` object will always take the same amount of memory, no\nmatter the size of the range it represents. There are no consistent\nperformance advantages.\n\nXRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList and ``bytearray`` objects support additional operations that\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable sequence types (where *x* is an arbitrary object):\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)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*\'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn\'t have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don\'t return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\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 In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **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 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n', 'typesseq-mutable': "\nMutable Sequence Types\n**********************\n\nList and ``bytearray`` objects support additional operations that\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable sequence types (where *x* is an arbitrary object):\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)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn't have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don't return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\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 In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **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 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\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\nplain or long integer argument. The bitwise inversion of ``x`` is\ndefined as ``-(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\nNew in version 2.5.\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\nNote: In Python 2.5, the ``with`` statement is only allowed when the\n ``with_statement`` feature has been enabled. It is always enabled\n in Python 2.6.\n\nChanged in version 2.7: 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 generator\'s ``next()``\nmethod 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\nAs of Python version 2.5, the ``yield`` statement is now allowed in\nthe ``try`` clause of a ``try`` ... ``finally`` construct. If the\ngenerator is not resumed before it is finalized (by reaching a zero\nreference count or by being garbage collected), the generator-\niterator\'s ``close()`` method will be called, allowing any pending\n``finally`` clauses to execute.\n\nNote: In Python 2.2, the ``yield`` statement was only allowed when the\n ``generators`` feature has been enabled. This ``__future__`` import\n statement was used to enable the feature:\n\n from __future__ import generators\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 that, among other generator enhancements, proposed\n allowing ``yield`` to appear inside a ``try`` ... ``finally``\n block.\n'}
gpl-2.0
Ingenico-ePayments/connect-sdk-python3
tests/unit/test_directory_params.py
1
1664
import unittest from ingenico.connect.sdk.merchant.products.directory_params import DirectoryParams from tests.unit.comparable_param import ComparableParam class DirectoryParamsTest(unittest.TestCase): """Tests if instances of the DirectoryParams class for products can be correctly converted to RequestParameter objects""" def test_empty_request_parameters(self): """Tests that the DirectoryParams object correctly functions when values are not set""" params = DirectoryParams() expected = [] self.assertCountEqual(expected, params.to_request_parameters()) def test_filled_request_parameters(self): """Tests that the DirectoryParams object can correctly store and convert its data to RequestParameters""" params = DirectoryParams() expected = [] params.country_code = "NL" expected.append(ComparableParam("countryCode", "NL")) params.currency_code = "EUR" expected.append(ComparableParam("currencyCode", "EUR")) request_params = params.to_request_parameters() self.maxDiff = None self.assertCountEqual(expected, request_params) def test_delete_request_parameters(self): """Test if removing parameter correctly removes them from the GetParams object""" params = DirectoryParams() expected = [] params.country_code = "NL" params.currency_code = "EUR" params.country_code = None params.currency_code = None request_params = params.to_request_parameters() self.assertCountEqual(expected, request_params) if __name__ == '__main__': unittest.main()
mit
thnee/ansible
lib/ansible/modules/network/avi/avi_gslbgeodbprofile.py
28
4241
#!/usr/bin/python # # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.2 # # Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_gslbgeodbprofile author: Gaurav Rastogi (@grastogi23) <grastogi@avinetworks.com> short_description: Module for setup of GslbGeoDbProfile Avi RESTful Object description: - This module is used to configure GslbGeoDbProfile object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.4" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] description: description: - Field introduced in 17.1.1. entries: description: - List of geodb entries. - An entry can either be a geodb file or an ip address group with geo properties. - Field introduced in 17.1.1. is_federated: description: - This field indicates that this object is replicated across gslb federation. - Field introduced in 17.1.3. - Default value when not specified in API or module is interpreted by Avi Controller as True. type: bool name: description: - A user-friendly name for the geodb profile. - Field introduced in 17.1.1. required: true tenant_ref: description: - It is a reference to an object of type tenant. - Field introduced in 17.1.1. url: description: - Avi controller URL of the object. uuid: description: - Uuid of the geodb profile. - Field introduced in 17.1.1. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create GslbGeoDbProfile object avi_gslbgeodbprofile: controller: 10.10.25.42 username: admin password: something state: present name: sample_gslbgeodbprofile """ RETURN = ''' obj: description: GslbGeoDbProfile (api/gslbgeodbprofile) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, avi_ansible_api, HAS_AVI) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), description=dict(type='str',), entries=dict(type='list',), is_federated=dict(type='bool',), name=dict(type='str', required=True), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) or requests is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'gslbgeodbprofile', set([])) if __name__ == '__main__': main()
gpl-3.0
fhaoquan/kbengine
kbe/res/scripts/common/Lib/test/test_builtin.py
72
58513
# Python test set -- built-in functions import ast import builtins import collections import io import locale import os import pickle import platform import random import sys import traceback import types import unittest import warnings from operator import neg from test.support import TESTFN, unlink, run_unittest, check_warnings from test.script_helper import assert_python_ok try: import pty, signal except ImportError: pty = signal = None class Squares: def __init__(self, max): self.max = max self.sofar = [] def __len__(self): return len(self.sofar) def __getitem__(self, i): if not 0 <= i < self.max: raise IndexError n = len(self.sofar) while n <= i: self.sofar.append(n*n) n += 1 return self.sofar[i] class StrSquares: def __init__(self, max): self.max = max self.sofar = [] def __len__(self): return len(self.sofar) def __getitem__(self, i): if not 0 <= i < self.max: raise IndexError n = len(self.sofar) while n <= i: self.sofar.append(str(n*n)) n += 1 return self.sofar[i] class BitBucket: def write(self, line): pass test_conv_no_sign = [ ('0', 0), ('1', 1), ('9', 9), ('10', 10), ('99', 99), ('100', 100), ('314', 314), (' 314', 314), ('314 ', 314), (' \t\t 314 \t\t ', 314), (repr(sys.maxsize), sys.maxsize), (' 1x', ValueError), (' 1 ', 1), (' 1\02 ', ValueError), ('', ValueError), (' ', ValueError), (' \t\t ', ValueError), (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), (chr(0x200), ValueError), ] test_conv_sign = [ ('0', 0), ('1', 1), ('9', 9), ('10', 10), ('99', 99), ('100', 100), ('314', 314), (' 314', ValueError), ('314 ', 314), (' \t\t 314 \t\t ', ValueError), (repr(sys.maxsize), sys.maxsize), (' 1x', ValueError), (' 1 ', ValueError), (' 1\02 ', ValueError), ('', ValueError), (' ', ValueError), (' \t\t ', ValueError), (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), (chr(0x200), ValueError), ] class TestFailingBool: def __bool__(self): raise RuntimeError class TestFailingIter: def __iter__(self): raise RuntimeError def filter_char(arg): return ord(arg) > ord("d") def map_char(arg): return chr(ord(arg)+1) class BuiltinTest(unittest.TestCase): # Helper to check picklability def check_iter_pickle(self, it, seq): itorg = it d = pickle.dumps(it) it = pickle.loads(d) self.assertEqual(type(itorg), type(it)) self.assertEqual(list(it), seq) #test the iterator after dropping one from it it = pickle.loads(d) try: next(it) except StopIteration: return d = pickle.dumps(it) it = pickle.loads(d) self.assertEqual(list(it), seq[1:]) def test_import(self): __import__('sys') __import__('time') __import__('string') __import__(name='sys') __import__(name='time', level=0) self.assertRaises(ImportError, __import__, 'spamspam') self.assertRaises(TypeError, __import__, 1, 2, 3, 4) self.assertRaises(ValueError, __import__, '') self.assertRaises(TypeError, __import__, 'sys', name='sys') def test_abs(self): # int self.assertEqual(abs(0), 0) self.assertEqual(abs(1234), 1234) self.assertEqual(abs(-1234), 1234) self.assertTrue(abs(-sys.maxsize-1) > 0) # float self.assertEqual(abs(0.0), 0.0) self.assertEqual(abs(3.14), 3.14) self.assertEqual(abs(-3.14), 3.14) # str self.assertRaises(TypeError, abs, 'a') # bool self.assertEqual(abs(True), 1) self.assertEqual(abs(False), 0) # other self.assertRaises(TypeError, abs) self.assertRaises(TypeError, abs, None) class AbsClass(object): def __abs__(self): return -5 self.assertEqual(abs(AbsClass()), -5) def test_all(self): self.assertEqual(all([2, 4, 6]), True) self.assertEqual(all([2, None, 6]), False) self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6]) self.assertRaises(RuntimeError, all, TestFailingIter()) self.assertRaises(TypeError, all, 10) # Non-iterable self.assertRaises(TypeError, all) # No args self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args self.assertEqual(all([]), True) # Empty iterator self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit S = [50, 60] self.assertEqual(all(x > 42 for x in S), True) S = [50, 40, 60] self.assertEqual(all(x > 42 for x in S), False) def test_any(self): self.assertEqual(any([None, None, None]), False) self.assertEqual(any([None, 4, None]), True) self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6]) self.assertRaises(RuntimeError, any, TestFailingIter()) self.assertRaises(TypeError, any, 10) # Non-iterable self.assertRaises(TypeError, any) # No args self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args self.assertEqual(any([]), False) # Empty iterator self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit S = [40, 60, 30] self.assertEqual(any(x > 42 for x in S), True) S = [10, 20, 30] self.assertEqual(any(x > 42 for x in S), False) def test_ascii(self): self.assertEqual(ascii(''), '\'\'') self.assertEqual(ascii(0), '0') self.assertEqual(ascii(()), '()') self.assertEqual(ascii([]), '[]') self.assertEqual(ascii({}), '{}') a = [] a.append(a) self.assertEqual(ascii(a), '[[...]]') a = {} a[0] = a self.assertEqual(ascii(a), '{0: {...}}') # Advanced checks for unicode strings def _check_uni(s): self.assertEqual(ascii(s), repr(s)) _check_uni("'") _check_uni('"') _check_uni('"\'') _check_uni('\0') _check_uni('\r\n\t .') # Unprintable non-ASCII characters _check_uni('\x85') _check_uni('\u1fff') _check_uni('\U00012fff') # Lone surrogates _check_uni('\ud800') _check_uni('\udfff') # Issue #9804: surrogates should be joined even for printable # wide characters (UCS-2 builds). self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'") # All together s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx." self.assertEqual(ascii(s), r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""") def test_neg(self): x = -sys.maxsize-1 self.assertTrue(isinstance(x, int)) self.assertEqual(-x, sys.maxsize+1) def test_callable(self): self.assertTrue(callable(len)) self.assertFalse(callable("a")) self.assertTrue(callable(callable)) self.assertTrue(callable(lambda x, y: x + y)) self.assertFalse(callable(__builtins__)) def f(): pass self.assertTrue(callable(f)) class C1: def meth(self): pass self.assertTrue(callable(C1)) c = C1() self.assertTrue(callable(c.meth)) self.assertFalse(callable(c)) # __call__ is looked up on the class, not the instance c.__call__ = None self.assertFalse(callable(c)) c.__call__ = lambda self: 0 self.assertFalse(callable(c)) del c.__call__ self.assertFalse(callable(c)) class C2(object): def __call__(self): pass c2 = C2() self.assertTrue(callable(c2)) c2.__call__ = None self.assertTrue(callable(c2)) class C3(C2): pass c3 = C3() self.assertTrue(callable(c3)) def test_chr(self): self.assertEqual(chr(32), ' ') self.assertEqual(chr(65), 'A') self.assertEqual(chr(97), 'a') self.assertEqual(chr(0xff), '\xff') self.assertRaises(ValueError, chr, 1<<24) self.assertEqual(chr(sys.maxunicode), str('\\U0010ffff'.encode("ascii"), 'unicode-escape')) self.assertRaises(TypeError, chr) self.assertEqual(chr(0x0000FFFF), "\U0000FFFF") self.assertEqual(chr(0x00010000), "\U00010000") self.assertEqual(chr(0x00010001), "\U00010001") self.assertEqual(chr(0x000FFFFE), "\U000FFFFE") self.assertEqual(chr(0x000FFFFF), "\U000FFFFF") self.assertEqual(chr(0x00100000), "\U00100000") self.assertEqual(chr(0x00100001), "\U00100001") self.assertEqual(chr(0x0010FFFE), "\U0010FFFE") self.assertEqual(chr(0x0010FFFF), "\U0010FFFF") self.assertRaises(ValueError, chr, -1) self.assertRaises(ValueError, chr, 0x00110000) self.assertRaises((OverflowError, ValueError), chr, 2**32) def test_cmp(self): self.assertTrue(not hasattr(builtins, "cmp")) def test_compile(self): compile('print(1)\n', '', 'exec') bom = b'\xef\xbb\xbf' compile(bom + b'print(1)\n', '', 'exec') compile(source='pass', filename='?', mode='exec') compile(dont_inherit=0, filename='tmp', source='0', mode='eval') compile('pass', '?', dont_inherit=1, mode='exec') compile(memoryview(b"text"), "name", "exec") self.assertRaises(TypeError, compile) self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode') self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff) self.assertRaises(TypeError, compile, chr(0), 'f', 'exec') self.assertRaises(TypeError, compile, 'pass', '?', 'exec', mode='eval', source='0', filename='tmp') compile('print("\xe5")\n', '', 'exec') self.assertRaises(TypeError, compile, chr(0), 'f', 'exec') self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad') # test the optimize argument codestr = '''def f(): """doc""" try: assert False except AssertionError: return (True, f.__doc__) else: return (False, f.__doc__) ''' def f(): """doc""" values = [(-1, __debug__, f.__doc__), (0, True, 'doc'), (1, False, 'doc'), (2, False, None)] for optval, debugval, docstring in values: # test both direct compilation and compilation via AST codeobjs = [] codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval)) tree = ast.parse(codestr) codeobjs.append(compile(tree, "<test>", "exec", optimize=optval)) for code in codeobjs: ns = {} exec(code, ns) rv = ns['f']() self.assertEqual(rv, (debugval, docstring)) def test_delattr(self): sys.spam = 1 delattr(sys, 'spam') self.assertRaises(TypeError, delattr) def test_dir(self): # dir(wrong number of arguments) self.assertRaises(TypeError, dir, 42, 42) # dir() - local scope local_var = 1 self.assertIn('local_var', dir()) # dir(module) self.assertIn('exit', dir(sys)) # dir(module_with_invalid__dict__) class Foo(types.ModuleType): __dict__ = 8 f = Foo("foo") self.assertRaises(TypeError, dir, f) # dir(type) self.assertIn("strip", dir(str)) self.assertNotIn("__mro__", dir(str)) # dir(obj) class Foo(object): def __init__(self): self.x = 7 self.y = 8 self.z = 9 f = Foo() self.assertIn("y", dir(f)) # dir(obj_no__dict__) class Foo(object): __slots__ = [] f = Foo() self.assertIn("__repr__", dir(f)) # dir(obj_no__class__with__dict__) # (an ugly trick to cause getattr(f, "__class__") to fail) class Foo(object): __slots__ = ["__class__", "__dict__"] def __init__(self): self.bar = "wow" f = Foo() self.assertNotIn("__repr__", dir(f)) self.assertIn("bar", dir(f)) # dir(obj_using __dir__) class Foo(object): def __dir__(self): return ["kan", "ga", "roo"] f = Foo() self.assertTrue(dir(f) == ["ga", "kan", "roo"]) # dir(obj__dir__tuple) class Foo(object): def __dir__(self): return ("b", "c", "a") res = dir(Foo()) self.assertIsInstance(res, list) self.assertTrue(res == ["a", "b", "c"]) # dir(obj__dir__not_sequence) class Foo(object): def __dir__(self): return 7 f = Foo() self.assertRaises(TypeError, dir, f) # dir(traceback) try: raise IndexError except: self.assertEqual(len(dir(sys.exc_info()[2])), 4) # test that object has a __dir__() self.assertEqual(sorted([].__dir__()), dir([])) def test_divmod(self): self.assertEqual(divmod(12, 7), (1, 5)) self.assertEqual(divmod(-12, 7), (-2, 2)) self.assertEqual(divmod(12, -7), (-2, -2)) self.assertEqual(divmod(-12, -7), (1, -5)) self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0)) for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)), (-3.25, 1.0, (-4.0, 0.75)), (3.25, -1.0, (-4.0, -0.75)), (-3.25, -1.0, (3.0, -0.25))]: result = divmod(num, denom) self.assertAlmostEqual(result[0], exp_result[0]) self.assertAlmostEqual(result[1], exp_result[1]) self.assertRaises(TypeError, divmod) def test_eval(self): self.assertEqual(eval('1+1'), 2) self.assertEqual(eval(' 1+1\n'), 2) globals = {'a': 1, 'b': 2} locals = {'b': 200, 'c': 300} self.assertEqual(eval('a', globals) , 1) self.assertEqual(eval('a', globals, locals), 1) self.assertEqual(eval('b', globals, locals), 200) self.assertEqual(eval('c', globals, locals), 300) globals = {'a': 1, 'b': 2} locals = {'b': 200, 'c': 300} bom = b'\xef\xbb\xbf' self.assertEqual(eval(bom + b'a', globals, locals), 1) self.assertEqual(eval('"\xe5"', globals), "\xe5") self.assertRaises(TypeError, eval) self.assertRaises(TypeError, eval, ()) self.assertRaises(SyntaxError, eval, bom[:2] + b'a') class X: def __getitem__(self, key): raise ValueError self.assertRaises(ValueError, eval, "foo", {}, X()) def test_general_eval(self): # Tests that general mappings can be used for the locals argument class M: "Test mapping interface versus possible calls from eval()." def __getitem__(self, key): if key == 'a': return 12 raise KeyError def keys(self): return list('xyz') m = M() g = globals() self.assertEqual(eval('a', g, m), 12) self.assertRaises(NameError, eval, 'b', g, m) self.assertEqual(eval('dir()', g, m), list('xyz')) self.assertEqual(eval('globals()', g, m), g) self.assertEqual(eval('locals()', g, m), m) self.assertRaises(TypeError, eval, 'a', m) class A: "Non-mapping" pass m = A() self.assertRaises(TypeError, eval, 'a', g, m) # Verify that dict subclasses work as well class D(dict): def __getitem__(self, key): if key == 'a': return 12 return dict.__getitem__(self, key) def keys(self): return list('xyz') d = D() self.assertEqual(eval('a', g, d), 12) self.assertRaises(NameError, eval, 'b', g, d) self.assertEqual(eval('dir()', g, d), list('xyz')) self.assertEqual(eval('globals()', g, d), g) self.assertEqual(eval('locals()', g, d), d) # Verify locals stores (used by list comps) eval('[locals() for i in (2,3)]', g, d) eval('[locals() for i in (2,3)]', g, collections.UserDict()) class SpreadSheet: "Sample application showing nested, calculated lookups." _cells = {} def __setitem__(self, key, formula): self._cells[key] = formula def __getitem__(self, key): return eval(self._cells[key], globals(), self) ss = SpreadSheet() ss['a1'] = '5' ss['a2'] = 'a1*6' ss['a3'] = 'a2*7' self.assertEqual(ss['a3'], 210) # Verify that dir() catches a non-list returned by eval # SF bug #1004669 class C: def __getitem__(self, item): raise KeyError(item) def keys(self): return 1 # used to be 'a' but that's no longer an error self.assertRaises(TypeError, eval, 'dir()', globals(), C()) def test_exec(self): g = {} exec('z = 1', g) if '__builtins__' in g: del g['__builtins__'] self.assertEqual(g, {'z': 1}) exec('z = 1+1', g) if '__builtins__' in g: del g['__builtins__'] self.assertEqual(g, {'z': 2}) g = {} l = {} with check_warnings(): warnings.filterwarnings("ignore", "global statement", module="<string>") exec('global a; a = 1; b = 2', g, l) if '__builtins__' in g: del g['__builtins__'] if '__builtins__' in l: del l['__builtins__'] self.assertEqual((g, l), ({'a': 1}, {'b': 2})) def test_exec_globals(self): code = compile("print('Hello World!')", "", "exec") # no builtin function self.assertRaisesRegex(NameError, "name 'print' is not defined", exec, code, {'__builtins__': {}}) # __builtins__ must be a mapping type self.assertRaises(TypeError, exec, code, {'__builtins__': 123}) # no __build_class__ function code = compile("class A: pass", "", "exec") self.assertRaisesRegex(NameError, "__build_class__ not found", exec, code, {'__builtins__': {}}) class frozendict_error(Exception): pass class frozendict(dict): def __setitem__(self, key, value): raise frozendict_error("frozendict is readonly") # read-only builtins if isinstance(__builtins__, types.ModuleType): frozen_builtins = frozendict(__builtins__.__dict__) else: frozen_builtins = frozendict(__builtins__) code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec") self.assertRaises(frozendict_error, exec, code, {'__builtins__': frozen_builtins}) # read-only globals namespace = frozendict({}) code = compile("x=1", "test", "exec") self.assertRaises(frozendict_error, exec, code, namespace) def test_exec_redirected(self): savestdout = sys.stdout sys.stdout = None # Whatever that cannot flush() try: # Used to raise SystemError('error return without exception set') exec('a') except NameError: pass finally: sys.stdout = savestdout def test_filter(self): self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81]) self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81]) def identity(item): return 1 filter(identity, Squares(5)) self.assertRaises(TypeError, filter) class BadSeq(object): def __getitem__(self, index): if index<4: return 42 raise ValueError self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq())) def badfunc(): pass self.assertRaises(TypeError, list, filter(badfunc, range(5))) # test bltinmodule.c::filtertuple() self.assertEqual(list(filter(None, (1, 2))), [1, 2]) self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) self.assertRaises(TypeError, list, filter(42, (1, 2))) def test_filter_pickle(self): f1 = filter(filter_char, "abcdeabcde") f2 = filter(filter_char, "abcdeabcde") self.check_iter_pickle(f1, list(f2)) def test_getattr(self): self.assertTrue(getattr(sys, 'stdout') is sys.stdout) self.assertRaises(TypeError, getattr, sys, 1) self.assertRaises(TypeError, getattr, sys, 1, "foo") self.assertRaises(TypeError, getattr) self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode)) # unicode surrogates are not encodable to the default encoding (utf8) self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E") def test_hasattr(self): self.assertTrue(hasattr(sys, 'stdout')) self.assertRaises(TypeError, hasattr, sys, 1) self.assertRaises(TypeError, hasattr) self.assertEqual(False, hasattr(sys, chr(sys.maxunicode))) # Check that hasattr propagates all exceptions outside of # AttributeError. class A: def __getattr__(self, what): raise SystemExit self.assertRaises(SystemExit, hasattr, A(), "b") class B: def __getattr__(self, what): raise ValueError self.assertRaises(ValueError, hasattr, B(), "b") def test_hash(self): hash(None) self.assertEqual(hash(1), hash(1)) self.assertEqual(hash(1), hash(1.0)) hash('spam') self.assertEqual(hash('spam'), hash(b'spam')) hash((0,1,2,3)) def f(): pass self.assertRaises(TypeError, hash, []) self.assertRaises(TypeError, hash, {}) # Bug 1536021: Allow hash to return long objects class X: def __hash__(self): return 2**100 self.assertEqual(type(hash(X())), int) class Z(int): def __hash__(self): return self self.assertEqual(hash(Z(42)), hash(42)) def test_hex(self): self.assertEqual(hex(16), '0x10') self.assertEqual(hex(-16), '-0x10') self.assertRaises(TypeError, hex, {}) def test_id(self): id(None) id(1) id(1.0) id('spam') id((0,1,2,3)) id([0,1,2,3]) id({'spam': 1, 'eggs': 2, 'ham': 3}) # Test input() later, alphabetized as if it were raw_input def test_iter(self): self.assertRaises(TypeError, iter) self.assertRaises(TypeError, iter, 42, 42) lists = [("1", "2"), ["1", "2"], "12"] for l in lists: i = iter(l) self.assertEqual(next(i), '1') self.assertEqual(next(i), '2') self.assertRaises(StopIteration, next, i) def test_isinstance(self): class C: pass class D(C): pass class E: pass c = C() d = D() e = E() self.assertTrue(isinstance(c, C)) self.assertTrue(isinstance(d, C)) self.assertTrue(not isinstance(e, C)) self.assertTrue(not isinstance(c, D)) self.assertTrue(not isinstance('foo', E)) self.assertRaises(TypeError, isinstance, E, 'foo') self.assertRaises(TypeError, isinstance) def test_issubclass(self): class C: pass class D(C): pass class E: pass c = C() d = D() e = E() self.assertTrue(issubclass(D, C)) self.assertTrue(issubclass(C, C)) self.assertTrue(not issubclass(C, D)) self.assertRaises(TypeError, issubclass, 'foo', E) self.assertRaises(TypeError, issubclass, E, 'foo') self.assertRaises(TypeError, issubclass) def test_len(self): self.assertEqual(len('123'), 3) self.assertEqual(len(()), 0) self.assertEqual(len((1, 2, 3, 4)), 4) self.assertEqual(len([1, 2, 3, 4]), 4) self.assertEqual(len({}), 0) self.assertEqual(len({'a':1, 'b': 2}), 2) class BadSeq: def __len__(self): raise ValueError self.assertRaises(ValueError, len, BadSeq()) class InvalidLen: def __len__(self): return None self.assertRaises(TypeError, len, InvalidLen()) class FloatLen: def __len__(self): return 4.5 self.assertRaises(TypeError, len, FloatLen()) class HugeLen: def __len__(self): return sys.maxsize + 1 self.assertRaises(OverflowError, len, HugeLen()) class NoLenMethod(object): pass self.assertRaises(TypeError, len, NoLenMethod()) def test_map(self): self.assertEqual( list(map(lambda x: x*x, range(1,4))), [1, 4, 9] ) try: from math import sqrt except ImportError: def sqrt(x): return pow(x, 0.5) self.assertEqual( list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])), [[4.0, 2.0], [9.0, 3.0]] ) self.assertEqual( list(map(lambda x, y: x+y, [1,3,2], [9,1,4])), [10, 4, 6] ) def plus(*v): accu = 0 for i in v: accu = accu + i return accu self.assertEqual( list(map(plus, [1, 3, 7])), [1, 3, 7] ) self.assertEqual( list(map(plus, [1, 3, 7], [4, 9, 2])), [1+4, 3+9, 7+2] ) self.assertEqual( list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])), [1+4+1, 3+9+1, 7+2+0] ) self.assertEqual( list(map(int, Squares(10))), [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ) def Max(a, b): if a is None: return b if b is None: return a return max(a, b) self.assertEqual( list(map(Max, Squares(3), Squares(2))), [0, 1] ) self.assertRaises(TypeError, map) self.assertRaises(TypeError, map, lambda x: x, 42) class BadSeq: def __iter__(self): raise ValueError yield None self.assertRaises(ValueError, list, map(lambda x: x, BadSeq())) def badfunc(x): raise RuntimeError self.assertRaises(RuntimeError, list, map(badfunc, range(5))) def test_map_pickle(self): m1 = map(map_char, "Is this the real life?") m2 = map(map_char, "Is this the real life?") self.check_iter_pickle(m1, list(m2)) def test_max(self): self.assertEqual(max('123123'), '3') self.assertEqual(max(1, 2, 3), 3) self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) self.assertEqual(max(1, 2, 3.0), 3.0) self.assertEqual(max(1, 2.0, 3), 3) self.assertEqual(max(1.0, 2, 3), 3) self.assertRaises(TypeError, max) self.assertRaises(TypeError, max, 42) self.assertRaises(ValueError, max, ()) class BadSeq: def __getitem__(self, index): raise ValueError self.assertRaises(ValueError, max, BadSeq()) for stmt in ( "max(key=int)", # no args "max(default=None)", "max(1, 2, default=None)", # require container for default "max(default=None, key=int)", "max(1, key=int)", # single arg not iterable "max(1, 2, keystone=int)", # wrong keyword "max(1, 2, key=int, abc=int)", # two many keywords "max(1, 2, key=1)", # keyfunc is not callable ): try: exec(stmt, globals()) except TypeError: pass else: self.fail(stmt) self.assertEqual(max((1,), key=neg), 1) # one elem iterable self.assertEqual(max((1,2), key=neg), 1) # two elem iterable self.assertEqual(max(1, 2, key=neg), 1) # two elems self.assertEqual(max((), default=None), None) # zero elem iterable self.assertEqual(max((1,), default=None), 1) # one elem iterable self.assertEqual(max((1,2), default=None), 2) # two elem iterable self.assertEqual(max((), default=1, key=neg), 1) self.assertEqual(max((1, 2), default=3, key=neg), 1) data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(max(data, key=f), sorted(reversed(data), key=f)[-1]) def test_min(self): self.assertEqual(min('123123'), '1') self.assertEqual(min(1, 2, 3), 1) self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) self.assertEqual(min(1, 2, 3.0), 1) self.assertEqual(min(1, 2.0, 3), 1) self.assertEqual(min(1.0, 2, 3), 1.0) self.assertRaises(TypeError, min) self.assertRaises(TypeError, min, 42) self.assertRaises(ValueError, min, ()) class BadSeq: def __getitem__(self, index): raise ValueError self.assertRaises(ValueError, min, BadSeq()) for stmt in ( "min(key=int)", # no args "min(default=None)", "min(1, 2, default=None)", # require container for default "min(default=None, key=int)", "min(1, key=int)", # single arg not iterable "min(1, 2, keystone=int)", # wrong keyword "min(1, 2, key=int, abc=int)", # two many keywords "min(1, 2, key=1)", # keyfunc is not callable ): try: exec(stmt, globals()) except TypeError: pass else: self.fail(stmt) self.assertEqual(min((1,), key=neg), 1) # one elem iterable self.assertEqual(min((1,2), key=neg), 2) # two elem iterable self.assertEqual(min(1, 2, key=neg), 2) # two elems self.assertEqual(min((), default=None), None) # zero elem iterable self.assertEqual(min((1,), default=None), 1) # one elem iterable self.assertEqual(min((1,2), default=None), 1) # two elem iterable self.assertEqual(min((), default=1, key=neg), 1) self.assertEqual(min((1, 2), default=1, key=neg), 2) data = [random.randrange(200) for i in range(100)] keys = dict((elem, random.randrange(50)) for elem in data) f = keys.__getitem__ self.assertEqual(min(data, key=f), sorted(data, key=f)[0]) def test_next(self): it = iter(range(2)) self.assertEqual(next(it), 0) self.assertEqual(next(it), 1) self.assertRaises(StopIteration, next, it) self.assertRaises(StopIteration, next, it) self.assertEqual(next(it, 42), 42) class Iter(object): def __iter__(self): return self def __next__(self): raise StopIteration it = iter(Iter()) self.assertEqual(next(it, 42), 42) self.assertRaises(StopIteration, next, it) def gen(): yield 1 return it = gen() self.assertEqual(next(it), 1) self.assertRaises(StopIteration, next, it) self.assertEqual(next(it, 42), 42) def test_oct(self): self.assertEqual(oct(100), '0o144') self.assertEqual(oct(-100), '-0o144') self.assertRaises(TypeError, oct, ()) def write_testfile(self): # NB the first 4 lines are also used to test input, below fp = open(TESTFN, 'w') self.addCleanup(unlink, TESTFN) with fp: fp.write('1+1\n') fp.write('The quick brown fox jumps over the lazy dog') fp.write('.\n') fp.write('Dear John\n') fp.write('XXX'*100) fp.write('YYY'*100) def test_open(self): self.write_testfile() fp = open(TESTFN, 'r') with fp: self.assertEqual(fp.readline(4), '1+1\n') self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') self.assertEqual(fp.readline(4), 'Dear') self.assertEqual(fp.readline(100), ' John\n') self.assertEqual(fp.read(300), 'XXX'*100) self.assertEqual(fp.read(1000), 'YYY'*100) def test_open_default_encoding(self): old_environ = dict(os.environ) try: # try to get a user preferred encoding different than the current # locale encoding to check that open() uses the current locale # encoding and not the user preferred encoding for key in ('LC_ALL', 'LANG', 'LC_CTYPE'): if key in os.environ: del os.environ[key] self.write_testfile() current_locale_encoding = locale.getpreferredencoding(False) fp = open(TESTFN, 'w') with fp: self.assertEqual(fp.encoding, current_locale_encoding) finally: os.environ.clear() os.environ.update(old_environ) def test_open_non_inheritable(self): fileobj = open(__file__) with fileobj: self.assertFalse(os.get_inheritable(fileobj.fileno())) def test_ord(self): self.assertEqual(ord(' '), 32) self.assertEqual(ord('A'), 65) self.assertEqual(ord('a'), 97) self.assertEqual(ord('\x80'), 128) self.assertEqual(ord('\xff'), 255) self.assertEqual(ord(b' '), 32) self.assertEqual(ord(b'A'), 65) self.assertEqual(ord(b'a'), 97) self.assertEqual(ord(b'\x80'), 128) self.assertEqual(ord(b'\xff'), 255) self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode) self.assertRaises(TypeError, ord, 42) self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF) self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF) self.assertEqual(ord("\U00010000"), 0x00010000) self.assertEqual(ord("\U00010001"), 0x00010001) self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE) self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF) self.assertEqual(ord("\U00100000"), 0x00100000) self.assertEqual(ord("\U00100001"), 0x00100001) self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE) self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF) def test_pow(self): self.assertEqual(pow(0,0), 1) self.assertEqual(pow(0,1), 0) self.assertEqual(pow(1,0), 1) self.assertEqual(pow(1,1), 1) self.assertEqual(pow(2,0), 1) self.assertEqual(pow(2,10), 1024) self.assertEqual(pow(2,20), 1024*1024) self.assertEqual(pow(2,30), 1024*1024*1024) self.assertEqual(pow(-2,0), 1) self.assertEqual(pow(-2,1), -2) self.assertEqual(pow(-2,2), 4) self.assertEqual(pow(-2,3), -8) self.assertAlmostEqual(pow(0.,0), 1.) self.assertAlmostEqual(pow(0.,1), 0.) self.assertAlmostEqual(pow(1.,0), 1.) self.assertAlmostEqual(pow(1.,1), 1.) self.assertAlmostEqual(pow(2.,0), 1.) self.assertAlmostEqual(pow(2.,10), 1024.) self.assertAlmostEqual(pow(2.,20), 1024.*1024.) self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) self.assertAlmostEqual(pow(-2.,0), 1.) self.assertAlmostEqual(pow(-2.,1), -2.) self.assertAlmostEqual(pow(-2.,2), 4.) self.assertAlmostEqual(pow(-2.,3), -8.) for x in 2, 2.0: for y in 10, 10.0: for z in 1000, 1000.0: if isinstance(x, float) or \ isinstance(y, float) or \ isinstance(z, float): self.assertRaises(TypeError, pow, x, y, z) else: self.assertAlmostEqual(pow(x, y, z), 24.0) self.assertAlmostEqual(pow(-1, 0.5), 1j) self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j) self.assertRaises(TypeError, pow, -1, -2, 3) self.assertRaises(ValueError, pow, 1, 2, 0) self.assertRaises(TypeError, pow) def test_input(self): self.write_testfile() fp = open(TESTFN, 'r') savestdin = sys.stdin savestdout = sys.stdout # Eats the echo try: sys.stdin = fp sys.stdout = BitBucket() self.assertEqual(input(), "1+1") self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.') self.assertEqual(input('testing\n'), 'Dear John') # SF 1535165: don't segfault on closed stdin # sys.stdout must be a regular file for triggering sys.stdout = savestdout sys.stdin.close() self.assertRaises(ValueError, input) sys.stdout = BitBucket() sys.stdin = io.StringIO("NULL\0") self.assertRaises(TypeError, input, 42, 42) sys.stdin = io.StringIO(" 'whitespace'") self.assertEqual(input(), " 'whitespace'") sys.stdin = io.StringIO() self.assertRaises(EOFError, input) del sys.stdout self.assertRaises(RuntimeError, input, 'prompt') del sys.stdin self.assertRaises(RuntimeError, input, 'prompt') finally: sys.stdin = savestdin sys.stdout = savestdout fp.close() @unittest.skipUnless(pty, "the pty and signal modules must be available") def check_input_tty(self, prompt, terminal_input, stdio_encoding=None): if not sys.stdin.isatty() or not sys.stdout.isatty(): self.skipTest("stdin and stdout must be ttys") r, w = os.pipe() try: pid, fd = pty.fork() except (OSError, AttributeError) as e: os.close(r) os.close(w) self.skipTest("pty.fork() raised {}".format(e)) if pid == 0: # Child try: # Make sure we don't get stuck if there's a problem signal.alarm(2) os.close(r) # Check the error handlers are accounted for if stdio_encoding: sys.stdin = io.TextIOWrapper(sys.stdin.detach(), encoding=stdio_encoding, errors='surrogateescape') sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding=stdio_encoding, errors='replace') with open(w, "w") as wpipe: print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe) print(ascii(input(prompt)), file=wpipe) except: traceback.print_exc() finally: # We don't want to return to unittest... os._exit(0) # Parent os.close(w) os.write(fd, terminal_input + b"\r\n") # Get results from the pipe with open(r, "r") as rpipe: lines = [] while True: line = rpipe.readline().strip() if line == "": # The other end was closed => the child exited break lines.append(line) # Check the result was got and corresponds to the user's terminal input if len(lines) != 2: # Something went wrong, try to get at stderr with open(fd, "r", encoding="ascii", errors="ignore") as child_output: self.fail("got %d lines in pipe but expected 2, child output was:\n%s" % (len(lines), child_output.read())) os.close(fd) # Check we did exercise the GNU readline path self.assertIn(lines[0], {'tty = True', 'tty = False'}) if lines[0] != 'tty = True': self.skipTest("standard IO in should have been a tty") input_result = eval(lines[1]) # ascii() -> eval() roundtrip if stdio_encoding: expected = terminal_input.decode(stdio_encoding, 'surrogateescape') else: expected = terminal_input.decode(sys.stdin.encoding) # what else? self.assertEqual(input_result, expected) def test_input_tty(self): # Test input() functionality when wired to a tty (the code path # is different and invokes GNU readline if available). self.check_input_tty("prompt", b"quux") def test_input_tty_non_ascii(self): # Check stdin/stdout encoding is used when invoking GNU readline self.check_input_tty("prompté", b"quux\xe9", "utf-8") def test_input_tty_non_ascii_unicode_errors(self): # Check stdin/stdout error handler is used when invoking GNU readline self.check_input_tty("prompté", b"quux\xe9", "ascii") # test_int(): see test_int.py for tests of built-in function int(). def test_repr(self): self.assertEqual(repr(''), '\'\'') self.assertEqual(repr(0), '0') self.assertEqual(repr(()), '()') self.assertEqual(repr([]), '[]') self.assertEqual(repr({}), '{}') a = [] a.append(a) self.assertEqual(repr(a), '[[...]]') a = {} a[0] = a self.assertEqual(repr(a), '{0: {...}}') def test_round(self): self.assertEqual(round(0.0), 0.0) self.assertEqual(type(round(0.0)), int) self.assertEqual(round(1.0), 1.0) self.assertEqual(round(10.0), 10.0) self.assertEqual(round(1000000000.0), 1000000000.0) self.assertEqual(round(1e20), 1e20) self.assertEqual(round(-1.0), -1.0) self.assertEqual(round(-10.0), -10.0) self.assertEqual(round(-1000000000.0), -1000000000.0) self.assertEqual(round(-1e20), -1e20) self.assertEqual(round(0.1), 0.0) self.assertEqual(round(1.1), 1.0) self.assertEqual(round(10.1), 10.0) self.assertEqual(round(1000000000.1), 1000000000.0) self.assertEqual(round(-1.1), -1.0) self.assertEqual(round(-10.1), -10.0) self.assertEqual(round(-1000000000.1), -1000000000.0) self.assertEqual(round(0.9), 1.0) self.assertEqual(round(9.9), 10.0) self.assertEqual(round(999999999.9), 1000000000.0) self.assertEqual(round(-0.9), -1.0) self.assertEqual(round(-9.9), -10.0) self.assertEqual(round(-999999999.9), -1000000000.0) self.assertEqual(round(-8.0, -1), -10.0) self.assertEqual(type(round(-8.0, -1)), float) self.assertEqual(type(round(-8.0, 0)), float) self.assertEqual(type(round(-8.0, 1)), float) # Check even / odd rounding behaviour self.assertEqual(round(5.5), 6) self.assertEqual(round(6.5), 6) self.assertEqual(round(-5.5), -6) self.assertEqual(round(-6.5), -6) # Check behavior on ints self.assertEqual(round(0), 0) self.assertEqual(round(8), 8) self.assertEqual(round(-8), -8) self.assertEqual(type(round(0)), int) self.assertEqual(type(round(-8, -1)), int) self.assertEqual(type(round(-8, 0)), int) self.assertEqual(type(round(-8, 1)), int) # test new kwargs self.assertEqual(round(number=-8.0, ndigits=-1), -10.0) self.assertRaises(TypeError, round) # test generic rounding delegation for reals class TestRound: def __round__(self): return 23 class TestNoRound: pass self.assertEqual(round(TestRound()), 23) self.assertRaises(TypeError, round, 1, 2, 3) self.assertRaises(TypeError, round, TestNoRound()) t = TestNoRound() t.__round__ = lambda *args: args self.assertRaises(TypeError, round, t) self.assertRaises(TypeError, round, t, 0) # Some versions of glibc for alpha have a bug that affects # float -> integer rounding (floor, ceil, rint, round) for # values in the range [2**52, 2**53). See: # # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350 # # We skip this test on Linux/alpha if it would fail. linux_alpha = (platform.system().startswith('Linux') and platform.machine().startswith('alpha')) system_round_bug = round(5e15+1) != 5e15+1 @unittest.skipIf(linux_alpha and system_round_bug, "test will fail; failure is probably due to a " "buggy system round function") def test_round_large(self): # Issue #1869: integral floats should remain unchanged self.assertEqual(round(5e15-1), 5e15-1) self.assertEqual(round(5e15), 5e15) self.assertEqual(round(5e15+1), 5e15+1) self.assertEqual(round(5e15+2), 5e15+2) self.assertEqual(round(5e15+3), 5e15+3) def test_setattr(self): setattr(sys, 'spam', 1) self.assertEqual(sys.spam, 1) self.assertRaises(TypeError, setattr, sys, 1, 'spam') self.assertRaises(TypeError, setattr) # test_str(): see test_unicode.py and test_bytes.py for str() tests. def test_sum(self): self.assertEqual(sum([]), 0) self.assertEqual(sum(list(range(2,8))), 27) self.assertEqual(sum(iter(list(range(2,8)))), 27) self.assertEqual(sum(Squares(10)), 285) self.assertEqual(sum(iter(Squares(10))), 285) self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) self.assertRaises(TypeError, sum) self.assertRaises(TypeError, sum, 42) self.assertRaises(TypeError, sum, ['a', 'b', 'c']) self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '') self.assertRaises(TypeError, sum, [b'a', b'c'], b'') values = [bytearray(b'a'), bytearray(b'b')] self.assertRaises(TypeError, sum, values, bytearray(b'')) self.assertRaises(TypeError, sum, [[1], [2], [3]]) self.assertRaises(TypeError, sum, [{2:3}]) self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3}) class BadSeq: def __getitem__(self, index): raise ValueError self.assertRaises(ValueError, sum, BadSeq()) empty = [] sum(([x] for x in range(10)), empty) self.assertEqual(empty, []) def test_type(self): self.assertEqual(type(''), type('123')) self.assertNotEqual(type(''), type(())) # We don't want self in vars(), so these are static methods @staticmethod def get_vars_f0(): return vars() @staticmethod def get_vars_f2(): BuiltinTest.get_vars_f0() a = 1 b = 2 return vars() class C_get_vars(object): def getDict(self): return {'a':2} __dict__ = property(fget=getDict) def test_vars(self): self.assertEqual(set(vars()), set(dir())) self.assertEqual(set(vars(sys)), set(dir(sys))) self.assertEqual(self.get_vars_f0(), {}) self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) self.assertRaises(TypeError, vars, 42, 42) self.assertRaises(TypeError, vars, 42) self.assertEqual(vars(self.C_get_vars()), {'a':2}) def test_zip(self): a = (1, 2, 3) b = (4, 5, 6) t = [(1, 4), (2, 5), (3, 6)] self.assertEqual(list(zip(a, b)), t) b = [4, 5, 6] self.assertEqual(list(zip(a, b)), t) b = (4, 5, 6, 7) self.assertEqual(list(zip(a, b)), t) class I: def __getitem__(self, i): if i < 0 or i > 2: raise IndexError return i + 4 self.assertEqual(list(zip(a, I())), t) self.assertEqual(list(zip()), []) self.assertEqual(list(zip(*[])), []) self.assertRaises(TypeError, zip, None) class G: pass self.assertRaises(TypeError, zip, a, G()) self.assertRaises(RuntimeError, zip, a, TestFailingIter()) # Make sure zip doesn't try to allocate a billion elements for the # result list when one of its arguments doesn't say how long it is. # A MemoryError is the most likely failure mode. class SequenceWithoutALength: def __getitem__(self, i): if i == 5: raise IndexError else: return i self.assertEqual( list(zip(SequenceWithoutALength(), range(2**30))), list(enumerate(range(5))) ) class BadSeq: def __getitem__(self, i): if i == 5: raise ValueError else: return i self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq())) def test_zip_pickle(self): a = (1, 2, 3) b = (4, 5, 6) t = [(1, 4), (2, 5), (3, 6)] z1 = zip(a, b) self.check_iter_pickle(z1, t) def test_format(self): # Test the basic machinery of the format() builtin. Don't test # the specifics of the various formatters self.assertEqual(format(3, ''), '3') # Returns some classes to use for various tests. There's # an old-style version, and a new-style version def classes_new(): class A(object): def __init__(self, x): self.x = x def __format__(self, format_spec): return str(self.x) + format_spec class DerivedFromA(A): pass class Simple(object): pass class DerivedFromSimple(Simple): def __init__(self, x): self.x = x def __format__(self, format_spec): return str(self.x) + format_spec class DerivedFromSimple2(DerivedFromSimple): pass return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2 def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2): self.assertEqual(format(A(3), 'spec'), '3spec') self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec') self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc') self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'), '10abcdef') class_test(*classes_new()) def empty_format_spec(value): # test that: # format(x, '') == str(x) # format(x) == str(x) self.assertEqual(format(value, ""), str(value)) self.assertEqual(format(value), str(value)) # for builtin types, format(x, "") == str(x) empty_format_spec(17**13) empty_format_spec(1.0) empty_format_spec(3.1415e104) empty_format_spec(-3.1415e104) empty_format_spec(3.1415e-104) empty_format_spec(-3.1415e-104) empty_format_spec(object) empty_format_spec(None) # TypeError because self.__format__ returns the wrong type class BadFormatResult: def __format__(self, format_spec): return 1.0 self.assertRaises(TypeError, format, BadFormatResult(), "") # TypeError because format_spec is not unicode or str self.assertRaises(TypeError, format, object(), 4) self.assertRaises(TypeError, format, object(), object()) # tests for object.__format__ really belong elsewhere, but # there's no good place to put them x = object().__format__('') self.assertTrue(x.startswith('<object object at')) # first argument to object.__format__ must be string self.assertRaises(TypeError, object().__format__, 3) self.assertRaises(TypeError, object().__format__, object()) self.assertRaises(TypeError, object().__format__, None) # -------------------------------------------------------------------- # Issue #7994: object.__format__ with a non-empty format string is # deprecated def test_deprecated_format_string(obj, fmt_str, should_raise): if should_raise: self.assertRaises(TypeError, format, obj, fmt_str) else: format(obj, fmt_str) fmt_strs = ['', 's'] class A: def __format__(self, fmt_str): return format('', fmt_str) for fmt_str in fmt_strs: test_deprecated_format_string(A(), fmt_str, False) class B: pass class C(object): pass for cls in [object, B, C]: for fmt_str in fmt_strs: test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0) # -------------------------------------------------------------------- # make sure we can take a subclass of str as a format spec class DerivedFromStr(str): pass self.assertEqual(format(0, DerivedFromStr('10')), ' 0') def test_bin(self): self.assertEqual(bin(0), '0b0') self.assertEqual(bin(1), '0b1') self.assertEqual(bin(-1), '-0b1') self.assertEqual(bin(2**65), '0b1' + '0' * 65) self.assertEqual(bin(2**65-1), '0b' + '1' * 65) self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65) self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65) def test_bytearray_translate(self): x = bytearray(b"abc") self.assertRaises(ValueError, x.translate, b"1", 1) self.assertRaises(TypeError, x.translate, b"1"*256, 1) def test_construct_singletons(self): for const in None, Ellipsis, NotImplemented: tp = type(const) self.assertIs(tp(), const) self.assertRaises(TypeError, tp, 1, 2) self.assertRaises(TypeError, tp, a=1, b=2) class TestSorted(unittest.TestCase): def test_basic(self): data = list(range(100)) copy = data[:] random.shuffle(copy) self.assertEqual(data, sorted(copy)) self.assertNotEqual(data, copy) data.reverse() random.shuffle(copy) self.assertEqual(data, sorted(copy, key=lambda x: -x)) self.assertNotEqual(data, copy) random.shuffle(copy) self.assertEqual(data, sorted(copy, reverse=1)) self.assertNotEqual(data, copy) def test_inputtypes(self): s = 'abracadabra' types = [list, tuple, str] for T in types: self.assertEqual(sorted(s), sorted(T(s))) s = ''.join(set(s)) # unique letters only types = [str, set, frozenset, list, tuple, dict.fromkeys] for T in types: self.assertEqual(sorted(s), sorted(T(s))) def test_baddecorator(self): data = 'The quick Brown fox Jumped over The lazy Dog'.split() self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) class ShutdownTest(unittest.TestCase): def test_cleanup(self): # Issue #19255: builtins are still available at shutdown code = """if 1: import builtins import sys class C: def __del__(self): print("before") # Check that builtins still exist len(()) print("after") c = C() # Make this module survive until builtins and sys are cleaned builtins.here = sys.modules[__name__] sys.here = sys.modules[__name__] # Create a reference loop so that this module needs to go # through a GC phase. here = sys.modules[__name__] """ # Issue #20599: Force ASCII encoding to get a codec implemented in C, # otherwise the codec may be unloaded before C.__del__() is called, and # so print("before") fails because the codec cannot be used to encode # "before" to sys.stdout.encoding. For example, on Windows, # sys.stdout.encoding is the OEM code page and these code pages are # implemented in Python rc, out, err = assert_python_ok("-c", code, PYTHONIOENCODING="ascii") self.assertEqual(["before", "after"], out.decode().splitlines()) def load_tests(loader, tests, pattern): from doctest import DocTestSuite tests.addTest(DocTestSuite(builtins)) return tests if __name__ == "__main__": unittest.main()
lgpl-3.0
qspin/qtaste
demo/pywinauto-0.3.8/examples/ForteAgentSample.py
19
2955
"""Perform some tests with Forte Agent NOTE: Forte Agent has a very dynamic interface e.g. whether it is free or not, whether it is still in the grace period. For this reason this example script may or may not work well for you""" print __doc__ import time from pprint import pprint from pywinauto.application import Application # start the application and wait for the Agent Dialog to be ready app = Application().start_(r"c:\program files\agent\agent.exe") while not app.Windows_(): time.sleep(.5) # if the trial nag dialog pops up if app.window_(title = "Forte Agent Trial").Exists(): #app.ForteAgentTrial.IdLikeToContinueUsingAgentfor7moredays.Click() app.ForteAgentTrial.IdliketouseFreeAgent app.ForteAgentTrial.OK.Click() if app.window_(title = "Free Agent Registration").Exists(): app.FreeAgentRegistration.ImreallybusyRemindmein30.Click() app.FreeAgentRegistration.OK.CloseClick() if app.window_(title = "What's New Reminder").Exists(): app.WhatsNewReminder.ImreallybusyRemindmein90.Click() app.WhatsNewReminder.OK.CloseClick() # wait until the app is ready app.FreeAgent.Wait("ready") # if we get the Agent Setup wizard pops up close it if app.AgentSetupWizard.Cancel.Exists(1): app.AgentSetupWizard.Cancel.Click() app.AgentSetupWizard2.Yes.Click() # Select to emtpy trash app.FreeAgent.MenuSelect("File->EmptyTrash") app.EmptyTrash.No.Click() # Select some more menus (typo not important :-) app.FreeAgent.MenuSelect("File->Purge and Compact -> Compact All Folders") app.FreeAgent.OK.Click() #print app.FreeAgent.MenuItem("File->Purge and compact").GetProperties() #app.FreeAgent.MenuSelect("File->Purge and Compact->PurgeFolder") #app.PurgeFoldersInDesks.Cancel.Click() # this is strange - when I do it by hand this is "Purge Folder" but during # automation the text of the menu item is Purge Selected Folders # FIXED - need to init the sub menu! app.FreeAgent.MenuSelect("File->Purge and Compact->Purge Folder") app.AgentTip.OK.Click() app.FreeAgent.MenuSelect("File->Import and Export->Import Messages") app.ImportMessages.Cancel.Click() app.FreeAgent.MenuSelect("File->Import and Export->Import Address Book") app.ImportAddresses.Cancel.Click() app.FreeAgent.MenuSelect("File->Import and Export->Export Address Book") app.ExportAddresses.Cancel.Click() # pick something other then a file menu item app.FreeAgent.MenuSelect("Tools->ApplyFiltersToFolder") if app.ToolsApplyFilters.OK.Exists(): app.ToolsApplyFilters.OK.Click() #app.AgentTip.OK.Click() #app.ApplyFiltersToFolders.Cancel.Click() print "==" * 20 print "The Agent File Menu..." print "==" * 20 pprint (app.FreeAgent.MenuItems()[1]) try: app.FreeAgent.MenuSelect("File->Print") app.Print.Cancel.Click() except: print "Print Menu was probably disabled" # quit Agent app.FreeAgent.MenuSelect("File -> Exit")
lgpl-3.0
sndnvaps/linux-1
tools/perf/python/twatch.py
1565
1316
#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # twatch - Experimental use of the perf python interface # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com> # # This application is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2. # # This application 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. import perf def main(): cpus = perf.cpu_map() threads = perf.thread_map() evsel = perf.evsel(task = 1, comm = 1, mmap = 0, wakeup_events = 1, watermark = 1, sample_id_all = 1, sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU) evsel.open(cpus = cpus, threads = threads); evlist = perf.evlist(cpus, threads) evlist.add(evsel) evlist.mmap() while True: evlist.poll(timeout = -1) for cpu in cpus: event = evlist.read_on_cpu(cpu) if not event: continue print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu, event.sample_pid, event.sample_tid), print event if __name__ == '__main__': main()
gpl-2.0
dafei2015/hugula
Client/tools/site-packages/PIL/ImageGrab.py
13
1926
# # The Python Imaging Library # $Id: ImageGrab.py 2134 2004-10-06 08:55:20Z fredrik $ # # screen grabber (windows only) # # History: # 2001-04-26 fl created # 2001-09-17 fl use builtin driver, if present # 2002-11-19 fl added grabclipboard support # # Copyright (c) 2001-2002 by Secret Labs AB # Copyright (c) 2001-2002 by Fredrik Lundh # # See the README file for information on usage and redistribution. # import Image ## # (New in 1.1.3) The <b>ImageGrab</b> module can be used to copy # the contents of the screen to a PIL image memory. # <p> # The current version works on Windows only.</p> # # @since 1.1.3 ## try: # built-in driver (1.1.3 and later) grabber = Image.core.grabscreen except AttributeError: # stand-alone driver (pil plus) import _grabscreen grabber = _grabscreen.grab ## # (New in 1.1.3) Take a snapshot of the screen. The pixels inside the # bounding box are returned as an "RGB" image. If the bounding box is # omitted, the entire screen is copied. # # @param bbox What region to copy. Default is the entire screen. # @return An image # @since 1.1.3 def grab(bbox=None): size, data = grabber() im = Image.fromstring( "RGB", size, data, # RGB, 32-bit line padding, origo in lower left corner "raw", "BGR", (size[0]*3 + 3) & -4, -1 ) if bbox: im = im.crop(bbox) return im ## # (New in 1.1.4) Take a snapshot of the clipboard image, if any. # # @return An image, a list of filenames, or None if the clipboard does # not contain image data or filenames. Note that if a list is # returned, the filenames may not represent image files. # @since 1.1.4 def grabclipboard(): debug = 0 # temporary interface data = Image.core.grabclipboard(debug) if Image.isStringType(data): import BmpImagePlugin, StringIO return BmpImagePlugin.DibImageFile(StringIO.StringIO(data)) return data
mit
matthijsvk/multimodalSR
code/Experiments/neon-master/examples/imagenet/ingest.py
1
9525
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- from builtins import str, zip from configargparse import ArgParser from itertools import repeat from neon import logger as neon_logger from neon.util.persist import ensure_dirs_exist from PIL import Image import logging import multiprocessing import numpy as np import os import re import shutil import tarfile import tqdm import zlib def process_i1k_tar_subpath(args): """ Process a single subpath in a I1K tar. By process: optionally untar recursive tars (only on 'train') resize/copy images Returns a list of [(fname, label), ...] """ target_size, toptar, img_dir, setn, label_dict, subpath = args name_slice = slice(None, 9) if setn == 'train' else slice(15, -5) label = label_dict[subpath.name[name_slice]] outpath = os.path.join(img_dir, str(label)) if setn == 'train': tf = tarfile.open(toptar) subtar = tarfile.open(fileobj=tf.extractfile(subpath)) file_list = subtar.getmembers() return process_files_in_tar(target_size, label, subtar, file_list, outpath) elif setn == 'val': tf = tarfile.open(toptar) file_list = [subpath] return process_files_in_tar(target_size, label, tf, file_list, outpath) def process_files_in_tar(target_size, label, tar_handle, file_list, outpath): pair_list = [] if not os.path.exists(outpath): # This avoids race conditions that sometimes happen when doing these # checks in parallel try: os.makedirs(outpath) except OSError: pass for fobj in file_list: fname = os.path.join(outpath, fobj.name) if not os.path.exists(fname): transform_and_save(target_size, tar_handle, fobj, fname) pair_list.append((fname, label)) return pair_list def transform_and_save(target_size, tar_handle, img_object, output_filename): """ Takes a tar file handle and a TarInfo object inside that tarfile and optionally transforms it and then writes it out to output_filename """ img_handle = tar_handle.extractfile(img_object) img = Image.open(img_handle) width, height = img.size # Take the smaller image dimension down to target_size # while retaining aspect_ration. Otherwise leave it alone if width < height: if width > target_size: scale_factor = float(target_size) / width width = target_size height = int(height*scale_factor) else: if height > target_size: scale_factor = float(target_size) / height height = target_size width = int(width*scale_factor) if img.size[0] != width or img.size[1] != height: img = img.resize((width, height), resample=Image.LANCZOS) img.save(output_filename, quality=95) else: # Avoid recompression by saving file out directly without transformation dname, fname = os.path.split(output_filename) tar_handle.extract(img_object, path=dname) if fname != img_object.name: # Rename if name inside of tar is different than what we want it # called on the outside shutil.move(os.path.join(dname, img_object.name), output_filename) assert(os.stat(output_filename).st_size > 0), "{} has size 0".format(output_filename) class IngestI1K(object): def __init__(self, input_dir, out_dir, target_size=256): np.random.seed(0) self.orig_out_dir = out_dir self.out_dir = os.path.join(out_dir, 'i1k-extracted') self.input_dir = os.path.expanduser(input_dir) if input_dir is not None else None self.devkit = os.path.join(self.input_dir, 'ILSVRC2012_devkit_t12.tar.gz') self.manifests, self.tars = dict(), dict() for setn in ('train', 'val'): self.manifests[setn] = os.path.join(self.out_dir, '{}-index.csv'.format(setn)) self.tars[setn] = os.path.join(self.input_dir, 'ILSVRC2012_img_{}.tar'.format(setn)) self.target_size = target_size self._target_filenames = {} def _target_filename(self, target): """ Return a filename of a file containing a binary representation of target. If no such file exists, make one. """ target_filename = self._target_filenames.get(target) if target_filename is None: target_filename = os.path.join(self.out_dir, 'labels', str(target) + '.txt') ensure_dirs_exist(target_filename) np.savetxt(target_filename, [target], '%d') self._target_filenames[target] = target_filename return target_filename def extract_labels(self, setn): if not os.path.exists(self.devkit): raise IOError(("Metadata file {} not found. Ensure you have ImageNet downloaded" ).format(self.devkit)) with tarfile.open(self.devkit, "r:gz") as tf: synsetfile = 'ILSVRC2012_devkit_t12/data/meta.mat' valfile = 'ILSVRC2012_devkit_t12/data/ILSVRC2012_validation_ground_truth.txt' if setn == 'train': # get the synset mapping by hacking around matlab's terrible compressed format meta_buff = tf.extractfile(synsetfile).read() decomp = zlib.decompressobj() self.synsets = re.findall(re.compile('n\d+'), decomp.decompress(meta_buff[136:])) return {s: i for i, s in enumerate(self.synsets)} elif setn == 'val': # get the ground truth validation labels and offset to zero return {"%08d" % (i + 1): int(x) - 1 for i, x in enumerate(tf.extractfile(valfile))} else: raise ValueError("Unknown set name: {}".format(setn)) def train_or_val_pairs(self, setn): """ untar imagenet tar files into directories that indicate their label. returns [(filename, label), ...] for train or val set partitions """ img_dir = os.path.join(self.out_dir, setn) neon_logger.display("Extracting %s files" % (setn)) root_tf_path = self.tars[setn] if not os.path.exists(root_tf_path): raise IOError(("tar file {} not found. Ensure you have ImageNet downloaded" ).format(root_tf_path)) try: root_tf = tarfile.open(root_tf_path) except tarfile.ReadError as e: raise ValueError('ReadError opening {}: {}'.format(root_tf_path, e)) label_dict = self.extract_labels(setn) subpaths = root_tf.getmembers() arg_iterator = zip(repeat(self.target_size), repeat(root_tf_path), repeat(img_dir), repeat(setn), repeat(label_dict), subpaths) pool = multiprocessing.Pool() pairs = [] for pair_list in tqdm.tqdm(pool.imap_unordered(process_i1k_tar_subpath, arg_iterator), total=len(subpaths)): pairs.extend(pair_list) pool.close() pool.join() root_tf.close() return pairs def run(self): """ extract and resize images then write manifest files to disk. """ cfg_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'train.cfg') log_file = os.path.join(self.orig_out_dir, 'train.log') manifest_list_cfg = ', '.join([k+':'+v for k, v in self.manifests.items()]) with open(cfg_file, 'w') as f: f.write('manifest = [{}]\n'.format(manifest_list_cfg)) f.write('manifest_root = {}\n'.format(self.out_dir)) f.write('log = {}\n'.format(log_file)) f.write('epochs = 90\nrng_seed = 0\nverbose = True\neval_freq = 1\n') for setn, manifest in self.manifests.items(): if not os.path.exists(manifest): pairs = self.train_or_val_pairs(setn) records = [(os.path.relpath(fname, self.out_dir), os.path.relpath(self._target_filename(int(tgt)), self.out_dir)) for fname, tgt in pairs] np.savetxt(manifest, records, fmt='%s,%s') if __name__ == "__main__": parser = ArgParser() parser.add_argument('--input_dir', help='Directory to find input tars', default=None) parser.add_argument('--out_dir', help='Directory to write ingested files', default=None) parser.add_argument('--target_size', type=int, default=256, help='Size in pixels to scale shortest side DOWN to (0 means no scaling)') args = parser.parse_args() logger = logging.getLogger(__name__) bw = IngestI1K(input_dir=args.input_dir, out_dir=args.out_dir, target_size=args.target_size) bw.run()
mit
tqchen/tvm
tutorials/frontend/deploy_model_on_rasp.py
1
8161
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ .. _tutorial-deploy-model-on-rasp: Deploy the Pretrained Model on Raspberry Pi =========================================== **Author**: `Ziheng Jiang <https://ziheng.org/>`_, \ `Hiroyuki Makino <https://makihiro.github.io/>`_ This is an example of using Relay to compile a ResNet model and deploy it on Raspberry Pi. """ import tvm from tvm import te import tvm.relay as relay from tvm import rpc from tvm.contrib import util, graph_runtime as runtime from tvm.contrib.download import download_testdata ###################################################################### # .. _build-tvm-runtime-on-device: # # Build TVM Runtime on Device # --------------------------- # # The first step is to build the TVM runtime on the remote device. # # .. note:: # # All instructions in both this section and next section should be # executed on the target device, e.g. Raspberry Pi. And we assume it # has Linux running. # # Since we do compilation on local machine, the remote device is only used # for running the generated code. We only need to build tvm runtime on # the remote device. # # .. code-block:: bash # # git clone --recursive https://github.com/apache/incubator-tvm tvm # cd tvm # mkdir build # cp cmake/config.cmake build # cd build # cmake .. # make runtime -j4 # # After building runtime successfully, we need to set environment varibles # in :code:`~/.bashrc` file. We can edit :code:`~/.bashrc` # using :code:`vi ~/.bashrc` and add the line below (Assuming your TVM # directory is in :code:`~/tvm`): # # .. code-block:: bash # # export PYTHONPATH=$PYTHONPATH:~/tvm/python # # To update the environment variables, execute :code:`source ~/.bashrc`. ###################################################################### # Set Up RPC Server on Device # --------------------------- # To start an RPC server, run the following command on your remote device # (Which is Raspberry Pi in our example). # # .. code-block:: bash # # python -m tvm.exec.rpc_server --host 0.0.0.0 --port=9090 # # If you see the line below, it means the RPC server started # successfully on your device. # # .. code-block:: bash # # INFO:root:RPCServer: bind to 0.0.0.0:9090 # ###################################################################### # Prepare the Pre-trained Model # ----------------------------- # Back to the host machine, which should have a full TVM installed (with LLVM). # # We will use pre-trained model from # `MXNet Gluon model zoo <https://mxnet.incubator.apache.org/api/python/gluon/model_zoo.html>`_. # You can found more details about this part at tutorial :ref:`tutorial-from-mxnet`. from mxnet.gluon.model_zoo.vision import get_model from PIL import Image import numpy as np # one line to get the model block = get_model("resnet18_v1", pretrained=True) ###################################################################### # In order to test our model, here we download an image of cat and # transform its format. img_url = "https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true" img_name = "cat.png" img_path = download_testdata(img_url, img_name, module="data") image = Image.open(img_path).resize((224, 224)) def transform_image(image): image = np.array(image) - np.array([123.0, 117.0, 104.0]) image /= np.array([58.395, 57.12, 57.375]) image = image.transpose((2, 0, 1)) image = image[np.newaxis, :] return image x = transform_image(image) ###################################################################### # synset is used to transform the label from number of ImageNet class to # the word human can understand. synset_url = "".join( [ "https://gist.githubusercontent.com/zhreshold/", "4d0b62f3d01426887599d4f7ede23ee5/raw/", "596b27d23537e5a1b5751d2b0481ef172f58b539/", "imagenet1000_clsid_to_human.txt", ] ) synset_name = "imagenet1000_clsid_to_human.txt" synset_path = download_testdata(synset_url, synset_name, module="data") with open(synset_path) as f: synset = eval(f.read()) ###################################################################### # Now we would like to port the Gluon model to a portable computational graph. # It's as easy as several lines. # We support MXNet static graph(symbol) and HybridBlock in mxnet.gluon shape_dict = {"data": x.shape} mod, params = relay.frontend.from_mxnet(block, shape_dict) # we want a probability so add a softmax operator func = mod["main"] func = relay.Function(func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs) ###################################################################### # Here are some basic data workload configurations. batch_size = 1 num_classes = 1000 image_shape = (3, 224, 224) data_shape = (batch_size,) + image_shape ###################################################################### # Compile The Graph # ----------------- # To compile the graph, we call the :any:`relay.build` function # with the graph configuration and parameters. However, You cannot to # deploy a x86 program on a device with ARM instruction set. It means # Relay also needs to know the compilation option of target device, # apart from arguments :code:`net` and :code:`params` to specify the # deep learning workload. Actually, the option matters, different option # will lead to very different performance. ###################################################################### # If we run the example on our x86 server for demonstration, we can simply # set it as :code:`llvm`. If running it on the Raspberry Pi, we need to # specify its instruction set. Set :code:`local_demo` to False if you want # to run this tutorial with a real device. local_demo = True if local_demo: target = tvm.target.Target("llvm") else: target = tvm.target.arm_cpu("rasp3b") # The above line is a simple form of # target = tvm.target.Target('llvm -device=arm_cpu -model=bcm2837 -mtriple=armv7l-linux-gnueabihf -mattr=+neon') with tvm.transform.PassContext(opt_level=3): lib = relay.build(func, target, params=params) # After `relay.build`, you will get three return values: graph, # library and the new parameter, since we do some optimization that will # change the parameters but keep the result of model as the same. # Save the library at local temporary directory. tmp = util.tempdir() lib_fname = tmp.relpath("net.tar") lib.export_library(lib_fname) ###################################################################### # Deploy the Model Remotely by RPC # -------------------------------- # With RPC, you can deploy the model remotely from your host machine # to the remote device. # obtain an RPC session from remote device. if local_demo: remote = rpc.LocalSession() else: # The following is my environment, change this to the IP address of your target device host = "10.77.1.162" port = 9090 remote = rpc.connect(host, port) # upload the library to remote device and load it remote.upload(lib_fname) rlib = remote.load_module("net.tar") # create the remote runtime module ctx = remote.cpu(0) module = runtime.GraphModule(rlib["default"](ctx)) # set input data module.set_input("data", tvm.nd.array(x.astype("float32"))) # run module.run() # get output out = module.get_output(0) # get top1 result top1 = np.argmax(out.asnumpy()) print("TVM prediction top-1: {}".format(synset[top1]))
apache-2.0
mixturemodel-flow/tensorflow
tensorflow/contrib/learn/python/learn/learn_io/data_feeder_test.py
71
12923
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for `DataFeeder`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six from six.moves import xrange # pylint: disable=redefined-builtin # pylint: disable=wildcard-import from tensorflow.contrib.learn.python.learn.learn_io import * from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.platform import test # pylint: enable=wildcard-import class DataFeederTest(test.TestCase): # pylint: disable=undefined-variable """Tests for `DataFeeder`.""" def _wrap_dict(self, data, prepend=''): return {prepend + '1': data, prepend + '2': data} def _assert_raises(self, input_data): with self.assertRaisesRegexp(TypeError, 'annot convert'): data_feeder.DataFeeder(input_data, None, n_classes=0, batch_size=1) def test_input_uint32(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.uint32) self._assert_raises(data) self._assert_raises(self._wrap_dict(data)) def test_input_uint64(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.uint64) self._assert_raises(data) self._assert_raises(self._wrap_dict(data)) def _assert_dtype(self, expected_np_dtype, expected_tf_dtype, input_data): feeder = data_feeder.DataFeeder(input_data, None, n_classes=0, batch_size=1) if isinstance(input_data, dict): for k, v in list(feeder.input_dtype.items()): self.assertEqual(expected_np_dtype, v) else: self.assertEqual(expected_np_dtype, feeder.input_dtype) with ops.Graph().as_default() as g, self.test_session(g): inp, _ = feeder.input_builder() if isinstance(inp, dict): for k, v in list(inp.items()): self.assertEqual(expected_tf_dtype, v.dtype) else: self.assertEqual(expected_tf_dtype, inp.dtype) def test_input_int8(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.int8) self._assert_dtype(np.int8, dtypes.int8, data) self._assert_dtype(np.int8, dtypes.int8, self._wrap_dict(data)) def test_input_int16(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.int16) self._assert_dtype(np.int16, dtypes.int16, data) self._assert_dtype(np.int16, dtypes.int16, self._wrap_dict(data)) def test_input_int32(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.int32) self._assert_dtype(np.int32, dtypes.int32, data) self._assert_dtype(np.int32, dtypes.int32, self._wrap_dict(data)) def test_input_int64(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.int64) self._assert_dtype(np.int64, dtypes.int64, data) self._assert_dtype(np.int64, dtypes.int64, self._wrap_dict(data)) def test_input_uint8(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.uint8) self._assert_dtype(np.uint8, dtypes.uint8, data) self._assert_dtype(np.uint8, dtypes.uint8, self._wrap_dict(data)) def test_input_uint16(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.uint16) self._assert_dtype(np.uint16, dtypes.uint16, data) self._assert_dtype(np.uint16, dtypes.uint16, self._wrap_dict(data)) def test_input_float16(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.float16) self._assert_dtype(np.float16, dtypes.float16, data) self._assert_dtype(np.float16, dtypes.float16, self._wrap_dict(data)) def test_input_float32(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.float32) self._assert_dtype(np.float32, dtypes.float32, data) self._assert_dtype(np.float32, dtypes.float32, self._wrap_dict(data)) def test_input_float64(self): data = np.matrix([[1, 2], [3, 4]], dtype=np.float64) self._assert_dtype(np.float64, dtypes.float64, data) self._assert_dtype(np.float64, dtypes.float64, self._wrap_dict(data)) def test_input_bool(self): data = np.array([[False for _ in xrange(2)] for _ in xrange(2)]) self._assert_dtype(np.bool, dtypes.bool, data) self._assert_dtype(np.bool, dtypes.bool, self._wrap_dict(data)) def test_input_string(self): input_data = np.array([['str%d' % i for i in xrange(2)] for _ in xrange(2)]) self._assert_dtype(input_data.dtype, dtypes.string, input_data) self._assert_dtype(input_data.dtype, dtypes.string, self._wrap_dict(input_data)) def _assertAllClose(self, src, dest, src_key_of=None, src_prop=None): def func(x): val = getattr(x, src_prop) if src_prop else x return val if src_key_of is None else src_key_of[val] if isinstance(src, dict): for k in list(src.keys()): self.assertAllClose(func(src[k]), dest) else: self.assertAllClose(func(src), dest) def test_unsupervised(self): def func(feeder): with self.test_session(): inp, _ = feeder.input_builder() feed_dict_fn = feeder.get_feed_dict_fn() feed_dict = feed_dict_fn() self._assertAllClose(inp, [[1, 2]], feed_dict, 'name') data = np.matrix([[1, 2], [2, 3], [3, 4]]) func(data_feeder.DataFeeder(data, None, n_classes=0, batch_size=1)) func( data_feeder.DataFeeder( self._wrap_dict(data), None, n_classes=0, batch_size=1)) def test_data_feeder_regression(self): def func(df): inp, out = df.input_builder() feed_dict_fn = df.get_feed_dict_fn() feed_dict = feed_dict_fn() self._assertAllClose(inp, [[3, 4], [1, 2]], feed_dict, 'name') self._assertAllClose(out, [2, 1], feed_dict, 'name') x = np.matrix([[1, 2], [3, 4]]) y = np.array([1, 2]) func(data_feeder.DataFeeder(x, y, n_classes=0, batch_size=3)) func( data_feeder.DataFeeder( self._wrap_dict(x, 'in'), self._wrap_dict(y, 'out'), n_classes=self._wrap_dict(0, 'out'), batch_size=3)) def test_epoch(self): def func(feeder): with self.test_session(): feeder.input_builder() epoch = feeder.make_epoch_variable() feed_dict_fn = feeder.get_feed_dict_fn() # First input feed_dict = feed_dict_fn() self.assertAllClose(feed_dict[epoch.name], [0]) # Second input feed_dict = feed_dict_fn() self.assertAllClose(feed_dict[epoch.name], [0]) # Third input feed_dict = feed_dict_fn() self.assertAllClose(feed_dict[epoch.name], [0]) # Back to the first input again, so new epoch. feed_dict = feed_dict_fn() self.assertAllClose(feed_dict[epoch.name], [1]) data = np.matrix([[1, 2], [2, 3], [3, 4]]) labels = np.array([0, 0, 1]) func(data_feeder.DataFeeder(data, labels, n_classes=0, batch_size=1)) func( data_feeder.DataFeeder( self._wrap_dict(data, 'in'), self._wrap_dict(labels, 'out'), n_classes=self._wrap_dict(0, 'out'), batch_size=1)) def test_data_feeder_multioutput_regression(self): def func(df): inp, out = df.input_builder() feed_dict_fn = df.get_feed_dict_fn() feed_dict = feed_dict_fn() self._assertAllClose(inp, [[3, 4], [1, 2]], feed_dict, 'name') self._assertAllClose(out, [[3, 4], [1, 2]], feed_dict, 'name') x = np.matrix([[1, 2], [3, 4]]) y = np.array([[1, 2], [3, 4]]) func(data_feeder.DataFeeder(x, y, n_classes=0, batch_size=2)) func( data_feeder.DataFeeder( self._wrap_dict(x, 'in'), self._wrap_dict(y, 'out'), n_classes=self._wrap_dict(0, 'out'), batch_size=2)) def test_data_feeder_multioutput_classification(self): def func(df): inp, out = df.input_builder() feed_dict_fn = df.get_feed_dict_fn() feed_dict = feed_dict_fn() self._assertAllClose(inp, [[3, 4], [1, 2]], feed_dict, 'name') self._assertAllClose( out, [[[0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]], [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0]]], feed_dict, 'name') x = np.matrix([[1, 2], [3, 4]]) y = np.array([[0, 1, 2], [2, 3, 4]]) func(data_feeder.DataFeeder(x, y, n_classes=5, batch_size=2)) func( data_feeder.DataFeeder( self._wrap_dict(x, 'in'), self._wrap_dict(y, 'out'), n_classes=self._wrap_dict(5, 'out'), batch_size=2)) def test_streaming_data_feeder(self): def func(df): inp, out = df.input_builder() feed_dict_fn = df.get_feed_dict_fn() feed_dict = feed_dict_fn() self._assertAllClose(inp, [[[1, 2]], [[3, 4]]], feed_dict, 'name') self._assertAllClose(out, [[[1], [2]], [[2], [2]]], feed_dict, 'name') def x_iter(wrap_dict=False): yield np.array([[1, 2]]) if not wrap_dict else self._wrap_dict( np.array([[1, 2]]), 'in') yield np.array([[3, 4]]) if not wrap_dict else self._wrap_dict( np.array([[3, 4]]), 'in') def y_iter(wrap_dict=False): yield np.array([[1], [2]]) if not wrap_dict else self._wrap_dict( np.array([[1], [2]]), 'out') yield np.array([[2], [2]]) if not wrap_dict else self._wrap_dict( np.array([[2], [2]]), 'out') func( data_feeder.StreamingDataFeeder( x_iter(), y_iter(), n_classes=0, batch_size=2)) func( data_feeder.StreamingDataFeeder( x_iter(True), y_iter(True), n_classes=self._wrap_dict(0, 'out'), batch_size=2)) # Test non-full batches. func( data_feeder.StreamingDataFeeder( x_iter(), y_iter(), n_classes=0, batch_size=10)) func( data_feeder.StreamingDataFeeder( x_iter(True), y_iter(True), n_classes=self._wrap_dict(0, 'out'), batch_size=10)) def test_dask_data_feeder(self): if HAS_PANDAS and HAS_DASK: x = pd.DataFrame( dict( a=np.array([.1, .3, .4, .6, .2, .1, .6]), b=np.array([.7, .8, .1, .2, .5, .3, .9]))) x = dd.from_pandas(x, npartitions=2) y = pd.DataFrame(dict(labels=np.array([1, 0, 2, 1, 0, 1, 2]))) y = dd.from_pandas(y, npartitions=2) # TODO(ipolosukhin): Remove or restore this. # x = extract_dask_data(x) # y = extract_dask_labels(y) df = data_feeder.DaskDataFeeder(x, y, n_classes=2, batch_size=2) inp, out = df.input_builder() feed_dict_fn = df.get_feed_dict_fn() feed_dict = feed_dict_fn() self.assertAllClose(feed_dict[inp.name], [[0.40000001, 0.1], [0.60000002, 0.2]]) self.assertAllClose(feed_dict[out.name], [[0., 0., 1.], [0., 1., 0.]]) def test_hdf5_data_feeder(self): def func(df): inp, out = df.input_builder() feed_dict_fn = df.get_feed_dict_fn() feed_dict = feed_dict_fn() self._assertAllClose(inp, [[3, 4], [1, 2]], feed_dict, 'name') self.assertAllClose(out, [2, 1], feed_dict, 'name') try: import h5py # pylint: disable=g-import-not-at-top x = np.matrix([[1, 2], [3, 4]]) y = np.array([1, 2]) h5f = h5py.File('test_hdf5.h5', 'w') h5f.create_dataset('x', data=x) h5f.create_dataset('y', data=y) h5f.close() h5f = h5py.File('test_hdf5.h5', 'r') x = h5f['x'] y = h5f['y'] func(data_feeder.DataFeeder(x, y, n_classes=0, batch_size=3)) func( data_feeder.DataFeeder( self._wrap_dict(x, 'in'), self._wrap_dict(y, 'out'), n_classes=self._wrap_dict(0, 'out'), batch_size=3)) except ImportError: print("Skipped test for hdf5 since it's not installed.") class SetupPredictDataFeederTest(DataFeederTest): """Tests for `DataFeeder.setup_predict_data_feeder`.""" def test_iterable_data(self): # pylint: disable=undefined-variable def func(df): self._assertAllClose(six.next(df), [[1, 2], [3, 4]]) self._assertAllClose(six.next(df), [[5, 6]]) data = [[1, 2], [3, 4], [5, 6]] x = iter(data) x_dict = iter([self._wrap_dict(v) for v in iter(data)]) func(data_feeder.setup_predict_data_feeder(x, batch_size=2)) func(data_feeder.setup_predict_data_feeder(x_dict, batch_size=2)) if __name__ == '__main__': test.main()
apache-2.0
FFMG/myoddweb.piger
myodd/boost/tools/build/test/builtin_exit.py
51
1029
#!/usr/bin/python # Copyright 2012 Steven Watanabe # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # This tests the EXIT rule. import BoostBuild def test_exit(name): t = BoostBuild.Tester(["-ffile.jam"], pass_toolset=0) t.write("file.jam", "%s ;" % name) t.run_build_system(status=1, stdout="\n") t.rm(".") t.write("file.jam", "%s : 0 ;" % name) t.run_build_system(stdout="\n") t.rm(".") t.write("file.jam", "%s : 1 ;" % name) t.run_build_system(status=1, stdout="\n") t.rm(".") t.write("file.jam", "%s : 2 ;" % name) t.run_build_system(status=2, stdout="\n") t.rm(".") t.write("file.jam", "%s a message ;" % name) t.run_build_system(status=1, stdout="a message\n") t.rm(".") t.write("file.jam", "%s a message : 0 ;" % name) t.run_build_system(stdout="a message\n") t.rm(".") t.cleanup() test_exit("EXIT") test_exit("Exit") test_exit("exit")
gpl-2.0
slevenhagen/odoo
addons/account/wizard/account_move_line_select.py
385
2800
# -*- 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 osv class account_move_line_select(osv.osv_memory): """ Account move line select """ _name = "account.move.line.select" _description = "Account move line select" def open_window(self, cr, uid, ids, context=None): mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') account_obj = self.pool.get('account.account') fiscalyear_obj = self.pool.get('account.fiscalyear') if context is None: context = {} if 'fiscalyear' not in context: fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) else: fiscalyear_ids = [context['fiscalyear']] fiscalyears = fiscalyear_obj.browse(cr, uid, fiscalyear_ids, context=context) period_ids = [] if fiscalyears: for fiscalyear in fiscalyears: for period in fiscalyear.period_ids: period_ids.append(period.id) domain = str(('period_id', 'in', period_ids)) result = mod_obj.get_object_reference(cr, uid, 'account', 'action_move_line_tree1') id = result and result[1] or False result = act_obj.read(cr, uid, [id])[0] result['context'] = { 'fiscalyear': False, 'account_id': context['active_id'], 'active_id': context['active_id'], } if context['active_id']: acc_data = account_obj.browse(cr, uid, context['active_id']).child_consol_ids if acc_data: result['context'].update({'consolidate_children': True}) result['domain']=result['domain'][0:-1]+','+domain+result['domain'][-1] return result # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
thekindlyone/msg2eml
msg2eml.py
1
6009
# -*- coding: utf-8 -*- import os import sys import glob import traceback from email.parser import Parser as EmailParser import email.utils import OleFileIO_PL as OleFile import email import random import string import mimetypes from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import codecs import kitchen from kitchen.text.converters import to_unicode, to_bytes import email.mime, email.mime.nonmultipart, email.charset sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) def windowsUnicode(string): if string is None: return None if sys.version_info[0] >= 3: # Python 3 return str(string, 'utf_16_le') else: # Python 2 return unicode(string, 'utf_16_le') class Attachment: def __init__(self, msg, dir_): # Get long filename self.longFilename = msg._getStringStream([dir_, '__substg1.0_3707']) # Get short filename self.shortFilename = msg._getStringStream([dir_, '__substg1.0_3704']) # Get attachment data self.data = msg._getStream([dir_, '__substg1.0_37010102']) class Message(OleFile.OleFileIO): def __init__(self, filename): OleFile.OleFileIO.__init__(self, filename) @property def header(self): try: return self._header except Exception: headerText = self._getStringStream('__substg1.0_007D') if headerText is not None: self._header = EmailParser().parsestr(headerText) else: self._header = None return self._header def _getStream(self, filename): if self.exists(filename): stream = self.openstream(filename) return stream.read() else: return None def _getStringStream(self, filename, prefer='unicode'): """Gets a string representation of the requested filename. Checks for both ASCII and Unicode representations and returns a value if possible. If there are both ASCII and Unicode versions, then the parameter /prefer/ specifies which will be returned. """ if isinstance(filename, list): # Join with slashes to make it easier to append the type filename = "/".join(filename) asciiVersion = self._getStream(filename + '001E') unicodeVersion = windowsUnicode(self._getStream(filename + '001F')) #unicodeVersion =self._getStream(filename + '001F') if asciiVersion is None: return unicodeVersion elif unicodeVersion is None: return asciiVersion else: if prefer == 'unicode': return unicodeVersion else: return asciiVersion @property def body(self): # Get the message body return self._getStringStream('__substg1.0_1000') @property def attachments(self): try: return self._attachments except Exception: # Get the attachments attachmentDirs = [] for dir_ in self.listdir(): if dir_[0].startswith('__attach') and dir_[0] not in attachmentDirs: attachmentDirs.append(dir_[0]) self._attachments = [] for attachmentDir in attachmentDirs: self._attachments.append(Attachment(self, attachmentDir)) return self._attachments def create_attachment(filename,data): ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(data, _subtype=subtype) #msg.set_payload(data) elif maintype == 'image': msg = MIMEImage(data, _subtype=subtype) #msg.set_payload(data) elif maintype == 'audio': msg = MIMEAudio(data, _subtype=subtype) #msg.set_payload(data) else: msg = MIMEBase(maintype, subtype) msg.set_payload(data) #fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg fn=sys.argv[1] msg=Message(fn) emlmsg = MIMEMultipart() for key in msg.header.keys(): emlmsg[key]=msg.header[key] #print(type(msg.body)) #print(kitchen.text.misc.guess_encoding(to_bytes(msg.body))) payload=(to_bytes(msg.body)).decode('utf-8') # f=open('temp.txt','w') # f.write(payload) # f.close() # text=open('temp.txt').read() #print(text) m=email.mime.nonmultipart.MIMENonMultipart('text', 'plain', charset='utf-8') cs=email.charset.Charset('utf-8') #cs.body_encoding = email.charset.QP #charset.add_charset('utf-8', charset.SHORTEST, charset.QP) m.set_payload(payload, charset=cs) print(m) # body=MIMEText(text,'plain', _charset='utf-8') # #body.replace_header('Content-Transfer-Encoding', '') # print(body) emlmsg.attach(m) for attachment in msg.attachments: filename=attachment.longFilename or attachment.shortFilename or 'noname'+''.join(random.sample(string.digits,5)) attach=create_attachment(filename,attachment.data) emlmsg.attach(attach) of=os.path.splitext(fn)[0]+'.eml' f=open(of,'w') emlstring=emlmsg.as_string() f.write(emlstring) #if __name__ == '__main__': # main()
gpl-2.0
mistercrunch/panoramix
superset/databases/commands/validate.py
1
5684
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json from contextlib import closing from typing import Any, Dict, Optional from flask_appbuilder.security.sqla.models import User from flask_babel import gettext as __ from sqlalchemy.engine.url import make_url from superset.commands.base import BaseCommand from superset.databases.commands.exceptions import ( DatabaseOfflineError, DatabaseTestConnectionFailedError, InvalidEngineError, InvalidParametersError, ) from superset.databases.dao import DatabaseDAO from superset.db_engine_specs import get_engine_specs from superset.db_engine_specs.base import BasicParametersMixin from superset.errors import ErrorLevel, SupersetError, SupersetErrorType from superset.models.core import Database class ValidateDatabaseParametersCommand(BaseCommand): def __init__(self, user: User, parameters: Dict[str, Any]): self._actor = user self._properties = parameters.copy() self._model: Optional[Database] = None def run(self) -> None: engine = self._properties["engine"] engine_specs = get_engine_specs() if engine not in engine_specs: raise InvalidEngineError( SupersetError( message=__( 'Engine "%(engine)s" is not a valid engine.', engine=engine, ), error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR, level=ErrorLevel.ERROR, extra={"allowed": list(engine_specs), "provided": engine}, ), ) engine_spec = engine_specs[engine] if not issubclass(engine_spec, BasicParametersMixin): raise InvalidEngineError( SupersetError( message=__( 'Engine "%(engine)s" cannot be configured through parameters.', engine=engine, ), error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR, level=ErrorLevel.ERROR, extra={ "allowed": [ name for name, engine_spec in engine_specs.items() if issubclass(engine_spec, BasicParametersMixin) ], "provided": engine, }, ), ) # perform initial validation errors = engine_spec.validate_parameters( self._properties.get("parameters", None) ) if errors: raise InvalidParametersError(errors) serialized_encrypted_extra = self._properties.get("encrypted_extra", "{}") try: encrypted_extra = json.loads(serialized_encrypted_extra) except json.decoder.JSONDecodeError: encrypted_extra = {} # try to connect sqlalchemy_uri = engine_spec.build_sqlalchemy_uri( self._properties.get("parameters", None), # type: ignore encrypted_extra, ) if self._model and sqlalchemy_uri == self._model.safe_sqlalchemy_uri(): sqlalchemy_uri = self._model.sqlalchemy_uri_decrypted database = DatabaseDAO.build_db_for_connection_test( server_cert=self._properties.get("server_cert", ""), extra=self._properties.get("extra", "{}"), impersonate_user=self._properties.get("impersonate_user", False), encrypted_extra=serialized_encrypted_extra, ) database.set_sqlalchemy_uri(sqlalchemy_uri) database.db_engine_spec.mutate_db_for_connection_test(database) username = self._actor.username if self._actor is not None else None engine = database.get_sqla_engine(user_name=username) try: with closing(engine.raw_connection()) as conn: alive = engine.dialect.do_ping(conn) except Exception as ex: # pylint: disable=broad-except url = make_url(sqlalchemy_uri) context = { "hostname": url.host, "password": url.password, "port": url.port, "username": url.username, "database": url.database, } errors = database.db_engine_spec.extract_errors(ex, context) raise DatabaseTestConnectionFailedError(errors) if not alive: raise DatabaseOfflineError( SupersetError( message=__("Database is offline."), error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR, level=ErrorLevel.ERROR, ), ) def validate(self) -> None: database_name = self._properties.get("database_name") if database_name is not None: self._model = DatabaseDAO.get_database_by_name(database_name)
apache-2.0
gkc1000/pyscf
pyscf/fci/test/test_rdm.py
2
10777
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 functools import reduce import unittest import numpy from pyscf import gto from pyscf import scf from pyscf import ao2mo from pyscf import fci norb = 6 nelec = 6 na = fci.cistring.num_strings(norb, nelec//2) numpy.random.seed(1) ci0 = numpy.random.random((na,na)) ci0 = ci0 + ci0.T rdm1, rdm2 = fci.direct_spin1.make_rdm12(ci0, norb, nelec) def tearDownModule(): global ci0, rdm1, rdm2 del ci0, rdm1, rdm2 class KnownValues(unittest.TestCase): def test_rdm3(self): dm3ref = make_dm3_o0(ci0, norb, nelec) dm1, dm2, dm3 = fci.rdm.make_dm123('FCI3pdm_kern_spin0', ci0, ci0, norb, nelec) self.assertTrue(numpy.allclose(dm3ref, dm3)) dm3a = reorder_dm123_o0(dm1, dm2, dm3, False)[2] dm3b = fci.rdm.reorder_dm123(dm1, dm2, dm3, False)[2] self.assertTrue(numpy.allclose(dm3a, dm3b)) dm3 = dm3b fac = 1. / (nelec-2) self.assertTrue(numpy.allclose(rdm2, numpy.einsum('ijklmm->ijkl',dm3)*fac)) self.assertTrue(numpy.allclose(rdm2, numpy.einsum('ijmmkl->ijkl',dm3)*fac)) self.assertTrue(numpy.allclose(rdm2, numpy.einsum('mmijkl->ijkl',dm3)*fac)) dm3 = fci.rdm.make_dm123('FCI3pdm_kern_sf', ci0, ci0, norb, nelec)[2] dm2 = fci.direct_spin1.make_rdm12(ci0, norb, nelec, reorder=False)[1] self.assertTrue(numpy.allclose(dm2, numpy.einsum('mmijkl->ijkl',dm3)/nelec)) numpy.random.seed(2) na = fci.cistring.num_strings(norb, 5) nb = fci.cistring.num_strings(norb, 3) ci1 = numpy.random.random((na,nb)) dm3ref = make_dm3_o0(ci1, norb, (5,3)) dm3 = fci.rdm.make_dm123('FCI3pdm_kern_sf', ci1, ci1, norb, (5,3))[2] self.assertTrue(numpy.allclose(dm3ref, dm3)) def test_dm4(self): dm4ref = make_dm4_o0(ci0, norb, nelec) dm4 = fci.rdm.make_dm1234('FCI4pdm_kern_sf', ci0, ci0, norb, nelec)[3] self.assertTrue(numpy.allclose(dm4ref, dm4)) numpy.random.seed(2) na = fci.cistring.num_strings(norb, 5) nb = fci.cistring.num_strings(norb, 3) ci1 = numpy.random.random((na,nb)) dm4ref = make_dm4_o0(ci1, norb, (5,3)) dm1, dm2, dm3, dm4 = fci.rdm.make_dm1234('FCI4pdm_kern_sf', ci1, ci1, norb, (5,3)) self.assertTrue(numpy.allclose(dm4ref, dm4)) self.assertTrue(numpy.allclose(dm3, numpy.einsum('ppmnijkl->mnijkl',dm4)/8)) self.assertTrue(numpy.allclose(dm3, numpy.einsum('mnppijkl->mnijkl',dm4)/8)) self.assertTrue(numpy.allclose(dm3, numpy.einsum('mnijppkl->mnijkl',dm4)/8)) self.assertTrue(numpy.allclose(dm3, numpy.einsum('mnijklpp->mnijkl',dm4)/8)) dm3a, dm4a = reorder_dm1234_o0(dm1, dm2, dm3, dm4, False)[2:] dm4b = fci.rdm.reorder_dm1234(dm1, dm2, dm3, dm4, False)[3] self.assertTrue(numpy.allclose(dm4a, dm4b)) self.assertTrue(numpy.allclose(dm3a, numpy.einsum('ppmnijkl->mnijkl',dm4b)/5)) self.assertTrue(numpy.allclose(dm3a, numpy.einsum('mnppijkl->mnijkl',dm4b)/5)) self.assertTrue(numpy.allclose(dm3a, numpy.einsum('mnijppkl->mnijkl',dm4b)/5)) self.assertTrue(numpy.allclose(dm3a, numpy.einsum('mnijklpp->mnijkl',dm4b)/5)) def test_tdm2(self): dm1 = numpy.einsum('ij,ijkl->lk', ci0, _trans1(ci0, norb, nelec)) self.assertTrue(numpy.allclose(rdm1, dm1)) dm2 = numpy.einsum('ij,ijklmn->klmn', ci0, _trans2(ci0, norb, nelec)) dm2 = fci.rdm.reorder_rdm(rdm1, dm2)[1] self.assertTrue(numpy.allclose(rdm2,dm2)) na = ci0.shape[0] numpy.random.seed(1) ci = numpy.random.random((na,na)) ci1 = numpy.random.random((na,na)) dm1, dm2 = fci.direct_spin1.trans_rdm12(ci, ci1, norb, nelec) numpy.random.seed(2) self.assertAlmostEqual(numpy.dot(dm2.flatten(),numpy.random.random(dm2.size)), 3790.8867819690477, 7) self.assertTrue(numpy.allclose(dm2, dm2.transpose(2,3,0,1))) t1 = _trans1(ci1, norb, nelec) t2 = _trans2(ci1, norb, nelec) dm1a = numpy.einsum('ij,ijpq->qp', ci, t1) dm2a = numpy.einsum('ij,ijpqrs->pqrs', ci, t2) self.assertTrue(numpy.allclose(dm1a, dm1)) dm1a, dm2a = fci.rdm.reorder_rdm(dm1a, dm2a) self.assertTrue(numpy.allclose(dm2a,dm2a.transpose(2,3,0,1))) def test_full_alpha(self): nelec = (6,3) norb = 6 npair = norb*(norb+1)//2 numpy.random.seed(12) h1 = numpy.random.random((norb,norb)) h1 = h1 + h1.T h2 = numpy.random.random((npair,npair)) * .1 h2 = h2 + h2.T cis = fci.direct_spin1.FCI() e, c = cis.kernel(h1, h2, norb, nelec, verbose=5) dm1s, dm2s = cis.make_rdm12s(c, norb, nelec) self.assertAlmostEqual(abs(dm1s[0]).sum(), 6, 9) self.assertAlmostEqual(dm1s[1].trace(), 3, 9) self.assertAlmostEqual(abs(dm2s[0]).sum(), 60, 9) self.assertAlmostEqual(abs(numpy.einsum('iijk->jk', dm2s[1])/6-dm1s[1]).sum(), 0, 9) self.assertAlmostEqual(abs(numpy.einsum('iijk->jk', dm2s[2])/2-dm1s[1]).sum(), 0, 9) def test_0beta(self): nelec = (3,0) norb = 6 npair = norb*(norb+1)//2 numpy.random.seed(12) h1 = numpy.random.random((norb,norb)) h1 = h1 + h1.T h2 = numpy.random.random((npair,npair)) * .1 h2 = h2 + h2.T cis = fci.direct_spin1.FCI() e, c = cis.kernel(h1, h2, norb, nelec, verbose=5) dm1s, dm2s = cis.make_rdm12s(c, norb, nelec) self.assertAlmostEqual(dm1s[0].trace(), 3, 9) self.assertAlmostEqual(abs(dm1s[1]).sum(), 0, 9) self.assertAlmostEqual(abs(numpy.einsum('iijk->jk', dm2s[0])/2-dm1s[0]).sum(), 0, 9) self.assertAlmostEqual(abs(dm2s[1]).sum(), 0, 9) self.assertAlmostEqual(abs(dm2s[2]).sum(), 0, 9) # (6o,6e) ~ 4MB # (8o,8e) ~ 153MB # (10o,10e) ~ 4.8GB # t2(*,ij,kl) = E_i^j E_k^l|0> def _trans2(fcivec, norb, nelec): if isinstance(nelec, (int, numpy.integer)): neleca = nelecb = nelec//2 else: neleca, nelecb = nelec link_indexa = fci.cistring.gen_linkstr_index(range(norb), neleca) link_indexb = fci.cistring.gen_linkstr_index(range(norb), nelecb) na, nlinka = link_indexa.shape[:2] nb, nlinkb = link_indexb.shape[:2] fcivec = fcivec.reshape(na,nb) t1 = _trans1(fcivec, norb, nelec) t2 = numpy.zeros((na,nb,norb,norb,norb,norb)) for str0, tab in enumerate(link_indexa): for a, i, str1, sign in tab: t2[str1,:,a,i] += sign * t1[str0] for k in range(na): for str0, tab in enumerate(link_indexb): for a, i, str1, sign in tab: t2[k,str1,a,i] += sign * t1[k,str0] return t2 def _trans1(fcivec, norb, nelec): if isinstance(nelec, (int, numpy.integer)): neleca = nelecb = nelec//2 else: neleca, nelecb = nelec link_indexa = fci.cistring.gen_linkstr_index(range(norb), neleca) link_indexb = fci.cistring.gen_linkstr_index(range(norb), nelecb) na, nlinka = link_indexa.shape[:2] nb, nlinkb = link_indexb.shape[:2] fcivec = fcivec.reshape(na,nb) t1 = numpy.zeros((na,nb,norb,norb)) for str0, tab in enumerate(link_indexa): for a, i, str1, sign in tab: t1[str1,:,a,i] += sign * fcivec[str0] for k in range(na): for str0, tab in enumerate(link_indexb): for a, i, str1, sign in tab: t1[k,str1,a,i] += sign * fcivec[k,str0] return t1 # # NOTE: this rdm3 is defined as # rdm3(p,q,r,s,t,u) = <p^+ q r^+ s t^+ u> def make_dm3_o0(fcivec, norb, nelec): # <0|p^+ q r^+ s|i> <i|t^+ u|0> t1 = _trans1(fcivec, norb, nelec) t2 = _trans2(fcivec, norb, nelec) na, nb = t1.shape[:2] rdm3 = numpy.dot(t1.reshape(na*nb,-1).T, t2.reshape(na*nb,-1)) return rdm3.reshape((norb,)*6).transpose(1,0,2,3,4,5) def make_dm4_o0(fcivec, norb, nelec): # <0|p^+ q r^+ s|i> <i|t^+ u|0> t2 = _trans2(fcivec, norb, nelec) na, nb = t2.shape[:2] rdm4 = numpy.dot(t2.reshape(na*nb,-1).T, t2.reshape(na*nb,-1)) return rdm4.reshape((norb,)*8).transpose(3,2,1,0,4,5,6,7) # <p^+ q r^+ s t^+ u> => <p^+ r^+ t^+ u s q> # rdm2 is <p^+ q r^+ s> def reorder_dm123_o0(rdm1, rdm2, rdm3, inplace=True): rdm1, rdm2 = fci.rdm.reorder_rdm(rdm1, rdm2, inplace) if not inplace: rdm3 = rdm3.copy() norb = rdm1.shape[0] for p in range(norb): for q in range(norb): for s in range(norb): rdm3[p,q,q,s] += -rdm2[p,s] for u in range(norb): rdm3[p,q,:,:,q,u] += -rdm2[p,u] for s in range(norb): rdm3[p,q,:,s,s,:] += -rdm2[p,q] for q in range(norb): for s in range(norb): rdm3[:,q,q,s,s,:] += -rdm1 return rdm1, rdm2, rdm3 # <p^+ q r^+ s t^+ u w^+ v> => <p^+ r^+ t^+ w^+ v u s q> # rdm2, rdm3 are the (reordered) standard 2-pdm and 3-pdm def reorder_dm1234_o0(rdm1, rdm2, rdm3, rdm4, inplace=True): rdm1, rdm2, rdm3 = fci.rdm.reorder_dm123(rdm1, rdm2, rdm3, inplace) if not inplace: rdm4 = rdm4.copy() norb = rdm1.shape[0] delta = numpy.eye(norb) rdm4 -= numpy.einsum('qv,pwrstu->pqrstuvw', delta, rdm3) rdm4 -= numpy.einsum('sv,pqrwtu->pqrstuvw', delta, rdm3) rdm4 -= numpy.einsum('uv,pqrstw->pqrstuvw', delta, rdm3) rdm4 -= numpy.einsum('qt,pursvw->pqrstuvw', delta, rdm3) rdm4 -= numpy.einsum('st,pqruvw->pqrstuvw', delta, rdm3) rdm4 -= numpy.einsum('qr,pstuvw->pqrstuvw', delta, rdm3) rdm4 -= numpy.einsum('qr,sv,pwtu', delta, delta, rdm2) rdm4 -= numpy.einsum('qr,uv,pstw', delta, delta, rdm2) rdm4 -= numpy.einsum('qt,uv,pwrs', delta, delta, rdm2) rdm4 -= numpy.einsum('qt,sv,purw', delta, delta, rdm2) rdm4 -= numpy.einsum('st,qv,pwru', delta, delta, rdm2) rdm4 -= numpy.einsum('st,uv,pqrw', delta, delta, rdm2) rdm4 -= numpy.einsum('qr,st,puvw', delta, delta, rdm2) rdm4 -= numpy.einsum('qr,st,uv,pw->pqrstuvw', delta, delta, delta, rdm1) return rdm1, rdm2, rdm3, rdm4 if __name__ == "__main__": print("Full Tests for fci.rdm") unittest.main()
apache-2.0
modoboa/modoboa
modoboa/admin/tests/test_mailbox_operations.py
1
3310
"""Management command tests.""" import os import shutil import tempfile from unittest import mock from django.core.management import call_command from django.test import override_settings from django.urls import reverse from modoboa.lib.tests import ModoTestCase from .. import factories, models @override_settings( DOVECOT_LOOKUP_PATH=["{}/dovecot".format(os.path.dirname(__file__))]) class MailboxOperationTestCase(ModoTestCase): """Test management command.""" @classmethod def setUpTestData(cls): # NOQA:N802 """Create test data.""" super(MailboxOperationTestCase, cls).setUpTestData() factories.populate_database() def setUp(self): """Initiate test env.""" super(MailboxOperationTestCase, self).setUp() self.workdir = tempfile.mkdtemp() path = "{}/test.com/admin".format(self.workdir) os.makedirs(path) self.set_global_parameter("handle_mailboxes", True) self.set_global_parameter("enable_admin_limits", False, app="limits") def tearDown(self): """Reset test env.""" shutil.rmtree(self.workdir) @mock.patch("modoboa.admin.models.Mailbox.mail_home") def test_delete_account(self, mail_home_mock): """Check delete operation.""" path = "{}/test.com/admin".format(self.workdir) mail_home_mock.__get__ = mock.Mock(return_value=path) mb = models.Mailbox.objects.select_related("user").get( address="admin", domain__name="test.com") self.ajax_post( reverse("admin:account_delete", args=[mb.user.pk]), {} ) call_command("handle_mailbox_operations") self.assertFalse(models.MailboxOperation.objects.exists()) self.assertFalse(os.path.exists(mb.mail_home)) @mock.patch("modoboa.admin.models.Mailbox.mail_home") def test_rename_account(self, mail_home_mock): """Check rename operation.""" path = "{}/test.com/admin".format(self.workdir) mail_home_mock.__get__ = mock.Mock(return_value=path) mb = models.Mailbox.objects.select_related("user").get( address="admin", domain__name="test.com") values = { "username": "admin2@test.com", "role": "DomainAdmins", "is_active": True, "email": "admin2@test.com", "language": "en" } self.ajax_post( reverse("admin:account_change", args=[mb.user.pk]), values ) path = "{}/test.com/admin2".format(self.workdir) mail_home_mock.__get__ = mock.Mock(return_value=path) call_command("handle_mailbox_operations") self.assertFalse(models.MailboxOperation.objects.exists()) self.assertTrue(os.path.exists(mb.mail_home)) @mock.patch("modoboa.admin.models.Mailbox.mail_home") def test_delete_domain(self, mail_home_mock): """Check delete operation.""" path = "{}/test.com/admin".format(self.workdir) mail_home_mock.__get__ = mock.Mock(return_value=path) domain = models.Domain.objects.get(name="test.com") self.ajax_post(reverse("admin:domain_delete", args=[domain.pk])) call_command("handle_mailbox_operations") self.assertFalse(models.MailboxOperation.objects.exists()) self.assertFalse(os.path.exists(path))
isc
shenhzou654321/protobuf-ios
compiler/python/google/protobuf/internal/generator_test.py
15
4312
#! /usr/bin/python # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # TODO(robinson): Flesh this out considerably. We focused on reflection_test.py # first, since it's testing the subtler code, and since it provides decent # indirect testing of the protocol compiler output. """Unittest that directly tests the output of the pure-Python protocol compiler. See //net/proto2/internal/reflection_test.py for a test which further ensures that we can use Python protocol message objects as we expect. """ __author__ = 'robinson@google.com (Will Robinson)' import unittest from google.protobuf import unittest_mset_pb2 from google.protobuf import unittest_pb2 class GeneratorTest(unittest.TestCase): def testNestedMessageDescriptor(self): field_name = 'optional_nested_message' proto_type = unittest_pb2.TestAllTypes self.assertEqual( proto_type.NestedMessage.DESCRIPTOR, proto_type.DESCRIPTOR.fields_by_name[field_name].message_type) def testEnums(self): # We test only module-level enums here. # TODO(robinson): Examine descriptors directly to check # enum descriptor output. self.assertEqual(4, unittest_pb2.FOREIGN_FOO) self.assertEqual(5, unittest_pb2.FOREIGN_BAR) self.assertEqual(6, unittest_pb2.FOREIGN_BAZ) proto = unittest_pb2.TestAllTypes() self.assertEqual(1, proto.FOO) self.assertEqual(1, unittest_pb2.TestAllTypes.FOO) self.assertEqual(2, proto.BAR) self.assertEqual(2, unittest_pb2.TestAllTypes.BAR) self.assertEqual(3, proto.BAZ) self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ) def testContainingTypeBehaviorForExtensions(self): self.assertEqual(unittest_pb2.optional_int32_extension.containing_type, unittest_pb2.TestAllExtensions.DESCRIPTOR) self.assertEqual(unittest_pb2.TestRequired.single.containing_type, unittest_pb2.TestAllExtensions.DESCRIPTOR) def testExtensionScope(self): self.assertEqual(unittest_pb2.optional_int32_extension.extension_scope, None) self.assertEqual(unittest_pb2.TestRequired.single.extension_scope, unittest_pb2.TestRequired.DESCRIPTOR) def testIsExtension(self): self.assertTrue(unittest_pb2.optional_int32_extension.is_extension) self.assertTrue(unittest_pb2.TestRequired.single.is_extension) message_descriptor = unittest_pb2.TestRequired.DESCRIPTOR non_extension_descriptor = message_descriptor.fields_by_name['a'] self.assertTrue(not non_extension_descriptor.is_extension) def testOptions(self): proto = unittest_mset_pb2.TestMessageSet() self.assertTrue(proto.DESCRIPTOR.GetOptions().message_set_wire_format) if __name__ == '__main__': unittest.main()
mit
ntuecon/server
pyenv/Lib/site-packages/twisted/words/xish/xpath.py
13
9556
# -*- test-case-name: twisted.words.test.test_xpath -*- # # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ XPath query support. This module provides L{XPathQuery} to match L{domish.Element<twisted.words.xish.domish.Element>} instances against XPath-like expressions. """ from __future__ import absolute_import, division from io import StringIO from twisted.python.compat import StringType, unicode class LiteralValue(unicode): def value(self, elem): return self class IndexValue: def __init__(self, index): self.index = int(index) - 1 def value(self, elem): return elem.children[self.index] class AttribValue: def __init__(self, attribname): self.attribname = attribname if self.attribname == "xmlns": self.value = self.value_ns def value_ns(self, elem): return elem.uri def value(self, elem): if self.attribname in elem.attributes: return elem.attributes[self.attribname] else: return None class CompareValue: def __init__(self, lhs, op, rhs): self.lhs = lhs self.rhs = rhs if op == "=": self.value = self._compareEqual else: self.value = self._compareNotEqual def _compareEqual(self, elem): return self.lhs.value(elem) == self.rhs.value(elem) def _compareNotEqual(self, elem): return self.lhs.value(elem) != self.rhs.value(elem) class BooleanValue: """ Provide boolean XPath expression operators. @ivar lhs: Left hand side expression of the operator. @ivar op: The operator. One of C{'and'}, C{'or'}. @ivar rhs: Right hand side expression of the operator. @ivar value: Reference to the method that will calculate the value of this expression given an element. """ def __init__(self, lhs, op, rhs): self.lhs = lhs self.rhs = rhs if op == "and": self.value = self._booleanAnd else: self.value = self._booleanOr def _booleanAnd(self, elem): """ Calculate boolean and of the given expressions given an element. @param elem: The element to calculate the value of the expression from. """ return self.lhs.value(elem) and self.rhs.value(elem) def _booleanOr(self, elem): """ Calculate boolean or of the given expressions given an element. @param elem: The element to calculate the value of the expression from. """ return self.lhs.value(elem) or self.rhs.value(elem) def Function(fname): """ Internal method which selects the function object """ klassname = "_%s_Function" % fname c = globals()[klassname]() return c class _not_Function: def __init__(self): self.baseValue = None def setParams(self, baseValue): self.baseValue = baseValue def value(self, elem): return not self.baseValue.value(elem) class _text_Function: def setParams(self): pass def value(self, elem): return unicode(elem) class _Location: def __init__(self): self.predicates = [] self.elementName = None self.childLocation = None def matchesPredicates(self, elem): if self.elementName != None and self.elementName != elem.name: return 0 for p in self.predicates: if not p.value(elem): return 0 return 1 def matches(self, elem): if not self.matchesPredicates(elem): return 0 if self.childLocation != None: for c in elem.elements(): if self.childLocation.matches(c): return 1 else: return 1 return 0 def queryForString(self, elem, resultbuf): if not self.matchesPredicates(elem): return if self.childLocation != None: for c in elem.elements(): self.childLocation.queryForString(c, resultbuf) else: resultbuf.write(unicode(elem)) def queryForNodes(self, elem, resultlist): if not self.matchesPredicates(elem): return if self.childLocation != None: for c in elem.elements(): self.childLocation.queryForNodes(c, resultlist) else: resultlist.append(elem) def queryForStringList(self, elem, resultlist): if not self.matchesPredicates(elem): return if self.childLocation != None: for c in elem.elements(): self.childLocation.queryForStringList(c, resultlist) else: for c in elem.children: if isinstance(c, StringType): resultlist.append(c) class _AnyLocation: def __init__(self): self.predicates = [] self.elementName = None self.childLocation = None def matchesPredicates(self, elem): for p in self.predicates: if not p.value(elem): return 0 return 1 def listParents(self, elem, parentlist): if elem.parent != None: self.listParents(elem.parent, parentlist) parentlist.append(elem.name) def isRootMatch(self, elem): if (self.elementName == None or self.elementName == elem.name) and \ self.matchesPredicates(elem): if self.childLocation != None: for c in elem.elements(): if self.childLocation.matches(c): return True else: return True return False def findFirstRootMatch(self, elem): if (self.elementName == None or self.elementName == elem.name) and \ self.matchesPredicates(elem): # Thus far, the name matches and the predicates match, # now check into the children and find the first one # that matches the rest of the structure # the rest of the structure if self.childLocation != None: for c in elem.elements(): if self.childLocation.matches(c): return c return None else: # No children locations; this is a match! return elem else: # Ok, predicates or name didn't match, so we need to start # down each child and treat it as the root and try # again for c in elem.elements(): if self.matches(c): return c # No children matched... return None def matches(self, elem): if self.isRootMatch(elem): return True else: # Ok, initial element isn't an exact match, walk # down each child and treat it as the root and try # again for c in elem.elements(): if self.matches(c): return True # No children matched... return False def queryForString(self, elem, resultbuf): raise NotImplementedError( "queryForString is not implemented for any location") def queryForNodes(self, elem, resultlist): # First check to see if _this_ element is a root if self.isRootMatch(elem): resultlist.append(elem) # Now check each child for c in elem.elements(): self.queryForNodes(c, resultlist) def queryForStringList(self, elem, resultlist): if self.isRootMatch(elem): for c in elem.children: if isinstance(c, StringType): resultlist.append(c) for c in elem.elements(): self.queryForStringList(c, resultlist) class XPathQuery: def __init__(self, queryStr): self.queryStr = queryStr # Prevent a circular import issue, as xpathparser imports this module. from twisted.words.xish.xpathparser import (XPathParser, XPathParserScanner) parser = XPathParser(XPathParserScanner(queryStr)) self.baseLocation = getattr(parser, 'XPATH')() def __hash__(self): return self.queryStr.__hash__() def matches(self, elem): return self.baseLocation.matches(elem) def queryForString(self, elem): result = StringIO() self.baseLocation.queryForString(elem, result) return result.getvalue() def queryForNodes(self, elem): result = [] self.baseLocation.queryForNodes(elem, result) if len(result) == 0: return None else: return result def queryForStringList(self, elem): result = [] self.baseLocation.queryForStringList(elem, result) if len(result) == 0: return None else: return result __internedQueries = {} def internQuery(queryString): if queryString not in __internedQueries: __internedQueries[queryString] = XPathQuery(queryString) return __internedQueries[queryString] def matches(xpathstr, elem): return internQuery(xpathstr).matches(elem) def queryForStringList(xpathstr, elem): return internQuery(xpathstr).queryForStringList(elem) def queryForString(xpathstr, elem): return internQuery(xpathstr).queryForString(elem) def queryForNodes(xpathstr, elem): return internQuery(xpathstr).queryForNodes(elem)
bsd-3-clause
matrixise/odoo
addons/account_anglo_saxon/product.py
384
3035
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class product_category(osv.osv): _inherit = "product.category" _columns = { 'property_account_creditor_price_difference_categ': fields.property( type='many2one', relation='account.account', string="Price Difference Account", help="This account will be used to value price difference between purchase price and cost price."), #Redefine fields to change help text for anglo saxon methodology. 'property_account_income_categ': fields.property( type='many2one', relation='account.account', string="Income Account", help="This account will be used to value outgoing stock using sale price."), 'property_account_expense_categ': fields.property( type='many2one', relation='account.account', string="Expense Account", help="This account will be used to value outgoing stock using cost price."), } class product_template(osv.osv): _inherit = "product.template" _columns = { 'property_account_creditor_price_difference': fields.property( type='many2one', relation='account.account', string="Price Difference Account", help="This account will be used to value price difference between purchase price and cost price."), #Redefine fields to change help text for anglo saxon methodology. 'property_account_income': fields.property( type='many2one', relation='account.account', string="Income Account", help="This account will be used to value outgoing stock using sale price."), 'property_account_expense': fields.property( type='many2one', relation='account.account', string="Expense Account", help="This account will be used to value outgoing stock using cost price."), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
gitgitcode/myflask
venv/lib/python2.7/site-packages/pip/req/req_set.py
338
34462
from __future__ import absolute_import from collections import defaultdict from itertools import chain import logging import os from pip._vendor import pkg_resources from pip._vendor import requests from pip.compat import expanduser from pip.download import (is_file_url, is_dir_url, is_vcs_url, url_to_path, unpack_url) from pip.exceptions import (InstallationError, BestVersionAlreadyInstalled, DistributionNotFound, PreviousBuildDirError, HashError, HashErrors, HashUnpinned, DirectoryUrlHashUnsupported, VcsHashUnsupported, UnsupportedPythonVersion) from pip.req.req_install import InstallRequirement from pip.utils import ( display_path, dist_in_usersite, ensure_dir, normalize_path) from pip.utils.hashes import MissingHashes from pip.utils.logging import indent_log from pip.utils.packaging import check_dist_requires_python from pip.vcs import vcs from pip.wheel import Wheel logger = logging.getLogger(__name__) class Requirements(object): def __init__(self): self._keys = [] self._dict = {} def keys(self): return self._keys def values(self): return [self._dict[key] for key in self._keys] def __contains__(self, item): return item in self._keys def __setitem__(self, key, value): if key not in self._keys: self._keys.append(key) self._dict[key] = value def __getitem__(self, key): return self._dict[key] def __repr__(self): values = ['%s: %s' % (repr(k), repr(self[k])) for k in self.keys()] return 'Requirements({%s})' % ', '.join(values) class DistAbstraction(object): """Abstracts out the wheel vs non-wheel prepare_files logic. The requirements for anything installable are as follows: - we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case). - we must be able to generate a list of run-time dependencies without installing any additional packages (or we would have to either burn time by doing temporary isolated installs or alternatively violate pips 'don't start installing unless all requirements are available' rule - neither of which are desirable). - for packages with setup requirements, we must also be able to determine their requirements without installing additional packages (for the same reason as run-time dependencies) - we must be able to create a Distribution object exposing the above metadata. """ def __init__(self, req_to_install): self.req_to_install = req_to_install def dist(self, finder): """Return a setuptools Dist object.""" raise NotImplementedError(self.dist) def prep_for_dist(self): """Ensure that we can get a Dist for this requirement.""" raise NotImplementedError(self.dist) def make_abstract_dist(req_to_install): """Factory to make an abstract dist object. Preconditions: Either an editable req with a source_dir, or satisfied_by or a wheel link, or a non-editable req with a source_dir. :return: A concrete DistAbstraction. """ if req_to_install.editable: return IsSDist(req_to_install) elif req_to_install.link and req_to_install.link.is_wheel: return IsWheel(req_to_install) else: return IsSDist(req_to_install) class IsWheel(DistAbstraction): def dist(self, finder): return list(pkg_resources.find_distributions( self.req_to_install.source_dir))[0] def prep_for_dist(self): # FIXME:https://github.com/pypa/pip/issues/1112 pass class IsSDist(DistAbstraction): def dist(self, finder): dist = self.req_to_install.get_dist() # FIXME: shouldn't be globally added: if dist.has_metadata('dependency_links.txt'): finder.add_dependency_links( dist.get_metadata_lines('dependency_links.txt') ) return dist def prep_for_dist(self): self.req_to_install.run_egg_info() self.req_to_install.assert_source_matches_version() class Installed(DistAbstraction): def dist(self, finder): return self.req_to_install.satisfied_by def prep_for_dist(self): pass class RequirementSet(object): def __init__(self, build_dir, src_dir, download_dir, upgrade=False, upgrade_strategy=None, ignore_installed=False, as_egg=False, target_dir=None, ignore_dependencies=False, force_reinstall=False, use_user_site=False, session=None, pycompile=True, isolated=False, wheel_download_dir=None, wheel_cache=None, require_hashes=False, ignore_requires_python=False): """Create a RequirementSet. :param wheel_download_dir: Where still-packed .whl files should be written to. If None they are written to the download_dir parameter. Separate to download_dir to permit only keeping wheel archives for pip wheel. :param download_dir: Where still packed archives should be written to. If None they are not saved, and are deleted immediately after unpacking. :param wheel_cache: The pip wheel cache, for passing to InstallRequirement. """ if session is None: raise TypeError( "RequirementSet() missing 1 required keyword argument: " "'session'" ) self.build_dir = build_dir self.src_dir = src_dir # XXX: download_dir and wheel_download_dir overlap semantically and may # be combined if we're willing to have non-wheel archives present in # the wheelhouse output by 'pip wheel'. self.download_dir = download_dir self.upgrade = upgrade self.upgrade_strategy = upgrade_strategy self.ignore_installed = ignore_installed self.force_reinstall = force_reinstall self.requirements = Requirements() # Mapping of alias: real_name self.requirement_aliases = {} self.unnamed_requirements = [] self.ignore_dependencies = ignore_dependencies self.ignore_requires_python = ignore_requires_python self.successfully_downloaded = [] self.successfully_installed = [] self.reqs_to_cleanup = [] self.as_egg = as_egg self.use_user_site = use_user_site self.target_dir = target_dir # set from --target option self.session = session self.pycompile = pycompile self.isolated = isolated if wheel_download_dir: wheel_download_dir = normalize_path(wheel_download_dir) self.wheel_download_dir = wheel_download_dir self._wheel_cache = wheel_cache self.require_hashes = require_hashes # Maps from install_req -> dependencies_of_install_req self._dependencies = defaultdict(list) def __str__(self): reqs = [req for req in self.requirements.values() if not req.comes_from] reqs.sort(key=lambda req: req.name.lower()) return ' '.join([str(req.req) for req in reqs]) def __repr__(self): reqs = [req for req in self.requirements.values()] reqs.sort(key=lambda req: req.name.lower()) reqs_str = ', '.join([str(req.req) for req in reqs]) return ('<%s object; %d requirement(s): %s>' % (self.__class__.__name__, len(reqs), reqs_str)) def add_requirement(self, install_req, parent_req_name=None, extras_requested=None): """Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we could otherwise end up with dependency links that point outside the Requirements set. parent_req must already be added. Note that None implies that this is a user supplied requirement, vs an inferred one. :param extras_requested: an iterable of extras used to evaluate the environement markers. :return: Additional requirements to scan. That is either [] if the requirement is not applicable, or [install_req] if the requirement is applicable and has just been added. """ name = install_req.name if not install_req.match_markers(extras_requested): logger.warning("Ignoring %s: markers '%s' don't match your " "environment", install_req.name, install_req.markers) return [] # This check has to come after we filter requirements with the # environment markers. if install_req.link and install_req.link.is_wheel: wheel = Wheel(install_req.link.filename) if not wheel.supported(): raise InstallationError( "%s is not a supported wheel on this platform." % wheel.filename ) install_req.as_egg = self.as_egg install_req.use_user_site = self.use_user_site install_req.target_dir = self.target_dir install_req.pycompile = self.pycompile install_req.is_direct = (parent_req_name is None) if not name: # url or path requirement w/o an egg fragment self.unnamed_requirements.append(install_req) return [install_req] else: try: existing_req = self.get_requirement(name) except KeyError: existing_req = None if (parent_req_name is None and existing_req and not existing_req.constraint and existing_req.extras == install_req.extras and not existing_req.req.specifier == install_req.req.specifier): raise InstallationError( 'Double requirement given: %s (already in %s, name=%r)' % (install_req, existing_req, name)) if not existing_req: # Add requirement self.requirements[name] = install_req # FIXME: what about other normalizations? E.g., _ vs. -? if name.lower() != name: self.requirement_aliases[name.lower()] = name result = [install_req] else: # Assume there's no need to scan, and that we've already # encountered this for scanning. result = [] if not install_req.constraint and existing_req.constraint: if (install_req.link and not (existing_req.link and install_req.link.path == existing_req.link.path)): self.reqs_to_cleanup.append(install_req) raise InstallationError( "Could not satisfy constraints for '%s': " "installation from path or url cannot be " "constrained to a version" % name) # If we're now installing a constraint, mark the existing # object for real installation. existing_req.constraint = False existing_req.extras = tuple( sorted(set(existing_req.extras).union( set(install_req.extras)))) logger.debug("Setting %s extras to: %s", existing_req, existing_req.extras) # And now we need to scan this. result = [existing_req] # Canonicalise to the already-added object for the backref # check below. install_req = existing_req if parent_req_name: parent_req = self.get_requirement(parent_req_name) self._dependencies[parent_req].append(install_req) return result def has_requirement(self, project_name): name = project_name.lower() if (name in self.requirements and not self.requirements[name].constraint or name in self.requirement_aliases and not self.requirements[self.requirement_aliases[name]].constraint): return True return False @property def has_requirements(self): return list(req for req in self.requirements.values() if not req.constraint) or self.unnamed_requirements @property def is_download(self): if self.download_dir: self.download_dir = expanduser(self.download_dir) if os.path.exists(self.download_dir): return True else: logger.critical('Could not find download directory') raise InstallationError( "Could not find or access download directory '%s'" % display_path(self.download_dir)) return False def get_requirement(self, project_name): for name in project_name, project_name.lower(): if name in self.requirements: return self.requirements[name] if name in self.requirement_aliases: return self.requirements[self.requirement_aliases[name]] raise KeyError("No project with the name %r" % project_name) def uninstall(self, auto_confirm=False): for req in self.requirements.values(): if req.constraint: continue req.uninstall(auto_confirm=auto_confirm) req.commit_uninstall() def prepare_files(self, finder): """ Prepare process. Create temp directories, download and/or unpack files. """ # make the wheelhouse if self.wheel_download_dir: ensure_dir(self.wheel_download_dir) # If any top-level requirement has a hash specified, enter # hash-checking mode, which requires hashes from all. root_reqs = self.unnamed_requirements + self.requirements.values() require_hashes = (self.require_hashes or any(req.has_hash_options for req in root_reqs)) if require_hashes and self.as_egg: raise InstallationError( '--egg is not allowed with --require-hashes mode, since it ' 'delegates dependency resolution to setuptools and could thus ' 'result in installation of unhashed packages.') # Actually prepare the files, and collect any exceptions. Most hash # exceptions cannot be checked ahead of time, because # req.populate_link() needs to be called before we can make decisions # based on link type. discovered_reqs = [] hash_errors = HashErrors() for req in chain(root_reqs, discovered_reqs): try: discovered_reqs.extend(self._prepare_file( finder, req, require_hashes=require_hashes, ignore_dependencies=self.ignore_dependencies)) except HashError as exc: exc.req = req hash_errors.append(exc) if hash_errors: raise hash_errors def _is_upgrade_allowed(self, req): return self.upgrade and ( self.upgrade_strategy == "eager" or ( self.upgrade_strategy == "only-if-needed" and req.is_direct ) ) def _check_skip_installed(self, req_to_install, finder): """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be upgraded/reinstalled etc. Any other value will be a dist recording the current thing installed that satisfies the requirement. Note that for vcs urls and the like we can't assess skipping in this routine - we simply identify that we need to pull the thing down, then later on it is pulled down and introspected to assess upgrade/ reinstalls etc. :return: A text reason for why it was skipped, or None. """ # Check whether to upgrade/reinstall this req or not. req_to_install.check_if_exists() if req_to_install.satisfied_by: upgrade_allowed = self._is_upgrade_allowed(req_to_install) # Is the best version is installed. best_installed = False if upgrade_allowed: # For link based requirements we have to pull the # tree down and inspect to assess the version #, so # its handled way down. if not (self.force_reinstall or req_to_install.link): try: finder.find_requirement( req_to_install, upgrade_allowed) except BestVersionAlreadyInstalled: best_installed = True except DistributionNotFound: # No distribution found, so we squash the # error - it will be raised later when we # re-try later to do the install. # Why don't we just raise here? pass if not best_installed: # don't uninstall conflict if user install and # conflict is not user install if not (self.use_user_site and not dist_in_usersite(req_to_install.satisfied_by)): req_to_install.conflicts_with = \ req_to_install.satisfied_by req_to_install.satisfied_by = None # Figure out a nice message to say why we're skipping this. if best_installed: skip_reason = 'already up-to-date' elif self.upgrade_strategy == "only-if-needed": skip_reason = 'not upgraded as not directly required' else: skip_reason = 'already satisfied' return skip_reason else: return None def _prepare_file(self, finder, req_to_install, require_hashes=False, ignore_dependencies=False): """Prepare a single requirements file. :return: A list of additional InstallRequirements to also install. """ # Tell user what we are doing for this requirement: # obtain (editable), skipping, processing (local url), collecting # (remote url or package name) if req_to_install.constraint or req_to_install.prepared: return [] req_to_install.prepared = True # ###################### # # # print log messages # # # ###################### # if req_to_install.editable: logger.info('Obtaining %s', req_to_install) else: # satisfied_by is only evaluated by calling _check_skip_installed, # so it must be None here. assert req_to_install.satisfied_by is None if not self.ignore_installed: skip_reason = self._check_skip_installed( req_to_install, finder) if req_to_install.satisfied_by: assert skip_reason is not None, ( '_check_skip_installed returned None but ' 'req_to_install.satisfied_by is set to %r' % (req_to_install.satisfied_by,)) logger.info( 'Requirement %s: %s', skip_reason, req_to_install) else: if (req_to_install.link and req_to_install.link.scheme == 'file'): path = url_to_path(req_to_install.link.url) logger.info('Processing %s', display_path(path)) else: logger.info('Collecting %s', req_to_install) with indent_log(): # ################################ # # # vcs update or unpack archive # # # ################################ # if req_to_install.editable: if require_hashes: raise InstallationError( 'The editable requirement %s cannot be installed when ' 'requiring hashes, because there is no single file to ' 'hash.' % req_to_install) req_to_install.ensure_has_source_dir(self.src_dir) req_to_install.update_editable(not self.is_download) abstract_dist = make_abstract_dist(req_to_install) abstract_dist.prep_for_dist() if self.is_download: req_to_install.archive(self.download_dir) req_to_install.check_if_exists() elif req_to_install.satisfied_by: if require_hashes: logger.debug( 'Since it is already installed, we are trusting this ' 'package without checking its hash. To ensure a ' 'completely repeatable environment, install into an ' 'empty virtualenv.') abstract_dist = Installed(req_to_install) else: # @@ if filesystem packages are not marked # editable in a req, a non deterministic error # occurs when the script attempts to unpack the # build directory req_to_install.ensure_has_source_dir(self.build_dir) # If a checkout exists, it's unwise to keep going. version # inconsistencies are logged later, but do not fail the # installation. # FIXME: this won't upgrade when there's an existing # package unpacked in `req_to_install.source_dir` if os.path.exists( os.path.join(req_to_install.source_dir, 'setup.py')): raise PreviousBuildDirError( "pip can't proceed with requirements '%s' due to a" " pre-existing build directory (%s). This is " "likely due to a previous installation that failed" ". pip is being responsible and not assuming it " "can delete this. Please delete it and try again." % (req_to_install, req_to_install.source_dir) ) req_to_install.populate_link( finder, self._is_upgrade_allowed(req_to_install), require_hashes ) # We can't hit this spot and have populate_link return None. # req_to_install.satisfied_by is None here (because we're # guarded) and upgrade has no impact except when satisfied_by # is not None. # Then inside find_requirement existing_applicable -> False # If no new versions are found, DistributionNotFound is raised, # otherwise a result is guaranteed. assert req_to_install.link link = req_to_install.link # Now that we have the real link, we can tell what kind of # requirements we have and raise some more informative errors # than otherwise. (For example, we can raise VcsHashUnsupported # for a VCS URL rather than HashMissing.) if require_hashes: # We could check these first 2 conditions inside # unpack_url and save repetition of conditions, but then # we would report less-useful error messages for # unhashable requirements, complaining that there's no # hash provided. if is_vcs_url(link): raise VcsHashUnsupported() elif is_file_url(link) and is_dir_url(link): raise DirectoryUrlHashUnsupported() if (not req_to_install.original_link and not req_to_install.is_pinned): # Unpinned packages are asking for trouble when a new # version is uploaded. This isn't a security check, but # it saves users a surprising hash mismatch in the # future. # # file:/// URLs aren't pinnable, so don't complain # about them not being pinned. raise HashUnpinned() hashes = req_to_install.hashes( trust_internet=not require_hashes) if require_hashes and not hashes: # Known-good hashes are missing for this requirement, so # shim it with a facade object that will provoke hash # computation and then raise a HashMissing exception # showing the user what the hash should be. hashes = MissingHashes() try: download_dir = self.download_dir # We always delete unpacked sdists after pip ran. autodelete_unpacked = True if req_to_install.link.is_wheel \ and self.wheel_download_dir: # when doing 'pip wheel` we download wheels to a # dedicated dir. download_dir = self.wheel_download_dir if req_to_install.link.is_wheel: if download_dir: # When downloading, we only unpack wheels to get # metadata. autodelete_unpacked = True else: # When installing a wheel, we use the unpacked # wheel. autodelete_unpacked = False unpack_url( req_to_install.link, req_to_install.source_dir, download_dir, autodelete_unpacked, session=self.session, hashes=hashes) except requests.HTTPError as exc: logger.critical( 'Could not install requirement %s because ' 'of error %s', req_to_install, exc, ) raise InstallationError( 'Could not install requirement %s because ' 'of HTTP error %s for URL %s' % (req_to_install, exc, req_to_install.link) ) abstract_dist = make_abstract_dist(req_to_install) abstract_dist.prep_for_dist() if self.is_download: # Make a .zip of the source_dir we already created. if req_to_install.link.scheme in vcs.all_schemes: req_to_install.archive(self.download_dir) # req_to_install.req is only avail after unpack for URL # pkgs repeat check_if_exists to uninstall-on-upgrade # (#14) if not self.ignore_installed: req_to_install.check_if_exists() if req_to_install.satisfied_by: if self.upgrade or self.ignore_installed: # don't uninstall conflict if user install and # conflict is not user install if not (self.use_user_site and not dist_in_usersite( req_to_install.satisfied_by)): req_to_install.conflicts_with = \ req_to_install.satisfied_by req_to_install.satisfied_by = None else: logger.info( 'Requirement already satisfied (use ' '--upgrade to upgrade): %s', req_to_install, ) # ###################### # # # parse dependencies # # # ###################### # dist = abstract_dist.dist(finder) try: check_dist_requires_python(dist) except UnsupportedPythonVersion as e: if self.ignore_requires_python: logger.warning(e.args[0]) else: req_to_install.remove_temporary_source() raise more_reqs = [] def add_req(subreq, extras_requested): sub_install_req = InstallRequirement( str(subreq), req_to_install, isolated=self.isolated, wheel_cache=self._wheel_cache, ) more_reqs.extend(self.add_requirement( sub_install_req, req_to_install.name, extras_requested=extras_requested)) # We add req_to_install before its dependencies, so that we # can refer to it when adding dependencies. if not self.has_requirement(req_to_install.name): # 'unnamed' requirements will get added here self.add_requirement(req_to_install, None) if not ignore_dependencies: if (req_to_install.extras): logger.debug( "Installing extra requirements: %r", ','.join(req_to_install.extras), ) missing_requested = sorted( set(req_to_install.extras) - set(dist.extras) ) for missing in missing_requested: logger.warning( '%s does not provide the extra \'%s\'', dist, missing ) available_requested = sorted( set(dist.extras) & set(req_to_install.extras) ) for subreq in dist.requires(available_requested): add_req(subreq, extras_requested=available_requested) # cleanup tmp src self.reqs_to_cleanup.append(req_to_install) if not req_to_install.editable and not req_to_install.satisfied_by: # XXX: --no-install leads this to report 'Successfully # downloaded' for only non-editable reqs, even though we took # action on them. self.successfully_downloaded.append(req_to_install) return more_reqs def cleanup_files(self): """Clean up files, remove builds.""" logger.debug('Cleaning up...') with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source() def _to_install(self): """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. """ # The current implementation, which we may change at any point # installs the user specified things in the order given, except when # dependencies must come earlier to achieve topological order. order = [] ordered_reqs = set() def schedule(req): if req.satisfied_by or req in ordered_reqs: return if req.constraint: return ordered_reqs.add(req) for dep in self._dependencies[req]: schedule(dep) order.append(req) for install_req in self.requirements.values(): schedule(install_req) return order def install(self, install_options, global_options=(), *args, **kwargs): """ Install everything in this set (after having downloaded and unpacked the packages) """ to_install = self._to_install() if to_install: logger.info( 'Installing collected packages: %s', ', '.join([req.name for req in to_install]), ) with indent_log(): for requirement in to_install: if requirement.conflicts_with: logger.info( 'Found existing installation: %s', requirement.conflicts_with, ) with indent_log(): requirement.uninstall(auto_confirm=True) try: requirement.install( install_options, global_options, *args, **kwargs ) except: # if install did not succeed, rollback previous uninstall if (requirement.conflicts_with and not requirement.install_succeeded): requirement.rollback_uninstall() raise else: if (requirement.conflicts_with and requirement.install_succeeded): requirement.commit_uninstall() requirement.remove_temporary_source() self.successfully_installed = to_install
mit
cryptodechange/electrum-asiccoin
plugins/virtualkeyboard.py
3
1951
from PyQt4.QtGui import * from electrum import BasePlugin from electrum.i18n import _ class Plugin(BasePlugin): def fullname(self): return 'Virtual Keyboard' def description(self): return '%s\n%s' % (_("Add an optional, mouse keyboard to the password dialog."), _("Warning: do not use this if it makes you pick a weaker password.")) def init(self): self.vkb = None self.vkb_index = 0 def password_dialog(self, pw, grid, pos): vkb_button = QPushButton(_("+")) vkb_button.setFixedWidth(20) vkb_button.clicked.connect(lambda: self.toggle_vkb(grid, pw)) grid.addWidget(vkb_button, pos, 2) self.kb_pos = 2 def toggle_vkb(self, grid, pw): if self.vkb: grid.removeItem(self.vkb) self.vkb = self.virtual_keyboard(self.vkb_index, pw) grid.addLayout(self.vkb, self.kb_pos, 0, 1, 3) self.vkb_index += 1 def virtual_keyboard(self, i, pw): import random i = i%3 if i == 0: chars = 'abcdefghijklmnopqrstuvwxyz ' elif i == 1: chars = 'ABCDEFGHIJKLMNOPQRTSUVWXYZ ' elif i == 2: chars = '1234567890!?.,;:/%&()[]{}+-' n = len(chars) s = [] for i in xrange(n): while True: k = random.randint(0,n-1) if k not in s: s.append(k) break def add_target(t): return lambda: pw.setText(str( pw.text() ) + t) vbox = QVBoxLayout() grid = QGridLayout() grid.setSpacing(2) for i in range(n): l_button = QPushButton(chars[s[i]]) l_button.setFixedWidth(25) l_button.setFixedHeight(25) l_button.clicked.connect(add_target(chars[s[i]]) ) grid.addWidget(l_button, i/6, i%6) vbox.addLayout(grid) return vbox
gpl-3.0
playm2mboy/edx-platform
cms/djangoapps/contentstore/views/tests/test_videos.py
83
15190
#-*- coding: utf-8 -*- """ Unit tests for video-related REST APIs. """ # pylint: disable=attribute-defined-outside-init import csv import json import dateutil.parser import re from StringIO import StringIO from django.conf import settings from django.test.utils import override_settings from mock import Mock, patch from edxval.api import create_profile, create_video, get_video_info from contentstore.models import VideoUploadConfig from contentstore.views.videos import KEY_EXPIRATION_IN_SECONDS, StatusDisplayStrings from contentstore.tests.utils import CourseTestCase from contentstore.utils import reverse_course_url from xmodule.modulestore.tests.factories import CourseFactory class VideoUploadTestMixin(object): """ Test cases for the video upload feature """ def get_url_for_course_key(self, course_key): """Return video handler URL for the given course""" return reverse_course_url(self.VIEW_NAME, course_key) def setUp(self): super(VideoUploadTestMixin, self).setUp() self.url = self.get_url_for_course_key(self.course.id) self.test_token = "test_token" self.course.video_upload_pipeline = { "course_video_upload_token": self.test_token, } self.save_course() self.profiles = ["profile1", "profile2"] self.previous_uploads = [ { "edx_video_id": "test1", "client_video_id": "test1.mp4", "duration": 42.0, "status": "upload", "courses": [unicode(self.course.id)], "encoded_videos": [], }, { "edx_video_id": "test2", "client_video_id": "test2.mp4", "duration": 128.0, "status": "file_complete", "courses": [unicode(self.course.id)], "encoded_videos": [ { "profile": "profile1", "url": "http://example.com/profile1/test2.mp4", "file_size": 1600, "bitrate": 100, }, { "profile": "profile2", "url": "http://example.com/profile2/test2.mov", "file_size": 16000, "bitrate": 1000, }, ], }, { "edx_video_id": "non-ascii", "client_video_id": u"nón-ascii-näme.mp4", "duration": 256.0, "status": "transcode_active", "courses": [unicode(self.course.id)], "encoded_videos": [ { "profile": "profile1", "url": u"http://example.com/profile1/nón-ascii-näme.mp4", "file_size": 3200, "bitrate": 100, }, ] }, ] # Ensure every status string is tested self.previous_uploads += [ { "edx_video_id": "status_test_{}".format(status), "client_video_id": "status_test.mp4", "duration": 3.14, "status": status, "courses": [unicode(self.course.id)], "encoded_videos": [], } for status in ( StatusDisplayStrings._STATUS_MAP.keys() + # pylint:disable=protected-access ["non_existent_status"] ) ] for profile in self.profiles: create_profile(profile) for video in self.previous_uploads: create_video(video) def _get_previous_upload(self, edx_video_id): """Returns the previous upload with the given video id.""" return next( video for video in self.previous_uploads if video["edx_video_id"] == edx_video_id ) def test_anon_user(self): self.client.logout() response = self.client.get(self.url) self.assertEqual(response.status_code, 302) def test_put(self): response = self.client.put(self.url) self.assertEqual(response.status_code, 405) def test_invalid_course_key(self): response = self.client.get( self.get_url_for_course_key("Non/Existent/Course") ) self.assertEqual(response.status_code, 404) def test_non_staff_user(self): client, __ = self.create_non_staff_authed_user_client() response = client.get(self.url) self.assertEqual(response.status_code, 403) def test_video_pipeline_not_enabled(self): settings.FEATURES["ENABLE_VIDEO_UPLOAD_PIPELINE"] = False self.assertEqual(self.client.get(self.url).status_code, 404) def test_video_pipeline_not_configured(self): settings.VIDEO_UPLOAD_PIPELINE = None self.assertEqual(self.client.get(self.url).status_code, 404) def test_course_not_configured(self): self.course.video_upload_pipeline = {} self.save_course() self.assertEqual(self.client.get(self.url).status_code, 404) @patch.dict("django.conf.settings.FEATURES", {"ENABLE_VIDEO_UPLOAD_PIPELINE": True}) @override_settings(VIDEO_UPLOAD_PIPELINE={"BUCKET": "test_bucket", "ROOT_PATH": "test_root"}) class VideosHandlerTestCase(VideoUploadTestMixin, CourseTestCase): """Test cases for the main video upload endpoint""" VIEW_NAME = "videos_handler" def test_get_json(self): response = self.client.get_json(self.url) self.assertEqual(response.status_code, 200) response_videos = json.loads(response.content)["videos"] self.assertEqual(len(response_videos), len(self.previous_uploads)) for i, response_video in enumerate(response_videos): # Videos should be returned by creation date descending original_video = self.previous_uploads[-(i + 1)] self.assertEqual( set(response_video.keys()), set(["edx_video_id", "client_video_id", "created", "duration", "status"]) ) dateutil.parser.parse(response_video["created"]) for field in ["edx_video_id", "client_video_id", "duration"]: self.assertEqual(response_video[field], original_video[field]) self.assertEqual( response_video["status"], StatusDisplayStrings.get(original_video["status"]) ) def test_get_html(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertRegexpMatches(response["Content-Type"], "^text/html(;.*)?$") # Crude check for presence of data in returned HTML for video in self.previous_uploads: self.assertIn(video["edx_video_id"], response.content) def test_post_non_json(self): response = self.client.post(self.url, {"files": []}) self.assertEqual(response.status_code, 400) def test_post_malformed_json(self): response = self.client.post(self.url, "{", content_type="application/json") self.assertEqual(response.status_code, 400) def test_post_invalid_json(self): def assert_bad(content): """Make request with content and assert that response is 400""" response = self.client.post( self.url, json.dumps(content), content_type="application/json" ) self.assertEqual(response.status_code, 400) # Top level missing files key assert_bad({}) # Entry missing file_name assert_bad({"files": [{"content_type": "video/mp4"}]}) # Entry missing content_type assert_bad({"files": [{"file_name": "test.mp4"}]}) @override_settings(AWS_ACCESS_KEY_ID="test_key_id", AWS_SECRET_ACCESS_KEY="test_secret") @patch("boto.s3.key.Key") @patch("boto.s3.connection.S3Connection") def test_post_success(self, mock_conn, mock_key): files = [ { "file_name": "first.mp4", "content_type": "video/mp4", }, { "file_name": "second.webm", "content_type": "video/webm", }, { "file_name": "third.mov", "content_type": "video/quicktime", }, { "file_name": "fourth.mp4", "content_type": "video/mp4", }, ] bucket = Mock() mock_conn.return_value = Mock(get_bucket=Mock(return_value=bucket)) mock_key_instances = [ Mock( generate_url=Mock( return_value="http://example.com/url_{}".format(file_info["file_name"]) ) ) for file_info in files ] # If extra calls are made, return a dummy mock_key.side_effect = mock_key_instances + [Mock()] response = self.client.post( self.url, json.dumps({"files": files}), content_type="application/json" ) self.assertEqual(response.status_code, 200) response_obj = json.loads(response.content) mock_conn.assert_called_once_with(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) self.assertEqual(len(response_obj["files"]), len(files)) self.assertEqual(mock_key.call_count, len(files)) for i, file_info in enumerate(files): # Ensure Key was set up correctly and extract id key_call_args, __ = mock_key.call_args_list[i] self.assertEqual(key_call_args[0], bucket) path_match = re.match( ( settings.VIDEO_UPLOAD_PIPELINE["ROOT_PATH"] + "/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})$" ), key_call_args[1] ) self.assertIsNotNone(path_match) video_id = path_match.group(1) mock_key_instance = mock_key_instances[i] mock_key_instance.set_metadata.assert_any_call( "course_video_upload_token", self.test_token ) mock_key_instance.set_metadata.assert_any_call( "client_video_id", file_info["file_name"] ) mock_key_instance.set_metadata.assert_any_call("course_key", unicode(self.course.id)) mock_key_instance.generate_url.assert_called_once_with( KEY_EXPIRATION_IN_SECONDS, "PUT", headers={"Content-Type": file_info["content_type"]} ) # Ensure VAL was updated val_info = get_video_info(video_id) self.assertEqual(val_info["status"], "upload") self.assertEqual(val_info["client_video_id"], file_info["file_name"]) self.assertEqual(val_info["status"], "upload") self.assertEqual(val_info["duration"], 0) self.assertEqual(val_info["courses"], [unicode(self.course.id)]) # Ensure response is correct response_file = response_obj["files"][i] self.assertEqual(response_file["file_name"], file_info["file_name"]) self.assertEqual(response_file["upload_url"], mock_key_instance.generate_url()) @patch.dict("django.conf.settings.FEATURES", {"ENABLE_VIDEO_UPLOAD_PIPELINE": True}) @override_settings(VIDEO_UPLOAD_PIPELINE={"BUCKET": "test_bucket", "ROOT_PATH": "test_root"}) class VideoUrlsCsvTestCase(VideoUploadTestMixin, CourseTestCase): """Test cases for the CSV download endpoint for video uploads""" VIEW_NAME = "video_encodings_download" def setUp(self): super(VideoUrlsCsvTestCase, self).setUp() VideoUploadConfig(profile_whitelist="profile1").save() def _check_csv_response(self, expected_profiles): """ Check that the response is a valid CSV response containing rows corresponding to previous_uploads and including the expected profiles. """ response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertEqual( response["Content-Disposition"], "attachment; filename={course}_video_urls.csv".format(course=self.course.id.course) ) response_reader = StringIO(response.content) reader = csv.DictReader(response_reader, dialect=csv.excel) self.assertEqual( reader.fieldnames, ( ["Name", "Duration", "Date Added", "Video ID", "Status"] + ["{} URL".format(profile) for profile in expected_profiles] ) ) rows = list(reader) self.assertEqual(len(rows), len(self.previous_uploads)) for i, row in enumerate(rows): response_video = { key.decode("utf-8"): value.decode("utf-8") for key, value in row.items() } # Videos should be returned by creation date descending original_video = self.previous_uploads[-(i + 1)] self.assertEqual(response_video["Name"], original_video["client_video_id"]) self.assertEqual(response_video["Duration"], str(original_video["duration"])) dateutil.parser.parse(response_video["Date Added"]) self.assertEqual(response_video["Video ID"], original_video["edx_video_id"]) self.assertEqual(response_video["Status"], StatusDisplayStrings.get(original_video["status"])) for profile in expected_profiles: response_profile_url = response_video["{} URL".format(profile)] original_encoded_for_profile = next( ( original_encoded for original_encoded in original_video["encoded_videos"] if original_encoded["profile"] == profile ), None ) if original_encoded_for_profile: self.assertEqual(response_profile_url, original_encoded_for_profile["url"]) else: self.assertEqual(response_profile_url, "") def test_basic(self): self._check_csv_response(["profile1"]) def test_profile_whitelist(self): VideoUploadConfig(profile_whitelist="profile1,profile2").save() self._check_csv_response(["profile1", "profile2"]) def test_non_ascii_course(self): course = CourseFactory.create( number=u"nón-äscii", video_upload_pipeline={ "course_video_upload_token": self.test_token, } ) response = self.client.get(self.get_url_for_course_key(course.id)) self.assertEqual(response.status_code, 200) self.assertEqual( response["Content-Disposition"], "attachment; filename=video_urls.csv; filename*=utf-8''n%C3%B3n-%C3%A4scii_video_urls.csv" )
agpl-3.0
commtrack/temp-rapidsms
apps/schools/xml.py
3
1531
''' Created on Nov 13, 2009 @author: Cory Zue ''' from __future__ import absolute_import from xml.etree import ElementTree from xml.etree.ElementTree import Element, SubElement from django.db import models class SerializableModel(): '''A serializable model. Override the ATTRS and ELEMS property on the to introspect out the attrs and elems. These should be dictionaries of the form: { attr_name: model_property, attr_name: model_property } and { elem_name: model_property, elem_name: model_property } ''' # these two fields determine how the model is displayed as XML # the key is the name of the attribute/element, the value is # the field/property used to display it. ATTRS = {} ELEMS = {} # TODO: foreign keys? def to_element(self): """Get this as an xml element""" return to_element(self) def to_xml(self): return ElementTree.tostring(self.to_element()) def to_element(model): """Converts a SerializableModel to xml. Uses the class name as the root tag. """ root_name = model.__class__.__name__ top_element = Element(root_name) for attr_name, model_attr in model.ATTRS.items(): top_element.set(attr_name, str(getattr(model, model_attr, ""))) for elem_name, model_attr in model.ELEMS.items(): sub_elt = SubElement(top_element, elem_name) sub_elt.text = str(getattr(model, model_attr, "")) return top_element
lgpl-3.0
glewarne/v9_testing
Documentation/networking/cxacru-cf.py
14668
1626
#!/usr/bin/env python # Copyright 2009 Simon Arlott # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Usage: cxacru-cf.py < cxacru-cf.bin # Output: values string suitable for the sysfs adsl_config attribute # # Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110 # contains mis-aligned values which will stop the modem from being able # to make a connection. If the first and last two bytes are removed then # the values become valid, but the modulation will be forced to ANSI # T1.413 only which may not be appropriate. # # The original binary format is a packed list of le32 values. import sys import struct i = 0 while True: buf = sys.stdin.read(4) if len(buf) == 0: break elif len(buf) != 4: sys.stdout.write("\n") sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf))) sys.exit(1) if i > 0: sys.stdout.write(" ") sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0])) i += 1 sys.stdout.write("\n")
gpl-2.0
kreatorkodi/repository.torrentbr
plugin.video.elementum/resources/site-packages/elementum/dialog_select.py
1
1990
import os import xbmcgui from elementum.addon import ADDON_PATH from dialog import * # NOQA class DialogSelect(xbmcgui.WindowXMLDialog): def __init__(self, *args, **kwargs): xbmcgui.WindowXML.__init__(self) self.items = kwargs['items'] self.title = kwargs['title'] self.count = 0 self.retval = -1 def onInit(self): self.getControl(32501).setLabel(self.title) for item in self.items: labels = item.split('\n') label1 = labels[0] try: label2 = labels[1] except: label2 = '' try: icon = labels[2] except: icon = None try: multi = labels[3] == 'multi' except: multi = False self.addItem(label1, label2, icon, multi) self.setFocusId(32503) def onClick(self, controlId): if controlId == 32500: # Close Button self.close() elif controlId == 32503: # Panel listControl = self.getControl(32503) selected = listControl.getSelectedItem() self.retval = int(selected.getProperty('index')) self.close() def onAction(self, action): if action.getId() in [ACTION_PARENT_DIR, KEY_NAV_BACK, ACTION_PREVIOUS_MENU]: # NOQA self.close() def addItem(self, label1, label2, icon=None, multi=False): listControl = self.getControl(32503) item = xbmcgui.ListItem(label1, label2) item.setProperty('index', str(self.count)) if multi: item.setIconImage(os.path.join(ADDON_PATH, "resources", "img", "multi-cloud.png")) else: if icon: item.setIconImage(icon) else: item.setIconImage(os.path.join(ADDON_PATH, "resources", "img", "cloud.png")) listControl.addItem(item) self.count += 1
gpl-2.0
sergiosgc/Syncthing.py
syncthing/bep/fileinfo.py
1
1801
from syncthing.bep.serializable import BEPSerializable from syncthing.bep.blockinfo import BEPBlockInfo from syncthing.xdr.XDRStringUnserializer import XDRStringUnserializer from syncthing.xdr.XDRIntegerUnserializer import XDRIntegerUnserializer from syncthing.xdr.XDRLongIntegerUnserializer import XDRLongIntegerUnserializer from syncthing.xdr.XDRArrayUnserializer import XDRArrayUnserializer from syncthing.xdr.XDRStringSerializer import XDRStringSerializer from syncthing.xdr.XDRIntegerSerializer import XDRIntegerSerializer from syncthing.xdr.XDRLongIntegerSerializer import XDRLongIntegerSerializer from syncthing.xdr.XDRArraySerializer import XDRArraySerializer class BEPFileInfo(BEPSerializable): def __init__(self): super(BEPFileInfo, self).__init__() self.name = None self.flags = None self.modified = None self.version = None self.blocks = None def nextUnserializer(self): if self.name is None: return (XDRStringUnserializer(), 'name') if self.flags is None: return (XDRIntegerUnserializer(), 'flags') if self.modified is None: return (XDRLongIntegerUnserializer(), 'modified') if self.version is None: return (XDRLongIntegerUnserializer(), 'version') if self.blocks is None: return (XDRArrayUnserializer(BEPBlockInfo), 'blocks') return None def serialize(self, destination): XDRStringSerializer().serialize(self.name, destination) XDRIntegerSerializer().serialize(self.flags, destination) XDRLongIntegerSerializer().serialize(self.modified, destination) XDRLongIntegerSerializer().serialize(self.version, destination) XDRArraySerializer().serialize(self.blocks, destination)
gpl-2.0
larrybradley/astropy
astropy/io/votable/tests/vo_test.py
8
35397
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This is a set of regression tests for vo. """ # STDLIB import difflib import io import pathlib import sys import gzip from unittest import mock # THIRD-PARTY import pytest import numpy as np from numpy.testing import assert_array_equal # LOCAL from astropy.io.votable.table import parse, parse_single_table, validate from astropy.io.votable import tree from astropy.io.votable.exceptions import VOTableSpecError, VOWarning, W39 from astropy.io.votable.xmlutil import validate_schema from astropy.utils.data import get_pkg_data_filename, get_pkg_data_filenames # Determine the kind of float formatting in this build of Python if hasattr(sys, 'float_repr_style'): legacy_float_repr = (sys.float_repr_style == 'legacy') else: legacy_float_repr = sys.platform.startswith('win') def assert_validate_schema(filename, version): if sys.platform.startswith('win'): return try: rc, stdout, stderr = validate_schema(filename, version) except OSError: # If xmllint is not installed, we want the test to pass anyway return assert rc == 0, 'File did not validate against VOTable schema' def test_parse_single_table(): table = parse_single_table(get_pkg_data_filename('data/regression.xml')) assert isinstance(table, tree.Table) assert len(table.array) == 5 def test_parse_single_table2(): table2 = parse_single_table(get_pkg_data_filename('data/regression.xml'), table_number=1) assert isinstance(table2, tree.Table) assert len(table2.array) == 1 assert len(table2.array.dtype.names) == 28 def test_parse_single_table3(): with pytest.raises(IndexError): parse_single_table(get_pkg_data_filename('data/regression.xml'), table_number=3) def _test_regression(tmpdir, _python_based=False, binary_mode=1): # Read the VOTABLE votable = parse(get_pkg_data_filename('data/regression.xml'), _debug_python_based_parser=_python_based) table = votable.get_first_table() dtypes = [ (('string test', 'string_test'), '|O8'), (('fixed string test', 'string_test_2'), '<U10'), ('unicode_test', '|O8'), (('unicode test', 'fixed_unicode_test'), '<U10'), (('string array test', 'string_array_test'), '<U4'), ('unsignedByte', '|u1'), ('short', '<i2'), ('int', '<i4'), ('long', '<i8'), ('double', '<f8'), ('float', '<f4'), ('array', '|O8'), ('bit', '|b1'), ('bitarray', '|b1', (3, 2)), ('bitvararray', '|O8'), ('bitvararray2', '|O8'), ('floatComplex', '<c8'), ('doubleComplex', '<c16'), ('doubleComplexArray', '|O8'), ('doubleComplexArrayFixed', '<c16', (2,)), ('boolean', '|b1'), ('booleanArray', '|b1', (4,)), ('nulls', '<i4'), ('nulls_array', '<i4', (2, 2)), ('precision1', '<f8'), ('precision2', '<f8'), ('doublearray', '|O8'), ('bitarray2', '|b1', (16,)) ] if sys.byteorder == 'big': new_dtypes = [] for dtype in dtypes: dtype = list(dtype) dtype[1] = dtype[1].replace('<', '>') new_dtypes.append(tuple(dtype)) dtypes = new_dtypes assert table.array.dtype == dtypes votable.to_xml(str(tmpdir.join("regression.tabledata.xml")), _debug_python_based_parser=_python_based) assert_validate_schema(str(tmpdir.join("regression.tabledata.xml")), votable.version) if binary_mode == 1: votable.get_first_table().format = 'binary' votable.version = '1.1' elif binary_mode == 2: votable.get_first_table()._config['version_1_3_or_later'] = True votable.get_first_table().format = 'binary2' votable.version = '1.3' # Also try passing a file handle with open(str(tmpdir.join("regression.binary.xml")), "wb") as fd: votable.to_xml(fd, _debug_python_based_parser=_python_based) assert_validate_schema(str(tmpdir.join("regression.binary.xml")), votable.version) # Also try passing a file handle with open(str(tmpdir.join("regression.binary.xml")), "rb") as fd: votable2 = parse(fd, _debug_python_based_parser=_python_based) votable2.get_first_table().format = 'tabledata' votable2.to_xml(str(tmpdir.join("regression.bin.tabledata.xml")), _astropy_version="testing", _debug_python_based_parser=_python_based) assert_validate_schema(str(tmpdir.join("regression.bin.tabledata.xml")), votable.version) with open( get_pkg_data_filename( f'data/regression.bin.tabledata.truth.{votable.version}.xml'), 'rt', encoding='utf-8') as fd: truth = fd.readlines() with open(str(tmpdir.join("regression.bin.tabledata.xml")), 'rt', encoding='utf-8') as fd: output = fd.readlines() # If the lines happen to be different, print a diff # This is convenient for debugging sys.stdout.writelines( difflib.unified_diff(truth, output, fromfile='truth', tofile='output')) assert truth == output # Test implicit gzip saving votable2.to_xml( str(tmpdir.join("regression.bin.tabledata.xml.gz")), _astropy_version="testing", _debug_python_based_parser=_python_based) with gzip.GzipFile( str(tmpdir.join("regression.bin.tabledata.xml.gz")), 'rb') as gzfd: output = gzfd.readlines() output = [x.decode('utf-8').rstrip() for x in output] truth = [x.rstrip() for x in truth] assert truth == output @pytest.mark.xfail('legacy_float_repr') def test_regression(tmpdir): # W39: Bit values can not be masked with pytest.warns(W39): _test_regression(tmpdir, False) @pytest.mark.xfail('legacy_float_repr') def test_regression_python_based_parser(tmpdir): # W39: Bit values can not be masked with pytest.warns(W39): _test_regression(tmpdir, True) @pytest.mark.xfail('legacy_float_repr') def test_regression_binary2(tmpdir): # W39: Bit values can not be masked with pytest.warns(W39): _test_regression(tmpdir, False, 2) class TestFixups: def setup_class(self): self.table = parse( get_pkg_data_filename('data/regression.xml')).get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_implicit_id(self): assert_array_equal(self.array['string_test_2'], self.array['fixed string test']) class TestReferences: def setup_class(self): self.votable = parse(get_pkg_data_filename('data/regression.xml')) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_fieldref(self): fieldref = self.table.groups[1].entries[0] assert isinstance(fieldref, tree.FieldRef) assert fieldref.get_ref().name == 'boolean' assert fieldref.get_ref().datatype == 'boolean' def test_paramref(self): paramref = self.table.groups[0].entries[0] assert isinstance(paramref, tree.ParamRef) assert paramref.get_ref().name == 'INPUT' assert paramref.get_ref().datatype == 'float' def test_iter_fields_and_params_on_a_group(self): assert len(list(self.table.groups[1].iter_fields_and_params())) == 2 def test_iter_groups_on_a_group(self): assert len(list(self.table.groups[1].iter_groups())) == 1 def test_iter_groups(self): # Because of the ref'd table, there are more logical groups # than actually exist in the file assert len(list(self.votable.iter_groups())) == 9 def test_ref_table(self): tables = list(self.votable.iter_tables()) for x, y in zip(tables[0].array.data[0], tables[1].array.data[0]): assert_array_equal(x, y) def test_iter_coosys(self): assert len(list(self.votable.iter_coosys())) == 1 def test_select_columns_by_index(): columns = [0, 5, 13] table = parse( get_pkg_data_filename('data/regression.xml'), columns=columns).get_first_table() # noqa array = table.array mask = table.array.mask assert array['string_test'][0] == "String & test" columns = ['string_test', 'unsignedByte', 'bitarray'] for c in columns: assert not np.all(mask[c]) assert np.all(mask['unicode_test']) def test_select_columns_by_name(): columns = ['string_test', 'unsignedByte', 'bitarray'] table = parse( get_pkg_data_filename('data/regression.xml'), columns=columns).get_first_table() # noqa array = table.array mask = table.array.mask assert array['string_test'][0] == "String & test" for c in columns: assert not np.all(mask[c]) assert np.all(mask['unicode_test']) class TestParse: def setup_class(self): self.votable = parse(get_pkg_data_filename('data/regression.xml')) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_string_test(self): assert issubclass(self.array['string_test'].dtype.type, np.object_) assert_array_equal( self.array['string_test'], ['String & test', 'String &amp; test', 'XXXX', '', '']) def test_fixed_string_test(self): assert issubclass(self.array['string_test_2'].dtype.type, np.unicode_) assert_array_equal( self.array['string_test_2'], ['Fixed stri', '0123456789', 'XXXX', '', '']) def test_unicode_test(self): assert issubclass(self.array['unicode_test'].dtype.type, np.object_) assert_array_equal(self.array['unicode_test'], ["Ceçi n'est pas un pipe", 'வணக்கம்', 'XXXX', '', '']) def test_fixed_unicode_test(self): assert issubclass(self.array['fixed_unicode_test'].dtype.type, np.unicode_) assert_array_equal(self.array['fixed_unicode_test'], ["Ceçi n'est", 'வணக்கம்', '0123456789', '', '']) def test_unsignedByte(self): assert issubclass(self.array['unsignedByte'].dtype.type, np.uint8) assert_array_equal(self.array['unsignedByte'], [128, 255, 0, 255, 255]) assert not np.any(self.mask['unsignedByte']) def test_short(self): assert issubclass(self.array['short'].dtype.type, np.int16) assert_array_equal(self.array['short'], [4096, 32767, -4096, 32767, 32767]) assert not np.any(self.mask['short']) def test_int(self): assert issubclass(self.array['int'].dtype.type, np.int32) assert_array_equal( self.array['int'], [268435456, 2147483647, -268435456, 268435455, 123456789]) assert_array_equal(self.mask['int'], [False, False, False, False, True]) def test_long(self): assert issubclass(self.array['long'].dtype.type, np.int64) assert_array_equal( self.array['long'], [922337203685477, 123456789, -1152921504606846976, 1152921504606846975, 123456789]) assert_array_equal(self.mask['long'], [False, True, False, False, True]) def test_double(self): assert issubclass(self.array['double'].dtype.type, np.float64) assert_array_equal(self.array['double'], [8.9990234375, 0.0, np.inf, np.nan, -np.inf]) assert_array_equal(self.mask['double'], [False, False, False, True, False]) def test_float(self): assert issubclass(self.array['float'].dtype.type, np.float32) assert_array_equal(self.array['float'], [1.0, 0.0, np.inf, np.inf, np.nan]) assert_array_equal(self.mask['float'], [False, False, False, False, True]) def test_array(self): assert issubclass(self.array['array'].dtype.type, np.object_) match = [[], [[42, 32], [12, 32]], [[12, 34], [56, 78], [87, 65], [43, 21]], [[-1, 23]], [[31, -1]]] for a, b in zip(self.array['array'], match): # assert issubclass(a.dtype.type, np.int64) # assert a.shape[1] == 2 for a0, b0 in zip(a, b): assert issubclass(a0.dtype.type, np.int64) assert_array_equal(a0, b0) assert self.array.data['array'][3].mask[0][0] assert self.array.data['array'][4].mask[0][1] def test_bit(self): assert issubclass(self.array['bit'].dtype.type, np.bool_) assert_array_equal(self.array['bit'], [True, False, True, False, False]) def test_bit_mask(self): assert_array_equal(self.mask['bit'], [False, False, False, False, True]) def test_bitarray(self): assert issubclass(self.array['bitarray'].dtype.type, np.bool_) assert self.array['bitarray'].shape == (5, 3, 2) assert_array_equal(self.array['bitarray'], [[[True, False], [True, True], [False, True]], [[False, True], [False, False], [True, True]], [[True, True], [True, False], [False, False]], [[False, False], [False, False], [False, False]], [[False, False], [False, False], [False, False]]]) def test_bitarray_mask(self): assert_array_equal(self.mask['bitarray'], [[[False, False], [False, False], [False, False]], [[False, False], [False, False], [False, False]], [[False, False], [False, False], [False, False]], [[True, True], [True, True], [True, True]], [[True, True], [True, True], [True, True]]]) def test_bitvararray(self): assert issubclass(self.array['bitvararray'].dtype.type, np.object_) match = [[True, True, True], [False, False, False, False, False], [True, False, True, False, True], [], []] for a, b in zip(self.array['bitvararray'], match): assert_array_equal(a, b) match_mask = [[False, False, False], [False, False, False, False, False], [False, False, False, False, False], False, False] for a, b in zip(self.array['bitvararray'], match_mask): assert_array_equal(a.mask, b) def test_bitvararray2(self): assert issubclass(self.array['bitvararray2'].dtype.type, np.object_) match = [[], [[[False, True], [False, False], [True, False]], [[True, False], [True, False], [True, False]]], [[[True, True], [True, True], [True, True]]], [], []] for a, b in zip(self.array['bitvararray2'], match): for a0, b0 in zip(a, b): assert a0.shape == (3, 2) assert issubclass(a0.dtype.type, np.bool_) assert_array_equal(a0, b0) def test_floatComplex(self): assert issubclass(self.array['floatComplex'].dtype.type, np.complex64) assert_array_equal(self.array['floatComplex'], [np.nan+0j, 0+0j, 0+-1j, np.nan+0j, np.nan+0j]) assert_array_equal(self.mask['floatComplex'], [True, False, False, True, True]) def test_doubleComplex(self): assert issubclass(self.array['doubleComplex'].dtype.type, np.complex128) assert_array_equal( self.array['doubleComplex'], [np.nan+0j, 0+0j, 0+-1j, np.nan+(np.inf*1j), np.nan+0j]) assert_array_equal(self.mask['doubleComplex'], [True, False, False, True, True]) def test_doubleComplexArray(self): assert issubclass(self.array['doubleComplexArray'].dtype.type, np.object_) assert ([len(x) for x in self.array['doubleComplexArray']] == [0, 2, 2, 0, 0]) def test_boolean(self): assert issubclass(self.array['boolean'].dtype.type, np.bool_) assert_array_equal(self.array['boolean'], [True, False, True, False, False]) def test_boolean_mask(self): assert_array_equal(self.mask['boolean'], [False, False, False, False, True]) def test_boolean_array(self): assert issubclass(self.array['booleanArray'].dtype.type, np.bool_) assert_array_equal(self.array['booleanArray'], [[True, True, True, True], [True, True, False, True], [True, True, False, True], [False, False, False, False], [False, False, False, False]]) def test_boolean_array_mask(self): assert_array_equal(self.mask['booleanArray'], [[False, False, False, False], [False, False, False, False], [False, False, True, False], [True, True, True, True], [True, True, True, True]]) def test_nulls(self): assert_array_equal(self.array['nulls'], [0, -9, 2, -9, -9]) assert_array_equal(self.mask['nulls'], [False, True, False, True, True]) def test_nulls_array(self): assert_array_equal(self.array['nulls_array'], [[[-9, -9], [-9, -9]], [[0, 1], [2, 3]], [[-9, 0], [-9, 1]], [[0, -9], [1, -9]], [[-9, -9], [-9, -9]]]) assert_array_equal(self.mask['nulls_array'], [[[True, True], [True, True]], [[False, False], [False, False]], [[True, False], [True, False]], [[False, True], [False, True]], [[True, True], [True, True]]]) def test_double_array(self): assert issubclass(self.array['doublearray'].dtype.type, np.object_) assert len(self.array['doublearray'][0]) == 0 assert_array_equal(self.array['doublearray'][1], [0, 1, np.inf, -np.inf, np.nan, 0, -1]) assert_array_equal(self.array.data['doublearray'][1].mask, [False, False, False, False, False, False, True]) def test_bit_array2(self): assert_array_equal(self.array['bitarray2'][0], [True, True, True, True, False, False, False, False, True, True, True, True, False, False, False, False]) def test_bit_array2_mask(self): assert not np.any(self.mask['bitarray2'][0]) assert np.all(self.mask['bitarray2'][1:]) def test_get_coosys_by_id(self): coosys = self.votable.get_coosys_by_id('J2000') assert coosys.system == 'eq_FK5' def test_get_field_by_utype(self): fields = list(self.votable.get_fields_by_utype("myint")) assert fields[0].name == "int" assert fields[0].values.min == -1000 def test_get_info_by_id(self): info = self.votable.get_info_by_id('QUERY_STATUS') assert info.value == 'OK' if self.votable.version != '1.1': info = self.votable.get_info_by_id("ErrorInfo") assert info.value == "One might expect to find some INFO here, too..." # noqa def test_repr(self): assert '3 tables' in repr(self.votable) assert repr(list(self.votable.iter_fields_and_params())[0]) == \ '<PARAM ID="awesome" arraysize="*" datatype="float" name="INPUT" unit="deg" value="[0.0 0.0]"/>' # noqa # Smoke test repr(list(self.votable.iter_groups())) # Resource assert repr(self.votable.resources) == '[</>]' class TestThroughTableData(TestParse): def setup_class(self): votable = parse(get_pkg_data_filename('data/regression.xml')) self.xmlout = bio = io.BytesIO() # W39: Bit values can not be masked with pytest.warns(W39): votable.to_xml(bio) bio.seek(0) self.votable = parse(bio) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_bit_mask(self): assert_array_equal(self.mask['bit'], [False, False, False, False, False]) def test_bitarray_mask(self): assert not np.any(self.mask['bitarray']) def test_bit_array2_mask(self): assert not np.any(self.mask['bitarray2']) def test_schema(self, tmpdir): # have to use an actual file because assert_validate_schema only works # on filenames, not file-like objects fn = str(tmpdir.join("test_through_tabledata.xml")) with open(fn, 'wb') as f: f.write(self.xmlout.getvalue()) assert_validate_schema(fn, '1.1') class TestThroughBinary(TestParse): def setup_class(self): votable = parse(get_pkg_data_filename('data/regression.xml')) votable.get_first_table().format = 'binary' self.xmlout = bio = io.BytesIO() # W39: Bit values can not be masked with pytest.warns(W39): votable.to_xml(bio) bio.seek(0) self.votable = parse(bio) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask # Masked values in bit fields don't roundtrip through the binary # representation -- that's not a bug, just a limitation, so # override the mask array checks here. def test_bit_mask(self): assert not np.any(self.mask['bit']) def test_bitarray_mask(self): assert not np.any(self.mask['bitarray']) def test_bit_array2_mask(self): assert not np.any(self.mask['bitarray2']) class TestThroughBinary2(TestParse): def setup_class(self): votable = parse(get_pkg_data_filename('data/regression.xml')) votable.version = '1.3' votable.get_first_table()._config['version_1_3_or_later'] = True votable.get_first_table().format = 'binary2' self.xmlout = bio = io.BytesIO() # W39: Bit values can not be masked with pytest.warns(W39): votable.to_xml(bio) bio.seek(0) self.votable = parse(bio) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_get_coosys_by_id(self): # No COOSYS in VOTable 1.2 or later pass def table_from_scratch(): from astropy.io.votable.tree import VOTableFile, Resource, Table, Field # Create a new VOTable file... votable = VOTableFile() # ...with one resource... resource = Resource() votable.resources.append(resource) # ... with one table table = Table(votable) resource.tables.append(table) # Define some fields table.fields.extend([ Field(votable, ID="filename", datatype="char"), Field(votable, ID="matrix", datatype="double", arraysize="2x2")]) # Now, use those field definitions to create the numpy record arrays, with # the given number of rows table.create_arrays(2) # Now table.array can be filled with data table.array[0] = ('test1.xml', [[1, 0], [0, 1]]) table.array[1] = ('test2.xml', [[0.5, 0.3], [0.2, 0.1]]) # Now write the whole thing to a file. # Note, we have to use the top-level votable file object out = io.StringIO() votable.to_xml(out) def test_open_files(): for filename in get_pkg_data_filenames('data', pattern='*.xml'): if (filename.endswith('custom_datatype.xml') or filename.endswith('timesys_errors.xml')): continue parse(filename) def test_too_many_columns(): with pytest.raises(VOTableSpecError): parse(get_pkg_data_filename('data/too_many_columns.xml.gz')) def test_build_from_scratch(tmpdir): # Create a new VOTable file... votable = tree.VOTableFile() # ...with one resource... resource = tree.Resource() votable.resources.append(resource) # ... with one table table = tree.Table(votable) resource.tables.append(table) # Define some fields table.fields.extend([ tree.Field(votable, ID="filename", name='filename', datatype="char", arraysize='1'), tree.Field(votable, ID="matrix", name='matrix', datatype="double", arraysize="2x2")]) # Now, use those field definitions to create the numpy record arrays, with # the given number of rows table.create_arrays(2) # Now table.array can be filled with data table.array[0] = ('test1.xml', [[1, 0], [0, 1]]) table.array[1] = ('test2.xml', [[0.5, 0.3], [0.2, 0.1]]) # Now write the whole thing to a file. # Note, we have to use the top-level votable file object votable.to_xml(str(tmpdir.join("new_votable.xml"))) votable = parse(str(tmpdir.join("new_votable.xml"))) table = votable.get_first_table() assert_array_equal( table.array.mask, np.array([(False, [[False, False], [False, False]]), (False, [[False, False], [False, False]])], dtype=[('filename', '?'), ('matrix', '?', (2, 2))])) def test_validate(test_path_object=False): """ test_path_object is needed for test below ``test_validate_path_object`` so that file could be passed as pathlib.Path object. """ output = io.StringIO() fpath = get_pkg_data_filename('data/regression.xml') if test_path_object: fpath = pathlib.Path(fpath) # We can't test xmllint, because we can't rely on it being on the # user's machine. result = validate(fpath, output, xmllint=False) assert result is False output.seek(0) output = output.readlines() # Uncomment to generate new groundtruth # with open('validation.txt', 'wt', encoding='utf-8') as fd: # fd.write(u''.join(output)) with open( get_pkg_data_filename('data/validation.txt'), 'rt', encoding='utf-8') as fd: truth = fd.readlines() truth = truth[1:] output = output[1:-1] sys.stdout.writelines( difflib.unified_diff(truth, output, fromfile='truth', tofile='output')) assert truth == output @mock.patch('subprocess.Popen') def test_validate_xmllint_true(mock_subproc_popen): process_mock = mock.Mock() attrs = {'communicate.return_value': ('ok', 'ko'), 'returncode': 0} process_mock.configure_mock(**attrs) mock_subproc_popen.return_value = process_mock assert validate(get_pkg_data_filename('data/empty_table.xml'), xmllint=True) def test_validate_path_object(): """ Validating when source is passed as path object. (#4412) """ test_validate(test_path_object=True) def test_gzip_filehandles(tmpdir): votable = parse(get_pkg_data_filename('data/regression.xml')) # W39: Bit values can not be masked with pytest.warns(W39): with open(str(tmpdir.join("regression.compressed.xml")), 'wb') as fd: votable.to_xml(fd, compressed=True, _astropy_version="testing") with open(str(tmpdir.join("regression.compressed.xml")), 'rb') as fd: votable = parse(fd) def test_from_scratch_example(): _run_test_from_scratch_example() def _run_test_from_scratch_example(): from astropy.io.votable.tree import VOTableFile, Resource, Table, Field # Create a new VOTable file... votable = VOTableFile() # ...with one resource... resource = Resource() votable.resources.append(resource) # ... with one table table = Table(votable) resource.tables.append(table) # Define some fields table.fields.extend([ Field(votable, name="filename", datatype="char", arraysize="*"), Field(votable, name="matrix", datatype="double", arraysize="2x2")]) # Now, use those field definitions to create the numpy record arrays, with # the given number of rows table.create_arrays(2) # Now table.array can be filled with data table.array[0] = ('test1.xml', [[1, 0], [0, 1]]) table.array[1] = ('test2.xml', [[0.5, 0.3], [0.2, 0.1]]) assert table.array[0][0] == 'test1.xml' def test_fileobj(): # Assert that what we get back is a raw C file pointer # so it will be super fast in the C extension. from astropy.utils.xml import iterparser filename = get_pkg_data_filename('data/regression.xml') with iterparser._convert_to_fd_or_read_function(filename) as fd: if sys.platform == 'win32': fd() else: assert isinstance(fd, io.FileIO) def test_nonstandard_units(): from astropy import units as u votable = parse(get_pkg_data_filename('data/nonstandard_units.xml')) assert isinstance( votable.get_first_table().fields[0].unit, u.UnrecognizedUnit) votable = parse(get_pkg_data_filename('data/nonstandard_units.xml'), unit_format='generic') assert not isinstance( votable.get_first_table().fields[0].unit, u.UnrecognizedUnit) def test_resource_structure(): # Based on issue #1223, as reported by @astro-friedel and @RayPlante from astropy.io.votable import tree as vot vtf = vot.VOTableFile() r1 = vot.Resource() vtf.resources.append(r1) t1 = vot.Table(vtf) t1.name = "t1" t2 = vot.Table(vtf) t2.name = 't2' r1.tables.append(t1) r1.tables.append(t2) r2 = vot.Resource() vtf.resources.append(r2) t3 = vot.Table(vtf) t3.name = "t3" t4 = vot.Table(vtf) t4.name = "t4" r2.tables.append(t3) r2.tables.append(t4) r3 = vot.Resource() vtf.resources.append(r3) t5 = vot.Table(vtf) t5.name = "t5" t6 = vot.Table(vtf) t6.name = "t6" r3.tables.append(t5) r3.tables.append(t6) buff = io.BytesIO() vtf.to_xml(buff) buff.seek(0) vtf2 = parse(buff) assert len(vtf2.resources) == 3 for r in range(len(vtf2.resources)): res = vtf2.resources[r] assert len(res.tables) == 2 assert len(res.resources) == 0 def test_no_resource_check(): output = io.StringIO() # We can't test xmllint, because we can't rely on it being on the # user's machine. result = validate(get_pkg_data_filename('data/no_resource.xml'), output, xmllint=False) assert result is False output.seek(0) output = output.readlines() # Uncomment to generate new groundtruth # with open('no_resource.txt', 'wt', encoding='utf-8') as fd: # fd.write(u''.join(output)) with open( get_pkg_data_filename('data/no_resource.txt'), 'rt', encoding='utf-8') as fd: truth = fd.readlines() truth = truth[1:] output = output[1:-1] sys.stdout.writelines( difflib.unified_diff(truth, output, fromfile='truth', tofile='output')) assert truth == output def test_instantiate_vowarning(): # This used to raise a deprecation exception. # See https://github.com/astropy/astroquery/pull/276 VOWarning(()) def test_custom_datatype(): votable = parse(get_pkg_data_filename('data/custom_datatype.xml'), datatype_mapping={'bar': 'int'}) table = votable.get_first_table() assert table.array.dtype['foo'] == np.int32 def _timesys_tests(votable): assert len(list(votable.iter_timesys())) == 4 timesys = votable.get_timesys_by_id('time_frame') assert timesys.timeorigin == 2455197.5 assert timesys.timescale == 'TCB' assert timesys.refposition == 'BARYCENTER' timesys = votable.get_timesys_by_id('mjd_origin') assert timesys.timeorigin == 'MJD-origin' assert timesys.timescale == 'TDB' assert timesys.refposition == 'EMBARYCENTER' timesys = votable.get_timesys_by_id('jd_origin') assert timesys.timeorigin == 'JD-origin' assert timesys.timescale == 'TT' assert timesys.refposition == 'HELIOCENTER' timesys = votable.get_timesys_by_id('no_origin') assert timesys.timeorigin is None assert timesys.timescale == 'UTC' assert timesys.refposition == 'TOPOCENTER' def test_timesys(): votable = parse(get_pkg_data_filename('data/timesys.xml')) _timesys_tests(votable) def test_timesys_roundtrip(): orig_votable = parse(get_pkg_data_filename('data/timesys.xml')) bio = io.BytesIO() orig_votable.to_xml(bio) bio.seek(0) votable = parse(bio) _timesys_tests(votable) def test_timesys_errors(): output = io.StringIO() validate(get_pkg_data_filename('data/timesys_errors.xml'), output, xmllint=False) outstr = output.getvalue() assert("E23: Invalid timeorigin attribute 'bad-origin'" in outstr) assert("E22: ID attribute is required for all TIMESYS elements" in outstr) assert("W48: Unknown attribute 'refposition_mispelled' on TIMESYS" in outstr)
bsd-3-clause
Mirdrack/4chanscrapper
lib/python2.7/site-packages/requests/status_codes.py
926
3200
# -*- coding: utf-8 -*- from .structures import LookupDict _codes = { # Informational. 100: ('continue',), 101: ('switching_protocols',), 102: ('processing',), 103: ('checkpoint',), 122: ('uri_too_long', 'request_uri_too_long'), 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'), 201: ('created',), 202: ('accepted',), 203: ('non_authoritative_info', 'non_authoritative_information'), 204: ('no_content',), 205: ('reset_content', 'reset'), 206: ('partial_content', 'partial'), 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'), 208: ('already_reported',), 226: ('im_used',), # Redirection. 300: ('multiple_choices',), 301: ('moved_permanently', 'moved', '\\o-'), 302: ('found',), 303: ('see_other', 'other'), 304: ('not_modified',), 305: ('use_proxy',), 306: ('switch_proxy',), 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 308: ('permanent_redirect', 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 # Client Error. 400: ('bad_request', 'bad'), 401: ('unauthorized',), 402: ('payment_required', 'payment'), 403: ('forbidden',), 404: ('not_found', '-o-'), 405: ('method_not_allowed', 'not_allowed'), 406: ('not_acceptable',), 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'), 408: ('request_timeout', 'timeout'), 409: ('conflict',), 410: ('gone',), 411: ('length_required',), 412: ('precondition_failed', 'precondition'), 413: ('request_entity_too_large',), 414: ('request_uri_too_large',), 415: ('unsupported_media_type', 'unsupported_media', 'media_type'), 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'), 417: ('expectation_failed',), 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'), 422: ('unprocessable_entity', 'unprocessable'), 423: ('locked',), 424: ('failed_dependency', 'dependency'), 425: ('unordered_collection', 'unordered'), 426: ('upgrade_required', 'upgrade'), 428: ('precondition_required', 'precondition'), 429: ('too_many_requests', 'too_many'), 431: ('header_fields_too_large', 'fields_too_large'), 444: ('no_response', 'none'), 449: ('retry_with', 'retry'), 450: ('blocked_by_windows_parental_controls', 'parental_controls'), 451: ('unavailable_for_legal_reasons', 'legal_reasons'), 499: ('client_closed_request',), # Server Error. 500: ('internal_server_error', 'server_error', '/o\\', '✗'), 501: ('not_implemented',), 502: ('bad_gateway',), 503: ('service_unavailable', 'unavailable'), 504: ('gateway_timeout',), 505: ('http_version_not_supported', 'http_version'), 506: ('variant_also_negotiates',), 507: ('insufficient_storage',), 509: ('bandwidth_limit_exceeded', 'bandwidth'), 510: ('not_extended',), } codes = LookupDict(name='status_codes') for (code, titles) in list(_codes.items()): for title in titles: setattr(codes, title, code) if not title.startswith('\\'): setattr(codes, title.upper(), code)
mit
tardis-sn/tardis
tardis/montecarlo/montecarlo_numba/interaction.py
1
4192
from numba import njit from tardis.montecarlo.montecarlo_numba import njit_dict, njit_dict_no_parallel from tardis.montecarlo.montecarlo_numba.numba_interface import ( LineInteractionType, ) from tardis.montecarlo import ( montecarlo_configuration as montecarlo_configuration, ) from tardis.montecarlo.montecarlo_numba.frame_transformations import ( get_doppler_factor, get_inverse_doppler_factor, angle_aberration_CMF_to_LF, ) from tardis.montecarlo.montecarlo_numba.r_packet import ( InteractionType, ) from tardis.montecarlo.montecarlo_numba.utils import get_random_mu from tardis.montecarlo.montecarlo_numba.macro_atom import macro_atom @njit(**njit_dict_no_parallel) def thomson_scatter(r_packet, time_explosion): """ Thomson scattering — no longer line scattering \n1) get the doppler factor at that position with the old angle \n2) convert the current energy and nu into the comoving frame with the old mu \n3) Scatter and draw new mu - update mu \n4) Transform the comoving energy and nu back using the new mu Parameters ---------- r_packet : tardis.montecarlo.montecarlo_numba.r_packet.RPacket time_explosion : float time since explosion in seconds """ old_doppler_factor = get_doppler_factor( r_packet.r, r_packet.mu, time_explosion ) comov_nu = r_packet.nu * old_doppler_factor comov_energy = r_packet.energy * old_doppler_factor r_packet.mu = get_random_mu() inverse_new_doppler_factor = get_inverse_doppler_factor( r_packet.r, r_packet.mu, time_explosion ) r_packet.nu = comov_nu * inverse_new_doppler_factor r_packet.energy = comov_energy * inverse_new_doppler_factor if montecarlo_configuration.full_relativity: r_packet.mu = angle_aberration_CMF_to_LF( r_packet, time_explosion, r_packet.mu ) @njit(**njit_dict_no_parallel) def line_scatter(r_packet, time_explosion, line_interaction_type, numba_plasma): """ Line scatter function that handles the scattering itself, including new angle drawn, and calculating nu out using macro atom Parameters ---------- r_packet : tardis.montecarlo.montecarlo_numba.r_packet.RPacket time_explosion : float line_interaction_type : enum numba_plasma : tardis.montecarlo.montecarlo_numba.numba_interface.NumbaPlasma """ old_doppler_factor = get_doppler_factor( r_packet.r, r_packet.mu, time_explosion ) r_packet.mu = get_random_mu() inverse_new_doppler_factor = get_inverse_doppler_factor( r_packet.r, r_packet.mu, time_explosion ) comov_energy = r_packet.energy * old_doppler_factor r_packet.energy = comov_energy * inverse_new_doppler_factor if line_interaction_type == LineInteractionType.SCATTER: line_emission( r_packet, r_packet.next_line_id, time_explosion, numba_plasma ) else: # includes both macro atom and downbranch - encoded in the transition probabilities emission_line_id = macro_atom(r_packet, numba_plasma) line_emission(r_packet, emission_line_id, time_explosion, numba_plasma) @njit(**njit_dict_no_parallel) def line_emission(r_packet, emission_line_id, time_explosion, numba_plasma): """ Sets the frequency of the RPacket properly given the emission channel Parameters ---------- r_packet : tardis.montecarlo.montecarlo_numba.r_packet.RPacket emission_line_id : int time_explosion : float numba_plasma : tardis.montecarlo.montecarlo_numba.numba_interface.NumbaPlasma """ r_packet.last_line_interaction_out_id = emission_line_id if emission_line_id != r_packet.next_line_id: pass inverse_doppler_factor = get_inverse_doppler_factor( r_packet.r, r_packet.mu, time_explosion ) r_packet.nu = ( numba_plasma.line_list_nu[emission_line_id] * inverse_doppler_factor ) r_packet.next_line_id = emission_line_id + 1 nu_line = numba_plasma.line_list_nu[emission_line_id] if montecarlo_configuration.full_relativity: r_packet.mu = angle_aberration_CMF_to_LF( r_packet, time_explosion, r_packet.mu )
bsd-3-clause
Sodki/ansible
lib/ansible/modules/cloud/vmware/vsphere_copy.py
36
6516
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2015 Dag Wieers <dag@wieers.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: vsphere_copy short_description: Copy a file to a vCenter datastore description: - Upload files to a vCenter datastore version_added: 2.0 author: Dag Wieers (@dagwieers) <dag@wieers.com> options: host: description: - The vCenter server on which the datastore is available. required: true login: description: - The login name to authenticate on the vCenter server. required: true password: description: - The password to authenticate on the vCenter server. required: true src: description: - The file to push to vCenter required: true datacenter: description: - The datacenter on the vCenter server that holds the datastore. required: true datastore: description: - The datastore on the vCenter server to push files to. required: true path: description: - The file to push to the datastore on the vCenter server. required: true validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be set to C(no) when no other option exists. required: false default: 'yes' choices: ['yes', 'no'] notes: - "This module ought to be run from a system that can access vCenter directly and has the file to transfer. It can be the normal remote target or you can change it either by using C(transport: local) or using C(delegate_to)." - Tested on vSphere 5.5 ''' EXAMPLES = ''' - vsphere_copy: host: vhost login: vuser password: vpass src: /some/local/file datacenter: DC1 Someplace datastore: datastore1 path: some/remote/file transport: local - vsphere_copy: host: vhost login: vuser password: vpass src: /other/local/file datacenter: DC2 Someplace datastore: datastore2 path: other/remote/file delegate_to: other_system ''' import atexit import urllib import mmap import errno import socket from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.urls import open_url def vmware_path(datastore, datacenter, path): ''' Constructs a URL path that VSphere accepts reliably ''' path = "/folder/%s" % path.lstrip("/") # Due to a software bug in vSphere, it fails to handle ampersand in datacenter names # The solution is to do what vSphere does (when browsing) and double-encode ampersands, maybe others ? datacenter = datacenter.replace('&', '%26') if not path.startswith("/"): path = "/" + path params = dict( dsName = datastore ) if datacenter: params["dcPath"] = datacenter params = urllib.urlencode(params) return "%s?%s" % (path, params) def main(): module = AnsibleModule( argument_spec = dict( host = dict(required=True, aliases=[ 'hostname' ]), login = dict(required=True, aliases=[ 'username' ]), password = dict(required=True, no_log=True), src = dict(required=True, aliases=[ 'name' ]), datacenter = dict(required=True), datastore = dict(required=True), dest = dict(required=True, aliases=[ 'path' ]), validate_certs = dict(required=False, default=True, type='bool'), ), # Implementing check-mode using HEAD is impossible, since size/date is not 100% reliable supports_check_mode = False, ) host = module.params.get('host') login = module.params.get('login') password = module.params.get('password') src = module.params.get('src') datacenter = module.params.get('datacenter') datastore = module.params.get('datastore') dest = module.params.get('dest') validate_certs = module.params.get('validate_certs') fd = open(src, "rb") atexit.register(fd.close) data = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ) atexit.register(data.close) remote_path = vmware_path(datastore, datacenter, dest) url = 'https://%s%s' % (host, remote_path) headers = { "Content-Type": "application/octet-stream", "Content-Length": str(len(data)), } try: r = open_url(url, data=data, headers=headers, method='PUT', url_username=login, url_password=password, validate_certs=validate_certs, force_basic_auth=True) except socket.error: e = get_exception() if isinstance(e.args, tuple) and e[0] == errno.ECONNRESET: # VSphere resets connection if the file is in use and cannot be replaced module.fail_json(msg='Failed to upload, image probably in use', status=None, errno=e[0], reason=str(e), url=url) else: module.fail_json(msg=str(e), status=None, errno=e[0], reason=str(e), url=url) except Exception: e = get_exception() error_code = -1 try: if isinstance(e[0], int): error_code = e[0] except KeyError: pass module.fail_json(msg=str(e), status=None, errno=error_code, reason=str(e), url=url) status = r.getcode() if 200 <= status < 300: module.exit_json(changed=True, status=status, reason=r.msg, url=url) else: length = r.headers.get('content-length', None) if r.headers.get('transfer-encoding', '').lower() == 'chunked': chunked = 1 else: chunked = 0 module.fail_json(msg='Failed to upload', errno=None, status=status, reason=r.msg, length=length, headers=dict(r.headers), chunked=chunked, url=url) if __name__ == '__main__': main()
gpl-3.0
wizardofwhimsy/wizardofwhimsy.github.io
vendor/bundle/ruby/2.7.0/gems/ffi-1.12.2/ext/ffi_c/libffi/generate-darwin-source-and-headers.py
22
6531
#!/usr/bin/env python import subprocess import os import errno import collections import glob import argparse class Platform(object): pass class simulator_platform(Platform): directory = 'darwin_ios' sdk = 'iphonesimulator' arch = 'i386' triple = 'i386-apple-darwin11' version_min = '-miphoneos-version-min=7.0' prefix = "#ifdef __i386__\n\n" suffix = "\n\n#endif" src_dir = 'x86' src_files = ['sysv.S', 'ffi.c', 'internal.h'] class simulator64_platform(Platform): directory = 'darwin_ios' sdk = 'iphonesimulator' arch = 'x86_64' triple = 'x86_64-apple-darwin13' version_min = '-miphoneos-version-min=7.0' prefix = "#ifdef __x86_64__\n\n" suffix = "\n\n#endif" src_dir = 'x86' src_files = ['unix64.S', 'ffi64.c', 'ffiw64.c', 'win64.S', 'internal64.h', 'asmnames.h'] class device_platform(Platform): directory = 'darwin_ios' sdk = 'iphoneos' arch = 'armv7' triple = 'arm-apple-darwin11' version_min = '-miphoneos-version-min=7.0' prefix = "#ifdef __arm__\n\n" suffix = "\n\n#endif" src_dir = 'arm' src_files = ['sysv.S', 'ffi.c', 'internal.h'] class device64_platform(Platform): directory = 'darwin_ios' sdk = 'iphoneos' arch = 'arm64' triple = 'aarch64-apple-darwin13' version_min = '-miphoneos-version-min=7.0' prefix = "#ifdef __arm64__\n\n" suffix = "\n\n#endif" src_dir = 'aarch64' src_files = ['sysv.S', 'ffi.c', 'internal.h'] class desktop32_platform(Platform): directory = 'darwin_osx' sdk = 'macosx' arch = 'i386' triple = 'i386-apple-darwin10' version_min = '-mmacosx-version-min=10.6' src_dir = 'x86' src_files = ['sysv.S', 'ffi.c', 'internal.h'] prefix = "#ifdef __i386__\n\n" suffix = "\n\n#endif" class desktop64_platform(Platform): directory = 'darwin_osx' sdk = 'macosx' arch = 'x86_64' triple = 'x86_64-apple-darwin10' version_min = '-mmacosx-version-min=10.6' prefix = "#ifdef __x86_64__\n\n" suffix = "\n\n#endif" src_dir = 'x86' src_files = ['unix64.S', 'ffi64.c', 'ffiw64.c', 'win64.S', 'internal64.h', 'asmnames.h'] def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno != errno.EEXIST: raise def move_file(src_dir, dst_dir, filename, file_suffix=None, prefix='', suffix=''): mkdir_p(dst_dir) out_filename = filename if file_suffix: if filename in ['internal64.h', 'asmnames.h', 'internal.h']: out_filename = filename else: split_name = os.path.splitext(filename) out_filename = "%s_%s%s" % (split_name[0], file_suffix, split_name[1]) with open(os.path.join(src_dir, filename)) as in_file: with open(os.path.join(dst_dir, out_filename), 'w') as out_file: if prefix: out_file.write(prefix) out_file.write(in_file.read()) if suffix: out_file.write(suffix) def list_files(src_dir, pattern=None, filelist=None): if pattern: filelist = glob.iglob(os.path.join(src_dir, pattern)) for file in filelist: yield os.path.basename(file) def copy_files(src_dir, dst_dir, pattern=None, filelist=None, file_suffix=None, prefix=None, suffix=None): for filename in list_files(src_dir, pattern=pattern, filelist=filelist): move_file(src_dir, dst_dir, filename, file_suffix=file_suffix, prefix=prefix, suffix=suffix) def copy_src_platform_files(platform): src_dir = os.path.join('src', platform.src_dir) dst_dir = os.path.join(platform.directory, 'src', platform.src_dir) copy_files(src_dir, dst_dir, filelist=platform.src_files, file_suffix=platform.arch, prefix=platform.prefix, suffix=platform.suffix) def build_target(platform, platform_headers): def xcrun_cmd(cmd): return 'xcrun -sdk %s %s -arch %s' % (platform.sdk, cmd, platform.arch) tag='%s-%s' % (platform.sdk, platform.arch) build_dir = 'build_%s' % tag mkdir_p(build_dir) env = dict(CC=xcrun_cmd('clang'), LD=xcrun_cmd('ld'), CFLAGS='%s -fembed-bitcode' % (platform.version_min)) working_dir = os.getcwd() try: os.chdir(build_dir) subprocess.check_call(['../configure', '-host', platform.triple], env=env) finally: os.chdir(working_dir) for src_dir in [build_dir, os.path.join(build_dir, 'include')]: copy_files(src_dir, os.path.join(platform.directory, 'include'), pattern='*.h', file_suffix=platform.arch, prefix=platform.prefix, suffix=platform.suffix) for filename in list_files(src_dir, pattern='*.h'): platform_headers[filename].add((platform.prefix, platform.arch, platform.suffix)) def generate_source_and_headers(generate_osx=True, generate_ios=True): copy_files('src', 'darwin_common/src', pattern='*.c') copy_files('include', 'darwin_common/include', pattern='*.h') if generate_ios: copy_src_platform_files(simulator_platform) copy_src_platform_files(simulator64_platform) copy_src_platform_files(device_platform) copy_src_platform_files(device64_platform) if generate_osx: copy_src_platform_files(desktop64_platform) platform_headers = collections.defaultdict(set) if generate_ios: build_target(simulator_platform, platform_headers) build_target(simulator64_platform, platform_headers) build_target(device_platform, platform_headers) build_target(device64_platform, platform_headers) if generate_osx: build_target(desktop64_platform, platform_headers) mkdir_p('darwin_common/include') for header_name, tag_tuples in platform_headers.iteritems(): basename, suffix = os.path.splitext(header_name) with open(os.path.join('darwin_common/include', header_name), 'w') as header: for tag_tuple in tag_tuples: header.write('%s#include <%s_%s%s>\n%s\n' % (tag_tuple[0], basename, tag_tuple[1], suffix, tag_tuple[2])) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--only-ios', action='store_true', default=False) parser.add_argument('--only-osx', action='store_true', default=False) args = parser.parse_args() generate_source_and_headers(generate_osx=not args.only_ios, generate_ios=not args.only_osx)
mit
anryko/ansible
lib/ansible/modules/network/fortios/fortios_log_memory_setting.py
7
8901
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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 <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_log_memory_setting short_description: Settings for memory buffer in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify log_memory feature and setting category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true version_added: 2.9 log_memory_setting: description: - Settings for memory buffer. default: null type: dict suboptions: diskfull: description: - Action to take when memory is full. type: str choices: - overwrite status: description: - Enable/disable logging to the FortiGate's memory. type: str choices: - enable - disable ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Settings for memory buffer. fortios_log_memory_setting: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" log_memory_setting: diskfull: "overwrite" status: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_log_memory_setting_data(json): option_list = ['diskfull', 'status'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for i, elem in enumerate(data): data[i] = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def log_memory_setting(data, fos): vdom = data['vdom'] log_memory_setting_data = data['log_memory_setting'] filtered_data = underscore_to_hyphen(filter_log_memory_setting_data(log_memory_setting_data)) return fos.set('log.memory', 'setting', data=filtered_data, vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_log_memory(data, fos): if data['log_memory_setting']: resp = log_memory_setting(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "log_memory_setting": { "required": False, "type": "dict", "default": None, "options": { "diskfull": {"required": False, "type": "str", "choices": ["overwrite"]}, "status": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_log_memory(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_log_memory(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
gpl-3.0
XiaodunServerGroup/ddyedx
cms/djangoapps/contentstore/management/commands/tests/test_rollback_split_course.py
17
4146
""" Unittests for deleting a split mongo course """ import unittest from StringIO import StringIO from mock import patch from django.contrib.auth.models import User from django.core.management import CommandError, call_command from django.test.utils import override_settings from contentstore.management.commands.rollback_split_course import Command from contentstore.tests.modulestore_config import TEST_MODULESTORE from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.persistent_factories import PersistentCourseFactory from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.django import modulestore, loc_mapper from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.split_migrator import SplitMigrator # pylint: disable=E1101 class TestArgParsing(unittest.TestCase): """ Tests for parsing arguments for the `rollback_split_course` management command """ def setUp(self): self.command = Command() def test_no_args(self): errstring = "rollback_split_course requires at least one argument" with self.assertRaisesRegexp(CommandError, errstring): self.command.handle() def test_invalid_locator(self): errstring = "Invalid locator string !?!" with self.assertRaisesRegexp(CommandError, errstring): self.command.handle("!?!") @override_settings(MODULESTORE=TEST_MODULESTORE) class TestRollbackSplitCourseNoOldMongo(ModuleStoreTestCase): """ Unit tests for rolling back a split-mongo course from command line, where the course doesn't exist in the old mongo store """ def setUp(self): super(TestRollbackSplitCourseNoOldMongo, self).setUp() self.course = PersistentCourseFactory() def test_no_old_course(self): locator = self.course.location errstring = "course does not exist in the old Mongo store" with self.assertRaisesRegexp(CommandError, errstring): Command().handle(str(locator)) @override_settings(MODULESTORE=TEST_MODULESTORE) class TestRollbackSplitCourseNoSplitMongo(ModuleStoreTestCase): """ Unit tests for rolling back a split-mongo course from command line, where the course doesn't exist in the split mongo store """ def setUp(self): super(TestRollbackSplitCourseNoSplitMongo, self).setUp() self.old_course = CourseFactory() def test_nonexistent_locator(self): locator = loc_mapper().translate_location(self.old_course.id, self.old_course.location) errstring = "No course found with locator" with self.assertRaisesRegexp(CommandError, errstring): Command().handle(str(locator)) @override_settings(MODULESTORE=TEST_MODULESTORE) class TestRollbackSplitCourse(ModuleStoreTestCase): """ Unit tests for rolling back a split-mongo course from command line """ def setUp(self): super(TestRollbackSplitCourse, self).setUp() self.old_course = CourseFactory() uname = 'testuser' email = 'test+courses@edx.org' password = 'foo' self.user = User.objects.create_user(uname, email, password) # migrate old course to split migrator = SplitMigrator( draft_modulestore=modulestore('default'), direct_modulestore=modulestore('direct'), split_modulestore=modulestore('split'), loc_mapper=loc_mapper(), ) migrator.migrate_mongo_course(self.old_course.location, self.user) locator = loc_mapper().translate_location(self.old_course.id, self.old_course.location) self.course = modulestore('split').get_course(locator) @patch("sys.stdout", new_callable=StringIO) def test_happy_path(self, mock_stdout): locator = self.course.location call_command( "rollback_split_course", str(locator), ) with self.assertRaises(ItemNotFoundError): modulestore('split').get_course(locator) self.assertIn("Course rolled back successfully", mock_stdout.getvalue())
agpl-3.0
plotly/python-api
packages/python/plotly/plotly/tests/test_core/test_optional_imports/test_optional_imports.py
2
1848
from __future__ import absolute_import import sys from unittest import TestCase from plotly.optional_imports import get_module class OptionalImportsTest(TestCase): def test_get_module_exists(self): import math module = get_module("math") self.assertIsNotNone(module) self.assertEqual(math, module) def test_get_module_exists_submodule(self): import requests.sessions module = get_module("requests.sessions") self.assertIsNotNone(module) self.assertEqual(requests.sessions, module) def test_get_module_does_not_exist(self): module = get_module("hoopla") self.assertIsNone(module) def test_get_module_import_exception(self): # Get module that raises an exception on import module_str = "plotly.tests.test_core." "test_optional_imports.exploding_module" if sys.version_info >= (3, 4): with self.assertLogs("_plotly_utils.optional_imports", level="ERROR") as cm: module = get_module(module_str) # No exception should be raised and None should be returned self.assertIsNone(module) # Check logging level and log message expected_start = ( "ERROR:_plotly_utils.optional_imports:" "Error importing optional module " + module_str ) self.assertEqual(cm.output[0][: len(expected_start)], expected_start) # Check that exception message is included after log message expected_end = "Boom!" self.assertEqual(cm.output[0][-len(expected_end) :], expected_end) else: # Don't check logging module = get_module(module_str) # No exception should be raised and None should be returned self.assertIsNone(module)
mit
elastic-coders/aiohttp
aiohttp/protocol.py
3
28891
"""Http related parsers and protocol.""" import collections import functools import http.server import re import string import sys import zlib from abc import abstractmethod, ABC from wsgiref.handlers import format_date_time from multidict import CIMultiDict, upstr import aiohttp from . import errors, hdrs from .log import internal_logger from .helpers import reify __all__ = ('HttpMessage', 'Request', 'Response', 'HttpVersion', 'HttpVersion10', 'HttpVersion11', 'RawRequestMessage', 'RawResponseMessage', 'HttpPrefixParser', 'HttpRequestParser', 'HttpResponseParser', 'HttpPayloadParser') ASCIISET = set(string.printable) METHRE = re.compile('[A-Z0-9$-_.]+') VERSRE = re.compile('HTTP/(\d+).(\d+)') HDRRE = re.compile(b'[\x00-\x1F\x7F()<>@,;:\[\]={} \t\\\\\"]') EOF_MARKER = object() EOL_MARKER = object() STATUS_LINE_READY = object() RESPONSES = http.server.BaseHTTPRequestHandler.responses HttpVersion = collections.namedtuple( 'HttpVersion', ['major', 'minor']) HttpVersion10 = HttpVersion(1, 0) HttpVersion11 = HttpVersion(1, 1) RawStatusLineMessage = collections.namedtuple( 'RawStatusLineMessage', ['method', 'path', 'version']) RawRequestMessage = collections.namedtuple( 'RawRequestMessage', ['method', 'path', 'version', 'headers', 'raw_headers', 'should_close', 'compression']) RawResponseMessage = collections.namedtuple( 'RawResponseMessage', ['version', 'code', 'reason', 'headers', 'raw_headers', 'should_close', 'compression']) class HttpParser: def __init__(self, max_line_size=8190, max_headers=32768, max_field_size=8190): self.max_line_size = max_line_size self.max_headers = max_headers self.max_field_size = max_field_size def parse_headers(self, lines): """Parses RFC 5322 headers from a stream. Line continuations are supported. Returns list of header name and value pairs. Header name is in upper case. """ close_conn = None encoding = None headers = CIMultiDict() raw_headers = [] lines_idx = 1 line = lines[1] while line: header_length = len(line) # Parse initial header name : value pair. try: bname, bvalue = line.split(b':', 1) except ValueError: raise errors.InvalidHeader(line) from None bname = bname.strip(b' \t').upper() if HDRRE.search(bname): raise errors.InvalidHeader(bname) # next line lines_idx += 1 line = lines[lines_idx] # consume continuation lines continuation = line and line[0] in (32, 9) # (' ', '\t') if continuation: bvalue = [bvalue] while continuation: header_length += len(line) if header_length > self.max_field_size: raise errors.LineTooLong( 'limit request headers fields size') bvalue.append(line) # next line lines_idx += 1 line = lines[lines_idx] continuation = line[0] in (32, 9) # (' ', '\t') bvalue = b'\r\n'.join(bvalue) else: if header_length > self.max_field_size: raise errors.LineTooLong( 'limit request headers fields size') bvalue = bvalue.strip() name = bname.decode('utf-8', 'surrogateescape') value = bvalue.decode('utf-8', 'surrogateescape') # keep-alive and encoding if name == hdrs.CONNECTION: v = value.lower() if v == 'close': close_conn = True elif v == 'keep-alive': close_conn = False elif name == hdrs.CONTENT_ENCODING: enc = value.lower() if enc in ('gzip', 'deflate'): encoding = enc headers.add(name, value) raw_headers.append((bname, bvalue)) return headers, raw_headers, close_conn, encoding class HttpPrefixParser: """Waits for 'HTTP' prefix (non destructive)""" def __init__(self, allowed_methods=()): self.allowed_methods = [m.upper() for m in allowed_methods] def __call__(self, out, buf): raw_data = yield from buf.waituntil(b' ', 12) method = raw_data.decode('ascii', 'surrogateescape').strip() # method method = method.upper() if not METHRE.match(method): raise errors.BadStatusLine(method) # allowed method if self.allowed_methods and method not in self.allowed_methods: raise errors.HttpMethodNotAllowed(message=method) out.feed_data(method, len(method)) out.feed_eof() class HttpRequestParser(HttpParser): """Read request status line. Exception errors.BadStatusLine could be raised in case of any errors in status line. Returns RawRequestMessage. """ def __call__(self, out, buf): # read HTTP message (request line + headers) try: raw_data = yield from buf.readuntil( b'\r\n\r\n', self.max_headers) except errors.LineLimitExceededParserError as exc: raise errors.LineTooLong(exc.limit) from None lines = raw_data.split(b'\r\n') # request line line = lines[0].decode('utf-8', 'surrogateescape') try: method, path, version = line.split(None, 2) except ValueError: raise errors.BadStatusLine(line) from None # method method = method.upper() if not METHRE.match(method): raise errors.BadStatusLine(method) # version try: if version.startswith('HTTP/'): n1, n2 = version[5:].split('.', 1) version = HttpVersion(int(n1), int(n2)) else: raise errors.BadStatusLine(version) except: raise errors.BadStatusLine(version) # read headers headers, raw_headers, close, compression = self.parse_headers(lines) if close is None: # then the headers weren't set in the request if version <= HttpVersion10: # HTTP 1.0 must asks to not close close = True else: # HTTP 1.1 must ask to close. close = False out.feed_data( RawRequestMessage( method, path, version, headers, raw_headers, close, compression), len(raw_data)) out.feed_eof() class HttpResponseParser(HttpParser): """Read response status line and headers. BadStatusLine could be raised in case of any errors in status line. Returns RawResponseMessage""" def __call__(self, out, buf): # read HTTP message (response line + headers) try: raw_data = yield from buf.readuntil( b'\r\n\r\n', self.max_line_size + self.max_headers) except errors.LineLimitExceededParserError as exc: raise errors.LineTooLong(exc.limit) from None lines = raw_data.split(b'\r\n') line = lines[0].decode('utf-8', 'surrogateescape') try: version, status = line.split(None, 1) except ValueError: raise errors.BadStatusLine(line) from None else: try: status, reason = status.split(None, 1) except ValueError: reason = '' # version match = VERSRE.match(version) if match is None: raise errors.BadStatusLine(line) version = HttpVersion(int(match.group(1)), int(match.group(2))) # The status code is a three-digit number try: status = int(status) except ValueError: raise errors.BadStatusLine(line) from None if status < 100 or status > 999: raise errors.BadStatusLine(line) # read headers headers, raw_headers, close, compression = self.parse_headers(lines) if close is None: close = version <= HttpVersion10 out.feed_data( RawResponseMessage( version, status, reason.strip(), headers, raw_headers, close, compression), len(raw_data)) out.feed_eof() class HttpPayloadParser: def __init__(self, message, length=None, compression=True, readall=False, response_with_body=True): self.message = message self.length = length self.compression = compression self.readall = readall self.response_with_body = response_with_body def __call__(self, out, buf): # payload params length = self.message.headers.get(hdrs.CONTENT_LENGTH, self.length) if hdrs.SEC_WEBSOCKET_KEY1 in self.message.headers: length = 8 # payload decompression wrapper if (self.response_with_body and self.compression and self.message.compression): out = DeflateBuffer(out, self.message.compression) # payload parser if not self.response_with_body: # don't parse payload if it's not expected to be received pass elif 'chunked' in self.message.headers.get( hdrs.TRANSFER_ENCODING, ''): yield from self.parse_chunked_payload(out, buf) elif length is not None: try: length = int(length) except ValueError: raise errors.InvalidHeader(hdrs.CONTENT_LENGTH) from None if length < 0: raise errors.InvalidHeader(hdrs.CONTENT_LENGTH) elif length > 0: yield from self.parse_length_payload(out, buf, length) else: if self.readall and getattr(self.message, 'code', 0) != 204: yield from self.parse_eof_payload(out, buf) elif getattr(self.message, 'method', None) in ('PUT', 'POST'): internal_logger.warning( # pragma: no cover 'Content-Length or Transfer-Encoding header is required') out.feed_eof() def parse_chunked_payload(self, out, buf): """Chunked transfer encoding parser.""" while True: # read next chunk size line = yield from buf.readuntil(b'\r\n', 8192) i = line.find(b';') if i >= 0: line = line[:i] # strip chunk-extensions else: line = line.strip() try: size = int(line, 16) except ValueError: raise errors.TransferEncodingError(line) from None if size == 0: # eof marker break # read chunk and feed buffer while size: chunk = yield from buf.readsome(size) out.feed_data(chunk, len(chunk)) size = size - len(chunk) # toss the CRLF at the end of the chunk yield from buf.skip(2) # read and discard trailer up to the CRLF terminator yield from buf.skipuntil(b'\r\n') def parse_length_payload(self, out, buf, length=0): """Read specified amount of bytes.""" required = length while required: chunk = yield from buf.readsome(required) out.feed_data(chunk, len(chunk)) required -= len(chunk) def parse_eof_payload(self, out, buf): """Read all bytes until eof.""" try: while True: chunk = yield from buf.readsome() out.feed_data(chunk, len(chunk)) except aiohttp.EofStream: pass class DeflateBuffer: """DeflateStream decompress stream and feed data into specified stream.""" def __init__(self, out, encoding): self.out = out zlib_mode = (16 + zlib.MAX_WBITS if encoding == 'gzip' else -zlib.MAX_WBITS) self.zlib = zlib.decompressobj(wbits=zlib_mode) def feed_data(self, chunk, size): try: chunk = self.zlib.decompress(chunk) except Exception: raise errors.ContentEncodingError('deflate') if chunk: self.out.feed_data(chunk, len(chunk)) def feed_eof(self): chunk = self.zlib.flush() self.out.feed_data(chunk, len(chunk)) if not self.zlib.eof: raise errors.ContentEncodingError('deflate') self.out.feed_eof() def wrap_payload_filter(func): """Wraps payload filter and piped filters. Filter is a generator that accepts arbitrary chunks of data, modify data and emit new stream of data. For example we have stream of chunks: ['1', '2', '3', '4', '5'], we can apply chunking filter to this stream: ['1', '2', '3', '4', '5'] | response.add_chunking_filter(2) | ['12', '34', '5'] It is possible to use different filters at the same time. For a example to compress incoming stream with 'deflate' encoding and then split data and emit chunks of 8192 bytes size chunks: >>> response.add_compression_filter('deflate') >>> response.add_chunking_filter(8192) Filters do not alter transfer encoding. Filter can receive types types of data, bytes object or EOF_MARKER. 1. If filter receives bytes object, it should process data and yield processed data then yield EOL_MARKER object. 2. If Filter received EOF_MARKER, it should yield remaining data (buffered) and then yield EOF_MARKER. """ @functools.wraps(func) def wrapper(self, *args, **kw): new_filter = func(self, *args, **kw) filter = self.filter if filter is not None: next(new_filter) self.filter = filter_pipe(filter, new_filter) else: self.filter = new_filter next(self.filter) return wrapper def filter_pipe(filter, filter2, *, EOF_MARKER=EOF_MARKER, EOL_MARKER=EOL_MARKER): """Creates pipe between two filters. filter_pipe() feeds first filter with incoming data and then send yielded from first filter data into filter2, results of filter2 are being emitted. 1. If filter_pipe receives bytes object, it sends it to the first filter. 2. Reads yielded values from the first filter until it receives EOF_MARKER or EOL_MARKER. 3. Each of this values is being send to second filter. 4. Reads yielded values from second filter until it receives EOF_MARKER or EOL_MARKER. Each of this values yields to writer. """ chunk = yield while True: eof = chunk is EOF_MARKER chunk = filter.send(chunk) while chunk is not EOL_MARKER: chunk = filter2.send(chunk) while chunk not in (EOF_MARKER, EOL_MARKER): yield chunk chunk = next(filter2) if chunk is not EOF_MARKER: if eof: chunk = EOF_MARKER else: chunk = next(filter) else: break chunk = yield EOL_MARKER class HttpMessage(ABC): """HttpMessage allows to write headers and payload to a stream. For example, lets say we want to read file then compress it with deflate compression and then send it with chunked transfer encoding, code may look like this: >>> response = aiohttp.Response(transport, 200) We have to use deflate compression first: >>> response.add_compression_filter('deflate') Then we want to split output stream into chunks of 1024 bytes size: >>> response.add_chunking_filter(1024) We can add headers to response with add_headers() method. add_headers() does not send data to transport, send_headers() sends request/response line and then sends headers: >>> response.add_headers( ... ('Content-Disposition', 'attachment; filename="..."')) >>> response.send_headers() Now we can use chunked writer to write stream to a network stream. First call to write() method sends response status line and headers, add_header() and add_headers() method unavailable at this stage: >>> with open('...', 'rb') as f: ... chunk = fp.read(8192) ... while chunk: ... response.write(chunk) ... chunk = fp.read(8192) >>> response.write_eof() """ writer = None # 'filter' is being used for altering write() behaviour, # add_chunking_filter adds deflate/gzip compression and # add_compression_filter splits incoming data into a chunks. filter = None HOP_HEADERS = None # Must be set by subclass. SERVER_SOFTWARE = 'Python/{0[0]}.{0[1]} aiohttp/{1}'.format( sys.version_info, aiohttp.__version__) upgrade = False # Connection: UPGRADE websocket = False # Upgrade: WEBSOCKET has_chunked_hdr = False # Transfer-encoding: chunked # subclass can enable auto sending headers with write() call, # this is useful for wsgi's start_response implementation. _send_headers = False def __init__(self, transport, version, close): self.transport = transport self._version = version self.closing = close self.keepalive = None self.chunked = False self.length = None self.headers = CIMultiDict() self.headers_sent = False self.output_length = 0 self.headers_length = 0 self._output_size = 0 @property @abstractmethod def status_line(self): return b'' @abstractmethod def autochunked(self): return False @property def version(self): return self._version @property def body_length(self): return self.output_length - self.headers_length def force_close(self): self.closing = True self.keepalive = False def enable_chunked_encoding(self): self.chunked = True def keep_alive(self): if self.keepalive is None: if self.version < HttpVersion10: # keep alive not supported at all return False if self.version == HttpVersion10: if self.headers.get(hdrs.CONNECTION) == 'keep-alive': return True else: # no headers means we close for Http 1.0 return False else: return not self.closing else: return self.keepalive def is_headers_sent(self): return self.headers_sent def add_header(self, name, value): """Analyze headers. Calculate content length, removes hop headers, etc.""" assert not self.headers_sent, 'headers have been sent already' assert isinstance(name, str), \ 'Header name should be a string, got {!r}'.format(name) assert set(name).issubset(ASCIISET), \ 'Header name should contain ASCII chars, got {!r}'.format(name) assert isinstance(value, str), \ 'Header {!r} should have string value, got {!r}'.format( name, value) name = upstr(name) value = value.strip() if name == hdrs.CONTENT_LENGTH: self.length = int(value) if name == hdrs.TRANSFER_ENCODING: self.has_chunked_hdr = value.lower().strip() == 'chunked' if name == hdrs.CONNECTION: val = value.lower() # handle websocket if 'upgrade' in val: self.upgrade = True # connection keep-alive elif 'close' in val: self.keepalive = False elif 'keep-alive' in val: self.keepalive = True elif name == hdrs.UPGRADE: if 'websocket' in value.lower(): self.websocket = True self.headers[name] = value elif name not in self.HOP_HEADERS: # ignore hop-by-hop headers self.headers.add(name, value) def add_headers(self, *headers): """Adds headers to a HTTP message.""" for name, value in headers: self.add_header(name, value) def send_headers(self, _sep=': ', _end='\r\n'): """Writes headers to a stream. Constructs payload writer.""" # Chunked response is only for HTTP/1.1 clients or newer # and there is no Content-Length header is set. # Do not use chunked responses when the response is guaranteed to # not have a response body (304, 204). assert not self.headers_sent, 'headers have been sent already' self.headers_sent = True if self.chunked or self.autochunked(): self.writer = self._write_chunked_payload() self.headers[hdrs.TRANSFER_ENCODING] = 'chunked' elif self.length is not None: self.writer = self._write_length_payload(self.length) else: self.writer = self._write_eof_payload() next(self.writer) self._add_default_headers() # status + headers headers = self.status_line + ''.join( [k + _sep + v + _end for k, v in self.headers.items()]) headers = headers.encode('utf-8') + b'\r\n' self.output_length += len(headers) self.headers_length = len(headers) self.transport.write(headers) def _add_default_headers(self): # set the connection header connection = None if self.upgrade: connection = 'upgrade' elif not self.closing if self.keepalive is None else self.keepalive: if self.version == HttpVersion10: connection = 'keep-alive' else: if self.version == HttpVersion11: connection = 'close' if connection is not None: self.headers[hdrs.CONNECTION] = connection def write(self, chunk, *, drain=False, EOF_MARKER=EOF_MARKER, EOL_MARKER=EOL_MARKER): """Writes chunk of data to a stream by using different writers. writer uses filter to modify chunk of data. write_eof() indicates end of stream. writer can't be used after write_eof() method being called. write() return drain future. """ assert (isinstance(chunk, (bytes, bytearray)) or chunk is EOF_MARKER), chunk size = self.output_length if self._send_headers and not self.headers_sent: self.send_headers() assert self.writer is not None, 'send_headers() is not called.' if self.filter: chunk = self.filter.send(chunk) while chunk not in (EOF_MARKER, EOL_MARKER): if chunk: self.writer.send(chunk) chunk = next(self.filter) else: if chunk is not EOF_MARKER: self.writer.send(chunk) self._output_size += self.output_length - size if self._output_size > 64 * 1024: if drain: self._output_size = 0 return self.transport.drain() return () def write_eof(self): self.write(EOF_MARKER) try: self.writer.throw(aiohttp.EofStream()) except StopIteration: pass return self.transport.drain() def _write_chunked_payload(self): """Write data in chunked transfer encoding.""" while True: try: chunk = yield except aiohttp.EofStream: self.transport.write(b'0\r\n\r\n') self.output_length += 5 break chunk = bytes(chunk) chunk_len = '{:x}\r\n'.format(len(chunk)).encode('ascii') self.transport.write(chunk_len + chunk + b'\r\n') self.output_length += len(chunk_len) + len(chunk) + 2 def _write_length_payload(self, length): """Write specified number of bytes to a stream.""" while True: try: chunk = yield except aiohttp.EofStream: break if length: l = len(chunk) if length >= l: self.transport.write(chunk) self.output_length += l length = length-l else: self.transport.write(chunk[:length]) self.output_length += length length = 0 def _write_eof_payload(self): while True: try: chunk = yield except aiohttp.EofStream: break self.transport.write(chunk) self.output_length += len(chunk) @wrap_payload_filter def add_chunking_filter(self, chunk_size=16*1024, *, EOF_MARKER=EOF_MARKER, EOL_MARKER=EOL_MARKER): """Split incoming stream into chunks.""" buf = bytearray() chunk = yield while True: if chunk is EOF_MARKER: if buf: yield buf yield EOF_MARKER else: buf.extend(chunk) while len(buf) >= chunk_size: chunk = bytes(buf[:chunk_size]) del buf[:chunk_size] yield chunk chunk = yield EOL_MARKER @wrap_payload_filter def add_compression_filter(self, encoding='deflate', *, EOF_MARKER=EOF_MARKER, EOL_MARKER=EOL_MARKER): """Compress incoming stream with deflate or gzip encoding.""" zlib_mode = (16 + zlib.MAX_WBITS if encoding == 'gzip' else -zlib.MAX_WBITS) zcomp = zlib.compressobj(wbits=zlib_mode) chunk = yield while True: if chunk is EOF_MARKER: yield zcomp.flush() chunk = yield EOF_MARKER else: yield zcomp.compress(chunk) chunk = yield EOL_MARKER class Response(HttpMessage): """Create HTTP response message. Transport is a socket stream transport. status is a response status code, status has to be integer value. http_version is a tuple that represents HTTP version, (1, 0) stands for HTTP/1.0 and (1, 1) is for HTTP/1.1 """ HOP_HEADERS = () @staticmethod def calc_reason(status, *, _RESPONSES=RESPONSES): record = _RESPONSES.get(status) if record is not None: reason = record[0] else: reason = str(status) return reason def __init__(self, transport, status, http_version=HttpVersion11, close=False, reason=None): super().__init__(transport, http_version, close) self._status = status if reason is None: reason = self.calc_reason(status) self._reason = reason @property def status(self): return self._status @property def reason(self): return self._reason @reify def status_line(self): version = self.version return 'HTTP/{}.{} {} {}\r\n'.format( version[0], version[1], self.status, self.reason) def autochunked(self): return (self.length is None and self.version >= HttpVersion11) def _add_default_headers(self): super()._add_default_headers() if hdrs.DATE not in self.headers: # format_date_time(None) is quite expensive self.headers.setdefault(hdrs.DATE, format_date_time(None)) self.headers.setdefault(hdrs.SERVER, self.SERVER_SOFTWARE) class Request(HttpMessage): HOP_HEADERS = () def __init__(self, transport, method, path, http_version=HttpVersion11, close=False): # set the default for HTTP 0.9 to be different # will only be overwritten with keep-alive header if http_version < HttpVersion10: close = True super().__init__(transport, http_version, close) self._method = method self._path = path @property def method(self): return self._method @property def path(self): return self._path @reify def status_line(self): return '{0} {1} HTTP/{2[0]}.{2[1]}\r\n'.format( self.method, self.path, self.version) def autochunked(self): return (self.length is None and self.version >= HttpVersion11 and self.status not in (304, 204))
apache-2.0
alex/raven
raven/contrib/django/models.py
1
7491
""" raven.contrib.django.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Acts as an implicit hook for Django installs. :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import sys import logging import warnings from django.conf import settings as django_settings from django.utils.hashcompat import md5_constructor logger = logging.getLogger('sentry.errors.client') def get_installed_apps(): """ Generate a list of modules in settings.INSTALLED_APPS. """ out = set() for app in django_settings.INSTALLED_APPS: out.add(app) return out _client = (None, None) class ProxyClient(object): """ A proxy which represents the currenty client at all times. """ # introspection support: __members__ = property(lambda x: x.__dir__()) # Need to pretend to be the wrapped class, for the sake of objects that care # about this (especially in equality tests) __class__ = property(lambda x: get_client().__class__) __dict__ = property(lambda o: get_client().__dict__) __repr__ = lambda: repr(get_client()) __getattr__ = lambda x, o: getattr(get_client(), o) __setattr__ = lambda x, o, v: setattr(get_client(), o, v) __delattr__ = lambda x, o: delattr(get_client(), o) __lt__ = lambda x, o: get_client() < o __le__ = lambda x, o: get_client() <= o __eq__ = lambda x, o: get_client() == o __ne__ = lambda x, o: get_client() != o __gt__ = lambda x, o: get_client() > o __ge__ = lambda x, o: get_client() >= o __cmp__ = lambda x, o: cmp(get_client(), o) __hash__ = lambda x: hash(get_client()) # attributes are currently not callable # __call__ = lambda x, *a, **kw: get_client()(*a, **kw) __nonzero__ = lambda x: bool(get_client()) __len__ = lambda x: len(get_client()) __getitem__ = lambda x, i: get_client()[i] __iter__ = lambda x: iter(get_client()) __contains__ = lambda x, i: i in get_client() __getslice__ = lambda x, i, j: get_client()[i:j] __add__ = lambda x, o: get_client() + o __sub__ = lambda x, o: get_client() - o __mul__ = lambda x, o: get_client() * o __floordiv__ = lambda x, o: get_client() // o __mod__ = lambda x, o: get_client() % o __divmod__ = lambda x, o: get_client().__divmod__(o) __pow__ = lambda x, o: get_client() ** o __lshift__ = lambda x, o: get_client() << o __rshift__ = lambda x, o: get_client() >> o __and__ = lambda x, o: get_client() & o __xor__ = lambda x, o: get_client() ^ o __or__ = lambda x, o: get_client() | o __div__ = lambda x, o: get_client().__div__(o) __truediv__ = lambda x, o: get_client().__truediv__(o) __neg__ = lambda x: -(get_client()) __pos__ = lambda x: +(get_client()) __abs__ = lambda x: abs(get_client()) __invert__ = lambda x: ~(get_client()) __complex__ = lambda x: complex(get_client()) __int__ = lambda x: int(get_client()) __long__ = lambda x: long(get_client()) __float__ = lambda x: float(get_client()) __str__ = lambda x: str(get_client()) __unicode__ = lambda x: unicode(get_client()) __oct__ = lambda x: oct(get_client()) __hex__ = lambda x: hex(get_client()) __index__ = lambda x: get_client().__index__() __coerce__ = lambda x, o: x.__coerce__(x, o) __enter__ = lambda x: x.__enter__() __exit__ = lambda x, *a, **kw: x.__exit__(*a, **kw) client = ProxyClient() def get_client(client=None): global _client tmp_client = client is not None if not tmp_client: client = getattr(django_settings, 'SENTRY_CLIENT', 'raven.contrib.django.DjangoClient') if _client[0] != client: ga = lambda x, d=None: getattr(django_settings, 'SENTRY_%s' % x, d) module, class_name = client.rsplit('.', 1) options = getattr(django_settings, 'RAVEN_CONFIG', {}) options.setdefault('servers', ga('SERVERS')) options.setdefault('include_paths', ga('INCLUDE_PATHS', [])) options['include_paths'] = set(options['include_paths']) | get_installed_apps() options.setdefault('exclude_paths', ga('EXCLUDE_PATHS')) options.setdefault('timeout', ga('TIMEOUT')) options.setdefault('name', ga('NAME')) options.setdefault('auto_log_stacks', ga('AUTO_LOG_STACKS')) options.setdefault('key', ga('KEY', md5_constructor(django_settings.SECRET_KEY).hexdigest())) options.setdefault('string_max_length', ga('MAX_LENGTH_STRING')) options.setdefault('list_max_length', ga('MAX_LENGTH_LIST')) options.setdefault('site', ga('SITE')) options.setdefault('public_key', ga('PUBLIC_KEY')) options.setdefault('secret_key', ga('SECRET_KEY')) options.setdefault('project', ga('PROJECT')) options.setdefault('processors', ga('PROCESSORS')) options.setdefault('dsn', ga('DSN')) instance = getattr(__import__(module, {}, {}, class_name), class_name)(**options) if not tmp_client: _client = (client, instance) return instance return _client[1] def get_transaction_wrapper(client): if client.servers: class MockTransaction(object): def commit_on_success(self, func): return func def is_dirty(self): return False def rollback(self): pass transaction = MockTransaction() else: from django.db import transaction return transaction def sentry_exception_handler(request=None, **kwargs): transaction = get_transaction_wrapper(client) @transaction.commit_on_success def actually_do_stuff(request=None, **kwargs): exc_info = sys.exc_info() try: if (django_settings.DEBUG and not getattr(django_settings, 'SENTRY_DEBUG', False)) or getattr(exc_info[1], 'skip_sentry', False): return if transaction.is_dirty(): transaction.rollback() get_client().capture('Exception', exc_info=exc_info, request=request) except Exception, exc: try: logger.exception(u'Unable to process log entry: %s' % (exc,)) except Exception, exc: warnings.warn(u'Unable to process log entry: %s' % (exc,)) finally: try: del exc_info except Exception, e: logger.exception(e) return actually_do_stuff(request, **kwargs) def register_handlers(): from django.core.signals import got_request_exception # Connect to Django's internal signal handler got_request_exception.connect(sentry_exception_handler) # If Celery is installed, register a signal handler if 'djcelery' in django_settings.INSTALLED_APPS: from raven.contrib.celery import register_signal try: register_signal(client) except Exception, e: logger.exception('Failed installing django-celery hook: %s' % e) def register_serializers(): import raven.contrib.django.serializers # force import so serializers can call register if 'raven.contrib.django' in django_settings.INSTALLED_APPS: # If we've explicitly enabled signals, or we're not running DEBUG, register handlers if getattr(django_settings, 'RAVEN_CONFIG', {}).get('register_signals', not django_settings.DEBUG): register_handlers() register_serializers()
bsd-3-clause
walac/servo
tests/wpt/css-tests/tools/pywebsocket/src/test/test_endtoend.py
449
26811
#!/usr/bin/env python # # Copyright 2012, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """End-to-end tests for pywebsocket. Tests standalone.py by default. You can also test mod_pywebsocket hosted on an Apache server by setting _use_external_server to True and modifying _external_server_port to point to the port on which the Apache server is running. """ import logging import os import signal import socket import subprocess import sys import time import unittest import set_sys_path # Update sys.path to locate mod_pywebsocket module. from test import client_for_testing from test import mux_client_for_testing # Special message that tells the echo server to start closing handshake _GOODBYE_MESSAGE = 'Goodbye' _SERVER_WARMUP_IN_SEC = 0.2 # If you want to use external server to run end to end tests, set following # parameters correctly. _use_external_server = False _external_server_port = 0 # Test body functions def _echo_check_procedure(client): client.connect() client.send_message('test') client.assert_receive('test') client.send_message('helloworld') client.assert_receive('helloworld') client.send_close() client.assert_receive_close() client.assert_connection_closed() def _echo_check_procedure_with_binary(client): client.connect() client.send_message('binary', binary=True) client.assert_receive('binary', binary=True) client.send_message('\x00\x80\xfe\xff\x00\x80', binary=True) client.assert_receive('\x00\x80\xfe\xff\x00\x80', binary=True) client.send_close() client.assert_receive_close() client.assert_connection_closed() def _echo_check_procedure_with_goodbye(client): client.connect() client.send_message('test') client.assert_receive('test') client.send_message(_GOODBYE_MESSAGE) client.assert_receive(_GOODBYE_MESSAGE) client.assert_receive_close() client.send_close() client.assert_connection_closed() def _echo_check_procedure_with_code_and_reason(client, code, reason): client.connect() client.send_close(code, reason) client.assert_receive_close(code, reason) client.assert_connection_closed() def _unmasked_frame_check_procedure(client): client.connect() client.send_message('test', mask=False) client.assert_receive_close(client_for_testing.STATUS_PROTOCOL_ERROR, '') client.assert_connection_closed() def _mux_echo_check_procedure(mux_client): mux_client.connect() mux_client.send_flow_control(1, 1024) logical_channel_options = client_for_testing.ClientOptions() logical_channel_options.server_host = 'localhost' logical_channel_options.server_port = 80 logical_channel_options.origin = 'http://localhost' logical_channel_options.resource = '/echo' mux_client.add_channel(2, logical_channel_options) mux_client.send_flow_control(2, 1024) mux_client.send_message(2, 'test') mux_client.assert_receive(2, 'test') mux_client.add_channel(3, logical_channel_options) mux_client.send_flow_control(3, 1024) mux_client.send_message(2, 'hello') mux_client.send_message(3, 'world') mux_client.assert_receive(2, 'hello') mux_client.assert_receive(3, 'world') # Don't send close message on channel id 1 so that server-initiated # closing handshake won't occur. mux_client.send_close(2) mux_client.send_close(3) mux_client.assert_receive_close(2) mux_client.assert_receive_close(3) mux_client.send_physical_connection_close() mux_client.assert_physical_connection_receive_close() class EndToEndTestBase(unittest.TestCase): """Base class for end-to-end tests that launch pywebsocket standalone server as a separate process, connect to it using the client_for_testing module, and check if the server behaves correctly by exchanging opening handshake and frames over a TCP connection. """ def setUp(self): self.server_stderr = None self.top_dir = os.path.join(os.path.split(__file__)[0], '..') os.putenv('PYTHONPATH', os.path.pathsep.join(sys.path)) self.standalone_command = os.path.join( self.top_dir, 'mod_pywebsocket', 'standalone.py') self.document_root = os.path.join(self.top_dir, 'example') s = socket.socket() s.bind(('localhost', 0)) (_, self.test_port) = s.getsockname() s.close() self._options = client_for_testing.ClientOptions() self._options.server_host = 'localhost' self._options.origin = 'http://localhost' self._options.resource = '/echo' # TODO(toyoshim): Eliminate launching a standalone server on using # external server. if _use_external_server: self._options.server_port = _external_server_port else: self._options.server_port = self.test_port # TODO(tyoshino): Use tearDown to kill the server. def _run_python_command(self, commandline, stdout=None, stderr=None): return subprocess.Popen([sys.executable] + commandline, close_fds=True, stdout=stdout, stderr=stderr) def _run_server(self): args = [self.standalone_command, '-H', 'localhost', '-V', 'localhost', '-p', str(self.test_port), '-P', str(self.test_port), '-d', self.document_root] # Inherit the level set to the root logger by test runner. root_logger = logging.getLogger() log_level = root_logger.getEffectiveLevel() if log_level != logging.NOTSET: args.append('--log-level') args.append(logging.getLevelName(log_level).lower()) return self._run_python_command(args, stderr=self.server_stderr) def _kill_process(self, pid): if sys.platform in ('win32', 'cygwin'): subprocess.call( ('taskkill.exe', '/f', '/pid', str(pid)), close_fds=True) else: os.kill(pid, signal.SIGKILL) class EndToEndHyBiTest(EndToEndTestBase): def setUp(self): EndToEndTestBase.setUp(self) def _run_test_with_client_options(self, test_function, options): server = self._run_server() try: # TODO(tyoshino): add some logic to poll the server until it # becomes ready time.sleep(_SERVER_WARMUP_IN_SEC) client = client_for_testing.create_client(options) try: test_function(client) finally: client.close_socket() finally: self._kill_process(server.pid) def _run_test(self, test_function): self._run_test_with_client_options(test_function, self._options) def _run_deflate_frame_test(self, test_function): server = self._run_server() try: time.sleep(_SERVER_WARMUP_IN_SEC) self._options.enable_deflate_frame() client = client_for_testing.create_client(self._options) try: test_function(client) finally: client.close_socket() finally: self._kill_process(server.pid) def _run_permessage_deflate_test( self, offer, response_checker, test_function): server = self._run_server() try: time.sleep(_SERVER_WARMUP_IN_SEC) self._options.extensions += offer self._options.check_permessage_deflate = response_checker client = client_for_testing.create_client(self._options) try: client.connect() if test_function is not None: test_function(client) client.assert_connection_closed() finally: client.close_socket() finally: self._kill_process(server.pid) def _run_close_with_code_and_reason_test(self, test_function, code, reason): server = self._run_server() try: time.sleep(_SERVER_WARMUP_IN_SEC) client = client_for_testing.create_client(self._options) try: test_function(client, code, reason) finally: client.close_socket() finally: self._kill_process(server.pid) def _run_http_fallback_test(self, options, status): server = self._run_server() try: time.sleep(_SERVER_WARMUP_IN_SEC) client = client_for_testing.create_client(options) try: client.connect() self.fail('Could not catch HttpStatusException') except client_for_testing.HttpStatusException, e: self.assertEqual(status, e.status) except Exception, e: self.fail('Catch unexpected exception') finally: client.close_socket() finally: self._kill_process(server.pid) def _run_mux_test(self, test_function): server = self._run_server() try: time.sleep(_SERVER_WARMUP_IN_SEC) client = mux_client_for_testing.MuxClient(self._options) try: test_function(client) finally: client.close_socket() finally: self._kill_process(server.pid) def test_echo(self): self._run_test(_echo_check_procedure) def test_echo_binary(self): self._run_test(_echo_check_procedure_with_binary) def test_echo_server_close(self): self._run_test(_echo_check_procedure_with_goodbye) def test_unmasked_frame(self): self._run_test(_unmasked_frame_check_procedure) def test_echo_deflate_frame(self): self._run_deflate_frame_test(_echo_check_procedure) def test_echo_deflate_frame_server_close(self): self._run_deflate_frame_test( _echo_check_procedure_with_goodbye) def test_echo_permessage_deflate(self): def test_function(client): # From the examples in the spec. compressed_hello = '\xf2\x48\xcd\xc9\xc9\x07\x00' client._stream.send_data( compressed_hello, client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.assert_receive_binary( compressed_hello, opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client.send_close() client.assert_receive_close() def response_checker(parameter): self.assertEquals('permessage-deflate', parameter.name()) self.assertEquals([], parameter.get_parameters()) self._run_permessage_deflate_test( ['permessage-deflate'], response_checker, test_function) def test_echo_permessage_deflate_two_frames(self): def test_function(client): # From the examples in the spec. client._stream.send_data( '\xf2\x48\xcd', client_for_testing.OPCODE_TEXT, end=False, rsv1=1) client._stream.send_data( '\xc9\xc9\x07\x00', client_for_testing.OPCODE_TEXT) client._stream.assert_receive_binary( '\xf2\x48\xcd\xc9\xc9\x07\x00', opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client.send_close() client.assert_receive_close() def response_checker(parameter): self.assertEquals('permessage-deflate', parameter.name()) self.assertEquals([], parameter.get_parameters()) self._run_permessage_deflate_test( ['permessage-deflate'], response_checker, test_function) def test_echo_permessage_deflate_two_messages(self): def test_function(client): # From the examples in the spec. client._stream.send_data( '\xf2\x48\xcd\xc9\xc9\x07\x00', client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.send_data( '\xf2\x00\x11\x00\x00', client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.assert_receive_binary( '\xf2\x48\xcd\xc9\xc9\x07\x00', opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.assert_receive_binary( '\xf2\x00\x11\x00\x00', opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client.send_close() client.assert_receive_close() def response_checker(parameter): self.assertEquals('permessage-deflate', parameter.name()) self.assertEquals([], parameter.get_parameters()) self._run_permessage_deflate_test( ['permessage-deflate'], response_checker, test_function) def test_echo_permessage_deflate_two_msgs_server_no_context_takeover(self): def test_function(client): # From the examples in the spec. client._stream.send_data( '\xf2\x48\xcd\xc9\xc9\x07\x00', client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.send_data( '\xf2\x00\x11\x00\x00', client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.assert_receive_binary( '\xf2\x48\xcd\xc9\xc9\x07\x00', opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.assert_receive_binary( '\xf2\x48\xcd\xc9\xc9\x07\x00', opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client.send_close() client.assert_receive_close() def response_checker(parameter): self.assertEquals('permessage-deflate', parameter.name()) self.assertEquals([('server_no_context_takeover', None)], parameter.get_parameters()) self._run_permessage_deflate_test( ['permessage-deflate; server_no_context_takeover'], response_checker, test_function) def test_echo_permessage_deflate_preference(self): def test_function(client): # From the examples in the spec. compressed_hello = '\xf2\x48\xcd\xc9\xc9\x07\x00' client._stream.send_data( compressed_hello, client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.assert_receive_binary( compressed_hello, opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client.send_close() client.assert_receive_close() def response_checker(parameter): self.assertEquals('permessage-deflate', parameter.name()) self.assertEquals([], parameter.get_parameters()) self._run_permessage_deflate_test( ['permessage-deflate', 'deflate-frame'], response_checker, test_function) def test_echo_permessage_deflate_with_parameters(self): def test_function(client): # From the examples in the spec. compressed_hello = '\xf2\x48\xcd\xc9\xc9\x07\x00' client._stream.send_data( compressed_hello, client_for_testing.OPCODE_TEXT, rsv1=1) client._stream.assert_receive_binary( compressed_hello, opcode=client_for_testing.OPCODE_TEXT, rsv1=1) client.send_close() client.assert_receive_close() def response_checker(parameter): self.assertEquals('permessage-deflate', parameter.name()) self.assertEquals([('server_max_window_bits', '10'), ('server_no_context_takeover', None)], parameter.get_parameters()) self._run_permessage_deflate_test( ['permessage-deflate; server_max_window_bits=10; ' 'server_no_context_takeover'], response_checker, test_function) def test_echo_permessage_deflate_with_bad_server_max_window_bits(self): def test_function(client): client.send_close() client.assert_receive_close() def response_checker(parameter): raise Exception('Unexpected acceptance of permessage-deflate') self._run_permessage_deflate_test( ['permessage-deflate; server_max_window_bits=3000000'], response_checker, test_function) def test_echo_permessage_deflate_with_bad_server_max_window_bits(self): def test_function(client): client.send_close() client.assert_receive_close() def response_checker(parameter): raise Exception('Unexpected acceptance of permessage-deflate') self._run_permessage_deflate_test( ['permessage-deflate; server_max_window_bits=3000000'], response_checker, test_function) def test_echo_permessage_deflate_with_undefined_parameter(self): def test_function(client): client.send_close() client.assert_receive_close() def response_checker(parameter): raise Exception('Unexpected acceptance of permessage-deflate') self._run_permessage_deflate_test( ['permessage-deflate; foo=bar'], response_checker, test_function) def test_echo_close_with_code_and_reason(self): self._options.resource = '/close' self._run_close_with_code_and_reason_test( _echo_check_procedure_with_code_and_reason, 3333, 'sunsunsunsun') def test_echo_close_with_empty_body(self): self._options.resource = '/close' self._run_close_with_code_and_reason_test( _echo_check_procedure_with_code_and_reason, None, '') def test_mux_echo(self): self._run_mux_test(_mux_echo_check_procedure) def test_close_on_protocol_error(self): """Tests that the server sends a close frame with protocol error status code when the client sends data with some protocol error. """ def test_function(client): client.connect() # Intermediate frame without any preceding start of fragmentation # frame. client.send_frame_of_arbitrary_bytes('\x80\x80', '') client.assert_receive_close( client_for_testing.STATUS_PROTOCOL_ERROR) self._run_test(test_function) def test_close_on_unsupported_frame(self): """Tests that the server sends a close frame with unsupported operation status code when the client sends data asking some operation that is not supported by the server. """ def test_function(client): client.connect() # Text frame with RSV3 bit raised. client.send_frame_of_arbitrary_bytes('\x91\x80', '') client.assert_receive_close( client_for_testing.STATUS_UNSUPPORTED_DATA) self._run_test(test_function) def test_close_on_invalid_frame(self): """Tests that the server sends a close frame with invalid frame payload data status code when the client sends an invalid frame like containing invalid UTF-8 character. """ def test_function(client): client.connect() # Text frame with invalid UTF-8 string. client.send_message('\x80', raw=True) client.assert_receive_close( client_for_testing.STATUS_INVALID_FRAME_PAYLOAD_DATA) self._run_test(test_function) def test_close_on_internal_endpoint_error(self): """Tests that the server sends a close frame with internal endpoint error status code when the handler does bad operation. """ self._options.resource = '/internal_error' def test_function(client): client.connect() client.assert_receive_close( client_for_testing.STATUS_INTERNAL_ENDPOINT_ERROR) self._run_test(test_function) # TODO(toyoshim): Add tests to verify invalid absolute uri handling like # host unmatch, port unmatch and invalid port description (':' without port # number). def test_absolute_uri(self): """Tests absolute uri request.""" options = self._options options.resource = 'ws://localhost:%d/echo' % options.server_port self._run_test_with_client_options(_echo_check_procedure, options) def test_origin_check(self): """Tests http fallback on origin check fail.""" options = self._options options.resource = '/origin_check' # Server shows warning message for http 403 fallback. This warning # message is confusing. Following pipe disposes warning messages. self.server_stderr = subprocess.PIPE self._run_http_fallback_test(options, 403) def test_version_check(self): """Tests http fallback on version check fail.""" options = self._options options.version = 99 self._run_http_fallback_test(options, 400) class EndToEndHyBi00Test(EndToEndTestBase): def setUp(self): EndToEndTestBase.setUp(self) def _run_test(self, test_function): server = self._run_server() try: time.sleep(_SERVER_WARMUP_IN_SEC) client = client_for_testing.create_client_hybi00(self._options) try: test_function(client) finally: client.close_socket() finally: self._kill_process(server.pid) def test_echo(self): self._run_test(_echo_check_procedure) def test_echo_server_close(self): self._run_test(_echo_check_procedure_with_goodbye) class EndToEndTestWithEchoClient(EndToEndTestBase): def setUp(self): EndToEndTestBase.setUp(self) def _check_example_echo_client_result( self, expected, stdoutdata, stderrdata): actual = stdoutdata.decode("utf-8") if actual != expected: raise Exception('Unexpected result on example echo client: ' '%r (expected) vs %r (actual)' % (expected, actual)) if stderrdata is not None: raise Exception('Unexpected error message on example echo ' 'client: %r' % stderrdata) def test_example_echo_client(self): """Tests that the echo_client.py example can talk with the server.""" server = self._run_server() try: time.sleep(_SERVER_WARMUP_IN_SEC) client_command = os.path.join( self.top_dir, 'example', 'echo_client.py') # Expected output for the default messages. default_expectation = ('Send: Hello\n' 'Recv: Hello\n' u'Send: \u65e5\u672c\n' u'Recv: \u65e5\u672c\n' 'Send close\n' 'Recv ack\n') args = [client_command, '-p', str(self._options.server_port)] client = self._run_python_command(args, stdout=subprocess.PIPE) stdoutdata, stderrdata = client.communicate() self._check_example_echo_client_result( default_expectation, stdoutdata, stderrdata) # Process a big message for which extended payload length is used. # To handle extended payload length, ws_version attribute will be # accessed. This test checks that ws_version is correctly set. big_message = 'a' * 1024 args = [client_command, '-p', str(self._options.server_port), '-m', big_message] client = self._run_python_command(args, stdout=subprocess.PIPE) stdoutdata, stderrdata = client.communicate() expected = ('Send: %s\nRecv: %s\nSend close\nRecv ack\n' % (big_message, big_message)) self._check_example_echo_client_result( expected, stdoutdata, stderrdata) # Test the permessage-deflate extension. args = [client_command, '-p', str(self._options.server_port), '--use_permessage_deflate'] client = self._run_python_command(args, stdout=subprocess.PIPE) stdoutdata, stderrdata = client.communicate() self._check_example_echo_client_result( default_expectation, stdoutdata, stderrdata) finally: self._kill_process(server.pid) if __name__ == '__main__': unittest.main() # vi:sts=4 sw=4 et
mpl-2.0
chaitanyanettem/justcompare
crawlers/bookadda.py
1
2941
#! /usr/bin/python import requests from bs4 import BeautifulSoup import re import sys reload(sys) sys.setdefaultencoding("utf-8") var=requests.get("http://www.bookadda.com") soup=BeautifulSoup(var.text) find1=soup.find('ul',{"class":"left_menu"}) f=open("bookaddalinks.txt",'w') for link in find1.find_all('a'): f.write(link.get('href')) f.write('\n') f.write('#') f.close() pattern=re.compile("filter") pattern0=re.compile("books") f=open("bookaddalinks.txt",'r') while True: line=f.readline() if line.startswith('#'): break var2=requests.get(line) soup2=BeautifulSoup(var2.text) find2=soup2.find('ul',{"class":"left_menu"}) f2=open("addabooklinks.txt",'a') for link in find2.find_all('a'): if pattern.search(link.get('href')): continue f2.write(link.get('href')) f2.write('\n') f2.write('#') f2.close() f2=open("addabooklinks.txt",'r') link2='' while True: line=f2.readline() if line.startswith('#'): break var3=requests.get(line) soup3=BeautifulSoup(var3.text) lineread=soup3.find('div',{"class":"head"}) no=re.findall(' \d+ ', str(re.findall(' \d+ ',str(lineread.text)))) offset=int(no[2]) while (not(offset%20==0)): offset=offset-1 print offset f3=open("booklinks1.txt",'a') f4=open("addabookinfo.txt",'a') i=0 while i<=offset: line2=(line+"?pager.offset="+str(offset)) var3=requests.get(line2) soup3=BeautifulSoup(var3.text) find3=soup3.find('ul',{"class":"results"}) i=i+20 for link in find3.find_all('a'): if pattern0.search(str(link.get('href'))): if link.get('href')==link2: continue f3.write(link.get('href')) f3.write('\n') link2=link.get('href') var4=requests.get(link2) soup4=BeautifulSoup(var4.text) find4=soup4.find('table', style="width: 100%; padding: 10px 10px 10px 10px;") f4.write(line2) f4.write(find4.text) find5=soup4.find('table',{"class":"tbl"}) find6=find5.find('span',{"class":"actlprc"}) f4.write(find6.text) find7=soup4.find('span',{"class":"stckdtls"}) f4.write(find7.text) find8=soup4.find('span',{"class":"numofdys"}) f4.write(find8.text) f3.write('#') f3.close() f2.close() f.close() pattern1=re.compile("online") pattern2=re.compile("kits") pattern3=re.compile("view-books") pattern4=re.compile("cds") pattern5=re.compile("competitive-exams") pattern6=re.compile("schools") f4=open("acadzonelinks.txt",'w') find4=soup.find('div',{"id":"smoothmenu2"},{"class":"ddsmoothmenu-v"}) for link in find4.find_all('a'): if pattern1.search(link.get('href')): continue if pattern2.search(link.get('href')): continue if pattern3.search(link.get('href')): continue if pattern4.search(link.get('href')): continue if pattern5.search(link.get('href')): continue if link.get('href').startswith('#'): continue if pattern6.search(link.get('href')) and link.get('href')==link2: continue f4.write(link.get('href')) link2=link.get('href') f4.write('\n') f4.close()
mit
eaplatanios/tensorflow
tensorflow/python/ops/math_grad_test.py
22
8339
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Python ops defined in math_grad.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class SquaredDifferenceOpTest(test.TestCase): def _testGrad(self, left_shape, right_shape): if len(left_shape) > len(right_shape): output_shape = left_shape else: output_shape = right_shape l = np.random.randn(*left_shape) r = np.random.randn(*right_shape) with self.test_session(use_gpu=True): left_tensor = constant_op.constant(l, shape=left_shape) right_tensor = constant_op.constant(r, shape=right_shape) output = math_ops.squared_difference(left_tensor, right_tensor) left_err = gradient_checker.compute_gradient_error( left_tensor, left_shape, output, output_shape, x_init_value=l) right_err = gradient_checker.compute_gradient_error( right_tensor, right_shape, output, output_shape, x_init_value=r) self.assertLess(left_err, 1e-10) self.assertLess(right_err, 1e-10) def testGrad(self): self._testGrad([1, 2, 3, 2], [3, 2]) self._testGrad([2, 4], [3, 2, 4]) class AbsOpTest(test.TestCase): def _biasedRandN(self, shape, bias=0.1, sigma=1.0): """Returns samples from a normal distribution shifted `bias` away from 0.""" value = np.random.randn(*shape) * sigma return value + np.sign(value) * bias def _testGrad(self, shape, dtype=None, max_error=None, bias=None, sigma=None): np.random.seed(7) if dtype in (dtypes.complex64, dtypes.complex128): value = math_ops.complex( self._biasedRandN( shape, bias=bias, sigma=sigma), self._biasedRandN( shape, bias=bias, sigma=sigma)) else: value = ops.convert_to_tensor( self._biasedRandN( shape, bias=bias), dtype=dtype) with self.test_session(use_gpu=True): output = math_ops.abs(value) error = gradient_checker.compute_gradient_error( value, shape, output, output.get_shape().as_list()) self.assertLess(error, max_error) def testComplexAbs(self): # Bias random test values away from zero to avoid numeric instabilities. self._testGrad( [3, 3], dtype=dtypes.float32, max_error=2e-5, bias=0.1, sigma=1.0) self._testGrad( [3, 3], dtype=dtypes.complex64, max_error=2e-5, bias=0.1, sigma=1.0) # Ensure stability near the pole at zero. self._testGrad( [3, 3], dtype=dtypes.float32, max_error=100.0, bias=0.0, sigma=0.1) self._testGrad( [3, 3], dtype=dtypes.complex64, max_error=100.0, bias=0.0, sigma=0.1) class MinOrMaxGradientTest(test.TestCase): def testMinGradient(self): inputs = constant_op.constant([1.0], dtype=dtypes.float32) outputs = math_ops.reduce_min(array_ops.concat([inputs, inputs], 0)) with self.test_session(): error = gradient_checker.compute_gradient_error(inputs, [1], outputs, []) self.assertLess(error, 1e-4) def testMaxGradient(self): inputs = constant_op.constant([1.0], dtype=dtypes.float32) outputs = math_ops.reduce_max(array_ops.concat([inputs, inputs], 0)) with self.test_session(): error = gradient_checker.compute_gradient_error(inputs, [1], outputs, []) self.assertLess(error, 1e-4) class MaximumOrMinimumGradientTest(test.TestCase): def testMaximumGradient(self): inputs = constant_op.constant([1.0, 2.0, 3.0, 4.0], dtype=dtypes.float32) outputs = math_ops.maximum(inputs, 3.0) with self.test_session(): error = gradient_checker.compute_gradient_error(inputs, [4], outputs, [4]) self.assertLess(error, 1e-4) def testMinimumGradient(self): inputs = constant_op.constant([1.0, 2.0, 3.0, 4.0], dtype=dtypes.float32) outputs = math_ops.minimum(inputs, 2.0) with self.test_session(): error = gradient_checker.compute_gradient_error(inputs, [4], outputs, [4]) self.assertLess(error, 1e-4) class ProdGradientTest(test.TestCase): def testProdGradient(self): inputs = constant_op.constant([[1., 2.], [3., 4.]], dtype=dtypes.float32) outputs = math_ops.reduce_prod(inputs) with self.test_session(): error = gradient_checker.compute_gradient_error( inputs, inputs.get_shape().as_list(), outputs, outputs.get_shape().as_list()) self.assertLess(error, 1e-4) def testProdGradientForNegativeAxis(self): inputs = constant_op.constant([[1., 2.], [3., 4.]], dtype=dtypes.float32) outputs = math_ops.reduce_prod(inputs, -1) with self.test_session(): error = gradient_checker.compute_gradient_error( inputs, inputs.get_shape().as_list(), outputs, outputs.get_shape().as_list()) self.assertLess(error, 1e-4) class SegmentMinOrMaxGradientTest(test.TestCase): def testSegmentMinGradient(self): data = constant_op.constant([1.0, 2.0, 3.0], dtype=dtypes.float32) segment_ids = constant_op.constant([0, 0, 1], dtype=dtypes.int64) segment_min = math_ops.segment_min(data, segment_ids) with self.test_session(): error = gradient_checker.compute_gradient_error(data, [3], segment_min, [2]) self.assertLess(error, 1e-4) def testSegmentMaxGradient(self): data = constant_op.constant([1.0, 2.0, 3.0], dtype=dtypes.float32) segment_ids = constant_op.constant([0, 0, 1], dtype=dtypes.int64) segment_max = math_ops.segment_max(data, segment_ids) with self.test_session(): error = gradient_checker.compute_gradient_error(data, [3], segment_max, [2]) self.assertLess(error, 1e-4) def testSegmentMinGradientWithTies(self): inputs = constant_op.constant([1.0], dtype=dtypes.float32) data = array_ops.concat([inputs, inputs], 0) segment_ids = constant_op.constant([0, 0], dtype=dtypes.int64) segment_min = math_ops.segment_min(data, segment_ids) with self.test_session(): error = gradient_checker.compute_gradient_error(inputs, [1], segment_min, [1]) self.assertLess(error, 1e-4) def testSegmentMaxGradientWithTies(self): inputs = constant_op.constant([1.0], dtype=dtypes.float32) data = array_ops.concat([inputs, inputs], 0) segment_ids = constant_op.constant([0, 0], dtype=dtypes.int64) segment_max = math_ops.segment_max(data, segment_ids) with self.test_session(): error = gradient_checker.compute_gradient_error(inputs, [1], segment_max, [1]) self.assertLess(error, 1e-4) class FloorModGradientTest(test.TestCase): def testFloorModGradient(self): # Making sure the input is not near the discontinuity point where # x/y == floor(x/y) ns = constant_op.constant([17.], dtype=dtypes.float32) inputs = constant_op.constant([131.], dtype=dtypes.float32) floor_mod = math_ops.floormod(inputs, ns) with self.test_session(): error = gradient_checker.compute_gradient_error(inputs, [1], floor_mod, [1]) self.assertLess(error, 1e-4) if __name__ == "__main__": test.main()
apache-2.0
OptimusGitEtna/RestSymf
Python-3.4.2/Lib/test/test_urllib2net.py
60
12676
import unittest from test import support from test.test_urllib2 import sanepathname2url import os import socket import urllib.error import urllib.request import sys try: import ssl except ImportError: ssl = None support.requires("network") TIMEOUT = 60 # seconds def _retry_thrice(func, exc, *args, **kwargs): for i in range(3): try: return func(*args, **kwargs) except exc as e: last_exc = e continue except: raise raise last_exc def _wrap_with_retry_thrice(func, exc): def wrapped(*args, **kwargs): return _retry_thrice(func, exc, *args, **kwargs) return wrapped # Connecting to remote hosts is flaky. Make it more robust by retrying # the connection several times. _urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen, urllib.error.URLError) class AuthTests(unittest.TestCase): """Tests urllib2 authentication features.""" ## Disabled at the moment since there is no page under python.org which ## could be used to HTTP authentication. # # def test_basic_auth(self): # import http.client # # test_url = "http://www.python.org/test/test_urllib2/basic_auth" # test_hostport = "www.python.org" # test_realm = 'Test Realm' # test_user = 'test.test_urllib2net' # test_password = 'blah' # # # failure # try: # _urlopen_with_retry(test_url) # except urllib2.HTTPError, exc: # self.assertEqual(exc.code, 401) # else: # self.fail("urlopen() should have failed with 401") # # # success # auth_handler = urllib2.HTTPBasicAuthHandler() # auth_handler.add_password(test_realm, test_hostport, # test_user, test_password) # opener = urllib2.build_opener(auth_handler) # f = opener.open('http://localhost/') # response = _urlopen_with_retry("http://www.python.org/") # # # The 'userinfo' URL component is deprecated by RFC 3986 for security # # reasons, let's not implement it! (it's already implemented for proxy # # specification strings (that is, URLs or authorities specifying a # # proxy), so we must keep that) # self.assertRaises(http.client.InvalidURL, # urllib2.urlopen, "http://evil:thing@example.com") class CloseSocketTest(unittest.TestCase): def test_close(self): # calling .close() on urllib2's response objects should close the # underlying socket url = "http://www.example.com/" with support.transient_internet(url): response = _urlopen_with_retry(url) sock = response.fp self.assertFalse(sock.closed) response.close() self.assertTrue(sock.closed) class OtherNetworkTests(unittest.TestCase): def setUp(self): if 0: # for debugging import logging logger = logging.getLogger("test_urllib2net") logger.addHandler(logging.StreamHandler()) # XXX The rest of these tests aren't very good -- they don't check much. # They do sometimes catch some major disasters, though. def test_ftp(self): urls = [ 'ftp://ftp.debian.org/debian/README', ('ftp://ftp.debian.org/debian/non-existent-file', None, urllib.error.URLError), 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC' '/research-reports/00README-Legal-Rules-Regs', ] self._test_urls(urls, self._extra_handlers()) def test_file(self): TESTFN = support.TESTFN f = open(TESTFN, 'w') try: f.write('hi there\n') f.close() urls = [ 'file:' + sanepathname2url(os.path.abspath(TESTFN)), ('file:///nonsensename/etc/passwd', None, urllib.error.URLError), ] self._test_urls(urls, self._extra_handlers(), retry=True) finally: os.remove(TESTFN) self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file') # XXX Following test depends on machine configurations that are internal # to CNRI. Need to set up a public server with the right authentication # configuration for test purposes. ## def test_cnri(self): ## if socket.gethostname() == 'bitdiddle': ## localhost = 'bitdiddle.cnri.reston.va.us' ## elif socket.gethostname() == 'bitdiddle.concentric.net': ## localhost = 'localhost' ## else: ## localhost = None ## if localhost is not None: ## urls = [ ## 'file://%s/etc/passwd' % localhost, ## 'http://%s/simple/' % localhost, ## 'http://%s/digest/' % localhost, ## 'http://%s/not/found.h' % localhost, ## ] ## bauth = HTTPBasicAuthHandler() ## bauth.add_password('basic_test_realm', localhost, 'jhylton', ## 'password') ## dauth = HTTPDigestAuthHandler() ## dauth.add_password('digest_test_realm', localhost, 'jhylton', ## 'password') ## self._test_urls(urls, self._extra_handlers()+[bauth, dauth]) def test_urlwithfrag(self): urlwith_frag = "https://docs.python.org/2/glossary.html#glossary" with support.transient_internet(urlwith_frag): req = urllib.request.Request(urlwith_frag) res = urllib.request.urlopen(req) self.assertEqual(res.geturl(), "https://docs.python.org/2/glossary.html#glossary") def test_redirect_url_withfrag(self): redirect_url_with_frag = "http://bit.ly/1iSHToT" with support.transient_internet(redirect_url_with_frag): req = urllib.request.Request(redirect_url_with_frag) res = urllib.request.urlopen(req) self.assertEqual(res.geturl(), "https://docs.python.org/3.4/glossary.html#term-global-interpreter-lock") def test_custom_headers(self): url = "http://www.example.com" with support.transient_internet(url): opener = urllib.request.build_opener() request = urllib.request.Request(url) self.assertFalse(request.header_items()) opener.open(request) self.assertTrue(request.header_items()) self.assertTrue(request.has_header('User-agent')) request.add_header('User-Agent','Test-Agent') opener.open(request) self.assertEqual(request.get_header('User-agent'),'Test-Agent') def test_sites_no_connection_close(self): # Some sites do not send Connection: close header. # Verify that those work properly. (#issue12576) URL = 'http://www.imdb.com' # mangles Connection:close with support.transient_internet(URL): try: with urllib.request.urlopen(URL) as res: pass except ValueError as e: self.fail("urlopen failed for site not sending \ Connection:close") else: self.assertTrue(res) req = urllib.request.urlopen(URL) res = req.read() self.assertTrue(res) def _test_urls(self, urls, handlers, retry=True): import time import logging debug = logging.getLogger("test_urllib2").debug urlopen = urllib.request.build_opener(*handlers).open if retry: urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError) for url in urls: with self.subTest(url=url): if isinstance(url, tuple): url, req, expected_err = url else: req = expected_err = None with support.transient_internet(url): try: f = urlopen(url, req, TIMEOUT) except OSError as err: if expected_err: msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" % (expected_err, url, req, type(err), err)) self.assertIsInstance(err, expected_err, msg) else: raise except urllib.error.URLError as err: if isinstance(err[0], socket.timeout): print("<timeout: %s>" % url, file=sys.stderr) continue else: raise else: try: with support.time_out, \ support.socket_peer_reset, \ support.ioerror_peer_reset: buf = f.read() debug("read %d bytes" % len(buf)) except socket.timeout: print("<timeout: %s>" % url, file=sys.stderr) f.close() time.sleep(0.1) def _extra_handlers(self): handlers = [] cfh = urllib.request.CacheFTPHandler() self.addCleanup(cfh.clear_cache) cfh.setTimeout(1) handlers.append(cfh) return handlers class TimeoutTest(unittest.TestCase): def test_http_basic(self): self.assertIsNone(socket.getdefaulttimeout()) url = "http://www.example.com" with support.transient_internet(url, timeout=None): u = _urlopen_with_retry(url) self.addCleanup(u.close) self.assertIsNone(u.fp.raw._sock.gettimeout()) def test_http_default_timeout(self): self.assertIsNone(socket.getdefaulttimeout()) url = "http://www.example.com" with support.transient_internet(url): socket.setdefaulttimeout(60) try: u = _urlopen_with_retry(url) self.addCleanup(u.close) finally: socket.setdefaulttimeout(None) self.assertEqual(u.fp.raw._sock.gettimeout(), 60) def test_http_no_timeout(self): self.assertIsNone(socket.getdefaulttimeout()) url = "http://www.example.com" with support.transient_internet(url): socket.setdefaulttimeout(60) try: u = _urlopen_with_retry(url, timeout=None) self.addCleanup(u.close) finally: socket.setdefaulttimeout(None) self.assertIsNone(u.fp.raw._sock.gettimeout()) def test_http_timeout(self): url = "http://www.example.com" with support.transient_internet(url): u = _urlopen_with_retry(url, timeout=120) self.addCleanup(u.close) self.assertEqual(u.fp.raw._sock.gettimeout(), 120) FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/" def test_ftp_basic(self): self.assertIsNone(socket.getdefaulttimeout()) with support.transient_internet(self.FTP_HOST, timeout=None): u = _urlopen_with_retry(self.FTP_HOST) self.addCleanup(u.close) self.assertIsNone(u.fp.fp.raw._sock.gettimeout()) def test_ftp_default_timeout(self): self.assertIsNone(socket.getdefaulttimeout()) with support.transient_internet(self.FTP_HOST): socket.setdefaulttimeout(60) try: u = _urlopen_with_retry(self.FTP_HOST) self.addCleanup(u.close) finally: socket.setdefaulttimeout(None) self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60) def test_ftp_no_timeout(self): self.assertIsNone(socket.getdefaulttimeout()) with support.transient_internet(self.FTP_HOST): socket.setdefaulttimeout(60) try: u = _urlopen_with_retry(self.FTP_HOST, timeout=None) self.addCleanup(u.close) finally: socket.setdefaulttimeout(None) self.assertIsNone(u.fp.fp.raw._sock.gettimeout()) def test_ftp_timeout(self): with support.transient_internet(self.FTP_HOST): u = _urlopen_with_retry(self.FTP_HOST, timeout=60) self.addCleanup(u.close) self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60) if __name__ == "__main__": unittest.main()
mit
kingofkosmos/-tg-station
tools/dmi/merge_driver.py
15
6601
#!/usr/bin/env python3 import sys import dmi from hooks.merge_frontend import MergeDriver def images_equal(left, right): if left.size != right.size: return False w, h = left.size left_load, right_load = left.load(), right.load() for y in range(0, h): for x in range(0, w): lpixel, rpixel = left_load[x, y], right_load[x, y] # quietly ignore changes where both pixels are fully transparent if lpixel != rpixel and (lpixel[3] != 0 or rpixel[3] != 0): return False return True def states_equal(left, right): result = True # basic properties for attr in ('loop', 'rewind', 'movement', 'dirs', 'delays', 'hotspots', 'framecount'): lval, rval = getattr(left, attr), getattr(right, attr) if lval != rval: result = False # frames for (left_frame, right_frame) in zip(left.frames, right.frames): if not images_equal(left_frame, right_frame): result = False return result def key_of(state): return (state.name, state.movement) def dictify(sheet): result = {} for state in sheet.states: k = key_of(state) if k in result: print(f" duplicate {k!r}") result[k] = state return result def three_way_merge(base, left, right): base_dims = base.width, base.height if base_dims != (left.width, left.height) or base_dims != (right.width, right.height): print("Dimensions have changed:") print(f" Base: {base.width} x {base.height}") print(f" Ours: {left.width} x {left.height}") print(f" Theirs: {right.width} x {right.height}") return True, None base_states, left_states, right_states = dictify(base), dictify(left), dictify(right) new_left = {k: v for k, v in left_states.items() if k not in base_states} new_right = {k: v for k, v in right_states.items() if k not in base_states} new_both = {} conflicts = [] for key, state in list(new_left.items()): in_right = new_right.get(key, None) if in_right: if states_equal(state, in_right): # allow it new_both[key] = state else: # generate conflict states print(f" C: {state.name!r}: added differently in both!") state.name = f"{state.name} !CONFLICT! left" conflicts.append(state) in_right.name = f"{state.name} !CONFLICT! right" conflicts.append(in_right) # don't add it a second time del new_left[key] del new_right[key] final_states = [] # add states that are currently in the base for state in base.states: in_left = left_states.get(key_of(state), None) in_right = right_states.get(key_of(state), None) left_equals = in_left and states_equal(state, in_left) right_equals = in_right and states_equal(state, in_right) if not in_left and not in_right: # deleted in both left and right, it's just deleted print(f" {state.name!r}: deleted in both") elif not in_left: # left deletes print(f" {state.name!r}: deleted in left") if not right_equals: print(f" ... but modified in right") final_states.append(in_right) elif not in_right: # right deletes print(f" {state.name!r}: deleted in right") if not left_equals: print(f" ... but modified in left") final_states.append(in_left) elif left_equals and right_equals: # changed in neither #print(f"Same in both: {state.name!r}") final_states.append(state) elif left_equals: # changed only in right print(f" {state.name!r}: changed in left") final_states.append(in_right) elif right_equals: # changed only in left print(f" {state.name!r}: changed in right") final_states.append(in_left) elif states_equal(in_left, in_right): # changed in both, to the same thing print(f" {state.name!r}: changed same in both") final_states.append(in_left) # either or else: # changed in both name = state.name print(f" C: {name!r}: changed differently in both!") state.name = f"{name} !CONFLICT! base" conflicts.append(state) in_left.name = f"{name} !CONFLICT! left" conflicts.append(in_left) in_right.name = f"{name} !CONFLICT! right" conflicts.append(in_right) # add states which both left and right added the same for key, state in new_both.items(): print(f" {state.name!r}: added same in both") final_states.append(state) # add states that are brand-new in the left for key, state in new_left.items(): print(f" {state.name!r}: added in left") final_states.append(state) # add states that are brand-new in the right for key, state in new_right.items(): print(f" {state.name!r}: added in right") final_states.append(state) final_states.extend(conflicts) merged = dmi.Dmi(base.width, base.height) merged.states = final_states return len(conflicts), merged class DmiDriver(MergeDriver): driver_id = 'dmi' def merge(self, base, left, right): icon_base = dmi.Dmi.from_file(base) icon_left = dmi.Dmi.from_file(left) icon_right = dmi.Dmi.from_file(right) trouble, merge_result = three_way_merge(icon_base, icon_left, icon_right) return not trouble, merge_result def to_file(self, outfile, merge_result): merge_result.to_file(outfile) def post_announce(self, success, merge_result): if not success: print("!!! Manual merge required!") if merge_result: print(" A best-effort merge was performed. You must edit the icon and remove all") print(" icon states marked with !CONFLICT!, leaving only the desired icon.") else: print(" The icon was totally unable to be merged, you must start with one version") print(" or the other and manually resolve the conflict.") print(" Information about which states conflicted is listed above.") if __name__ == '__main__': exit(DmiDriver().main())
agpl-3.0
ColdSauce/IsSittingOnButt
server/env/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/langcyrillicmodel.py
2762
17725
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # KOI8-R language model # Character Mapping Table: KOI8R_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, # 80 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, # 90 223,224,225, 68,226,227,228,229,230,231,232,233,234,235,236,237, # a0 238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253, # b0 27, 3, 21, 28, 13, 2, 39, 19, 26, 4, 23, 11, 8, 12, 5, 1, # c0 15, 16, 9, 7, 6, 14, 24, 10, 17, 18, 20, 25, 30, 29, 22, 54, # d0 59, 37, 44, 58, 41, 48, 53, 46, 55, 42, 60, 36, 49, 38, 31, 34, # e0 35, 43, 45, 32, 40, 52, 56, 33, 61, 62, 51, 57, 47, 63, 50, 70, # f0 ) win1251_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 239,240,241,242,243,244,245,246, 68,247,248,249,250,251,252,253, 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, ) latin5_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, 239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255, ) macCyrillic_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 239,240,241,242,243,244,245,246,247,248,249,250,251,252, 68, 16, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27,255, ) IBM855_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194, 68,195,196,197,198,199,200,201,202,203,204,205, 206,207,208,209,210,211,212,213,214,215,216,217, 27, 59, 54, 70, 3, 37, 21, 44, 28, 58, 13, 41, 2, 48, 39, 53, 19, 46,218,219, 220,221,222,223,224, 26, 55, 4, 42,225,226,227,228, 23, 60,229, 230,231,232,233,234,235, 11, 36,236,237,238,239,240,241,242,243, 8, 49, 12, 38, 5, 31, 1, 34, 15,244,245,246,247, 35, 16,248, 43, 9, 45, 7, 32, 6, 40, 14, 52, 24, 56, 10, 33, 17, 61,249, 250, 18, 62, 20, 51, 25, 57, 30, 47, 29, 63, 22, 50,251,252,255, ) IBM866_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, 239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255, ) # Model Table: # total sequences: 100% # first 512 sequences: 97.6601% # first 1024 sequences: 2.3389% # rest sequences: 0.1237% # negative sequences: 0.0009% RussianLangModel = ( 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,1,3,3,3,2,3,2,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2,2,2,2,0,0,2, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,2,3,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,2,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,2,3,3,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1, 0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1, 0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,2,2,3,1,3,3,1,3,3,3,3,2,2,3,0,2,2,2,3,3,2,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,3,3,3,2,2,3,2,3,3,3,2,1,2,2,0,1,2,2,2,2,2,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,3,0,2,2,3,3,2,1,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,1,2,3,2,2,3,2,3,3,3,3,2,2,3,0,3,2,2,3,1,1,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,3,3,3,3,2,2,2,0,3,3,3,2,2,2,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,2,3,2,2,0,1,3,2,1,2,2,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,1,1,3,0,1,1,1,1,2,1,1,0,2,2,2,1,2,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,2,2,2,2,1,3,2,3,2,3,2,1,2,2,0,1,1,2,1,2,1,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,2,2,2,2,0,2,2,2,2,3,1,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,2,3,2,2,3,3,3,3,3,3,3,3,3,1,3,2,0,0,3,3,3,3,2,3,3,3,3,2,3,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,3,2,2,3,3,0,2,1,0,3,2,3,2,3,0,0,1,2,0,0,1,0,1,2,1,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,3,0,2,3,3,3,3,2,3,3,3,3,1,2,2,0,0,2,3,2,2,2,3,2,3,2,2,3,0,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,0,2,3,2,3,0,1,2,3,3,2,0,2,3,0,0,2,3,2,2,0,1,3,1,3,2,2,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,3,0,2,3,3,3,3,3,3,3,3,2,1,3,2,0,0,2,2,3,3,3,2,3,3,0,2,2,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,3,2,2,2,3,3,0,0,1,1,1,1,1,2,0,0,1,1,1,1,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,3,3,3,3,3,3,0,3,2,3,3,2,3,2,0,2,1,0,1,1,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,3,2,2,2,2,3,1,3,2,3,1,1,2,1,0,2,2,2,2,1,3,1,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 2,2,3,3,3,3,3,1,2,2,1,3,1,0,3,0,0,3,0,0,0,1,1,0,1,2,1,0,0,0,0,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,2,1,1,3,3,3,2,2,1,2,2,3,1,1,2,0,0,2,2,1,3,0,0,2,1,1,2,1,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,3,3,3,1,2,2,2,1,2,1,3,3,1,1,2,1,2,1,2,2,0,2,0,0,1,1,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,3,2,1,3,2,2,3,2,0,3,2,0,3,0,1,0,1,1,0,0,1,1,1,1,0,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,3,3,3,2,2,2,3,3,1,2,1,2,1,0,1,0,1,1,0,1,0,0,2,1,1,1,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 3,1,1,2,1,2,3,3,2,2,1,2,2,3,0,2,1,0,0,2,2,3,2,1,2,2,2,2,2,3,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,1,1,0,1,1,2,2,1,1,3,0,0,1,3,1,1,1,0,0,0,1,0,1,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,3,3,3,2,0,0,0,2,1,0,1,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,1,0,0,2,3,2,2,2,1,2,2,2,1,2,1,0,0,1,1,1,0,2,0,1,1,1,0,0,1,1, 1,0,0,0,0,0,1,2,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,0,0,0,0,1,0,0,0,0,3,0,1,2,1,0,0,0,0,0,0,0,1,1,0,0,1,1, 1,0,1,0,1,2,0,0,1,1,2,1,0,1,1,1,1,0,1,1,1,1,0,1,0,0,1,0,0,1,1,0, 2,2,3,2,2,2,3,1,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,0,1,0,1,1,1,0,2,1, 1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,0,1,1,0, 3,3,3,2,2,2,2,3,2,2,1,1,2,2,2,2,1,1,3,1,2,1,2,0,0,1,1,0,1,0,2,1, 1,1,1,1,1,2,1,0,1,1,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,0, 2,0,0,1,0,3,2,2,2,2,1,2,1,2,1,2,0,0,0,2,1,2,2,1,1,2,2,0,1,1,0,2, 1,1,1,1,1,0,1,1,1,2,1,1,1,2,1,0,1,2,1,1,1,1,0,1,1,1,0,0,1,0,0,1, 1,3,2,2,2,1,1,1,2,3,0,0,0,0,2,0,2,2,1,0,0,0,0,0,0,1,0,0,0,0,1,1, 1,0,1,1,0,1,0,1,1,0,1,1,0,2,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0, 2,3,2,3,2,1,2,2,2,2,1,0,0,0,2,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,2,1, 1,1,2,1,0,2,0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0, 3,0,0,1,0,2,2,2,3,2,2,2,2,2,2,2,0,0,0,2,1,2,1,1,1,2,2,0,0,0,1,2, 1,1,1,1,1,0,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1, 2,3,2,3,3,2,0,1,1,1,0,0,1,0,2,0,1,1,3,1,0,0,0,0,0,0,0,1,0,0,2,1, 1,1,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0, 2,3,3,3,3,1,2,2,2,2,0,1,1,0,2,1,1,1,2,1,0,1,1,0,0,1,0,1,0,0,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,2,0,0,1,1,2,2,1,0,0,2,0,1,1,3,0,0,1,0,0,0,0,0,1,0,1,2,1, 1,1,2,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,1,0, 1,3,2,3,2,1,0,0,2,2,2,0,1,0,2,0,1,1,1,0,1,0,0,0,3,0,1,1,0,0,2,1, 1,1,1,0,1,1,0,0,0,0,1,1,0,1,0,0,2,1,1,0,1,0,0,0,1,0,1,0,0,1,1,0, 3,1,2,1,1,2,2,2,2,2,2,1,2,2,1,1,0,0,0,2,2,2,0,0,0,1,2,1,0,1,0,1, 2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,2,1,1,1,0,1,0,1,1,0,1,1,1,0,0,1, 3,0,0,0,0,2,0,1,1,1,1,1,1,1,0,1,0,0,0,1,1,1,0,1,0,1,1,0,0,1,0,1, 1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1, 1,3,3,2,2,0,0,0,2,2,0,0,0,1,2,0,1,1,2,0,0,0,0,0,0,0,0,1,0,0,2,1, 0,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0, 2,3,2,3,2,0,0,0,0,1,1,0,0,0,2,0,2,0,2,0,0,0,0,0,1,0,0,1,0,0,1,1, 1,1,2,0,1,2,1,0,1,1,2,1,1,1,1,1,2,1,1,0,1,0,0,1,1,1,1,1,0,1,1,0, 1,3,2,2,2,1,0,0,2,2,1,0,1,2,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,0,2,3,1,2,2,2,2,2,2,1,1,0,0,0,1,0,1,0,2,1,1,1,0,0,0,0,1, 1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0, 2,0,2,0,0,1,0,3,2,1,2,1,2,2,0,1,0,0,0,2,1,0,0,2,1,1,1,1,0,2,0,2, 2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,0,0,0,1,1,1,1,0,1,0,0,1, 1,2,2,2,2,1,0,0,1,0,0,0,0,0,2,0,1,1,1,1,0,0,0,0,1,0,1,2,0,0,2,0, 1,0,1,1,1,2,1,0,1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0, 2,1,2,2,2,0,3,0,1,1,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,0,1,1,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0, 1,2,2,3,2,2,0,0,1,1,2,0,1,2,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1, 0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0, 2,2,1,1,2,1,2,2,2,2,2,1,2,2,0,1,0,0,0,1,2,2,2,1,2,1,1,1,1,1,2,1, 1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,0,1, 1,2,2,2,2,0,1,0,2,2,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0, 0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,0,0,2,2,2,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1, 0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,0,0,0,1,0,0,1,1,2,0,0,0,0,1,0,1,0,0,1,0,0,2,0,0,0,1, 0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,1,1,2,0,2,1,1,1,1,0,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1, 0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,0,2,1,2,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0, 0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,0,0,2,0,1,2,1,0,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1, 0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1, 2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,1,1,0,1,0,1,0,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0, 0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, ) Koi8rModel = { 'charToOrderMap': KOI8R_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "KOI8-R" } Win1251CyrillicModel = { 'charToOrderMap': win1251_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "windows-1251" } Latin5CyrillicModel = { 'charToOrderMap': latin5_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "ISO-8859-5" } MacCyrillicModel = { 'charToOrderMap': macCyrillic_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "MacCyrillic" }; Ibm866Model = { 'charToOrderMap': IBM866_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "IBM866" } Ibm855Model = { 'charToOrderMap': IBM855_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "IBM855" } # flake8: noqa
apache-2.0
yaroslavvb/tensorflow
tensorflow/python/ops/variables.py
11
48817
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Variable class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import attr_value_pb2 from tensorflow.core.framework import variable_pb2 from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.util import compat from tensorflow.python.util.deprecation import deprecated class Variable(object): """See the @{$variables$Variables How To} for a high level overview. A variable maintains state in the graph across calls to `run()`. You add a variable to the graph by constructing an instance of the class `Variable`. The `Variable()` constructor requires an initial value for the variable, which can be a `Tensor` of any type and shape. The initial value defines the type and shape of the variable. After construction, the type and shape of the variable are fixed. The value can be changed using one of the assign methods. If you want to change the shape of a variable later you have to use an `assign` Op with `validate_shape=False`. Just like any `Tensor`, variables created with `Variable()` can be used as inputs for other Ops in the graph. Additionally, all the operators overloaded for the `Tensor` class are carried over to variables, so you can also add nodes to the graph by just doing arithmetic on variables. ```python import tensorflow as tf # Create a variable. w = tf.Variable(<initial-value>, name=<optional-name>) # Use the variable in the graph like any Tensor. y = tf.matmul(w, ...another variable or tensor...) # The overloaded operators are available too. z = tf.sigmoid(w + y) # Assign a new value to the variable with `assign()` or a related method. w.assign(w + 1.0) w.assign_add(1.0) ``` When you launch the graph, variables have to be explicitly initialized before you can run Ops that use their value. You can initialize a variable by running its *initializer op*, restoring the variable from a save file, or simply running an `assign` Op that assigns a value to the variable. In fact, the variable *initializer op* is just an `assign` Op that assigns the variable's initial value to the variable itself. ```python # Launch the graph in a session. with tf.Session() as sess: # Run the variable initializer. sess.run(w.initializer) # ...you now can run ops that use the value of 'w'... ``` The most common initialization pattern is to use the convenience function `global_variables_initializer()` to add an Op to the graph that initializes all the variables. You then run that Op after launching the graph. ```python # Add an Op to initialize global variables. init_op = tf.global_variables_initializer() # Launch the graph in a session. with tf.Session() as sess: # Run the Op that initializes global variables. sess.run(init_op) # ...you can now run any Op that uses variable values... ``` If you need to create a variable with an initial value dependent on another variable, use the other variable's `initialized_value()`. This ensures that variables are initialized in the right order. All variables are automatically collected in the graph where they are created. By default, the constructor adds the new variable to the graph collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function `global_variables()` returns the contents of that collection. When building a machine learning model it is often convenient to distinguish between variables holding the trainable model parameters and other variables such as a `global step` variable used to count training steps. To make this easier, the variable constructor supports a `trainable=<bool>` parameter. If `True`, the new variable is also added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. The convenience function `trainable_variables()` returns the contents of this collection. The various `Optimizer` classes use this collection as the default list of variables to optimize. """ def __init__(self, initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None): """Creates a new variable with value `initial_value`. The new variable is added to the graph collections listed in `collections`, which defaults to `[GraphKeys.GLOBAL_VARIABLES]`. If `trainable` is `True` the variable is also added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This constructor creates both a `variable` Op and an `assign` Op to set the variable to its initial value. Args: initial_value: A `Tensor`, or Python object convertible to a `Tensor`, which is the initial value for the Variable. The initial value must have a shape specified unless `validate_shape` is set to False. Can also be a callable with no argument that returns the initial value when called. In that case, `dtype` must be specified. (Note that initializer functions from init_ops.py must first be bound to a shape before being used here.) trainable: If `True`, the default, also adds the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default list of variables to use by the `Optimizer` classes. collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. validate_shape: If `False`, allows the variable to be initialized with a value of unknown shape. If `True`, the default, the shape of `initial_value` must be known. caching_device: Optional device string describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. name: Optional name for the variable. Defaults to `'Variable'` and gets uniquified automatically. variable_def: `VariableDef` protocol buffer. If not `None`, recreates the Variable object with its contents. `variable_def` and the other arguments are mutually exclusive. dtype: If set, initial_value will be converted to the given type. If `None`, either the datatype will be kept (if `initial_value` is a Tensor), or `convert_to_tensor` will decide. expected_shape: A TensorShape. If set, initial_value is expected to have this shape. import_scope: Optional `string`. Name scope to add to the `Variable.` Only used when initializing from protocol buffer. Raises: ValueError: If both `variable_def` and initial_value are specified. ValueError: If the initial value is not specified, or does not have a shape and `validate_shape` is `True`. """ if variable_def: # If variable_def is provided, recreates the variable from its fields. if initial_value: raise ValueError("variable_def and initial_value are mutually " "exclusive.") self._init_from_proto(variable_def, import_scope=import_scope) else: # Create from initial_value. self._init_from_args( initial_value=initial_value, trainable=trainable, collections=collections, validate_shape=validate_shape, caching_device=caching_device, name=name, dtype=dtype, expected_shape=expected_shape) def __repr__(self): return "<tf.Variable '%s' shape=%s dtype=%s>" % ( self.name, self.get_shape(), self.dtype.name) def _init_from_args(self, initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, dtype=None, expected_shape=None): """Creates a new variable from arguments. Args: initial_value: A `Tensor`, or Python object convertible to a `Tensor`, which is the initial value for the Variable. The initial value must have a shape specified unless `validate_shape` is set to False. Can also be a callable with no argument that returns the initial value when called. (Note that initializer functions from init_ops.py must first be bound to a shape before being used here.) trainable: If `True`, the default, also adds the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default list of variables to use by the `Optimizer` classes. collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. validate_shape: If `False`, allows the variable to be initialized with a value of unknown shape. If `True`, the default, the shape of `initial_value` must be known. caching_device: Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. name: Optional name for the variable. Defaults to `'Variable'` and gets uniquified automatically. dtype: If set, initial_value will be converted to the given type. If None, either the datatype will be kept (if initial_value is a Tensor) or float32 will be used (if it is a Python object convertible to a Tensor). expected_shape: Deprecated. Ignored. Raises: ValueError: If the initial value is not specified, or does not have a shape and `validate_shape` is `True`. """ _ = expected_shape if initial_value is None: raise ValueError("initial_value must be specified.") init_from_fn = callable(initial_value) if collections is None: collections = [ops.GraphKeys.GLOBAL_VARIABLES] if not isinstance(collections, (list, tuple, set)): raise ValueError( "collections argument to Variable constructor must be a list, tuple, " "or set. Got %s of type %s" % (collections, type(collections))) if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections: collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES] with ops.control_dependencies(None): with ops.name_scope(name, "Variable", [] if init_from_fn else [initial_value]) as name: if init_from_fn: # Use attr_scope and device(None) to simulate the behavior of # colocate_with when the variable we want to colocate with doesn't # yet exist. true_name = ops._name_from_scope_name(name) attr = attr_value_pb2.AttrValue( list=attr_value_pb2.AttrValue.ListValue( s=[compat.as_bytes("loc:@%s" % true_name)])) # pylint: disable=protected-access with ops.get_default_graph()._attr_scope({"_class": attr}): with ops.name_scope("Initializer"), ops.device(None): self._initial_value = ops.convert_to_tensor( initial_value(), name="initial_value", dtype=dtype) shape = (self._initial_value.get_shape() if validate_shape else tensor_shape.unknown_shape()) self._variable = state_ops.variable_op_v2( shape, self._initial_value.dtype.base_dtype, name=name) # Or get the initial value from a Tensor or Python object. else: self._initial_value = ops.convert_to_tensor( initial_value, name="initial_value", dtype=dtype) shape = (self._initial_value.get_shape() if validate_shape else tensor_shape.unknown_shape()) # In this case, the variable op can't be created until after the # initial_value has been converted to a Tensor with a known type. self._variable = state_ops.variable_op_v2( shape, self._initial_value.dtype.base_dtype, name=name) # Manually overrides the variable's shape with the initial value's. if validate_shape: initial_value_shape = self._initial_value.get_shape() if not initial_value_shape.is_fully_defined(): raise ValueError("initial_value must have a shape specified: %s" % self._initial_value) # Assigns initial value. self._initializer_op = state_ops.assign( self._variable, self._initial_value, validate_shape=validate_shape).op # TODO(vrv): Change this class to not take caching_device, but # to take the op to colocate the snapshot with, so we can use # colocation rather than devices. if caching_device is not None: with ops.device(caching_device): self._snapshot = array_ops.identity(self._variable, name="read") else: with ops.colocate_with(self._variable.op): self._snapshot = array_ops.identity(self._variable, name="read") ops.add_to_collections(collections, self) self._caching_device = caching_device self._save_slice_info = None def _init_from_proto(self, variable_def, import_scope=None): """Creates a new variable from `VariableDef` protocol buffer. Args: variable_def: `VariableDef` protocol buffer. import_scope: Optional `string`. Name scope to add. """ assert isinstance(variable_def, variable_pb2.VariableDef) # Create from variable_def. g = ops.get_default_graph() self._variable = g.as_graph_element( ops.prepend_name_scope(variable_def.variable_name, import_scope=import_scope)) self._initializer_op = g.as_graph_element( ops.prepend_name_scope(variable_def.initializer_name, import_scope=import_scope)) self._snapshot = g.as_graph_element( ops.prepend_name_scope(variable_def.snapshot_name, import_scope=import_scope)) if variable_def.HasField("save_slice_info_def"): self._save_slice_info = Variable.SaveSliceInfo( save_slice_info_def=variable_def.save_slice_info_def) else: self._save_slice_info = None self._caching_device = None def _as_graph_element(self): """Conversion function for Graph.as_graph_element().""" return self._variable def _AsTensor(self): # pylint: disable=invalid-name """Converts this variable to a Tensor. See @{tf.Variable.value}. Returns: A `Tensor` containing the value of the variable. """ return self._snapshot def __iter__(self): """Dummy method to prevent iteration. Do not call. NOTE(mrry): If we register __getitem__ as an overloaded operator, Python will valiantly attempt to iterate over the variable's Tensor from 0 to infinity. Declaring this method prevents this unintended behavior. Raises: TypeError: when invoked. """ raise TypeError("'Variable' object is not iterable.") def value(self): """Returns the last snapshot of this variable. You usually do not need to call this method as all ops that need the value of the variable call it automatically through a `convert_to_tensor()` call. Returns a `Tensor` which holds the value of the variable. You can not assign a new value to this tensor as it is not a reference to the variable. To avoid copies, if the consumer of the returned value is on the same device as the variable, this actually returns the live value of the variable, not a copy. Updates to the variable are seen by the consumer. If the consumer is on a different device it will get a copy of the variable. Returns: A `Tensor` containing the value of the variable. """ return self._snapshot def read_value(self): """Returns the value of this variable, read in the current context. Can be different from value() if it's on another device, with control dependencies, etc. Returns: A `Tensor` containing the value of the variable. """ return array_ops.identity(self._variable, name="read") def _ref(self): """Returns a reference to this variable. You usually do not need to call this method as all ops that need a reference to the variable call it automatically. Returns is a `Tensor` which holds a reference to the variable. You can assign a new value to the variable by passing the tensor to an assign op. See @{tf.Variable.value} if you want to get the value of the variable. Returns: A `Tensor` that is a reference to the variable. """ return self._variable def set_shape(self, shape): """Overrides the shape for this variable. Args: shape: the `TensorShape` representing the overridden shape. """ self._ref().set_shape(shape) self.value().set_shape(shape) def eval(self, session=None): """In a session, computes and returns the value of this variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. See @{tf.Session} for more information on launching a graph and on sessions. ```python v = tf.Variable([1, 2]) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) # Usage passing the session explicitly. print(v.eval(sess)) # Usage with the default session. The 'with' block # above makes 'sess' the default session. print(v.eval()) ``` Args: session: The session to use to evaluate this variable. If none, the default session is used. Returns: A numpy `ndarray` with a copy of the value of this variable. """ return self._variable.eval(session=session) def initialized_value(self): """Returns the value of the initialized variable. You should use this instead of the variable itself to initialize another variable with a value that depends on the value of this variable. Beware of using initialized_value except during initialization: initialized_value causes the Variable's initializer op to be run, so running this op resets the variable to the initial value. ```python # Initialize 'v' with a random tensor. v = tf.Variable(tf.truncated_normal([10, 40])) # Use `initialized_value` to guarantee that `v` has been # initialized before its value is used to initialize `w`. # The random values are picked only once. w = tf.Variable(v.initialized_value() * 2.0) ``` Returns: A `Tensor` holding the value of this variable after its initializer has run. """ with ops.control_dependencies(None): with ops.control_dependencies([self._initializer_op]): # TODO(vrv): Change this class to not take caching_device, but # to take the op to colocate the snapshot with, so we can use # colocation rather than devices. if self._caching_device is not None: with ops.device(self._caching_device): return array_ops.identity(self._variable) else: with ops.colocate_with(self._variable.op): return array_ops.identity(self._variable) @property def initial_value(self): """Returns the Tensor used as the initial value for the variable. Note that this is different from `initialized_value()` which runs the op that initializes the variable before returning its value. This method returns the tensor that is used by the op that initializes the variable. Returns: A `Tensor`. """ return self._initial_value def assign(self, value, use_locking=False): """Assigns a new value to the variable. This is essentially a shortcut for `assign(self, value)`. Args: value: A `Tensor`. The new value for this variable. use_locking: If `True`, use locking during the assignment. Returns: A `Tensor` that will hold the new value of this variable after the assignment has completed. """ return state_ops.assign(self._variable, value, use_locking=use_locking) def assign_add(self, delta, use_locking=False): """Adds a value to this variable. This is essentially a shortcut for `assign_add(self, delta)`. Args: delta: A `Tensor`. The value to add to this variable. use_locking: If `True`, use locking during the operation. Returns: A `Tensor` that will hold the new value of this variable after the addition has completed. """ return state_ops.assign_add(self._variable, delta, use_locking=use_locking) def assign_sub(self, delta, use_locking=False): """Subtracts a value from this variable. This is essentially a shortcut for `assign_sub(self, delta)`. Args: delta: A `Tensor`. The value to subtract from this variable. use_locking: If `True`, use locking during the operation. Returns: A `Tensor` that will hold the new value of this variable after the subtraction has completed. """ return state_ops.assign_sub(self._variable, delta, use_locking=use_locking) def scatter_sub(self, sparse_delta, use_locking=False): """Subtracts `IndexedSlices` from this variable. This is essentially a shortcut for `scatter_sub(self, sparse_delta.indices, sparse_delta.values)`. Args: sparse_delta: `IndexedSlices` to be subtracted from this variable. use_locking: If `True`, use locking during the operation. Returns: A `Tensor` that will hold the new value of this variable after the scattered subtraction has completed. Raises: ValueError: if `sparse_delta` is not an `IndexedSlices`. """ if not isinstance(sparse_delta, ops.IndexedSlices): raise ValueError("sparse_delta is not IndexedSlices: %s" % sparse_delta) return state_ops.scatter_sub( self._variable, sparse_delta.indices, sparse_delta.values, use_locking=use_locking) def count_up_to(self, limit): """Increments this variable until it reaches `limit`. When that Op is run it tries to increment the variable by `1`. If incrementing the variable would bring it above `limit` then the Op raises the exception `OutOfRangeError`. If no error is raised, the Op outputs the value of the variable before the increment. This is essentially a shortcut for `count_up_to(self, limit)`. Args: limit: value at which incrementing the variable raises an error. Returns: A `Tensor` that will hold the variable value before the increment. If no other Op modifies this variable, the values produced will all be distinct. """ return state_ops.count_up_to(self._variable, limit=limit) def load(self, value, session=None): """Load new value into this variable Writes new value to variable's memory. Doesn't add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. See @{tf.Session} for more information on launching a graph and on sessions. ```python v = tf.Variable([1, 2]) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) # Usage passing the session explicitly. v.load([2, 3], sess) print(v.eval(sess)) # prints [2 3] # Usage with the default session. The 'with' block # above makes 'sess' the default session. v.load([3, 4], sess) print(v.eval()) # prints [3 4] ``` Args: value: New variable value session: The session to use to evaluate this variable. If none, the default session is used. Raises: ValueError: Session is not passed and no default session """ session = session or ops.get_default_session() if session is None: raise ValueError( "Either session argument should be provided or default session " "should be established") session.run(self._initializer_op, {self._initializer_op.inputs[1]: value}) # Conversion to tensor. @staticmethod def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name """Utility function for converting a Variable to a Tensor.""" _ = name if dtype and not dtype.is_compatible_with(v.dtype): raise ValueError( "Incompatible type conversion requested to type '%s' for variable " "of type '%s'" % (dtype.name, v.dtype.name)) if as_ref: return v._ref() # pylint: disable=protected-access else: return v.value() @staticmethod def _OverloadAllOperators(): # pylint: disable=invalid-name """Register overloads for all operators.""" for operator in ops.Tensor.OVERLOADABLE_OPERATORS: Variable._OverloadOperator(operator) # For slicing, bind getitem differently than a tensor (use SliceHelperVar # instead) # pylint: disable=protected-access setattr(Variable, "__getitem__", array_ops._SliceHelperVar) @staticmethod def _OverloadOperator(operator): # pylint: disable=invalid-name """Defer an operator overload to `ops.Tensor`. We pull the operator out of ops.Tensor dynamically to avoid ordering issues. Args: operator: string. The operator name. """ def _run_op(a, *args): # pylint: disable=protected-access return getattr(ops.Tensor, operator)(a._AsTensor(), *args) # Propagate __doc__ to wrapper try: _run_op.__doc__ = getattr(ops.Tensor, operator).__doc__ except AttributeError: pass setattr(Variable, operator, _run_op) # NOTE(mrry): This enables the Variable's overloaded "right" binary # operators to run when the left operand is an ndarray, because it # accords the Variable class higher priority than an ndarray, or a # numpy matrix. # TODO(mrry): Convert this to using numpy's __numpy_ufunc__ # mechanism, which allows more control over how Variables interact # with ndarrays. __array_priority__ = 100 @property def name(self): """The name of this variable.""" return self._variable.name @property def initializer(self): """The initializer operation for this variable.""" return self._initializer_op @property def device(self): """The device of this variable.""" return self._variable.device @property def dtype(self): """The `DType` of this variable.""" return self._variable.dtype @property def op(self): """The `Operation` of this variable.""" return self._variable.op @property def graph(self): """The `Graph` of this variable.""" return self._variable.graph @property def shape(self): """The `TensorShape` of this variable. Returns: A `TensorShape`. """ return self._variable.get_shape() def get_shape(self): """Alias of Variable.shape.""" return self.shape def to_proto(self, export_scope=None): """Converts a `Variable` to a `VariableDef` protocol buffer. Args: export_scope: Optional `string`. Name scope to remove. Returns: A `VariableDef` protocol buffer, or `None` if the `Variable` is not in the specified name scope. """ if (export_scope is None or self._variable.name.startswith(export_scope)): var_def = variable_pb2.VariableDef() var_def.variable_name = ops.strip_name_scope( self._variable.name, export_scope) var_def.initializer_name = ops.strip_name_scope( self.initializer.name, export_scope) var_def.snapshot_name = ops.strip_name_scope( self._snapshot.name, export_scope) if self._save_slice_info: var_def.save_slice_info_def.MergeFrom(self._save_slice_info.to_proto( export_scope=export_scope)) return var_def else: return None @staticmethod def from_proto(variable_def, import_scope=None): """Returns a `Variable` object created from `variable_def`.""" return Variable(variable_def=variable_def, import_scope=import_scope) class SaveSliceInfo(object): """Information on how to save this Variable as a slice. Provides internal support for saving variables as slices of a larger variable. This API is not public and is subject to change. Available properties: * full_name * full_shape * var_offset * var_shape """ def __init__(self, full_name=None, full_shape=None, var_offset=None, var_shape=None, save_slice_info_def=None, import_scope=None): """Create a `SaveSliceInfo`. Args: full_name: Name of the full variable of which this `Variable` is a slice. full_shape: Shape of the full variable, as a list of int. var_offset: Offset of this `Variable` into the full variable, as a list of int. var_shape: Shape of this `Variable`, as a list of int. save_slice_info_def: `SaveSliceInfoDef` protocol buffer. If not `None`, recreates the SaveSliceInfo object its contents. `save_slice_info_def` and other arguments are mutually exclusive. import_scope: Optional `string`. Name scope to add. Only used when initializing from protocol buffer. """ if save_slice_info_def: assert isinstance(save_slice_info_def, variable_pb2.SaveSliceInfoDef) self.full_name = ops.prepend_name_scope( save_slice_info_def.full_name, import_scope=import_scope) self.full_shape = [i for i in save_slice_info_def.full_shape] self.var_offset = [i for i in save_slice_info_def.var_offset] self.var_shape = [i for i in save_slice_info_def.var_shape] else: self.full_name = full_name self.full_shape = full_shape self.var_offset = var_offset self.var_shape = var_shape @property def spec(self): """Computes the spec string used for saving.""" full_shape_str = " ".join(["%d" % d for d in self.full_shape]) + " " sl_spec = ":".join([ "%d,%d" % (o, s) for o, s in zip(self.var_offset, self.var_shape) ]) return full_shape_str + sl_spec def to_proto(self, export_scope=None): """Returns a SaveSliceInfoDef() proto. Args: export_scope: Optional `string`. Name scope to remove. Returns: A `SaveSliceInfoDef` protocol buffer, or None if the `Variable` is not in the specified name scope. """ if (export_scope is None or self.full_name.startswith(export_scope)): save_slice_info_def = variable_pb2.SaveSliceInfoDef() save_slice_info_def.full_name = ops.strip_name_scope( self.full_name, export_scope) for i in self.full_shape: save_slice_info_def.full_shape.append(i) for i in self.var_offset: save_slice_info_def.var_offset.append(i) for i in self.var_shape: save_slice_info_def.var_shape.append(i) return save_slice_info_def else: return None def _set_save_slice_info(self, save_slice_info): """Sets the slice info for this `Variable`. Args: save_slice_info: A `Variable.SaveSliceInfo` object. """ self._save_slice_info = save_slice_info def _get_save_slice_info(self): return self._save_slice_info class PartitionedVariable(object): """A container for partitioned `Variable` objects.""" class PartitionedVariableIterator(object): """An iterator that allows accessing the underlying `Variable` objects. This iterator is necessary to control order of access when Variables are not partitioned in a standard way along a single axis. Allows e.g. `list(partitioned_variable)` to return a proper list. """ def __init__(self, partitioned_variable): self._ix = 0 self._partitioned_variable = partitioned_variable def __iter__(self): return self def __next__(self): # For python3 compatibility. return self.next() def next(self): # pylint: disable=protected-access if self._ix >= len(self._partitioned_variable._variable_list): raise StopIteration() variable = self._partitioned_variable._variable_list[self._ix] # pylint: enable=protected-access self._ix += 1 return variable def __init__(self, name, shape, dtype, variable_list, partitions): """Creates a new partitioned variable wrapper. Variables passed via the variable_list must contain a save_slice_info field. Concatenation and iteration is in lexicographic order according to the var_offset property of the save_slice_info. Args: name: String. Overall name of the variables. shape: List of integers. Overall shape of the variables. dtype: Type of the variables. variable_list: List of `Variable` that comprise this partitioned variable. partitions: List of integers. Number of partitions for each dimension. Raises: TypeError: If `variable_list` is not a list of `Variable` objects, or `partitions` is not a list. ValueError: If `variable_list` is empty, or the `Variable` shape information does not match `shape`, or `partitions` has invalid values. """ if not isinstance(variable_list, (list, tuple)): raise TypeError( "variable_list is not a list or tuple: %s" % variable_list) if not isinstance(partitions, (list, tuple)): raise TypeError("partitions is not a list or tuple: %s" % partitions) if not all([p >= 1 for p in partitions]): raise ValueError("partition values must be positive: %s" % partitions) if not variable_list: raise ValueError("variable_list may not be empty") # pylint: disable=protected-access for v in variable_list: # Sort the variable_list lexicographically according to var offset value. if not all([v._get_save_slice_info() is not None for v in variable_list]): raise ValueError( "All variables must have a save_slice_info available: %s" % [v.name for v in variable_list]) if len(shape) != len(partitions): raise ValueError("len(shape) != len(partitions): %s vs. %s" % (shape, partitions)) if not all([v._get_save_slice_info().full_shape == shape]): raise ValueError( "All variables' full shapes must match shape: %s; " "but full shapes were: %s" % (shape, str([v._get_save_slice_info().full_shape]))) self._variable_list = sorted( variable_list, key=lambda v: v._get_save_slice_info().var_offset) # pylint: enable=protected-access self._name = name self._shape = shape self._dtype = dtype self._partitions = partitions self._as_tensor = None def __iter__(self): """Return an iterable for accessing the underlying partition Variables.""" return self.PartitionedVariableIterator(self) def __len__(self): num_partition_axes = len(self._partition_axes()) if num_partition_axes > 1: raise ValueError("Cannot get a length for %d > 1 partition axes" % num_partition_axes) return len(self._variable_list) def _partition_axes(self): if all([p == 1 for p in self._partitions]): return [0] else: return [i for i, p in enumerate(self._partitions) if p > 1] def _concat(self): """Returns the overall concatenated value as a `Tensor`. This is different from using the partitioned variable directly as a tensor (through tensor conversion and `as_tensor`) in that it creates a new set of operations that keeps the control dependencies from its scope. Returns: `Tensor` containing the concatenated value. """ if len(self._variable_list) == 1: with ops.name_scope(None): return array_ops.identity(self._variable_list[0], name=self._name) partition_axes = self._partition_axes() if len(partition_axes) > 1: raise NotImplementedError( "Cannot concatenate along more than one dimension: %s. " "Multi-axis partition concat is not supported" % str(partition_axes)) partition_ix = partition_axes[0] with ops.name_scope(self._name + "/ConcatPartitions/"): concatenated = array_ops.concat(self._variable_list, partition_ix) with ops.name_scope(None): return array_ops.identity(concatenated, name=self._name) def as_tensor(self): """Returns the overall concatenated value as a `Tensor`. The returned tensor will not inherit the control dependencies from the scope where the value is used, which is similar to getting the value of `Variable`. Returns: `Tensor` containing the concatenated value. """ with ops.control_dependencies(None): return self._concat() @staticmethod def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name _ = name if dtype is not None and not dtype.is_compatible_with(v.dtype): raise ValueError( "Incompatible type conversion requested to type '%s' for variable " "of type '%s'" % (dtype.name, v.dtype.name)) if as_ref: raise NotImplementedError( "PartitionedVariable doesn't support being used as a reference.") else: return v.as_tensor() @property def name(self): return self._name @property def dtype(self): return self._dtype def get_shape(self): return self._shape def _get_variable_list(self): return self._variable_list def _get_partitions(self): return self._partitions def assign(self, value, use_locking=False): _ = value, use_locking raise NotImplementedError( "assign() has not been implemented for PartitionedVariable.") def global_variables(): """Returns global variables. Global variables are variables that are shared across machines in a distributed environment. The `Variable()` constructor or `get_variable()` automatically adds new variables to the graph collection `GraphKeys.GLOBAL_VARIABLES`. This convenience function returns the contents of that collection. An alternative to global variables are local variables. See @{tf.local_variables} Returns: A list of `Variable` objects. """ return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) @deprecated("2017-03-02", "Please use tf.global_variables instead.") def all_variables(): """See `tf.global_variables`.""" return global_variables() def _all_saveable_objects(): """Returns all variables and `SaveableObject`s that must be checkpointed. Returns: A list of `Variable` and `SaveableObject` to be checkpointed """ # TODO(andreasst): make this function public once things are settled. return (ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) + ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS)) def local_variables(): """Returns local variables. Local variables - per process variables, usually not saved/restored to checkpoint and used for temporary or intermediate values. For example, they can be used as counters for metrics computation or number of epochs this machine has read data. The `tf.contrib.framework.local_variable()` function automatically adds the new variable to `GraphKeys.LOCAL_VARIABLES`. This convenience function returns the contents of that collection. An alternative to local variables are global variables. See @{tf.global_variables} Returns: A list of local `Variable` objects. """ return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES) def model_variables(): """Returns all variables in the MODEL_VARIABLES collection. Returns: A list of local Variable objects. """ return ops.get_collection(ops.GraphKeys.MODEL_VARIABLES) def trainable_variables(): """Returns all variables created with `trainable=True`. When passed `trainable=True`, the `Variable()` constructor automatically adds new variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This convenience function returns the contents of that collection. Returns: A list of Variable objects. """ return ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) def moving_average_variables(): """Returns all variables that maintain their moving averages. If an `ExponentialMovingAverage` object is created and the `apply()` method is called on a list of variables, these variables will be added to the `GraphKeys.MOVING_AVERAGE_VARIABLES` collection. This convenience function returns the contents of that collection. Returns: A list of Variable objects. """ return ops.get_collection(ops.GraphKeys.MOVING_AVERAGE_VARIABLES) def variables_initializer(var_list, name="init"): """Returns an Op that initializes a list of variables. After you launch the graph in a session, you can run the returned Op to initialize all the variables in `var_list`. This Op runs all the initializers of the variables in `var_list` in parallel. Calling `initialize_variables()` is equivalent to passing the list of initializers to `Group()`. If `var_list` is empty, however, the function still returns an Op that can be run. That Op just has no effect. Args: var_list: List of `Variable` objects to initialize. name: Optional name for the returned operation. Returns: An Op that run the initializers of all the specified variables. """ if var_list: return control_flow_ops.group(*[v.initializer for v in var_list], name=name) return control_flow_ops.no_op(name=name) @deprecated("2017-03-02", "Use `tf.variables_initializer` instead.") def initialize_variables(var_list, name="init"): """See `tf.variables_initializer`.""" return variables_initializer(var_list, name=name) def global_variables_initializer(): """Returns an Op that initializes global variables. This is just a shortcut for `variable_initializers(global_variables())` Returns: An Op that initializes global variables in the graph. """ return variables_initializer(global_variables()) @deprecated("2017-03-02", "Use `tf.global_variables_initializer` instead.") def initialize_all_variables(): """See `tf.global_variables_initializer`.""" return global_variables_initializer() def local_variables_initializer(): """Returns an Op that initializes all local variables. This is just a shortcut for `variable_initializers(local_variables())` Returns: An Op that initializes all local variables in the graph. """ return variables_initializer(local_variables()) @deprecated("2017-03-02", "Use `tf.local_variables_initializer` instead.") def initialize_local_variables(): """See `tf.local_variables_initializer`.""" return local_variables_initializer() def is_variable_initialized(variable): """Tests if a variable has been initialized. Args: variable: A `Variable`. Returns: Returns a scalar boolean Tensor, `True` if the variable has been initialized, `False` otherwise. """ return state_ops.is_variable_initialized(variable) def assert_variables_initialized(var_list=None): """Returns an Op to check if variables are initialized. NOTE: This function is obsolete and will be removed in 6 months. Please change your implementation to use `report_uninitialized_variables()`. When run, the returned Op will raise the exception `FailedPreconditionError` if any of the variables has not yet been initialized. Note: This function is implemented by trying to fetch the values of the variables. If one of the variables is not initialized a message may be logged by the C++ runtime. This is expected. Args: var_list: List of `Variable` objects to check. Defaults to the value of `global_variables().` Returns: An Op, or None if there are no variables. """ if var_list is None: var_list = global_variables() + local_variables() # Backwards compatibility for old-style variables. TODO(touts): remove. if not var_list: var_list = [] for op in ops.get_default_graph().get_operations(): if op.type in ["Variable", "VariableV2", "AutoReloadVariable"]: var_list.append(op.outputs[0]) if not var_list: return None else: ranks = [] for var in var_list: with ops.colocate_with(var.op): ranks.append(array_ops.rank_internal(var, optimize=False)) if len(ranks) == 1: return ranks[0] else: return array_ops.stack(ranks) def report_uninitialized_variables(var_list=None, name="report_uninitialized_variables"): """Adds ops to list the names of uninitialized variables. When run, it returns a 1-D tensor containing the names of uninitialized variables if there are any, or an empty array if there are none. Args: var_list: List of `Variable` objects to check. Defaults to the value of `global_variables() + local_variables()` name: Optional name of the `Operation`. Returns: A 1-D tensor containing names of the uninitialized variables, or an empty 1-D tensor if there are no variables or no uninitialized variables. """ if var_list is None: var_list = global_variables() + local_variables() # Backwards compatibility for old-style variables. TODO(touts): remove. if not var_list: var_list = [] for op in ops.get_default_graph().get_operations(): if op.type in ["Variable", "VariableV2", "AutoReloadVariable"]: var_list.append(op.outputs[0]) with ops.name_scope(name): if not var_list: # Return an empty tensor so we only need to check for returned tensor # size being 0 as an indication of model ready. return array_ops.constant([], dtype=dtypes.string) else: # Get a 1-D boolean tensor listing whether each variable is initialized. variables_mask = math_ops.logical_not( array_ops.stack( [state_ops.is_variable_initialized(v) for v in var_list])) # Get a 1-D string tensor containing all the variable names. variable_names_tensor = array_ops.constant([s.op.name for s in var_list]) # Return a 1-D tensor containing all the names of uninitialized variables. return array_ops.boolean_mask(variable_names_tensor, variables_mask) # pylint: disable=protected-access ops.register_tensor_conversion_function(Variable, Variable._TensorConversionFunction) Variable._OverloadAllOperators() ops.register_tensor_conversion_function( PartitionedVariable, PartitionedVariable._TensorConversionFunction) # pylint: enable=protected-access ops.register_dense_tensor_like_type(Variable)
apache-2.0
potato/searx
searx/engines/google_news.py
1
2179
""" Google (News) @website https://news.google.com @provide-api no @using-api no @results HTML @stable no @parse url, title, content, publishedDate """ from lxml import html from searx.engines.google import _fetch_supported_languages, supported_languages_url from searx.url_utils import urlencode # search-url categories = ['news'] paging = True language_support = True safesearch = True time_range_support = True number_of_results = 10 search_url = 'https://www.google.com/search'\ '?{query}'\ '&tbm=nws'\ '&gws_rd=cr'\ '&{search_options}' time_range_attr = "qdr:{range}" time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'} # do search-request def request(query, params): search_options = { 'start': (params['pageno'] - 1) * number_of_results } if params['time_range'] in time_range_dict: search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']]) if safesearch and params['safesearch']: search_options['safe'] = 'on' params['url'] = search_url.format(query=urlencode({'q': query}), search_options=urlencode(search_options)) if params['language'] != 'all': language_array = params['language'].lower().split('-') params['url'] += '&lr=lang_' + language_array[0] return params # get response from search-request def response(resp): results = [] dom = html.fromstring(resp.text) # parse results for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'): try: r = { 'url': result.xpath('.//div[@class="_cnc"]//a/@href')[0], 'title': ''.join(result.xpath('.//div[@class="_cnc"]//h3//text()')), 'content': ''.join(result.xpath('.//div[@class="st"]//text()')), } except: continue imgs = result.xpath('.//img/@src') if len(imgs) and not imgs[0].startswith('data'): r['img_src'] = imgs[0] results.append(r) # return results return results
agpl-3.0
pacoqueen/bbinn
formularios/consulta_ventas_solo_tickets.py
1
29443
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2005-2008 Francisco José Rodríguez Bogado # # (pacoqueen@users.sourceforge.net) # # # # This file is part of GeotexInn. # # # # GeotexInn 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. # # # # GeotexInn 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 GeotexInn; if not, write to the Free Software # # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # ############################################################################### ################################################################### ## consulta_ventas_solo_tickets.py - sum((PVP - IVA) * porcentaje_tarifa) ################################################################### ## NOTAS: ## - Solo cuenta lineas de venta, no servicios (que además no se ## pueden vender por TPV, ergo no tienen ticket). ## - Las LDVs de tickets facturados se ignoran. ################################################################### ## Changelog: ## ################################################################### ## Consulta tanto por ticket como agrupada por tipo de material (familia). ################################################################### from ventana import Ventana import utils import pygtk pygtk.require('2.0') import gtk, gtk.glade, time, sqlobject import sys, os try: import pclases except ImportError: sys.path.append(os.path.join('..', 'framework')) import pclases import mx try: import geninformes except ImportError: sys.path.append(os.path.join('..', 'informes')) import geninformes try: from treeview2pdf import treeview2pdf except ImportError: sys.path.append(os.path.join("..", "informes")) from treeview2pdf import treeview2pdf try: from treeview2csv import treeview2csv except ImportError: sys.path.append(os.path.join("..", "informes")) from treeview2pdf import treeview2pdf from informes import abrir_pdf, abrir_csv import ventana_progreso class ConsultaBeneficioSoloTickets(Ventana): def __init__(self, objeto = None, usuario = None): self.usuario = usuario Ventana.__init__(self, 'consulta_ventas_ticket.glade', objeto) connections = {'b_salir/clicked': self.salir, 'b_buscar/clicked': self.buscar, 'b_imprimir/clicked': self.imprimir, 'b_exportar/clicked': self.exportar, 'b_fecha_inicio/clicked': self.set_inicio, 'b_fecha_fin/clicked': self.set_fin} self.add_connections(connections) cols = (('Fecha', 'gobject.TYPE_STRING', False, True, False, None), ('Ticket', 'gobject.TYPE_STRING',False,True,True,None), ('Imp. total', 'gobject.TYPE_STRING',False,True,False,None), ('Imp. (s/IVA)','gobject.TYPE_STRING',False,True,False,None), ('Ben. sobre tarifa', 'gobject.TYPE_STRING', False, True, False, None), ('ID','gobject.TYPE_STRING', False, False, False, None)) utils.preparar_treeview(self.wids['tv_datos'], cols) for col in self.wids['tv_datos'].get_columns()[2:]: for cell in col.get_cell_renderers(): cell.set_property("xalign", 1.0) col.set_alignment(0.5) self.wids['tv_datos'].connect("row-activated", self.abrir_producto) self.fin = mx.DateTime.today() #self.inicio = mx.DateTime.DateTimeFrom(day = 1, month = self.fin.month, year = self.fin.year) self.inicio = self.fin self.wids['e_fechafin'].set_text(utils.str_fecha(self.fin)) self.wids['e_fechainicio'].set_text(utils.str_fecha(self.inicio)) self.wids['hbox1'].set_property("visible", False) self.wids['hbox6'].set_property("visible", False) gtk.main() def abrir_producto(self, tv, path, vc): """ Abre el producto al que se le ha hecho doble clic en una ventana nueva. """ model = tv.get_model() tipo_e_id = model[path][-1] if "LDV" in tipo_e_id: tipo, id = tipo_e_id.split(':') ldv = pclases.LineaDeVenta.get(id) producto = ldv.producto if isinstance(producto, pclases.ProductoVenta): if producto.es_rollo(): import productos_de_venta_rollos ventana_producto = productos_de_venta_rollos.ProductosDeVentaRollos(producto, usuario = self.usuario) elif producto.es_bala() or producto.es_bigbag(): import productos_de_venta_balas ventana_producto = productos_de_venta_balas.ProductosDeVentaBalas(producto, usuario = self.usuario) elif isinstance(producto, pclases.ProductoCompra): import productos_compra ventana_producto = productos_compra.ProductosCompra(producto, usuario = self.usuario) def chequear_cambios(self): pass def rellenar_tabla_por_ticket(self, resultados): """ Rellena el model con los items de la consulta """ model = self.wids['tv_datos'].get_model() model.clear() totfact = totsiniva = totbeneficio = totbeneficio_cobro = 0.0 self.wids['tv_datos'].freeze_child_notify() self.wids['tv_datos'].set_model(None) totcobrado = totpendiente = 0.0 total_costo = total_costo_cobrado = 0.0 tratados = {} for material in resultados: for fecha in resultados[material]: if fecha: str_fecha = utils.str_fecha(fecha) else: str_fecha = "" for ldv in resultados[material][fecha]: # Para que coincidan los totales con la suma de las # columnas y por coherencia con todas las cifras de la # ventana, es necesario redondear a 2 decimales. subtotal = round(ldv.get_subtotal(iva = True), 2) subtotal_siva = round(ldv.get_subtotal(iva = False), 2) beneficio = round(ldv.calcular_beneficio(), 2) costo = round(ldv.calcular_precio_costo()*ldv.cantidad, 2) fac_alb_tic = "Ticket %d" % ldv.ticket.numticket cobrado = subtotal pendiente = 0.0 beneficio_cobro = beneficio costo_cobrado = costo # Los tickets se asume que se cobran siempre, por # tanto el costo de los productos sobre lo cobrado # es del 100%. desc_producto = utils.wrap(ldv.producto.descripcion, 40) try: beneficio_costo = 100.0 * beneficio / costo except ZeroDivisionError: beneficio_costo = 0.0 if ldv.ticket not in tratados: padre_ticket = model.append(None, (str_fecha, ldv.ticket.numticket, "0", "0", "0", "")) tratados[ldv.ticket] = padre_ticket else: padre_ticket = tratados[ldv.ticket] model.append(padre_ticket, (desc_producto, fac_alb_tic, utils.float2str(subtotal), utils.float2str(subtotal_siva), "%s (%s%%)" % ( utils.float2str(beneficio), utils.float2str( beneficio_costo)), "LDV:%d" % ldv.id)) # Actualizo totales en memoria y en nodos padre TreeView totfact += subtotal totsiniva += subtotal_siva totbeneficio += beneficio totbeneficio_cobro += beneficio_cobro totcobrado += cobrado totpendiente += pendiente total_costo += costo total_costo_cobrado += costo_cobrado model[padre_ticket][2] = utils.float2str( utils._float(model[padre_ticket][2]) + subtotal) model[padre_ticket][3] = utils.float2str( utils._float(model[padre_ticket][3]) + subtotal_siva) model[padre_ticket][4] = utils.float2str( utils._float(model[padre_ticket][4]) + beneficio) self.rellenar_totales(totfact, totsiniva, totbeneficio, totcobrado, totpendiente, totbeneficio_cobro, total_costo, total_costo_cobrado) self.wids['tv_datos'].set_model(model) self.wids['tv_datos'].thaw_child_notify() def rellenar_tabla(self, resultados): """ Rellena el model con los items de la consulta """ model = self.wids['tv_datos'].get_model() model.clear() totfact = totsiniva = totbeneficio = totbeneficio_cobro = 0.0 self.wids['tv_datos'].freeze_child_notify() self.wids['tv_datos'].set_model(None) totcobrado = totpendiente = 0.0 total_costo = total_costo_cobrado = 0.0 for material in resultados: if material != None: nombre_mat = material.descripcion else: nombre_mat = "" padre_mat = model.append(None, (nombre_mat, "", "0", "0", "0", "M:%d" % (material and material.id or -1))) for fecha in resultados[material]: if fecha: str_fecha = utils.str_fecha(fecha) else: str_fecha = "" padre_fec = model.append(padre_mat, (str_fecha, "", "0", "0", "0", "")) for ldv in resultados[material][fecha]: # Para que coincidan los totales con la suma de las # columnas y por coherencia con todas las cifras de la # ventana, es necesario redondear a 2 decimales. subtotal = round(ldv.get_subtotal(iva = True), 2) subtotal_siva = round(ldv.get_subtotal(iva = False), 2) beneficio = round(ldv.calcular_beneficio(), 2) costo = round(ldv.calcular_precio_costo()*ldv.cantidad, 2) if ldv.facturaVenta: fac_alb_tic = ldv.facturaVenta.numfactura cobradofra = ldv.facturaVenta.calcular_cobrado() pendientefra = ldv.facturaVenta.calcular_pendiente_cobro() try: fraccion = cobradofra / (cobradofra + pendientefra) except ZeroDivisionError: fraccion = 1.0 cobrado = subtotal * fraccion pendiente = subtotal - cobrado beneficio_cobro = beneficio * fraccion costo_cobrado = costo * fraccion elif ldv.albaranSalida: fac_alb_tic = ldv.albaranSalida.numalbaran cobrado = 0.0 pendiente = subtotal beneficio_cobro = 0.0 costo_cobrado = 0.0 elif ldv.ticket: fac_alb_tic = "Ticket %d" % ldv.ticket.numticket cobrado = subtotal pendiente = 0.0 beneficio_cobro = beneficio costo_cobrado = costo # Los tickets se asume que se cobran siempre, por # tanto el costo de los productos sobre lo cobrado # es del 100%. else: fac_alb_tic = "" cobrado = pendiente = beneficio_cobro = 0.0 costo_cobrado = 0.0 desc_producto = utils.wrap(ldv.producto.descripcion, 40) try: beneficio_costo = 100.0 * beneficio / costo except ZeroDivisionError: beneficio_costo = 0.0 model.append(padre_fec, (desc_producto, fac_alb_tic, utils.float2str(subtotal), utils.float2str(subtotal_siva), "%s (%s%%)" % ( utils.float2str(beneficio), utils.float2str( beneficio_costo)), "LDV:%d" % ldv.id)) # Actualizo totales en memoria y en nodos padre TreeView totfact += subtotal totsiniva += subtotal_siva totbeneficio += beneficio totbeneficio_cobro += beneficio_cobro totcobrado += cobrado totpendiente += pendiente total_costo += costo total_costo_cobrado += costo_cobrado model[padre_fec][2] = utils.float2str( utils._float(model[padre_fec][2]) + subtotal) model[padre_fec][3] = utils.float2str( utils._float(model[padre_fec][3]) + subtotal_siva) model[padre_fec][4] = utils.float2str( utils._float(model[padre_fec][4]) + beneficio) model[padre_mat][2] = utils.float2str( utils._float(model[padre_mat][2]) + subtotal) model[padre_mat][3] = utils.float2str( utils._float(model[padre_mat][3]) + subtotal_siva) model[padre_mat][4] = utils.float2str( utils._float(model[padre_mat][4]) + beneficio) self.rellenar_totales(totfact, totsiniva, totbeneficio, totcobrado, totpendiente, totbeneficio_cobro, total_costo, total_costo_cobrado) self.wids['tv_datos'].set_model(model) self.wids['tv_datos'].thaw_child_notify() def rellenar_tabla_por_proveedor(self, resultados): """ Rellena el model con los items de la consulta """ model = self.wids['tv_datos'].get_model() model.clear() totfact = totsiniva = totbeneficio = totbeneficio_cobro = 0.0 self.wids['tv_datos'].freeze_child_notify() self.wids['tv_datos'].set_model(None) totcobrado = totpendiente = 0.0 total_costo = total_costo_cobrado = 0.0 padres = {} for material in resultados: for fecha in resultados[material]: for ldv in resultados[material][fecha]: # Para que coincidan los totales con la suma de las # columnas y por coherencia con todas las cifras de la # ventana, es necesario redondear a 2 decimales. subtotal = round(ldv.get_subtotal(iva = True), 2) subtotal_siva = round(ldv.get_subtotal(iva = False), 2) beneficio = round(ldv.calcular_beneficio(), 2) costo = round(ldv.calcular_precio_costo()*ldv.cantidad, 2) if ldv.facturaVenta: fac_alb_tic = ldv.facturaVenta.numfactura cobradofra = ldv.facturaVenta.calcular_cobrado() pendientefra = ldv.facturaVenta.calcular_pendiente_cobro() try: fraccion = cobradofra / (cobradofra + pendientefra) except ZeroDivisionError: fraccion = 1.0 cobrado = subtotal * fraccion pendiente = subtotal - cobrado beneficio_cobro = beneficio * fraccion costo_cobrado = costo * fraccion elif ldv.albaranSalida: fac_alb_tic = ldv.albaranSalida.numalbaran cobrado = 0.0 pendiente = subtotal beneficio_cobro = 0.0 costo_cobrado = 0.0 elif ldv.ticket: fac_alb_tic = "Ticket %d" % ldv.ticket.numticket cobrado = subtotal pendiente = 0.0 beneficio_cobro = beneficio costo_cobrado = costo # Los tickets se asume que se cobran siempre, por # tanto el costo de los productos sobre lo cobrado # es del 100%. else: fac_alb_tic = "" cobrado = pendiente = beneficio_cobro = 0.0 costo_cobrado = 0.0 desc_producto = utils.wrap(ldv.producto.descripcion, 40) try: beneficio_costo = 100.0 * beneficio / costo except ZeroDivisionError: beneficio_costo = 0.0 proveedor = ldv.get_proveedor() try: padre = padres[proveedor] except KeyError: padre = padres[proveedor] = model.append(None, (proveedor and proveedor.nombre or "Sin proveedor", "-", utils.float2str(0.0), utils.float2str(0.0), utils.float2str(0.0), proveedor and proveedor.get_puid() or "" )) model.append(padre, (desc_producto, fac_alb_tic, utils.float2str(subtotal), utils.float2str(subtotal_siva), "%s (%s%%)" % ( utils.float2str(beneficio), utils.float2str( beneficio_costo)), ldv.get_puid() )) # Actualizo totales en memoria y en nodos padre TreeView totfact += subtotal totsiniva += subtotal_siva totbeneficio += beneficio totbeneficio_cobro += beneficio_cobro totcobrado += cobrado totpendiente += pendiente total_costo += costo total_costo_cobrado += costo_cobrado model[padre][2] = utils.float2str( utils._float(model[padre][2]) + subtotal) model[padre][3] = utils.float2str( utils._float(model[padre][3]) + subtotal_siva) model[padre][4] = utils.float2str( utils._float(model[padre][4]) + beneficio) self.rellenar_totales(totfact, totsiniva, totbeneficio, totcobrado, totpendiente, totbeneficio_cobro, total_costo, total_costo_cobrado) self.wids['tv_datos'].set_model(model) self.wids['tv_datos'].thaw_child_notify() def rellenar_totales(self, total_facturado, total_siniva, total_beneficio, total_cobrado, total_pendiente_de_cobro, total_beneficio_de_lo_cobrado, total_costo, total_costo_cobrado): """ Introduce los totales en los "entries". """ self.wids['e_total'].set_text(utils.float2str(total_facturado)) self.wids['e_siniva'].set_text(utils.float2str(total_siniva)) try: beneficio = total_beneficio * 100.0 / total_siniva except ZeroDivisionError: beneficio = 0 try: beneficio_sobre_costo = total_beneficio * 100.0 / total_costo except ZeroDivisionError: beneficio_sobre_costo = 0 try: beneficio_cobro = (total_beneficio_de_lo_cobrado * 100.0 / total_cobrado) except ZeroDivisionError: beneficio_cobro = 0 try: beneficio_cobro_sobre_costo = (100 * total_beneficio_de_lo_cobrado / total_costo_cobrado) except ZeroDivisionError: beneficio_cobro_sobre_costo = 0 #self.wids['e_beneficio'].set_text("%s (%s%% de las ventas; %s%% sobre precio defecto)" % ( self.wids['e_beneficio'].set_text("%s (%s%% sobre precio defecto)" % ( utils.float2str(total_beneficio), utils.float2str(beneficio_sobre_costo, 2, autodec = True))) #self.wids['e_beneficio_cobro'].set_text("%s (%s%% de lo cobrado; %s%% sobre precio defecto en cobros)" % ( self.wids['e_beneficio_cobro'].set_text("%s (%s%% sobre precio defecto en cobros)" % ( utils.float2str(total_beneficio_de_lo_cobrado), utils.float2str(beneficio_cobro_sobre_costo, 2, autodec = True))) self.wids['e_cobrado'].set_text(utils.float2str(total_cobrado)) self.wids['e_pendiente'].set_text( utils.float2str(total_pendiente_de_cobro)) def set_inicio(self, boton): temp = utils.mostrar_calendario(fecha_defecto = self.inicio, padre = self.wids['ventana']) self.inicio = mx.DateTime.DateTimeFrom(day = temp[0], month = temp[1], year = temp[2]) self.wids['e_fechainicio'].set_text(utils.str_fecha(self.inicio)) self.fin = self.inicio self.wids['e_fechafin'].set_text(utils.str_fecha(self.fin)) def set_fin(self, boton): temp = utils.mostrar_calendario(fecha_defecto = self.fin, padre = self.wids['ventana']) self.fin = temp self.fin = mx.DateTime.DateTimeFrom(day = temp[0], month = temp[1], year = temp[2]) self.wids['e_fechafin'].set_text(utils.str_fecha(self.fin)) def buscar(self,boton): """ Dadas fecha de inicio y de fin, busca todas las LDV de tickets sin factura (ni albarán, lógicamente). OJO: NO CUENTA SERVICIOS. """ vpro = ventana_progreso.VentanaProgreso(padre = self.wids['ventana']) vpro.mostrar() inicio = self.inicio fin = self.fin LDV = pclases.LineaDeVenta FV = pclases.FacturaVenta AS = pclases.AlbaranSalida T = pclases.Ticket ldvst = LDV.select(pclases.AND(LDV.q.ticketID == T.q.id, LDV.q.albaranSalidaID == None, LDV.q.facturaVentaID == None, T.q.fechahora >= inicio, T.q.fechahora < fin + mx.DateTime.oneDay)) self.resultados = {} act = 0.0; tot = ldvst.count() for ldv in ldvst: vpro.set_valor(act/tot, "Calculando beneficio tickets...") add_ldv_a_diccionario_resultados(ldv, self.resultados) act += 1 vpro.set_valor(1.0, "Calculando totales...") if self.wids['rb_por_familia'].get_active(): self.rellenar_tabla(self.resultados) elif self.wids['rb_por_ticket'].get_active(): self.rellenar_tabla_por_ticket(self.resultados) elif self.wids['rb_por_proveedor'].get_active(): self.rellenar_tabla_por_proveedor(self.resultados) vpro.ocultar() def imprimir(self, boton): """ Prepara la vista preliminar para la impresión del informe. """ resp = utils.dialogo(titulo = "¿IMPRIMIR DESGLOSE?", texto = "Puede imprimir un resumen o todo el " "contenido de la consulta\n" "¿Desea imprimir toda la información " "desglosada?", padre = self.wids['ventana']) if resp: tv = self.wids['tv_datos'] tv.expand_all() while gtk.events_pending(): gtk.main_iteration(False) colstotales = [] else: tv = self.wids['tv_datos'] tv.collapse_all() while gtk.events_pending(): gtk.main_iteration(False) from consulta_ventas_por_producto import convertir_a_listview tv = convertir_a_listview(tv) colstotales = [2, 3, 4] strfecha = "De %s a %s" % (self.wids['e_fechainicio'].get_text(), self.wids['e_fechafin'].get_text()) abrir_pdf(treeview2pdf(tv, titulo = "Beneficio sobre tarifa (tickets)", fecha = strfecha, numcols_a_totalizar = colstotales)) def exportar(self, boton): """ Exporta el TreeView a CSV. """ abrir_csv(treeview2csv(self.wids['tv_datos'])) def add_ldv_a_diccionario_resultados(ldv, r): if ldv.productoCompra: material = ldv.productoCompra.tipoDeMaterial else: material = None if material not in r: r[material] = {} if ldv.facturaVenta: fecha = ldv.facturaVenta.fecha elif ldv.albaranSalida: fecha = ldv.albaranSalida.fecha elif ldv.ticket: fecha = utils.abs_mxfecha(ldv.ticket.fechahora) else: fecha = None if fecha not in r[material]: r[material][fecha] = [ldv] else: r[material][fecha].append(ldv) if __name__ == '__main__': t = ConsultaBeneficioSoloTickets()
gpl-2.0
ClovisIRex/Snake-django
env/lib/python3.6/site-packages/django/contrib/gis/geoip/prototypes.py
23
3950
from ctypes import POINTER, Structure, c_char_p, c_float, c_int, string_at from django.contrib.gis.geoip.libgeoip import free, lgeoip # #### GeoIP C Structure definitions #### class GeoIPRecord(Structure): _fields_ = [('country_code', c_char_p), ('country_code3', c_char_p), ('country_name', c_char_p), ('region', c_char_p), ('city', c_char_p), ('postal_code', c_char_p), ('latitude', c_float), ('longitude', c_float), # TODO: In 1.4.6 this changed from `int dma_code;` to # `union {int metro_code; int dma_code;};`. Change # to a `ctypes.Union` in to accommodate in future when # pre-1.4.6 versions are no longer distributed. ('dma_code', c_int), ('area_code', c_int), ('charset', c_int), ('continent_code', c_char_p), ] geoip_char_fields = [name for name, ctype in GeoIPRecord._fields_ if ctype is c_char_p] GEOIP_DEFAULT_ENCODING = 'iso-8859-1' geoip_encodings = { 0: 'iso-8859-1', 1: 'utf8', } class GeoIPTag(Structure): pass RECTYPE = POINTER(GeoIPRecord) DBTYPE = POINTER(GeoIPTag) # #### ctypes function prototypes #### # GeoIP_lib_version appeared in version 1.4.7. if hasattr(lgeoip, 'GeoIP_lib_version'): GeoIP_lib_version = lgeoip.GeoIP_lib_version GeoIP_lib_version.argtypes = None GeoIP_lib_version.restype = c_char_p else: GeoIP_lib_version = None # For freeing memory allocated within a record GeoIPRecord_delete = lgeoip.GeoIPRecord_delete GeoIPRecord_delete.argtypes = [RECTYPE] GeoIPRecord_delete.restype = None # For retrieving records by name or address. def check_record(result, func, cargs): if result: # Checking the pointer to the C structure, if valid pull out elements # into a dictionary. rec = result.contents record = {fld: getattr(rec, fld) for fld, ctype in rec._fields_} # Now converting the strings to unicode using the proper encoding. encoding = geoip_encodings[record['charset']] for char_field in geoip_char_fields: if record[char_field]: record[char_field] = record[char_field].decode(encoding) # Free the memory allocated for the struct & return. GeoIPRecord_delete(result) return record else: return None def record_output(func): func.argtypes = [DBTYPE, c_char_p] func.restype = RECTYPE func.errcheck = check_record return func GeoIP_record_by_addr = record_output(lgeoip.GeoIP_record_by_addr) GeoIP_record_by_name = record_output(lgeoip.GeoIP_record_by_name) # For opening & closing GeoIP database files. GeoIP_open = lgeoip.GeoIP_open GeoIP_open.restype = DBTYPE GeoIP_delete = lgeoip.GeoIP_delete GeoIP_delete.argtypes = [DBTYPE] GeoIP_delete.restype = None # This is so the string pointer can be freed within Python. class geoip_char_p(c_char_p): pass def check_string(result, func, cargs): if result: s = string_at(result) free(result) else: s = '' return s.decode(GEOIP_DEFAULT_ENCODING) GeoIP_database_info = lgeoip.GeoIP_database_info GeoIP_database_info.restype = geoip_char_p GeoIP_database_info.errcheck = check_string # String output routines. def string_output(func): def _err_check(result, func, cargs): if result: return result.decode(GEOIP_DEFAULT_ENCODING) return result func.restype = c_char_p func.errcheck = _err_check return func GeoIP_country_code_by_addr = string_output(lgeoip.GeoIP_country_code_by_addr) GeoIP_country_code_by_name = string_output(lgeoip.GeoIP_country_code_by_name) GeoIP_country_name_by_addr = string_output(lgeoip.GeoIP_country_name_by_addr) GeoIP_country_name_by_name = string_output(lgeoip.GeoIP_country_name_by_name)
mit
gisce/OCB
addons/project_long_term/project_long_term.py
33
16612
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from datetime import datetime from openerp.tools.translate import _ from openerp.osv import fields, osv from openerp.addons.resource.faces import task as Task class project_phase(osv.osv): _name = "project.phase" _description = "Project Phase" def _check_recursion(self, cr, uid, ids, context=None): if context is None: context = {} data_phase = self.browse(cr, uid, ids[0], context=context) prev_ids = data_phase.previous_phase_ids next_ids = data_phase.next_phase_ids # it should neither be in prev_ids nor in next_ids if (data_phase in prev_ids) or (data_phase in next_ids): return False ids = [id for id in prev_ids if id in next_ids] # both prev_ids and next_ids must be unique if ids: return False # unrelated project prev_ids = [rec.id for rec in prev_ids] next_ids = [rec.id for rec in next_ids] # iter prev_ids while prev_ids: cr.execute('SELECT distinct prv_phase_id FROM project_phase_rel WHERE next_phase_id IN %s', (tuple(prev_ids),)) prv_phase_ids = filter(None, map(lambda x: x[0], cr.fetchall())) if data_phase.id in prv_phase_ids: return False ids = [id for id in prv_phase_ids if id in next_ids] if ids: return False prev_ids = prv_phase_ids # iter next_ids while next_ids: cr.execute('SELECT distinct next_phase_id FROM project_phase_rel WHERE prv_phase_id IN %s', (tuple(next_ids),)) next_phase_ids = filter(None, map(lambda x: x[0], cr.fetchall())) if data_phase.id in next_phase_ids: return False ids = [id for id in next_phase_ids if id in prev_ids] if ids: return False next_ids = next_phase_ids return True def _check_dates(self, cr, uid, ids, context=None): for phase in self.read(cr, uid, ids, ['date_start', 'date_end'], context=context): if phase['date_start'] and phase['date_end'] and phase['date_start'] > phase['date_end']: return False return True def _compute_progress(self, cr, uid, ids, field_name, arg, context=None): res = {} if not ids: return res for phase in self.browse(cr, uid, ids, context=context): if phase.state=='done': res[phase.id] = 100.0 continue elif phase.state=="cancelled": res[phase.id] = 0.0 continue elif not phase.task_ids: res[phase.id] = 0.0 continue tot = done = 0.0 for task in phase.task_ids: tot += task.total_hours done += min(task.effective_hours, task.total_hours) if not tot: res[phase.id] = 0.0 else: res[phase.id] = round(100.0 * done / tot, 2) return res _columns = { 'name': fields.char("Name", size=64, required=True), 'date_start': fields.datetime('Start Date', select=True, help="It's computed by the scheduler according the project date or the end date of the previous phase.", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}), 'date_end': fields.datetime('End Date', help=" It's computed by the scheduler according to the start date and the duration.", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}), 'constraint_date_start': fields.datetime('Minimum Start Date', help='force the phase to start after this date', states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}), 'constraint_date_end': fields.datetime('Deadline', help='force the phase to finish before this date', states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}), 'project_id': fields.many2one('project.project', 'Project', required=True, select=True), 'next_phase_ids': fields.many2many('project.phase', 'project_phase_rel', 'prv_phase_id', 'next_phase_id', 'Next Phases', states={'cancelled':[('readonly',True)]}), 'previous_phase_ids': fields.many2many('project.phase', 'project_phase_rel', 'next_phase_id', 'prv_phase_id', 'Previous Phases', states={'cancelled':[('readonly',True)]}), 'sequence': fields.integer('Sequence', select=True, help="Gives the sequence order when displaying a list of phases."), 'duration': fields.float('Duration', required=True, help="By default in days", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}), 'product_uom': fields.many2one('product.uom', 'Duration Unit of Measure', required=True, help="Unit of Measure (Unit of Measure) is the unit of measurement for Duration", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}), 'task_ids': fields.one2many('project.task', 'phase_id', "Project Tasks", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}), 'user_force_ids': fields.many2many('res.users', string='Force Assigned Users'), 'user_ids': fields.one2many('project.user.allocation', 'phase_id', "Assigned Users",states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}, help="The resources on the project can be computed automatically by the scheduler."), 'state': fields.selection([('draft', 'New'), ('cancelled', 'Cancelled'),('open', 'In Progress'), ('pending', 'Pending'), ('done', 'Done')], 'Status', readonly=True, required=True, help='If the phase is created the status \'Draft\'.\n If the phase is started, the status becomes \'In Progress\'.\n If review is needed the phase is in \'Pending\' status.\ \n If the phase is over, the status is set to \'Done\'.'), 'progress': fields.function(_compute_progress, string='Progress', help="Computed based on related tasks"), } _defaults = { 'state': 'draft', 'sequence': 10, } _order = "project_id, date_start, sequence" _constraints = [ (_check_recursion,'Loops in phases not allowed',['next_phase_ids', 'previous_phase_ids']), (_check_dates, 'Phase start-date must be lower than phase end-date.', ['date_start', 'date_end']), ] def onchange_project(self, cr, uid, ids, project, context=None): return {} def copy(self, cr, uid, id, default=None, context=None): if default is None: default = {} if not default.get('name', False): default.update(name=_('%s (copy)') % (self.browse(cr, uid, id, context=context).name)) return super(project_phase, self).copy(cr, uid, id, default, context) def set_draft(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'draft'}) return True def set_open(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'open'}) return True def set_pending(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'pending'}) return True def set_cancel(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'cancelled'}) return True def set_done(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'done'}) return True def generate_phase(self, cr, uid, phases, context=None): context = context or {} result = "" task_pool = self.pool.get('project.task') for phase in phases: if phase.state in ('done','cancelled'): continue # FIXME: brittle and not working if context['lang'] != 'en_US' duration_uom = { 'day(s)': 'd', 'days': 'd', 'day': 'd', 'd':'d', 'month(s)': 'm', 'months': 'm', 'month':'month', 'm':'m', 'week(s)': 'w', 'weeks': 'w', 'week': 'w', 'w':'w', 'hour(s)': 'H', 'hours': 'H', 'hour': 'H', 'h':'H', }.get(phase.product_uom.name.lower(), "H") duration = str(phase.duration) + duration_uom result += ''' def Phase_%s(): effort = \"%s\"''' % (phase.id, duration) start = [] if phase.constraint_date_start: start.append('datetime.datetime.strptime("'+str(phase.constraint_date_start)+'", "%Y-%m-%d %H:%M:%S")') for previous_phase in phase.previous_phase_ids: start.append("up.Phase_%s.end" % (previous_phase.id,)) if start: result += ''' start = max(%s) ''' % (','.join(start)) if phase.user_force_ids: result += ''' resource = %s ''' % '|'.join(map(lambda x: 'User_'+str(x.id), phase.user_force_ids)) result += task_pool._generate_task(cr, uid, phase.task_ids, ident=8, context=context) result += "\n" return result project_phase() class project_user_allocation(osv.osv): _name = 'project.user.allocation' _description = 'Phase User Allocation' _rec_name = 'user_id' _columns = { 'user_id': fields.many2one('res.users', 'User', required=True), 'phase_id': fields.many2one('project.phase', 'Project Phase', ondelete='cascade', required=True), 'project_id': fields.related('phase_id', 'project_id', type='many2one', relation="project.project", string='Project', store=True), 'date_start': fields.datetime('Start Date', help="Starting Date"), 'date_end': fields.datetime('End Date', help="Ending Date"), } project_user_allocation() class project(osv.osv): _inherit = "project.project" def _phase_count(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, 0) phase_ids = self.pool.get('project.phase').search(cr, uid, [('project_id', 'in', ids)]) for phase in self.pool.get('project.phase').browse(cr, uid, phase_ids, context): res[phase.project_id.id] += 1 return res _columns = { 'phase_ids': fields.one2many('project.phase', 'project_id', "Project Phases"), 'phase_count': fields.function(_phase_count, type='integer', string="Open Phases"), } def schedule_phases(self, cr, uid, ids, context=None): context = context or {} if type(ids) in (long, int,): ids = [ids] projects = self.browse(cr, uid, ids, context=context) result = self._schedule_header(cr, uid, ids, context=context) for project in projects: result += self._schedule_project(cr, uid, project, context=context) result += self.pool.get('project.phase').generate_phase(cr, uid, project.phase_ids, context=context) local_dict = {} exec result in local_dict projects_gantt = Task.BalancedProject(local_dict['Project']) for project in projects: project_gantt = getattr(projects_gantt, 'Project_%d' % (project.id,)) for phase in project.phase_ids: if phase.state in ('done','cancelled'): continue # Maybe it's better to update than unlink/create if it already exists ? p = getattr(project_gantt, 'Phase_%d' % (phase.id,)) self.pool.get('project.user.allocation').unlink(cr, uid, [x.id for x in phase.user_ids], context=context ) for r in p.booked_resource: self.pool.get('project.user.allocation').create(cr, uid, { 'user_id': int(r.name[5:]), 'phase_id': phase.id, 'date_start': p.start.strftime('%Y-%m-%d %H:%M:%S'), 'date_end': p.end.strftime('%Y-%m-%d %H:%M:%S') }, context=context) self.pool.get('project.phase').write(cr, uid, [phase.id], { 'date_start': p.start.strftime('%Y-%m-%d %H:%M:%S'), 'date_end': p.end.strftime('%Y-%m-%d %H:%M:%S') }, context=context) return True def map_phase(self, cr, uid, old_project_id, new_project_id, context=None): """ copy and map phases from old to new project while keeping order relations """ project_phase = self.pool['project.phase'] project_task = self.pool['project.task'] # mapping source and copy ids to recreate m2m links phase_ids_mapping = {} project = self.browse(cr, uid, old_project_id, context=context) if project.phase_ids: for phase in project.phase_ids: phase_default = { 'project_id': new_project_id, 'previous_phase_ids': [], 'next_phase_ids': [], 'task_ids': [], } # adding relationships with already copied phases for previous_phase in phase.previous_phase_ids: if previous_phase.id in phase_ids_mapping: phase_default['previous_phase_ids'].append((4, phase_ids_mapping[previous_phase.id])) for next_phase in phase.next_phase_ids: if next_phase.id in phase_ids_mapping: phase_default['previous_phase_ids'].append((4, phase_ids_mapping[next_phase.id])) phase_ids_mapping[phase.id] = project_phase.copy(cr, uid, phase.id, phase_default, context=context) if project.tasks: # if has copied tasks, need to update phase_id for task in self.browse(cr, uid, new_project_id, context=context).tasks: if task.phase_id and task.phase_id.id in phase_ids_mapping: project_task.write(cr, uid, task.id, {'phase_id': phase_ids_mapping[phase.id]}, context=context) return True def copy(self, cr, uid, id, default=None, context=None): if default is None: default = {} default.update(phase_ids=[]) new_project_id = super(project, self).copy(cr, uid, id, default, context) self.map_phase(cr, uid, id, new_project_id, context=context) return new_project_id class account_analytic_account(osv.osv): _inherit = 'account.analytic.account' _description = 'Analytic Account' _columns = { 'use_phases': fields.boolean('Phases', help="Check this field if you plan to use phase-based scheduling"), } def on_change_template(self, cr, uid, ids, template_id, context=None): res = super(account_analytic_account, self).on_change_template(cr, uid, ids, template_id, context=context) if template_id and 'value' in res: template = self.browse(cr, uid, template_id, context=context) res['value']['use_phases'] = template.use_phases return res def _trigger_project_creation(self, cr, uid, vals, context=None): if context is None: context = {} res = super(account_analytic_account, self)._trigger_project_creation(cr, uid, vals, context=context) return res or (vals.get('use_phases') and not 'project_creation_in_progress' in context) account_analytic_account() class project_task(osv.osv): _inherit = "project.task" _columns = { 'phase_id': fields.many2one('project.phase', 'Project Phase', domain="[('project_id', '=', project_id)]"), } project_task() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
VagrantApe/flaskMicroblog
venv/lib/python2.7/site-packages/sqlalchemy/orm/dynamic.py
14
13297
# orm/dynamic.py # Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Dynamic collection API. Dynamic collections act like Query() objects for read operations and support basic add/delete mutation. """ from .. import log, util, exc from ..sql import operators from . import ( attributes, object_session, util as orm_util, strategies, object_mapper, exc as orm_exc ) from .query import Query class DynaLoader(strategies.AbstractRelationshipLoader): def init_class_attribute(self, mapper): self.is_class_level = True if not self.uselist: raise exc.InvalidRequestError( "On relationship %s, 'dynamic' loaders cannot be used with " "many-to-one/one-to-one relationships and/or " "uselist=False." % self.parent_property) strategies._register_attribute(self, mapper, useobject=True, uselist=True, impl_class=DynamicAttributeImpl, target_mapper=self.parent_property.mapper, order_by=self.parent_property.order_by, query_class=self.parent_property.query_class, backref=self.parent_property.back_populates, ) log.class_logger(DynaLoader) class DynamicAttributeImpl(attributes.AttributeImpl): uses_objects = True accepts_scalar_loader = False supports_population = False collection = False def __init__(self, class_, key, typecallable, dispatch, target_mapper, order_by, query_class=None, **kw): super(DynamicAttributeImpl, self).\ __init__(class_, key, typecallable, dispatch, **kw) self.target_mapper = target_mapper self.order_by = order_by if not query_class: self.query_class = AppenderQuery elif AppenderMixin in query_class.mro(): self.query_class = query_class else: self.query_class = mixin_user_query(query_class) def get(self, state, dict_, passive=attributes.PASSIVE_OFF): if not passive & attributes.SQL_OK: return self._get_collection_history(state, attributes.PASSIVE_NO_INITIALIZE).added_items else: return self.query_class(self, state) def get_collection(self, state, dict_, user_data=None, passive=attributes.PASSIVE_NO_INITIALIZE): if not passive & attributes.SQL_OK: return self._get_collection_history(state, passive).added_items else: history = self._get_collection_history(state, passive) return history.added_plus_unchanged def fire_append_event(self, state, dict_, value, initiator, collection_history=None): if collection_history is None: collection_history = self._modified_event(state, dict_) collection_history.add_added(value) for fn in self.dispatch.append: value = fn(state, value, initiator or self) if self.trackparent and value is not None: self.sethasparent(attributes.instance_state(value), state, True) def fire_remove_event(self, state, dict_, value, initiator, collection_history=None): if collection_history is None: collection_history = self._modified_event(state, dict_) collection_history.add_removed(value) if self.trackparent and value is not None: self.sethasparent(attributes.instance_state(value), state, False) for fn in self.dispatch.remove: fn(state, value, initiator or self) def _modified_event(self, state, dict_): if self.key not in state.committed_state: state.committed_state[self.key] = CollectionHistory(self, state) state._modified_event(dict_, self, attributes.NEVER_SET) # this is a hack to allow the fixtures.ComparableEntity fixture # to work dict_[self.key] = True return state.committed_state[self.key] def set(self, state, dict_, value, initiator, passive=attributes.PASSIVE_OFF, check_old=None, pop=False): if initiator and initiator.parent_token is self.parent_token: return if pop and value is None: return self._set_iterable(state, dict_, value) def _set_iterable(self, state, dict_, iterable, adapter=None): new_values = list(iterable) if state.has_identity: old_collection = util.IdentitySet(self.get(state, dict_)) collection_history = self._modified_event(state, dict_) if not state.has_identity: old_collection = collection_history.added_items else: old_collection = old_collection.union( collection_history.added_items) idset = util.IdentitySet constants = old_collection.intersection(new_values) additions = idset(new_values).difference(constants) removals = old_collection.difference(constants) for member in new_values: if member in additions: self.fire_append_event(state, dict_, member, None, collection_history=collection_history) for member in removals: self.fire_remove_event(state, dict_, member, None, collection_history=collection_history) def delete(self, *args, **kwargs): raise NotImplementedError() def set_committed_value(self, state, dict_, value): raise NotImplementedError("Dynamic attributes don't support " "collection population.") def get_history(self, state, dict_, passive=attributes.PASSIVE_OFF): c = self._get_collection_history(state, passive) return c.as_history() def get_all_pending(self, state, dict_): c = self._get_collection_history( state, attributes.PASSIVE_NO_INITIALIZE) return [ (attributes.instance_state(x), x) for x in c.all_items ] def _get_collection_history(self, state, passive=attributes.PASSIVE_OFF): if self.key in state.committed_state: c = state.committed_state[self.key] else: c = CollectionHistory(self, state) if state.has_identity and (passive & attributes.INIT_OK): return CollectionHistory(self, state, apply_to=c) else: return c def append(self, state, dict_, value, initiator, passive=attributes.PASSIVE_OFF): if initiator is not self: self.fire_append_event(state, dict_, value, initiator) def remove(self, state, dict_, value, initiator, passive=attributes.PASSIVE_OFF): if initiator is not self: self.fire_remove_event(state, dict_, value, initiator) def pop(self, state, dict_, value, initiator, passive=attributes.PASSIVE_OFF): self.remove(state, dict_, value, initiator, passive=passive) class AppenderMixin(object): query_class = None def __init__(self, attr, state): super(AppenderMixin, self).__init__(attr.target_mapper, None) self.instance = instance = state.obj() self.attr = attr mapper = object_mapper(instance) prop = mapper._props[self.attr.key] self._criterion = prop.compare( operators.eq, instance, value_is_parent=True, alias_secondary=False) if self.attr.order_by: self._order_by = self.attr.order_by def session(self): sess = object_session(self.instance) if sess is not None and self.autoflush and sess.autoflush \ and self.instance in sess: sess.flush() if not orm_util.has_identity(self.instance): return None else: return sess session = property(session, lambda s, x: None) def __iter__(self): sess = self.session if sess is None: return iter(self.attr._get_collection_history( attributes.instance_state(self.instance), attributes.PASSIVE_NO_INITIALIZE).added_items) else: return iter(self._clone(sess)) def __getitem__(self, index): sess = self.session if sess is None: return self.attr._get_collection_history( attributes.instance_state(self.instance), attributes.PASSIVE_NO_INITIALIZE).indexed(index) else: return self._clone(sess).__getitem__(index) def count(self): sess = self.session if sess is None: return len(self.attr._get_collection_history( attributes.instance_state(self.instance), attributes.PASSIVE_NO_INITIALIZE).added_items) else: return self._clone(sess).count() def _clone(self, sess=None): # note we're returning an entirely new Query class instance # here without any assignment capabilities; the class of this # query is determined by the session. instance = self.instance if sess is None: sess = object_session(instance) if sess is None: raise orm_exc.DetachedInstanceError( "Parent instance %s is not bound to a Session, and no " "contextual session is established; lazy load operation " "of attribute '%s' cannot proceed" % ( orm_util.instance_str(instance), self.attr.key)) if self.query_class: query = self.query_class(self.attr.target_mapper, session=sess) else: query = sess.query(self.attr.target_mapper) query._criterion = self._criterion query._order_by = self._order_by return query def extend(self, iterator): for item in iterator: self.attr.append( attributes.instance_state(self.instance), attributes.instance_dict(self.instance), item, None) def append(self, item): self.attr.append( attributes.instance_state(self.instance), attributes.instance_dict(self.instance), item, None) def remove(self, item): self.attr.remove( attributes.instance_state(self.instance), attributes.instance_dict(self.instance), item, None) class AppenderQuery(AppenderMixin, Query): """A dynamic query that supports basic collection storage operations.""" def mixin_user_query(cls): """Return a new class with AppenderQuery functionality layered over.""" name = 'Appender' + cls.__name__ return type(name, (AppenderMixin, cls), {'query_class': cls}) class CollectionHistory(object): """Overrides AttributeHistory to receive append/remove events directly.""" def __init__(self, attr, state, apply_to=None): if apply_to: coll = AppenderQuery(attr, state).autoflush(False) self.unchanged_items = util.OrderedIdentitySet(coll) self.added_items = apply_to.added_items self.deleted_items = apply_to.deleted_items self._reconcile_collection = True else: self.deleted_items = util.OrderedIdentitySet() self.added_items = util.OrderedIdentitySet() self.unchanged_items = util.OrderedIdentitySet() self._reconcile_collection = False @property def added_plus_unchanged(self): return list(self.added_items.union(self.unchanged_items)) @property def all_items(self): return list(self.added_items.union( self.unchanged_items).union(self.deleted_items)) def as_history(self): if self._reconcile_collection: added = self.added_items.difference(self.unchanged_items) deleted = self.deleted_items.intersection(self.unchanged_items) unchanged = self.unchanged_items.difference(deleted) else: added, unchanged, deleted = self.added_items,\ self.unchanged_items,\ self.deleted_items return attributes.History( list(added), list(unchanged), list(deleted), ) def indexed(self, index): return list(self.added_items)[index] def add_added(self, value): self.added_items.add(value) def add_removed(self, value): if value in self.added_items: self.added_items.remove(value) else: self.deleted_items.add(value)
bsd-3-clause
supasate/word_prediction
Chapter9/9-2-last-word-solution.py
1
1531
# เติมโค้ดในลูป while เพื่อหาคำสุดท้ายก่อนกด tab def add_to_corpus_index(key, next_word, corpus_index): if key not in corpus_index: corpus_index[key] = {next_word: 1} else: if next_word in corpus_index[key]: corpus_index[key][next_word] += 1 else: corpus_index[key][next_word] = 1 def init_corpus_stats(corpus_index, corpus): splitted_text = corpus.split() for i in range(len(splitted_text) - 1): word, next_word = splitted_text[i], splitted_text[i + 1] add_to_corpus_index(word, next_word, corpus_index) def predict(word, corpus_stats): if word in corpus_stats: return max(corpus_stats[word], key=corpus_stats[word].get) else: return "" def load_corpus(file_name): corpus = "" with open(file_name, "r") as corpus_file: corpus = corpus_file.read() return corpus corpus = load_corpus("corpus.txt") corpus_stats = {} init_corpus_stats(corpus_stats, corpus) screen = curses.initscr() curses.noecho() text_buffer = '' while True: c = screen.getkey() if ord(c) == 27: break elif c == '\t': last_word_begin = text_buffer.strip().rfind(' ') + 1 last_word = text_buffer[last_word_begin: ].strip() next_word = predict(last_word, corpus_stats) screen.addstr(' ' + next_word) text_buffer = next_word else: screen.addch(c) text_buffer += c
gpl-2.0
nikolas/lettuce
tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/regressions.py
50
7623
# -*- coding: utf-8 -*- from django.forms import * from django.utils.unittest import TestCase from django.utils.translation import ugettext_lazy, activate, deactivate from regressiontests.forms.models import Cheese class FormsRegressionsTestCase(TestCase): def test_class(self): # Tests to prevent against recurrences of earlier bugs. extra_attrs = {'class': 'special'} class TestForm(Form): f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs)) f2 = CharField(widget=TextInput(attrs=extra_attrs)) self.assertEqual(TestForm(auto_id=False).as_p(), u'<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>') def test_regression_3600(self): # Tests for form i18n # # There were some problems with form translations in #3600 class SomeForm(Form): username = CharField(max_length=10, label=ugettext_lazy('Username')) f = SomeForm() self.assertEqual(f.as_p(), '<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') # Translations are done at rendering time, so multi-lingual apps can define forms) activate('de') self.assertEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') activate('pl') self.assertEqual(f.as_p(), u'<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') deactivate() def test_regression_5216(self): # There was some problems with form translations in #5216 class SomeForm(Form): field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) f = SomeForm() self.assertEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1</label>') self.assertEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2</label>') # Unicode decoding problems... GENDERS = ((u'\xc5', u'En tied\xe4'), (u'\xf8', u'Mies'), (u'\xdf', u'Nainen')) class SomeForm(Form): somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label=u'\xc5\xf8\xdf') f = SomeForm() self.assertEqual(f.as_p(), u'<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') # Testing choice validation with UTF-8 bytestrings as input (these are the # Russian abbreviations "мес." and "шт.". UNITS = (('\xd0\xbc\xd0\xb5\xd1\x81.', '\xd0\xbc\xd0\xb5\xd1\x81.'), ('\xd1\x88\xd1\x82.', '\xd1\x88\xd1\x82.')) f = ChoiceField(choices=UNITS) self.assertEqual(f.clean(u'\u0448\u0442.'), u'\u0448\u0442.') self.assertEqual(f.clean('\xd1\x88\xd1\x82.'), u'\u0448\u0442.') # Translated error messages used to be buggy. activate('ru') f = SomeForm({}) self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') deactivate() # Deep copying translated text shouldn't raise an error) from django.utils.translation import gettext_lazy class CopyForm(Form): degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) f = CopyForm() def test_misc(self): # There once was a problem with Form fields called "data". Let's make sure that # doesn't come back. class DataForm(Form): data = CharField(max_length=10) f = DataForm({'data': 'xyzzy'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {'data': u'xyzzy'}) # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul>\n<p> <input type="hidden" name="data" id="id_data" /></p>') self.assertEqual(f.as_table(), u'<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul><input type="hidden" name="data" id="id_data" /></td></tr>') def test_xss_error_messages(self): ################################################### # Tests for XSS vulnerabilities in error messages # ################################################### # The forms layer doesn't escape input values directly because error messages # might be presented in non-HTML contexts. Instead, the message is just marked # for escaping by the template engine. So we'll need to construct a little # silly template to trigger the escaping. from django.template import Template, Context t = Template('{{ form.errors }}') class SomeForm(Form): field = ChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': '<script>'}) self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>') class SomeForm(Form): field = MultipleChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': ['<script>']}) self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>') from regressiontests.forms.models import ChoiceModel class SomeForm(Form): field = ModelMultipleChoiceField(ChoiceModel.objects.all()) f = SomeForm({'field': ['<script>']}) self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>') def test_regression_14234(self): """ Re-cleaning an instance that was added via a ModelForm should not raise a pk uniqueness error. """ class CheeseForm(ModelForm): class Meta: model = Cheese form = CheeseForm({ 'name': 'Brie', }) self.assertTrue(form.is_valid()) obj = form.save() obj.name = 'Camembert' obj.full_clean()
gpl-3.0
jmesteve/asterisk
openerp/addons/point_of_sale/report/pos_details_summary.py
22
5615
# -*- 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 time from openerp.report import report_sxw class pos_details_summary(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(pos_details_summary, self).__init__(cr, uid, name, context=context) self.total = 0.0 self.localcontext.update({ 'time': time, 'strip_name': self._strip_name, 'getpayments': self._get_payments, 'getqtytotal': self._get_qty_total, 'getsumdisc': self._get_sum_discount, 'getpaidtotal': self._paid_total, 'gettotalofthaday': self._total_of_the_day, 'getsuminvoice': self._sum_invoice, 'gettaxamount': self._get_tax_amount, 'getsalestotal': self._get_sales_total, 'getstartperiod': self._get_start_period, 'getendperiod': self._get_end_period, 'getcompany':self.get_company }) def get_company(self, objects): comp=[obj.company_id.name for obj in objects] return '%s' % (comp[0]) def _get_qty_total(self, objects): #code for the sum of qty_total return reduce(lambda acc, object: acc + reduce( lambda sum_qty, line: sum_qty + line.qty, object.lines, 0 ), objects, 0) def _get_sum_discount(self, objects): #code for the sum of discount value return reduce(lambda acc, object: acc + reduce( lambda sum_dis, line: sum_dis + ((line.price_unit * line.qty ) * (line.discount / 100)), object.lines, 0.0), objects, 0.0 ) def _get_payments(self, objects): result = {} for obj in objects: for statement in obj.statement_ids: if statement.journal_id: result[statement.journal_id] = result.get(statement.journal_id, 0.0) + statement.amount return result def _paid_total(self, objects): return sum(self._get_payments(objects).values(), 0.0) def _total_of_the_day(self, objects): total_paid = self._paid_total(objects) total_invoiced = self._sum_invoice(objects) return total_paid - total_invoiced def _sum_invoice(self, objects): return reduce(lambda acc, obj: acc + obj.invoice_id.amount_total, [o for o in objects if o.invoice_id and o.invoice_id.number], 0.0) def _ellipsis(self, string, maxlen=100, ellipsis = '...'): ellipsis = ellipsis or '' return string[:maxlen - len(ellipsis) ] + (ellipsis, '')[len(string) < maxlen] def _strip_name(self, name, maxlen=50): return self._ellipsis(name, maxlen, ' ...') def _get_tax_amount(self, objects): res = {} list_ids = [] for order in objects: for line in order.lines: if len(line.product_id.taxes_id): tax = line.product_id.taxes_id[0] res[tax.name] = (line.price_unit * line.qty * (1-(line.discount or 0.0) / 100.0)) + (tax.id in list_ids and res[tax.name] or 0) list_ids.append(tax.id) return res def _get_sales_total(self, objects): return reduce(lambda x, o: x + len(o.lines), objects, 0) def _get_start_period(self, objects): date_orders = sorted([obj.date_order for obj in objects]) min_date = date_orders[0] return '%s' % min_date def _get_end_period(self, objects): date_orders = sorted([obj.date_order for obj in objects]) max_date = date_orders[-1] return '%s' % max_date report_sxw.report_sxw('report.pos.details_summary', 'pos.order', 'addons/point_of_sale/report/pos_details_summary.rml', parser=pos_details_summary, header='internal') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
gdi2290/django
django/conf/locale/nn/formats.py
197
1810
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' # '%d. %b %Y', '%d %b %Y', # '25. okt 2006', '25 okt 2006' # '%d. %b. %Y', '%d %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%d. %B %Y', '%d %B %Y', # '25. oktober 2006', '25 oktober 2006' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
bsd-3-clause
YComputer/react-native
JSCLegacyProfiler/trace_data.py
375
8013
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re import unittest """ # _-----=> irqs-off # / _----=> need-resched # | / _---=> hardirq/softirq # || / _--=> preempt-depth # ||| / delay # TASK-PID CPU# |||| TIMESTAMP FUNCTION # | | | |||| | | <idle>-0 [001] ...2 3269.291072: sched_switch: prev_comm=swapper/1 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=mmcqd/0 next_pid=120 next_prio=120 """ TRACE_LINE_PATTERN = re.compile( r'^\s*(?P<task>.+)-(?P<pid>\d+)\s+(?:\((?P<tgid>.+)\)\s+)?\[(?P<cpu>\d+)\]\s+(?:(?P<flags>\S{4})\s+)?(?P<timestamp>[0-9.]+):\s+(?P<function>.+)$') """ Example lines from custom app traces: 0: B|27295|providerRemove 0: E tracing_mark_write: S|27311|NNFColdStart<D-7744962>|1112249168 """ APP_TRACE_LINE_PATTERN = re.compile( r'^(?P<type>.+?): (?P<args>.+)$') """ Example section names: NNFColdStart NNFColdStart<0><T7744962> NNFColdStart<X> NNFColdStart<T7744962> """ DECORATED_SECTION_NAME_PATTERN = re.compile(r'^(?P<section_name>.*?)(?:<0>)?(?:<(?P<command>.)(?P<argument>.*?)>)?$') SYSTRACE_LINE_TYPES = set(['0', 'tracing_mark_write']) class TraceLine(object): def __init__(self, task, pid, tgid, cpu, flags, timestamp, function): self.task = task self.pid = pid self.tgid = tgid self.cpu = cpu self.flags = flags self.timestamp = timestamp self.function = function self.canceled = False @property def is_app_trace_line(self): return isinstance(self.function, AppTraceFunction) def cancel(self): self.canceled = True def __str__(self): if self.canceled: return "" elif self.tgid: return "{task:>16s}-{pid:<5d} ({tgid:5s}) [{cpu:03d}] {flags:4s} {timestamp:12f}: {function}\n".format(**vars(self)) elif self.flags: return "{task:>16s}-{pid:<5d} [{cpu:03d}] {flags:4s} {timestamp:12f}: {function}\n".format(**vars(self)) else: return "{task:>16s}-{pid:<5d} [{cpu:03d}] {timestamp:12.6f}: {function}\n".format(**vars(self)) class AppTraceFunction(object): def __init__(self, type, args): self.type = type self.args = args self.operation = args[0] if len(args) >= 2 and args[1]: self.pid = int(args[1]) if len(args) >= 3: self._section_name, self.command, self.argument = _parse_section_name(args[2]) args[2] = self._section_name else: self._section_name = None self.command = None self.argument = None self.cookie = None @property def section_name(self): return self._section_name @section_name.setter def section_name(self, value): self._section_name = value self.args[2] = value def __str__(self): return "{type}: {args}".format(type=self.type, args='|'.join(self.args)) class AsyncTraceFunction(AppTraceFunction): def __init__(self, type, args): super(AsyncTraceFunction, self).__init__(type, args) self.cookie = int(args[3]) TRACE_TYPE_MAP = { 'S': AsyncTraceFunction, 'T': AsyncTraceFunction, 'F': AsyncTraceFunction, } def parse_line(line): match = TRACE_LINE_PATTERN.match(line.strip()) if not match: return None task = match.group("task") pid = int(match.group("pid")) tgid = match.group("tgid") cpu = int(match.group("cpu")) flags = match.group("flags") timestamp = float(match.group("timestamp")) function = match.group("function") app_trace = _parse_function(function) if app_trace: function = app_trace return TraceLine(task, pid, tgid, cpu, flags, timestamp, function) def parse_dextr_line(line): task = line["name"] pid = line["pid"] tgid = line["tid"] cpu = None flags = None timestamp = line["ts"] function = AppTraceFunction("DextrTrace", [line["ph"], line["pid"], line["name"]]) return TraceLine(task, pid, tgid, cpu, flags, timestamp, function) def _parse_function(function): line_match = APP_TRACE_LINE_PATTERN.match(function) if not line_match: return None type = line_match.group("type") if not type in SYSTRACE_LINE_TYPES: return None args = line_match.group("args").split('|') if len(args) == 1 and len(args[0]) == 0: args = None constructor = TRACE_TYPE_MAP.get(args[0], AppTraceFunction) return constructor(type, args) def _parse_section_name(section_name): if section_name is None: return section_name, None, None section_name_match = DECORATED_SECTION_NAME_PATTERN.match(section_name) section_name = section_name_match.group("section_name") command = section_name_match.group("command") argument = section_name_match.group("argument") return section_name, command, argument def _format_section_name(section_name, command, argument): if not command: return section_name return "{section_name}<{command}{argument}>".format(**vars()) class RoundTripFormattingTests(unittest.TestCase): def testPlainSectionName(self): section_name = "SectionName12345-5562342fas" self.assertEqual(section_name, _format_section_name(*_parse_section_name(section_name))) def testDecoratedSectionName(self): section_name = "SectionName12345-5562342fas<D-123456>" self.assertEqual(section_name, _format_section_name(*_parse_section_name(section_name))) def testSimpleFunction(self): function = "0: E" self.assertEqual(function, str(_parse_function(function))) def testFunctionWithoutCookie(self): function = "0: B|27295|providerRemove" self.assertEqual(function, str(_parse_function(function))) def testFunctionWithCookie(self): function = "0: S|27311|NNFColdStart|1112249168" self.assertEqual(function, str(_parse_function(function))) def testFunctionWithCookieAndArgs(self): function = "0: T|27311|NNFColdStart|1122|Start" self.assertEqual(function, str(_parse_function(function))) def testFunctionWithArgsButNoPid(self): function = "0: E|||foo=bar" self.assertEqual(function, str(_parse_function(function))) def testKitKatFunction(self): function = "tracing_mark_write: B|14127|Looper.dispatchMessage|arg=>>>>> Dispatching to Handler (android.os.Handler) {422ae980} null: 0|Java" self.assertEqual(function, str(_parse_function(function))) def testNonSysTraceFunctionIgnored(self): function = "sched_switch: prev_comm=swapper/1 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=mmcqd/0 next_pid=120 next_prio=120" self.assertEqual(None, _parse_function(function)) def testLineWithFlagsAndTGID(self): line = " <idle>-0 ( 550) [000] d..2 7953.258473: cpu_idle: state=1 cpu_id=0\n" self.assertEqual(line, str(parse_line(line))) def testLineWithFlagsAndNoTGID(self): line = " <idle>-0 (-----) [000] d..2 7953.258473: cpu_idle: state=1 cpu_id=0\n" self.assertEqual(line, str(parse_line(line))) def testLineWithFlags(self): line = " <idle>-0 [001] ...2 3269.291072: sched_switch: prev_comm=swapper/1 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=mmcqd/0 next_pid=120 next_prio=120\n" self.assertEqual(line, str(parse_line(line))) def testLineWithoutFlags(self): line = " <idle>-0 [001] 3269.291072: sched_switch: prev_comm=swapper/1 prev_pid=0 prev_prio=120 prev_state=R ==> next_comm=mmcqd/0 next_pid=120 next_prio=120\n" self.assertEqual(line, str(parse_line(line)))
bsd-3-clause
mikedchavez1010/XX-Net
python27/1.0/lib/linux/gevent/pool.py
10
10938
# Copyright (c) 2009-2010 Denis Bilenko. See LICENSE for details. """Managing greenlets in a group. The :class:`Group` class in this module abstracts a group of running greenlets. When a greenlet dies, it's automatically removed from the group. The :class:`Pool` which a subclass of :class:`Group` provides a way to limit concurrency: its :meth:`spawn <Pool.spawn>` method blocks if the number of greenlets in the pool has already reached the limit, until there is a free slot. """ from gevent.hub import GreenletExit, getcurrent from gevent.greenlet import joinall, Greenlet from gevent.timeout import Timeout from gevent.event import Event from gevent.coros import Semaphore, DummySemaphore __all__ = ['Group', 'Pool'] class Group(object): """Maintain a group of greenlets that are still running. Links to each item and removes it upon notification. """ greenlet_class = Greenlet def __init__(self, *args): assert len(args) <= 1, args self.greenlets = set(*args) if args: for greenlet in args[0]: greenlet.rawlink(self.discard) # each item we kill we place in dying, to avoid killing the same greenlet twice self.dying = set() self._empty_event = Event() self._empty_event.set() def __repr__(self): try: classname = self.__class__.__name__ except AttributeError: classname = 'Group' # XXX check if 2.4 really uses this line return '<%s at %s %s>' % (classname, hex(id(self)), self.greenlets) def __len__(self): return len(self.greenlets) def __contains__(self, item): return item in self.greenlets def __iter__(self): return iter(self.greenlets) def add(self, greenlet): greenlet.rawlink(self.discard) self.greenlets.add(greenlet) self._empty_event.clear() def discard(self, greenlet): self.greenlets.discard(greenlet) self.dying.discard(greenlet) if not self.greenlets: self._empty_event.set() def start(self, greenlet): self.add(greenlet) greenlet.start() def spawn(self, *args, **kwargs): add = self.add greenlet = self.greenlet_class.spawn(*args, **kwargs) add(greenlet) return greenlet def spawn_link(self, *args, **kwargs): greenlet = self.spawn(*args, **kwargs) greenlet.link() return greenlet def spawn_link_value(self, *args, **kwargs): greenlet = self.spawn(*args, **kwargs) greenlet.link_value() return greenlet def spawn_link_exception(self, *args, **kwargs): greenlet = self.spawn(*args, **kwargs) greenlet.link_exception() return greenlet # def close(self): # """Prevents any more tasks from being submitted to the pool""" # self.add = RaiseException("This %s has been closed" % self.__class__.__name__) def join(self, timeout=None, raise_error=False): if raise_error: greenlets = self.greenlets.copy() self._empty_event.wait(timeout=timeout) for greenlet in greenlets: if greenlet.exception is not None: raise greenlet.exception else: self._empty_event.wait(timeout=timeout) def kill(self, exception=GreenletExit, block=True, timeout=None): timer = Timeout.start_new(timeout) try: try: while self.greenlets: for greenlet in list(self.greenlets): if greenlet not in self.dying: greenlet.kill(exception, block=False) self.dying.add(greenlet) if not block: break joinall(self.greenlets) except Timeout, ex: if ex is not timer: raise finally: timer.cancel() def killone(self, greenlet, exception=GreenletExit, block=True, timeout=None): if greenlet not in self.dying and greenlet in self.greenlets: greenlet.kill(exception, block=False) self.dying.add(greenlet) if block: greenlet.join(timeout) def apply(self, func, args=None, kwds=None): """Equivalent of the apply() builtin function. It blocks till the result is ready.""" if args is None: args = () if kwds is None: kwds = {} if getcurrent() in self: return func(*args, **kwds) else: return self.spawn(func, *args, **kwds).get() def apply_cb(self, func, args=None, kwds=None, callback=None): result = self.apply(func, args, kwds) if callback is not None: Greenlet.spawn(callback, result) return result def apply_async(self, func, args=None, kwds=None, callback=None): """A variant of the apply() method which returns a Greenlet object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready callback is applied to it (unless the call failed).""" if args is None: args = () if kwds is None: kwds = {} if self.full(): # cannot call spawn() directly because it will block return Greenlet.spawn(self.apply_cb, func, args, kwds, callback) else: greenlet = self.spawn(func, *args, **kwds) if callback is not None: greenlet.link(pass_value(callback)) return greenlet def map(self, func, iterable): greenlets = [self.spawn(func, item) for item in iterable] return [greenlet.get() for greenlet in greenlets] def map_cb(self, func, iterable, callback=None): result = self.map(func, iterable) if callback is not None: callback(result) return result def map_async(self, func, iterable, callback=None): """ A variant of the map() method which returns a Greenlet object. If callback is specified then it should be a callable which accepts a single argument. """ return Greenlet.spawn(self.map_cb, func, iterable, callback) def imap(self, func, iterable): """An equivalent of itertools.imap() **TODO**: Fix this. """ return iter(self.map(func, iterable)) def imap_unordered(self, func, iterable): """The same as imap() except that the ordering of the results from the returned iterator should be considered in arbitrary order.""" return IMapUnordered.spawn(self.spawn, func, iterable) def full(self): return False def wait_available(self): pass class IMapUnordered(Greenlet): def __init__(self, spawn, func, iterable): from gevent.queue import Queue Greenlet.__init__(self) self.spawn = spawn self.func = func self.iterable = iterable self.queue = Queue() self.count = 0 def __iter__(self): return self.queue def _run(self): try: func = self.func for item in self.iterable: self.count += 1 self.spawn(func, item).rawlink(self._on_result) finally: self.__dict__.pop('spawn', None) self.__dict__.pop('func', None) self.__dict__.pop('iterable', None) def _on_result(self, greenlet): self.count -= 1 if greenlet.successful(): self.queue.put(greenlet.value) if self.ready() and self.count <= 0: self.queue.put(StopIteration) def GreenletSet(*args, **kwargs): import warnings warnings.warn("gevent.pool.GreenletSet was renamed to gevent.pool.Group since version 0.13.0", DeprecationWarning, stacklevel=2) return Group(*args, **kwargs) class Pool(Group): def __init__(self, size=None, greenlet_class=None): if size is not None and size < 1: raise ValueError('Invalid size for pool (positive integer or None required): %r' % (size, )) Group.__init__(self) self.size = size if greenlet_class is not None: self.greenlet_class = greenlet_class if size is None: self._semaphore = DummySemaphore() else: self._semaphore = Semaphore(size) def wait_available(self): self._semaphore.wait() def full(self): return self.free_count() <= 0 def free_count(self): if self.size is None: return 1 return max(0, self.size - len(self)) def start(self, greenlet): self._semaphore.acquire() try: self.add(greenlet) except: self._semaphore.release() raise greenlet.start() def spawn(self, *args, **kwargs): self._semaphore.acquire() try: greenlet = self.greenlet_class.spawn(*args, **kwargs) self.add(greenlet) except: self._semaphore.release() raise return greenlet def spawn_link(self, *args, **kwargs): self._semaphore.acquire() try: greenlet = self.greenlet_class.spawn_link(*args, **kwargs) self.add(greenlet) except: self._semaphore.release() raise return greenlet def spawn_link_value(self, *args, **kwargs): self._semaphore.acquire() try: greenlet = self.greenlet_class.spawn_link_value(*args, **kwargs) self.add(greenlet) except: self._semaphore.release() raise return greenlet def spawn_link_exception(self, *args, **kwargs): self._semaphore.acquire() try: greenlet = self.greenlet_class.spawn_link_exception(*args, **kwargs) self.add(greenlet) except: self._semaphore.release() raise return greenlet def discard(self, greenlet): Group.discard(self, greenlet) self._semaphore.release() def get_values(greenlets): joinall(greenlets) return [x.value for x in greenlets] class pass_value(object): __slots__ = ['callback'] def __init__(self, callback): self.callback = callback def __call__(self, source): if source.successful(): self.callback(source.value) def __hash__(self): return hash(self.callback) def __eq__(self, other): return self.callback == getattr(other, 'callback', other) def __str__(self): return str(self.callback) def __repr__(self): return repr(self.callback) def __getattr__(self, item): assert item != 'callback' return getattr(self.callback, item)
bsd-2-clause
ReachingOut/unisubs
apps/search/management/commands/test_index_updating.py
5
9879
import datetime import os import warnings from optparse import make_option from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management.base import AppCommand from django.db import reset_queries from django.utils.encoding import smart_str from haystack.query import SearchQuerySet try: from django.utils import importlib except ImportError: from haystack.utils import importlib DEFAULT_BATCH_SIZE = getattr(settings, 'HAYSTACK_BATCH_SIZE', 1000) DEFAULT_AGE = None def worker(bits): # We need to reset the connections, otherwise the different processes # will try to share the connection, which causes things to blow up. from django.db import connections for alias, info in connections.databases.items(): # We need to also tread lightly with SQLite, because blindly wiping # out connections (via ``... = {}``) destroys in-memory DBs. if not 'sqlite3' in info['ENGINE']: try: del(connections._connections[alias]) except KeyError: pass if bits[0] == 'do_update': func, model, start, end, total, optional_site, age, verbosity = bits elif bits[0] == 'do_remove': func, model, pks_seen, start, upper_bound, optional_site, verbosity = bits else: return site = get_site(optional_site) index = site.get_index(model) if func == 'do_update': qs = build_queryset(index, model, age=age, verbosity=verbosity) do_update(index, qs, start, end, total, verbosity=verbosity) elif bits[0] == 'do_remove': do_remove(index, model, pks_seen, start, upper_bound, verbosity=verbosity) def get_site(optional_site=None): # Cause the default site to load. from haystack import site if optional_site: path_bits = optional_site.split('.') module_name = '.'.join(path_bits[:-1]) site_name = path_bits[-1] try: module = importlib.import_module(module_name) site = getattr(module, site_name) except (ImportError, NameError): pass return site def build_queryset(index, model, age=DEFAULT_AGE, verbosity=1): extra_lookup_kwargs = {} updated_field = index.get_updated_field() if age: if updated_field: extra_lookup_kwargs['%s__gte' % updated_field] = datetime.datetime.now() - datetime.timedelta(hours=age) else: if verbosity >= 2: print "No updated date field found for '%s' - not restricting by age." % model.__name__ index_qs = None if hasattr(index, 'get_queryset'): warnings.warn("'SearchIndex.get_queryset' is pending deprecation & will be removed in Haystack v2. Please rename them to 'index_queryset'.") index_qs = index.get_queryset() else: index_qs = index.index_queryset() if not hasattr(index_qs, 'filter'): raise ImproperlyConfigured("The '%r' class must return a 'QuerySet' in the 'index_queryset' method." % index) # `.select_related()` seems like a good idea here but can fail on # nullable `ForeignKey` as well as what seems like other cases. return index_qs.filter(**extra_lookup_kwargs) def do_update(index, qs, start, end, total, verbosity=1): # Get a clone of the QuerySet so that the cache doesn't bloat up # in memory. Useful when reindexing large amounts of data. small_cache_qs = qs.all() current_qs = small_cache_qs[start:end] if verbosity >= 2: if os.getpid() == os.getppid(): print " indexed %s - %d of %d." % (start+1, end, total) else: print " indexed %s - %d of %d (by %s)." % (start+1, end, total, os.getpid()) print current_qs[0].pk index.backend.update(index, current_qs) # Clear out the DB connections queries because it bloats up RAM. reset_queries() def do_remove(index, model, pks_seen, start, upper_bound, verbosity=1): # Fetch a list of results. # Can't do pk range, because id's are strings (thanks comments # & UUIDs!). stuff_in_the_index = SearchQuerySet().models(model)[start:upper_bound] # Iterate over those results. for result in stuff_in_the_index: # Be careful not to hit the DB. if not smart_str(result.pk) in pks_seen: # The id is NOT in the small_cache_qs, issue a delete. if verbosity >= 2: print " removing %s." % result.pk index.backend.remove(".".join([result.app_label, result.model_name, str(result.pk)])) class Command(AppCommand): help = "Freshens the index for the given app(s)." base_options = ( make_option('-a', '--age', action='store', dest='age', default=DEFAULT_AGE, type='int', help='Number of hours back to consider objects new.' ), make_option('-b', '--batch-size', action='store', dest='batchsize', default=DEFAULT_BATCH_SIZE, type='int', help='Number of items to index at once.' ), make_option('-s', '--site', action='store', dest='site', type='string', help='The site object to use when reindexing (like `search_sites.mysite`).' ), make_option('-r', '--remove', action='store_true', dest='remove', default=False, help='Remove objects from the index that are no longer present in the database.' ), make_option('-k', '--workers', action='store', dest='workers', default=0, type='int', help='Allows for the use multiple workers to parallelize indexing. Requires multiprocessing.' ), ) option_list = AppCommand.option_list + base_options # Django 1.0.X compatibility. verbosity_present = False for option in option_list: if option.get_opt_string() == '--verbosity': verbosity_present = True if verbosity_present is False: option_list = option_list + ( make_option('--verbosity', action='store', dest='verbosity', default='1', type='choice', choices=['0', '1', '2'], help='Verbosity level; 0=minimal output, 1=normal output, 2=all output' ), ) def handle(self, *apps, **options): self.verbosity = int(options.get('verbosity', 1)) self.batchsize = options.get('batchsize', DEFAULT_BATCH_SIZE) self.age = options.get('age', DEFAULT_AGE) self.site = options.get('site') self.remove = options.get('remove', False) self.workers = int(options.get('workers', 0)) if not apps: from django.db.models import get_app # Do all, in an INSTALLED_APPS sorted order. apps = [] for app in settings.INSTALLED_APPS: try: app_label = app.split('.')[-1] loaded_app = get_app(app_label) apps.append(app_label) except: # No models, no problem. pass return super(Command, self).handle(*apps, **options) def handle_app(self, app, **options): from django.db.models import get_models from haystack.exceptions import NotRegistered site = get_site(self.site) if self.workers > 0: import multiprocessing for model in get_models(app): try: index = site.get_index(model) except NotRegistered: if self.verbosity >= 2: print "Skipping '%s' - no index." % model continue qs = build_queryset(index, model, age=self.age, verbosity=self.verbosity) total = qs.count() if self.verbosity >= 1: print "Indexing %d %s." % (total, smart_str(model._meta.verbose_name_plural)) pks_seen = set([smart_str(pk) for pk in qs.values_list('pk', flat=True)]) if self.workers > 0: ghetto_queue = [] for start in range(0, total, self.batchsize): end = min(start + self.batchsize, total) if self.workers == 0: do_update(index, qs, start, end, total, self.verbosity) else: ghetto_queue.append(('do_update', model, start, end, total, self.site, self.age, self.verbosity)) if self.workers > 0: pool = multiprocessing.Pool(self.workers) pool.map(worker, ghetto_queue) if self.remove: if self.age or total <= 0: # They're using a reduced set, which may not incorporate # all pks. Rebuild the list with everything. qs = index.index_queryset().values_list('pk', flat=True) pks_seen = set([smart_str(pk) for pk in qs]) total = len(pks_seen) if self.workers > 0: ghetto_queue = [] for start in range(0, total, self.batchsize): upper_bound = start + self.batchsize if self.workers == 0: do_remove(index, model, pks_seen, start, upper_bound) else: ghetto_queue.append(('do_remove', model, pks_seen, start, upper_bound, self.site, self.verbosity)) if self.workers > 0: pool = multiprocessing.Pool(self.workers) pool.map(worker, ghetto_queue)
agpl-3.0
anomen-s/programming-challenges
cryptopals.com/0028-Implement_a_SHA-1_keyed_MAC/solve.py
1
1113
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Find a SHA-1 implementation in the language you code in. Don't cheat. It won't work. Do not use the SHA-1 implementation your language already provides (for instance, don't use the "Digest" library in Ruby, or call OpenSSL; in Ruby, you'd want a pure-Ruby SHA-1). Write a function to authenticate a message under a secret key by using a secret-prefix MAC, which is simply: SHA1(key || message) Verify that you cannot tamper with the message without breaking the MAC you've produced, and that you can't produce a new MAC without knowing the secret key. ''' import sys from Crypto.Hash import SHA sys.path.append("../toolbox") import tools import crypto import sha1 def _native_sha1mac(key, data): h = SHA.new() h.update(key) h.update(data) return h.hexdigest() def sha1mac(key, data): return sha1.hexdigest(key+data) def main(): print('some hashes: ') print(sha1mac(b'A'*16, b'sampleText')) print(sha1mac(b'A'*15 + b'B', b'sampleText')) print(sha1mac(b'A'*16, b'sampleTextLonger')) if __name__ =='__main__': tools.run(main)
gpl-2.0
adelez/grpc
test/cpp/qps/gen_build_yaml.py
8
4953
#!/usr/bin/env python2.7 # Copyright 2015 gRPC 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 json import pipes import shutil import sys import os import yaml run_tests_root = os.path.abspath(os.path.join( os.path.dirname(sys.argv[0]), '../../../tools/run_tests')) sys.path.append(run_tests_root) import performance.scenario_config as scenario_config configs_from_yaml = yaml.load(open(os.path.join(os.path.dirname(sys.argv[0]), '../../../build.yaml')))['configs'].keys() def mutate_scenario(scenario_json, is_tsan): # tweak parameters to get fast test times scenario_json = dict(scenario_json) scenario_json['warmup_seconds'] = 0 scenario_json['benchmark_seconds'] = 1 outstanding_rpcs_divisor = 1 if is_tsan and ( scenario_json['client_config']['client_type'] == 'SYNC_CLIENT' or scenario_json['server_config']['server_type'] == 'SYNC_SERVER'): outstanding_rpcs_divisor = 10 scenario_json['client_config']['outstanding_rpcs_per_channel'] = max(1, int(scenario_json['client_config']['outstanding_rpcs_per_channel'] / outstanding_rpcs_divisor)) return scenario_json def _scenario_json_string(scenario_json, is_tsan): scenarios_json = {'scenarios': [scenario_config.remove_nonproto_fields(mutate_scenario(scenario_json, is_tsan))]} return json.dumps(scenarios_json) def threads_required(scenario_json, where, is_tsan): scenario_json = mutate_scenario(scenario_json, is_tsan) if scenario_json['%s_config' % where]['%s_type' % where] == 'ASYNC_%s' % where.upper(): return scenario_json['%s_config' % where].get('async_%s_threads' % where, 0) return scenario_json['client_config']['outstanding_rpcs_per_channel'] * scenario_json['client_config']['client_channels'] def guess_cpu(scenario_json, is_tsan): client = threads_required(scenario_json, 'client', is_tsan) server = threads_required(scenario_json, 'server', is_tsan) # make an arbitrary guess if set to auto-detect # about the size of the jenkins instances we have for unit tests if client == 0 or server == 0: return 'capacity' return (scenario_json['num_clients'] * client + scenario_json['num_servers'] * server) print yaml.dump({ 'tests': [ { 'name': 'json_run_localhost', 'shortname': 'json_run_localhost:%s' % scenario_json['name'], 'args': ['--scenarios_json', _scenario_json_string(scenario_json, False)], 'ci_platforms': ['linux'], 'platforms': ['linux'], 'flaky': False, 'language': 'c++', 'boringssl': True, 'defaults': 'boringssl', 'cpu_cost': guess_cpu(scenario_json, False), 'exclude_configs': ['tsan', 'asan'], 'timeout_seconds': 2*60, 'excluded_poll_engines': scenario_json.get('EXCLUDED_POLL_ENGINES', []), 'auto_timeout_scaling': False } for scenario_json in scenario_config.CXXLanguage().scenarios() if 'scalable' in scenario_json.get('CATEGORIES', []) ] + [ { 'name': 'qps_json_driver', 'shortname': 'qps_json_driver:inproc_%s' % scenario_json['name'], 'args': ['--run_inproc', '--scenarios_json', _scenario_json_string(scenario_json, False)], 'ci_platforms': ['linux'], 'platforms': ['linux'], 'flaky': False, 'language': 'c++', 'boringssl': True, 'defaults': 'boringssl', 'cpu_cost': guess_cpu(scenario_json, False), 'exclude_configs': ['tsan', 'asan'], 'timeout_seconds': 6*60, 'excluded_poll_engines': scenario_json.get('EXCLUDED_POLL_ENGINES', []) } for scenario_json in scenario_config.CXXLanguage().scenarios() if 'inproc' in scenario_json.get('CATEGORIES', []) ] + [ { 'name': 'json_run_localhost', 'shortname': 'json_run_localhost:%s_low_thread_count' % scenario_json['name'], 'args': ['--scenarios_json', _scenario_json_string(scenario_json, True)], 'ci_platforms': ['linux'], 'platforms': ['linux'], 'flaky': False, 'language': 'c++', 'boringssl': True, 'defaults': 'boringssl', 'cpu_cost': guess_cpu(scenario_json, True), 'exclude_configs': sorted(c for c in configs_from_yaml if c not in ('tsan', 'asan')), 'timeout_seconds': 10*60, 'excluded_poll_engines': scenario_json.get('EXCLUDED_POLL_ENGINES', []), 'auto_timeout_scaling': False } for scenario_json in scenario_config.CXXLanguage().scenarios() if 'scalable' in scenario_json.get('CATEGORIES', []) ] })
apache-2.0
Yong-Lee/django
tests/forms_tests/tests/test_regressions.py
155
8024
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import ( CharField, ChoiceField, Form, HiddenInput, IntegerField, ModelForm, ModelMultipleChoiceField, MultipleChoiceField, RadioSelect, Select, TextInput, ) from django.test import TestCase, ignore_warnings from django.utils import translation from django.utils.translation import gettext_lazy, ugettext_lazy from ..models import Cheese class FormsRegressionsTestCase(TestCase): def test_class(self): # Tests to prevent against recurrences of earlier bugs. extra_attrs = {'class': 'special'} class TestForm(Form): f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs)) f2 = CharField(widget=TextInput(attrs=extra_attrs)) self.assertHTMLEqual(TestForm(auto_id=False).as_p(), '<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>') def test_regression_3600(self): # Tests for form i18n # # There were some problems with form translations in #3600 class SomeForm(Form): username = CharField(max_length=10, label=ugettext_lazy('username')) f = SomeForm() self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') # Translations are done at rendering time, so multi-lingual apps can define forms) with translation.override('de'): self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') with translation.override('pl'): self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">u\u017cytkownik:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') def test_regression_5216(self): # There was some problems with form translations in #5216 class SomeForm(Form): field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) f = SomeForm() self.assertHTMLEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1:</label>') self.assertHTMLEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2:</label>') # Unicode decoding problems... GENDERS = (('\xc5', 'En tied\xe4'), ('\xf8', 'Mies'), ('\xdf', 'Nainen')) class SomeForm(Form): somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label='\xc5\xf8\xdf') f = SomeForm() self.assertHTMLEqual(f.as_p(), '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul id="id_somechoice">\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') # Translated error messages used to be buggy. with translation.override('ru'): f = SomeForm({}) self.assertHTMLEqual(f.as_p(), '<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul id="id_somechoice">\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') # Deep copying translated text shouldn't raise an error) class CopyForm(Form): degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) f = CopyForm() @ignore_warnings(category=UnicodeWarning) def test_regression_5216_b(self): # Testing choice validation with UTF-8 bytestrings as input (these are the # Russian abbreviations "мес." and "шт.". UNITS = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'), (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.')) f = ChoiceField(choices=UNITS) self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.') self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.') def test_misc(self): # There once was a problem with Form fields called "data". Let's make sure that # doesn't come back. class DataForm(Form): data = CharField(max_length=10) f = DataForm({'data': 'xyzzy'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {'data': 'xyzzy'}) # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertHTMLEqual(f.as_p(), '<ul class="errorlist nonfield"><li>(Hidden field data) This field is required.</li></ul>\n<p> <input type="hidden" name="data" id="id_data" /></p>') self.assertHTMLEqual(f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield"><li>(Hidden field data) This field is required.</li></ul><input type="hidden" name="data" id="id_data" /></td></tr>') def test_xss_error_messages(self): ################################################### # Tests for XSS vulnerabilities in error messages # ################################################### # The forms layer doesn't escape input values directly because error messages # might be presented in non-HTML contexts. Instead, the message is just marked # for escaping by the template engine. So we'll need to construct a little # silly template to trigger the escaping. from django.template import Template, Context t = Template('{{ form.errors }}') class SomeForm(Form): field = ChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': '<script>'}) self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>') class SomeForm(Form): field = MultipleChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': ['<script>']}) self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>') from forms_tests.models import ChoiceModel class SomeForm(Form): field = ModelMultipleChoiceField(ChoiceModel.objects.all()) f = SomeForm({'field': ['<script>']}) self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>') def test_regression_14234(self): """ Re-cleaning an instance that was added via a ModelForm should not raise a pk uniqueness error. """ class CheeseForm(ModelForm): class Meta: model = Cheese fields = '__all__' form = CheeseForm({ 'name': 'Brie', }) self.assertTrue(form.is_valid()) obj = form.save() obj.name = 'Camembert' obj.full_clean()
bsd-3-clause
cchurch/ansible
lib/ansible/modules/cloud/amazon/aws_direct_connect_link_aggregation_group.py
31
18136
#!/usr/bin/python # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: aws_direct_connect_link_aggregation_group short_description: Manage Direct Connect LAG bundles. description: - Create, delete, or modify a Direct Connect link aggregation group. version_added: "2.4" author: "Sloane Hertel (@s-hertel)" extends_documentation_fragment: - aws - ec2 requirements: - boto3 - botocore options: state: description: - The state of the Direct Connect link aggregation group. choices: - present - absent name: description: - The name of the Direct Connect link aggregation group. link_aggregation_group_id: description: - The ID of the Direct Connect link aggregation group. num_connections: description: - The number of connections with which to intialize the link aggregation group. min_links: description: - The minimum number of physical connections that must be operational for the LAG itself to be operational. location: description: - The location of the link aggregation group. bandwidth: description: - The bandwidth of the link aggregation group. force_delete: description: - This allows the minimum number of links to be set to 0, any hosted connections disassociated, and any virtual interfaces associated to the LAG deleted. type: bool connection_id: description: - A connection ID to link with the link aggregation group upon creation. delete_with_disassociation: description: - To be used with I(state=absent) to delete connections after disassociating them with the LAG. type: bool wait: description: - Whether or not to wait for the operation to complete. May be useful when waiting for virtual interfaces to be deleted. May modify the time of waiting with C(wait_timeout). type: bool wait_timeout: description: - The duration in seconds to wait if I(wait) is True. default: 120 """ EXAMPLES = """ # create a Direct Connect connection - aws_direct_connect_link_aggregation_group: state: present location: EqDC2 lag_id: dxlag-xxxxxxxx bandwidth: 1Gbps """ RETURN = """ changed: type: str description: Whether or not the LAG has changed. returned: always aws_device: type: str description: The AWS Direct Connection endpoint that hosts the LAG. sample: "EqSe2-1bwfvazist2k0" returned: when I(state=present) connections: type: list description: A list of connections bundled by this LAG. sample: "connections": [ { "aws_device": "EqSe2-1bwfvazist2k0", "bandwidth": "1Gbps", "connection_id": "dxcon-fgzjah5a", "connection_name": "Requested Connection 1 for Lag dxlag-fgtoh97h", "connection_state": "down", "lag_id": "dxlag-fgnsp4rq", "location": "EqSe2", "owner_account": "448830907657", "region": "us-west-2" } ] returned: when I(state=present) connections_bandwidth: type: str description: The individual bandwidth of the physical connections bundled by the LAG. sample: "1Gbps" returned: when I(state=present) lag_id: type: str description: Unique identifier for the link aggregation group. sample: "dxlag-fgnsp4rq" returned: when I(state=present) lag_name: type: str description: User-provided name for the link aggregation group. returned: when I(state=present) lag_state: type: str description: State of the LAG. sample: "pending" returned: when I(state=present) location: type: str description: Where the connection is located. sample: "EqSe2" returned: when I(state=present) minimum_links: type: int description: The minimum number of physical connections that must be operational for the LAG itself to be operational. returned: when I(state=present) number_of_connections: type: int description: The number of physical connections bundled by the LAG. returned: when I(state=present) owner_account: type: str description: Owner account ID of the LAG. returned: when I(state=present) region: type: str description: The region in which the LAG exists. returned: when I(state=present) """ from ansible.module_utils.ec2 import (camel_dict_to_snake_dict, ec2_argument_spec, HAS_BOTO3, get_aws_connection_info, boto3_conn, AWSRetry) from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.aws.direct_connect import (DirectConnectError, delete_connection, delete_virtual_interface, disassociate_connection_and_lag) import traceback import time try: import botocore except Exception: pass # handled by imported HAS_BOTO3 def lag_status(client, lag_id): return lag_exists(client, lag_id=lag_id, lag_name=None, verify=False) def lag_exists(client, lag_id=None, lag_name=None, verify=True): """ If verify=True, returns the LAG ID or None If verify=False, returns the LAG's data (or an empty dict) """ try: if lag_id: response = client.describe_lags(lagId=lag_id) else: response = client.describe_lags() except botocore.exceptions.ClientError as e: if lag_id and verify: return False elif lag_id: return {} else: failed_op = "Failed to describe DirectConnect link aggregation groups." raise DirectConnectError(msg=failed_op, last_traceback=traceback.format_exc(), exception=e) match = [] # List of LAG IDs that are exact matches lag = [] # List of LAG data that are exact matches # look for matching connections if len(response.get('lags', [])) == 1 and lag_id: if response['lags'][0]['lagState'] != 'deleted': match.append(response['lags'][0]['lagId']) lag.append(response['lags'][0]) else: for each in response.get('lags', []): if each['lagState'] != 'deleted': if not lag_id: if lag_name == each['lagName']: match.append(each['lagId']) else: match.append(each['lagId']) # verifying if the connections exists; if true, return connection identifier, otherwise return False if verify and len(match) == 1: return match[0] elif verify: return False # not verifying if the connection exists; just return current connection info else: if len(lag) == 1: return lag[0] else: return {} def create_lag(client, num_connections, location, bandwidth, name, connection_id): if not name: raise DirectConnectError(msg="Failed to create a Direct Connect link aggregation group: name required.", last_traceback=None, exception="") parameters = dict(numberOfConnections=num_connections, location=location, connectionsBandwidth=bandwidth, lagName=name) if connection_id: parameters.update(connectionId=connection_id) try: lag = client.create_lag(**parameters) except botocore.exceptions.ClientError as e: raise DirectConnectError(msg="Failed to create DirectConnect link aggregation group {0}".format(name), last_traceback=traceback.format_exc(), exception=e) return lag['lagId'] def delete_lag(client, lag_id): try: client.delete_lag(lagId=lag_id) except botocore.exceptions.ClientError as e: raise DirectConnectError(msg="Failed to delete Direct Connect link aggregation group {0}.".format(lag_id), last_traceback=traceback.format_exc(), exception=e) @AWSRetry.backoff(tries=5, delay=2, backoff=2.0, catch_extra_error_codes=['DirectConnectClientException']) def _update_lag(client, lag_id, lag_name, min_links): params = {} if min_links: params.update(minimumLinks=min_links) if lag_name: params.update(lagName=lag_name) client.update_lag(lagId=lag_id, **params) def update_lag(client, lag_id, lag_name, min_links, num_connections, wait, wait_timeout): start = time.time() if min_links and min_links > num_connections: raise DirectConnectError( msg="The number of connections {0} must be greater than the minimum number of links " "{1} to update the LAG {2}".format(num_connections, min_links, lag_id), last_traceback=None, exception=None ) while True: try: _update_lag(client, lag_id, lag_name, min_links) except botocore.exceptions.ClientError as e: if wait and time.time() - start <= wait_timeout: continue msg = "Failed to update Direct Connect link aggregation group {0}.".format(lag_id) if "MinimumLinks cannot be set higher than the number of connections" in e.response['Error']['Message']: msg += "Unable to set the min number of links to {0} while the LAG connections are being requested".format(min_links) raise DirectConnectError(msg=msg, last_traceback=traceback.format_exc(), exception=e) else: break def lag_changed(current_status, name, min_links): """ Determines if a modifiable link aggregation group attribute has been modified. """ return (name and name != current_status['lagName']) or (min_links and min_links != current_status['minimumLinks']) def ensure_present(client, num_connections, lag_id, lag_name, location, bandwidth, connection_id, min_links, wait, wait_timeout): exists = lag_exists(client, lag_id, lag_name) if not exists and lag_id: raise DirectConnectError(msg="The Direct Connect link aggregation group {0} does not exist.".format(lag_id), last_traceback=None, exception="") # the connection is found; get the latest state and see if it needs to be updated if exists: lag_id = exists latest_state = lag_status(client, lag_id) if lag_changed(latest_state, lag_name, min_links): update_lag(client, lag_id, lag_name, min_links, num_connections, wait, wait_timeout) return True, lag_id return False, lag_id # no connection found; create a new one else: lag_id = create_lag(client, num_connections, location, bandwidth, lag_name, connection_id) update_lag(client, lag_id, lag_name, min_links, num_connections, wait, wait_timeout) return True, lag_id def describe_virtual_interfaces(client, lag_id): try: response = client.describe_virtual_interfaces(connectionId=lag_id) except botocore.exceptions.ClientError as e: raise DirectConnectError(msg="Failed to describe any virtual interfaces associated with LAG: {0}".format(lag_id), last_traceback=traceback.format_exc(), exception=e) return response.get('virtualInterfaces', []) def get_connections_and_virtual_interfaces(client, lag_id): virtual_interfaces = describe_virtual_interfaces(client, lag_id) connections = lag_status(client, lag_id=lag_id).get('connections', []) return virtual_interfaces, connections def disassociate_vis(client, lag_id, virtual_interfaces): for vi in virtual_interfaces: delete_virtual_interface(client, vi['virtualInterfaceId']) try: response = client.delete_virtual_interface(virtualInterfaceId=vi['virtualInterfaceId']) except botocore.exceptions.ClientError as e: raise DirectConnectError(msg="Could not delete virtual interface {0} to delete link aggregation group {1}.".format(vi, lag_id), last_traceback=traceback.format_exc(), exception=e) def ensure_absent(client, lag_id, lag_name, force_delete, delete_with_disassociation, wait, wait_timeout): lag_id = lag_exists(client, lag_id, lag_name) if not lag_id: return False latest_status = lag_status(client, lag_id) # determinine the associated connections and virtual interfaces to disassociate virtual_interfaces, connections = get_connections_and_virtual_interfaces(client, lag_id) # If min_links is not 0, there are associated connections, or if there are virtual interfaces, ask for force_delete if any((latest_status['minimumLinks'], virtual_interfaces, connections)) and not force_delete: raise DirectConnectError(msg="There are a minimum number of links, hosted connections, or associated virtual interfaces for LAG {0}. " "To force deletion of the LAG use delete_force: True (if the LAG has virtual interfaces they will be deleted). " "Optionally, to ensure hosted connections are deleted after disassociation use delete_with_disassociation: True " "and wait: True (as Virtual Interfaces may take a few moments to delete)".format(lag_id), last_traceback=None, exception=None) # update min_links to be 0 so we can remove the LAG update_lag(client, lag_id, None, 0, len(connections), wait, wait_timeout) # if virtual_interfaces and not delete_vi_with_disassociation: Raise failure; can't delete while vi attached for connection in connections: disassociate_connection_and_lag(client, connection['connectionId'], lag_id) if delete_with_disassociation: delete_connection(client, connection['connectionId']) for vi in virtual_interfaces: delete_virtual_interface(client, vi['virtualInterfaceId']) start_time = time.time() while True: try: delete_lag(client, lag_id) except DirectConnectError as e: if ('until its Virtual Interfaces are deleted' in e.exception) and (time.time() - start_time < wait_timeout) and wait: continue else: return True def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), name=dict(), link_aggregation_group_id=dict(), num_connections=dict(type='int'), min_links=dict(type='int'), location=dict(), bandwidth=dict(), connection_id=dict(), delete_with_disassociation=dict(type='bool', default=False), force_delete=dict(type='bool', default=False), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=120), )) module = AnsibleModule(argument_spec=argument_spec, required_one_of=[('link_aggregation_group_id', 'name')], required_if=[('state', 'present', ('location', 'bandwidth'))]) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) if not region: module.fail_json(msg="Either region or AWS_REGION or EC2_REGION environment variable or boto config aws_region or ec2_region must be set.") connection = boto3_conn(module, conn_type='client', resource='directconnect', region=region, endpoint=ec2_url, **aws_connect_kwargs) state = module.params.get('state') response = {} try: if state == 'present': changed, lag_id = ensure_present(connection, num_connections=module.params.get("num_connections"), lag_id=module.params.get("link_aggregation_group_id"), lag_name=module.params.get("name"), location=module.params.get("location"), bandwidth=module.params.get("bandwidth"), connection_id=module.params.get("connection_id"), min_links=module.params.get("min_links"), wait=module.params.get("wait"), wait_timeout=module.params.get("wait_timeout")) response = lag_status(connection, lag_id) elif state == "absent": changed = ensure_absent(connection, lag_id=module.params.get("link_aggregation_group_id"), lag_name=module.params.get("name"), force_delete=module.params.get("force_delete"), delete_with_disassociation=module.params.get("delete_with_disassociation"), wait=module.params.get('wait'), wait_timeout=module.params.get('wait_timeout')) except DirectConnectError as e: if e.last_traceback: module.fail_json(msg=e.msg, exception=e.last_traceback, **camel_dict_to_snake_dict(e.exception)) else: module.fail_json(msg=e.msg) module.exit_json(changed=changed, **camel_dict_to_snake_dict(response)) if __name__ == '__main__': main()
gpl-3.0
TheWardoctor/Wardoctors-repo
script.module.uncoded/lib/resources/lib/sources/en/vodly.py
7
4367
# -*- coding: utf-8 -*- ''' Covenant Add-on 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 re, urlparse, urllib, base64 from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import cache from resources.lib.modules import dom_parser2 class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['vodly.us', 'vodly.unblocked.pro'] self.base_link = 'http://vodly.us' self.search_link = '/search?s=%s' def movie(self, imdb, title, localtitle, aliases, year): try: items = [] clean_title = cleantitle.geturl(title) +'-'+ year search_url = urlparse.urljoin(self.base_link, self.search_link % clean_title.replace('-', '+')) r = cache.get(client.request, 1, search_url) r = client.parseDOM(r, 'div', {'class': 'col-sm-12'}) r = client.parseDOM(r, 'div', {'class': 'col-sm-2.+?'}) r1 = client.parseDOM(r, 'h3') r1 = [(client.parseDOM(i, 'a', ret='href')[0], client.parseDOM(i, 'a')[0])for i in r1] y = [re.findall('</i>\s*(\d{4})</span>', i) for i in r] items += [(r1[i], y[i]) for i in range(len(y))] r = [(i[0][0], i[1][0], i[0][1]) for i in items if (cleantitle.get(i[0][1]) == cleantitle.get(title) and i[1][0] == year)] url = r[0][0] return url except Exception: return def sources(self, url, hostDict, hostprDict): try: sources = [] url = urlparse.urljoin(self.base_link,url) r = cache.get(client.request, 1, url) try: v = client.parseDOM(r, 'iframe', ret='data-src')[0] url = v.split('=')[1] try: host = re.findall('([\w]+[.][\w]+)$', urlparse.urlparse(url.strip().lower()).netloc)[0] host = client.replaceHTMLCodes(host) host = host.encode('utf-8') sources.append({ 'source': host, 'quality': 'SD', 'language': 'en', 'url': url.replace('\/', '/'), 'direct': False, 'debridonly': False }) except: pass except: pass r = client.parseDOM(r, 'tbody') r = client.parseDOM(r, 'tr') r = [(re.findall('<td>(.+?)</td>', i)[0], client.parseDOM(i, 'a', ret='href')[0]) for i in r] if r: for i in r: try: host = i[0] url = urlparse.urljoin(self.base_link, i[1]) host = client.replaceHTMLCodes(host) host = host.encode('utf-8') if 'other'in host: continue sources.append({ 'source': host, 'quality': 'SD', 'language': 'en', 'url': url.replace('\/', '/'), 'direct': False, 'debridonly': False }) except: pass return sources except Exception: return def resolve(self, url): if self.base_link in url: url = client.request(url) url = client.parseDOM(url, 'div', attrs={'class': 'wrap'}) url = client.parseDOM(url, 'a', ret='href')[0] return url
apache-2.0
uranusjr/django
django/conf/locale/sv/formats.py
65
1502
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y-m-d' SHORT_DATETIME_FORMAT = 'Y-m-d H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y', # '10/25/06' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
bsd-3-clause
Edraak/edx-platform
common/lib/xmodule/xmodule/capa_base.py
1
61702
"""Implements basics of Capa, including class CapaModule.""" import cgi import copy import datetime import hashlib import json import logging import os import traceback import struct import sys import re # We don't want to force a dependency on datadog, so make the import conditional try: import dogstats_wrapper as dog_stats_api except ImportError: dog_stats_api = None from capa.capa_problem import LoncapaProblem, LoncapaSystem from capa.responsetypes import StudentInputError, \ ResponseError, LoncapaProblemError from capa.util import convert_files_to_filenames, get_inner_html_from_xpath from .progress import Progress from xmodule.exceptions import NotFoundError from xblock.fields import Scope, String, Boolean, Dict, Integer, Float from .fields import Timedelta, Date from django.utils.timezone import UTC from xmodule.capa_base_constants import RANDOMIZATION, SHOWANSWER from django.conf import settings log = logging.getLogger("edx.courseware") # Make '_' a no-op so we can scrape strings. Using lambda instead of # `django.utils.translation.ugettext_noop` because Django cannot be imported in this file _ = lambda text: text # Generate this many different variants of problems with rerandomize=per_student NUM_RANDOMIZATION_BINS = 20 # Never produce more than this many different seeds, no matter what. MAX_RANDOMIZATION_BINS = 1000 def randomization_bin(seed, problem_id): """ Pick a randomization bin for the problem given the user's seed and a problem id. We do this because we only want e.g. 20 randomizations of a problem to make analytics interesting. To avoid having sets of students that always get the same problems, we'll combine the system's per-student seed with the problem id in picking the bin. """ r_hash = hashlib.sha1() r_hash.update(str(seed)) r_hash.update(str(problem_id)) # get the first few digits of the hash, convert to an int, then mod. return int(r_hash.hexdigest()[:7], 16) % NUM_RANDOMIZATION_BINS class Randomization(String): """ Define a field to store how to randomize a problem. """ def from_json(self, value): if value in ("", "true"): return RANDOMIZATION.ALWAYS elif value == "false": return RANDOMIZATION.PER_STUDENT return value to_json = from_json class ComplexEncoder(json.JSONEncoder): """ Extend the JSON encoder to correctly handle complex numbers """ def default(self, obj): """ Print a nicely formatted complex number, or default to the JSON encoder """ if isinstance(obj, complex): return u"{real:.7g}{imag:+.7g}*j".format(real=obj.real, imag=obj.imag) return json.JSONEncoder.default(self, obj) class CapaFields(object): """ Define the possible fields for a Capa problem """ display_name = String( display_name=_("Display Name"), help=_("This name appears in the horizontal navigation at the top of the page."), scope=Scope.settings, # it'd be nice to have a useful default but it screws up other things; so, # use display_name_with_default for those default=_("Blank Advanced Problem") ) attempts = Integer( help=_("Number of attempts taken by the student on this problem"), default=0, scope=Scope.user_state) max_attempts = Integer( display_name=_("Maximum Attempts"), help=_("Defines the number of times a student can try to answer this problem. " "If the value is not set, infinite attempts are allowed."), values={"min": 0}, scope=Scope.settings ) due = Date(help=_("Date that this problem is due by"), scope=Scope.settings) graceperiod = Timedelta( help=_("Amount of time after the due date that submissions will be accepted"), scope=Scope.settings ) showanswer = String( display_name=_("Show Answer"), help=_("Defines when to show the answer to the problem. " "A default value can be set in Advanced Settings."), scope=Scope.settings, default=SHOWANSWER.FINISHED, values=[ {"display_name": _("Always"), "value": SHOWANSWER.ALWAYS}, {"display_name": _("Answered"), "value": SHOWANSWER.ANSWERED}, {"display_name": _("Attempted"), "value": SHOWANSWER.ATTEMPTED}, {"display_name": _("Closed"), "value": SHOWANSWER.CLOSED}, {"display_name": _("Finished"), "value": SHOWANSWER.FINISHED}, {"display_name": _("Correct or Past Due"), "value": SHOWANSWER.CORRECT_OR_PAST_DUE}, {"display_name": _("Past Due"), "value": SHOWANSWER.PAST_DUE}, {"display_name": _("Never"), "value": SHOWANSWER.NEVER}] ) force_save_button = Boolean( help=_("Whether to force the save button to appear on the page"), scope=Scope.settings, default=False ) reset_key = "DEFAULT_SHOW_RESET_BUTTON" default_reset_button = getattr(settings, reset_key) if hasattr(settings, reset_key) else False show_reset_button = Boolean( display_name=_("Show Reset Button"), help=_("Determines whether a 'Reset' button is shown so the user may reset their answer. " "A default value can be set in Advanced Settings."), scope=Scope.settings, default=default_reset_button ) rerandomize = Randomization( display_name=_("Randomization"), help=_( 'Defines when to randomize the variables specified in the associated Python script. ' 'For problems that do not randomize values, specify \"Never\". ' ), default=RANDOMIZATION.NEVER, scope=Scope.settings, values=[ {"display_name": _("Always"), "value": RANDOMIZATION.ALWAYS}, {"display_name": _("On Reset"), "value": RANDOMIZATION.ONRESET}, {"display_name": _("Never"), "value": RANDOMIZATION.NEVER}, {"display_name": _("Per Student"), "value": RANDOMIZATION.PER_STUDENT} ] ) data = String(help=_("XML data for the problem"), scope=Scope.content, default="<problem></problem>") correct_map = Dict(help=_("Dictionary with the correctness of current student answers"), scope=Scope.user_state, default={}) input_state = Dict(help=_("Dictionary for maintaining the state of inputtypes"), scope=Scope.user_state) student_answers = Dict(help=_("Dictionary with the current student responses"), scope=Scope.user_state) done = Boolean(help=_("Whether the student has answered the problem"), scope=Scope.user_state) seed = Integer(help=_("Random seed for this student"), scope=Scope.user_state) last_submission_time = Date(help=_("Last submission time"), scope=Scope.user_state) submission_wait_seconds = Integer( display_name=_("Timer Between Attempts"), help=_("Seconds a student must wait between submissions for a problem with multiple attempts."), scope=Scope.settings, default=0) weight = Float( display_name=_("Problem Weight"), help=_("Defines the number of points each problem is worth. " "If the value is not set, each response field in the problem is worth one point."), values={"min": 0, "step": .1}, scope=Scope.settings ) markdown = String(help=_("Markdown source of this module"), default=None, scope=Scope.settings) source_code = String( help=_("Source code for LaTeX and Word problems. This feature is not well-supported."), scope=Scope.settings ) text_customization = Dict( help=_("String customization substitutions for particular locations"), scope=Scope.settings # TODO: someday it should be possible to not duplicate this definition here # and in inheritance.py ) use_latex_compiler = Boolean( help=_("Enable LaTeX templates?"), default=False, scope=Scope.settings ) matlab_api_key = String( display_name=_("Matlab API key"), help=_("Enter the API key provided by MathWorks for accessing the MATLAB Hosted Service. " "This key is granted for exclusive use by this course for the specified duration. " "Please do not share the API key with other courses and notify MathWorks immediately " "if you believe the key is exposed or compromised. To obtain a key for your course, " "or to report an issue, please contact moocsupport@mathworks.com"), scope=Scope.settings ) class CapaMixin(CapaFields): """ Core logic for Capa Problem, which can be used by XModules or XBlocks. """ def __init__(self, *args, **kwargs): super(CapaMixin, self).__init__(*args, **kwargs) due_date = self.due if self.graceperiod is not None and due_date: self.close_date = due_date + self.graceperiod else: self.close_date = due_date if self.seed is None: self.choose_new_seed() # Need the problem location in openendedresponse to send out. Adding # it to the system here seems like the least clunky way to get it # there. self.runtime.set('location', self.location.to_deprecated_string()) try: # TODO (vshnayder): move as much as possible of this work and error # checking to descriptor load time self.lcp = self.new_lcp(self.get_state_for_lcp()) # At this point, we need to persist the randomization seed # so that when the problem is re-loaded (to check/view/save) # it stays the same. # However, we do not want to write to the database # every time the module is loaded. # So we set the seed ONLY when there is not one set already if self.seed is None: self.seed = self.lcp.seed except Exception as err: # pylint: disable=broad-except msg = u'cannot create LoncapaProblem {loc}: {err}'.format( loc=self.location.to_deprecated_string(), err=err) # TODO (vshnayder): do modules need error handlers too? # We shouldn't be switching on DEBUG. if self.runtime.DEBUG: log.warning(msg) # TODO (vshnayder): This logic should be general, not here--and may # want to preserve the data instead of replacing it. # e.g. in the CMS msg = u'<p>{msg}</p>'.format(msg=cgi.escape(msg)) msg += u'<p><pre>{tb}</pre></p>'.format( # just the traceback, no message - it is already present above tb=cgi.escape( u''.join( ['Traceback (most recent call last):\n'] + traceback.format_tb(sys.exc_info()[2]) ) ) ) # create a dummy problem with error message instead of failing problem_text = (u'<problem><text><span class="inline-error">' u'Problem {url} has an error:</span>{msg}</text></problem>'.format( url=self.location.to_deprecated_string(), msg=msg) ) self.lcp = self.new_lcp(self.get_state_for_lcp(), text=problem_text) else: # add extra info and raise raise Exception(msg), None, sys.exc_info()[2] self.set_state_from_lcp() assert self.seed is not None def choose_new_seed(self): """ Choose a new seed. """ if self.rerandomize == RANDOMIZATION.NEVER: self.seed = 1 elif self.rerandomize == RANDOMIZATION.PER_STUDENT and hasattr(self.runtime, 'seed'): # see comment on randomization_bin self.seed = randomization_bin(self.runtime.seed, unicode(self.location).encode('utf-8')) else: self.seed = struct.unpack('i', os.urandom(4))[0] # So that sandboxed code execution can be cached, but still have an interesting # number of possibilities, cap the number of different random seeds. self.seed %= MAX_RANDOMIZATION_BINS def new_lcp(self, state, text=None): """ Generate a new Loncapa Problem """ if text is None: text = self.data capa_system = LoncapaSystem( ajax_url=self.runtime.ajax_url, anonymous_student_id=self.runtime.anonymous_student_id, cache=self.runtime.cache, can_execute_unsafe_code=self.runtime.can_execute_unsafe_code, get_python_lib_zip=self.runtime.get_python_lib_zip, DEBUG=self.runtime.DEBUG, filestore=self.runtime.filestore, i18n=self.runtime.service(self, "i18n"), node_path=self.runtime.node_path, render_template=self.runtime.render_template, seed=self.runtime.seed, # Why do we do this if we have self.seed? STATIC_URL=self.runtime.STATIC_URL, xqueue=self.runtime.xqueue, matlab_api_key=self.matlab_api_key ) return LoncapaProblem( problem_text=text, id=self.location.html_id(), state=state, seed=self.seed, capa_system=capa_system, capa_module=self, # njp ) def get_state_for_lcp(self): """ Give a dictionary holding the state of the module """ return { 'done': self.done, 'correct_map': self.correct_map, 'student_answers': self.student_answers, 'input_state': self.input_state, 'seed': self.seed, } def set_state_from_lcp(self): """ Set the module's state from the settings in `self.lcp` """ lcp_state = self.lcp.get_state() self.done = lcp_state['done'] self.correct_map = lcp_state['correct_map'] self.input_state = lcp_state['input_state'] self.student_answers = lcp_state['student_answers'] self.seed = lcp_state['seed'] def set_last_submission_time(self): """ Set the module's last submission time (when the problem was checked) """ self.last_submission_time = datetime.datetime.now(UTC()) def get_score(self): """ Access the problem's score """ return self.lcp.get_score() def max_score(self): """ Access the problem's max score """ return self.lcp.get_max_score() def get_progress(self): """ For now, just return score / max_score """ score_dict = self.get_score() score = score_dict['score'] total = score_dict['total'] if total > 0: if self.weight is not None: # Progress objects expect total > 0 if self.weight == 0: return None # scale score and total by weight/total: score = score * self.weight / total total = self.weight try: return Progress(score, total) except (TypeError, ValueError): log.exception("Got bad progress") return None return None def get_html(self): """ Return some html with data about the module """ progress = self.get_progress() return self.runtime.render_template('problem_ajax.html', { 'element_id': self.location.html_id(), 'id': self.location.to_deprecated_string(), 'ajax_url': self.runtime.ajax_url, 'progress_status': Progress.to_js_status_str(progress), 'progress_detail': Progress.to_js_detail_str(progress), }) def check_button_name(self): """ Determine the name for the "check" button. Usually it is just "Check", but if this is the student's final attempt, change the name to "Final Check". The text can be customized by the text_customization setting. """ # The logic flow is a little odd so that _('xxx') strings can be found for # translation while also running _() just once for each string. _ = self.runtime.service(self, "i18n").ugettext # Edraak: The name for the "check" button will not change anymore check = _('Check') final_check = check # Apply customizations if present if 'custom_check' in self.text_customization: check = _(self.text_customization.get('custom_check')) # pylint: disable=translation-of-non-string if 'custom_final_check' in self.text_customization: final_check = _(self.text_customization.get('custom_final_check')) # pylint: disable=translation-of-non-string # TODO: need a way to get the customized words into the list of # words to be translated if self.max_attempts is not None and self.attempts >= self.max_attempts - 1: return final_check else: return check def check_button_checking_name(self): """ Return the "checking..." text for the "check" button. After the user presses the "check" button, the button will briefly display the value returned by this function until a response is received by the server. The text can be customized by the text_customization setting. """ # Apply customizations if present if 'custom_checking' in self.text_customization: return self.text_customization.get('custom_checking') _ = self.runtime.service(self, "i18n").ugettext return _('Checking...') def should_show_check_button(self): """ Return True/False to indicate whether to show the "Check" button. """ submitted_without_reset = (self.is_submitted() and self.rerandomize == RANDOMIZATION.ALWAYS) # If the problem is closed (past due / too many attempts) # then we do NOT show the "check" button # Also, do not show the "check" button if we're waiting # for the user to reset a randomized problem if self.closed() or submitted_without_reset: return False else: return True def should_show_reset_button(self): """ Return True/False to indicate whether to show the "Reset" button. """ is_survey_question = (self.max_attempts == 0) # If the problem is closed (and not a survey question with max_attempts==0), # then do NOT show the reset button. if self.closed() and not is_survey_question: return False # Button only shows up for randomized problems if the question has been submitted if self.rerandomize in [RANDOMIZATION.ALWAYS, RANDOMIZATION.ONRESET] and self.is_submitted(): return True else: # Do NOT show the button if the problem is correct if self.is_correct(): return False else: return self.show_reset_button def should_show_save_button(self): """ Return True/False to indicate whether to show the "Save" button. """ # If the user has forced the save button to display, # then show it as long as the problem is not closed # (past due / too many attempts) if self.force_save_button: return not self.closed() else: is_survey_question = (self.max_attempts == 0) needs_reset = self.is_submitted() and self.rerandomize == RANDOMIZATION.ALWAYS # If the student has unlimited attempts, and their answers # are not randomized, then we do not need a save button # because they can use the "Check" button without consequences. # # The consequences we want to avoid are: # * Using up an attempt (if max_attempts is set) # * Changing the current problem, and no longer being # able to view it (if rerandomize is "always") # # In those cases. the if statement below is false, # and the save button can still be displayed. # if self.max_attempts is None and self.rerandomize != RANDOMIZATION.ALWAYS: return False # If the problem is closed (and not a survey question with max_attempts==0), # then do NOT show the save button # If we're waiting for the user to reset a randomized problem # then do NOT show the save button elif (self.closed() and not is_survey_question) or needs_reset: return False else: return True def handle_problem_html_error(self, err): """ Create a dummy problem to represent any errors. Change our problem to a dummy problem containing a warning message to display to users. Returns the HTML to show to users `err` is the Exception encountered while rendering the problem HTML. """ log.exception(err.message) # TODO (vshnayder): another switch on DEBUG. if self.runtime.DEBUG: msg = ( u'[courseware.capa.capa_module] <font size="+1" color="red">' u'Failed to generate HTML for problem {url}</font>'.format( url=cgi.escape(self.location.to_deprecated_string())) ) msg += u'<p>Error:</p><p><pre>{msg}</pre></p>'.format(msg=cgi.escape(err.message)) msg += u'<p><pre>{tb}</pre></p>'.format(tb=cgi.escape(traceback.format_exc())) html = msg else: # We're in non-debug mode, and possibly even in production. We want # to avoid bricking of problem as much as possible # Presumably, student submission has corrupted LoncapaProblem HTML. # First, pull down all student answers student_answers = self.lcp.student_answers answer_ids = student_answers.keys() # Some inputtypes, such as dynamath, have additional "hidden" state that # is not exposed to the student. Keep those hidden # TODO: Use regex, e.g. 'dynamath' is suffix at end of answer_id hidden_state_keywords = ['dynamath'] for answer_id in answer_ids: for hidden_state_keyword in hidden_state_keywords: if answer_id.find(hidden_state_keyword) >= 0: student_answers.pop(answer_id) # Next, generate a fresh LoncapaProblem self.lcp = self.new_lcp(None) self.set_state_from_lcp() # Prepend a scary warning to the student _ = self.runtime.service(self, "i18n").ugettext warning_msg = _("Warning: The problem has been reset to its initial state!") warning = '<div class="capa_reset"> <h2> ' + warning_msg + '</h2>' # Translators: Following this message, there will be a bulleted list of items. warning_msg = _("The problem's state was corrupted by an invalid submission. The submission consisted of:") warning += warning_msg + '<ul>' for student_answer in student_answers.values(): if student_answer != '': warning += '<li>' + cgi.escape(student_answer) + '</li>' warning_msg = _('If this error persists, please contact the course staff.') warning += '</ul>' + warning_msg + '</div>' html = warning try: html += self.lcp.get_html() except Exception: # Couldn't do it. Give up. log.exception("Unable to generate html from LoncapaProblem") raise return html def get_demand_hint(self, hint_index): """ Return html for the problem. Adds check, reset, save, and hint buttons as necessary based on the problem config and state. encapsulate: if True (the default) embed the html in a problem <div> hint_index: (None is the default) if not None, this is the index of the next demand hint to show. """ demand_hints = self.lcp.tree.xpath("//problem/demandhint/hint") hint_index = hint_index % len(demand_hints) _ = self.runtime.service(self, "i18n").ugettext hint_element = demand_hints[hint_index] hint_text = get_inner_html_from_xpath(hint_element) if len(demand_hints) == 1: prefix = _('Hint: ') else: # Translators: e.g. "Hint 1 of 3" meaning we are showing the first of three hints. prefix = _('Hint ({hint_num} of {hints_count}): ').format(hint_num=hint_index + 1, hints_count=len(demand_hints)) # Log this demand-hint request event_info = dict() event_info['module_id'] = self.location.to_deprecated_string() event_info['hint_index'] = hint_index event_info['hint_len'] = len(demand_hints) event_info['hint_text'] = hint_text self.runtime.track_function('edx.problem.hint.demandhint_displayed', event_info) # We report the index of this hint, the client works out what index to use to get the next hint return { 'success': True, 'contents': prefix + hint_text, 'hint_index': hint_index } def get_problem_html(self, encapsulate=True): """ Return html for the problem. Adds check, reset, save, and hint buttons as necessary based on the problem config and state. encapsulate: if True (the default) embed the html in a problem <div> """ try: html = self.lcp.get_html() # If we cannot construct the problem HTML, # then generate an error message instead. except Exception as err: # pylint: disable=broad-except html = self.handle_problem_html_error(err) html = self.remove_tags_from_html(html) # The convention is to pass the name of the check button if we want # to show a check button, and False otherwise This works because # non-empty strings evaluate to True. We use the same convention # for the "checking" state text. if self.should_show_check_button(): check_button = self.check_button_name() check_button_checking = self.check_button_checking_name() else: check_button = False check_button_checking = False content = { 'name': self.display_name_with_default_escaped, 'html': html, 'weight': self.weight, } # If demand hints are available, emit hint button and div. demand_hints = self.lcp.tree.xpath("//problem/demandhint/hint") demand_hint_possible = len(demand_hints) > 0 context = { 'problem': content, 'id': self.location.to_deprecated_string(), 'check_button': check_button, 'check_button_checking': check_button_checking, 'reset_button': self.should_show_reset_button(), 'save_button': self.should_show_save_button(), 'answer_available': self.answer_available(), 'attempts_used': self.attempts, 'attempts_allowed': self.max_attempts, 'demand_hint_possible': demand_hint_possible } html = self.runtime.render_template('problem.html', context) if encapsulate: html = u'<div id="problem_{id}" class="problem" data-url="{ajax_url}">'.format( id=self.location.html_id(), ajax_url=self.runtime.ajax_url ) + html + "</div>" # Now do all the substitutions which the LMS module_render normally does, but # we need to do here explicitly since we can get called for our HTML via AJAX html = self.runtime.replace_urls(html) if self.runtime.replace_course_urls: html = self.runtime.replace_course_urls(html) if self.runtime.replace_jump_to_id_urls: html = self.runtime.replace_jump_to_id_urls(html) return html def remove_tags_from_html(self, html): """ The capa xml includes many tags such as <additional_answer> or <demandhint> which are not meant to be part of the client html. We strip them all and return the resulting html. """ tags = ['demandhint', 'choicehint', 'optionhint', 'stringhint', 'numerichint', 'optionhint', 'correcthint', 'regexphint', 'additional_answer', 'stringequalhint', 'compoundhint', 'stringequalhint'] for tag in tags: html = re.sub(r'<%s.*?>.*?</%s>' % (tag, tag), '', html, flags=re.DOTALL) # Some of these tags span multiple lines # Note: could probably speed this up by calling sub() once with a big regex # vs. simply calling sub() many times as we have here. return html def hint_button(self, data): """ Hint button handler, returns new html using hint_index from the client. """ hint_index = int(data['hint_index']) return self.get_demand_hint(hint_index) def is_past_due(self): """ Is it now past this problem's due date, including grace period? """ return (self.close_date is not None and datetime.datetime.now(UTC()) > self.close_date) def closed(self): """ Is the student still allowed to submit answers? """ if self.max_attempts is not None and self.attempts >= self.max_attempts: return True if self.is_past_due(): return True return False def is_submitted(self): """ Used to decide to show or hide RESET or CHECK buttons. Means that student submitted problem and nothing more. Problem can be completely wrong. Pressing RESET button makes this function to return False. """ # used by conditional module return self.lcp.done def is_attempted(self): """ Has the problem been attempted? used by conditional module """ return self.attempts > 0 def is_correct(self): """ True iff full points """ score_dict = self.get_score() return score_dict['score'] == score_dict['total'] def answer_available(self): """ Is the user allowed to see an answer? """ if self.showanswer == '': return False elif self.showanswer == SHOWANSWER.NEVER: return False elif self.runtime.user_is_staff: # This is after the 'never' check because admins can see the answer # unless the problem explicitly prevents it return True elif self.showanswer == SHOWANSWER.ATTEMPTED: return self.attempts > 0 elif self.showanswer == SHOWANSWER.ANSWERED: # NOTE: this is slightly different from 'attempted' -- resetting the problems # makes lcp.done False, but leaves attempts unchanged. return self.lcp.done elif self.showanswer == SHOWANSWER.CLOSED: return self.closed() elif self.showanswer == SHOWANSWER.FINISHED: return self.closed() or self.is_correct() elif self.showanswer == SHOWANSWER.CORRECT_OR_PAST_DUE: return self.is_correct() or self.is_past_due() elif self.showanswer == SHOWANSWER.PAST_DUE: return self.is_past_due() elif self.showanswer == SHOWANSWER.ALWAYS: return True return False def update_score(self, data): """ Delivers grading response (e.g. from asynchronous code checking) to the capa problem, so its score can be updated 'data' must have a key 'response' which is a string that contains the grader's response No ajax return is needed. Return empty dict. """ queuekey = data['queuekey'] score_msg = data['xqueue_body'] self.lcp.update_score(score_msg, queuekey) self.set_state_from_lcp() self.publish_grade() return dict() # No AJAX return is needed def handle_ungraded_response(self, data): """ Delivers a response from the XQueue to the capa problem The score of the problem will not be updated Args: - data (dict) must contain keys: queuekey - a key specific to this response xqueue_body - the body of the response Returns: empty dictionary No ajax return is needed, so an empty dict is returned """ queuekey = data['queuekey'] score_msg = data['xqueue_body'] # pass along the xqueue message to the problem self.lcp.ungraded_response(score_msg, queuekey) self.set_state_from_lcp() return dict() def handle_input_ajax(self, data): """ Handle ajax calls meant for a particular input in the problem Args: - data (dict) - data that should be passed to the input Returns: - dict containing the response from the input """ response = self.lcp.handle_input_ajax(data) # save any state changes that may occur self.set_state_from_lcp() return response def get_answer(self, _data): """ For the "show answer" button. Returns the answers: {'answers' : answers} """ event_info = dict() event_info['problem_id'] = self.location.to_deprecated_string() self.track_function_unmask('showanswer', event_info) if not self.answer_available(): raise NotFoundError('Answer is not available') else: answers = self.lcp.get_question_answers() self.set_state_from_lcp() # answers (eg <solution>) may have embedded images # but be careful, some problems are using non-string answer dicts new_answers = dict() for answer_id in answers: try: answer_content = self.runtime.replace_urls(answers[answer_id]) if self.runtime.replace_jump_to_id_urls: answer_content = self.runtime.replace_jump_to_id_urls(answer_content) new_answer = {answer_id: answer_content} except TypeError: log.debug(u'Unable to perform URL substitution on answers[%s]: %s', answer_id, answers[answer_id]) new_answer = {answer_id: answers[answer_id]} new_answers.update(new_answer) return {'answers': new_answers} # Figure out if we should move these to capa_problem? def get_problem(self, _data): """ Return results of get_problem_html, as a simple dict for json-ing. { 'html': <the-html> } Used if we want to reconfirm we have the right thing e.g. after several AJAX calls. """ return {'html': self.get_problem_html(encapsulate=False)} @staticmethod def make_dict_of_responses(data): """ Make dictionary of student responses (aka "answers") `data` is POST dictionary (webob.multidict.MultiDict). The `data` dict has keys of the form 'x_y', which are mapped to key 'y' in the returned dict. For example, 'input_1_2_3' would be mapped to '1_2_3' in the returned dict. Some inputs always expect a list in the returned dict (e.g. checkbox inputs). The convention is that keys in the `data` dict that end with '[]' will always have list values in the returned dict. For example, if the `data` dict contains {'input_1[]': 'test' } then the output dict would contain {'1': ['test'] } (the value is a list). Some other inputs such as ChoiceTextInput expect a dict of values in the returned dict If the key ends with '{}' then we will assume that the value is a json encoded dict and deserialize it. For example, if the `data` dict contains {'input_1{}': '{"1_2_1": 1}'} then the output dict would contain {'1': {"1_2_1": 1} } (the value is a dictionary) Raises an exception if: -A key in the `data` dictionary does not contain at least one underscore (e.g. "input" is invalid, but "input_1" is valid) -Two keys end up with the same name in the returned dict. (e.g. 'input_1' and 'input_1[]', which both get mapped to 'input_1' in the returned dict) """ answers = dict() # webob.multidict.MultiDict is a view of a list of tuples, # so it will return a multi-value key once for each value. # We only want to consider each key a single time, so we use set(data.keys()) for key in set(data.keys()): # e.g. input_resistor_1 ==> resistor_1 _, _, name = key.partition('_') # If key has no underscores, then partition # will return (key, '', '') # We detect this and raise an error if not name: raise ValueError(u"{key} must contain at least one underscore".format(key=key)) else: # This allows for answers which require more than one value for # the same form input (e.g. checkbox inputs). The convention is that # if the name ends with '[]' (which looks like an array), then the # answer will be an array. # if the name ends with '{}' (Which looks like a dict), # then the answer will be a dict is_list_key = name.endswith('[]') is_dict_key = name.endswith('{}') name = name[:-2] if is_list_key or is_dict_key else name if is_list_key: val = data.getall(key) elif is_dict_key: try: val = json.loads(data[key]) # If the submission wasn't deserializable, raise an error. except(KeyError, ValueError): raise ValueError( u"Invalid submission: {val} for {key}".format(val=data[key], key=key) ) else: val = data[key] # If the name already exists, then we don't want # to override it. Raise an error instead if name in answers: raise ValueError(u"Key {name} already exists in answers dict".format(name=name)) else: answers[name] = val return answers def publish_grade(self): """ Publishes the student's current grade to the system as an event """ score = self.lcp.get_score() self.runtime.publish( self, 'grade', { 'value': score['score'], 'max_value': score['total'], } ) return {'grade': score['score'], 'max_grade': score['total']} # pylint: disable=too-many-statements def check_problem(self, data, override_time=False): """ Checks whether answers to a problem are correct Returns a map of correct/incorrect answers: {'success' : 'correct' | 'incorrect' | AJAX alert msg string, 'contents' : html} """ event_info = dict() event_info['state'] = self.lcp.get_state() event_info['problem_id'] = self.location.to_deprecated_string() answers = self.make_dict_of_responses(data) answers_without_files = convert_files_to_filenames(answers) event_info['answers'] = answers_without_files metric_name = u'capa.check_problem.{}'.format # Can override current time current_time = datetime.datetime.now(UTC()) if override_time is not False: current_time = override_time _ = self.runtime.service(self, "i18n").ugettext # Too late. Cannot submit if self.closed(): event_info['failure'] = 'closed' self.track_function_unmask('problem_check_fail', event_info) if dog_stats_api: dog_stats_api.increment(metric_name('checks'), tags=[u'result:failed', u'failure:closed']) raise NotFoundError(_("Problem is closed.")) # Problem submitted. Student should reset before checking again if self.done and self.rerandomize == RANDOMIZATION.ALWAYS: event_info['failure'] = 'unreset' self.track_function_unmask('problem_check_fail', event_info) if dog_stats_api: dog_stats_api.increment(metric_name('checks'), tags=[u'result:failed', u'failure:unreset']) raise NotFoundError(_("Problem must be reset before it can be checked again.")) # Problem queued. Students must wait a specified waittime before they are allowed to submit # IDEA: consider stealing code from below: pretty-print of seconds, cueing of time remaining if self.lcp.is_queued(): prev_submit_time = self.lcp.get_recentmost_queuetime() waittime_between_requests = self.runtime.xqueue['waittime'] if (current_time - prev_submit_time).total_seconds() < waittime_between_requests: msg = _(u"You must wait at least {wait} seconds between submissions.").format( wait=waittime_between_requests) return {'success': msg, 'html': ''} # Wait time between resets: check if is too soon for submission. if self.last_submission_time is not None and self.submission_wait_seconds != 0: if (current_time - self.last_submission_time).total_seconds() < self.submission_wait_seconds: remaining_secs = int(self.submission_wait_seconds - (current_time - self.last_submission_time).total_seconds()) msg = _(u'You must wait at least {wait_secs} between submissions. {remaining_secs} remaining.').format( wait_secs=self.pretty_print_seconds(self.submission_wait_seconds), remaining_secs=self.pretty_print_seconds(remaining_secs)) return { 'success': msg, 'html': '' } try: correct_map = self.lcp.grade_answers(answers) self.attempts = self.attempts + 1 self.lcp.done = True self.set_state_from_lcp() self.set_last_submission_time() except (StudentInputError, ResponseError, LoncapaProblemError) as inst: log.warning("StudentInputError in capa_module:problem_check", exc_info=True) # Save the user's state before failing self.set_state_from_lcp() # If the user is a staff member, include # the full exception, including traceback, # in the response if self.runtime.user_is_staff: msg = u"Staff debug info: {tb}".format(tb=cgi.escape(traceback.format_exc())) # Otherwise, display just an error message, # without a stack trace else: # Translators: {msg} will be replaced with a problem's error message. msg = _(u"Error: {msg}").format(msg=inst.message) return {'success': msg} except Exception as err: # Save the user's state before failing self.set_state_from_lcp() if self.runtime.DEBUG: msg = u"Error checking problem: {}".format(err.message) msg += u'\nTraceback:\n{}'.format(traceback.format_exc()) return {'success': msg} raise published_grade = self.publish_grade() # success = correct if ALL questions in this problem are correct success = 'correct' for answer_id in correct_map: if not correct_map.is_correct(answer_id): success = 'incorrect' # NOTE: We are logging both full grading and queued-grading submissions. In the latter, # 'success' will always be incorrect event_info['grade'] = published_grade['grade'] event_info['max_grade'] = published_grade['max_grade'] event_info['correct_map'] = correct_map.get_dict() event_info['success'] = success event_info['attempts'] = self.attempts event_info['submission'] = self.get_submission_metadata_safe(answers_without_files, correct_map) self.track_function_unmask('problem_check', event_info) if dog_stats_api: dog_stats_api.increment(metric_name('checks'), tags=[u'result:success']) dog_stats_api.histogram( metric_name('correct_pct'), float(published_grade['grade']) / published_grade['max_grade'], ) dog_stats_api.histogram( metric_name('attempts'), self.attempts, ) # render problem into HTML html = self.get_problem_html(encapsulate=False) return { 'success': success, 'contents': html } # pylint: enable=too-many-statements def track_function_unmask(self, title, event_info): """ All calls to runtime.track_function route through here so that the choice names can be unmasked. """ # Do the unmask translates on a copy of event_info, # avoiding problems where an event_info is unmasked twice. event_unmasked = copy.deepcopy(event_info) self.unmask_event(event_unmasked) self.runtime.track_function(title, event_unmasked) def unmask_event(self, event_info): """ Translates in-place the event_info to account for masking and adds information about permutation options in force. """ # answers is like: {u'i4x-Stanford-CS99-problem-dada976e76f34c24bc8415039dee1300_2_1': u'mask_0'} # Each response values has an answer_id which matches the key in answers. for response in self.lcp.responders.values(): # Un-mask choice names in event_info for masked responses. if response.has_mask(): # We don't assume much about the structure of event_info, # but check for the existence of the things we need to un-mask. # Look for answers/id answer = event_info.get('answers', {}).get(response.answer_id) if answer is not None: event_info['answers'][response.answer_id] = response.unmask_name(answer) # Look for state/student_answers/id answer = event_info.get('state', {}).get('student_answers', {}).get(response.answer_id) if answer is not None: event_info['state']['student_answers'][response.answer_id] = response.unmask_name(answer) # Look for old_state/student_answers/id -- parallel to the above case, happens on reset answer = event_info.get('old_state', {}).get('student_answers', {}).get(response.answer_id) if answer is not None: event_info['old_state']['student_answers'][response.answer_id] = response.unmask_name(answer) # Add 'permutation' to event_info for permuted responses. permutation_option = None if response.has_shuffle(): permutation_option = 'shuffle' elif response.has_answerpool(): permutation_option = 'answerpool' if permutation_option is not None: # Add permutation record tuple: (one of:'shuffle'/'answerpool', [as-displayed list]) if 'permutation' not in event_info: event_info['permutation'] = {} event_info['permutation'][response.answer_id] = (permutation_option, response.unmask_order()) def pretty_print_seconds(self, num_seconds): """ Returns time duration nicely formated, e.g. "3 minutes 4 seconds" """ # Here _ is the N variant ungettext that does pluralization with a 3-arg call ungettext = self.runtime.service(self, "i18n").ungettext hours = num_seconds // 3600 sub_hour = num_seconds % 3600 minutes = sub_hour // 60 seconds = sub_hour % 60 display = "" if hours > 0: display += ungettext("{num_hour} hour", "{num_hour} hours", hours).format(num_hour=hours) if minutes > 0: if display != "": display += " " # translators: "minute" refers to a minute of time display += ungettext("{num_minute} minute", "{num_minute} minutes", minutes).format(num_minute=minutes) # Taking care to make "0 seconds" instead of "" for 0 time if seconds > 0 or (hours == 0 and minutes == 0): if display != "": display += " " # translators: "second" refers to a second of time display += ungettext("{num_second} second", "{num_second} seconds", seconds).format(num_second=seconds) return display def get_submission_metadata_safe(self, answers, correct_map): """ Ensures that no exceptions are thrown while generating input metadata summaries. Returns the summary if it is successfully created, otherwise an empty dictionary. """ try: return self.get_submission_metadata(answers, correct_map) except Exception: # pylint: disable=broad-except # NOTE: The above process requires deep inspection of capa structures that may break for some # uncommon problem types. Ensure that it does not prevent answer submission in those # cases. Any occurrences of errors in this block should be investigated and resolved. log.exception('Unable to gather submission metadata, it will not be included in the event.') return {} def get_submission_metadata(self, answers, correct_map): """ Return a map of inputs to their corresponding summarized metadata. Returns: A map whose keys are a unique identifier for the input (in this case a capa input_id) and whose values are: question (str): Is the prompt that was presented to the student. It corresponds to the label of the input. answer (mixed): Is the answer the student provided. This may be a rich structure, however it must be json serializable. response_type (str): The XML tag of the capa response type. input_type (str): The XML tag of the capa input type. correct (bool): Whether or not the provided answer is correct. Will be an empty string if correctness could not be determined. variant (str): In some cases the same question can have several different variants. This string should uniquely identify the variant of the question that was answered. In the capa context this corresponds to the `seed`. This function attempts to be very conservative and make very few assumptions about the structure of the problem. If problem related metadata cannot be located it should be replaced with empty strings ''. """ input_metadata = {} for input_id, internal_answer in answers.iteritems(): answer_input = self.lcp.inputs.get(input_id) if answer_input is None: log.warning('Input id %s is not mapped to an input type.', input_id) answer_response = None for response, responder in self.lcp.responders.iteritems(): if input_id in responder.answer_ids: answer_response = responder if answer_response is None: log.warning('Answer responder could not be found for input_id %s.', input_id) user_visible_answer = internal_answer if hasattr(answer_input, 'get_user_visible_answer'): user_visible_answer = answer_input.get_user_visible_answer(internal_answer) # If this problem has rerandomize enabled, then it will generate N variants of the # question, one per unique seed value. In this case we would like to know which # variant was selected. Ideally it would be nice to have the exact question that # was presented to the user, with values interpolated etc, but that can be done # later if necessary. variant = '' if self.rerandomize != RANDOMIZATION.NEVER: variant = self.seed is_correct = correct_map.is_correct(input_id) if is_correct is None: is_correct = '' input_metadata[input_id] = { 'question': getattr(answer_input, 'loaded_attributes', {}).get('label', ''), 'answer': user_visible_answer, 'response_type': getattr(getattr(answer_response, 'xml', None), 'tag', ''), 'input_type': getattr(answer_input, 'tag', ''), 'correct': is_correct, 'variant': variant, } return input_metadata def rescore_problem(self): """ Checks whether the existing answers to a problem are correct. This is called when the correct answer to a problem has been changed, and the grade should be re-evaluated. Returns a dict with one key: {'success' : 'correct' | 'incorrect' | AJAX alert msg string } Raises NotFoundError if called on a problem that has not yet been answered, or NotImplementedError if it's a problem that cannot be rescored. Returns the error messages for exceptions occurring while performing the rescoring, rather than throwing them. """ event_info = {'state': self.lcp.get_state(), 'problem_id': self.location.to_deprecated_string()} _ = self.runtime.service(self, "i18n").ugettext if not self.lcp.supports_rescoring(): event_info['failure'] = 'unsupported' self.track_function_unmask('problem_rescore_fail', event_info) # Translators: 'rescoring' refers to the act of re-submitting a student's solution so it can get a new score. raise NotImplementedError(_("Problem's definition does not support rescoring.")) if not self.done: event_info['failure'] = 'unanswered' self.track_function_unmask('problem_rescore_fail', event_info) raise NotFoundError(_("Problem must be answered before it can be graded again.")) # get old score, for comparison: orig_score = self.lcp.get_score() event_info['orig_score'] = orig_score['score'] event_info['orig_total'] = orig_score['total'] try: correct_map = self.lcp.rescore_existing_answers() except (StudentInputError, ResponseError, LoncapaProblemError) as inst: log.warning("Input error in capa_module:problem_rescore", exc_info=True) event_info['failure'] = 'input_error' self.track_function_unmask('problem_rescore_fail', event_info) return {'success': u"Error: {0}".format(inst.message)} except Exception as err: event_info['failure'] = 'unexpected' self.track_function_unmask('problem_rescore_fail', event_info) if self.runtime.DEBUG: msg = u"Error checking problem: {0}".format(err.message) msg += u'\nTraceback:\n' + traceback.format_exc() return {'success': msg} raise # rescoring should have no effect on attempts, so don't # need to increment here, or mark done. Just save. self.set_state_from_lcp() self.publish_grade() new_score = self.lcp.get_score() event_info['new_score'] = new_score['score'] event_info['new_total'] = new_score['total'] # success = correct if ALL questions in this problem are correct success = 'correct' for answer_id in correct_map: if not correct_map.is_correct(answer_id): success = 'incorrect' # NOTE: We are logging both full grading and queued-grading submissions. In the latter, # 'success' will always be incorrect event_info['correct_map'] = correct_map.get_dict() event_info['success'] = success event_info['attempts'] = self.attempts self.track_function_unmask('problem_rescore', event_info) return {'success': success} def save_problem(self, data): """ Save the passed in answers. Returns a dict { 'success' : bool, 'msg' : message } The message is informative on success, and an error message on failure. """ event_info = dict() event_info['state'] = self.lcp.get_state() event_info['problem_id'] = self.location.to_deprecated_string() answers = self.make_dict_of_responses(data) event_info['answers'] = answers _ = self.runtime.service(self, "i18n").ugettext # Too late. Cannot submit if self.closed() and not self.max_attempts == 0: event_info['failure'] = 'closed' self.track_function_unmask('save_problem_fail', event_info) return { 'success': False, # Translators: 'closed' means the problem's due date has passed. You may no longer attempt to solve the problem. 'msg': _("Problem is closed.") } # Problem submitted. Student should reset before saving # again. if self.done and self.rerandomize == RANDOMIZATION.ALWAYS: event_info['failure'] = 'done' self.track_function_unmask('save_problem_fail', event_info) return { 'success': False, 'msg': _("Problem needs to be reset prior to save.") } self.lcp.student_answers = answers self.set_state_from_lcp() self.track_function_unmask('save_problem_success', event_info) msg = _("Your answers have been saved.") if not self.max_attempts == 0: msg = _( "Your answers have been saved but not graded. Click '{button_name}' to grade them." ).format(button_name=self.check_button_name()) return { 'success': True, 'msg': msg, } def reset_problem(self, _data): """ Changes problem state to unfinished -- removes student answers, Causes problem to rerender itself if randomization is enabled. Returns a dictionary of the form: {'success': True/False, 'html': Problem HTML string } If an error occurs, the dictionary will also have an `error` key containing an error message. """ event_info = dict() event_info['old_state'] = self.lcp.get_state() event_info['problem_id'] = self.location.to_deprecated_string() _ = self.runtime.service(self, "i18n").ugettext if self.closed(): event_info['failure'] = 'closed' self.track_function_unmask('reset_problem_fail', event_info) return { 'success': False, # Translators: 'closed' means the problem's due date has passed. You may no longer attempt to solve the problem. 'error': _("Problem is closed."), } if not self.is_submitted(): event_info['failure'] = 'not_done' self.track_function_unmask('reset_problem_fail', event_info) return { 'success': False, # Translators: A student must "make an attempt" to solve the problem on the page before they can reset it. 'error': _("Refresh the page and make an attempt before resetting."), } if self.is_submitted() and self.rerandomize in [RANDOMIZATION.ALWAYS, RANDOMIZATION.ONRESET]: # Reset random number generator seed. self.choose_new_seed() # Generate a new problem with either the previous seed or a new seed self.lcp = self.new_lcp(None) # Pull in the new problem seed self.set_state_from_lcp() event_info['new_state'] = self.lcp.get_state() self.track_function_unmask('reset_problem', event_info) return { 'success': True, 'html': self.get_problem_html(encapsulate=False), }
agpl-3.0
ppribeli/AliPhysics
PWGJE/EMCALJetTasks/Tracks/analysis/model/SpectrumSmearer.py
41
3661
#************************************************************************** #* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. * #* * #* Author: The ALICE Off-line Project. * #* Contributors are mentioned in the code where appropriate. * #* * #* Permission to use, copy, modify and distribute this software and its * #* documentation strictly for non-commercial purposes is hereby granted * #* without fee, provided that the above copyright notice appears in all * #* copies and that both the copyright notice and this permission notice * #* appear in the supporting documentation. The authors make no claims * #* about the suitability of this software for any purpose. It is * #* provided "as is" without express or implied warranty. * #************************************************************************** from copy import deepcopy import random class SpectrumSmearer(object): ''' Simple smearing utility ''' def __init__(self, spectrum): ''' Constructor ''' self.__inputspectrum = spectrum self.__niterations = 1000 self.__smearmodel = None def SetNumberOfIterations(self, niter): """ Set the number of iterations """ self.__niterations = niter def SetSmearModel(self, model): """ Set the model used for the smearing """ self.__smearmodel = model def RunSmearing(self): """ Run smearing of the input spectrum - randomly generate values within the bin, and generate a gaussian response using the smear model for the width - Fill target bin with weight sigma(bin)/ntiterations """ random.seed() smearedspectrum = deepcopy(self.__inputspectrum) # For error propagation smearederror = deepcopy(self.__inputspectrum) for jbin in range(1,smearedspectrum.GetXaxis().GetNbins()+1): smearedspectrum.SetBinContent(jbin, 0) smearedspectrum.SetBinError(jbin, 0) smearederror.SetBinContent(jbin, 0) smearederror.SetBinError(jbin, 0) smearedspectrum.SetName("%sSmeared" %(self.__inputspectrum)) # run actual smearing for ibin in range(1, self.__spectrum.GetXaxis().GetNbins()+1): weight = self.__inputspectrum.GetBinContent(ibin)/self.__niterations weighthigh = (self.__inputspectrum.GetBinContent(ibin)+self.__inputspectrum.GetBinError(ibin))/self.__niterations for itrial in range(0, self.__niterations): binval = random.uniform(self.__inputspectrum.GetXaxis().GetBinLowEdge(ibin), self.__inputspectrum.GetXaxis().GetBinUpEdge(ibin)) # get the response generated = random.gauss(binval, self.__smearmodel.Eval(binval)) binInSpectrum = smearedspectrum.GetXaxis().FindBin(generated) if binInSpectrum < 1 or binInSpectrum >= smearedspectrum.GetXaxis().GetNbins(): continue smearedspectrum.Fill(generated, weight) smearederror.Fill(generated, weighthigh) # Fix errors for ibin in range(1, self.__spectrum.GetXaxis().GetNbins()+1): smearedspectrum.SetBinError(smearederror.GetBinContent(ibin) - smearedspectrum.GetBinContent(ibin)) return smearedspectrum
bsd-3-clause
RedhawkSDR/integration-gnuhawk
qa/gnuradio/gr/gnuradioStubs.py
1
2524
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is 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. # # GNUHAWK 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/. # from ossie.utils import sb GR_CONST_WAVE = 100 GR_SIN_WAVE = 101 GR_COS_WAVE = 102 GR_SQR_WAVE = 103 GR_TRI_WAVE = 104 GR_SAW_WAVE = 105 # Noise types GR_UNIFORM = 200 GR_GAUSSIAN = 201 GR_LAPLACIAN = 202 GR_IMPULSE = 203 class sizeof_char(object): def __init__(self): pass class sizeof_float(object): def __init__(self): pass class sizeof_int(object): def __init__(self): pass class sizeof_gr_complex(object): def __init__(self): pass class sizeof_short(object): def __init__(self): pass class stream_to_vector(object): def __init__(self, sizeof, vlen): pass class vector_to_stream(object): def __init__(self, sizeof, vlen): pass class head: def __init__(self, sizeof, num_items): self.comp = None if str(sizeof.__name__).find("sizeof_char") != -1: self.comp = sb.launch("./components/gr_head_octet/gr_head_octet.spd.xml") elif str(sizeof.__name__).find("sizeof_float") != -1: self.comp = sb.launch("./components/gr_head_float/gr_head_float.spd.xml") elif str(sizeof.__name__).find("sizeof_gr_complex") != -1: self.comp = sb.launch("./components/gr_head_complex/gr_head_complex.spd.xml") elif str(sizeof.__name__).find("sizeof_int") != -1: self.comp = sb.launch("./components/gr_head_int/gr_head_int.spd.xml") elif str(sizeof.__name__).find("sizeof_short") != -1: self.comp = sb.launch("./components/gr_head_short/gr_head_short.spd.xml") if self.comp != None: self.comp.num = num_items def connect(self, dst): if self.comp != None: self.comp.connect(dst)
gpl-3.0
rkerr/trigger
trigger/utils/notifications/events.py
13
4682
# -*- coding: utf-8 -*- """ Event objects for the notification system. These are intended to be used within event handlers such as `~trigger.utils.notifications.handlers.email_handler()`. If not customized within :setting:`NOTIFICATION_HANDLERS`, the default notification type is an `~trigger.utils.notification.events.EmailEvent` that is handled by `~trigger.utils.notifications.handlers.email_handler`. """ __author__ = 'Jathan McCollum' __maintainer__ = 'Jathan McCollum' __email__ = 'jathan.mccollum@teamaol.com' __copyright__ = 'Copyright 2012-2012, AOL Inc.' import socket from trigger.conf import settings # Exports __all__ = ('Event', 'Notification', 'EmailEvent') # Classes class Event(object): """ Base class for events. It just populates the attribute dict with all keyword arguments thrown at the constructor. All ``Event`` objects are expected to have a ``.handle()`` method that willl be called by a handler function. Any user-defined event objects must have a working ``.handle()`` method that returns ``True`` upon success or ``None`` upon a failure when handling the event passed to it. If you specify ``required_args``, these must have a value other than ``None`` when passed to the constructor. """ required_args = () def __init__(self, **kwargs): self.__dict__.update(kwargs) # Brute force wins! local_vars = self.__dict__ for var, value in local_vars.iteritems(): if var in self.required_args and value is None: raise SyntaxError('`%s` is a required argument' % var) def __repr__(self): return '<%s>' % self.__class__.__name__ def handle(self): raise NotImplementedError('Define me in your subclass!') class Notification(Event): """ Base class for notification events. The ``title`` and ``message`` arguments are the only two that are required. This is to simplify the interface when sending notifications and will cause notifications to send from the default ``sender to the default ``recipients`` that are specified withing the global settings. If ``sender`` or ``recipients`` are specified, they will override the global defaults. Note that this base class has no ``.handle()`` method defined. :param title: The title/subject of the notification :param message: The message/body of the notification :param sender: A string representing the sender of the notification (such as an email address or a hostname) :param recipients: An iterable containing strings representing the recipients of of the notification (such as a list of emails or hostnames) :param event_status: Whether this event is a `failure` or a `success` """ required_args = ('title', 'message') status_map = { 'success': settings.SUCCESS_RECIPIENTS, 'failure': settings.FAILURE_RECIPIENTS, } default_sender = settings.NOTIFICATION_SENDER def __init__(self, title=None, message=None, sender=None, recipients=None, event_status='failure', **kwargs): self.title = title self.message = message # If the sender isn't specified, use the global sender if sender is None: sender = self.default_sender self.sender = sender # We want to know whether we're sending a failure or success email if event_status not in self.status_map: raise SyntaxError('`event_status` must be in `status_map`') self.event_status = event_status # If recipients aren't specified, use the global success/failure # recipients if recipients is None: recipients = self.status_map.get(self.event_status) self.recipients = recipients super(Notification, self).__init__(**kwargs) self.kwargs = kwargs class EmailEvent(Notification): """ An email notification event. """ default_sender = settings.EMAIL_SENDER status_map = { 'success': settings.SUCCESS_EMAILS, 'failure': settings.FAILURE_EMAILS, } mailhost = 'localhost' def handle(self): from trigger.utils.notifications import send_email try: # This should return True upon successfully sending email e = self return send_email(addresses=e.recipients, subject=e.title, body=e.message, sender=e.sender, mailhost=e.mailhost) except Exception as err: print 'Got exception', err return None
bsd-3-clause
cataliniordache/Human-Computer-Interaction-Project
RestfulServices/flask/lib/python2.7/site-packages/sqlalchemy/dialects/sybase/pysybase.py
33
3208
# sybase/pysybase.py # Copyright (C) 2010-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: sybase+pysybase :name: Python-Sybase :dbapi: Sybase :connectstring: sybase+pysybase://<username>:<password>@<dsn>/\ [database name] :url: http://python-sybase.sourceforge.net/ Unicode Support --------------- The python-sybase driver does not appear to support non-ASCII strings of any kind at this time. """ from sqlalchemy import types as sqltypes, processors from sqlalchemy.dialects.sybase.base import SybaseDialect, \ SybaseExecutionContext, SybaseSQLCompiler class _SybNumeric(sqltypes.Numeric): def result_processor(self, dialect, type_): if not self.asdecimal: return processors.to_float else: return sqltypes.Numeric.result_processor(self, dialect, type_) class SybaseExecutionContext_pysybase(SybaseExecutionContext): def set_ddl_autocommit(self, dbapi_connection, value): if value: # call commit() on the Sybase connection directly, # to avoid any side effects of calling a Connection # transactional method inside of pre_exec() dbapi_connection.commit() def pre_exec(self): SybaseExecutionContext.pre_exec(self) for param in self.parameters: for key in list(param): param["@" + key] = param[key] del param[key] class SybaseSQLCompiler_pysybase(SybaseSQLCompiler): def bindparam_string(self, name, **kw): return "@" + name class SybaseDialect_pysybase(SybaseDialect): driver = 'pysybase' execution_ctx_cls = SybaseExecutionContext_pysybase statement_compiler = SybaseSQLCompiler_pysybase colspecs = { sqltypes.Numeric: _SybNumeric, sqltypes.Float: sqltypes.Float } @classmethod def dbapi(cls): import Sybase return Sybase def create_connect_args(self, url): opts = url.translate_connect_args(username='user', password='passwd') return ([opts.pop('host')], opts) def do_executemany(self, cursor, statement, parameters, context=None): # calling python-sybase executemany yields: # TypeError: string too long for buffer for param in parameters: cursor.execute(statement, param) def _get_server_version_info(self, connection): vers = connection.scalar("select @@version_number") # i.e. 15500, 15000, 12500 == (15, 5, 0, 0), (15, 0, 0, 0), # (12, 5, 0, 0) return (vers / 1000, vers % 1000 / 100, vers % 100 / 10, vers % 10) def is_disconnect(self, e, connection, cursor): if isinstance(e, (self.dbapi.OperationalError, self.dbapi.ProgrammingError)): msg = str(e) return ('Unable to complete network request to host' in msg or 'Invalid connection state' in msg or 'Invalid cursor state' in msg) else: return False dialect = SybaseDialect_pysybase
apache-2.0
manqala/erpnext
erpnext/accounts/doctype/gl_entry/test_gl_entry.py
59
1071
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, unittest from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry class TestGLEntry(unittest.TestCase): def test_round_off_entry(self): frappe.db.set_value("Company", "_Test Company", "round_off_account", "_Test Write Off - _TC") frappe.db.set_value("Company", "_Test Company", "round_off_cost_center", "_Test Cost Center - _TC") jv = make_journal_entry("_Test Account Cost for Goods Sold - _TC", "_Test Bank - _TC", 100, "_Test Cost Center - _TC", submit=False) jv.get("accounts")[0].debit = 100.01 jv.flags.ignore_validate = True jv.submit() round_off_entry = frappe.db.sql("""select name from `tabGL Entry` where voucher_type='Journal Entry' and voucher_no = %s and account='_Test Write Off - _TC' and cost_center='_Test Cost Center - _TC' and debit = 0 and credit = '.01'""", jv.name) self.assertTrue(round_off_entry)
gpl-3.0
zhukaixy/kbengine
kbe/src/lib/python/Lib/test/test_posixpath.py
68
23737
import itertools import os import posixpath import sys import unittest import warnings from posixpath import realpath, abspath, dirname, basename from test import support, test_genericpath try: import posix except ImportError: posix = None # An absolute path to a temporary filename for testing. We can't rely on TESTFN # being an absolute path, so we need this. ABSTFN = abspath(support.TESTFN) def skip_if_ABSTFN_contains_backslash(test): """ On Windows, posixpath.abspath still returns paths with backslashes instead of posix forward slashes. If this is the case, several tests fail, so skip them. """ found_backslash = '\\' in ABSTFN msg = "ABSTFN is not a posix path - tests fail" return [test, unittest.skip(msg)(test)][found_backslash] def safe_rmdir(dirname): try: os.rmdir(dirname) except OSError: pass class PosixPathTest(unittest.TestCase): def setUp(self): self.tearDown() def tearDown(self): for suffix in ["", "1", "2"]: support.unlink(support.TESTFN + suffix) safe_rmdir(support.TESTFN + suffix) def test_join(self): self.assertEqual(posixpath.join("/foo", "bar", "/bar", "baz"), "/bar/baz") self.assertEqual(posixpath.join("/foo", "bar", "baz"), "/foo/bar/baz") self.assertEqual(posixpath.join("/foo/", "bar/", "baz/"), "/foo/bar/baz/") self.assertEqual(posixpath.join(b"/foo", b"bar", b"/bar", b"baz"), b"/bar/baz") self.assertEqual(posixpath.join(b"/foo", b"bar", b"baz"), b"/foo/bar/baz") self.assertEqual(posixpath.join(b"/foo/", b"bar/", b"baz/"), b"/foo/bar/baz/") def test_join_errors(self): # Check posixpath.join raises friendly TypeErrors. errmsg = "Can't mix strings and bytes in path components" with self.assertRaisesRegex(TypeError, errmsg): posixpath.join(b'bytes', 'str') with self.assertRaisesRegex(TypeError, errmsg): posixpath.join('str', b'bytes') # regression, see #15377 with self.assertRaises(TypeError) as cm: posixpath.join(None, 'str') self.assertNotEqual(cm.exception.args[0], errmsg) def test_split(self): self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar")) self.assertEqual(posixpath.split("/"), ("/", "")) self.assertEqual(posixpath.split("foo"), ("", "foo")) self.assertEqual(posixpath.split("////foo"), ("////", "foo")) self.assertEqual(posixpath.split("//foo//bar"), ("//foo", "bar")) self.assertEqual(posixpath.split(b"/foo/bar"), (b"/foo", b"bar")) self.assertEqual(posixpath.split(b"/"), (b"/", b"")) self.assertEqual(posixpath.split(b"foo"), (b"", b"foo")) self.assertEqual(posixpath.split(b"////foo"), (b"////", b"foo")) self.assertEqual(posixpath.split(b"//foo//bar"), (b"//foo", b"bar")) def splitextTest(self, path, filename, ext): self.assertEqual(posixpath.splitext(path), (filename, ext)) self.assertEqual(posixpath.splitext("/" + path), ("/" + filename, ext)) self.assertEqual(posixpath.splitext("abc/" + path), ("abc/" + filename, ext)) self.assertEqual(posixpath.splitext("abc.def/" + path), ("abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext("/abc.def/" + path), ("/abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext(path + "/"), (filename + ext + "/", "")) path = bytes(path, "ASCII") filename = bytes(filename, "ASCII") ext = bytes(ext, "ASCII") self.assertEqual(posixpath.splitext(path), (filename, ext)) self.assertEqual(posixpath.splitext(b"/" + path), (b"/" + filename, ext)) self.assertEqual(posixpath.splitext(b"abc/" + path), (b"abc/" + filename, ext)) self.assertEqual(posixpath.splitext(b"abc.def/" + path), (b"abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext(b"/abc.def/" + path), (b"/abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext(path + b"/"), (filename + ext + b"/", b"")) def test_splitext(self): self.splitextTest("foo.bar", "foo", ".bar") self.splitextTest("foo.boo.bar", "foo.boo", ".bar") self.splitextTest("foo.boo.biff.bar", "foo.boo.biff", ".bar") self.splitextTest(".csh.rc", ".csh", ".rc") self.splitextTest("nodots", "nodots", "") self.splitextTest(".cshrc", ".cshrc", "") self.splitextTest("...manydots", "...manydots", "") self.splitextTest("...manydots.ext", "...manydots", ".ext") self.splitextTest(".", ".", "") self.splitextTest("..", "..", "") self.splitextTest("........", "........", "") self.splitextTest("", "", "") def test_isabs(self): self.assertIs(posixpath.isabs(""), False) self.assertIs(posixpath.isabs("/"), True) self.assertIs(posixpath.isabs("/foo"), True) self.assertIs(posixpath.isabs("/foo/bar"), True) self.assertIs(posixpath.isabs("foo/bar"), False) self.assertIs(posixpath.isabs(b""), False) self.assertIs(posixpath.isabs(b"/"), True) self.assertIs(posixpath.isabs(b"/foo"), True) self.assertIs(posixpath.isabs(b"/foo/bar"), True) self.assertIs(posixpath.isabs(b"foo/bar"), False) def test_basename(self): self.assertEqual(posixpath.basename("/foo/bar"), "bar") self.assertEqual(posixpath.basename("/"), "") self.assertEqual(posixpath.basename("foo"), "foo") self.assertEqual(posixpath.basename("////foo"), "foo") self.assertEqual(posixpath.basename("//foo//bar"), "bar") self.assertEqual(posixpath.basename(b"/foo/bar"), b"bar") self.assertEqual(posixpath.basename(b"/"), b"") self.assertEqual(posixpath.basename(b"foo"), b"foo") self.assertEqual(posixpath.basename(b"////foo"), b"foo") self.assertEqual(posixpath.basename(b"//foo//bar"), b"bar") def test_dirname(self): self.assertEqual(posixpath.dirname("/foo/bar"), "/foo") self.assertEqual(posixpath.dirname("/"), "/") self.assertEqual(posixpath.dirname("foo"), "") self.assertEqual(posixpath.dirname("////foo"), "////") self.assertEqual(posixpath.dirname("//foo//bar"), "//foo") self.assertEqual(posixpath.dirname(b"/foo/bar"), b"/foo") self.assertEqual(posixpath.dirname(b"/"), b"/") self.assertEqual(posixpath.dirname(b"foo"), b"") self.assertEqual(posixpath.dirname(b"////foo"), b"////") self.assertEqual(posixpath.dirname(b"//foo//bar"), b"//foo") def test_islink(self): self.assertIs(posixpath.islink(support.TESTFN + "1"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), False) f = open(support.TESTFN + "1", "wb") try: f.write(b"foo") f.close() self.assertIs(posixpath.islink(support.TESTFN + "1"), False) if support.can_symlink(): os.symlink(support.TESTFN + "1", support.TESTFN + "2") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) os.remove(support.TESTFN + "1") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) self.assertIs(posixpath.exists(support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), True) finally: if not f.close(): f.close() def test_ismount(self): self.assertIs(posixpath.ismount("/"), True) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertIs(posixpath.ismount(b"/"), True) def test_ismount_non_existent(self): # Non-existent mountpoint. self.assertIs(posixpath.ismount(ABSTFN), False) try: os.mkdir(ABSTFN) self.assertIs(posixpath.ismount(ABSTFN), False) finally: safe_rmdir(ABSTFN) @unittest.skipUnless(support.can_symlink(), "Test requires symlink support") def test_ismount_symlinks(self): # Symlinks are never mountpoints. try: os.symlink("/", ABSTFN) self.assertIs(posixpath.ismount(ABSTFN), False) finally: os.unlink(ABSTFN) @unittest.skipIf(posix is None, "Test requires posix module") def test_ismount_different_device(self): # Simulate the path being on a different device from its parent by # mocking out st_dev. save_lstat = os.lstat def fake_lstat(path): st_ino = 0 st_dev = 0 if path == ABSTFN: st_dev = 1 st_ino = 1 return posix.stat_result((0, st_ino, st_dev, 0, 0, 0, 0, 0, 0, 0)) try: os.lstat = fake_lstat self.assertIs(posixpath.ismount(ABSTFN), True) finally: os.lstat = save_lstat def test_expanduser(self): self.assertEqual(posixpath.expanduser("foo"), "foo") self.assertEqual(posixpath.expanduser(b"foo"), b"foo") try: import pwd except ImportError: pass else: self.assertIsInstance(posixpath.expanduser("~/"), str) self.assertIsInstance(posixpath.expanduser(b"~/"), bytes) # if home directory == root directory, this test makes no sense if posixpath.expanduser("~") != '/': self.assertEqual( posixpath.expanduser("~") + "/", posixpath.expanduser("~/") ) self.assertEqual( posixpath.expanduser(b"~") + b"/", posixpath.expanduser(b"~/") ) self.assertIsInstance(posixpath.expanduser("~root/"), str) self.assertIsInstance(posixpath.expanduser("~foo/"), str) self.assertIsInstance(posixpath.expanduser(b"~root/"), bytes) self.assertIsInstance(posixpath.expanduser(b"~foo/"), bytes) with support.EnvironmentVarGuard() as env: env['HOME'] = '/' self.assertEqual(posixpath.expanduser("~"), "/") self.assertEqual(posixpath.expanduser("~/foo"), "/foo") # expanduser should fall back to using the password database del env['HOME'] home = pwd.getpwuid(os.getuid()).pw_dir # $HOME can end with a trailing /, so strip it (see #17809) self.assertEqual(posixpath.expanduser("~"), home.rstrip("/")) def test_normpath(self): self.assertEqual(posixpath.normpath(""), ".") self.assertEqual(posixpath.normpath("/"), "/") self.assertEqual(posixpath.normpath("//"), "//") self.assertEqual(posixpath.normpath("///"), "/") self.assertEqual(posixpath.normpath("///foo/.//bar//"), "/foo/bar") self.assertEqual(posixpath.normpath("///foo/.//bar//.//..//.//baz"), "/foo/baz") self.assertEqual(posixpath.normpath("///..//./foo/.//bar"), "/foo/bar") self.assertEqual(posixpath.normpath(b""), b".") self.assertEqual(posixpath.normpath(b"/"), b"/") self.assertEqual(posixpath.normpath(b"//"), b"//") self.assertEqual(posixpath.normpath(b"///"), b"/") self.assertEqual(posixpath.normpath(b"///foo/.//bar//"), b"/foo/bar") self.assertEqual(posixpath.normpath(b"///foo/.//bar//.//..//.//baz"), b"/foo/baz") self.assertEqual(posixpath.normpath(b"///..//./foo/.//bar"), b"/foo/bar") @skip_if_ABSTFN_contains_backslash def test_realpath_curdir(self): self.assertEqual(realpath('.'), os.getcwd()) self.assertEqual(realpath('./.'), os.getcwd()) self.assertEqual(realpath('/'.join(['.'] * 100)), os.getcwd()) self.assertEqual(realpath(b'.'), os.getcwdb()) self.assertEqual(realpath(b'./.'), os.getcwdb()) self.assertEqual(realpath(b'/'.join([b'.'] * 100)), os.getcwdb()) @skip_if_ABSTFN_contains_backslash def test_realpath_pardir(self): self.assertEqual(realpath('..'), dirname(os.getcwd())) self.assertEqual(realpath('../..'), dirname(dirname(os.getcwd()))) self.assertEqual(realpath('/'.join(['..'] * 100)), '/') self.assertEqual(realpath(b'..'), dirname(os.getcwdb())) self.assertEqual(realpath(b'../..'), dirname(dirname(os.getcwdb()))) self.assertEqual(realpath(b'/'.join([b'..'] * 100)), b'/') @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_basic(self): # Basic operation. try: os.symlink(ABSTFN+"1", ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN+"1") finally: support.unlink(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_relative(self): try: os.symlink(posixpath.relpath(ABSTFN+"1"), ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN+"1") finally: support.unlink(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_symlink_loops(self): # Bug #930024, return the path unchanged if we get into an infinite # symlink loop. try: old_path = abspath('.') os.symlink(ABSTFN, ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN) os.symlink(ABSTFN+"1", ABSTFN+"2") os.symlink(ABSTFN+"2", ABSTFN+"1") self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1") self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2") self.assertEqual(realpath(ABSTFN+"1/x"), ABSTFN+"1/x") self.assertEqual(realpath(ABSTFN+"1/.."), dirname(ABSTFN)) self.assertEqual(realpath(ABSTFN+"1/../x"), dirname(ABSTFN) + "/x") os.symlink(ABSTFN+"x", ABSTFN+"y") self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "y"), ABSTFN + "y") self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "1"), ABSTFN + "1") os.symlink(basename(ABSTFN) + "a/b", ABSTFN+"a") self.assertEqual(realpath(ABSTFN+"a"), ABSTFN+"a/b") os.symlink("../" + basename(dirname(ABSTFN)) + "/" + basename(ABSTFN) + "c", ABSTFN+"c") self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c") # Test using relative path as well. os.chdir(dirname(ABSTFN)) self.assertEqual(realpath(basename(ABSTFN)), ABSTFN) finally: os.chdir(old_path) support.unlink(ABSTFN) support.unlink(ABSTFN+"1") support.unlink(ABSTFN+"2") support.unlink(ABSTFN+"y") support.unlink(ABSTFN+"c") support.unlink(ABSTFN+"a") @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_repeated_indirect_symlinks(self): # Issue #6975. try: os.mkdir(ABSTFN) os.symlink('../' + basename(ABSTFN), ABSTFN + '/self') os.symlink('self/self/self', ABSTFN + '/link') self.assertEqual(realpath(ABSTFN + '/link'), ABSTFN) finally: support.unlink(ABSTFN + '/self') support.unlink(ABSTFN + '/link') safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_deep_recursion(self): depth = 10 old_path = abspath('.') try: os.mkdir(ABSTFN) for i in range(depth): os.symlink('/'.join(['%d' % i] * 10), ABSTFN + '/%d' % (i + 1)) os.symlink('.', ABSTFN + '/0') self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN) # Test using relative path as well. os.chdir(ABSTFN) self.assertEqual(realpath('%d' % depth), ABSTFN) finally: os.chdir(old_path) for i in range(depth + 1): support.unlink(ABSTFN + '/%d' % i) safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_resolve_parents(self): # We also need to resolve any symlinks in the parents of a relative # path passed to realpath. E.g.: current working directory is # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call # realpath("a"). This should return /usr/share/doc/a/. try: old_path = abspath('.') os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/y") os.symlink(ABSTFN + "/y", ABSTFN + "/k") os.chdir(ABSTFN + "/k") self.assertEqual(realpath("a"), ABSTFN + "/y/a") finally: os.chdir(old_path) support.unlink(ABSTFN + "/k") safe_rmdir(ABSTFN + "/y") safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_resolve_before_normalizing(self): # Bug #990669: Symbolic links should be resolved before we # normalize the path. E.g.: if we have directories 'a', 'k' and 'y' # in the following hierarchy: # a/k/y # # and a symbolic link 'link-y' pointing to 'y' in directory 'a', # then realpath("link-y/..") should return 'k', not 'a'. try: old_path = abspath('.') os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k/y") os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y") # Absolute path. self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k") # Relative path. os.chdir(dirname(ABSTFN)) self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k") finally: os.chdir(old_path) support.unlink(ABSTFN + "/link-y") safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_resolve_first(self): # Bug #1213894: The first component of the path, if not absolute, # must be resolved too. try: old_path = abspath('.') os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.symlink(ABSTFN, ABSTFN + "link") os.chdir(dirname(ABSTFN)) base = basename(ABSTFN) self.assertEqual(realpath(base + "link"), ABSTFN) self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k") finally: os.chdir(old_path) support.unlink(ABSTFN + "link") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN) def test_relpath(self): (real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar") try: curdir = os.path.split(os.getcwd())[-1] self.assertRaises(ValueError, posixpath.relpath, "") self.assertEqual(posixpath.relpath("a"), "a") self.assertEqual(posixpath.relpath(posixpath.abspath("a")), "a") self.assertEqual(posixpath.relpath("a/b"), "a/b") self.assertEqual(posixpath.relpath("../a/b"), "../a/b") self.assertEqual(posixpath.relpath("a", "../b"), "../"+curdir+"/a") self.assertEqual(posixpath.relpath("a/b", "../c"), "../"+curdir+"/a/b") self.assertEqual(posixpath.relpath("a", "b/c"), "../../a") self.assertEqual(posixpath.relpath("a", "a"), ".") self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x/y/z"), '../../../foo/bar/bat') self.assertEqual(posixpath.relpath("/foo/bar/bat", "/foo/bar"), 'bat') self.assertEqual(posixpath.relpath("/foo/bar/bat", "/"), 'foo/bar/bat') self.assertEqual(posixpath.relpath("/", "/foo/bar/bat"), '../../..') self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x"), '../foo/bar/bat') self.assertEqual(posixpath.relpath("/x", "/foo/bar/bat"), '../../../x') self.assertEqual(posixpath.relpath("/", "/"), '.') self.assertEqual(posixpath.relpath("/a", "/a"), '.') self.assertEqual(posixpath.relpath("/a/b", "/a/b"), '.') finally: os.getcwd = real_getcwd def test_relpath_bytes(self): (real_getcwdb, os.getcwdb) = (os.getcwdb, lambda: br"/home/user/bar") try: curdir = os.path.split(os.getcwdb())[-1] self.assertRaises(ValueError, posixpath.relpath, b"") self.assertEqual(posixpath.relpath(b"a"), b"a") self.assertEqual(posixpath.relpath(posixpath.abspath(b"a")), b"a") self.assertEqual(posixpath.relpath(b"a/b"), b"a/b") self.assertEqual(posixpath.relpath(b"../a/b"), b"../a/b") self.assertEqual(posixpath.relpath(b"a", b"../b"), b"../"+curdir+b"/a") self.assertEqual(posixpath.relpath(b"a/b", b"../c"), b"../"+curdir+b"/a/b") self.assertEqual(posixpath.relpath(b"a", b"b/c"), b"../../a") self.assertEqual(posixpath.relpath(b"a", b"a"), b".") self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x/y/z"), b'../../../foo/bar/bat') self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/foo/bar"), b'bat') self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/"), b'foo/bar/bat') self.assertEqual(posixpath.relpath(b"/", b"/foo/bar/bat"), b'../../..') self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x"), b'../foo/bar/bat') self.assertEqual(posixpath.relpath(b"/x", b"/foo/bar/bat"), b'../../../x') self.assertEqual(posixpath.relpath(b"/", b"/"), b'.') self.assertEqual(posixpath.relpath(b"/a", b"/a"), b'.') self.assertEqual(posixpath.relpath(b"/a/b", b"/a/b"), b'.') self.assertRaises(TypeError, posixpath.relpath, b"bytes", "str") self.assertRaises(TypeError, posixpath.relpath, "str", b"bytes") finally: os.getcwdb = real_getcwdb class PosixCommonTest(test_genericpath.CommonTest, unittest.TestCase): pathmodule = posixpath attributes = ['relpath', 'samefile', 'sameopenfile', 'samestat'] if __name__=="__main__": unittest.main()
lgpl-3.0
PW-Sat2/PWSat2OBC
integration_tests/emulator/comm_zmq_adapter.py
1
5457
from Queue import Empty from threading import Thread from time import sleep import numpy as np import logging import zmq import devices from utils import ensure_string class ZeroMQAdapter(object): def __init__(self, comm, grc_uplink_address="tcp://localhost:7002", grc_downlink_address="tcp://localhost:7003", uplink_per=0, downlink_per=0): self._comm = comm # type: devices.Comm self._comm.transmitter.on_send_frame = self._on_downlink_frame self._context = zmq.Context.instance() self._socket_uplink = self._context.socket(zmq.SUB) self._socket_uplink_gnuradio = self._context.socket(zmq.SUB) self._downlink_new_msg = self._context.socket(zmq.PUSH) self._downlink_delay_msg = self._context.socket(zmq.PULL) self._downlink_pub = self._context.socket(zmq.PUB) self._downlink_gnuradio_pub = self._context.socket(zmq.PUB) self._socket_uplink.bind("tcp://*:%s" % 7000) self._socket_uplink_gnuradio.connect(grc_uplink_address) self._downlink_new_msg.bind("inproc://downlink/new_msg") self._downlink_delay_msg.connect("inproc://downlink/new_msg") self._downlink_pub.bind("tcp://*:%s" % 7001) self._downlink_gnuradio_pub.connect(grc_downlink_address) self._socket_uplink.setsockopt(zmq.SUBSCRIBE, '') self._socket_uplink_gnuradio.setsockopt(zmq.SUBSCRIBE, '') self._uplink_listener = Thread(target=self._uplink_worker) self._uplink_listener.daemon = True self._uplink_listener.start() self._uplink_gnuradio_listener = Thread(target=self._uplink_gnuradio_worker) self._uplink_gnuradio_listener.daemon = True self._uplink_gnuradio_listener.start() self._downlink_handler = Thread(target=self._downlink_worker) self._downlink_handler.daemon = True self._downlink_handler.start() self._uplink_per = uplink_per self._downlink_per = downlink_per @staticmethod def _encode_callsign(call): return ''.join([chr(ord(i) << 1) for i in call]) @staticmethod def _build_kiss_header(): return ''.join([ ZeroMQAdapter._encode_callsign('PWSAT2'), chr(96), ZeroMQAdapter._encode_callsign('PWSAT2'), chr(97), chr(3), chr(0xF0) ]) @staticmethod def _build_kiss(text): return ''.join([ ZeroMQAdapter._build_kiss_header(), text, '\x00\x00' ]) @staticmethod def _build_gnuradio_frame(text): return ''.join([ ZeroMQAdapter._build_kiss_header(), text ]) def _on_downlink_frame(self, comm, frame): self._downlink_new_msg.send(ensure_string(frame)) def _delay_uplink_frame(self, frame): message_sending_time = 8.0 * len(frame) / 1200.0 sleep(message_sending_time) def _delay_downlink_frame(self, frame): message_sending_time = 8.0 * len(frame) / float(str(self._comm.transmitter.baud_rate)) sleep(message_sending_time) def _uplink_worker(self): while True: frame = self._socket_uplink.recv() just_content = frame[16:] self._delay_uplink_frame(just_content) self._comm.receiver.put_frame(just_content) def _uplink_gnuradio_worker(self): log = logging.getLogger("GNURADIO UPLINK") count_all_frames = 0.0 count_rejected = 0.0 while True: frame = self._socket_uplink_gnuradio.recv() just_content = frame[16:] count_all_frames+=1 if self._uplink_per == 0 or np.random.choice(['reject', 'accept'], 1, p=[self._uplink_per, 1 - self._uplink_per])[0] == 'accept': log.debug("Uplink frame accepted") self._comm.receiver.put_frame(just_content) else: log.info("Uplink frame dropped because of PER setting") count_rejected+=1 if self._uplink_per != 0: log.debug("Current uplink PER = {0}".format(count_rejected/count_all_frames)) def _downlink_worker(self): log = logging.getLogger("GNURADIO DOWNLINK") count_all_frames = 0.0 count_rejected = 0.0 while True: frame = self._downlink_delay_msg.recv() count_all_frames+=1 if self._downlink_per == 0 or np.random.choice(['reject', 'accept'], 1, p=[self._downlink_per, 1 - self._downlink_per])[0] == 'accept': log.debug("Downlink frame accepted") gnuradio_frame = ZeroMQAdapter._build_gnuradio_frame(frame) self._downlink_gnuradio_pub.send(gnuradio_frame) kiss_frame = ZeroMQAdapter._build_kiss(frame) self._downlink_pub.send(kiss_frame) try: self._comm.transmitter.get_message_from_buffer(0) except Empty: pass else: log.info("Downlink frame dropped because of PER setting") count_rejected+=1 if self._downlink_per != 0: log.debug("Current downlink PER = {0}".format(count_rejected/count_all_frames))
agpl-3.0
zlz3907/TextLineProcessor
WordXmlParse.py
1
2778
#! /usr/bin/python # -*- coding: utf-8 -*- import re; import sys; import os; textre = re.compile("\!\[CDATA\[(.*?)\]\]", re.DOTALL); def get_text(xml): match = re.search(textre, xml); if not match: return xml; return match.group(1); def get_elements(xml, elem): p = re.compile("<" + elem + ">" + "(.*?)</" + elem + ">", re.DOTALL); it = p.finditer(xml); result = []; for m in it: result.append(m.group(1)); return result; def get_elements_by_path(xml, elem): if type(xml) == type(''): xml = [xml]; if type(elem) == type(''): elem = elem.split('/'); if (len(xml) == 0): return []; elif (len(elem) == 0): return xml; elif (len(elem) == 1): result = []; for item in xml: result += get_elements(item, elem[0]); return result; else: subitems = []; for item in xml: subitems += get_elements(item, elem[0]); return get_elements_by_path(subitems, elem[1:]); def write_xml_tocache(xml, path): afile = open(path, 'w'); afile.write(xml); afile.close(); str_list = []; def process(path): xmlfile = open(path); xml = xmlfile.read(); original_query = get_elements(xml, "query"); queryword = get_text(original_query[0]); custom_translations = get_elements(xml, "basic"); translated = False; el_phonetic = get_elements(xml, "phonetic"); phonetic_symbol = " "; if not len(el_phonetic) <= 0: phonetic_symbol = " [" + get_text(get_elements(xml, "phonetic")[0]) + "] "; paragraph_symbol = get_text(get_elements(xml, "paragraph")[0]); str_arow = "<item><word><![CDATA[" + queryword + "]]></word><trans><![CDATA[" + paragraph_symbol + " "; arow_trans = ""; for cus in custom_translations: source = "youdao:"; #get_elements_by_path(cus, "basic/explains"); contents = get_elements_by_path(cus, "explains/ex"); str_trans = []; for content in contents[0:5]: str_trans.append(get_text(content)); translated = True; arow_trans = " ".join(str_trans); arow = str_arow + arow_trans + "]]></trans><phonetic><![CDATA[" + phonetic_symbol + "]]></phonetic><tags></tags><progress>0</progress></item>\n"; str_list.append(arow); print queryword + "\t" + phonetic_symbol + "\t" + arow_trans; xmlfile.close(); def main(argv): if len(argv) <= 1: sys.exit(1); word_folder = argv[0]; print word_folder; if os.path.exists(word_folder): for f in os.listdir(word_folder): process(os.path.join(word_folder, f)); write_xml_tocache("<wordbook>\n" + "".join(str_list) + "\n</wordbook>\n", argv[1]); if __name__ == "__main__": main(sys.argv[1:]);
gpl-2.0
molmod/zeobuilder
zeobuilder/conversion.py
1
3834
# -*- coding: utf-8 -*- # Zeobuilder is an extensible GUI-toolkit for molecular model construction. # Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center # for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights # reserved unless otherwise stated. # # This file is part of Zeobuilder. # # Zeobuilder 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. # # In addition to the regulations of the GNU General Public License, # publications and communications based in parts on this program or on # parts of this program are required to cite the following article: # # "ZEOBUILDER: a GUI toolkit for the construction of complex molecules on the # nanoscale with building blocks", Toon Verstraelen, Veronique Van Speybroeck # and Michel Waroquier, Journal of Chemical Information and Modeling, Vol. 48 # (7), 1530-1541, 2008 # DOI:10.1021/ci8000748 # # Zeobuilder 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/> # #-- from zeobuilder import context import molmod.units __all__ = [ "measures", "unit", "units_by_measure", "to_unit", "from_unit", "eval_measure", "express_measure", "express_data_size" ] measures = ["Length", "Energy", "Mass", "Charge", "Angle", "Time"] units = { "au": 1, "A": molmod.units.angstrom, "nm": molmod.units.nanometer, "kJ/mol": molmod.units.kjmol, "kcal/mol": molmod.units.kcalmol, "eV": molmod.units.electronvolt, "amu": molmod.units.unified, "rad": 1, "deg": molmod.units.deg, "ns": molmod.units.nanosecond, "ps": molmod.units.picosecond, "fs": molmod.units.femtosecond, } units_by_measure = { "Length": ["A", "au", "nm"], "Energy": ["kJ/mol", "au", "kcal/mol", "eV"], "Mass": ["amu", "au"], "Charge": ["au"], "Angle": ["deg", "rad"], "Time": ["ps", "au", "ns", "fs"], } from_unit = dict((unit, eval("lambda x: x*%s" % value)) for unit, value in units.iteritems()) to_unit = dict((unit, eval("lambda x: x/%s" % value)) for unit, value in units.iteritems()) # some sanity checks assert len(measures) == len(set(measures)), "Some measures have the same name." assert len(measures) == len(units_by_measure), "Some measures don't have units." assert len(units) == len(set(sum((u for u in units_by_measure.itervalues()), []))) # * evaluation routines (from string to value) def eval_measure(s, measure): s = s.lower().strip() suffix = None for unit_name in units_by_measure[measure]: if s.endswith(unit_name.lower()): s = s[:-len(unit_name)] suffix = unit_name break if suffix is None: suffix = context.application.configuration.default_units[measure] return from_unit[suffix](float(s)) # * expression routines (from value to string) def express_measure(val, measure, decimals=3, scientific=False, unit_name=None): if unit_name is None: unit_name = context.application.configuration.default_units[measure] printf_character = {True: "E", False: "F"}[scientific] return ("%.*" + printf_character + " %s") % (decimals, to_unit[unit_name](val), unit_name) def express_data_size(val): if val < 1024: return str(val) + " b" elif val < 1024 * 1024: return str(val/1024) + " Kb" else:# val < 1024 * 1024 * 1024: return str(val/(1024*1024)) + " Mb"
gpl-3.0
kkh029/Alchemy
Alchemy/cocos2d/tools/particle/convert_YCoordFlipped.py
89
2224
#!/usr/bin/python #ConvertYCoordFlipped.py import plistlib import os.path import argparse import glob import shutil #keys in dictionary metaDataKey = 'metaData' yCoordFlippedConvertedKey = 'yCoordFlippedConverted' yCoordFlippedKey = 'yCoordFlipped' #check if the particle file has been converted def checkFlippedConvertFlag(plistDict): if(not plistDict.has_key(metaDataKey)): return False else: metaDict = plistDict.get(metaDataKey) if(not metaDict.has_key(yCoordFlippedConvertedKey)): return False else: return metaDict.get(yCoordFlippedConvertedKey) is 1 #write flag to indicate to file has been converted def writeFlippedConvertFlag(plistDict): metaDict = dict() metaDict.update(yCoordFlippedConverted = 1) plistDict.update(metaData = metaDict) #process file def processConvertFile(filename): #print a line to separate files print ('') if(not os.path.isfile(filename)): print(filename + ' dose not exist!') return print('Begin process particle file: ' + filename) fp = open(filename, 'r') pl = plistlib.readPlist(fp) if (not pl.has_key(yCoordFlippedKey)): print('Skip plist file: ' + filename + ' for there is no key for yCoordFlipped,') else: if(not checkFlippedConvertFlag(pl)): backupFileName = filename+'.backup' print('Write backup file to ' + backupFileName) shutil.copyfile(filename,backupFileName) print('converting...') pl[yCoordFlippedKey] = -pl[yCoordFlippedKey] writeFlippedConvertFlag(pl) print('converted...') print('Write new plist file to ' + filename) plistlib.writePlist(pl,filename) else: print('Skip a converted file ' + filename) # -------------- entrance -------------- if __name__ == '__main__': argparser = argparse.ArgumentParser() argparser.add_argument("file", nargs = "+",help = "specify a file or a patten") #argparser.add_argument("-r", "--recursive",action = "store_true", help = "recursive folder or not") args = argparser.parse_args() for file in args.file: processConvertFile(file)
apache-2.0
ax333l/QuoteBook
QuoteBook/sqv.py
1
3777
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'sqw.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Quote(object): def setupUi(self, Quote): Quote.setObjectName("Quote") Quote.resize(271, 66) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Quote.sizePolicy().hasHeightForWidth()) Quote.setSizePolicy(sizePolicy) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Quote.setWindowIcon(icon) Quote.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates)) self.verticalLayout = QtWidgets.QVBoxLayout(Quote) self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize) self.verticalLayout.setObjectName("verticalLayout") self.lQuote = QtWidgets.QLabel(Quote) self.lQuote.setText("") self.lQuote.setObjectName("lQuote") self.verticalLayout.addWidget(self.lQuote) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize) self.horizontalLayout.setObjectName("horizontalLayout") self.lCharacter = QtWidgets.QLabel(Quote) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lCharacter.sizePolicy().hasHeightForWidth()) self.lCharacter.setSizePolicy(sizePolicy) self.lCharacter.setText("") self.lCharacter.setObjectName("lCharacter") self.horizontalLayout.addWidget(self.lCharacter) self.lTitle = QtWidgets.QLabel(Quote) self.lTitle.setText("") self.lTitle.setObjectName("lTitle") self.horizontalLayout.addWidget(self.lTitle) self.lAuthor = QtWidgets.QLabel(Quote) self.lAuthor.setText("") self.lAuthor.setObjectName("lAuthor") self.horizontalLayout.addWidget(self.lAuthor) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.btnCopy = QtWidgets.QPushButton(Quote) self.btnCopy.setObjectName("btnCopy") self.horizontalLayout.addWidget(self.btnCopy) self.btnSQEdit = QtWidgets.QPushButton(Quote) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSQEdit.sizePolicy().hasHeightForWidth()) self.btnSQEdit.setSizePolicy(sizePolicy) self.btnSQEdit.setObjectName("btnSQEdit") self.horizontalLayout.addWidget(self.btnSQEdit) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(Quote) QtCore.QMetaObject.connectSlotsByName(Quote) def retranslateUi(self, Quote): _translate = QtCore.QCoreApplication.translate Quote.setWindowTitle(_translate("Quote", "Quote")) self.btnCopy.setText(_translate("Quote", "Copy")) self.btnSQEdit.setText(_translate("Quote", "Edit")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Quote = QtWidgets.QDialog() ui = Ui_Quote() ui.setupUi(Quote) Quote.show() sys.exit(app.exec_())
gpl-3.0
wndias/bc.repository
script.module.urlresolver/lib/urlresolver/plugins/videohut.py
4
2399
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 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 re import urllib from urlresolver import common from urlresolver.resolver import UrlResolver, ResolverError class VideoHutResolver(UrlResolver): name = "videohut.to" domains = ["videohut.to"] pattern = '(?://|\.)(videohut\.to)/(?:v\/|embed.php\?id=)([0-9a-z]+)' def __init__(self): self.net = common.Net() def get_media_url(self, host, media_id): web_url = self.get_url(host, media_id) html = self.net.http_GET(web_url).content key = re.compile('key\s*:\s*[\'"](.+?)[\'"]').findall(html) if key: key = urllib.quote_plus(key[0]).replace('.', '%2E').replace('-', '%2D') filekey = re.compile('file\s*:\s*[\'"](.+?)[\'"]').findall(html) if filekey: filekey = urllib.quote_plus(filekey[0]).replace('.', '%2E').replace('-', '%2D') for _i in range(0, 3): try: player_url = 'http://www.videohut.to/api/player.api.php?key=%s&file=%s' % (key, filekey) html = self.net.http_GET(player_url).content stream_url = re.search('url=(.+?)&', html).group(1) stream_url = urllib.unquote(stream_url) return stream_url except: pass raise ResolverError('File Not Found or removed') def get_url(self, host, media_id): return 'http://www.videohut.to/embed.php?id=%s' % media_id def get_host_and_id(self, url): r = re.search(self.pattern, url) if r: return r.groups() else: return False def valid_url(self, url, host): return re.search(self.pattern, url) or self.name in host
gpl-2.0
hogarthj/ansible
lib/ansible/module_utils/urls.py
2
42462
# 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. # # Copyright (c), Michael DeHaan <michael.dehaan@gmail.com>, 2012-2013 # Copyright (c), Toshio Kuratomi <tkuratomi@ansible.com>, 2015 # # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) # # The match_hostname function and supporting code is under the terms and # conditions of the Python Software Foundation License. They were taken from # the Python3 standard library and adapted for use in Python2. See comments in the # source for which code precisely is under this License. # # PSF License (see licenses/PSF-license.txt or https://opensource.org/licenses/Python-2.0) ''' The **urls** utils module offers a replacement for the urllib2 python library. urllib2 is the python stdlib way to retrieve files from the Internet but it lacks some security features (around verifying SSL certificates) that users should care about in most situations. Using the functions in this module corrects deficiencies in the urllib2 module wherever possible. There are also third-party libraries (for instance, requests) which can be used to replace urllib2 with a more secure library. However, all third party libraries require that the library be installed on the managed machine. That is an extra step for users making use of a module. If possible, avoid third party libraries by using this code instead. ''' import base64 import netrc import os import platform import re import socket import sys import tempfile import traceback try: import httplib except ImportError: # Python 3 import http.client as httplib import ansible.module_utils.six.moves.http_cookiejar as cookiejar import ansible.module_utils.six.moves.urllib.request as urllib_request import ansible.module_utils.six.moves.urllib.error as urllib_error from ansible.module_utils.basic import get_distribution from ansible.module_utils._text import to_bytes, to_native, to_text try: # python3 import urllib.request as urllib_request from urllib.request import AbstractHTTPHandler except ImportError: # python2 import urllib2 as urllib_request from urllib2 import AbstractHTTPHandler try: from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse HAS_URLPARSE = True except: HAS_URLPARSE = False try: import ssl HAS_SSL = True except: HAS_SSL = False try: # SNI Handling needs python2.7.9's SSLContext from ssl import create_default_context, SSLContext HAS_SSLCONTEXT = True except ImportError: HAS_SSLCONTEXT = False # SNI Handling for python < 2.7.9 with urllib3 support try: # urllib3>=1.15 HAS_URLLIB3_SSL_WRAP_SOCKET = False try: from urllib3.contrib.pyopenssl import PyOpenSSLContext except ImportError: from requests.packages.urllib3.contrib.pyopenssl import PyOpenSSLContext HAS_URLLIB3_PYOPENSSLCONTEXT = True except ImportError: # urllib3<1.15,>=1.6 HAS_URLLIB3_PYOPENSSLCONTEXT = False try: try: from urllib3.contrib.pyopenssl import ssl_wrap_socket except ImportError: from requests.packages.urllib3.contrib.pyopenssl import ssl_wrap_socket HAS_URLLIB3_SSL_WRAP_SOCKET = True except ImportError: pass # Select a protocol that includes all secure tls protocols # Exclude insecure ssl protocols if possible if HAS_SSL: # If we can't find extra tls methods, ssl.PROTOCOL_TLSv1 is sufficient PROTOCOL = ssl.PROTOCOL_TLSv1 if not HAS_SSLCONTEXT and HAS_SSL: try: import ctypes import ctypes.util except ImportError: # python 2.4 (likely rhel5 which doesn't have tls1.1 support in its openssl) pass else: libssl_name = ctypes.util.find_library('ssl') libssl = ctypes.CDLL(libssl_name) for method in ('TLSv1_1_method', 'TLSv1_2_method'): try: libssl[method] # Found something - we'll let openssl autonegotiate and hope # the server has disabled sslv2 and 3. best we can do. PROTOCOL = ssl.PROTOCOL_SSLv23 break except AttributeError: pass del libssl LOADED_VERIFY_LOCATIONS = set() HAS_MATCH_HOSTNAME = True try: from ssl import match_hostname, CertificateError except ImportError: try: from backports.ssl_match_hostname import match_hostname, CertificateError except ImportError: HAS_MATCH_HOSTNAME = False if not HAS_MATCH_HOSTNAME: # The following block of code is under the terms and conditions of the # Python Software Foundation License """The match_hostname() function from Python 3.4, essential when using SSL.""" class CertificateError(ValueError): pass def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False # Ported from python3-syntax: # leftmost, *remainder = dn.split(r'.') parts = dn.split(r'.') leftmost = parts[0] remainder = parts[1:] wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn)) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') elif leftmost.startswith('xn--') or hostname.startswith('xn--'): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) return pat.match(hostname) def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_match(value, hostname): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise CertificateError("hostname %r doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError("no appropriate commonName or subjectAltName fields were found") # End of Python Software Foundation Licensed code HAS_MATCH_HOSTNAME = True # This is a dummy cacert provided for Mac OS since you need at least 1 # ca cert, regardless of validity, for Python on Mac OS to use the # keychain functionality in OpenSSL for validating SSL certificates. # See: http://mercurial.selenic.com/wiki/CACertificates#Mac_OS_X_10.6_and_higher b_DUMMY_CA_CERT = b"""-----BEGIN CERTIFICATE----- MIICvDCCAiWgAwIBAgIJAO8E12S7/qEpMA0GCSqGSIb3DQEBBQUAMEkxCzAJBgNV BAYTAlVTMRcwFQYDVQQIEw5Ob3J0aCBDYXJvbGluYTEPMA0GA1UEBxMGRHVyaGFt MRAwDgYDVQQKEwdBbnNpYmxlMB4XDTE0MDMxODIyMDAyMloXDTI0MDMxNTIyMDAy MlowSTELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYD VQQHEwZEdXJoYW0xEDAOBgNVBAoTB0Fuc2libGUwgZ8wDQYJKoZIhvcNAQEBBQAD gY0AMIGJAoGBANtvpPq3IlNlRbCHhZAcP6WCzhc5RbsDqyh1zrkmLi0GwcQ3z/r9 gaWfQBYhHpobK2Tiq11TfraHeNB3/VfNImjZcGpN8Fl3MWwu7LfVkJy3gNNnxkA1 4Go0/LmIvRFHhbzgfuo9NFgjPmmab9eqXJceqZIlz2C8xA7EeG7ku0+vAgMBAAGj gaswgagwHQYDVR0OBBYEFPnN1nPRqNDXGlCqCvdZchRNi/FaMHkGA1UdIwRyMHCA FPnN1nPRqNDXGlCqCvdZchRNi/FaoU2kSzBJMQswCQYDVQQGEwJVUzEXMBUGA1UE CBMOTm9ydGggQ2Fyb2xpbmExDzANBgNVBAcTBkR1cmhhbTEQMA4GA1UEChMHQW5z aWJsZYIJAO8E12S7/qEpMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEA MUB80IR6knq9K/tY+hvPsZer6eFMzO3JGkRFBh2kn6JdMDnhYGX7AXVHGflrwNQH qFy+aenWXsC0ZvrikFxbQnX8GVtDADtVznxOi7XzFw7JOxdsVrpXgSN0eh0aMzvV zKPZsZ2miVGclicJHzm5q080b1p/sZtuKIEZk6vZqEg= -----END CERTIFICATE----- """ # # Exceptions # class ConnectionError(Exception): """Failed to connect to the server""" pass class ProxyError(ConnectionError): """Failure to connect because of a proxy""" pass class SSLValidationError(ConnectionError): """Failure to connect due to SSL validation failing""" pass class NoSSLError(SSLValidationError): """Needed to connect to an HTTPS url but no ssl library available to verify the certificate""" pass # Some environments (Google Compute Engine's CoreOS deploys) do not compile # against openssl and thus do not have any HTTPS support. CustomHTTPSConnection = CustomHTTPSHandler = None if hasattr(httplib, 'HTTPSConnection') and hasattr(urllib_request, 'HTTPSHandler'): class CustomHTTPSConnection(httplib.HTTPSConnection): def __init__(self, *args, **kwargs): httplib.HTTPSConnection.__init__(self, *args, **kwargs) self.context = None if HAS_SSLCONTEXT: self.context = create_default_context() elif HAS_URLLIB3_PYOPENSSLCONTEXT: self.context = PyOpenSSLContext(PROTOCOL) if self.context and self.cert_file: self.context.load_cert_chain(self.cert_file, self.key_file) def connect(self): "Connect to a host on a given (SSL) port." if hasattr(self, 'source_address'): sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) else: sock = socket.create_connection((self.host, self.port), self.timeout) server_hostname = self.host # Note: self._tunnel_host is not available on py < 2.6 but this code # isn't used on py < 2.6 (lack of create_connection) if self._tunnel_host: self.sock = sock self._tunnel() server_hostname = self._tunnel_host if HAS_SSLCONTEXT or HAS_URLLIB3_PYOPENSSLCONTEXT: self.sock = self.context.wrap_socket(sock, server_hostname=server_hostname) elif HAS_URLLIB3_SSL_WRAP_SOCKET: self.sock = ssl_wrap_socket(sock, keyfile=self.key_file, cert_reqs=ssl.CERT_NONE, certfile=self.cert_file, ssl_version=PROTOCOL, server_hostname=server_hostname) else: self.sock = ssl.wrap_socket(sock, keyfile=self.key_file, certfile=self.cert_file, ssl_version=PROTOCOL) class CustomHTTPSHandler(urllib_request.HTTPSHandler): def https_open(self, req): return self.do_open(CustomHTTPSConnection, req) https_request = AbstractHTTPHandler.do_request_ class HTTPSClientAuthHandler(urllib_request.HTTPSHandler): '''Handles client authentication via cert/key This is a fairly lightweight extension on HTTPSHandler, and can be used in place of HTTPSHandler ''' def __init__(self, client_cert=None, client_key=None, **kwargs): urllib_request.HTTPSHandler.__init__(self, **kwargs) self.client_cert = client_cert self.client_key = client_key def https_open(self, req): return self.do_open(self._build_https_connection, req) def _build_https_connection(self, host, **kwargs): kwargs.update({ 'cert_file': self.client_cert, 'key_file': self.client_key, }) try: kwargs['context'] = self._context except AttributeError: pass return httplib.HTTPSConnection(host, **kwargs) class ParseResultDottedDict(dict): ''' A dict that acts similarly to the ParseResult named tuple from urllib ''' def __init__(self, *args, **kwargs): super(ParseResultDottedDict, self).__init__(*args, **kwargs) self.__dict__ = self def as_list(self): ''' Generate a list from this dict, that looks like the ParseResult named tuple ''' return [self.get(k, None) for k in ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')] def generic_urlparse(parts): ''' Returns a dictionary of url parts as parsed by urlparse, but accounts for the fact that older versions of that library do not support named attributes (ie. .netloc) ''' generic_parts = ParseResultDottedDict() if hasattr(parts, 'netloc'): # urlparse is newer, just read the fields straight # from the parts object generic_parts['scheme'] = parts.scheme generic_parts['netloc'] = parts.netloc generic_parts['path'] = parts.path generic_parts['params'] = parts.params generic_parts['query'] = parts.query generic_parts['fragment'] = parts.fragment generic_parts['username'] = parts.username generic_parts['password'] = parts.password generic_parts['hostname'] = parts.hostname generic_parts['port'] = parts.port else: # we have to use indexes, and then parse out # the other parts not supported by indexing generic_parts['scheme'] = parts[0] generic_parts['netloc'] = parts[1] generic_parts['path'] = parts[2] generic_parts['params'] = parts[3] generic_parts['query'] = parts[4] generic_parts['fragment'] = parts[5] # get the username, password, etc. try: netloc_re = re.compile(r'^((?:\w)+(?::(?:\w)+)?@)?([A-Za-z0-9.-]+)(:\d+)?$') match = netloc_re.match(parts[1]) auth = match.group(1) hostname = match.group(2) port = match.group(3) if port: # the capture group for the port will include the ':', # so remove it and convert the port to an integer port = int(port[1:]) if auth: # the capture group above includes the @, so remove it # and then split it up based on the first ':' found auth = auth[:-1] username, password = auth.split(':', 1) else: username = password = None generic_parts['username'] = username generic_parts['password'] = password generic_parts['hostname'] = hostname generic_parts['port'] = port except: generic_parts['username'] = None generic_parts['password'] = None generic_parts['hostname'] = parts[1] generic_parts['port'] = None return generic_parts class RequestWithMethod(urllib_request.Request): ''' Workaround for using DELETE/PUT/etc with urllib2 Originally contained in library/net_infrastructure/dnsmadeeasy ''' def __init__(self, url, method, data=None, headers=None): if headers is None: headers = {} self._method = method.upper() urllib_request.Request.__init__(self, url, data, headers) def get_method(self): if self._method: return self._method else: return urllib_request.Request.get_method(self) def RedirectHandlerFactory(follow_redirects=None, validate_certs=True): """This is a class factory that closes over the value of ``follow_redirects`` so that the RedirectHandler class has access to that value without having to use globals, and potentially cause problems where ``open_url`` or ``fetch_url`` are used multiple times in a module. """ class RedirectHandler(urllib_request.HTTPRedirectHandler): """This is an implementation of a RedirectHandler to match the functionality provided by httplib2. It will utilize the value of ``follow_redirects`` that is passed into ``RedirectHandlerFactory`` to determine how redirects should be handled in urllib2. """ def redirect_request(self, req, fp, code, msg, hdrs, newurl): handler = maybe_add_ssl_handler(newurl, validate_certs) if handler: urllib_request._opener.add_handler(handler) if follow_redirects == 'urllib2': return urllib_request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, hdrs, newurl) elif follow_redirects in ['no', 'none', False]: raise urllib_error.HTTPError(newurl, code, msg, hdrs, fp) do_redirect = False if follow_redirects in ['all', 'yes', True]: do_redirect = (code >= 300 and code < 400) elif follow_redirects == 'safe': m = req.get_method() do_redirect = (code >= 300 and code < 400 and m in ('GET', 'HEAD')) if do_redirect: # be conciliant with URIs containing a space newurl = newurl.replace(' ', '%20') newheaders = dict((k, v) for k, v in req.headers.items() if k.lower() not in ("content-length", "content-type")) try: # Python 2-3.3 origin_req_host = req.get_origin_req_host() except AttributeError: # Python 3.4+ origin_req_host = req.origin_req_host return urllib_request.Request(newurl, headers=newheaders, origin_req_host=origin_req_host, unverifiable=True) else: raise urllib_error.HTTPError(req.get_full_url(), code, msg, hdrs, fp) return RedirectHandler def build_ssl_validation_error(hostname, port, paths, exc=None): '''Inteligently build out the SSLValidationError based on what support you have installed ''' msg = [ ('Failed to validate the SSL certificate for %s:%s.' ' Make sure your managed systems have a valid CA' ' certificate installed.') ] if not HAS_SSLCONTEXT: msg.append('If the website serving the url uses SNI you need' ' python >= 2.7.9 on your managed machine') msg.append(' (the python executable used (%s) is version: %s)' % (sys.executable, ''.join(sys.version.splitlines()))) if not HAS_URLLIB3_PYOPENSSLCONTEXT or not HAS_URLLIB3_SSL_WRAP_SOCKET: msg.append('or you can install the `urllib3`, `pyOpenSSL`,' ' `ndg-httpsclient`, and `pyasn1` python modules') msg.append('to perform SNI verification in python >= 2.6.') msg.append('You can use validate_certs=False if you do' ' not need to confirm the servers identity but this is' ' unsafe and not recommended.' ' Paths checked for this platform: %s.') if exc: msg.append('The exception msg was: %s.' % to_native(exc)) raise SSLValidationError(' '.join(msg) % (hostname, port, ", ".join(paths))) class SSLValidationHandler(urllib_request.BaseHandler): ''' A custom handler class for SSL validation. Based on: http://stackoverflow.com/questions/1087227/validate-ssl-certificates-with-python http://techknack.net/python-urllib2-handlers/ ''' CONNECT_COMMAND = "CONNECT %s:%s HTTP/1.0\r\nConnection: close\r\n" def __init__(self, hostname, port): self.hostname = hostname self.port = port def get_ca_certs(self): # tries to find a valid CA cert in one of the # standard locations for the current distribution ca_certs = [] paths_checked = [] system = to_text(platform.system(), errors='surrogate_or_strict') # build a list of paths to check for .crt/.pem files # based on the platform type paths_checked.append('/etc/ssl/certs') if system == u'Linux': paths_checked.append('/etc/pki/ca-trust/extracted/pem') paths_checked.append('/etc/pki/tls/certs') paths_checked.append('/usr/share/ca-certificates/cacert.org') elif system == u'FreeBSD': paths_checked.append('/usr/local/share/certs') elif system == u'OpenBSD': paths_checked.append('/etc/ssl') elif system == u'NetBSD': ca_certs.append('/etc/openssl/certs') elif system == u'SunOS': paths_checked.append('/opt/local/etc/openssl/certs') # fall back to a user-deployed cert in a standard # location if the OS platform one is not available paths_checked.append('/etc/ansible') tmp_fd, tmp_path = tempfile.mkstemp() to_add_fd, to_add_path = tempfile.mkstemp() to_add = False # Write the dummy ca cert if we are running on Mac OS X if system == u'Darwin': os.write(tmp_fd, b_DUMMY_CA_CERT) # Default Homebrew path for OpenSSL certs paths_checked.append('/usr/local/etc/openssl') # for all of the paths, find any .crt or .pem files # and compile them into single temp file for use # in the ssl check to speed up the test for path in paths_checked: if os.path.exists(path) and os.path.isdir(path): dir_contents = os.listdir(path) for f in dir_contents: full_path = os.path.join(path, f) if os.path.isfile(full_path) and os.path.splitext(f)[1] in ('.crt', '.pem'): try: cert_file = open(full_path, 'rb') cert = cert_file.read() cert_file.close() os.write(tmp_fd, cert) os.write(tmp_fd, b'\n') if full_path not in LOADED_VERIFY_LOCATIONS: to_add = True os.write(to_add_fd, cert) os.write(to_add_fd, b'\n') LOADED_VERIFY_LOCATIONS.add(full_path) except (OSError, IOError): pass if not to_add: try: os.remove(to_add_path) except OSError: pass to_add_path = None return (tmp_path, to_add_path, paths_checked) def validate_proxy_response(self, response, valid_codes=None): ''' make sure we get back a valid code from the proxy ''' valid_codes = [200] if valid_codes is None else valid_codes try: (http_version, resp_code, msg) = re.match(br'(HTTP/\d\.\d) (\d\d\d) (.*)', response).groups() if int(resp_code) not in valid_codes: raise Exception except: raise ProxyError('Connection to proxy failed') def detect_no_proxy(self, url): ''' Detect if the 'no_proxy' environment variable is set and honor those locations. ''' env_no_proxy = os.environ.get('no_proxy') if env_no_proxy: env_no_proxy = env_no_proxy.split(',') netloc = urlparse(url).netloc for host in env_no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # Our requested URL matches something in no_proxy, so don't # use the proxy for this return False return True def _make_context(self, to_add_ca_cert_path): if HAS_SSLCONTEXT: context = create_default_context() elif HAS_URLLIB3_PYOPENSSLCONTEXT: context = PyOpenSSLContext(PROTOCOL) else: raise NotImplementedError('Host libraries are too old to support creating an sslcontext') if to_add_ca_cert_path: context.load_verify_locations(to_add_ca_cert_path) return context def http_request(self, req): tmp_ca_cert_path, to_add_ca_cert_path, paths_checked = self.get_ca_certs() https_proxy = os.environ.get('https_proxy') context = None try: context = self._make_context(to_add_ca_cert_path) except Exception: # We'll make do with no context below pass # Detect if 'no_proxy' environment variable is set and if our URL is included use_proxy = self.detect_no_proxy(req.get_full_url()) if not use_proxy: # ignore proxy settings for this host request if tmp_ca_cert_path: try: os.remove(tmp_ca_cert_path) except OSError: pass if to_add_ca_cert_path: try: os.remove(to_add_ca_cert_path) except OSError: pass return req try: if https_proxy: proxy_parts = generic_urlparse(urlparse(https_proxy)) port = proxy_parts.get('port') or 443 s = socket.create_connection((proxy_parts.get('hostname'), port)) if proxy_parts.get('scheme') == 'http': s.sendall(to_bytes(self.CONNECT_COMMAND % (self.hostname, self.port), errors='surrogate_or_strict')) if proxy_parts.get('username'): credentials = "%s:%s" % (proxy_parts.get('username', ''), proxy_parts.get('password', '')) s.sendall(b'Proxy-Authorization: Basic %s\r\n' % base64.b64encode(to_bytes(credentials, errors='surrogate_or_strict')).strip()) s.sendall(b'\r\n') connect_result = b"" while connect_result.find(b"\r\n\r\n") <= 0: connect_result += s.recv(4096) # 128 kilobytes of headers should be enough for everyone. if len(connect_result) > 131072: raise ProxyError('Proxy sent too verbose headers. Only 128KiB allowed.') self.validate_proxy_response(connect_result) if context: ssl_s = context.wrap_socket(s, server_hostname=self.hostname) elif HAS_URLLIB3_SSL_WRAP_SOCKET: ssl_s = ssl_wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL, server_hostname=self.hostname) else: ssl_s = ssl.wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL) match_hostname(ssl_s.getpeercert(), self.hostname) else: raise ProxyError('Unsupported proxy scheme: %s. Currently ansible only supports HTTP proxies.' % proxy_parts.get('scheme')) else: s = socket.create_connection((self.hostname, self.port)) if context: ssl_s = context.wrap_socket(s, server_hostname=self.hostname) elif HAS_URLLIB3_SSL_WRAP_SOCKET: ssl_s = ssl_wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL, server_hostname=self.hostname) else: ssl_s = ssl.wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL) match_hostname(ssl_s.getpeercert(), self.hostname) # close the ssl connection # ssl_s.unwrap() s.close() except (ssl.SSLError, CertificateError) as e: build_ssl_validation_error(self.hostname, self.port, paths_checked, e) except socket.error as e: raise ConnectionError('Failed to connect to %s at port %s: %s' % (self.hostname, self.port, to_native(e))) try: # cleanup the temp file created, don't worry # if it fails for some reason os.remove(tmp_ca_cert_path) except: pass try: # cleanup the temp file created, don't worry # if it fails for some reason if to_add_ca_cert_path: os.remove(to_add_ca_cert_path) except: pass return req https_request = http_request def maybe_add_ssl_handler(url, validate_certs): parsed = generic_urlparse(urlparse(url)) if parsed.scheme == 'https' and validate_certs: if not HAS_SSL: raise NoSSLError('SSL validation is not available in your version of python. You can use validate_certs=False,' ' however this is unsafe and not recommended') # do the cert validation netloc = parsed.netloc if '@' in netloc: netloc = netloc.split('@', 1)[1] if ':' in netloc: hostname, port = netloc.split(':', 1) port = int(port) else: hostname = netloc port = 443 # create the SSL validation handler and # add it to the list of handlers return SSLValidationHandler(hostname, port) def open_url(url, data=None, headers=None, method=None, use_proxy=True, force=False, last_mod_time=None, timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None, force_basic_auth=False, follow_redirects='urllib2', client_cert=None, client_key=None, cookies=None): ''' Sends a request via HTTP(S) or FTP using urllib2 (Python2) or urllib (Python3) Does not require the module environment ''' handlers = [] ssl_handler = maybe_add_ssl_handler(url, validate_certs) if ssl_handler: handlers.append(ssl_handler) parsed = generic_urlparse(urlparse(url)) if parsed.scheme != 'ftp': username = url_username if headers is None: headers = {} if username: password = url_password netloc = parsed.netloc elif '@' in parsed.netloc: credentials, netloc = parsed.netloc.split('@', 1) if ':' in credentials: username, password = credentials.split(':', 1) else: username = credentials password = '' parsed_list = parsed.as_list() parsed_list[1] = netloc # reconstruct url without credentials url = urlunparse(parsed_list) if username and not force_basic_auth: passman = urllib_request.HTTPPasswordMgrWithDefaultRealm() # this creates a password manager passman.add_password(None, netloc, username, password) # because we have put None at the start it will always # use this username/password combination for urls # for which `theurl` is a super-url authhandler = urllib_request.HTTPBasicAuthHandler(passman) digest_authhandler = urllib_request.HTTPDigestAuthHandler(passman) # create the AuthHandler handlers.append(authhandler) handlers.append(digest_authhandler) elif username and force_basic_auth: headers["Authorization"] = basic_auth_header(username, password) else: try: rc = netrc.netrc(os.environ.get('NETRC')) login = rc.authenticators(parsed.hostname) except IOError: login = None if login: username, _, password = login if username and password: headers["Authorization"] = basic_auth_header(username, password) if not use_proxy: proxyhandler = urllib_request.ProxyHandler({}) handlers.append(proxyhandler) if HAS_SSLCONTEXT and not validate_certs: # In 2.7.9, the default context validates certificates context = SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 context.options |= ssl.OP_NO_SSLv3 context.verify_mode = ssl.CERT_NONE context.check_hostname = False handlers.append(HTTPSClientAuthHandler(client_cert=client_cert, client_key=client_key, context=context)) elif client_cert: handlers.append(HTTPSClientAuthHandler(client_cert=client_cert, client_key=client_key)) # pre-2.6 versions of python cannot use the custom https # handler, since the socket class is lacking create_connection. # Some python builds lack HTTPS support. if hasattr(socket, 'create_connection') and CustomHTTPSHandler: handlers.append(CustomHTTPSHandler) handlers.append(RedirectHandlerFactory(follow_redirects, validate_certs)) # add some nicer cookie handling if cookies is not None: handlers.append(urllib_request.HTTPCookieProcessor(cookies)) opener = urllib_request.build_opener(*handlers) urllib_request.install_opener(opener) data = to_bytes(data, nonstring='passthru') if method: if method.upper() not in ('OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT', 'PATCH'): raise ConnectionError('invalid HTTP request method; %s' % method.upper()) request = RequestWithMethod(url, method.upper(), data) else: request = urllib_request.Request(url, data) # add the custom agent header, to help prevent issues # with sites that block the default urllib agent string if http_agent: request.add_header('User-agent', http_agent) # Cache control # Either we directly force a cache refresh if force: request.add_header('cache-control', 'no-cache') # or we do it if the original is more recent than our copy elif last_mod_time: tstamp = last_mod_time.strftime('%a, %d %b %Y %H:%M:%S +0000') request.add_header('If-Modified-Since', tstamp) # user defined headers now, which may override things we've set above if headers: if not isinstance(headers, dict): raise ValueError("headers provided to fetch_url() must be a dict") for header in headers: request.add_header(header, headers[header]) urlopen_args = [request, None] if sys.version_info >= (2, 6, 0): # urlopen in python prior to 2.6.0 did not # have a timeout parameter urlopen_args.append(timeout) r = urllib_request.urlopen(*urlopen_args) return r # # Module-related functions # def basic_auth_header(username, password): """Takes a username and password and returns a byte string suitable for using as value of an Authorization header to do basic auth. """ return b"Basic %s" % base64.b64encode(to_bytes("%s:%s" % (username, password), errors='surrogate_or_strict')) def url_argument_spec(): ''' Creates an argument spec that can be used with any module that will be requesting content via urllib/urllib2 ''' return dict( url=dict(), force=dict(default='no', aliases=['thirsty'], type='bool'), http_agent=dict(default='ansible-httpget'), use_proxy=dict(default='yes', type='bool'), validate_certs=dict(default='yes', type='bool'), url_username=dict(required=False), url_password=dict(required=False, no_log=True), force_basic_auth=dict(required=False, type='bool', default='no'), client_cert=dict(required=False, type='path', default=None), client_key=dict(required=False, type='path', default=None), ) def fetch_url(module, url, data=None, headers=None, method=None, use_proxy=True, force=False, last_mod_time=None, timeout=10): """Sends a request via HTTP(S) or FTP (needs the module as parameter) :arg module: The AnsibleModule (used to get username, password etc. (s.b.). :arg url: The url to use. :kwarg data: The data to be sent (in case of POST/PUT). :kwarg headers: A dict with the request headers. :kwarg method: "POST", "PUT", etc. :kwarg boolean use_proxy: Default: True :kwarg boolean force: If True: Do not get a cached copy (Default: False) :kwarg last_mod_time: Default: None :kwarg int timeout: Default: 10 :returns: A tuple of (**response**, **info**). Use ``response.read()`` to read the data. The **info** contains the 'status' and other meta data. When a HttpError (status > 400) occurred then ``info['body']`` contains the error response data:: Example:: data={...} resp, info = fetch_url(module, "http://example.com", data=module.jsonify(data) header={Content-type': 'application/json'}, method="POST") status_code = info["status"] body = resp.read() if status_code >= 400 : body = info['body'] """ if not HAS_URLPARSE: module.fail_json(msg='urlparse is not installed') # ensure we use proper tempdir old_tempdir = tempfile.tempdir tempfile.tempdir = module.tmpdir # Get validate_certs from the module params validate_certs = module.params.get('validate_certs', True) username = module.params.get('url_username', '') password = module.params.get('url_password', '') http_agent = module.params.get('http_agent', 'ansible-httpget') force_basic_auth = module.params.get('force_basic_auth', '') follow_redirects = module.params.get('follow_redirects', 'urllib2') client_cert = module.params.get('client_cert') client_key = module.params.get('client_key') cookies = cookiejar.LWPCookieJar() r = None info = dict(url=url) try: r = open_url(url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=username, url_password=password, http_agent=http_agent, force_basic_auth=force_basic_auth, follow_redirects=follow_redirects, client_cert=client_cert, client_key=client_key, cookies=cookies) info.update(r.info()) # parse the cookies into a nice dictionary cookie_dict = dict() for cookie in cookies: cookie_dict[cookie.name] = cookie.value info['cookies'] = cookie_dict # finally update the result with a message about the fetch info.update(dict(msg="OK (%s bytes)" % r.headers.get('Content-Length', 'unknown'), url=r.geturl(), status=r.code)) except NoSSLError as e: distribution = get_distribution() if distribution is not None and distribution.lower() == 'redhat': module.fail_json(msg='%s. You can also install python-ssl from EPEL' % to_native(e)) else: module.fail_json(msg='%s' % to_native(e)) except (ConnectionError, ValueError) as e: module.fail_json(msg=to_native(e)) except urllib_error.HTTPError as e: try: body = e.read() except AttributeError: body = '' # Try to add exception info to the output but don't fail if we can't try: info.update(dict(**e.info())) except: pass info.update({'msg': to_native(e), 'body': body, 'status': e.code}) except urllib_error.URLError as e: code = int(getattr(e, 'code', -1)) info.update(dict(msg="Request failed: %s" % to_native(e), status=code)) except socket.error as e: info.update(dict(msg="Connection failure: %s" % to_native(e), status=-1)) except httplib.BadStatusLine as e: info.update(dict(msg="Connection failure: connection was closed before a valid response was received: %s" % to_native(e.line), status=-1)) except Exception as e: info.update(dict(msg="An unknown error occurred: %s" % to_native(e), status=-1), exception=traceback.format_exc()) finally: tempfile.tempdir = old_tempdir return r, info
gpl-3.0
indirectlylit/kolibri
kolibri/core/discovery/test/test_network_utils.py
3
6974
import mock import requests from django.test import TestCase from ..utils.network import errors from ..utils.network.client import NetworkClient from ..utils.network.urls import get_normalized_url_variations from .helpers import mock_request class TestURLParsing(TestCase): def test_valid_ipv4_address(self): urls = get_normalized_url_variations("192.168.0.1") self.assertEqual( urls, [ "http://192.168.0.1:8080/", "http://192.168.0.1/", "http://192.168.0.1:8008/", "http://192.168.0.1:8000/", "http://192.168.0.1:5000/", "https://192.168.0.1/", ], ) def test_valid_ipv6_address(self): urls = get_normalized_url_variations("2001:0db8:85a3:0000:0000:8a2e:0370:7334") self.assertEqual( urls, [ "http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8080/", "http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/", "http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8008/", "http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8000/", "http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:5000/", "https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/", ], ) def test_valid_domain_name(self): urls = get_normalized_url_variations("www.nomansland.com") self.assertEqual( urls, [ "http://www.nomansland.com:8080/", "http://www.nomansland.com/", "http://www.nomansland.com:8008/", "http://www.nomansland.com:8000/", "http://www.nomansland.com:5000/", "https://www.nomansland.com/", ], ) def test_valid_domain_name_with_valid_port(self): urls = get_normalized_url_variations("www.nomansland.com:7007") self.assertEqual( urls, [ "http://www.nomansland.com:7007/", "http://www.nomansland.com:8080/", "http://www.nomansland.com/", "http://www.nomansland.com:8008/", "http://www.nomansland.com:8000/", "http://www.nomansland.com:5000/", "https://www.nomansland.com:7007/", "https://www.nomansland.com/", ], ) def test_valid_domain_name_with_path(self): urls = get_normalized_url_variations("www.nomansland.com/mapath") self.assertEqual( urls, [ "http://www.nomansland.com:8080/mapath/", "http://www.nomansland.com/mapath/", "http://www.nomansland.com:8008/mapath/", "http://www.nomansland.com:8000/mapath/", "http://www.nomansland.com:5000/mapath/", "https://www.nomansland.com/mapath/", "http://www.nomansland.com:8080/", "http://www.nomansland.com/", "http://www.nomansland.com:8008/", "http://www.nomansland.com:8000/", "http://www.nomansland.com:5000/", "https://www.nomansland.com/", ], ) def test_valid_http_url(self): urls = get_normalized_url_variations("http://www.nomansland.com") self.assertEqual( urls, [ "http://www.nomansland.com:8080/", "http://www.nomansland.com/", "http://www.nomansland.com:8008/", "http://www.nomansland.com:8000/", "http://www.nomansland.com:5000/", "https://www.nomansland.com/", ], ) def test_valid_https_url(self): urls = get_normalized_url_variations("https://www.nomansland.com") self.assertEqual( urls, [ "https://www.nomansland.com/", "http://www.nomansland.com:8080/", "http://www.nomansland.com/", "http://www.nomansland.com:8008/", "http://www.nomansland.com:8000/", "http://www.nomansland.com:5000/", ], ) def test_invalid_scheme(self): with self.assertRaises(errors.InvalidScheme): get_normalized_url_variations("ftp://www.nomansland.com") def test_invalid_ipv4_address(self): with self.assertRaises(errors.InvalidHostname): get_normalized_url_variations("192.168.1") def test_invalid_ipv6_address(self): with self.assertRaises(errors.InvalidHostname): get_normalized_url_variations("2001:0db8:85a3:0000:0000:0370:7334") def test_invalid_domain_name(self): with self.assertRaises(errors.InvalidHostname): get_normalized_url_variations("www.nomans&land.com") def test_valid_domain_name_with_invalid_huge_port(self): with self.assertRaises(errors.InvalidPort): get_normalized_url_variations("www.nomansland.com:1234567") def test_valid_domain_name_with_invalid_nonnumeric_port(self): with self.assertRaises(errors.InvalidPort): get_normalized_url_variations("www.nomansland.com:1231d") @mock.patch.object(requests.Session, "get", mock_request) class TestNetworkClientConnections(TestCase): def test_successful_connection_to_kolibri_address(self): nc = NetworkClient(address="kolibrihappyurl.qqq") self.assertEqual(nc.base_url, "https://kolibrihappyurl.qqq/") def test_unsuccessful_connection_to_unavailable_address(self): with self.assertRaises(errors.NetworkLocationNotFound): NetworkClient(address="sadurl.qqq") def test_unsuccessful_connection_to_nonkolibri_address(self): with self.assertRaises(errors.NetworkLocationNotFound): NetworkClient(address="nonkolibrihappyurl.qqq") def test_successful_connection_to_address_with_port80_timeout(self): nc = NetworkClient(address="timeoutonport80url.qqq") self.assertEqual(nc.base_url, "http://timeoutonport80url.qqq:8080/") def test_successful_connection_to_kolibri_base_url(self): nc = NetworkClient(base_url="https://kolibrihappyurl.qqq/") self.assertEqual(nc.base_url, "https://kolibrihappyurl.qqq/") def test_unsuccessful_connection_to_unavailable_base_url(self): with self.assertRaises(errors.NetworkLocationNotFound): NetworkClient(base_url="https://sadurl.qqq") def test_unsuccessful_connection_to_nonkolibri_base_url(self): with self.assertRaises(errors.NetworkLocationNotFound): NetworkClient(base_url="nonkolibrihappyurl.qqq") def test_unsuccessful_connection_to_base_url_with_timeout(self): with self.assertRaises(errors.NetworkLocationNotFound): NetworkClient(base_url="http://timeoutonport80url.qqq/")
mit
martin-craig/Airtime
python_apps/media-monitor2/mm2.py
2
1082
# -*- coding: utf-8 -*- import sys import os from media.saas.launcher import setup_global, launch_instance, setup_logger from media.monitor.config import MMConfig def main(global_config, api_client_config, log_config): """ function to run hosted install """ mm_config = MMConfig(global_config) log = setup_logger( log_config, mm_config['logpath'] ) setup_global(log) launch_instance('hosted_install', '/', global_config, api_client_config) __doc__ = """ Usage: mm2.py --config=<path> --apiclient=<path> --log=<path> Options: -h --help Show this screen --config=<path> path to mm2 config --apiclient=<path> path to apiclient config --log=<path> log config at <path> """ if __name__ == '__main__': from docopt import docopt args = docopt(__doc__,version="mm1.99") for k in ['--apiclient','--config','--log']: if not os.path.exists(args[k]): print("'%s' must exist" % args[k]) sys.exit(0) print("Running mm1.99") main(args['--config'],args['--apiclient'],args['--log'])
gpl-3.0
Azure/azure-sdk-for-python
sdk/purview/azure-mgmt-purview/azure/mgmt/purview/_purview_management_client.py
1
4032
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential from ._configuration import PurviewManagementClientConfiguration from .operations import AccountsOperations from .operations import DefaultAccountsOperations from .operations import Operations from .operations import PrivateEndpointConnectionsOperations from .operations import PrivateLinkResourcesOperations from . import models class PurviewManagementClient(object): """Creates a Microsoft.Purview management client. :ivar accounts: AccountsOperations operations :vartype accounts: azure.mgmt.purview.operations.AccountsOperations :ivar default_accounts: DefaultAccountsOperations operations :vartype default_accounts: azure.mgmt.purview.operations.DefaultAccountsOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.purview.operations.Operations :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: azure.mgmt.purview.operations.PrivateEndpointConnectionsOperations :ivar private_link_resources: PrivateLinkResourcesOperations operations :vartype private_link_resources: azure.mgmt.purview.operations.PrivateLinkResourcesOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The subscription identifier. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential, # type: "TokenCredential" subscription_id, # type: str base_url=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> None if not base_url: base_url = 'https://management.azure.com' self._config = PurviewManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self.accounts = AccountsOperations( self._client, self._config, self._serialize, self._deserialize) self.default_accounts = DefaultAccountsOperations( self._client, self._config, self._serialize, self._deserialize) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( self._client, self._config, self._serialize, self._deserialize) self.private_link_resources = PrivateLinkResourcesOperations( self._client, self._config, self._serialize, self._deserialize) def close(self): # type: () -> None self._client.close() def __enter__(self): # type: () -> PurviewManagementClient self._client.__enter__() return self def __exit__(self, *exc_details): # type: (Any) -> None self._client.__exit__(*exc_details)
mit
mattclay/ansible
lib/ansible/plugins/strategy/linear.py
23
22994
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' name: linear short_description: Executes tasks in a linear fashion description: - Task execution is in lockstep per host batch as defined by C(serial) (default all). Up to the fork limit of hosts will execute each task at the same time and then the next series of hosts until the batch is done, before going on to the next task. version_added: "2.0" notes: - This was the default Ansible behaviour before 'strategy plugins' were introduced in 2.0. author: Ansible Core Team ''' from ansible import constants as C from ansible.errors import AnsibleError, AnsibleAssertionError from ansible.executor.play_iterator import PlayIterator from ansible.module_utils.six import iteritems from ansible.module_utils._text import to_text from ansible.playbook.block import Block from ansible.playbook.included_file import IncludedFile from ansible.playbook.task import Task from ansible.plugins.loader import action_loader from ansible.plugins.strategy import StrategyBase from ansible.template import Templar from ansible.utils.display import Display display = Display() class StrategyModule(StrategyBase): noop_task = None def _replace_with_noop(self, target): if self.noop_task is None: raise AnsibleAssertionError('strategy.linear.StrategyModule.noop_task is None, need Task()') result = [] for el in target: if isinstance(el, Task): result.append(self.noop_task) elif isinstance(el, Block): result.append(self._create_noop_block_from(el, el._parent)) return result def _create_noop_block_from(self, original_block, parent): noop_block = Block(parent_block=parent) noop_block.block = self._replace_with_noop(original_block.block) noop_block.always = self._replace_with_noop(original_block.always) noop_block.rescue = self._replace_with_noop(original_block.rescue) return noop_block def _prepare_and_create_noop_block_from(self, original_block, parent, iterator): self.noop_task = Task() self.noop_task.action = 'meta' self.noop_task.args['_raw_params'] = 'noop' self.noop_task.implicit = True self.noop_task.set_loader(iterator._play._loader) return self._create_noop_block_from(original_block, parent) def _get_next_task_lockstep(self, hosts, iterator): ''' Returns a list of (host, task) tuples, where the task may be a noop task to keep the iterator in lock step across all hosts. ''' noop_task = Task() noop_task.action = 'meta' noop_task.args['_raw_params'] = 'noop' noop_task.implicit = True noop_task.set_loader(iterator._play._loader) host_tasks = {} display.debug("building list of next tasks for hosts") for host in hosts: host_tasks[host.name] = iterator.get_next_task_for_host(host, peek=True) display.debug("done building task lists") num_setups = 0 num_tasks = 0 num_rescue = 0 num_always = 0 display.debug("counting tasks in each state of execution") host_tasks_to_run = [(host, state_task) for host, state_task in iteritems(host_tasks) if state_task and state_task[1]] if host_tasks_to_run: try: lowest_cur_block = min( (iterator.get_active_state(s).cur_block for h, (s, t) in host_tasks_to_run if s.run_state != PlayIterator.ITERATING_COMPLETE)) except ValueError: lowest_cur_block = None else: # empty host_tasks_to_run will just run till the end of the function # without ever touching lowest_cur_block lowest_cur_block = None for (k, v) in host_tasks_to_run: (s, t) = v s = iterator.get_active_state(s) if s.cur_block > lowest_cur_block: # Not the current block, ignore it continue if s.run_state == PlayIterator.ITERATING_SETUP: num_setups += 1 elif s.run_state == PlayIterator.ITERATING_TASKS: num_tasks += 1 elif s.run_state == PlayIterator.ITERATING_RESCUE: num_rescue += 1 elif s.run_state == PlayIterator.ITERATING_ALWAYS: num_always += 1 display.debug("done counting tasks in each state of execution:\n\tnum_setups: %s\n\tnum_tasks: %s\n\tnum_rescue: %s\n\tnum_always: %s" % (num_setups, num_tasks, num_rescue, num_always)) def _advance_selected_hosts(hosts, cur_block, cur_state): ''' This helper returns the task for all hosts in the requested state, otherwise they get a noop dummy task. This also advances the state of the host, since the given states are determined while using peek=True. ''' # we return the values in the order they were originally # specified in the given hosts array rvals = [] display.debug("starting to advance hosts") for host in hosts: host_state_task = host_tasks.get(host.name) if host_state_task is None: continue (s, t) = host_state_task s = iterator.get_active_state(s) if t is None: continue if s.run_state == cur_state and s.cur_block == cur_block: new_t = iterator.get_next_task_for_host(host) rvals.append((host, t)) else: rvals.append((host, noop_task)) display.debug("done advancing hosts to next task") return rvals # if any hosts are in ITERATING_SETUP, return the setup task # while all other hosts get a noop if num_setups: display.debug("advancing hosts in ITERATING_SETUP") return _advance_selected_hosts(hosts, lowest_cur_block, PlayIterator.ITERATING_SETUP) # if any hosts are in ITERATING_TASKS, return the next normal # task for these hosts, while all other hosts get a noop if num_tasks: display.debug("advancing hosts in ITERATING_TASKS") return _advance_selected_hosts(hosts, lowest_cur_block, PlayIterator.ITERATING_TASKS) # if any hosts are in ITERATING_RESCUE, return the next rescue # task for these hosts, while all other hosts get a noop if num_rescue: display.debug("advancing hosts in ITERATING_RESCUE") return _advance_selected_hosts(hosts, lowest_cur_block, PlayIterator.ITERATING_RESCUE) # if any hosts are in ITERATING_ALWAYS, return the next always # task for these hosts, while all other hosts get a noop if num_always: display.debug("advancing hosts in ITERATING_ALWAYS") return _advance_selected_hosts(hosts, lowest_cur_block, PlayIterator.ITERATING_ALWAYS) # at this point, everything must be ITERATING_COMPLETE, so we # return None for all hosts in the list display.debug("all hosts are done, so returning None's for all hosts") return [(host, None) for host in hosts] def run(self, iterator, play_context): ''' The linear strategy is simple - get the next task and queue it for all hosts, then wait for the queue to drain before moving on to the next task ''' # iterate over each task, while there is one left to run result = self._tqm.RUN_OK work_to_do = True self._set_hosts_cache(iterator._play) while work_to_do and not self._tqm._terminated: try: display.debug("getting the remaining hosts for this loop") hosts_left = self.get_hosts_left(iterator) display.debug("done getting the remaining hosts for this loop") # queue up this task for each host in the inventory callback_sent = False work_to_do = False host_results = [] host_tasks = self._get_next_task_lockstep(hosts_left, iterator) # skip control skip_rest = False choose_step = True # flag set if task is set to any_errors_fatal any_errors_fatal = False results = [] for (host, task) in host_tasks: if not task: continue if self._tqm._terminated: break run_once = False work_to_do = True # check to see if this task should be skipped, due to it being a member of a # role which has already run (and whether that role allows duplicate execution) if task._role and task._role.has_run(host): # If there is no metadata, the default behavior is to not allow duplicates, # if there is metadata, check to see if the allow_duplicates flag was set to true if task._role._metadata is None or task._role._metadata and not task._role._metadata.allow_duplicates: display.debug("'%s' skipped because role has already run" % task) continue display.debug("getting variables") task_vars = self._variable_manager.get_vars(play=iterator._play, host=host, task=task, _hosts=self._hosts_cache, _hosts_all=self._hosts_cache_all) self.add_tqm_variables(task_vars, play=iterator._play) templar = Templar(loader=self._loader, variables=task_vars) display.debug("done getting variables") # test to see if the task across all hosts points to an action plugin which # sets BYPASS_HOST_LOOP to true, or if it has run_once enabled. If so, we # will only send this task to the first host in the list. task.action = templar.template(task.action) try: action = action_loader.get(task.action, class_only=True, collection_list=task.collections) except KeyError: # we don't care here, because the action may simply not have a # corresponding action plugin action = None if task.action in C._ACTION_META: # for the linear strategy, we run meta tasks just once and for # all hosts currently being iterated over rather than one host results.extend(self._execute_meta(task, play_context, iterator, host)) if task.args.get('_raw_params', None) not in ('noop', 'reset_connection', 'end_host', 'role_complete'): run_once = True if (task.any_errors_fatal or run_once) and not task.ignore_errors: any_errors_fatal = True else: # handle step if needed, skip meta actions as they are used internally if self._step and choose_step: if self._take_step(task): choose_step = False else: skip_rest = True break run_once = templar.template(task.run_once) or action and getattr(action, 'BYPASS_HOST_LOOP', False) if (task.any_errors_fatal or run_once) and not task.ignore_errors: any_errors_fatal = True if not callback_sent: display.debug("sending task start callback, copying the task so we can template it temporarily") saved_name = task.name display.debug("done copying, going to template now") try: task.name = to_text(templar.template(task.name, fail_on_undefined=False), nonstring='empty') display.debug("done templating") except Exception: # just ignore any errors during task name templating, # we don't care if it just shows the raw name display.debug("templating failed for some reason") display.debug("here goes the callback...") self._tqm.send_callback('v2_playbook_on_task_start', task, is_conditional=False) task.name = saved_name callback_sent = True display.debug("sending task start callback") self._blocked_hosts[host.get_name()] = True self._queue_task(host, task, task_vars, play_context) del task_vars # if we're bypassing the host loop, break out now if run_once: break results += self._process_pending_results(iterator, max_passes=max(1, int(len(self._tqm._workers) * 0.1))) # go to next host/task group if skip_rest: continue display.debug("done queuing things up, now waiting for results queue to drain") if self._pending_results > 0: results += self._wait_on_pending_results(iterator) host_results.extend(results) self.update_active_connections(results) included_files = IncludedFile.process_include_results( host_results, iterator=iterator, loader=self._loader, variable_manager=self._variable_manager ) include_failure = False if len(included_files) > 0: display.debug("we have included files to process") display.debug("generating all_blocks data") all_blocks = dict((host, []) for host in hosts_left) display.debug("done generating all_blocks data") for included_file in included_files: display.debug("processing included file: %s" % included_file._filename) # included hosts get the task list while those excluded get an equal-length # list of noop tasks, to make sure that they continue running in lock-step try: if included_file._is_role: new_ir = self._copy_included_file(included_file) new_blocks, handler_blocks = new_ir.get_block_list( play=iterator._play, variable_manager=self._variable_manager, loader=self._loader, ) else: new_blocks = self._load_included_file(included_file, iterator=iterator) display.debug("iterating over new_blocks loaded from include file") for new_block in new_blocks: task_vars = self._variable_manager.get_vars( play=iterator._play, task=new_block.get_first_parent_include(), _hosts=self._hosts_cache, _hosts_all=self._hosts_cache_all, ) display.debug("filtering new block on tags") final_block = new_block.filter_tagged_tasks(task_vars) display.debug("done filtering new block on tags") noop_block = self._prepare_and_create_noop_block_from(final_block, task._parent, iterator) for host in hosts_left: if host in included_file._hosts: all_blocks[host].append(final_block) else: all_blocks[host].append(noop_block) display.debug("done iterating over new_blocks loaded from include file") except AnsibleError as e: for host in included_file._hosts: self._tqm._failed_hosts[host.name] = True iterator.mark_host_failed(host) display.error(to_text(e), wrap_text=False) include_failure = True continue # finally go through all of the hosts and append the # accumulated blocks to their list of tasks display.debug("extending task lists for all hosts with included blocks") for host in hosts_left: iterator.add_tasks(host, all_blocks[host]) display.debug("done extending task lists") display.debug("done processing included files") display.debug("results queue empty") display.debug("checking for any_errors_fatal") failed_hosts = [] unreachable_hosts = [] for res in results: # execute_meta() does not set 'failed' in the TaskResult # so we skip checking it with the meta tasks and look just at the iterator if (res.is_failed() or res._task.action in C._ACTION_META) and iterator.is_failed(res._host): failed_hosts.append(res._host.name) elif res.is_unreachable(): unreachable_hosts.append(res._host.name) # if any_errors_fatal and we had an error, mark all hosts as failed if any_errors_fatal and (len(failed_hosts) > 0 or len(unreachable_hosts) > 0): dont_fail_states = frozenset([iterator.ITERATING_RESCUE, iterator.ITERATING_ALWAYS]) for host in hosts_left: (s, _) = iterator.get_next_task_for_host(host, peek=True) # the state may actually be in a child state, use the get_active_state() # method in the iterator to figure out the true active state s = iterator.get_active_state(s) if s.run_state not in dont_fail_states or \ s.run_state == iterator.ITERATING_RESCUE and s.fail_state & iterator.FAILED_RESCUE != 0: self._tqm._failed_hosts[host.name] = True result |= self._tqm.RUN_FAILED_BREAK_PLAY display.debug("done checking for any_errors_fatal") display.debug("checking for max_fail_percentage") if iterator._play.max_fail_percentage is not None and len(results) > 0: percentage = iterator._play.max_fail_percentage / 100.0 if (len(self._tqm._failed_hosts) / iterator.batch_size) > percentage: for host in hosts_left: # don't double-mark hosts, or the iterator will potentially # fail them out of the rescue/always states if host.name not in failed_hosts: self._tqm._failed_hosts[host.name] = True iterator.mark_host_failed(host) self._tqm.send_callback('v2_playbook_on_no_hosts_remaining') result |= self._tqm.RUN_FAILED_BREAK_PLAY display.debug('(%s failed / %s total )> %s max fail' % (len(self._tqm._failed_hosts), iterator.batch_size, percentage)) display.debug("done checking for max_fail_percentage") display.debug("checking to see if all hosts have failed and the running result is not ok") if result != self._tqm.RUN_OK and len(self._tqm._failed_hosts) >= len(hosts_left): display.debug("^ not ok, so returning result now") self._tqm.send_callback('v2_playbook_on_no_hosts_remaining') return result display.debug("done checking to see if all hosts have failed") except (IOError, EOFError) as e: display.debug("got IOError/EOFError in task loop: %s" % e) # most likely an abort, return failed return self._tqm.RUN_UNKNOWN_ERROR # run the base class run() method, which executes the cleanup function # and runs any outstanding handlers which have been triggered return super(StrategyModule, self).run(iterator, play_context, result)
gpl-3.0
pgmillon/ansible
test/units/modules/network/f5/test_bigip_gtm_monitor_https.py
38
5285
# -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule try: from library.modules.bigip_gtm_monitor_https import ApiParameters from library.modules.bigip_gtm_monitor_https import ModuleParameters from library.modules.bigip_gtm_monitor_https import ModuleManager from library.modules.bigip_gtm_monitor_https import ArgumentSpec # In Ansible 2.8, Ansible changed import paths. from test.units.compat import unittest from test.units.compat.mock import Mock from test.units.compat.mock import patch from test.units.modules.utils import set_module_args except ImportError: from ansible.modules.network.f5.bigip_gtm_monitor_https import ApiParameters from ansible.modules.network.f5.bigip_gtm_monitor_https import ModuleParameters from ansible.modules.network.f5.bigip_gtm_monitor_https import ModuleManager from ansible.modules.network.f5.bigip_gtm_monitor_https import ArgumentSpec # Ansible 2.8 imports from units.compat import unittest from units.compat.mock import Mock from units.compat.mock import patch from units.modules.utils import set_module_args fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( name='foo', parent='/Common/my-http', send='the send string', receive='the receive string', ip='1.1.1.1', port='80', interval='10', timeout='20', client_cert='default', client_key='default', target_username='user1', target_password='secret1', ignore_down_response=True, transparent=False, probe_timeout='30', reverse=True ) p = ModuleParameters(params=args) assert p.name == 'foo' assert p.parent == '/Common/my-http' assert p.send == 'the send string' assert p.receive == 'the receive string' assert p.destination == '1.1.1.1:80' assert p.ip == '1.1.1.1' assert p.port == 80 assert p.interval == 10 assert p.timeout == 20 assert p.client_cert == '/Common/default.crt' assert p.client_key == '/Common/default.key' assert p.target_username == 'user1' assert p.target_password == 'secret1' assert p.ignore_down_response is True assert p.transparent is False assert p.probe_timeout == 30 assert p.reverse is True def test_api_parameters(self): args = load_fixture('load_gtm_monitor_http_1.json') p = ApiParameters(params=args) assert p.name == 'foo' assert p.parent == '/Common/http' assert p.send == 'GET /' assert p.receive == 'the receive string' assert p.destination == '3.3.3.3:8080' assert p.ip == '3.3.3.3' assert p.port == 8080 assert p.interval == 30 assert p.timeout == 120 assert p.ignore_down_response is False assert p.transparent is True assert p.probe_timeout == 5 assert p.reverse is True class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() try: self.p1 = patch('library.modules.bigip_gtm_monitor_https.module_provisioned') self.m1 = self.p1.start() self.m1.return_value = True except Exception: self.p1 = patch('ansible.modules.network.f5.bigip_gtm_monitor_https.module_provisioned') self.m1 = self.p1.start() self.m1.return_value = True def tearDown(self): self.p1.stop() def test_create_monitor(self, *args): set_module_args(dict( name='foo', ip='10.10.10.10', port=80, interval=20, timeout=30, provider=dict( server='localhost', password='password', user='admin' ) )) module = AnsibleModule( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode ) # Override methods in the specific type of manager mm = ModuleManager(module=module) mm.exists = Mock(side_effect=[False, True]) mm.create_on_device = Mock(return_value=True) mm.module_provisioned = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True
gpl-3.0
axant/tgext.ecommerce
tgext/ecommerce/lib/utils.py
1
2806
import os import re, unicodedata import tg import gettext import math import inspect class NoDefault(object): """A dummy value used for parameters with no default.""" def slugify(value, type, models): if isinstance(value, dict): for k, v in value.iteritems(): key = k value = v counter = models.Product.query.find({'name.%s' % key: value, 'type': type}).count() else: counter = models.Product.query.find({'name.%s' % tg.config.lang: value, 'type': type}).count() value = type + '-' + value value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub('[^\w\s-]', '', value).strip().lower() value = re.sub('[-\s]+', '-', value) value = value + '-' + str(counter) return value def slugify_category(value, models): if isinstance(value, dict): for k, v in value.iteritems(): key = k value = v counter = models.Category.query.find({'name.%s' % key: value}).count() else: counter = models.Category.query.find({'name.%s' % tg.config.lang: value}).count() value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub('[^\w\s-]', '', value).strip().lower() value = re.sub('[-\s]+', '-', value) if counter != 0: value += '-' + str(counter) return value def short_lang(languages_list): try: return languages_list[0].split("_")[0] except (IndexError, TypeError): return tg.config.lang def internationalise(value): if isinstance(value, dict): return value return {tg.config.lang: value} def preferred_language(): return short_lang(tg.i18n.get_lang(all=False)) class with_currency(object): @staticmethod def float2cur(n): return int(round(n*100.0)) @staticmethod def cur2float(n): return math.floor(float(n))/100.0 def __init__(self, *args): self.currencies = args def __call__(self, f): def _decorated(*args, **kwargs): named_params = inspect.getcallargs(f, *args, **kwargs) for cur in self.currencies: value = named_params[cur] named_params[cur] = self.float2cur(value) return self.cur2float(f(**named_params)) return _decorated @with_currency('price') def apply_vat(price, vat): return price*vat @with_currency('total', 'discount') def apply_discount(total, discount): return total - discount def apply_percentage_discount(total, percentage): discount = get_percentage_discount(total, percentage) return apply_discount(total, discount) @with_currency('total') def get_percentage_discount(total, percentage): return total * (percentage / 100.0)
mit
Titulacion-Sistemas/PythonTitulacion-EV
Lib/site-packages/setuptools/command/setopt.py
285
5068
import distutils, os from setuptools import Command from distutils.util import convert_path from distutils import log from distutils.errors import * __all__ = ['config_file', 'edit_config', 'option_base', 'setopt'] def config_file(kind="local"): """Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user" """ if kind=='local': return 'setup.cfg' if kind=='global': return os.path.join( os.path.dirname(distutils.__file__),'distutils.cfg' ) if kind=='user': dot = os.name=='posix' and '.' or '' return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot)) raise ValueError( "config_file() type must be 'local', 'global', or 'user'", kind ) def edit_config(filename, settings, dry_run=False): """Edit a configuration file to include `settings` `settings` is a dictionary of dictionaries or ``None`` values, keyed by command/section name. A ``None`` value means to delete the entire section, while a dictionary lists settings to be changed or deleted in that section. A setting of ``None`` means to delete that setting. """ from setuptools.compat import ConfigParser log.debug("Reading configuration from %s", filename) opts = ConfigParser.RawConfigParser() opts.read([filename]) for section, options in settings.items(): if options is None: log.info("Deleting section [%s] from %s", section, filename) opts.remove_section(section) else: if not opts.has_section(section): log.debug("Adding new section [%s] to %s", section, filename) opts.add_section(section) for option,value in options.items(): if value is None: log.debug("Deleting %s.%s from %s", section, option, filename ) opts.remove_option(section,option) if not opts.options(section): log.info("Deleting empty [%s] section from %s", section, filename) opts.remove_section(section) else: log.debug( "Setting %s.%s to %r in %s", section, option, value, filename ) opts.set(section,option,value) log.info("Writing %s", filename) if not dry_run: f = open(filename,'w'); opts.write(f); f.close() class option_base(Command): """Abstract base class for commands that mess with config files""" user_options = [ ('global-config', 'g', "save options to the site-wide distutils.cfg file"), ('user-config', 'u', "save options to the current user's pydistutils.cfg file"), ('filename=', 'f', "configuration file to use (default=setup.cfg)"), ] boolean_options = [ 'global-config', 'user-config', ] def initialize_options(self): self.global_config = None self.user_config = None self.filename = None def finalize_options(self): filenames = [] if self.global_config: filenames.append(config_file('global')) if self.user_config: filenames.append(config_file('user')) if self.filename is not None: filenames.append(self.filename) if not filenames: filenames.append(config_file('local')) if len(filenames)>1: raise DistutilsOptionError( "Must specify only one configuration file option", filenames ) self.filename, = filenames class setopt(option_base): """Save command-line options to a file""" description = "set an option in setup.cfg or another config file" user_options = [ ('command=', 'c', 'command to set an option for'), ('option=', 'o', 'option to set'), ('set-value=', 's', 'value of the option'), ('remove', 'r', 'remove (unset) the value'), ] + option_base.user_options boolean_options = option_base.boolean_options + ['remove'] def initialize_options(self): option_base.initialize_options(self) self.command = None self.option = None self.set_value = None self.remove = None def finalize_options(self): option_base.finalize_options(self) if self.command is None or self.option is None: raise DistutilsOptionError("Must specify --command *and* --option") if self.set_value is None and not self.remove: raise DistutilsOptionError("Must specify --set-value or --remove") def run(self): edit_config( self.filename, { self.command: {self.option.replace('-','_'):self.set_value} }, self.dry_run )
mit
alxgu/ansible
lib/ansible/modules/cloud/openstack/os_user_facts.py
31
4544
#!/usr/bin/python # Copyright (c) 2016 Hewlett-Packard Enterprise Corporation # 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: os_user_facts short_description: Retrieve facts about one or more OpenStack users extends_documentation_fragment: openstack version_added: "2.1" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" description: - Retrieve facts about a one or more OpenStack users requirements: - "python >= 2.7" - "openstacksdk" options: name: description: - Name or ID of the user required: true domain: description: - Name or ID of the domain containing the user if the cloud supports domains filters: description: - A dictionary of meta data to use for further filtering. Elements of this dictionary may be additional dictionaries. availability_zone: description: - Ignored. Present for backwards compatibility ''' EXAMPLES = ''' # Gather facts about previously created users - os_user_facts: cloud: awesomecloud - debug: var: openstack_users # Gather facts about a previously created user by name - os_user_facts: cloud: awesomecloud name: demouser - debug: var: openstack_users # Gather facts about a previously created user in a specific domain - os_user_facts: cloud: awesomecloud name: demouser domain: admindomain - debug: var: openstack_users # Gather facts about a previously created user in a specific domain with filter - os_user_facts: cloud: awesomecloud name: demouser domain: admindomain filters: enabled: False - debug: var: openstack_users ''' RETURN = ''' openstack_users: description: has all the OpenStack facts about users returned: always, but can be null type: complex contains: id: description: Unique UUID. returned: success type: str name: description: Name given to the user. returned: success type: str enabled: description: Flag to indicate if the user is enabled returned: success type: bool domain_id: description: Domain ID containing the user returned: success type: str default_project_id: description: Default project ID of the user returned: success type: str email: description: Email of the user returned: success type: str username: description: Username of the user returned: success type: str ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs, openstack_cloud_from_module def main(): argument_spec = openstack_full_argument_spec( name=dict(required=False, default=None), domain=dict(required=False, default=None), filters=dict(required=False, type='dict', default=None), ) module = AnsibleModule(argument_spec) sdk, opcloud = openstack_cloud_from_module(module) try: name = module.params['name'] domain = module.params['domain'] filters = module.params['filters'] if domain: try: # We assume admin is passing domain id dom = opcloud.get_domain(domain)['id'] domain = dom except Exception: # If we fail, maybe admin is passing a domain name. # Note that domains have unique names, just like id. dom = opcloud.search_domains(filters={'name': domain}) if dom: domain = dom[0]['id'] else: module.fail_json(msg='Domain name or ID does not exist') if not filters: filters = {} filters['domain_id'] = domain users = opcloud.search_users(name, filters) module.exit_json(changed=False, ansible_facts=dict( openstack_users=users)) except sdk.exceptions.OpenStackCloudException as e: module.fail_json(msg=str(e)) if __name__ == '__main__': main()
gpl-3.0
danic85/virtual_assistant
behaviours/tests/test_translator.py
2
2268
import datetime, unittest import os, sys from mock import Mock, call, patch from lib import feeds import re from behaviours import translator import json class TestTranslatorMethods(unittest.TestCase): def test_translate(self): path = os.path.dirname(os.path.realpath(__file__)) + '/testdata/translator_get_language_code.json' with open(path) as data_file: data = json.load(data_file) translate = {"to": "es", "translationText": "Esto Es un prueba", "from": "en", "text": "this is a test"} feeds.get_json = Mock() feeds.get_json.side_effect = [data, translate] b = translator.Translator(db=None, config={}, dir='') b.match = re.search('^translate (.*) (to|from) (\w*)$', 'translate this is a test to spanish', re.IGNORECASE) self.assertEqual(b.translate(), "Esto Es un prueba") def test_translate_back(self): path = os.path.dirname(os.path.realpath(__file__)) + '/testdata/translator_get_language_code.json' with open(path) as data_file: data = json.load(data_file) translate = {"to": "en", "translationText": "This is a test", "from": "es", "text": "Esto Es un prueba"} feeds.get_json = Mock() feeds.get_json.side_effect = [data, translate] b = translator.Translator(db=None, config={}, dir='') b.match = re.search('^translate (.*) (to|from) (\w*)$', 'translate Esto Es un prueba from spanish', re.IGNORECASE) self.assertEqual(b.translate(), "This is a test") def test_translate_no_language(self): path = os.path.dirname(os.path.realpath(__file__)) + '/testdata/translator_get_language_code.json' with open(path) as data_file: data = json.load(data_file) # this should not be needed, as it will not hit it translate = {"to": "", "translationText": "Esto Es un prueba", "from": "en", "text": "this is a test"} feeds.get_json = Mock() feeds.get_json.side_effect = [data, translate] b = translator.Translator(db=None, config={}, dir='') b.match = re.search('^translate (.*) (to|from) (\w*)$', 'translate this is a test to Unknown', re.IGNORECASE) self.assertEqual(b.translate(), "I can't translate to Unknown")
gpl-3.0
epiphany27/NewsBlur
vendor/paypal/standard/ipn/django_migrations/0001_initial.py
18
10862
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='PayPalIPN', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('business', models.CharField(help_text=b'Email where the money was sent.', max_length=127, blank=True)), ('charset', models.CharField(max_length=32, blank=True)), ('custom', models.CharField(max_length=255, blank=True)), ('notify_version', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('parent_txn_id', models.CharField(max_length=19, verbose_name=b'Parent Transaction ID', blank=True)), ('receiver_email', models.EmailField(max_length=127, blank=True)), ('receiver_id', models.CharField(max_length=127, blank=True)), ('residence_country', models.CharField(max_length=2, blank=True)), ('test_ipn', models.BooleanField(default=False)), ('txn_id', models.CharField(help_text=b'PayPal transaction ID.', max_length=19, verbose_name=b'Transaction ID', db_index=True, blank=True)), ('txn_type', models.CharField(help_text=b'PayPal transaction type.', max_length=128, verbose_name=b'Transaction Type', blank=True)), ('verify_sign', models.CharField(max_length=255, blank=True)), ('address_country', models.CharField(max_length=64, blank=True)), ('address_city', models.CharField(max_length=40, blank=True)), ('address_country_code', models.CharField(help_text=b'ISO 3166', max_length=64, blank=True)), ('address_name', models.CharField(max_length=128, blank=True)), ('address_state', models.CharField(max_length=40, blank=True)), ('address_status', models.CharField(max_length=11, blank=True)), ('address_street', models.CharField(max_length=200, blank=True)), ('address_zip', models.CharField(max_length=20, blank=True)), ('contact_phone', models.CharField(max_length=20, blank=True)), ('first_name', models.CharField(max_length=64, blank=True)), ('last_name', models.CharField(max_length=64, blank=True)), ('payer_business_name', models.CharField(max_length=127, blank=True)), ('payer_email', models.CharField(max_length=127, blank=True)), ('payer_id', models.CharField(max_length=13, blank=True)), ('auth_amount', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('auth_exp', models.CharField(max_length=28, blank=True)), ('auth_id', models.CharField(max_length=19, blank=True)), ('auth_status', models.CharField(max_length=9, blank=True)), ('exchange_rate', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=16, blank=True)), ('invoice', models.CharField(max_length=127, blank=True)), ('item_name', models.CharField(max_length=127, blank=True)), ('item_number', models.CharField(max_length=127, blank=True)), ('mc_currency', models.CharField(default=b'USD', max_length=32, blank=True)), ('mc_fee', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('mc_gross', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('mc_handling', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('mc_shipping', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('memo', models.CharField(max_length=255, blank=True)), ('num_cart_items', models.IntegerField(default=0, null=True, blank=True)), ('option_name1', models.CharField(max_length=64, blank=True)), ('option_name2', models.CharField(max_length=64, blank=True)), ('payer_status', models.CharField(max_length=10, blank=True)), ('payment_date', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('payment_gross', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('payment_status', models.CharField(max_length=17, blank=True)), ('payment_type', models.CharField(max_length=7, blank=True)), ('pending_reason', models.CharField(max_length=14, blank=True)), ('protection_eligibility', models.CharField(max_length=32, blank=True)), ('quantity', models.IntegerField(default=1, null=True, blank=True)), ('reason_code', models.CharField(max_length=15, blank=True)), ('remaining_settle', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('settle_amount', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('settle_currency', models.CharField(max_length=32, blank=True)), ('shipping', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('shipping_method', models.CharField(max_length=255, blank=True)), ('tax', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('transaction_entity', models.CharField(max_length=7, blank=True)), ('auction_buyer_id', models.CharField(max_length=64, blank=True)), ('auction_closing_date', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('auction_multi_item', models.IntegerField(default=0, null=True, blank=True)), ('for_auction', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('amount', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('amount_per_cycle', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('initial_payment_amount', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('next_payment_date', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('outstanding_balance', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('payment_cycle', models.CharField(max_length=32, blank=True)), ('period_type', models.CharField(max_length=32, blank=True)), ('product_name', models.CharField(max_length=128, blank=True)), ('product_type', models.CharField(max_length=128, blank=True)), ('profile_status', models.CharField(max_length=32, blank=True)), ('recurring_payment_id', models.CharField(max_length=128, blank=True)), ('rp_invoice_id', models.CharField(max_length=127, blank=True)), ('time_created', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('amount1', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('amount2', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('amount3', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('mc_amount1', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('mc_amount2', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('mc_amount3', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('password', models.CharField(max_length=24, blank=True)), ('period1', models.CharField(max_length=32, blank=True)), ('period2', models.CharField(max_length=32, blank=True)), ('period3', models.CharField(max_length=32, blank=True)), ('reattempt', models.CharField(max_length=1, blank=True)), ('recur_times', models.IntegerField(default=0, null=True, blank=True)), ('recurring', models.CharField(max_length=1, blank=True)), ('retry_at', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('subscr_date', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('subscr_effective', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('subscr_id', models.CharField(max_length=19, blank=True)), ('username', models.CharField(max_length=64, blank=True)), ('case_creation_date', models.DateTimeField(help_text=b'HH:MM:SS DD Mmm YY, YYYY PST', null=True, blank=True)), ('case_id', models.CharField(max_length=14, blank=True)), ('case_type', models.CharField(max_length=24, blank=True)), ('receipt_id', models.CharField(max_length=64, blank=True)), ('currency_code', models.CharField(default=b'USD', max_length=32, blank=True)), ('handling_amount', models.DecimalField(default=0, null=True, max_digits=64, decimal_places=2, blank=True)), ('transaction_subject', models.CharField(max_length=255, blank=True)), ('ipaddress', models.IPAddressField(blank=True)), ('flag', models.BooleanField(default=False)), ('flag_code', models.CharField(max_length=16, blank=True)), ('flag_info', models.TextField(blank=True)), ('query', models.TextField(blank=True)), ('response', models.TextField(blank=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('from_view', models.CharField(max_length=6, null=True, blank=True)), ], options={ 'db_table': 'paypal_ipn', 'verbose_name': 'PayPal IPN', }, bases=(models.Model,), ), ]
mit
BT-fgarbely/odoo
addons/delivery/partner.py
383
1404
# -*- 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 res_partner(osv.osv): _inherit = 'res.partner' _columns = { 'property_delivery_carrier': fields.property( type='many2one', relation='delivery.carrier', string="Delivery Method", help="This delivery method will be used when invoicing from picking."), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
mlperf/training_results_v0.5
v0.5.0/google/cloud_v2.8/ssd-tpuv2-8/code/ssd/model/tpu/models/experimental/resnet50_keras/resnet_preprocessing.py
5
6831
# Copyright 2018 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. # ============================================================================== """ImageNet preprocessing for ResNet.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf IMAGE_SIZE = 224 CROP_PADDING = 32 def distorted_bounding_box_crop(image_bytes, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None): """Generates cropped_image using one of the bboxes randomly distorted. See `tf.image.sample_distorted_bounding_box` for more documentation. Args: image_bytes: `Tensor` of binary image data. bbox: `Tensor` of bounding boxes arranged `[1, num_boxes, coords]` where each coordinate is [0, 1) and the coordinates are arranged as `[ymin, xmin, ymax, xmax]`. If num_boxes is 0 then use the whole image. min_object_covered: An optional `float`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. aspect_ratio_range: An optional list of `float`s. The cropped area of the image must have an aspect ratio = width / height within this range. area_range: An optional list of `float`s. The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts: An optional `int`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. scope: Optional `str` for name scope. Returns: (cropped image `Tensor`, distorted bbox `Tensor`). """ with tf.name_scope(scope, 'distorted_bounding_box_crop', [image_bytes, bbox]): shape = tf.image.extract_jpeg_shape(image_bytes) sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box( shape, bounding_boxes=bbox, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, max_attempts=max_attempts, use_image_if_no_bounding_boxes=True) bbox_begin, bbox_size, _ = sample_distorted_bounding_box # Crop the image to the specified bounding box. offset_y, offset_x, _ = tf.unstack(bbox_begin) target_height, target_width, _ = tf.unstack(bbox_size) crop_window = tf.stack([offset_y, offset_x, target_height, target_width]) image = tf.image.decode_and_crop_jpeg(image_bytes, crop_window, channels=3) return image def _at_least_x_are_equal(a, b, x): """At least `x` of `a` and `b` `Tensors` are equal.""" match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x) def _decode_and_random_crop(image_bytes): """Make a random crop of IMAGE_SIZE.""" bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) image = distorted_bounding_box_crop( image_bytes, bbox, min_object_covered=0.1, aspect_ratio_range=(3. / 4, 4. / 3.), area_range=(0.08, 1.0), max_attempts=10, scope=None) original_shape = tf.image.extract_jpeg_shape(image_bytes) bad = _at_least_x_are_equal(original_shape, tf.shape(image), 3) image = tf.cond( bad, lambda: _decode_and_center_crop(image_bytes), lambda: tf.image.resize_bicubic([image], # pylint: disable=g-long-lambda [IMAGE_SIZE, IMAGE_SIZE])[0]) return image def _decode_and_center_crop(image_bytes): """Crops to center of image with padding then scales IMAGE_SIZE.""" shape = tf.image.extract_jpeg_shape(image_bytes) image_height = shape[0] image_width = shape[1] padded_center_crop_size = tf.cast( ((IMAGE_SIZE / (IMAGE_SIZE + CROP_PADDING)) * tf.cast(tf.minimum(image_height, image_width), tf.float32)), tf.int32) offset_height = ((image_height - padded_center_crop_size) + 1) // 2 offset_width = ((image_width - padded_center_crop_size) + 1) // 2 crop_window = tf.stack([offset_height, offset_width, padded_center_crop_size, padded_center_crop_size]) image = tf.image.decode_and_crop_jpeg(image_bytes, crop_window, channels=3) image = tf.image.resize_bicubic([image], [IMAGE_SIZE, IMAGE_SIZE])[0] return image def _flip(image): """Random horizontal image flip.""" image = tf.image.random_flip_left_right(image) return image def preprocess_for_train(image_bytes, use_bfloat16): """Preprocesses the given image for evaluation. Args: image_bytes: `Tensor` representing an image binary of arbitrary size. use_bfloat16: `bool` for whether to use bfloat16. Returns: A preprocessed image `Tensor`. """ image = _decode_and_random_crop(image_bytes) image = _flip(image) image = tf.reshape(image, [IMAGE_SIZE, IMAGE_SIZE, 3]) image = tf.image.convert_image_dtype( image, dtype=tf.bfloat16 if use_bfloat16 else tf.float32) return image def preprocess_for_eval(image_bytes, use_bfloat16): """Preprocesses the given image for evaluation. Args: image_bytes: `Tensor` representing an image binary of arbitrary size. use_bfloat16: `bool` for whether to use bfloat16. Returns: A preprocessed image `Tensor`. """ image = _decode_and_center_crop(image_bytes) image = tf.reshape(image, [IMAGE_SIZE, IMAGE_SIZE, 3]) image = tf.image.convert_image_dtype( image, dtype=tf.bfloat16 if use_bfloat16 else tf.float32) return image def preprocess_image(image_bytes, is_training=False, use_bfloat16=False): """Preprocesses the given image. Args: image_bytes: `Tensor` representing an image binary of arbitrary size. is_training: `bool` for whether the preprocessing is for training. use_bfloat16: `bool` for whether to use bfloat16. Returns: A preprocessed image `Tensor`. """ if is_training: return preprocess_for_train(image_bytes, use_bfloat16) else: return preprocess_for_eval(image_bytes, use_bfloat16)
apache-2.0
mscuthbert/abjad
abjad/tools/selectiontools/test/test_selectiontools_Selection__all_are_components_in_same_logical_voice.py
2
46366
# -*- encoding: utf-8 -*- import pytest from abjad import * Component = scoretools.Component Selection = selectiontools.Selection def test_selectiontools_Selection__all_are_components_in_same_logical_voice_01(): r'''Unincorporated leaves do not share a logical voice. Unicorporated leaves do not share a root component. False if not allow orphans; True if allow orphans. ''' notes = [Note("c'8"), Note("d'8"), Note("e'8"), Note("f'8")] assert Selection._all_are_components_in_same_logical_voice(notes) assert not Selection._all_are_components_in_same_logical_voice( notes, allow_orphans=False) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_02(): r'''Container and leaves all logical voice. ''' container = Container("c'8 d'8 e'8 f'8") r''' { c'8 d'8 e'8 f'8 } ''' assert Selection._all_are_components_in_same_logical_voice( list(iterate(container).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_03(): r'''Tuplet and leaves all logical voice. ''' tuplet = scoretools.FixedDurationTuplet(Duration(2, 8), "c'8 d'8 e'8") r''' \times 2/3 { c'8 d'8 e'8 } ''' assert Selection._all_are_components_in_same_logical_voice( list(iterate(tuplet).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_04(): r'''Voice and leaves all appear in same logical voice. ''' voice = Voice("c'8 d'8 e'8 f'8") r''' \new Voice { c'8 d'8 e'8 f'8 } ''' assert Selection._all_are_components_in_same_logical_voice( list(iterate(voice).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_05(): r'''Anonymous staff and leaves all appear in same logical voice. ''' staff = Staff("c'8 d'8 e'8 f'8") r''' \new Staff { c'8 d'8 e'8 f'8 } ''' assert Selection._all_are_components_in_same_logical_voice( list(iterate(staff).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_06(): r'''Voice, sequential and leaves all appear in same logical voice. ''' voice = Voice(r''' { c'8 d'8 e'8 f'8 } { g'8 a'8 b'8 c''8 } ''') assert systemtools.TestManager.compare( voice, r''' \new Voice { { c'8 d'8 e'8 f'8 } { g'8 a'8 b'8 c''8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( list(iterate(voice).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_07(): r'''Anonymous voice, tuplets and leaves all appear in same logical voice. ''' voice = Voice(r''' \times 2/3 { c'8 d'8 e'8 } \times 2/3 { f'8 g'8 a'8 } ''') assert systemtools.TestManager.compare( voice, r''' \new Voice { \times 2/3 { c'8 d'8 e'8 } \times 2/3 { f'8 g'8 a'8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( list(iterate(voice).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_08(): r'''Logical voice does not extend across anonymous voices. ''' staff = Staff(r''' \new Voice { c'8 d'8 e'8 f'8 } \new Voice { g'8 a'8 b'8 c''8 } ''') assert systemtools.TestManager.compare( staff, r''' \new Staff { \new Voice { c'8 d'8 e'8 f'8 } \new Voice { g'8 a'8 b'8 c''8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( staff.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( staff.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( staff.select_leaves(allow_discontiguous_leaves=True)) assert not Selection._all_are_components_in_same_logical_voice( staff[:]) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_09(): r'''Logical voice encompasses across like-named voices. ''' staff = Staff(r''' \context Voice = "foo" { c'8 d'8 e'8 f'8 } \context Voice = "foo" { g'8 a'8 b'8 c''8 } ''') assert systemtools.TestManager.compare( staff, r''' \new Staff { \context Voice = "foo" { c'8 d'8 e'8 f'8 } \context Voice = "foo" { g'8 a'8 b'8 c''8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( staff.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_10(): r'''Logical voice does not extend across differently named voices. ''' staff = Staff(r''' \context Voice = "foo" { c'8 d'8 } \context Voice = "bar" { e'8 f'8 } ''') assert systemtools.TestManager.compare( staff, r''' \new Staff { \context Voice = "foo" { c'8 d'8 } \context Voice = "bar" { e'8 f'8 } } ''' ) assert not Selection._all_are_components_in_same_logical_voice( staff.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_11(): r'''Logical voice does not across anonymous voices. Logical voice does not extend across anonymous staves. ''' container = Container(r''' \new Staff { \new Voice { c'8 d'8 } } \new Staff { \new Voice { e'8 f'8 } } ''') assert systemtools.TestManager.compare( container, r''' { \new Staff { \new Voice { c'8 d'8 } } \new Staff { \new Voice { e'8 f'8 } } } ''' ) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_12(): r'''Logical voice does not extend across anonymous voices. Logical voice does not extend across anonymous staves. ''' container = Container(r''' \new Staff << \new Voice { c'8 d'8 } \new Voice { e'8 f'8 } >> \new Staff << \new Voice { g'8 a'8 } \new Voice { b'8 c''8 } >> ''') assert systemtools.TestManager.compare( container, r''' { \new Staff << \new Voice { c'8 d'8 } \new Voice { e'8 f'8 } >> \new Staff << \new Voice { g'8 a'8 } \new Voice { b'8 c''8 } >> } ''' ) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_13(): r'''Anonymous voice, sequentials and leaves all appear in same logical voice. ''' voice = Voice(r''' { c'8 d'8 } { e'8 f'8 } ''') assert systemtools.TestManager.compare( voice, r''' \new Voice { { c'8 d'8 } { e'8 f'8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( voice.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_14(): r'''Logical voice can extend across like-named staves. Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' \context Staff = "foo" { c'8 cs'8 d'8 ef'8 } \context Staff = "foo" { e'8 f'8 fs'8 g'8 } ''') assert systemtools.TestManager.compare( container, r''' { \context Staff = "foo" { c'8 cs'8 d'8 ef'8 } \context Staff = "foo" { e'8 f'8 fs'8 g'8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_15(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' { c'8 d'8 e'8 f'8 } \new Voice { g'8 a'8 b'8 c''8 } ''') assert systemtools.TestManager.compare( container, r''' { { c'8 d'8 e'8 f'8 } \new Voice { g'8 a'8 b'8 c''8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_16(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' \new Voice { c'8 d'8 e'8 f'8 } { g'8 a'8 b'8 c''8 } ''') assert systemtools.TestManager.compare( container, r''' { \new Voice { c'8 d'8 e'8 f'8 } { g'8 a'8 b'8 c''8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_17(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' { c'8 d'8 e'8 f'8 } \context Voice = "foo" { g'8 a'8 b'8 c''8 } ''') r''' { { c'8 d'8 e'8 f'8 } \context Voice = "foo" { g'8 a'8 b'8 c''8 } } ''' assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_18(): r'''Logical voice can not extend acrossdifferently named implicit voices. ''' container = Container(r''' \context Voice = "foo" { c'8 d'8 e'8 f'8 } { g'8 a'8 b'8 c''8 } ''') assert systemtools.TestManager.compare( container, r''' { \context Voice = "foo" { c'8 d'8 e'8 f'8 } { g'8 a'8 b'8 c''8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_19(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' { c'8 d'8 e'8 f'8 } \new Staff { g'8 a'8 b'8 c''8 } ''') assert systemtools.TestManager.compare( container, r''' { { c'8 d'8 e'8 f'8 } \new Staff { g'8 a'8 b'8 c''8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_20(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' \new Staff { c'8 cs'8 d'8 ef'8 } { e'8 f'8 fs'8 g'8 } ''') assert systemtools.TestManager.compare( container, r''' { \new Staff { c'8 cs'8 d'8 ef'8 } { e'8 f'8 fs'8 g'8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_21(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' c'8 cs'8 d'8 ef'8 \new Voice { e'8 f'8 fs'8 g'8 } ''') assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 d'8 ef'8 \new Voice { e'8 f'8 fs'8 g'8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_22(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' \new Voice { c'8 cs'8 d'8 ef'8 } e'8 f'8 fs'8 g'8 ''') assert systemtools.TestManager.compare( container, r''' { \new Voice { c'8 cs'8 d'8 ef'8 } e'8 f'8 fs'8 g'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_23(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' c'8 cs'8 d'8 ef'8 \context Voice = "foo" { e'8 f'8 fs'8 g'8 } ''') assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 d'8 ef'8 \context Voice = "foo" { e'8 f'8 fs'8 g'8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_24(): r'''Logical voice can not extend across differently named implicit voices. NOTE: THIS IS THE LILYPOND LACUNA. LilyPond *does* extend logical voice in this case. Abjad does not. ''' container = Container(r''' \context Voice = "foo" { c'8 cs'8 d'8 ef'8 } e'8 f'8 fs'8 g'8 ''') assert systemtools.TestManager.compare( container, r''' { \context Voice = "foo" { c'8 cs'8 d'8 ef'8 } e'8 f'8 fs'8 g'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_25(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' c'8 cs'8 d'8 ef'8 \new Voice { e'8 f'8 fs'8 g'8 } ''') assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 d'8 ef'8 \new Voice { e'8 f'8 fs'8 g'8 } } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_26(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' \new Staff { c'8 d'8 e'8 f'8 } g'8 a'8 b'8 c''8 ''') assert systemtools.TestManager.compare( container, r''' { \new Staff { c'8 d'8 e'8 f'8 } g'8 a'8 b'8 c''8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_27(): r'''Logical voice can not extend across differently named implicit voices. ''' voice = Voice([Note(n, (1, 8)) for n in range(4)]) container = Container([voice]) notes = [Note(n, (1, 8)) for n in range(4, 8)] container = Container([container] + notes) assert systemtools.TestManager.compare( container, r''' { { \new Voice { c'8 cs'8 d'8 ef'8 } } e'8 f'8 fs'8 g'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_28(): r'''Logical voice can not extend across differently named implicit voices. ''' voice = Voice([Note(n, (1, 8)) for n in range(4)]) voice.name = 'foo' q = Container([voice]) notes = [Note(n, (1, 8)) for n in range(4, 8)] container = Container([q] + notes) r''' { { \context Voice = "foo" { c'8 cs'8 d'8 ef'8 } } e'8 f'8 fs'8 g'8 } ''' assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_29(): r'''Logical voice can not extend across differently named implicit voices. ''' voice_1 = Voice([Note(n, (1, 8)) for n in range(4)]) voice_1.name = 'foo' voice_2 = Voice([voice_1]) voice_2.name = 'bar' notes = [Note(n, (1, 8)) for n in range(4, 8)] container = Container([voice_2] + notes) assert systemtools.TestManager.compare( container, r''' { \context Voice = "bar" { \context Voice = "foo" { c'8 cs'8 d'8 ef'8 } } e'8 f'8 fs'8 g'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_30(): r'''Logical voice can not extend across differently named implicit voices. ''' voice_1 = Voice([Note(n, (1, 8)) for n in range(4)]) voice_2 = Voice([voice_1]) notes = [Note(n, (1, 8)) for n in range(4, 8)] container = Container([voice_2] + notes) assert systemtools.TestManager.compare( container, r''' { \new Voice { \new Voice { c'8 cs'8 d'8 ef'8 } } e'8 f'8 fs'8 g'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_31(): r'''Logical voice can not extend across differently named implicit voices. ''' notes = [Note(n, (1, 8)) for n in range(4)] voice_1 = Voice(Note(12, (1, 8)) * 4) voice_2 = Voice(Note(0, (1, 8)) * 4) container = Container([voice_1, voice_2]) container.is_simultaneous = True container = Container(notes + [container]) assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 d'8 ef'8 << \new Voice { c''8 c''8 c''8 c''8 } \new Voice { c'8 c'8 c'8 c'8 } >> } ''' ) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:8]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_32(): r'''Logical voice can not extend across differently named implicit voices. ''' container = Container(r''' << \new Voice { c'8 cs'8 d'8 ef'8 } \new Voice { e'8 f'8 fs'8 g'8 } >> af'8 a'8 bf'8 b'8 ''') assert systemtools.TestManager.compare( container, r''' { << \new Voice { c'8 cs'8 d'8 ef'8 } \new Voice { e'8 f'8 fs'8 g'8 } >> af'8 a'8 bf'8 b'8 } ''' ) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:8]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_33(): r'''Logical voice does extend across gaps. Logical voice can not extend across differently named voices. ''' container = Container(r''' c'8 cs'8 \new Voice { d'8 ef'8 \new Voice { e'8 f'8 fs'8 g'8 } af'8 a'8 } bf'8 b'8 ''') outer = (0, 1, 10, 11) middle = (2, 3, 8, 9) inner = (4, 5, 6, 7) assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 \new Voice { d'8 ef'8 \new Voice { e'8 f'8 fs'8 g'8 } af'8 a'8 } bf'8 b'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves(allow_discontiguous_leaves=True)[i] for i in outer]) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves(allow_discontiguous_leaves=True)[i] for i in middle]) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves(allow_discontiguous_leaves=True)[i] for i in inner]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_34(): r'''Logical voice does extend across gaps. Logical voice can not extend across differently named implicit voices. ''' staff = Staff(r''' c'8 cs'8 \new Staff { d'8 ef'8 \new Staff { e'8 f'8 fs'8 g'8 } af'8 a'8 } bf'8 b'8 ''') outer = (0, 1, 10, 11) middle = (2, 3, 8, 9) inner = (4, 5, 6, 7) assert systemtools.TestManager.compare( staff, r''' \new Staff { c'8 cs'8 \new Staff { d'8 ef'8 \new Staff { e'8 f'8 fs'8 g'8 } af'8 a'8 } bf'8 b'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( [staff.select_leaves(allow_discontiguous_leaves=True)[i] for i in outer]) assert Selection._all_are_components_in_same_logical_voice( [staff.select_leaves(allow_discontiguous_leaves=True)[i] for i in middle]) assert Selection._all_are_components_in_same_logical_voice( [staff.select_leaves(allow_discontiguous_leaves=True)[i] for i in inner]) assert not Selection._all_are_components_in_same_logical_voice( staff.select_leaves(allow_discontiguous_leaves=True)[:4]) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_35(): r'''Containers and leaves all appear in same logical voice. ''' container = Container(r''' c'8 cs'8 { d'8 ef'8 { e'8 f'8 fs'8 g'8 } af'8 a'8 } bf'8 b'8 ''') assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 { d'8 ef'8 { e'8 f'8 fs'8 g'8 } af'8 a'8 } bf'8 b'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( list(iterate(container).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_36(): r'''Tuplets and leaves all appear in same logical voice. ''' a = scoretools.FixedDurationTuplet( Duration(3, 8), "e'8 f'8 fs'8 g'8") b = scoretools.FixedDurationTuplet( Duration(3, 8), "d'8 ef'8 af'8 a'8") t = scoretools.FixedDurationTuplet( Duration(3, 8), "c'8 cs'8 bf'8 b'8") b.insert(2, a) t.insert(2, b) b.target_duration = Duration(6, 8) t.target_duration = Duration(9, 8) assert systemtools.TestManager.compare( t, r''' \tweak #'text #tuplet-number::calc-fraction-text \times 9/10 { c'8 cs'8 \tweak #'text #tuplet-number::calc-fraction-text \times 6/7 { d'8 ef'8 \tweak #'text #tuplet-number::calc-fraction-text \times 3/4 { e'8 f'8 fs'8 g'8 } af'8 a'8 } bf'8 b'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( list(iterate(t).by_class())) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_37(): r'''Logical voice can not extend across differently named voices. ''' container = Container(r''' c'8 cs'8 { { \context Voice = "foo" { d'8 ef'8 e'8 f'8 } } } fs'8 g'8 ''') assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 { { \context Voice = "foo" { d'8 ef'8 e'8 f'8 } } } fs'8 g'8 } ''' ) outer = (0, 1, 6, 7) inner = (2, 3, 4, 5) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves(allow_discontiguous_leaves=True)[i] for i in outer]) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves(allow_discontiguous_leaves=True)[i] for i in inner]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_38(): r'''Logical voice does not extend over differently named voices. ''' container = Container(r''' { { \context Voice = "foo" { c'8 cs'8 d'8 ef'8 } } } e'8 f'8 fs'8 g'8 ''') assert systemtools.TestManager.compare( container, r''' { { { \context Voice = "foo" { c'8 cs'8 d'8 ef'8 } } } e'8 f'8 fs'8 g'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_39(): r'''Can not nest across differently named implicit voices. ''' container = Voice( r''' { { { c'8 cs'8 \new Voice { d'8 ef'8 e'8 f'8 } fs'8 g'8 } } } ''') assert systemtools.TestManager.compare( container, r''' \new Voice { { { { c'8 cs'8 \new Voice { d'8 ef'8 e'8 f'8 } fs'8 g'8 } } } } ''' ) outer = (0, 1, 6, 7) inner = (2, 3, 4, 5) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves( allow_discontiguous_leaves=True)[i] for i in outer]) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves(allow_discontiguous_leaves=True)[i] for i in inner]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_40(): r'''Logical voice can not extend across differently named voices. ''' voice = Voice(r''' c'8 cs'8 { d'8 ef'8 { e'8 f'8 \context Voice = "bar" { fs'8 g'8 af'8 a'8 } bf'8 b'8 } c''8 cs''8 } d''8 ef''8 ''') voice.name = 'foo' assert systemtools.TestManager.compare( voice, r''' \context Voice = "foo" { c'8 cs'8 { d'8 ef'8 { e'8 f'8 \context Voice = "bar" { fs'8 g'8 af'8 a'8 } bf'8 b'8 } c''8 cs''8 } d''8 ef''8 } ''' ) outer = (0, 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15) inner = (6, 7, 8, 9) assert Selection._all_are_components_in_same_logical_voice( [voice.select_leaves(allow_discontiguous_leaves=True)[i] for i in outer]) assert Selection._all_are_components_in_same_logical_voice( [voice.select_leaves(allow_discontiguous_leaves=True)[i] for i in inner]) assert not Selection._all_are_components_in_same_logical_voice( voice.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_41(): r'''Logical voice can not extend across differently named anonymous voices. ''' container = Container(r''' \new Voice { c'8 cs'8 d'8 ef'8 } \new Voice { e'8 f'8 fs'8 g'8 } af'8 a'8 bf'8 b'8 ''') assert systemtools.TestManager.compare( container, r''' { \new Voice { c'8 cs'8 d'8 ef'8 } \new Voice { e'8 f'8 fs'8 g'8 } af'8 a'8 bf'8 b'8 } ''' ) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:4]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:8]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[8:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:8]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[4:]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)) def test_selectiontools_Selection__all_are_components_in_same_logical_voice_42(): r'''Logical voice can not extend across differently named anonymous voices. ''' container = Container(r''' c'8 cs'8 << \new Voice { d'8 ef'8 e'8 f'8 } \new Voice { fs'8 g'8 af'8 a'8 } >> bf'8 b'8 ''') assert systemtools.TestManager.compare( container, r''' { c'8 cs'8 << \new Voice { d'8 ef'8 e'8 f'8 } \new Voice { fs'8 g'8 af'8 a'8 } >> bf'8 b'8 } ''' ) outer = (0, 1, 10, 11) assert Selection._all_are_components_in_same_logical_voice( [container.select_leaves(allow_discontiguous_leaves=True)[i] for i in outer]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[2:6]) assert Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[6:10]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True)[:6]) assert not Selection._all_are_components_in_same_logical_voice( container.select_leaves(allow_discontiguous_leaves=True))
gpl-3.0
samthor/intellij-community
python/lib/Lib/anydbm.py
171
2620
"""Generic interface to all dbm clones. Instead of import dbm d = dbm.open(file, 'w', 0666) use import anydbm d = anydbm.open(file, 'w') The returned object is a dbhash, gdbm, dbm or dumbdbm object, dependent on the type of database being opened (determined by whichdb module) in the case of an existing dbm. If the dbm does not exist and the create or new flag ('c' or 'n') was specified, the dbm type will be determined by the availability of the modules (tested in the above order). It has the following interface (key and data are strings): d[key] = data # store data at key (may override data at # existing key) data = d[key] # retrieve data at key (raise KeyError if no # such key) del d[key] # delete data stored at key (raises KeyError # if no such key) flag = key in d # true if the key exists list = d.keys() # return a list of all existing keys (slow!) Future versions may change the order in which implementations are tested for existence, add interfaces to other dbm-like implementations. The open function has an optional second argument. This can be 'r', for read-only access, 'w', for read-write access of an existing database, 'c' for read-write access to a new or existing database, and 'n' for read-write access to a new database. The default is 'r'. Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it only if it doesn't exist; and 'n' always creates a new database. """ class error(Exception): pass _names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] _errors = [error] _defaultmod = None for _name in _names: try: _mod = __import__(_name) except ImportError: continue if not _defaultmod: _defaultmod = _mod _errors.append(_mod.error) if not _defaultmod: raise ImportError, "no dbm clone found; tried %s" % _names error = tuple(_errors) def open(file, flag = 'r', mode = 0666): # guess the type of an existing database from whichdb import whichdb result=whichdb(file) if result is None: # db doesn't exist if 'c' in flag or 'n' in flag: # file doesn't exist and the new # flag was used so use default type mod = _defaultmod else: raise error, "need 'c' or 'n' flag to open new db" elif result == "": # db type cannot be determined raise error, "db type could not be determined" else: mod = __import__(result) return mod.open(file, flag, mode)
apache-2.0
bbondy/brianbondy.gae
libs/markdown/extensions/toc.py
1
5238
""" Table of Contents Extension for Python-Markdown * * * (c) 2008 [Jack Miller](http://codezen.org) Dependencies: * [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/) """ import markdown from markdown import etree import re class TocTreeprocessor(markdown.treeprocessors.Treeprocessor): # Iterator wrapper to get parent and child all at once def iterparent(self, root): for parent in root.getiterator(): for child in parent: yield parent, child def run(self, doc): div = etree.Element("div") div.attrib["class"] = "toc" last_li = None # Add title to the div if self.config["title"][0]: header = etree.SubElement(div, "span") header.attrib["class"] = "toctitle" header.text = self.config["title"][0] level = 0 list_stack=[div] header_rgx = re.compile("[Hh][123456]") # Get a list of id attributes used_ids = [] for c in doc.getiterator(): if "id" in c.attrib: used_ids.append(c.attrib["id"]) for (p, c) in self.iterparent(doc): if not c.text: continue # To keep the output from screwing up the # validation by putting a <div> inside of a <p> # we actually replace the <p> in its entirety. # We do not allow the marker inside a header as that # would causes an enless loop of placing a new TOC # inside previously generated TOC. if c.text.find(self.config["marker"][0]) > -1 and not header_rgx.match(c.tag): for i in range(len(p)): if p[i] == c: p[i] = div break if header_rgx.match(c.tag): tag_level = int(c.tag[-1]) # Regardless of how many levels we jumped # only one list should be created, since # empty lists containing lists are illegal. if tag_level < level: list_stack.pop() level = tag_level if tag_level > level: newlist = etree.Element("ul") if last_li: last_li.append(newlist) else: list_stack[-1].append(newlist) list_stack.append(newlist) level = tag_level # Do not override pre-existing ids if not "id" in c.attrib: id = self.config["slugify"][0](c.text) if id in used_ids: ctr = 1 while "%s_%d" % (id, ctr) in used_ids: ctr += 1 id = "%s_%d" % (id, ctr) used_ids.append(id) c.attrib["id"] = id else: id = c.attrib["id"] # List item link, to be inserted into the toc div last_li = etree.Element("li") link = etree.SubElement(last_li, "a") link.text = c.text link.attrib["href"] = '#' + id if int(self.config["anchorlink"][0]): anchor = etree.SubElement(c, "a") anchor.text = c.text anchor.attrib["href"] = "#" + id anchor.attrib["class"] = "toclink" c.text = "" list_stack[-1].append(last_li) class TocExtension(markdown.Extension): def __init__(self, configs): self.config = { "marker" : ["[TOC]", "Text to find and replace with Table of Contents -" "Defaults to \"[TOC]\""], "slugify" : [self.slugify, "Function to generate anchors based on header text-" "Defaults to a built in slugify function."], "title" : [None, "Title to insert into TOC <div> - " "Defaults to None"], "anchorlink" : [0, "1 if header should be a self link" "Defaults to 0"]} for key, value in configs: self.setConfig(key, value) # This is exactly the same as Django's slugify def slugify(self, value): """ Slugify a string, to make it URL friendly. """ import unicodedata value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+','-',value) def extendMarkdown(self, md, md_globals): tocext = TocTreeprocessor(md) tocext.config = self.config md.treeprocessors.add("toc", tocext, "_begin") def makeExtension(configs={}): return TocExtension(configs=configs)
mit