repo_name
stringlengths 5
104
| path
stringlengths 4
248
| content
stringlengths 102
99.9k
|
|---|---|---|
kvar/ansible
|
lib/ansible/modules/network/fortios/fortios_system_replacemsg_traffic_quota.py
|
#!/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_system_replacemsg_traffic_quota
short_description: Replacement messages 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 system_replacemsg feature and traffic_quota category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.9"
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
state:
description:
- Indicates whether to create or remove the object.
type: str
required: true
choices:
- present
- absent
system_replacemsg_traffic_quota:
description:
- Replacement messages.
default: null
type: dict
suboptions:
buffer:
description:
- Message string.
type: str
format:
description:
- Format flag.
type: str
choices:
- none
- text
- html
- wml
header:
description:
- Header flag.
type: str
choices:
- none
- http
- 8bit
msg_type:
description:
- Message type.
type: str
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Replacement messages.
fortios_system_replacemsg_traffic_quota:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
https: "False"
state: "present"
system_replacemsg_traffic_quota:
buffer: "<your_own_value>"
format: "none"
header: "none"
msg_type: "<your_own_value>"
'''
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_system_replacemsg_traffic_quota_data(json):
option_list = ['buffer', 'format', 'header',
'msg_type']
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 elem in data:
elem = 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 system_replacemsg_traffic_quota(data, fos):
vdom = data['vdom']
state = data['state']
system_replacemsg_traffic_quota_data = data['system_replacemsg_traffic_quota']
filtered_data = underscore_to_hyphen(filter_system_replacemsg_traffic_quota_data(system_replacemsg_traffic_quota_data))
if state == "present":
return fos.set('system.replacemsg',
'traffic-quota',
data=filtered_data,
vdom=vdom)
elif state == "absent":
return fos.delete('system.replacemsg',
'traffic-quota',
mkey=filtered_data['msg-type'],
vdom=vdom)
def is_successful_status(status):
return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
def fortios_system_replacemsg(data, fos):
if data['system_replacemsg_traffic_quota']:
resp = system_replacemsg_traffic_quota(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},
"state": {"required": True, "type": "str",
"choices": ["present", "absent"]},
"system_replacemsg_traffic_quota": {
"required": False, "type": "dict", "default": None,
"options": {
"buffer": {"required": False, "type": "str"},
"format": {"required": False, "type": "str",
"choices": ["none", "text", "html",
"wml"]},
"header": {"required": False, "type": "str",
"choices": ["none", "http", "8bit"]},
"msg_type": {"required": False, "type": "str"}
}
}
}
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_system_replacemsg(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_system_replacemsg(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()
|
andrius-preimantas/purchase-workflow
|
purchase_order_force_number/__openerp__.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': "Purchase orders - Force number",
'version': '0.1',
'category': 'Purchase Management',
'summary': "Force purchase orders numeration",
'description': """
This simple module allows to specify the number to use when creating purchase
orders. If user does not change the default value ('/'), the standard sequence
is used.""",
'author': "Agile Business Group,Odoo Community Association (OCA)",
'website': 'http://www.agilebg.com',
'license': 'AGPL-3',
"depends": ['purchase'],
"data": [
'purchase_view.xml',
],
"demo": [],
"active": False,
"installable": False
}
|
dragorosson/heat
|
heat/db/sqlalchemy/migrate_repo/versions/064_raw_template_predecessor.py
|
#
# 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 migrate
import sqlalchemy
from heat.db.sqlalchemy import utils as migrate_utils
def upgrade(migrate_engine):
if migrate_engine.name == 'sqlite':
upgrade_sqlite(migrate_engine)
return
meta = sqlalchemy.MetaData()
meta.bind = migrate_engine
tmpl_table = sqlalchemy.Table('raw_template', meta, autoload=True)
# drop constraint
fkey = migrate.ForeignKeyConstraint(
columns=[tmpl_table.c.predecessor],
refcolumns=[tmpl_table.c.id],
name='predecessor_fkey_ref')
fkey.drop()
tmpl_table.c.predecessor.drop()
def upgrade_sqlite(migrate_engine):
meta = sqlalchemy.MetaData()
meta.bind = migrate_engine
tmpl_table = sqlalchemy.Table('raw_template', meta, autoload=True)
ignorecols = [tmpl_table.c.predecessor.name]
new_template = migrate_utils.clone_table('new_raw_template',
tmpl_table,
meta, ignorecols=ignorecols)
# migrate stacks to new table
migrate_utils.migrate_data(migrate_engine,
tmpl_table,
new_template,
skip_columns=['predecessor'])
|
charris/numpy
|
numpy/lib/mixins.py
|
"""Mixin classes for custom array types that don't inherit from ndarray."""
from numpy.core import umath as um
__all__ = ['NDArrayOperatorsMixin']
def _disables_array_ufunc(obj):
"""True when __array_ufunc__ is set to None."""
try:
return obj.__array_ufunc__ is None
except AttributeError:
return False
def _binary_method(ufunc, name):
"""Implement a forward binary method with a ufunc, e.g., __add__."""
def func(self, other):
if _disables_array_ufunc(other):
return NotImplemented
return ufunc(self, other)
func.__name__ = '__{}__'.format(name)
return func
def _reflected_binary_method(ufunc, name):
"""Implement a reflected binary method with a ufunc, e.g., __radd__."""
def func(self, other):
if _disables_array_ufunc(other):
return NotImplemented
return ufunc(other, self)
func.__name__ = '__r{}__'.format(name)
return func
def _inplace_binary_method(ufunc, name):
"""Implement an in-place binary method with a ufunc, e.g., __iadd__."""
def func(self, other):
return ufunc(self, other, out=(self,))
func.__name__ = '__i{}__'.format(name)
return func
def _numeric_methods(ufunc, name):
"""Implement forward, reflected and inplace binary methods with a ufunc."""
return (_binary_method(ufunc, name),
_reflected_binary_method(ufunc, name),
_inplace_binary_method(ufunc, name))
def _unary_method(ufunc, name):
"""Implement a unary special method with a ufunc."""
def func(self):
return ufunc(self)
func.__name__ = '__{}__'.format(name)
return func
class NDArrayOperatorsMixin:
"""Mixin defining all operator special methods using __array_ufunc__.
This class implements the special methods for almost all of Python's
builtin operators defined in the `operator` module, including comparisons
(``==``, ``>``, etc.) and arithmetic (``+``, ``*``, ``-``, etc.), by
deferring to the ``__array_ufunc__`` method, which subclasses must
implement.
It is useful for writing classes that do not inherit from `numpy.ndarray`,
but that should support arithmetic and numpy universal functions like
arrays as described in `A Mechanism for Overriding Ufuncs
<https://numpy.org/neps/nep-0013-ufunc-overrides.html>`_.
As an trivial example, consider this implementation of an ``ArrayLike``
class that simply wraps a NumPy array and ensures that the result of any
arithmetic operation is also an ``ArrayLike`` object::
class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin):
def __init__(self, value):
self.value = np.asarray(value)
# One might also consider adding the built-in list type to this
# list, to support operations like np.add(array_like, list)
_HANDLED_TYPES = (np.ndarray, numbers.Number)
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
out = kwargs.get('out', ())
for x in inputs + out:
# Only support operations with instances of _HANDLED_TYPES.
# Use ArrayLike instead of type(self) for isinstance to
# allow subclasses that don't override __array_ufunc__ to
# handle ArrayLike objects.
if not isinstance(x, self._HANDLED_TYPES + (ArrayLike,)):
return NotImplemented
# Defer to the implementation of the ufunc on unwrapped values.
inputs = tuple(x.value if isinstance(x, ArrayLike) else x
for x in inputs)
if out:
kwargs['out'] = tuple(
x.value if isinstance(x, ArrayLike) else x
for x in out)
result = getattr(ufunc, method)(*inputs, **kwargs)
if type(result) is tuple:
# multiple return values
return tuple(type(self)(x) for x in result)
elif method == 'at':
# no return value
return None
else:
# one return value
return type(self)(result)
def __repr__(self):
return '%s(%r)' % (type(self).__name__, self.value)
In interactions between ``ArrayLike`` objects and numbers or numpy arrays,
the result is always another ``ArrayLike``:
>>> x = ArrayLike([1, 2, 3])
>>> x - 1
ArrayLike(array([0, 1, 2]))
>>> 1 - x
ArrayLike(array([ 0, -1, -2]))
>>> np.arange(3) - x
ArrayLike(array([-1, -1, -1]))
>>> x - np.arange(3)
ArrayLike(array([1, 1, 1]))
Note that unlike ``numpy.ndarray``, ``ArrayLike`` does not allow operations
with arbitrary, unrecognized types. This ensures that interactions with
ArrayLike preserve a well-defined casting hierarchy.
.. versionadded:: 1.13
"""
# Like np.ndarray, this mixin class implements "Option 1" from the ufunc
# overrides NEP.
# comparisons don't have reflected and in-place versions
__lt__ = _binary_method(um.less, 'lt')
__le__ = _binary_method(um.less_equal, 'le')
__eq__ = _binary_method(um.equal, 'eq')
__ne__ = _binary_method(um.not_equal, 'ne')
__gt__ = _binary_method(um.greater, 'gt')
__ge__ = _binary_method(um.greater_equal, 'ge')
# numeric methods
__add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add')
__sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub')
__mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul')
__matmul__, __rmatmul__, __imatmul__ = _numeric_methods(
um.matmul, 'matmul')
# Python 3 does not use __div__, __rdiv__, or __idiv__
__truediv__, __rtruediv__, __itruediv__ = _numeric_methods(
um.true_divide, 'truediv')
__floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(
um.floor_divide, 'floordiv')
__mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod')
__divmod__ = _binary_method(um.divmod, 'divmod')
__rdivmod__ = _reflected_binary_method(um.divmod, 'divmod')
# __idivmod__ does not exist
# TODO: handle the optional third argument for __pow__?
__pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow')
__lshift__, __rlshift__, __ilshift__ = _numeric_methods(
um.left_shift, 'lshift')
__rshift__, __rrshift__, __irshift__ = _numeric_methods(
um.right_shift, 'rshift')
__and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and')
__xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor')
__or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or')
# unary methods
__neg__ = _unary_method(um.negative, 'neg')
__pos__ = _unary_method(um.positive, 'pos')
__abs__ = _unary_method(um.absolute, 'abs')
__invert__ = _unary_method(um.invert, 'invert')
|
thaim/ansible
|
lib/ansible/modules/cloud/google/gcp_resourcemanager_project.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file at
# https://www.github.com/GoogleCloudPlatform/magic-modules
#
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_resourcemanager_project
description:
- Represents a GCP Project. A project is a container for ACLs, APIs, App Engine Apps,
VMs, and other Google Cloud Platform resources.
short_description: Creates a GCP Project
version_added: '2.8'
author: Google Inc. (@googlecloudplatform)
requirements:
- python >= 2.6
- requests >= 2.18.4
- google-auth >= 1.3.0
options:
state:
description:
- Whether the given object should exist in GCP
choices:
- present
- absent
default: present
type: str
name:
description:
- 'The user-assigned display name of the Project. It must be 4 to 30 characters.
Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote,
double-quote, space, and exclamation point.'
required: false
type: str
labels:
description:
- The labels associated with this Project.
- 'Label keys must be between 1 and 63 characters long and must conform to the
following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`.'
- Label values must be between 0 and 63 characters long and must conform to the
regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`.
- No more than 256 labels can be associated with a given resource.
- Clients should store labels in a representation such as JSON that does not depend
on specific characters being disallowed .
required: false
type: dict
parent:
description:
- A parent organization.
required: false
type: dict
suboptions:
type:
description:
- Must be organization.
required: false
type: str
id:
description:
- Id of the organization.
required: false
type: str
id:
description:
- The unique, user-assigned ID of the Project. It must be 6 to 30 lowercase letters,
digits, or hyphens. It must start with a letter.
- Trailing hyphens are prohibited.
required: true
type: str
project:
description:
- The Google Cloud Platform project to use.
type: str
auth_kind:
description:
- The type of credential used.
type: str
required: true
choices:
- application
- machineaccount
- serviceaccount
service_account_contents:
description:
- The contents of a Service Account JSON file, either in a dictionary or as a
JSON string that represents it.
type: jsonarg
service_account_file:
description:
- The path of a Service Account JSON file if serviceaccount is selected as type.
type: path
service_account_email:
description:
- An optional service account email address if machineaccount is selected and
the user does not wish to use the default email.
type: str
scopes:
description:
- Array of scopes to be used
type: list
env_type:
description:
- Specifies which Ansible environment you're running this module within.
- This should not be set unless you know what you're doing.
- This only alters the User Agent string for any API requests.
type: str
'''
EXAMPLES = '''
- name: create a project
gcp_resourcemanager_project:
name: My Sample Project
id: alextest-{{ 10000000000 | random }}
auth_kind: serviceaccount
service_account_file: "/tmp/auth.pem"
parent:
type: organization
id: 636173955921
state: present
'''
RETURN = '''
number:
description:
- Number uniquely identifying the project.
returned: success
type: int
lifecycleState:
description:
- The Project lifecycle state.
returned: success
type: str
name:
description:
- 'The user-assigned display name of the Project. It must be 4 to 30 characters.
Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote,
double-quote, space, and exclamation point.'
returned: success
type: str
createTime:
description:
- Time of creation.
returned: success
type: str
labels:
description:
- The labels associated with this Project.
- 'Label keys must be between 1 and 63 characters long and must conform to the following
regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`.'
- Label values must be between 0 and 63 characters long and must conform to the
regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`.
- No more than 256 labels can be associated with a given resource.
- Clients should store labels in a representation such as JSON that does not depend
on specific characters being disallowed .
returned: success
type: dict
parent:
description:
- A parent organization.
returned: success
type: complex
contains:
type:
description:
- Must be organization.
returned: success
type: str
id:
description:
- Id of the organization.
returned: success
type: str
id:
description:
- The unique, user-assigned ID of the Project. It must be 6 to 30 lowercase letters,
digits, or hyphens. It must start with a letter.
- Trailing hyphens are prohibited.
returned: success
type: str
'''
################################################################################
# Imports
################################################################################
from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict
import json
import time
################################################################################
# Main
################################################################################
def main():
"""Main function"""
module = GcpModule(
argument_spec=dict(
state=dict(default='present', choices=['present', 'absent'], type='str'),
name=dict(type='str'),
labels=dict(type='dict'),
parent=dict(type='dict', options=dict(type=dict(type='str'), id=dict(type='str'))),
id=dict(required=True, type='str'),
)
)
if not module.params['scopes']:
module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform']
state = module.params['state']
fetch = fetch_resource(module, self_link(module))
changed = False
if fetch:
if state == 'present':
if is_different(module, fetch):
update(module, self_link(module))
fetch = fetch_resource(module, self_link(module))
changed = True
else:
delete(module, self_link(module))
fetch = {}
changed = True
else:
if state == 'present':
fetch = create(module, collection(module))
changed = True
else:
fetch = {}
fetch.update({'changed': changed})
module.exit_json(**fetch)
def create(module, link):
auth = GcpSession(module, 'resourcemanager')
return wait_for_operation(module, auth.post(link, resource_to_request(module)))
def update(module, link):
auth = GcpSession(module, 'resourcemanager')
return wait_for_operation(module, auth.put(link, resource_to_request(module)))
def delete(module, link):
auth = GcpSession(module, 'resourcemanager')
return wait_for_operation(module, auth.delete(link))
def resource_to_request(module):
request = {
u'projectId': module.params.get('id'),
u'name': module.params.get('name'),
u'labels': module.params.get('labels'),
u'parent': ProjectParent(module.params.get('parent', {}), module).to_request(),
}
return_vals = {}
for k, v in request.items():
if v or v is False:
return_vals[k] = v
return return_vals
def fetch_resource(module, link, allow_not_found=True):
auth = GcpSession(module, 'resourcemanager')
return return_if_object(module, auth.get(link), allow_not_found)
def self_link(module):
return "https://cloudresourcemanager.googleapis.com/v1/projects/{id}".format(**module.params)
def collection(module):
return "https://cloudresourcemanager.googleapis.com/v1/projects".format(**module.params)
def return_if_object(module, response, allow_not_found=False):
# If not found, return nothing.
if allow_not_found and response.status_code == 404:
return None
# If no content, return nothing.
if response.status_code == 204:
return None
# SQL only: return on 403 if not exist
if allow_not_found and response.status_code == 403:
return None
try:
result = response.json()
except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
module.fail_json(msg="Invalid JSON response with error: %s" % inst)
if navigate_hash(result, ['error', 'message']):
module.fail_json(msg=navigate_hash(result, ['error', 'message']))
return result
def is_different(module, response):
request = resource_to_request(module)
response = response_to_hash(module, response)
# Remove all output-only from response.
response_vals = {}
for k, v in response.items():
if k in request:
response_vals[k] = v
request_vals = {}
for k, v in request.items():
if k in response:
request_vals[k] = v
return GcpRequest(request_vals) != GcpRequest(response_vals)
# Remove unnecessary properties from the response.
# This is for doing comparisons with Ansible's current parameters.
def response_to_hash(module, response):
return {
u'projectNumber': response.get(u'projectNumber'),
u'lifecycleState': response.get(u'lifecycleState'),
u'name': response.get(u'name'),
u'createTime': response.get(u'createTime'),
u'labels': response.get(u'labels'),
u'parent': ProjectParent(response.get(u'parent', {}), module).from_response(),
}
def async_op_url(module, extra_data=None):
if extra_data is None:
extra_data = {}
url = "https://cloudresourcemanager.googleapis.com/v1/{op_id}"
combined = extra_data.copy()
combined.update(module.params)
return url.format(**combined)
def wait_for_operation(module, response):
op_result = return_if_object(module, response)
if op_result is None:
return {}
status = navigate_hash(op_result, ['done'])
wait_done = wait_for_completion(status, op_result, module)
raise_if_errors(wait_done, ['error'], module)
return navigate_hash(wait_done, ['response'])
def wait_for_completion(status, op_result, module):
op_id = navigate_hash(op_result, ['name'])
op_uri = async_op_url(module, {'op_id': op_id})
while not status:
raise_if_errors(op_result, ['error'], module)
time.sleep(1.0)
op_result = fetch_resource(module, op_uri, False)
status = navigate_hash(op_result, ['done'])
return op_result
def raise_if_errors(response, err_path, module):
errors = navigate_hash(response, err_path)
if errors is not None:
module.fail_json(msg=errors)
class ProjectParent(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict({u'type': self.request.get('type'), u'id': self.request.get('id')})
def from_response(self):
return remove_nones_from_dict({u'type': self.request.get(u'type'), u'id': self.request.get(u'id')})
if __name__ == '__main__':
main()
|
infilect/ml-course1
|
week4/attention_ocr/python/datasets/unittest_utils.py
|
# Copyright 2017 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions to make unit testing easier."""
import StringIO
import numpy as np
from PIL import Image as PILImage
import tensorflow as tf
def create_random_image(image_format, shape):
"""Creates an image with random values.
Args:
image_format: An image format (PNG or JPEG).
shape: A tuple with image shape (including channels).
Returns:
A tuple (<numpy ndarray>, <a string with encoded image>)
"""
image = np.random.randint(low=0, high=255, size=shape, dtype='uint8')
io = StringIO.StringIO()
image_pil = PILImage.fromarray(image)
image_pil.save(io, image_format, subsampling=0, quality=100)
return image, io.getvalue()
def create_serialized_example(name_to_values):
"""Creates a tf.Example proto using a dictionary.
It automatically detects type of values and define a corresponding feature.
Args:
name_to_values: A dictionary.
Returns:
tf.Example proto.
"""
example = tf.train.Example()
for name, values in name_to_values.items():
feature = example.features.feature[name]
if isinstance(values[0], str):
add = feature.bytes_list.value.extend
elif isinstance(values[0], float):
add = feature.float32_list.value.extend
elif isinstance(values[0], int):
add = feature.int64_list.value.extend
else:
raise AssertionError('Unsupported type: %s' % type(values[0]))
add(values)
return example.SerializeToString()
|
emersonsoftware/ansiblefork
|
lib/ansible/galaxy/role.py
|
########################################################################
#
# (C) 2015, Brian Coca <bcoca@ansible.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/>.
#
########################################################################
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import os
import tarfile
import tempfile
import yaml
from distutils.version import LooseVersion
from shutil import rmtree
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement
from ansible.galaxy.api import GalaxyAPI
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class GalaxyRole(object):
SUPPORTED_SCMS = set(['git', 'hg'])
META_MAIN = os.path.join('meta', 'main.yml')
META_INSTALL = os.path.join('meta', '.galaxy_install_info')
ROLE_DIRS = ('defaults','files','handlers','meta','tasks','templates','vars','tests')
def __init__(self, galaxy, name, src=None, version=None, scm=None, path=None):
self._metadata = None
self._install_info = None
self._validate_certs = not galaxy.options.ignore_certs
display.debug('Validate TLS certificates: %s' % self._validate_certs)
self.options = galaxy.options
self.galaxy = galaxy
self.name = name
self.version = version
self.src = src or name
self.scm = scm
if path is not None:
if self.name not in path:
path = os.path.join(path, self.name)
self.path = path
else:
for role_path_dir in galaxy.roles_paths:
role_path = os.path.join(role_path_dir, self.name)
if os.path.exists(role_path):
self.path = role_path
break
else:
# use the first path by default
self.path = os.path.join(galaxy.roles_paths[0], self.name)
# create list of possible paths
self.paths = [x for x in galaxy.roles_paths]
self.paths = [os.path.join(x, self.name) for x in self.paths]
def __repr__(self):
"""
Returns "rolename (version)" if version is not null
Returns "rolename" otherwise
"""
if self.version:
return "%s (%s)" % (self.name, self.version)
else:
return self.name
def __eq__(self, other):
return self.name == other.name
@property
def metadata(self):
"""
Returns role metadata
"""
if self._metadata is None:
meta_path = os.path.join(self.path, self.META_MAIN)
if os.path.isfile(meta_path):
try:
f = open(meta_path, 'r')
self._metadata = yaml.safe_load(f)
except:
display.vvvvv("Unable to load metadata for %s" % self.name)
return False
finally:
f.close()
return self._metadata
@property
def install_info(self):
"""
Returns role install info
"""
if self._install_info is None:
info_path = os.path.join(self.path, self.META_INSTALL)
if os.path.isfile(info_path):
try:
f = open(info_path, 'r')
self._install_info = yaml.safe_load(f)
except:
display.vvvvv("Unable to load Galaxy install info for %s" % self.name)
return False
finally:
f.close()
return self._install_info
def _write_galaxy_install_info(self):
"""
Writes a YAML-formatted file to the role's meta/ directory
(named .galaxy_install_info) which contains some information
we can use later for commands like 'list' and 'info'.
"""
info = dict(
version=self.version,
install_date=datetime.datetime.utcnow().strftime("%c"),
)
if not os.path.exists(os.path.join(self.path, 'meta')):
os.makedirs(os.path.join(self.path, 'meta'))
info_path = os.path.join(self.path, self.META_INSTALL)
with open(info_path, 'w+') as f:
try:
self._install_info = yaml.safe_dump(info, f)
except:
return False
return True
def remove(self):
"""
Removes the specified role from the roles path.
There is a sanity check to make sure there's a meta/main.yml file at this
path so the user doesn't blow away random directories.
"""
if self.metadata:
try:
rmtree(self.path)
return True
except:
pass
return False
def fetch(self, role_data):
"""
Downloads the archived role from github to a temp location
"""
if role_data:
# first grab the file and save it to a temp location
if "github_user" in role_data and "github_repo" in role_data:
archive_url = 'https://github.com/%s/%s/archive/%s.tar.gz' % (role_data["github_user"], role_data["github_repo"], self.version)
else:
archive_url = self.src
display.display("- downloading role from %s" % archive_url)
try:
url_file = open_url(archive_url, validate_certs=self._validate_certs)
temp_file = tempfile.NamedTemporaryFile(delete=False)
data = url_file.read()
while data:
temp_file.write(data)
data = url_file.read()
temp_file.close()
return temp_file.name
except Exception as e:
display.error("failed to download the file: %s" % str(e))
return False
def install(self):
# the file is a tar, so open it that way and extract it
# to the specified (or default) roles directory
local_file = False
if self.scm:
# create tar file from scm url
tmp_file = RoleRequirement.scm_archive_role(**self.spec)
elif self.src:
if os.path.isfile(self.src):
# installing a local tar.gz
local_file = True
tmp_file = self.src
elif '://' in self.src:
role_data = self.src
tmp_file = self.fetch(role_data)
else:
api = GalaxyAPI(self.galaxy)
role_data = api.lookup_role_by_name(self.src)
if not role_data:
raise AnsibleError("- sorry, %s was not found on %s." % (self.src, api.api_server))
if role_data.get('role_type') == 'CON' and not os.environ.get('ANSIBLE_CONTAINER'):
# Container Enabled, running outside of a container
display.warning("%s is a Container Enabled role and should only be installed using "
"Ansible Container" % self.name)
if role_data.get('role_type') == 'APP':
# Container Role
display.warning("%s is a Container App role and should only be installed using Ansible "
"Container" % self.name)
role_versions = api.fetch_role_related('versions', role_data['id'])
if not self.version:
# convert the version names to LooseVersion objects
# and sort them to get the latest version. If there
# are no versions in the list, we'll grab the head
# of the master branch
if len(role_versions) > 0:
loose_versions = [LooseVersion(a.get('name',None)) for a in role_versions]
loose_versions.sort()
self.version = str(loose_versions[-1])
elif role_data.get('github_branch', None):
self.version = role_data['github_branch']
else:
self.version = 'master'
elif self.version != 'master':
if role_versions and str(self.version) not in [a.get('name', None) for a in role_versions]:
raise AnsibleError("- the specified version (%s) of %s was not found in the list of available versions (%s)." % (self.version, self.name, role_versions))
tmp_file = self.fetch(role_data)
else:
raise AnsibleError("No valid role data found")
if tmp_file:
display.debug("installing from %s" % tmp_file)
if not tarfile.is_tarfile(tmp_file):
raise AnsibleError("the file downloaded was not a tar.gz")
else:
if tmp_file.endswith('.gz'):
role_tar_file = tarfile.open(tmp_file, "r:gz")
else:
role_tar_file = tarfile.open(tmp_file, "r")
# verify the role's meta file
meta_file = None
members = role_tar_file.getmembers()
# next find the metadata file
for member in members:
if self.META_MAIN in member.name:
meta_file = member
break
if not meta_file:
raise AnsibleError("this role does not appear to have a meta/main.yml file.")
else:
try:
self._metadata = yaml.safe_load(role_tar_file.extractfile(meta_file))
except:
raise AnsibleError("this role does not appear to have a valid meta/main.yml file.")
# we strip off the top-level directory for all of the files contained within
# the tar file here, since the default is 'github_repo-target', and change it
# to the specified role's name
installed = False
while not installed:
display.display("- extracting %s to %s" % (self.name, self.path))
try:
if os.path.exists(self.path):
if not os.path.isdir(self.path):
raise AnsibleError("the specified roles path exists and is not a directory.")
elif not getattr(self.options, "force", False):
raise AnsibleError("the specified role %s appears to already exist. Use --force to replace it." % self.name)
else:
# using --force, remove the old path
if not self.remove():
raise AnsibleError("%s doesn't appear to contain a role.\n please remove this directory manually if you really want to put the role here." % self.path)
else:
os.makedirs(self.path)
# now we do the actual extraction to the path
for member in members:
# we only extract files, and remove any relative path
# bits that might be in the file for security purposes
# and drop the leading directory, as mentioned above
if member.isreg() or member.issym():
parts = member.name.split(os.sep)[1:]
final_parts = []
for part in parts:
if part != '..' and '~' not in part and '$' not in part:
final_parts.append(part)
member.name = os.path.join(*final_parts)
role_tar_file.extract(member, self.path)
# write out the install info file for later use
self._write_galaxy_install_info()
installed = True
except OSError as e:
error = True
if e[0] == 13 and len(self.paths) > 1:
current = self.paths.index(self.path)
nextidx = current + 1
if len(self.paths) >= current:
self.path = self.paths[nextidx]
error = False
if error:
raise AnsibleError("Could not update files in %s: %s" % (self.path, str(e)))
# return the parsed yaml metadata
display.display("- %s was installed successfully" % str(self))
if not local_file:
try:
os.unlink(tmp_file)
except (OSError,IOError) as e:
display.warning("Unable to remove tmp file (%s): %s" % (tmp_file, str(e)))
return True
return False
@property
def spec(self):
"""
Returns role spec info
{
'scm': 'git',
'src': 'http://git.example.com/repos/repo.git',
'version': 'v1.0',
'name': 'repo'
}
"""
return dict(scm=self.scm, src=self.src, version=self.version, name=self.name)
|
likelyzhao/mxnet
|
example/speech-demo/io_func/feat_readers/common.py
|
import numpy
import os
class ByteOrder:
LittleEndian, BigEndian = range(2)
class FeatureException(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
def ReadLabel(filename):
labels = numpy.loadtxt(filename, ndmin=1)
return labels.astype(numpy.int32)
class BaseReader():
def __init__(self, featureFile, labelFile, byteOrder=None):
self.byteOrder = byteOrder
self.featureFile = featureFile
self.labelFile = labelFile
self.done = False
def _markDone(self):
self.done = True
def IsDone(self):
return self.done
def Read(self):
pass
def Cleanup(self):
pass
# no slashes or weird characters
def GetUttId(self):
return os.path.basename(self.featureFile)
def getReader(fileformat, featureFile, labelFile):
if fileformat.lower() == 'htk':
import reader_htk
return reader_htk.htkReader(featureFile, labelFile, ByteOrder.BigEndian)
elif fileformat.lower() == 'htk_little':
import reader_htk
return reader_htk.htkReader(featureFile, labelFile, ByteOrder.LittleEndian)
elif fileformat.lower() == 'bvec':
import reader_bvec
return reader_bvec.bvecReader(featureFile, labelFile)
elif fileformat.lower() == 'atrack':
import reader_atrack
return reader_atrack.atrackReader(featureFile, labelFile)
elif fileformat.lower() == 'kaldi':
import reader_kaldi
return reader_kaldi.kaldiReader(featureFile, labelFile)
else:
msg = "Error: Specified format '{}' is not supported".format(fileformat)
raise Exception(msg)
|
OpenUpgrade-dev/OpenUpgrade
|
addons/fleet/migrations/8.0.0.1/post_migration.py
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Akretion
# (<http://www.akretion.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import pooler, SUPERUSER_ID
from openerp.openupgrade import openupgrade, openupgrade_80
@openupgrade.migrate()
def migrate(cr, version):
pool = pooler.get_pool(cr.dbname)
uid = SUPERUSER_ID
openupgrade_80.set_message_last_post(
cr, uid, pool, ['fleet.vehicule']
)
|
Tesora/tesora-tempest
|
tempest/api/compute/test_extensions.py
|
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from tempest.api.compute import base
from tempest import config
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class ExtensionsTestJSON(base.BaseV2ComputeTest):
@test.idempotent_id('3bb27738-b759-4e0d-a5fa-37d7a6df07d1')
def test_list_extensions(self):
# List of all extensions
if len(CONF.compute_feature_enabled.api_extensions) == 0:
raise self.skipException('There are not any extensions configured')
extensions = self.extensions_client.list_extensions()['extensions']
ext = CONF.compute_feature_enabled.api_extensions[0]
if ext == 'all':
self.assertIn('Hosts', map(lambda x: x['name'], extensions))
elif ext:
self.assertIn(ext, map(lambda x: x['alias'], extensions))
else:
raise self.skipException('There are not any extensions configured')
# Log extensions list
extension_list = map(lambda x: x['alias'], extensions)
LOG.debug("Nova extensions: %s" % ','.join(extension_list))
@test.idempotent_id('05762f39-bdfa-4cdb-9b46-b78f8e78e2fd')
@test.requires_ext(extension='os-consoles', service='compute')
def test_get_extension(self):
# get the specified extensions
extension = self.extensions_client.show_extension('os-consoles')
self.assertEqual('os-consoles', extension['extension']['alias'])
|
orvi2014/kitsune
|
kitsune/kbadge/tasks.py
|
from django.conf import settings
from django.contrib.sites.models import Site
from celery import task
from tower import ugettext as _
from kitsune.sumo.decorators import timeit
from kitsune.sumo import email_utils
@task()
@timeit
def send_award_notification(award):
"""Sends the award notification email
:arg award: the django-badger Award instance
"""
@email_utils.safe_translation
def _make_mail(locale, context, email):
subject = _(u"You were awarded the '{title}' badge!").format(
title=_(award.badge.title, 'DB: badger.Badge.title'))
mail = email_utils.make_mail(
subject=subject,
text_template='kbadge/email/award_notification.ltxt',
html_template='kbadge/email/award_notification.html',
context_vars=context,
from_email=settings.DEFAULT_FROM_EMAIL,
to_email=email)
return mail
msg = _make_mail(
locale=award.user.profile.locale,
context={
'host': Site.objects.get_current().domain,
'award': award,
'badge': award.badge,
},
email=award.user.email
)
# FIXME: this sends emails to the person who was awarded the
# badge. Should we also send an email to the person who awarded
# the badge? Currently, I think we shouldn't.
email_utils.send_messages([msg])
|
inclement/kivy
|
kivy/uix/behaviors/button.py
|
'''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons that preserve Kivy button behavior.
For an overview of behaviors, please refer to the :mod:`~kivy.uix.behaviors`
documentation.
Example
-------
The following example adds button behavior to an image to make a checkbox that
behaves like a button::
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.behaviors import ButtonBehavior
class MyButton(ButtonBehavior, Image):
def __init__(self, **kwargs):
super(MyButton, self).__init__(**kwargs)
self.source = 'atlas://data/images/defaulttheme/checkbox_off'
def on_press(self):
self.source = 'atlas://data/images/defaulttheme/checkbox_on'
def on_release(self):
self.source = 'atlas://data/images/defaulttheme/checkbox_off'
class SampleApp(App):
def build(self):
return MyButton()
SampleApp().run()
See :class:`~kivy.uix.behaviors.ButtonBehavior` for details.
'''
__all__ = ('ButtonBehavior', )
from kivy.clock import Clock
from kivy.config import Config
from kivy.properties import OptionProperty, ObjectProperty, \
BooleanProperty, NumericProperty
from time import time
class ButtonBehavior(object):
'''
This `mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. Please see the
:mod:`button behaviors module <kivy.uix.behaviors.button>` documentation
for more information.
:Events:
`on_press`
Fired when the button is pressed.
`on_release`
Fired when the button is released (i.e. the touch/click that
pressed the button goes away).
'''
state = OptionProperty('normal', options=('normal', 'down'))
'''The state of the button, must be one of 'normal' or 'down'.
The state is 'down' only when the button is currently touched/clicked,
otherwise its 'normal'.
:attr:`state` is an :class:`~kivy.properties.OptionProperty` and defaults
to 'normal'.
'''
last_touch = ObjectProperty(None)
'''Contains the last relevant touch received by the Button. This can
be used in `on_press` or `on_release` in order to know which touch
dispatched the event.
.. versionadded:: 1.8.0
:attr:`last_touch` is a :class:`~kivy.properties.ObjectProperty` and
defaults to `None`.
'''
min_state_time = NumericProperty(0)
'''The minimum period of time which the widget must remain in the
`'down'` state.
.. versionadded:: 1.9.1
:attr:`min_state_time` is a float and defaults to 0.035. This value is
taken from :class:`~kivy.config.Config`.
'''
always_release = BooleanProperty(False)
'''This determines whether or not the widget fires an `on_release` event if
the touch_up is outside the widget.
.. versionadded:: 1.9.0
.. versionchanged:: 1.10.0
The default value is now False.
:attr:`always_release` is a :class:`~kivy.properties.BooleanProperty` and
defaults to `False`.
'''
def __init__(self, **kwargs):
self.register_event_type('on_press')
self.register_event_type('on_release')
if 'min_state_time' not in kwargs:
self.min_state_time = float(Config.get('graphics',
'min_state_time'))
super(ButtonBehavior, self).__init__(**kwargs)
self.__state_event = None
self.__touch_time = None
self.fbind('state', self.cancel_event)
def _do_press(self):
self.state = 'down'
def _do_release(self, *args):
self.state = 'normal'
def cancel_event(self, *args):
if self.__state_event:
self.__state_event.cancel()
self.__state_event = None
def on_touch_down(self, touch):
if super(ButtonBehavior, self).on_touch_down(touch):
return True
if touch.is_mouse_scrolling:
return False
if not self.collide_point(touch.x, touch.y):
return False
if self in touch.ud:
return False
touch.grab(self)
touch.ud[self] = True
self.last_touch = touch
self.__touch_time = time()
self._do_press()
self.dispatch('on_press')
return True
def on_touch_move(self, touch):
if touch.grab_current is self:
return True
if super(ButtonBehavior, self).on_touch_move(touch):
return True
return self in touch.ud
def on_touch_up(self, touch):
if touch.grab_current is not self:
return super(ButtonBehavior, self).on_touch_up(touch)
assert(self in touch.ud)
touch.ungrab(self)
self.last_touch = touch
if (not self.always_release and
not self.collide_point(*touch.pos)):
self._do_release()
return
touchtime = time() - self.__touch_time
if touchtime < self.min_state_time:
self.__state_event = Clock.schedule_once(
self._do_release, self.min_state_time - touchtime)
else:
self._do_release()
self.dispatch('on_release')
return True
def on_press(self):
pass
def on_release(self):
pass
def trigger_action(self, duration=0.1):
'''Trigger whatever action(s) have been bound to the button by calling
both the on_press and on_release callbacks.
This simulates a quick button press without using any touch events.
Duration is the length of the press in seconds. Pass 0 if you want
the action to happen instantly.
.. versionadded:: 1.8.0
'''
self._do_press()
self.dispatch('on_press')
def trigger_release(dt):
self._do_release()
self.dispatch('on_release')
if not duration:
trigger_release(0)
else:
Clock.schedule_once(trigger_release, duration)
|
keen99/SickRage
|
tornado/test/gen_test.py
|
from __future__ import absolute_import, division, print_function, with_statement
import contextlib
import datetime
import functools
import sys
import textwrap
import time
import platform
import weakref
from tornado.concurrent import return_future, Future
from tornado.escape import url_escape
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop
from tornado.log import app_log
from tornado import stack_context
from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test
from tornado.test.util import unittest, skipOnTravis
from tornado.web import Application, RequestHandler, asynchronous, HTTPError
from tornado import gen
try:
from concurrent import futures
except ImportError:
futures = None
skipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')
skipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',
'Not CPython implementation')
class GenEngineTest(AsyncTestCase):
def setUp(self):
super(GenEngineTest, self).setUp()
self.named_contexts = []
def named_context(self, name):
@contextlib.contextmanager
def context():
self.named_contexts.append(name)
try:
yield
finally:
self.assertEqual(self.named_contexts.pop(), name)
return context
def run_gen(self, f):
f()
return self.wait()
def delay_callback(self, iterations, callback, arg):
"""Runs callback(arg) after a number of IOLoop iterations."""
if iterations == 0:
callback(arg)
else:
self.io_loop.add_callback(functools.partial(
self.delay_callback, iterations - 1, callback, arg))
@return_future
def async_future(self, result, callback):
self.io_loop.add_callback(callback, result)
def test_no_yield(self):
@gen.engine
def f():
self.stop()
self.run_gen(f)
def test_inline_cb(self):
@gen.engine
def f():
(yield gen.Callback("k1"))()
res = yield gen.Wait("k1")
self.assertTrue(res is None)
self.stop()
self.run_gen(f)
def test_ioloop_cb(self):
@gen.engine
def f():
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.stop()
self.run_gen(f)
def test_exception_phase1(self):
@gen.engine
def f():
1 / 0
self.assertRaises(ZeroDivisionError, self.run_gen, f)
def test_exception_phase2(self):
@gen.engine
def f():
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
1 / 0
self.assertRaises(ZeroDivisionError, self.run_gen, f)
def test_exception_in_task_phase1(self):
def fail_task(callback):
1 / 0
@gen.engine
def f():
try:
yield gen.Task(fail_task)
raise Exception("did not get expected exception")
except ZeroDivisionError:
self.stop()
self.run_gen(f)
def test_exception_in_task_phase2(self):
# This is the case that requires the use of stack_context in gen.engine
def fail_task(callback):
self.io_loop.add_callback(lambda: 1 / 0)
@gen.engine
def f():
try:
yield gen.Task(fail_task)
raise Exception("did not get expected exception")
except ZeroDivisionError:
self.stop()
self.run_gen(f)
def test_with_arg(self):
@gen.engine
def f():
(yield gen.Callback("k1"))(42)
res = yield gen.Wait("k1")
self.assertEqual(42, res)
self.stop()
self.run_gen(f)
def test_with_arg_tuple(self):
@gen.engine
def f():
(yield gen.Callback((1, 2)))((3, 4))
res = yield gen.Wait((1, 2))
self.assertEqual((3, 4), res)
self.stop()
self.run_gen(f)
def test_key_reuse(self):
@gen.engine
def f():
yield gen.Callback("k1")
yield gen.Callback("k1")
self.stop()
self.assertRaises(gen.KeyReuseError, self.run_gen, f)
def test_key_reuse_tuple(self):
@gen.engine
def f():
yield gen.Callback((1, 2))
yield gen.Callback((1, 2))
self.stop()
self.assertRaises(gen.KeyReuseError, self.run_gen, f)
def test_key_mismatch(self):
@gen.engine
def f():
yield gen.Callback("k1")
yield gen.Wait("k2")
self.stop()
self.assertRaises(gen.UnknownKeyError, self.run_gen, f)
def test_key_mismatch_tuple(self):
@gen.engine
def f():
yield gen.Callback((1, 2))
yield gen.Wait((2, 3))
self.stop()
self.assertRaises(gen.UnknownKeyError, self.run_gen, f)
def test_leaked_callback(self):
@gen.engine
def f():
yield gen.Callback("k1")
self.stop()
self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)
def test_leaked_callback_tuple(self):
@gen.engine
def f():
yield gen.Callback((1, 2))
self.stop()
self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)
def test_parallel_callback(self):
@gen.engine
def f():
for k in range(3):
self.io_loop.add_callback((yield gen.Callback(k)))
yield gen.Wait(1)
self.io_loop.add_callback((yield gen.Callback(3)))
yield gen.Wait(0)
yield gen.Wait(3)
yield gen.Wait(2)
self.stop()
self.run_gen(f)
def test_bogus_yield(self):
@gen.engine
def f():
yield 42
self.assertRaises(gen.BadYieldError, self.run_gen, f)
def test_bogus_yield_tuple(self):
@gen.engine
def f():
yield (1, 2)
self.assertRaises(gen.BadYieldError, self.run_gen, f)
def test_reuse(self):
@gen.engine
def f():
self.io_loop.add_callback((yield gen.Callback(0)))
yield gen.Wait(0)
self.stop()
self.run_gen(f)
self.run_gen(f)
def test_task(self):
@gen.engine
def f():
yield gen.Task(self.io_loop.add_callback)
self.stop()
self.run_gen(f)
def test_wait_all(self):
@gen.engine
def f():
(yield gen.Callback("k1"))("v1")
(yield gen.Callback("k2"))("v2")
results = yield gen.WaitAll(["k1", "k2"])
self.assertEqual(results, ["v1", "v2"])
self.stop()
self.run_gen(f)
def test_exception_in_yield(self):
@gen.engine
def f():
try:
yield gen.Wait("k1")
raise Exception("did not get expected exception")
except gen.UnknownKeyError:
pass
self.stop()
self.run_gen(f)
def test_resume_after_exception_in_yield(self):
@gen.engine
def f():
try:
yield gen.Wait("k1")
raise Exception("did not get expected exception")
except gen.UnknownKeyError:
pass
(yield gen.Callback("k2"))("v2")
self.assertEqual((yield gen.Wait("k2")), "v2")
self.stop()
self.run_gen(f)
def test_orphaned_callback(self):
@gen.engine
def f():
self.orphaned_callback = yield gen.Callback(1)
try:
self.run_gen(f)
raise Exception("did not get expected exception")
except gen.LeakedCallbackError:
pass
self.orphaned_callback()
def test_multi(self):
@gen.engine
def f():
(yield gen.Callback("k1"))("v1")
(yield gen.Callback("k2"))("v2")
results = yield [gen.Wait("k1"), gen.Wait("k2")]
self.assertEqual(results, ["v1", "v2"])
self.stop()
self.run_gen(f)
def test_multi_dict(self):
@gen.engine
def f():
(yield gen.Callback("k1"))("v1")
(yield gen.Callback("k2"))("v2")
results = yield dict(foo=gen.Wait("k1"), bar=gen.Wait("k2"))
self.assertEqual(results, dict(foo="v1", bar="v2"))
self.stop()
self.run_gen(f)
# The following tests explicitly run with both gen.Multi
# and gen.multi_future (Task returns a Future, so it can be used
# with either).
def test_multi_yieldpoint_delayed(self):
@gen.engine
def f():
# callbacks run at different times
responses = yield gen.Multi([
gen.Task(self.delay_callback, 3, arg="v1"),
gen.Task(self.delay_callback, 1, arg="v2"),
])
self.assertEqual(responses, ["v1", "v2"])
self.stop()
self.run_gen(f)
def test_multi_yieldpoint_dict_delayed(self):
@gen.engine
def f():
# callbacks run at different times
responses = yield gen.Multi(dict(
foo=gen.Task(self.delay_callback, 3, arg="v1"),
bar=gen.Task(self.delay_callback, 1, arg="v2"),
))
self.assertEqual(responses, dict(foo="v1", bar="v2"))
self.stop()
self.run_gen(f)
def test_multi_future_delayed(self):
@gen.engine
def f():
# callbacks run at different times
responses = yield gen.multi_future([
gen.Task(self.delay_callback, 3, arg="v1"),
gen.Task(self.delay_callback, 1, arg="v2"),
])
self.assertEqual(responses, ["v1", "v2"])
self.stop()
self.run_gen(f)
def test_multi_future_dict_delayed(self):
@gen.engine
def f():
# callbacks run at different times
responses = yield gen.multi_future(dict(
foo=gen.Task(self.delay_callback, 3, arg="v1"),
bar=gen.Task(self.delay_callback, 1, arg="v2"),
))
self.assertEqual(responses, dict(foo="v1", bar="v2"))
self.stop()
self.run_gen(f)
@skipOnTravis
@gen_test
def test_multi_performance(self):
# Yielding a list used to have quadratic performance; make
# sure a large list stays reasonable. On my laptop a list of
# 2000 used to take 1.8s, now it takes 0.12.
start = time.time()
yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]
end = time.time()
self.assertLess(end - start, 1.0)
@gen_test
def test_multi_empty(self):
# Empty lists or dicts should return the same type.
x = yield []
self.assertTrue(isinstance(x, list))
y = yield {}
self.assertTrue(isinstance(y, dict))
@gen_test
def test_multi_mixed_types(self):
# A YieldPoint (Wait) and Future (Task) can be combined
# (and use the YieldPoint codepath)
(yield gen.Callback("k1"))("v1")
responses = yield [gen.Wait("k1"),
gen.Task(self.delay_callback, 3, arg="v2")]
self.assertEqual(responses, ["v1", "v2"])
@gen_test
def test_future(self):
result = yield self.async_future(1)
self.assertEqual(result, 1)
@gen_test
def test_multi_future(self):
results = yield [self.async_future(1), self.async_future(2)]
self.assertEqual(results, [1, 2])
@gen_test
def test_multi_dict_future(self):
results = yield dict(foo=self.async_future(1), bar=self.async_future(2))
self.assertEqual(results, dict(foo=1, bar=2))
def test_arguments(self):
@gen.engine
def f():
(yield gen.Callback("noargs"))()
self.assertEqual((yield gen.Wait("noargs")), None)
(yield gen.Callback("1arg"))(42)
self.assertEqual((yield gen.Wait("1arg")), 42)
(yield gen.Callback("kwargs"))(value=42)
result = yield gen.Wait("kwargs")
self.assertTrue(isinstance(result, gen.Arguments))
self.assertEqual(((), dict(value=42)), result)
self.assertEqual(dict(value=42), result.kwargs)
(yield gen.Callback("2args"))(42, 43)
result = yield gen.Wait("2args")
self.assertTrue(isinstance(result, gen.Arguments))
self.assertEqual(((42, 43), {}), result)
self.assertEqual((42, 43), result.args)
def task_func(callback):
callback(None, error="foo")
result = yield gen.Task(task_func)
self.assertTrue(isinstance(result, gen.Arguments))
self.assertEqual(((None,), dict(error="foo")), result)
self.stop()
self.run_gen(f)
def test_stack_context_leak(self):
# regression test: repeated invocations of a gen-based
# function should not result in accumulated stack_contexts
def _stack_depth():
head = stack_context._state.contexts[1]
length = 0
while head is not None:
length += 1
head = head.old_contexts[1]
return length
@gen.engine
def inner(callback):
yield gen.Task(self.io_loop.add_callback)
callback()
@gen.engine
def outer():
for i in range(10):
yield gen.Task(inner)
stack_increase = _stack_depth() - initial_stack_depth
self.assertTrue(stack_increase <= 2)
self.stop()
initial_stack_depth = _stack_depth()
self.run_gen(outer)
def test_stack_context_leak_exception(self):
# same as previous, but with a function that exits with an exception
@gen.engine
def inner(callback):
yield gen.Task(self.io_loop.add_callback)
1 / 0
@gen.engine
def outer():
for i in range(10):
try:
yield gen.Task(inner)
except ZeroDivisionError:
pass
stack_increase = len(stack_context._state.contexts) - initial_stack_depth
self.assertTrue(stack_increase <= 2)
self.stop()
initial_stack_depth = len(stack_context._state.contexts)
self.run_gen(outer)
def function_with_stack_context(self, callback):
# Technically this function should stack_context.wrap its callback
# upon entry. However, it is very common for this step to be
# omitted.
def step2():
self.assertEqual(self.named_contexts, ['a'])
self.io_loop.add_callback(callback)
with stack_context.StackContext(self.named_context('a')):
self.io_loop.add_callback(step2)
@gen_test
def test_wait_transfer_stack_context(self):
# Wait should not pick up contexts from where callback was invoked,
# even if that function improperly fails to wrap its callback.
cb = yield gen.Callback('k1')
self.function_with_stack_context(cb)
self.assertEqual(self.named_contexts, [])
yield gen.Wait('k1')
self.assertEqual(self.named_contexts, [])
@gen_test
def test_task_transfer_stack_context(self):
yield gen.Task(self.function_with_stack_context)
self.assertEqual(self.named_contexts, [])
def test_raise_after_stop(self):
# This pattern will be used in the following tests so make sure
# the exception propagates as expected.
@gen.engine
def f():
self.stop()
1 / 0
with self.assertRaises(ZeroDivisionError):
self.run_gen(f)
def test_sync_raise_return(self):
# gen.Return is allowed in @gen.engine, but it may not be used
# to return a value.
@gen.engine
def f():
self.stop(42)
raise gen.Return()
result = self.run_gen(f)
self.assertEqual(result, 42)
def test_async_raise_return(self):
@gen.engine
def f():
yield gen.Task(self.io_loop.add_callback)
self.stop(42)
raise gen.Return()
result = self.run_gen(f)
self.assertEqual(result, 42)
def test_sync_raise_return_value(self):
@gen.engine
def f():
raise gen.Return(42)
with self.assertRaises(gen.ReturnValueIgnoredError):
self.run_gen(f)
def test_sync_raise_return_value_tuple(self):
@gen.engine
def f():
raise gen.Return((1, 2))
with self.assertRaises(gen.ReturnValueIgnoredError):
self.run_gen(f)
def test_async_raise_return_value(self):
@gen.engine
def f():
yield gen.Task(self.io_loop.add_callback)
raise gen.Return(42)
with self.assertRaises(gen.ReturnValueIgnoredError):
self.run_gen(f)
def test_async_raise_return_value_tuple(self):
@gen.engine
def f():
yield gen.Task(self.io_loop.add_callback)
raise gen.Return((1, 2))
with self.assertRaises(gen.ReturnValueIgnoredError):
self.run_gen(f)
def test_return_value(self):
# It is an error to apply @gen.engine to a function that returns
# a value.
@gen.engine
def f():
return 42
with self.assertRaises(gen.ReturnValueIgnoredError):
self.run_gen(f)
def test_return_value_tuple(self):
# It is an error to apply @gen.engine to a function that returns
# a value.
@gen.engine
def f():
return (1, 2)
with self.assertRaises(gen.ReturnValueIgnoredError):
self.run_gen(f)
@skipNotCPython
def test_task_refcounting(self):
# On CPython, tasks and their arguments should be released immediately
# without waiting for garbage collection.
@gen.engine
def f():
class Foo(object):
pass
arg = Foo()
self.arg_ref = weakref.ref(arg)
task = gen.Task(self.io_loop.add_callback, arg=arg)
self.task_ref = weakref.ref(task)
yield task
self.stop()
self.run_gen(f)
self.assertIs(self.arg_ref(), None)
self.assertIs(self.task_ref(), None)
class GenCoroutineTest(AsyncTestCase):
def setUp(self):
# Stray StopIteration exceptions can lead to tests exiting prematurely,
# so we need explicit checks here to make sure the tests run all
# the way through.
self.finished = False
super(GenCoroutineTest, self).setUp()
def tearDown(self):
super(GenCoroutineTest, self).tearDown()
assert self.finished
@gen_test
def test_sync_gen_return(self):
@gen.coroutine
def f():
raise gen.Return(42)
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_async_gen_return(self):
@gen.coroutine
def f():
yield gen.Task(self.io_loop.add_callback)
raise gen.Return(42)
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_sync_return(self):
@gen.coroutine
def f():
return 42
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@skipBefore33
@gen_test
def test_async_return(self):
# It is a compile-time error to return a value in a generator
# before Python 3.3, so we must test this with exec.
# Flatten the real global and local namespace into our fake globals:
# it's all global from the perspective of f().
global_namespace = dict(globals(), **locals())
local_namespace = {}
exec(textwrap.dedent("""
@gen.coroutine
def f():
yield gen.Task(self.io_loop.add_callback)
return 42
"""), global_namespace, local_namespace)
result = yield local_namespace['f']()
self.assertEqual(result, 42)
self.finished = True
@skipBefore33
@gen_test
def test_async_early_return(self):
# A yield statement exists but is not executed, which means
# this function "returns" via an exception. This exception
# doesn't happen before the exception handling is set up.
global_namespace = dict(globals(), **locals())
local_namespace = {}
exec(textwrap.dedent("""
@gen.coroutine
def f():
if True:
return 42
yield gen.Task(self.io_loop.add_callback)
"""), global_namespace, local_namespace)
result = yield local_namespace['f']()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_sync_return_no_value(self):
@gen.coroutine
def f():
return
result = yield f()
self.assertEqual(result, None)
self.finished = True
@gen_test
def test_async_return_no_value(self):
# Without a return value we don't need python 3.3.
@gen.coroutine
def f():
yield gen.Task(self.io_loop.add_callback)
return
result = yield f()
self.assertEqual(result, None)
self.finished = True
@gen_test
def test_sync_raise(self):
@gen.coroutine
def f():
1 / 0
# The exception is raised when the future is yielded
# (or equivalently when its result method is called),
# not when the function itself is called).
future = f()
with self.assertRaises(ZeroDivisionError):
yield future
self.finished = True
@gen_test
def test_async_raise(self):
@gen.coroutine
def f():
yield gen.Task(self.io_loop.add_callback)
1 / 0
future = f()
with self.assertRaises(ZeroDivisionError):
yield future
self.finished = True
@gen_test
def test_pass_callback(self):
@gen.coroutine
def f():
raise gen.Return(42)
result = yield gen.Task(f)
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_replace_yieldpoint_exception(self):
# Test exception handling: a coroutine can catch one exception
# raised by a yield point and raise a different one.
@gen.coroutine
def f1():
1 / 0
@gen.coroutine
def f2():
try:
yield f1()
except ZeroDivisionError:
raise KeyError()
future = f2()
with self.assertRaises(KeyError):
yield future
self.finished = True
@gen_test
def test_swallow_yieldpoint_exception(self):
# Test exception handling: a coroutine can catch an exception
# raised by a yield point and not raise a different one.
@gen.coroutine
def f1():
1 / 0
@gen.coroutine
def f2():
try:
yield f1()
except ZeroDivisionError:
raise gen.Return(42)
result = yield f2()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_replace_context_exception(self):
# Test exception handling: exceptions thrown into the stack context
# can be caught and replaced.
# Note that this test and the following are for behavior that is
# not really supported any more: coroutines no longer create a
# stack context automatically; but one is created after the first
# YieldPoint (i.e. not a Future).
@gen.coroutine
def f2():
(yield gen.Callback(1))()
yield gen.Wait(1)
self.io_loop.add_callback(lambda: 1 / 0)
try:
yield gen.Task(self.io_loop.add_timeout,
self.io_loop.time() + 10)
except ZeroDivisionError:
raise KeyError()
future = f2()
with self.assertRaises(KeyError):
yield future
self.finished = True
@gen_test
def test_swallow_context_exception(self):
# Test exception handling: exceptions thrown into the stack context
# can be caught and ignored.
@gen.coroutine
def f2():
(yield gen.Callback(1))()
yield gen.Wait(1)
self.io_loop.add_callback(lambda: 1 / 0)
try:
yield gen.Task(self.io_loop.add_timeout,
self.io_loop.time() + 10)
except ZeroDivisionError:
raise gen.Return(42)
result = yield f2()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_moment(self):
calls = []
@gen.coroutine
def f(name, yieldable):
for i in range(5):
calls.append(name)
yield yieldable
# First, confirm the behavior without moment: each coroutine
# monopolizes the event loop until it finishes.
immediate = Future()
immediate.set_result(None)
yield [f('a', immediate), f('b', immediate)]
self.assertEqual(''.join(calls), 'aaaaabbbbb')
# With moment, they take turns.
calls = []
yield [f('a', gen.moment), f('b', gen.moment)]
self.assertEqual(''.join(calls), 'ababababab')
self.finished = True
calls = []
yield [f('a', gen.moment), f('b', immediate)]
self.assertEqual(''.join(calls), 'abbbbbaaaa')
@gen_test
def test_sleep(self):
yield gen.sleep(0.01)
self.finished = True
class GenSequenceHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
self.io_loop = self.request.connection.stream.io_loop
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.write("1")
self.io_loop.add_callback((yield gen.Callback("k2")))
yield gen.Wait("k2")
self.write("2")
# reuse an old key
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.finish("3")
class GenCoroutineSequenceHandler(RequestHandler):
@gen.coroutine
def get(self):
self.io_loop = self.request.connection.stream.io_loop
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.write("1")
self.io_loop.add_callback((yield gen.Callback("k2")))
yield gen.Wait("k2")
self.write("2")
# reuse an old key
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.finish("3")
class GenCoroutineUnfinishedSequenceHandler(RequestHandler):
@asynchronous
@gen.coroutine
def get(self):
self.io_loop = self.request.connection.stream.io_loop
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.write("1")
self.io_loop.add_callback((yield gen.Callback("k2")))
yield gen.Wait("k2")
self.write("2")
# reuse an old key
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
# just write, don't finish
self.write("3")
class GenTaskHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
io_loop = self.request.connection.stream.io_loop
client = AsyncHTTPClient(io_loop=io_loop)
response = yield gen.Task(client.fetch, self.get_argument('url'))
response.rethrow()
self.finish(b"got response: " + response.body)
class GenExceptionHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
# This test depends on the order of the two decorators.
io_loop = self.request.connection.stream.io_loop
yield gen.Task(io_loop.add_callback)
raise Exception("oops")
class GenCoroutineExceptionHandler(RequestHandler):
@gen.coroutine
def get(self):
# This test depends on the order of the two decorators.
io_loop = self.request.connection.stream.io_loop
yield gen.Task(io_loop.add_callback)
raise Exception("oops")
class GenYieldExceptionHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
io_loop = self.request.connection.stream.io_loop
# Test the interaction of the two stack_contexts.
def fail_task(callback):
io_loop.add_callback(lambda: 1 / 0)
try:
yield gen.Task(fail_task)
raise Exception("did not get expected exception")
except ZeroDivisionError:
self.finish('ok')
class UndecoratedCoroutinesHandler(RequestHandler):
@gen.coroutine
def prepare(self):
self.chunks = []
yield gen.Task(IOLoop.current().add_callback)
self.chunks.append('1')
@gen.coroutine
def get(self):
self.chunks.append('2')
yield gen.Task(IOLoop.current().add_callback)
self.chunks.append('3')
yield gen.Task(IOLoop.current().add_callback)
self.write(''.join(self.chunks))
class AsyncPrepareErrorHandler(RequestHandler):
@gen.coroutine
def prepare(self):
yield gen.Task(IOLoop.current().add_callback)
raise HTTPError(403)
def get(self):
self.finish('ok')
class GenWebTest(AsyncHTTPTestCase):
def get_app(self):
return Application([
('/sequence', GenSequenceHandler),
('/coroutine_sequence', GenCoroutineSequenceHandler),
('/coroutine_unfinished_sequence',
GenCoroutineUnfinishedSequenceHandler),
('/task', GenTaskHandler),
('/exception', GenExceptionHandler),
('/coroutine_exception', GenCoroutineExceptionHandler),
('/yield_exception', GenYieldExceptionHandler),
('/undecorated_coroutine', UndecoratedCoroutinesHandler),
('/async_prepare_error', AsyncPrepareErrorHandler),
])
def test_sequence_handler(self):
response = self.fetch('/sequence')
self.assertEqual(response.body, b"123")
def test_coroutine_sequence_handler(self):
response = self.fetch('/coroutine_sequence')
self.assertEqual(response.body, b"123")
def test_coroutine_unfinished_sequence_handler(self):
response = self.fetch('/coroutine_unfinished_sequence')
self.assertEqual(response.body, b"123")
def test_task_handler(self):
response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))
self.assertEqual(response.body, b"got response: 123")
def test_exception_handler(self):
# Make sure we get an error and not a timeout
with ExpectLog(app_log, "Uncaught exception GET /exception"):
response = self.fetch('/exception')
self.assertEqual(500, response.code)
def test_coroutine_exception_handler(self):
# Make sure we get an error and not a timeout
with ExpectLog(app_log, "Uncaught exception GET /coroutine_exception"):
response = self.fetch('/coroutine_exception')
self.assertEqual(500, response.code)
def test_yield_exception_handler(self):
response = self.fetch('/yield_exception')
self.assertEqual(response.body, b'ok')
def test_undecorated_coroutines(self):
response = self.fetch('/undecorated_coroutine')
self.assertEqual(response.body, b'123')
def test_async_prepare_error_handler(self):
response = self.fetch('/async_prepare_error')
self.assertEqual(response.code, 403)
class WithTimeoutTest(AsyncTestCase):
@gen_test
def test_timeout(self):
with self.assertRaises(gen.TimeoutError):
yield gen.with_timeout(datetime.timedelta(seconds=0.1),
Future())
@gen_test
def test_completes_before_timeout(self):
future = Future()
self.io_loop.add_timeout(datetime.timedelta(seconds=0.1),
lambda: future.set_result('asdf'))
result = yield gen.with_timeout(datetime.timedelta(seconds=3600),
future, io_loop=self.io_loop)
self.assertEqual(result, 'asdf')
@gen_test
def test_fails_before_timeout(self):
future = Future()
self.io_loop.add_timeout(
datetime.timedelta(seconds=0.1),
lambda: future.set_exception(ZeroDivisionError()))
with self.assertRaises(ZeroDivisionError):
yield gen.with_timeout(datetime.timedelta(seconds=3600),
future, io_loop=self.io_loop)
@gen_test
def test_already_resolved(self):
future = Future()
future.set_result('asdf')
result = yield gen.with_timeout(datetime.timedelta(seconds=3600),
future, io_loop=self.io_loop)
self.assertEqual(result, 'asdf')
@unittest.skipIf(futures is None, 'futures module not present')
@gen_test
def test_timeout_concurrent_future(self):
with futures.ThreadPoolExecutor(1) as executor:
with self.assertRaises(gen.TimeoutError):
yield gen.with_timeout(self.io_loop.time(),
executor.submit(time.sleep, 0.1))
@unittest.skipIf(futures is None, 'futures module not present')
@gen_test
def test_completed_concurrent_future(self):
with futures.ThreadPoolExecutor(1) as executor:
yield gen.with_timeout(datetime.timedelta(seconds=3600),
executor.submit(lambda: None))
class WaitIteratorTest(AsyncTestCase):
@gen_test
def test_empty_iterator(self):
g = gen.WaitIterator()
self.assertTrue(g.done(), 'empty generator iterated')
with self.assertRaises(ValueError):
g = gen.WaitIterator(False, bar=False)
self.assertEqual(g.current_index, None, "bad nil current index")
self.assertEqual(g.current_future, None, "bad nil current future")
@gen_test
def test_already_done(self):
f1 = Future()
f2 = Future()
f3 = Future()
f1.set_result(24)
f2.set_result(42)
f3.set_result(84)
g = gen.WaitIterator(f1, f2, f3)
i = 0
while not g.done():
r = yield g.next()
# Order is not guaranteed, but the current implementation
# preserves ordering of already-done Futures.
if i == 0:
self.assertEqual(g.current_index, 0)
self.assertIs(g.current_future, f1)
self.assertEqual(r, 24)
elif i == 1:
self.assertEqual(g.current_index, 1)
self.assertIs(g.current_future, f2)
self.assertEqual(r, 42)
elif i == 2:
self.assertEqual(g.current_index, 2)
self.assertIs(g.current_future, f3)
self.assertEqual(r, 84)
i += 1
self.assertEqual(g.current_index, None, "bad nil current index")
self.assertEqual(g.current_future, None, "bad nil current future")
dg = gen.WaitIterator(f1=f1, f2=f2)
while not dg.done():
dr = yield dg.next()
if dg.current_index == "f1":
self.assertTrue(dg.current_future==f1 and dr==24,
"WaitIterator dict status incorrect")
elif dg.current_index == "f2":
self.assertTrue(dg.current_future==f2 and dr==42,
"WaitIterator dict status incorrect")
else:
self.fail("got bad WaitIterator index {}".format(
dg.current_index))
i += 1
self.assertEqual(dg.current_index, None, "bad nil current index")
self.assertEqual(dg.current_future, None, "bad nil current future")
def finish_coroutines(self, iteration, futures):
if iteration == 3:
futures[2].set_result(24)
elif iteration == 5:
futures[0].set_exception(ZeroDivisionError())
elif iteration == 8:
futures[1].set_result(42)
futures[3].set_result(84)
if iteration < 8:
self.io_loop.add_callback(self.finish_coroutines, iteration+1, futures)
@gen_test
def test_iterator(self):
futures = [Future(), Future(), Future(), Future()]
self.finish_coroutines(0, futures)
g = gen.WaitIterator(*futures)
i = 0
while not g.done():
try:
r = yield g.next()
except ZeroDivisionError:
self.assertIs(g.current_future, futures[0],
'exception future invalid')
else:
if i == 0:
self.assertEqual(r, 24, 'iterator value incorrect')
self.assertEqual(g.current_index, 2, 'wrong index')
elif i == 2:
self.assertEqual(r, 42, 'iterator value incorrect')
self.assertEqual(g.current_index, 1, 'wrong index')
elif i == 3:
self.assertEqual(r, 84, 'iterator value incorrect')
self.assertEqual(g.current_index, 3, 'wrong index')
i += 1
if __name__ == '__main__':
unittest.main()
|
rdo-management/neutron
|
neutron/openstack/common/eventlet_backdoor.py
|
# Copyright (c) 2012 OpenStack Foundation.
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import print_function
import copy
import errno
import gc
import logging
import os
import pprint
import socket
import sys
import traceback
import eventlet.backdoor
import greenlet
from oslo_config import cfg
from neutron.openstack.common._i18n import _LI
help_for_backdoor_port = (
"Acceptable values are 0, <port>, and <start>:<end>, where 0 results "
"in listening on a random tcp port number; <port> results in listening "
"on the specified port number (and not enabling backdoor if that port "
"is in use); and <start>:<end> results in listening on the smallest "
"unused port number within the specified range of port numbers. The "
"chosen port is displayed in the service's log file.")
eventlet_backdoor_opts = [
cfg.StrOpt('backdoor_port',
help="Enable eventlet backdoor. %s" % help_for_backdoor_port)
]
CONF = cfg.CONF
CONF.register_opts(eventlet_backdoor_opts)
LOG = logging.getLogger(__name__)
def list_opts():
"""Entry point for oslo-config-generator.
"""
return [(None, copy.deepcopy(eventlet_backdoor_opts))]
class EventletBackdoorConfigValueError(Exception):
def __init__(self, port_range, help_msg, ex):
msg = ('Invalid backdoor_port configuration %(range)s: %(ex)s. '
'%(help)s' %
{'range': port_range, 'ex': ex, 'help': help_msg})
super(EventletBackdoorConfigValueError, self).__init__(msg)
self.port_range = port_range
def _dont_use_this():
print("Don't use this, just disconnect instead")
def _find_objects(t):
return [o for o in gc.get_objects() if isinstance(o, t)]
def _print_greenthreads():
for i, gt in enumerate(_find_objects(greenlet.greenlet)):
print(i, gt)
traceback.print_stack(gt.gr_frame)
print()
def _print_nativethreads():
for threadId, stack in sys._current_frames().items():
print(threadId)
traceback.print_stack(stack)
print()
def _parse_port_range(port_range):
if ':' not in port_range:
start, end = port_range, port_range
else:
start, end = port_range.split(':', 1)
try:
start, end = int(start), int(end)
if end < start:
raise ValueError
return start, end
except ValueError as ex:
raise EventletBackdoorConfigValueError(port_range, ex,
help_for_backdoor_port)
def _listen(host, start_port, end_port, listen_func):
try_port = start_port
while True:
try:
return listen_func((host, try_port))
except socket.error as exc:
if (exc.errno != errno.EADDRINUSE or
try_port >= end_port):
raise
try_port += 1
def initialize_if_enabled():
backdoor_locals = {
'exit': _dont_use_this, # So we don't exit the entire process
'quit': _dont_use_this, # So we don't exit the entire process
'fo': _find_objects,
'pgt': _print_greenthreads,
'pnt': _print_nativethreads,
}
if CONF.backdoor_port is None:
return None
start_port, end_port = _parse_port_range(str(CONF.backdoor_port))
# NOTE(johannes): The standard sys.displayhook will print the value of
# the last expression and set it to __builtin__._, which overwrites
# the __builtin__._ that gettext sets. Let's switch to using pprint
# since it won't interact poorly with gettext, and it's easier to
# read the output too.
def displayhook(val):
if val is not None:
pprint.pprint(val)
sys.displayhook = displayhook
sock = _listen('localhost', start_port, end_port, eventlet.listen)
# In the case of backdoor port being zero, a port number is assigned by
# listen(). In any case, pull the port number out here.
port = sock.getsockname()[1]
LOG.info(
_LI('Eventlet backdoor listening on %(port)s for process %(pid)d') %
{'port': port, 'pid': os.getpid()}
)
eventlet.spawn_n(eventlet.backdoor.backdoor_server, sock,
locals=backdoor_locals)
return port
|
moreati/numpy
|
runtests.py
|
#!/usr/bin/env python
"""
runtests.py [OPTIONS] [-- ARGS]
Run tests, building the project first.
Examples::
$ python runtests.py
$ python runtests.py -s {SAMPLE_SUBMODULE}
$ python runtests.py -t {SAMPLE_TEST}
$ python runtests.py --ipython
$ python runtests.py --python somescript.py
$ python runtests.py --bench
Run a debugger:
$ gdb --args python runtests.py [...other args...]
Generate C code coverage listing under build/lcov/:
(requires http://ltp.sourceforge.net/coverage/lcov.php)
$ python runtests.py --gcov [...other args...]
$ python runtests.py --lcov-html
"""
#
# This is a generic test runner script for projects using Numpy's test
# framework. Change the following values to adapt to your project:
#
PROJECT_MODULE = "numpy"
PROJECT_ROOT_FILES = ['numpy', 'LICENSE.txt', 'setup.py']
SAMPLE_TEST = "numpy/linalg/tests/test_linalg.py:test_byteorder_check"
SAMPLE_SUBMODULE = "linalg"
EXTRA_PATH = ['/usr/lib/ccache', '/usr/lib/f90cache',
'/usr/local/lib/ccache', '/usr/local/lib/f90cache']
# ---------------------------------------------------------------------
if __doc__ is None:
__doc__ = "Run without -OO if you want usage info"
else:
__doc__ = __doc__.format(**globals())
import sys
import os
# In case we are run from the source directory, we don't want to import the
# project from there:
sys.path.pop(0)
import shutil
import subprocess
import time
import imp
from argparse import ArgumentParser, REMAINDER
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
def main(argv):
parser = ArgumentParser(usage=__doc__.lstrip())
parser.add_argument("--verbose", "-v", action="count", default=1,
help="more verbosity")
parser.add_argument("--no-build", "-n", action="store_true", default=False,
help="do not build the project (use system installed version)")
parser.add_argument("--build-only", "-b", action="store_true", default=False,
help="just build, do not run any tests")
parser.add_argument("--doctests", action="store_true", default=False,
help="Run doctests in module")
parser.add_argument("--coverage", action="store_true", default=False,
help=("report coverage of project code. HTML output goes "
"under build/coverage"))
parser.add_argument("--gcov", action="store_true", default=False,
help=("enable C code coverage via gcov (requires GCC). "
"gcov output goes to build/**/*.gc*"))
parser.add_argument("--lcov-html", action="store_true", default=False,
help=("produce HTML for C code coverage information "
"from a previous run with --gcov. "
"HTML output goes to build/lcov/"))
parser.add_argument("--mode", "-m", default="fast",
help="'fast', 'full', or something that could be "
"passed to nosetests -A [default: fast]")
parser.add_argument("--submodule", "-s", default=None,
help="Submodule whose tests to run (cluster, constants, ...)")
parser.add_argument("--pythonpath", "-p", default=None,
help="Paths to prepend to PYTHONPATH")
parser.add_argument("--tests", "-t", action='append',
help="Specify tests to run")
parser.add_argument("--python", action="store_true",
help="Start a Python shell with PYTHONPATH set")
parser.add_argument("--ipython", "-i", action="store_true",
help="Start IPython shell with PYTHONPATH set")
parser.add_argument("--shell", action="store_true",
help="Start Unix shell with PYTHONPATH set")
parser.add_argument("--debug", "-g", action="store_true",
help="Debug build")
parser.add_argument("--parallel", "-j", type=int, default=0,
help="Number of parallel jobs during build")
parser.add_argument("--show-build-log", action="store_true",
help="Show build output rather than using a log file")
parser.add_argument("--bench", action="store_true",
help="Run benchmark suite instead of test suite")
parser.add_argument("--bench-compare", action="store", metavar="COMMIT",
help=("Compare benchmark results to COMMIT. "
"Note that you need to commit your changes first!"))
parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER,
help="Arguments to pass to Nose, Python or shell")
args = parser.parse_args(argv)
if args.bench_compare:
args.bench = True
args.no_build = True # ASV does the building
if args.lcov_html:
# generate C code coverage output
lcov_generate()
sys.exit(0)
if args.pythonpath:
for p in reversed(args.pythonpath.split(os.pathsep)):
sys.path.insert(0, p)
if args.gcov:
gcov_reset_counters()
if args.debug and args.bench:
print("*** Benchmarks should not be run against debug "
"version; remove -g flag ***")
if not args.no_build:
site_dir = build_project(args)
sys.path.insert(0, site_dir)
os.environ['PYTHONPATH'] = site_dir
extra_argv = args.args[:]
if extra_argv and extra_argv[0] == '--':
extra_argv = extra_argv[1:]
if args.python:
# Debugging issues with warnings is much easier if you can see them
print("Enabling display of all warnings")
import warnings; warnings.filterwarnings("always")
if extra_argv:
# Don't use subprocess, since we don't want to include the
# current path in PYTHONPATH.
sys.argv = extra_argv
with open(extra_argv[0], 'r') as f:
script = f.read()
sys.modules['__main__'] = imp.new_module('__main__')
ns = dict(__name__='__main__',
__file__=extra_argv[0])
exec_(script, ns)
sys.exit(0)
else:
import code
code.interact()
sys.exit(0)
if args.ipython:
# Debugging issues with warnings is much easier if you can see them
print("Enabling display of all warnings and pre-importing numpy as np")
import warnings; warnings.filterwarnings("always")
import IPython
import numpy as np
IPython.embed(user_ns={"np": np})
sys.exit(0)
if args.shell:
shell = os.environ.get('SHELL', 'sh')
print("Spawning a Unix shell...")
os.execv(shell, [shell] + extra_argv)
sys.exit(1)
if args.coverage:
dst_dir = os.path.join(ROOT_DIR, 'build', 'coverage')
fn = os.path.join(dst_dir, 'coverage_html.js')
if os.path.isdir(dst_dir) and os.path.isfile(fn):
shutil.rmtree(dst_dir)
extra_argv += ['--cover-html',
'--cover-html-dir='+dst_dir]
if args.bench:
# Run ASV
items = extra_argv
if args.tests:
items += args.tests
if args.submodule:
items += [args.submodule]
bench_args = []
for a in items:
bench_args.extend(['--bench', a])
if not args.bench_compare:
cmd = ['asv', 'run', '-n', '-e', '--python=same'] + bench_args
os.chdir(os.path.join(ROOT_DIR, 'benchmarks'))
os.execvp(cmd[0], cmd)
sys.exit(1)
else:
commits = [x.strip() for x in args.bench_compare.split(',')]
if len(commits) == 1:
commit_a = commits[0]
commit_b = 'HEAD'
elif len(commits) == 2:
commit_a, commit_b = commits
else:
p.error("Too many commits to compare benchmarks for")
# Check for uncommitted files
if commit_b == 'HEAD':
r1 = subprocess.call(['git', 'diff-index', '--quiet',
'--cached', 'HEAD'])
r2 = subprocess.call(['git', 'diff-files', '--quiet'])
if r1 != 0 or r2 != 0:
print("*"*80)
print("WARNING: you have uncommitted changes --- "
"these will NOT be benchmarked!")
print("*"*80)
# Fix commit ids (HEAD is local to current repo)
p = subprocess.Popen(['git', 'rev-parse', commit_b],
stdout=subprocess.PIPE)
out, err = p.communicate()
commit_b = out.strip()
p = subprocess.Popen(['git', 'rev-parse', commit_a],
stdout=subprocess.PIPE)
out, err = p.communicate()
commit_a = out.strip()
cmd = ['asv', 'continuous', '-e', '-f', '1.05',
commit_a, commit_b] + bench_args
os.chdir(os.path.join(ROOT_DIR, 'benchmarks'))
os.execvp(cmd[0], cmd)
sys.exit(1)
test_dir = os.path.join(ROOT_DIR, 'build', 'test')
if args.build_only:
sys.exit(0)
elif args.submodule:
modname = PROJECT_MODULE + '.' + args.submodule
try:
__import__(modname)
test = sys.modules[modname].test
except (ImportError, KeyError, AttributeError):
print("Cannot run tests for %s" % modname)
sys.exit(2)
elif args.tests:
def fix_test_path(x):
# fix up test path
p = x.split(':')
p[0] = os.path.relpath(os.path.abspath(p[0]),
test_dir)
return ':'.join(p)
tests = [fix_test_path(x) for x in args.tests]
def test(*a, **kw):
extra_argv = kw.pop('extra_argv', ())
extra_argv = extra_argv + tests[1:]
kw['extra_argv'] = extra_argv
from numpy.testing import Tester
return Tester(tests[0]).test(*a, **kw)
else:
__import__(PROJECT_MODULE)
test = sys.modules[PROJECT_MODULE].test
# Run the tests under build/test
try:
shutil.rmtree(test_dir)
except OSError:
pass
try:
os.makedirs(test_dir)
except OSError:
pass
cwd = os.getcwd()
try:
os.chdir(test_dir)
result = test(args.mode,
verbose=args.verbose,
extra_argv=extra_argv,
doctests=args.doctests,
coverage=args.coverage)
finally:
os.chdir(cwd)
if result.wasSuccessful():
sys.exit(0)
else:
sys.exit(1)
def build_project(args):
"""
Build a dev version of the project.
Returns
-------
site_dir
site-packages directory where it was installed
"""
root_ok = [os.path.exists(os.path.join(ROOT_DIR, fn))
for fn in PROJECT_ROOT_FILES]
if not all(root_ok):
print("To build the project, run runtests.py in "
"git checkout or unpacked source")
sys.exit(1)
dst_dir = os.path.join(ROOT_DIR, 'build', 'testenv')
env = dict(os.environ)
cmd = [sys.executable, 'setup.py']
# Always use ccache, if installed
env['PATH'] = os.pathsep.join(EXTRA_PATH + env.get('PATH', '').split(os.pathsep))
if args.debug or args.gcov:
# assume everyone uses gcc/gfortran
env['OPT'] = '-O0 -ggdb'
env['FOPT'] = '-O0 -ggdb'
if args.gcov:
import distutils.sysconfig
cvars = distutils.sysconfig.get_config_vars()
env['OPT'] = '-O0 -ggdb'
env['FOPT'] = '-O0 -ggdb'
env['CC'] = cvars['CC'] + ' --coverage'
env['CXX'] = cvars['CXX'] + ' --coverage'
env['F77'] = 'gfortran --coverage '
env['F90'] = 'gfortran --coverage '
env['LDSHARED'] = cvars['LDSHARED'] + ' --coverage'
env['LDFLAGS'] = " ".join(cvars['LDSHARED'].split()[1:]) + ' --coverage'
cmd += ["build"]
if args.parallel > 1:
cmd += ["-j", str(args.parallel)]
cmd += ['install', '--prefix=' + dst_dir]
log_filename = os.path.join(ROOT_DIR, 'build.log')
if args.show_build_log:
ret = subprocess.call(cmd, env=env, cwd=ROOT_DIR)
else:
log_filename = os.path.join(ROOT_DIR, 'build.log')
print("Building, see build.log...")
with open(log_filename, 'w') as log:
p = subprocess.Popen(cmd, env=env, stdout=log, stderr=log,
cwd=ROOT_DIR)
# Wait for it to finish, and print something to indicate the
# process is alive, but only if the log file has grown (to
# allow continuous integration environments kill a hanging
# process accurately if it produces no output)
last_blip = time.time()
last_log_size = os.stat(log_filename).st_size
while p.poll() is None:
time.sleep(0.5)
if time.time() - last_blip > 60:
log_size = os.stat(log_filename).st_size
if log_size > last_log_size:
print(" ... build in progress")
last_blip = time.time()
last_log_size = log_size
ret = p.wait()
if ret == 0:
print("Build OK")
else:
if not args.show_build_log:
with open(log_filename, 'r') as f:
print(f.read())
print("Build failed!")
sys.exit(1)
from distutils.sysconfig import get_python_lib
site_dir = get_python_lib(prefix=dst_dir, plat_specific=True)
return site_dir
#
# GCOV support
#
def gcov_reset_counters():
print("Removing previous GCOV .gcda files...")
build_dir = os.path.join(ROOT_DIR, 'build')
for dirpath, dirnames, filenames in os.walk(build_dir):
for fn in filenames:
if fn.endswith('.gcda') or fn.endswith('.da'):
pth = os.path.join(dirpath, fn)
os.unlink(pth)
#
# LCOV support
#
LCOV_OUTPUT_FILE = os.path.join(ROOT_DIR, 'build', 'lcov.out')
LCOV_HTML_DIR = os.path.join(ROOT_DIR, 'build', 'lcov')
def lcov_generate():
try: os.unlink(LCOV_OUTPUT_FILE)
except OSError: pass
try: shutil.rmtree(LCOV_HTML_DIR)
except OSError: pass
print("Capturing lcov info...")
subprocess.call(['lcov', '-q', '-c',
'-d', os.path.join(ROOT_DIR, 'build'),
'-b', ROOT_DIR,
'--output-file', LCOV_OUTPUT_FILE])
print("Generating lcov HTML output...")
ret = subprocess.call(['genhtml', '-q', LCOV_OUTPUT_FILE,
'--output-directory', LCOV_HTML_DIR,
'--legend', '--highlight'])
if ret != 0:
print("genhtml failed!")
else:
print("HTML output generated under build/lcov/")
#
# Python 3 support
#
if sys.version_info[0] >= 3:
import builtins
exec_ = getattr(builtins, "exec")
else:
def exec_(code, globs=None, locs=None):
"""Execute code in a namespace."""
if globs is None:
frame = sys._getframe(1)
globs = frame.f_globals
if locs is None:
locs = frame.f_locals
del frame
elif locs is None:
locs = globs
exec("""exec code in globs, locs""")
if __name__ == "__main__":
main(argv=sys.argv[1:])
|
Slezhuk/ansible
|
lib/ansible/modules/network/nxos/nxos_vpc_interface.py
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: nxos_vpc_interface
extends_documentation_fragment: nxos
version_added: "2.2"
short_description: Manages interface VPC configuration
description:
- Manages interface VPC configuration
author:
- Jason Edelman (@jedelman8)
- Gabriele Gerbino (@GGabriele)
notes:
- Either vpc or peer_link param is required, but not both.
- C(state=absent) removes whatever VPC config is on a port-channel
if one exists.
- Re-assigning a vpc or peerlink from one portchannel to another is not
supported. The module will force the user to unconfigure an existing
vpc/pl before configuring the same value on a new portchannel
options:
portchannel:
description:
- Group number of the portchannel that will be configured.
required: true
vpc:
description:
- VPC group/id that will be configured on associated portchannel.
required: false
default: null
peer_link:
description:
- Set to true/false for peer link config on associated portchannel.
required: false
default: null
state:
description:
- Manages desired state of the resource.
required: true
choices: ['present','absent']
'''
EXAMPLES = '''
- nxos_vpc_portchannel:
portchannel: 10
vpc: 100
username: "{{ un }}"
password: "{{ pwd }}"
host: "{{ inventory_hostname }}"
'''
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: always
type: dict
sample: {"portchannel": "100", "vpc": "10"}
existing:
description: k/v pairs of existing configuration
type: dict
sample: {}
end_state:
description: k/v pairs of configuration after module execution
returned: always
type: dict
sample: {"peer-link": false, "portchannel": "100", "vpc": "10"}
updates:
description: commands sent to the device
returned: always
type: list
sample: ["interface port-channel100", "vpc 10"]
changed:
description: check to see if a change was made on the device
returned: always
type: boolean
sample: true
'''
from ansible.module_utils.nxos import get_config, load_config, run_commands
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.netcfg import CustomNetworkConfig
def execute_show_command(command, module, command_type='cli_show'):
if module.params['transport'] == 'cli':
command += ' | json'
cmds = [command]
body = run_commands(module, cmds)
elif module.params['transport'] == 'nxapi':
cmds = [command]
body = run_commands(module, cmds)
return body
def flatten_list(command_lists):
flat_command_list = []
for command in command_lists:
if isinstance(command, list):
flat_command_list.extend(command)
else:
flat_command_list.append(command)
return flat_command_list
def get_portchannel_list(module):
command = 'show port-channel summary'
portchannels = []
pc_list = []
body = execute_show_command(command, module)
try:
pc_list = body[0]['TABLE_channel']['ROW_channel']
except (KeyError, AttributeError):
return portchannels
if pc_list:
if isinstance(pc_list, dict):
pc_list = [pc_list]
for pc in pc_list:
portchannels.append(pc['group'])
return portchannels
def get_existing_portchannel_to_vpc_mappings(module):
command = 'show vpc brief'
pc_vpc_mapping = {}
body = execute_show_command(command, module)
try:
vpc_table = body[0]['TABLE_vpc']['ROW_vpc']
except (KeyError, AttributeError, TypeError):
vpc_table = None
if vpc_table:
if isinstance(vpc_table, dict):
vpc_table = [vpc_table]
for vpc in vpc_table:
pc_vpc_mapping[str(vpc['vpc-id'])] = str(vpc['vpc-ifindex'])
return pc_vpc_mapping
def peer_link_exists(module):
found = False
run = get_vpc_running_config(module)
vpc_list = run.split('\n')
for each in vpc_list:
if 'peer-link' in each:
found = True
return found
def get_vpc_running_config(module):
command = 'show running section vpc'
body = execute_show_command(command, module,
command_type='cli_show_ascii')[0]
return body
def get_active_vpc_peer_link(module):
command = 'show vpc brief'
peer_link = None
body = execute_show_command(command, module)
try:
peer_link = body[0]['TABLE_peerlink']['ROW_peerlink']['peerlink-ifindex']
except (KeyError, AttributeError):
return peer_link
return peer_link
def get_portchannel_vpc_config(module, portchannel):
command = 'show vpc brief'
peer_link_pc = None
peer_link = False
vpc = ""
pc = ""
config = {}
body = execute_show_command(command, module)
try:
table = body[0]['TABLE_peerlink']['ROW_peerlink']
except (KeyError, AttributeError, TypeError):
table = {}
if table:
peer_link_pc = table.get('peerlink-ifindex', None)
if peer_link_pc:
plpc = str(peer_link_pc[2:])
if portchannel == plpc:
config['portchannel'] = portchannel
config['peer-link'] = True
config['vpc'] = vpc
mapping = get_existing_portchannel_to_vpc_mappings(module)
for existing_vpc, port_channel in mapping.items():
port_ch = str(port_channel[2:])
if port_ch == portchannel:
pc = port_ch
vpc = str(existing_vpc)
config['portchannel'] = pc
config['peer-link'] = peer_link
config['vpc'] = vpc
return config
def get_commands_to_config_vpc_interface(portchannel, delta, config_value, existing):
commands = []
if delta.get('peer-link') is False and existing.get('peer-link') is True:
command = 'no vpc peer-link'
commands.append('no vpc peer-link')
commands.insert(0, 'interface port-channel{0}'.format(portchannel))
elif delta.get('peer-link') or not existing.get('vpc'):
command = 'vpc {0}'.format(config_value)
commands.append(command)
commands.insert(0, 'interface port-channel{0}'.format(portchannel))
return commands
def main():
argument_spec = dict(
portchannel=dict(required=True, type='str'),
vpc=dict(required=False, type='str'),
peer_link=dict(required=False, type='bool'),
state=dict(choices=['absent', 'present'], default='present'),
include_defaults=dict(default=False),
config=dict(),
save=dict(type='bool', default=False)
)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=[['vpc', 'peer_link']],
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
portchannel = module.params['portchannel']
vpc = module.params['vpc']
peer_link = module.params['peer_link']
state = module.params['state']
changed = False
args = {'portchannel': portchannel, 'vpc': vpc, 'peer-link': peer_link}
active_peer_link = None
if portchannel not in get_portchannel_list(module):
module.fail_json(msg="The portchannel you are trying to make a"
" VPC or PL is not created yet. "
"Create it first!")
if vpc:
mapping = get_existing_portchannel_to_vpc_mappings(module)
if vpc in mapping and portchannel != mapping[vpc].strip('Po'):
module.fail_json(msg="This vpc is already configured on "
"another portchannel. Remove it first "
"before trying to assign it here. ",
existing_portchannel=mapping[vpc])
for vpcid, existing_pc in mapping.items():
if portchannel == existing_pc.strip('Po') and vpcid != vpc:
module.fail_json(msg="This portchannel already has another"
" VPC configured. Remove it first "
"before assigning this one",
existing_vpc=vpcid)
if peer_link_exists(module):
active_peer_link = get_active_vpc_peer_link(module)
if active_peer_link[-2:] == portchannel:
module.fail_json(msg="That port channel is the current "
"PEER LINK. Remove it if you want it"
" to be a VPC")
config_value = vpc
elif peer_link is not None:
if peer_link_exists(module):
active_peer_link = get_active_vpc_peer_link(module)[2::]
if active_peer_link != portchannel:
if peer_link:
module.fail_json(msg="A peer link already exists on"
" the device. Remove it first",
current_peer_link='Po{0}'.format(
active_peer_link))
config_value = 'peer-link'
proposed = dict((k, v) for k, v in args.items() if v is not None)
existing = get_portchannel_vpc_config(module, portchannel)
end_state = existing
commands = []
if state == 'present':
delta = dict(set(proposed.items()).difference(existing.items()))
if delta:
command = get_commands_to_config_vpc_interface(
portchannel,
delta,
config_value,
existing
)
commands.append(command)
elif state == 'absent':
if existing.get('vpc'):
command = ['no vpc']
commands.append(command)
elif existing.get('peer-link'):
command = ['no vpc peer-link']
commands.append(command)
if commands:
commands.insert(0, ['interface port-channel{0}'.format(portchannel)])
cmds = flatten_list(commands)
if cmds:
if module.check_mode:
module.exit_json(changed=True, commands=cmds)
else:
changed = True
load_config(module, cmds)
if module.params['transport'] == 'cli':
output = ' '.join(output)
if 'error' in output.lower():
module.fail_json(msg=output.replace('\n', ''))
end_state = get_portchannel_vpc_config(module, portchannel)
if 'configure' in cmds:
cmds.pop(0)
results = {}
results['proposed'] = proposed
results['existing'] = existing
results['end_state'] = end_state
results['updates'] = cmds
results['changed'] = changed
results['warnings'] = warnings
module.exit_json(**results)
if __name__ == '__main__':
main()
|
infinity0/obfsproxy
|
obfsproxy/network/buffer.py
|
class Buffer(object):
"""
A Buffer is a simple FIFO buffer. You write() stuff to it, and you
read() them back. You can also peek() or drain() data.
"""
def __init__(self, data=''):
"""
Initialize a buffer with 'data'.
"""
self.buffer = bytes(data)
def read(self, n=-1):
"""
Read and return 'n' bytes from the buffer.
If 'n' is negative, read and return the whole buffer.
If 'n' is larger than the size of the buffer, read and return
the whole buffer.
"""
if (n < 0) or (n > len(self.buffer)):
the_whole_buffer = self.buffer
self.buffer = bytes('')
return the_whole_buffer
data = self.buffer[:n]
self.buffer = self.buffer[n:]
return data
def write(self, data):
"""
Append 'data' to the buffer.
"""
self.buffer = self.buffer + data
def peek(self, n=-1):
"""
Return 'n' bytes from the buffer, without draining them.
If 'n' is negative, return the whole buffer.
If 'n' is larger than the size of the buffer, return the whole
buffer.
"""
if (n < 0) or (n > len(self.buffer)):
return self.buffer
return self.buffer[:n]
def drain(self, n=-1):
"""
Drain 'n' bytes from the buffer.
If 'n' is negative, drain the whole buffer.
If 'n' is larger than the size of the buffer, drain the whole
buffer.
"""
if (n < 0) or (n > len(self.buffer)):
self.buffer = bytes('')
return
self.buffer = self.buffer[n:]
return
def __len__(self):
"""Returns length of buffer. Used in len()."""
return len(self.buffer)
def __nonzero__(self):
"""
Returns True if the buffer is non-empty.
Used in truth-value testing.
"""
return True if len(self.buffer) else False
|
Ormod/Diamond
|
src/diamond/handler/archive.py
|
# coding=utf-8
"""
Write the collected stats to a locally stored log file. Rotate the log file
every night and remove after 7 days.
"""
from Handler import Handler
import logging
import logging.handlers
class ArchiveHandler(Handler):
"""
Implements the Handler abstract class, archiving data to a log file
"""
def __init__(self, config):
"""
Create a new instance of the ArchiveHandler class
"""
# Initialize Handler
Handler.__init__(self, config)
# Create Archive Logger
self.archive = logging.getLogger('archive')
self.archive.setLevel(logging.DEBUG)
self.archive.propagate = self.config['propagate']
# Create Archive Log Formatter
formatter = logging.Formatter('%(message)s')
# Create Archive Log Handler
handler = logging.handlers.TimedRotatingFileHandler(
filename=self.config['log_file'],
when='midnight',
interval=1,
backupCount=int(self.config['days']),
encoding=self.config['encoding']
)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
self.archive.addHandler(handler)
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(ArchiveHandler, self).get_default_config_help()
config.update({
'log_file': 'Path to the logfile',
'days': 'How many days to store',
'encoding': '',
'propagate': 'Pass handled metrics to configured root logger',
})
return config
def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(ArchiveHandler, self).get_default_config()
config.update({
'log_file': '',
'days': 7,
'encoding': None,
'propagate': False,
})
return config
def process(self, metric):
"""
Send a Metric to the Archive.
"""
# Archive Metric
self.archive.info(str(metric).strip())
|
waseem18/oh-mainline
|
vendor/packages/Django/tests/regressiontests/servers/tests.py
|
# -*- encoding: utf-8 -*-
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import os
import socket
try:
from urllib.request import urlopen, HTTPError
except ImportError: # Python 2
from urllib2 import urlopen, HTTPError
from django.core.exceptions import ImproperlyConfigured
from django.test import LiveServerTestCase
from django.test.utils import override_settings
from django.utils.http import urlencode
from django.utils._os import upath
from .models import Person
TEST_ROOT = os.path.dirname(upath(__file__))
TEST_SETTINGS = {
'MEDIA_URL': '/media/',
'MEDIA_ROOT': os.path.join(TEST_ROOT, 'media'),
'STATIC_URL': '/static/',
'STATIC_ROOT': os.path.join(TEST_ROOT, 'static'),
}
class LiveServerBase(LiveServerTestCase):
urls = 'regressiontests.servers.urls'
fixtures = ['testdata.json']
@classmethod
def setUpClass(cls):
# Override settings
cls.settings_override = override_settings(**TEST_SETTINGS)
cls.settings_override.enable()
super(LiveServerBase, cls).setUpClass()
@classmethod
def tearDownClass(cls):
# Restore original settings
cls.settings_override.disable()
super(LiveServerBase, cls).tearDownClass()
def urlopen(self, url):
return urlopen(self.live_server_url + url)
class LiveServerAddress(LiveServerBase):
"""
Ensure that the address set in the environment variable is valid.
Refs #2879.
"""
@classmethod
def setUpClass(cls):
# Backup original environment variable
address_predefined = 'DJANGO_LIVE_TEST_SERVER_ADDRESS' in os.environ
old_address = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS')
# Just the host is not accepted
cls.raises_exception('localhost', ImproperlyConfigured)
# The host must be valid
cls.raises_exception('blahblahblah:8081', socket.error)
# The list of ports must be in a valid format
cls.raises_exception('localhost:8081,', ImproperlyConfigured)
cls.raises_exception('localhost:8081,blah', ImproperlyConfigured)
cls.raises_exception('localhost:8081-', ImproperlyConfigured)
cls.raises_exception('localhost:8081-blah', ImproperlyConfigured)
cls.raises_exception('localhost:8081-8082-8083', ImproperlyConfigured)
# If contrib.staticfiles isn't configured properly, the exception
# should bubble up to the main thread.
old_STATIC_URL = TEST_SETTINGS['STATIC_URL']
TEST_SETTINGS['STATIC_URL'] = None
cls.raises_exception('localhost:8081', ImproperlyConfigured)
TEST_SETTINGS['STATIC_URL'] = old_STATIC_URL
# Restore original environment variable
if address_predefined:
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = old_address
else:
del os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS']
@classmethod
def raises_exception(cls, address, exception):
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = address
try:
super(LiveServerAddress, cls).setUpClass()
raise Exception("The line above should have raised an exception")
except exception:
pass
finally:
super(LiveServerAddress, cls).tearDownClass()
def test_test_test(self):
# Intentionally empty method so that the test is picked up by the
# test runner and the overriden setUpClass() method is executed.
pass
class LiveServerViews(LiveServerBase):
def test_404(self):
"""
Ensure that the LiveServerTestCase serves 404s.
Refs #2879.
"""
try:
self.urlopen('/')
except HTTPError as err:
self.assertEqual(err.code, 404, 'Expected 404 response')
else:
self.fail('Expected 404 response')
def test_view(self):
"""
Ensure that the LiveServerTestCase serves views.
Refs #2879.
"""
f = self.urlopen('/example_view/')
self.assertEqual(f.read(), b'example view')
def test_static_files(self):
"""
Ensure that the LiveServerTestCase serves static files.
Refs #2879.
"""
f = self.urlopen('/static/example_static_file.txt')
self.assertEqual(f.read().rstrip(b'\r\n'), b'example static file')
def test_media_files(self):
"""
Ensure that the LiveServerTestCase serves media files.
Refs #2879.
"""
f = self.urlopen('/media/example_media_file.txt')
self.assertEqual(f.read().rstrip(b'\r\n'), b'example media file')
def test_environ(self):
f = self.urlopen('/environ_view/?%s' % urlencode({'q': 'тест'}))
self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read())
class LiveServerDatabase(LiveServerBase):
def test_fixtures_loaded(self):
"""
Ensure that fixtures are properly loaded and visible to the
live server thread.
Refs #2879.
"""
f = self.urlopen('/model_view/')
self.assertEqual(f.read().splitlines(), [b'jane', b'robert'])
def test_database_writes(self):
"""
Ensure that data written to the database by a view can be read.
Refs #2879.
"""
self.urlopen('/create_model_instance/')
self.assertQuerysetEqual(
Person.objects.all().order_by('pk'),
['jane', 'robert', 'emily'],
lambda b: b.name
)
|
AlericInglewood/3p-google-breakpad
|
src/tools/gyp/pylib/gyp/generator/scons.py
|
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import gyp
import gyp.common
import gyp.SCons as SCons
import os.path
import pprint
import re
# TODO: remove when we delete the last WriteList() call in this module
WriteList = SCons.WriteList
generator_default_variables = {
'EXECUTABLE_PREFIX': '',
'EXECUTABLE_SUFFIX': '',
'STATIC_LIB_PREFIX': '${LIBPREFIX}',
'SHARED_LIB_PREFIX': '${SHLIBPREFIX}',
'STATIC_LIB_SUFFIX': '${LIBSUFFIX}',
'SHARED_LIB_SUFFIX': '${SHLIBSUFFIX}',
'INTERMEDIATE_DIR': '${INTERMEDIATE_DIR}',
'SHARED_INTERMEDIATE_DIR': '${SHARED_INTERMEDIATE_DIR}',
'OS': 'linux',
'PRODUCT_DIR': '$TOP_BUILDDIR',
'SHARED_LIB_DIR': '$LIB_DIR',
'LIB_DIR': '$LIB_DIR',
'RULE_INPUT_ROOT': '${SOURCE.filebase}',
'RULE_INPUT_DIRNAME': '${SOURCE.dir}',
'RULE_INPUT_EXT': '${SOURCE.suffix}',
'RULE_INPUT_NAME': '${SOURCE.file}',
'RULE_INPUT_PATH': '${SOURCE.abspath}',
'CONFIGURATION_NAME': '${CONFIG_NAME}',
}
# Tell GYP how to process the input for us.
generator_handles_variants = True
generator_wants_absolute_build_file_paths = True
def FixPath(path, prefix):
if not os.path.isabs(path) and not path[0] == '$':
path = prefix + path
return path
header = """\
# This file is generated; do not edit.
"""
_alias_template = """
if GetOption('verbose'):
_action = Action([%(action)s])
else:
_action = Action([%(action)s], %(message)s)
_outputs = env.Alias(
['_%(target_name)s_action'],
%(inputs)s,
_action
)
env.AlwaysBuild(_outputs)
"""
_run_as_template = """
if GetOption('verbose'):
_action = Action([%(action)s])
else:
_action = Action([%(action)s], %(message)s)
"""
_run_as_template_suffix = """
_run_as_target = env.Alias('run_%(target_name)s', target_files, _action)
env.Requires(_run_as_target, [
Alias('%(target_name)s'),
])
env.AlwaysBuild(_run_as_target)
"""
_command_template = """
if GetOption('verbose'):
_action = Action([%(action)s])
else:
_action = Action([%(action)s], %(message)s)
_outputs = env.Command(
%(outputs)s,
%(inputs)s,
_action
)
"""
# This is copied from the default SCons action, updated to handle symlinks.
_copy_action_template = """
import shutil
import SCons.Action
def _copy_files_or_dirs_or_symlinks(dest, src):
SCons.Node.FS.invalidate_node_memos(dest)
if SCons.Util.is_List(src) and os.path.isdir(dest):
for file in src:
shutil.copy2(file, dest)
return 0
elif os.path.islink(src):
linkto = os.readlink(src)
os.symlink(linkto, dest)
return 0
elif os.path.isfile(src):
return shutil.copy2(src, dest)
else:
return shutil.copytree(src, dest, 1)
def _copy_files_or_dirs_or_symlinks_str(dest, src):
return 'Copying %s to %s ...' % (src, dest)
GYPCopy = SCons.Action.ActionFactory(_copy_files_or_dirs_or_symlinks,
_copy_files_or_dirs_or_symlinks_str,
convert=str)
"""
_rule_template = """
%(name)s_additional_inputs = %(inputs)s
%(name)s_outputs = %(outputs)s
def %(name)s_emitter(target, source, env):
return (%(name)s_outputs, source + %(name)s_additional_inputs)
if GetOption('verbose'):
%(name)s_action = Action([%(action)s])
else:
%(name)s_action = Action([%(action)s], %(message)s)
env['BUILDERS']['%(name)s'] = Builder(action=%(name)s_action,
emitter=%(name)s_emitter)
_outputs = []
_processed_input_files = []
for infile in input_files:
if (type(infile) == type('')
and not os.path.isabs(infile)
and not infile[0] == '$'):
infile = %(src_dir)r + infile
if str(infile).endswith('.%(extension)s'):
_generated = env.%(name)s(infile)
env.Precious(_generated)
_outputs.append(_generated)
%(process_outputs_as_sources_line)s
else:
_processed_input_files.append(infile)
prerequisites.extend(_outputs)
input_files = _processed_input_files
"""
_spawn_hack = """
import re
import SCons.Platform.posix
needs_shell = re.compile('["\\'><!^&]')
def gyp_spawn(sh, escape, cmd, args, env):
def strip_scons_quotes(arg):
if arg[0] == '"' and arg[-1] == '"':
return arg[1:-1]
return arg
stripped_args = [strip_scons_quotes(a) for a in args]
if needs_shell.search(' '.join(stripped_args)):
return SCons.Platform.posix.exec_spawnvpe([sh, '-c', ' '.join(args)], env)
else:
return SCons.Platform.posix.exec_spawnvpe(stripped_args, env)
"""
def EscapeShellArgument(s):
"""Quotes an argument so that it will be interpreted literally by a POSIX
shell. Taken from
http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
"""
return "'" + s.replace("'", "'\\''") + "'"
def InvertNaiveSConsQuoting(s):
"""SCons tries to "help" with quoting by naively putting double-quotes around
command-line arguments containing space or tab, which is broken for all
but trivial cases, so we undo it. (See quote_spaces() in Subst.py)"""
if ' ' in s or '\t' in s:
# Then SCons will put double-quotes around this, so add our own quotes
# to close its quotes at the beginning and end.
s = '"' + s + '"'
return s
def EscapeSConsVariableExpansion(s):
"""SCons has its own variable expansion syntax using $. We must escape it for
strings to be interpreted literally. For some reason this requires four
dollar signs, not two, even without the shell involved."""
return s.replace('$', '$$$$')
def EscapeCppDefine(s):
"""Escapes a CPP define so that it will reach the compiler unaltered."""
s = EscapeShellArgument(s)
s = InvertNaiveSConsQuoting(s)
s = EscapeSConsVariableExpansion(s)
return s
def GenerateConfig(fp, config, indent='', src_dir=''):
"""
Generates SCons dictionary items for a gyp configuration.
This provides the main translation between the (lower-case) gyp settings
keywords and the (upper-case) SCons construction variables.
"""
var_mapping = {
'ASFLAGS' : 'asflags',
'CCFLAGS' : 'cflags',
'CFLAGS' : 'cflags_c',
'CXXFLAGS' : 'cflags_cc',
'CPPDEFINES' : 'defines',
'CPPPATH' : 'include_dirs',
# Add the ldflags value to $LINKFLAGS, but not $SHLINKFLAGS.
# SCons defines $SHLINKFLAGS to incorporate $LINKFLAGS, so
# listing both here would case 'ldflags' to get appended to
# both, and then have it show up twice on the command line.
'LINKFLAGS' : 'ldflags',
}
postamble='\n%s],\n' % indent
for scons_var in sorted(var_mapping.keys()):
gyp_var = var_mapping[scons_var]
value = config.get(gyp_var)
if value:
if gyp_var in ('defines',):
value = [EscapeCppDefine(v) for v in value]
if gyp_var in ('include_dirs',):
if src_dir and not src_dir.endswith('/'):
src_dir += '/'
result = []
for v in value:
v = FixPath(v, src_dir)
# Force SCons to evaluate the CPPPATH directories at
# SConscript-read time, so delayed evaluation of $SRC_DIR
# doesn't point it to the --generator-output= directory.
result.append('env.Dir(%r)' % v)
value = result
else:
value = map(repr, value)
WriteList(fp,
value,
prefix=indent,
preamble='%s%s = [\n ' % (indent, scons_var),
postamble=postamble)
def GenerateSConscript(output_filename, spec, build_file, build_file_data):
"""
Generates a SConscript file for a specific target.
This generates a SConscript file suitable for building any or all of
the target's configurations.
A SConscript file may be called multiple times to generate targets for
multiple configurations. Consequently, it needs to be ready to build
the target for any requested configuration, and therefore contains
information about the settings for all configurations (generated into
the SConscript file at gyp configuration time) as well as logic for
selecting (at SCons build time) the specific configuration being built.
The general outline of a generated SConscript file is:
-- Header
-- Import 'env'. This contains a $CONFIG_NAME construction
variable that specifies what configuration to build
(e.g. Debug, Release).
-- Configurations. This is a dictionary with settings for
the different configurations (Debug, Release) under which this
target can be built. The values in the dictionary are themselves
dictionaries specifying what construction variables should added
to the local copy of the imported construction environment
(Append), should be removed (FilterOut), and should outright
replace the imported values (Replace).
-- Clone the imported construction environment and update
with the proper configuration settings.
-- Initialize the lists of the targets' input files and prerequisites.
-- Target-specific actions and rules. These come after the
input file and prerequisite initializations because the
outputs of the actions and rules may affect the input file
list (process_outputs_as_sources) and get added to the list of
prerequisites (so that they're guaranteed to be executed before
building the target).
-- Call the Builder for the target itself.
-- Arrange for any copies to be made into installation directories.
-- Set up the {name} Alias (phony Node) for the target as the
primary handle for building all of the target's pieces.
-- Use env.Require() to make sure the prerequisites (explicitly
specified, but also including the actions and rules) are built
before the target itself.
-- Return the {name} Alias to the calling SConstruct file
so it can be added to the list of default targets.
"""
scons_target = SCons.Target(spec)
gyp_dir = os.path.dirname(output_filename)
if not gyp_dir:
gyp_dir = '.'
gyp_dir = os.path.abspath(gyp_dir)
output_dir = os.path.dirname(output_filename)
src_dir = build_file_data['_DEPTH']
src_dir_rel = gyp.common.RelativePath(src_dir, output_dir)
subdir = gyp.common.RelativePath(os.path.dirname(build_file), src_dir)
src_subdir = '$SRC_DIR/' + subdir
src_subdir_ = src_subdir + '/'
component_name = os.path.splitext(os.path.basename(build_file))[0]
target_name = spec['target_name']
if not os.path.exists(gyp_dir):
os.makedirs(gyp_dir)
fp = open(output_filename, 'w')
fp.write(header)
fp.write('\nimport os\n')
fp.write('\nImport("env")\n')
#
fp.write('\n')
fp.write('env = env.Clone(COMPONENT_NAME=%s,\n' % repr(component_name))
fp.write(' TARGET_NAME=%s)\n' % repr(target_name))
#
for config in spec['configurations'].itervalues():
if config.get('scons_line_length'):
fp.write(_spawn_hack)
break
#
indent = ' ' * 12
fp.write('\n')
fp.write('configurations = {\n')
for config_name, config in spec['configurations'].iteritems():
fp.write(' \'%s\' : {\n' % config_name)
fp.write(' \'Append\' : dict(\n')
GenerateConfig(fp, config, indent, src_subdir)
libraries = spec.get('libraries')
if libraries:
WriteList(fp,
map(repr, libraries),
prefix=indent,
preamble='%sLIBS = [\n ' % indent,
postamble='\n%s],\n' % indent)
fp.write(' ),\n')
fp.write(' \'FilterOut\' : dict(\n' )
for key, var in config.get('scons_remove', {}).iteritems():
fp.write(' %s = %s,\n' % (key, repr(var)))
fp.write(' ),\n')
fp.write(' \'Replace\' : dict(\n' )
scons_settings = config.get('scons_variable_settings', {})
for key in sorted(scons_settings.keys()):
val = pprint.pformat(scons_settings[key])
fp.write(' %s = %s,\n' % (key, val))
if 'c++' in spec.get('link_languages', []):
fp.write(' %s = %s,\n' % ('LINK', repr('$CXX')))
if config.get('scons_line_length'):
fp.write(' SPAWN = gyp_spawn,\n')
fp.write(' ),\n')
fp.write(' \'ImportExternal\' : [\n' )
for var in config.get('scons_import_variables', []):
fp.write(' %s,\n' % repr(var))
fp.write(' ],\n')
fp.write(' \'PropagateExternal\' : [\n' )
for var in config.get('scons_propagate_variables', []):
fp.write(' %s,\n' % repr(var))
fp.write(' ],\n')
fp.write(' },\n')
fp.write('}\n')
fp.write('\n'
'config = configurations[env[\'CONFIG_NAME\']]\n'
'env.Append(**config[\'Append\'])\n'
'env.FilterOut(**config[\'FilterOut\'])\n'
'env.Replace(**config[\'Replace\'])\n')
fp.write('\n'
'# Scons forces -fPIC for SHCCFLAGS on some platforms.\n'
'# Disable that so we can control it from cflags in gyp.\n'
'# Note that Scons itself is inconsistent with its -fPIC\n'
'# setting. SHCCFLAGS forces -fPIC, and SHCFLAGS does not.\n'
'# This will make SHCCFLAGS consistent with SHCFLAGS.\n'
'env[\'SHCCFLAGS\'] = [\'$CCFLAGS\']\n')
fp.write('\n'
'for _var in config[\'ImportExternal\']:\n'
' if _var in ARGUMENTS:\n'
' env[_var] = ARGUMENTS[_var]\n'
' elif _var in os.environ:\n'
' env[_var] = os.environ[_var]\n'
'for _var in config[\'PropagateExternal\']:\n'
' if _var in ARGUMENTS:\n'
' env[_var] = ARGUMENTS[_var]\n'
' elif _var in os.environ:\n'
' env[\'ENV\'][_var] = os.environ[_var]\n')
fp.write('\n'
"env['ENV']['LD_LIBRARY_PATH'] = env.subst('$LIB_DIR')\n")
#
#fp.write("\nif env.has_key('CPPPATH'):\n")
#fp.write(" env['CPPPATH'] = map(env.Dir, env['CPPPATH'])\n")
variants = spec.get('variants', {})
for setting in sorted(variants.keys()):
if_fmt = 'if ARGUMENTS.get(%s) not in (None, \'0\'):\n'
fp.write('\n')
fp.write(if_fmt % repr(setting.upper()))
fp.write(' env.AppendUnique(\n')
GenerateConfig(fp, variants[setting], indent, src_subdir)
fp.write(' )\n')
#
scons_target.write_input_files(fp)
fp.write('\n')
fp.write('target_files = []\n')
prerequisites = spec.get('scons_prerequisites', [])
fp.write('prerequisites = %s\n' % pprint.pformat(prerequisites))
actions = spec.get('actions', [])
for action in actions:
a = ['cd', src_subdir, '&&'] + action['action']
message = action.get('message')
if message:
message = repr(message)
inputs = [FixPath(f, src_subdir_) for f in action.get('inputs', [])]
outputs = [FixPath(f, src_subdir_) for f in action.get('outputs', [])]
if outputs:
template = _command_template
else:
template = _alias_template
fp.write(template % {
'inputs' : pprint.pformat(inputs),
'outputs' : pprint.pformat(outputs),
'action' : pprint.pformat(a),
'message' : message,
'target_name': target_name,
})
if int(action.get('process_outputs_as_sources', 0)):
fp.write('input_files.extend(_outputs)\n')
fp.write('prerequisites.extend(_outputs)\n')
fp.write('target_files.extend(_outputs)\n')
rules = spec.get('rules', [])
for rule in rules:
name = re.sub('[^a-zA-Z0-9_]', '_', rule['rule_name'])
message = rule.get('message')
if message:
message = repr(message)
if int(rule.get('process_outputs_as_sources', 0)):
poas_line = '_processed_input_files.extend(_generated)'
else:
poas_line = '_processed_input_files.append(infile)'
inputs = [FixPath(f, src_subdir_) for f in rule.get('inputs', [])]
outputs = [FixPath(f, src_subdir_) for f in rule.get('outputs', [])]
# Skip a rule with no action and no inputs.
if 'action' not in rule and not rule.get('rule_sources', []):
continue
a = ['cd', src_subdir, '&&'] + rule['action']
fp.write(_rule_template % {
'inputs' : pprint.pformat(inputs),
'outputs' : pprint.pformat(outputs),
'action' : pprint.pformat(a),
'extension' : rule['extension'],
'name' : name,
'message' : message,
'process_outputs_as_sources_line' : poas_line,
'src_dir' : src_subdir_,
})
scons_target.write_target(fp, src_subdir)
copies = spec.get('copies', [])
if copies:
fp.write(_copy_action_template)
for copy in copies:
destdir = None
files = None
try:
destdir = copy['destination']
except KeyError, e:
gyp.common.ExceptionAppend(
e,
"Required 'destination' key missing for 'copies' in %s." % build_file)
raise
try:
files = copy['files']
except KeyError, e:
gyp.common.ExceptionAppend(
e, "Required 'files' key missing for 'copies' in %s." % build_file)
raise
if not files:
# TODO: should probably add a (suppressible) warning;
# a null file list may be unintentional.
continue
if not destdir:
raise Exception(
"Required 'destination' key is empty for 'copies' in %s." % build_file)
fmt = ('\n'
'_outputs = env.Command(%s,\n'
' %s,\n'
' GYPCopy(\'$TARGET\', \'$SOURCE\'))\n')
for f in copy['files']:
# Remove trailing separators so basename() acts like Unix basename and
# always returns the last element, whether a file or dir. Without this,
# only the contents, not the directory itself, are copied (and nothing
# might be copied if dest already exists, since scons thinks nothing needs
# to be done).
dest = os.path.join(destdir, os.path.basename(f.rstrip(os.sep)))
f = FixPath(f, src_subdir_)
dest = FixPath(dest, src_subdir_)
fp.write(fmt % (repr(dest), repr(f)))
fp.write('target_files.extend(_outputs)\n')
run_as = spec.get('run_as')
if run_as:
action = run_as.get('action', [])
working_directory = run_as.get('working_directory')
if not working_directory:
working_directory = gyp_dir
else:
if not os.path.isabs(working_directory):
working_directory = os.path.normpath(os.path.join(gyp_dir,
working_directory))
if run_as.get('environment'):
for (key, val) in run_as.get('environment').iteritems():
action = ['%s="%s"' % (key, val)] + action
action = ['cd', '"%s"' % working_directory, '&&'] + action
fp.write(_run_as_template % {
'action' : pprint.pformat(action),
'message' : run_as.get('message', ''),
})
fmt = "\ngyp_target = env.Alias('%s', target_files)\n"
fp.write(fmt % target_name)
dependencies = spec.get('scons_dependencies', [])
if dependencies:
WriteList(fp, dependencies, preamble='dependencies = [\n ',
postamble='\n]\n')
fp.write('env.Requires(target_files, dependencies)\n')
fp.write('env.Requires(gyp_target, dependencies)\n')
fp.write('for prerequisite in prerequisites:\n')
fp.write(' env.Requires(prerequisite, dependencies)\n')
fp.write('env.Requires(gyp_target, prerequisites)\n')
if run_as:
fp.write(_run_as_template_suffix % {
'target_name': target_name,
})
fp.write('Return("gyp_target")\n')
fp.close()
#############################################################################
# TEMPLATE BEGIN
_wrapper_template = """\
__doc__ = '''
Wrapper configuration for building this entire "solution,"
including all the specific targets in various *.scons files.
'''
import os
import sys
import SCons.Environment
import SCons.Util
def GetProcessorCount():
'''
Detects the number of CPUs on the system. Adapted form:
http://codeliberates.blogspot.com/2008/05/detecting-cpuscores-in-python.html
'''
# Linux, Unix and Mac OS X:
if hasattr(os, 'sysconf'):
if os.sysconf_names.has_key('SC_NPROCESSORS_ONLN'):
# Linux and Unix or Mac OS X with python >= 2.5:
return os.sysconf('SC_NPROCESSORS_ONLN')
else: # Mac OS X with Python < 2.5:
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
# Windows:
if os.environ.has_key('NUMBER_OF_PROCESSORS'):
return max(int(os.environ.get('NUMBER_OF_PROCESSORS', '1')), 1)
return 1 # Default
# Support PROGRESS= to show progress in different ways.
p = ARGUMENTS.get('PROGRESS')
if p == 'spinner':
Progress(['/\\r', '|\\r', '\\\\\\r', '-\\r'],
interval=5,
file=open('/dev/tty', 'w'))
elif p == 'name':
Progress('$TARGET\\r', overwrite=True, file=open('/dev/tty', 'w'))
# Set the default -j value based on the number of processors.
SetOption('num_jobs', GetProcessorCount() + 1)
# Have SCons use its cached dependency information.
SetOption('implicit_cache', 1)
# Only re-calculate MD5 checksums if a timestamp has changed.
Decider('MD5-timestamp')
# Since we set the -j value by default, suppress SCons warnings about being
# unable to support parallel build on versions of Python with no threading.
default_warnings = ['no-no-parallel-support']
SetOption('warn', default_warnings + GetOption('warn'))
AddOption('--mode', nargs=1, dest='conf_list', default=[],
action='append', help='Configuration to build.')
AddOption('--verbose', dest='verbose', default=False,
action='store_true', help='Verbose command-line output.')
#
sconscript_file_map = %(sconscript_files)s
class LoadTarget:
'''
Class for deciding if a given target sconscript is to be included
based on a list of included target names, optionally prefixed with '-'
to exclude a target name.
'''
def __init__(self, load):
'''
Initialize a class with a list of names for possible loading.
Arguments:
load: list of elements in the LOAD= specification
'''
self.included = set([c for c in load if not c.startswith('-')])
self.excluded = set([c[1:] for c in load if c.startswith('-')])
if not self.included:
self.included = set(['all'])
def __call__(self, target):
'''
Returns True if the specified target's sconscript file should be
loaded, based on the initialized included and excluded lists.
'''
return (target in self.included or
('all' in self.included and not target in self.excluded))
if 'LOAD' in ARGUMENTS:
load = ARGUMENTS['LOAD'].split(',')
else:
load = []
load_target = LoadTarget(load)
sconscript_files = []
for target, sconscript in sconscript_file_map.iteritems():
if load_target(target):
sconscript_files.append(sconscript)
target_alias_list= []
conf_list = GetOption('conf_list')
if conf_list:
# In case the same --mode= value was specified multiple times.
conf_list = list(set(conf_list))
else:
conf_list = [%(default_configuration)r]
sconsbuild_dir = Dir(%(sconsbuild_dir)s)
def FilterOut(self, **kw):
kw = SCons.Environment.copy_non_reserved_keywords(kw)
for key, val in kw.items():
envval = self.get(key, None)
if envval is None:
# No existing variable in the environment, so nothing to delete.
continue
for vremove in val:
# Use while not if, so we can handle duplicates.
while vremove in envval:
envval.remove(vremove)
self[key] = envval
# TODO(sgk): SCons.Environment.Append() has much more logic to deal
# with various types of values. We should handle all those cases in here
# too. (If variable is a dict, etc.)
non_compilable_suffixes = {
'LINUX' : set([
'.bdic',
'.css',
'.dat',
'.fragment',
'.gperf',
'.h',
'.hh',
'.hpp',
'.html',
'.hxx',
'.idl',
'.in',
'.in0',
'.in1',
'.js',
'.mk',
'.rc',
'.sigs',
'',
]),
'WINDOWS' : set([
'.h',
'.hh',
'.hpp',
'.dat',
'.idl',
'.in',
'.in0',
'.in1',
]),
}
def compilable(env, file):
base, ext = os.path.splitext(str(file))
if ext in non_compilable_suffixes[env['TARGET_PLATFORM']]:
return False
return True
def compilable_files(env, sources):
return [x for x in sources if compilable(env, x)]
def GypProgram(env, target, source, *args, **kw):
source = compilable_files(env, source)
result = env.Program(target, source, *args, **kw)
if env.get('INCREMENTAL'):
env.Precious(result)
return result
def GypTestProgram(env, target, source, *args, **kw):
source = compilable_files(env, source)
result = env.Program(target, source, *args, **kw)
if env.get('INCREMENTAL'):
env.Precious(*result)
return result
def GypLibrary(env, target, source, *args, **kw):
source = compilable_files(env, source)
result = env.Library(target, source, *args, **kw)
return result
def GypLoadableModule(env, target, source, *args, **kw):
source = compilable_files(env, source)
result = env.LoadableModule(target, source, *args, **kw)
return result
def GypStaticLibrary(env, target, source, *args, **kw):
source = compilable_files(env, source)
result = env.StaticLibrary(target, source, *args, **kw)
return result
def GypSharedLibrary(env, target, source, *args, **kw):
source = compilable_files(env, source)
result = env.SharedLibrary(target, source, *args, **kw)
if env.get('INCREMENTAL'):
env.Precious(result)
return result
def add_gyp_methods(env):
env.AddMethod(GypProgram)
env.AddMethod(GypTestProgram)
env.AddMethod(GypLibrary)
env.AddMethod(GypLoadableModule)
env.AddMethod(GypStaticLibrary)
env.AddMethod(GypSharedLibrary)
env.AddMethod(FilterOut)
env.AddMethod(compilable)
base_env = Environment(
tools = %(scons_tools)s,
INTERMEDIATE_DIR='$OBJ_DIR/${COMPONENT_NAME}/_${TARGET_NAME}_intermediate',
LIB_DIR='$TOP_BUILDDIR/lib',
OBJ_DIR='$TOP_BUILDDIR/obj',
SCONSBUILD_DIR=sconsbuild_dir.abspath,
SHARED_INTERMEDIATE_DIR='$OBJ_DIR/_global_intermediate',
SRC_DIR=Dir(%(src_dir)r),
TARGET_PLATFORM='LINUX',
TOP_BUILDDIR='$SCONSBUILD_DIR/$CONFIG_NAME',
LIBPATH=['$LIB_DIR'],
)
if not GetOption('verbose'):
base_env.SetDefault(
ARCOMSTR='Creating library $TARGET',
ASCOMSTR='Assembling $TARGET',
CCCOMSTR='Compiling $TARGET',
CONCATSOURCECOMSTR='ConcatSource $TARGET',
CXXCOMSTR='Compiling $TARGET',
LDMODULECOMSTR='Building loadable module $TARGET',
LINKCOMSTR='Linking $TARGET',
MANIFESTCOMSTR='Updating manifest for $TARGET',
MIDLCOMSTR='Compiling IDL $TARGET',
PCHCOMSTR='Precompiling $TARGET',
RANLIBCOMSTR='Indexing $TARGET',
RCCOMSTR='Compiling resource $TARGET',
SHCCCOMSTR='Compiling $TARGET',
SHCXXCOMSTR='Compiling $TARGET',
SHLINKCOMSTR='Linking $TARGET',
SHMANIFESTCOMSTR='Updating manifest for $TARGET',
)
add_gyp_methods(base_env)
for conf in conf_list:
env = base_env.Clone(CONFIG_NAME=conf)
SConsignFile(env.File('$TOP_BUILDDIR/.sconsign').abspath)
for sconscript in sconscript_files:
target_alias = env.SConscript(sconscript, exports=['env'])
if target_alias:
target_alias_list.extend(target_alias)
Default(Alias('all', target_alias_list))
help_fmt = '''
Usage: hammer [SCONS_OPTIONS] [VARIABLES] [TARGET] ...
Local command-line build options:
--mode=CONFIG Configuration to build:
--mode=Debug [default]
--mode=Release
--verbose Print actual executed command lines.
Supported command-line build variables:
LOAD=[module,...] Comma-separated list of components to load in the
dependency graph ('-' prefix excludes)
PROGRESS=type Display a progress indicator:
name: print each evaluated target name
spinner: print a spinner every 5 targets
The following TARGET names can also be used as LOAD= module names:
%%s
'''
if GetOption('help'):
def columnar_text(items, width=78, indent=2, sep=2):
result = []
colwidth = max(map(len, items)) + sep
cols = (width - indent) / colwidth
if cols < 1:
cols = 1
rows = (len(items) + cols - 1) / cols
indent = '%%*s' %% (indent, '')
sep = indent
for row in xrange(0, rows):
result.append(sep)
for i in xrange(row, len(items), rows):
result.append('%%-*s' %% (colwidth, items[i]))
sep = '\\n' + indent
result.append('\\n')
return ''.join(result)
load_list = set(sconscript_file_map.keys())
target_aliases = set(map(str, target_alias_list))
common = load_list and target_aliases
load_only = load_list - common
target_only = target_aliases - common
help_text = [help_fmt %% columnar_text(sorted(list(common)))]
if target_only:
fmt = "The following are additional TARGET names:\\n\\n%%s\\n"
help_text.append(fmt %% columnar_text(sorted(list(target_only))))
if load_only:
fmt = "The following are additional LOAD= module names:\\n\\n%%s\\n"
help_text.append(fmt %% columnar_text(sorted(list(load_only))))
Help(''.join(help_text))
"""
# TEMPLATE END
#############################################################################
def GenerateSConscriptWrapper(build_file, build_file_data, name,
output_filename, sconscript_files,
default_configuration):
"""
Generates the "wrapper" SConscript file (analogous to the Visual Studio
solution) that calls all the individual target SConscript files.
"""
output_dir = os.path.dirname(output_filename)
src_dir = build_file_data['_DEPTH']
src_dir_rel = gyp.common.RelativePath(src_dir, output_dir)
if not src_dir_rel:
src_dir_rel = '.'
scons_settings = build_file_data.get('scons_settings', {})
sconsbuild_dir = scons_settings.get('sconsbuild_dir', '#')
scons_tools = scons_settings.get('tools', ['default'])
sconscript_file_lines = ['dict(']
for target in sorted(sconscript_files.keys()):
sconscript = sconscript_files[target]
sconscript_file_lines.append(' %s = %r,' % (target, sconscript))
sconscript_file_lines.append(')')
fp = open(output_filename, 'w')
fp.write(header)
fp.write(_wrapper_template % {
'default_configuration' : default_configuration,
'name' : name,
'scons_tools' : repr(scons_tools),
'sconsbuild_dir' : repr(sconsbuild_dir),
'sconscript_files' : '\n'.join(sconscript_file_lines),
'src_dir' : src_dir_rel,
})
fp.close()
# Generate the SConstruct file that invokes the wrapper SConscript.
dir, fname = os.path.split(output_filename)
SConstruct = os.path.join(dir, 'SConstruct')
fp = open(SConstruct, 'w')
fp.write(header)
fp.write('SConscript(%s)\n' % repr(fname))
fp.close()
def TargetFilename(target, build_file=None, output_suffix=''):
"""Returns the .scons file name for the specified target.
"""
if build_file is None:
build_file, target = gyp.common.ParseQualifiedTarget(target)[:2]
output_file = os.path.join(os.path.dirname(build_file),
target + output_suffix + '.scons')
return output_file
def GenerateOutput(target_list, target_dicts, data, params):
"""
Generates all the output files for the specified targets.
"""
options = params['options']
if options.generator_output:
def output_path(filename):
return filename.replace(params['cwd'], options.generator_output)
else:
def output_path(filename):
return filename
default_configuration = None
for qualified_target in target_list:
spec = target_dicts[qualified_target]
if spec['toolset'] != 'target':
raise Exception(
'Multiple toolsets not supported in scons build (target %s)' %
qualified_target)
scons_target = SCons.Target(spec)
if scons_target.is_ignored:
continue
# TODO: assumes the default_configuration of the first target
# non-Default target is the correct default for all targets.
# Need a better model for handle variation between targets.
if (not default_configuration and
spec['default_configuration'] != 'Default'):
default_configuration = spec['default_configuration']
build_file, target = gyp.common.ParseQualifiedTarget(qualified_target)[:2]
output_file = TargetFilename(target, build_file, options.suffix)
if options.generator_output:
output_file = output_path(output_file)
if not spec.has_key('libraries'):
spec['libraries'] = []
# Add dependent static library targets to the 'libraries' value.
deps = spec.get('dependencies', [])
spec['scons_dependencies'] = []
for d in deps:
td = target_dicts[d]
target_name = td['target_name']
spec['scons_dependencies'].append("Alias('%s')" % target_name)
if td['type'] in ('static_library', 'shared_library'):
libname = td.get('product_name', target_name)
spec['libraries'].append('lib' + libname)
if td['type'] == 'loadable_module':
prereqs = spec.get('scons_prerequisites', [])
# TODO: parameterize with <(SHARED_LIBRARY_*) variables?
td_target = SCons.Target(td)
td_target.target_prefix = '${SHLIBPREFIX}'
td_target.target_suffix = '${SHLIBSUFFIX}'
GenerateSConscript(output_file, spec, build_file, data[build_file])
if not default_configuration:
default_configuration = 'Default'
for build_file in sorted(data.keys()):
path, ext = os.path.splitext(build_file)
if ext != '.gyp':
continue
output_dir, basename = os.path.split(path)
output_filename = path + '_main' + options.suffix + '.scons'
all_targets = gyp.common.AllTargets(target_list, target_dicts, build_file)
sconscript_files = {}
for t in all_targets:
scons_target = SCons.Target(target_dicts[t])
if scons_target.is_ignored:
continue
bf, target = gyp.common.ParseQualifiedTarget(t)[:2]
target_filename = TargetFilename(target, bf, options.suffix)
tpath = gyp.common.RelativePath(target_filename, output_dir)
sconscript_files[target] = tpath
output_filename = output_path(output_filename)
if sconscript_files:
GenerateSConscriptWrapper(build_file, data[build_file], basename,
output_filename, sconscript_files,
default_configuration)
|
adamwwt/chvac
|
venv/lib/python2.7/site-packages/sqlalchemy/events.py
|
# sqlalchemy/events.py
# Copyright (C) 2005-2015 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
"""Core event interfaces."""
from . import event, exc
from .pool import Pool
from .engine import Connectable, Engine, Dialect
from .sql.base import SchemaEventTarget
class DDLEvents(event.Events):
"""
Define event listeners for schema objects,
that is, :class:`.SchemaItem` and other :class:`.SchemaEventTarget`
subclasses, including :class:`.MetaData`, :class:`.Table`,
:class:`.Column`.
:class:`.MetaData` and :class:`.Table` support events
specifically regarding when CREATE and DROP
DDL is emitted to the database.
Attachment events are also provided to customize
behavior whenever a child schema element is associated
with a parent, such as, when a :class:`.Column` is associated
with its :class:`.Table`, when a :class:`.ForeignKeyConstraint`
is associated with a :class:`.Table`, etc.
Example using the ``after_create`` event::
from sqlalchemy import event
from sqlalchemy import Table, Column, Metadata, Integer
m = MetaData()
some_table = Table('some_table', m, Column('data', Integer))
def after_create(target, connection, **kw):
connection.execute("ALTER TABLE %s SET name=foo_%s" %
(target.name, target.name))
event.listen(some_table, "after_create", after_create)
DDL events integrate closely with the
:class:`.DDL` class and the :class:`.DDLElement` hierarchy
of DDL clause constructs, which are themselves appropriate
as listener callables::
from sqlalchemy import DDL
event.listen(
some_table,
"after_create",
DDL("ALTER TABLE %(table)s SET name=foo_%(table)s")
)
The methods here define the name of an event as well
as the names of members that are passed to listener
functions.
See also:
:ref:`event_toplevel`
:class:`.DDLElement`
:class:`.DDL`
:ref:`schema_ddl_sequences`
"""
_target_class_doc = "SomeSchemaClassOrObject"
_dispatch_target = SchemaEventTarget
def before_create(self, target, connection, **kw):
"""Called before CREATE statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
CREATE statement or statements will be emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def after_create(self, target, connection, **kw):
"""Called after CREATE statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
CREATE statement or statements have been emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def before_drop(self, target, connection, **kw):
"""Called before DROP statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
DROP statement or statements will be emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def after_drop(self, target, connection, **kw):
"""Called after DROP statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
DROP statement or statements have been emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def before_parent_attach(self, target, parent):
"""Called before a :class:`.SchemaItem` is associated with
a parent :class:`.SchemaItem`.
:param target: the target object
:param parent: the parent to which the target is being attached.
:func:`.event.listen` also accepts a modifier for this event:
:param propagate=False: When True, the listener function will
be established for any copies made of the target object,
i.e. those copies that are generated when
:meth:`.Table.tometadata` is used.
"""
def after_parent_attach(self, target, parent):
"""Called after a :class:`.SchemaItem` is associated with
a parent :class:`.SchemaItem`.
:param target: the target object
:param parent: the parent to which the target is being attached.
:func:`.event.listen` also accepts a modifier for this event:
:param propagate=False: When True, the listener function will
be established for any copies made of the target object,
i.e. those copies that are generated when
:meth:`.Table.tometadata` is used.
"""
def column_reflect(self, inspector, table, column_info):
"""Called for each unit of 'column info' retrieved when
a :class:`.Table` is being reflected.
The dictionary of column information as returned by the
dialect is passed, and can be modified. The dictionary
is that returned in each element of the list returned
by :meth:`.reflection.Inspector.get_columns`.
The event is called before any action is taken against
this dictionary, and the contents can be modified.
The :class:`.Column` specific arguments ``info``, ``key``,
and ``quote`` can also be added to the dictionary and
will be passed to the constructor of :class:`.Column`.
Note that this event is only meaningful if either
associated with the :class:`.Table` class across the
board, e.g.::
from sqlalchemy.schema import Table
from sqlalchemy import event
def listen_for_reflect(inspector, table, column_info):
"receive a column_reflect event"
# ...
event.listen(
Table,
'column_reflect',
listen_for_reflect)
...or with a specific :class:`.Table` instance using
the ``listeners`` argument::
def listen_for_reflect(inspector, table, column_info):
"receive a column_reflect event"
# ...
t = Table(
'sometable',
autoload=True,
listeners=[
('column_reflect', listen_for_reflect)
])
This because the reflection process initiated by ``autoload=True``
completes within the scope of the constructor for :class:`.Table`.
"""
class PoolEvents(event.Events):
"""Available events for :class:`.Pool`.
The methods here define the name of an event as well
as the names of members that are passed to listener
functions.
e.g.::
from sqlalchemy import event
def my_on_checkout(dbapi_conn, connection_rec, connection_proxy):
"handle an on checkout event"
event.listen(Pool, 'checkout', my_on_checkout)
In addition to accepting the :class:`.Pool` class and
:class:`.Pool` instances, :class:`.PoolEvents` also accepts
:class:`.Engine` objects and the :class:`.Engine` class as
targets, which will be resolved to the ``.pool`` attribute of the
given engine or the :class:`.Pool` class::
engine = create_engine("postgresql://scott:tiger@localhost/test")
# will associate with engine.pool
event.listen(engine, 'checkout', my_on_checkout)
"""
_target_class_doc = "SomeEngineOrPool"
_dispatch_target = Pool
@classmethod
def _accept_with(cls, target):
if isinstance(target, type):
if issubclass(target, Engine):
return Pool
elif issubclass(target, Pool):
return target
elif isinstance(target, Engine):
return target.pool
else:
return target
def connect(self, dbapi_connection, connection_record):
"""Called at the moment a particular DBAPI connection is first
created for a given :class:`.Pool`.
This event allows one to capture the point directly after which
the DBAPI module-level ``.connect()`` method has been used in order
to produce a new DBAPI connection.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
"""
def first_connect(self, dbapi_connection, connection_record):
"""Called exactly once for the first time a DBAPI connection is
checked out from a particular :class:`.Pool`.
The rationale for :meth:`.PoolEvents.first_connect` is to determine
information about a particular series of database connections based
on the settings used for all connections. Since a particular
:class:`.Pool` refers to a single "creator" function (which in terms
of a :class:`.Engine` refers to the URL and connection options used),
it is typically valid to make observations about a single connection
that can be safely assumed to be valid about all subsequent
connections, such as the database version, the server and client
encoding settings, collation settings, and many others.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
"""
def checkout(self, dbapi_connection, connection_record, connection_proxy):
"""Called when a connection is retrieved from the Pool.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
:param connection_proxy: the :class:`._ConnectionFairy` object which
will proxy the public interface of the DBAPI connection for the
lifespan of the checkout.
If you raise a :class:`~sqlalchemy.exc.DisconnectionError`, the current
connection will be disposed and a fresh connection retrieved.
Processing of all checkout listeners will abort and restart
using the new connection.
.. seealso:: :meth:`.ConnectionEvents.engine_connect` - a similar event
which occurs upon creation of a new :class:`.Connection`.
"""
def checkin(self, dbapi_connection, connection_record):
"""Called when a connection returns to the pool.
Note that the connection may be closed, and may be None if the
connection has been invalidated. ``checkin`` will not be called
for detached connections. (They do not return to the pool.)
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
"""
def reset(self, dbapi_connnection, connection_record):
"""Called before the "reset" action occurs for a pooled connection.
This event represents
when the ``rollback()`` method is called on the DBAPI connection
before it is returned to the pool. The behavior of "reset" can
be controlled, including disabled, using the ``reset_on_return``
pool argument.
The :meth:`.PoolEvents.reset` event is usually followed by the
:meth:`.PoolEvents.checkin` event is called, except in those
cases where the connection is discarded immediately after reset.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
.. versionadded:: 0.8
.. seealso::
:meth:`.ConnectionEvents.rollback`
:meth:`.ConnectionEvents.commit`
"""
def invalidate(self, dbapi_connection, connection_record, exception):
"""Called when a DBAPI connection is to be "invalidated".
This event is called any time the :meth:`._ConnectionRecord.invalidate`
method is invoked, either from API usage or via "auto-invalidation".
The event occurs before a final attempt to call ``.close()`` on the
connection occurs.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
:param exception: the exception object corresponding to the reason
for this invalidation, if any. May be ``None``.
.. versionadded:: 0.9.2 Added support for connection invalidation
listening.
.. seealso::
:ref:`pool_connection_invalidation`
"""
class ConnectionEvents(event.Events):
"""Available events for :class:`.Connectable`, which includes
:class:`.Connection` and :class:`.Engine`.
The methods here define the name of an event as well as the names of
members that are passed to listener functions.
An event listener can be associated with any :class:`.Connectable`
class or instance, such as an :class:`.Engine`, e.g.::
from sqlalchemy import event, create_engine
def before_cursor_execute(conn, cursor, statement, parameters, context,
executemany):
log.info("Received statement: %s" % statement)
engine = create_engine('postgresql://scott:tiger@localhost/test')
event.listen(engine, "before_cursor_execute", before_cursor_execute)
or with a specific :class:`.Connection`::
with engine.begin() as conn:
@event.listens_for(conn, 'before_cursor_execute')
def before_cursor_execute(conn, cursor, statement, parameters,
context, executemany):
log.info("Received statement: %s" % statement)
When the methods are called with a `statement` parameter, such as in
:meth:`.after_cursor_execute`, :meth:`.before_cursor_execute` and
:meth:`.dbapi_error`, the statement is the exact SQL string that was
prepared for transmission to the DBAPI ``cursor`` in the connection's
:class:`.Dialect`.
The :meth:`.before_execute` and :meth:`.before_cursor_execute`
events can also be established with the ``retval=True`` flag, which
allows modification of the statement and parameters to be sent
to the database. The :meth:`.before_cursor_execute` event is
particularly useful here to add ad-hoc string transformations, such
as comments, to all executions::
from sqlalchemy.engine import Engine
from sqlalchemy import event
@event.listens_for(Engine, "before_cursor_execute", retval=True)
def comment_sql_calls(conn, cursor, statement, parameters,
context, executemany):
statement = statement + " -- some comment"
return statement, parameters
.. note:: :class:`.ConnectionEvents` can be established on any
combination of :class:`.Engine`, :class:`.Connection`, as well
as instances of each of those classes. Events across all
four scopes will fire off for a given instance of
:class:`.Connection`. However, for performance reasons, the
:class:`.Connection` object determines at instantiation time
whether or not its parent :class:`.Engine` has event listeners
established. Event listeners added to the :class:`.Engine`
class or to an instance of :class:`.Engine` *after* the instantiation
of a dependent :class:`.Connection` instance will usually
*not* be available on that :class:`.Connection` instance. The newly
added listeners will instead take effect for :class:`.Connection`
instances created subsequent to those event listeners being
established on the parent :class:`.Engine` class or instance.
:param retval=False: Applies to the :meth:`.before_execute` and
:meth:`.before_cursor_execute` events only. When True, the
user-defined event function must have a return value, which
is a tuple of parameters that replace the given statement
and parameters. See those methods for a description of
specific return arguments.
.. versionchanged:: 0.8 :class:`.ConnectionEvents` can now be associated
with any :class:`.Connectable` including :class:`.Connection`,
in addition to the existing support for :class:`.Engine`.
"""
_target_class_doc = "SomeEngine"
_dispatch_target = Connectable
@classmethod
def _listen(cls, event_key, retval=False):
target, identifier, fn = \
event_key.dispatch_target, event_key.identifier, \
event_key._listen_fn
target._has_events = True
if not retval:
if identifier == 'before_execute':
orig_fn = fn
def wrap_before_execute(conn, clauseelement,
multiparams, params):
orig_fn(conn, clauseelement, multiparams, params)
return clauseelement, multiparams, params
fn = wrap_before_execute
elif identifier == 'before_cursor_execute':
orig_fn = fn
def wrap_before_cursor_execute(conn, cursor, statement,
parameters, context,
executemany):
orig_fn(conn, cursor, statement,
parameters, context, executemany)
return statement, parameters
fn = wrap_before_cursor_execute
elif retval and \
identifier not in ('before_execute',
'before_cursor_execute', 'handle_error'):
raise exc.ArgumentError(
"Only the 'before_execute', "
"'before_cursor_execute' and 'handle_error' engine "
"event listeners accept the 'retval=True' "
"argument.")
event_key.with_wrapper(fn).base_listen()
def before_execute(self, conn, clauseelement, multiparams, params):
"""Intercept high level execute() events, receiving uncompiled
SQL constructs and other objects prior to rendering into SQL.
This event is good for debugging SQL compilation issues as well
as early manipulation of the parameters being sent to the database,
as the parameter lists will be in a consistent format here.
This event can be optionally established with the ``retval=True``
flag. The ``clauseelement``, ``multiparams``, and ``params``
arguments should be returned as a three-tuple in this case::
@event.listens_for(Engine, "before_execute", retval=True)
def before_execute(conn, conn, clauseelement, multiparams, params):
# do something with clauseelement, multiparams, params
return clauseelement, multiparams, params
:param conn: :class:`.Connection` object
:param clauseelement: SQL expression construct, :class:`.Compiled`
instance, or string statement passed to :meth:`.Connection.execute`.
:param multiparams: Multiple parameter sets, a list of dictionaries.
:param params: Single parameter set, a single dictionary.
See also:
:meth:`.before_cursor_execute`
"""
def after_execute(self, conn, clauseelement, multiparams, params, result):
"""Intercept high level execute() events after execute.
:param conn: :class:`.Connection` object
:param clauseelement: SQL expression construct, :class:`.Compiled`
instance, or string statement passed to :meth:`.Connection.execute`.
:param multiparams: Multiple parameter sets, a list of dictionaries.
:param params: Single parameter set, a single dictionary.
:param result: :class:`.ResultProxy` generated by the execution.
"""
def before_cursor_execute(self, conn, cursor, statement,
parameters, context, executemany):
"""Intercept low-level cursor execute() events before execution,
receiving the string SQL statement and DBAPI-specific parameter list to
be invoked against a cursor.
This event is a good choice for logging as well as late modifications
to the SQL string. It's less ideal for parameter modifications except
for those which are specific to a target backend.
This event can be optionally established with the ``retval=True``
flag. The ``statement`` and ``parameters`` arguments should be
returned as a two-tuple in this case::
@event.listens_for(Engine, "before_cursor_execute", retval=True)
def before_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
# do something with statement, parameters
return statement, parameters
See the example at :class:`.ConnectionEvents`.
:param conn: :class:`.Connection` object
:param cursor: DBAPI cursor object
:param statement: string SQL statement, as to be passed to the DBAPI
:param parameters: Dictionary, tuple, or list of parameters being
passed to the ``execute()`` or ``executemany()`` method of the
DBAPI ``cursor``. In some cases may be ``None``.
:param context: :class:`.ExecutionContext` object in use. May
be ``None``.
:param executemany: boolean, if ``True``, this is an ``executemany()``
call, if ``False``, this is an ``execute()`` call.
See also:
:meth:`.before_execute`
:meth:`.after_cursor_execute`
"""
def after_cursor_execute(self, conn, cursor, statement,
parameters, context, executemany):
"""Intercept low-level cursor execute() events after execution.
:param conn: :class:`.Connection` object
:param cursor: DBAPI cursor object. Will have results pending
if the statement was a SELECT, but these should not be consumed
as they will be needed by the :class:`.ResultProxy`.
:param statement: string SQL statement, as passed to the DBAPI
:param parameters: Dictionary, tuple, or list of parameters being
passed to the ``execute()`` or ``executemany()`` method of the
DBAPI ``cursor``. In some cases may be ``None``.
:param context: :class:`.ExecutionContext` object in use. May
be ``None``.
:param executemany: boolean, if ``True``, this is an ``executemany()``
call, if ``False``, this is an ``execute()`` call.
"""
def dbapi_error(self, conn, cursor, statement, parameters,
context, exception):
"""Intercept a raw DBAPI error.
This event is called with the DBAPI exception instance
received from the DBAPI itself, *before* SQLAlchemy wraps the
exception with it's own exception wrappers, and before any
other operations are performed on the DBAPI cursor; the
existing transaction remains in effect as well as any state
on the cursor.
The use case here is to inject low-level exception handling
into an :class:`.Engine`, typically for logging and
debugging purposes.
.. warning::
Code should **not** modify
any state or throw any exceptions here as this will
interfere with SQLAlchemy's cleanup and error handling
routines. For exception modification, please refer to the
new :meth:`.ConnectionEvents.handle_error` event.
Subsequent to this hook, SQLAlchemy may attempt any
number of operations on the connection/cursor, including
closing the cursor, rolling back of the transaction in the
case of connectionless execution, and disposing of the entire
connection pool if a "disconnect" was detected. The
exception is then wrapped in a SQLAlchemy DBAPI exception
wrapper and re-thrown.
:param conn: :class:`.Connection` object
:param cursor: DBAPI cursor object
:param statement: string SQL statement, as passed to the DBAPI
:param parameters: Dictionary, tuple, or list of parameters being
passed to the ``execute()`` or ``executemany()`` method of the
DBAPI ``cursor``. In some cases may be ``None``.
:param context: :class:`.ExecutionContext` object in use. May
be ``None``.
:param exception: The **unwrapped** exception emitted directly from the
DBAPI. The class here is specific to the DBAPI module in use.
.. deprecated:: 0.9.7 - replaced by
:meth:`.ConnectionEvents.handle_error`
"""
def handle_error(self, exception_context):
"""Intercept all exceptions processed by the :class:`.Connection`.
This includes all exceptions emitted by the DBAPI as well as
within SQLAlchemy's statement invocation process, including
encoding errors and other statement validation errors. Other areas
in which the event is invoked include transaction begin and end,
result row fetching, cursor creation.
Note that :meth:`.handle_error` may support new kinds of exceptions
and new calling scenarios at *any time*. Code which uses this
event must expect new calling patterns to be present in minor
releases.
To support the wide variety of members that correspond to an exception,
as well as to allow extensibility of the event without backwards
incompatibility, the sole argument received is an instance of
:class:`.ExceptionContext`. This object contains data members
representing detail about the exception.
Use cases supported by this hook include:
* read-only, low-level exception handling for logging and
debugging purposes
* exception re-writing
The hook is called while the cursor from the failed operation
(if any) is still open and accessible. Special cleanup operations
can be called on this cursor; SQLAlchemy will attempt to close
this cursor subsequent to this hook being invoked. If the connection
is in "autocommit" mode, the transaction also remains open within
the scope of this hook; the rollback of the per-statement transaction
also occurs after the hook is called.
The user-defined event handler has two options for replacing
the SQLAlchemy-constructed exception into one that is user
defined. It can either raise this new exception directly, in
which case all further event listeners are bypassed and the
exception will be raised, after appropriate cleanup as taken
place::
@event.listens_for(Engine, "handle_error")
def handle_exception(context):
if isinstance(context.original_exception,
psycopg2.OperationalError) and \\
"failed" in str(context.original_exception):
raise MySpecialException("failed operation")
Alternatively, a "chained" style of event handling can be
used, by configuring the handler with the ``retval=True``
modifier and returning the new exception instance from the
function. In this case, event handling will continue onto the
next handler. The "chained" exception is available using
:attr:`.ExceptionContext.chained_exception`::
@event.listens_for(Engine, "handle_error", retval=True)
def handle_exception(context):
if context.chained_exception is not None and \\
"special" in context.chained_exception.message:
return MySpecialException("failed",
cause=context.chained_exception)
Handlers that return ``None`` may remain within this chain; the
last non-``None`` return value is the one that continues to be
passed to the next handler.
When a custom exception is raised or returned, SQLAlchemy raises
this new exception as-is, it is not wrapped by any SQLAlchemy
object. If the exception is not a subclass of
:class:`sqlalchemy.exc.StatementError`,
certain features may not be available; currently this includes
the ORM's feature of adding a detail hint about "autoflush" to
exceptions raised within the autoflush process.
:param context: an :class:`.ExceptionContext` object. See this
class for details on all available members.
.. versionadded:: 0.9.7 Added the
:meth:`.ConnectionEvents.handle_error` hook.
"""
def engine_connect(self, conn, branch):
"""Intercept the creation of a new :class:`.Connection`.
This event is called typically as the direct result of calling
the :meth:`.Engine.connect` method.
It differs from the :meth:`.PoolEvents.connect` method, which
refers to the actual connection to a database at the DBAPI level;
a DBAPI connection may be pooled and reused for many operations.
In contrast, this event refers only to the production of a higher level
:class:`.Connection` wrapper around such a DBAPI connection.
It also differs from the :meth:`.PoolEvents.checkout` event
in that it is specific to the :class:`.Connection` object, not the
DBAPI connection that :meth:`.PoolEvents.checkout` deals with, although
this DBAPI connection is available here via the
:attr:`.Connection.connection` attribute. But note there can in fact
be multiple :meth:`.PoolEvents.checkout` events within the lifespan
of a single :class:`.Connection` object, if that :class:`.Connection`
is invalidated and re-established. There can also be multiple
:class:`.Connection` objects generated for the same already-checked-out
DBAPI connection, in the case that a "branch" of a :class:`.Connection`
is produced.
:param conn: :class:`.Connection` object.
:param branch: if True, this is a "branch" of an existing
:class:`.Connection`. A branch is generated within the course
of a statement execution to invoke supplemental statements, most
typically to pre-execute a SELECT of a default value for the purposes
of an INSERT statement.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.PoolEvents.checkout` the lower-level pool checkout event
for an individual DBAPI connection
:meth:`.ConnectionEvents.set_connection_execution_options` - a copy
of a :class:`.Connection` is also made when the
:meth:`.Connection.execution_options` method is called.
"""
def set_connection_execution_options(self, conn, opts):
"""Intercept when the :meth:`.Connection.execution_options`
method is called.
This method is called after the new :class:`.Connection` has been
produced, with the newly updated execution options collection, but
before the :class:`.Dialect` has acted upon any of those new options.
Note that this method is not called when a new :class:`.Connection`
is produced which is inheriting execution options from its parent
:class:`.Engine`; to intercept this condition, use the
:meth:`.ConnectionEvents.engine_connect` event.
:param conn: The newly copied :class:`.Connection` object
:param opts: dictionary of options that were passed to the
:meth:`.Connection.execution_options` method.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.ConnectionEvents.set_engine_execution_options` - event
which is called when :meth:`.Engine.execution_options` is called.
"""
def set_engine_execution_options(self, engine, opts):
"""Intercept when the :meth:`.Engine.execution_options`
method is called.
The :meth:`.Engine.execution_options` method produces a shallow
copy of the :class:`.Engine` which stores the new options. That new
:class:`.Engine` is passed here. A particular application of this
method is to add a :meth:`.ConnectionEvents.engine_connect` event
handler to the given :class:`.Engine` which will perform some per-
:class:`.Connection` task specific to these execution options.
:param conn: The newly copied :class:`.Engine` object
:param opts: dictionary of options that were passed to the
:meth:`.Connection.execution_options` method.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.ConnectionEvents.set_connection_execution_options` - event
which is called when :meth:`.Connection.execution_options` is
called.
"""
def begin(self, conn):
"""Intercept begin() events.
:param conn: :class:`.Connection` object
"""
def rollback(self, conn):
"""Intercept rollback() events, as initiated by a
:class:`.Transaction`.
Note that the :class:`.Pool` also "auto-rolls back"
a DBAPI connection upon checkin, if the ``reset_on_return``
flag is set to its default value of ``'rollback'``.
To intercept this
rollback, use the :meth:`.PoolEvents.reset` hook.
:param conn: :class:`.Connection` object
.. seealso::
:meth:`.PoolEvents.reset`
"""
def commit(self, conn):
"""Intercept commit() events, as initiated by a
:class:`.Transaction`.
Note that the :class:`.Pool` may also "auto-commit"
a DBAPI connection upon checkin, if the ``reset_on_return``
flag is set to the value ``'commit'``. To intercept this
commit, use the :meth:`.PoolEvents.reset` hook.
:param conn: :class:`.Connection` object
"""
def savepoint(self, conn, name):
"""Intercept savepoint() events.
:param conn: :class:`.Connection` object
:param name: specified name used for the savepoint.
"""
def rollback_savepoint(self, conn, name, context):
"""Intercept rollback_savepoint() events.
:param conn: :class:`.Connection` object
:param name: specified name used for the savepoint.
:param context: :class:`.ExecutionContext` in use. May be ``None``.
"""
def release_savepoint(self, conn, name, context):
"""Intercept release_savepoint() events.
:param conn: :class:`.Connection` object
:param name: specified name used for the savepoint.
:param context: :class:`.ExecutionContext` in use. May be ``None``.
"""
def begin_twophase(self, conn, xid):
"""Intercept begin_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
"""
def prepare_twophase(self, conn, xid):
"""Intercept prepare_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
"""
def rollback_twophase(self, conn, xid, is_prepared):
"""Intercept rollback_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
:param is_prepared: boolean, indicates if
:meth:`.TwoPhaseTransaction.prepare` was called.
"""
def commit_twophase(self, conn, xid, is_prepared):
"""Intercept commit_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
:param is_prepared: boolean, indicates if
:meth:`.TwoPhaseTransaction.prepare` was called.
"""
class DialectEvents(event.Events):
"""event interface for execution-replacement functions.
These events allow direct instrumentation and replacement
of key dialect functions which interact with the DBAPI.
.. note::
:class:`.DialectEvents` hooks should be considered **semi-public**
and experimental.
These hooks are not for general use and are only for those situations
where intricate re-statement of DBAPI mechanics must be injected onto
an existing dialect. For general-use statement-interception events,
please use the :class:`.ConnectionEvents` interface.
.. seealso::
:meth:`.ConnectionEvents.before_cursor_execute`
:meth:`.ConnectionEvents.before_execute`
:meth:`.ConnectionEvents.after_cursor_execute`
:meth:`.ConnectionEvents.after_execute`
.. versionadded:: 0.9.4
"""
_target_class_doc = "SomeEngine"
_dispatch_target = Dialect
@classmethod
def _listen(cls, event_key, retval=False):
target, identifier, fn = \
event_key.dispatch_target, event_key.identifier, event_key.fn
target._has_events = True
event_key.base_listen()
@classmethod
def _accept_with(cls, target):
if isinstance(target, type):
if issubclass(target, Engine):
return Dialect
elif issubclass(target, Dialect):
return target
elif isinstance(target, Engine):
return target.dialect
else:
return target
def do_executemany(self, cursor, statement, parameters, context):
"""Receive a cursor to have executemany() called.
Return the value True to halt further events from invoking,
and to indicate that the cursor execution has already taken
place within the event handler.
"""
def do_execute_no_params(self, cursor, statement, context):
"""Receive a cursor to have execute() with no parameters called.
Return the value True to halt further events from invoking,
and to indicate that the cursor execution has already taken
place within the event handler.
"""
def do_execute(self, cursor, statement, parameters, context):
"""Receive a cursor to have execute() called.
Return the value True to halt further events from invoking,
and to indicate that the cursor execution has already taken
place within the event handler.
"""
|
eharney/nova
|
nova/api/openstack/compute/views/limits.py
|
# Copyright 2010-2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
from nova.openstack.common import timeutils
class ViewBuilder(object):
"""OpenStack API base limits view builder."""
def build(self, rate_limits, absolute_limits):
rate_limits = self._build_rate_limits(rate_limits)
absolute_limits = self._build_absolute_limits(absolute_limits)
output = {
"limits": {
"rate": rate_limits,
"absolute": absolute_limits,
},
}
return output
def _build_absolute_limits(self, absolute_limits):
"""Builder for absolute limits
absolute_limits should be given as a dict of limits.
For example: {"ram": 512, "gigabytes": 1024}.
"""
limit_names = {
"ram": ["maxTotalRAMSize"],
"instances": ["maxTotalInstances"],
"cores": ["maxTotalCores"],
"key_pairs": ["maxTotalKeypairs"],
"floating_ips": ["maxTotalFloatingIps"],
"metadata_items": ["maxServerMeta", "maxImageMeta"],
"injected_files": ["maxPersonality"],
"injected_file_content_bytes": ["maxPersonalitySize"],
"security_groups": ["maxSecurityGroups"],
"security_group_rules": ["maxSecurityGroupRules"],
}
limits = {}
for name, value in absolute_limits.iteritems():
if name in limit_names and value is not None:
for name in limit_names[name]:
limits[name] = value
return limits
def _build_rate_limits(self, rate_limits):
limits = []
for rate_limit in rate_limits:
_rate_limit_key = None
_rate_limit = self._build_rate_limit(rate_limit)
# check for existing key
for limit in limits:
if (limit["uri"] == rate_limit["URI"] and
limit["regex"] == rate_limit["regex"]):
_rate_limit_key = limit
break
# ensure we have a key if we didn't find one
if not _rate_limit_key:
_rate_limit_key = {
"uri": rate_limit["URI"],
"regex": rate_limit["regex"],
"limit": [],
}
limits.append(_rate_limit_key)
_rate_limit_key["limit"].append(_rate_limit)
return limits
def _build_rate_limit(self, rate_limit):
_get_utc = datetime.datetime.utcfromtimestamp
next_avail = _get_utc(rate_limit["resetTime"])
return {
"verb": rate_limit["verb"],
"value": rate_limit["value"],
"remaining": int(rate_limit["remaining"]),
"unit": rate_limit["unit"],
"next-available": timeutils.isotime(at=next_avail),
}
class ViewBuilderV3(ViewBuilder):
def build(self, rate_limits):
rate_limits = self._build_rate_limits(rate_limits)
return {"limits": {"rate": rate_limits}}
|
calamityman/ansible-modules-extras
|
network/openvswitch_bridge.py
|
#!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, David Stygstra <david.stygstra@gmail.com>
#
# Portions copyright @ 2015 VMware, Inc.
#
# This file is part of Ansible
#
# This module 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 software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
# pylint: disable=C0111
DOCUMENTATION = '''
---
module: openvswitch_bridge
version_added: 1.4
author: "David Stygstra (@stygstra)"
short_description: Manage Open vSwitch bridges
requirements: [ ovs-vsctl ]
description:
- Manage Open vSwitch bridges
options:
bridge:
required: true
description:
- Name of bridge to manage
state:
required: false
default: "present"
choices: [ present, absent ]
description:
- Whether the bridge should exist
timeout:
required: false
default: 5
description:
- How long to wait for ovs-vswitchd to respond
external_ids:
version_added: 2.0
required: false
default: None
description:
- A dictionary of external-ids. Omitting this parameter is a No-op.
To clear all external-ids pass an empty value.
fail_mode:
version_added: 2.0
default: None
required: false
choices : [secure, standalone]
description:
- Set bridge fail-mode. The default value (None) is a No-op.
'''
EXAMPLES = '''
# Create a bridge named br-int
- openvswitch_bridge: bridge=br-int state=present
# Create an integration bridge
- openvswitch_bridge: bridge=br-int state=present fail_mode=secure
args:
external_ids:
bridge-id: "br-int"
'''
class OVSBridge(object):
""" Interface to ovs-vsctl. """
def __init__(self, module):
self.module = module
self.bridge = module.params['bridge']
self.state = module.params['state']
self.timeout = module.params['timeout']
self.fail_mode = module.params['fail_mode']
def _vsctl(self, command):
'''Run ovs-vsctl command'''
return self.module.run_command(['ovs-vsctl', '-t',
str(self.timeout)] + command)
def exists(self):
'''Check if the bridge already exists'''
rtc, _, err = self._vsctl(['br-exists', self.bridge])
if rtc == 0: # See ovs-vsctl(8) for status codes
return True
if rtc == 2:
return False
self.module.fail_json(msg=err)
def add(self):
'''Create the bridge'''
rtc, _, err = self._vsctl(['add-br', self.bridge])
if rtc != 0:
self.module.fail_json(msg=err)
if self.fail_mode:
self.set_fail_mode()
def delete(self):
'''Delete the bridge'''
rtc, _, err = self._vsctl(['del-br', self.bridge])
if rtc != 0:
self.module.fail_json(msg=err)
def check(self):
'''Run check mode'''
changed = False
# pylint: disable=W0703
try:
if self.state == 'present' and self.exists():
if (self.fail_mode and
(self.fail_mode != self.get_fail_mode())):
changed = True
##
# Check if external ids would change.
current_external_ids = self.get_external_ids()
exp_external_ids = self.module.params['external_ids']
if exp_external_ids is not None:
for (key, value) in exp_external_ids:
if ((key in current_external_ids) and
(value != current_external_ids[key])):
changed = True
##
# Check if external ids would be removed.
for (key, value) in current_external_ids.items():
if key not in exp_external_ids:
changed = True
elif self.state == 'absent' and self.exists():
changed = True
elif self.state == 'present' and not self.exists():
changed = True
except Exception, earg:
self.module.fail_json(msg=str(earg))
# pylint: enable=W0703
self.module.exit_json(changed=changed)
def run(self):
'''Make the necessary changes'''
changed = False
# pylint: disable=W0703
try:
if self.state == 'absent':
if self.exists():
self.delete()
changed = True
elif self.state == 'present':
if not self.exists():
self.add()
changed = True
current_fail_mode = self.get_fail_mode()
if self.fail_mode and (self.fail_mode != current_fail_mode):
self.module.log( "changing fail mode %s to %s" % (current_fail_mode, self.fail_mode))
self.set_fail_mode()
changed = True
current_external_ids = self.get_external_ids()
##
# Change and add existing external ids.
exp_external_ids = self.module.params['external_ids']
if exp_external_ids is not None:
for (key, value) in exp_external_ids.items():
if ((value != current_external_ids.get(key, None)) and
self.set_external_id(key, value)):
changed = True
##
# Remove current external ids that are not passed in.
for (key, value) in current_external_ids.items():
if ((key not in exp_external_ids) and
self.set_external_id(key, None)):
changed = True
except Exception, earg:
self.module.fail_json(msg=str(earg))
# pylint: enable=W0703
self.module.exit_json(changed=changed)
def get_external_ids(self):
""" Return the bridge's external ids as a dict. """
results = {}
if self.exists():
rtc, out, err = self._vsctl(['br-get-external-id', self.bridge])
if rtc != 0:
self.module.fail_json(msg=err)
lines = out.split("\n")
lines = [item.split("=") for item in lines if len(item) > 0]
for item in lines:
results[item[0]] = item[1]
return results
def set_external_id(self, key, value):
""" Set external id. """
if self.exists():
cmd = ['br-set-external-id', self.bridge, key]
if value:
cmd += [value]
(rtc, _, err) = self._vsctl(cmd)
if rtc != 0:
self.module.fail_json(msg=err)
return True
return False
def get_fail_mode(self):
""" Get failure mode. """
value = ''
if self.exists():
rtc, out, err = self._vsctl(['get-fail-mode', self.bridge])
if rtc != 0:
self.module.fail_json(msg=err)
value = out.strip("\n")
return value
def set_fail_mode(self):
""" Set failure mode. """
if self.exists():
(rtc, _, err) = self._vsctl(['set-fail-mode', self.bridge,
self.fail_mode])
if rtc != 0:
self.module.fail_json(msg=err)
# pylint: disable=E0602
def main():
""" Entry point. """
module = AnsibleModule(
argument_spec={
'bridge': {'required': True},
'state': {'default': 'present', 'choices': ['present', 'absent']},
'timeout': {'default': 5, 'type': 'int'},
'external_ids': {'default': None, 'type': 'dict'},
'fail_mode': {'default': None},
},
supports_check_mode=True,
)
bridge = OVSBridge(module)
if module.check_mode:
bridge.check()
else:
bridge.run()
# pylint: disable=W0614
# pylint: disable=W0401
# pylint: disable=W0622
# import module snippets
from ansible.module_utils.basic import *
main()
|
tokyo-jesus/university
|
src/python/koans/python3/runner/path_to_enlightenment.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The path to enlightenment starts with the following:
import unittest
from koans.about_asserts import AboutAsserts
from koans.about_strings import AboutStrings
from koans.about_none import AboutNone
from koans.about_lists import AboutLists
from koans.about_list_assignments import AboutListAssignments
from koans.about_dictionaries import AboutDictionaries
from koans.about_string_manipulation import AboutStringManipulation
from koans.about_tuples import AboutTuples
from koans.about_methods import AboutMethods
from koans.about_control_statements import AboutControlStatements
from koans.about_true_and_false import AboutTrueAndFalse
from koans.about_sets import AboutSets
from koans.about_triangle_project import AboutTriangleProject
from koans.about_exceptions import AboutExceptions
from koans.about_triangle_project2 import AboutTriangleProject2
from koans.about_iteration import AboutIteration
from koans.about_comprehension import AboutComprehension
from koans.about_generators import AboutGenerators
from koans.about_lambdas import AboutLambdas
from koans.about_scoring_project import AboutScoringProject
from koans.about_classes import AboutClasses
from koans.about_with_statements import AboutWithStatements
from koans.about_monkey_patching import AboutMonkeyPatching
from koans.about_dice_project import AboutDiceProject
from koans.about_method_bindings import AboutMethodBindings
from koans.about_decorating_with_functions import AboutDecoratingWithFunctions
from koans.about_decorating_with_classes import AboutDecoratingWithClasses
from koans.about_inheritance import AboutInheritance
from koans.about_multiple_inheritance import AboutMultipleInheritance
from koans.about_regex import AboutRegex
from koans.about_scope import AboutScope
from koans.about_modules import AboutModules
from koans.about_packages import AboutPackages
from koans.about_class_attributes import AboutClassAttributes
from koans.about_attribute_access import AboutAttributeAccess
from koans.about_deleting_objects import AboutDeletingObjects
from koans.about_proxy_object_project import *
from koans.about_extra_credit import AboutExtraCredit
def koans():
loader = unittest.TestLoader()
suite = unittest.TestSuite()
loader.sortTestMethodsUsing = None
suite.addTests(loader.loadTestsFromTestCase(AboutAsserts))
suite.addTests(loader.loadTestsFromTestCase(AboutStrings))
suite.addTests(loader.loadTestsFromTestCase(AboutNone))
suite.addTests(loader.loadTestsFromTestCase(AboutLists))
suite.addTests(loader.loadTestsFromTestCase(AboutListAssignments))
suite.addTests(loader.loadTestsFromTestCase(AboutDictionaries))
suite.addTests(loader.loadTestsFromTestCase(AboutStringManipulation))
suite.addTests(loader.loadTestsFromTestCase(AboutTuples))
suite.addTests(loader.loadTestsFromTestCase(AboutMethods))
suite.addTests(loader.loadTestsFromTestCase(AboutControlStatements))
suite.addTests(loader.loadTestsFromTestCase(AboutTrueAndFalse))
suite.addTests(loader.loadTestsFromTestCase(AboutSets))
suite.addTests(loader.loadTestsFromTestCase(AboutTriangleProject))
suite.addTests(loader.loadTestsFromTestCase(AboutExceptions))
suite.addTests(loader.loadTestsFromTestCase(AboutTriangleProject2))
suite.addTests(loader.loadTestsFromTestCase(AboutIteration))
suite.addTests(loader.loadTestsFromTestCase(AboutComprehension))
suite.addTests(loader.loadTestsFromTestCase(AboutGenerators))
suite.addTests(loader.loadTestsFromTestCase(AboutLambdas))
suite.addTests(loader.loadTestsFromTestCase(AboutScoringProject))
suite.addTests(loader.loadTestsFromTestCase(AboutClasses))
suite.addTests(loader.loadTestsFromTestCase(AboutWithStatements))
suite.addTests(loader.loadTestsFromTestCase(AboutMonkeyPatching))
suite.addTests(loader.loadTestsFromTestCase(AboutDiceProject))
suite.addTests(loader.loadTestsFromTestCase(AboutMethodBindings))
suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithFunctions))
suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithClasses))
suite.addTests(loader.loadTestsFromTestCase(AboutInheritance))
suite.addTests(loader.loadTestsFromTestCase(AboutMultipleInheritance))
suite.addTests(loader.loadTestsFromTestCase(AboutScope))
suite.addTests(loader.loadTestsFromTestCase(AboutModules))
suite.addTests(loader.loadTestsFromTestCase(AboutPackages))
suite.addTests(loader.loadTestsFromTestCase(AboutClassAttributes))
suite.addTests(loader.loadTestsFromTestCase(AboutAttributeAccess))
suite.addTests(loader.loadTestsFromTestCase(AboutDeletingObjects))
suite.addTests(loader.loadTestsFromTestCase(AboutProxyObjectProject))
suite.addTests(loader.loadTestsFromTestCase(TelevisionTest))
suite.addTests(loader.loadTestsFromTestCase(AboutExtraCredit))
return suite
|
arjunsinghy96/coala
|
tests/core/CircularDependencyErrorTest.py
|
import unittest
from coalib.core.CircularDependencyError import CircularDependencyError
class CircularDependencyErrorTest(unittest.TestCase):
def test_default_message(self):
with self.assertRaises(CircularDependencyError) as cm:
# test the default case (names is None)
raise CircularDependencyError
self.assertEqual(str(cm.exception), 'Circular dependency detected.')
def test_message_with_dependency_circle(self):
with self.assertRaises(CircularDependencyError) as cm:
raise CircularDependencyError(['A', 'B', 'C'])
self.assertEqual(str(cm.exception),
'Circular dependency detected: A -> B -> C')
|
Shrews/PyGerrit
|
webapp/django/test/testcases.py
|
import re
import unittest
from urlparse import urlsplit, urlunsplit
from xml.dom.minidom import parseString, Node
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import clear_url_caches
from django.db import transaction
from django.http import QueryDict
from django.test import _doctest as doctest
from django.test.client import Client
from django.utils import simplejson
normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
def to_list(value):
"""
Puts value into a list if it's not already one.
Returns an empty list if value is None.
"""
if value is None:
value = []
elif not isinstance(value, list):
value = [value]
return value
class OutputChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
"The entry method for doctest output checking. Defers to a sequence of child checkers"
checks = (self.check_output_default,
self.check_output_long,
self.check_output_xml,
self.check_output_json)
for check in checks:
if check(want, got, optionflags):
return True
return False
def check_output_default(self, want, got, optionflags):
"The default comparator provided by doctest - not perfect, but good for most purposes"
return doctest.OutputChecker.check_output(self, want, got, optionflags)
def check_output_long(self, want, got, optionflags):
"""Doctest does an exact string comparison of output, which means long
integers aren't equal to normal integers ("22L" vs. "22"). The
following code normalizes long integers so that they equal normal
integers.
"""
return normalize_long_ints(want) == normalize_long_ints(got)
def check_output_xml(self, want, got, optionsflags):
"""Tries to do a 'xml-comparision' of want and got. Plain string
comparision doesn't always work because, for example, attribute
ordering should not be important.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
"""
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
def child_text(element):
return ''.join([c.data for c in element.childNodes
if c.nodeType == Node.TEXT_NODE])
def children(element):
return [c for c in element.childNodes
if c.nodeType == Node.ELEMENT_NODE]
def norm_child_text(element):
return norm_whitespace(child_text(element))
def attrs_dict(element):
return dict(element.attributes.items())
def check_element(want_element, got_element):
if want_element.tagName != got_element.tagName:
return False
if norm_child_text(want_element) != norm_child_text(got_element):
return False
if attrs_dict(want_element) != attrs_dict(got_element):
return False
want_children = children(want_element)
got_children = children(got_element)
if len(want_children) != len(got_children):
return False
for want, got in zip(want_children, got_children):
if not check_element(want, got):
return False
return True
want, got = self._strip_quotes(want, got)
want = want.replace('\\n','\n')
got = got.replace('\\n','\n')
# If the string is not a complete xml document, we may need to add a
# root element. This allow us to compare fragments, like "<foo/><bar/>"
if not want.startswith('<?xml'):
wrapper = '<root>%s</root>'
want = wrapper % want
got = wrapper % got
# Parse the want and got strings, and compare the parsings.
try:
want_root = parseString(want).firstChild
got_root = parseString(got).firstChild
except:
return False
return check_element(want_root, got_root)
def check_output_json(self, want, got, optionsflags):
"Tries to compare want and got as if they were JSON-encoded data"
want, got = self._strip_quotes(want, got)
try:
want_json = simplejson.loads(want)
got_json = simplejson.loads(got)
except:
return False
return want_json == got_json
def _strip_quotes(self, want, got):
"""
Strip quotes of doctests output values:
>>> o = OutputChecker()
>>> o._strip_quotes("'foo'")
"foo"
>>> o._strip_quotes('"foo"')
"foo"
>>> o._strip_quotes("u'foo'")
"foo"
>>> o._strip_quotes('u"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"))
def is_quoted_unicode(s):
s = s.strip()
return (len(s) >= 3
and s[0] == 'u'
and s[1] == s[-1]
and s[1] in ('"', "'"))
if is_quoted_string(want) and is_quoted_string(got):
want = want.strip()[1:-1]
got = got.strip()[1:-1]
elif is_quoted_unicode(want) and is_quoted_unicode(got):
want = want.strip()[2:-1]
got = got.strip()[2:-1]
return want, got
class DocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwargs):
doctest.DocTestRunner.__init__(self, *args, **kwargs)
self.optionflags = doctest.ELLIPSIS
def report_unexpected_exception(self, out, test, example, exc_info):
doctest.DocTestRunner.report_unexpected_exception(self, out, test,
example, exc_info)
# Rollback, in case of database errors. Otherwise they'd have
# side effects on other tests.
transaction.rollback_unless_managed()
class TestCase(unittest.TestCase):
def _pre_setup(self):
"""Performs any pre-test setup. This includes:
* Flushing the database.
* If the Test Case class has a 'fixtures' member, installing the
named fixtures.
* If the Test Case class has a 'urls' member, replace the
ROOT_URLCONF with it.
* Clearing the mail test outbox.
"""
call_command('flush', verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
call_command('loaddata', *self.fixtures, **{'verbosity': 0})
if hasattr(self, 'urls'):
self._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = self.urls
clear_url_caches()
mail.outbox = []
def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
self.client = Client()
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
super(TestCase, self).__call__(result)
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
def _post_teardown(self):
""" Performs any post-test things. This includes:
* Putting back the original ROOT_URLCONF if it was changed.
"""
if hasattr(self, '_old_root_urlconf'):
settings.ROOT_URLCONF = self._old_root_urlconf
clear_url_caches()
def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, host=None):
"""Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded.
Note that assertRedirects won't work for external links since it uses
TestClient to do a request.
"""
self.assertEqual(response.status_code, status_code,
("Response didn't redirect as expected: Response code was %d"
" (expected %d)" % (response.status_code, status_code)))
url = response['Location']
scheme, netloc, path, query, fragment = urlsplit(url)
e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url)
if not (e_scheme or e_netloc):
expected_url = urlunsplit(('http', host or 'testserver', e_path,
e_query, e_fragment))
self.assertEqual(url, expected_url,
"Response redirected to '%s', expected '%s'" % (url, expected_url))
# Get the redirection page, using the same client that was used
# to obtain the original response.
redirect_response = response.client.get(path, QueryDict(query))
self.assertEqual(redirect_response.status_code, target_status_code,
("Couldn't retrieve redirection page '%s': response code was %d"
" (expected %d)") %
(path, redirect_response.status_code, target_status_code))
def assertContains(self, response, text, count=None, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
real_count = response.content.count(text)
if count is not None:
self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" %
(real_count, text, count))
else:
self.failUnless(real_count != 0,
"Couldn't find '%s' in response" % text)
def assertNotContains(self, response, text, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` doesn't occurs in the content of the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
self.assertEqual(response.content.count(text), 0,
"Response should not contain '%s'" % text)
def assertFormError(self, response, form, field, errors):
"""
Asserts that a form used to render the response has a specific field
error.
"""
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail('Response did not use any contexts to render the'
' response')
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_form = False
for i,context in enumerate(contexts):
if form not in context:
continue
found_form = True
for err in errors:
if field:
if field in context[form].errors:
field_errors = context[form].errors[field]
self.failUnless(err in field_errors,
"The field '%s' on form '%s' in"
" context %d does not contain the"
" error '%s' (actual errors: %s)" %
(field, form, i, err,
repr(field_errors)))
elif field in context[form].fields:
self.fail("The field '%s' on form '%s' in context %d"
" contains no errors" % (field, form, i))
else:
self.fail("The form '%s' in context %d does not"
" contain the field '%s'" %
(form, i, field))
else:
non_field_errors = context[form].non_field_errors()
self.failUnless(err in non_field_errors,
"The form '%s' in context %d does not contain the"
" non-field error '%s' (actual errors: %s)" %
(form, i, err, non_field_errors))
if not found_form:
self.fail("The form '%s' was not used to render the response" %
form)
def assertTemplateUsed(self, response, template_name):
"""
Asserts that the template with the provided name was used in rendering
the response.
"""
template_names = [t.name for t in to_list(response.template)]
if not template_names:
self.fail('No templates used to render the response')
self.failUnless(template_name in template_names,
(u"Template '%s' was not a template used to render the response."
u" Actual template(s) used: %s") % (template_name,
u', '.join(template_names)))
def assertTemplateNotUsed(self, response, template_name):
"""
Asserts that the template with the provided name was NOT used in
rendering the response.
"""
template_names = [t.name for t in to_list(response.template)]
self.failIf(template_name in template_names,
(u"Template '%s' was used unexpectedly in rendering the"
u" response") % template_name)
|
tsdmgz/ansible
|
lib/ansible/modules/web_infrastructure/ansible_tower/tower_credential.py
|
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: tower_credential
author: "Wayne Witzel III (@wwitzel3)"
version_added: "2.3"
short_description: create, update, or destroy Ansible Tower credential.
description:
- Create, update, or destroy Ansible Tower credentials. See
U(https://www.ansible.com/tower) for an overview.
options:
name:
description:
- The name to use for the credential.
required: True
description:
description:
- The description to use for the credential.
user:
description:
- User that should own this credential.
required: False
default: null
team:
description:
- Team that should own this credential.
required: False
default: null
project:
description:
- Project that should for this credential.
required: False
default: null
organization:
description:
- Organization that should own the credential.
required: False
default: null
kind:
description:
- Type of credential being added.
required: True
choices: ["ssh", "net", "scm", "aws", "rax", "vmware", "satellite6", "cloudforms", "gce", "azure", "azure_rm", "openstack"]
host:
description:
- Host for this credential.
required: False
default: null
username:
description:
- Username for this credential. access_key for AWS.
required: False
default: null
password:
description:
- Password for this credential. Use ASK for prompting. secret_key for AWS. api_key for RAX.
required: False
default: null
ssh_key_data:
description:
- Path to SSH private key.
required: False
default: null
ssh_key_unlock:
description:
- Unlock password for ssh_key. Use ASK for prompting.
authorize:
description:
- Should use authroize for net type.
required: False
default: False
authorize_password:
description:
- Password for net credentials that require authroize.
required: False
default: null
client:
description:
- Client or application ID for azure_rm type.
required: False
default: null
secret:
description:
- Secret token for azure_rm type.
required: False
default: null
subscription:
description:
- Subscription ID for azure_rm type.
required: False
default: null
tenant:
description:
- Tenant ID for azure_rm type.
required: False
default: null
domain:
description:
- Domain for openstack type.
required: False
default: null
become_method:
description:
- Become method to Use for privledge escalation.
required: False
choices: ["None", "sudo", "su", "pbrun", "pfexec", "pmrun"]
default: "None"
become_username:
description:
- Become username. Use ASK for prompting.
required: False
default: null
become_password:
description:
- Become password. Use ASK for prompting.
required: False
default: null
vault_password:
description:
- Valut password. Use ASK for prompting.
state:
description:
- Desired state of the resource.
required: False
default: "present"
choices: ["present", "absent"]
extends_documentation_fragment: tower
'''
EXAMPLES = '''
- name: Add tower credential
tower_credential:
name: Team Name
description: Team Description
organization: test-org
state: present
tower_config_file: "~/tower_cli.cfg"
'''
import os
from ansible.module_utils.ansible_tower import tower_argument_spec, tower_auth_config, tower_check_mode, HAS_TOWER_CLI
try:
import tower_cli
import tower_cli.utils.exceptions as exc
from tower_cli.conf import settings
except ImportError:
pass
def main():
argument_spec = tower_argument_spec()
argument_spec.update(dict(
name=dict(required=True),
user=dict(),
team=dict(),
kind=dict(required=True,
choices=["ssh", "net", "scm", "aws", "rax", "vmware", "satellite6",
"cloudforms", "gce", "azure", "azure_rm", "openstack"]),
host=dict(),
username=dict(),
password=dict(no_log=True),
ssh_key_data=dict(no_log=True, type='path'),
ssh_key_unlock=dict(no_log=True),
authorize=dict(type='bool', default=False),
authorize_password=dict(no_log=True),
client=dict(),
secret=dict(),
tenant=dict(),
subscription=dict(),
domain=dict(),
become_method=dict(),
become_username=dict(),
become_password=dict(no_log=True),
vault_password=dict(no_log=True),
description=dict(),
organization=dict(required=True),
project=dict(),
state=dict(choices=['present', 'absent'], default='present'),
))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_TOWER_CLI:
module.fail_json(msg='ansible-tower-cli required for this module')
name = module.params.get('name')
organization = module.params.get('organization')
state = module.params.get('state')
json_output = {'credential': name, 'state': state}
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
credential = tower_cli.get_resource('credential')
try:
params = module.params.copy()
params['create_on_missing'] = True
if organization:
org_res = tower_cli.get_resource('organization')
org = org_res.get(name=organization)
params['organization'] = org['id']
if params['ssh_key_data']:
filename = params['ssh_key_data']
if not os.path.exists(filename):
module.fail_json(msg='file not found: %s' % filename)
if os.path.isdir(filename):
module.fail_json(msg='attempted to read contents of directory: %s' % filename)
with open(filename, 'rb') as f:
params['ssh_key_data'] = f.read()
if state == 'present':
result = credential.modify(**params)
json_output['id'] = result['id']
elif state == 'absent':
result = credential.delete(**params)
except (exc.NotFound) as excinfo:
module.fail_json(msg='Failed to update credential, organization not found: {0}'.format(excinfo), changed=False)
except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
module.fail_json(msg='Failed to update credential: {0}'.format(excinfo), changed=False)
json_output['changed'] = result['changed']
module.exit_json(**json_output)
from ansible.module_utils.basic import AnsibleModule
if __name__ == '__main__':
main()
|
Microvellum/Fluid-Designer
|
win64-vc/2.78/python/lib/imp.py
|
"""This module provides the components needed to build your own __import__
function. Undocumented functions are obsolete.
In most cases it is preferred you consider using the importlib module's
functionality over this module.
"""
# (Probably) need to stay in _imp
from _imp import (lock_held, acquire_lock, release_lock,
get_frozen_object, is_frozen_package,
init_frozen, is_builtin, is_frozen,
_fix_co_filename)
try:
from _imp import create_dynamic
except ImportError:
# Platform doesn't support dynamic loading.
create_dynamic = None
from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
from importlib._bootstrap_external import SourcelessFileLoader
from importlib import machinery
from importlib import util
import importlib
import os
import sys
import tokenize
import types
import warnings
warnings.warn("the imp module is deprecated in favour of importlib; "
"see the module's documentation for alternative uses",
PendingDeprecationWarning, stacklevel=2)
# DEPRECATED
SEARCH_ERROR = 0
PY_SOURCE = 1
PY_COMPILED = 2
C_EXTENSION = 3
PY_RESOURCE = 4
PKG_DIRECTORY = 5
C_BUILTIN = 6
PY_FROZEN = 7
PY_CODERESOURCE = 8
IMP_HOOK = 9
def new_module(name):
"""**DEPRECATED**
Create a new module.
The module is not entered into sys.modules.
"""
return types.ModuleType(name)
def get_magic():
"""**DEPRECATED**
Return the magic number for .pyc files.
"""
return util.MAGIC_NUMBER
def get_tag():
"""Return the magic tag for .pyc files."""
return sys.implementation.cache_tag
def cache_from_source(path, debug_override=None):
"""**DEPRECATED**
Given the path to a .py file, return the path to its .pyc file.
The .py file does not need to exist; this simply returns the path to the
.pyc file calculated as if the .py file were imported.
If debug_override is not None, then it must be a boolean and is used in
place of sys.flags.optimize.
If sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return util.cache_from_source(path, debug_override)
def source_from_cache(path):
"""**DEPRECATED**
Given the path to a .pyc. file, return the path to its .py file.
The .pyc file does not need to exist; this simply returns the path to
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147 format, ValueError will be raised. If
sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
return util.source_from_cache(path)
def get_suffixes():
"""**DEPRECATED**"""
extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
return extensions + source + bytecode
class NullImporter:
"""**DEPRECATED**
Null import object.
"""
def __init__(self, path):
if path == '':
raise ImportError('empty pathname', path='')
elif os.path.isdir(path):
raise ImportError('existing directory', path=path)
def find_module(self, fullname):
"""Always returns None."""
return None
class _HackedGetData:
"""Compatibility support for 'file' arguments of various load_*()
functions."""
def __init__(self, fullname, path, file=None):
super().__init__(fullname, path)
self.file = file
def get_data(self, path):
"""Gross hack to contort loader to deal w/ load_*()'s bad API."""
if self.file and path == self.path:
if not self.file.closed:
file = self.file
else:
self.file = file = open(self.path, 'r')
with file:
# Technically should be returning bytes, but
# SourceLoader.get_code() just passed what is returned to
# compile() which can handle str. And converting to bytes would
# require figuring out the encoding to decode to and
# tokenize.detect_encoding() only accepts bytes.
return file.read()
else:
return super().get_data(path)
class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
"""Compatibility support for implementing load_source()."""
def load_source(name, pathname, file=None):
loader = _LoadSourceCompatibility(name, pathname, file)
spec = util.spec_from_file_location(name, pathname, loader=loader)
if name in sys.modules:
module = _exec(spec, sys.modules[name])
else:
module = _load(spec)
# To allow reloading to potentially work, use a non-hacked loader which
# won't rely on a now-closed file object.
module.__loader__ = machinery.SourceFileLoader(name, pathname)
module.__spec__.loader = module.__loader__
return module
class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
"""Compatibility support for implementing load_compiled()."""
def load_compiled(name, pathname, file=None):
"""**DEPRECATED**"""
loader = _LoadCompiledCompatibility(name, pathname, file)
spec = util.spec_from_file_location(name, pathname, loader=loader)
if name in sys.modules:
module = _exec(spec, sys.modules[name])
else:
module = _load(spec)
# To allow reloading to potentially work, use a non-hacked loader which
# won't rely on a now-closed file object.
module.__loader__ = SourcelessFileLoader(name, pathname)
module.__spec__.loader = module.__loader__
return module
def load_package(name, path):
"""**DEPRECATED**"""
if os.path.isdir(path):
extensions = (machinery.SOURCE_SUFFIXES[:] +
machinery.BYTECODE_SUFFIXES[:])
for extension in extensions:
path = os.path.join(path, '__init__'+extension)
if os.path.exists(path):
break
else:
raise ValueError('{!r} is not a package'.format(path))
spec = util.spec_from_file_location(name, path,
submodule_search_locations=[])
if name in sys.modules:
return _exec(spec, sys.modules[name])
else:
return _load(spec)
def load_module(name, file, filename, details):
"""**DEPRECATED**
Load a module, given information returned by find_module().
The module name must include the full package name, if any.
"""
suffix, mode, type_ = details
if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
raise ValueError('invalid file open mode {!r}'.format(mode))
elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
msg = 'file object required for import (type code {})'.format(type_)
raise ValueError(msg)
elif type_ == PY_SOURCE:
return load_source(name, filename, file)
elif type_ == PY_COMPILED:
return load_compiled(name, filename, file)
elif type_ == C_EXTENSION and load_dynamic is not None:
if file is None:
with open(filename, 'rb') as opened_file:
return load_dynamic(name, filename, opened_file)
else:
return load_dynamic(name, filename, file)
elif type_ == PKG_DIRECTORY:
return load_package(name, filename)
elif type_ == C_BUILTIN:
return init_builtin(name)
elif type_ == PY_FROZEN:
return init_frozen(name)
else:
msg = "Don't know how to import {} (type code {})".format(name, type_)
raise ImportError(msg, name=name)
def find_module(name, path=None):
"""**DEPRECATED**
Search for a module.
If path is omitted or None, search for a built-in, frozen or special
module and continue search in sys.path. The module name cannot
contain '.'; to search for a submodule of a package, pass the
submodule name and the package's __path__.
"""
if not isinstance(name, str):
raise TypeError("'name' must be a str, not {}".format(type(name)))
elif not isinstance(path, (type(None), list)):
# Backwards-compatibility
raise RuntimeError("'list' must be None or a list, "
"not {}".format(type(name)))
if path is None:
if is_builtin(name):
return None, None, ('', '', C_BUILTIN)
elif is_frozen(name):
return None, None, ('', '', PY_FROZEN)
else:
path = sys.path
for entry in path:
package_directory = os.path.join(entry, name)
for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
package_file_name = '__init__' + suffix
file_path = os.path.join(package_directory, package_file_name)
if os.path.isfile(file_path):
return None, package_directory, ('', '', PKG_DIRECTORY)
for suffix, mode, type_ in get_suffixes():
file_name = name + suffix
file_path = os.path.join(entry, file_name)
if os.path.isfile(file_path):
break
else:
continue
break # Break out of outer loop when breaking out of inner loop.
else:
raise ImportError(_ERR_MSG.format(name), name=name)
encoding = None
if 'b' not in mode:
with open(file_path, 'rb') as file:
encoding = tokenize.detect_encoding(file.readline)[0]
file = open(file_path, mode, encoding=encoding)
return file, file_path, (suffix, mode, type_)
def reload(module):
"""**DEPRECATED**
Reload the module and return it.
The module must have been successfully imported before.
"""
return importlib.reload(module)
def init_builtin(name):
"""**DEPRECATED**
Load and return a built-in module by name, or None is such module doesn't
exist
"""
try:
return _builtin_from_name(name)
except ImportError:
return None
if create_dynamic:
def load_dynamic(name, path, file=None):
"""**DEPRECATED**
Load an extension module.
"""
import importlib.machinery
loader = importlib.machinery.ExtensionFileLoader(name, path)
# Issue #24748: Skip the sys.modules check in _load_module_shim;
# always load new extension
spec = importlib.machinery.ModuleSpec(
name=name, loader=loader, origin=path)
return _load(spec)
else:
load_dynamic = None
|
hsaputra/tensorflow
|
tensorflow/python/keras/_impl/keras/layers/embeddings_test.py
|
# 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 embedding layers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.keras._impl import keras
from tensorflow.python.keras._impl.keras import testing_utils
from tensorflow.python.platform import test
class EmbeddingTest(test.TestCase):
def test_embedding(self):
with self.test_session():
testing_utils.layer_test(
keras.layers.Embedding,
kwargs={'output_dim': 4,
'input_dim': 10,
'input_length': 2},
input_shape=(3, 2),
input_dtype='int32',
expected_output_dtype='float32')
with self.test_session():
testing_utils.layer_test(
keras.layers.Embedding,
kwargs={'output_dim': 4,
'input_dim': 10,
'mask_zero': True},
input_shape=(3, 2),
input_dtype='int32',
expected_output_dtype='float32')
with self.test_session():
testing_utils.layer_test(
keras.layers.Embedding,
kwargs={'output_dim': 4,
'input_dim': 10,
'mask_zero': True},
input_shape=(3, 4, 2),
input_dtype='int32',
expected_output_dtype='float32')
with self.test_session():
testing_utils.layer_test(
keras.layers.Embedding,
kwargs={'output_dim': 4,
'input_dim': 10,
'mask_zero': True,
'input_length': (None, 2)},
input_shape=(3, 4, 2),
input_dtype='int32',
expected_output_dtype='float32')
if __name__ == '__main__':
test.main()
|
mycodeday/crm-platform
|
payment_ogone/models/ogone.py
|
# -*- coding: utf-'8' "-*-"
from hashlib import sha1
import logging
from lxml import etree, objectify
from pprint import pformat
import time
from urllib import urlencode
import urllib2
import urlparse
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_ogone.controllers.main import OgoneController
from openerp.addons.payment_ogone.data import ogone
from openerp.osv import osv, fields
from openerp.tools import float_round
from openerp.tools.float_utils import float_compare
_logger = logging.getLogger(__name__)
class PaymentAcquirerOgone(osv.Model):
_inherit = 'payment.acquirer'
def _get_ogone_urls(self, cr, uid, environment, context=None):
""" Ogone URLS:
- standard order: POST address for form-based
@TDETODO: complete me
"""
return {
'ogone_standard_order_url': 'https://secure.ogone.com/ncol/%s/orderstandard_utf8.asp' % (environment,),
'ogone_direct_order_url': 'https://secure.ogone.com/ncol/%s/orderdirect_utf8.asp' % (environment,),
'ogone_direct_query_url': 'https://secure.ogone.com/ncol/%s/querydirect_utf8.asp' % (environment,),
'ogone_afu_agree_url': 'https://secure.ogone.com/ncol/%s/AFU_agree.asp' % (environment,),
}
def _get_providers(self, cr, uid, context=None):
providers = super(PaymentAcquirerOgone, self)._get_providers(cr, uid, context=context)
providers.append(['ogone', 'Ogone'])
return providers
_columns = {
'ogone_pspid': fields.char('PSPID', required_if_provider='ogone'),
'ogone_userid': fields.char('API User ID', required_if_provider='ogone'),
'ogone_password': fields.char('API User Password', required_if_provider='ogone'),
'ogone_shakey_in': fields.char('SHA Key IN', size=32, required_if_provider='ogone'),
'ogone_shakey_out': fields.char('SHA Key OUT', size=32, required_if_provider='ogone'),
}
def _ogone_generate_shasign(self, acquirer, inout, values):
""" Generate the shasign for incoming or outgoing communications.
:param browse acquirer: the payment.acquirer browse record. It should
have a shakey in shaky out
:param string inout: 'in' (openerp contacting ogone) or 'out' (ogone
contacting openerp). In this last case only some
fields should be contained (see e-Commerce basic)
:param dict values: transaction values
:return string: shasign
"""
assert inout in ('in', 'out')
assert acquirer.provider == 'ogone'
key = getattr(acquirer, 'ogone_shakey_' + inout)
def filter_key(key):
if inout == 'in':
return True
else:
# SHA-OUT keys
# source https://viveum.v-psp.com/Ncol/Viveum_e-Com-BAS_EN.pdf
keys = [
'AAVADDRESS',
'AAVCHECK',
'AAVMAIL',
'AAVNAME',
'AAVPHONE',
'AAVZIP',
'ACCEPTANCE',
'ALIAS',
'AMOUNT',
'BIC',
'BIN',
'BRAND',
'CARDNO',
'CCCTY',
'CN',
'COMPLUS',
'CREATION_STATUS',
'CURRENCY',
'CVCCHECK',
'DCC_COMMPERCENTAGE',
'DCC_CONVAMOUNT',
'DCC_CONVCCY',
'DCC_EXCHRATE',
'DCC_EXCHRATESOURCE',
'DCC_EXCHRATETS',
'DCC_INDICATOR',
'DCC_MARGINPERCENTAGE',
'DCC_VALIDHOURS',
'DIGESTCARDNO',
'ECI',
'ED',
'ENCCARDNO',
'FXAMOUNT',
'FXCURRENCY',
'IBAN',
'IP',
'IPCTY',
'NBREMAILUSAGE',
'NBRIPUSAGE',
'NBRIPUSAGE_ALLTX',
'NBRUSAGE',
'NCERROR',
'NCERRORCARDNO',
'NCERRORCN',
'NCERRORCVC',
'NCERRORED',
'ORDERID',
'PAYID',
'PM',
'SCO_CATEGORY',
'SCORING',
'STATUS',
'SUBBRAND',
'SUBSCRIPTION_ID',
'TRXDATE',
'VC'
]
return key.upper() in keys
items = sorted((k.upper(), v) for k, v in values.items())
sign = ''.join('%s=%s%s' % (k, v, key) for k, v in items if v and filter_key(k))
sign = sign.encode("utf-8")
shasign = sha1(sign).hexdigest()
return shasign
def ogone_form_generate_values(self, cr, uid, id, partner_values, tx_values, context=None):
base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
acquirer = self.browse(cr, uid, id, context=context)
ogone_tx_values = dict(tx_values)
temp_ogone_tx_values = {
'PSPID': acquirer.ogone_pspid,
'ORDERID': tx_values['reference'],
'AMOUNT': '%d' % int(float_round(tx_values['amount'], 2) * 100),
'CURRENCY': tx_values['currency'] and tx_values['currency'].name or '',
'LANGUAGE': partner_values['lang'],
'CN': partner_values['name'],
'EMAIL': partner_values['email'],
'OWNERZIP': partner_values['zip'],
'OWNERADDRESS': partner_values['address'],
'OWNERTOWN': partner_values['city'],
'OWNERCTY': partner_values['country'] and partner_values['country'].name or '',
'OWNERTELNO': partner_values['phone'],
'ACCEPTURL': '%s' % urlparse.urljoin(base_url, OgoneController._accept_url),
'DECLINEURL': '%s' % urlparse.urljoin(base_url, OgoneController._decline_url),
'EXCEPTIONURL': '%s' % urlparse.urljoin(base_url, OgoneController._exception_url),
'CANCELURL': '%s' % urlparse.urljoin(base_url, OgoneController._cancel_url),
}
if ogone_tx_values.get('return_url'):
temp_ogone_tx_values['PARAMPLUS'] = 'return_url=%s' % ogone_tx_values.pop('return_url')
shasign = self._ogone_generate_shasign(acquirer, 'in', temp_ogone_tx_values)
temp_ogone_tx_values['SHASIGN'] = shasign
ogone_tx_values.update(temp_ogone_tx_values)
return partner_values, ogone_tx_values
def ogone_get_form_action_url(self, cr, uid, id, context=None):
acquirer = self.browse(cr, uid, id, context=context)
return self._get_ogone_urls(cr, uid, acquirer.environment, context=context)['ogone_standard_order_url']
class PaymentTxOgone(osv.Model):
_inherit = 'payment.transaction'
# ogone status
_ogone_valid_tx_status = [5, 9]
_ogone_wait_tx_status = [41, 50, 51, 52, 55, 56, 91, 92, 99]
_ogone_pending_tx_status = [46] # 3DS HTML response
_ogone_cancel_tx_status = [1]
_columns = {
'ogone_3ds': fields.boolean('3DS Activated'),
'ogone_3ds_html': fields.html('3DS HTML'),
'ogone_complus': fields.char('Complus'),
'ogone_payid': fields.char('PayID', help='Payment ID, generated by Ogone')
}
# --------------------------------------------------
# FORM RELATED METHODS
# --------------------------------------------------
def _ogone_form_get_tx_from_data(self, cr, uid, data, context=None):
""" Given a data dict coming from ogone, verify it and find the related
transaction record. """
reference, pay_id, shasign = data.get('orderID'), data.get('PAYID'), data.get('SHASIGN')
if not reference or not pay_id or not shasign:
error_msg = 'Ogone: received data with missing reference (%s) or pay_id (%s) or shashign (%s)' % (reference, pay_id, shasign)
_logger.error(error_msg)
raise ValidationError(error_msg)
# find tx -> @TDENOTE use paytid ?
tx_ids = self.search(cr, uid, [('reference', '=', reference)], context=context)
if not tx_ids or len(tx_ids) > 1:
error_msg = 'Ogone: received data for reference %s' % (reference)
if not tx_ids:
error_msg += '; no order found'
else:
error_msg += '; multiple order found'
_logger.error(error_msg)
raise ValidationError(error_msg)
tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context)
# verify shasign
shasign_check = self.pool['payment.acquirer']._ogone_generate_shasign(tx.acquirer_id, 'out', data)
if shasign_check.upper() != shasign.upper():
error_msg = 'Ogone: invalid shasign, received %s, computed %s, for data %s' % (shasign, shasign_check, data)
_logger.error(error_msg)
raise ValidationError(error_msg)
return tx
def _ogone_form_get_invalid_parameters(self, cr, uid, tx, data, context=None):
invalid_parameters = []
# TODO: txn_id: should be false at draft, set afterwards, and verified with txn details
if tx.acquirer_reference and data.get('PAYID') != tx.acquirer_reference:
invalid_parameters.append(('PAYID', data.get('PAYID'), tx.acquirer_reference))
# check what is bought
if float_compare(float(data.get('amount', '0.0')), tx.amount, 2) != 0:
invalid_parameters.append(('amount', data.get('amount'), '%.2f' % tx.amount))
if data.get('currency') != tx.currency_id.name:
invalid_parameters.append(('currency', data.get('currency'), tx.currency_id.name))
return invalid_parameters
def _ogone_form_validate(self, cr, uid, tx, data, context=None):
if tx.state == 'done':
_logger.warning('Ogone: trying to validate an already validated tx (ref %s)' % tx.reference)
return True
status = int(data.get('STATUS', '0'))
if status in self._ogone_valid_tx_status:
tx.write({
'state': 'done',
'date_validate': data['TRXDATE'],
'acquirer_reference': data['PAYID'],
})
return True
elif status in self._ogone_cancel_tx_status:
tx.write({
'state': 'cancel',
'acquirer_reference': data.get('PAYID'),
})
elif status in self._ogone_pending_tx_status:
tx.write({
'state': 'pending',
'acquirer_reference': data.get('PAYID'),
})
else:
error = 'Ogone: feedback error: %(error_str)s\n\n%(error_code)s: %(error_msg)s' % {
'error_str': data.get('NCERROR'),
'error_code': data.get('NCERRORPLUS'),
'error_msg': ogone.OGONE_ERROR_MAP.get(data.get('NCERRORPLUS')),
}
_logger.info(error)
tx.write({
'state': 'error',
'state_message': error,
'acquirer_reference': data.get('PAYID'),
})
return False
# --------------------------------------------------
# S2S RELATED METHODS
# --------------------------------------------------
def ogone_s2s_create_alias(self, cr, uid, id, values, context=None):
""" Create an alias at Ogone via batch.
.. versionadded:: pre-v8 saas-3
.. warning::
Experimental code. You should not use it before OpenERP v8 official
release.
"""
tx = self.browse(cr, uid, id, context=context)
assert tx.type == 'server2server', 'Calling s2s dedicated method for a %s acquirer' % tx.type
alias = 'OPENERP-%d-%d' % (tx.partner_id.id, tx.id)
expiry_date = '%s%s' % (values['expiry_date_mm'], values['expiry_date_yy'][2:])
line = 'ADDALIAS;%(alias)s;%(holder_name)s;%(number)s;%(expiry_date)s;%(brand)s;%(pspid)s'
line = line % dict(values, alias=alias, expiry_date=expiry_date, pspid=tx.acquirer_id.ogone_pspid)
tx_data = {
'FILE_REFERENCE': 'OPENERP-NEW-ALIAS-%s' % time.time(), # something unique,
'TRANSACTION_CODE': 'ATR',
'OPERATION': 'SAL',
'NB_PAYMENTS': 1, # even if we do not actually have any payment, ogone want it to not be 0
'FILE': line,
'REPLY_TYPE': 'XML',
'PSPID': tx.acquirer_id.ogone_pspid,
'USERID': tx.acquirer_id.ogone_userid,
'PSWD': tx.acquirer_id.ogone_password,
'PROCESS_MODE': 'CHECKANDPROCESS',
}
# TODO: fix URL computation
request = urllib2.Request(tx.acquirer_id.ogone_afu_agree_url, urlencode(tx_data))
result = urllib2.urlopen(request).read()
try:
tree = objectify.fromstring(result)
except etree.XMLSyntaxError:
_logger.exception('Invalid xml response from ogone')
return None
error_code = error_str = None
if hasattr(tree, 'PARAMS_ERROR'):
error_code = tree.NCERROR.text
error_str = 'PARAMS ERROR: %s' % (tree.PARAMS_ERROR.text or '',)
else:
node = tree.FORMAT_CHECK
error_node = getattr(node, 'FORMAT_CHECK_ERROR', None)
if error_node is not None:
error_code = error_node.NCERROR.text
error_str = 'CHECK ERROR: %s' % (error_node.ERROR.text or '',)
if error_code:
error_msg = ogone.OGONE_ERROR_MAP.get(error_code)
error = '%s\n\n%s: %s' % (error_str, error_code, error_msg)
_logger.error(error)
raise Exception(error) # TODO specific exception
tx.write({'partner_reference': alias})
return True
def ogone_s2s_generate_values(self, cr, uid, id, custom_values, context=None):
""" Generate valid Ogone values for a s2s tx.
.. versionadded:: pre-v8 saas-3
.. warning::
Experimental code. You should not use it before OpenERP v8 official
release.
"""
tx = self.browse(cr, uid, id, context=context)
tx_data = {
'PSPID': tx.acquirer_id.ogone_pspid,
'USERID': tx.acquirer_id.ogone_userid,
'PSWD': tx.acquirer_id.ogone_password,
'OrderID': tx.reference,
'amount': '%d' % int(float_round(tx.amount, 2) * 100), # tde check amount or str * 100 ?
'CURRENCY': tx.currency_id.name,
'LANGUAGE': tx.partner_lang,
'OPERATION': 'SAL',
'ECI': 2, # Recurring (from MOTO)
'ALIAS': tx.partner_reference,
'RTIMEOUT': 30,
}
if custom_values.get('ogone_cvc'):
tx_data['CVC'] = custom_values.get('ogone_cvc')
if custom_values.pop('ogone_3ds', None):
tx_data.update({
'FLAG3D': 'Y', # YEAH!!
})
if custom_values.get('ogone_complus'):
tx_data['COMPLUS'] = custom_values.get('ogone_complus')
if custom_values.get('ogone_accept_url'):
pass
shasign = self.pool['payment.acquirer']._ogone_generate_shasign(tx.acquirer_id, 'in', tx_data)
tx_data['SHASIGN'] = shasign
return tx_data
def ogone_s2s_feedback(self, cr, uid, data, context=None):
"""
.. versionadded:: pre-v8 saas-3
.. warning::
Experimental code. You should not use it before OpenERP v8 official
release.
"""
pass
def ogone_s2s_execute(self, cr, uid, id, values, context=None):
"""
.. versionadded:: pre-v8 saas-3
.. warning::
Experimental code. You should not use it before OpenERP v8 official
release.
"""
tx = self.browse(cr, uid, id, context=context)
tx_data = self.ogone_s2s_generate_values(cr, uid, id, values, context=context)
_logger.info('Generated Ogone s2s data %s', pformat(tx_data)) # debug
request = urllib2.Request(tx.acquirer_id.ogone_direct_order_url, urlencode(tx_data))
result = urllib2.urlopen(request).read()
_logger.info('Contacted Ogone direct order; result %s', result) # debug
tree = objectify.fromstring(result)
payid = tree.get('PAYID')
query_direct_data = dict(
PSPID=tx.acquirer_id.ogone_pspid,
USERID=tx.acquirer_id.ogone_userid,
PSWD=tx.acquirer_id.ogone_password,
ID=payid,
)
query_direct_url = 'https://secure.ogone.com/ncol/%s/querydirect.asp' % (tx.acquirer_id.environment,)
tries = 2
tx_done = False
tx_status = False
while not tx_done or tries > 0:
try:
tree = objectify.fromstring(result)
except etree.XMLSyntaxError:
# invalid response from ogone
_logger.exception('Invalid xml response from ogone')
raise
# see https://secure.ogone.com/ncol/paymentinfos1.asp
VALID_TX = [5, 9]
WAIT_TX = [41, 50, 51, 52, 55, 56, 91, 92, 99]
PENDING_TX = [46] # 3DS HTML response
# other status are errors...
status = tree.get('STATUS')
if status == '':
status = None
else:
status = int(status)
if status in VALID_TX:
tx_status = True
tx_done = True
elif status in PENDING_TX:
html = str(tree.HTML_ANSWER)
tx_data.update(ogone_3ds_html=html.decode('base64'))
tx_status = False
tx_done = True
elif status in WAIT_TX:
time.sleep(1500)
request = urllib2.Request(query_direct_url, urlencode(query_direct_data))
result = urllib2.urlopen(request).read()
_logger.debug('Contacted Ogone query direct; result %s', result)
else:
error_code = tree.get('NCERROR')
if not ogone.retryable(error_code):
error_str = tree.get('NCERRORPLUS')
error_msg = ogone.OGONE_ERROR_MAP.get(error_code)
error = 'ERROR: %s\n\n%s: %s' % (error_str, error_code, error_msg)
_logger.info(error)
raise Exception(error)
tries = tries - 1
if not tx_done and tries == 0:
raise Exception('Cannot get transaction status...')
return tx_status
|
e-gob/plataforma-kioscos-autoatencion
|
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/windows/win_msg.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk>
#
# 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/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_msg
version_added: "2.3"
short_description: Sends a message to logged in users on Windows hosts.
description:
- Wraps the msg.exe command in order to send messages to Windows hosts.
options:
to:
description:
- Who to send the message to. Can be a username, sessionname or sessionid.
default: '*'
display_seconds:
description:
- How long to wait for receiver to acknowledge message, in seconds.
default: 10
wait:
description:
- Whether to wait for users to respond. Module will only wait for the number of seconds specified in display_seconds or 10 seconds if not specified.
However, if I(wait) is true, the message is sent to each logged on user in turn, waiting for the user to either press 'ok' or for
the timeout to elapse before moving on to the next user.
type: bool
default: 'no'
msg:
description:
- The text of the message to be displayed.
- The message must be less than 256 characters.
default: Hello world!
author:
- Jon Hawkesworth (@jhawkesworth)
notes:
- This module must run on a windows host, so ensure your play targets windows
hosts, or delegates to a windows host.
- Messages are only sent to the local host where the module is run.
- The module does not support sending to users listed in a file.
- Setting wait to true can result in long run times on systems with many logged in users.
'''
EXAMPLES = r'''
- name: Warn logged in users of impending upgrade
win_msg:
display_seconds: 60
msg: Automated upgrade about to start. Please save your work and log off before {{ deployment_start_time }}
'''
RETURN = r'''
msg:
description: Test of the message that was sent.
returned: changed
type: string
sample: Automated upgrade about to start. Please save your work and log off before 22 July 2016 18:00:00
display_seconds:
description: Value of display_seconds module parameter.
returned: success
type: string
sample: 10
rc:
description: The return code of the API call
returned: always
type: int
sample: 0
runtime_seconds:
description: How long the module took to run on the remote windows host.
returned: success
type: string
sample: 22 July 2016 17:45:51
sent_localtime:
description: local time from windows host when the message was sent.
returned: success
type: string
sample: 22 July 2016 17:45:51
wait:
description: Value of wait module parameter.
returned: success
type: boolean
sample: false
'''
|
esplinr/foodcheck
|
wsgi/foodcheck_proj/south/tests/__init__.py
|
from __future__ import print_function
#import unittest
import os
import sys
from functools import wraps
from django.conf import settings
from south.hacks import hacks
# Make sure skipping tests is available.
try:
# easiest and best is unittest included in Django>=1.3
from django.utils import unittest
except ImportError:
# earlier django... use unittest from stdlib
import unittest
# however, skipUnless was only added in Python 2.7;
# if not available, we need to do something else
try:
skipUnless = unittest.skipUnless #@UnusedVariable
except AttributeError:
def skipUnless(condition, message):
def decorator(testfunc):
@wraps(testfunc)
def wrapper(self):
if condition:
# Apply method
testfunc(self)
else:
# The skip exceptions are not available either...
print("Skipping", testfunc.__name__,"--", message)
return wrapper
return decorator
# ditto for skipIf
try:
skipIf = unittest.skipIf #@UnusedVariable
except AttributeError:
def skipIf(condition, message):
def decorator(testfunc):
@wraps(testfunc)
def wrapper(self):
if condition:
print("Skipping", testfunc.__name__,"--", message)
else:
# Apply method
testfunc(self)
return wrapper
return decorator
# Add the tests directory so fakeapp is on sys.path
test_root = os.path.dirname(__file__)
sys.path.append(test_root)
# Note: the individual test files are imported below this.
class Monkeypatcher(unittest.TestCase):
"""
Base test class for tests that play with the INSTALLED_APPS setting at runtime.
"""
def create_fake_app(self, name):
class Fake:
pass
fake = Fake()
fake.__name__ = name
try:
fake.migrations = __import__(name + ".migrations", {}, {}, ['migrations'])
except ImportError:
pass
return fake
def setUp(self):
"""
Changes the Django environment so we can run tests against our test apps.
"""
if hasattr(self, 'installed_apps'):
hacks.store_app_cache_state()
hacks.set_installed_apps(self.installed_apps)
# Make sure dependencies are calculated for new apps
Migrations._dependencies_done = False
def tearDown(self):
"""
Undoes what setUp did.
"""
if hasattr(self, 'installed_apps'):
hacks.reset_installed_apps()
hacks.restore_app_cache_state()
# Try importing all tests if asked for (then we can run 'em)
try:
skiptest = settings.SKIP_SOUTH_TESTS
except:
skiptest = True
if not skiptest:
from south.tests.db import *
from south.tests.db_mysql import *
from south.tests.logic import *
from south.tests.autodetection import *
from south.tests.logger import *
from south.tests.inspector import *
from south.tests.freezer import *
|
amrdraz/brython
|
www/src/Lib/encodings/mac_arabic.py
|
""" Python Character Mapping Codec generated from 'VENDORS/APPLE/ARABIC.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='mac-arabic',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x0081: 0x00a0, # NO-BREAK SPACE, right-left
0x0082: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0084: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE
0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x008b: 0x06ba, # ARABIC LETTER NOON GHUNNA
0x008c: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left
0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x0093: 0x2026, # HORIZONTAL ELLIPSIS, right-left
0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS
0x0096: 0x00f1, # LATIN SMALL LETTER N WITH TILDE
0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x0098: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left
0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x009b: 0x00f7, # DIVISION SIGN, right-left
0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE
0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x00a0: 0x0020, # SPACE, right-left
0x00a1: 0x0021, # EXCLAMATION MARK, right-left
0x00a2: 0x0022, # QUOTATION MARK, right-left
0x00a3: 0x0023, # NUMBER SIGN, right-left
0x00a4: 0x0024, # DOLLAR SIGN, right-left
0x00a5: 0x066a, # ARABIC PERCENT SIGN
0x00a6: 0x0026, # AMPERSAND, right-left
0x00a7: 0x0027, # APOSTROPHE, right-left
0x00a8: 0x0028, # LEFT PARENTHESIS, right-left
0x00a9: 0x0029, # RIGHT PARENTHESIS, right-left
0x00aa: 0x002a, # ASTERISK, right-left
0x00ab: 0x002b, # PLUS SIGN, right-left
0x00ac: 0x060c, # ARABIC COMMA
0x00ad: 0x002d, # HYPHEN-MINUS, right-left
0x00ae: 0x002e, # FULL STOP, right-left
0x00af: 0x002f, # SOLIDUS, right-left
0x00b0: 0x0660, # ARABIC-INDIC DIGIT ZERO, right-left (need override)
0x00b1: 0x0661, # ARABIC-INDIC DIGIT ONE, right-left (need override)
0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO, right-left (need override)
0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE, right-left (need override)
0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR, right-left (need override)
0x00b5: 0x0665, # ARABIC-INDIC DIGIT FIVE, right-left (need override)
0x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX, right-left (need override)
0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN, right-left (need override)
0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT, right-left (need override)
0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE, right-left (need override)
0x00ba: 0x003a, # COLON, right-left
0x00bb: 0x061b, # ARABIC SEMICOLON
0x00bc: 0x003c, # LESS-THAN SIGN, right-left
0x00bd: 0x003d, # EQUALS SIGN, right-left
0x00be: 0x003e, # GREATER-THAN SIGN, right-left
0x00bf: 0x061f, # ARABIC QUESTION MARK
0x00c0: 0x274a, # EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left
0x00c1: 0x0621, # ARABIC LETTER HAMZA
0x00c2: 0x0622, # ARABIC LETTER ALEF WITH MADDA ABOVE
0x00c3: 0x0623, # ARABIC LETTER ALEF WITH HAMZA ABOVE
0x00c4: 0x0624, # ARABIC LETTER WAW WITH HAMZA ABOVE
0x00c5: 0x0625, # ARABIC LETTER ALEF WITH HAMZA BELOW
0x00c6: 0x0626, # ARABIC LETTER YEH WITH HAMZA ABOVE
0x00c7: 0x0627, # ARABIC LETTER ALEF
0x00c8: 0x0628, # ARABIC LETTER BEH
0x00c9: 0x0629, # ARABIC LETTER TEH MARBUTA
0x00ca: 0x062a, # ARABIC LETTER TEH
0x00cb: 0x062b, # ARABIC LETTER THEH
0x00cc: 0x062c, # ARABIC LETTER JEEM
0x00cd: 0x062d, # ARABIC LETTER HAH
0x00ce: 0x062e, # ARABIC LETTER KHAH
0x00cf: 0x062f, # ARABIC LETTER DAL
0x00d0: 0x0630, # ARABIC LETTER THAL
0x00d1: 0x0631, # ARABIC LETTER REH
0x00d2: 0x0632, # ARABIC LETTER ZAIN
0x00d3: 0x0633, # ARABIC LETTER SEEN
0x00d4: 0x0634, # ARABIC LETTER SHEEN
0x00d5: 0x0635, # ARABIC LETTER SAD
0x00d6: 0x0636, # ARABIC LETTER DAD
0x00d7: 0x0637, # ARABIC LETTER TAH
0x00d8: 0x0638, # ARABIC LETTER ZAH
0x00d9: 0x0639, # ARABIC LETTER AIN
0x00da: 0x063a, # ARABIC LETTER GHAIN
0x00db: 0x005b, # LEFT SQUARE BRACKET, right-left
0x00dc: 0x005c, # REVERSE SOLIDUS, right-left
0x00dd: 0x005d, # RIGHT SQUARE BRACKET, right-left
0x00de: 0x005e, # CIRCUMFLEX ACCENT, right-left
0x00df: 0x005f, # LOW LINE, right-left
0x00e0: 0x0640, # ARABIC TATWEEL
0x00e1: 0x0641, # ARABIC LETTER FEH
0x00e2: 0x0642, # ARABIC LETTER QAF
0x00e3: 0x0643, # ARABIC LETTER KAF
0x00e4: 0x0644, # ARABIC LETTER LAM
0x00e5: 0x0645, # ARABIC LETTER MEEM
0x00e6: 0x0646, # ARABIC LETTER NOON
0x00e7: 0x0647, # ARABIC LETTER HEH
0x00e8: 0x0648, # ARABIC LETTER WAW
0x00e9: 0x0649, # ARABIC LETTER ALEF MAKSURA
0x00ea: 0x064a, # ARABIC LETTER YEH
0x00eb: 0x064b, # ARABIC FATHATAN
0x00ec: 0x064c, # ARABIC DAMMATAN
0x00ed: 0x064d, # ARABIC KASRATAN
0x00ee: 0x064e, # ARABIC FATHA
0x00ef: 0x064f, # ARABIC DAMMA
0x00f0: 0x0650, # ARABIC KASRA
0x00f1: 0x0651, # ARABIC SHADDA
0x00f2: 0x0652, # ARABIC SUKUN
0x00f3: 0x067e, # ARABIC LETTER PEH
0x00f4: 0x0679, # ARABIC LETTER TTEH
0x00f5: 0x0686, # ARABIC LETTER TCHEH
0x00f6: 0x06d5, # ARABIC LETTER AE
0x00f7: 0x06a4, # ARABIC LETTER VEH
0x00f8: 0x06af, # ARABIC LETTER GAF
0x00f9: 0x0688, # ARABIC LETTER DDAL
0x00fa: 0x0691, # ARABIC LETTER RREH
0x00fb: 0x007b, # LEFT CURLY BRACKET, right-left
0x00fc: 0x007c, # VERTICAL LINE, right-left
0x00fd: 0x007d, # RIGHT CURLY BRACKET, right-left
0x00fe: 0x0698, # ARABIC LETTER JEH
0x00ff: 0x06d2, # ARABIC LETTER YEH BARREE
})
### Decoding Table
decoding_table = (
'\x00' # 0x0000 -> CONTROL CHARACTER
'\x01' # 0x0001 -> CONTROL CHARACTER
'\x02' # 0x0002 -> CONTROL CHARACTER
'\x03' # 0x0003 -> CONTROL CHARACTER
'\x04' # 0x0004 -> CONTROL CHARACTER
'\x05' # 0x0005 -> CONTROL CHARACTER
'\x06' # 0x0006 -> CONTROL CHARACTER
'\x07' # 0x0007 -> CONTROL CHARACTER
'\x08' # 0x0008 -> CONTROL CHARACTER
'\t' # 0x0009 -> CONTROL CHARACTER
'\n' # 0x000a -> CONTROL CHARACTER
'\x0b' # 0x000b -> CONTROL CHARACTER
'\x0c' # 0x000c -> CONTROL CHARACTER
'\r' # 0x000d -> CONTROL CHARACTER
'\x0e' # 0x000e -> CONTROL CHARACTER
'\x0f' # 0x000f -> CONTROL CHARACTER
'\x10' # 0x0010 -> CONTROL CHARACTER
'\x11' # 0x0011 -> CONTROL CHARACTER
'\x12' # 0x0012 -> CONTROL CHARACTER
'\x13' # 0x0013 -> CONTROL CHARACTER
'\x14' # 0x0014 -> CONTROL CHARACTER
'\x15' # 0x0015 -> CONTROL CHARACTER
'\x16' # 0x0016 -> CONTROL CHARACTER
'\x17' # 0x0017 -> CONTROL CHARACTER
'\x18' # 0x0018 -> CONTROL CHARACTER
'\x19' # 0x0019 -> CONTROL CHARACTER
'\x1a' # 0x001a -> CONTROL CHARACTER
'\x1b' # 0x001b -> CONTROL CHARACTER
'\x1c' # 0x001c -> CONTROL CHARACTER
'\x1d' # 0x001d -> CONTROL CHARACTER
'\x1e' # 0x001e -> CONTROL CHARACTER
'\x1f' # 0x001f -> CONTROL CHARACTER
' ' # 0x0020 -> SPACE, left-right
'!' # 0x0021 -> EXCLAMATION MARK, left-right
'"' # 0x0022 -> QUOTATION MARK, left-right
'#' # 0x0023 -> NUMBER SIGN, left-right
'$' # 0x0024 -> DOLLAR SIGN, left-right
'%' # 0x0025 -> PERCENT SIGN, left-right
'&' # 0x0026 -> AMPERSAND, left-right
"'" # 0x0027 -> APOSTROPHE, left-right
'(' # 0x0028 -> LEFT PARENTHESIS, left-right
')' # 0x0029 -> RIGHT PARENTHESIS, left-right
'*' # 0x002a -> ASTERISK, left-right
'+' # 0x002b -> PLUS SIGN, left-right
',' # 0x002c -> COMMA, left-right; in Arabic-script context, displayed as 0x066C ARABIC THOUSANDS SEPARATOR
'-' # 0x002d -> HYPHEN-MINUS, left-right
'.' # 0x002e -> FULL STOP, left-right; in Arabic-script context, displayed as 0x066B ARABIC DECIMAL SEPARATOR
'/' # 0x002f -> SOLIDUS, left-right
'0' # 0x0030 -> DIGIT ZERO; in Arabic-script context, displayed as 0x0660 ARABIC-INDIC DIGIT ZERO
'1' # 0x0031 -> DIGIT ONE; in Arabic-script context, displayed as 0x0661 ARABIC-INDIC DIGIT ONE
'2' # 0x0032 -> DIGIT TWO; in Arabic-script context, displayed as 0x0662 ARABIC-INDIC DIGIT TWO
'3' # 0x0033 -> DIGIT THREE; in Arabic-script context, displayed as 0x0663 ARABIC-INDIC DIGIT THREE
'4' # 0x0034 -> DIGIT FOUR; in Arabic-script context, displayed as 0x0664 ARABIC-INDIC DIGIT FOUR
'5' # 0x0035 -> DIGIT FIVE; in Arabic-script context, displayed as 0x0665 ARABIC-INDIC DIGIT FIVE
'6' # 0x0036 -> DIGIT SIX; in Arabic-script context, displayed as 0x0666 ARABIC-INDIC DIGIT SIX
'7' # 0x0037 -> DIGIT SEVEN; in Arabic-script context, displayed as 0x0667 ARABIC-INDIC DIGIT SEVEN
'8' # 0x0038 -> DIGIT EIGHT; in Arabic-script context, displayed as 0x0668 ARABIC-INDIC DIGIT EIGHT
'9' # 0x0039 -> DIGIT NINE; in Arabic-script context, displayed as 0x0669 ARABIC-INDIC DIGIT NINE
':' # 0x003a -> COLON, left-right
';' # 0x003b -> SEMICOLON, left-right
'<' # 0x003c -> LESS-THAN SIGN, left-right
'=' # 0x003d -> EQUALS SIGN, left-right
'>' # 0x003e -> GREATER-THAN SIGN, left-right
'?' # 0x003f -> QUESTION MARK, left-right
'@' # 0x0040 -> COMMERCIAL AT
'A' # 0x0041 -> LATIN CAPITAL LETTER A
'B' # 0x0042 -> LATIN CAPITAL LETTER B
'C' # 0x0043 -> LATIN CAPITAL LETTER C
'D' # 0x0044 -> LATIN CAPITAL LETTER D
'E' # 0x0045 -> LATIN CAPITAL LETTER E
'F' # 0x0046 -> LATIN CAPITAL LETTER F
'G' # 0x0047 -> LATIN CAPITAL LETTER G
'H' # 0x0048 -> LATIN CAPITAL LETTER H
'I' # 0x0049 -> LATIN CAPITAL LETTER I
'J' # 0x004a -> LATIN CAPITAL LETTER J
'K' # 0x004b -> LATIN CAPITAL LETTER K
'L' # 0x004c -> LATIN CAPITAL LETTER L
'M' # 0x004d -> LATIN CAPITAL LETTER M
'N' # 0x004e -> LATIN CAPITAL LETTER N
'O' # 0x004f -> LATIN CAPITAL LETTER O
'P' # 0x0050 -> LATIN CAPITAL LETTER P
'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
'R' # 0x0052 -> LATIN CAPITAL LETTER R
'S' # 0x0053 -> LATIN CAPITAL LETTER S
'T' # 0x0054 -> LATIN CAPITAL LETTER T
'U' # 0x0055 -> LATIN CAPITAL LETTER U
'V' # 0x0056 -> LATIN CAPITAL LETTER V
'W' # 0x0057 -> LATIN CAPITAL LETTER W
'X' # 0x0058 -> LATIN CAPITAL LETTER X
'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
'Z' # 0x005a -> LATIN CAPITAL LETTER Z
'[' # 0x005b -> LEFT SQUARE BRACKET, left-right
'\\' # 0x005c -> REVERSE SOLIDUS, left-right
']' # 0x005d -> RIGHT SQUARE BRACKET, left-right
'^' # 0x005e -> CIRCUMFLEX ACCENT, left-right
'_' # 0x005f -> LOW LINE, left-right
'`' # 0x0060 -> GRAVE ACCENT
'a' # 0x0061 -> LATIN SMALL LETTER A
'b' # 0x0062 -> LATIN SMALL LETTER B
'c' # 0x0063 -> LATIN SMALL LETTER C
'd' # 0x0064 -> LATIN SMALL LETTER D
'e' # 0x0065 -> LATIN SMALL LETTER E
'f' # 0x0066 -> LATIN SMALL LETTER F
'g' # 0x0067 -> LATIN SMALL LETTER G
'h' # 0x0068 -> LATIN SMALL LETTER H
'i' # 0x0069 -> LATIN SMALL LETTER I
'j' # 0x006a -> LATIN SMALL LETTER J
'k' # 0x006b -> LATIN SMALL LETTER K
'l' # 0x006c -> LATIN SMALL LETTER L
'm' # 0x006d -> LATIN SMALL LETTER M
'n' # 0x006e -> LATIN SMALL LETTER N
'o' # 0x006f -> LATIN SMALL LETTER O
'p' # 0x0070 -> LATIN SMALL LETTER P
'q' # 0x0071 -> LATIN SMALL LETTER Q
'r' # 0x0072 -> LATIN SMALL LETTER R
's' # 0x0073 -> LATIN SMALL LETTER S
't' # 0x0074 -> LATIN SMALL LETTER T
'u' # 0x0075 -> LATIN SMALL LETTER U
'v' # 0x0076 -> LATIN SMALL LETTER V
'w' # 0x0077 -> LATIN SMALL LETTER W
'x' # 0x0078 -> LATIN SMALL LETTER X
'y' # 0x0079 -> LATIN SMALL LETTER Y
'z' # 0x007a -> LATIN SMALL LETTER Z
'{' # 0x007b -> LEFT CURLY BRACKET, left-right
'|' # 0x007c -> VERTICAL LINE, left-right
'}' # 0x007d -> RIGHT CURLY BRACKET, left-right
'~' # 0x007e -> TILDE
'\x7f' # 0x007f -> CONTROL CHARACTER
'\xc4' # 0x0080 -> LATIN CAPITAL LETTER A WITH DIAERESIS
'\xa0' # 0x0081 -> NO-BREAK SPACE, right-left
'\xc7' # 0x0082 -> LATIN CAPITAL LETTER C WITH CEDILLA
'\xc9' # 0x0083 -> LATIN CAPITAL LETTER E WITH ACUTE
'\xd1' # 0x0084 -> LATIN CAPITAL LETTER N WITH TILDE
'\xd6' # 0x0085 -> LATIN CAPITAL LETTER O WITH DIAERESIS
'\xdc' # 0x0086 -> LATIN CAPITAL LETTER U WITH DIAERESIS
'\xe1' # 0x0087 -> LATIN SMALL LETTER A WITH ACUTE
'\xe0' # 0x0088 -> LATIN SMALL LETTER A WITH GRAVE
'\xe2' # 0x0089 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
'\xe4' # 0x008a -> LATIN SMALL LETTER A WITH DIAERESIS
'\u06ba' # 0x008b -> ARABIC LETTER NOON GHUNNA
'\xab' # 0x008c -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left
'\xe7' # 0x008d -> LATIN SMALL LETTER C WITH CEDILLA
'\xe9' # 0x008e -> LATIN SMALL LETTER E WITH ACUTE
'\xe8' # 0x008f -> LATIN SMALL LETTER E WITH GRAVE
'\xea' # 0x0090 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
'\xeb' # 0x0091 -> LATIN SMALL LETTER E WITH DIAERESIS
'\xed' # 0x0092 -> LATIN SMALL LETTER I WITH ACUTE
'\u2026' # 0x0093 -> HORIZONTAL ELLIPSIS, right-left
'\xee' # 0x0094 -> LATIN SMALL LETTER I WITH CIRCUMFLEX
'\xef' # 0x0095 -> LATIN SMALL LETTER I WITH DIAERESIS
'\xf1' # 0x0096 -> LATIN SMALL LETTER N WITH TILDE
'\xf3' # 0x0097 -> LATIN SMALL LETTER O WITH ACUTE
'\xbb' # 0x0098 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left
'\xf4' # 0x0099 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
'\xf6' # 0x009a -> LATIN SMALL LETTER O WITH DIAERESIS
'\xf7' # 0x009b -> DIVISION SIGN, right-left
'\xfa' # 0x009c -> LATIN SMALL LETTER U WITH ACUTE
'\xf9' # 0x009d -> LATIN SMALL LETTER U WITH GRAVE
'\xfb' # 0x009e -> LATIN SMALL LETTER U WITH CIRCUMFLEX
'\xfc' # 0x009f -> LATIN SMALL LETTER U WITH DIAERESIS
' ' # 0x00a0 -> SPACE, right-left
'!' # 0x00a1 -> EXCLAMATION MARK, right-left
'"' # 0x00a2 -> QUOTATION MARK, right-left
'#' # 0x00a3 -> NUMBER SIGN, right-left
'$' # 0x00a4 -> DOLLAR SIGN, right-left
'\u066a' # 0x00a5 -> ARABIC PERCENT SIGN
'&' # 0x00a6 -> AMPERSAND, right-left
"'" # 0x00a7 -> APOSTROPHE, right-left
'(' # 0x00a8 -> LEFT PARENTHESIS, right-left
')' # 0x00a9 -> RIGHT PARENTHESIS, right-left
'*' # 0x00aa -> ASTERISK, right-left
'+' # 0x00ab -> PLUS SIGN, right-left
'\u060c' # 0x00ac -> ARABIC COMMA
'-' # 0x00ad -> HYPHEN-MINUS, right-left
'.' # 0x00ae -> FULL STOP, right-left
'/' # 0x00af -> SOLIDUS, right-left
'\u0660' # 0x00b0 -> ARABIC-INDIC DIGIT ZERO, right-left (need override)
'\u0661' # 0x00b1 -> ARABIC-INDIC DIGIT ONE, right-left (need override)
'\u0662' # 0x00b2 -> ARABIC-INDIC DIGIT TWO, right-left (need override)
'\u0663' # 0x00b3 -> ARABIC-INDIC DIGIT THREE, right-left (need override)
'\u0664' # 0x00b4 -> ARABIC-INDIC DIGIT FOUR, right-left (need override)
'\u0665' # 0x00b5 -> ARABIC-INDIC DIGIT FIVE, right-left (need override)
'\u0666' # 0x00b6 -> ARABIC-INDIC DIGIT SIX, right-left (need override)
'\u0667' # 0x00b7 -> ARABIC-INDIC DIGIT SEVEN, right-left (need override)
'\u0668' # 0x00b8 -> ARABIC-INDIC DIGIT EIGHT, right-left (need override)
'\u0669' # 0x00b9 -> ARABIC-INDIC DIGIT NINE, right-left (need override)
':' # 0x00ba -> COLON, right-left
'\u061b' # 0x00bb -> ARABIC SEMICOLON
'<' # 0x00bc -> LESS-THAN SIGN, right-left
'=' # 0x00bd -> EQUALS SIGN, right-left
'>' # 0x00be -> GREATER-THAN SIGN, right-left
'\u061f' # 0x00bf -> ARABIC QUESTION MARK
'\u274a' # 0x00c0 -> EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left
'\u0621' # 0x00c1 -> ARABIC LETTER HAMZA
'\u0622' # 0x00c2 -> ARABIC LETTER ALEF WITH MADDA ABOVE
'\u0623' # 0x00c3 -> ARABIC LETTER ALEF WITH HAMZA ABOVE
'\u0624' # 0x00c4 -> ARABIC LETTER WAW WITH HAMZA ABOVE
'\u0625' # 0x00c5 -> ARABIC LETTER ALEF WITH HAMZA BELOW
'\u0626' # 0x00c6 -> ARABIC LETTER YEH WITH HAMZA ABOVE
'\u0627' # 0x00c7 -> ARABIC LETTER ALEF
'\u0628' # 0x00c8 -> ARABIC LETTER BEH
'\u0629' # 0x00c9 -> ARABIC LETTER TEH MARBUTA
'\u062a' # 0x00ca -> ARABIC LETTER TEH
'\u062b' # 0x00cb -> ARABIC LETTER THEH
'\u062c' # 0x00cc -> ARABIC LETTER JEEM
'\u062d' # 0x00cd -> ARABIC LETTER HAH
'\u062e' # 0x00ce -> ARABIC LETTER KHAH
'\u062f' # 0x00cf -> ARABIC LETTER DAL
'\u0630' # 0x00d0 -> ARABIC LETTER THAL
'\u0631' # 0x00d1 -> ARABIC LETTER REH
'\u0632' # 0x00d2 -> ARABIC LETTER ZAIN
'\u0633' # 0x00d3 -> ARABIC LETTER SEEN
'\u0634' # 0x00d4 -> ARABIC LETTER SHEEN
'\u0635' # 0x00d5 -> ARABIC LETTER SAD
'\u0636' # 0x00d6 -> ARABIC LETTER DAD
'\u0637' # 0x00d7 -> ARABIC LETTER TAH
'\u0638' # 0x00d8 -> ARABIC LETTER ZAH
'\u0639' # 0x00d9 -> ARABIC LETTER AIN
'\u063a' # 0x00da -> ARABIC LETTER GHAIN
'[' # 0x00db -> LEFT SQUARE BRACKET, right-left
'\\' # 0x00dc -> REVERSE SOLIDUS, right-left
']' # 0x00dd -> RIGHT SQUARE BRACKET, right-left
'^' # 0x00de -> CIRCUMFLEX ACCENT, right-left
'_' # 0x00df -> LOW LINE, right-left
'\u0640' # 0x00e0 -> ARABIC TATWEEL
'\u0641' # 0x00e1 -> ARABIC LETTER FEH
'\u0642' # 0x00e2 -> ARABIC LETTER QAF
'\u0643' # 0x00e3 -> ARABIC LETTER KAF
'\u0644' # 0x00e4 -> ARABIC LETTER LAM
'\u0645' # 0x00e5 -> ARABIC LETTER MEEM
'\u0646' # 0x00e6 -> ARABIC LETTER NOON
'\u0647' # 0x00e7 -> ARABIC LETTER HEH
'\u0648' # 0x00e8 -> ARABIC LETTER WAW
'\u0649' # 0x00e9 -> ARABIC LETTER ALEF MAKSURA
'\u064a' # 0x00ea -> ARABIC LETTER YEH
'\u064b' # 0x00eb -> ARABIC FATHATAN
'\u064c' # 0x00ec -> ARABIC DAMMATAN
'\u064d' # 0x00ed -> ARABIC KASRATAN
'\u064e' # 0x00ee -> ARABIC FATHA
'\u064f' # 0x00ef -> ARABIC DAMMA
'\u0650' # 0x00f0 -> ARABIC KASRA
'\u0651' # 0x00f1 -> ARABIC SHADDA
'\u0652' # 0x00f2 -> ARABIC SUKUN
'\u067e' # 0x00f3 -> ARABIC LETTER PEH
'\u0679' # 0x00f4 -> ARABIC LETTER TTEH
'\u0686' # 0x00f5 -> ARABIC LETTER TCHEH
'\u06d5' # 0x00f6 -> ARABIC LETTER AE
'\u06a4' # 0x00f7 -> ARABIC LETTER VEH
'\u06af' # 0x00f8 -> ARABIC LETTER GAF
'\u0688' # 0x00f9 -> ARABIC LETTER DDAL
'\u0691' # 0x00fa -> ARABIC LETTER RREH
'{' # 0x00fb -> LEFT CURLY BRACKET, right-left
'|' # 0x00fc -> VERTICAL LINE, right-left
'}' # 0x00fd -> RIGHT CURLY BRACKET, right-left
'\u0698' # 0x00fe -> ARABIC LETTER JEH
'\u06d2' # 0x00ff -> ARABIC LETTER YEH BARREE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # CONTROL CHARACTER
0x0001: 0x0001, # CONTROL CHARACTER
0x0002: 0x0002, # CONTROL CHARACTER
0x0003: 0x0003, # CONTROL CHARACTER
0x0004: 0x0004, # CONTROL CHARACTER
0x0005: 0x0005, # CONTROL CHARACTER
0x0006: 0x0006, # CONTROL CHARACTER
0x0007: 0x0007, # CONTROL CHARACTER
0x0008: 0x0008, # CONTROL CHARACTER
0x0009: 0x0009, # CONTROL CHARACTER
0x000a: 0x000a, # CONTROL CHARACTER
0x000b: 0x000b, # CONTROL CHARACTER
0x000c: 0x000c, # CONTROL CHARACTER
0x000d: 0x000d, # CONTROL CHARACTER
0x000e: 0x000e, # CONTROL CHARACTER
0x000f: 0x000f, # CONTROL CHARACTER
0x0010: 0x0010, # CONTROL CHARACTER
0x0011: 0x0011, # CONTROL CHARACTER
0x0012: 0x0012, # CONTROL CHARACTER
0x0013: 0x0013, # CONTROL CHARACTER
0x0014: 0x0014, # CONTROL CHARACTER
0x0015: 0x0015, # CONTROL CHARACTER
0x0016: 0x0016, # CONTROL CHARACTER
0x0017: 0x0017, # CONTROL CHARACTER
0x0018: 0x0018, # CONTROL CHARACTER
0x0019: 0x0019, # CONTROL CHARACTER
0x001a: 0x001a, # CONTROL CHARACTER
0x001b: 0x001b, # CONTROL CHARACTER
0x001c: 0x001c, # CONTROL CHARACTER
0x001d: 0x001d, # CONTROL CHARACTER
0x001e: 0x001e, # CONTROL CHARACTER
0x001f: 0x001f, # CONTROL CHARACTER
0x0020: 0x0020, # SPACE, left-right
0x0020: 0x00a0, # SPACE, right-left
0x0021: 0x0021, # EXCLAMATION MARK, left-right
0x0021: 0x00a1, # EXCLAMATION MARK, right-left
0x0022: 0x0022, # QUOTATION MARK, left-right
0x0022: 0x00a2, # QUOTATION MARK, right-left
0x0023: 0x0023, # NUMBER SIGN, left-right
0x0023: 0x00a3, # NUMBER SIGN, right-left
0x0024: 0x0024, # DOLLAR SIGN, left-right
0x0024: 0x00a4, # DOLLAR SIGN, right-left
0x0025: 0x0025, # PERCENT SIGN, left-right
0x0026: 0x0026, # AMPERSAND, left-right
0x0026: 0x00a6, # AMPERSAND, right-left
0x0027: 0x0027, # APOSTROPHE, left-right
0x0027: 0x00a7, # APOSTROPHE, right-left
0x0028: 0x0028, # LEFT PARENTHESIS, left-right
0x0028: 0x00a8, # LEFT PARENTHESIS, right-left
0x0029: 0x0029, # RIGHT PARENTHESIS, left-right
0x0029: 0x00a9, # RIGHT PARENTHESIS, right-left
0x002a: 0x002a, # ASTERISK, left-right
0x002a: 0x00aa, # ASTERISK, right-left
0x002b: 0x002b, # PLUS SIGN, left-right
0x002b: 0x00ab, # PLUS SIGN, right-left
0x002c: 0x002c, # COMMA, left-right; in Arabic-script context, displayed as 0x066C ARABIC THOUSANDS SEPARATOR
0x002d: 0x002d, # HYPHEN-MINUS, left-right
0x002d: 0x00ad, # HYPHEN-MINUS, right-left
0x002e: 0x002e, # FULL STOP, left-right; in Arabic-script context, displayed as 0x066B ARABIC DECIMAL SEPARATOR
0x002e: 0x00ae, # FULL STOP, right-left
0x002f: 0x002f, # SOLIDUS, left-right
0x002f: 0x00af, # SOLIDUS, right-left
0x0030: 0x0030, # DIGIT ZERO; in Arabic-script context, displayed as 0x0660 ARABIC-INDIC DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE; in Arabic-script context, displayed as 0x0661 ARABIC-INDIC DIGIT ONE
0x0032: 0x0032, # DIGIT TWO; in Arabic-script context, displayed as 0x0662 ARABIC-INDIC DIGIT TWO
0x0033: 0x0033, # DIGIT THREE; in Arabic-script context, displayed as 0x0663 ARABIC-INDIC DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR; in Arabic-script context, displayed as 0x0664 ARABIC-INDIC DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE; in Arabic-script context, displayed as 0x0665 ARABIC-INDIC DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX; in Arabic-script context, displayed as 0x0666 ARABIC-INDIC DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN; in Arabic-script context, displayed as 0x0667 ARABIC-INDIC DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT; in Arabic-script context, displayed as 0x0668 ARABIC-INDIC DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE; in Arabic-script context, displayed as 0x0669 ARABIC-INDIC DIGIT NINE
0x003a: 0x003a, # COLON, left-right
0x003a: 0x00ba, # COLON, right-left
0x003b: 0x003b, # SEMICOLON, left-right
0x003c: 0x003c, # LESS-THAN SIGN, left-right
0x003c: 0x00bc, # LESS-THAN SIGN, right-left
0x003d: 0x003d, # EQUALS SIGN, left-right
0x003d: 0x00bd, # EQUALS SIGN, right-left
0x003e: 0x003e, # GREATER-THAN SIGN, left-right
0x003e: 0x00be, # GREATER-THAN SIGN, right-left
0x003f: 0x003f, # QUESTION MARK, left-right
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET, left-right
0x005b: 0x00db, # LEFT SQUARE BRACKET, right-left
0x005c: 0x005c, # REVERSE SOLIDUS, left-right
0x005c: 0x00dc, # REVERSE SOLIDUS, right-left
0x005d: 0x005d, # RIGHT SQUARE BRACKET, left-right
0x005d: 0x00dd, # RIGHT SQUARE BRACKET, right-left
0x005e: 0x005e, # CIRCUMFLEX ACCENT, left-right
0x005e: 0x00de, # CIRCUMFLEX ACCENT, right-left
0x005f: 0x005f, # LOW LINE, left-right
0x005f: 0x00df, # LOW LINE, right-left
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET, left-right
0x007b: 0x00fb, # LEFT CURLY BRACKET, right-left
0x007c: 0x007c, # VERTICAL LINE, left-right
0x007c: 0x00fc, # VERTICAL LINE, right-left
0x007d: 0x007d, # RIGHT CURLY BRACKET, left-right
0x007d: 0x00fd, # RIGHT CURLY BRACKET, right-left
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # CONTROL CHARACTER
0x00a0: 0x0081, # NO-BREAK SPACE, right-left
0x00ab: 0x008c, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left
0x00bb: 0x0098, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left
0x00c4: 0x0080, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c7: 0x0082, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c9: 0x0083, # LATIN CAPITAL LETTER E WITH ACUTE
0x00d1: 0x0084, # LATIN CAPITAL LETTER N WITH TILDE
0x00d6: 0x0085, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x00dc: 0x0086, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00e0: 0x0088, # LATIN SMALL LETTER A WITH GRAVE
0x00e1: 0x0087, # LATIN SMALL LETTER A WITH ACUTE
0x00e2: 0x0089, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4: 0x008a, # LATIN SMALL LETTER A WITH DIAERESIS
0x00e7: 0x008d, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008f, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x008e, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0090, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb: 0x0091, # LATIN SMALL LETTER E WITH DIAERESIS
0x00ed: 0x0092, # LATIN SMALL LETTER I WITH ACUTE
0x00ee: 0x0094, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x00ef: 0x0095, # LATIN SMALL LETTER I WITH DIAERESIS
0x00f1: 0x0096, # LATIN SMALL LETTER N WITH TILDE
0x00f3: 0x0097, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0099, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6: 0x009a, # LATIN SMALL LETTER O WITH DIAERESIS
0x00f7: 0x009b, # DIVISION SIGN, right-left
0x00f9: 0x009d, # LATIN SMALL LETTER U WITH GRAVE
0x00fa: 0x009c, # LATIN SMALL LETTER U WITH ACUTE
0x00fb: 0x009e, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00fc: 0x009f, # LATIN SMALL LETTER U WITH DIAERESIS
0x060c: 0x00ac, # ARABIC COMMA
0x061b: 0x00bb, # ARABIC SEMICOLON
0x061f: 0x00bf, # ARABIC QUESTION MARK
0x0621: 0x00c1, # ARABIC LETTER HAMZA
0x0622: 0x00c2, # ARABIC LETTER ALEF WITH MADDA ABOVE
0x0623: 0x00c3, # ARABIC LETTER ALEF WITH HAMZA ABOVE
0x0624: 0x00c4, # ARABIC LETTER WAW WITH HAMZA ABOVE
0x0625: 0x00c5, # ARABIC LETTER ALEF WITH HAMZA BELOW
0x0626: 0x00c6, # ARABIC LETTER YEH WITH HAMZA ABOVE
0x0627: 0x00c7, # ARABIC LETTER ALEF
0x0628: 0x00c8, # ARABIC LETTER BEH
0x0629: 0x00c9, # ARABIC LETTER TEH MARBUTA
0x062a: 0x00ca, # ARABIC LETTER TEH
0x062b: 0x00cb, # ARABIC LETTER THEH
0x062c: 0x00cc, # ARABIC LETTER JEEM
0x062d: 0x00cd, # ARABIC LETTER HAH
0x062e: 0x00ce, # ARABIC LETTER KHAH
0x062f: 0x00cf, # ARABIC LETTER DAL
0x0630: 0x00d0, # ARABIC LETTER THAL
0x0631: 0x00d1, # ARABIC LETTER REH
0x0632: 0x00d2, # ARABIC LETTER ZAIN
0x0633: 0x00d3, # ARABIC LETTER SEEN
0x0634: 0x00d4, # ARABIC LETTER SHEEN
0x0635: 0x00d5, # ARABIC LETTER SAD
0x0636: 0x00d6, # ARABIC LETTER DAD
0x0637: 0x00d7, # ARABIC LETTER TAH
0x0638: 0x00d8, # ARABIC LETTER ZAH
0x0639: 0x00d9, # ARABIC LETTER AIN
0x063a: 0x00da, # ARABIC LETTER GHAIN
0x0640: 0x00e0, # ARABIC TATWEEL
0x0641: 0x00e1, # ARABIC LETTER FEH
0x0642: 0x00e2, # ARABIC LETTER QAF
0x0643: 0x00e3, # ARABIC LETTER KAF
0x0644: 0x00e4, # ARABIC LETTER LAM
0x0645: 0x00e5, # ARABIC LETTER MEEM
0x0646: 0x00e6, # ARABIC LETTER NOON
0x0647: 0x00e7, # ARABIC LETTER HEH
0x0648: 0x00e8, # ARABIC LETTER WAW
0x0649: 0x00e9, # ARABIC LETTER ALEF MAKSURA
0x064a: 0x00ea, # ARABIC LETTER YEH
0x064b: 0x00eb, # ARABIC FATHATAN
0x064c: 0x00ec, # ARABIC DAMMATAN
0x064d: 0x00ed, # ARABIC KASRATAN
0x064e: 0x00ee, # ARABIC FATHA
0x064f: 0x00ef, # ARABIC DAMMA
0x0650: 0x00f0, # ARABIC KASRA
0x0651: 0x00f1, # ARABIC SHADDA
0x0652: 0x00f2, # ARABIC SUKUN
0x0660: 0x00b0, # ARABIC-INDIC DIGIT ZERO, right-left (need override)
0x0661: 0x00b1, # ARABIC-INDIC DIGIT ONE, right-left (need override)
0x0662: 0x00b2, # ARABIC-INDIC DIGIT TWO, right-left (need override)
0x0663: 0x00b3, # ARABIC-INDIC DIGIT THREE, right-left (need override)
0x0664: 0x00b4, # ARABIC-INDIC DIGIT FOUR, right-left (need override)
0x0665: 0x00b5, # ARABIC-INDIC DIGIT FIVE, right-left (need override)
0x0666: 0x00b6, # ARABIC-INDIC DIGIT SIX, right-left (need override)
0x0667: 0x00b7, # ARABIC-INDIC DIGIT SEVEN, right-left (need override)
0x0668: 0x00b8, # ARABIC-INDIC DIGIT EIGHT, right-left (need override)
0x0669: 0x00b9, # ARABIC-INDIC DIGIT NINE, right-left (need override)
0x066a: 0x00a5, # ARABIC PERCENT SIGN
0x0679: 0x00f4, # ARABIC LETTER TTEH
0x067e: 0x00f3, # ARABIC LETTER PEH
0x0686: 0x00f5, # ARABIC LETTER TCHEH
0x0688: 0x00f9, # ARABIC LETTER DDAL
0x0691: 0x00fa, # ARABIC LETTER RREH
0x0698: 0x00fe, # ARABIC LETTER JEH
0x06a4: 0x00f7, # ARABIC LETTER VEH
0x06af: 0x00f8, # ARABIC LETTER GAF
0x06ba: 0x008b, # ARABIC LETTER NOON GHUNNA
0x06d2: 0x00ff, # ARABIC LETTER YEH BARREE
0x06d5: 0x00f6, # ARABIC LETTER AE
0x2026: 0x0093, # HORIZONTAL ELLIPSIS, right-left
0x274a: 0x00c0, # EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left
}
|
WillGuan105/django
|
tests/gis_tests/relatedapp/tests.py
|
from __future__ import unicode_literals
from django.contrib.gis.db.models import F, Collect, Count, Extent, Union
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature
from django.test.utils import override_settings
from django.utils import timezone
from ..utils import no_oracle
from .models import (
Article, Author, Book, City, DirectoryEntry, Event, Location, Parcel,
)
@skipUnlessDBFeature("gis_enabled")
class RelatedGeoModelTest(TestCase):
fixtures = ['initial']
def test02_select_related(self):
"Testing `select_related` on geographic models (see #7126)."
qs1 = City.objects.order_by('id')
qs2 = City.objects.order_by('id').select_related()
qs3 = City.objects.order_by('id').select_related('location')
# Reference data for what's in the fixtures.
cities = (
('Aurora', 'TX', -97.516111, 33.058333),
('Roswell', 'NM', -104.528056, 33.387222),
('Kecksburg', 'PA', -79.460734, 40.18476),
)
for qs in (qs1, qs2, qs3):
for ref, c in zip(cities, qs):
nm, st, lon, lat = ref
self.assertEqual(nm, c.name)
self.assertEqual(st, c.state)
self.assertEqual(Point(lon, lat), c.location.point)
@skipUnlessDBFeature("has_transform_method")
def test03_transform_related(self):
"Testing the `transform` GeoQuerySet method on related geographic models."
# All the transformations are to state plane coordinate systems using
# US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot).
tol = 0
def check_pnt(ref, pnt):
self.assertAlmostEqual(ref.x, pnt.x, tol)
self.assertAlmostEqual(ref.y, pnt.y, tol)
self.assertEqual(ref.srid, pnt.srid)
# Each city transformed to the SRID of their state plane coordinate system.
transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'),
('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'),
('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'),
)
for name, srid, wkt in transformed:
# Doing this implicitly sets `select_related` select the location.
# TODO: Fix why this breaks on Oracle.
qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point'))
check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point)
@skipUnlessDBFeature("supports_extent_aggr")
def test_related_extent_aggregate(self):
"Testing the `Extent` aggregate on related geographic models."
# This combines the Extent and Union aggregates into one query
aggs = City.objects.aggregate(Extent('location__point'))
# One for all locations, one that excludes New Mexico (Roswell).
all_extent = (-104.528056, 29.763374, -79.460734, 40.18476)
txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476)
e1 = City.objects.aggregate(Extent('location__point'))['location__point__extent']
e2 = City.objects.exclude(state='NM').aggregate(Extent('location__point'))['location__point__extent']
e3 = aggs['location__point__extent']
# The tolerance value is to four decimal places because of differences
# between the Oracle and PostGIS spatial backends on the extent calculation.
tol = 4
for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]:
for ref_val, e_val in zip(ref, e):
self.assertAlmostEqual(ref_val, e_val, tol)
@skipUnlessDBFeature("supports_extent_aggr")
def test_related_extent_annotate(self):
"""
Test annotation with Extent GeoAggregate.
"""
cities = City.objects.annotate(points_extent=Extent('location__point')).order_by('name')
tol = 4
self.assertAlmostEqual(
cities[0].points_extent,
(-97.516111, 33.058333, -97.516111, 33.058333),
tol
)
@skipUnlessDBFeature("has_unionagg_method")
def test_related_union_aggregate(self):
"Testing the `Union` aggregate on related geographic models."
# This combines the Extent and Union aggregates into one query
aggs = City.objects.aggregate(Union('location__point'))
# These are the points that are components of the aggregate geographic
# union that is returned. Each point # corresponds to City PK.
p1 = Point(-104.528056, 33.387222)
p2 = Point(-97.516111, 33.058333)
p3 = Point(-79.460734, 40.18476)
p4 = Point(-96.801611, 32.782057)
p5 = Point(-95.363151, 29.763374)
# The second union aggregate is for a union
# query that includes limiting information in the WHERE clause (in other
# words a `.filter()` precedes the call to `.aggregate(Union()`).
ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326)
ref_u2 = MultiPoint(p2, p3, srid=4326)
u1 = City.objects.aggregate(Union('location__point'))['location__point__union']
u2 = City.objects.exclude(
name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth'),
).aggregate(Union('location__point'))['location__point__union']
u3 = aggs['location__point__union']
self.assertEqual(type(u1), MultiPoint)
self.assertEqual(type(u3), MultiPoint)
# Ordering of points in the result of the union is not defined and
# implementation-dependent (DB backend, GEOS version)
self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1})
self.assertSetEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2})
self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3})
def test05_select_related_fk_to_subclass(self):
"Testing that calling select_related on a query over a model with an FK to a model subclass works"
# Regression test for #9752.
list(DirectoryEntry.objects.all().select_related())
def test06_f_expressions(self):
"Testing F() expressions on GeometryFields."
# Constructing a dummy parcel border and getting the City instance for
# assigning the FK.
b1 = GEOSGeometry(
'POLYGON((-97.501205 33.052520,-97.501205 33.052576,'
'-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))',
srid=4326
)
pcity = City.objects.get(name='Aurora')
# First parcel has incorrect center point that is equal to the City;
# it also has a second border that is different from the first as a
# 100ft buffer around the City.
c1 = pcity.location.point
c2 = c1.transform(2276, clone=True)
b2 = c2.buffer(100)
Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2)
# Now creating a second Parcel where the borders are the same, just
# in different coordinate systems. The center points are also the
# same (but in different coordinate systems), and this time they
# actually correspond to the centroid of the border.
c1 = b1.centroid
c2 = c1.transform(2276, clone=True)
Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1)
# Should return the second Parcel, which has the center within the
# border.
qs = Parcel.objects.filter(center1__within=F('border1'))
self.assertEqual(1, len(qs))
self.assertEqual('P2', qs[0].name)
if connection.features.supports_transform:
# This time center2 is in a different coordinate system and needs
# to be wrapped in transformation SQL.
qs = Parcel.objects.filter(center2__within=F('border1'))
self.assertEqual(1, len(qs))
self.assertEqual('P2', qs[0].name)
# Should return the first Parcel, which has the center point equal
# to the point in the City ForeignKey.
qs = Parcel.objects.filter(center1=F('city__location__point'))
self.assertEqual(1, len(qs))
self.assertEqual('P1', qs[0].name)
if connection.features.supports_transform:
# This time the city column should be wrapped in transformation SQL.
qs = Parcel.objects.filter(border2__contains=F('city__location__point'))
self.assertEqual(1, len(qs))
self.assertEqual('P1', qs[0].name)
def test07_values(self):
"Testing values() and values_list() and GeoQuerySets."
gqs = Location.objects.all()
gvqs = Location.objects.values()
gvlqs = Location.objects.values_list()
# Incrementing through each of the models, dictionaries, and tuples
# returned by the different types of GeoQuerySets.
for m, d, t in zip(gqs, gvqs, gvlqs):
# The values should be Geometry objects and not raw strings returned
# by the spatial database.
self.assertIsInstance(d['point'], Geometry)
self.assertIsInstance(t[1], Geometry)
self.assertEqual(m.point, d['point'])
self.assertEqual(m.point, t[1])
@override_settings(USE_TZ=True)
def test_07b_values(self):
"Testing values() and values_list() with aware datetime. See #21565."
Event.objects.create(name="foo", when=timezone.now())
list(Event.objects.values_list('when'))
def test08_defer_only(self):
"Testing defer() and only() on Geographic models."
qs = Location.objects.all()
def_qs = Location.objects.defer('point')
for loc, def_loc in zip(qs, def_qs):
self.assertEqual(loc.point, def_loc.point)
def test09_pk_relations(self):
"Ensuring correct primary key column is selected across relations. See #10757."
# The expected ID values -- notice the last two location IDs
# are out of order. Dallas and Houston have location IDs that differ
# from their PKs -- this is done to ensure that the related location
# ID column is selected instead of ID column for the city.
city_ids = (1, 2, 3, 4, 5)
loc_ids = (1, 2, 3, 5, 4)
ids_qs = City.objects.order_by('id').values('id', 'location__id')
for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids):
self.assertEqual(val_dict['id'], c_id)
self.assertEqual(val_dict['location__id'], l_id)
# TODO: fix on Oracle -- qs2 returns an empty result for an unknown reason
@no_oracle
def test10_combine(self):
"Testing the combination of two GeoQuerySets. See #10807."
buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1)
buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1)
qs1 = City.objects.filter(location__point__within=buf1)
qs2 = City.objects.filter(location__point__within=buf2)
combined = qs1 | qs2
names = [c.name for c in combined]
self.assertEqual(2, len(names))
self.assertIn('Aurora', names)
self.assertIn('Kecksburg', names)
# TODO: fix on Oracle -- get the following error because the SQL is ordered
# by a geometry object, which Oracle apparently doesn't like:
# ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
@no_oracle
def test12a_count(self):
"Testing `Count` aggregate use with the `GeoManager` on geo-fields."
# The City, 'Fort Worth' uses the same location as Dallas.
dallas = City.objects.get(name='Dallas')
# Count annotation should be 2 for the Dallas location now.
loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id)
self.assertEqual(2, loc.num_cities)
def test12b_count(self):
"Testing `Count` aggregate use with the `GeoManager` on non geo-fields. See #11087."
# Should only be one author (Trevor Paglen) returned by this query, and
# the annotation should have 3 for the number of books, see #11087.
# Also testing with a values(), see #11489.
qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1)
self.assertEqual(1, len(qs))
self.assertEqual(3, qs[0].num_books)
self.assertEqual(1, len(vqs))
self.assertEqual(3, vqs[0]['num_books'])
# TODO: fix on Oracle -- get the following error because the SQL is ordered
# by a geometry object, which Oracle apparently doesn't like:
# ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
@no_oracle
def test13c_count(self):
"Testing `Count` aggregate with `.values()`. See #15305."
qs = Location.objects.filter(id=5).annotate(num_cities=Count('city')).values('id', 'point', 'num_cities')
self.assertEqual(1, len(qs))
self.assertEqual(2, qs[0]['num_cities'])
self.assertIsInstance(qs[0]['point'], GEOSGeometry)
# TODO: The phantom model does appear on Oracle.
@no_oracle
def test13_select_related_null_fk(self):
"Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381."
Book.objects.create(title='Without Author')
b = Book.objects.select_related('author').get(title='Without Author')
# Should be `None`, and not a 'dummy' model.
self.assertIsNone(b.author)
@skipUnlessDBFeature("supports_collect_aggr")
def test_collect(self):
"""
Testing the `Collect` aggregate.
"""
# Reference query:
# SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
# "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
# WHERE "relatedapp_city"."state" = 'TX';
ref_geom = GEOSGeometry(
'MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,'
'-95.363151 29.763374,-96.801611 32.782057)'
)
coll = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect']
# Even though Dallas and Ft. Worth share same point, Collect doesn't
# consolidate -- that's why 4 points in MultiPoint.
self.assertEqual(4, len(coll))
self.assertTrue(ref_geom.equals(coll))
def test15_invalid_select_related(self):
"Testing doing select_related on the related name manager of a unique FK. See #13934."
qs = Article.objects.select_related('author__article')
# This triggers TypeError when `get_default_columns` has no `local_only`
# keyword. The TypeError is swallowed if QuerySet is actually
# evaluated as list generation swallows TypeError in CPython.
str(qs.query)
def test16_annotated_date_queryset(self):
"Ensure annotated date querysets work if spatial backend is used. See #14648."
birth_years = [dt.year for dt in
list(Author.objects.annotate(num_books=Count('books')).dates('dob', 'year'))]
birth_years.sort()
self.assertEqual([1950, 1974], birth_years)
# TODO: Related tests for KML, GML, and distance lookups.
|
jose36/plugin.video.live.ProyectoLuzDigital-
|
servers/adfly.py
|
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para adfly (acortador de url)
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core import scrapertools
from core import logger
from core import config
def get_long_url( short_url ):
logger.info("servers.adfly get_long_url(short_url='%s')" % short_url)
request_headers = []
request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; es-ES; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12"])
request_headers.append(["Referer","http://linkdecrypter.com"])
post=urllib.urlencode({"pro_links":short_url,"modo_links":"text","modo_recursivo":"on","link_cache":"on"})
url = "http://linkdecrypter.com/"
# Parche porque python no parece reconocer bien la cabecera phpsessid
body,response_headers = scrapertools.read_body_and_headers(url,post=post,headers=request_headers)
n = 1
while True:
for name,value in response_headers:
if name=="set-cookie":
logger.info("Set-Cookie: "+value)
cookie_name = scrapertools.get_match(value,'(.*?)\=.*?\;')
cookie_value = scrapertools.get_match(value,'.*?\=(.*?)\;')
request_headers.append(["Cookie",cookie_name+"="+cookie_value])
body,response_headers = scrapertools.read_body_and_headers(url,headers=request_headers)
logger.info("body="+body)
try:
location = scrapertools.get_match(body,'<textarea.*?class="caja_des">([^<]+)</textarea>')
logger.info("location="+location)
break
except:
n = n + 1
if n>3:
break
return location
def test():
location = get_long_url("http://85093635.linkbucks.com/")
ok = ("freakshare.com" in location)
#if ok:
# location = get_long_url("http://adf.ly/Fp6BF")
# ok = "http://vk.com/" in location
print "Funciona:",ok
return ok
|
diegoguimaraes/django
|
tests/reserved_names/models.py
|
"""
18. Using SQL reserved names
Need to use a reserved SQL name as a column name or table name? Need to include
a hyphen in a column or table name? No problem. Django quotes names
appropriately behind the scenes, so your database won't complain about
reserved-name usage.
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Thing(models.Model):
when = models.CharField(max_length=1, primary_key=True)
join = models.CharField(max_length=1)
like = models.CharField(max_length=1)
drop = models.CharField(max_length=1)
alter = models.CharField(max_length=1)
having = models.CharField(max_length=1)
where = models.DateField(max_length=1)
has_hyphen = models.CharField(max_length=1, db_column='has-hyphen')
class Meta:
db_table = 'select'
def __str__(self):
return self.when
|
837468220/python-for-android
|
python3-alpha/python3-src/Lib/test/test_codecs.py
|
from test import support
import unittest
import codecs
import locale
import sys, _testcapi, io
class Queue(object):
"""
queue: write bytes at one end, read bytes from the other end
"""
def __init__(self, buffer):
self._buffer = buffer
def write(self, chars):
self._buffer += chars
def read(self, size=-1):
if size<0:
s = self._buffer
self._buffer = self._buffer[:0] # make empty
return s
else:
s = self._buffer[:size]
self._buffer = self._buffer[size:]
return s
class MixInCheckStateHandling:
def check_state_handling_decode(self, encoding, u, s):
for i in range(len(s)+1):
d = codecs.getincrementaldecoder(encoding)()
part1 = d.decode(s[:i])
state = d.getstate()
self.assertIsInstance(state[1], int)
# Check that the condition stated in the documentation for
# IncrementalDecoder.getstate() holds
if not state[1]:
# reset decoder to the default state without anything buffered
d.setstate((state[0][:0], 0))
# Feeding the previous input may not produce any output
self.assertTrue(not d.decode(state[0]))
# The decoder must return to the same state
self.assertEqual(state, d.getstate())
# Create a new decoder and set it to the state
# we extracted from the old one
d = codecs.getincrementaldecoder(encoding)()
d.setstate(state)
part2 = d.decode(s[i:], True)
self.assertEqual(u, part1+part2)
def check_state_handling_encode(self, encoding, u, s):
for i in range(len(u)+1):
d = codecs.getincrementalencoder(encoding)()
part1 = d.encode(u[:i])
state = d.getstate()
d = codecs.getincrementalencoder(encoding)()
d.setstate(state)
part2 = d.encode(u[i:], True)
self.assertEqual(s, part1+part2)
class ReadTest(unittest.TestCase, MixInCheckStateHandling):
def check_partial(self, input, partialresults):
# get a StreamReader for the encoding and feed the bytestring version
# of input to the reader byte by byte. Read everything available from
# the StreamReader and check that the results equal the appropriate
# entries from partialresults.
q = Queue(b"")
r = codecs.getreader(self.encoding)(q)
result = ""
for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
q.write(bytes([c]))
result += r.read()
self.assertEqual(result, partialresult)
# check that there's nothing left in the buffers
self.assertEqual(r.read(), "")
self.assertEqual(r.bytebuffer, b"")
# do the check again, this time using a incremental decoder
d = codecs.getincrementaldecoder(self.encoding)()
result = ""
for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
result += d.decode(bytes([c]))
self.assertEqual(result, partialresult)
# check that there's nothing left in the buffers
self.assertEqual(d.decode(b"", True), "")
self.assertEqual(d.buffer, b"")
# Check whether the reset method works properly
d.reset()
result = ""
for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
result += d.decode(bytes([c]))
self.assertEqual(result, partialresult)
# check that there's nothing left in the buffers
self.assertEqual(d.decode(b"", True), "")
self.assertEqual(d.buffer, b"")
# check iterdecode()
encoded = input.encode(self.encoding)
self.assertEqual(
input,
"".join(codecs.iterdecode([bytes([c]) for c in encoded], self.encoding))
)
def test_readline(self):
def getreader(input):
stream = io.BytesIO(input.encode(self.encoding))
return codecs.getreader(self.encoding)(stream)
def readalllines(input, keepends=True, size=None):
reader = getreader(input)
lines = []
while True:
line = reader.readline(size=size, keepends=keepends)
if not line:
break
lines.append(line)
return "|".join(lines)
s = "foo\nbar\r\nbaz\rspam\u2028eggs"
sexpected = "foo\n|bar\r\n|baz\r|spam\u2028|eggs"
sexpectednoends = "foo|bar|baz|spam|eggs"
self.assertEqual(readalllines(s, True), sexpected)
self.assertEqual(readalllines(s, False), sexpectednoends)
self.assertEqual(readalllines(s, True, 10), sexpected)
self.assertEqual(readalllines(s, False, 10), sexpectednoends)
# Test long lines (multiple calls to read() in readline())
vw = []
vwo = []
for (i, lineend) in enumerate("\n \r\n \r \u2028".split()):
vw.append((i*200)*"\3042" + lineend)
vwo.append((i*200)*"\3042")
self.assertEqual(readalllines("".join(vw), True), "".join(vw))
self.assertEqual(readalllines("".join(vw), False),"".join(vwo))
# Test lines where the first read might end with \r, so the
# reader has to look ahead whether this is a lone \r or a \r\n
for size in range(80):
for lineend in "\n \r\n \r \u2028".split():
s = 10*(size*"a" + lineend + "xxx\n")
reader = getreader(s)
for i in range(10):
self.assertEqual(
reader.readline(keepends=True),
size*"a" + lineend,
)
reader = getreader(s)
for i in range(10):
self.assertEqual(
reader.readline(keepends=False),
size*"a",
)
def test_bug1175396(self):
s = [
'<%!--===================================================\r\n',
' BLOG index page: show recent articles,\r\n',
' today\'s articles, or articles of a specific date.\r\n',
'========================================================--%>\r\n',
'<%@inputencoding="ISO-8859-1"%>\r\n',
'<%@pagetemplate=TEMPLATE.y%>\r\n',
'<%@import=import frog.util, frog%>\r\n',
'<%@import=import frog.objects%>\r\n',
'<%@import=from frog.storageerrors import StorageError%>\r\n',
'<%\r\n',
'\r\n',
'import logging\r\n',
'log=logging.getLogger("Snakelets.logger")\r\n',
'\r\n',
'\r\n',
'user=self.SessionCtx.user\r\n',
'storageEngine=self.SessionCtx.storageEngine\r\n',
'\r\n',
'\r\n',
'def readArticlesFromDate(date, count=None):\r\n',
' entryids=storageEngine.listBlogEntries(date)\r\n',
' entryids.reverse() # descending\r\n',
' if count:\r\n',
' entryids=entryids[:count]\r\n',
' try:\r\n',
' return [ frog.objects.BlogEntry.load(storageEngine, date, Id) for Id in entryids ]\r\n',
' except StorageError,x:\r\n',
' log.error("Error loading articles: "+str(x))\r\n',
' self.abort("cannot load articles")\r\n',
'\r\n',
'showdate=None\r\n',
'\r\n',
'arg=self.Request.getArg()\r\n',
'if arg=="today":\r\n',
' #-------------------- TODAY\'S ARTICLES\r\n',
' self.write("<h2>Today\'s articles</h2>")\r\n',
' showdate = frog.util.isodatestr() \r\n',
' entries = readArticlesFromDate(showdate)\r\n',
'elif arg=="active":\r\n',
' #-------------------- ACTIVE ARTICLES redirect\r\n',
' self.Yredirect("active.y")\r\n',
'elif arg=="login":\r\n',
' #-------------------- LOGIN PAGE redirect\r\n',
' self.Yredirect("login.y")\r\n',
'elif arg=="date":\r\n',
' #-------------------- ARTICLES OF A SPECIFIC DATE\r\n',
' showdate = self.Request.getParameter("date")\r\n',
' self.write("<h2>Articles written on %s</h2>"% frog.util.mediumdatestr(showdate))\r\n',
' entries = readArticlesFromDate(showdate)\r\n',
'else:\r\n',
' #-------------------- RECENT ARTICLES\r\n',
' self.write("<h2>Recent articles</h2>")\r\n',
' dates=storageEngine.listBlogEntryDates()\r\n',
' if dates:\r\n',
' entries=[]\r\n',
' SHOWAMOUNT=10\r\n',
' for showdate in dates:\r\n',
' entries.extend( readArticlesFromDate(showdate, SHOWAMOUNT-len(entries)) )\r\n',
' if len(entries)>=SHOWAMOUNT:\r\n',
' break\r\n',
' \r\n',
]
stream = io.BytesIO("".join(s).encode(self.encoding))
reader = codecs.getreader(self.encoding)(stream)
for (i, line) in enumerate(reader):
self.assertEqual(line, s[i])
def test_readlinequeue(self):
q = Queue(b"")
writer = codecs.getwriter(self.encoding)(q)
reader = codecs.getreader(self.encoding)(q)
# No lineends
writer.write("foo\r")
self.assertEqual(reader.readline(keepends=False), "foo")
writer.write("\nbar\r")
self.assertEqual(reader.readline(keepends=False), "")
self.assertEqual(reader.readline(keepends=False), "bar")
writer.write("baz")
self.assertEqual(reader.readline(keepends=False), "baz")
self.assertEqual(reader.readline(keepends=False), "")
# Lineends
writer.write("foo\r")
self.assertEqual(reader.readline(keepends=True), "foo\r")
writer.write("\nbar\r")
self.assertEqual(reader.readline(keepends=True), "\n")
self.assertEqual(reader.readline(keepends=True), "bar\r")
writer.write("baz")
self.assertEqual(reader.readline(keepends=True), "baz")
self.assertEqual(reader.readline(keepends=True), "")
writer.write("foo\r\n")
self.assertEqual(reader.readline(keepends=True), "foo\r\n")
def test_bug1098990_a(self):
s1 = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\r\n"
s2 = "offending line: ladfj askldfj klasdj fskla dfzaskdj fasklfj laskd fjasklfzzzzaa%whereisthis!!!\r\n"
s3 = "next line.\r\n"
s = (s1+s2+s3).encode(self.encoding)
stream = io.BytesIO(s)
reader = codecs.getreader(self.encoding)(stream)
self.assertEqual(reader.readline(), s1)
self.assertEqual(reader.readline(), s2)
self.assertEqual(reader.readline(), s3)
self.assertEqual(reader.readline(), "")
def test_bug1098990_b(self):
s1 = "aaaaaaaaaaaaaaaaaaaaaaaa\r\n"
s2 = "bbbbbbbbbbbbbbbbbbbbbbbb\r\n"
s3 = "stillokay:bbbbxx\r\n"
s4 = "broken!!!!badbad\r\n"
s5 = "againokay.\r\n"
s = (s1+s2+s3+s4+s5).encode(self.encoding)
stream = io.BytesIO(s)
reader = codecs.getreader(self.encoding)(stream)
self.assertEqual(reader.readline(), s1)
self.assertEqual(reader.readline(), s2)
self.assertEqual(reader.readline(), s3)
self.assertEqual(reader.readline(), s4)
self.assertEqual(reader.readline(), s5)
self.assertEqual(reader.readline(), "")
class UTF32Test(ReadTest):
encoding = "utf-32"
spamle = (b'\xff\xfe\x00\x00'
b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00'
b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00')
spambe = (b'\x00\x00\xfe\xff'
b'\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m'
b'\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m')
def test_only_one_bom(self):
_,_,reader,writer = codecs.lookup(self.encoding)
# encode some stream
s = io.BytesIO()
f = writer(s)
f.write("spam")
f.write("spam")
d = s.getvalue()
# check whether there is exactly one BOM in it
self.assertTrue(d == self.spamle or d == self.spambe)
# try to read it back
s = io.BytesIO(d)
f = reader(s)
self.assertEqual(f.read(), "spamspam")
def test_badbom(self):
s = io.BytesIO(4*b"\xff")
f = codecs.getreader(self.encoding)(s)
self.assertRaises(UnicodeError, f.read)
s = io.BytesIO(8*b"\xff")
f = codecs.getreader(self.encoding)(s)
self.assertRaises(UnicodeError, f.read)
def test_partial(self):
self.check_partial(
"\x00\xff\u0100\uffff",
[
"", # first byte of BOM read
"", # second byte of BOM read
"", # third byte of BOM read
"", # fourth byte of BOM read => byteorder known
"",
"",
"",
"\x00",
"\x00",
"\x00",
"\x00",
"\x00\xff",
"\x00\xff",
"\x00\xff",
"\x00\xff",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100\uffff",
]
)
def test_handlers(self):
self.assertEqual(('\ufffd', 1),
codecs.utf_32_decode(b'\x01', 'replace', True))
self.assertEqual(('', 1),
codecs.utf_32_decode(b'\x01', 'ignore', True))
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_32_decode,
b"\xff", "strict", True)
def test_decoder_state(self):
self.check_state_handling_decode(self.encoding,
"spamspam", self.spamle)
self.check_state_handling_decode(self.encoding,
"spamspam", self.spambe)
def test_issue8941(self):
# Issue #8941: insufficient result allocation when decoding into
# surrogate pairs on UCS-2 builds.
encoded_le = b'\xff\xfe\x00\x00' + b'\x00\x00\x01\x00' * 1024
self.assertEqual('\U00010000' * 1024,
codecs.utf_32_decode(encoded_le)[0])
encoded_be = b'\x00\x00\xfe\xff' + b'\x00\x01\x00\x00' * 1024
self.assertEqual('\U00010000' * 1024,
codecs.utf_32_decode(encoded_be)[0])
class UTF32LETest(ReadTest):
encoding = "utf-32-le"
def test_partial(self):
self.check_partial(
"\x00\xff\u0100\uffff",
[
"",
"",
"",
"\x00",
"\x00",
"\x00",
"\x00",
"\x00\xff",
"\x00\xff",
"\x00\xff",
"\x00\xff",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100\uffff",
]
)
def test_simple(self):
self.assertEqual("\U00010203".encode(self.encoding), b"\x03\x02\x01\x00")
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_32_le_decode,
b"\xff", "strict", True)
def test_issue8941(self):
# Issue #8941: insufficient result allocation when decoding into
# surrogate pairs on UCS-2 builds.
encoded = b'\x00\x00\x01\x00' * 1024
self.assertEqual('\U00010000' * 1024,
codecs.utf_32_le_decode(encoded)[0])
class UTF32BETest(ReadTest):
encoding = "utf-32-be"
def test_partial(self):
self.check_partial(
"\x00\xff\u0100\uffff",
[
"",
"",
"",
"\x00",
"\x00",
"\x00",
"\x00",
"\x00\xff",
"\x00\xff",
"\x00\xff",
"\x00\xff",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100\uffff",
]
)
def test_simple(self):
self.assertEqual("\U00010203".encode(self.encoding), b"\x00\x01\x02\x03")
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_32_be_decode,
b"\xff", "strict", True)
def test_issue8941(self):
# Issue #8941: insufficient result allocation when decoding into
# surrogate pairs on UCS-2 builds.
encoded = b'\x00\x01\x00\x00' * 1024
self.assertEqual('\U00010000' * 1024,
codecs.utf_32_be_decode(encoded)[0])
class UTF16Test(ReadTest):
encoding = "utf-16"
spamle = b'\xff\xfes\x00p\x00a\x00m\x00s\x00p\x00a\x00m\x00'
spambe = b'\xfe\xff\x00s\x00p\x00a\x00m\x00s\x00p\x00a\x00m'
def test_only_one_bom(self):
_,_,reader,writer = codecs.lookup(self.encoding)
# encode some stream
s = io.BytesIO()
f = writer(s)
f.write("spam")
f.write("spam")
d = s.getvalue()
# check whether there is exactly one BOM in it
self.assertTrue(d == self.spamle or d == self.spambe)
# try to read it back
s = io.BytesIO(d)
f = reader(s)
self.assertEqual(f.read(), "spamspam")
def test_badbom(self):
s = io.BytesIO(b"\xff\xff")
f = codecs.getreader(self.encoding)(s)
self.assertRaises(UnicodeError, f.read)
s = io.BytesIO(b"\xff\xff\xff\xff")
f = codecs.getreader(self.encoding)(s)
self.assertRaises(UnicodeError, f.read)
def test_partial(self):
self.check_partial(
"\x00\xff\u0100\uffff",
[
"", # first byte of BOM read
"", # second byte of BOM read => byteorder known
"",
"\x00",
"\x00",
"\x00\xff",
"\x00\xff",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100\uffff",
]
)
def test_handlers(self):
self.assertEqual(('\ufffd', 1),
codecs.utf_16_decode(b'\x01', 'replace', True))
self.assertEqual(('', 1),
codecs.utf_16_decode(b'\x01', 'ignore', True))
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode,
b"\xff", "strict", True)
def test_decoder_state(self):
self.check_state_handling_decode(self.encoding,
"spamspam", self.spamle)
self.check_state_handling_decode(self.encoding,
"spamspam", self.spambe)
def test_bug691291(self):
# Files are always opened in binary mode, even if no binary mode was
# specified. This means that no automatic conversion of '\n' is done
# on reading and writing.
s1 = 'Hello\r\nworld\r\n'
s = s1.encode(self.encoding)
self.addCleanup(support.unlink, support.TESTFN)
with open(support.TESTFN, 'wb') as fp:
fp.write(s)
with codecs.open(support.TESTFN, 'U', encoding=self.encoding) as reader:
self.assertEqual(reader.read(), s1)
class UTF16LETest(ReadTest):
encoding = "utf-16-le"
def test_partial(self):
self.check_partial(
"\x00\xff\u0100\uffff",
[
"",
"\x00",
"\x00",
"\x00\xff",
"\x00\xff",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100\uffff",
]
)
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode,
b"\xff", "strict", True)
def test_nonbmp(self):
self.assertEqual("\U00010203".encode(self.encoding),
b'\x00\xd8\x03\xde')
self.assertEqual(b'\x00\xd8\x03\xde'.decode(self.encoding),
"\U00010203")
class UTF16BETest(ReadTest):
encoding = "utf-16-be"
def test_partial(self):
self.check_partial(
"\x00\xff\u0100\uffff",
[
"",
"\x00",
"\x00",
"\x00\xff",
"\x00\xff",
"\x00\xff\u0100",
"\x00\xff\u0100",
"\x00\xff\u0100\uffff",
]
)
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode,
b"\xff", "strict", True)
def test_nonbmp(self):
self.assertEqual("\U00010203".encode(self.encoding),
b'\xd8\x00\xde\x03')
self.assertEqual(b'\xd8\x00\xde\x03'.decode(self.encoding),
"\U00010203")
class UTF8Test(ReadTest):
encoding = "utf-8"
def test_partial(self):
self.check_partial(
"\x00\xff\u07ff\u0800\uffff",
[
"\x00",
"\x00",
"\x00\xff",
"\x00\xff",
"\x00\xff\u07ff",
"\x00\xff\u07ff",
"\x00\xff\u07ff",
"\x00\xff\u07ff\u0800",
"\x00\xff\u07ff\u0800",
"\x00\xff\u07ff\u0800",
"\x00\xff\u07ff\u0800\uffff",
]
)
def test_decoder_state(self):
u = "\x00\x7f\x80\xff\u0100\u07ff\u0800\uffff\U0010ffff"
self.check_state_handling_decode(self.encoding,
u, u.encode(self.encoding))
def test_lone_surrogates(self):
self.assertRaises(UnicodeEncodeError, "\ud800".encode, "utf-8")
self.assertRaises(UnicodeDecodeError, b"\xed\xa0\x80".decode, "utf-8")
self.assertEqual("[\uDC80]".encode("utf-8", "backslashreplace"),
b'[\\udc80]')
self.assertEqual("[\uDC80]".encode("utf-8", "xmlcharrefreplace"),
b'[�]')
self.assertEqual("[\uDC80]".encode("utf-8", "surrogateescape"),
b'[\x80]')
self.assertEqual("[\uDC80]".encode("utf-8", "ignore"),
b'[]')
self.assertEqual("[\uDC80]".encode("utf-8", "replace"),
b'[?]')
def test_surrogatepass_handler(self):
self.assertEqual("abc\ud800def".encode("utf-8", "surrogatepass"),
b"abc\xed\xa0\x80def")
self.assertEqual(b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass"),
"abc\ud800def")
self.assertTrue(codecs.lookup_error("surrogatepass"))
class UTF7Test(ReadTest):
encoding = "utf-7"
def test_partial(self):
self.check_partial(
"a+-b",
[
"a",
"a",
"a+",
"a+-",
"a+-b",
]
)
class UTF16ExTest(unittest.TestCase):
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_ex_decode, b"\xff", "strict", 0, True)
def test_bad_args(self):
self.assertRaises(TypeError, codecs.utf_16_ex_decode)
class ReadBufferTest(unittest.TestCase):
def test_array(self):
import array
self.assertEqual(
codecs.readbuffer_encode(array.array("b", b"spam")),
(b"spam", 4)
)
def test_empty(self):
self.assertEqual(codecs.readbuffer_encode(""), (b"", 0))
def test_bad_args(self):
self.assertRaises(TypeError, codecs.readbuffer_encode)
self.assertRaises(TypeError, codecs.readbuffer_encode, 42)
class UTF8SigTest(ReadTest):
encoding = "utf-8-sig"
def test_partial(self):
self.check_partial(
"\ufeff\x00\xff\u07ff\u0800\uffff",
[
"",
"",
"", # First BOM has been read and skipped
"",
"",
"\ufeff", # Second BOM has been read and emitted
"\ufeff\x00", # "\x00" read and emitted
"\ufeff\x00", # First byte of encoded "\xff" read
"\ufeff\x00\xff", # Second byte of encoded "\xff" read
"\ufeff\x00\xff", # First byte of encoded "\u07ff" read
"\ufeff\x00\xff\u07ff", # Second byte of encoded "\u07ff" read
"\ufeff\x00\xff\u07ff",
"\ufeff\x00\xff\u07ff",
"\ufeff\x00\xff\u07ff\u0800",
"\ufeff\x00\xff\u07ff\u0800",
"\ufeff\x00\xff\u07ff\u0800",
"\ufeff\x00\xff\u07ff\u0800\uffff",
]
)
def test_bug1601501(self):
# SF bug #1601501: check that the codec works with a buffer
self.assertEqual(str(b"\xef\xbb\xbf", "utf-8-sig"), "")
def test_bom(self):
d = codecs.getincrementaldecoder("utf-8-sig")()
s = "spam"
self.assertEqual(d.decode(s.encode("utf-8-sig")), s)
def test_stream_bom(self):
unistring = "ABC\u00A1\u2200XYZ"
bytestring = codecs.BOM_UTF8 + b"ABC\xC2\xA1\xE2\x88\x80XYZ"
reader = codecs.getreader("utf-8-sig")
for sizehint in [None] + list(range(1, 11)) + \
[64, 128, 256, 512, 1024]:
istream = reader(io.BytesIO(bytestring))
ostream = io.StringIO()
while 1:
if sizehint is not None:
data = istream.read(sizehint)
else:
data = istream.read()
if not data:
break
ostream.write(data)
got = ostream.getvalue()
self.assertEqual(got, unistring)
def test_stream_bare(self):
unistring = "ABC\u00A1\u2200XYZ"
bytestring = b"ABC\xC2\xA1\xE2\x88\x80XYZ"
reader = codecs.getreader("utf-8-sig")
for sizehint in [None] + list(range(1, 11)) + \
[64, 128, 256, 512, 1024]:
istream = reader(io.BytesIO(bytestring))
ostream = io.StringIO()
while 1:
if sizehint is not None:
data = istream.read(sizehint)
else:
data = istream.read()
if not data:
break
ostream.write(data)
got = ostream.getvalue()
self.assertEqual(got, unistring)
class EscapeDecodeTest(unittest.TestCase):
def test_empty(self):
self.assertEqual(codecs.escape_decode(""), ("", 0))
class RecodingTest(unittest.TestCase):
def test_recoding(self):
f = io.BytesIO()
f2 = codecs.EncodedFile(f, "unicode_internal", "utf-8")
f2.write("a")
f2.close()
# Python used to crash on this at exit because of a refcount
# bug in _codecsmodule.c
# From RFC 3492
punycode_testcases = [
# A Arabic (Egyptian):
("\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644"
"\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F",
b"egbpdaj6bu4bxfgehfvwxn"),
# B Chinese (simplified):
("\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587",
b"ihqwcrb4cv8a8dqg056pqjye"),
# C Chinese (traditional):
("\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587",
b"ihqwctvzc91f659drss3x8bo0yb"),
# D Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky
("\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074"
"\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D"
"\u0065\u0073\u006B\u0079",
b"Proprostnemluvesky-uyb24dma41a"),
# E Hebrew:
("\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8"
"\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2"
"\u05D1\u05E8\u05D9\u05EA",
b"4dbcagdahymbxekheh6e0a7fei0b"),
# F Hindi (Devanagari):
("\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D"
"\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939"
"\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947"
"\u0939\u0948\u0902",
b"i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd"),
#(G) Japanese (kanji and hiragana):
("\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092"
"\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B",
b"n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa"),
# (H) Korean (Hangul syllables):
("\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774"
"\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74"
"\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C",
b"989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j"
b"psd879ccm6fea98c"),
# (I) Russian (Cyrillic):
("\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E"
"\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440"
"\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A"
"\u0438",
b"b1abfaaepdrnnbgefbaDotcwatmq2g4l"),
# (J) Spanish: Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol
("\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070"
"\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070"
"\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061"
"\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070"
"\u0061\u00F1\u006F\u006C",
b"PorqunopuedensimplementehablarenEspaol-fmd56a"),
# (K) Vietnamese:
# T<adotbelow>isaoh<odotbelow>kh<ocirc>ngth<ecirchookabove>ch\
# <ihookabove>n<oacute>iti<ecircacute>ngVi<ecircdotbelow>t
("\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B"
"\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068"
"\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067"
"\u0056\u0069\u1EC7\u0074",
b"TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g"),
#(L) 3<nen>B<gumi><kinpachi><sensei>
("\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F",
b"3B-ww4c5e180e575a65lsy2b"),
# (M) <amuro><namie>-with-SUPER-MONKEYS
("\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074"
"\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D"
"\u004F\u004E\u004B\u0045\u0059\u0053",
b"-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n"),
# (N) Hello-Another-Way-<sorezore><no><basho>
("\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F"
"\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D"
"\u305D\u308C\u305E\u308C\u306E\u5834\u6240",
b"Hello-Another-Way--fc4qua05auwb3674vfr0b"),
# (O) <hitotsu><yane><no><shita>2
("\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032",
b"2-u9tlzr9756bt3uc0v"),
# (P) Maji<de>Koi<suru>5<byou><mae>
("\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059"
"\u308B\u0035\u79D2\u524D",
b"MajiKoi5-783gue6qz075azm5e"),
# (Q) <pafii>de<runba>
("\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0",
b"de-jg4avhby1noc0d"),
# (R) <sono><supiido><de>
("\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067",
b"d9juau41awczczp"),
# (S) -> $1.00 <-
("\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020"
"\u003C\u002D",
b"-> $1.00 <--")
]
for i in punycode_testcases:
if len(i)!=2:
print(repr(i))
class PunycodeTest(unittest.TestCase):
def test_encode(self):
for uni, puny in punycode_testcases:
# Need to convert both strings to lower case, since
# some of the extended encodings use upper case, but our
# code produces only lower case. Converting just puny to
# lower is also insufficient, since some of the input characters
# are upper case.
self.assertEqual(
str(uni.encode("punycode"), "ascii").lower(),
str(puny, "ascii").lower()
)
def test_decode(self):
for uni, puny in punycode_testcases:
self.assertEqual(uni, puny.decode("punycode"))
puny = puny.decode("ascii").encode("ascii")
self.assertEqual(uni, puny.decode("punycode"))
class UnicodeInternalTest(unittest.TestCase):
def test_bug1251300(self):
# Decoding with unicode_internal used to not correctly handle "code
# points" above 0x10ffff on UCS-4 builds.
if sys.maxunicode > 0xffff:
ok = [
(b"\x00\x10\xff\xff", "\U0010ffff"),
(b"\x00\x00\x01\x01", "\U00000101"),
(b"", ""),
]
not_ok = [
b"\x7f\xff\xff\xff",
b"\x80\x00\x00\x00",
b"\x81\x00\x00\x00",
b"\x00",
b"\x00\x00\x00\x00\x00",
]
for internal, uni in ok:
if sys.byteorder == "little":
internal = bytes(reversed(internal))
self.assertEqual(uni, internal.decode("unicode_internal"))
for internal in not_ok:
if sys.byteorder == "little":
internal = bytes(reversed(internal))
self.assertRaises(UnicodeDecodeError, internal.decode,
"unicode_internal")
def test_decode_error_attributes(self):
if sys.maxunicode > 0xffff:
try:
b"\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal")
except UnicodeDecodeError as ex:
self.assertEqual("unicode_internal", ex.encoding)
self.assertEqual(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object)
self.assertEqual(4, ex.start)
self.assertEqual(8, ex.end)
else:
self.fail()
def test_decode_callback(self):
if sys.maxunicode > 0xffff:
codecs.register_error("UnicodeInternalTest", codecs.ignore_errors)
decoder = codecs.getdecoder("unicode_internal")
ab = "ab".encode("unicode_internal").decode()
ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]),
"ascii"),
"UnicodeInternalTest")
self.assertEqual(("ab", 12), ignored)
def test_encode_length(self):
# Issue 3739
encoder = codecs.getencoder("unicode_internal")
self.assertEqual(encoder("a")[1], 1)
self.assertEqual(encoder("\xe9\u0142")[1], 2)
self.assertEqual(codecs.escape_encode(br'\x00')[1], 4)
# From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html
nameprep_tests = [
# 3.1 Map to nothing.
(b'foo\xc2\xad\xcd\x8f\xe1\xa0\x86\xe1\xa0\x8bbar'
b'\xe2\x80\x8b\xe2\x81\xa0baz\xef\xb8\x80\xef\xb8\x88\xef'
b'\xb8\x8f\xef\xbb\xbf',
b'foobarbaz'),
# 3.2 Case folding ASCII U+0043 U+0041 U+0046 U+0045.
(b'CAFE',
b'cafe'),
# 3.3 Case folding 8bit U+00DF (german sharp s).
# The original test case is bogus; it says \xc3\xdf
(b'\xc3\x9f',
b'ss'),
# 3.4 Case folding U+0130 (turkish capital I with dot).
(b'\xc4\xb0',
b'i\xcc\x87'),
# 3.5 Case folding multibyte U+0143 U+037A.
(b'\xc5\x83\xcd\xba',
b'\xc5\x84 \xce\xb9'),
# 3.6 Case folding U+2121 U+33C6 U+1D7BB.
# XXX: skip this as it fails in UCS-2 mode
#('\xe2\x84\xa1\xe3\x8f\x86\xf0\x9d\x9e\xbb',
# 'telc\xe2\x88\x95kg\xcf\x83'),
(None, None),
# 3.7 Normalization of U+006a U+030c U+00A0 U+00AA.
(b'j\xcc\x8c\xc2\xa0\xc2\xaa',
b'\xc7\xb0 a'),
# 3.8 Case folding U+1FB7 and normalization.
(b'\xe1\xbe\xb7',
b'\xe1\xbe\xb6\xce\xb9'),
# 3.9 Self-reverting case folding U+01F0 and normalization.
# The original test case is bogus, it says `\xc7\xf0'
(b'\xc7\xb0',
b'\xc7\xb0'),
# 3.10 Self-reverting case folding U+0390 and normalization.
(b'\xce\x90',
b'\xce\x90'),
# 3.11 Self-reverting case folding U+03B0 and normalization.
(b'\xce\xb0',
b'\xce\xb0'),
# 3.12 Self-reverting case folding U+1E96 and normalization.
(b'\xe1\xba\x96',
b'\xe1\xba\x96'),
# 3.13 Self-reverting case folding U+1F56 and normalization.
(b'\xe1\xbd\x96',
b'\xe1\xbd\x96'),
# 3.14 ASCII space character U+0020.
(b' ',
b' '),
# 3.15 Non-ASCII 8bit space character U+00A0.
(b'\xc2\xa0',
b' '),
# 3.16 Non-ASCII multibyte space character U+1680.
(b'\xe1\x9a\x80',
None),
# 3.17 Non-ASCII multibyte space character U+2000.
(b'\xe2\x80\x80',
b' '),
# 3.18 Zero Width Space U+200b.
(b'\xe2\x80\x8b',
b''),
# 3.19 Non-ASCII multibyte space character U+3000.
(b'\xe3\x80\x80',
b' '),
# 3.20 ASCII control characters U+0010 U+007F.
(b'\x10\x7f',
b'\x10\x7f'),
# 3.21 Non-ASCII 8bit control character U+0085.
(b'\xc2\x85',
None),
# 3.22 Non-ASCII multibyte control character U+180E.
(b'\xe1\xa0\x8e',
None),
# 3.23 Zero Width No-Break Space U+FEFF.
(b'\xef\xbb\xbf',
b''),
# 3.24 Non-ASCII control character U+1D175.
(b'\xf0\x9d\x85\xb5',
None),
# 3.25 Plane 0 private use character U+F123.
(b'\xef\x84\xa3',
None),
# 3.26 Plane 15 private use character U+F1234.
(b'\xf3\xb1\x88\xb4',
None),
# 3.27 Plane 16 private use character U+10F234.
(b'\xf4\x8f\x88\xb4',
None),
# 3.28 Non-character code point U+8FFFE.
(b'\xf2\x8f\xbf\xbe',
None),
# 3.29 Non-character code point U+10FFFF.
(b'\xf4\x8f\xbf\xbf',
None),
# 3.30 Surrogate code U+DF42.
(b'\xed\xbd\x82',
None),
# 3.31 Non-plain text character U+FFFD.
(b'\xef\xbf\xbd',
None),
# 3.32 Ideographic description character U+2FF5.
(b'\xe2\xbf\xb5',
None),
# 3.33 Display property character U+0341.
(b'\xcd\x81',
b'\xcc\x81'),
# 3.34 Left-to-right mark U+200E.
(b'\xe2\x80\x8e',
None),
# 3.35 Deprecated U+202A.
(b'\xe2\x80\xaa',
None),
# 3.36 Language tagging character U+E0001.
(b'\xf3\xa0\x80\x81',
None),
# 3.37 Language tagging character U+E0042.
(b'\xf3\xa0\x81\x82',
None),
# 3.38 Bidi: RandALCat character U+05BE and LCat characters.
(b'foo\xd6\xbebar',
None),
# 3.39 Bidi: RandALCat character U+FD50 and LCat characters.
(b'foo\xef\xb5\x90bar',
None),
# 3.40 Bidi: RandALCat character U+FB38 and LCat characters.
(b'foo\xef\xb9\xb6bar',
b'foo \xd9\x8ebar'),
# 3.41 Bidi: RandALCat without trailing RandALCat U+0627 U+0031.
(b'\xd8\xa71',
None),
# 3.42 Bidi: RandALCat character U+0627 U+0031 U+0628.
(b'\xd8\xa71\xd8\xa8',
b'\xd8\xa71\xd8\xa8'),
# 3.43 Unassigned code point U+E0002.
# Skip this test as we allow unassigned
#(b'\xf3\xa0\x80\x82',
# None),
(None, None),
# 3.44 Larger test (shrinking).
# Original test case reads \xc3\xdf
(b'X\xc2\xad\xc3\x9f\xc4\xb0\xe2\x84\xa1j\xcc\x8c\xc2\xa0\xc2'
b'\xaa\xce\xb0\xe2\x80\x80',
b'xssi\xcc\x87tel\xc7\xb0 a\xce\xb0 '),
# 3.45 Larger test (expanding).
# Original test case reads \xc3\x9f
(b'X\xc3\x9f\xe3\x8c\x96\xc4\xb0\xe2\x84\xa1\xe2\x92\x9f\xe3\x8c'
b'\x80',
b'xss\xe3\x82\xad\xe3\x83\xad\xe3\x83\xa1\xe3\x83\xbc\xe3'
b'\x83\x88\xe3\x83\xabi\xcc\x87tel\x28d\x29\xe3\x82'
b'\xa2\xe3\x83\x91\xe3\x83\xbc\xe3\x83\x88')
]
class NameprepTest(unittest.TestCase):
def test_nameprep(self):
from encodings.idna import nameprep
for pos, (orig, prepped) in enumerate(nameprep_tests):
if orig is None:
# Skipped
continue
# The Unicode strings are given in UTF-8
orig = str(orig, "utf-8", "surrogatepass")
if prepped is None:
# Input contains prohibited characters
self.assertRaises(UnicodeError, nameprep, orig)
else:
prepped = str(prepped, "utf-8", "surrogatepass")
try:
self.assertEqual(nameprep(orig), prepped)
except Exception as e:
raise support.TestFailed("Test 3.%d: %s" % (pos+1, str(e)))
class IDNACodecTest(unittest.TestCase):
def test_builtin_decode(self):
self.assertEqual(str(b"python.org", "idna"), "python.org")
self.assertEqual(str(b"python.org.", "idna"), "python.org.")
self.assertEqual(str(b"xn--pythn-mua.org", "idna"), "pyth\xf6n.org")
self.assertEqual(str(b"xn--pythn-mua.org.", "idna"), "pyth\xf6n.org.")
def test_builtin_encode(self):
self.assertEqual("python.org".encode("idna"), b"python.org")
self.assertEqual("python.org.".encode("idna"), b"python.org.")
self.assertEqual("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org")
self.assertEqual("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.")
def test_stream(self):
r = codecs.getreader("idna")(io.BytesIO(b"abc"))
r.read(3)
self.assertEqual(r.read(), "")
def test_incremental_decode(self):
self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"python.org"), "idna")),
"python.org"
)
self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"python.org."), "idna")),
"python.org."
)
self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
"pyth\xf6n.org."
)
self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
"pyth\xf6n.org."
)
decoder = codecs.getincrementaldecoder("idna")()
self.assertEqual(decoder.decode(b"xn--xam", ), "")
self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
self.assertEqual(decoder.decode(b"rg"), "")
self.assertEqual(decoder.decode(b"", True), "org")
decoder.reset()
self.assertEqual(decoder.decode(b"xn--xam", ), "")
self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
self.assertEqual(decoder.decode(b"rg."), "org.")
self.assertEqual(decoder.decode(b"", True), "")
def test_incremental_encode(self):
self.assertEqual(
b"".join(codecs.iterencode("python.org", "idna")),
b"python.org"
)
self.assertEqual(
b"".join(codecs.iterencode("python.org.", "idna")),
b"python.org."
)
self.assertEqual(
b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
b"xn--pythn-mua.org."
)
self.assertEqual(
b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
b"xn--pythn-mua.org."
)
encoder = codecs.getincrementalencoder("idna")()
self.assertEqual(encoder.encode("\xe4x"), b"")
self.assertEqual(encoder.encode("ample.org"), b"xn--xample-9ta.")
self.assertEqual(encoder.encode("", True), b"org")
encoder.reset()
self.assertEqual(encoder.encode("\xe4x"), b"")
self.assertEqual(encoder.encode("ample.org."), b"xn--xample-9ta.org.")
self.assertEqual(encoder.encode("", True), b"")
class CodecsModuleTest(unittest.TestCase):
def test_decode(self):
self.assertEqual(codecs.decode(b'\xe4\xf6\xfc', 'latin-1'),
'\xe4\xf6\xfc')
self.assertRaises(TypeError, codecs.decode)
self.assertEqual(codecs.decode(b'abc'), 'abc')
self.assertRaises(UnicodeDecodeError, codecs.decode, b'\xff', 'ascii')
def test_encode(self):
self.assertEqual(codecs.encode('\xe4\xf6\xfc', 'latin-1'),
b'\xe4\xf6\xfc')
self.assertRaises(TypeError, codecs.encode)
self.assertRaises(LookupError, codecs.encode, "foo", "__spam__")
self.assertEqual(codecs.encode('abc'), b'abc')
self.assertRaises(UnicodeEncodeError, codecs.encode, '\xffff', 'ascii')
def test_register(self):
self.assertRaises(TypeError, codecs.register)
self.assertRaises(TypeError, codecs.register, 42)
def test_lookup(self):
self.assertRaises(TypeError, codecs.lookup)
self.assertRaises(LookupError, codecs.lookup, "__spam__")
self.assertRaises(LookupError, codecs.lookup, " ")
def test_getencoder(self):
self.assertRaises(TypeError, codecs.getencoder)
self.assertRaises(LookupError, codecs.getencoder, "__spam__")
def test_getdecoder(self):
self.assertRaises(TypeError, codecs.getdecoder)
self.assertRaises(LookupError, codecs.getdecoder, "__spam__")
def test_getreader(self):
self.assertRaises(TypeError, codecs.getreader)
self.assertRaises(LookupError, codecs.getreader, "__spam__")
def test_getwriter(self):
self.assertRaises(TypeError, codecs.getwriter)
self.assertRaises(LookupError, codecs.getwriter, "__spam__")
def test_lookup_issue1813(self):
# Issue #1813: under Turkish locales, lookup of some codecs failed
# because 'I' is lowercased as "ı" (dotless i)
oldlocale = locale.setlocale(locale.LC_CTYPE)
self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
try:
locale.setlocale(locale.LC_CTYPE, 'tr_TR')
except locale.Error:
# Unsupported locale on this system
self.skipTest('test needs Turkish locale')
c = codecs.lookup('ASCII')
self.assertEqual(c.name, 'ascii')
class StreamReaderTest(unittest.TestCase):
def setUp(self):
self.reader = codecs.getreader('utf-8')
self.stream = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80')
def test_readlines(self):
f = self.reader(self.stream)
self.assertEqual(f.readlines(), ['\ud55c\n', '\uae00'])
class EncodedFileTest(unittest.TestCase):
def test_basic(self):
f = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80')
ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8')
self.assertEqual(ef.read(), b'\\\xd5\n\x00\x00\xae')
f = io.BytesIO()
ef = codecs.EncodedFile(f, 'utf-8', 'latin1')
ef.write(b'\xc3\xbc')
self.assertEqual(f.getvalue(), b'\xfc')
all_unicode_encodings = [
"ascii",
"big5",
"big5hkscs",
"charmap",
"cp037",
"cp1006",
"cp1026",
"cp1140",
"cp1250",
"cp1251",
"cp1252",
"cp1253",
"cp1254",
"cp1255",
"cp1256",
"cp1257",
"cp1258",
"cp424",
"cp437",
"cp500",
"cp720",
"cp737",
"cp775",
"cp850",
"cp852",
"cp855",
"cp856",
"cp857",
"cp858",
"cp860",
"cp861",
"cp862",
"cp863",
"cp864",
"cp865",
"cp866",
"cp869",
"cp874",
"cp875",
"cp932",
"cp949",
"cp950",
"euc_jis_2004",
"euc_jisx0213",
"euc_jp",
"euc_kr",
"gb18030",
"gb2312",
"gbk",
"hp_roman8",
"hz",
"idna",
"iso2022_jp",
"iso2022_jp_1",
"iso2022_jp_2",
"iso2022_jp_2004",
"iso2022_jp_3",
"iso2022_jp_ext",
"iso2022_kr",
"iso8859_1",
"iso8859_10",
"iso8859_11",
"iso8859_13",
"iso8859_14",
"iso8859_15",
"iso8859_16",
"iso8859_2",
"iso8859_3",
"iso8859_4",
"iso8859_5",
"iso8859_6",
"iso8859_7",
"iso8859_8",
"iso8859_9",
"johab",
"koi8_r",
"koi8_u",
"latin_1",
"mac_cyrillic",
"mac_greek",
"mac_iceland",
"mac_latin2",
"mac_roman",
"mac_turkish",
"palmos",
"ptcp154",
"punycode",
"raw_unicode_escape",
"shift_jis",
"shift_jis_2004",
"shift_jisx0213",
"tis_620",
"unicode_escape",
"unicode_internal",
"utf_16",
"utf_16_be",
"utf_16_le",
"utf_7",
"utf_8",
]
if hasattr(codecs, "mbcs_encode"):
all_unicode_encodings.append("mbcs")
# The following encoding is not tested, because it's not supposed
# to work:
# "undefined"
# The following encodings don't work in stateful mode
broken_unicode_with_streams = [
"punycode",
"unicode_internal"
]
broken_incremental_coders = broken_unicode_with_streams + [
"idna",
]
class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
def test_basics(self):
s = "abc123" # all codecs should be able to encode these
for encoding in all_unicode_encodings:
name = codecs.lookup(encoding).name
if encoding.endswith("_codec"):
name += "_codec"
elif encoding == "latin_1":
name = "latin_1"
self.assertEqual(encoding.replace("_", "-"), name.replace("_", "-"))
(b, size) = codecs.getencoder(encoding)(s)
self.assertEqual(size, len(s), "%r != %r (encoding=%r)" % (size, len(s), encoding))
(chars, size) = codecs.getdecoder(encoding)(b)
self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding))
if encoding not in broken_unicode_with_streams:
# check stream reader/writer
q = Queue(b"")
writer = codecs.getwriter(encoding)(q)
encodedresult = b""
for c in s:
writer.write(c)
chunk = q.read()
self.assertTrue(type(chunk) is bytes, type(chunk))
encodedresult += chunk
q = Queue(b"")
reader = codecs.getreader(encoding)(q)
decodedresult = ""
for c in encodedresult:
q.write(bytes([c]))
decodedresult += reader.read()
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
if encoding not in broken_incremental_coders:
# check incremental decoder/encoder (fetched via the Python
# and C API) and iterencode()/iterdecode()
try:
encoder = codecs.getincrementalencoder(encoding)()
cencoder = _testcapi.codec_incrementalencoder(encoding)
except LookupError: # no IncrementalEncoder
pass
else:
# check incremental decoder/encoder
encodedresult = b""
for c in s:
encodedresult += encoder.encode(c)
encodedresult += encoder.encode("", True)
decoder = codecs.getincrementaldecoder(encoding)()
decodedresult = ""
for c in encodedresult:
decodedresult += decoder.decode(bytes([c]))
decodedresult += decoder.decode(b"", True)
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
# check C API
encodedresult = b""
for c in s:
encodedresult += cencoder.encode(c)
encodedresult += cencoder.encode("", True)
cdecoder = _testcapi.codec_incrementaldecoder(encoding)
decodedresult = ""
for c in encodedresult:
decodedresult += cdecoder.decode(bytes([c]))
decodedresult += cdecoder.decode(b"", True)
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
# check iterencode()/iterdecode()
result = "".join(codecs.iterdecode(codecs.iterencode(s, encoding), encoding))
self.assertEqual(result, s, "%r != %r (encoding=%r)" % (result, s, encoding))
# check iterencode()/iterdecode() with empty string
result = "".join(codecs.iterdecode(codecs.iterencode("", encoding), encoding))
self.assertEqual(result, "")
if encoding not in ("idna", "mbcs"):
# check incremental decoder/encoder with errors argument
try:
encoder = codecs.getincrementalencoder(encoding)("ignore")
cencoder = _testcapi.codec_incrementalencoder(encoding, "ignore")
except LookupError: # no IncrementalEncoder
pass
else:
encodedresult = b"".join(encoder.encode(c) for c in s)
decoder = codecs.getincrementaldecoder(encoding)("ignore")
decodedresult = "".join(decoder.decode(bytes([c])) for c in encodedresult)
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
encodedresult = b"".join(cencoder.encode(c) for c in s)
cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore")
decodedresult = "".join(cdecoder.decode(bytes([c])) for c in encodedresult)
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
def test_seek(self):
# all codecs should be able to encode these
s = "%s\n%s\n" % (100*"abc123", 100*"def456")
for encoding in all_unicode_encodings:
if encoding == "idna": # FIXME: See SF bug #1163178
continue
if encoding in broken_unicode_with_streams:
continue
reader = codecs.getreader(encoding)(io.BytesIO(s.encode(encoding)))
for t in range(5):
# Test that calling seek resets the internal codec state and buffers
reader.seek(0, 0)
data = reader.read()
self.assertEqual(s, data)
def test_bad_decode_args(self):
for encoding in all_unicode_encodings:
decoder = codecs.getdecoder(encoding)
self.assertRaises(TypeError, decoder)
if encoding not in ("idna", "punycode"):
self.assertRaises(TypeError, decoder, 42)
def test_bad_encode_args(self):
for encoding in all_unicode_encodings:
encoder = codecs.getencoder(encoding)
self.assertRaises(TypeError, encoder)
def test_encoding_map_type_initialized(self):
from encodings import cp1140
# This used to crash, we are only verifying there's no crash.
table_type = type(cp1140.encoding_table)
self.assertEqual(table_type, table_type)
def test_decoder_state(self):
# Check that getstate() and setstate() handle the state properly
u = "abc123"
for encoding in all_unicode_encodings:
if encoding not in broken_incremental_coders:
self.check_state_handling_decode(encoding, u, u.encode(encoding))
self.check_state_handling_encode(encoding, u, u.encode(encoding))
class CharmapTest(unittest.TestCase):
def test_decode_with_string_map(self):
self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "strict", "abc"),
("abc", 3)
)
self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab"),
("ab\ufffd", 3)
)
self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab\ufffe"),
("ab\ufffd", 3)
)
self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab"),
("ab", 3)
)
self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab\ufffe"),
("ab", 3)
)
allbytes = bytes(range(256))
self.assertEqual(
codecs.charmap_decode(allbytes, "ignore", ""),
("", len(allbytes))
)
class WithStmtTest(unittest.TestCase):
def test_encodedfile(self):
f = io.BytesIO(b"\xc3\xbc")
with codecs.EncodedFile(f, "latin-1", "utf-8") as ef:
self.assertEqual(ef.read(), b"\xfc")
def test_streamreaderwriter(self):
f = io.BytesIO(b"\xc3\xbc")
info = codecs.lookup("utf-8")
with codecs.StreamReaderWriter(f, info.streamreader,
info.streamwriter, 'strict') as srw:
self.assertEqual(srw.read(), "\xfc")
class TypesTest(unittest.TestCase):
def test_decode_unicode(self):
# Most decoders don't accept unicode input
decoders = [
codecs.utf_7_decode,
codecs.utf_8_decode,
codecs.utf_16_le_decode,
codecs.utf_16_be_decode,
codecs.utf_16_ex_decode,
codecs.utf_32_decode,
codecs.utf_32_le_decode,
codecs.utf_32_be_decode,
codecs.utf_32_ex_decode,
codecs.latin_1_decode,
codecs.ascii_decode,
codecs.charmap_decode,
]
if hasattr(codecs, "mbcs_decode"):
decoders.append(codecs.mbcs_decode)
for decoder in decoders:
self.assertRaises(TypeError, decoder, "xxx")
def test_unicode_escape(self):
# Escape-decoding an unicode string is supported ang gives the same
# result as decoding the equivalent ASCII bytes string.
self.assertEqual(codecs.unicode_escape_decode(r"\u1234"), ("\u1234", 6))
self.assertEqual(codecs.unicode_escape_decode(br"\u1234"), ("\u1234", 6))
self.assertEqual(codecs.raw_unicode_escape_decode(r"\u1234"), ("\u1234", 6))
self.assertEqual(codecs.raw_unicode_escape_decode(br"\u1234"), ("\u1234", 6))
class SurrogateEscapeTest(unittest.TestCase):
def test_utf8(self):
# Bad byte
self.assertEqual(b"foo\x80bar".decode("utf-8", "surrogateescape"),
"foo\udc80bar")
self.assertEqual("foo\udc80bar".encode("utf-8", "surrogateescape"),
b"foo\x80bar")
# bad-utf-8 encoded surrogate
self.assertEqual(b"\xed\xb0\x80".decode("utf-8", "surrogateescape"),
"\udced\udcb0\udc80")
self.assertEqual("\udced\udcb0\udc80".encode("utf-8", "surrogateescape"),
b"\xed\xb0\x80")
def test_ascii(self):
# bad byte
self.assertEqual(b"foo\x80bar".decode("ascii", "surrogateescape"),
"foo\udc80bar")
self.assertEqual("foo\udc80bar".encode("ascii", "surrogateescape"),
b"foo\x80bar")
def test_charmap(self):
# bad byte: \xa5 is unmapped in iso-8859-3
self.assertEqual(b"foo\xa5bar".decode("iso-8859-3", "surrogateescape"),
"foo\udca5bar")
self.assertEqual("foo\udca5bar".encode("iso-8859-3", "surrogateescape"),
b"foo\xa5bar")
def test_latin1(self):
# Issue6373
self.assertEqual("\udce4\udceb\udcef\udcf6\udcfc".encode("latin1", "surrogateescape"),
b"\xe4\xeb\xef\xf6\xfc")
class BomTest(unittest.TestCase):
def test_seek0(self):
data = "1234567890"
tests = ("utf-16",
"utf-16-le",
"utf-16-be",
"utf-32",
"utf-32-le",
"utf-32-be")
self.addCleanup(support.unlink, support.TESTFN)
for encoding in tests:
# Check if the BOM is written only once
with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
f.write(data)
f.write(data)
f.seek(0)
self.assertEqual(f.read(), data * 2)
f.seek(0)
self.assertEqual(f.read(), data * 2)
# Check that the BOM is written after a seek(0)
with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
f.write(data[0])
self.assertNotEqual(f.tell(), 0)
f.seek(0)
f.write(data)
f.seek(0)
self.assertEqual(f.read(), data)
# (StreamWriter) Check that the BOM is written after a seek(0)
with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
f.writer.write(data[0])
self.assertNotEqual(f.writer.tell(), 0)
f.writer.seek(0)
f.writer.write(data)
f.seek(0)
self.assertEqual(f.read(), data)
# Check that the BOM is not written after a seek() at a position
# different than the start
with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
f.write(data)
f.seek(f.tell())
f.write(data)
f.seek(0)
self.assertEqual(f.read(), data * 2)
# (StreamWriter) Check that the BOM is not written after a seek()
# at a position different than the start
with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
f.writer.write(data)
f.writer.seek(f.writer.tell())
f.writer.write(data)
f.seek(0)
self.assertEqual(f.read(), data * 2)
bytes_transform_encodings = [
"base64_codec",
"uu_codec",
"quopri_codec",
"hex_codec",
]
try:
import zlib
except ImportError:
pass
else:
bytes_transform_encodings.append("zlib_codec")
try:
import bz2
except ImportError:
pass
else:
bytes_transform_encodings.append("bz2_codec")
class TransformCodecTest(unittest.TestCase):
def test_basics(self):
binput = bytes(range(256))
for encoding in bytes_transform_encodings:
# generic codecs interface
(o, size) = codecs.getencoder(encoding)(binput)
self.assertEqual(size, len(binput))
(i, size) = codecs.getdecoder(encoding)(o)
self.assertEqual(size, len(o))
self.assertEqual(i, binput)
def test_read(self):
for encoding in bytes_transform_encodings:
sin = codecs.encode(b"\x80", encoding)
reader = codecs.getreader(encoding)(io.BytesIO(sin))
sout = reader.read()
self.assertEqual(sout, b"\x80")
def test_readline(self):
for encoding in bytes_transform_encodings:
if encoding in ['uu_codec', 'zlib_codec']:
continue
sin = codecs.encode(b"\x80", encoding)
reader = codecs.getreader(encoding)(io.BytesIO(sin))
sout = reader.readline()
self.assertEqual(sout, b"\x80")
def test_main():
support.run_unittest(
UTF32Test,
UTF32LETest,
UTF32BETest,
UTF16Test,
UTF16LETest,
UTF16BETest,
UTF8Test,
UTF8SigTest,
UTF7Test,
UTF16ExTest,
ReadBufferTest,
RecodingTest,
PunycodeTest,
UnicodeInternalTest,
NameprepTest,
IDNACodecTest,
CodecsModuleTest,
StreamReaderTest,
EncodedFileTest,
BasicUnicodeTest,
CharmapTest,
WithStmtTest,
TypesTest,
SurrogateEscapeTest,
BomTest,
TransformCodecTest,
)
if __name__ == "__main__":
test_main()
|
nuclearsandwich/autokey
|
src/lib/qtui/dialogs.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Chris Dekter
#
# 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 logging, sys, os, re
#from PyKDE4.kdeui import KApplication, KXmlGuiWindow, KStandardAction, KIcon, KTextEdit, KAction, KStandardShortcut
from PyKDE4.kdeui import *
from PyKDE4.kdecore import i18n
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt, QRegExp
__all__ = ["validate", "EMPTY_FIELD_REGEX", "AbbrSettingsDialog", "HotkeySettingsDialog", "WindowFilterSettingsDialog", "RecordDialog"]
import abbrsettings, hotkeysettings, windowfiltersettings, recorddialog, detectdialog
from autokey import model, iomediator
WORD_CHAR_OPTIONS = {
"All non-word" : model.DEFAULT_WORDCHAR_REGEX,
"Space and Enter" : r"[^ \n]",
"Tab" : r"[^\t]"
}
WORD_CHAR_OPTIONS_ORDERED = ["All non-word", "Space and Enter", "Tab"]
EMPTY_FIELD_REGEX = re.compile(r"^ *$", re.UNICODE)
def validate(expression, message, widget, parent):
if not expression:
KMessageBox.error(parent, message)
if widget is not None:
widget.setFocus()
return expression
class AbbrListItem(QListWidgetItem):
def __init__(self, text):
QListWidgetItem.__init__(self, text)
self.setFlags(self.flags() | Qt.ItemFlags(Qt.ItemIsEditable))
def setData(self, role, value):
if value.toString() == "":
self.listWidget().itemChanged.emit(self)
else:
QListWidgetItem.setData(self, role, value)
class AbbrSettings(QWidget, abbrsettings.Ui_Form):
def __init__(self, parent):
QWidget.__init__(self, parent)
abbrsettings.Ui_Form.__init__(self)
self.setupUi(self)
for item in WORD_CHAR_OPTIONS_ORDERED:
self.wordCharCombo.addItem(item)
self.addButton.setIcon(KIcon("list-add"))
self.removeButton.setIcon(KIcon("list-remove"))
def on_addButton_pressed(self):
item = AbbrListItem("")
self.abbrListWidget.addItem(item)
self.abbrListWidget.editItem(item)
self.removeButton.setEnabled(True)
def on_removeButton_pressed(self):
item = self.abbrListWidget.takeItem(self.abbrListWidget.currentRow())
if self.abbrListWidget.count() == 0:
self.removeButton.setEnabled(False)
def on_abbrListWidget_itemChanged(self, item):
if EMPTY_FIELD_REGEX.match(item.text()):
row = self.abbrListWidget.row(item)
self.abbrListWidget.takeItem(row)
del item
if self.abbrListWidget.count() == 0:
self.removeButton.setEnabled(False)
def on_abbrListWidget_itemDoubleClicked(self, item):
self.abbrListWidget.editItem(item)
def on_ignoreCaseCheckbox_stateChanged(self, state):
if not self.ignoreCaseCheckbox.isChecked():
self.matchCaseCheckbox.setChecked(False)
def on_matchCaseCheckbox_stateChanged(self, state):
if self.matchCaseCheckbox.isChecked():
self.ignoreCaseCheckbox.setChecked(True)
def on_immediateCheckbox_stateChanged(self, state):
if self.immediateCheckbox.isChecked():
self.omitTriggerCheckbox.setChecked(False)
self.omitTriggerCheckbox.setEnabled(False)
self.wordCharCombo.setEnabled(False)
else:
self.omitTriggerCheckbox.setEnabled(True)
self.wordCharCombo.setEnabled(True)
class AbbrSettingsDialog(KDialog):
def __init__(self, parent):
KDialog.__init__(self, parent)
self.widget = AbbrSettings(self)
self.setMainWidget(self.widget)
self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel)))
self.setPlainCaption(i18n("Set Abbreviations"))
self.setModal(True)
#self.connect(self, SIGNAL("okClicked()"), self.on_okClicked)
def load(self, item):
self.targetItem = item
self.widget.abbrListWidget.clear()
if model.TriggerMode.ABBREVIATION in item.modes:
for abbr in item.abbreviations:
self.widget.abbrListWidget.addItem(AbbrListItem(abbr))
self.widget.removeButton.setEnabled(True)
self.widget.abbrListWidget.setCurrentRow(0)
else:
self.widget.removeButton.setEnabled(False)
self.widget.removeTypedCheckbox.setChecked(item.backspace)
self.__resetWordCharCombo()
wordCharRegex = item.get_word_chars()
if wordCharRegex in WORD_CHAR_OPTIONS.values():
# Default wordchar regex used
for desc, regex in WORD_CHAR_OPTIONS.iteritems():
if item.get_word_chars() == regex:
self.widget.wordCharCombo.setCurrentIndex(WORD_CHAR_OPTIONS_ORDERED.index(desc))
break
else:
# Custom wordchar regex used
self.widget.wordCharCombo.addItem(model.extract_wordchars(wordCharRegex))
self.widget.wordCharCombo.setCurrentIndex(len(WORD_CHAR_OPTIONS))
if isinstance(item, model.Folder):
self.widget.omitTriggerCheckbox.setVisible(False)
else:
self.widget.omitTriggerCheckbox.setVisible(True)
self.widget.omitTriggerCheckbox.setChecked(item.omitTrigger)
if isinstance(item, model.Phrase):
self.widget.matchCaseCheckbox.setVisible(True)
self.widget.matchCaseCheckbox.setChecked(item.matchCase)
else:
self.widget.matchCaseCheckbox.setVisible(False)
self.widget.ignoreCaseCheckbox.setChecked(item.ignoreCase)
self.widget.triggerInsideCheckbox.setChecked(item.triggerInside)
self.widget.immediateCheckbox.setChecked(item.immediate)
def save(self, item):
item.modes.append(model.TriggerMode.ABBREVIATION)
item.clear_abbreviations()
item.abbreviations = self.get_abbrs()
item.backspace = self.widget.removeTypedCheckbox.isChecked()
option = unicode(self.widget.wordCharCombo.currentText())
if option in WORD_CHAR_OPTIONS:
item.set_word_chars(WORD_CHAR_OPTIONS[option])
else:
item.set_word_chars(model.make_wordchar_re(option))
if not isinstance(item, model.Folder):
item.omitTrigger = self.widget.omitTriggerCheckbox.isChecked()
if isinstance(item, model.Phrase):
item.matchCase = self.widget.matchCaseCheckbox.isChecked()
item.ignoreCase = self.widget.ignoreCaseCheckbox.isChecked()
item.triggerInside = self.widget.triggerInsideCheckbox.isChecked()
item.immediate = self.widget.immediateCheckbox.isChecked()
def reset(self):
self.widget.removeButton.setEnabled(False)
self.widget.abbrListWidget.clear()
self.__resetWordCharCombo()
self.widget.omitTriggerCheckbox.setChecked(False)
self.widget.removeTypedCheckbox.setChecked(True)
self.widget.matchCaseCheckbox.setChecked(False)
self.widget.ignoreCaseCheckbox.setChecked(False)
self.widget.triggerInsideCheckbox.setChecked(False)
self.widget.immediateCheckbox.setChecked(False)
def __resetWordCharCombo(self):
self.widget.wordCharCombo.clear()
for item in WORD_CHAR_OPTIONS_ORDERED:
self.widget.wordCharCombo.addItem(item)
self.widget.wordCharCombo.setCurrentIndex(0)
def get_abbrs(self):
ret = []
for i in range(self.widget.abbrListWidget.count()):
text = self.widget.abbrListWidget.item(i).text()
ret.append(unicode(text))
return ret
def get_abbrs_readable(self):
abbrs = self.get_abbrs()
if len(abbrs) == 1:
return abbrs[0]
else:
return "[%s]" % ','.join(abbrs)
def reset_focus(self):
self.widget.addButton.setFocus()
def __valid(self):
if not validate(len(self.get_abbrs()) > 0, i18n("You must specify at least one abbreviation"),
self.widget.addButton, self): return False
return True
def slotButtonClicked(self, button):
if button == KDialog.Ok:
if self.__valid():
KDialog.slotButtonClicked(self, button)
else:
self.load(self.targetItem)
KDialog.slotButtonClicked(self, button)
class HotkeySettings(QWidget, hotkeysettings.Ui_Form):
def __init__(self, parent):
QWidget.__init__(self, parent)
hotkeysettings.Ui_Form.__init__(self)
self.setupUi(self)
# ---- Signal handlers
def on_setButton_pressed(self):
self.setButton.setEnabled(False)
self.keyLabel.setText(i18n("Press a key or combination..."))
self.grabber = iomediator.KeyGrabber(self.parentWidget())
self.grabber.start()
class HotkeySettingsDialog(KDialog):
KEY_MAP = {
' ' : "<space>",
}
REVERSE_KEY_MAP = {}
for key, value in KEY_MAP.iteritems():
REVERSE_KEY_MAP[value] = key
def __init__(self, parent):
KDialog.__init__(self, parent)
self.widget = HotkeySettings(self)
self.setMainWidget(self.widget)
self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel)))
self.setPlainCaption(i18n("Set Hotkey"))
self.setModal(True)
self.key = None
def load(self, item):
self.targetItem = item
self.widget.setButton.setEnabled(True)
if model.TriggerMode.HOTKEY in item.modes:
self.widget.controlButton.setChecked(iomediator.Key.CONTROL in item.modifiers)
self.widget.altButton.setChecked(iomediator.Key.ALT in item.modifiers)
self.widget.shiftButton.setChecked(iomediator.Key.SHIFT in item.modifiers)
self.widget.superButton.setChecked(iomediator.Key.SUPER in item.modifiers)
self.widget.hyperButton.setChecked(iomediator.Key.HYPER in item.modifiers)
self.widget.metaButton.setChecked(iomediator.Key.META in item.modifiers)
key = item.hotKey
if key in self.KEY_MAP:
keyText = self.KEY_MAP[key]
else:
keyText = key
self._setKeyLabel(keyText)
self.key = keyText
else:
self.reset()
def save(self, item):
item.modes.append(model.TriggerMode.HOTKEY)
# Build modifier list
modifiers = self.build_modifiers()
keyText = self.key
if keyText in self.REVERSE_KEY_MAP:
key = self.REVERSE_KEY_MAP[keyText]
else:
key = keyText
assert key != None, "Attempt to set hotkey with no key"
item.set_hotkey(modifiers, key)
def reset(self):
self.widget.controlButton.setChecked(False)
self.widget.altButton.setChecked(False)
self.widget.shiftButton.setChecked(False)
self.widget.superButton.setChecked(False)
self.widget.hyperButton.setChecked(False)
self.widget.metaButton.setChecked(False)
self._setKeyLabel(i18n("(None)"))
self.key = None
self.widget.setButton.setEnabled(True)
def set_key(self, key, modifiers=[]):
if self.KEY_MAP.has_key(key):
key = self.KEY_MAP[key]
self._setKeyLabel(key)
self.key = key
self.widget.controlButton.setChecked(iomediator.Key.CONTROL in modifiers)
self.widget.altButton.setChecked(iomediator.Key.ALT in modifiers)
self.widget.shiftButton.setChecked(iomediator.Key.SHIFT in modifiers)
self.widget.superButton.setChecked(iomediator.Key.SUPER in modifiers)
self.widget.hyperButton.setChecked(iomediator.Key.HYPER in modifiers)
self.widget.metaButton.setChecked(iomediator.Key.META in modifiers)
self.widget.setButton.setEnabled(True)
def cancel_grab(self):
self.widget.setButton.setEnabled(True)
self._setKeyLabel(self.key)
def build_modifiers(self):
modifiers = []
if self.widget.controlButton.isChecked():
modifiers.append(iomediator.Key.CONTROL)
if self.widget.altButton.isChecked():
modifiers.append(iomediator.Key.ALT)
if self.widget.shiftButton.isChecked():
modifiers.append(iomediator.Key.SHIFT)
if self.widget.superButton.isChecked():
modifiers.append(iomediator.Key.SUPER)
if self.widget.hyperButton.isChecked():
modifiers.append(iomediator.Key.HYPER)
if self.widget.metaButton.isChecked():
modifiers.append(iomediator.Key.META)
modifiers.sort()
return modifiers
def slotButtonClicked(self, button):
if button == KDialog.Ok:
if self.__valid():
KDialog.slotButtonClicked(self, button)
else:
self.load(self.targetItem)
KDialog.slotButtonClicked(self, button)
def _setKeyLabel(self, key):
self.widget.keyLabel.setText(i18n("Key: ") + key)
def __valid(self):
if not validate(self.key is not None, i18n("You must specify a key for the hotkey."),
None, self): return False
return True
class GlobalHotkeyDialog(HotkeySettingsDialog):
def load(self, item):
self.targetItem = item
if item.enabled:
self.widget.controlButton.setChecked(iomediator.Key.CONTROL in item.modifiers)
self.widget.altButton.setChecked(iomediator.Key.ALT in item.modifiers)
self.widget.shiftButton.setChecked(iomediator.Key.SHIFT in item.modifiers)
self.widget.superButton.setChecked(iomediator.Key.SUPER in item.modifiers)
self.widget.hyperButton.setChecked(iomediator.Key.HYPER in item.modifiers)
self.widget.metaButton.setChecked(iomediator.Key.META in item.modifiers)
key = item.hotKey
if key in self.KEY_MAP:
keyText = self.KEY_MAP[key]
else:
keyText = key
self._setKeyLabel(keyText)
self.key = keyText
else:
self.reset()
def save(self, item):
# Build modifier list
modifiers = self.build_modifiers()
keyText = self.key
if keyText in self.REVERSE_KEY_MAP:
key = self.REVERSE_KEY_MAP[keyText]
else:
key = keyText
assert key != None, "Attempt to set hotkey with no key"
item.set_hotkey(modifiers, key)
class WindowFilterSettings(QWidget, windowfiltersettings.Ui_Form):
def __init__(self, parent):
QWidget.__init__(self, parent)
windowfiltersettings.Ui_Form.__init__(self)
self.setupUi(self)
m = QFontMetrics(QApplication.font())
self.triggerRegexLineEdit.setMinimumWidth(m.width("windowclass.WindowClass"))
# ---- Signal handlers
def on_detectButton_pressed(self):
self.detectButton.setEnabled(False)
self.grabber = iomediator.WindowGrabber(self.parentWidget())
self.grabber.start()
class WindowFilterSettingsDialog(KDialog):
def __init__(self, parent):
KDialog.__init__(self, parent)
self.widget = WindowFilterSettings(self)
self.setMainWidget(self.widget)
self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel)))
self.setPlainCaption(i18n("Set Window Filter"))
self.setModal(True)
def load(self, item):
self.targetItem = item
if not isinstance(item, model.Folder):
self.widget.recursiveCheckBox.hide()
else:
self.widget.recursiveCheckBox.show()
if not item.has_filter():
self.reset()
else:
self.widget.triggerRegexLineEdit.setText(item.get_filter_regex())
self.widget.recursiveCheckBox.setChecked(item.isRecursive)
def save(self, item):
item.set_window_titles(self.get_filter_text())
item.set_filter_recursive(self.get_is_recursive())
def get_is_recursive(self):
return self.widget.recursiveCheckBox.isChecked()
def reset(self):
self.widget.triggerRegexLineEdit.setText("")
self.widget.recursiveCheckBox.setChecked(False)
def reset_focus(self):
self.widget.triggerRegexLineEdit.setFocus()
def get_filter_text(self):
return unicode(self.widget.triggerRegexLineEdit.text())
def receive_window_info(self, info):
self.parentWidget().topLevelWidget().app.exec_in_main(self.__receiveWindowInfo, info)
def __receiveWindowInfo(self, info):
dlg = DetectDialog(self)
dlg.populate(info)
dlg.exec_()
if dlg.result() == QDialog.Accepted:
self.widget.triggerRegexLineEdit.setText(dlg.get_choice())
self.widget.detectButton.setEnabled(True)
# --- event handlers ---
def slotButtonClicked(self, button):
if button == KDialog.Cancel:
self.load(self.targetItem)
KDialog.slotButtonClicked(self, button)
class DetectSettings(QWidget, detectdialog.Ui_Form):
def __init__(self, parent):
QWidget.__init__(self, parent)
detectdialog.Ui_Form.__init__(self)
self.setupUi(self)
self.kbuttongroup.setSelected(0)
class DetectDialog(KDialog):
def __init__(self, parent):
KDialog.__init__(self, parent)
self.widget = DetectSettings(self)
self.setMainWidget(self.widget)
self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel)))
self.setPlainCaption(i18n("Window Information"))
self.setModal(True)
def populate(self, windowInfo):
self.widget.titleLabel.setText(i18n("Window title: %1", windowInfo[0]))
self.widget.classLabel.setText(i18n("Window class: %1", windowInfo[1]))
self.windowInfo = windowInfo
def get_choice(self):
index = self.widget.kbuttongroup.selected()
if index == 0:
return self.windowInfo[1]
else:
return self.windowInfo[0]
class RecordSettings(QWidget, recorddialog.Ui_Form):
def __init__(self, parent):
QWidget.__init__(self, parent)
recorddialog.Ui_Form.__init__(self)
self.setupUi(self)
class RecordDialog(KDialog):
def __init__(self, parent, closure):
KDialog.__init__(self, parent)
self.widget = RecordSettings(self)
self.setMainWidget(self.widget)
self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel)))
self.setPlainCaption(i18n("Record Script"))
self.setModal(True)
self.closure = closure
def get_record_keyboard(self):
return self.widget.recKeyboardButton.isChecked()
def get_record_mouse(self):
return self.widget.recMouseButton.isChecked()
def get_delay(self):
return self.widget.secondsSpinBox.value()
def slotButtonClicked(self, button):
if button == KDialog.Ok:
KDialog.slotButtonClicked(self, button)
self.closure(True, self.get_record_keyboard(), self.get_record_mouse(), self.get_delay())
else:
self.closure(False, self.get_record_keyboard(), self.get_record_mouse(), self.get_delay())
KDialog.slotButtonClicked(self, button)
|
AKFourSeven/antoinekougblenou
|
old/wiki/includes/zhtable/Makefile.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author Philip
import tarfile as tf
import zipfile as zf
import os, re, shutil, sys, platform
pyversion = platform.python_version()
islinux = platform.system().lower() == 'linux'
if pyversion[:3] in ['2.6', '2.7']:
import urllib as urllib_request
import codecs
open = codecs.open
_unichr = unichr
if sys.maxunicode < 0x10000:
def unichr(i):
if i < 0x10000:
return _unichr(i)
else:
return _unichr( 0xD7C0 + ( i>>10 ) ) + _unichr( 0xDC00 + ( i & 0x3FF ) )
elif pyversion[:2] == '3.':
import urllib.request as urllib_request
unichr = chr
def unichr2( *args ):
return [unichr( int( i.split('<')[0][2:], 16 ) ) for i in args]
def unichr3( *args ):
return [unichr( int( i[2:7], 16 ) ) for i in args if i[2:7]]
# DEFINE
UNIHAN_VER = '5.2.0'
SF_MIRROR = 'cdnetworks-kr-2'
SCIM_TABLES_VER = '0.5.10'
SCIM_PINYIN_VER = '0.5.91'
LIBTABE_VER = '0.2.3'
# END OF DEFINE
def download( url, dest ):
if os.path.isfile( dest ):
print( 'File %s up to date.' % dest )
return
global islinux
if islinux:
# we use wget instead urlretrieve under Linux,
# because wget could display details like download progress
os.system( 'wget %s -O %s' % ( url, dest ) )
else:
print( 'Downloading from [%s] ...' % url )
urllib_request.urlretrieve( url, dest )
print( 'Download complete.\n' )
return
def uncompress( fp, member, encoding = 'U8' ):
name = member.rsplit( '/', 1 )[-1]
print( 'Extracting %s ...' % name )
fp.extract( member )
shutil.move( member, name )
if '/' in member:
shutil.rmtree( member.split( '/', 1 )[0] )
return open( name, 'rb', encoding, 'ignore' )
unzip = lambda path, member, encoding = 'U8': \
uncompress( zf.ZipFile( path ), member, encoding )
untargz = lambda path, member, encoding = 'U8': \
uncompress( tf.open( path, 'r:gz' ), member, encoding )
def parserCore( fp, pos, beginmark = None, endmark = None ):
if beginmark and endmark:
start = False
else: start = True
mlist = set()
for line in fp:
if beginmark and line.startswith( beginmark ):
start = True
continue
elif endmark and line.startswith( endmark ):
break
if start and not line.startswith( '#' ):
elems = line.split()
if len( elems ) < 2:
continue
elif len( elems[0] ) > 1 and \
len( elems[pos] ) > 1: # words only
mlist.add( elems[pos] )
return mlist
def tablesParser( path, name ):
""" Read file from scim-tables and parse it. """
global SCIM_TABLES_VER
src = 'scim-tables-%s/tables/zh/%s' % ( SCIM_TABLES_VER, name )
fp = untargz( path, src, 'U8' )
return parserCore( fp, 1, 'BEGIN_TABLE', 'END_TABLE' )
ezbigParser = lambda path: tablesParser( path, 'EZ-Big.txt.in' )
wubiParser = lambda path: tablesParser( path, 'Wubi.txt.in' )
zrmParser = lambda path: tablesParser( path, 'Ziranma.txt.in' )
def phraseParser( path ):
""" Read phrase_lib.txt and parse it. """
global SCIM_PINYIN_VER
src = 'scim-pinyin-%s/data/phrase_lib.txt' % SCIM_PINYIN_VER
dst = 'phrase_lib.txt'
fp = untargz( path, src, 'U8' )
return parserCore( fp, 0 )
def tsiParser( path ):
""" Read tsi.src and parse it. """
src = 'libtabe/tsi-src/tsi.src'
dst = 'tsi.src'
fp = untargz( path, src, 'big5hkscs' )
return parserCore( fp, 0 )
def unihanParser( path ):
""" Read Unihan_Variants.txt and parse it. """
fp = unzip( path, 'Unihan_Variants.txt', 'U8' )
t2s = dict()
s2t = dict()
for line in fp:
if line.startswith( '#' ):
continue
else:
elems = line.split()
if len( elems ) < 3:
continue
type = elems.pop( 1 )
elems = unichr2( *elems )
if type == 'kTraditionalVariant':
s2t[elems[0]] = elems[1:]
elif type == 'kSimplifiedVariant':
t2s[elems[0]] = elems[1:]
fp.close()
return ( t2s, s2t )
def applyExcludes( mlist, path ):
""" Apply exclude rules from path to mlist. """
excludes = open( path, 'rb', 'U8' ).read().split()
excludes = [word.split( '#' )[0].strip() for word in excludes]
excludes = '|'.join( excludes )
excptn = re.compile( '.*(?:%s).*' % excludes )
diff = [mword for mword in mlist if excptn.search( mword )]
mlist.difference_update( diff )
return mlist
def charManualTable( path ):
fp = open( path, 'rb', 'U8' )
ret = {}
for line in fp:
elems = line.split( '#' )[0].split( '|' )
elems = unichr3( *elems )
if len( elems ) > 1:
ret[elems[0]] = elems[1:]
return ret
def toManyRules( src_table ):
tomany = set()
for ( f, t ) in src_table.iteritems():
for i in range( 1, len( t ) ):
tomany.add( t[i] )
return tomany
def removeRules( path, table ):
fp = open( path, 'rb', 'U8' )
texc = list()
for line in fp:
elems = line.split( '=>' )
f = t = elems[0].strip()
if len( elems ) == 2:
t = elems[1].strip()
f = f.strip('"').strip("'")
t = t.strip('"').strip("'")
if f:
try:
table.pop( f )
except:
pass
if t:
texc.append( t )
texcptn = re.compile( '^(?:%s)$' % '|'.join( texc ) )
for (tmp_f, tmp_t) in table.copy().iteritems():
if texcptn.match( tmp_t ):
table.pop( tmp_f )
return table
def customRules( path ):
fp = open( path, 'rb', 'U8' )
ret = dict()
for line in fp:
elems = line.split( '#' )[0].split()
if len( elems ) > 1:
ret[elems[0]] = elems[1]
return ret
def dictToSortedList( src_table, pos ):
return sorted( src_table.items(), key = lambda m: m[pos] )
def translate( text, conv_table ):
i = 0
while i < len( text ):
for j in range( len( text ) - i, 0, -1 ):
f = text[i:][:j]
t = conv_table.get( f )
if t:
text = text[:i] + t + text[i:][j:]
i += len(t) - 1
break
i += 1
return text
def manualWordsTable( path, conv_table, reconv_table ):
fp = open( path, 'rb', 'U8' )
reconv_table = {}
wordlist = [line.split( '#' )[0].strip() for line in fp]
wordlist = list( set( wordlist ) )
wordlist.sort( key = len, reverse = True )
while wordlist:
word = wordlist.pop()
new_word = translate( word, conv_table )
rcv_word = translate( word, reconv_table )
if word != rcv_word:
reconv_table[word] = word
reconv_table[new_word] = word
return reconv_table
def defaultWordsTable( src_wordlist, src_tomany, char_conv_table, char_reconv_table ):
wordlist = list( src_wordlist )
wordlist.sort( key = len, reverse = True )
word_conv_table = {}
word_reconv_table = {}
conv_table = char_conv_table.copy()
reconv_table = char_reconv_table.copy()
tomanyptn = re.compile( '(?:%s)' % '|'.join( src_tomany ) )
while wordlist:
conv_table.update( word_conv_table )
reconv_table.update( word_reconv_table )
word = wordlist.pop()
new_word_len = word_len = len( word )
while new_word_len == word_len:
add = False
test_word = translate( word, reconv_table )
new_word = translate( word, conv_table )
if not reconv_table.get( new_word ) \
and ( test_word != word \
or ( tomanyptn.search( word ) \
and word != translate( new_word, reconv_table ) ) ):
word_conv_table[word] = new_word
word_reconv_table[new_word] = word
try:
word = wordlist.pop()
except IndexError:
break
new_word_len = len(word)
return word_reconv_table
def PHPArray( table ):
lines = ['\'%s\' => \'%s\',' % (f, t) for (f, t) in table if f and t]
return '\n'.join(lines)
def main():
#Get Unihan.zip:
url = 'http://www.unicode.org/Public/%s/ucd/Unihan.zip' % UNIHAN_VER
han_dest = 'Unihan.zip'
download( url, han_dest )
# Get scim-tables-$(SCIM_TABLES_VER).tar.gz:
url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-tables-%s.tar.gz' % ( SF_MIRROR, SCIM_TABLES_VER )
tbe_dest = 'scim-tables-%s.tar.gz' % SCIM_TABLES_VER
download( url, tbe_dest )
# Get scim-pinyin-$(SCIM_PINYIN_VER).tar.gz:
url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-pinyin-%s.tar.gz' % ( SF_MIRROR, SCIM_PINYIN_VER )
pyn_dest = 'scim-pinyin-%s.tar.gz' % SCIM_PINYIN_VER
download( url, pyn_dest )
# Get libtabe-$(LIBTABE_VER).tgz:
url = 'http://%s.dl.sourceforge.net/sourceforge/libtabe/libtabe-%s.tgz' % ( SF_MIRROR, LIBTABE_VER )
lbt_dest = 'libtabe-%s.tgz' % LIBTABE_VER
download( url, lbt_dest )
# Unihan.txt
( t2s_1tomany, s2t_1tomany ) = unihanParser( han_dest )
t2s_1tomany.update( charManualTable( 'trad2simp.manual' ) )
s2t_1tomany.update( charManualTable( 'simp2trad.manual' ) )
t2s_1to1 = dict( [( f, t[0] ) for ( f, t ) in t2s_1tomany.iteritems()] )
s2t_1to1 = dict( [( f, t[0] ) for ( f, t ) in s2t_1tomany.iteritems()] )
s_tomany = toManyRules( t2s_1tomany )
t_tomany = toManyRules( s2t_1tomany )
# noconvert rules
t2s_1to1 = removeRules( 'trad2simp_noconvert.manual', t2s_1to1 )
s2t_1to1 = removeRules( 'simp2trad_noconvert.manual', s2t_1to1 )
# the supper set for word to word conversion
t2s_1to1_supp = t2s_1to1.copy()
s2t_1to1_supp = s2t_1to1.copy()
t2s_1to1_supp.update( customRules( 'trad2simp_supp_set.manual' ) )
s2t_1to1_supp.update( customRules( 'simp2trad_supp_set.manual' ) )
# word to word manual rules
t2s_word2word_manual = manualWordsTable( 'simpphrases.manual', s2t_1to1_supp, t2s_1to1_supp )
t2s_word2word_manual.update( customRules( 'toSimp.manual' ) )
s2t_word2word_manual = manualWordsTable( 'tradphrases.manual', t2s_1to1_supp, s2t_1to1_supp )
s2t_word2word_manual.update( customRules( 'toTrad.manual' ) )
# word to word rules from input methods
t_wordlist = set()
s_wordlist = set()
t_wordlist.update( ezbigParser( tbe_dest ),
tsiParser( lbt_dest ) )
s_wordlist.update( wubiParser( tbe_dest ),
zrmParser( tbe_dest ),
phraseParser( pyn_dest ) )
# exclude
s_wordlist = applyExcludes( s_wordlist, 'simpphrases_exclude.manual' )
t_wordlist = applyExcludes( t_wordlist, 'tradphrases_exclude.manual' )
s2t_supp = s2t_1to1_supp.copy()
s2t_supp.update( s2t_word2word_manual )
t2s_supp = t2s_1to1_supp.copy()
t2s_supp.update( t2s_word2word_manual )
# parse list to dict
t2s_word2word = defaultWordsTable( s_wordlist, s_tomany, s2t_1to1_supp, t2s_supp )
t2s_word2word.update( t2s_word2word_manual )
s2t_word2word = defaultWordsTable( t_wordlist, t_tomany, t2s_1to1_supp, s2t_supp )
s2t_word2word.update( s2t_word2word_manual )
# Final tables
# sorted list toHans
t2s_1to1 = dict( [( f, t ) for ( f, t ) in t2s_1to1.iteritems() if f != t] )
toHans = dictToSortedList( t2s_1to1, 0 ) + dictToSortedList( t2s_word2word, 1 )
# sorted list toHant
s2t_1to1 = dict( [( f, t ) for ( f, t ) in s2t_1to1.iteritems() if f != t] )
toHant = dictToSortedList( s2t_1to1, 0 ) + dictToSortedList( s2t_word2word, 1 )
# sorted list toCN
toCN = dictToSortedList( customRules( 'toCN.manual' ), 1 )
# sorted list toHK
toHK = dictToSortedList( customRules( 'toHK.manual' ), 1 )
# sorted list toSG
toSG = dictToSortedList( customRules( 'toSG.manual' ), 1 )
# sorted list toTW
toTW = dictToSortedList( customRules( 'toTW.manual' ), 1 )
# Get PHP Array
php = '''<?php
/**
* Simplified / Traditional Chinese conversion tables
*
* Automatically generated using code and data in includes/zhtable/
* Do not modify directly!
*
* @file
*/
$zh2Hant = array(\n'''
php += PHPArray( toHant ) \
+ '\n);\n\n$zh2Hans = array(\n' \
+ PHPArray( toHans ) \
+ '\n);\n\n$zh2TW = array(\n' \
+ PHPArray( toTW ) \
+ '\n);\n\n$zh2HK = array(\n' \
+ PHPArray( toHK ) \
+ '\n);\n\n$zh2CN = array(\n' \
+ PHPArray( toCN ) \
+ '\n);\n\n$zh2SG = array(\n' \
+ PHPArray( toSG ) \
+ '\n);'
f = open( 'ZhConversion.php', 'wb', encoding = 'utf8' )
print ('Writing ZhConversion.php ... ')
f.write( php )
f.close()
#Remove temp files
print ('Deleting temp files ... ')
os.remove('EZ-Big.txt.in')
os.remove('phrase_lib.txt')
os.remove('tsi.src')
os.remove('Unihan_Variants.txt')
os.remove('Wubi.txt.in')
os.remove('Ziranma.txt.in')
if __name__ == '__main__':
main()
|
snehasi/servo
|
tests/wpt/web-platform-tests/referrer-policy/generic/subresource/subresource.py
|
import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
"template"))
template_filename = os.path.join(template_directory, template_basename);
with open(template_filename, "r") as f:
return f.read()
# TODO(kristijanburnik): subdomain_prefix is a hardcoded value aligned with
# referrer-policy-test-case.js. The prefix should be configured in one place.
def get_swapped_origin_netloc(netloc, subdomain_prefix = "www1."):
if netloc.startswith(subdomain_prefix):
return netloc[len(subdomain_prefix):]
else:
return subdomain_prefix + netloc
def create_redirect_url(request, cross_origin = False):
parsed = urlparse.urlsplit(request.url)
destination_netloc = parsed.netloc
if cross_origin:
destination_netloc = get_swapped_origin_netloc(parsed.netloc)
destination_url = urlparse.urlunsplit(urlparse.SplitResult(
scheme = parsed.scheme,
netloc = destination_netloc,
path = parsed.path,
query = None,
fragment = None))
return destination_url
def redirect(url, response):
response.add_required_headers = False
response.writer.write_status(301)
response.writer.write_header("access-control-allow-origin", "*")
response.writer.write_header("location", url)
response.writer.end_headers()
response.writer.write("")
def preprocess_redirection(request, response):
if "redirection" not in request.GET:
return False
redirection = request.GET["redirection"]
if redirection == "no-redirect":
return False
elif redirection == "keep-origin-redirect":
redirect_url = create_redirect_url(request, cross_origin = False)
elif redirection == "swap-origin-redirect":
redirect_url = create_redirect_url(request, cross_origin = True)
else:
raise ValueError("Invalid redirection type '%s'" % redirection)
redirect(redirect_url, response)
return True
def __noop(request, response):
return ""
def respond(request,
response,
status_code = 200,
content_type = "text/html",
payload_generator = __noop,
cache_control = "no-cache; must-revalidate",
access_control_allow_origin = "*"):
if preprocess_redirection(request, response):
return
response.add_required_headers = False
response.writer.write_status(status_code)
if access_control_allow_origin != None:
response.writer.write_header("access-control-allow-origin",
access_control_allow_origin)
response.writer.write_header("content-type", content_type)
response.writer.write_header("cache-control", cache_control)
response.writer.end_headers()
server_data = {"headers": json.dumps(request.headers, indent = 4)}
payload = payload_generator(server_data)
response.writer.write(payload)
|
ysung-pivotal/incubator-hawq
|
tools/bin/gppylib/pgconf.py
|
#!/usr/bin/env python
# $Id: $
"""
postgresql.conf configuration file reader
Module contents:
readfile() - Read postgresql.conf file
class gucdict - Container for postgresql.conf settings
class setting - Holds one setting
class ConfigurationError - a subclass of EnvironmentError
Example:
import lib.pgconf as pgconf
d = pgconf.readfile()
port = d.int('port', 5432)
pe = d.bool('password_encryption', False)
sb = d.kB('shared_buffers')
at = d.time('authentication_timeout', 'ms', 2500)
"""
import os
import os.path
import re
# Max recursion level for postgresql.conf include directives.
# The max value is 10 in the postgres code, so it's the same here.
MAX_RECURSION_LEVEL=10
def readfile(filename='postgresql.conf', defaultpath=None):
"""
Read postgresql.conf file and put the settings into a dictionary.
Returns the dictionary: a newly created pgconf.gucdict object.
If filename does not specify an absolute path, it is treated as relative
to defaultpath, or to the current working directory.
"""
if not os.path.isabs(filename):
if defaultpath is None:
defaultpath = os.getcwd()
filename = os.path.normpath(os.path.join(defaultpath, filename))
fp = open(filename)
try:
dictionary = gucdict()
dictionary.populate(fp, filename)
return dictionary
except Exception:
raise
finally:
fp.close()
class gucdict(dict):
"""
A container for settings from a postgresql.conf file.
Behaves as an ordinary dictionary, with a few added methods.
The keys of the dictionary are GUC names in lower case, and the
values are instances of the pgconf.setting class.
The populate() method loads the dictionary with settings from a file.
The str(), bool(), int(), float(), kB(), and time() methods return a
value from the dictionary, converted to internal form.
"""
def populate(self, lines, filename='', recurLevel=0):
'''
Given a postgresql.conf input file (or a list of strings, or some
iterable object yielding lines), look for lines of the form
name[=][value][#comment]
For each one found, construct a pgconf.setting object and put it
into our dictionary.
'''
if recurLevel == MAX_RECURSION_LEVEL:
raise Exception('could not open configuration file "%s": maximum nesting depth exceeded' % filename)
linenumber = 0
for line in lines:
linenumber += 1
m = _setpat.match(line)
if m:
name, value, pos = m.group(1), m.group(3), m.start(3)
if name == 'include':
try:
# Remove the ' from the filename and then convert to abspath if needed.
incfilename = value.strip("'")
if not incfilename.startswith('/') and filename != '':
incfilename = '%s/%s' % (filename[0:filename.rfind('/')], incfilename)
fp = open(incfilename)
self.populate(fp, incfilename, recurLevel+1)
fp.close()
except IOError:
raise Exception('File %s included from %s:%d does not exist' % (incfilename, filename, linenumber))
else:
self[name.lower()] = setting(name, value, filename, linenumber, pos)
def str(self, name, default=None):
"""
Return string setting, or default if absent.
"""
v = self.get(name)
if v:
return v.str()
else:
return default
def bool(self, name, default=None):
"""
Return Boolean setting, or default if absent.
"""
v = self.get(name)
if v:
return v.bool()
else:
return default
def int(self, name, default=None):
"""
Return integer setting, or default if absent.
"""
v = self.get(name)
if v:
return v.int()
else:
return default
def float(self, name, default=None):
"""
Return floating-point setting, or default if absent.
"""
v = self.get(name)
if v:
return v.float()
else:
return default
def kB(self, name, default=None):
"""
Return memory setting in units of 1024 bytes, or default if absent.
"""
v = self.get(name)
if v:
return v.kB()
else:
return default
def time(self, name, unit='s', default=None):
"""
Return time setting, or default if absent.
Specify desired unit as 'ms', 's', or 'min'.
"""
v = self.get(name)
if v:
return v.time(unit)
else:
return default
class setting(object):
"""
Holds a GUC setting from a postgresql.conf file.
The str(), bool(), int(), float(), kB(), and time() methods return the
value converted to the requested internal form. pgconf.ConfigurationError
is raised if the conversion fails, i.e. the value does not conform to the
expected syntax.
"""
def __init__(self, name, value, filename='', linenumber=0, pos=0):
self.name = name
self.value = value
self.filename = filename
self.linenumber = linenumber
self.pos = pos # starting offset of value within the input line
def __repr__(self):
return repr(self.value)
def str(self):
"""
Return the value as a string.
"""
v = self.value
if v and v.endswith("'"):
# Single-quoted string. Remove the opening and closing quotes.
# Replace each escape sequence with the character it stands for.
i = v.index("'") + 1
v = _escapepat.sub(_escapefun, v[i:-1])
return v
def bool(self):
"""
Interpret the value as a Boolean. Returns True or False.
"""
s = self.value
if s:
s = s.lower()
n = len(s)
if (s == '1' or
s == 'on' or
s == 'true'[:n] or
s == 'yes'[:n]):
return True
if (s == '0' or
s == 'off'[:n] or
s == 'false'[:n] or
s == 'no'[:n]):
return False
raise self.ConfigurationError('Boolean value should be one of: 1, 0, '
'on, off, true, false, yes, no.')
def int(self):
"""
Interpret the value as an integer. Returns an int or long.
"""
try:
return int(self.value, 0)
except ValueError:
raise self.ConfigurationError('Value should be integer.')
def float(self):
"""
Interpret the value as floating point. Returns a float.
"""
try:
return float(self.value)
except ValueError:
raise self.ConfigurationError('Value should be floating point.')
def kB(self):
"""
Interpret the value as an amount of memory. Returns an int or long,
in units of 1024 bytes.
"""
try:
m = 1
t = re.split('(kB|MB|GB)', self.value)
if len(t) > 1:
i = ['kB', 'MB', 'GB'].index(t[1])
m = (1, 1024, 1024*1024)[i]
try:
return int(t[0], 0) * m
except ValueError:
pass
return int(float(t[0]) * m)
except (ValueError, IndexError):
raise self.ConfigurationError('Value should be integer or float '
'with optional suffix kB, MB, or GB '
'(kB is default).')
def time(self, unit='s'):
"""
Interpret the value as a time. Returns an int or long.
Specify desired unit as 'ms', 's', or 'min'.
"""
u = ['ms', 's', 'min'].index(unit)
u = (1, 1000, 60*1000)[u]
try:
m = u
t = re.split('(ms|s|min|h|d)', self.value)
if len(t) > 1:
i = ['ms', 's', 'min', 'h', 'd'].index(t[1])
m = (1, 1000, 60*1000, 3600*1000, 24*3600*1000)[i]
return int(t[0], 0) * m / u
except (ValueError, IndexError):
raise self.ConfigurationError('Value should be integer with '
'optional suffix ms, s, min, h, or d '
'(%s is default).' % unit)
def ConfigurationError(self, msg):
msg = '(%s = %s) %s' % (self.name, self.value, msg)
return ConfigurationError(msg, self.filename, self.linenumber)
class ConfigurationError(EnvironmentError):
def __init__(self, msg, filename='', linenumber=0):
self.msg = msg
self.filename = filename
self.linenumber = linenumber
if linenumber:
msg = '%s line %d: %s' % (filename, linenumber, msg)
elif filename:
msg = '%s: %s' % (filename, msg)
EnvironmentError.__init__(self, msg)
def __str__(self):
return self.message
#-------------------------------- private --------------------------------
_setpat = re.compile(r"\s*(\w+)\s*(=\s*)?" # name [=]
'('
r"[eE]?('((\\.)?[^\\']*)*')+|" # single-quoted string or
r"[^\s#']*" # token ending at whitespace or comment
')')
_escapepat = re.compile(r"''|" # pair of single quotes, or
r"\\(" # backslash followed by
r"[0-7][0-7]?[0-7]?|" # nnn (1 to 3 octal digits) or
r"x[0-9A-Fa-f][0-9A-Fa-f]?|" # xHH (1 or 2 hex digits) or
r".)") # one char
def _escapefun(matchobj):
"""Callback to interpret an escape sequence"""
s = matchobj.group()
c = s[1]
i = "bfnrt".find(c)
if i >= 0:
c = "\b\f\n\r\t"[i]
elif c == 'x':
c = chr(int(s[2:], 16))
elif c in '01234567':
c = chr(int(s[1:], 8))
return c
|
kristerhedfors/xnet
|
xnet/packages/urllib3/request.py
|
# urllib3/request.py
# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from .filepost import encode_multipart_formdata
__all__ = ['RequestMethods']
class RequestMethods(object):
"""
Convenience mixin for classes who implement a :meth:`urlopen` method, such
as :class:`~urllib3.connectionpool.HTTPConnectionPool` and
:class:`~urllib3.poolmanager.PoolManager`.
Provides behavior for making common types of HTTP request methods and
decides which type of request field encoding to use.
Specifically,
:meth:`.request_encode_url` is for sending requests whose fields are encoded
in the URL (such as GET, HEAD, DELETE).
:meth:`.request_encode_body` is for sending requests whose fields are
encoded in the *body* of the request using multipart or www-orm-urlencoded
(such as for POST, PUT, PATCH).
:meth:`.request` is for making any kind of request, it will look up the
appropriate encoding format and use one of the above two methods to make
the request.
Initializer parameters:
:param headers:
Headers to include with all requests, unless other headers are given
explicitly.
"""
_encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])
_encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])
def __init__(self, headers=None):
self.headers = headers or {}
def urlopen(self, method, url, body=None, headers=None,
encode_multipart=True, multipart_boundary=None,
**kw): # Abstract
raise NotImplemented("Classes extending RequestMethods must implement "
"their own ``urlopen`` method.")
def request(self, method, url, fields=None, headers=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used.
This is a convenience method that requires the least amount of manual
effort. It can be used in most situations, while still having the option
to drop down to more specific methods when necessary, such as
:meth:`request_encode_url`, :meth:`request_encode_body`,
or even the lowest level :meth:`urlopen`.
"""
method = method.upper()
if method in self._encode_url_methods:
return self.request_encode_url(method, url, fields=fields,
headers=headers,
**urlopen_kw)
else:
return self.request_encode_body(method, url, fields=fields,
headers=headers,
**urlopen_kw)
def request_encode_url(self, method, url, fields=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
"""
if fields:
url += '?' + urlencode(fields)
return self.urlopen(method, url, **urlopen_kw)
def request_encode_body(self, method, url, fields=None, headers=None,
encode_multipart=True, multipart_boundary=None,
**urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc.
When ``encode_multipart=True`` (default), then
:meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the
payload with the appropriate content type. Otherwise
:meth:`urllib.urlencode` is used with the
'application/x-www-form-urlencoded' content type.
Multipart encoding must be used when posting files, and it's reasonably
safe to use it in other times too. However, it may break request signing,
such as with OAuth.
Supports an optional ``fields`` parameter of key/value strings AND
key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
the MIME type is optional. For example: ::
fields = {
'foo': 'bar',
'fakefile': ('foofile.txt', 'contents of foofile'),
'realfile': ('barfile.txt', open('realfile').read()),
'typedfile': ('bazfile.bin', open('bazfile').read(),
'image/jpeg'),
'nonamefile': 'contents of nonamefile field',
}
When uploading a file, providing a filename (the first parameter of the
tuple) is optional but recommended to best mimick behavior of browsers.
Note that if ``headers`` are supplied, the 'Content-Type' header will be
overwritten because it depends on the dynamic random boundary string
which is used to compose the body of the request. The random boundary
string can be explicitly set with the ``multipart_boundary`` parameter.
"""
if encode_multipart:
body, content_type = encode_multipart_formdata(fields or {},
boundary=multipart_boundary)
else:
body, content_type = (urlencode(fields or {}),
'application/x-www-form-urlencoded')
if headers is None:
headers = self.headers
headers_ = {'Content-Type': content_type}
headers_.update(headers)
return self.urlopen(method, url, body=body, headers=headers_,
**urlopen_kw)
|
912/M-new
|
virtualenvironment/experimental/lib/python2.7/site-packages/django/contrib/gis/db/backends/postgis/creation.py
|
from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND'
@cached_property
def template_postgis(self):
template_postgis = getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis')
with self.connection.cursor() as cursor:
cursor.execute('SELECT 1 FROM pg_database WHERE datname = %s LIMIT 1;', (template_postgis,))
if cursor.fetchone():
return template_postgis
return None
def sql_indexes_for_field(self, model, f, style):
"Return any spatial index creation SQL for the field."
from django.contrib.gis.db.models.fields import GeometryField
output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style)
if isinstance(f, GeometryField):
gqn = self.connection.ops.geo_quote_name
qn = self.connection.ops.quote_name
db_table = model._meta.db_table
if f.geography or self.connection.ops.geometry:
# Geography and Geometry (PostGIS 2.0+) columns are
# created normally.
pass
else:
# Geometry columns are created by `AddGeometryColumn`
# stored procedure.
output.append(style.SQL_KEYWORD('SELECT ') +
style.SQL_TABLE('AddGeometryColumn') + '(' +
style.SQL_TABLE(gqn(db_table)) + ', ' +
style.SQL_FIELD(gqn(f.column)) + ', ' +
style.SQL_FIELD(str(f.srid)) + ', ' +
style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' +
style.SQL_KEYWORD(str(f.dim)) + ');')
if not f.null:
# Add a NOT NULL constraint to the field
output.append(style.SQL_KEYWORD('ALTER TABLE ') +
style.SQL_TABLE(qn(db_table)) +
style.SQL_KEYWORD(' ALTER ') +
style.SQL_FIELD(qn(f.column)) +
style.SQL_KEYWORD(' SET NOT NULL') + ';')
if f.spatial_index:
# Spatial indexes created the same way for both Geometry and
# Geography columns.
# PostGIS 2.0 does not support GIST_GEOMETRY_OPS. So, on 1.5
# we use GIST_GEOMETRY_OPS, on 2.0 we use either "nd" ops
# which are fast on multidimensional cases, or just plain
# gist index for the 2d case.
if f.geography:
index_ops = ''
elif self.connection.ops.geometry:
if f.dim > 2:
index_ops = ' ' + style.SQL_KEYWORD(self.geom_index_ops_nd)
else:
index_ops = ''
else:
index_ops = ' ' + style.SQL_KEYWORD(self.geom_index_ops)
output.append(style.SQL_KEYWORD('CREATE INDEX ') +
style.SQL_TABLE(qn('%s_%s_id' % (db_table, f.column))) +
style.SQL_KEYWORD(' ON ') +
style.SQL_TABLE(qn(db_table)) +
style.SQL_KEYWORD(' USING ') +
style.SQL_COLTYPE(self.geom_index_type) + ' ( ' +
style.SQL_FIELD(qn(f.column)) + index_ops + ' );')
return output
def sql_table_creation_suffix(self):
if self.template_postgis is not None:
return ' TEMPLATE %s' % (
self.connection.ops.quote_name(self.template_postgis),)
return ''
def _create_test_db(self, verbosity, autoclobber):
test_database_name = super(PostGISCreation, self)._create_test_db(verbosity, autoclobber)
if self.template_postgis is None:
# Connect to the test database in order to create the postgis extension
self.connection.close()
self.connection.settings_dict["NAME"] = test_database_name
with self.connection.cursor() as cursor:
cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis")
cursor.connection.commit()
return test_database_name
|
redhat-cip/horizon
|
openstack_dashboard/dashboards/admin/defaults/urls.py
|
# Copyright 2013 Kylin, 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 django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.defaults import views
urlpatterns = patterns(
'openstack_dashboard.dashboards.admin.defaults.views',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^update_defaults$',
views.UpdateDefaultQuotasView.as_view(), name='update_defaults'))
|
YakindanEgitim/EN-LinuxClipper
|
thrift/transport/TZlibTransport.py
|
#
# 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.
#
'''
TZlibTransport provides a compressed transport and transport factory
class, using the python standard library zlib module to implement
data compression.
'''
from __future__ import division
import zlib
from cStringIO import StringIO
from TTransport import TTransportBase, CReadableTransport
class TZlibTransportFactory(object):
'''
Factory transport that builds zlib compressed transports.
This factory caches the last single client/transport that it was passed
and returns the same TZlibTransport object that was created.
This caching means the TServer class will get the _same_ transport
object for both input and output transports from this factory.
(For non-threaded scenarios only, since the cache only holds one object)
The purpose of this caching is to allocate only one TZlibTransport where
only one is really needed (since it must have separate read/write buffers),
and makes the statistics from getCompSavings() and getCompRatio()
easier to understand.
'''
# class scoped cache of last transport given and zlibtransport returned
_last_trans = None
_last_z = None
def getTransport(self, trans, compresslevel=9):
'''Wrap a transport , trans, with the TZlibTransport
compressed transport class, returning a new
transport to the caller.
@param compresslevel: The zlib compression level, ranging
from 0 (no compression) to 9 (best compression). Defaults to 9.
@type compresslevel: int
This method returns a TZlibTransport which wraps the
passed C{trans} TTransport derived instance.
'''
if trans == self._last_trans:
return self._last_z
ztrans = TZlibTransport(trans, compresslevel)
self._last_trans = trans
self._last_z = ztrans
return ztrans
class TZlibTransport(TTransportBase, CReadableTransport):
'''
Class that wraps a transport with zlib, compressing writes
and decompresses reads, using the python standard
library zlib module.
'''
# Read buffer size for the python fastbinary C extension,
# the TBinaryProtocolAccelerated class.
DEFAULT_BUFFSIZE = 4096
def __init__(self, trans, compresslevel=9):
'''
Create a new TZlibTransport, wrapping C{trans}, another
TTransport derived object.
@param trans: A thrift transport object, i.e. a TSocket() object.
@type trans: TTransport
@param compresslevel: The zlib compression level, ranging
from 0 (no compression) to 9 (best compression). Default is 9.
@type compresslevel: int
'''
self.__trans = trans
self.compresslevel = compresslevel
self.__rbuf = StringIO()
self.__wbuf = StringIO()
self._init_zlib()
self._init_stats()
def _reinit_buffers(self):
'''
Internal method to initialize/reset the internal StringIO objects
for read and write buffers.
'''
self.__rbuf = StringIO()
self.__wbuf = StringIO()
def _init_stats(self):
'''
Internal method to reset the internal statistics counters
for compression ratios and bandwidth savings.
'''
self.bytes_in = 0
self.bytes_out = 0
self.bytes_in_comp = 0
self.bytes_out_comp = 0
def _init_zlib(self):
'''
Internal method for setting up the zlib compression and
decompression objects.
'''
self._zcomp_read = zlib.decompressobj()
self._zcomp_write = zlib.compressobj(self.compresslevel)
def getCompRatio(self):
'''
Get the current measured compression ratios (in,out) from
this transport.
Returns a tuple of:
(inbound_compression_ratio, outbound_compression_ratio)
The compression ratios are computed as:
compressed / uncompressed
E.g., data that compresses by 10x will have a ratio of: 0.10
and data that compresses to half of ts original size will
have a ratio of 0.5
None is returned if no bytes have yet been processed in
a particular direction.
'''
r_percent, w_percent = (None, None)
if self.bytes_in > 0:
r_percent = self.bytes_in_comp / self.bytes_in
if self.bytes_out > 0:
w_percent = self.bytes_out_comp / self.bytes_out
return (r_percent, w_percent)
def getCompSavings(self):
'''
Get the current count of saved bytes due to data
compression.
Returns a tuple of:
(inbound_saved_bytes, outbound_saved_bytes)
Note: if compression is actually expanding your
data (only likely with very tiny thrift objects), then
the values returned will be negative.
'''
r_saved = self.bytes_in - self.bytes_in_comp
w_saved = self.bytes_out - self.bytes_out_comp
return (r_saved, w_saved)
def isOpen(self):
'''Return the underlying transport's open status'''
return self.__trans.isOpen()
def open(self):
"""Open the underlying transport"""
self._init_stats()
return self.__trans.open()
def listen(self):
'''Invoke the underlying transport's listen() method'''
self.__trans.listen()
def accept(self):
'''Accept connections on the underlying transport'''
return self.__trans.accept()
def close(self):
'''Close the underlying transport,'''
self._reinit_buffers()
self._init_zlib()
return self.__trans.close()
def read(self, sz):
'''
Read up to sz bytes from the decompressed bytes buffer, and
read from the underlying transport if the decompression
buffer is empty.
'''
ret = self.__rbuf.read(sz)
if len(ret) > 0:
return ret
# keep reading from transport until something comes back
while True:
if self.readComp(sz):
break
ret = self.__rbuf.read(sz)
return ret
def readComp(self, sz):
'''
Read compressed data from the underlying transport, then
decompress it and append it to the internal StringIO read buffer
'''
zbuf = self.__trans.read(sz)
zbuf = self._zcomp_read.unconsumed_tail + zbuf
buf = self._zcomp_read.decompress(zbuf)
self.bytes_in += len(zbuf)
self.bytes_in_comp += len(buf)
old = self.__rbuf.read()
self.__rbuf = StringIO(old + buf)
if len(old) + len(buf) == 0:
return False
return True
def write(self, buf):
'''
Write some bytes, putting them into the internal write
buffer for eventual compression.
'''
self.__wbuf.write(buf)
def flush(self):
'''
Flush any queued up data in the write buffer and ensure the
compression buffer is flushed out to the underlying transport
'''
wout = self.__wbuf.getvalue()
if len(wout) > 0:
zbuf = self._zcomp_write.compress(wout)
self.bytes_out += len(wout)
self.bytes_out_comp += len(zbuf)
else:
zbuf = ''
ztail = self._zcomp_write.flush(zlib.Z_SYNC_FLUSH)
self.bytes_out_comp += len(ztail)
if (len(zbuf) + len(ztail)) > 0:
self.__wbuf = StringIO()
self.__trans.write(zbuf + ztail)
self.__trans.flush()
@property
def cstringio_buf(self):
'''Implement the CReadableTransport interface'''
return self.__rbuf
def cstringio_refill(self, partialread, reqlen):
'''Implement the CReadableTransport interface for refill'''
retstring = partialread
if reqlen < self.DEFAULT_BUFFSIZE:
retstring += self.read(self.DEFAULT_BUFFSIZE)
while len(retstring) < reqlen:
retstring += self.read(reqlen - len(retstring))
self.__rbuf = StringIO(retstring)
return self.__rbuf
|
nmercier/linux-cross-gcc
|
win32/bin/Lib/email/errors.py
|
# Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""email package exception classes."""
class MessageError(Exception):
"""Base class for errors in the email package."""
class MessageParseError(MessageError):
"""Base class for message parsing errors."""
class HeaderParseError(MessageParseError):
"""Error while parsing headers."""
class BoundaryError(MessageParseError):
"""Couldn't find terminating boundary."""
class MultipartConversionError(MessageError, TypeError):
"""Conversion to a multipart is prohibited."""
class CharsetError(MessageError):
"""An illegal charset was given."""
# These are parsing defects which the parser was able to work around.
class MessageDefect:
"""Base class for a message defect."""
def __init__(self, line=None):
self.line = line
class NoBoundaryInMultipartDefect(MessageDefect):
"""A message claimed to be a multipart but had no boundary parameter."""
class StartBoundaryNotFoundDefect(MessageDefect):
"""The claimed start boundary was never found."""
class FirstHeaderLineIsContinuationDefect(MessageDefect):
"""A message had a continuation line as its first header line."""
class MisplacedEnvelopeHeaderDefect(MessageDefect):
"""A 'Unix-from' header was found in the middle of a header block."""
class MalformedHeaderDefect(MessageDefect):
"""Found a header that was missing a colon, or was otherwise malformed."""
class MultipartInvariantViolationDefect(MessageDefect):
"""A message claimed to be a multipart but no subparts were found."""
|
camradal/ansible
|
lib/ansible/module_utils/lxd.py
|
# -*- coding: utf-8 -*-
# (c) 2016, Hiroaki Nakamura <hnakamur@gmail.com>
#
# 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.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
try:
import json
except ImportError:
import simplejson as json
# httplib/http.client connection using unix domain socket
import socket
import ssl
try:
from httplib import HTTPConnection, HTTPSConnection
except ImportError:
# Python 3
from http.client import HTTPConnection, HTTPSConnection
class UnixHTTPConnection(HTTPConnection):
def __init__(self, path):
HTTPConnection.__init__(self, 'localhost')
self.path = path
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.path)
self.sock = sock
from ansible.module_utils.urls import generic_urlparse
try:
from urlparse import urlparse
except ImportError:
# Python 3
from url.parse import urlparse
class LXDClientException(Exception):
def __init__(self, msg, **kwargs):
self.msg = msg
self.kwargs = kwargs
class LXDClient(object):
def __init__(self, url, key_file=None, cert_file=None, debug=False):
"""LXD Client.
:param url: The URL of the LXD server. (e.g. unix:/var/lib/lxd/unix.socket or https://127.0.0.1)
:type url: ``str``
:param key_file: The path of the client certificate key file.
:type key_file: ``str``
:param cert_file: The path of the client certificate file.
:type cert_file: ``str``
:param debug: The debug flag. The request and response are stored in logs when debug is true.
:type debug: ``bool``
"""
self.url = url
self.debug = debug
self.logs = []
if url.startswith('https:'):
self.cert_file = cert_file
self.key_file = key_file
parts = generic_urlparse(urlparse(self.url))
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ctx.load_cert_chain(cert_file, keyfile=key_file)
self.connection = HTTPSConnection(parts.get('netloc'), context=ctx)
elif url.startswith('unix:'):
unix_socket_path = url[len('unix:'):]
self.connection = UnixHTTPConnection(unix_socket_path)
else:
raise LXDClientException('URL scheme must be unix: or https:')
def do(self, method, url, body_json=None, ok_error_codes=None, timeout=None):
resp_json = self._send_request(method, url, body_json=body_json, ok_error_codes=ok_error_codes, timeout=timeout)
if resp_json['type'] == 'async':
url = '{0}/wait'.format(resp_json['operation'])
resp_json = self._send_request('GET', url)
if resp_json['metadata']['status'] != 'Success':
self._raise_err_from_json(resp_json)
return resp_json
def authenticate(self, trust_password):
body_json = {'type': 'client', 'password': trust_password}
return self._send_request('POST', '/1.0/certificates', body_json=body_json)
def _send_request(self, method, url, body_json=None, ok_error_codes=None, timeout=None):
try:
body = json.dumps(body_json)
self.connection.request(method, url, body=body)
resp = self.connection.getresponse()
resp_json = json.loads(resp.read())
self.logs.append({
'type': 'sent request',
'request': {'method': method, 'url': url, 'json': body_json, 'timeout': timeout},
'response': {'json': resp_json}
})
resp_type = resp_json.get('type', None)
if resp_type == 'error':
if ok_error_codes is not None and resp_json['error_code'] in ok_error_codes:
return resp_json
if resp_json['error'] == "Certificate already in trust store":
return resp_json
self._raise_err_from_json(resp_json)
return resp_json
except socket.error as e:
raise LXDClientException('cannot connect to the LXD server', err=e)
def _raise_err_from_json(self, resp_json):
err_params = {}
if self.debug:
err_params['logs'] = self.logs
raise LXDClientException(self._get_err_from_resp_json(resp_json), **err_params)
@staticmethod
def _get_err_from_resp_json(resp_json):
err = None
metadata = resp_json.get('metadata', None)
if metadata is not None:
err = metadata.get('err', None)
if err is None:
err = resp_json.get('error', None)
return err
|
ramcn/demo3
|
venv/lib/python3.4/site-packages/rest_framework/authtoken/south_migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Token'
db.create_table('authtoken_token', (
('key', self.gf('django.db.models.fields.CharField')(max_length=40, primary_key=True)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='auth_token', unique=True, to=orm['%s.%s' % (User._meta.app_label, User._meta.object_name)])),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal('authtoken', ['Token'])
def backwards(self, orm):
# Deleting model 'Token'
db.delete_table('authtoken_token')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
"%s.%s" % (User._meta.app_label, User._meta.module_name): {
'Meta': {'object_name': User._meta.module_name, 'db_table': repr(User._meta.db_table)},
},
'authtoken.token': {
'Meta': {'object_name': 'Token'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'auth_token'", 'unique': 'True', 'to': "orm['%s.%s']" % (User._meta.app_label, User._meta.object_name)})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['authtoken']
|
ychen820/microblog
|
y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/contrib/sessions/backends/cached_db.py
|
"""
Cached, database-backed sessions.
"""
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import cache
KEY_PREFIX = "django.contrib.sessions.cached_db"
class SessionStore(DBStore):
"""
Implements cached, database backed sessions.
"""
def __init__(self, session_key=None):
super(SessionStore, self).__init__(session_key)
@property
def cache_key(self):
return KEY_PREFIX + self._get_or_create_session_key()
def load(self):
try:
data = cache.get(self.cache_key, None)
except Exception:
# Some backends (e.g. memcache) raise an exception on invalid
# cache keys. If this happens, reset the session. See #17810.
data = None
if data is None:
data = super(SessionStore, self).load()
cache.set(self.cache_key, data, settings.SESSION_COOKIE_AGE)
return data
def exists(self, session_key):
if (KEY_PREFIX + session_key) in cache:
return True
return super(SessionStore, self).exists(session_key)
def save(self, must_create=False):
super(SessionStore, self).save(must_create)
cache.set(self.cache_key, self._session, settings.SESSION_COOKIE_AGE)
def delete(self, session_key=None):
super(SessionStore, self).delete(session_key)
if session_key is None:
if self.session_key is None:
return
session_key = self.session_key
cache.delete(KEY_PREFIX + session_key)
def flush(self):
"""
Removes the current session data from the database and regenerates the
key.
"""
self.clear()
self.delete(self.session_key)
self.create()
|
e-gob/plataforma-kioscos-autoatencion
|
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/action/netconf_config.py
|
#
# Copyright 2016 Peter Sprygada <psprygada@ansible.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/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
from ansible.plugins.action.net_config import ActionModule as NetActionModule
class ActionModule(NetActionModule, ActionBase):
pass
|
fharenheit/template-spark-app
|
src/main/python/ml/sql_transformer.py
|
#
# 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.
#
from __future__ import print_function
# $example on$
from pyspark.ml.feature import SQLTransformer
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("SQLTransformerExample")\
.getOrCreate()
# $example on$
df = spark.createDataFrame([
(0, 1.0, 3.0),
(2, 2.0, 5.0)
], ["id", "v1", "v2"])
sqlTrans = SQLTransformer(
statement="SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__")
sqlTrans.transform(df).show()
# $example off$
spark.stop()
|
friend0/tower
|
tower/server/server.py
|
"""
The server module is responsible for managng the threaded UDP socket server.
This server is used to communicate with Matlab/Simulink simulations. It will be renamed appropriately soon
@todo: rename this module to indicate it's role in any Matlab connections
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import object
import socketserver
import re
import struct
from re import split
from ast import literal_eval
from threading import Timer
from time import strftime
import numpy as np
import requests
from tower import utils
from tower.map.map_interface import MapInterface
from server_conf.config import settings
HOST = 'localhost'
PORT = 2002
# @todo: think about including in a separate module for exceptions
class CommandNotFound(Exception):
""" Command received does not match one listed in the command dictionary """
pass
class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
"""
Threaded UDP server for receiving and responding to requests from client applications. We can run the server safely
by doing:
Example::
map_server = ThreadedUDPServer((HOST, PORT), UDP_Interrupt)
server_thread = None
logger.info('Instantiation succesful')
# terminate with Ctrl-C
try:
server_thread = Thread(target=map_server.serve_forever)
server_thread.daemon = False
logger.info("Threaded server loop running in: {}".format(server_thread.name))
print("Threaded server loop running in: {}".format(server_thread.name))
server_thread.start()
except KeyboardInterrupt:
server_thread.kill()
map_server.shutdown()
sys.exit(0)
"""
def get_request(self):
"""
Override native get_request function in order to print out who is connecting to the server
@todo make this Python3 compatible by using superclasses. Will need to update socketServer package
:return:
"""
(data, self.socket), client_addr = socketserver.UDPServer.get_request(self)
logger.info("Server connected to by:{}".format(client_addr))
return (data, self.socket), client_addr
class UDP_Interrupt(socketserver.BaseRequestHandler):
"""
This class works similar to the TCP handler class, except that
self.request consists of a pair of data and client sockets, and since
there is no connection the client address must be given explicitly
when sending data back via sendto().
"""
def setup(self):
"""
Instantiate the connection with the worldEngine, the MapInterface.
:rtype : None
"""
# TODO : figure out how to make the map interface a singleton class
if not hasattr(self, 'mapInterface'):
self.mapInterface = MapInterface(settings['FILE_CONFIG']['filename'])
def handle(self):
"""
Handles UDP requests to the server.
The map interface class is responsible for parsing the request, and executing the requested function.
:return:
"""
socket = self.request[1]
data = self.request[0].strip()
logger.info("Address {} at {} wrote: '{}'".format(self.client_address[1], self.client_address[0], data))
cmd_strn, ret = self.command_service(data)
print(ret)
self.command_response(cmd_strn, ret, self.request[1], self.client_address[0],
self.mapInterface.router[cmd_strn])
def command_service(self, rawCommand):
"""
Parse raw input and execute specified function with args
:param rawCommand: csv string from Matlab/Simulink of the form:
'command, namedArg1, arg1, namedArg2, arg2, ..., namedArgN, argN'
:return: the command and arguments as a dictionary
"""
pack = [x.strip() for x in split('[,()]*', rawCommand.strip())]
raw_cmd = pack[0]
argDict = {key: literal_eval(value) for key, value in utils.grouper(pack[1:], 2)}
cmd = self.mapInterface.commands[raw_cmd]
ret = cmd(**argDict)
logger.info("Command '{}' run with args {}".format(raw_cmd, argDict))
return raw_cmd, ret
def command_response(self, returned_data, socket, client_ip, client_address):
"""
Parse raw input and execute specified function with args
:param coords: coordinates in lat/lon
:return: the command and arguments as a dictionary
"""
returned_data.astype(np.float32)
response = returned_data.tostring('C')
response_length = len(response)
response_arr = [response]
if response_length > 256:
response_arr = list(self.split_by_n(response_arr[0], 256 * 4))
data = [response_length]
s = struct.pack('f' * len(data), *data)
socket.sendto(s, (client_ip, client_address))
for response_packet in response_arr:
socket.sendto(response_packet, (client_ip, client_address))
@staticmethod
def split_by_n(seq, n):
"""A generator to divide a sequence into chunks of n units."""
while seq:
yield seq[:n]
seq = seq[n:]
@staticmethod
def func_explode(s):
pattern = r'(\w[\w\d_]*)\((.*)\)$'
match = re.match(pattern, s)
if match:
return list(match.groups())
else:
return []
def finish(self):
pass
class Interrupt(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.daemon = True
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
def call_request(url=None, data=None, headers=None):
url = 'http://httpbin.org/post'
headers = {'content-type': 'application/json'}
time_stamp = strftime("%Y-%m-%d %H:%M:%S")
data = {'flightId': 0o001, 'time': time_stamp, 'latitude': 36, 'longitude': -120, 'altitude': 50, 'speed': 100,
'heading': 0, 'hasLanded': False, 'dataSource': "UCSC"}
r = requests.post(url, json=data, headers=headers)
print(r.status_code)
|
maartenq/pcrunner
|
tests/test_configuration.py
|
# tests/test_configuration.py
# vim: ai et ts=4 sw=4 sts=4 ft=python fileencoding=utf-8
from io import StringIO
from pcrunner.configuration import (
read_check_commands,
read_check_commands_txt,
read_check_commands_yaml,
)
def test_read_check_commmands_txt_with_extra_lines():
fd = StringIO(
u'''SERVICE|CHECK_01|check_dummy.py|0 OK -s 0
SERVICE|CHECK_02|check_dummy.py|1 WARNING -s 10
'''
)
assert read_check_commands_txt(fd) == [
{
'command': u'check_dummy.py 0 OK -s 0',
'name': u'CHECK_01',
'result_type': 'PROCESS_SERVICE_CHECK_RESULT',
},
{
'command': u'check_dummy.py 1 WARNING -s 10',
'name': u'CHECK_02',
'result_type': 'PROCESS_SERVICE_CHECK_RESULT',
},
]
def test_read_check_commmands_yaml():
fd = StringIO(
u'''
- name: 'CHECK_01'
command: 'check_dummy.py 0 OK -s 0'
result_type: 'PROCESS_SERVICE_CHECK_RESULT'
- name: 'CHECK_02'
command: 'check_dummy.py 1 WARNING -s 10'
result_type: 'PROCESS_SERVICE_CHECK_RESULT'
'''
)
assert read_check_commands_yaml(fd) == [
{
'command': u'check_dummy.py 0 OK -s 0',
'name': u'CHECK_01',
'result_type': 'PROCESS_SERVICE_CHECK_RESULT',
},
{
'command': u'check_dummy.py 1 WARNING -s 10',
'name': u'CHECK_02',
'result_type': 'PROCESS_SERVICE_CHECK_RESULT',
},
]
def test_read_check_commands_returns_empyt_list():
assert read_check_commands('/does/not/exists') == []
|
lorian1333/netcopy
|
netcopy.py
|
#!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
if os.name == "nt":
sep = "\\"
else:
sep = '/'
def main():
if len(sys.argv)<2:
usage()
return
if sys.argv[1]=='-s' and len(sys.argv) >= 4:
try:
send()
except KeyboardInterrupt:
printError("\nAbort")
elif sys.argv[1]=='-r':
try:
recieve()
except KeyboardInterrupt:
printError("\nAbort")
else:
usage()
def printError(s):
sys.stderr.write(s+'\n')
def encodeInt(l, size):
if l > ((0x1 << (8*size))-1):
raise ValueError("Number too large: {0}".format(l))
b = bytearray(size)
i = 0
while l > 0:
b[i] = (l & 0xff)
l = l >> 8
i+=1
b.reverse()
return b
def encodeString(s):
return s+b'\x00'
def recieveInt(size, conn):
data = conn.recv(size)
b = bytearray(data)
if len(b) != size:
raise ValueError("Received invalid data")
value = 0
for i in range(0,size):
value = value << 8
value += b[i]
return value
def recieveString(conn):
s = ""
ch = ''
while True:
ch = conn.recv(1)
if ch == b'\x00':
break
s += ch
return s
def send():
port = DEFAULT_PORT
i = 2
files = []
while i < len(sys.argv): #-2
if sys.argv[i]=='-p':
if i+1 >= len(sys.argv):
printError("Expecting port after '-p'")
return
try:
port = int(sys.argv[i+1])
except ValueError:
printError("Invalid port: "+sys.argv[i+1])
return
i+=1
else:
receiver = sys.argv[i]
files = sys.argv[i+1:]
break
i+=1
num_files = 0
open_files = []
for fn in files:
try:
f = open(fn, "rb")
open_files.append((fn, f))
num_files+=1
except IOError as e:
printError("Could not open file {0}: {1}. Skipping".format(fn, e.strerror))
if num_files == 0:
printError("No files to send. Aborting")
return
try:
client = socket.create_connection((receiver, port), CONNECTION_TIMEOUT)
except Exception as e:
message = str(e)
if hasattr(e, 'strerror'):
message = e.strerror
printError("Could not connect to {0}: {1}".format(receiver, message))
return
print("--- Sending {0} file(s) to {1} ---".format(num_files, receiver))
metadata = bytearray()
metadata += encodeInt(num_files, 4)
for (fn, f) in open_files:
metadata += encodeString(fn[fn.rfind(sep)+1:])
f.seek(0,2)
size = f.tell()
print("- Sending {0} ({1} bytes)".format(fn, size))
metadata += encodeInt(size, 8)
client.sendall(metadata)
metadata = bytearray()
f.seek(0,0)
while size > 0:
bytebuf = bytearray(f.read(BUFSIZE))
client.sendall(bytebuf)
size -= BUFSIZE
f.close()
client.close()
def recieve():
port = DEFAULT_PORT
i = 2
while i < len(sys.argv):
if sys.argv[i]=='-p':
if i+1 >= len(sys.argv):
printError("Expecting port after '-p'")
return
try:
port = int(sys.argv[i+1])
except ValueError:
printError("Invalid port: "+sys.argv[i+1])
return
i+=1
else:
printError("Unrecognized argument: "+sys.argv[i])
return
i+=1
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', port))
except Exception as e:
printError("Could not bind socket: {0}".format(e.strerror))
return
print("Waiting for incoming connections...")
server.listen(1)
conn, addr = server.accept()
print("Connected to {0}".format(addr[0]))
num_files = recieveInt(4, conn)
print("Recieving {0} file(s)".format(num_files))
if num_files > (0x1 << 16):
printError("Too many files. Aborting")
return
try:
for i in range(0,num_files):
fn = recieveString(conn)
filesize = recieveInt(8, conn)
print("- {0} ({1} bytes)".format(fn, filesize))
if os.path.isfile(fn):
print(" Error: file '{0}' already exists. Skipping".format(fn))
conn.recv(filesize)
continue
f = open(fn, "wb")
size = filesize
printProgressBar(0)
lastreceivetime = time()
printProgressBar(0)
while size > 0:
buffersize = min(BUFSIZE, size)
data = conn.recv(buffersize)
if len(data) == 0:
if time()-lastreceivetime > RECEIVE_TIMEOUT:
printError("\nReceive timeout. Aborting")
server.close()
return
continue
lastreceivetime = time()
size -= len(data)
f.write(data)
ratio = float(filesize-size)/float(filesize)
printProgressBar(ratio)
printProgressBar(1)
print("")
f.close()
except ValueError:
printError("Protocol error. Aborting")
finally:
server.close()
def printProgressBar(ratio):
if ratio < 0 or ratio > 1:
raise ValueError("Error: invalid ratio: {0}".format(ratio))
progressbar_length = int(ratio * PROGRESSBAR_WIDTH)
progressbar = '#'*progressbar_length + ' '*(PROGRESSBAR_WIDTH-progressbar_length) + " - {0:.2f}%".format(ratio*100.0)
sys.stdout.write("\r"+progressbar)
sys.stdout.flush()
def usage():
print("Usage:\n"
"\t{0} -s [-p port] [receiver] [files...]\t- Send files to receiver\n"
"\t{0} -r [-p port]\t\t\t\t- Receive files"
.format(sys.argv[0][sys.argv[0].rfind(sep)+1:]))
if __name__ == "__main__":
main()
|
leejz/meta-omics-scripts
|
query_ncbi_lineage_from_mgrast_md5.py
|
#!/usr/bin/env python
"""
--------------------------------------------------------------------------------
Created: Jackson Lee 11/4/14
This script reads in a tab delimited file of annotations and queries
asynchronously the MGRAST REST API to parse back the original ncbi tax_id entry.
This script then uses the ncbi tax_id to query the taxonomic lineage.
Input file format:
query sequence id hit m5nr id (md5sum) percentage identity alignment length, number of mismatches number of gap openings query start query end hit start hit end e-value bit score semicolon separated list of annotations
mgm4581121.3|contig-1350000035_45_1_2592_+ 0000679ceb3fc9c950779468e06329a7 61.03 136 53 654 789 366 501 6.80E-44 175 hyalin repeat protein
mgm4581121.3|contig-18000183_1_1_2226_+ 0000679ceb3fc9c950779468e06329a7 64.44 45 16 525 569 457 501 1.70E-08 57 hyalin repeat protein
['Download complete. 78538 rows retrieved']
MGRAST REST API:
http://api.metagenomics.anl.gov/m5nr/md5/<M5nr MD5 hash>?source=GenBank
e.g. http://api.metagenomics.anl.gov/m5nr/md5/000821a2e2f63df1a3873e4b280002a8?source=GenBank
resources:
http://api.metagenomics.anl.gov/api.html#m5nr
http://angus.readthedocs.org/en/2014/howe-mgrast.html
Returns:
{"next":null,"prev":null,"version":"10","url":"http://api.metagenomics.anl.gov//m5nr/md5/000821a2e2f63df1a3873e4b280002a8?source=GenBank&offset=0","data":[{"source":"GenBank","function":"sulfatase","ncbi_tax_id":399741,"accession":"ABV39241.1","type":"protein","organism":"Serratia proteamaculans 568","md5":"000821a2e2f63df1a3873e4b280002a8","alias":["GI:157320144"]}],"limit":10,"total_count":1,"offset":0}
This output will then be stored in a buffer and queried for the exact id and grab the xml based lineage
http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=taxonomy&id=399741
<TaxaSet><Taxon><TaxId>399741</TaxId><ScientificName>Serratia proteamaculans 568</ScientificName><OtherNames><EquivalentName>Serratia proteamaculans str. 568</EquivalentName><EquivalentName>Serratia proteamaculans strain 568</EquivalentName></OtherNames><ParentTaxId>28151</ParentTaxId><Rank>no rank</Rank><Division>Bacteria</Division><GeneticCode><GCId>11</GCId><GCName>Bacterial, Archaeal and Plant Plastid</GCName></GeneticCode><MitoGeneticCode><MGCId>0</MGCId><MGCName>Unspecified</MGCName></MitoGeneticCode><Lineage>cellular organisms; Bacteria; Proteobacteria; Gammaproteobacteria; Enterobacteriales; Enterobacteriaceae; Serratia; Serratia proteamaculans</Lineage>
Output file format:
A tab delimited file of
contig-faa-name\tlineage
an error.log of mismatches from both MGRAST and NCBI is also generated
--------------------------------------------------------------------------------
usage: query_ncbi_lineage_from_mgrast_md5.py -i mgrast_organism.txt -o output.file
"""
#-------------------------------------------------------------------------------
#
##http thread pool from: http://stackoverflow.com/questions/2632520/what-is-the-fastest-way-to-send-100-000-http-requests-in-python
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#Header - Linkers, Libs, Constants
from string import strip
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from threading import Thread
import sys
import time
import requests
import json
from Queue import Queue
#-------------------------------------------------------------------------------
#function declarations
def doWork():
while not exitapp:
id, name, mgrast_urlstring = q.get()
if id % 100 == 0:
print 'Query: HTTP Thread: ' + str(id) + ' started.'
try:
mgrast_response = requests.get(url=mgrast_urlstring, timeout=10)
if mgrast_response.status_code == 200:
json_data = json.loads(mgrast_response.text)
if json_data['data']!= []:
if 'ncbi_tax_id' in json_data['data'][0]:
eutils_urlstring = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=taxonomy&id=' + str(json_data['data'][0]['ncbi_tax_id'])
eutils_response = requests.get(url=eutils_urlstring, timeout=10)
if eutils_response.status_code == 200:
if '<Lineage>' in eutils_response.text:
output_dict[name] = eutils_response.text.split('Lineage>')[1][0:-2]
else:
output_dict[name] = 'No NCBI'
else:
print 'HTTP error, Thread: ' + str(id) + ' in eutils worker with error: ' + eutils_response.reason
logfile.write(str(id) + '\t' + urlstring + '\t' + eutils_response.reason + '\n')
raise
else:
output_dict[name] = 'No MGRAST tax ID'
else:
output_dict[name] = 'No MGRAST source data'
else:
print 'HTTP error, Thread: ' + str(id) + ' in MG-RAST worker with error: ' + mgrast_response.reason
logfile.write(str(id) + '\t' + urlstring + '\t' + mgrast_response.reason + '\n')
raise
except:
print 'Thread: ' + str(id) + '. Error. '
print sys.exc_info()[0]
q.task_done()
#-------------------------------------------------------------------------------
#Body
print "Running..."
if __name__ == '__main__':
parser = ArgumentParser(usage = "query_ncbi_lineage_from_mgrast_md5.py -i \
mgrast_organism.txt -o output.file",
description=__doc__,
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("-i", "--input_file", action="store",
dest="inputfilename",
help="tab-delimited MGRAST organism file")
parser.add_argument("-o", "--output_filename", action="store",
dest="outputfilename",
help="tab-delimited output file")
options = parser.parse_args()
mandatories = ["outputfilename","inputfilename"]
for m in mandatories:
if not options.__dict__[m]:
print "\nError: Missing Arguments\n"
parser.print_help()
exit(-1)
inputfilename = options.inputfilename
outputfilename = options.outputfilename
infile_list = []
with open(inputfilename,'U') as infile:
infile_list = [line.strip().split('\t') for line in infile]
infile.close()
urlpool = []
name_list = []
for entry in infile_list[1:-1]:
contig_name = entry[0]
md5_hash = entry[1]
urlpool.append([contig_name, 'http://api.metagenomics.anl.gov/m5nr/md5/' + md5_hash + '?source=RefSeq'])
name_list.append(contig_name)
concurrent = 10
exitapp = False
output_dict = {}
print "Querying MGRAST REST API Service..."
with open('./' + outputfilename + '.errorlog.txt','w') as logfile:
q = Queue(concurrent * 2)
for i in range(concurrent):
t = Thread(target=doWork)
t.daemon = True
time.sleep(1)
t.start()
try:
for id, url_load in enumerate(urlpool):
q.put([id] + url_load)
q.join()
except KeyboardInterrupt:
exitapp = True
sys.exit(1)
logfile.close()
logfile.close()
print "Matching taxonomies and writing..."
with open(outputfilename, 'w') as outfile:
for name in name_list:
if name in output_dict:
outfile.write(name + '\t' + output_dict[name] + '\n')
else:
outfile.write(name + '\t' + 'None\n')
outfile.close()
print "Done!"
|
posborne/mlcollection
|
mlcollection/lib/collaborativefiltering/pearson.py
|
"""Implementation of Pearson collaborative filtering algorithm"""
from math import sqrt, pow
from mlcollection.lib.collaborativefiltering.collaborativefilterbase import \
AbstractCollaborativeFilter
from operator import itemgetter
from scipy import stats, isnan
__author__ = 'Paul Osborne <osbpau@gmail.com>'
class PearsonCollaborativeFilter(AbstractCollaborativeFilter):
"""Filter based on the Pearson correlation score between items/individuals
The Pearson correlation score or coefficient is a measure of how well two
sets of data fit onto a straight line. There is some added complexity
when compared to the Euclidean filtering algorithm, but the Pearson
algorithm does a better job of dealing with data which is not normalized.
An example where data is not normalized might be examining movie reviews.
It may be the case that some reviewers are just more harsh than other
reviewers. In this case we cannot just draw conclusions about shared
interest based on the score, we need to look a bit deeper to see if there
really is a correlation between the preferences of these two people.
The Pearson algorithm, when finding the similarity between two inviduals,
first finds the subset of data that the two members have each rated/scored.
Then, the score is calculated (using some statistics) based on the sum of
the squares of the ratings and the sum of the products of the ratings.
The formula for pearson's product-moment coefficent is as follows:
.. math::
\rho_{X,Y}={\mathrm{cov}(X,Y) \over \sigma_X \sigma_Y} ={E[(X-\mu_X)(Y-\mu_Y)] \over \sigma_X\sigma_Y}
which in the statistics world is often just referred to as `corr(x,y)`.
"""
def __init__(self, ranked_dataset=None):
AbstractCollaborativeFilter.__init__(self, ranked_dataset)
def get_recommendations(self, individual):
"""Find recommendedations for this individual
Given the individual return a dictionary where the keys are the items
and the values are ratings for the movie for the individual. The
higher the rating, the more likely it is that the individual may like
the movie.
"""
dataset = self.ranked_dataset
totals = {}
sim_sums = {}
ind_items = set(dataset[individual].keys())
for other in (x for x in dataset if x != individual):
shared_items = ind_items & set(dataset[other].keys())
# get a measure of how similar individual and other are
if len(shared_items) == 0:
continue
x = [dataset[individual][i] for i in shared_items]
y = [dataset[other][i] for i in shared_items]
coeff = stats.pearsonr(x, y)[0]
if coeff < 0 or isnan(coeff):
continue
for item in set(dataset[other]) - ind_items:
if not item in sim_sums:
sim_sums[item] = 0
totals[item] = 0
sim_sums[item] += coeff * dataset[other][item]
totals[item] += coeff
rankings = {}
for item in totals:
rankings[item] = sim_sums[item] / totals[item]
return rankings
|
grantstephens/pyluno
|
setup.py
|
from setuptools import setup, find_packages
with open('pyluno/meta.py') as f:
exec(f.read())
setup(
name='pyluno',
version=__version__,
packages=find_packages(exclude=['tests']),
description='A Luno API for Python',
author='Cayle Sharrock/Grant Stephens',
author_email='grant@stephens.co.za',
scripts=['demo.py'],
install_requires=[
'futures>=3.0.3',
'nose>=1.3.7',
'requests>=2.8.1',
'pandas>=0.17.0',
],
license='MIT',
url='https://github.com/grantstephens/pyluno',
download_url='https://github.com/grantstephens/pyluno/tarball/%s'
% (__version__, ),
keywords='Luno Bitcoin exchange API',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Office/Business :: Financial',
'Topic :: Utilities',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
test_suite='tests',
extras_require={
'test': ['requests-mock>=0.7.0', 'nose'],
}
)
|
underlost/GamerNews
|
gamernews/apps/news/fields.py
|
import re
from django.db.models import fields
from django.template.defaultfilters import slugify
def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'):
slug_field = instance._meta.get_field(slug_field_name)
slug_len = slug_field.max_length
# Sort out the initial slug. Chop its length down if we need to.
slug = slugify(value)
if slug_len:
slug = slug[:slug_len]
slug = _slug_strip(slug, slug_separator)
original_slug = slug
# Create a queryset, excluding the current instance.
if queryset is None:
queryset = instance.__class__._default_manager.all()
if instance.pk:
queryset = queryset.exclude(pk=instance.pk)
# Find a unique slug. If one matches, at '-2' to the end and try again
# (then '-3', etc).
next = 2
while not slug or queryset.filter(**{slug_field_name: slug}):
slug = original_slug
end = '-%s' % next
if slug_len and len(slug) + len(end) > slug_len:
slug = slug[:slug_len-len(end)]
slug = _slug_strip(slug, slug_separator)
slug = '%s%s' % (slug, end)
next += 1
setattr(instance, slug_field.attname, slug)
return slug
def _slug_strip(value, separator=None):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of the
default '-' separator with the new separator.
"""
if separator == '-' or not separator:
re_sep = '-'
else:
re_sep = '(?:-|%s)' % re.escape(separator)
value = re.sub('%s+' % re_sep, separator, value)
return re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)
class AutoSlugField(fields.SlugField):
"""Auto slug field, creates unique slug for model."""
def __init__(self, prepopulate_from, *args, **kwargs):
"""Create auto slug field.
If field is unique, the uniqueness of the slug is ensured from existing
slugs by adding extra number at the end of slug.
If field has slug given, it is used instead. If you want to re-generate
the slug, just set it :const:`None` or :const:`""` so it will be re-
generated automatically.
:param prepopulate_from: Must be assigned to list of field names which
are used to prepopulate automatically.
:type prepopulate_from: sequence
"""
self.prepopulate_separator = kwargs.get("prepopulate_separator", u"-")
self.prepopulate_from = prepopulate_from
kwargs["blank"] = True
super(fields.SlugField, self).__init__(*args, **kwargs)
def pre_save(self, model_instance, add): #@UnusedVariable
"""Pre-save event"""
current_slug = getattr(model_instance, self.attname)
# Use current slug instead, if it is given.
# Assumption: There are no empty slugs.
if not (current_slug is None or current_slug == ""):
slug = current_slug
else:
slug = self.prepopulate_separator.\
join(unicode(getattr(model_instance, prepop))
for prepop in self.prepopulate_from)
if self.unique:
return _unique_slugify(model_instance, value=slug,
slug_field_name=self.attname)
else:
return slugify(slug)[:self.max_length]
|
TheDSCPL/SSRE_2017-2018_group8
|
Projeto/Python/cryptopy/crypto/keyedHash/hmacHash.py
|
# -*- coding: utf-8 -*-
""" hmacHash.py
Implemention of Request for Comments: 2104
HMAC: Keyed-Hashing for Message Authentication
HMAC is a mechanism for message authentication
using cryptographic hash functions. HMAC can be used with any
iterative cryptographic hash function, e.g., MD5, SHA-1, in
combination with a secret shared key. The cryptographic strength of
HMAC depends on the properties of the underlying hash function.
This implementation of HMAC uses a generic cryptographic 'hashFunction'
(self.H). Hash functions must conform to the crypto.hash method
conventions and are not directly compatible with the Python sha1 or md5 algorithms.
[IETF] RFC 2104 "HMAC: Keyed-Hashing for Message Authentication"
>>>key = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>keyedHashAlg = HMAC(SHA1, key)
>>>result = keyedHashAlg(data)
"""
from crypto.hash.hash import Hash
class HMAC(Hash):
""" To compute HMAC over the data `text' we perform
H(K XOR opad, H(K XOR ipad, text))
"""
def __init__(self, hashFunction, key = None):
""" initialize HMAC with hashfunction and optionally the key """
# should check for right type of function
self.H = hashFunction() # a new instance for inner hash
self.H_outer = hashFunction() # separate outer context to allow intermediate digests
self.B = self.H.raw_block_size # in bytes, note - hash block size typically 1
# and raw_block_size much larger
# e.g. raw_block_size is 64 bytes for SHA1 and MD5
self.name = 'HMAC_'+self.H.name
self.blocksize = 1 # single octets can be hashed by padding to raw block size
self.raw_block_size = self.H.raw_block_size
self.digest_size = self.H.digest_size
if key != None:
self.setKey(key)
else:
self.keyed = None
def setKey(self,key):
""" setKey(key) ... key is binary string """
if len(key) > self.B: # if key is too long then hash it
key = self.H(key) # humm... this is odd, hash can be smaller than B
else: # should raise error on short key, but breaks tests :-(
key =key + (self.B-len(key)) * chr(0)
self.k_xor_ipad = ''.join([chr(ord(bchar)^0x36) for bchar in key])
self.k_xor_opad = ''.join([chr(ord(bchar)^0x5C) for bchar in key])
self.keyed = 1
self.reset()
def reset(self):
self.H.reset()
if self.keyed == None :
raise 'no key defined'
self.H.update(self.k_xor_ipad) # start inner hash with key xored with ipad
# outer hash always called as one full pass (no updates)
def update(self,data):
if self.keyed == None :
raise 'no key defined'
self.H.update(data)
def digest(self):
if self.keyed == None :
raise 'no key defined'
return self.H_outer(self.k_xor_opad+self.H.digest())
from crypto.hash.sha1Hash import SHA1
class HMAC_SHA1(HMAC):
""" Predefined HMAC built on SHA1 """
def __init__(self, key = None):
""" optionally initialize with key """
HMAC.__init__(self,SHA1,key)
from crypto.hash.md5Hash import MD5
class HMAC_MD5(HMAC):
""" Predefined HMAC built on SHA1 """
def __init__(self, key = None):
""" optionally initialize with key """
HMAC.__init__(self,MD5,key)
|
koxudaxi/BacklogPy
|
tests/backlog/test_base.py
|
from __future__ import absolute_import
import six
if six.PY3:
from unittest import TestCase, mock
else:
import sys
if sys.version_info < (2, 7, 0):
from unittest2 import TestCase
else:
from unittest import TestCase
import mock
from BacklogPy.base import BacklogBase
class TestBacklogBase(TestCase):
def test_api_url(self):
backlog_base = BacklogBase('space-id', 'api-key')
self.assertEqual(backlog_base._api_url,
'https://space-id.backlog.jp/api/v2')
backlog_base = BacklogBase('space-id', 'api-key', suffix='com')
self.assertEqual(backlog_base._api_url,
'https://space-id.backlog.com/api/v2')
def test_request(self):
with mock.patch('requests.request') as m:
backlog_base = BacklogBase('space-id', 'api-key')
backlog_base._request('/path')
args, kwargs = m.call_args_list[0]
self.assertTupleEqual(args, ('GET',
'https://space-id.backlog.jp/api/v2/path'))
self.assertDictEqual(kwargs,
{'params': {'apiKey': 'api-key'}, 'data': {},
'headers': {}})
with mock.patch('requests.request') as m:
backlog_base._request('/path', method='POST')
args, kwargs = m.call_args_list[0]
self.assertTupleEqual(args,
('POST',
'https://space-id.backlog.jp/api/v2/path'))
self.assertDictEqual(kwargs,
{'params': {'apiKey': 'api-key'}, 'data': {},
'headers': {}})
with mock.patch('requests.request') as m:
backlog_base._request('/path', method='POST',
query_parameters={'id': 123})
args, kwargs = m.call_args_list[0]
self.assertTupleEqual(args,
('POST',
'https://space-id.backlog.jp/api/v2/path'))
self.assertDictEqual(kwargs,
{'params': {'apiKey': 'api-key', 'id': 123},
'data': {},
'headers': {}})
with mock.patch('requests.request') as m:
backlog_base._request('/path', method='POST',
query_parameters={'id': 123},
form_parameters={'name': 'abc'})
args, kwargs = m.call_args_list[0]
self.assertTupleEqual(args,
('POST',
'https://space-id.backlog.jp/api/v2/path'))
self.assertDictEqual(kwargs,
{'params': {'apiKey': 'api-key', 'id': 123},
'data': {'name': 'abc'},
'headers': {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}})
|
msabramo/pycobertura
|
tests/test_cobertura.py
|
import mock
import lxml.etree as ET
from .utils import make_cobertura
def test_parse_path():
from pycobertura import Cobertura
xml_path = 'foo.xml'
with mock.patch('pycobertura.cobertura.os.path.exists', return_value=True):
with mock.patch('pycobertura.cobertura.ET.parse') as mock_parse:
cobertura = Cobertura(xml_path)
assert cobertura.xml is mock_parse.return_value.getroot.return_value
def test_version():
cobertura = make_cobertura()
assert cobertura.version == '1.9'
def test_line_rate():
cobertura = make_cobertura()
assert cobertura.line_rate() == 0.9
def test_line_rate_by_class():
cobertura = make_cobertura()
expected_line_rates = {
'Main': 1.0,
'search.BinarySearch': 0.9166666666666666,
'search.ISortedArraySearch': 1.0,
'search.LinearSearch': 0.7142857142857143,
}
for class_name in cobertura.classes():
assert cobertura.line_rate(class_name) == \
expected_line_rates[class_name]
def test_branch_rate():
cobertura = make_cobertura()
assert cobertura.branch_rate() == 0.75
def test_branch_rate_by_class():
cobertura = make_cobertura()
expected_branch_rates = {
'Main': 1.0,
'search.BinarySearch': 0.8333333333333334,
'search.ISortedArraySearch': 1.0,
'search.LinearSearch': 0.6666666666666666,
}
for class_name in cobertura.classes():
assert cobertura.branch_rate(class_name) == \
expected_branch_rates[class_name]
def test_total_misses():
cobertura = make_cobertura()
assert cobertura.total_misses() == 3
def test_missed_statements_by_class_name():
cobertura = make_cobertura()
expected_missed_statements = {
'Main': [],
'search.BinarySearch': [24],
'search.ISortedArraySearch': [],
'search.LinearSearch': [19, 24],
}
for class_name in cobertura.classes():
assert cobertura.missed_statements(class_name) == \
expected_missed_statements[class_name]
def test_list_packages():
cobertura = make_cobertura()
packages = cobertura.packages()
assert packages == ['', 'search']
def test_list_classes():
cobertura = make_cobertura()
classes = cobertura.classes()
assert classes == [
'Main',
'search.BinarySearch',
'search.ISortedArraySearch',
'search.LinearSearch'
]
def test_hit_lines__by_iterating_over_classes():
cobertura = make_cobertura()
expected_lines = {
'Main': [10, 16, 17, 18, 19, 23, 25, 26, 28, 29, 30],
'search.BinarySearch': [12, 16, 18, 20, 21, 23, 25, 26, 28, 29, 31],
'search.ISortedArraySearch': [],
'search.LinearSearch': [9, 13, 15, 16, 17],
}
for class_name in cobertura.classes():
assert cobertura.hit_statements(class_name) == expected_lines[class_name]
def test_missed_lines():
cobertura = make_cobertura()
expected_lines = {
'Main': [],
'search.BinarySearch': [24],
'search.ISortedArraySearch': [],
'search.LinearSearch': [19, 20, 21, 22, 23, 24],
}
for class_name in cobertura.classes():
assert cobertura.missed_lines(class_name) == expected_lines[class_name]
def test_total_statements():
cobertura = make_cobertura()
assert cobertura.total_statements() == 30
def test_total_statements_by_class():
cobertura = make_cobertura()
expected_total_statements = {
'Main': 11,
'search.BinarySearch': 12,
'search.ISortedArraySearch': 0,
'search.LinearSearch': 7,
}
for class_name in cobertura.classes():
assert cobertura.total_statements(class_name) == \
expected_total_statements[class_name]
def test_total_misses():
cobertura = make_cobertura()
assert cobertura.total_misses() == 3
def test_total_misses_by_class():
cobertura = make_cobertura()
expected_total_misses = {
'Main': 0,
'search.BinarySearch': 1,
'search.ISortedArraySearch': 0,
'search.LinearSearch': 2,
}
for class_name in cobertura.classes():
assert cobertura.total_misses(class_name) == \
expected_total_misses[class_name]
def test_total_hits():
cobertura = make_cobertura()
assert cobertura.total_hits() == 27
def test_total_hits_by_class():
cobertura = make_cobertura()
expected_total_misses = {
'Main': 11,
'search.BinarySearch': 11,
'search.ISortedArraySearch': 0,
'search.LinearSearch': 5,
}
for class_name in cobertura.classes():
assert cobertura.total_hits(class_name) == \
expected_total_misses[class_name]
def test_filename():
cobertura = make_cobertura()
expected_filenames = {
'Main': 'Main.java',
'search.BinarySearch': 'search/BinarySearch.java',
'search.ISortedArraySearch': 'search/ISortedArraySearch.java',
'search.LinearSearch': 'search/LinearSearch.java',
}
for class_name in cobertura.classes():
assert cobertura.filename(class_name) == \
expected_filenames[class_name]
def test_filepath():
base_path = 'foo/bar/baz'
cobertura = make_cobertura(base_path=base_path)
expected_filepaths = {
'Main': 'foo/bar/baz/Main.java',
'search.BinarySearch': 'foo/bar/baz/search/BinarySearch.java',
'search.ISortedArraySearch': 'foo/bar/baz/search/ISortedArraySearch.java',
'search.LinearSearch': 'foo/bar/baz/search/LinearSearch.java',
}
for class_name in cobertura.classes():
assert cobertura.filepath(class_name) == \
expected_filepaths[class_name]
def test_class_source__sources_not_found():
cobertura = make_cobertura('tests/cobertura.xml')
expected_sources = {
'Main': [(0, 'tests/Main.java not found', None)],
'search.BinarySearch': [(0, 'tests/search/BinarySearch.java not found', None)],
'search.ISortedArraySearch': [(0, 'tests/search/ISortedArraySearch.java not found', None)],
'search.LinearSearch': [(0, 'tests/search/LinearSearch.java not found', None)],
}
for class_name in cobertura.classes():
assert cobertura.class_source(class_name) == expected_sources[class_name]
def test_line_statuses():
cobertura = make_cobertura('tests/dummy.source1/coverage.xml')
expected_line_statuses = {
'dummy/__init__': [],
'dummy/dummy': [
(1, True),
(2, True),
(4, True),
(5, False),
(6, False),
],
'dummy/dummy2': [
(1, True),
(2, True),
],
'dummy/dummy4': [
(1, False),
(2, False),
(4, False),
(5, False),
(6, False)
],
}
for class_name in cobertura.classes():
assert cobertura.line_statuses(class_name) == \
expected_line_statuses[class_name]
def test_class_source__sources_found():
cobertura = make_cobertura('tests/dummy.source1/coverage.xml')
expected_sources = {
'dummy/__init__': [],
'dummy/dummy': [
(1, 'def foo():\n', True),
(2, ' pass\n', True),
(3, '\n', None),
(4, 'def bar():\n', True),
(5, " a = 'a'\n", False),
(6, " b = 'b'\n", False),
],
'dummy/dummy2': [
(1, 'def baz():\n', True),
(2, ' pass\n', True)
],
'dummy/dummy4': [
(1, 'def barbaz():\n', False),
(2, ' pass\n', False),
(3, '\n', None),
(4, 'def foobarbaz():\n', False),
(5, ' a = 1 + 3\n', False),
(6, ' pass\n', False)
],
}
for class_name in cobertura.classes():
assert cobertura.class_source(class_name) == \
expected_sources[class_name]
|
RyanEggert/space-lander
|
rocket_control/printvals.py
|
import time
from usb_vendor import PIC_USB
import traceback
# Product IDs: Master PIC is 0x0004, Rocket PIC is 0x0005, Barge PIC is 0x0006
comms = PIC_USB(0x0005)
def main():
print("START")
loop_time = .2 # How often to run the main loop, in seconds
while True:
start_time = time.clock()
# print(chr(27) + "[2J")
# quad_info()
try:
# debug_uart_buffers()
# debug_uart_status()
rocket_info()
endstops()
# debug_oc_status()
except Exception, e:
print "Error occurred. {}".format(e)
traceback.print_exc()
print "Retrying..."
comms = PIC_USB(0x0005)
while (time.clock() - start_time) < loop_time:
pass
def rocket_info():
info = comms.get_rocket_info()
print "Rocket Tilt {} | Rocket Speed {} | Throttle {} | Motor Speed {} | Motor Thrust {} | Stepper Speed {} | Tilt Angle {} | Tilt Direction {} | Rocket State {}".format(
info["tilt"],
info["speed"],
info["throttle"],
info["motor_speed"],
info["motor_thrust"],
info["stepper_speed"],
info["tilt_ang"],
info["tilt_dir"],
info["rocket_state"],
)
def debug_uart_buffers():
info = comms.debug_uart_buffers()
rx = info["rx"]
tx = info["tx"]
print "TX_head {} | TX_tail {} | TX_count {} || RX_head {} | RX_tail {} | RX_count {}".format(
tx["head"],
tx["tail"],
tx["count"],
rx["head"],
rx["tail"],
rx["count"],
)
def debug_uart_status():
info = comms.debug_uart_status()
uart1 = info["uart1"]
uart2 = info["uart2"]
print "[UART1] URXDA: {} | OERR {} | FERR {} || PERR {} | RIDLE {} | ADDEN {}".format(
uart1["URXDA"],
uart1["OERR"],
uart1["FERR"],
uart1["PERR"],
uart1["RIDLE"],
uart1["ADDEN"]
)
print "[UART2] URXDA: {} | OERR {} | FERR {} || PERR {} | RIDLE {} | ADDEN {}".format(
uart2["URXDA"],
uart2["OERR"],
uart2["FERR"],
uart2["PERR"],
uart2["RIDLE"],
uart2["ADDEN"]
)
def debug_oc_status():
info = comms.debug_oc_status()
print "DC_OCM0 {} | DC_OCM1 {} | DC_OCM2 {} | DC_OCTSEL {} | DC_OCFLT {}".format(
info["DC_OCM0"],
info["DC_OCM1"],
info["DC_CM2"],
info["DC_OCTSEL"],
info["DC_OCFLT"],
)
print "ST_OCM0 {} | ST_OCM1 {} | ST_OCM2 {} | ST_OCTSEL {} | ST_OCFLT {}".format(
info["ST_OCM0"],
info["ST_OCM1"],
info["ST_CM2"],
info["ST_OCTSEL"],
info["ST_OCFLT"]
)
def current_state():
info = comms.get_state()
print "Current State {}".format(
info["state"],
)
def quad_info():
info = comms.get_quad_info()
print "Quad Counter {} | Overflow {}".format(
info["counter"],
info["overflow"],
)
def endstops():
"""
Reads the system's endstops.
"""
info = comms.get_limit_sw_info()
print("Y_BOT {} | Y_TOP {} | X_L {} | X_R {} | BARGE {} ".format(
info["Y_BOT"],
info["Y_TOP"],
info["X_L"],
info["X_R"],
info["BARGE"])
)
if __name__ == '__main__':
main()
|
gingi99/research_dr
|
python/FPgrowth/orange_fpgrowth.py
|
# coding: utf-8
# python 3.5
import Orange
from orangecontrib.associate.fpgrowth import *
import pandas as pd
import numpy as np
import sys
import os
from collections import defaultdict
from itertools import chain
from itertools import combinations
from itertools import compress
from itertools import product
from sklearn.metrics import accuracy_score
from multiprocessing import Pool
from multiprocessing import freeze_support
# Global Setting
DIR_UCI = '/mnt/data/uci'
# ------------------------------------------------------
# Rule Class
# ------------------------------------------------------
class Rule :
def __init__(self):
self.value = list()
self.consequent = list()
self.support = float()
self.conf = float()
def setValue(self, values) :
self.value = values
def setConsequent(self, consequents) :
self.consequent = consequents
def setSupport(self, supports) :
self.support = supports
def setConf(self, confidence) :
self.conf = confidence
def getValue(self) :
return(self.value)
def getConsequent(self) :
return(self.consequent)
def getSupport(self) :
return(self.support)
def getSupportD(self) :
return(self.support * len(self.value))
def getConf(self) :
return(self.conf)
def output(self) :
print("value:" + str(self.value))
print("consequent:" + str(self.consequent))
print("support:" + str(self.support))
print("conf:" + str(self.conf))
# ======================================================
# Rules のうち、P個の属性値が分かれば、クラスを推定できるか
# ======================================================
def getPerIdentifiedClass(rules, p) :
attribute_values = [rule.getValue() for rule in rules]
attribute_values = list(chain.from_iterable(attribute_values))
attribute_values = list(set(attribute_values))
combi_attribute_values = combinations(attribute_values,p)
count = 0
bunbo = 0
for combi in combi_attribute_values :
bunbo += 1
rules_target = []
for rule in rules :
matching_count = len(list(set(combi) & set(rule.getValue())))
if matching_count == len(list(combi)) :
rules_target.append(rule)
# rules_target が空なら評価から外す
if len(rules_target) == 0:
bunbo -= 1
#
else :
consequents = [rule.getConsequent() for rule in rules_target]
if len(list(set(consequents))) == 1:
count += 1
if bunbo == 0:
ans = 0
else:
ans = (float(count) / float(bunbo))
return(ans)
# ======================================================
# ルールが対象のクラスを説明するかどうか
# ======================================================
def isExplainRule(obj, rule) :
matching_count = len(list(set(obj) & set(rule.getValue())))
if matching_count == len(rule.getValue()) : return(True)
else : return(False)
# ======================================================
# ルールが対象のクラスを説明するかどうか
# ======================================================
def getMatchingFactor(obj, rule) :
matching_factor = len(list(set(obj) & set(rule.getValue())))
matching_factor = matching_factor / len(rule.getValue())
return(matching_factor)
# ======================================================
# ルールのsupport P を返す
# ======================================================
def getSupportP(obj, rule) :
matching_factor = getMatchingFactor(obj, rule)
return(rule.getSupportD() * matching_factor)
# ======================================================
# ルールから対象のクラスを予測
# ======================================================
def estimateClass(obj, rules) :
list_judge = [isExplainRule(obj, r) for r in rules]
# 1つ以上マッチするなら
if any(list_judge) :
consequents = [rules[i].getConsequent() for i, judge in enumerate(list_judge) if judge]
# マッチしたルールが推論するクラスの数がただ1つなら
if len(set(consequents)) == 1 :
return(consequents[0])
else :
rules_match = list(compress(rules,list_judge))
supportD = [r.getSupportD() for r in rules_match]
return(rules_match[supportD.index(max(supportD))].getConsequent())
# rule が objに1つもマッチしない場合は部分一致ルールによる推定
else :
supportP = [getSupportP(obj, rule) for rule in rules]
return(rules[supportP.index(max(supportP))].getConsequent())
# ======================================================
# LERS による精度評価
# ======================================================
def predictByLERS(FILENAME, iter1, iter2, rules) :
# read test data
filepath = DIR_UCI+'/'+FILENAME+'/alpha/'+FILENAME+'-test'+str(iter1)+'-'+str(iter2)+'.txt'
decision_table_test = pd.read_csv(filepath, delimiter=' ', header=None)
decision_table_test = decision_table_test.dropna()
decision_class = decision_table_test[decision_table_test.columns[-1]].values.tolist()
decision_table_test = decision_table_test.drop(decision_table_test.columns[len(decision_table_test.columns)-1], axis=1)
decision_table_test = decision_table_test.values.tolist()
# LERS で予測
predictions = []
for obj in decision_table_test:
estimated_class = estimateClass(obj, rules)
predictions.append(estimated_class)
# 正答率を求める
accuracy = accuracy_score(decision_class, predictions)
print(accuracy)
return(accuracy)
# =====================================
# Main 関数
# =====================================
def getRulesByFPGrowth(FILENAME, classes, iter1, iter2, minsup, minconf) :
# read data
filepath = DIR_UCI+'/'+FILENAME+'/alpha/'+FILENAME+'-train'+str(iter1)+'-'+str(iter2)+'.txt'
data_pd = pd.read_csv(filepath, delimiter=' ')
pd.DataFrame.to_csv(data_pd, DIR_UCI+'/'+FILENAME+'/alpha/'+FILENAME+'-train'+str(iter1)+'-'+str(iter2)+'.basket', index=False, sep=',')
filepath = DIR_UCI+'/'+FILENAME+'/alpha/'+FILENAME+'-train'+str(iter1)+'-'+str(iter2)+'.basket'
data_table = Orange.data.Table(filepath)
#print len(data_table)
# set parameter
num_lines = sum(1 for line in open(filepath))
minsup = float(minsup) / float(num_lines)
#
#itemsets = frequent_itemsets(data_table, minsup)
#print(itemsets)
#print(list(itemsets))
X, mapping = OneHot.encode(data_table, include_class=True)
#print(X)
itemsets = dict(frequent_itemsets(X, minsup))
#print(itemsets)
#print(len(itemsets))
rules = [(P, Q, supp, conf) for P, Q, supp, conf in association_rules(itemsets, minconf) if len(Q) == 1]
#print(rules)
names = {item: '{}={}'.format(var.name, val) for item, var, val in OneHot.decode(mapping, data_table, mapping)}
for ante, cons, supp, conf in rules:
print(', '.join(names[i] for i in ante), '-->', names[next(iter(cons))], '(supp: {}, conf: {})'.format(supp, conf))
# induce rules
#rules_orange = Orange.associate.AssociationRulesSparseInducer(data_table, support=minsup, confidence=minconf)
#rules_orange = Orange.associate.AssociationRulesSparseInducer(data_table, support = minsup, max_item_sets = 2000)
# convert Rule Class
#rules = []
#for rule_orange in rules_orange :
# consequent = rule_orange.right.get_metas(str).keys()
# if len(consequent) == 1 and consequent[0] in classes and rule_orange.confidence >= minconf :
# rule = Rule()
# rule.setValue(rule_orange.left.get_metas(str).keys())
# rule.setConsequent(consequent[0])
# rule.setSupport(rule_orange.support)
# rule.setConf(rule_orange.confidence)
# rules.append(rule)
# END
#return(rules)
# ======================================================
# Apriori_LERS
# ======================================================
def Apriori_LERS(FILENAME, classes, iter1, iter2, min_sup, min_conf):
# rule 抽出
rules = getRulesByApriori(FILENAME, classes, iter1, iter2, min_sup, min_conf)
# predict by LERS
accuracy = predictByLERS(FILENAME, iter1, iter2, rules)
# save
savepath = DIR_UCI+'/'+FILENAME+'/Apriori_LERS.csv'
with open(savepath, "a") as f :
f.writelines('Apriori_LERS,{min_sup},{FILENAME},{iter1},{iter2},{acc}'.format(FILENAME=FILENAME,iter1=iter1,iter2=iter2,acc=accuracy,min_sup=min_sup)+"\n")
# END
return(accuracy)
def wrapper_Apriori_LERS(multi_args):
multi_args[0](multi_args[1],multi_args[2],multi_args[3],multi_args[4],multi_args[5],multi_args[6])
# ========================================
# listの平均と分散を求める
# ========================================
def getEvalMeanVar(result):
ans = '{mean}±{std}'.format(mean=('%.3f' % round(np.mean(results),3)), std=('%.3f' % round(np.std(results),3)))
return(ans)
# ========================================
# multi に実行する
# ========================================
def multi_main(proc, FILENAME, FUN, **kargs):
pool = Pool(proc)
results = []
multiargs = []
classes = kargs['classes']
min_sup_range = kargs['min_sup'] if 'min_sup' in kargs else range(2,11)
min_conf = kargs['min_conf']
# Apriori_LERS 用
if FUN == Apriori_LERS :
WRAPPER_FUN = wrapper_Apriori_LERS
for iter1, iter2, min_sup in product(range(1,11), range(1,11), min_sup_range):
multiargs.append((FUN, FILENAME, classes, iter1, iter2, min_sup, min_conf))
#print(multiargs)
results = pool.map(WRAPPER_FUN, multiargs)
else :
print("I dont' know the function.")
return(results)
# ========================================
# main
# ========================================
if __name__ == "__main__":
FILENAME = 'hayes-roth'
FILENAME = 'german_credit_categorical'
# number of class
classes = ['D1', 'D2', 'D3']
classes = ['D1', 'D2',]
iter1 = 10
iter2 = 3
# support と confidence の閾値
#min_sup_range = range(2,11,1)
#min_sup_range = range(2,20,2)
min_sup = 100
min_conf = 1.0
# rule induction
getRulesByFPGrowth(FILENAME, classes, iter1, iter2, min_sup, min_conf)
#print len(rules)
#for r in rules:
# print(r.output())
# predict by LERS
#print(predictByLERS(FILENAME, iter1, iter2, rules))
# 並列実行して全データで評価
#proc=32
#freeze_support()
#FUN = Apriori_LERS
#results = multi_main(proc, FILENAME, FUN, classes = classes, min_sup = min_sup_range, min_conf = min_conf)
|
chriskuech/wavelab
|
pitchanalysis.py
|
#!/usr/bin/env python
"""
pitchanalysis.py
--
Christopher Kuech
cjkuech@gmail.com
--
Requires:
Python 2.7
Instructions:
python pitchanalysis.py [wav-file-name]
"""
import matplotlib
from math import log
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import pyaudio
import sys
from time import time, sleep
import Tkinter as tk
import wavelab
(WIDTH, HEIGHT) = (800, 500)
FNAME = './Bach.wav' if len(sys.argv) != 2 else sys.argv[1]
font = ('Helvetica', 14, 'bold')
CHUNK = 1024
def audioworker():
"""the function run on the audio thread"""
global frame
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2),
channels=1, rate=4*44100, output=True)
# unknown why rate is off by 4x
while True:
stream.write(data[frame:frame+CHUNK].tostring())
frame = (frame + CHUNK) % len(wav)
stream.stop_stream()
stream.close()
p.terminate()
def graphicsworker():
"""the function run on the graphics thread"""
while True:
start = time()
p = ptype.get()
w = wsize.get()
wty = wtype.get()
# compute frequencies from clip
clip = data[frame:frame+w]
if wty == "hanning":
clip *= np.hanning(w)
elif wty == "hamming":
clip *= np.hamming(w)
freqs = wavelab.frequencies(clip)
# update plot
xs = np.sort(freqs.keys())
ys = np.array(map(freqs.get, xs))
axes.cla()
(xmax, ymin, ymax) = (10e4, 0.000001, 10e2)
# (xlim, ylim) = (_, (ymin, ymax)) = ((0, 1e4), (1e-3, 1e7))
axes.set_xscale("log")
axes.set_yscale("linear")
axes.set_xlim((1, xmax))
if p == "square":
# axes.set_yscale("linear")
axes.set_ylim((ymin**2, ymax**2))
ys = ys * ys
elif p == "dB":
# axes.set_yscale("log")
axes.set_ylim((log(ymin), log(ymax)))
ys = np.log(ys)
elif p == "-dB":
# axes.set_yscale("log")
axes.set_ylim((-log(ymax), -log(ymin)))
ys = -np.log(ys)
elif p == "linear":
# axes.set_yscale("linear")
axes.set_ylim((ymin, ymax))
axes.plot(xs, ys, 'r-')
canvas.show()
# pitch tracker
freq = max(freqs, key=lambda f: freqs[f])
pitch.set(wavelab.pitch(freq).replace('/','\n'))
# attempt to achieve 30fps animation (at best)
dt = time() - start
sleep(max(0, 1.0/30.0 - dt))
# read wave file
(framerate, wav) = wavelab.readwav(FNAME)
data = np.concatenate((wav, wav)) # avoid out of bounds
frame = 0
# create a GUI instance (do before any use of Tkinter)
root = tk.Tk()
root.wm_title("Frequency Spectrogram")
# these objects hold the variables from the widgets
wsize = tk.IntVar() # window size (in frames)
wsize.set(2205)
wtype = tk.StringVar() # type of windowing to use
wtype.set("rectangle")
ptype = tk.StringVar() # type of power to use
ptype.set("square")
pitch = tk.StringVar() # the current pitch
pitch.set("")
widgetps = lambda n, v: {'variable': v, 'text': n, 'value': n}
# returns the dict of kwargs that initialize a widget
# create the canvas widget and add it to the GUI
# canvas = tk.Canvas(root, borderwidth=0, width=WIDTH, height=HEIGHT, bg='#000')
# canvas.grid(row=0, column=0, columnspan=4)
# canvas.show()
canvasframe = tk.Frame(root, width=WIDTH, height=HEIGHT)
canvasframe.grid(row=0, column=0, columnspan=4)
figure = Figure()
axes = figure.add_axes( (0.1, 0.1, 0.8, 0.8), frameon=True,
xlabel="Frequency (Hz)", ylabel="Power")
canvas = FigureCanvasTkAgg(figure, canvasframe)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
canvas.show()
# create the wtype controller and add it to the GUI
tk.Label(root, font=font, text="Windowing").grid(row=1, column=0, pady=10)
wframe = tk.Frame(root)
wframe.grid(row=2, column=0, pady=10, sticky="n")
tk.Radiobutton(wframe, **widgetps("rectangle", wtype)).grid(sticky="w", row=0)
tk.Radiobutton(wframe, **widgetps("hamming" , wtype)).grid(sticky="w", row=1)
tk.Radiobutton(wframe, **widgetps("hanning" , wtype)).grid(sticky="w", row=2)
# create the wsize controller and add it to the GUI
tk.Label(root, font=font, text="Window Size").grid(row=1, column=1, pady=10)
tk.Scale(root, variable=wsize, orient=tk.HORIZONTAL, from_=10, to=4410).grid(row=2, column=1, sticky="wen")
# create the ptype controller and add it to the GUI
tk.Label(root, font=font, text="Power").grid(row=1, column=2, pady=10)
pframe = tk.Frame(root)
pframe.grid(row=2, column=2, pady=10, sticky="n")
tk.Radiobutton(pframe, **widgetps("square", ptype)).grid(sticky="w", row=0)
tk.Radiobutton(pframe, **widgetps("dB", ptype)).grid(sticky="w", row=1)
tk.Radiobutton(pframe, **widgetps("-dB", ptype)).grid(sticky="w", row=2)
tk.Radiobutton(pframe, **widgetps("linear", ptype)).grid(sticky="w", row=3)
# create the area where the pitchlabel is displayed
tk.Label(root, font=font, text="Pitch").grid(row=1, column=3, pady=10)
(fontfamily, fontsize, fontweight) = font
pitchfont = (fontfamily, 24, fontweight)
pitchlabel = tk.Label(root, font=pitchfont, textvariable=pitch, width=7).grid(row=2, column=3)
# start the other threads
wavelab.thread(audioworker)
wavelab.thread(graphicsworker)
# start the main update loop for the GUI (and block)
tk.mainloop()
|
mohikhsan/px-labeler
|
px-labeler/pxgui/ui_pxmarkerdialog.py
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pxmarkerdialog.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_PxMarkerDialog(object):
def setupUi(self, PxMarkerDialog):
PxMarkerDialog.setObjectName("PxMarkerDialog")
PxMarkerDialog.resize(400, 300)
self.btn_confirm_box = QtWidgets.QDialogButtonBox(PxMarkerDialog)
self.btn_confirm_box.setGeometry(QtCore.QRect(290, 20, 81, 241))
self.btn_confirm_box.setOrientation(QtCore.Qt.Vertical)
self.btn_confirm_box.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.btn_confirm_box.setObjectName("btn_confirm_box")
self.pxmarker_table_widget = QtWidgets.QTableWidget(PxMarkerDialog)
self.pxmarker_table_widget.setGeometry(QtCore.QRect(10, 20, 271, 261))
self.pxmarker_table_widget.setEditTriggers(QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed)
self.pxmarker_table_widget.setObjectName("pxmarker_table_widget")
self.pxmarker_table_widget.setColumnCount(3)
self.pxmarker_table_widget.setRowCount(0)
item = QtWidgets.QTableWidgetItem()
self.pxmarker_table_widget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.pxmarker_table_widget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.pxmarker_table_widget.setHorizontalHeaderItem(2, item)
self.pxmarker_table_widget.horizontalHeader().setDefaultSectionSize(50)
self.pxmarker_table_widget.horizontalHeader().setMinimumSectionSize(40)
self.pxmarker_table_widget.horizontalHeader().setStretchLastSection(True)
self.pxmarker_table_widget.verticalHeader().setVisible(False)
self.pxmarker_table_widget.verticalHeader().setHighlightSections(False)
self.retranslateUi(PxMarkerDialog)
self.btn_confirm_box.accepted.connect(PxMarkerDialog.accept)
self.btn_confirm_box.rejected.connect(PxMarkerDialog.reject)
QtCore.QMetaObject.connectSlotsByName(PxMarkerDialog)
def retranslateUi(self, PxMarkerDialog):
_translate = QtCore.QCoreApplication.translate
PxMarkerDialog.setWindowTitle(_translate("PxMarkerDialog", "Edit Pixel Markers"))
item = self.pxmarker_table_widget.horizontalHeaderItem(0)
item.setText(_translate("PxMarkerDialog", "Class"))
item = self.pxmarker_table_widget.horizontalHeaderItem(1)
item.setText(_translate("PxMarkerDialog", "Color"))
item = self.pxmarker_table_widget.horizontalHeaderItem(2)
item.setText(_translate("PxMarkerDialog", "Feature"))
|
wnavarre/email-dictator
|
web/run_on.py
|
import sys
import os
import files.io
from StringIO import StringIO
from constants import *
added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script")
sys.path.append(added_path)
import script
import mess
sys.path.pop()
def full_file(pointer):
pointer.seek(0)
return pointer.read()
def send_confirmation_email(recipient, contents):
connection = script.get_mailserver_connection()
email_headers = {
"Subject": CONFIRMATION_EMAIL_SUBJECT,
"To": recipient,
"From": CONFIRMATION_EMAIL_FROM
}
mess.Message(email_headers, contents).send(connection)
connection.quit()
def run_on(key, actually_send=False, confirmation_email=CONFIRMATION_EMAIL_FROM, confirmation_email_on_success=True, confirmation_email_on_fail=True, special_text="", send_default_confirmation=False):
input_files = files.io.get(key)
assert "template" in input_files, "Need to submit non-empty template"
assert "spreadsheet" in input_files, "Need to submit non-empty spreadsheet"
output_location = StringIO()
kwargs = {}
if send_default_confirmation:
pass
else:
kwargs["send_confirmation_to"] = None
if "constants" in input_files:
kwargs["constants"] = StringIO(input_files["constants"])
success = script.run_script(
StringIO(input_files["template"]),
StringIO(input_files["spreadsheet"]),
output=output_location,
actually_send=actually_send,
**kwargs
)
script_results = special_text + full_file(output_location)
if confirmation_email and ((confirmation_email_on_success and success) or (confirmation_email_on_fail and not success)):
send_confirmation_email(confirmation_email, script_results)
return script_results, success
|
zegra1989/pytree
|
rtree.py
|
# -*- coding:utf-8 -*-
# 使用 UTF-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import sys
from heap import Heap
class Rectangle(object):
"""docstring for Rectangle"""
def __init__(self, dimension, entry=None):
super(Rectangle, self).__init__()
self.dimension = dimension
self.min_dim = [None for _ in xrange(dimension)]
self.max_dim = [None for _ in xrange(dimension)]
if entry is not None:
for ipos in xrange(self.dimension):
self.min_dim[ipos] = entry[ipos]
self.max_dim[ipos] = entry[ipos]
def resize(self, rects):
"""
通过给定的 子节点Rectangle列表
重新计算当前 Rectangle 的 MBR(Minimal Boundary Rect)
"""
for ipos in xrange(self.dimension):
self.min_dim[ipos] = min(map(lambda x: x.min_dim[ipos], rects))
self.max_dim[ipos] = max(map(lambda x: x.max_dim[ipos], rects))
def resize2(self, entry):
"""
通过给定的 entry,
重新计算当前 Rectangle 的 MBR(Minimal Boundary Rect)
entry 代表一条数据的所有维度
"""
for ipos in xrange(self.dimension):
if entry[ipos] < self.min_dim[ipos]:
self.min_dim[ipos] = entry[ipos]
elif entry[ipos] > self.max_dim[ipos]:
self.max_dim[ipos] = entry[ipos]
def expand_area(self, entry):
new_area = 1.0
curr_area = 1.0
for ipos in xrange(self.dimension):
max_value = self.max_dim[ipos]
min_value = self.min_dim[ipos]
try:
curr_area *= (max_value - min_value)
except TypeError as e:
# 未完全初始化的 Rectangle
return -1
if entry[ipos] > self.max_dim[ipos]:
max_value = entry[ipos]
elif entry[ipos] < self.min_dim[ipos]:
min_value = entry[ipos]
try:
new_area *= (max_value - min_value)
except TypeError as e:
# 未完全初始化的 Rectangle
return -1
return new_area - curr_area
def overlap_area(self, rect):
area = 1.0
for ipos in xrange(self.dimension):
try:
if self.max_dim[ipos] < rect.max_dim[ipos]:
factor = self.max_dim[ipos] - rect.min_dim[ipos]
else:
factor = rect.max_dim[ipos] - self.min_dim[ipos]
except TypeError as e:
# 未完全初始化的 Rectangle
return -1
if factor < 0:
return 0.0
area *= factor
return area
def __contains__(self, rect):
for ipos in xrange(self.dimension):
if self.max_dim[ipos] < rect.min_dim[ipos]:
return False
if self.min_dim[ipos] > rect.max_dim[ipos]:
return False
return True
def __str__(self):
return "Min:{0}, Max:{1}".format(
self.min_dim, self.max_dim)
class RNode(object):
def __init__(self, degree, dimension):
super(RNode, self).__init__()
self.num = 0
self.isleaf = True
self.degree = degree
self.dimension = dimension
if dimension < 2:
raise Exception("请使用 B/B+树 代替")
if dimension > 6:
print "WARNING:R树推荐维度为 [2,6]"
self.mbr = Rectangle(self.dimension)
self.threshold = degree*2
self.rects = [None for _ in xrange(self.threshold)]
self.pnodes = [None for _ in xrange(self.threshold)]
def adjust(self):
self.mbr = Rectangle(self.dimension)
self.mbr.resize(self.rects[:self.num])
def involve(self, entry):
self.mbr.resize2(entry)
def pointer(self):
return self
def most_overlap_pos(self, ipos):
"""
从 self.pnodes 中找到与 self.pnodes[ipos] 重合度最大的点的位置
"""
child = self.pnodes[ipos]
ichild_pos, max_overlap, max_overlap_pos = 0, -1, 0
while ichild_pos < self.num:
if ipos == ichild_pos:
continue
overlap = child.overlap_area(self.pnodes[ichild_pos].mbr)
if max_overlap < overlap:
max_overlap = overlap
max_overlap_pos = ichild_pos
ichild_pos += 1
return max_overlap_pos
class DataNode(object):
"""docstring for DataNode"""
def __init__(self, max_length=10):
super(DataNode, self).__init__()
self.num = 0
self.data = None
self.max_length = max_length
base, mode = divmod(self.max_length, 2)
if mode > 0:
base += 1
self.min_length = base
self.mbr = Rectangle(self.dimension)
class RTree(object):
"""docstring for RTree"""
def __init__(self, degree, dimension):
super(RTree, self).__init__()
self.degree = degree
self.dimension = dimension
self.threshold = degree*2
self.root = self.allocate_namenode()
def allocate_namenode(self):
raise NotImplementedError()
def deallocate_namenode(self, node):
raise NotImplementedError()
def allocate_datanode(self):
raise NotImplementedError()
def deallocate_datanode(self, node):
raise NotImplementedError()
def save_docs(self, metanode):
raise NotImplementedError()
def load_docs(self, metanode, ipos):
raise NotImplementedError()
def search(self, rect, node=None):
if node is None:
node = self.root
indexes = []
ipos = node.num-1
while ipos >= 0:
if rect in node.rects[ipos]:
indexes.append(ipos)
ipos -= 1
if len(indexes) == 0:
return []
if node.isleaf is True:
return map(lambda x: self.load_docs(node.pnodes[x]), indexes)
results = []
for ipos in indexes:
results.extend(self.search(rect, node.pnodes[ipos]))
return results
def split(self, parent, ipos, node):
"""
由于 R树 中节点内部是无序的,为了减少移动数据的开销
分裂后的两个节点一个放在分裂前节点的位置,一个放在末尾
目前分裂的简单算法:
直接选取第一个点当作旧节点的核心rect
计算旧核心rect与其他rect的重合度
选取重合度最低的一个rect作为新节点的核心rect
计算新核心rect与其他rect的重合度
对比每个非核心rect与两个核心的重合度
选出与新核心重合度更高的 degree-1 个节点组成新节点
"""
if parent.isleaf is False:
new_node = self.allocate_namenode()
new_node.isleaf = node.isleaf
ancor = node.rects[0]
heap = Heap(node.pnodes, reverse=True,
key=lambda x: ancor.overlap_area(x.mbr))
ipos = 0
while ipos < node.degree:
new_node.pnodes[ipos] = heap.pop()
new_node.rects[ipos] = new_node.pnodes[ipos].mbr
ipos += 1
new_node.num = node.degree
new_node.adjust()
ipos = 0
length = len(heap)
while ipos < length:
node.pnodes[ipos] = heap.heap[ipos]
node.pnodes[ipos].adjust()
node.rects[ipos] = heap.heap[ipos].mbr
ipos += 1
node.num = length
node.adjust()
parent.pnodes[parent.num-1] = new_node.pointer()
parent.rects[parent.num-1] = new_node.mbr
parent.num += 1
return None
new_node = node.split()
parent.pnodes[parent.num-1] = new_node.pointer()
parent.rects[parent.num-1] = new_node.mbr
parent.num += 1
return None
def insert(self, entry, doc):
"""
entry 是长度为 self.dimension 的数组
entry 中每一个维度都需要是数值型
"""
if self.root.num != self.threshold:
return self.insert_nonfull(self.root, entry, doc)
old_root = self.root
new_root = self.allocate_namenode()
new_root.isleaf = False
new_root.pnodes[0] = old_root.pointer()
new_root.rects[0] = old_root.mbr
new_root.num += 1
self.root = new_root
self.split(new_root, 0, old_root)
return self.insert_nonfull(new_root, entry, doc)
def insert_nonfull(self, node, entry, doc):
ipos = 0
min_expand = sys.maxint
min_expand_pos = 0
while ipos < node.num:
expand_area = node.pnodes[ipos].mbr.expand_area(entry)
if min_expand > expand_area:
min_expand = expand_area
min_expand_pos = ipos
ipos += 1
ipos = min_expand_pos
node.involve(entry)
if node.isleaf is True:
datanode = node.pnodes[ipos]
if datanode is None:
datanode = self.allocate_datanode()
node.pnodes[ipos] = datanode
node.num += 1
# 此处不用连接 DataNode 的链表,因为此处仅在初始化时运行一次
if datanode.isfull() is True:
self.split(node, ipos, datanode)
if node.pnodes[ipos].mbr.expand_area(entry) < \
node.pnodes[ipos+1].mbr.expand_area(entry):
ipos += 1
datanode = node.pnodes[ipos]
datanode.insert(entry, doc)
node.rects[ipos] = datanode.mbr
return None
child = node.pnodes[ipos]
if child.num == self.threshold:
self.split(node, ipos, child)
if node.pnodes[ipos].mbr.expand_area(entry) < \
node.pnodes[ipos+1].mbr.expand_area(entry):
child = node.pnodes[ipos+1]
return self.insert_nonfull(child, entry, doc)
def merge(self, node, ipos):
"""
将当前节点 位置(ipos) 对应的孩子与其重合面积最大的兄弟合并
"""
child = node.pnodes[ipos]
# 在 node 中寻找与 child 重合面积最大的兄弟
max_overlap_pos = node.most_overlap_pos(ipos)
mchild = node.pnodes[max_overlap_pos]
if node.isleaf is True:
child.merge(mchild)
self.deallocate_datanode(mchild)
else:
impos = 0
while impos < mchild.num:
child.rects[child.num+impos] = mchild.rects[impos]
child.pnodes[child.num+impos] = mchild.pnodes[impos]
impos += 1
child.num += mchild.num
child.adjust()
self.deallocate_namenode(mchild)
node.rects[max_overlap_pos] = node.rects[node.num-1]
node.pnodes[max_overlap_pos] = node.pnodes[node.num-1]
node.num -= 1
# node 的 mbr 没有变化,不用调用 adjust()
return ipos
def guarantee(self, node, ipos):
"""
确保 node.pnodes[ipos] 拥有至少 t 个孩子
注意: node 一定是非叶子节点
"""
child = node.pnodes[ipos]
if child.num > self.degree:
return ipos
# 在 node 中寻找与 child 重合面积最大的兄弟
ichild_pos, max_overlap, max_overlap_pos = 0, -1, -1
while ichild_pos < node.num:
if ipos == ichild_pos:
continue
candidate = node.pnodes[ichild_pos]
if candidate.num <= self.degree:
continue
overlap = child.overlap_area(candidate.mbr)
if max_overlap < overlap:
max_overlap = overlap
max_overlap_pos = ichild_pos
ichild_pos += 1
if max_overlap_pos > 0:
mchild = node.pnodes[max_overlap_pos]
# 在 mchild 中找到与 child 重合度最高的点, 将其合并到 child.pnodes 中
ichild_pos, max_overlap, max_overlap_pos = 0, -1, 0
while ichild_pos < mchild.num:
overlap = child.overlap_area(mchild.pnodes[ichild_pos].mbr)
if max_overlap < overlap:
max_overlap = overlap
max_overlap_pos = ichild_pos
ichild_pos += 1
child.pnodes[child.num] = mchild.pnodes[max_overlap_pos]
child.rects[child.num] = mchild.rects[max_overlap_pos]
child.num += 1
child.adjust()
impos = max_overlap_pos
while impos < mchild.num-1:
mchild.rects[impos] = mchild.rects[impos+1]
mchild.pnodes[impos] = mchild.pnodes[impos+1]
impos += 1
mchild.num -= 1
mchild.adjust()
return ipos
return self.merge(node, ipos)
def remove_key(self, node, entry):
ipos = 0
indexes = []
min_expand, min_expand_pos = sys.maxint, 0
while ipos < node.num:
expand_area = node.pnodes[ipos].mbr.expand_area(entry)
if expand_area == 0:
indexes.append(ipos)
ipos += 1
if len(indexes) == 0:
return None
if node.isleaf is False:
icpos = self.guarantee(node, ipos)
child = node.pnodes[icpos]
self.remove_key(child, entry)
# TODO
if len(indexes) == 0:
return []
if node.isleaf is True:
return map(lambda x: self.load_docs(node.pnodes[x]), indexes)
results = []
for ipos in indexes:
results.extend(self.search(rect, node.pnodes[ipos]))
return results
|
DeppSRL/open_bilanci
|
bilanci_project/bilanci/settings/staging.py
|
"""Production settings and globals."""
from base import *
########## HOST CONFIGURATION
# See: https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production
MAIN_HOST = ['openbilanci.staging.deppsviluppo.org',]
# Allowed hosts expansion: needed for servizi ai Comuni
HOSTS_COMUNI = [
'novara.comuni.deppsviluppo.org',
'rapallo.comuni.deppsviluppo.org',
'castiglionedellestiviere.comuni.deppsviluppo.org',
'firenze.comuni.deppsviluppo.org',
'terni.comuni.deppsviluppo.org'
]
ALLOWED_HOSTS += MAIN_HOST + HOSTS_COMUNI
########## END HOST CONFIGURATION
########## EMAIL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
########## END EMAIL CONFIGURATION
########## TOOLBAR CONFIGURATION
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
INSTALLED_APPS += (
'debug_toolbar',
)
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
INTERNAL_IPS = ('176.31.74.29',)
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
MIDDLEWARE_CLASSES = (
'debug_toolbar.middleware.DebugToolbarMiddleware',
) + MIDDLEWARE_CLASSES
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'SHOW_TEMPLATE_CONTEXT': True,
}
def show_toolbar(request):
print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR'])
return True
SHOW_TOOLBAR_CALLBACK = show_toolbar
DEBUG_TOOLBAR_PATCH_SETTINGS=False
########## END TOOLBAR CONFIGURATION
BILANCI_PATH = "/home/open_bilanci/dati/bilanci_subset"
OUTPUT_FOLDER = '../scraper_project/scraper/output/'
LISTA_COMUNI = 'listacomuni.csv'
LISTA_COMUNI_PATH = OUTPUT_FOLDER + LISTA_COMUNI
PATH_PREVENTIVI = BILANCI_PATH+"/%s/%s/Preventivo/%s.html"
PATH_CONSUNTIVI = BILANCI_PATH+"/%s/%s/Consuntivo/%s.html"
BILANCI_RAW_DB = 'bilanci_raw'
|
chuck1/web_sheets
|
old/web_sheets_django/manage.py
|
#!/usr/bin/env python3
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web_sheets_django.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
angelsanz/linkstore
|
linkstore/links.py
|
import os
from os import path
import sqlite3
from .link import Link
class Links(object):
def __init__(self):
self._links = {}
def add(self, link):
self._links[link.url] = link
def find_by_tag(self, tag):
return [link for link in self._links.values() if tag in link.tags]
def get_all(self):
return self._links.values()
def remove(self, link):
del self._links[link.url]
def find_by_url(self, url):
return self._links[url]
class SqliteLinks(object):
def __init__(self, table_gateways):
self._links_table = table_gateways['links']
self._tags_table = table_gateways['tags']
def add(self, link):
self._links_table.save(link.url, link.date)
self._tags_table.reset_tags(link.url, link.tags)
def find_by_tag(self, tag):
found = []
for url in self._tags_table.get_urls_of_links_with_tag(tag):
date = self._links_table.get_date(url)
tags = self._tags_table.get_tags(url)
found.append(Link(url, tags, date))
return found
def get_all(self):
all_links = []
for url, date in self._links_table.get_all():
tags = self._tags_table.get_tags(url)
all_links.append(Link(url, tags, date))
return all_links
def remove(self, link):
self._tags_table.remove_tags(link.url)
self._links_table.remove_url_and_date(link.url)
def find_by_url(self, url):
date = self._links_table.get_date(url)
tags = self._tags_table.get_tags(url)
return Link(url, tags, date)
class SqliteTable(object):
def __init__(self, sqlite_connection):
self._connection = sqlite_connection
self._set_up()
def _set_up(self):
with self._connection as connection:
connection.execute(self.SQL_COMMAND_FOR_TABLE_CREATION)
class LinksTable(SqliteTable):
SQL_COMMAND_FOR_TABLE_CREATION = '''
create table if not exists links(
url
primary key
not null,
date_saved
not null
)
'''
def get_all(self):
with self._connection as connection:
return connection.execute('select url, date_saved from links').fetchall()
def save(self, url, date):
with self._connection as connection:
connection.execute(
'insert or ignore into links(url, date_saved) values(?, ?)',
(url, date)
)
def get_date(self, url):
with self._connection as connection:
row = connection.execute(
'select date_saved from links where url = ?',
(url,)
).fetchone()
date = row[0]
return date
def remove_url_and_date(self, url):
with self._connection as connection:
connection.execute('delete from links where url = ?', (url,))
class TagsTable(SqliteTable):
SQL_COMMAND_FOR_TABLE_CREATION = '''
create table if not exists tags(
url
not null,
name
not null,
foreign key(url) references links(url)
on delete restrict
on update restrict
)
'''
def get_urls_of_links_with_tag(self, tag):
with self._connection as connection:
list_of_rows = connection.execute(
'select url from tags where name = ?',
(tag,)
).fetchall()
return tuple(url for (url,) in list_of_rows)
def get_tags(self, url):
with self._connection as connection:
list_of_rows = connection.execute(
'select name from tags where url = ?',
(url,)
).fetchall()
return tuple(tag for (tag,) in list_of_rows)
def reset_tags(self, url, tags):
self.remove_tags(url)
self.add_tags(url, tags)
def remove_tags(self, url):
with self._connection as connection:
connection.execute('delete from tags where url = ?', (url,))
def add_tags(self, url, tags):
with self._connection as connection:
connection.executemany(
'insert into tags(url, name) values(?, ?)',
[(url, tag) for tag in tags]
)
class SqliteConnectionFactory(object):
@staticmethod
def create_autoclosing_on_disk():
return AutoclosingSqliteConnection()
@classmethod
def create_in_memory(cls):
connection_to_in_memory_database = sqlite3.connect(':memory:')
cls._enable_enforcement_of_foreign_key_constraints(connection_to_in_memory_database)
return connection_to_in_memory_database
@staticmethod
def _enable_enforcement_of_foreign_key_constraints(sqlite_connection):
sqlite_connection.execute('pragma foreign_keys = on')
@classmethod
def create_on_disk(cls, data_directory):
connection_to_on_disk_database = sqlite3.connect(data_directory.path_to_database_file)
cls._enable_enforcement_of_foreign_key_constraints(connection_to_on_disk_database)
return connection_to_on_disk_database
class AutoclosingSqliteConnection(object):
def __init__(self, provider_of_sqlite_connection=None):
self._provider_of_sqlite_connection = provider_of_sqlite_connection if provider_of_sqlite_connection is not None \
else ProviderOfConnectionToOnDiskSqliteDatabase()
def __enter__(self):
self._current_connection = self._provider_of_sqlite_connection.get()
self._current_connection.__enter__()
return self._current_connection
def __exit__(self, type_, value, traceback):
self._current_connection.__exit__(type_, value, traceback)
self._current_connection.close()
return False
class ProviderOfConnectionToOnDiskSqliteDatabase(object):
def __init__(self):
self._directory = ApplicationDataDirectory()
def get(self):
return SqliteConnectionFactory.create_on_disk(self._directory)
class ApplicationDataDirectory(object):
@property
def path(self):
return path.expanduser('~/.linkstore/')
@property
def name_of_database_file(self):
return 'linkstore.sqlite'
@property
def path_to_database_file(self):
self._ensure_data_directory_exists()
return path.join(self.path, self.name_of_database_file)
def _ensure_data_directory_exists(self):
if path.exists(self.path):
return
os.mkdir(self.path)
|
sigma-geosistemas/django-tenants
|
dts_test_project/dts_test_project/settings.py
|
"""
Django settings for dts_test_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TENANT_APPS_DIR = os.path.join(BASE_DIR, os.pardir)
sys.path.insert(0, TENANT_APPS_DIR)
sys.path.insert(0, BASE_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'cl1)b#c&xmm36z3e(quna-vb@ab#&gpjtdjtpyzh!qn%bc^xxn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
SHARED_APPS = (
'django_tenants', # mandatory
'customers', # you must list the app where your tenant model resides in
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
TENANT_APPS = (
'dts_test_app',
)
TENANT_MODEL = "customers.Client" # app.Model
TENANT_DOMAIN_MODEL = "customers.Domain" # app.Model
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]
ROOT_URLCONF = 'dts_test_project.urls'
WSGI_APPLICATION = 'dts_test_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django_tenants.postgresql_backend',
'NAME': 'dts_test_project',
'USER': 'postgres',
'PASSWORD': os.environ.get('DATABASE_PASSWORD', 'root'),
'HOST': os.environ.get('DATABASE_HOST', 'localhost'),
'PORT': '',
}
}
DATABASE_ROUTERS = (
'django_tenants.routers.TenantSyncRouter',
)
MIDDLEWARE = (
'tenant_tutorial.middleware.TenantTutorialMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
)
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
|
kyon-bll/.dotfiles
|
.emacs.d/elpa/jedi-core-20191011.1750/jediepcserver.py
|
#!/usr/bin/env python
"""
Jedi EPC server.
Copyright (C) 2012 Takafumi Arakaki
Author: Takafumi Arakaki <aka.tkf at gmail.com>
This file is NOT part of GNU Emacs.
Jedi EPC server 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.
Jedi EPC server 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 Jedi EPC server.
If not, see <http://www.gnu.org/licenses/>.
"""
import argparse
import glob
import itertools
import logging
import logging.handlers
import os
import re
import site
import sys
from collections import namedtuple
import jedi
import jedi.api
import epc
import epc.server
import sexpdata
logger = logging.getLogger('jediepcserver')
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description=__doc__)
parser.add_argument(
'--address', default='localhost')
parser.add_argument(
'--port', default=0, type=int)
parser.add_argument(
'--port-file', '-f', default='-', type=argparse.FileType('wt'),
help='file to write port on. default is stdout.')
parser.add_argument(
'--sys-path', '-p', default=[], action='append',
help='paths to be inserted at the top of `sys.path`.')
parser.add_argument(
'--sys-path-append', default=[], action='append',
help='paths to be appended at the end of `sys.path`.')
parser.add_argument(
'--virtual-env', '-v', default=[], action='append',
help='paths to be used as if VIRTUAL_ENV is set to it.')
parser.add_argument(
'--log', help='Save server log to this file.')
parser.add_argument(
'--log-level',
choices=['CRITICAL', 'ERROR', 'WARN', 'INFO', 'DEBUG'],
help='Logging level for log file.')
parser.add_argument(
'--log-rotate-max-size', default=0, type=int,
help='Rotate log file after it reaches this size',
)
parser.add_argument(
'--log-rotate-max-count', default=3, type=int,
help='Max number of log rotations before removal',
)
parser.add_argument(
'--log-traceback', action='store_true', default=False,
help='Include traceback in logging output.')
parser.add_argument(
'--pdb', dest='debugger', const='pdb', action='store_const',
help='start pdb when error occurs.')
parser.add_argument(
'--ipdb', dest='debugger', const='ipdb', action='store_const',
help='start ipdb when error occurs.')
PY3 = (sys.version_info[0] >= 3)
NEED_ENCODE = not PY3
LogSettings = namedtuple(
'LogSettings',
[
'log_file',
'log_level',
'log_rotate_max_size',
'log_rotate_max_count',
],
)
try:
jedi.create_environment
except AttributeError:
jedi_create_environment = None
else:
_cached_jedi_environments = {}
def jedi_create_environment(venv, safe=False):
"""Cache jedi environments to avoid startup cost."""
try:
return _cached_jedi_environments[venv]
except KeyError:
logger.info('Creating jedi environment: %s', venv)
if venv is None:
jedienv = jedi.api.environment.get_default_environment()
else:
jedienv = jedi.create_environment(venv, safe=safe)
_cached_jedi_environments[venv] = jedienv
return jedienv
def get_venv_sys_path(venv):
if jedi_create_environment is not None:
return jedi_create_environment(venv).get_sys_path()
from jedi.evaluate.sys_path import get_venv_path
return get_venv_path(venv)
class JediEPCHandler(object):
def __init__(self, sys_path=(), virtual_envs=(), sys_path_append=()):
self.script_kwargs = self._get_script_path_kwargs(
sys_path=sys_path,
virtual_envs=virtual_envs,
sys_path_append=sys_path_append,
)
def get_sys_path(self):
environment = self.script_kwargs.get('environment')
if environment is not None:
return environment.get_sys_path()
sys_path = self.script_kwargs.get('sys_path')
if sys_path is not None:
return sys_path
return sys.path
@classmethod
def _get_script_path_kwargs(cls, sys_path, virtual_envs, sys_path_append):
result = {}
if jedi_create_environment:
# Need to specify some environment explicitly to workaround
# https://github.com/davidhalter/jedi/issues/1242. Otherwise jedi
# will create a lot of child processes.
if virtual_envs:
primary_env, virtual_envs = virtual_envs[0], virtual_envs[1:]
primary_env = path_expand_vars_and_user(primary_env)
else:
primary_env = None
try:
result['environment'] = jedi_create_environment(primary_env)
except Exception:
logger.warning(
'Cannot create environment for %r', primary_env, exc_info=1
)
if primary_env is not None:
result['environment'] = jedi_create_environment(None)
if not sys_path and not virtual_envs and not sys_path_append:
# No additional path customizations.
return result
# Either multiple environments or custom sys_path extensions are
# specified, or jedi version doesn't support environments.
final_sys_path = []
final_sys_path.extend(path_expand_vars_and_user(p) for p in sys_path)
for p in virtual_envs:
final_sys_path.extend(get_venv_sys_path(path_expand_vars_and_user(p)))
final_sys_path.extend(
path_expand_vars_and_user(p) for p in sys_path_append
)
dupes = set()
def not_seen_yet(val):
if val in dupes:
return False
dupes.add(val)
return True
result['sys_path'] = [p for p in final_sys_path if not_seen_yet(p)]
return result
def jedi_script(self, source, line, column, source_path):
if NEED_ENCODE:
source = source.encode('utf-8')
source_path = source_path and source_path.encode('utf-8')
return jedi.Script(
source, line, column, source_path or '', **self.script_kwargs
)
def complete(self, *args):
def _wrap_completion_result(comp):
try:
docstr = comp.docstring()
except Exception:
logger.warning(
"Cannot get docstring for completion %s", comp, exc_info=1
)
docstr = ""
return dict(
word=comp.name,
doc=docstr,
description=candidates_description(comp),
symbol=candidate_symbol(comp),
)
return [
_wrap_completion_result(comp)
for comp in self.jedi_script(*args).completions()
]
def get_in_function_call(self, *args):
sig = self.jedi_script(*args).call_signatures()
call_def = sig[0] if sig else None
if not call_def:
return []
return dict(
# p.description should do the job. But jedi-vim use replace.
# So follow what jedi-vim does...
params=[PARAM_PREFIX_RE.sub('', p.description).replace('\n', '')
for p in call_def.params],
index=call_def.index,
call_name=call_def.name,
)
def _goto(self, method, *args):
"""
Helper function for `goto_assignments` and `usages`.
:arg method: `jedi.Script.goto_assignments` or `jedi.Script.usages`
:arg args: Arguments to `jedi_script`
"""
# `definitions` is a list. Each element is an instances of
# `jedi.api_classes.BaseOutput` subclass, i.e.,
# `jedi.api_classes.RelatedName` or `jedi.api_classes.Definition`.
definitions = method(self.jedi_script(*args))
return [dict(
column=d.column,
line_nr=d.line,
module_path=d.module_path if d.module_path != '__builtin__' else [],
module_name=d.module_name,
description=d.description,
) for d in definitions]
def goto(self, *args):
return self._goto(jedi.Script.goto_assignments, *args)
def related_names(self, *args):
return self._goto(jedi.Script.usages, *args)
def get_definition(self, *args):
definitions = self.jedi_script(*args).goto_definitions()
return [definition_to_dict(d) for d in definitions]
def defined_names(self, *args):
# XXX: there's a bug in Jedi that returns returns definitions from inside
# classes or functions even though all_scopes=False is set by
# default. Hence some additional filtering is in order.
#
# See https://github.com/davidhalter/jedi/issues/1202
top_level_names = [
defn
for defn in jedi.api.names(*args)
if defn.parent().type == 'module'
]
return list(map(get_names_recursively, top_level_names))
def get_jedi_version(self):
return [dict(
name=module.__name__,
file=getattr(module, '__file__', []),
version=get_module_version(module) or [],
) for module in [sys, jedi, epc, sexpdata]]
def candidate_symbol(comp):
"""
Return a character representing completion type.
:type comp: jedi.api.Completion
:arg comp: A completion object returned by `jedi.Script.completions`.
"""
try:
return comp.type[0].lower()
except (AttributeError, TypeError):
return '?'
def candidates_description(comp):
"""
Return `comp.description` in an appropriate format.
* Avoid return a string 'None'.
* Strip off all newlines. This is required for using
`comp.description` as candidate summary.
"""
desc = comp.description
return _WHITESPACES_RE.sub(' ', desc) if desc and desc != 'None' else ''
_WHITESPACES_RE = re.compile(r'\s+')
PARAM_PREFIX_RE = re.compile(r'^param\s+')
"""RE to strip unwanted "param " prefix returned by param.description."""
def definition_to_dict(d):
return dict(
doc=d.docstring(),
description=d.description,
desc_with_module=d.desc_with_module,
line_nr=d.line,
column=d.column,
module_path=d.module_path,
name=getattr(d, 'name', []),
full_name=getattr(d, 'full_name', []),
type=getattr(d, 'type', []),
)
def get_names_recursively(definition, parent=None):
"""
Fetch interesting defined names in sub-scopes under `definition`.
:type names: jedi.api_classes.Definition
"""
d = definition_to_dict(definition)
try:
d['local_name'] = parent['local_name'] + '.' + d['name']
except (AttributeError, TypeError):
d['local_name'] = d['name']
if definition.type == 'class':
ds = definition.defined_names()
return [d] + [get_names_recursively(c, d) for c in ds]
else:
return [d]
def get_module_version(module):
notfound = object()
for key in ['__version__', 'version']:
version = getattr(module, key, notfound)
if version is not notfound:
return version
try:
from pkg_resources import get_distribution, DistributionNotFound
try:
return get_distribution(module.__name__).version
except DistributionNotFound:
pass
except ImportError:
pass
def path_expand_vars_and_user(p):
return os.path.expandvars(os.path.expanduser(p))
def configure_logging(log_settings):
"""
:type log_settings: LogSettings
"""
if not log_settings.log_file:
return
fmter = logging.Formatter('%(asctime)s:' + logging.BASIC_FORMAT)
if log_settings.log_rotate_max_size > 0:
handler = logging.handlers.RotatingFileHandler(
filename=log_settings.log_file,
mode='w',
maxBytes=log_settings.log_rotate_max_size,
backupCount=log_settings.log_rotate_max_count,
)
else:
handler = logging.FileHandler(filename=log_settings.log_file, mode='w')
handler.setFormatter(fmter)
if log_settings.log_level:
logging.root.setLevel(log_settings.log_level.upper())
logging.root.addHandler(handler)
def jedi_epc_server(
address='localhost',
port=0,
port_file=sys.stdout,
sys_path=[],
virtual_env=[],
sys_path_append=[],
debugger=None,
log_traceback=None,
):
"""Start EPC server.
:type log_settings: LogSettings
"""
logger.debug(
'jedi_epc_server: sys_path=%r virtual_env=%r sys_path_append=%r',
sys_path, virtual_env, sys_path_append,
)
if not virtual_env and os.getenv('VIRTUAL_ENV'):
logger.debug(
'Taking virtual env from VIRTUAL_ENV: %r',
os.environ['VIRTUAL_ENV'],
)
virtual_env = [os.environ['VIRTUAL_ENV']]
handler = JediEPCHandler(
sys_path=sys_path,
virtual_envs=virtual_env,
sys_path_append=sys_path_append,
)
logger.debug(
'Starting Jedi EPC server with the following sys.path: %r',
handler.get_sys_path(),
)
server = epc.server.EPCServer((address, port))
server.register_function(handler.complete)
server.register_function(handler.get_in_function_call)
server.register_function(handler.goto)
server.register_function(handler.related_names)
server.register_function(handler.get_definition)
server.register_function(handler.defined_names)
server.register_function(handler.get_jedi_version)
@server.register_function
def toggle_log_traceback():
server.log_traceback = not server.log_traceback
return server.log_traceback
port_file.write(str(server.server_address[1])) # needed for Emacs client
port_file.write("\n")
port_file.flush()
if port_file is not sys.stdout:
port_file.close()
# This is not supported Python-EPC API, but I am using this for
# backward compatibility for Python-EPC < 0.0.4. In the future,
# it should be passed to the constructor.
server.log_traceback = bool(log_traceback)
if debugger:
server.set_debugger(debugger)
handler = logging.StreamHandler()
fmter = logging.Formatter('%(asctime)s:' + logging.BASIC_FORMAT)
handler.setFormatter(fmter)
handler.setLevel(logging.DEBUG)
server.logger.addHandler(handler)
server.logger.setLevel(logging.DEBUG)
return server
# def add_virtualenv_path(venv):
# """Add virtualenv's site-packages to `sys.path`."""
# venv = os.path.abspath(venv)
# paths = glob.glob(os.path.join(
# venv, 'lib', 'python*', 'site-packages'))
# if not paths:
# raise ValueError('Invalid venv: no site-packages found: %s' % venv)
# for path in paths:
# site.addsitedir(path)
def main(args=None):
ns = parser.parse_args(args)
ns_vars = vars(ns).copy()
log_settings = LogSettings(
log_file=ns_vars.pop('log'),
log_level=ns_vars.pop('log_level'),
log_rotate_max_size=ns_vars.pop('log_rotate_max_size'),
log_rotate_max_count=ns_vars.pop('log_rotate_max_count'),
)
configure_logging(log_settings)
server = jedi_epc_server(**ns_vars)
server.serve_forever()
server.logger.info('exit')
if __name__ == '__main__':
main()
|
frascoweb/frasco
|
frasco/angular/__init__.py
|
from frasco.ext import *
from frasco.assets import expose_package, register_assets_builder
from frasco.utils import join_url_rule
from flask import render_template
import os
import json
import re
import htmlmin
import codecs
class FrascoAngular(Extension):
name = "frasco_angular"
defaults = {"static_dir": None, # defaults to app.static_folder
"static_url_path": None, # defaults to app.static_url_path
"angular_template": "angular_layout.html",
"app_dir": "app",
"services_module": "services",
"services_name": "%s",
"templates_file": None,
"templates_module": "templatesCache",
"templates_search_paths": [],
"disable_templates_cache": None, # app.debug
"templates_matcher": r".*\.html$",
"add_app_dir_in_babel_extract": True}
def _init_app(self, app, state):
require_extension('frasco_assets', app)
expose_package(app, "frasco_angular", __name__)
if not state.options["static_dir"]:
state.options["static_dir"] = app.static_folder
if not state.options["static_url_path"]:
state.options["static_url_path"] = app.static_url_path
state.options['templates_search_paths'].append(
(os.path.join(state.options["static_dir"], state.options['app_dir']), state.options["static_url_path"] + '/' + state.options['app_dir'])
)
if state.options['templates_file']:
register_assets_builder(self.build_templates)
if has_extension('frasco_babel', app) and state.options['add_app_dir_in_babel_extract']:
app.extensions.frasco_babel.add_extract_dir(os.path.join(state.options['static_dir'], state.options['app_dir']),
'.', ['frasco.angular.babel.AngularCompatExtension'], [('javascript:**.js', {})])
@ext_stateful_method
def add_route(self, state, endpoint, rule, decorators=None, **options):
rules = rule if isinstance(rule, (list, tuple)) else [rule]
def func(*args, **kwargs):
return self.angular_view_response()
if decorators:
for decorator in reversed(decorators):
func = decorator(func)
for rule in rules:
self.get_app().add_url_rule(rule, endpoint, func, **options)
def angular_view_response(self):
return render_template(get_extension_state('frasco_angular').options['angular_template'])
@ext_stateful_method
def register_service_builder(self, state, api_version, filename):
def builder():
module = ("/* This file is auto-generated by frasco-angular. DO NOT MODIFY. */\n'use strict';\n"
"\n(function() {\n\nvar services = angular.module('%s', ['frasco']);\n") % state.options["services_module"]
for service in api_version.iter_services():
endpoints = {}
for rule, endpoint, func, options in service.iter_endpoints():
args = []
if hasattr(func, 'request_params'):
for p in reversed(func.request_params):
args.extend(p.names)
endpoints[endpoint] = [_convert_url_args(join_url_rule(service.url_prefix, rule)), args]
module += ("\nservices.factory('%s', ['frascoServiceFactory', function(frascoServiceFactory) {\n"
"return frascoServiceFactory.make('%s', '%s', [], %s);\n}]);\n") % \
(state.options['services_name'] % service.name, service.name, api_version.url_prefix,
json.dumps(endpoints, indent=2))
module += "\n})();"
_write_file(os.path.join(state.options["static_dir"], state.options["app_dir"], filename), module)
register_assets_builder(builder)
@ext_stateful_method
def build_templates(self, state):
module = [("/* This file is auto-generated by frasco-angular. DO NOT MODIFY. */\n'use strict';\n"
"\nangular.module('%s', []).run(['$templateCache', function($templateCache) {") % state.options["templates_module"]]
matcher = re.compile(state.options["templates_matcher"], re.I)
done = set()
def process_file(filename, path, relpath, url_path):
pathname = os.path.join(path, filename)
relname = "/".join([p for p in [url_path, os.path.relpath(path, relpath), filename] if p])
if pathname not in done and matcher.match(relname):
with codecs.open(pathname, 'r', 'utf-8') as f:
content = f.read()
module.append(" $templateCache.put('%s', %s);" % (relname, json.dumps(htmlmin.minify(content))))
done.add(pathname)
disable = state.options["disable_templates_cache"]
if (disable is None and not self.get_app().debug) or disable is False:
for templates_dir, url_path in state.options['templates_search_paths']:
for path, dirnames, filenames in os.walk(templates_dir):
for filename in filenames:
process_file(filename, path, templates_dir, url_path)
module = "\n".join(module) + "\n}]);"
filename = os.path.join(state.options["static_dir"], state.options["app_dir"], state.options['templates_file'])
_write_file(filename, module)
_url_arg_re = re.compile(r"<([a-z]+:)?([a-z0-9_]+)>")
def _convert_url_args(url):
return _url_arg_re.sub(r":\2", url)
def _write_file(filename, source):
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with codecs.open(filename, "w", "utf-8") as f:
f.write(source)
|
econne01/flask_blog
|
app/app.py
|
""" Configuration for Flask app """
import os
import urllib
from flask import (Flask, abort, flash, Response)
from playhouse.flask_utils import FlaskDB
ADMIN_PASSWORD = 'secret'
APP_DIR = os.path.dirname(os.path.realpath(__file__))
DATABASE = 'sqliteext:///%s' % os.path.join(APP_DIR, 'blog.db')
DEBUG = False
SECRET_KEY = 'shhh, secret!' # Used by Flask to encrypt session cookie.
SITE_WIDTH = 800
app = Flask(__name__)
app.config.from_object(__name__)
flask_db = FlaskDB(app)
database = flask_db.database
from models import Entry, FTSEntry
database.create_tables([Entry, FTSEntry], safe=True)
# Setup routes
import views
app.add_url_rule('/login/', 'login', views.login, methods=['GET', 'POST'])
app.add_url_rule('/logout/', 'logout', views.logout, methods=['GET', 'POST'])
app.add_url_rule('/', 'index', views.index, methods=['GET'])
app.add_url_rule('/create', 'create', views.create, methods=['GET', 'POST'])
app.add_url_rule('/drafts', 'drafts', views.drafts, methods=['GET'])
app.add_url_rule('/<slug>', 'detail', views.detail, methods=['GET'])
app.add_url_rule('/<slug>/edit', 'edit', views.edit, methods=['GET', 'POST'])
@app.template_filter('clean_querystring')
def clean_querystring(request_args, *keys_to_remove, **new_values):
querystring = dict((key, value) for key, value in request_args.items())
for key in keys_to_remove:
querystring.pop(key, None)
querystring.update(new_values)
return urllib.urlencode(querystring)
@app.errorhandler(404)
def not_found(exc):
return Response('<h3>404 Error: Page Not found</h3>'), 404
|
daveinnyc/various
|
python-practice/class_demos.py
|
# Notes on classes
class Sample():
def __init__(self, name, number):
self.name = name
self.number = number
def print_values(self):
print(f"name: {self.name}")
print(f"number: {self.number}")
class SampleWithProperties():
def __init__(self, name, number):
self.name = name
self.number = number
@property
def name(self):
# double underscore is to tell future devs to avoid variable
return self.__name
@property
def double_name(self):
# Can return calculated or other values besides fields
return 2 * self.__name
@property
def number(self):
return self.__number
@name.setter
def name(self, value):
# Often has some sort of validation or transformation code
self.__name = value
@number.setter
def number(self, value):
# Often has some sort of validation or transformation code
self.__number = value % 2
class SuperClass():
def __init__(self, name):
self.name = name
def speak(self):
print(f"Hey, ho {self.name}")
class SubClass(SuperClass):
def __init__(self, name, location):
super().__init__(name)
self.location = location
def shout_out(self):
print(f"{self.location} is where it's at")
def speak(self):
# Need to explicitly over ride parent methods
# calling it here, eg, super().speak()
# just calls it. If super.method() is not
# called, then only this code would run
print(f"{self.location}, let's go! ")
if __name__ == "__main__":
'''
# Demo Sample()
instance = Sample("fred", 3)
instance.print_values()
print(f"Access name field directly: {instance.name}")
instance.number += 100
print(f"Access number field directly: {instance.number}")
'''
'''
# Demo SampleWithProperties()
instance_with_props = SampleWithProperties("fred", 3)
# Directly accessing values
# Next line fails
# print(f"Access name field, direct: {instance_with_props.__name}")
# Python rewrites value names with intial __ to protect namespace
# not really a private value, but less likely to be accessed
print(f"Access name field, direct: {instance_with_props._SampleWithProperties__name}")
# Using getter to access values, looks like direct access but isn't
# name field
print(f"Access name field, getter: {instance_with_props.name}")
print(f"Access name field, getter: {instance_with_props.double_name}")
instance_with_props.name = "Barney"
print(f"Access name field, after setter: {instance_with_props.name}")
# number field
print(f"Access number field, before setter: {instance_with_props.number}")
instance_with_props.number = 4
print(f"Access number field, after setter: {instance_with_props.number}")
instance_with_props.number = 3
print(f"Access number field, after setter: {instance_with_props.number}")
'''
# Demo inheritance
# Show super class functions
instance_super = SuperClass("Johnny")
print(f"Name, super: {instance_super.name}")
print("")
# Show sub inherits name, methods
instance_sub = SubClass("Joey", "Lower East Side")
print(f"Name, super: {instance_sub.name}")
print(f"Method from super: ", end="")
instance_sub.super().speak()
print("")
# Show sub can override parent
print(f"Overide from super: ", end="")
instance_sub.speak()
# Figure out how to call the super method from the instance rather than from the class definition
|
thelazier/dash
|
contrib/devtools/security-check.py
|
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Perform basic ELF security checks on a series of executables.
Exit status will be 0 if successful, and the program will be silent.
Otherwise the exit status will be 1 and it will log which executables failed which checks.
Needs `readelf` (for ELF) and `objdump` (for PE).
'''
import subprocess
import sys
import os
READELF_CMD = os.getenv('READELF', '/usr/bin/readelf')
OBJDUMP_CMD = os.getenv('OBJDUMP', '/usr/bin/objdump')
NONFATAL = {} # checks which are non-fatal for now but only generate a warning
def check_ELF_PIE(executable):
'''
Check for position independent executable (PIE), allowing for address space randomization.
'''
p = subprocess.Popen([READELF_CMD, '-h', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
ok = False
for line in stdout.splitlines():
line = line.split()
if len(line)>=2 and line[0] == 'Type:' and line[1] == 'DYN':
ok = True
return ok
def get_ELF_program_headers(executable):
'''Return type and flags for ELF program headers'''
p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
in_headers = False
count = 0
headers = []
for line in stdout.splitlines():
if line.startswith('Program Headers:'):
in_headers = True
if line == '':
in_headers = False
if in_headers:
if count == 1: # header line
ofs_typ = line.find('Type')
ofs_offset = line.find('Offset')
ofs_flags = line.find('Flg')
ofs_align = line.find('Align')
if ofs_typ == -1 or ofs_offset == -1 or ofs_flags == -1 or ofs_align == -1:
raise ValueError('Cannot parse elfread -lW output')
elif count > 1:
typ = line[ofs_typ:ofs_offset].rstrip()
flags = line[ofs_flags:ofs_align].rstrip()
headers.append((typ, flags))
count += 1
return headers
def check_ELF_NX(executable):
'''
Check that no sections are writable and executable (including the stack)
'''
have_wx = False
have_gnu_stack = False
for (typ, flags) in get_ELF_program_headers(executable):
if typ == 'GNU_STACK':
have_gnu_stack = True
if 'W' in flags and 'E' in flags: # section is both writable and executable
have_wx = True
return have_gnu_stack and not have_wx
def check_ELF_RELRO(executable):
'''
Check for read-only relocations.
GNU_RELRO program header must exist
Dynamic section must have BIND_NOW flag
'''
have_gnu_relro = False
for (typ, flags) in get_ELF_program_headers(executable):
# Note: not checking flags == 'R': here as linkers set the permission differently
# This does not affect security: the permission flags of the GNU_RELRO program header are ignored, the PT_LOAD header determines the effective permissions.
# However, the dynamic linker need to write to this area so these are RW.
# Glibc itself takes care of mprotecting this area R after relocations are finished.
# See also https://marc.info/?l=binutils&m=1498883354122353
if typ == 'GNU_RELRO':
have_gnu_relro = True
have_bindnow = False
p = subprocess.Popen([READELF_CMD, '-d', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
for line in stdout.splitlines():
tokens = line.split()
if len(tokens)>1 and tokens[1] == '(BIND_NOW)' or (len(tokens)>2 and tokens[1] == '(FLAGS)' and 'BIND_NOW' in tokens[2:]):
have_bindnow = True
return have_gnu_relro and have_bindnow
def check_ELF_Canary(executable):
'''
Check for use of stack canary
'''
p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
ok = False
for line in stdout.splitlines():
if '__stack_chk_fail' in line:
ok = True
return ok
def get_PE_dll_characteristics(executable):
'''
Get PE DllCharacteristics bits.
Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386'
and bits is the DllCharacteristics value.
'''
p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
arch = ''
bits = 0
for line in stdout.splitlines():
tokens = line.split()
if len(tokens)>=2 and tokens[0] == 'architecture:':
arch = tokens[1].rstrip(',')
if len(tokens)>=2 and tokens[0] == 'DllCharacteristics':
bits = int(tokens[1],16)
return (arch,bits)
IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA = 0x0020
IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040
IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100
def check_PE_DYNAMIC_BASE(executable):
'''PIE: DllCharacteristics bit 0x40 signifies dynamicbase (ASLR)'''
(arch,bits) = get_PE_dll_characteristics(executable)
reqbits = IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE
return (bits & reqbits) == reqbits
# On 64 bit, must support high-entropy 64-bit address space layout randomization in addition to DYNAMIC_BASE
# to have secure ASLR.
def check_PE_HIGH_ENTROPY_VA(executable):
'''PIE: DllCharacteristics bit 0x20 signifies high-entropy ASLR'''
(arch,bits) = get_PE_dll_characteristics(executable)
if arch == 'i386:x86-64':
reqbits = IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA
else: # Unnecessary on 32-bit
assert(arch == 'i386')
reqbits = 0
return (bits & reqbits) == reqbits
def check_PE_NX(executable):
'''NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)'''
(arch,bits) = get_PE_dll_characteristics(executable)
return (bits & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) == IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
CHECKS = {
'ELF': [
('PIE', check_ELF_PIE),
('NX', check_ELF_NX),
('RELRO', check_ELF_RELRO),
('Canary', check_ELF_Canary)
],
'PE': [
('DYNAMIC_BASE', check_PE_DYNAMIC_BASE),
('HIGH_ENTROPY_VA', check_PE_HIGH_ENTROPY_VA),
('NX', check_PE_NX)
]
}
def identify_executable(executable):
with open(filename, 'rb') as f:
magic = f.read(4)
if magic.startswith(b'MZ'):
return 'PE'
elif magic.startswith(b'\x7fELF'):
return 'ELF'
return None
if __name__ == '__main__':
retval = 0
for filename in sys.argv[1:]:
try:
etype = identify_executable(filename)
if etype is None:
print('%s: unknown format' % filename)
retval = 1
continue
failed = []
warning = []
for (name, func) in CHECKS[etype]:
if not func(filename):
if name in NONFATAL:
warning.append(name)
else:
failed.append(name)
if failed:
print('%s: failed %s' % (filename, ' '.join(failed)))
retval = 1
if warning:
print('%s: warning %s' % (filename, ' '.join(warning)))
except IOError:
print('%s: cannot open' % filename)
retval = 1
sys.exit(retval)
|
guillon/mdi
|
examples/mini/scripts/generate_executions.py
|
#!/usr/bin/env python
#
# Machine Description Interface C API
#
# This software is delivered under the terms of the MIT License
#
# Copyright (c) 2016 STMicroelectronics
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
#
from __future__ import print_function
import sys
class ENUM:
instructions_list = []
def __init__(self, ID, mnemonic, properties, parsing, encoding, short_desc, execution, description):
self.ID = ID
self.mnemonic = mnemonic
self.properties = properties
self.parsing = parsing
self.encoding = encoding
self.short_desc = short_desc
self.execution = execution
self.description = description
self.instructions_list.append(self)
@staticmethod
def emit_execution(out):
with open(out, "w") as outf:
print("/* BEGIN: Generated executions */", file=outf)
ENUM._emit_executions(outf)
print("/* END: Generated executions */", file=outf)
@staticmethod
def _emit_executions(out):
idx = 0;
print("#define P(idx) EXE_OPS(_operands,idx)", file=out)
print("#define NEXT_PC() (RR(PC,0) + _op_size)", file=out)
print("#define RR(rf,idx) EXE_CPU_RR((*_cpu_prev),rf,idx)", file=out)
print("#define RS(rf,idx) EXE_CPU_RS(_cpu,rf,idx)", file=out)
print("#define MR32(idx) EXE_MEM_FETCH32(_mem,idx)", file=out)
print("#define MS32(idx) EXE_MEM_SLICE32(_mem,idx)", file=out)
for inst in ENUM.instructions_list:
print("", file=out)
print("static int32_t _execution_%i /* %s */ (EXE_CTX_T _context, EXE_OPS_T _operands, size_t _op_size)" %
(idx, inst.ID), file=out)
print("{", file=out)
print(" CPU_T _cpu, *_cpu_prev = EXE_CTX_CPU(_context);", file=out)
print(" MEM_T _mem, *_mem_prev = EXE_CTX_MEM(_context);", file=out)
print(" EXE_CPU_CLONE(_cpu, _cpu_prev);", file=out)
print(" EXE_MEM_CLONE(_mem, _mem_prev);", file=out)
print(" RS(PC,0) = NEXT_PC();", file=out)
print(" %s;" % inst.execution, file=out)
print(" EXE_CPU_UPDATE(*_cpu_prev, &_cpu);", file=out);
print(" EXE_CPU_UPDATE(*_mem_prev, &_mem);", file=out);
print(" return 0;", file=out)
print("}", file=out);
idx += 1
print("#undef RF", file=out)
print("#undef MEM", file=out)
print("typedef int32_t (*EXE_FUNC_T)(EXE_CTX_T _context, EXE_OPS_T _operands, size_t _op_size);", file=out);
print("static const EXE_FUNC_T _executions[] = {", file=out)
idx = 0
for inst in ENUM.instructions_list:
print(" _execution_%i /* %s */," % (idx, inst.ID), file=out)
idx += 1
print("};", file=out)
execfile(sys.argv[1])
ENUM.emit_execution(sys.argv[2])
|
shtalinberg/django-actions-logger
|
actionslog/settings.py
|
# """Django Actions Log settings file."""
#
from __future__ import unicode_literals
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
CREATE = 100
SUCCESS = 110
ACTIVATE = 130
AUTH = 150
VIEW = 180
UPDATE = 200
SUSPEND = 250
UNSUSPEND = 260
DELETE = 300
TERMINATE = 500
FAILED = 999
ERROR = 1000
LOG_ACTION_CHOICES_DEFAULT = [
(CREATE, _("create")),
(SUCCESS, _("success")),
(ACTIVATE, _("activate")),
(AUTH, _("authorize")),
(VIEW, _("view")),
(UPDATE, _("update")),
(SUSPEND, _("suspend")),
(UNSUSPEND, _("unsuspend")),
(DELETE, _("delete")),
(TERMINATE, _("terminate")),
(FAILED, _("failed")),
(ERROR, _("error")),
]
AL_LOG_ACTION_SETTINGS = getattr(
settings, 'AL_LOG_ACTION_CHOICES',
LOG_ACTION_CHOICES_DEFAULT
)
LOG_ACTION_CHOICES = [
(value[0], value[1])
for value in AL_LOG_ACTION_SETTINGS
]
|
pygeo/pycmbs
|
pycmbs/tests/test_icon.py
|
# -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
import unittest
from pycmbs.icon import Icon
class TestPycmbsIcon(unittest.TestCase):
def setUp(self):
# requires local installation of ICON sample files!
self.gridfile ='../..//example_data/icon/r2b4_amip.nc'
self.datafile = '../../example_data/icon/rms0006_atm_phy_DOM01_ML_0001.nc'
def test_DummyTest(self):
pass
def test_IconInit(self):
x = Icon(None, None, 'None')
def test_IconInitMissingFile(self):
x = Icon('no.nc', 'nothing.nc', 'novar')
with self.assertRaises(ValueError):
x.read()
def test_IconInitMissingGridFile(self):
x = Icon(self.datafile, 'nothing.nc', 'novar')
with self.assertRaises(ValueError):
x.read()
#~ def test_IconReadOK(self):
#~ x = Icon(self.datafile, self.datafile, 'rsns')
#~ x.read()
if __name__ == "__main__":
unittest.main()
|
tlake/advent-of-code
|
2016/day07_internet_protocol_version_7/python/src/part2.py
|
#!/usr/bin/env python
"""Docstring."""
import re
from functools import reduce
from collections import Counter
from common import get_input
class SSLTester:
"""."""
def __init__(self, input_list=[]):
"""Initialize."""
self.input_list = input_list
def find_aba(self, seq):
"""Return list: all 'aba's found in the string <seq>."""
i = 0
abas = []
while i < len(seq) - 2:
if (seq[i] == seq[i + 2] and
seq[i] != seq[i + 1]):
abas.append(seq[i:i + 3])
i += 1
return abas
def batch_find_aba(self, seqs):
"""Return list: all 'aba's found from all strings in <seqs>."""
return reduce(lambda x, y: x + y, [self.find_aba(x) for x in seqs], [])
def has_corresponding_bab(self, input_key, seqs):
"""Return bool: <key> exists for any string in <seqs>."""
key = input_key[1::] + input_key[1]
return True in [key in x for x in seqs]
def ip_supports_ssl(self, ip_string):
"""Return bool: <ip_string> supports SSL.
True:
some string in <unbracketed> contains 'aba' pattern
AND some string in <bracketed> contains matching 'bab' pattern
"""
all_segments = re.split(r"\[(\w+)\]", ip_string)
bracketed = re.findall(r"\[(\w+)\]", ip_string)
unbracketed = [x for x in all_segments if x not in bracketed]
return True in [self.has_corresponding_bab(x, bracketed) for x in self.batch_find_aba(unbracketed)]
def count_supported_ips(self, input_list=None):
"""Return int: number of items in <input_list> which support SSL."""
input_list = input_list if input_list else self.input_list
return Counter([self.ip_supports_ssl(x) for x in input_list])[True]
if __name__ == "__main__":
tester = SSLTester(get_input())
print("Out of {} IPs, {} support SSL.".format(
len(tester.input_list),
tester.count_supported_ips()
))
|
rahulg/eulerswift
|
setup.py
|
import sys
import EulerPy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
def requirements():
install_requires = []
with open('requirements.txt') as f:
for line in f:
install_requires.append(line.strip())
# Terminal colors for Windows
if 'win32' in str(sys.platform).lower():
install_requires.append('colorama>=0.2.4')
return install_requires
setup(
name='EulerPy',
version=EulerPy.__version__,
description=EulerPy.__doc__.strip(),
long_description=readme(),
url='https://github.com/iKevinY/EulerPy',
author=EulerPy.__author__,
author_email='me@kevinyap.ca',
license=EulerPy.__license__,
packages=['EulerPy'],
entry_points={'console_scripts': ['euler = EulerPy.__main__:main']},
install_requires=requirements(),
classifiers=[
"License :: OSI Approved :: MIT License",
"Topic :: Utilities",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
],
keywords=['EulerPy', 'euler', 'project-euler', 'projecteuler'],
include_package_data=True,
zip_safe=False,
)
|
pythonkr/pyconkr-2014
|
pyconkr/forms.py
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from django_summernote.widgets import SummernoteInplaceWidget
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Speaker, Program
class EmailLoginForm(forms.Form):
email = forms.EmailField(
max_length=255,
label='',
widget=forms.TextInput(attrs={
'placeholder': 'Email address',
'class': 'form-control',
})
)
def clean(self):
cleaned_data = super(EmailLoginForm, self).clean()
return cleaned_data
class SpeakerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SpeakerForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', _('Submit')))
class Meta:
model = Speaker
fields = ('desc', 'info', )
widgets = {
'desc': SummernoteInplaceWidget(),
}
labels = {
'desc': _('Profile'),
'info': _('Additional information'),
}
class ProgramForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProgramForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', _('Submit')))
class Meta:
model = Program
fields = ('slide_url', 'video_url', 'is_recordable', 'desc', )
widgets = {
'desc': SummernoteInplaceWidget(),
}
labels = {
'slide_url': _('Slide URL'),
'video_url': _('Video URL'),
'is_recordable': _('Photography and recording is allowed'),
'desc': _('Description'),
}
|
mandrive/FlaskTest
|
__init__.py
|
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from RestResources.Resources import PostsList, Posts
from services.Services import UserService
from views import Login, Common, Post, Admin
app = Flask(__name__)
CsrfProtect(app)
login_serializer = URLSafeTimedSerializer(AppConfig.APPSECRETKEY)
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
# set the secret key. keep this really secret:
app.secret_key = AppConfig.APPSECRETKEY
def register_mods():
app.register_blueprint(Common.mod)
app.register_blueprint(Login.mod)
app.register_blueprint(Post.mod)
app.register_blueprint(Admin.mod)
def create_db_engine():
return create_engine(AppConfig.CONNECTIONSTRING, pool_recycle=3600, echo=True)
def build_db_engine():
AppConfig.DBENGINE = create_db_engine()
def init_login():
login_manager = LoginManager()
login_manager.init_app(app)
AppConfig.LOGINMANAGER = login_manager
# Create user loader function
@login_manager.user_loader
def load_user(user_id):
return UserService().getAll().filter_by(id=user_id).first()
@login_manager.token_loader
def get_user_token(token):
max_age = app.config["REMEMBER_COOKIE_DURATION"].total_seconds()
#Decrypt the Security Token, data = [username, hashpass]
data = login_serializer.loads(token, max_age=max_age)
userService = UserService()
#Find the User
user = userService.getById(data[0])
#Check Password and return user or None
if user and userService.validate(user.username, user.password):
return user
return None
def init_logger():
handler = RotatingFileHandler('FlaskTest.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
def register_rest_api():
return Api(app)
def register_rest_resources():
api.add_resource(PostsList, '/api/posts')
api.add_resource(Posts, '/api/posts/<string:post_id>')
def set_app_configuration():
app.config['REMEMBER_COOKIE_DURATION'] = AppConfig.REMEMBER_COOKIE_DURATION
register_mods()
api = register_rest_api()
register_rest_resources()
build_db_engine()
init_login()
init_logger()
set_app_configuration()
app.run(AppConfig.APPHOST, AppConfig.APPPORT)
|
vetlehjelmtvedt/TranscriptApp
|
sttClient.py
|
#
# Copyright IBM Corp. 2014
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: Daniel Bolanos
# Date: 2015
# coding=utf-8
import json # json
import threading # multi threading
import os # for listing directories
import Queue # queue used for thread syncronization
import sys # system calls
import argparse # for parsing arguments
import base64 # necessary to encode in base64
# according to the RFC2045 standard
import requests # python HTTP requests library
# WebSockets
from autobahn.twisted.websocket import WebSocketClientProtocol, \
WebSocketClientFactory, connectWS
from twisted.python import log
from twisted.internet import ssl, reactor
with open("path_output.txt", "r") as file:
path_output = file.read()
class Utils:
@staticmethod
def getAuthenticationToken(hostname, serviceName, username, password):
uri = hostname + "/authorization/api/v1/token?url=" + hostname + '/' \
+ serviceName + "/api"
uri = uri.replace("wss://", "https://")
uri = uri.replace("ws://", "https://")
print uri
resp = requests.get(uri, auth=(username, password), verify=False,
headers={'Accept': 'application/json'},
timeout=(30, 30))
print resp.text
jsonObject = resp.json()
return jsonObject['token']
class WSInterfaceFactory(WebSocketClientFactory):
def __init__(self, queue, summary, dirOutput, contentType, model,
url=None, headers=None, debug=None):
WebSocketClientFactory.__init__(self, url=url, headers=headers)
self.queue = queue
self.summary = summary
self.dirOutput = dirOutput
self.contentType = contentType
self.model = model
self.queueProto = Queue.Queue()
self.openHandshakeTimeout = 10
self.closeHandshakeTimeout = 10
# start the thread that takes care of ending the reactor so
# the script can finish automatically (without ctrl+c)
endingThread = threading.Thread(target=self.endReactor, args=())
endingThread.daemon = True
endingThread.start()
def prepareUtterance(self):
try:
utt = self.queue.get_nowait()
self.queueProto.put(utt)
return True
except Queue.Empty:
print "getUtterance: no more utterances to process, queue is empty!"
return False
def endReactor(self):
self.queue.join()
print "about to stop the reactor!"
reactor.stop()
# this function gets called every time connectWS is called (once
# per WebSocket connection/session)
def buildProtocol(self, addr):
try:
utt = self.queueProto.get_nowait()
proto = WSInterfaceProtocol(self, self.queue, self.summary,
self.dirOutput, self.contentType)
proto.setUtterance(utt)
return proto
except Queue.Empty:
print ("queue should not be empty, otherwise this function "
"should not have been called")
return None
# WebSockets interface to the STT service
#
# note: an object of this class is created for each WebSocket
# connection, every time we call connectWS
class WSInterfaceProtocol(WebSocketClientProtocol):
def __init__(self, factory, queue, summary, dirOutput, contentType):
self.factory = factory
self.queue = queue
self.summary = summary
self.dirOutput = dirOutput
self.contentType = contentType
self.packetRate = 20
self.listeningMessages = 0
self.timeFirstInterim = -1
self.bytesSent = 0
self.chunkSize = 2000 # in bytes
super(self.__class__, self).__init__()
print dirOutput
print "contentType: " + str(self.contentType) + " queueSize: " + \
str(self.queue.qsize())
def setUtterance(self, utt):
self.uttNumber = utt[0]
self.uttFilename = utt[1]
self.summary[self.uttNumber] = {"hypothesis": "",
"status": {"code": "", "reason": ""}}
self.fileJson = self.dirOutput + "/" + str(self.uttNumber) + \
".json.txt"
try:
os.remove(self.fileJson)
except OSError:
pass
# helper method that sends a chunk of audio if needed (as required
# what the specified pacing is)
def maybeSendChunk(self, data):
def sendChunk(chunk, final=False):
self.bytesSent += len(chunk)
self.sendMessage(chunk, isBinary=True)
if final:
self.sendMessage(b'', isBinary=True)
if (self.bytesSent + self.chunkSize >= len(data)):
if (len(data) > self.bytesSent):
sendChunk(data[self.bytesSent:len(data)], True)
return
sendChunk(data[self.bytesSent:self.bytesSent + self.chunkSize])
self.factory.reactor.callLater(0.01, self.maybeSendChunk, data=data)
return
def onConnect(self, response):
print "onConnect, server connected: {0}".format(response.peer)
def onOpen(self):
print "onOpen"
data = {"action": "start", "content-type": str(self.contentType),
"continuous": True, "interim_results": True,
"inactivity_timeout": 600}
data['word_confidence'] = True
data['timestamps'] = True
data['max_alternatives'] = 3
print "sendMessage(init)"
# send the initialization parameters
self.sendMessage(json.dumps(data).encode('utf8'))
# start sending audio right away (it will get buffered in the
# STT service)
print self.uttFilename
f = open(str(self.uttFilename), 'rb')
self.bytesSent = 0
dataFile = f.read()
self.maybeSendChunk(dataFile)
print "onOpen ends"
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print(u"Text message received: {0}".format(payload.decode('utf8')))
# if uninitialized, receive the initialization response
# from the server
jsonObject = json.loads(payload.decode('utf8'))
if 'state' in jsonObject:
self.listeningMessages += 1
if (self.listeningMessages == 2):
print "sending close 1000"
# close the connection
self.sendClose(1000)
# if in streaming
elif 'results' in jsonObject:
jsonObject = json.loads(payload.decode('utf8'))
hypothesis = ""
# empty hypothesis
if (len(jsonObject['results']) == 0):
print "empty hypothesis!"
# regular hypothesis
else:
# dump the message to the output directory
jsonObject = json.loads(payload.decode('utf8'))
f = open(self.fileJson, "a")
f.write(json.dumps(jsonObject, indent=4, sort_keys=True))
f.close()
res = jsonObject['results'][0]
hypothesis = res['alternatives'][0]['transcript']
bFinal = (res['final'] == True)
if bFinal:
print "final hypothesis: \"" + hypothesis + "\""
self.summary[self.uttNumber]['hypothesis'] += hypothesis
else:
print "interim hyp: \"" + hypothesis + "\""
def onClose(self, wasClean, code, reason):
print("onClose")
print("WebSocket connection closed: {0}".format(reason), "code: ",
code, "clean: ", wasClean, "reason: ", reason)
self.summary[self.uttNumber]['status']['code'] = code
self.summary[self.uttNumber]['status']['reason'] = reason
# create a new WebSocket connection if there are still
# utterances in the queue that need to be processed
self.queue.task_done()
if self.factory.prepareUtterance() == False:
return
# SSL client context: default
if self.factory.isSecure:
contextFactory = ssl.ClientContextFactory()
else:
contextFactory = None
connectWS(self.factory, contextFactory)
# function to check that a value is a positive integer
def check_positive_int(value):
ivalue = int(value)
if ivalue < 1:
raise argparse.ArgumentTypeError(
"\"%s\" is an invalid positive int value" % value)
return ivalue
# function to check the credentials format
def check_credentials(credentials):
elements = credentials.split(":")
if (len(elements) == 2):
return elements
else:
raise argparse.ArgumentTypeError(
"\"%s\" is not a valid format for the credentials " % credentials)
if __name__ == '__main__':
# parse command line parameters
parser = argparse.ArgumentParser(
description=('client to do speech recognition using the WebSocket '
'interface to the Watson STT service'))
parser.add_argument(
'-credentials', action='store', dest='credentials',
help="Basic Authentication credentials in the form 'username:password'",
required=True, type=check_credentials)
parser.add_argument(
'-in', action='store', dest='fileInput', default='./recordings.txt',
help='text file containing audio files')
parser.add_argument(
'-out', action='store', dest='dirOutput', default='./output',
help='output directory')
parser.add_argument(
'-type', action='store', dest='contentType', default='audio/wav',
help='audio content type, for example: \'audio/l16; rate=44100\'')
parser.add_argument(
'-model', action='store', dest='model', default='en-US_BroadbandModel',
help='STT model that will be used')
parser.add_argument(
'-threads', action='store', dest='threads', default='1',
help='number of simultaneous STT sessions', type=check_positive_int)
parser.add_argument(
'-optout', action='store_true', dest='optOut',
help=('specify opt-out header so user data, such as speech and '
'hypotheses are not logged into the server'))
parser.add_argument(
'-tokenauth', action='store_true', dest='tokenauth',
help='use token based authentication')
args = parser.parse_args()
# create output directory if necessary
if (os.path.isdir(args.dirOutput)):
pass
else:
os.makedirs(args.dirOutput)
# logging
log.startLogging(sys.stdout)
# add audio files to the processing queue
q = Queue.Queue()
lines = [line.rstrip('\n') for line in open(args.fileInput)]
fileNumber = 0
for fileName in(lines):
print fileName
q.put((fileNumber, fileName))
fileNumber += 1
hostname = "stream.watsonplatform.net"
headers = {}
if (args.optOut is True):
headers['X-WDC-PL-OPT-OUT'] = '1'
# authentication header
if args.tokenauth:
headers['X-Watson-Authorization-Token'] = (
Utils.getAuthenticationToken(
"https://" + hostname, 'speech-to-text',
args.credentials[0], args.credentials[1]))
else:
string = args.credentials[0] + ":" + args.credentials[1]
headers["Authorization"] = "Basic " + base64.b64encode(string)
print headers
# create a WS server factory with our protocol
url = "wss://" + hostname + "/speech-to-text/api/v1/recognize?model=" \
+ args.model
summary = {}
factory = WSInterfaceFactory(q, summary, args.dirOutput, args.contentType,
args.model, url, headers, debug=False)
factory.protocol = WSInterfaceProtocol
for i in range(min(int(args.threads), q.qsize())):
factory.prepareUtterance()
# SSL client context: default
if factory.isSecure:
contextFactory = ssl.ClientContextFactory()
else:
contextFactory = None
connectWS(factory, contextFactory)
reactor.run()
# dump the hypotheses to the output file
fileHypotheses = path_output
f = open(fileHypotheses, "w")
counter = 1
successful = 0
emptyHypotheses = 0
for key, value in (sorted(summary.items())):
if value['status']['code'] == 1000:
print (value['status']['code'], " ",
value['hypothesis'].encode('utf-8'))
successful += 1
if value['hypothesis'][0] == "":
emptyHypotheses += 1
else:
print (value['status']['code'], " REASON: ",
value['status']['reason'])
f.write(value['hypothesis'].encode('utf-8') + "\n")
counter += 1
f.close()
print ("successful sessions: ", successful, " (",
len(summary) - successful, " errors) (" +
str(emptyHypotheses) + " empty hypotheses)")
|
luisalves05/shortener-url
|
src/apps/miudo/views.py
|
import uuid
from random import randint
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Url
def index(request):
if request.session.has_key("has_url"):
url = request.session.get("has_url")
del request.session['has_url']
return render(request, "miudo/index.html", locals())
return render(request, "miudo/index.html", {})
def make_url(request):
if request.method == "POST":
url = None # initial url
url_site = request.POST['url']
url_id = generate_key()
try:
url = Url.objects.get(url_id = url_id)
while url:
url_id = generate_key()
url = Url.objects.get(url_id = url_id)
create_url(request, url_id, url_site)
request.session["has_url"] = url_id
except Url.DoesNotExist:
create_url(request, url_id, url_site)
request.session["has_url"] = url_id
return HttpResponseRedirect("/")
def create_url(custom_request, url_id, url_site):
if custom_request.user.is_authenticated():
url = Url.objects.create(url_id = url_id, url_site = url_site,
url_author = custom_request.user)
else:
url = Url.objects.create(url_id = url_id, url_site = url_site)
url.save()
def generate_key():
to_choose = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
url_id = ""
while len(url_id) != 6:
i = randint(0, len(to_choose) - 1)
url_id += to_choose[i]
return url_id
def redirect_url(request, url_id=None):
try:
url = Url.objects.get(url_id = url_id)
url.url_clicked = url.url_clicked + 1
url.save()
except Url.DoesNotExist:
return render(request, "base/page_not_found.html", {})
return HttpResponseRedirect(url.url_site)
|
plusplus7/EasyMemo2
|
server.py
|
import tornado.web
import tornado.ioloop
import os
from handlers import *
urls = [
(r'/', IndexHandler),
(r'/api/(?P<action>[a-zA-Z0-9-_]+)', ApiServiceHandler),
(r'/about', AboutHandler),
]
settings = {
"static_path" : os.path.join(os.path.dirname(__file__), "static"),
"template_path" : os.path.join(os.path.dirname(__file__), "templates"),
"debug" : True,
"gzip" : True,
"cookie_secret" : "asdf"
}
def main(addr):
application = tornado.web.Application(urls, **settings)
application.listen(8080, addr)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main("127.0.0.1")
|
APSL/kaneda
|
kaneda/queues/rq.py
|
from __future__ import absolute_import
import logging
try:
from redis import Redis
from rq import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: queue instance of RQ class.
:param redis_url: Redis connection url where RQ will attend the async reporting requests.
:param queue_name: name of the queue being used by the RQ worker process.
"""
settings_namespace = 'RQ'
def __init__(self, queue=None, redis_url=None, queue_name='kaneda'):
if not Redis:
raise ImproperlyConfigured('You need to install redis to use the RQ queue.')
if not Queue:
raise ImproperlyConfigured('You need to install rq library to use the RQ queue.')
if queue:
if not isinstance(queue, Queue):
raise ImproperlyConfigured('"queue" parameter is not an instance of RQ queue.')
self.queue = queue
elif redis_url:
self.queue = Queue(queue_name, connection=Redis.from_url(redis_url))
else:
self.queue = Queue(queue_name, connection=Redis())
def report(self, name, metric, value, tags, id_):
try:
return self.queue.enqueue('kaneda.tasks.rq.report', name, metric, value, tags, id_)
except Exception as e:
logger = logging.getLogger(__name__)
logger.exception(e)
|
the-blue-alliance/the-blue-alliance
|
src/backend/api/main.py
|
from json import JSONDecodeError
from flask import Blueprint, Flask, make_response, Response
from flask_cors import CORS
from google.appengine.api import wrap_wsgi_app
from werkzeug.routing import BaseConverter
from backend.api.handlers.district import (
district_events,
district_list_year,
district_rankings,
district_teams,
)
from backend.api.handlers.error import handle_404
from backend.api.handlers.event import (
event,
event_awards,
event_detail,
event_list_all,
event_list_year,
event_matches,
event_playoff_advancement,
event_teams,
event_teams_statuses,
)
from backend.api.handlers.helpers.profiled_jsonify import profiled_jsonify
from backend.api.handlers.match import match, zebra_motionworks
from backend.api.handlers.media import media_tags
from backend.api.handlers.status import status
from backend.api.handlers.team import (
team,
team_awards,
team_event_awards,
team_event_matches,
team_event_status,
team_events,
team_events_statuses_year,
team_history_districts,
team_history_robots,
team_list,
team_list_all,
team_matches,
team_media_tag,
team_media_year,
team_social_media,
team_years_participated,
)
from backend.api.handlers.trusted import (
add_event_media,
add_match_video,
add_match_zebra_motionworks_info,
delete_all_event_matches,
delete_event_matches,
update_event_alliances,
update_event_awards,
update_event_info,
update_event_matches,
update_event_rankings,
update_teams,
)
from backend.common.datafeed_parsers.exceptions import ParserInputException
from backend.common.flask_cache import configure_flask_cache
from backend.common.logging import configure_logging
from backend.common.middleware import install_middleware
from backend.common.url_converters import install_url_converters
class SimpleModelTypeConverter(BaseConverter):
regex = r"simple"
class ModelTypeConverter(BaseConverter):
regex = r"simple|keys"
class EventDetailTypeConverter(BaseConverter):
regex = r"alliances|district_points|insights|oprs|predictions|rankings"
configure_logging()
app = Flask(__name__)
app.wsgi_app = wrap_wsgi_app(app.wsgi_app)
install_middleware(app)
install_url_converters(app)
configure_flask_cache(app)
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = True
app.url_map.converters["simple_model_type"] = SimpleModelTypeConverter
app.url_map.converters["model_type"] = ModelTypeConverter
app.url_map.converters["event_detail_type"] = EventDetailTypeConverter
api_v3 = Blueprint("apiv3", __name__, url_prefix="/api/v3")
CORS(
api_v3,
origins="*",
methods=["OPTIONS", "GET"],
allow_headers=["X-TBA-Auth-Key", "If-None-Match", "If-Modified-Since"],
)
# Overall Status
api_v3.add_url_rule("/status", view_func=status)
# District
api_v3.add_url_rule("/district/<string:district_key>/events", view_func=district_events)
api_v3.add_url_rule(
"/district/<string:district_key>/events/<model_type:model_type>",
view_func=district_events,
)
api_v3.add_url_rule("/district/<string:district_key>/teams", view_func=district_teams)
api_v3.add_url_rule(
"/district/<string:district_key>/teams/<model_type:model_type>",
view_func=district_teams,
)
api_v3.add_url_rule(
"/district/<string:district_key>/rankings", view_func=district_rankings
)
# District List
api_v3.add_url_rule("/districts/<int:year>", view_func=district_list_year)
# Event
api_v3.add_url_rule("/event/<string:event_key>", view_func=event)
api_v3.add_url_rule(
"/event/<string:event_key>/<simple_model_type:model_type>", view_func=event
)
api_v3.add_url_rule(
"/event/<string:event_key>/<event_detail_type:detail_type>",
view_func=event_detail,
)
api_v3.add_url_rule("/event/<string:event_key>/teams", view_func=event_teams)
api_v3.add_url_rule(
"/event/<string:event_key>/teams/<model_type:model_type>",
view_func=event_teams,
)
api_v3.add_url_rule(
"/event/<string:event_key>/teams/statuses", view_func=event_teams_statuses
)
api_v3.add_url_rule("event/<string:event_key>/matches", view_func=event_matches)
# api_v3.add_url_rule("event/<string:event_key>/matches/timeseries", view_func=TODO)
api_v3.add_url_rule(
"/event/<string:event_key>/matches/<model_type:model_type>",
view_func=event_matches,
)
api_v3.add_url_rule("/event/<string:event_key>/awards", view_func=event_awards)
api_v3.add_url_rule(
"/event/<string:event_key>/playoff_advancement", view_func=event_playoff_advancement
)
# Event List
api_v3.add_url_rule("/events/all", view_func=event_list_all)
api_v3.add_url_rule("/events/all/<model_type:model_type>", view_func=event_list_all)
api_v3.add_url_rule("/events/<int:year>", view_func=event_list_year)
api_v3.add_url_rule(
"/events/<int:year>/<model_type:model_type>", view_func=event_list_year
)
# Match
api_v3.add_url_rule("/match/<string:match_key>", view_func=match)
api_v3.add_url_rule(
"/match/<string:match_key>/<simple_model_type:model_type>", view_func=match
)
# api_v3.add_url_rule("/match/<string:match_key>/timeseries", view_func=TODO)
api_v3.add_url_rule(
"/match/<string:match_key>/zebra_motionworks", view_func=zebra_motionworks
)
# Media
api_v3.add_url_rule("/media/tags", view_func=media_tags)
# Team
api_v3.add_url_rule("/team/<string:team_key>", view_func=team)
api_v3.add_url_rule(
"/team/<string:team_key>/<simple_model_type:model_type>", view_func=team
)
# Team History
api_v3.add_url_rule(
"/team/<string:team_key>/years_participated", view_func=team_years_participated
)
api_v3.add_url_rule(
"/team/<string:team_key>/districts", view_func=team_history_districts
)
api_v3.add_url_rule("/team/<string:team_key>/robots", view_func=team_history_robots)
api_v3.add_url_rule("/team/<string:team_key>/social_media", view_func=team_social_media)
# Team Events
api_v3.add_url_rule("/team/<string:team_key>/events", view_func=team_events)
api_v3.add_url_rule(
"/team/<string:team_key>/events/<model_type:model_type>", view_func=team_events
)
api_v3.add_url_rule("/team/<string:team_key>/events/<int:year>", view_func=team_events)
api_v3.add_url_rule(
"/team/<string:team_key>/events/<int:year>/<model_type:model_type>",
view_func=team_events,
)
api_v3.add_url_rule(
"/team/<string:team_key>/events/<int:year>/statuses",
view_func=team_events_statuses_year,
)
# Team @ Event
api_v3.add_url_rule(
"/team/<string:team_key>/event/<string:event_key>/matches",
view_func=team_event_matches,
)
api_v3.add_url_rule(
"/team/<string:team_key>/event/<string:event_key>/matches/<model_type:model_type>",
view_func=team_event_matches,
)
api_v3.add_url_rule(
"/team/<string:team_key>/event/<string:event_key>/awards",
view_func=team_event_awards,
)
api_v3.add_url_rule(
"/team/<string:team_key>/event/<string:event_key>/status",
view_func=team_event_status,
)
# Team Awards
api_v3.add_url_rule("/team/<string:team_key>/awards", view_func=team_awards)
api_v3.add_url_rule("/team/<string:team_key>/awards/<int:year>", view_func=team_awards)
# Team Matches
api_v3.add_url_rule(
"/team/<string:team_key>/matches/<int:year>", view_func=team_matches
)
api_v3.add_url_rule(
"/team/<string:team_key>/matches/<int:year>/<model_type:model_type>",
view_func=team_matches,
)
# Team Media
api_v3.add_url_rule(
"/team/<string:team_key>/media/<int:year>", view_func=team_media_year
)
api_v3.add_url_rule(
"/team/<string:team_key>/media/tag/<string:media_tag>", view_func=team_media_tag
)
api_v3.add_url_rule(
"/team/<string:team_key>/media/tag/<string:media_tag>/<int:year>",
view_func=team_media_tag,
)
# Team List
api_v3.add_url_rule("/teams/all", view_func=team_list_all)
api_v3.add_url_rule("/teams/all/<model_type:model_type>", view_func=team_list_all)
api_v3.add_url_rule("/teams/<int:page_num>", view_func=team_list)
api_v3.add_url_rule(
"/teams/<int:page_num>/<model_type:model_type>", view_func=team_list
)
api_v3.add_url_rule("/teams/<int:year>/<int:page_num>", view_func=team_list)
api_v3.add_url_rule(
"/teams/<int:year>/<int:page_num>/<model_type:model_type>",
view_func=team_list,
)
# Trusted API
trusted_api = Blueprint("trusted_api", __name__, url_prefix="/api/trusted/v1")
CORS(
trusted_api,
origins="*",
methods=["OPTIONS", "POST"],
allow_headers=["Content-Type", "X-TBA-Auth-Id", "X-TBA-Auth-Sig"],
)
trusted_api.add_url_rule(
"/event/<string:event_key>/alliance_selections/update",
methods=["POST"],
view_func=update_event_alliances,
),
trusted_api.add_url_rule(
"/event/<string:event_key>/awards/update",
methods=["POST"],
view_func=update_event_awards,
),
trusted_api.add_url_rule(
"/event/<string:event_key>/info/update",
methods=["POST"],
view_func=update_event_info,
),
trusted_api.add_url_rule(
"/event/<string:event_key>/matches/update",
methods=["POST"],
view_func=update_event_matches,
)
trusted_api.add_url_rule(
"/event/<string:event_key>/matches/delete",
methods=["POST"],
view_func=delete_event_matches,
)
trusted_api.add_url_rule(
"/event/<string:event_key>/matches/delete_all",
methods=["POST"],
view_func=delete_all_event_matches,
)
trusted_api.add_url_rule(
"/event/<string:event_key>/match_videos/add",
methods=["POST"],
view_func=add_match_video,
)
trusted_api.add_url_rule(
"/event/<string:event_key>/media/add",
methods=["POST"],
view_func=add_event_media,
)
trusted_api.add_url_rule(
"/event/<string:event_key>/rankings/update",
methods=["POST"],
view_func=update_event_rankings,
)
trusted_api.add_url_rule(
"/event/<string:event_key>/team_list/update",
methods=["POST"],
view_func=update_teams,
)
trusted_api.add_url_rule(
"/event/<string:event_key>/zebra_motionworks/add",
methods=["POST"],
view_func=add_match_zebra_motionworks_info,
)
@trusted_api.errorhandler(JSONDecodeError)
@trusted_api.errorhandler(ParserInputException)
def handle_bad_input(e: Exception) -> Response:
return make_response(profiled_jsonify({"Error": f"{e}"}), 400)
app.register_blueprint(api_v3)
app.register_blueprint(trusted_api)
app.register_error_handler(404, handle_404)
|
gmjosack/modlunky
|
setup.py
|
#!/usr/bin/env python
from distutils.core import setup
execfile('modlunky/version.py')
with open('requirements.txt') as requirements:
required = requirements.read().splitlines()
kwargs = {
"name": "modlunky",
"version": str(__version__),
"packages": ["modlunky"],
"scripts": ["bin/modlunky"],
"description": "Library and Command Line Tool for Spelunky.",
"author": "Gary M. Josack",
"maintainer": "Gary M. Josack",
"author_email": "gary@byoteki.com",
"maintainer_email": "gary@byoteki.com",
"license": "MIT",
"url": "https://github.com/gmjosack/modlunky",
"download_url": "https://github.com/gmjosack/modlunky/archive/master.tar.gz",
"classifiers": [
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
]
}
if required:
kwargs["install_requires"] = required
setup(**kwargs)
|
grantjenks/pyannote-core
|
pyannote/core/__init__.py
|
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2014 CNRS
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# AUTHORS
# Hervé BREDIN - http://herve.niderb.fr
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
PYANNOTE_URI = 'uri'
PYANNOTE_MODALITY = 'modality'
PYANNOTE_SEGMENT = 'segment'
PYANNOTE_TRACK = 'track'
PYANNOTE_LABEL = 'label'
PYANNOTE_SCORE = 'score'
PYANNOTE_IDENTITY = 'identity'
from .time import T, TStart, TEnd
from .segment import Segment, SlidingWindow
from .timeline import Timeline
from .annotation import Annotation
from .transcription import Transcription
from .scores import Scores
from .feature import SlidingWindowFeature
try:
from .notebook import notebook
except ImportError as e:
pass
|
ellisdg/3DUnetCNN
|
unet3d/utils/normalize.py
|
import numpy as np
def zero_mean_normalize_image_data(data, axis=(0, 1, 2)):
return np.divide(data - data.mean(axis=axis), data.std(axis=axis))
def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5):
data = np.copy(data)
if data.ndim == channel_dim or data.shape[channel_dim] == 1:
# only 1 channel, so the std and mean calculations are straight forward
foreground_mask = np.abs(data) > (background_value + tolerance)
foreground = data[foreground_mask]
mean = foreground.mean()
std = foreground.std()
data[foreground_mask] = np.divide(foreground - mean, std)
return data
else:
# std and mean need to be calculated for each channel in the 4th dimension
for channel in range(data.shape[channel_dim]):
channel_data = data[..., channel]
channel_mask = np.abs(channel_data) > (background_value + tolerance)
channel_foreground = channel_data[channel_mask]
channel_mean = channel_foreground.mean()
channel_std = channel_foreground.std()
channel_data[channel_mask] = np.divide(channel_foreground - channel_mean, channel_std)
data[..., channel] = channel_data
return data
def zero_floor_normalize_image_data(data, axis=(0, 1, 2), floor_percentile=1, floor=0):
floor_threshold = np.percentile(data, floor_percentile, axis=axis)
if data.ndim != len(axis):
floor_threshold_shape = np.asarray(floor_threshold.shape * data.ndim)
floor_threshold_shape[np.asarray(axis)] = 1
floor_threshold = floor_threshold.reshape(floor_threshold_shape)
background = data <= floor_threshold
data = np.ma.masked_array(data - floor_threshold, mask=background)
std = data.std(axis=axis)
if data.ndim != len(axis):
std = std.reshape(floor_threshold_shape)
return np.divide(data, std).filled(floor)
def zero_one_window(data, axis=(0, 1, 2), ceiling_percentile=99, floor_percentile=1, floor=0, ceiling=1,
channels_axis=None):
"""
:param data: Numpy ndarray.
:param axis:
:param ceiling_percentile: Percentile value of the foreground to set to the ceiling.
:param floor_percentile: Percentile value of the image to set to the floor.
:param floor: New minimum value.
:param ceiling: New maximum value.
:param channels_axis:
:return:
"""
data = np.copy(data)
if len(axis) != data.ndim:
floor_threshold = np.percentile(data, floor_percentile, axis=axis)
if channels_axis is None:
channels_axis = find_channel_axis(data.ndim, axis=axis)
data = np.moveaxis(data, channels_axis, 0)
for channel in range(data.shape[0]):
channel_data = data[channel]
# find the background
bg_mask = channel_data <= floor_threshold[channel]
# use background to find foreground
fg = channel_data[bg_mask == False]
# find threshold based on foreground percentile
ceiling_threshold = np.percentile(fg, ceiling_percentile)
# normalize the data for this channel
data[channel] = window_data(channel_data, floor_threshold=floor_threshold[channel],
ceiling_threshold=ceiling_threshold, floor=floor, ceiling=ceiling)
data = np.moveaxis(data, 0, channels_axis)
else:
floor_threshold = np.percentile(data, floor_percentile)
fg_mask = data > floor_threshold
fg = data[fg_mask]
ceiling_threshold = np.percentile(fg, ceiling_percentile)
data = window_data(data, floor_threshold=floor_threshold, ceiling_threshold=ceiling_threshold, floor=floor,
ceiling=ceiling)
return data
def find_channel_axis(ndim, axis):
for i in range(ndim):
if i not in axis and (i - ndim) not in axis:
# I don't understand the second part of this if statement
# answer: it is checking ot make sure that the axis is not indexed in reverse (i.e. axis 3 might be
# indexed as -1)
channels_axis = i
return channels_axis
def static_windows(data, windows, floor=0, ceiling=1):
"""
Normalizes the data according to a set of predefined windows. This is helpful for CT normalization where the
units are static and radiologists often have a set of windowing parameters that the use that allow them to look at
different features in the image.
:param data: 3D numpy array.
:param windows:
:param floor: defaults to 0.
:param ceiling: defaults to 1.
:return: Array with data windows listed in the final dimension
"""
data = np.squeeze(data)
normalized_data = np.ones(data.shape + (len(windows),)) * floor
for i, (l, w) in enumerate(windows):
normalized_data[..., i] = radiology_style_windowing(data, l, w, floor=floor, ceiling=ceiling)
return normalized_data
def radiology_style_windowing(data, l, w, floor=0, ceiling=1):
upper = l + w/2
lower = l - w/2
return window_data(data, floor_threshold=lower, ceiling_threshold=upper, floor=floor, ceiling=ceiling)
def window_data(data, floor_threshold, ceiling_threshold, floor, ceiling):
data = (data - floor_threshold) / (ceiling_threshold - floor_threshold)
# set the data below the floor to equal the floor
data[data < floor] = floor
# set the data above the ceiling to equal the ceiling
data[data > ceiling] = ceiling
return data
def hist_match(source, template):
"""
Source: https://stackoverflow.com/a/33047048
Adjust the pixel values of a grayscale image such that its histogram
matches that of a target image
Arguments:
-----------
source: np.ndarray
Image to transform; the histogram is computed over the flattened
array
template: np.ndarray
Template image; can have different dimensions to source
Returns:
-----------
matched: np.ndarray
The transformed output image
"""
oldshape = source.shape
source = source.ravel()
template = template.ravel()
# get the set of unique pixel values and their corresponding indices and
# counts
s_values, bin_idx, s_counts = np.unique(source, return_inverse=True,
return_counts=True)
t_values, t_counts = np.unique(template, return_counts=True)
# take the cumsum of the counts and normalize by the number of pixels to
# get the empirical cumulative distribution functions for the source and
# template images (maps pixel value --> quantile)
s_quantiles = np.cumsum(s_counts).astype(np.float64)
s_quantiles /= s_quantiles[-1]
t_quantiles = np.cumsum(t_counts).astype(np.float64)
t_quantiles /= t_quantiles[-1]
# interpolate linearly to find the pixel values in the template image
# that correspond most closely to the quantiles in the source image
interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)
return interp_t_values[bin_idx].reshape(oldshape)
|
timrchavez/capomastro
|
projects/templatetags/projects_tags.py
|
from django.template.base import Library
from django.core.urlresolvers import reverse
from projects.models import ProjectBuild
register = Library()
@register.simple_tag()
def build_url(build_id):
"""
Fetches the ProjectBuild for a given build_id, if any.
"""
try:
build = ProjectBuild.objects.get(build_id=build_id)
return reverse(
"project_projectbuild_detail",
kwargs={"project_pk": build.project.pk, "build_pk": build.pk})
except ProjectBuild.DoesNotExist:
return ""
|
walidsa3d/shaman
|
shaman/providers/api.py
|
from allocine import allocine
from constants import *
from elcinema import elcinema
from imdb import imdby as Imdb
from rotten import rotten
from tmdb import tmdb
def search(query, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rottentomatoes":
provider = rotten(rotten_key)
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site == "allocine":
provider = allocine()
results = provider.search(query)
return results
def info(movie_id, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rottentomatoes":
provider = rotten(rotten_key)
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site == "allocine":
provider = allocine()
result = provider.info(movie_id)
return result
|
nicoddemus/pytest
|
src/_pytest/logging.py
|
"""Access and control log capturing."""
import logging
import os
import re
import sys
from contextlib import contextmanager
from io import StringIO
from pathlib import Path
from typing import AbstractSet
from typing import Dict
from typing import Generator
from typing import List
from typing import Mapping
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union
from _pytest import nodes
from _pytest._io import TerminalWriter
from _pytest.capture import CaptureManager
from _pytest.compat import final
from _pytest.compat import nullcontext
from _pytest.config import _strtobool
from _pytest.config import Config
from _pytest.config import create_terminal_writer
from _pytest.config import hookimpl
from _pytest.config import UsageError
from _pytest.config.argparsing import Parser
from _pytest.deprecated import check_ispytest
from _pytest.fixtures import fixture
from _pytest.fixtures import FixtureRequest
from _pytest.main import Session
from _pytest.store import StoreKey
from _pytest.terminal import TerminalReporter
DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
caplog_handler_key = StoreKey["LogCaptureHandler"]()
caplog_records_key = StoreKey[Dict[str, List[logging.LogRecord]]]()
def _remove_ansi_escape_sequences(text: str) -> str:
return _ANSI_ESCAPE_SEQ.sub("", text)
class ColoredLevelFormatter(logging.Formatter):
"""A logging formatter which colorizes the %(levelname)..s part of the
log format passed to __init__."""
LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = {
logging.CRITICAL: {"red"},
logging.ERROR: {"red", "bold"},
logging.WARNING: {"yellow"},
logging.WARN: {"yellow"},
logging.INFO: {"green"},
logging.DEBUG: {"purple"},
logging.NOTSET: set(),
}
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)")
def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._original_fmt = self._style._fmt
self._level_to_fmt_mapping: Dict[int, str] = {}
assert self._fmt is not None
levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
if not levelname_fmt_match:
return
levelname_fmt = levelname_fmt_match.group()
for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
formatted_levelname = levelname_fmt % {
"levelname": logging.getLevelName(level)
}
# add ANSI escape sequences around the formatted levelname
color_kwargs = {name: True for name in color_opts}
colorized_formatted_levelname = terminalwriter.markup(
formatted_levelname, **color_kwargs
)
self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
colorized_formatted_levelname, self._fmt
)
def format(self, record: logging.LogRecord) -> str:
fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
self._style._fmt = fmt
return super().format(record)
class PercentStyleMultiline(logging.PercentStyle):
"""A logging style with special support for multiline messages.
If the message of a record consists of multiple lines, this style
formats the message as if each line were logged separately.
"""
def __init__(self, fmt: str, auto_indent: Union[int, str, bool, None]) -> None:
super().__init__(fmt)
self._auto_indent = self._get_auto_indent(auto_indent)
@staticmethod
def _update_message(
record_dict: Dict[str, object], message: str
) -> Dict[str, object]:
tmp = record_dict.copy()
tmp["message"] = message
return tmp
@staticmethod
def _get_auto_indent(auto_indent_option: Union[int, str, bool, None]) -> int:
"""Determine the current auto indentation setting.
Specify auto indent behavior (on/off/fixed) by passing in
extra={"auto_indent": [value]} to the call to logging.log() or
using a --log-auto-indent [value] command line or the
log_auto_indent [value] config option.
Default behavior is auto-indent off.
Using the string "True" or "on" or the boolean True as the value
turns auto indent on, using the string "False" or "off" or the
boolean False or the int 0 turns it off, and specifying a
positive integer fixes the indentation position to the value
specified.
Any other values for the option are invalid, and will silently be
converted to the default.
:param None|bool|int|str auto_indent_option:
User specified option for indentation from command line, config
or extra kwarg. Accepts int, bool or str. str option accepts the
same range of values as boolean config options, as well as
positive integers represented in str form.
:returns:
Indentation value, which can be
-1 (automatically determine indentation) or
0 (auto-indent turned off) or
>0 (explicitly set indentation position).
"""
if auto_indent_option is None:
return 0
elif isinstance(auto_indent_option, bool):
if auto_indent_option:
return -1
else:
return 0
elif isinstance(auto_indent_option, int):
return int(auto_indent_option)
elif isinstance(auto_indent_option, str):
try:
return int(auto_indent_option)
except ValueError:
pass
try:
if _strtobool(auto_indent_option):
return -1
except ValueError:
return 0
return 0
def format(self, record: logging.LogRecord) -> str:
if "\n" in record.message:
if hasattr(record, "auto_indent"):
# Passed in from the "extra={}" kwarg on the call to logging.log().
auto_indent = self._get_auto_indent(record.auto_indent) # type: ignore[attr-defined]
else:
auto_indent = self._auto_indent
if auto_indent:
lines = record.message.splitlines()
formatted = self._fmt % self._update_message(record.__dict__, lines[0])
if auto_indent < 0:
indentation = _remove_ansi_escape_sequences(formatted).find(
lines[0]
)
else:
# Optimizes logging by allowing a fixed indentation.
indentation = auto_indent
lines[0] = formatted
return ("\n" + " " * indentation).join(lines)
return self._fmt % record.__dict__
def get_option_ini(config: Config, *names: str):
for name in names:
ret = config.getoption(name) # 'default' arg won't work as expected
if ret is None:
ret = config.getini(name)
if ret:
return ret
def pytest_addoption(parser: Parser) -> None:
"""Add options to control log capturing."""
group = parser.getgroup("logging")
def add_option_ini(option, dest, default=None, type=None, **kwargs):
parser.addini(
dest, default=default, type=type, help="default value for " + option
)
group.addoption(option, dest=dest, **kwargs)
add_option_ini(
"--log-level",
dest="log_level",
default=None,
metavar="LEVEL",
help=(
"level of messages to catch/display.\n"
"Not set by default, so it depends on the root/parent log handler's"
' effective level, where it is "WARNING" by default.'
),
)
add_option_ini(
"--log-format",
dest="log_format",
default=DEFAULT_LOG_FORMAT,
help="log format as used by the logging module.",
)
add_option_ini(
"--log-date-format",
dest="log_date_format",
default=DEFAULT_LOG_DATE_FORMAT,
help="log date format as used by the logging module.",
)
parser.addini(
"log_cli",
default=False,
type="bool",
help='enable log display during test run (also known as "live logging").',
)
add_option_ini(
"--log-cli-level", dest="log_cli_level", default=None, help="cli logging level."
)
add_option_ini(
"--log-cli-format",
dest="log_cli_format",
default=None,
help="log format as used by the logging module.",
)
add_option_ini(
"--log-cli-date-format",
dest="log_cli_date_format",
default=None,
help="log date format as used by the logging module.",
)
add_option_ini(
"--log-file",
dest="log_file",
default=None,
help="path to a file when logging will be written to.",
)
add_option_ini(
"--log-file-level",
dest="log_file_level",
default=None,
help="log file logging level.",
)
add_option_ini(
"--log-file-format",
dest="log_file_format",
default=DEFAULT_LOG_FORMAT,
help="log format as used by the logging module.",
)
add_option_ini(
"--log-file-date-format",
dest="log_file_date_format",
default=DEFAULT_LOG_DATE_FORMAT,
help="log date format as used by the logging module.",
)
add_option_ini(
"--log-auto-indent",
dest="log_auto_indent",
default=None,
help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.",
)
_HandlerType = TypeVar("_HandlerType", bound=logging.Handler)
# Not using @contextmanager for performance reasons.
class catching_logs:
"""Context manager that prepares the whole logging machinery properly."""
__slots__ = ("handler", "level", "orig_level")
def __init__(self, handler: _HandlerType, level: Optional[int] = None) -> None:
self.handler = handler
self.level = level
def __enter__(self):
root_logger = logging.getLogger()
if self.level is not None:
self.handler.setLevel(self.level)
root_logger.addHandler(self.handler)
if self.level is not None:
self.orig_level = root_logger.level
root_logger.setLevel(min(self.orig_level, self.level))
return self.handler
def __exit__(self, type, value, traceback):
root_logger = logging.getLogger()
if self.level is not None:
root_logger.setLevel(self.orig_level)
root_logger.removeHandler(self.handler)
class LogCaptureHandler(logging.StreamHandler):
"""A logging handler that stores log records and the log text."""
stream: StringIO
def __init__(self) -> None:
"""Create a new log handler."""
super().__init__(StringIO())
self.records: List[logging.LogRecord] = []
def emit(self, record: logging.LogRecord) -> None:
"""Keep the log records in a list in addition to the log text."""
self.records.append(record)
super().emit(record)
def reset(self) -> None:
self.records = []
self.stream = StringIO()
def handleError(self, record: logging.LogRecord) -> None:
if logging.raiseExceptions:
# Fail the test if the log message is bad (emit failed).
# The default behavior of logging is to print "Logging error"
# to stderr with the call stack and some extra details.
# pytest wants to make such mistakes visible during testing.
raise
@final
class LogCaptureFixture:
"""Provides access and control of log capturing."""
def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None:
check_ispytest(_ispytest)
self._item = item
self._initial_handler_level: Optional[int] = None
# Dict of log name -> log level.
self._initial_logger_levels: Dict[Optional[str], int] = {}
def _finalize(self) -> None:
"""Finalize the fixture.
This restores the log levels changed by :meth:`set_level`.
"""
# Restore log levels.
if self._initial_handler_level is not None:
self.handler.setLevel(self._initial_handler_level)
for logger_name, level in self._initial_logger_levels.items():
logger = logging.getLogger(logger_name)
logger.setLevel(level)
@property
def handler(self) -> LogCaptureHandler:
"""Get the logging handler used by the fixture.
:rtype: LogCaptureHandler
"""
return self._item._store[caplog_handler_key]
def get_records(self, when: str) -> List[logging.LogRecord]:
"""Get the logging records for one of the possible test phases.
:param str when:
Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown".
:returns: The list of captured records at the given stage.
:rtype: List[logging.LogRecord]
.. versionadded:: 3.4
"""
return self._item._store[caplog_records_key].get(when, [])
@property
def text(self) -> str:
"""The formatted log text."""
return _remove_ansi_escape_sequences(self.handler.stream.getvalue())
@property
def records(self) -> List[logging.LogRecord]:
"""The list of log records."""
return self.handler.records
@property
def record_tuples(self) -> List[Tuple[str, int, str]]:
"""A list of a stripped down version of log records intended
for use in assertion comparison.
The format of the tuple is:
(logger_name, log_level, message)
"""
return [(r.name, r.levelno, r.getMessage()) for r in self.records]
@property
def messages(self) -> List[str]:
"""A list of format-interpolated log messages.
Unlike 'records', which contains the format string and parameters for
interpolation, log messages in this list are all interpolated.
Unlike 'text', which contains the output from the handler, log
messages in this list are unadorned with levels, timestamps, etc,
making exact comparisons more reliable.
Note that traceback or stack info (from :func:`logging.exception` or
the `exc_info` or `stack_info` arguments to the logging functions) is
not included, as this is added by the formatter in the handler.
.. versionadded:: 3.7
"""
return [r.getMessage() for r in self.records]
def clear(self) -> None:
"""Reset the list of log records and the captured log text."""
self.handler.reset()
def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None:
"""Set the level of a logger for the duration of a test.
.. versionchanged:: 3.4
The levels of the loggers changed by this function will be
restored to their initial values at the end of the test.
:param int level: The level.
:param str logger: The logger to update. If not given, the root logger.
"""
logger_obj = logging.getLogger(logger)
# Save the original log-level to restore it during teardown.
self._initial_logger_levels.setdefault(logger, logger_obj.level)
logger_obj.setLevel(level)
if self._initial_handler_level is None:
self._initial_handler_level = self.handler.level
self.handler.setLevel(level)
@contextmanager
def at_level(
self, level: int, logger: Optional[str] = None
) -> Generator[None, None, None]:
"""Context manager that sets the level for capturing of logs. After
the end of the 'with' statement the level is restored to its original
value.
:param int level: The level.
:param str logger: The logger to update. If not given, the root logger.
"""
logger_obj = logging.getLogger(logger)
orig_level = logger_obj.level
logger_obj.setLevel(level)
handler_orig_level = self.handler.level
self.handler.setLevel(level)
try:
yield
finally:
logger_obj.setLevel(orig_level)
self.handler.setLevel(handler_orig_level)
@fixture
def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture, None, None]:
"""Access and control log capturing.
Captured logs are available through the following properties/methods::
* caplog.messages -> list of format-interpolated log messages
* caplog.text -> string containing formatted log output
* caplog.records -> list of logging.LogRecord instances
* caplog.record_tuples -> list of (logger_name, level, message) tuples
* caplog.clear() -> clear captured records and formatted log output string
"""
result = LogCaptureFixture(request.node, _ispytest=True)
yield result
result._finalize()
def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]:
for setting_name in setting_names:
log_level = config.getoption(setting_name)
if log_level is None:
log_level = config.getini(setting_name)
if log_level:
break
else:
return None
if isinstance(log_level, str):
log_level = log_level.upper()
try:
return int(getattr(logging, log_level, log_level))
except ValueError as e:
# Python logging does not recognise this as a logging level
raise UsageError(
"'{}' is not recognized as a logging level name for "
"'{}'. Please consider passing the "
"logging level num instead.".format(log_level, setting_name)
) from e
# run after terminalreporter/capturemanager are configured
@hookimpl(trylast=True)
def pytest_configure(config: Config) -> None:
config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
class LoggingPlugin:
"""Attaches to the logging module and captures log messages for each test."""
def __init__(self, config: Config) -> None:
"""Create a new plugin to capture log messages.
The formatter can be safely shared across all handlers so
create a single one for the entire test session here.
"""
self._config = config
# Report logging.
self.formatter = self._create_formatter(
get_option_ini(config, "log_format"),
get_option_ini(config, "log_date_format"),
get_option_ini(config, "log_auto_indent"),
)
self.log_level = get_log_level_for_setting(config, "log_level")
self.caplog_handler = LogCaptureHandler()
self.caplog_handler.setFormatter(self.formatter)
self.report_handler = LogCaptureHandler()
self.report_handler.setFormatter(self.formatter)
# File logging.
self.log_file_level = get_log_level_for_setting(config, "log_file_level")
log_file = get_option_ini(config, "log_file") or os.devnull
if log_file != os.devnull:
directory = os.path.dirname(os.path.abspath(log_file))
if not os.path.isdir(directory):
os.makedirs(directory)
self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8")
log_file_format = get_option_ini(config, "log_file_format", "log_format")
log_file_date_format = get_option_ini(
config, "log_file_date_format", "log_date_format"
)
log_file_formatter = logging.Formatter(
log_file_format, datefmt=log_file_date_format
)
self.log_file_handler.setFormatter(log_file_formatter)
# CLI/live logging.
self.log_cli_level = get_log_level_for_setting(
config, "log_cli_level", "log_level"
)
if self._log_cli_enabled():
terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
capture_manager = config.pluginmanager.get_plugin("capturemanager")
# if capturemanager plugin is disabled, live logging still works.
self.log_cli_handler: Union[
_LiveLoggingStreamHandler, _LiveLoggingNullHandler
] = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)
else:
self.log_cli_handler = _LiveLoggingNullHandler()
log_cli_formatter = self._create_formatter(
get_option_ini(config, "log_cli_format", "log_format"),
get_option_ini(config, "log_cli_date_format", "log_date_format"),
get_option_ini(config, "log_auto_indent"),
)
self.log_cli_handler.setFormatter(log_cli_formatter)
def _create_formatter(self, log_format, log_date_format, auto_indent):
# Color option doesn't exist if terminal plugin is disabled.
color = getattr(self._config.option, "color", "no")
if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(
log_format
):
formatter: logging.Formatter = ColoredLevelFormatter(
create_terminal_writer(self._config), log_format, log_date_format
)
else:
formatter = logging.Formatter(log_format, log_date_format)
formatter._style = PercentStyleMultiline(
formatter._style._fmt, auto_indent=auto_indent
)
return formatter
def set_log_path(self, fname: str) -> None:
"""Set the filename parameter for Logging.FileHandler().
Creates parent directory if it does not exist.
.. warning::
This is an experimental API.
"""
fpath = Path(fname)
if not fpath.is_absolute():
fpath = self._config.rootpath / fpath
if not fpath.parent.exists():
fpath.parent.mkdir(exist_ok=True, parents=True)
stream = fpath.open(mode="w", encoding="UTF-8")
if sys.version_info >= (3, 7):
old_stream = self.log_file_handler.setStream(stream)
else:
old_stream = self.log_file_handler.stream
self.log_file_handler.acquire()
try:
self.log_file_handler.flush()
self.log_file_handler.stream = stream
finally:
self.log_file_handler.release()
if old_stream:
old_stream.close()
def _log_cli_enabled(self):
"""Return whether live logging is enabled."""
enabled = self._config.getoption(
"--log-cli-level"
) is not None or self._config.getini("log_cli")
if not enabled:
return False
terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter")
if terminal_reporter is None:
# terminal reporter is disabled e.g. by pytest-xdist.
return False
return True
@hookimpl(hookwrapper=True, tryfirst=True)
def pytest_sessionstart(self) -> Generator[None, None, None]:
self.log_cli_handler.set_when("sessionstart")
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
with catching_logs(self.log_file_handler, level=self.log_file_level):
yield
@hookimpl(hookwrapper=True, tryfirst=True)
def pytest_collection(self) -> Generator[None, None, None]:
self.log_cli_handler.set_when("collection")
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
with catching_logs(self.log_file_handler, level=self.log_file_level):
yield
@hookimpl(hookwrapper=True)
def pytest_runtestloop(self, session: Session) -> Generator[None, None, None]:
if session.config.option.collectonly:
yield
return
if self._log_cli_enabled() and self._config.getoption("verbose") < 1:
# The verbose flag is needed to avoid messy test progress output.
self._config.option.verbose = 1
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
with catching_logs(self.log_file_handler, level=self.log_file_level):
yield # Run all the tests.
@hookimpl
def pytest_runtest_logstart(self) -> None:
self.log_cli_handler.reset()
self.log_cli_handler.set_when("start")
@hookimpl
def pytest_runtest_logreport(self) -> None:
self.log_cli_handler.set_when("logreport")
def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]:
"""Implement the internals of the pytest_runtest_xxx() hooks."""
with catching_logs(
self.caplog_handler,
level=self.log_level,
) as caplog_handler, catching_logs(
self.report_handler,
level=self.log_level,
) as report_handler:
caplog_handler.reset()
report_handler.reset()
item._store[caplog_records_key][when] = caplog_handler.records
item._store[caplog_handler_key] = caplog_handler
yield
log = report_handler.stream.getvalue().strip()
item.add_report_section(when, "log", log)
@hookimpl(hookwrapper=True)
def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None, None, None]:
self.log_cli_handler.set_when("setup")
empty: Dict[str, List[logging.LogRecord]] = {}
item._store[caplog_records_key] = empty
yield from self._runtest_for(item, "setup")
@hookimpl(hookwrapper=True)
def pytest_runtest_call(self, item: nodes.Item) -> Generator[None, None, None]:
self.log_cli_handler.set_when("call")
yield from self._runtest_for(item, "call")
@hookimpl(hookwrapper=True)
def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None, None, None]:
self.log_cli_handler.set_when("teardown")
yield from self._runtest_for(item, "teardown")
del item._store[caplog_records_key]
del item._store[caplog_handler_key]
@hookimpl
def pytest_runtest_logfinish(self) -> None:
self.log_cli_handler.set_when("finish")
@hookimpl(hookwrapper=True, tryfirst=True)
def pytest_sessionfinish(self) -> Generator[None, None, None]:
self.log_cli_handler.set_when("sessionfinish")
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
with catching_logs(self.log_file_handler, level=self.log_file_level):
yield
@hookimpl
def pytest_unconfigure(self) -> None:
# Close the FileHandler explicitly.
# (logging.shutdown might have lost the weakref?!)
self.log_file_handler.close()
class _FileHandler(logging.FileHandler):
"""A logging FileHandler with pytest tweaks."""
def handleError(self, record: logging.LogRecord) -> None:
# Handled by LogCaptureHandler.
pass
class _LiveLoggingStreamHandler(logging.StreamHandler):
"""A logging StreamHandler used by the live logging feature: it will
write a newline before the first log message in each test.
During live logging we must also explicitly disable stdout/stderr
capturing otherwise it will get captured and won't appear in the
terminal.
"""
# Officially stream needs to be a IO[str], but TerminalReporter
# isn't. So force it.
stream: TerminalReporter = None # type: ignore
def __init__(
self,
terminal_reporter: TerminalReporter,
capture_manager: Optional[CaptureManager],
) -> None:
logging.StreamHandler.__init__(self, stream=terminal_reporter) # type: ignore[arg-type]
self.capture_manager = capture_manager
self.reset()
self.set_when(None)
self._test_outcome_written = False
def reset(self) -> None:
"""Reset the handler; should be called before the start of each test."""
self._first_record_emitted = False
def set_when(self, when: Optional[str]) -> None:
"""Prepare for the given test phase (setup/call/teardown)."""
self._when = when
self._section_name_shown = False
if when == "start":
self._test_outcome_written = False
def emit(self, record: logging.LogRecord) -> None:
ctx_manager = (
self.capture_manager.global_and_fixture_disabled()
if self.capture_manager
else nullcontext()
)
with ctx_manager:
if not self._first_record_emitted:
self.stream.write("\n")
self._first_record_emitted = True
elif self._when in ("teardown", "finish"):
if not self._test_outcome_written:
self._test_outcome_written = True
self.stream.write("\n")
if not self._section_name_shown and self._when:
self.stream.section("live log " + self._when, sep="-", bold=True)
self._section_name_shown = True
super().emit(record)
def handleError(self, record: logging.LogRecord) -> None:
# Handled by LogCaptureHandler.
pass
class _LiveLoggingNullHandler(logging.NullHandler):
"""A logging handler used when live logging is disabled."""
def reset(self) -> None:
pass
def set_when(self, when: str) -> None:
pass
def handleError(self, record: logging.LogRecord) -> None:
# Handled by LogCaptureHandler.
pass
|
sarojaerabelli/HVGS
|
CareerTinderServer/CareerTinder/migrations/0005_auto_20160918_0221.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-18 06:21
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('CareerTinder', '0004_auto_20160918_0152'),
]
operations = [
migrations.RenameField(
model_name='hiree',
old_name='first_name',
new_name='email',
),
migrations.RenameField(
model_name='hiree',
old_name='last_name',
new_name='name',
),
]
|
mic4ael/indico
|
indico/util/passwords.py
|
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
import bcrypt
class BCryptPassword(object):
def __init__(self, hash_):
self.hash = str(hash_)
def __eq__(self, value):
if not self.hash or not value:
# For security reasons we never consider an empty password/hash valid
return False
if isinstance(value, unicode):
value = value.encode('utf-8')
return bcrypt.checkpw(value, self.hash)
def __ne__(self, other):
return not (self == other)
def __hash__(self): # pragma: no cover
return hash(self.hash)
def __repr__(self):
return '<BCryptPassword({})>'.format(self.hash)
@staticmethod
def hash(value):
if isinstance(value, unicode):
value = value.encode('utf-8')
return bcrypt.hashpw(value, bcrypt.gensalt())
class PasswordProperty(object):
"""Defines a hashed password property.
When reading this property, it will return an object which will
let you use the ``==`` operator to compare the password against
a plaintext password. When assigning a value to it, it will be
hashed and stored in :attr:`attr` of the containing object.
:param attr: The attribute of the containing object where the
password hash is stored.
:param backend: The password backend that handles hashing/checking
passwords.
"""
def __init__(self, attr, backend=BCryptPassword):
self.attr = attr
self.backend = backend
def __get__(self, instance, owner):
return self.backend(getattr(instance, self.attr, None)) if instance is not None else self
def __set__(self, instance, value):
if not value:
raise ValueError('Password may not be empty')
setattr(instance, self.attr, self.backend.hash(value))
def __delete__(self, instance):
setattr(instance, self.attr, None)
|
bsiegfreid/tkdraw
|
tkdraw/config.py
|
import os
from appdirs import AppDirs
class Config:
def __init__(self):
self.app_dir = get_app_dir()
def save_geometry(self, window):
path = os.path.join(self.app_dir, 'geometry.conf')
print(path)
with open(path, "w") as conf:
conf.write(window.geometry())
def read_geometry(self):
path = os.path.join(self.app_dir, 'geometry.conf')
try:
with open(path, "w") as conf:
geometry = conf.read()
# TODO Validate!
except IOError:
geometry = ''
print(geometry)
return geometry
def get_app_dir():
app_dirs = AppDirs('tkdraw', 'tkdraw')
user_config_dir = os.path.normpath(app_dirs.user_config_dir)
if not os.path.isdir(user_config_dir):
os.makedirs(user_config_dir)
return user_config_dir
|
thonkify/thonkify
|
src/lib/sparkpost/tornado/base.py
|
import json
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError
from .exceptions import SparkPostAPIException
class TornadoTransport(object):
@gen.coroutine
def request(self, method, uri, headers, **kwargs):
if "data" in kwargs:
kwargs["body"] = kwargs.pop("data")
client = AsyncHTTPClient()
try:
response = yield client.fetch(uri, method=method, headers=headers,
**kwargs)
except HTTPError as ex:
raise SparkPostAPIException(ex.response)
if response.code == 204:
raise gen.Return(True)
if response.code == 200:
result = None
try:
result = json.loads(response.body.decode("utf-8"))
except:
pass
if result:
if 'results' in result:
raise gen.Return(result['results'])
raise gen.Return(result)
raise SparkPostAPIException(response)
|
injectnique/KnuckleHeadedMcSpazatron
|
GenericBytecode.py
|
#!C:\Python27\python.exe
# Filename: GenericBytecode.py
# -*- coding: utf-8 -*-
import os
import Settings
'''
Generic Bytecode
Simply add, remove or modify bytecode for use in KHMS
'''
createFrame = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1',
'iconst_1', 'iadd', 'putfield', 'iload_1', 'aload_0', 'getfield', \
'invokevirtual', 'iadd', 'i2b', 'bastore', 'return']
writeDWord = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \
'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \
'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
'bipush', 'ishr', 'i2b', 'bastore', 'aload_0', 'getfield', \
'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \
'putfield', 'iload_1', 'bipush', 'ishr', 'i2b', 'bastore', \
'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', 'return']
# writeWordBigEndian = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \
# 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
# 'i2b', 'bastore', 'return', 'aload_0', 'dup', 'getfield', \
# 'iconst_3', 'iadd', 'putfield', 'sipush', 'aload_0', \
# 'getfield', 'aload_0', 'getfield', 'iconst_3', 'isub', \
# 'baload', 'bipush', 'ishl', 'iand', 'sipush', 'aload_0', \
# 'getfield', 'aload_0', 'getfield', 'iconst_2', 'isub', \
# 'baload', 'bipush', 'ishl', 'iand', 'iadd', 'sipush', \
# 'aload_0', 'getfield', 'aload_0', 'getfield', 'iconst_1', \
# 'isub', 'baload', 'iand', 'iadd', 'ireturn']
writeWordBigEndian = ['aload_0',
'getfield Stream/buffer [B',
'aload_0',
'dup',
'getfield Stream/currentOffset I',
'dup_x1',
'iconst_1',
'iadd',
'putfield Stream/currentOffset I',
'iload_1',
'i2b',
'bastore',
'return']
writeWord = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \
'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \
'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
'i2b', 'bastore', 'return']
writeDWordBigEndian = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \
'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
'bipush', 'ishr', 'i2b', 'bastore', 'aload_0', \
'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', \
'ishr', 'i2b', 'bastore', 'aload_0', 'getfield', \
'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', \
'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', 'return']
method403 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', \
'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \
'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \
'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
'bipush', 'ishr', 'i2b', 'bastore', 'aload_0', 'getfield', \
'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \
'putfield', 'iload_1', 'bipush', 'ishr', 'i2b', 'bastore', 'return']
writeQWord = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'lload_1', 'bipush', 'lshr', \
'l2i', 'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', \
'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', \
'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', 'bastore', 'aload_0', \
'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', \
'iadd', 'putfield', 'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', \
'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \
'dup_x1', 'iconst_1', 'iadd', 'putfield', 'lload_1', 'bipush', \
'lshr', 'l2i', 'i2b', 'bastore', 'aload_0', 'getfield', \
'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \
'putfield', 'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', \
'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \
'dup_x1', 'iconst_1', 'iadd', 'putfield', 'lload_1', 'bipush', \
'lshr', 'l2i', 'i2b', 'bastore', 'aload_0', 'getfield', \
'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \
'putfield', 'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', \
'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \
'dup_x1', 'iconst_1', 'iadd', 'putfield', 'lload_1', 'l2i', \
'i2b', 'bastore', 'goto', 'astore_3', 'new', 'dup', \
'invokespecial', 'ldc', 'invokevirtual', 'lload_1', \
'invokevirtual', 'ldc', 'invokevirtual', 'aload_3', \
'invokevirtual', 'invokevirtual', 'invokevirtual', \
'invokestatic', 'new', 'dup', 'invokespecial', 'athrow', 'return']
writeString = ['aload_1', 'invokevirtual', 'iconst_0', 'aload_0', 'getfield', \
'aload_0', 'getfield', 'aload_1', 'invokevirtual', \
'invokestatic', 'aload_0', 'dup', 'getfield', 'aload_1', \
'invokevirtual', 'iadd', 'putfield', 'aload_0', 'getfield', \
'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \
'putfield', 'bipush', 'bastore', 'return']
method424 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'ineg', 'i2b', \
'bastore', 'return']
method425 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'sipush', 'iload_1', 'isub', \
'i2b', 'bastore', 'return']
method431 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', \
'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \
'i2b', 'bastore', 'return']
method432 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \
'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \
'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
'sipush', 'iadd', 'i2b', 'bastore', 'return']
method433 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'sipush', 'iadd', \
'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \
'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
'bipush', 'ishr', 'i2b', 'bastore', 'return']
getNextKey = ['aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'isub', \
'putfield', 'ifne', 'aload_0', 'invokespecial', 'aload_0', \
'sipush', 'putfield', 'aload_0', 'getfield', 'aload_0', \
'getfield', 'iaload', 'ireturn']
isaac = ['aload_0', 'dup', 'getfield', 'aload_0', 'dup', 'getfield', \
'iconst_1', 'iadd', 'dup_x1', 'putfield', 'iadd', 'putfield', \
'iconst_0', 'istore_1', 'goto', 'aload_0', 'getfield', 'iload_1', \
'iaload', 'istore_2', 'iload_1', 'iconst_3', 'iand', 'ifne', \
'aload_0', 'dup', 'getfield', 'aload_0', 'getfield', 'bipush', \
'ishl', 'ixor', 'putfield', 'goto', 'iload_1', 'iconst_3', 'iand', \
'iconst_1', 'if_icmpne', 'aload_0', 'dup', 'getfield', 'aload_0', \
'getfield', 'bipush', 'iushr', 'ixor', 'putfield', 'goto', \
'iload_1', 'iconst_3', 'iand', 'iconst_2', 'if_icmpne', 'aload_0', \
'dup', 'getfield', 'aload_0', 'getfield', 'iconst_2', 'ishl', \
'ixor', 'putfield', 'goto', 'iload_1', 'iconst_3', 'iand', \
'iconst_3', 'if_icmpne', 'aload_0', 'dup', 'getfield', 'aload_0', \
'getfield', 'bipush', 'iushr', 'ixor', 'putfield', 'aload_0', \
'dup', 'getfield', 'aload_0', 'getfield', 'iload_1', 'sipush', \
'iadd', 'sipush', 'iand', 'iaload', 'iadd', 'putfield', 'aload_0', \
'getfield', 'iload_1', 'aload_0', 'getfield', 'iload_2', 'sipush', \
'iand', 'iconst_2', 'ishr', 'iaload', 'aload_0', 'getfield', \
'iadd', 'aload_0', 'getfield', 'iadd', 'dup', 'istore_3', \
'iastore', 'aload_0', 'getfield', 'iload_1', 'aload_0', 'aload_0', \
'getfield', 'iload_3', 'bipush', 'ishr', 'sipush', 'iand', \
'iconst_2', 'ishr', 'iaload', 'iload_2', 'iadd', 'dup_x1', \
'putfield', 'iastore', 'iinc', 'iload_1', 'sipush', \
'if_icmplt', 'return']
initializeKeySet2 = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', 'istore', \
'dup', 'istore', 'dup', 'istore_3', 'dup', 'istore_2', \
'dup', 'istore_1', 'istore', 'iconst_0', 'istore', \
'iload', 'iconst_4', 'if_icmpge', 'iload', 'iload_1', \
'bipush', 'ishl', 'ixor', 'istore', 'iload_3', 'iload', \
'iadd', 'istore_3', 'iload_1', 'iload_2', 'iadd', \
'istore_1', 'iload_1', 'iload_2', 'iconst_2', 'iushr', \
'ixor', 'istore_1', 'iload', 'iload_1', 'iadd', 'istore', \
'iload_2', 'iload_3', 'iadd', 'istore_2', 'iload_2', \
'iload_3', 'bipush', 'ishl', 'ixor', 'istore_2', \
'iload', 'iload_2', 'iadd', 'istore', 'iload_3', \
'iload', 'iadd', 'istore_3', 'iload_3', 'iload', \
'bipush', 'iushr', 'ixor', 'istore_3', 'iload', \
'iload_3', 'iadd', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'bipush', 'ishl', 'ixor', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', \
'iconst_4', 'iushr', 'ixor', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'bipush', 'ishl', 'ixor', \
'istore', 'iload_1', 'iload', 'iadd', 'istore_1', \
'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'bipush', 'iushr', 'ixor', 'istore', \
'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \
'iload_1', 'iadd', 'istore', 'iinc', 'goto', \
'iconst_0', 'istore', 'iload', 'sipush', 'if_icmpge', \
'iload', 'aload_0', 'getfield', 'iload', 'iaload', \
'iadd', 'istore', 'iload_1', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iaload', 'iadd', \
'istore_1', 'iload_2', 'aload_0', 'getfield', \
'iload', 'iconst_2', 'iadd', 'iaload', 'iadd', \
'istore_2', 'iload_3', 'aload_0', 'getfield', \
'iload', 'iconst_3', 'iadd', 'iaload', 'iadd', \
'istore_3', 'iload', 'aload_0', 'getfield', \
'iload', 'iconst_4', 'iadd', 'iaload', 'iadd', \
'istore', 'iload', 'aload_0', 'getfield', 'iload', \
'iconst_5', 'iadd', 'iaload', 'iadd', 'istore', \
'iload', 'aload_0', 'getfield', 'iload', 'bipush', \
'iadd', 'iaload', 'iadd', 'istore', 'iload', 'aload_0', \
'getfield', 'iload', 'bipush', 'iadd', 'iaload', 'iadd', \
'istore', 'iload', 'iload_1', 'bipush', 'ishl', 'ixor', \
'istore', 'iload_3', 'iload', 'iadd', 'istore_3', \
'iload_1', 'iload_2', 'iadd', 'istore_1', 'iload_1', \
'iload_2', 'iconst_2', 'iushr', 'ixor', 'istore_1', \
'iload', 'iload_1', 'iadd', 'istore', 'iload_2', \
'iload_3', 'iadd', 'istore_2', 'iload_2', 'iload_3', \
'bipush', 'ishl', 'ixor', 'istore_2', 'iload', \
'iload_2', 'iadd', 'istore', 'iload_3', 'iload', \
'iadd', 'istore_3', 'iload_3', 'iload', 'bipush', \
'iushr', 'ixor', 'istore_3', 'iload', 'iload_3', \
'iadd', 'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'bipush', 'ishl', 'ixor', 'istore', \
'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \
'iadd', 'istore', 'iload', 'iload', 'iconst_4', \
'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'bipush', 'ishl', 'ixor', 'istore', \
'iload_1', 'iload', 'iadd', 'istore_1', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', \
'bipush', 'iushr', 'ixor', 'istore', 'iload_2', \
'iload', 'iadd', 'istore_2', 'iload', 'iload_1', \
'iadd', 'istore', 'aload_0', 'getfield', 'iload', \
'iload', 'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_1', 'iadd', 'iload_1', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_2', 'iadd', 'iload_2', \
'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', 'iconst_5', \
'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iload', 'iastore', \
'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \
'iload', 'iastore', 'iinc', 'goto', 'iconst_0', \
'istore', 'iload', 'sipush', 'if_icmpge', 'iload', \
'aload_0', 'getfield', 'iload', 'iaload', 'iadd', \
'istore', 'iload_1', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iaload', 'iadd', \
'istore_1', 'iload_2', 'aload_0', 'getfield', \
'iload', 'iconst_2', 'iadd', 'iaload', 'iadd', \
'istore_2', 'iload_3', 'aload_0', 'getfield', \
'iload', 'iconst_3', 'iadd', 'iaload', 'iadd', \
'istore_3', 'iload', 'aload_0', 'getfield', \
'iload', 'iconst_4', 'iadd', 'iaload', 'iadd', \
'istore', 'iload', 'aload_0', 'getfield', 'iload', \
'iconst_5', 'iadd', 'iaload', 'iadd', 'istore', \
'iload', 'aload_0', 'getfield', 'iload', 'bipush', \
'iadd', 'iaload', 'iadd', 'istore', 'iload', \
'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \
'iaload', 'iadd', 'istore', 'iload', 'iload_1', \
'bipush', 'ishl', 'ixor', 'istore', 'iload_3', \
'iload', 'iadd', 'istore_3', 'iload_1', 'iload_2', \
'iadd', 'istore_1', 'iload_1', 'iload_2', \
'iconst_2', 'iushr', 'ixor', 'istore_1', 'iload', \
'iload_1', 'iadd', 'istore', 'iload_2', 'iload_3', \
'iadd', 'istore_2', 'iload_2', 'iload_3', 'bipush', \
'ishl', 'ixor', 'istore_2', 'iload', 'iload_2', \
'iadd', 'istore', 'iload_3', 'iload', 'iadd', \
'istore_3', 'iload_3', 'iload', 'bipush', 'iushr', \
'ixor', 'istore_3', 'iload', 'iload_3', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'bipush', 'ishl', 'ixor', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iconst_4', 'iushr', 'ixor', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', 'bipush', \
'ishl', 'ixor', 'istore', 'iload_1', 'iload', 'iadd', \
'istore_1', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'bipush', 'iushr', 'ixor', 'istore', 'iload_2', \
'iload', 'iadd', 'istore_2', 'iload', 'iload_1', 'iadd', \
'istore', 'aload_0', 'getfield', 'iload', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', 'iconst_1', \
'iadd', 'iload_1', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_2', 'iadd', 'iload_2', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_3', 'iadd', \
'iload_3', 'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_4', 'iadd', 'iload', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_5', 'iadd', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', 'bipush', \
'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iload', 'iastore', 'iinc', \
'goto', 'aload_0', 'invokespecial', 'aload_0', \
'sipush', 'putfield', 'return']
initializeKeySet3 = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', 'istore', \
'dup', 'istore', 'dup', 'istore_3', 'dup', 'istore_2', \
'dup', 'istore_1', 'istore', 'iconst_0', 'istore', \
'goto', 'iload', 'iload_1', 'bipush', 'ishl', 'ixor', \
'istore', 'iload_3', 'iload', 'iadd', 'istore_3', \
'iload_1', 'iload_2', 'iadd', 'dup', 'istore_1', \
'iload_2', 'iconst_2', 'iushr', 'ixor', 'istore_1', \
'iload', 'iload_1', 'iadd', 'istore', 'iload_2', \
'iload_3', 'iadd', 'dup', 'istore_2', 'iload_3', \
'bipush', 'ishl', 'ixor', 'istore_2', 'iload', \
'iload_2', 'iadd', 'istore', 'iload_3', 'iload', \
'iadd', 'dup', 'istore_3', 'iload', 'bipush', \
'iushr', 'ixor', 'istore_3', 'iload', \
'iload_3', 'iadd', 'istore', 'iload', 'iload', \
'iadd', 'dup', 'istore', 'iload', 'bipush', \
'ishl', 'ixor', 'istore', 'iload', 'iload', \
'iadd', 'istore', 'iload', 'iload', 'iadd', \
'dup', 'istore', 'iload', 'iconst_4', \
'iushr', 'ixor', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', \
'iadd', 'dup', 'istore', 'iload', 'bipush', \
'ishl', 'ixor', 'istore', 'iload_1', 'iload', \
'iadd', 'istore_1', 'iload', 'iload', 'iadd', \
'dup', 'istore', 'iload', 'bipush', 'iushr', \
'ixor', 'istore', 'iload_2', 'iload', 'iadd', \
'istore_2', 'iload', 'iload_1', 'iadd', \
'istore', 'iinc', 'iload', 'iconst_4', 'if_icmplt', \
'iconst_0', 'istore', 'goto', 'iload', 'aload_0', \
'getfield', 'iload', 'iaload', 'iadd', 'istore', \
'iload_1', 'aload_0', 'getfield', 'iload', \
'iconst_1', 'iadd', 'iaload', 'iadd', 'istore_1', \
'iload_2', 'aload_0', 'getfield', 'iload', \
'iconst_2', 'iadd', 'iaload', 'iadd', 'istore_2', \
'iload_3', 'aload_0', 'getfield', 'iload', 'iconst_3', \
'iadd', 'iaload', 'iadd', 'istore_3', 'iload', \
'aload_0', 'getfield', 'iload', 'iconst_4', 'iadd', \
'iaload', 'iadd', 'istore', 'iload', 'aload_0', \
'getfield', 'iload', 'iconst_5', 'iadd', 'iaload', \
'iadd', 'istore', 'iload', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iaload', 'iadd', \
'istore', 'iload', 'aload_0', 'getfield', 'iload', \
'bipush', 'iadd', 'iaload', 'iadd', 'istore', 'iload', \
'iload_1', 'bipush', 'ishl', 'ixor', 'istore', \
'iload_3', 'iload', 'iadd', 'istore_3', 'iload_1', \
'iload_2', 'iadd', 'dup', 'istore_1', 'iload_2', \
'iconst_2', 'iushr', 'ixor', 'istore_1', 'iload', \
'iload_1', 'iadd', 'istore', 'iload_2', 'iload_3', \
'iadd', 'dup', 'istore_2', 'iload_3', 'bipush', \
'ishl', 'ixor', 'istore_2', 'iload', 'iload_2', \
'iadd', 'istore', 'iload_3', 'iload', 'iadd', 'dup', \
'istore_3', 'iload', 'bipush', 'iushr', 'ixor', \
'istore_3', 'iload', 'iload_3', 'iadd', 'istore', \
'iload', 'iload', 'iadd', 'dup', 'istore', 'iload', \
'bipush', 'ishl', 'ixor', 'istore', 'iload', 'iload', \
'iadd', 'istore', 'iload', 'iload', 'iadd', 'dup', \
'istore', 'iload', 'iconst_4', 'iushr', 'ixor', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'iadd', 'dup', 'istore', 'iload', 'bipush', \
'ishl', 'ixor', 'istore', 'iload_1', 'iload', 'iadd', \
'istore_1', 'iload', 'iload', 'iadd', 'dup', 'istore', \
'iload', 'bipush', 'iushr', 'ixor', 'istore', \
'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \
'iload_1', 'iadd', 'istore', 'aload_0', 'getfield', \
'iload', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \
'iload_2', 'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', 'iconst_5', \
'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iload', 'iastore', \
'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \
'iload', 'iastore', 'iinc', 'iload', 'sipush', \
'if_icmplt', 'iconst_0', 'istore', 'goto', 'iload', \
'aload_0', 'getfield', 'iload', 'iaload', 'iadd', \
'istore', 'iload_1', 'aload_0', 'getfield', 'iload', \
'iconst_1', 'iadd', 'iaload', 'iadd', 'istore_1', \
'iload_2', 'aload_0', 'getfield', 'iload', 'iconst_2', \
'iadd', 'iaload', 'iadd', 'istore_2', 'iload_3', \
'aload_0', 'getfield', 'iload', 'iconst_3', 'iadd', \
'iaload', 'iadd', 'istore_3', 'iload', 'aload_0', \
'getfield', 'iload', 'iconst_4', 'iadd', 'iaload', \
'iadd', 'istore', 'iload', 'aload_0', 'getfield', \
'iload', 'iconst_5', 'iadd', 'iaload', 'iadd', \
'istore', 'iload', 'aload_0', 'getfield', 'iload', \
'bipush', 'iadd', 'iaload', 'iadd', 'istore', 'iload', \
'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \
'iaload', 'iadd', 'istore', 'iload', 'iload_1', \
'bipush', 'ishl', 'ixor', 'istore', 'iload_3', \
'iload', 'iadd', 'istore_3', 'iload_1', 'iload_2', \
'iadd', 'dup', 'istore_1', 'iload_2', 'iconst_2', \
'iushr', 'ixor', 'istore_1', 'iload', 'iload_1', \
'iadd', 'istore', 'iload_2', 'iload_3', 'iadd', 'dup', \
'istore_2', 'iload_3', 'bipush', 'ishl', 'ixor', \
'istore_2', 'iload', 'iload_2', 'iadd', 'istore', \
'iload_3', 'iload', 'iadd', 'dup', 'istore_3', \
'iload', 'bipush', 'iushr', 'ixor', 'istore_3', \
'iload', 'iload_3', 'iadd', 'istore', 'iload', \
'iload', 'iadd', 'dup', 'istore', 'iload', 'bipush', \
'ishl', 'ixor', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'dup', 'istore', \
'iload', 'iconst_4', 'iushr', 'ixor', 'istore', \
'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \
'iadd', 'dup', 'istore', 'iload', 'bipush', 'ishl', \
'ixor', 'istore', 'iload_1', 'iload', 'iadd', \
'istore_1', 'iload', 'iload', 'iadd', 'dup', 'istore', \
'iload', 'bipush', 'iushr', 'ixor', 'istore', \
'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \
'iload_1', 'iadd', 'istore', 'aload_0', 'getfield', \
'iload', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \
'iload_2', 'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', 'iconst_5', \
'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iload', 'iastore', \
'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \
'iload', 'iastore', 'iinc', 'iload', 'sipush', \
'if_icmplt', 'aload_0', 'invokespecial', \
'aload_0', 'sipush', 'putfield', 'return']
initializeKeySet4 = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', \
'istore', 'dup', 'istore', 'dup', 'istore_3', 'dup', \
'istore_2', 'dup', 'istore_1', 'istore', 'iconst_0', \
'istore', 'iload', 'iconst_4', 'if_icmpge', \
'iload', 'iload_1', 'bipush', 'ishl', 'ixor', \
'istore', 'iload_3', 'iload', 'iadd', 'istore_3', \
'iload_1', 'iload_2', 'iadd', 'istore_1', 'iload_1', \
'iload_2', 'iconst_2', 'iushr', 'ixor', \
'istore_1', 'iload', 'iload_1', 'iadd', 'istore', \
'iload_2', 'iload_3', 'iadd', 'istore_2', 'iload_2', \
'iload_3', 'bipush', 'ishl', 'ixor', 'istore_2', \
'iload', 'iload_2', 'iadd', 'istore', 'iload_3', \
'iload', 'iadd', 'istore_3', 'iload_3', 'iload', \
'bipush', 'iushr', 'ixor', 'istore_3', 'iload', \
'iload_3', 'iadd', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'bipush', 'ishl', 'ixor', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', 'iconst_4', \
'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \
'iload', 'iadd', 'istore_1', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'bipush', 'iushr', 'ixor', \
'istore', 'iload_2', 'iload', 'iadd', 'istore_2', \
'iload', 'iload_1', 'iadd', 'istore', 'iinc', 'goto', \
'iconst_0', 'istore', 'iload', 'sipush', 'if_icmpge', \
'iload', 'aload_0', 'getfield', 'iload', 'iaload', \
'iadd', 'istore', 'iload_1', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iaload', 'iadd', \
'istore_1', 'iload_2', 'aload_0', 'getfield', 'iload', \
'iconst_2', 'iadd', 'iaload', 'iadd', 'istore_2', \
'iload_3', 'aload_0', 'getfield', 'iload', 'iconst_3', \
'iadd', 'iaload', 'iadd', 'istore_3', 'iload', \
'aload_0', 'getfield', 'iload', 'iconst_4', 'iadd', \
'iaload', 'iadd', 'istore', 'iload', 'aload_0', \
'getfield', 'iload', 'iconst_5', 'iadd', 'iaload', \
'iadd', 'istore', 'iload', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iaload', 'iadd', 'istore', \
'iload', 'aload_0', 'getfield', 'iload', 'bipush', \
'iadd', 'iaload', 'iadd', 'istore', 'iload', 'iload_1', \
'bipush', 'ishl', 'ixor', 'istore', 'iload_3', 'iload', \
'iadd', 'istore_3', 'iload_1', 'iload_2', 'iadd', \
'istore_1', 'iload_1', 'iload_2', 'iconst_2', 'iushr', \
'ixor', 'istore_1', 'iload', 'iload_1', 'iadd', \
'istore', 'iload_2', 'iload_3', 'iadd', 'istore_2', \
'iload_2', 'iload_3', 'bipush', 'ishl', 'ixor', \
'istore_2', 'iload', 'iload_2', 'iadd', 'istore', \
'iload_3', 'iload', 'iadd', 'istore_3', 'iload_3', \
'iload', 'bipush', 'iushr', 'ixor', 'istore_3', \
'iload', 'iload_3', 'iadd', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', \
'bipush', 'ishl', 'ixor', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iconst_4', 'iushr', \
'ixor', 'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \
'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \
'iload', 'iadd', 'istore_1', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'bipush', 'iushr', 'ixor', \
'istore', 'iload_2', 'iload', 'iadd', 'istore_2', \
'iload', 'iload_1', 'iadd', 'istore', 'aload_0', \
'getfield', 'iload', 'iload', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_1', 'iadd', 'iload_1', \
'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_2', 'iadd', 'iload_2', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_3', 'iadd', 'iload_3', \
'iastore', 'aload_0', 'getfield', 'iload', 'iconst_4', \
'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_5', 'iadd', 'iload', 'iastore', \
'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \
'iload', 'iastore', 'aload_0', 'getfield', 'iload', \
'bipush', 'iadd', 'iload', 'iastore', 'iinc', \
'goto', 'iconst_0', 'istore', 'iload', 'sipush', \
'if_icmpge', 'iload', 'aload_0', 'getfield', 'iload', \
'iaload', 'iadd', 'istore', 'iload_1', 'aload_0', \
'getfield', 'iload', 'iconst_1', 'iadd', 'iaload', \
'iadd', 'istore_1', 'iload_2', 'aload_0', 'getfield', \
'iload', 'iconst_2', 'iadd', 'iaload', 'iadd', \
'istore_2', 'iload_3', 'aload_0', 'getfield', 'iload', \
'iconst_3', 'iadd', 'iaload', 'iadd', 'istore_3', \
'iload', 'aload_0', 'getfield', 'iload', 'iconst_4', \
'iadd', 'iaload', 'iadd', 'istore', 'iload', \
'aload_0', 'getfield', 'iload', 'iconst_5', 'iadd', \
'iaload', 'iadd', 'istore', 'iload', 'aload_0', \
'getfield', 'iload', 'bipush', 'iadd', 'iaload', \
'iadd', 'istore', 'iload', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iaload', 'iadd', 'istore', \
'iload', 'iload_1', 'bipush', 'ishl', 'ixor', 'istore', \
'iload_3', 'iload', 'iadd', 'istore_3', 'iload_1', \
'iload_2', 'iadd', 'istore_1', 'iload_1', 'iload_2', \
'iconst_2', 'iushr', 'ixor', 'istore_1', 'iload', \
'iload_1', 'iadd', 'istore', 'iload_2', 'iload_3', \
'iadd', 'istore_2', 'iload_2', 'iload_3', 'bipush', \
'ishl', 'ixor', 'istore_2', 'iload', 'iload_2', \
'iadd', 'istore', 'iload_3', 'iload', 'iadd', \
'istore_3', 'iload_3', 'iload', 'bipush', 'iushr', \
'ixor', 'istore_3', 'iload', 'iload_3', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'bipush', 'ishl', 'ixor', 'istore', \
'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \
'iadd', 'istore', 'iload', 'iload', 'iconst_4', \
'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'bipush', 'ishl', 'ixor', \
'istore', 'iload_1', 'iload', 'iadd', 'istore_1', \
'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'bipush', 'iushr', 'ixor', 'istore', \
'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \
'iload_1', 'iadd', 'istore', 'aload_0', 'getfield', \
'iload', 'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \
'iload_2', 'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_5', 'iadd', 'iload', 'iastore', 'aload_0', \
'getfield', 'iload', 'bipush', 'iadd', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', 'bipush', \
'iadd', 'iload', 'iastore', 'iinc', 'goto', 'aload_0', \
'invokespecial', 'aload_0', 'sipush', 'putfield', 'return']
initializeKeySet = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', \
'istore', 'dup', 'istore', 'dup', 'istore_3', \
'dup', 'istore_2', 'dup', 'istore_1', 'istore', \
'iconst_0', 'istore', 'goto', 'iload', 'iload_1', \
'bipush', 'ishl', 'ixor', 'istore', 'iload_3', \
'iload', 'iadd', 'istore_3', 'iload_1', \
'iload_2', 'iadd', 'istore_1', 'iload_1', \
'iload_2', 'iconst_2', 'iushr', 'ixor', \
'istore_1', 'iload', 'iload_1', 'iadd', 'istore', \
'iload_2', 'iload_3', 'iadd', 'istore_2', \
'iload_2', 'iload_3', 'bipush', 'ishl', 'ixor', \
'istore_2', 'iload', 'iload_2', 'iadd', 'istore', \
'iload_3', 'iload', 'iadd', 'istore_3', \
'iload_3', 'iload', 'bipush', 'iushr', 'ixor', \
'istore_3', 'iload', 'iload_3', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'bipush', 'ishl', 'ixor', \
'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'iconst_4', 'iushr', 'ixor', 'istore', \
'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', \
'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \
'iload', 'iadd', 'istore_1', 'iload', 'iload', \
'iadd', 'istore', 'iload', 'iload', 'bipush', \
'iushr', 'ixor', 'istore', 'iload_2', 'iload', \
'iadd', 'istore_2', 'iload', 'iload_1', 'iadd', \
'istore', 'iinc', 'iload', 'iconst_4', \
'if_icmplt', 'iconst_0', 'istore', 'goto', \
'iload', 'aload_0', 'getfield', 'iload', \
'iaload', 'iadd', 'istore', 'iload_1', \
'aload_0', 'getfield', 'iload', 'iconst_1', \
'iadd', 'iaload', 'iadd', 'istore_1', \
'iload_2', 'aload_0', 'getfield', 'iload', \
'iconst_2', 'iadd', 'iaload', 'iadd', \
'istore_2', 'iload_3', 'aload_0', \
'getfield', 'iload', 'iconst_3', 'iadd', \
'iaload', 'iadd', 'istore_3', 'iload', \
'aload_0', 'getfield', 'iload', 'iconst_4', \
'iadd', 'iaload', 'iadd', 'istore', \
'iload', 'aload_0', 'getfield', 'iload', \
'iconst_5', 'iadd', 'iaload', 'iadd', \
'istore', 'iload', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iaload', \
'iadd', 'istore', 'iload', 'aload_0', \
'getfield', 'iload', 'bipush', 'iadd', \
'iaload', 'iadd', 'istore', 'iload', \
'iload_1', 'bipush', 'ishl', 'ixor', \
'istore', 'iload_3', 'iload', 'iadd', \
'istore_3', 'iload_1', 'iload_2', 'iadd', \
'istore_1', 'iload_1', 'iload_2', \
'iconst_2', 'iushr', 'ixor', 'istore_1', \
'iload', 'iload_1', 'iadd', 'istore', \
'iload_2', 'iload_3', 'iadd', 'istore_2', \
'iload_2', 'iload_3', 'bipush', 'ishl', \
'ixor', 'istore_2', 'iload', 'iload_2', \
'iadd', 'istore', 'iload_3', 'iload', \
'iadd', 'istore_3', 'iload_3', 'iload', \
'bipush', 'iushr', 'ixor', 'istore_3', \
'iload', 'iload_3', 'iadd', 'istore', \
'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'bipush', 'ishl', \
'ixor', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', \
'iload', 'iload', 'iconst_4', \
'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'bipush', 'ishl', 'ixor', 'istore', \
'iload_1', 'iload', 'iadd', 'istore_1', 'iload', \
'iload', 'iadd', 'istore', 'iload', 'iload', \
'bipush', 'iushr', 'ixor', 'istore', 'iload_2', \
'iload', 'iadd', 'istore_2', 'iload', 'iload_1', \
'iadd', 'istore', 'aload_0', 'getfield', 'iload', \
'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_2', \
'iadd', 'iload_2', 'iastore', 'aload_0', \
'getfield', 'iload', 'iconst_3', 'iadd', 'iload_3', \
'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_4', 'iadd', 'iload', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_5', 'iadd', \
'iload', 'iastore', 'aload_0', 'getfield', 'iload', \
'bipush', 'iadd', 'iload', 'iastore', 'aload_0', \
'getfield', 'iload', 'bipush', 'iadd', 'iload', \
'iastore', 'iinc', 'iload', 'sipush', \
'if_icmplt', 'iconst_0', 'istore', 'goto', \
'iload', 'aload_0', 'getfield', 'iload', 'iaload', \
'iadd', 'istore', 'iload_1', 'aload_0', \
'getfield', 'iload', 'iconst_1', 'iadd', \
'iaload', 'iadd', 'istore_1', 'iload_2', \
'aload_0', 'getfield', 'iload', 'iconst_2', \
'iadd', 'iaload', 'iadd', 'istore_2', \
'iload_3', 'aload_0', 'getfield', 'iload', \
'iconst_3', 'iadd', 'iaload', 'iadd', 'istore_3', \
'iload', 'aload_0', 'getfield', 'iload', \
'iconst_4', 'iadd', 'iaload', 'iadd', 'istore', \
'iload', 'aload_0', 'getfield', 'iload', \
'iconst_5', 'iadd', 'iaload', 'iadd', \
'istore', 'iload', 'aload_0', 'getfield', \
'iload', 'bipush', 'iadd', 'iaload', \
'iadd', 'istore', 'iload', 'aload_0', \
'getfield', 'iload', 'bipush', 'iadd', \
'iaload', 'iadd', 'istore', 'iload', \
'iload_1', 'bipush', 'ishl', 'ixor', 'istore', \
'iload_3', 'iload', 'iadd', 'istore_3', \
'iload_1', 'iload_2', 'iadd', 'istore_1', \
'iload_1', 'iload_2', 'iconst_2', 'iushr', \
'ixor', 'istore_1', 'iload', 'iload_1', \
'iadd', 'istore', 'iload_2', 'iload_3', \
'iadd', 'istore_2', 'iload_2', 'iload_3', \
'bipush', 'ishl', 'ixor', 'istore_2', \
'iload', 'iload_2', 'iadd', 'istore', \
'iload_3', 'iload', 'iadd', 'istore_3', \
'iload_3', 'iload', 'bipush', 'iushr', \
'ixor', 'istore_3', 'iload', 'iload_3', \
'iadd', 'istore', 'iload', 'iload', \
'iadd', 'istore', 'iload', 'iload', 'bipush', \
'ishl', 'ixor', 'istore', 'iload', 'iload', \
'iadd', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iconst_4', 'iushr', \
'ixor', 'istore', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \
'iload', 'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \
'iload', 'iadd', 'istore_1', 'iload', 'iload', 'iadd', \
'istore', 'iload', 'iload', 'bipush', 'iushr', 'ixor', \
'istore', 'iload_2', 'iload', \
'iadd', 'istore_2', 'iload', 'iload_1', \
'iadd', 'istore', 'aload_0', 'getfield', 'iload', \
'iload', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \
'iload_2', 'iastore', 'aload_0', 'getfield', \
'iload', 'iconst_3', 'iadd', 'iload_3', 'iastore', \
'aload_0', 'getfield', 'iload', 'iconst_4', 'iadd', \
'iload', 'iastore', 'aload_0', 'getfield', 'iload', \
'iconst_5', 'iadd', 'iload', 'iastore', 'aload_0', \
'getfield', 'iload', 'bipush', 'iadd', 'iload', \
'iastore', 'aload_0', 'getfield', 'iload', 'bipush', \
'iadd', 'iload', 'iastore', 'iinc', 'iload', \
'sipush', 'if_icmplt', 'aload_0', 'invokespecial', \
'aload_0', 'sipush', 'putfield', 'return']
Generic_Methods = [
['createFrame', createFrame],
['writeDWord', writeDWord],
['writeWordBigEndian', writeWordBigEndian],
['writeWord', writeWord],
['writeDWordBigEndian', writeDWordBigEndian],
['method403', method403],
['writeQWord', writeQWord],
['writeString', writeString],
['method424', method424],
['method425', method425],
['method431', method431],
['method432', method432],
['method433', method433],
['getNextKey', getNextKey],
['isaac', isaac],
['initializeKeySet', initializeKeySet],
['initializeKeySet3', initializeKeySet3],
['initializeKeySet4', initializeKeySet4],
['initializeKeySet2', initializeKeySet2]
]
|
simonz05/activity-feed
|
tests/test_utility.py
|
# -*- coding: utf-8 -*-
import unittest
from activity_feed import ActivityFeed
class UtilityTest(unittest.TestCase):
def test_key(self):
'should return the correct key for the non-aggregate feed'
a = ActivityFeed()
self.assertEquals(a.feed_key('david'), 'activity_feed:david')
def test_key_aggregate(self):
'should return the correct key for an aggregate feed'
a = ActivityFeed()
self.assertEqual(a.feed_key('david', True), 'activity_feed:aggregate:david')
def test_feederboard_for(self):
'should create a leaderboard using an existing Redis connection'
a = ActivityFeed()
feederboard_david = a.feederboard_for('david')
feederboard_person = a.feederboard_for('person')
self.assertEqual(feederboard_david is None, False)
self.assertEqual(feederboard_person is None, False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.