hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f729f3ba1a2a0c58defbcfe07cea84dae747f8f4 | 868 | py | Python | factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/azure_projects/tests/test_drf_urls.py | kaka-lin/azure-intelligent-edge-patterns | 766833c7c25d2458cec697937be288202d1763bc | [
"MIT"
] | 176 | 2019-07-03T00:20:15.000Z | 2022-03-14T07:51:22.000Z | factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/azure_projects/tests/test_drf_urls.py | kaka-lin/azure-intelligent-edge-patterns | 766833c7c25d2458cec697937be288202d1763bc | [
"MIT"
] | 121 | 2019-06-24T20:47:27.000Z | 2022-03-28T02:16:18.000Z | factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/azure_projects/tests/test_drf_urls.py | kaka-lin/azure-intelligent-edge-patterns | 766833c7c25d2458cec697937be288202d1763bc | [
"MIT"
] | 144 | 2019-06-18T18:48:43.000Z | 2022-03-31T12:14:46.000Z | """App drf url tests.
"""
from unittest import mock
import pytest
from django.urls import resolve, reverse
from .factories import ProjectFactory
pytestmark = pytest.mark.django_db
@pytest.mark.fast
@mock.patch(
"vision_on_edge.azure_projects.models.Project.validate",
mock.MagicMock(return_value=True),
)
def test_project_detail():
"""test_project_detail.
Args:
project (Project): project
"""
project = ProjectFactory()
assert (
reverse("api:project-detail", kwargs={"pk": project.id})
== f"/api/projects/{project.id}"
)
assert resolve(f"/api/projects/{project.id}").view_name == "api:project-detail"
@pytest.mark.fast
def test_project_list():
"""test_project_list."""
assert reverse("api:project-list") == "/api/projects"
assert resolve("/api/projects").view_name == "api:project-list"
| 22.842105 | 83 | 0.684332 |
from unittest import mock
import pytest
from django.urls import resolve, reverse
from .factories import ProjectFactory
pytestmark = pytest.mark.django_db
@pytest.mark.fast
@mock.patch(
"vision_on_edge.azure_projects.models.Project.validate",
mock.MagicMock(return_value=True),
)
def test_project_detail():
project = ProjectFactory()
assert (
reverse("api:project-detail", kwargs={"pk": project.id})
== f"/api/projects/{project.id}"
)
assert resolve(f"/api/projects/{project.id}").view_name == "api:project-detail"
@pytest.mark.fast
def test_project_list():
assert reverse("api:project-list") == "/api/projects"
assert resolve("/api/projects").view_name == "api:project-list"
| true | true |
f729f4a05df40e49a35b4c3c584b696d124c3396 | 7,632 | py | Python | salt/log/handlers/sentry_mod.py | andrew-vant/salt | 26fd2bc89e0faaff0fd0176a9896500660204cd5 | [
"Apache-2.0"
] | null | null | null | salt/log/handlers/sentry_mod.py | andrew-vant/salt | 26fd2bc89e0faaff0fd0176a9896500660204cd5 | [
"Apache-2.0"
] | 1 | 2015-09-02T12:49:48.000Z | 2015-09-02T19:22:58.000Z | salt/log/handlers/sentry_mod.py | andrew-vant/salt | 26fd2bc89e0faaff0fd0176a9896500660204cd5 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
Sentry Logging Handler
======================
.. versionadded:: 0.17.0
This module provides a `Sentry`_ logging handler.
.. admonition:: Note
The `Raven`_ library needs to be installed on the system for this
logging handler to be available.
Configuring the python `Sentry`_ client, `Raven`_, should be done under the
``sentry_handler`` configuration key. Additional `context` may be provided
for coresponding grain item(s).
At the bare minimum, you need to define the `DSN`_. As an example:
.. code-block:: yaml
sentry_handler:
dsn: https://pub-key:secret-key@app.getsentry.com/app-id
More complex configurations can be achieved, for example:
.. code-block:: yaml
sentry_handler:
servers:
- https://sentry.example.com
- http://192.168.1.1
project: app-id
public_key: deadbeefdeadbeefdeadbeefdeadbeef
secret_key: beefdeadbeefdeadbeefdeadbeefdead
context:
- os
- master
- saltversion
- cpuarch
- ec2.tags.environment
All the client configuration keys are supported, please see the
`Raven client documentation`_.
The default logging level for the sentry handler is ``ERROR``. If you wish
to define a different one, define ``log_level`` under the
``sentry_handler`` configuration key:
.. code-block:: yaml
sentry_handler:
dsn: https://pub-key:secret-key@app.getsentry.com/app-id
log_level: warning
The available log levels are those also available for the salt ``cli``
tools and configuration; ``salt --help`` should give you the required
information.
Threaded Transports
-------------------
Raven's documents rightly suggest using its threaded transport for
critical applications. However, don't forget that if you start having
troubles with Salt after enabling the threaded transport, please try
switching to a non-threaded transport to see if that fixes your problem.
.. _`DSN`: http://raven.readthedocs.org/en/latest/config/index.html#the-sentry-dsn
.. _`Sentry`: https://getsentry.com
.. _`Raven`: http://raven.readthedocs.org
.. _`Raven client documentation`: http://raven.readthedocs.org/en/latest/config/index.html#client-arguments
'''
from __future__ import absolute_import
# Import python libs
import logging
# Import salt libs
import salt.loader
from salt.log import LOG_LEVELS
# Import 3rd party libs
try:
import raven
from raven.handlers.logging import SentryHandler
HAS_RAVEN = True
except ImportError:
HAS_RAVEN = False
log = logging.getLogger(__name__)
__grains__ = {}
__salt__ = {}
# Define the module's virtual name
__virtualname__ = 'sentry'
def __virtual__():
if HAS_RAVEN is True:
__grains__ = salt.loader.grains(__opts__)
__salt__ = salt.loader.minion_mods(__opts__)
return __virtualname__
return False
def setup_handlers():
if 'sentry_handler' not in __opts__:
log.debug('No \'sentry_handler\' key was found in the configuration')
return False
options = {}
dsn = get_config_value('dsn')
if dsn is not None:
try:
# support raven ver 5.5.0
from raven.transport import TransportRegistry, default_transports
from raven.utils.urlparse import urlparse
transport_registry = TransportRegistry(default_transports)
url = urlparse(dsn)
if not transport_registry.supported_scheme(url.scheme):
raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(url.scheme))
dsn_config = {}
conf_extras = transport_registry.compute_scope(url, dsn_config)
dsn_config.update(conf_extras)
options.update({
'project': dsn_config['SENTRY_PROJECT'],
'servers': dsn_config['SENTRY_SERVERS'],
'public_key': dsn_config['SENTRY_PUBLIC_KEY'],
'secret_key': dsn_config['SENTRY_SECRET_KEY']
})
except ValueError as exc:
log.info(
'Raven failed to parse the configuration provided '
'DSN: {0}'.format(exc)
)
# Allow options to be overridden if previously parsed, or define them
for key in ('project', 'servers', 'public_key', 'secret_key'):
config_value = get_config_value(key)
if config_value is None and key not in options:
log.debug(
'The required \'sentry_handler\' configuration key, '
'\'{0}\', is not properly configured. Not configuring '
'the sentry logging handler.'.format(key)
)
return
elif config_value is None:
continue
options[key] = config_value
# site: An optional, arbitrary string to identify this client installation.
options.update({
# site: An optional, arbitrary string to identify this client
# installation
'site': get_config_value('site'),
# name: This will override the server_name value for this installation.
# Defaults to socket.gethostname()
'name': get_config_value('name'),
# exclude_paths: Extending this allow you to ignore module prefixes
# when sentry attempts to discover which function an error comes from
'exclude_paths': get_config_value('exclude_paths', ()),
# include_paths: For example, in Django this defaults to your list of
# INSTALLED_APPS, and is used for drilling down where an exception is
# located
'include_paths': get_config_value('include_paths', ()),
# list_max_length: The maximum number of items a list-like container
# should store.
'list_max_length': get_config_value('list_max_length'),
# string_max_length: The maximum characters of a string that should be
# stored.
'string_max_length': get_config_value('string_max_length'),
# auto_log_stacks: Should Raven automatically log frame stacks
# (including locals) all calls as it would for exceptions.
'auto_log_stacks': get_config_value('auto_log_stacks'),
# timeout: If supported, the timeout value for sending messages to
# remote.
'timeout': get_config_value('timeout', 1),
# processors: A list of processors to apply to events before sending
# them to the Sentry server. Useful for sending additional global state
# data or sanitizing data that you want to keep off of the server.
'processors': get_config_value('processors'),
# dsn: Ensure the DSN is passed into the client
'dsn': dsn
})
client = raven.Client(**options)
context = get_config_value('context')
context_dict = {}
if context is not None:
for tag in context:
tag_value = __salt__['grains.get'](tag)
if len(tag_value) > 0:
context_dict[tag] = tag_value
if len(context_dict) > 0:
client.context.merge({'tags': context_dict})
try:
handler = SentryHandler(client)
handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
return handler
except ValueError as exc:
log.debug(
'Failed to setup the sentry logging handler: {0}'.format(exc),
exc_info=exc
)
def get_config_value(name, default=None):
return __opts__['sentry_handler'].get(name, default)
| 34.378378 | 111 | 0.643082 |
from __future__ import absolute_import
import logging
import salt.loader
from salt.log import LOG_LEVELS
try:
import raven
from raven.handlers.logging import SentryHandler
HAS_RAVEN = True
except ImportError:
HAS_RAVEN = False
log = logging.getLogger(__name__)
__grains__ = {}
__salt__ = {}
__virtualname__ = 'sentry'
def __virtual__():
if HAS_RAVEN is True:
__grains__ = salt.loader.grains(__opts__)
__salt__ = salt.loader.minion_mods(__opts__)
return __virtualname__
return False
def setup_handlers():
if 'sentry_handler' not in __opts__:
log.debug('No \'sentry_handler\' key was found in the configuration')
return False
options = {}
dsn = get_config_value('dsn')
if dsn is not None:
try:
# support raven ver 5.5.0
from raven.transport import TransportRegistry, default_transports
from raven.utils.urlparse import urlparse
transport_registry = TransportRegistry(default_transports)
url = urlparse(dsn)
if not transport_registry.supported_scheme(url.scheme):
raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(url.scheme))
dsn_config = {}
conf_extras = transport_registry.compute_scope(url, dsn_config)
dsn_config.update(conf_extras)
options.update({
'project': dsn_config['SENTRY_PROJECT'],
'servers': dsn_config['SENTRY_SERVERS'],
'public_key': dsn_config['SENTRY_PUBLIC_KEY'],
'secret_key': dsn_config['SENTRY_SECRET_KEY']
})
except ValueError as exc:
log.info(
'Raven failed to parse the configuration provided '
'DSN: {0}'.format(exc)
)
# Allow options to be overridden if previously parsed, or define them
for key in ('project', 'servers', 'public_key', 'secret_key'):
config_value = get_config_value(key)
if config_value is None and key not in options:
log.debug(
'The required \'sentry_handler\' configuration key, '
'\'{0}\', is not properly configured. Not configuring '
'the sentry logging handler.'.format(key)
)
return
elif config_value is None:
continue
options[key] = config_value
# site: An optional, arbitrary string to identify this client installation.
options.update({
# site: An optional, arbitrary string to identify this client
# installation
'site': get_config_value('site'),
# name: This will override the server_name value for this installation.
# Defaults to socket.gethostname()
'name': get_config_value('name'),
# exclude_paths: Extending this allow you to ignore module prefixes
# when sentry attempts to discover which function an error comes from
'exclude_paths': get_config_value('exclude_paths', ()),
# include_paths: For example, in Django this defaults to your list of
# INSTALLED_APPS, and is used for drilling down where an exception is
# located
'include_paths': get_config_value('include_paths', ()),
# list_max_length: The maximum number of items a list-like container
# should store.
'list_max_length': get_config_value('list_max_length'),
# string_max_length: The maximum characters of a string that should be
# stored.
'string_max_length': get_config_value('string_max_length'),
# auto_log_stacks: Should Raven automatically log frame stacks
# (including locals) all calls as it would for exceptions.
'auto_log_stacks': get_config_value('auto_log_stacks'),
# timeout: If supported, the timeout value for sending messages to
# remote.
'timeout': get_config_value('timeout', 1),
# processors: A list of processors to apply to events before sending
# them to the Sentry server. Useful for sending additional global state
# data or sanitizing data that you want to keep off of the server.
'processors': get_config_value('processors'),
# dsn: Ensure the DSN is passed into the client
'dsn': dsn
})
client = raven.Client(**options)
context = get_config_value('context')
context_dict = {}
if context is not None:
for tag in context:
tag_value = __salt__['grains.get'](tag)
if len(tag_value) > 0:
context_dict[tag] = tag_value
if len(context_dict) > 0:
client.context.merge({'tags': context_dict})
try:
handler = SentryHandler(client)
handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
return handler
except ValueError as exc:
log.debug(
'Failed to setup the sentry logging handler: {0}'.format(exc),
exc_info=exc
)
def get_config_value(name, default=None):
return __opts__['sentry_handler'].get(name, default)
| true | true |
f729f5a7091e28863cdde678afbd7609e9b5fc64 | 1,244 | py | Python | tests/syosetsu/fixtures.py | julot/sphinxcontrib-translation-assistant | 44ba6b81efdc77b6ce0b2ee46097ed7ac0c9bbc9 | [
"MIT"
] | 1 | 2017-10-21T07:54:57.000Z | 2017-10-21T07:54:57.000Z | tests/syosetsu/fixtures.py | julot/sphinxcontrib-translation-assistant | 44ba6b81efdc77b6ce0b2ee46097ed7ac0c9bbc9 | [
"MIT"
] | null | null | null | tests/syosetsu/fixtures.py | julot/sphinxcontrib-translation-assistant | 44ba6b81efdc77b6ce0b2ee46097ed7ac0c9bbc9 | [
"MIT"
] | null | null | null | JAPANESE = {
'title': '%プロローグ',
'contents': [
'% |本須 麗乃(もとすうらの)、22歳。',
'% わたしは本が好きだ。',
'$大好きだ。',
'% 三度のご飯より愛してる。',
'%「うっ……」',
],
'notes': {
'pre': [
'%蒼枝と申します。',
'%長編を書くのは初めてです。',
],
'post': [
'%とうとう始めてしまいました。',
'%楽しんでいただけたら嬉しいです。',
],
},
}
ENGLISH = {
'title': 'Prologue',
'contents': [
' My name is Mototsu Urano, 22 years old.',
' I like book.',
'Really really like.',
' I love it more than three times meals.',
'「Uu……」'
],
'notes': {
'pre': [
'I am Aoieda.',
"It's my first time writing novel.",
],
'post': [
'It has started at last.',
'I am glad if you enjoy it.',
],
},
}
JAPANESE_BODIES = [
JAPANESE['title'],
'%',
JAPANESE['contents'][0],
JAPANESE['contents'][1],
JAPANESE['contents'][2],
JAPANESE['contents'][3],
]
ENGLISH_BODIES = [
ENGLISH['title'],
'',
ENGLISH['contents'][0],
ENGLISH['contents'][1],
ENGLISH['contents'][2],
ENGLISH['contents'][3],
]
TITLES = (JAPANESE['title'][1:], ENGLISH['title'])
| 20.064516 | 51 | 0.434887 | JAPANESE = {
'title': '%プロローグ',
'contents': [
'% |本須 麗乃(もとすうらの)、22歳。',
'% わたしは本が好きだ。',
'$大好きだ。',
'% 三度のご飯より愛してる。',
'%「うっ……」',
],
'notes': {
'pre': [
'%蒼枝と申します。',
'%長編を書くのは初めてです。',
],
'post': [
'%とうとう始めてしまいました。',
'%楽しんでいただけたら嬉しいです。',
],
},
}
ENGLISH = {
'title': 'Prologue',
'contents': [
' My name is Mototsu Urano, 22 years old.',
' I like book.',
'Really really like.',
' I love it more than three times meals.',
'「Uu……」'
],
'notes': {
'pre': [
'I am Aoieda.',
"It's my first time writing novel.",
],
'post': [
'It has started at last.',
'I am glad if you enjoy it.',
],
},
}
JAPANESE_BODIES = [
JAPANESE['title'],
'%',
JAPANESE['contents'][0],
JAPANESE['contents'][1],
JAPANESE['contents'][2],
JAPANESE['contents'][3],
]
ENGLISH_BODIES = [
ENGLISH['title'],
'',
ENGLISH['contents'][0],
ENGLISH['contents'][1],
ENGLISH['contents'][2],
ENGLISH['contents'][3],
]
TITLES = (JAPANESE['title'][1:], ENGLISH['title'])
| true | true |
f729f6695b2e009749a202fe5cfeba04073f23f7 | 4,126 | py | Python | spinqkit/compiler/translator/qiskit_to_spinq.py | SpinQTech/SpinQKit | 2e24826688b2b26cf7efa66fd47f0e7ef883a96c | [
"Apache-2.0"
] | 2 | 2021-12-20T05:19:44.000Z | 2021-12-20T05:21:48.000Z | spinqkit/compiler/translator/qiskit_to_spinq.py | SpinQTech/SpinQKit | 2e24826688b2b26cf7efa66fd47f0e7ef883a96c | [
"Apache-2.0"
] | null | null | null | spinqkit/compiler/translator/qiskit_to_spinq.py | SpinQTech/SpinQKit | 2e24826688b2b26cf7efa66fd47f0e7ef883a96c | [
"Apache-2.0"
] | 1 | 2021-12-20T05:20:35.000Z | 2021-12-20T05:20:35.000Z | # Copyright 2021 SpinQ Technology Co., Ltd.
#
# 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 typing import Dict, List, Tuple, Optional
from math import pi
import qiskit.circuit as qqc
from spinqkit.model.gates import *
from spinqkit.model import Circuit, UnsupportedQiskitInstructionError
basis_map = {'id': I, 'h': H, 'x': X, 'y': Y, 'z': Z, 'rx': Rx, 'ry': Ry, 'rz': Rz, 't': T, 'tdg': Td, 's': S, 'sdg': Sd, 'p': P, 'cx': CX, 'cy': CY, 'cz': CZ, 'swap': SWAP, 'ccx': CCX, 'u': U, 'measure': MEASURE}
def qiskit_to_spinq(qc: qqc.QuantumCircuit) -> Circuit:
circ = Circuit()
qreg_map = {}
creg_map = {}
for register in qc.qregs:
tmp = circ.allocateQubits(register.size)
qreg_map[register.name] = tmp
for register in qc.cregs:
tmp = circ.allocateClbits(register.size)
creg_map[register.name] = tmp
add_instruction(qc, circ, qreg_map, creg_map)
return circ
def add_instruction(qc: qqc.QuantumCircuit, circ: Circuit, qreg_map: Dict, creg_map: Dict, qubits: Optional[List] = None, condition: Optional[Tuple] = None):
"""
Args:
qubits: for recursive conversion, None at first.
condition: for recursive conversion, None at first.
"""
ctl_count = 0
for reg in qc.qregs:
if reg.name == 'control':
ctl_count += reg.size
for instruction, qargs, cargs in qc.data:
if instruction.condition != None:
classical = instruction.condition[0]
if isinstance(classical, qqc.Clbit):
clbits = [creg_map[classical.register.name][classical.index]]
else:
clbits = creg_map[classical.name]
condition = (clbits, '==', int(instruction.condition[1]))
if not isinstance(instruction, (qqc.Gate, qqc.Instruction, qqc.Measure, qqc.Barrier)):
raise UnsupportedQiskitInstructionError
if qubits == None:
sub_qubits = qargs
else:
if isinstance(instruction, qqc.ControlledGate):
sub_qubits = []
for q in qargs:
if q.register.name == 'control':
sub_qubits.append(qubits[q.index])
else:
sub_qubits.append(qubits[q.index + ctl_count])
else:
sub_qubits = [qubits[q.index + ctl_count] for q in qargs]
if instruction.name in basis_map.keys():
gate = basis_map[instruction.name]
qlist = [qreg_map[arg.register.name][arg.index] for arg in sub_qubits]
if cargs != None:
clist = [creg_map[arg.register.name][arg.index] for arg in cargs]
params = instruction.params
if params != None and len(params) > 0:
if condition != None:
circ<< (gate, qlist, *params) | condition
else:
circ<< (gate, qlist, *params)
else:
if condition != None:
if gate == MEASURE:
raise UnsupportedQiskitInstructionError('Measure cannot be conditional.')
circ<< (gate, qlist) | condition
else:
if gate == MEASURE:
circ.measure(qlist, clist)
else:
circ<< (gate, qlist)
elif isinstance(instruction, qqc.Barrier):
continue
else:
add_instruction(instruction.definition, circ, qreg_map, creg_map, sub_qubits, condition)
| 40.45098 | 213 | 0.579738 |
from typing import Dict, List, Tuple, Optional
from math import pi
import qiskit.circuit as qqc
from spinqkit.model.gates import *
from spinqkit.model import Circuit, UnsupportedQiskitInstructionError
basis_map = {'id': I, 'h': H, 'x': X, 'y': Y, 'z': Z, 'rx': Rx, 'ry': Ry, 'rz': Rz, 't': T, 'tdg': Td, 's': S, 'sdg': Sd, 'p': P, 'cx': CX, 'cy': CY, 'cz': CZ, 'swap': SWAP, 'ccx': CCX, 'u': U, 'measure': MEASURE}
def qiskit_to_spinq(qc: qqc.QuantumCircuit) -> Circuit:
circ = Circuit()
qreg_map = {}
creg_map = {}
for register in qc.qregs:
tmp = circ.allocateQubits(register.size)
qreg_map[register.name] = tmp
for register in qc.cregs:
tmp = circ.allocateClbits(register.size)
creg_map[register.name] = tmp
add_instruction(qc, circ, qreg_map, creg_map)
return circ
def add_instruction(qc: qqc.QuantumCircuit, circ: Circuit, qreg_map: Dict, creg_map: Dict, qubits: Optional[List] = None, condition: Optional[Tuple] = None):
ctl_count = 0
for reg in qc.qregs:
if reg.name == 'control':
ctl_count += reg.size
for instruction, qargs, cargs in qc.data:
if instruction.condition != None:
classical = instruction.condition[0]
if isinstance(classical, qqc.Clbit):
clbits = [creg_map[classical.register.name][classical.index]]
else:
clbits = creg_map[classical.name]
condition = (clbits, '==', int(instruction.condition[1]))
if not isinstance(instruction, (qqc.Gate, qqc.Instruction, qqc.Measure, qqc.Barrier)):
raise UnsupportedQiskitInstructionError
if qubits == None:
sub_qubits = qargs
else:
if isinstance(instruction, qqc.ControlledGate):
sub_qubits = []
for q in qargs:
if q.register.name == 'control':
sub_qubits.append(qubits[q.index])
else:
sub_qubits.append(qubits[q.index + ctl_count])
else:
sub_qubits = [qubits[q.index + ctl_count] for q in qargs]
if instruction.name in basis_map.keys():
gate = basis_map[instruction.name]
qlist = [qreg_map[arg.register.name][arg.index] for arg in sub_qubits]
if cargs != None:
clist = [creg_map[arg.register.name][arg.index] for arg in cargs]
params = instruction.params
if params != None and len(params) > 0:
if condition != None:
circ<< (gate, qlist, *params) | condition
else:
circ<< (gate, qlist, *params)
else:
if condition != None:
if gate == MEASURE:
raise UnsupportedQiskitInstructionError('Measure cannot be conditional.')
circ<< (gate, qlist) | condition
else:
if gate == MEASURE:
circ.measure(qlist, clist)
else:
circ<< (gate, qlist)
elif isinstance(instruction, qqc.Barrier):
continue
else:
add_instruction(instruction.definition, circ, qreg_map, creg_map, sub_qubits, condition)
| true | true |
f729f681eda6168bd03f4dd8f947ad2edae46e87 | 5,047 | py | Python | polaris/polaris/tests/commands/test_watch_transactions.py | yuriescl/django-polaris | 8806d0e4e8baaddbffbceb3609786d2436b8abe1 | [
"Apache-2.0"
] | 81 | 2019-11-16T21:47:22.000Z | 2022-02-17T07:35:02.000Z | polaris/polaris/tests/commands/test_watch_transactions.py | yuriescl/django-polaris | 8806d0e4e8baaddbffbceb3609786d2436b8abe1 | [
"Apache-2.0"
] | 491 | 2019-11-10T23:44:30.000Z | 2022-03-20T00:25:02.000Z | polaris/polaris/tests/commands/test_watch_transactions.py | yuriescl/django-polaris | 8806d0e4e8baaddbffbceb3609786d2436b8abe1 | [
"Apache-2.0"
] | 89 | 2019-11-18T21:31:01.000Z | 2022-03-28T13:47:41.000Z | import pytest
from copy import deepcopy
from stellar_sdk.keypair import Keypair
from asgiref.sync import async_to_sync
from polaris.models import Transaction, Asset
from polaris.management.commands.watch_transactions import Command
test_module = "polaris.management.commands.watch_transactions"
SUCCESS_PAYMENT_TRANSACTION_JSON = {
"id": "57544d839c3b172a5a6651630115e5189f5a7436ddcb8ce2bece14e908f156c5",
"successful": True,
"envelope_xdr": "AAAAAgAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAGQAByFhAAAAAwAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAADRA2v7e/0dICoolPpt+5L+v45drrxXm4r3H+S8fQdfngAAAAFURVNUAAAAAL2egQB+kGbcOoO4/fGQa///H8tqChQ/wtoiYJ6djCsoAAAAF0h26AAAAAAAAAAAAZ2MKygAAABAGYFWPSC205xgP1UjSHftcBp2N06shrZYfRcjr8ekHsf6iK/+7uWPw0adncxgOmy2oMGbdFi+ZH+MGrAKDY8WCg==",
"result_xdr": "AAAAAAAAAGQAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAA=",
"memo": "AAAAAAAAAAAAAAAAAAAAAIDqc+oB00EajZzqIpme754=",
"memo_type": "hash",
"source": "GC6Z5AIAP2IGNXB2QO4P34MQNP776H6LNIFBIP6C3IRGBHU5RQVSQ7XM",
"paging_token": "2007270145658880",
}
SUCCESS_STRICT_SEND_PAYMENT = {
"id": "00768d12b1753414316c9760993f3998868583121b5560b52a3bcf7dacf3dfc2",
"successful": True,
"envelope_xdr": "AAAAAgAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAGQAByFhAAAABAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAh0ZXh0bWVtbwAAAAEAAAAAAAAADQAAAAFURVNUAAAAAL2egQB+kGbcOoO4/fGQa///H8tqChQ/wtoiYJ6djCsoAAAAAlSkeoAAAAAA0QNr+3v9HSAqKJT6bfuS/r+OXa68V5uK9x/kvH0HX54AAAABVEVTVAAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAAJUC+QAAAAAAAAAAAAAAAABnYwrKAAAAECbS2lOWDZmOxHu4e5z+Ema+71wLtsktlxBnB20SZrteur8hu9cRls/sWR2Klg2Q2jhgL/wslYPzvbBg4La8nUM",
"result_xdr": "AAAAAAAAAGQAAAAAAAAAAQAAAAAAAAANAAAAAAAAAAAAAAAA0QNr+3v9HSAqKJT6bfuS/r+OXa68V5uK9x/kvH0HX54AAAABVEVTVAAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAAJUpHqAAAAAAA==",
"memo": "textmemo",
"memo_type": "text",
"source": "GC6Z5AIAP2IGNXB2QO4P34MQNP776H6LNIFBIP6C3IRGBHU5RQVSQ7XM",
"paging_token": "2009348909830144",
}
TEST_ASSET_ISSUER_SEED = "SADPW3NKRUNSNKXZ3UCNKF5QKXFS3IBNDLIEDV4PEDLIXBXJOGSOQW6J"
TEST_ASSET_ISSUER_PUBLIC_KEY = Keypair.from_secret(TEST_ASSET_ISSUER_SEED).public_key
TEST_ASSET_DISTRIBUTION_SEED = (
"SBYMIF4ZEVMDF4JTLKLKZNJW4TGO4XBQK6UGLRY4XSWMNIFY4KHG5XKD"
)
TEST_ASSET_DISTRIBUTION_PUBLIC_KEY = Keypair.from_secret(
TEST_ASSET_DISTRIBUTION_SEED
).public_key
@pytest.mark.django_db
def test_process_response_success(client):
"""
Tests successful processing of the SUCCESS_PAYMENT_TRANSACTION_JSON
"""
asset = Asset.objects.create(
code="TEST",
issuer=TEST_ASSET_ISSUER_PUBLIC_KEY,
distribution_seed=TEST_ASSET_DISTRIBUTION_SEED,
)
transaction = Transaction.objects.create(
asset=asset,
stellar_account=Keypair.random().public_key,
amount_in=9000,
amount_expected=9000,
kind=Transaction.KIND.withdrawal,
status=Transaction.STATUS.pending_user_transfer_start,
memo=SUCCESS_PAYMENT_TRANSACTION_JSON["memo"],
protocol=Transaction.PROTOCOL.sep24,
receiving_anchor_account=TEST_ASSET_DISTRIBUTION_PUBLIC_KEY,
)
json = deepcopy(SUCCESS_PAYMENT_TRANSACTION_JSON)
async_to_sync(Command().process_response)(json, TEST_ASSET_DISTRIBUTION_PUBLIC_KEY)
transaction.refresh_from_db()
assert transaction.from_address
assert transaction.stellar_transaction_id
assert transaction.paging_token
assert transaction.status == Transaction.STATUS.pending_anchor
assert transaction.amount_in == 10000
assert transaction.amount_expected == 9000
@pytest.mark.django_db
def test_process_response_strict_send_success(client):
"""
Tests successful processing of the SUCCESS_PAYMENT_TRANSACTION_JSON
"""
asset = Asset.objects.create(
code="TEST",
issuer=TEST_ASSET_ISSUER_PUBLIC_KEY,
distribution_seed=TEST_ASSET_DISTRIBUTION_SEED,
)
transaction = Transaction.objects.create(
asset=asset,
stellar_account=Keypair.random().public_key,
amount_in=1001,
kind=Transaction.KIND.send,
status=Transaction.STATUS.pending_sender,
memo=SUCCESS_STRICT_SEND_PAYMENT["memo"],
protocol=Transaction.PROTOCOL.sep31,
receiving_anchor_account=TEST_ASSET_DISTRIBUTION_PUBLIC_KEY,
)
json = deepcopy(SUCCESS_STRICT_SEND_PAYMENT)
async_to_sync(Command().process_response)(json, TEST_ASSET_DISTRIBUTION_PUBLIC_KEY)
transaction.refresh_from_db()
assert transaction.from_address
assert transaction.stellar_transaction_id
assert transaction.paging_token
assert transaction.status == Transaction.STATUS.pending_receiver
assert transaction.amount_in == 1001
def test_process_response_unsuccessful(client, acc1_usd_withdrawal_transaction_factory):
json = {"successful": False}
try:
async_to_sync(Command().process_response)(json, None)
except KeyError:
assert False, "process_response() did not return for unsuccessful transaction"
| 44.663717 | 455 | 0.799881 | import pytest
from copy import deepcopy
from stellar_sdk.keypair import Keypair
from asgiref.sync import async_to_sync
from polaris.models import Transaction, Asset
from polaris.management.commands.watch_transactions import Command
test_module = "polaris.management.commands.watch_transactions"
SUCCESS_PAYMENT_TRANSACTION_JSON = {
"id": "57544d839c3b172a5a6651630115e5189f5a7436ddcb8ce2bece14e908f156c5",
"successful": True,
"envelope_xdr": "AAAAAgAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAGQAByFhAAAAAwAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAADRA2v7e/0dICoolPpt+5L+v45drrxXm4r3H+S8fQdfngAAAAFURVNUAAAAAL2egQB+kGbcOoO4/fGQa///H8tqChQ/wtoiYJ6djCsoAAAAF0h26AAAAAAAAAAAAZ2MKygAAABAGYFWPSC205xgP1UjSHftcBp2N06shrZYfRcjr8ekHsf6iK/+7uWPw0adncxgOmy2oMGbdFi+ZH+MGrAKDY8WCg==",
"result_xdr": "AAAAAAAAAGQAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAA=",
"memo": "AAAAAAAAAAAAAAAAAAAAAIDqc+oB00EajZzqIpme754=",
"memo_type": "hash",
"source": "GC6Z5AIAP2IGNXB2QO4P34MQNP776H6LNIFBIP6C3IRGBHU5RQVSQ7XM",
"paging_token": "2007270145658880",
}
SUCCESS_STRICT_SEND_PAYMENT = {
"id": "00768d12b1753414316c9760993f3998868583121b5560b52a3bcf7dacf3dfc2",
"successful": True,
"envelope_xdr": "AAAAAgAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAGQAByFhAAAABAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAh0ZXh0bWVtbwAAAAEAAAAAAAAADQAAAAFURVNUAAAAAL2egQB+kGbcOoO4/fGQa///H8tqChQ/wtoiYJ6djCsoAAAAAlSkeoAAAAAA0QNr+3v9HSAqKJT6bfuS/r+OXa68V5uK9x/kvH0HX54AAAABVEVTVAAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAAJUC+QAAAAAAAAAAAAAAAABnYwrKAAAAECbS2lOWDZmOxHu4e5z+Ema+71wLtsktlxBnB20SZrteur8hu9cRls/sWR2Klg2Q2jhgL/wslYPzvbBg4La8nUM",
"result_xdr": "AAAAAAAAAGQAAAAAAAAAAQAAAAAAAAANAAAAAAAAAAAAAAAA0QNr+3v9HSAqKJT6bfuS/r+OXa68V5uK9x/kvH0HX54AAAABVEVTVAAAAAC9noEAfpBm3DqDuP3xkGv//x/LagoUP8LaImCenYwrKAAAAAJUpHqAAAAAAA==",
"memo": "textmemo",
"memo_type": "text",
"source": "GC6Z5AIAP2IGNXB2QO4P34MQNP776H6LNIFBIP6C3IRGBHU5RQVSQ7XM",
"paging_token": "2009348909830144",
}
TEST_ASSET_ISSUER_SEED = "SADPW3NKRUNSNKXZ3UCNKF5QKXFS3IBNDLIEDV4PEDLIXBXJOGSOQW6J"
TEST_ASSET_ISSUER_PUBLIC_KEY = Keypair.from_secret(TEST_ASSET_ISSUER_SEED).public_key
TEST_ASSET_DISTRIBUTION_SEED = (
"SBYMIF4ZEVMDF4JTLKLKZNJW4TGO4XBQK6UGLRY4XSWMNIFY4KHG5XKD"
)
TEST_ASSET_DISTRIBUTION_PUBLIC_KEY = Keypair.from_secret(
TEST_ASSET_DISTRIBUTION_SEED
).public_key
@pytest.mark.django_db
def test_process_response_success(client):
asset = Asset.objects.create(
code="TEST",
issuer=TEST_ASSET_ISSUER_PUBLIC_KEY,
distribution_seed=TEST_ASSET_DISTRIBUTION_SEED,
)
transaction = Transaction.objects.create(
asset=asset,
stellar_account=Keypair.random().public_key,
amount_in=9000,
amount_expected=9000,
kind=Transaction.KIND.withdrawal,
status=Transaction.STATUS.pending_user_transfer_start,
memo=SUCCESS_PAYMENT_TRANSACTION_JSON["memo"],
protocol=Transaction.PROTOCOL.sep24,
receiving_anchor_account=TEST_ASSET_DISTRIBUTION_PUBLIC_KEY,
)
json = deepcopy(SUCCESS_PAYMENT_TRANSACTION_JSON)
async_to_sync(Command().process_response)(json, TEST_ASSET_DISTRIBUTION_PUBLIC_KEY)
transaction.refresh_from_db()
assert transaction.from_address
assert transaction.stellar_transaction_id
assert transaction.paging_token
assert transaction.status == Transaction.STATUS.pending_anchor
assert transaction.amount_in == 10000
assert transaction.amount_expected == 9000
@pytest.mark.django_db
def test_process_response_strict_send_success(client):
asset = Asset.objects.create(
code="TEST",
issuer=TEST_ASSET_ISSUER_PUBLIC_KEY,
distribution_seed=TEST_ASSET_DISTRIBUTION_SEED,
)
transaction = Transaction.objects.create(
asset=asset,
stellar_account=Keypair.random().public_key,
amount_in=1001,
kind=Transaction.KIND.send,
status=Transaction.STATUS.pending_sender,
memo=SUCCESS_STRICT_SEND_PAYMENT["memo"],
protocol=Transaction.PROTOCOL.sep31,
receiving_anchor_account=TEST_ASSET_DISTRIBUTION_PUBLIC_KEY,
)
json = deepcopy(SUCCESS_STRICT_SEND_PAYMENT)
async_to_sync(Command().process_response)(json, TEST_ASSET_DISTRIBUTION_PUBLIC_KEY)
transaction.refresh_from_db()
assert transaction.from_address
assert transaction.stellar_transaction_id
assert transaction.paging_token
assert transaction.status == Transaction.STATUS.pending_receiver
assert transaction.amount_in == 1001
def test_process_response_unsuccessful(client, acc1_usd_withdrawal_transaction_factory):
json = {"successful": False}
try:
async_to_sync(Command().process_response)(json, None)
except KeyError:
assert False, "process_response() did not return for unsuccessful transaction"
| true | true |
f729f7025003e41e6ac53ba5dfc94c8f2008dbff | 2,865 | py | Python | src/ggrc/models/category.py | sriharshakappala/ggrc-core | 7561ce27cd987d73468a44df5b6e2b7425f050ef | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-04-21T12:21:17.000Z | 2019-04-21T12:21:17.000Z | src/ggrc/models/category.py | sriharshakappala/ggrc-core | 7561ce27cd987d73468a44df5b6e2b7425f050ef | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/ggrc/models/category.py | sriharshakappala/ggrc-core | 7561ce27cd987d73468a44df5b6e2b7425f050ef | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By:
# Maintained By:
from ggrc import db
from sqlalchemy.ext.associationproxy import association_proxy
from .categorization import Categorization
from .mixins import deferred, Base, Hierarchical
class CategorizedPublishable(object):
def __init__(self, attr_name, type_name):
self.attr_name = attr_name
self.type_name = type_name
@property
def rel_class(self):
import ggrc.models
return getattr(ggrc.models, self.type_name)
def __call__(self, updater, obj, json_obj):
return updater.query_for(self.rel_class, json_obj, self.attr_name, True)
class Category(Hierarchical, Base, db.Model):
__tablename__ = 'categories'
name = deferred(db.Column(db.String), 'Category')
lft = deferred(db.Column(db.Integer), 'Category')
rgt = deferred(db.Column(db.Integer), 'Category')
scope_id = deferred(db.Column(db.Integer), 'Category')
depth = deferred(db.Column(db.Integer), 'Category')
required = deferred(db.Column(db.Boolean), 'Category')
categorizations = db.relationship(
'ggrc.models.categorization.Categorization',
backref='category',
cascade='all, delete-orphan',
)
control_categorizations = db.relationship(
'Categorization',
primaryjoin=\
'and_(foreign(Categorization.category_id) == Category.id, '
'foreign(Categorization.categorizable_type) == "Control")',
)
risk_categorizations = db.relationship(
'Categorization',
primaryjoin=\
'and_(foreign(Categorization.category_id) == Category.id, '
'foreign(Categorization.categorizable_type) == "Risk")',
)
controls = association_proxy(
'control_categorizations', 'categorizable',
creator=lambda categorizable: Categorization(
categorizable=categorizable,
categorizable_type='Control',
),
)
risks = association_proxy(
'risk_categorizations', 'categorizable',
creator=lambda categorizable: Categorization(
categorizable=categorizable,
categorizable_type='Risk',
),
)
# REST properties
_publish_attrs = [
'name',
'scope_id',
'required',
'categorizations',
'control_categorizations',
'risk_categorizations',
CategorizedPublishable('controls', 'Control'),
CategorizedPublishable('risks', 'Risk'),
]
_sanitize_html = [
'name',
]
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(Category, cls).eager_query()
return query.options(
orm.subqueryload('categorizations'),
orm.subqueryload('risk_categorizations'),
orm.subqueryload('control_categorizations'))
| 31.483516 | 78 | 0.681675 |
from ggrc import db
from sqlalchemy.ext.associationproxy import association_proxy
from .categorization import Categorization
from .mixins import deferred, Base, Hierarchical
class CategorizedPublishable(object):
def __init__(self, attr_name, type_name):
self.attr_name = attr_name
self.type_name = type_name
@property
def rel_class(self):
import ggrc.models
return getattr(ggrc.models, self.type_name)
def __call__(self, updater, obj, json_obj):
return updater.query_for(self.rel_class, json_obj, self.attr_name, True)
class Category(Hierarchical, Base, db.Model):
__tablename__ = 'categories'
name = deferred(db.Column(db.String), 'Category')
lft = deferred(db.Column(db.Integer), 'Category')
rgt = deferred(db.Column(db.Integer), 'Category')
scope_id = deferred(db.Column(db.Integer), 'Category')
depth = deferred(db.Column(db.Integer), 'Category')
required = deferred(db.Column(db.Boolean), 'Category')
categorizations = db.relationship(
'ggrc.models.categorization.Categorization',
backref='category',
cascade='all, delete-orphan',
)
control_categorizations = db.relationship(
'Categorization',
primaryjoin=\
'and_(foreign(Categorization.category_id) == Category.id, '
'foreign(Categorization.categorizable_type) == "Control")',
)
risk_categorizations = db.relationship(
'Categorization',
primaryjoin=\
'and_(foreign(Categorization.category_id) == Category.id, '
'foreign(Categorization.categorizable_type) == "Risk")',
)
controls = association_proxy(
'control_categorizations', 'categorizable',
creator=lambda categorizable: Categorization(
categorizable=categorizable,
categorizable_type='Control',
),
)
risks = association_proxy(
'risk_categorizations', 'categorizable',
creator=lambda categorizable: Categorization(
categorizable=categorizable,
categorizable_type='Risk',
),
)
_publish_attrs = [
'name',
'scope_id',
'required',
'categorizations',
'control_categorizations',
'risk_categorizations',
CategorizedPublishable('controls', 'Control'),
CategorizedPublishable('risks', 'Risk'),
]
_sanitize_html = [
'name',
]
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(Category, cls).eager_query()
return query.options(
orm.subqueryload('categorizations'),
orm.subqueryload('risk_categorizations'),
orm.subqueryload('control_categorizations'))
| true | true |
f729f79dcce70336521e1975dfaa2420b22bc995 | 2,167 | py | Python | benchmarks/operator_benchmark/pt/qbatchnorm_test.py | jsun94/nimble | e5c899a69677818b1becc58100577441e15ede13 | [
"BSD-3-Clause"
] | 206 | 2020-11-28T22:56:38.000Z | 2022-03-27T02:33:04.000Z | benchmarks/operator_benchmark/pt/qbatchnorm_test.py | jsun94/nimble | e5c899a69677818b1becc58100577441e15ede13 | [
"BSD-3-Clause"
] | 19 | 2020-12-09T23:13:14.000Z | 2022-01-24T23:24:08.000Z | benchmarks/operator_benchmark/pt/qbatchnorm_test.py | jsun94/nimble | e5c899a69677818b1becc58100577441e15ede13 | [
"BSD-3-Clause"
] | 28 | 2020-11-29T15:25:12.000Z | 2022-01-20T02:16:27.000Z |
import operator_benchmark as op_bench
import torch
"""Microbenchmarks for quantized batchnorm operator."""
batchnorm_configs_short = op_bench.config_list(
attr_names=["M", "N", "K"],
attrs=[
[1, 256, 3136],
],
cross_product_configs={
'device': ['cpu'],
'dtype': (torch.qint8,),
},
tags=["short"]
)
class QBatchNormBenchmark(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device, dtype):
self._init(M, N, K, device)
x_scale = 0.1
x_zero_point = 0
self.q_input_one = torch.quantize_per_tensor(
self.input_one, scale=x_scale, zero_point=x_zero_point, dtype=dtype)
self.mean = torch.rand(N)
self.var = torch.rand(N)
self.weight = torch.rand(N)
self.bias = torch.rand(N)
self.eps = 1e-5
self.Y_scale = 0.1
self.Y_zero_point = 0
def _init(self, M, N, K, device):
pass
def forward(self):
pass
class QBatchNorm1dBenchmark(QBatchNormBenchmark):
def _init(self, M, N, K, device):
self.set_module_name("QBatchNorm1d")
self.input_one = torch.rand(M, N, K, device=device, requires_grad=self.auto_set())
def forward(self):
return torch.ops.quantized.batch_norm1d(
self.q_input_one, self.weight, self.bias, self.mean, self.var, self.eps,
self.Y_scale, self.Y_zero_point)
class QBatchNorm2dBenchmark(QBatchNormBenchmark):
def _init(self, M, N, K, device):
self.set_module_name("QBatchNorm2d")
# Note: quantized implementation requires rank 4, which is why we
# add a 1 as the last dimension
self.input_one = torch.rand(M, N, K, 1, device=device, requires_grad=self.auto_set())
def forward(self):
return torch.ops.quantized.batch_norm2d(
self.q_input_one, self.weight, self.bias, self.mean, self.var, self.eps,
self.Y_scale, self.Y_zero_point)
op_bench.generate_pt_test(batchnorm_configs_short, QBatchNorm1dBenchmark)
op_bench.generate_pt_test(batchnorm_configs_short, QBatchNorm2dBenchmark)
if __name__ == "__main__":
op_bench.benchmark_runner.main()
| 30.097222 | 93 | 0.653438 |
import operator_benchmark as op_bench
import torch
batchnorm_configs_short = op_bench.config_list(
attr_names=["M", "N", "K"],
attrs=[
[1, 256, 3136],
],
cross_product_configs={
'device': ['cpu'],
'dtype': (torch.qint8,),
},
tags=["short"]
)
class QBatchNormBenchmark(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device, dtype):
self._init(M, N, K, device)
x_scale = 0.1
x_zero_point = 0
self.q_input_one = torch.quantize_per_tensor(
self.input_one, scale=x_scale, zero_point=x_zero_point, dtype=dtype)
self.mean = torch.rand(N)
self.var = torch.rand(N)
self.weight = torch.rand(N)
self.bias = torch.rand(N)
self.eps = 1e-5
self.Y_scale = 0.1
self.Y_zero_point = 0
def _init(self, M, N, K, device):
pass
def forward(self):
pass
class QBatchNorm1dBenchmark(QBatchNormBenchmark):
def _init(self, M, N, K, device):
self.set_module_name("QBatchNorm1d")
self.input_one = torch.rand(M, N, K, device=device, requires_grad=self.auto_set())
def forward(self):
return torch.ops.quantized.batch_norm1d(
self.q_input_one, self.weight, self.bias, self.mean, self.var, self.eps,
self.Y_scale, self.Y_zero_point)
class QBatchNorm2dBenchmark(QBatchNormBenchmark):
def _init(self, M, N, K, device):
self.set_module_name("QBatchNorm2d")
self.input_one = torch.rand(M, N, K, 1, device=device, requires_grad=self.auto_set())
def forward(self):
return torch.ops.quantized.batch_norm2d(
self.q_input_one, self.weight, self.bias, self.mean, self.var, self.eps,
self.Y_scale, self.Y_zero_point)
op_bench.generate_pt_test(batchnorm_configs_short, QBatchNorm1dBenchmark)
op_bench.generate_pt_test(batchnorm_configs_short, QBatchNorm2dBenchmark)
if __name__ == "__main__":
op_bench.benchmark_runner.main()
| true | true |
f729f7dcdbbe095d24e280d9ce242d54664e518e | 1,146 | py | Python | 2 - data2graph/evaluateData/changeNames.py | Tocha4/HSM-Solubility | 8a83c1270d739f0c7fbb7decf6202e90e6ebc083 | [
"MIT"
] | null | null | null | 2 - data2graph/evaluateData/changeNames.py | Tocha4/HSM-Solubility | 8a83c1270d739f0c7fbb7decf6202e90e6ebc083 | [
"MIT"
] | null | null | null | 2 - data2graph/evaluateData/changeNames.py | Tocha4/HSM-Solubility | 8a83c1270d739f0c7fbb7decf6202e90e6ebc083 | [
"MIT"
] | null | null | null | import Anton as aen
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.stats import linregress
def changeCelsius(path):
files = aen.searchfiles(path, '.npy')
files.sort()
for i in files:
fname,name = os.path.split(i)
if 'Celsius' in name:
nm = name.split('Celsius')
nm = nm[0]+nm[1]
os.rename(os.path.join(fname,name), os.path.join(fname,nm))
return print('geaender')
def change2under(path):
files = aen.searchfiles(path, '.npy')
files.sort()
j = 0
for i in files:
j += 1
fname, name = os.path.split(i)
try:
nm = name.replace('KE60','KE_60')
os.rename(os.path.join(fname,name), os.path.join(fname,nm))
print(nm)
except: pass
return print('%s Files vorhanden'% str(j))
if __name__ == '__main__':
path = r'Z:\2_Projekt__Permeabilitätsbeeinflussung\02_Löslichkeitsuntersuchungen\HS Microscope\Experiments\Final_results\data'
change2under(path)
| 19.1 | 130 | 0.558464 | import Anton as aen
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.stats import linregress
def changeCelsius(path):
files = aen.searchfiles(path, '.npy')
files.sort()
for i in files:
fname,name = os.path.split(i)
if 'Celsius' in name:
nm = name.split('Celsius')
nm = nm[0]+nm[1]
os.rename(os.path.join(fname,name), os.path.join(fname,nm))
return print('geaender')
def change2under(path):
files = aen.searchfiles(path, '.npy')
files.sort()
j = 0
for i in files:
j += 1
fname, name = os.path.split(i)
try:
nm = name.replace('KE60','KE_60')
os.rename(os.path.join(fname,name), os.path.join(fname,nm))
print(nm)
except: pass
return print('%s Files vorhanden'% str(j))
if __name__ == '__main__':
path = r'Z:\2_Projekt__Permeabilitätsbeeinflussung\02_Löslichkeitsuntersuchungen\HS Microscope\Experiments\Final_results\data'
change2under(path)
| true | true |
f729f8438327633fc7d4f11f24f1136b21b56cd5 | 2,045 | py | Python | {{ cookiecutter.repo_name }}/{{ cookiecutter.repo_name }}/due.py | gpnlab/cookiecutter-gpnlab | dd6e949fe2a203c77f6ea30e84c95f0306c7b64e | [
"MIT"
] | 213 | 2015-06-22T09:23:32.000Z | 2022-03-17T02:01:53.000Z | {{ cookiecutter.repo_name }}/{{ cookiecutter.repo_name }}/due.py | gpnlab/cookiecutter-gpnlab | dd6e949fe2a203c77f6ea30e84c95f0306c7b64e | [
"MIT"
] | 165 | 2015-06-14T23:23:15.000Z | 2021-09-30T20:06:15.000Z | {{ cookiecutter.repo_name }}/{{ cookiecutter.repo_name }}/due.py | gpnlab/cookiecutter-gpnlab | dd6e949fe2a203c77f6ea30e84c95f0306c7b64e | [
"MIT"
] | 29 | 2015-06-12T20:37:43.000Z | 2021-04-13T12:23:55.000Z | # emacs: at the end of the file
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
"""
Stub file for a guaranteed safe import of duecredit constructs: if duecredit
is not available.
To use it, place it into your project codebase to be imported, e.g. copy as
cp stub.py /path/tomodule/module/due.py
Note that it might be better to avoid naming it duecredit.py to avoid shadowing
installed duecredit.
Then use in your code as
from .due import due, Doi, BibTeX, Text
See https://github.com/duecredit/duecredit/blob/master/README.md for examples.
Origin: Originally a part of the duecredit
Copyright: 2015-2021 DueCredit developers
License: BSD-2
"""
__version__ = '0.0.9'
class InactiveDueCreditCollector(object):
"""Just a stub at the Collector which would not do anything"""
def _donothing(self, *args, **kwargs):
"""Perform no good and no bad"""
pass
def dcite(self, *args, **kwargs):
"""If I could cite I would"""
def nondecorating_decorator(func):
return func
return nondecorating_decorator
active = False
activate = add = cite = dump = load = _donothing
def __repr__(self):
return self.__class__.__name__ + '()'
def _donothing_func(*args, **kwargs):
"""Perform no good and no bad"""
pass
try:
from duecredit import due, BibTeX, Doi, Url, Text # lgtm [py/unused-import]
if 'due' in locals() and not hasattr(due, 'cite'):
raise RuntimeError(
"Imported due lacks .cite. DueCredit is now disabled")
except Exception as e:
if not isinstance(e, ImportError):
import logging
logging.getLogger("duecredit").error(
"Failed to import duecredit due to %s" % str(e))
# Initiate due stub
due = InactiveDueCreditCollector()
BibTeX = Doi = Url = Text = _donothing_func
# Emacs mode definitions
# Local Variables:
# mode: python
# py-indent-offset: 4
# tab-width: 4
# indent-tabs-mode: nil
# End:
| 27.266667 | 80 | 0.642543 | true | true | |
f729f8abc8999e421fa1f8940589e2a205788fd1 | 6,256 | py | Python | custom_components/aarlo/sensor.py | PysX/home-assistant-conf | 614c5a67314b6c7b8af4237a918a437b79ab460d | [
"MIT"
] | 28 | 2019-05-31T12:30:15.000Z | 2022-03-10T18:54:57.000Z | custom_components/aarlo/sensor.py | PysX/home-assistant-conf | 614c5a67314b6c7b8af4237a918a437b79ab460d | [
"MIT"
] | 5 | 2020-08-14T17:43:48.000Z | 2021-01-08T21:12:45.000Z | custom_components/aarlo/sensor.py | PysX/home-assistant-config | 614c5a67314b6c7b8af4237a918a437b79ab460d | [
"MIT"
] | 2 | 2021-03-31T08:27:19.000Z | 2021-04-30T15:13:24.000Z | """
This component provides HA sensor for Netgear Arlo IP cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.arlo/
"""
import logging
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_MONITORED_CONDITIONS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
TEMP_CELSIUS,
)
from homeassistant.core import callback
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.icon import icon_for_battery_level
from . import COMPONENT_ATTRIBUTION, COMPONENT_BRAND, COMPONENT_DATA, COMPONENT_DOMAIN
from .pyaarlo.constant import (
AIR_QUALITY_KEY,
BATTERY_KEY,
CAPTURED_TODAY_KEY,
HUMIDITY_KEY,
LAST_CAPTURE_KEY,
RECENT_ACTIVITY_KEY,
SIGNAL_STR_KEY,
TEMPERATURE_KEY,
TOTAL_CAMERAS_KEY,
)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = [COMPONENT_DOMAIN]
# sensor_type [ description, unit, icon, attribute ]
SENSOR_TYPES = {
"last_capture": ["Last", None, "run-fast", LAST_CAPTURE_KEY],
"total_cameras": ["Arlo Cameras", None, "video", TOTAL_CAMERAS_KEY],
"recent_activity": ["Recent Activity", None, "run-fast", RECENT_ACTIVITY_KEY],
"captured_today": ["Captured Today", None, "file-video", CAPTURED_TODAY_KEY],
"battery_level": ["Battery Level", "%", "battery-50", BATTERY_KEY],
"signal_strength": ["Signal Strength", None, "signal", SIGNAL_STR_KEY],
"temperature": ["Temperature", TEMP_CELSIUS, "thermometer", TEMPERATURE_KEY],
"humidity": ["Humidity", "%", "water-percent", HUMIDITY_KEY],
"air_quality": ["Air Quality", "ppm", "biohazard", AIR_QUALITY_KEY],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
),
}
)
async def async_setup_platform(hass, config, async_add_entities, _discovery_info=None):
"""Set up an Arlo IP sensor."""
arlo = hass.data.get(COMPONENT_DATA)
if not arlo:
return
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type == "total_cameras":
sensors.append(ArloSensor(arlo, None, sensor_type))
else:
for camera in arlo.cameras:
if camera.has_capability(SENSOR_TYPES[sensor_type][3]):
sensors.append(ArloSensor(arlo, camera, sensor_type))
for doorbell in arlo.doorbells:
if doorbell.has_capability(SENSOR_TYPES[sensor_type][3]):
sensors.append(ArloSensor(arlo, doorbell, sensor_type))
for light in arlo.lights:
if light.has_capability(SENSOR_TYPES[sensor_type][3]):
sensors.append(ArloSensor(arlo, light, sensor_type))
async_add_entities(sensors)
class ArloSensor(Entity):
"""An implementation of a Netgear Arlo IP sensor."""
def __init__(self, arlo, device, sensor_type):
"""Initialize an Arlo sensor."""
sensor_details = SENSOR_TYPES[sensor_type]
if device is None:
self._name = sensor_details[0]
self._unique_id = sensor_type
self._device = arlo
else:
self._name = "{0} {1}".format(sensor_details[0], device.name)
self._unique_id = (
"{0}_{1}".format(sensor_details[0], device.entity_id)
.lower()
.replace(" ", "_")
)
self._device = device
self._sensor_type = sensor_type
self._icon = "mdi:{}".format(sensor_details[2])
self._state = None
self._attr = sensor_details[3]
_LOGGER.info("ArloSensor: %s created", self._name)
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def update_state(_device, attr, value):
_LOGGER.debug("callback:" + self._name + ":" + attr + ":" + str(value)[:80])
self._state = value
self.async_schedule_update_ha_state()
if self._attr is not None:
self._state = self._device.attribute(self._attr)
self._device.add_attr_callback(self._attr, update_state)
@property
def should_poll(self):
return False
@property
def unique_id(self):
"""Return a unique ID."""
return self._unique_id
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def icon(self):
"""Icon to use in the frontend, if any."""
if self._sensor_type == "battery_level" and self._state is not None:
return icon_for_battery_level(
battery_level=int(self._state), charging=False
)
return self._icon
@property
def unit_of_measurement(self):
"""Return the units of measurement."""
return SENSOR_TYPES.get(self._sensor_type)[1]
@property
def device_class(self):
"""Return the device class of the sensor."""
if self._sensor_type == "temperature":
return DEVICE_CLASS_TEMPERATURE
if self._sensor_type == "humidity":
return DEVICE_CLASS_HUMIDITY
return None
@property
def device_state_attributes(self):
"""Return the device state attributes."""
attrs = {
ATTR_ATTRIBUTION: COMPONENT_ATTRIBUTION,
"brand": COMPONENT_BRAND,
"friendly_name": self._name,
"camera_name": self._device.name,
"device_id": self._device.device_id,
"model": self._device.model_id,
}
if self._sensor_type == "last_capture":
video = self._device.last_video
if video is not None:
attrs["object_type"] = video.object_type
attrs["object_region"] = video.object_region
attrs["thumbnail_url"] = video.thumbnail_url
attrs["video_url"] = video.video_url
else:
attrs["object_type"] = None
return attrs
| 33.634409 | 88 | 0.638427 | import logging
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_MONITORED_CONDITIONS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
TEMP_CELSIUS,
)
from homeassistant.core import callback
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.icon import icon_for_battery_level
from . import COMPONENT_ATTRIBUTION, COMPONENT_BRAND, COMPONENT_DATA, COMPONENT_DOMAIN
from .pyaarlo.constant import (
AIR_QUALITY_KEY,
BATTERY_KEY,
CAPTURED_TODAY_KEY,
HUMIDITY_KEY,
LAST_CAPTURE_KEY,
RECENT_ACTIVITY_KEY,
SIGNAL_STR_KEY,
TEMPERATURE_KEY,
TOTAL_CAMERAS_KEY,
)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = [COMPONENT_DOMAIN]
SENSOR_TYPES = {
"last_capture": ["Last", None, "run-fast", LAST_CAPTURE_KEY],
"total_cameras": ["Arlo Cameras", None, "video", TOTAL_CAMERAS_KEY],
"recent_activity": ["Recent Activity", None, "run-fast", RECENT_ACTIVITY_KEY],
"captured_today": ["Captured Today", None, "file-video", CAPTURED_TODAY_KEY],
"battery_level": ["Battery Level", "%", "battery-50", BATTERY_KEY],
"signal_strength": ["Signal Strength", None, "signal", SIGNAL_STR_KEY],
"temperature": ["Temperature", TEMP_CELSIUS, "thermometer", TEMPERATURE_KEY],
"humidity": ["Humidity", "%", "water-percent", HUMIDITY_KEY],
"air_quality": ["Air Quality", "ppm", "biohazard", AIR_QUALITY_KEY],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
),
}
)
async def async_setup_platform(hass, config, async_add_entities, _discovery_info=None):
arlo = hass.data.get(COMPONENT_DATA)
if not arlo:
return
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type == "total_cameras":
sensors.append(ArloSensor(arlo, None, sensor_type))
else:
for camera in arlo.cameras:
if camera.has_capability(SENSOR_TYPES[sensor_type][3]):
sensors.append(ArloSensor(arlo, camera, sensor_type))
for doorbell in arlo.doorbells:
if doorbell.has_capability(SENSOR_TYPES[sensor_type][3]):
sensors.append(ArloSensor(arlo, doorbell, sensor_type))
for light in arlo.lights:
if light.has_capability(SENSOR_TYPES[sensor_type][3]):
sensors.append(ArloSensor(arlo, light, sensor_type))
async_add_entities(sensors)
class ArloSensor(Entity):
def __init__(self, arlo, device, sensor_type):
sensor_details = SENSOR_TYPES[sensor_type]
if device is None:
self._name = sensor_details[0]
self._unique_id = sensor_type
self._device = arlo
else:
self._name = "{0} {1}".format(sensor_details[0], device.name)
self._unique_id = (
"{0}_{1}".format(sensor_details[0], device.entity_id)
.lower()
.replace(" ", "_")
)
self._device = device
self._sensor_type = sensor_type
self._icon = "mdi:{}".format(sensor_details[2])
self._state = None
self._attr = sensor_details[3]
_LOGGER.info("ArloSensor: %s created", self._name)
async def async_added_to_hass(self):
@callback
def update_state(_device, attr, value):
_LOGGER.debug("callback:" + self._name + ":" + attr + ":" + str(value)[:80])
self._state = value
self.async_schedule_update_ha_state()
if self._attr is not None:
self._state = self._device.attribute(self._attr)
self._device.add_attr_callback(self._attr, update_state)
@property
def should_poll(self):
return False
@property
def unique_id(self):
return self._unique_id
@property
def state(self):
return self._state
@property
def icon(self):
if self._sensor_type == "battery_level" and self._state is not None:
return icon_for_battery_level(
battery_level=int(self._state), charging=False
)
return self._icon
@property
def unit_of_measurement(self):
return SENSOR_TYPES.get(self._sensor_type)[1]
@property
def device_class(self):
if self._sensor_type == "temperature":
return DEVICE_CLASS_TEMPERATURE
if self._sensor_type == "humidity":
return DEVICE_CLASS_HUMIDITY
return None
@property
def device_state_attributes(self):
attrs = {
ATTR_ATTRIBUTION: COMPONENT_ATTRIBUTION,
"brand": COMPONENT_BRAND,
"friendly_name": self._name,
"camera_name": self._device.name,
"device_id": self._device.device_id,
"model": self._device.model_id,
}
if self._sensor_type == "last_capture":
video = self._device.last_video
if video is not None:
attrs["object_type"] = video.object_type
attrs["object_region"] = video.object_region
attrs["thumbnail_url"] = video.thumbnail_url
attrs["video_url"] = video.video_url
else:
attrs["object_type"] = None
return attrs
| true | true |
f729f97ebd39e6806075207fe6b3f0af5ed7b553 | 2,783 | py | Python | openstates/openstates-master/openstates/pa/committees.py | Jgorsick/Advocacy_Angular | 8906af3ba729b2303880f319d52bce0d6595764c | [
"CC-BY-4.0"
] | null | null | null | openstates/openstates-master/openstates/pa/committees.py | Jgorsick/Advocacy_Angular | 8906af3ba729b2303880f319d52bce0d6595764c | [
"CC-BY-4.0"
] | null | null | null | openstates/openstates-master/openstates/pa/committees.py | Jgorsick/Advocacy_Angular | 8906af3ba729b2303880f319d52bce0d6595764c | [
"CC-BY-4.0"
] | null | null | null | import re
from billy.scrape.committees import CommitteeScraper, Committee
import lxml.html
class CommitteeDict(dict):
def __missing__(self, key):
(chamber, committee_name, subcommittee_name) = key
committee = Committee(chamber, committee_name)
if subcommittee_name:
committee['subcommittee'] = subcommittee_name
self[key] = committee
return committee
class PACommitteeScraper(CommitteeScraper):
jurisdiction = 'pa'
latest_only = True
def scrape(self, chamber, term):
if chamber == 'upper':
url = ('http://www.legis.state.pa.us/cfdocs/legis/'
'home/member_information/senators_ca.cfm')
else:
url = ('http://www.legis.state.pa.us/cfdocs/legis/'
'home/member_information/representatives_ca.cfm')
page = self.get(url).text
page = lxml.html.fromstring(page)
committees = CommitteeDict()
for div in page.xpath("//div[@class='MemberInfoCteeList-Member']"):
thumbnail, bio, committee_list, _ = list(div)
name = bio.xpath(".//a")[-1].text_content().strip()
namey_bits = name.split()
party = namey_bits.pop().strip('()')
name = ' '.join(namey_bits).replace(' ,', ',')
for li in committee_list.xpath('div/ul/li'):
# Add the ex-officio members to all committees, apparently.
msg = 'Member ex-officio of all Standing Committees'
if li.text_content() == msg:
for (_chamber, _, _), committee in committees.items():
if chamber != _chamber:
continue
committee.add_member(name, 'member')
continue
# Everybody else normal.
subcommittee_name = None
committee_name = li.xpath('a/text()').pop()
role = 'member'
for _role in li.xpath('i/text()') or []:
if 'subcommittee' in _role.lower():
subcommittee_name, _, _role = _role.rpartition('-')
subcommittee_name = re.sub(r'[\s,]+', ' ',
subcommittee_name).strip()
role = re.sub(r'[\s,]+', ' ', _role).lower()
# Add the committee member.
key = (chamber, committee_name, subcommittee_name)
committees[key].add_member(name, role)
# Save the non-empty committees.
for committee in committees.values():
if not committee['members']:
continue
committee.add_source(url)
self.save_committee(committee)
| 36.618421 | 77 | 0.537909 | import re
from billy.scrape.committees import CommitteeScraper, Committee
import lxml.html
class CommitteeDict(dict):
def __missing__(self, key):
(chamber, committee_name, subcommittee_name) = key
committee = Committee(chamber, committee_name)
if subcommittee_name:
committee['subcommittee'] = subcommittee_name
self[key] = committee
return committee
class PACommitteeScraper(CommitteeScraper):
jurisdiction = 'pa'
latest_only = True
def scrape(self, chamber, term):
if chamber == 'upper':
url = ('http://www.legis.state.pa.us/cfdocs/legis/'
'home/member_information/senators_ca.cfm')
else:
url = ('http://www.legis.state.pa.us/cfdocs/legis/'
'home/member_information/representatives_ca.cfm')
page = self.get(url).text
page = lxml.html.fromstring(page)
committees = CommitteeDict()
for div in page.xpath("//div[@class='MemberInfoCteeList-Member']"):
thumbnail, bio, committee_list, _ = list(div)
name = bio.xpath(".//a")[-1].text_content().strip()
namey_bits = name.split()
party = namey_bits.pop().strip('()')
name = ' '.join(namey_bits).replace(' ,', ',')
for li in committee_list.xpath('div/ul/li'):
msg = 'Member ex-officio of all Standing Committees'
if li.text_content() == msg:
for (_chamber, _, _), committee in committees.items():
if chamber != _chamber:
continue
committee.add_member(name, 'member')
continue
subcommittee_name = None
committee_name = li.xpath('a/text()').pop()
role = 'member'
for _role in li.xpath('i/text()') or []:
if 'subcommittee' in _role.lower():
subcommittee_name, _, _role = _role.rpartition('-')
subcommittee_name = re.sub(r'[\s,]+', ' ',
subcommittee_name).strip()
role = re.sub(r'[\s,]+', ' ', _role).lower()
key = (chamber, committee_name, subcommittee_name)
committees[key].add_member(name, role)
for committee in committees.values():
if not committee['members']:
continue
committee.add_source(url)
self.save_committee(committee)
| true | true |
f729f9f23dfeec7bda100bb4d12668df62d6b044 | 460 | py | Python | output/models/nist_data/list_pkg/any_uri/schema_instance/nistschema_sv_iv_list_any_uri_length_2_xsd/nistschema_sv_iv_list_any_uri_length_2.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 1 | 2021-08-14T17:59:21.000Z | 2021-08-14T17:59:21.000Z | output/models/nist_data/list_pkg/any_uri/schema_instance/nistschema_sv_iv_list_any_uri_length_2_xsd/nistschema_sv_iv_list_any_uri_length_2.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 4 | 2020-02-12T21:30:44.000Z | 2020-04-15T20:06:46.000Z | output/models/nist_data/list_pkg/any_uri/schema_instance/nistschema_sv_iv_list_any_uri_length_2_xsd/nistschema_sv_iv_list_any_uri_length_2.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | null | null | null | from dataclasses import dataclass, field
from typing import List
__NAMESPACE__ = "NISTSchema-SV-IV-list-anyURI-length-2-NS"
@dataclass
class NistschemaSvIvListAnyUriLength2:
class Meta:
name = "NISTSchema-SV-IV-list-anyURI-length-2"
namespace = "NISTSchema-SV-IV-list-anyURI-length-2-NS"
value: List[str] = field(
default_factory=list,
metadata={
"length": 6,
"tokens": True,
}
)
| 23 | 62 | 0.636957 | from dataclasses import dataclass, field
from typing import List
__NAMESPACE__ = "NISTSchema-SV-IV-list-anyURI-length-2-NS"
@dataclass
class NistschemaSvIvListAnyUriLength2:
class Meta:
name = "NISTSchema-SV-IV-list-anyURI-length-2"
namespace = "NISTSchema-SV-IV-list-anyURI-length-2-NS"
value: List[str] = field(
default_factory=list,
metadata={
"length": 6,
"tokens": True,
}
)
| true | true |
f729fa6181d9109b928cc1ef1836cc6217b4d5fe | 8,853 | py | Python | commands/settings.py | FunTa3y/sfuakefzu1 | 63cec021bc8e1b1321568c711388095837b81ec1 | [
"Apache-2.0"
] | 1 | 2022-03-06T05:40:59.000Z | 2022-03-06T05:40:59.000Z | commands/settings.py | FunTa3y/sfuakefzu1 | 63cec021bc8e1b1321568c711388095837b81ec1 | [
"Apache-2.0"
] | null | null | null | commands/settings.py | FunTa3y/sfuakefzu1 | 63cec021bc8e1b1321568c711388095837b81ec1 | [
"Apache-2.0"
] | null | null | null | """
Здесь собраны все команды настроек
"""
import json
from vkbottle.user import Blueprint, Message
from utils.edit_msg import edit_msg
from utils.emojis import ENABLED, DISABLED, ERROR
from filters import ForEveryoneRule
bp = Blueprint("Settings command")
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>для всех <command>")
async def for_everyone_handler(message: Message, command):
"""
Команда для изменения доступности других команд для других людей
"""
with open("commands_for_everyone.json", "r", encoding="utf-8") as file:
content = json.load(file)
if command == "default":
with open("commands_for_everyone.json", "w", encoding="utf-8") as file:
content = {
"advancements": True,
"blank": True,
"bomb": True,
"code": False,
"demotivator": True,
"info": True,
"interactive_commands": True,
"ping": True,
"random_case": True,
"settings": False,
"show_config": False,
}
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Настройки для всех вернуты к значению по умолчанию",
)
elif command == "none":
with open("commands_for_everyone.json", "w", encoding="utf-8") as file:
for allowed_command in content:
content[allowed_command] = False
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api, message, f"{DISABLED} | Все команды для всех выключены"
)
elif command not in content:
await edit_msg(bp.api, message, f"{ERROR} | Такой команды нет ")
else:
if content[command]:
content[command] = False
with open(
"commands_for_everyone.json", "w", encoding="utf-8"
) as file:
content[command] = False
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api, message, f"{DISABLED} | Команда {command} отключена "
)
else:
content[command] = True
with open(
"commands_for_everyone.json", "w", encoding="utf-8"
) as file:
content[command] = True
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"Команда {command} включена " + ENABLED,
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>для всех")
async def show_for_everyone_handler(message: Message):
"""
Команда для проверки доступности команд для других людей
"""
with open("commands_for_everyone.json", "r", encoding="utf-8") as file:
content = json.load(file)
text = "Команды для всех:\n"
for command in content:
if content[command]:
text += f"{command} | {ENABLED}\n"
else:
text += f"{command} | {DISABLED}\n"
await edit_msg(bp.api, message, text)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>время бомбы <time>")
async def set_bomb_time_handler(message: Message, time):
"""
Команда для настройки времени бомбы (!бомба)
"""
try:
time = int(time)
except ValueError:
await edit_msg(
bp.api,
message,
"Время бомбы - не число! " + ERROR,
)
return
if time < 1:
await edit_msg(
bp.api,
message,
"Время бомбы не может быть меньше 1! " + ERROR,
)
else:
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
with open("config.json", "w", encoding="utf-8") as file:
content["bomb_time"] = int(message.text.split()[2])
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Время бомбы изменено на "
f"{content['bomb_time']} секунд ",
)
@bp.on.message(
ForEveryoneRule("settings"), text="<prefix>время удаления <time>"
)
async def set_delete_time_handler(message: Message, time):
"""
Команда для настройки времени удаления всех выполненных команд
"""
try:
time = int(time)
except ValueError:
await edit_msg(
bp.api,
message,
"Время удаления - не число! " + ERROR,
)
return
if time < 0:
await edit_msg(
bp.api,
message,
"Время удаления не может быть меньше 0! " + ERROR,
)
else:
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
with open("config.json", "w", encoding="utf-8") as file:
content["delete_after"] = int(message.text.split()[2])
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Время удаления изменено на "
f"{content['delete_after']} секунд",
)
@bp.on.message(
ForEveryoneRule("settings"), text="<prefix>префикс <prefix_new>"
)
async def set_prefix_handler(message: Message, prefix_new):
"""
Команда для изменения префикса бота
"""
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
with open("config.json", "w", encoding="utf-8") as file:
content["prefix"] = prefix_new
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f'{ENABLED} | Ваш префикс изменился на "{content["prefix"]}"!',
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>инфо лс")
async def info_in_dm_handler(message: Message):
"""
Команда для изменения отправки информации о людях (!инфо)
"""
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
if content["send_info_in_dm"]:
content["send_info_in_dm"] = False
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
"👥 | Теперь информация будет присылаться в чат",
)
else:
content["send_info_in_dm"] = True
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
"👤 | Теперь информация будет присылаться в лс",
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>ред")
async def edit_or_del_handler(message: Message):
"""
Команда для выбора - редактировать, или удалять команды
"""
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
if content["edit_or_send"] == "edit":
content["edit_or_send"] = "send"
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{DISABLED} | Теперь сообщения будут отправляться, а не "
"редактироваться",
)
else:
content["edit_or_send"] = "edit"
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Теперь сообщения будут редактироваться, а не "
"отправляться",
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>debug")
async def debug_mode_handler(message: Message):
"""
Команда для включения и выключения режима debug
"""
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
if content["debug"]:
content["debug"] = False
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(bp.api, message, f"{DISABLED} | Debug-режим выключен")
else:
content["debug"] = True
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(bp.api, message, f"{ENABLED} | Debug-режим включен")
| 32.788889 | 80 | 0.544448 | import json
from vkbottle.user import Blueprint, Message
from utils.edit_msg import edit_msg
from utils.emojis import ENABLED, DISABLED, ERROR
from filters import ForEveryoneRule
bp = Blueprint("Settings command")
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>для всех <command>")
async def for_everyone_handler(message: Message, command):
with open("commands_for_everyone.json", "r", encoding="utf-8") as file:
content = json.load(file)
if command == "default":
with open("commands_for_everyone.json", "w", encoding="utf-8") as file:
content = {
"advancements": True,
"blank": True,
"bomb": True,
"code": False,
"demotivator": True,
"info": True,
"interactive_commands": True,
"ping": True,
"random_case": True,
"settings": False,
"show_config": False,
}
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Настройки для всех вернуты к значению по умолчанию",
)
elif command == "none":
with open("commands_for_everyone.json", "w", encoding="utf-8") as file:
for allowed_command in content:
content[allowed_command] = False
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api, message, f"{DISABLED} | Все команды для всех выключены"
)
elif command not in content:
await edit_msg(bp.api, message, f"{ERROR} | Такой команды нет ")
else:
if content[command]:
content[command] = False
with open(
"commands_for_everyone.json", "w", encoding="utf-8"
) as file:
content[command] = False
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api, message, f"{DISABLED} | Команда {command} отключена "
)
else:
content[command] = True
with open(
"commands_for_everyone.json", "w", encoding="utf-8"
) as file:
content[command] = True
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"Команда {command} включена " + ENABLED,
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>для всех")
async def show_for_everyone_handler(message: Message):
with open("commands_for_everyone.json", "r", encoding="utf-8") as file:
content = json.load(file)
text = "Команды для всех:\n"
for command in content:
if content[command]:
text += f"{command} | {ENABLED}\n"
else:
text += f"{command} | {DISABLED}\n"
await edit_msg(bp.api, message, text)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>время бомбы <time>")
async def set_bomb_time_handler(message: Message, time):
try:
time = int(time)
except ValueError:
await edit_msg(
bp.api,
message,
"Время бомбы - не число! " + ERROR,
)
return
if time < 1:
await edit_msg(
bp.api,
message,
"Время бомбы не может быть меньше 1! " + ERROR,
)
else:
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
with open("config.json", "w", encoding="utf-8") as file:
content["bomb_time"] = int(message.text.split()[2])
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Время бомбы изменено на "
f"{content['bomb_time']} секунд ",
)
@bp.on.message(
ForEveryoneRule("settings"), text="<prefix>время удаления <time>"
)
async def set_delete_time_handler(message: Message, time):
try:
time = int(time)
except ValueError:
await edit_msg(
bp.api,
message,
"Время удаления - не число! " + ERROR,
)
return
if time < 0:
await edit_msg(
bp.api,
message,
"Время удаления не может быть меньше 0! " + ERROR,
)
else:
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
with open("config.json", "w", encoding="utf-8") as file:
content["delete_after"] = int(message.text.split()[2])
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Время удаления изменено на "
f"{content['delete_after']} секунд",
)
@bp.on.message(
ForEveryoneRule("settings"), text="<prefix>префикс <prefix_new>"
)
async def set_prefix_handler(message: Message, prefix_new):
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
with open("config.json", "w", encoding="utf-8") as file:
content["prefix"] = prefix_new
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f'{ENABLED} | Ваш префикс изменился на "{content["prefix"]}"!',
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>инфо лс")
async def info_in_dm_handler(message: Message):
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
if content["send_info_in_dm"]:
content["send_info_in_dm"] = False
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
"👥 | Теперь информация будет присылаться в чат",
)
else:
content["send_info_in_dm"] = True
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
"👤 | Теперь информация будет присылаться в лс",
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>ред")
async def edit_or_del_handler(message: Message):
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
if content["edit_or_send"] == "edit":
content["edit_or_send"] = "send"
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{DISABLED} | Теперь сообщения будут отправляться, а не "
"редактироваться",
)
else:
content["edit_or_send"] = "edit"
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(
bp.api,
message,
f"{ENABLED} | Теперь сообщения будут редактироваться, а не "
"отправляться",
)
@bp.on.message(ForEveryoneRule("settings"), text="<prefix>debug")
async def debug_mode_handler(message: Message):
with open("config.json", "r", encoding="utf-8") as file:
content = json.load(file)
if content["debug"]:
content["debug"] = False
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(bp.api, message, f"{DISABLED} | Debug-режим выключен")
else:
content["debug"] = True
with open("config.json", "w", encoding="utf-8") as file:
file.write(json.dumps(content, indent=4))
await edit_msg(bp.api, message, f"{ENABLED} | Debug-режим включен")
| true | true |
f729fb1ebee6b643883c68219d68f5f7837e9319 | 1,636 | py | Python | api_client/python/grr_api_client/types.py | isabella232/grr | db43c7df6eccd6696a5ad3ba8a338088b289d8b1 | [
"Apache-2.0"
] | null | null | null | api_client/python/grr_api_client/types.py | isabella232/grr | db43c7df6eccd6696a5ad3ba8a338088b289d8b1 | [
"Apache-2.0"
] | 1 | 2021-02-23T10:13:00.000Z | 2021-02-23T10:13:00.000Z | api_client/python/grr_api_client/types.py | isabella232/grr | db43c7df6eccd6696a5ad3ba8a338088b289d8b1 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
"""Types-related part of GRR API client library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from typing import Any
from grr_api_client import errors
from grr_api_client import utils
from grr_response_proto import flows_pb2
class UnknownFlowName(errors.Error):
pass
class Types(object):
"""Object that helps users to deal with GRR type system."""
def __init__(self, context=None):
super(Types, self).__init__()
if not context:
raise ValueError("context can't be empty")
self._context = context
self._flow_descriptors = None
def CreateFlowRunnerArgs(self):
"""Creates flow runner args object."""
return flows_pb2.FlowRunnerArgs()
def CreateHuntRunnerArgs(self):
"""Creates hunt runner args object."""
return flows_pb2.HuntRunnerArgs()
# TODO: Delete this method as it is not really type-safe.
def CreateFlowArgs(self, flow_name=None) -> Any:
"""Creates flow arguments object for a flow with a given name."""
if not self._flow_descriptors:
self._flow_descriptors = {}
result = self._context.SendRequest("ListFlowDescriptors", None)
for item in result.items:
self._flow_descriptors[item.name] = item
try:
flow_descriptor = self._flow_descriptors[flow_name]
except KeyError:
raise UnknownFlowName(flow_name)
return utils.CopyProto(utils.UnpackAny(flow_descriptor.default_args))
def UnpackAny(self, proto_any):
"""Resolves the type and unpacks the given protobuf Any object."""
return utils.UnpackAny(proto_any)
| 27.728814 | 73 | 0.732885 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from typing import Any
from grr_api_client import errors
from grr_api_client import utils
from grr_response_proto import flows_pb2
class UnknownFlowName(errors.Error):
pass
class Types(object):
def __init__(self, context=None):
super(Types, self).__init__()
if not context:
raise ValueError("context can't be empty")
self._context = context
self._flow_descriptors = None
def CreateFlowRunnerArgs(self):
return flows_pb2.FlowRunnerArgs()
def CreateHuntRunnerArgs(self):
return flows_pb2.HuntRunnerArgs()
# TODO: Delete this method as it is not really type-safe.
def CreateFlowArgs(self, flow_name=None) -> Any:
if not self._flow_descriptors:
self._flow_descriptors = {}
result = self._context.SendRequest("ListFlowDescriptors", None)
for item in result.items:
self._flow_descriptors[item.name] = item
try:
flow_descriptor = self._flow_descriptors[flow_name]
except KeyError:
raise UnknownFlowName(flow_name)
return utils.CopyProto(utils.UnpackAny(flow_descriptor.default_args))
def UnpackAny(self, proto_any):
return utils.UnpackAny(proto_any)
| true | true |
f729fb524e45739cedf45c1e9fd71ddbe6b08b2b | 15,311 | py | Python | configs/example/arm/devices.py | zinob15/gem5 | fb2946e314ea9e63c7696ee8023150ed13956582 | [
"BSD-3-Clause"
] | 19 | 2018-07-20T15:08:50.000Z | 2022-03-26T16:15:59.000Z | configs/example/arm/devices.py | zinob15/gem5 | fb2946e314ea9e63c7696ee8023150ed13956582 | [
"BSD-3-Clause"
] | 148 | 2018-07-20T00:58:36.000Z | 2021-11-16T01:52:33.000Z | configs/example/arm/devices.py | zinob15/gem5 | fb2946e314ea9e63c7696ee8023150ed13956582 | [
"BSD-3-Clause"
] | 10 | 2019-01-10T03:01:30.000Z | 2022-01-21T18:36:18.000Z | # Copyright (c) 2016-2017, 2019, 2021 Arm Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# System components used by the bigLITTLE.py configuration script
import m5
from m5.objects import *
m5.util.addToPath('../../')
from common.Caches import *
from common import ObjectList
have_kvm = "ArmV8KvmCPU" in ObjectList.cpu_list.get_names()
have_fastmodel = "FastModelCortexA76" in ObjectList.cpu_list.get_names()
class L1I(L1_ICache):
tag_latency = 1
data_latency = 1
response_latency = 1
mshrs = 4
tgts_per_mshr = 8
size = '48kB'
assoc = 3
class L1D(L1_DCache):
tag_latency = 2
data_latency = 2
response_latency = 1
mshrs = 16
tgts_per_mshr = 16
size = '32kB'
assoc = 2
write_buffers = 16
class WalkCache(PageTableWalkerCache):
tag_latency = 4
data_latency = 4
response_latency = 4
mshrs = 6
tgts_per_mshr = 8
size = '1kB'
assoc = 8
write_buffers = 16
class L2(L2Cache):
tag_latency = 12
data_latency = 12
response_latency = 5
mshrs = 32
tgts_per_mshr = 8
size = '1MB'
assoc = 16
write_buffers = 8
clusivity='mostly_excl'
class L3(Cache):
size = '16MB'
assoc = 16
tag_latency = 20
data_latency = 20
response_latency = 20
mshrs = 20
tgts_per_mshr = 12
clusivity='mostly_excl'
class MemBus(SystemXBar):
badaddr_responder = BadAddr(warn_access="warn")
default = Self.badaddr_responder.pio
class CpuCluster(SubSystem):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage,
cpu_type, l1i_type, l1d_type, wcache_type, l2_type):
super(CpuCluster, self).__init__()
self._cpu_type = cpu_type
self._l1i_type = l1i_type
self._l1d_type = l1d_type
self._wcache_type = wcache_type
self._l2_type = l2_type
assert num_cpus > 0
self.voltage_domain = VoltageDomain(voltage=cpu_voltage)
self.clk_domain = SrcClockDomain(clock=cpu_clock,
voltage_domain=self.voltage_domain)
self.cpus = [ self._cpu_type(cpu_id=system.numCpus() + idx,
clk_domain=self.clk_domain)
for idx in range(num_cpus) ]
for cpu in self.cpus:
cpu.createThreads()
cpu.createInterruptController()
cpu.socket_id = system.numCpuClusters()
system.addCpuCluster(self, num_cpus)
def requireCaches(self):
return self._cpu_type.require_caches()
def memoryMode(self):
return self._cpu_type.memory_mode()
def addL1(self):
for cpu in self.cpus:
l1i = None if self._l1i_type is None else self._l1i_type()
l1d = None if self._l1d_type is None else self._l1d_type()
iwc = None if self._wcache_type is None else self._wcache_type()
dwc = None if self._wcache_type is None else self._wcache_type()
cpu.addPrivateSplitL1Caches(l1i, l1d, iwc, dwc)
def addL2(self, clk_domain):
if self._l2_type is None:
return
self.toL2Bus = L2XBar(width=64, clk_domain=clk_domain)
self.l2 = self._l2_type()
for cpu in self.cpus:
cpu.connectAllPorts(self.toL2Bus)
self.toL2Bus.mem_side_ports = self.l2.cpu_side
def addPMUs(self, ints, events=[]):
"""
Instantiates 1 ArmPMU per PE. The method is accepting a list of
interrupt numbers (ints) used by the PMU and a list of events to
register in it.
:param ints: List of interrupt numbers. The code will iterate over
the cpu list in order and will assign to every cpu in the cluster
a PMU with the matching interrupt.
:type ints: List[int]
:param events: Additional events to be measured by the PMUs
:type events: List[Union[ProbeEvent, SoftwareIncrement]]
"""
assert len(ints) == len(self.cpus)
for cpu, pint in zip(self.cpus, ints):
int_cls = ArmPPI if pint < 32 else ArmSPI
for isa in cpu.isa:
isa.pmu = ArmPMU(interrupt=int_cls(num=pint))
isa.pmu.addArchEvents(cpu=cpu,
itb=cpu.mmu.itb, dtb=cpu.mmu.dtb,
icache=getattr(cpu, 'icache', None),
dcache=getattr(cpu, 'dcache', None),
l2cache=getattr(self, 'l2', None))
for ev in events:
isa.pmu.addEvent(ev)
def connectMemSide(self, bus):
try:
self.l2.mem_side = bus.cpu_side_ports
except AttributeError:
for cpu in self.cpus:
cpu.connectAllPorts(bus)
class AtomicCluster(CpuCluster):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage="1.0V"):
cpu_config = [ ObjectList.cpu_list.get("AtomicSimpleCPU"), None,
None, None, None ]
super(AtomicCluster, self).__init__(system, num_cpus, cpu_clock,
cpu_voltage, *cpu_config)
def addL1(self):
pass
class KvmCluster(CpuCluster):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage="1.0V"):
cpu_config = [ ObjectList.cpu_list.get("ArmV8KvmCPU"), None, None,
None, None ]
super(KvmCluster, self).__init__(system, num_cpus, cpu_clock,
cpu_voltage, *cpu_config)
def addL1(self):
pass
class FastmodelCluster(SubSystem):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage="1.0V"):
super(FastmodelCluster, self).__init__()
# Setup GIC
gic = system.realview.gic
gic.sc_gic.cpu_affinities = ','.join(
[ '0.0.%d.0' % i for i in range(num_cpus) ])
# Parse the base address of redistributor.
redist_base = gic.get_redist_bases()[0]
redist_frame_size = 0x40000 if gic.sc_gic.has_gicv4_1 else 0x20000
gic.sc_gic.reg_base_per_redistributor = ','.join([
'0.0.%d.0=%#x' % (i, redist_base + redist_frame_size * i)
for i in range(num_cpus)
])
gic_a2t = AmbaToTlmBridge64(amba=gic.amba_m)
gic_t2g = TlmToGem5Bridge64(tlm=gic_a2t.tlm,
gem5=system.iobus.cpu_side_ports)
gic_g2t = Gem5ToTlmBridge64(gem5=system.membus.mem_side_ports)
gic_g2t.addr_ranges = gic.get_addr_ranges()
gic_t2a = AmbaFromTlmBridge64(tlm=gic_g2t.tlm)
gic.amba_s = gic_t2a.amba
system.gic_hub = SubSystem()
system.gic_hub.gic_a2t = gic_a2t
system.gic_hub.gic_t2g = gic_t2g
system.gic_hub.gic_g2t = gic_g2t
system.gic_hub.gic_t2a = gic_t2a
self.voltage_domain = VoltageDomain(voltage=cpu_voltage)
self.clk_domain = SrcClockDomain(clock=cpu_clock,
voltage_domain=self.voltage_domain)
# Setup CPU
assert num_cpus <= 4
CpuClasses = [FastModelCortexA76x1, FastModelCortexA76x2,
FastModelCortexA76x3, FastModelCortexA76x4]
CpuClass = CpuClasses[num_cpus - 1]
cpu = CpuClass(GICDISABLE=False)
for core in cpu.cores:
core.semihosting_enable = False
core.RVBARADDR = 0x10
core.redistributor = gic.redistributor
core.createThreads()
core.createInterruptController()
self.cpus = [ cpu ]
a2t = AmbaToTlmBridge64(amba=cpu.amba)
t2g = TlmToGem5Bridge64(tlm=a2t.tlm, gem5=system.membus.cpu_side_ports)
system.gic_hub.a2t = a2t
system.gic_hub.t2g = t2g
system.addCpuCluster(self, num_cpus)
def requireCaches(self):
return False
def memoryMode(self):
return 'atomic_noncaching'
def addL1(self):
pass
def addL2(self, clk_domain):
pass
def connectMemSide(self, bus):
pass
class BaseSimpleSystem(ArmSystem):
cache_line_size = 64
def __init__(self, mem_size, platform, **kwargs):
super(BaseSimpleSystem, self).__init__(**kwargs)
self.voltage_domain = VoltageDomain(voltage="1.0V")
self.clk_domain = SrcClockDomain(
clock="1GHz",
voltage_domain=Parent.voltage_domain)
if platform is None:
self.realview = VExpress_GEM5_V1()
else:
self.realview = platform
if hasattr(self.realview.gic, 'cpu_addr'):
self.gic_cpu_addr = self.realview.gic.cpu_addr
self.terminal = Terminal()
self.vncserver = VncServer()
self.iobus = IOXBar()
# Device DMA -> MEM
self.mem_ranges = self.getMemRanges(int(Addr(mem_size)))
self._clusters = []
self._num_cpus = 0
def getMemRanges(self, mem_size):
"""
Define system memory ranges. This depends on the physical
memory map provided by the realview platform and by the memory
size provided by the user (mem_size argument).
The method is iterating over all platform ranges until they cover
the entire user's memory requirements.
"""
mem_ranges = []
for mem_range in self.realview._mem_regions:
size_in_range = min(mem_size, mem_range.size())
mem_ranges.append(
AddrRange(start=mem_range.start, size=size_in_range))
mem_size -= size_in_range
if mem_size == 0:
return mem_ranges
raise ValueError("memory size too big for platform capabilities")
def numCpuClusters(self):
return len(self._clusters)
def addCpuCluster(self, cpu_cluster, num_cpus):
assert cpu_cluster not in self._clusters
assert num_cpus > 0
self._clusters.append(cpu_cluster)
self._num_cpus += num_cpus
def numCpus(self):
return self._num_cpus
def addCaches(self, need_caches, last_cache_level):
if not need_caches:
# connect each cluster to the memory hierarchy
for cluster in self._clusters:
cluster.connectMemSide(self.membus)
return
cluster_mem_bus = self.membus
assert last_cache_level >= 1 and last_cache_level <= 3
for cluster in self._clusters:
cluster.addL1()
if last_cache_level > 1:
for cluster in self._clusters:
cluster.addL2(cluster.clk_domain)
if last_cache_level > 2:
max_clock_cluster = max(self._clusters,
key=lambda c: c.clk_domain.clock[0])
self.l3 = L3(clk_domain=max_clock_cluster.clk_domain)
self.toL3Bus = L2XBar(width=64)
self.toL3Bus.mem_side_ports = self.l3.cpu_side
self.l3.mem_side = self.membus.cpu_side_ports
cluster_mem_bus = self.toL3Bus
# connect each cluster to the memory hierarchy
for cluster in self._clusters:
cluster.connectMemSide(cluster_mem_bus)
class SimpleSystem(BaseSimpleSystem):
"""
Meant to be used with the classic memory model
"""
def __init__(self, caches, mem_size, platform=None, **kwargs):
super(SimpleSystem, self).__init__(mem_size, platform, **kwargs)
self.membus = MemBus()
# CPUs->PIO
self.iobridge = Bridge(delay='50ns')
self._caches = caches
if self._caches:
self.iocache = IOCache(addr_ranges=self.mem_ranges)
else:
self.dmabridge = Bridge(delay='50ns',
ranges=self.mem_ranges)
def connect(self):
self.iobridge.mem_side_port = self.iobus.cpu_side_ports
self.iobridge.cpu_side_port = self.membus.mem_side_ports
if self._caches:
self.iocache.mem_side = self.membus.cpu_side_ports
self.iocache.cpu_side = self.iobus.mem_side_ports
else:
self.dmabridge.mem_side_port = self.membus.cpu_side_ports
self.dmabridge.cpu_side_port = self.iobus.mem_side_ports
if hasattr(self.realview.gic, 'cpu_addr'):
self.gic_cpu_addr = self.realview.gic.cpu_addr
self.realview.attachOnChipIO(self.membus, self.iobridge)
self.realview.attachIO(self.iobus)
self.system_port = self.membus.cpu_side_ports
def attach_pci(self, dev):
self.realview.attachPciDevice(dev, self.iobus)
class ArmRubySystem(BaseSimpleSystem):
"""
Meant to be used with ruby
"""
def __init__(self, mem_size, platform=None, **kwargs):
super(ArmRubySystem, self).__init__(mem_size, platform, **kwargs)
self._dma_ports = []
self._mem_ports = []
def connect(self):
self.realview.attachOnChipIO(self.iobus,
dma_ports=self._dma_ports, mem_ports=self._mem_ports)
self.realview.attachIO(self.iobus, dma_ports=self._dma_ports)
for cluster in self._clusters:
for i, cpu in enumerate(cluster.cpus):
self.ruby._cpu_ports[i].connectCpuPorts(cpu)
def attach_pci(self, dev):
self.realview.attachPciDevice(dev, self.iobus,
dma_ports=self._dma_ports)
| 35.689977 | 79 | 0.640585 |
import m5
from m5.objects import *
m5.util.addToPath('../../')
from common.Caches import *
from common import ObjectList
have_kvm = "ArmV8KvmCPU" in ObjectList.cpu_list.get_names()
have_fastmodel = "FastModelCortexA76" in ObjectList.cpu_list.get_names()
class L1I(L1_ICache):
tag_latency = 1
data_latency = 1
response_latency = 1
mshrs = 4
tgts_per_mshr = 8
size = '48kB'
assoc = 3
class L1D(L1_DCache):
tag_latency = 2
data_latency = 2
response_latency = 1
mshrs = 16
tgts_per_mshr = 16
size = '32kB'
assoc = 2
write_buffers = 16
class WalkCache(PageTableWalkerCache):
tag_latency = 4
data_latency = 4
response_latency = 4
mshrs = 6
tgts_per_mshr = 8
size = '1kB'
assoc = 8
write_buffers = 16
class L2(L2Cache):
tag_latency = 12
data_latency = 12
response_latency = 5
mshrs = 32
tgts_per_mshr = 8
size = '1MB'
assoc = 16
write_buffers = 8
clusivity='mostly_excl'
class L3(Cache):
size = '16MB'
assoc = 16
tag_latency = 20
data_latency = 20
response_latency = 20
mshrs = 20
tgts_per_mshr = 12
clusivity='mostly_excl'
class MemBus(SystemXBar):
badaddr_responder = BadAddr(warn_access="warn")
default = Self.badaddr_responder.pio
class CpuCluster(SubSystem):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage,
cpu_type, l1i_type, l1d_type, wcache_type, l2_type):
super(CpuCluster, self).__init__()
self._cpu_type = cpu_type
self._l1i_type = l1i_type
self._l1d_type = l1d_type
self._wcache_type = wcache_type
self._l2_type = l2_type
assert num_cpus > 0
self.voltage_domain = VoltageDomain(voltage=cpu_voltage)
self.clk_domain = SrcClockDomain(clock=cpu_clock,
voltage_domain=self.voltage_domain)
self.cpus = [ self._cpu_type(cpu_id=system.numCpus() + idx,
clk_domain=self.clk_domain)
for idx in range(num_cpus) ]
for cpu in self.cpus:
cpu.createThreads()
cpu.createInterruptController()
cpu.socket_id = system.numCpuClusters()
system.addCpuCluster(self, num_cpus)
def requireCaches(self):
return self._cpu_type.require_caches()
def memoryMode(self):
return self._cpu_type.memory_mode()
def addL1(self):
for cpu in self.cpus:
l1i = None if self._l1i_type is None else self._l1i_type()
l1d = None if self._l1d_type is None else self._l1d_type()
iwc = None if self._wcache_type is None else self._wcache_type()
dwc = None if self._wcache_type is None else self._wcache_type()
cpu.addPrivateSplitL1Caches(l1i, l1d, iwc, dwc)
def addL2(self, clk_domain):
if self._l2_type is None:
return
self.toL2Bus = L2XBar(width=64, clk_domain=clk_domain)
self.l2 = self._l2_type()
for cpu in self.cpus:
cpu.connectAllPorts(self.toL2Bus)
self.toL2Bus.mem_side_ports = self.l2.cpu_side
def addPMUs(self, ints, events=[]):
assert len(ints) == len(self.cpus)
for cpu, pint in zip(self.cpus, ints):
int_cls = ArmPPI if pint < 32 else ArmSPI
for isa in cpu.isa:
isa.pmu = ArmPMU(interrupt=int_cls(num=pint))
isa.pmu.addArchEvents(cpu=cpu,
itb=cpu.mmu.itb, dtb=cpu.mmu.dtb,
icache=getattr(cpu, 'icache', None),
dcache=getattr(cpu, 'dcache', None),
l2cache=getattr(self, 'l2', None))
for ev in events:
isa.pmu.addEvent(ev)
def connectMemSide(self, bus):
try:
self.l2.mem_side = bus.cpu_side_ports
except AttributeError:
for cpu in self.cpus:
cpu.connectAllPorts(bus)
class AtomicCluster(CpuCluster):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage="1.0V"):
cpu_config = [ ObjectList.cpu_list.get("AtomicSimpleCPU"), None,
None, None, None ]
super(AtomicCluster, self).__init__(system, num_cpus, cpu_clock,
cpu_voltage, *cpu_config)
def addL1(self):
pass
class KvmCluster(CpuCluster):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage="1.0V"):
cpu_config = [ ObjectList.cpu_list.get("ArmV8KvmCPU"), None, None,
None, None ]
super(KvmCluster, self).__init__(system, num_cpus, cpu_clock,
cpu_voltage, *cpu_config)
def addL1(self):
pass
class FastmodelCluster(SubSystem):
def __init__(self, system, num_cpus, cpu_clock, cpu_voltage="1.0V"):
super(FastmodelCluster, self).__init__()
gic = system.realview.gic
gic.sc_gic.cpu_affinities = ','.join(
[ '0.0.%d.0' % i for i in range(num_cpus) ])
redist_base = gic.get_redist_bases()[0]
redist_frame_size = 0x40000 if gic.sc_gic.has_gicv4_1 else 0x20000
gic.sc_gic.reg_base_per_redistributor = ','.join([
'0.0.%d.0=%#x' % (i, redist_base + redist_frame_size * i)
for i in range(num_cpus)
])
gic_a2t = AmbaToTlmBridge64(amba=gic.amba_m)
gic_t2g = TlmToGem5Bridge64(tlm=gic_a2t.tlm,
gem5=system.iobus.cpu_side_ports)
gic_g2t = Gem5ToTlmBridge64(gem5=system.membus.mem_side_ports)
gic_g2t.addr_ranges = gic.get_addr_ranges()
gic_t2a = AmbaFromTlmBridge64(tlm=gic_g2t.tlm)
gic.amba_s = gic_t2a.amba
system.gic_hub = SubSystem()
system.gic_hub.gic_a2t = gic_a2t
system.gic_hub.gic_t2g = gic_t2g
system.gic_hub.gic_g2t = gic_g2t
system.gic_hub.gic_t2a = gic_t2a
self.voltage_domain = VoltageDomain(voltage=cpu_voltage)
self.clk_domain = SrcClockDomain(clock=cpu_clock,
voltage_domain=self.voltage_domain)
assert num_cpus <= 4
CpuClasses = [FastModelCortexA76x1, FastModelCortexA76x2,
FastModelCortexA76x3, FastModelCortexA76x4]
CpuClass = CpuClasses[num_cpus - 1]
cpu = CpuClass(GICDISABLE=False)
for core in cpu.cores:
core.semihosting_enable = False
core.RVBARADDR = 0x10
core.redistributor = gic.redistributor
core.createThreads()
core.createInterruptController()
self.cpus = [ cpu ]
a2t = AmbaToTlmBridge64(amba=cpu.amba)
t2g = TlmToGem5Bridge64(tlm=a2t.tlm, gem5=system.membus.cpu_side_ports)
system.gic_hub.a2t = a2t
system.gic_hub.t2g = t2g
system.addCpuCluster(self, num_cpus)
def requireCaches(self):
return False
def memoryMode(self):
return 'atomic_noncaching'
def addL1(self):
pass
def addL2(self, clk_domain):
pass
def connectMemSide(self, bus):
pass
class BaseSimpleSystem(ArmSystem):
cache_line_size = 64
def __init__(self, mem_size, platform, **kwargs):
super(BaseSimpleSystem, self).__init__(**kwargs)
self.voltage_domain = VoltageDomain(voltage="1.0V")
self.clk_domain = SrcClockDomain(
clock="1GHz",
voltage_domain=Parent.voltage_domain)
if platform is None:
self.realview = VExpress_GEM5_V1()
else:
self.realview = platform
if hasattr(self.realview.gic, 'cpu_addr'):
self.gic_cpu_addr = self.realview.gic.cpu_addr
self.terminal = Terminal()
self.vncserver = VncServer()
self.iobus = IOXBar()
self.mem_ranges = self.getMemRanges(int(Addr(mem_size)))
self._clusters = []
self._num_cpus = 0
def getMemRanges(self, mem_size):
mem_ranges = []
for mem_range in self.realview._mem_regions:
size_in_range = min(mem_size, mem_range.size())
mem_ranges.append(
AddrRange(start=mem_range.start, size=size_in_range))
mem_size -= size_in_range
if mem_size == 0:
return mem_ranges
raise ValueError("memory size too big for platform capabilities")
def numCpuClusters(self):
return len(self._clusters)
def addCpuCluster(self, cpu_cluster, num_cpus):
assert cpu_cluster not in self._clusters
assert num_cpus > 0
self._clusters.append(cpu_cluster)
self._num_cpus += num_cpus
def numCpus(self):
return self._num_cpus
def addCaches(self, need_caches, last_cache_level):
if not need_caches:
for cluster in self._clusters:
cluster.connectMemSide(self.membus)
return
cluster_mem_bus = self.membus
assert last_cache_level >= 1 and last_cache_level <= 3
for cluster in self._clusters:
cluster.addL1()
if last_cache_level > 1:
for cluster in self._clusters:
cluster.addL2(cluster.clk_domain)
if last_cache_level > 2:
max_clock_cluster = max(self._clusters,
key=lambda c: c.clk_domain.clock[0])
self.l3 = L3(clk_domain=max_clock_cluster.clk_domain)
self.toL3Bus = L2XBar(width=64)
self.toL3Bus.mem_side_ports = self.l3.cpu_side
self.l3.mem_side = self.membus.cpu_side_ports
cluster_mem_bus = self.toL3Bus
for cluster in self._clusters:
cluster.connectMemSide(cluster_mem_bus)
class SimpleSystem(BaseSimpleSystem):
def __init__(self, caches, mem_size, platform=None, **kwargs):
super(SimpleSystem, self).__init__(mem_size, platform, **kwargs)
self.membus = MemBus()
self.iobridge = Bridge(delay='50ns')
self._caches = caches
if self._caches:
self.iocache = IOCache(addr_ranges=self.mem_ranges)
else:
self.dmabridge = Bridge(delay='50ns',
ranges=self.mem_ranges)
def connect(self):
self.iobridge.mem_side_port = self.iobus.cpu_side_ports
self.iobridge.cpu_side_port = self.membus.mem_side_ports
if self._caches:
self.iocache.mem_side = self.membus.cpu_side_ports
self.iocache.cpu_side = self.iobus.mem_side_ports
else:
self.dmabridge.mem_side_port = self.membus.cpu_side_ports
self.dmabridge.cpu_side_port = self.iobus.mem_side_ports
if hasattr(self.realview.gic, 'cpu_addr'):
self.gic_cpu_addr = self.realview.gic.cpu_addr
self.realview.attachOnChipIO(self.membus, self.iobridge)
self.realview.attachIO(self.iobus)
self.system_port = self.membus.cpu_side_ports
def attach_pci(self, dev):
self.realview.attachPciDevice(dev, self.iobus)
class ArmRubySystem(BaseSimpleSystem):
def __init__(self, mem_size, platform=None, **kwargs):
super(ArmRubySystem, self).__init__(mem_size, platform, **kwargs)
self._dma_ports = []
self._mem_ports = []
def connect(self):
self.realview.attachOnChipIO(self.iobus,
dma_ports=self._dma_ports, mem_ports=self._mem_ports)
self.realview.attachIO(self.iobus, dma_ports=self._dma_ports)
for cluster in self._clusters:
for i, cpu in enumerate(cluster.cpus):
self.ruby._cpu_ports[i].connectCpuPorts(cpu)
def attach_pci(self, dev):
self.realview.attachPciDevice(dev, self.iobus,
dma_ports=self._dma_ports)
| true | true |
f729fc3eb1ab171fa0021b34ddb3f3124a367be7 | 3,634 | py | Python | azure-mgmt-network/azure/mgmt/network/v2015_06_15/models/network_interface_ip_configuration.py | Christina-Kang/azure-sdk-for-python | bbf982eb06aab04b8151f69f1d230b7f5fb96ebf | [
"MIT"
] | 1 | 2022-03-30T22:39:15.000Z | 2022-03-30T22:39:15.000Z | azure-mgmt-network/azure/mgmt/network/v2015_06_15/models/network_interface_ip_configuration.py | Christina-Kang/azure-sdk-for-python | bbf982eb06aab04b8151f69f1d230b7f5fb96ebf | [
"MIT"
] | 54 | 2016-03-25T17:25:01.000Z | 2018-10-22T17:27:54.000Z | azure-mgmt-network/azure/mgmt/network/v2015_06_15/models/network_interface_ip_configuration.py | Christina-Kang/azure-sdk-for-python | bbf982eb06aab04b8151f69f1d230b7f5fb96ebf | [
"MIT"
] | 2 | 2017-01-20T18:25:46.000Z | 2017-05-12T21:31:47.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .sub_resource import SubResource
class NetworkInterfaceIPConfiguration(SubResource):
"""IPConfiguration in a network interface.
:param id: Resource Identifier.
:type id: str
:param load_balancer_backend_address_pools: The reference of
LoadBalancerBackendAddressPool resource.
:type load_balancer_backend_address_pools:
list[~azure.mgmt.network.v2015_06_15.models.BackendAddressPool]
:param load_balancer_inbound_nat_rules: A list of references of
LoadBalancerInboundNatRules.
:type load_balancer_inbound_nat_rules:
list[~azure.mgmt.network.v2015_06_15.models.InboundNatRule]
:param private_ip_address:
:type private_ip_address: str
:param private_ip_allocation_method: Defines how a private IP address is
assigned. Possible values are: 'Static' and 'Dynamic'. Possible values
include: 'Static', 'Dynamic'
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2015_06_15.models.IPAllocationMethod
:param subnet:
:type subnet: ~azure.mgmt.network.v2015_06_15.models.Subnet
:param public_ip_address:
:type public_ip_address:
~azure.mgmt.network.v2015_06_15.models.PublicIPAddress
:param provisioning_state:
:type provisioning_state: str
:param name: The name of the resource that is unique within a resource
group. This name can be used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'load_balancer_backend_address_pools': {'key': 'properties.loadBalancerBackendAddressPools', 'type': '[BackendAddressPool]'},
'load_balancer_inbound_nat_rules': {'key': 'properties.loadBalancerInboundNatRules', 'type': '[InboundNatRule]'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, **kwargs):
super(NetworkInterfaceIPConfiguration, self).__init__(**kwargs)
self.load_balancer_backend_address_pools = kwargs.get('load_balancer_backend_address_pools', None)
self.load_balancer_inbound_nat_rules = kwargs.get('load_balancer_inbound_nat_rules', None)
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
| 49.108108 | 133 | 0.686021 |
from .sub_resource import SubResource
class NetworkInterfaceIPConfiguration(SubResource):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'load_balancer_backend_address_pools': {'key': 'properties.loadBalancerBackendAddressPools', 'type': '[BackendAddressPool]'},
'load_balancer_inbound_nat_rules': {'key': 'properties.loadBalancerInboundNatRules', 'type': '[InboundNatRule]'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, **kwargs):
super(NetworkInterfaceIPConfiguration, self).__init__(**kwargs)
self.load_balancer_backend_address_pools = kwargs.get('load_balancer_backend_address_pools', None)
self.load_balancer_inbound_nat_rules = kwargs.get('load_balancer_inbound_nat_rules', None)
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
| true | true |
f729fca17167c275820d551d107bd174590db42d | 6,921 | py | Python | backend/aptitude_32653/settings.py | crowdbotics-apps/aptitude-32653 | 381e5da874f4dd461c90bc9705d6bb4be7adfd0e | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/aptitude_32653/settings.py | crowdbotics-apps/aptitude-32653 | 381e5da874f4dd461c90bc9705d6bb4be7adfd0e | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/aptitude_32653/settings.py | crowdbotics-apps/aptitude-32653 | 381e5da874f4dd461c90bc9705d6bb4be7adfd0e | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | """
Django settings for aptitude_32653 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import environ
import logging
from modules.manifest import get_modules
env = environ.Env()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
LOCAL_APPS = [
'home',
'users.apps.UsersConfig',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'bootstrap4',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_extensions',
'drf_yasg',
'storages',
]
MODULES_APPS = get_modules()
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS + MODULES_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'aptitude_32653.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web_build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'aptitude_32653.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/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/2.2/howto/static-files/
STATIC_URL = '/static/'
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY and
AWS_STORAGE_BUCKET_NAME and
AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.")
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| 29.576923 | 112 | 0.730675 |
import os
import environ
import logging
from modules.manifest import get_modules
env = environ.Env()
DEBUG = env.bool("DEBUG", default=False)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
LOCAL_APPS = [
'home',
'users.apps.UsersConfig',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'bootstrap4',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_extensions',
'drf_yasg',
'storages',
]
MODULES_APPS = get_modules()
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS + MODULES_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'aptitude_32653.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web_build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'aptitude_32653.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/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/2.2/howto/static-files/
STATIC_URL = '/static/'
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY and
AWS_STORAGE_BUCKET_NAME and
AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.")
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| true | true |
f729fd1d7a671f40e92ec81c3f4592cf5c2c7299 | 2,125 | py | Python | code-samples/canonical-samples/python/long-running-operation/speech_transcribe_async.py | tswast/gapic-docs-samples | 16976b148fb6eb53a8a685d475dcdb713ceb9e60 | [
"Apache-2.0"
] | null | null | null | code-samples/canonical-samples/python/long-running-operation/speech_transcribe_async.py | tswast/gapic-docs-samples | 16976b148fb6eb53a8a685d475dcdb713ceb9e60 | [
"Apache-2.0"
] | null | null | null | code-samples/canonical-samples/python/long-running-operation/speech_transcribe_async.py | tswast/gapic-docs-samples | 16976b148fb6eb53a8a685d475dcdb713ceb9e60 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START speech_transcribe_async_gcs]
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
def long_running_recognize_gcs(
gcs_uri='gs://cloud-sample-data/speech/brooklyn.raw',
language_code='en-US'
):
"""Asynchronously transcribes the audio file specified by the gcs_uri.
Args:
gcs_uri: Path to audio file in Google Cloud Storage
e.g. gs://BUCKET/FILE
language_code: The language of the supplied audio as
a BCP-47 language tag, e.g. 'en-US'
"""
client = speech.SpeechClient()
audio = types.RecognitionAudio(uri=gcs_uri)
config = types.RecognitionConfig(
# This is a comment describing one of the fields being set
encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
sample_rate_hertz=16000,
language_code=language_code)
operation = client.long_running_recognize(config, audio)
print('Waiting for operation to complete...')
response = operation.result(timeout=90)
# Each result is for a consecutive portion of the audio. Iterate through
# them to get the transcripts for the entire audio file.
for result in response.results:
# The first alternative is the most likely one for this portion.
print(u'Transcript: {}'.format(result.alternatives[0].transcript))
print('Confidence: {}'.format(result.alternatives[0].confidence))
# [END speech_transcribe_async_gcs]
# import argparse
| 37.280702 | 76 | 0.720941 |
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
def long_running_recognize_gcs(
gcs_uri='gs://cloud-sample-data/speech/brooklyn.raw',
language_code='en-US'
):
client = speech.SpeechClient()
audio = types.RecognitionAudio(uri=gcs_uri)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
sample_rate_hertz=16000,
language_code=language_code)
operation = client.long_running_recognize(config, audio)
print('Waiting for operation to complete...')
response = operation.result(timeout=90)
for result in response.results:
print(u'Transcript: {}'.format(result.alternatives[0].transcript))
print('Confidence: {}'.format(result.alternatives[0].confidence))
| true | true |
f729fe054a7c675d4141710bc2b5a4e5decab527 | 1,812 | py | Python | folders_arranger/folders_arranger.py | devded/Automation-scripts | e3b7e623d5fa20496f98a61f896d54ed8a30b8c4 | [
"MIT"
] | null | null | null | folders_arranger/folders_arranger.py | devded/Automation-scripts | e3b7e623d5fa20496f98a61f896d54ed8a30b8c4 | [
"MIT"
] | null | null | null | folders_arranger/folders_arranger.py | devded/Automation-scripts | e3b7e623d5fa20496f98a61f896d54ed8a30b8c4 | [
"MIT"
] | null | null | null | import shutil
import os
import string
class ArrangeScripts:
def __init__(self, path_to_folder):
self.folders = ['a_e', 'f_j', 'k_o', 'p_t', 'u_z']
self.folder_mapping = {}
for alphabet in list(string.ascii_lowercase):
if alphabet in list('abcde'):
self.folder_mapping[alphabet] = 'a_e'
elif alphabet in list('fghij'):
self.folder_mapping[alphabet] = 'f_j'
elif alphabet in list('klmno'):
self.folder_mapping[alphabet] = 'k_o'
elif alphabet in list('pqrst'):
self.folder_mapping[alphabet] = 'p_t'
elif alphabet in list('uvwxyz'):
self.folder_mapping[alphabet] = 'u_z'
self.path_to_folder = path_to_folder
def create_folders(self):
for folder in self.folders:
new_folder = os.path.join(self.path_to_folder, folder)
if not os.path.isdir(new_folder):
os.mkdir(new_folder)
def organize_folder(self):
self.create_folders()
for a_folder in os.listdir(self.path_to_folder):
if a_folder in self.folders:
continue
source_path = os.path.join(self.path_to_folder, a_folder)
first_char = a_folder.lower()[0]
destination_path = os.path.join(self.path_to_folder, self.folder_mapping[first_char])
shutil.move(source_path, destination_path, copy_function=shutil.copytree)
def process_folders():
# get folder path
user_input = input('Enter path to folder which needs to be organized: ')
arrange = ArrangeScripts(user_input)
arrange.organize_folder()
if __name__ == "__main__":
try:
process_folders()
except Exception as e:
print(e.__class__, "occurred.")
| 32.945455 | 97 | 0.616446 | import shutil
import os
import string
class ArrangeScripts:
def __init__(self, path_to_folder):
self.folders = ['a_e', 'f_j', 'k_o', 'p_t', 'u_z']
self.folder_mapping = {}
for alphabet in list(string.ascii_lowercase):
if alphabet in list('abcde'):
self.folder_mapping[alphabet] = 'a_e'
elif alphabet in list('fghij'):
self.folder_mapping[alphabet] = 'f_j'
elif alphabet in list('klmno'):
self.folder_mapping[alphabet] = 'k_o'
elif alphabet in list('pqrst'):
self.folder_mapping[alphabet] = 'p_t'
elif alphabet in list('uvwxyz'):
self.folder_mapping[alphabet] = 'u_z'
self.path_to_folder = path_to_folder
def create_folders(self):
for folder in self.folders:
new_folder = os.path.join(self.path_to_folder, folder)
if not os.path.isdir(new_folder):
os.mkdir(new_folder)
def organize_folder(self):
self.create_folders()
for a_folder in os.listdir(self.path_to_folder):
if a_folder in self.folders:
continue
source_path = os.path.join(self.path_to_folder, a_folder)
first_char = a_folder.lower()[0]
destination_path = os.path.join(self.path_to_folder, self.folder_mapping[first_char])
shutil.move(source_path, destination_path, copy_function=shutil.copytree)
def process_folders():
user_input = input('Enter path to folder which needs to be organized: ')
arrange = ArrangeScripts(user_input)
arrange.organize_folder()
if __name__ == "__main__":
try:
process_folders()
except Exception as e:
print(e.__class__, "occurred.")
| true | true |
f729fedf70edfac479931ac38e0c12163c8ee92f | 25,493 | py | Python | nltk/corpus/reader/childes.py | PhanatosZou/nltk | 750e488569b6f80c72ae6ca74eff90eae55e6c4e | [
"Apache-2.0"
] | null | null | null | nltk/corpus/reader/childes.py | PhanatosZou/nltk | 750e488569b6f80c72ae6ca74eff90eae55e6c4e | [
"Apache-2.0"
] | null | null | null | nltk/corpus/reader/childes.py | PhanatosZou/nltk | 750e488569b6f80c72ae6ca74eff90eae55e6c4e | [
"Apache-2.0"
] | null | null | null | # CHILDES XML Corpus Reader
# Copyright (C) 2001-2019 NLTK Project
# Author: Tomonori Nagano <tnagano@gc.cuny.edu>
# Alexis Dimitriadis <A.Dimitriadis@uu.nl>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Corpus reader for the XML version of the CHILDES corpus.
"""
__docformat__ = "epytext en"
import re
from collections import defaultdict
from nltk.util import flatten, LazyMap, LazyConcatenation
from nltk.corpus.reader.util import concat
from nltk.corpus.reader.xmldocs import XMLCorpusReader, ElementTree
# to resolve the namespace issue
NS = "http://www.talkbank.org/ns/talkbank"
class CHILDESCorpusReader(XMLCorpusReader):
"""
Corpus reader for the XML version of the CHILDES corpus.
The CHILDES corpus is available at ``https://childes.talkbank.org/``. The XML
version of CHILDES is located at ``https://childes.talkbank.org/data-xml/``.
Copy the needed parts of the CHILDES XML corpus into the NLTK data directory
(``nltk_data/corpora/CHILDES/``).
For access to the file text use the usual nltk functions,
``words()``, ``sents()``, ``tagged_words()`` and ``tagged_sents()``.
"""
def __init__(self, root, fileids, lazy=True):
XMLCorpusReader.__init__(self, root, fileids)
self._lazy = lazy
def words(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=False,
strip_space=True,
replace=False,
):
"""
:return: the given file(s) as a list of words
:rtype: list(str)
:param speaker: If specified, select specific speaker(s) defined
in the corpus. Default is 'ALL' (all participants). Common choices
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
researchers)
:param stem: If true, then use word stems instead of word strings.
:param relation: If true, then return tuples of (stem, index,
dependent_index)
:param strip_space: If true, then strip trailing spaces from word
tokens. Otherwise, leave the spaces on the tokens.
:param replace: If true, then use the replaced (intended) word instead
of the original word (e.g., 'wat' will be replaced with 'watch')
"""
sent = None
pos = False
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def tagged_words(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=False,
strip_space=True,
replace=False,
):
"""
:return: the given file(s) as a list of tagged
words and punctuation symbols, encoded as tuples
``(word,tag)``.
:rtype: list(tuple(str,str))
:param speaker: If specified, select specific speaker(s) defined
in the corpus. Default is 'ALL' (all participants). Common choices
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
researchers)
:param stem: If true, then use word stems instead of word strings.
:param relation: If true, then return tuples of (stem, index,
dependent_index)
:param strip_space: If true, then strip trailing spaces from word
tokens. Otherwise, leave the spaces on the tokens.
:param replace: If true, then use the replaced (intended) word instead
of the original word (e.g., 'wat' will be replaced with 'watch')
"""
sent = None
pos = True
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def sents(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=None,
strip_space=True,
replace=False,
):
"""
:return: the given file(s) as a list of sentences or utterances, each
encoded as a list of word strings.
:rtype: list(list(str))
:param speaker: If specified, select specific speaker(s) defined
in the corpus. Default is 'ALL' (all participants). Common choices
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
researchers)
:param stem: If true, then use word stems instead of word strings.
:param relation: If true, then return tuples of ``(str,pos,relation_list)``.
If there is manually-annotated relation info, it will return
tuples of ``(str,pos,test_relation_list,str,pos,gold_relation_list)``
:param strip_space: If true, then strip trailing spaces from word
tokens. Otherwise, leave the spaces on the tokens.
:param replace: If true, then use the replaced (intended) word instead
of the original word (e.g., 'wat' will be replaced with 'watch')
"""
sent = True
pos = False
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def tagged_sents(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=None,
strip_space=True,
replace=False,
):
"""
:return: the given file(s) as a list of
sentences, each encoded as a list of ``(word,tag)`` tuples.
:rtype: list(list(tuple(str,str)))
:param speaker: If specified, select specific speaker(s) defined
in the corpus. Default is 'ALL' (all participants). Common choices
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
researchers)
:param stem: If true, then use word stems instead of word strings.
:param relation: If true, then return tuples of ``(str,pos,relation_list)``.
If there is manually-annotated relation info, it will return
tuples of ``(str,pos,test_relation_list,str,pos,gold_relation_list)``
:param strip_space: If true, then strip trailing spaces from word
tokens. Otherwise, leave the spaces on the tokens.
:param replace: If true, then use the replaced (intended) word instead
of the original word (e.g., 'wat' will be replaced with 'watch')
"""
sent = True
pos = True
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def corpus(self, fileids=None):
"""
:return: the given file(s) as a dict of ``(corpus_property_key, value)``
:rtype: list(dict)
"""
if not self._lazy:
return [self._get_corpus(fileid) for fileid in self.abspaths(fileids)]
return LazyMap(self._get_corpus, self.abspaths(fileids))
def _get_corpus(self, fileid):
results = dict()
xmldoc = ElementTree.parse(fileid).getroot()
for key, value in xmldoc.items():
results[key] = value
return results
def participants(self, fileids=None):
"""
:return: the given file(s) as a dict of
``(participant_property_key, value)``
:rtype: list(dict)
"""
if not self._lazy:
return [self._get_participants(fileid) for fileid in self.abspaths(fileids)]
return LazyMap(self._get_participants, self.abspaths(fileids))
def _get_participants(self, fileid):
# multidimensional dicts
def dictOfDicts():
return defaultdict(dictOfDicts)
xmldoc = ElementTree.parse(fileid).getroot()
# getting participants' data
pat = dictOfDicts()
for participant in xmldoc.findall(
".//{%s}Participants/{%s}participant" % (NS, NS)
):
for (key, value) in participant.items():
pat[participant.get("id")][key] = value
return pat
def age(self, fileids=None, speaker="CHI", month=False):
"""
:return: the given file(s) as string or int
:rtype: list or int
:param month: If true, return months instead of year-month-date
"""
if not self._lazy:
return [
self._get_age(fileid, speaker, month)
for fileid in self.abspaths(fileids)
]
get_age = lambda fileid: self._get_age(fileid, speaker, month)
return LazyMap(get_age, self.abspaths(fileids))
def _get_age(self, fileid, speaker, month):
xmldoc = ElementTree.parse(fileid).getroot()
for pat in xmldoc.findall(".//{%s}Participants/{%s}participant" % (NS, NS)):
try:
if pat.get("id") == speaker:
age = pat.get("age")
if month:
age = self.convert_age(age)
return age
# some files don't have age data
except (TypeError, AttributeError) as e:
return None
def convert_age(self, age_year):
"Caclculate age in months from a string in CHILDES format"
m = re.match("P(\d+)Y(\d+)M?(\d?\d?)D?", age_year)
age_month = int(m.group(1)) * 12 + int(m.group(2))
try:
if int(m.group(3)) > 15:
age_month += 1
# some corpora don't have age information?
except ValueError as e:
pass
return age_month
def MLU(self, fileids=None, speaker="CHI"):
"""
:return: the given file(s) as a floating number
:rtype: list(float)
"""
if not self._lazy:
return [
self._getMLU(fileid, speaker=speaker)
for fileid in self.abspaths(fileids)
]
get_MLU = lambda fileid: self._getMLU(fileid, speaker=speaker)
return LazyMap(get_MLU, self.abspaths(fileids))
def _getMLU(self, fileid, speaker):
sents = self._get_words(
fileid,
speaker=speaker,
sent=True,
stem=True,
relation=False,
pos=True,
strip_space=True,
replace=True,
)
results = []
lastSent = []
numFillers = 0
sentDiscount = 0
for sent in sents:
posList = [pos for (word, pos) in sent]
# if any part of the sentence is intelligible
if any(pos == "unk" for pos in posList):
continue
# if the sentence is null
elif sent == []:
continue
# if the sentence is the same as the last sent
elif sent == lastSent:
continue
else:
results.append([word for (word, pos) in sent])
# count number of fillers
if len(set(["co", None]).intersection(posList)) > 0:
numFillers += posList.count("co")
numFillers += posList.count(None)
sentDiscount += 1
lastSent = sent
try:
thisWordList = flatten(results)
# count number of morphemes
# (e.g., 'read' = 1 morpheme but 'read-PAST' is 2 morphemes)
numWords = (
len(flatten([word.split("-") for word in thisWordList])) - numFillers
)
numSents = len(results) - sentDiscount
mlu = numWords / numSents
except ZeroDivisionError:
mlu = 0
# return {'mlu':mlu,'wordNum':numWords,'sentNum':numSents}
return mlu
def _get_words(
self, fileid, speaker, sent, stem, relation, pos, strip_space, replace
):
if (
isinstance(speaker, str) and speaker != "ALL"
): # ensure we have a list of speakers
speaker = [speaker]
xmldoc = ElementTree.parse(fileid).getroot()
# processing each xml doc
results = []
for xmlsent in xmldoc.findall(".//{%s}u" % NS):
sents = []
# select speakers
if speaker == "ALL" or xmlsent.get("who") in speaker:
for xmlword in xmlsent.findall(".//{%s}w" % NS):
infl = None
suffixStem = None
suffixTag = None
# getting replaced words
if replace and xmlsent.find(".//{%s}w/{%s}replacement" % (NS, NS)):
xmlword = xmlsent.find(
".//{%s}w/{%s}replacement/{%s}w" % (NS, NS, NS)
)
elif replace and xmlsent.find(".//{%s}w/{%s}wk" % (NS, NS)):
xmlword = xmlsent.find(".//{%s}w/{%s}wk" % (NS, NS))
# get text
if xmlword.text:
word = xmlword.text
else:
word = ""
# strip tailing space
if strip_space:
word = word.strip()
# stem
if relation or stem:
try:
xmlstem = xmlword.find(".//{%s}stem" % NS)
word = xmlstem.text
except AttributeError as e:
pass
# if there is an inflection
try:
xmlinfl = xmlword.find(
".//{%s}mor/{%s}mw/{%s}mk" % (NS, NS, NS)
)
word += "-" + xmlinfl.text
except:
pass
# if there is a suffix
try:
xmlsuffix = xmlword.find(
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}stem"
% (NS, NS, NS, NS)
)
suffixStem = xmlsuffix.text
except AttributeError:
suffixStem = ""
if suffixStem:
word += "~" + suffixStem
# pos
if relation or pos:
try:
xmlpos = xmlword.findall(".//{%s}c" % NS)
xmlpos2 = xmlword.findall(".//{%s}s" % NS)
if xmlpos2 != []:
tag = xmlpos[0].text + ":" + xmlpos2[0].text
else:
tag = xmlpos[0].text
except (AttributeError, IndexError) as e:
tag = ""
try:
xmlsuffixpos = xmlword.findall(
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}pos/{%s}c"
% (NS, NS, NS, NS, NS)
)
xmlsuffixpos2 = xmlword.findall(
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}pos/{%s}s"
% (NS, NS, NS, NS, NS)
)
if xmlsuffixpos2:
suffixTag = (
xmlsuffixpos[0].text + ":" + xmlsuffixpos2[0].text
)
else:
suffixTag = xmlsuffixpos[0].text
except:
pass
if suffixTag:
tag += "~" + suffixTag
word = (word, tag)
# relational
# the gold standard is stored in
# <mor></mor><mor type="trn"><gra type="grt">
if relation == True:
for xmlstem_rel in xmlword.findall(
".//{%s}mor/{%s}gra" % (NS, NS)
):
if not xmlstem_rel.get("type") == "grt":
word = (
word[0],
word[1],
xmlstem_rel.get("index")
+ "|"
+ xmlstem_rel.get("head")
+ "|"
+ xmlstem_rel.get("relation"),
)
else:
word = (
word[0],
word[1],
word[2],
word[0],
word[1],
xmlstem_rel.get("index")
+ "|"
+ xmlstem_rel.get("head")
+ "|"
+ xmlstem_rel.get("relation"),
)
try:
for xmlpost_rel in xmlword.findall(
".//{%s}mor/{%s}mor-post/{%s}gra" % (NS, NS, NS)
):
if not xmlpost_rel.get("type") == "grt":
suffixStem = (
suffixStem[0],
suffixStem[1],
xmlpost_rel.get("index")
+ "|"
+ xmlpost_rel.get("head")
+ "|"
+ xmlpost_rel.get("relation"),
)
else:
suffixStem = (
suffixStem[0],
suffixStem[1],
suffixStem[2],
suffixStem[0],
suffixStem[1],
xmlpost_rel.get("index")
+ "|"
+ xmlpost_rel.get("head")
+ "|"
+ xmlpost_rel.get("relation"),
)
except:
pass
sents.append(word)
if sent or relation:
results.append(sents)
else:
results.extend(sents)
return LazyMap(lambda x: x, results)
# Ready-to-use browser opener
"""
The base URL for viewing files on the childes website. This
shouldn't need to be changed, unless CHILDES changes the configuration
of their server or unless the user sets up their own corpus webserver.
"""
childes_url_base = r"https://childes.talkbank.org/browser/index.php?url="
def webview_file(self, fileid, urlbase=None):
"""Map a corpus file to its web version on the CHILDES website,
and open it in a web browser.
The complete URL to be used is:
childes.childes_url_base + urlbase + fileid.replace('.xml', '.cha')
If no urlbase is passed, we try to calculate it. This
requires that the childes corpus was set up to mirror the
folder hierarchy under childes.psy.cmu.edu/data-xml/, e.g.:
nltk_data/corpora/childes/Eng-USA/Cornell/??? or
nltk_data/corpora/childes/Romance/Spanish/Aguirre/???
The function first looks (as a special case) if "Eng-USA" is
on the path consisting of <corpus root>+fileid; then if
"childes", possibly followed by "data-xml", appears. If neither
one is found, we use the unmodified fileid and hope for the best.
If this is not right, specify urlbase explicitly, e.g., if the
corpus root points to the Cornell folder, urlbase='Eng-USA/Cornell'.
"""
import webbrowser
if urlbase:
path = urlbase + "/" + fileid
else:
full = self.root + "/" + fileid
full = re.sub(r"\\", "/", full)
if "/childes/" in full.lower():
# Discard /data-xml/ if present
path = re.findall(r"(?i)/childes(?:/data-xml)?/(.*)\.xml", full)[0]
elif "eng-usa" in full.lower():
path = "Eng-USA/" + re.findall(r"/(?i)Eng-USA/(.*)\.xml", full)[0]
else:
path = fileid
# Strip ".xml" and add ".cha", as necessary:
if path.endswith(".xml"):
path = path[:-4]
if not path.endswith(".cha"):
path = path + ".cha"
url = self.childes_url_base + path
webbrowser.open_new_tab(url)
print("Opening in browser:", url)
# Pausing is a good idea, but it's up to the user...
# raw_input("Hit Return to continue")
def demo(corpus_root=None):
"""
The CHILDES corpus should be manually downloaded and saved
to ``[NLTK_Data_Dir]/corpora/childes/``
"""
if not corpus_root:
from nltk.data import find
corpus_root = find("corpora/childes/data-xml/Eng-USA/")
try:
childes = CHILDESCorpusReader(corpus_root, ".*.xml")
# describe all corpus
for file in childes.fileids()[:5]:
corpus = ""
corpus_id = ""
for (key, value) in childes.corpus(file)[0].items():
if key == "Corpus":
corpus = value
if key == "Id":
corpus_id = value
print("Reading", corpus, corpus_id, " .....")
print("words:", childes.words(file)[:7], "...")
print(
"words with replaced words:",
childes.words(file, replace=True)[:7],
" ...",
)
print("words with pos tags:", childes.tagged_words(file)[:7], " ...")
print("words (only MOT):", childes.words(file, speaker="MOT")[:7], "...")
print("words (only CHI):", childes.words(file, speaker="CHI")[:7], "...")
print("stemmed words:", childes.words(file, stem=True)[:7], " ...")
print(
"words with relations and pos-tag:",
childes.words(file, relation=True)[:5],
" ...",
)
print("sentence:", childes.sents(file)[:2], " ...")
for (participant, values) in childes.participants(file)[0].items():
for (key, value) in values.items():
print("\tparticipant", participant, key, ":", value)
print("num of sent:", len(childes.sents(file)))
print("num of morphemes:", len(childes.words(file, stem=True)))
print("age:", childes.age(file))
print("age in month:", childes.age(file, month=True))
print("MLU:", childes.MLU(file))
print()
except LookupError as e:
print(
"""The CHILDES corpus, or the parts you need, should be manually
downloaded from https://childes.talkbank.org/data-xml/ and saved at
[NLTK_Data_Dir]/corpora/childes/
Alternately, you can call the demo with the path to a portion of the CHILDES corpus, e.g.:
demo('/path/to/childes/data-xml/Eng-USA/")
"""
)
# corpus_root_http = urllib2.urlopen('https://childes.talkbank.org/data-xml/Eng-USA/Bates.zip')
# corpus_root_http_bates = zipfile.ZipFile(cStringIO.StringIO(corpus_root_http.read()))
##this fails
# childes = CHILDESCorpusReader(corpus_root_http_bates,corpus_root_http_bates.namelist())
if __name__ == "__main__":
demo()
| 40.337025 | 103 | 0.484839 |
__docformat__ = "epytext en"
import re
from collections import defaultdict
from nltk.util import flatten, LazyMap, LazyConcatenation
from nltk.corpus.reader.util import concat
from nltk.corpus.reader.xmldocs import XMLCorpusReader, ElementTree
NS = "http://www.talkbank.org/ns/talkbank"
class CHILDESCorpusReader(XMLCorpusReader):
def __init__(self, root, fileids, lazy=True):
XMLCorpusReader.__init__(self, root, fileids)
self._lazy = lazy
def words(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=False,
strip_space=True,
replace=False,
):
sent = None
pos = False
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def tagged_words(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=False,
strip_space=True,
replace=False,
):
sent = None
pos = True
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def sents(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=None,
strip_space=True,
replace=False,
):
sent = True
pos = False
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def tagged_sents(
self,
fileids=None,
speaker="ALL",
stem=False,
relation=None,
strip_space=True,
replace=False,
):
sent = True
pos = True
if not self._lazy:
return [
self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
for fileid in self.abspaths(fileids)
]
get_words = lambda fileid: self._get_words(
fileid, speaker, sent, stem, relation, pos, strip_space, replace
)
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
def corpus(self, fileids=None):
if not self._lazy:
return [self._get_corpus(fileid) for fileid in self.abspaths(fileids)]
return LazyMap(self._get_corpus, self.abspaths(fileids))
def _get_corpus(self, fileid):
results = dict()
xmldoc = ElementTree.parse(fileid).getroot()
for key, value in xmldoc.items():
results[key] = value
return results
def participants(self, fileids=None):
if not self._lazy:
return [self._get_participants(fileid) for fileid in self.abspaths(fileids)]
return LazyMap(self._get_participants, self.abspaths(fileids))
def _get_participants(self, fileid):
def dictOfDicts():
return defaultdict(dictOfDicts)
xmldoc = ElementTree.parse(fileid).getroot()
pat = dictOfDicts()
for participant in xmldoc.findall(
".//{%s}Participants/{%s}participant" % (NS, NS)
):
for (key, value) in participant.items():
pat[participant.get("id")][key] = value
return pat
def age(self, fileids=None, speaker="CHI", month=False):
if not self._lazy:
return [
self._get_age(fileid, speaker, month)
for fileid in self.abspaths(fileids)
]
get_age = lambda fileid: self._get_age(fileid, speaker, month)
return LazyMap(get_age, self.abspaths(fileids))
def _get_age(self, fileid, speaker, month):
xmldoc = ElementTree.parse(fileid).getroot()
for pat in xmldoc.findall(".//{%s}Participants/{%s}participant" % (NS, NS)):
try:
if pat.get("id") == speaker:
age = pat.get("age")
if month:
age = self.convert_age(age)
return age
# some files don't have age data
except (TypeError, AttributeError) as e:
return None
def convert_age(self, age_year):
m = re.match("P(\d+)Y(\d+)M?(\d?\d?)D?", age_year)
age_month = int(m.group(1)) * 12 + int(m.group(2))
try:
if int(m.group(3)) > 15:
age_month += 1
except ValueError as e:
pass
return age_month
def MLU(self, fileids=None, speaker="CHI"):
if not self._lazy:
return [
self._getMLU(fileid, speaker=speaker)
for fileid in self.abspaths(fileids)
]
get_MLU = lambda fileid: self._getMLU(fileid, speaker=speaker)
return LazyMap(get_MLU, self.abspaths(fileids))
def _getMLU(self, fileid, speaker):
sents = self._get_words(
fileid,
speaker=speaker,
sent=True,
stem=True,
relation=False,
pos=True,
strip_space=True,
replace=True,
)
results = []
lastSent = []
numFillers = 0
sentDiscount = 0
for sent in sents:
posList = [pos for (word, pos) in sent]
# if any part of the sentence is intelligible
if any(pos == "unk" for pos in posList):
continue
# if the sentence is null
elif sent == []:
continue
# if the sentence is the same as the last sent
elif sent == lastSent:
continue
else:
results.append([word for (word, pos) in sent])
# count number of fillers
if len(set(["co", None]).intersection(posList)) > 0:
numFillers += posList.count("co")
numFillers += posList.count(None)
sentDiscount += 1
lastSent = sent
try:
thisWordList = flatten(results)
# count number of morphemes
# (e.g., 'read' = 1 morpheme but 'read-PAST' is 2 morphemes)
numWords = (
len(flatten([word.split("-") for word in thisWordList])) - numFillers
)
numSents = len(results) - sentDiscount
mlu = numWords / numSents
except ZeroDivisionError:
mlu = 0
# return {'mlu':mlu,'wordNum':numWords,'sentNum':numSents}
return mlu
def _get_words(
self, fileid, speaker, sent, stem, relation, pos, strip_space, replace
):
if (
isinstance(speaker, str) and speaker != "ALL"
): # ensure we have a list of speakers
speaker = [speaker]
xmldoc = ElementTree.parse(fileid).getroot()
# processing each xml doc
results = []
for xmlsent in xmldoc.findall(".//{%s}u" % NS):
sents = []
# select speakers
if speaker == "ALL" or xmlsent.get("who") in speaker:
for xmlword in xmlsent.findall(".//{%s}w" % NS):
infl = None
suffixStem = None
suffixTag = None
# getting replaced words
if replace and xmlsent.find(".//{%s}w/{%s}replacement" % (NS, NS)):
xmlword = xmlsent.find(
".//{%s}w/{%s}replacement/{%s}w" % (NS, NS, NS)
)
elif replace and xmlsent.find(".//{%s}w/{%s}wk" % (NS, NS)):
xmlword = xmlsent.find(".//{%s}w/{%s}wk" % (NS, NS))
# get text
if xmlword.text:
word = xmlword.text
else:
word = ""
# strip tailing space
if strip_space:
word = word.strip()
# stem
if relation or stem:
try:
xmlstem = xmlword.find(".//{%s}stem" % NS)
word = xmlstem.text
except AttributeError as e:
pass
# if there is an inflection
try:
xmlinfl = xmlword.find(
".//{%s}mor/{%s}mw/{%s}mk" % (NS, NS, NS)
)
word += "-" + xmlinfl.text
except:
pass
# if there is a suffix
try:
xmlsuffix = xmlword.find(
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}stem"
% (NS, NS, NS, NS)
)
suffixStem = xmlsuffix.text
except AttributeError:
suffixStem = ""
if suffixStem:
word += "~" + suffixStem
# pos
if relation or pos:
try:
xmlpos = xmlword.findall(".//{%s}c" % NS)
xmlpos2 = xmlword.findall(".//{%s}s" % NS)
if xmlpos2 != []:
tag = xmlpos[0].text + ":" + xmlpos2[0].text
else:
tag = xmlpos[0].text
except (AttributeError, IndexError) as e:
tag = ""
try:
xmlsuffixpos = xmlword.findall(
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}pos/{%s}c"
% (NS, NS, NS, NS, NS)
)
xmlsuffixpos2 = xmlword.findall(
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}pos/{%s}s"
% (NS, NS, NS, NS, NS)
)
if xmlsuffixpos2:
suffixTag = (
xmlsuffixpos[0].text + ":" + xmlsuffixpos2[0].text
)
else:
suffixTag = xmlsuffixpos[0].text
except:
pass
if suffixTag:
tag += "~" + suffixTag
word = (word, tag)
# relational
# the gold standard is stored in
# <mor></mor><mor type="trn"><gra type="grt">
if relation == True:
for xmlstem_rel in xmlword.findall(
".//{%s}mor/{%s}gra" % (NS, NS)
):
if not xmlstem_rel.get("type") == "grt":
word = (
word[0],
word[1],
xmlstem_rel.get("index")
+ "|"
+ xmlstem_rel.get("head")
+ "|"
+ xmlstem_rel.get("relation"),
)
else:
word = (
word[0],
word[1],
word[2],
word[0],
word[1],
xmlstem_rel.get("index")
+ "|"
+ xmlstem_rel.get("head")
+ "|"
+ xmlstem_rel.get("relation"),
)
try:
for xmlpost_rel in xmlword.findall(
".//{%s}mor/{%s}mor-post/{%s}gra" % (NS, NS, NS)
):
if not xmlpost_rel.get("type") == "grt":
suffixStem = (
suffixStem[0],
suffixStem[1],
xmlpost_rel.get("index")
+ "|"
+ xmlpost_rel.get("head")
+ "|"
+ xmlpost_rel.get("relation"),
)
else:
suffixStem = (
suffixStem[0],
suffixStem[1],
suffixStem[2],
suffixStem[0],
suffixStem[1],
xmlpost_rel.get("index")
+ "|"
+ xmlpost_rel.get("head")
+ "|"
+ xmlpost_rel.get("relation"),
)
except:
pass
sents.append(word)
if sent or relation:
results.append(sents)
else:
results.extend(sents)
return LazyMap(lambda x: x, results)
# Ready-to-use browser opener
childes_url_base = r"https://childes.talkbank.org/browser/index.php?url="
def webview_file(self, fileid, urlbase=None):
import webbrowser
if urlbase:
path = urlbase + "/" + fileid
else:
full = self.root + "/" + fileid
full = re.sub(r"\\", "/", full)
if "/childes/" in full.lower():
# Discard /data-xml/ if present
path = re.findall(r"(?i)/childes(?:/data-xml)?/(.*)\.xml", full)[0]
elif "eng-usa" in full.lower():
path = "Eng-USA/" + re.findall(r"/(?i)Eng-USA/(.*)\.xml", full)[0]
else:
path = fileid
# Strip ".xml" and add ".cha", as necessary:
if path.endswith(".xml"):
path = path[:-4]
if not path.endswith(".cha"):
path = path + ".cha"
url = self.childes_url_base + path
webbrowser.open_new_tab(url)
print("Opening in browser:", url)
# Pausing is a good idea, but it's up to the user...
def demo(corpus_root=None):
if not corpus_root:
from nltk.data import find
corpus_root = find("corpora/childes/data-xml/Eng-USA/")
try:
childes = CHILDESCorpusReader(corpus_root, ".*.xml")
for file in childes.fileids()[:5]:
corpus = ""
corpus_id = ""
for (key, value) in childes.corpus(file)[0].items():
if key == "Corpus":
corpus = value
if key == "Id":
corpus_id = value
print("Reading", corpus, corpus_id, " .....")
print("words:", childes.words(file)[:7], "...")
print(
"words with replaced words:",
childes.words(file, replace=True)[:7],
" ...",
)
print("words with pos tags:", childes.tagged_words(file)[:7], " ...")
print("words (only MOT):", childes.words(file, speaker="MOT")[:7], "...")
print("words (only CHI):", childes.words(file, speaker="CHI")[:7], "...")
print("stemmed words:", childes.words(file, stem=True)[:7], " ...")
print(
"words with relations and pos-tag:",
childes.words(file, relation=True)[:5],
" ...",
)
print("sentence:", childes.sents(file)[:2], " ...")
for (participant, values) in childes.participants(file)[0].items():
for (key, value) in values.items():
print("\tparticipant", participant, key, ":", value)
print("num of sent:", len(childes.sents(file)))
print("num of morphemes:", len(childes.words(file, stem=True)))
print("age:", childes.age(file))
print("age in month:", childes.age(file, month=True))
print("MLU:", childes.MLU(file))
print()
except LookupError as e:
print(
"""The CHILDES corpus, or the parts you need, should be manually
downloaded from https://childes.talkbank.org/data-xml/ and saved at
[NLTK_Data_Dir]/corpora/childes/
Alternately, you can call the demo with the path to a portion of the CHILDES corpus, e.g.:
demo('/path/to/childes/data-xml/Eng-USA/")
"""
)
# corpus_root_http = urllib2.urlopen('https://childes.talkbank.org/data-xml/Eng-USA/Bates.zip')
# corpus_root_http_bates = zipfile.ZipFile(cStringIO.StringIO(corpus_root_http.read()))
##this fails
# childes = CHILDESCorpusReader(corpus_root_http_bates,corpus_root_http_bates.namelist())
if __name__ == "__main__":
demo()
| true | true |
f72a01337fef4faaba288b693e58d4c5ca437e37 | 31,822 | py | Python | TCFC/eval/bert_eval_acc.py | silverriver/Stylized_Dialog | 559dd97c4ec9c91e94deb048f789684ef3f1f9fa | [
"MIT"
] | 21 | 2020-12-16T08:53:38.000Z | 2022-01-21T09:08:55.000Z | TCFC/eval/bert_eval_acc.py | silverriver/Stylized_Dialog | 559dd97c4ec9c91e94deb048f789684ef3f1f9fa | [
"MIT"
] | 1 | 2020-12-27T07:56:01.000Z | 2020-12-30T05:13:11.000Z | TCFC/eval/bert_eval_acc.py | silverriver/Stylized_Dialog | 559dd97c4ec9c91e94deb048f789684ef3f1f9fa | [
"MIT"
] | 1 | 2022-02-28T12:19:19.000Z | 2022-02-28T12:19:19.000Z | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Finetuning the library models for sequence classification on GLUE (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa)."""
import argparse
import glob
import json
import logging
import os
import random
import shutil
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from transformers import (
WEIGHTS_NAME,
AdamW,
AlbertConfig,
AlbertForSequenceClassification,
AlbertTokenizer,
BertConfig,
BertForSequenceClassification,
BertTokenizer,
DistilBertConfig,
DistilBertForSequenceClassification,
DistilBertTokenizer,
FlaubertConfig,
FlaubertForSequenceClassification,
FlaubertTokenizer,
RobertaConfig,
RobertaForSequenceClassification,
RobertaTokenizer,
XLMConfig,
XLMForSequenceClassification,
XLMRobertaConfig,
XLMRobertaForSequenceClassification,
XLMRobertaTokenizer,
XLMTokenizer,
XLNetConfig,
XLNetForSequenceClassification,
XLNetTokenizer,
get_linear_schedule_with_warmup,
)
from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes as output_modes
from transformers import glue_processors as processors
from torch.utils.tensorboard import SummaryWriter
logger = logging.getLogger(__name__)
ALL_MODELS = sum(
(
tuple(conf.pretrained_config_archive_map.keys())
for conf in (
BertConfig,
XLNetConfig,
XLMConfig,
RobertaConfig,
DistilBertConfig,
AlbertConfig,
XLMRobertaConfig,
FlaubertConfig,
)
),
(),
)
MODEL_CLASSES = {
"bert": (BertConfig, BertForSequenceClassification, BertTokenizer),
"xlnet": (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer),
"xlm": (XLMConfig, XLMForSequenceClassification, XLMTokenizer),
"roberta": (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer),
"distilbert": (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer),
"albert": (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer),
"xlmroberta": (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer),
"flaubert": (FlaubertConfig, FlaubertForSequenceClassification, FlaubertTokenizer),
}
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def softmax(x):
x_row_max = x.max(axis=-1)
x_row_max = x_row_max.reshape(list(x.shape)[:-1]+[1])
x = x - x_row_max
x_exp = np.exp(x)
x_exp_row_sum = x_exp.sum(axis=-1).reshape(list(x.shape)[:-1]+[1])
softmax = x_exp / x_exp_row_sum
return softmax
def train(args, train_dataset, model, tokenizer):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
if args.max_steps > 0:
t_total = args.max_steps
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
else:
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
)
# Check if saved optimizer or scheduler states exist
if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(
os.path.join(args.model_name_or_path, "scheduler.pt")
):
# Load in optimizer and scheduler states
optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
if args.fp16:
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True,
)
# Train!
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(
" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size
* args.gradient_accumulation_steps
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
)
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 0
epochs_trained = 0
steps_trained_in_current_epoch = 0
# Check if continuing training from a checkpoint
if os.path.exists(args.model_name_or_path):
# set global_step to global_step of last saved checkpoint from model path
try:
global_step = int(args.model_name_or_path.split("-")[-1].split("/")[0])
except ValueError:
global_step = 0
epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(" Continuing training from epoch %d", epochs_trained)
logger.info(" Continuing training from global step %d", global_step)
logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
tr_loss, logging_loss = 0.0, 0.0
model.zero_grad()
train_iterator = trange(
epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0],
)
set_seed(args) # Added here for reproductibility
for _ in train_iterator:
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
for step, batch in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
model.train()
batch = tuple(t.to(args.device) for t in batch)
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
if args.model_type != "distilbert":
inputs["token_type_ids"] = (
batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None
) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids
outputs = model(**inputs)
loss = outputs[0] # model outputs are always tuple in transformers (see doc)
if args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
tr_loss += loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.fp16:
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
else:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step() # Update learning rate schedule
model.zero_grad()
global_step += 1
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
logs = {}
if (
args.local_rank == -1 and args.evaluate_during_training
): # Only evaluate when single GPU otherwise metrics may not average well
results = evaluate(args, model, tokenizer)
for key, value in results.items():
eval_key = "eval_{}".format(key)
logs[eval_key] = value
loss_scalar = (tr_loss - logging_loss) / args.logging_steps
learning_rate_scalar = scheduler.get_lr()[0]
logs["learning_rate"] = learning_rate_scalar
logs["loss"] = loss_scalar
logging_loss = tr_loss
for key, value in logs.items():
tb_writer.add_scalar(key, value, global_step)
print(json.dumps({**logs, **{"step": global_step}}))
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
# Save model checkpoint
output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
model_to_save = (
model.module if hasattr(model, "module") else model
) # Take care of distributed/parallel training
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, "training_args.bin"))
logger.info("Saving model checkpoint to %s", output_dir)
torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
logger.info("Saving optimizer and scheduler states to %s", output_dir)
if args.max_steps > 0 and global_step > args.max_steps:
epoch_iterator.close()
break
if args.max_steps > 0 and global_step > args.max_steps:
train_iterator.close()
break
if args.local_rank in [-1, 0]:
tb_writer.close()
return global_step, tr_loss / global_step
def evaluate(args, model, tokenizer, prefix=""):
# Loop to handle MNLI double evaluation (matched, mis-matched)
eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,)
eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,)
results = {}
for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
eval_sampler = SequentialSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
# multi-gpu eval
if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
model = torch.nn.DataParallel(model)
# Eval!
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
eval_loss = 0.0
nb_eval_steps = 0
preds = None
out_label_ids = None
for batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
batch = tuple(t.to(args.device) for t in batch)
with torch.no_grad():
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
if args.model_type != "distilbert":
inputs["token_type_ids"] = (
batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None
) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids
outputs = model(**inputs)
tmp_eval_loss, logits = outputs[:2]
eval_loss += tmp_eval_loss.mean().item()
nb_eval_steps += 1
if preds is None:
preds = logits.detach().cpu().numpy()
out_label_ids = inputs["labels"].detach().cpu().numpy()
else:
preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)
out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0)
eval_loss = eval_loss / nb_eval_steps
if args.output_mode == "classification":
preds = np.argmax(preds, axis=1)
elif args.output_mode == "regression":
preds = np.squeeze(preds)
result = compute_metrics(eval_task, preds, out_label_ids)
results.update(result)
output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt")
with open(output_eval_file, "w") as writer:
logger.info("***** Eval results {} *****".format(prefix))
for key in sorted(result.keys()):
logger.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
return results
def pred_prob(args, model, tokenizer, prefix=""):
# Loop to handle MNLI double evaluation (matched, mis-matched)
eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,)
eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,)
for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
eval_sampler = SequentialSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
# multi-gpu eval
if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
model = torch.nn.DataParallel(model)
# Eval!
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
all_logits = None
for batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
batch = tuple(t.to(args.device) for t in batch)
with torch.no_grad():
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
if args.model_type != "distilbert":
inputs["token_type_ids"] = (
batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None
) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids
outputs = model(**inputs)
tmp_eval_loss, logits = outputs[:2]
logits = logits.detach().cpu().numpy()
if all_logits is None:
all_logits = logits
else:
all_logits = np.concatenate((all_logits, logits), 0)
all_logits = softmax(all_logits)
results = all_logits[:, 1].reshape(-1)
return results
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
if args.local_rank not in [-1, 0] and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
processor = processors[task]()
output_mode = output_modes[task]
# Load data features from cache or dataset file
cached_features_file = os.path.join(
args.data_dir,
"cached_{}_{}_{}_{}".format(
"dev" if evaluate else "train",
list(filter(None, args.model_name_or_path.split("/"))).pop(),
str(args.max_seq_length),
str(task),
),
)
if os.path.exists(cached_features_file) and not args.overwrite_cache:
logger.info("Loading features from cached file %s", cached_features_file)
features = torch.load(cached_features_file)
else:
logger.info("Creating features from dataset file at %s", args.data_dir)
label_list = processor.get_labels()
if task in ["mnli", "mnli-mm"] and args.model_type in ["roberta", "xlmroberta"]:
# HACK(label indices are swapped in RoBERTa pretrained model)
label_list[1], label_list[2] = label_list[2], label_list[1]
examples = (
processor.get_dev_examples(args.data_dir) if evaluate else processor.get_train_examples(args.data_dir)
)
features = convert_examples_to_features(
examples,
tokenizer,
label_list=label_list,
max_length=args.max_seq_length,
output_mode=output_mode,
pad_on_left=bool(args.model_type in ["xlnet"]), # pad on the left for xlnet
pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],
pad_token_segment_id=4 if args.model_type in ["xlnet"] else 0,
)
if args.local_rank in [-1, 0]:
logger.info("Saving features into cached file %s", cached_features_file)
torch.save(features, cached_features_file)
if args.local_rank == 0 and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
# Convert to Tensors and build dataset
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
if output_mode == "classification":
all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
elif output_mode == "regression":
all_labels = torch.tensor([f.label for f in features], dtype=torch.float)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels)
return dataset
def main(file_path):
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument('--eval_file_path', help='path of the eval file')
parser.add_argument(
"--data_dir",
default="tmp",
type=str,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
)
parser.add_argument(
"--model_type",
default="bert",
type=str,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()),
)
parser.add_argument(
"--model_name_or_path",
default="bert-base-cased",
type=str,
help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS),
)
parser.add_argument(
"--task_name",
default="sst-2",
type=str,
help="The name of the task to train selected in the list: " + ", ".join(processors.keys()),
)
parser.add_argument(
"--output_dir",
default="../data/out_cased",
type=str,
help="The output directory where the model predictions and checkpoints will be written.",
)
# Other parameters
parser.add_argument(
"--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name",
)
parser.add_argument(
"--tokenizer_name",
default="",
type=str,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--cache_dir",
default="../data/cache",
type=str,
help="Where do you want to store the pre-trained models downloaded from s3",
)
parser.add_argument(
"--max_seq_length",
default=128,
type=int,
help="The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.",
)
parser.add_argument(
"--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step.",
)
parser.add_argument(
"--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model.",
)
parser.add_argument(
"--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.",
)
parser.add_argument(
"--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument("--learning_rate", default=2e-5, type=float, help="The initial learning rate for Adam.")
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
parser.add_argument(
"--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform.",
)
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
)
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.")
parser.add_argument("--save_steps", type=int, default=500, help="Save checkpoint every X updates steps.")
parser.add_argument(
"--eval_all_checkpoints",
action="store_true",
help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number",
)
parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
parser.add_argument(
"--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory",
)
parser.add_argument(
"--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets",
)
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument(
"--fp16",
action="store_true",
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
)
parser.add_argument(
"--fp16_opt_level",
type=str,
default="O1",
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
"See details at https://nvidia.github.io/apex/amp.html",
)
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
parser.add_argument("--server_ip", type=str, default="", help="For distant debugging.")
parser.add_argument("--server_port", type=str, default="", help="For distant debugging.")
args = parser.parse_args()
args.no_cuda = True
# Setup distant debugging if needed
if args.server_ip and args.server_port:
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
import ptvsd
print("Waiting for debugger attach")
ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
ptvsd.wait_for_attach()
# Setup CUDA, GPU & distributed training
if args.local_rank == -1 or args.no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend="nccl")
args.n_gpu = 1
args.device = device
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.ERROR
)
logger.warning(
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
args.local_rank,
device,
args.n_gpu,
bool(args.local_rank != -1),
args.fp16,
)
# Set seed
set_seed(args)
# Prepare GLUE task
args.task_name = args.task_name.lower()
if args.task_name not in processors:
raise ValueError("Task not found: %s" % (args.task_name))
processor = processors[args.task_name]()
args.output_mode = output_modes[args.task_name]
label_list = processor.get_labels()
num_labels = len(label_list)
# Load pretrained model and tokenizer
if args.local_rank not in [-1, 0]:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
args.model_type = args.model_type.lower()
config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
config = config_class.from_pretrained(
args.config_name if args.config_name else args.model_name_or_path,
num_labels=num_labels,
finetuning_task=args.task_name,
cache_dir=args.cache_dir if args.cache_dir else None,
)
tokenizer = tokenizer_class.from_pretrained(
args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
do_lower_case=args.do_lower_case,
cache_dir=args.cache_dir if args.cache_dir else None,
)
model = model_class.from_pretrained(
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
cache_dir=args.cache_dir if args.cache_dir else None,
)
if args.local_rank == 0:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
model.to(args.device)
logger.info("Evaluation parameters %s", args)
# Evaluation
if args.local_rank in [-1, 0]:
tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
checkpoints = [args.output_dir]
if args.eval_all_checkpoints:
checkpoints = list(
os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
)
logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging
logger.info("Evaluate the following checkpoints: %s", checkpoints)
for checkpoint in checkpoints:
global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
prefix = checkpoint.split("/")[-1] if checkpoint.find("checkpoint") != -1 else ""
model = model_class.from_pretrained(checkpoint)
model.to(args.device)
data_folder = args.data_dir
dev_file_path = os.path.join(data_folder, 'dev.tsv')
preds = []
with open(file_path, encoding='utf8') as f:
d = f.read().strip().split('\n')
for s in d:
j = json.loads(s)
preds += j['pred_style0']
preds = '\n'.join([s + '\t0' for s in preds]) + '\n'
if os.path.exists(data_folder):
shutil.rmtree(data_folder)
os.makedirs(data_folder)
with open(dev_file_path, 'w', encoding='utf8') as f:
f.write(preds)
result = evaluate(args, model, tokenizer, prefix=prefix)
acc0 = result['acc']
preds = []
with open(file_path, encoding='utf8') as f:
d = f.read().strip().split('\n')
for s in d:
j = json.loads(s)
preds += j['pred_style1']
preds = '\n'.join([s + '\t1' for s in preds]) + '\n'
if os.path.exists(data_folder):
shutil.rmtree(data_folder)
os.makedirs(data_folder)
with open(dev_file_path, 'w', encoding='utf8') as f:
f.write(preds)
result = evaluate(args, model, tokenizer, prefix=prefix)
acc1 = result['acc']
print('BERT:', 's0', acc0 * 100, 's1', acc1 * 100, 'mean', (acc0 + acc1) / 2 * 100)
| 42.829071 | 150 | 0.639683 |
import argparse
import glob
import json
import logging
import os
import random
import shutil
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from transformers import (
WEIGHTS_NAME,
AdamW,
AlbertConfig,
AlbertForSequenceClassification,
AlbertTokenizer,
BertConfig,
BertForSequenceClassification,
BertTokenizer,
DistilBertConfig,
DistilBertForSequenceClassification,
DistilBertTokenizer,
FlaubertConfig,
FlaubertForSequenceClassification,
FlaubertTokenizer,
RobertaConfig,
RobertaForSequenceClassification,
RobertaTokenizer,
XLMConfig,
XLMForSequenceClassification,
XLMRobertaConfig,
XLMRobertaForSequenceClassification,
XLMRobertaTokenizer,
XLMTokenizer,
XLNetConfig,
XLNetForSequenceClassification,
XLNetTokenizer,
get_linear_schedule_with_warmup,
)
from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes as output_modes
from transformers import glue_processors as processors
from torch.utils.tensorboard import SummaryWriter
logger = logging.getLogger(__name__)
ALL_MODELS = sum(
(
tuple(conf.pretrained_config_archive_map.keys())
for conf in (
BertConfig,
XLNetConfig,
XLMConfig,
RobertaConfig,
DistilBertConfig,
AlbertConfig,
XLMRobertaConfig,
FlaubertConfig,
)
),
(),
)
MODEL_CLASSES = {
"bert": (BertConfig, BertForSequenceClassification, BertTokenizer),
"xlnet": (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer),
"xlm": (XLMConfig, XLMForSequenceClassification, XLMTokenizer),
"roberta": (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer),
"distilbert": (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer),
"albert": (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer),
"xlmroberta": (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer),
"flaubert": (FlaubertConfig, FlaubertForSequenceClassification, FlaubertTokenizer),
}
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def softmax(x):
x_row_max = x.max(axis=-1)
x_row_max = x_row_max.reshape(list(x.shape)[:-1]+[1])
x = x - x_row_max
x_exp = np.exp(x)
x_exp_row_sum = x_exp.sum(axis=-1).reshape(list(x.shape)[:-1]+[1])
softmax = x_exp / x_exp_row_sum
return softmax
def train(args, train_dataset, model, tokenizer):
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
if args.max_steps > 0:
t_total = args.max_steps
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
else:
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
)
if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(
os.path.join(args.model_name_or_path, "scheduler.pt")
):
optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
if args.fp16:
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True,
)
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(
" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size
* args.gradient_accumulation_steps
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
)
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 0
epochs_trained = 0
steps_trained_in_current_epoch = 0
if os.path.exists(args.model_name_or_path):
try:
global_step = int(args.model_name_or_path.split("-")[-1].split("/")[0])
except ValueError:
global_step = 0
epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(" Continuing training from epoch %d", epochs_trained)
logger.info(" Continuing training from global step %d", global_step)
logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
tr_loss, logging_loss = 0.0, 0.0
model.zero_grad()
train_iterator = trange(
epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0],
)
set_seed(args)
for _ in train_iterator:
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
for step, batch in enumerate(epoch_iterator):
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
model.train()
batch = tuple(t.to(args.device) for t in batch)
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
if args.model_type != "distilbert":
inputs["token_type_ids"] = (
batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None
)
outputs = model(**inputs)
loss = outputs[0] # model outputs are always tuple in transformers (see doc)
if args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
tr_loss += loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.fp16:
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
else:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step() # Update learning rate schedule
model.zero_grad()
global_step += 1
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
logs = {}
if (
args.local_rank == -1 and args.evaluate_during_training
): # Only evaluate when single GPU otherwise metrics may not average well
results = evaluate(args, model, tokenizer)
for key, value in results.items():
eval_key = "eval_{}".format(key)
logs[eval_key] = value
loss_scalar = (tr_loss - logging_loss) / args.logging_steps
learning_rate_scalar = scheduler.get_lr()[0]
logs["learning_rate"] = learning_rate_scalar
logs["loss"] = loss_scalar
logging_loss = tr_loss
for key, value in logs.items():
tb_writer.add_scalar(key, value, global_step)
print(json.dumps({**logs, **{"step": global_step}}))
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
# Save model checkpoint
output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
model_to_save = (
model.module if hasattr(model, "module") else model
) # Take care of distributed/parallel training
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, "training_args.bin"))
logger.info("Saving model checkpoint to %s", output_dir)
torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
logger.info("Saving optimizer and scheduler states to %s", output_dir)
if args.max_steps > 0 and global_step > args.max_steps:
epoch_iterator.close()
break
if args.max_steps > 0 and global_step > args.max_steps:
train_iterator.close()
break
if args.local_rank in [-1, 0]:
tb_writer.close()
return global_step, tr_loss / global_step
def evaluate(args, model, tokenizer, prefix=""):
# Loop to handle MNLI double evaluation (matched, mis-matched)
eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,)
eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,)
results = {}
for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
eval_sampler = SequentialSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
# multi-gpu eval
if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
model = torch.nn.DataParallel(model)
# Eval!
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
eval_loss = 0.0
nb_eval_steps = 0
preds = None
out_label_ids = None
for batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
batch = tuple(t.to(args.device) for t in batch)
with torch.no_grad():
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
if args.model_type != "distilbert":
inputs["token_type_ids"] = (
batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None
) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids
outputs = model(**inputs)
tmp_eval_loss, logits = outputs[:2]
eval_loss += tmp_eval_loss.mean().item()
nb_eval_steps += 1
if preds is None:
preds = logits.detach().cpu().numpy()
out_label_ids = inputs["labels"].detach().cpu().numpy()
else:
preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)
out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0)
eval_loss = eval_loss / nb_eval_steps
if args.output_mode == "classification":
preds = np.argmax(preds, axis=1)
elif args.output_mode == "regression":
preds = np.squeeze(preds)
result = compute_metrics(eval_task, preds, out_label_ids)
results.update(result)
output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt")
with open(output_eval_file, "w") as writer:
logger.info("***** Eval results {} *****".format(prefix))
for key in sorted(result.keys()):
logger.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
return results
def pred_prob(args, model, tokenizer, prefix=""):
eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,)
eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,)
for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
eval_sampler = SequentialSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
model = torch.nn.DataParallel(model)
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
all_logits = None
for batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
batch = tuple(t.to(args.device) for t in batch)
with torch.no_grad():
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
if args.model_type != "distilbert":
inputs["token_type_ids"] = (
batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None
)
outputs = model(**inputs)
tmp_eval_loss, logits = outputs[:2]
logits = logits.detach().cpu().numpy()
if all_logits is None:
all_logits = logits
else:
all_logits = np.concatenate((all_logits, logits), 0)
all_logits = softmax(all_logits)
results = all_logits[:, 1].reshape(-1)
return results
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
if args.local_rank not in [-1, 0] and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
processor = processors[task]()
output_mode = output_modes[task]
# Load data features from cache or dataset file
cached_features_file = os.path.join(
args.data_dir,
"cached_{}_{}_{}_{}".format(
"dev" if evaluate else "train",
list(filter(None, args.model_name_or_path.split("/"))).pop(),
str(args.max_seq_length),
str(task),
),
)
if os.path.exists(cached_features_file) and not args.overwrite_cache:
logger.info("Loading features from cached file %s", cached_features_file)
features = torch.load(cached_features_file)
else:
logger.info("Creating features from dataset file at %s", args.data_dir)
label_list = processor.get_labels()
if task in ["mnli", "mnli-mm"] and args.model_type in ["roberta", "xlmroberta"]:
# HACK(label indices are swapped in RoBERTa pretrained model)
label_list[1], label_list[2] = label_list[2], label_list[1]
examples = (
processor.get_dev_examples(args.data_dir) if evaluate else processor.get_train_examples(args.data_dir)
)
features = convert_examples_to_features(
examples,
tokenizer,
label_list=label_list,
max_length=args.max_seq_length,
output_mode=output_mode,
pad_on_left=bool(args.model_type in ["xlnet"]), # pad on the left for xlnet
pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],
pad_token_segment_id=4 if args.model_type in ["xlnet"] else 0,
)
if args.local_rank in [-1, 0]:
logger.info("Saving features into cached file %s", cached_features_file)
torch.save(features, cached_features_file)
if args.local_rank == 0 and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
# Convert to Tensors and build dataset
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
if output_mode == "classification":
all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
elif output_mode == "regression":
all_labels = torch.tensor([f.label for f in features], dtype=torch.float)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels)
return dataset
def main(file_path):
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument('--eval_file_path', help='path of the eval file')
parser.add_argument(
"--data_dir",
default="tmp",
type=str,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
)
parser.add_argument(
"--model_type",
default="bert",
type=str,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()),
)
parser.add_argument(
"--model_name_or_path",
default="bert-base-cased",
type=str,
help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS),
)
parser.add_argument(
"--task_name",
default="sst-2",
type=str,
help="The name of the task to train selected in the list: " + ", ".join(processors.keys()),
)
parser.add_argument(
"--output_dir",
default="../data/out_cased",
type=str,
help="The output directory where the model predictions and checkpoints will be written.",
)
# Other parameters
parser.add_argument(
"--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name",
)
parser.add_argument(
"--tokenizer_name",
default="",
type=str,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--cache_dir",
default="../data/cache",
type=str,
help="Where do you want to store the pre-trained models downloaded from s3",
)
parser.add_argument(
"--max_seq_length",
default=128,
type=int,
help="The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.",
)
parser.add_argument(
"--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step.",
)
parser.add_argument(
"--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model.",
)
parser.add_argument(
"--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.",
)
parser.add_argument(
"--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument("--learning_rate", default=2e-5, type=float, help="The initial learning rate for Adam.")
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
parser.add_argument(
"--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform.",
)
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
)
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.")
parser.add_argument("--save_steps", type=int, default=500, help="Save checkpoint every X updates steps.")
parser.add_argument(
"--eval_all_checkpoints",
action="store_true",
help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number",
)
parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
parser.add_argument(
"--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory",
)
parser.add_argument(
"--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets",
)
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument(
"--fp16",
action="store_true",
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
)
parser.add_argument(
"--fp16_opt_level",
type=str,
default="O1",
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
"See details at https://nvidia.github.io/apex/amp.html",
)
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
parser.add_argument("--server_ip", type=str, default="", help="For distant debugging.")
parser.add_argument("--server_port", type=str, default="", help="For distant debugging.")
args = parser.parse_args()
args.no_cuda = True
# Setup distant debugging if needed
if args.server_ip and args.server_port:
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
import ptvsd
print("Waiting for debugger attach")
ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
ptvsd.wait_for_attach()
# Setup CUDA, GPU & distributed training
if args.local_rank == -1 or args.no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend="nccl")
args.n_gpu = 1
args.device = device
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.ERROR
)
logger.warning(
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
args.local_rank,
device,
args.n_gpu,
bool(args.local_rank != -1),
args.fp16,
)
# Set seed
set_seed(args)
# Prepare GLUE task
args.task_name = args.task_name.lower()
if args.task_name not in processors:
raise ValueError("Task not found: %s" % (args.task_name))
processor = processors[args.task_name]()
args.output_mode = output_modes[args.task_name]
label_list = processor.get_labels()
num_labels = len(label_list)
# Load pretrained model and tokenizer
if args.local_rank not in [-1, 0]:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
args.model_type = args.model_type.lower()
config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
config = config_class.from_pretrained(
args.config_name if args.config_name else args.model_name_or_path,
num_labels=num_labels,
finetuning_task=args.task_name,
cache_dir=args.cache_dir if args.cache_dir else None,
)
tokenizer = tokenizer_class.from_pretrained(
args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
do_lower_case=args.do_lower_case,
cache_dir=args.cache_dir if args.cache_dir else None,
)
model = model_class.from_pretrained(
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
cache_dir=args.cache_dir if args.cache_dir else None,
)
if args.local_rank == 0:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
model.to(args.device)
logger.info("Evaluation parameters %s", args)
# Evaluation
if args.local_rank in [-1, 0]:
tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
checkpoints = [args.output_dir]
if args.eval_all_checkpoints:
checkpoints = list(
os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
)
logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging
logger.info("Evaluate the following checkpoints: %s", checkpoints)
for checkpoint in checkpoints:
global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
prefix = checkpoint.split("/")[-1] if checkpoint.find("checkpoint") != -1 else ""
model = model_class.from_pretrained(checkpoint)
model.to(args.device)
data_folder = args.data_dir
dev_file_path = os.path.join(data_folder, 'dev.tsv')
preds = []
with open(file_path, encoding='utf8') as f:
d = f.read().strip().split('\n')
for s in d:
j = json.loads(s)
preds += j['pred_style0']
preds = '\n'.join([s + '\t0' for s in preds]) + '\n'
if os.path.exists(data_folder):
shutil.rmtree(data_folder)
os.makedirs(data_folder)
with open(dev_file_path, 'w', encoding='utf8') as f:
f.write(preds)
result = evaluate(args, model, tokenizer, prefix=prefix)
acc0 = result['acc']
preds = []
with open(file_path, encoding='utf8') as f:
d = f.read().strip().split('\n')
for s in d:
j = json.loads(s)
preds += j['pred_style1']
preds = '\n'.join([s + '\t1' for s in preds]) + '\n'
if os.path.exists(data_folder):
shutil.rmtree(data_folder)
os.makedirs(data_folder)
with open(dev_file_path, 'w', encoding='utf8') as f:
f.write(preds)
result = evaluate(args, model, tokenizer, prefix=prefix)
acc1 = result['acc']
print('BERT:', 's0', acc0 * 100, 's1', acc1 * 100, 'mean', (acc0 + acc1) / 2 * 100)
| true | true |
f72a01605237507418ed31df2bec474d55d68fe7 | 1,246 | py | Python | apm/step05/thinker.py | l0k0ms/TrainingEnvironment | f51837cdaf71c6ec41980b8bd1d28275d26a563b | [
"BSD-3-Clause"
] | 6 | 2018-07-27T15:54:49.000Z | 2020-02-08T01:39:05.000Z | apm/step05/thinker.py | l0k0ms/TrainingEnvironment | f51837cdaf71c6ec41980b8bd1d28275d26a563b | [
"BSD-3-Clause"
] | 1 | 2018-10-18T12:20:04.000Z | 2018-12-10T19:50:36.000Z | apm/step05/thinker.py | l0k0ms/TrainingEnvironment | f51837cdaf71c6ec41980b8bd1d28275d26a563b | [
"BSD-3-Clause"
] | 5 | 2018-09-28T11:40:55.000Z | 2021-02-23T11:25:42.000Z | import requests
from flask import Flask, Response, jsonify
from flask import request as flask_request
from flask_caching import Cache
from ddtrace import tracer, patch
from ddtrace.contrib.flask import TraceMiddleware
from bootstrap import create_app
from models import Thought
from time import sleep
patch(redis=True)
app = create_app()
cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_HOST': 'redis'})
cache.init_app(app)
traced_app = TraceMiddleware(app, tracer, service='thinker-microservice', distributed_tracing=True)
# Tracer configuration
tracer.configure(hostname='agent')
@tracer.wrap(name='think')
@cache.memoize(30)
def think(subject):
tracer.current_span().set_tag('subject', subject)
sleep(0.5)
quote = Thought.query.filter_by(subject=subject).first()
if quote is None:
return Thought(quote='Hmmm, that\'s something I\'ll need to think about.',
author='The Machine',
subject=subject)
return quote
@app.route('/')
def think_microservice():
# because we have distributed tracing, don't need to manually grab headers
subject = flask_request.args.get('subject')
thoughts = think(subject)
return jsonify(thoughts.serialize())
| 27.086957 | 99 | 0.724719 | import requests
from flask import Flask, Response, jsonify
from flask import request as flask_request
from flask_caching import Cache
from ddtrace import tracer, patch
from ddtrace.contrib.flask import TraceMiddleware
from bootstrap import create_app
from models import Thought
from time import sleep
patch(redis=True)
app = create_app()
cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_HOST': 'redis'})
cache.init_app(app)
traced_app = TraceMiddleware(app, tracer, service='thinker-microservice', distributed_tracing=True)
tracer.configure(hostname='agent')
@tracer.wrap(name='think')
@cache.memoize(30)
def think(subject):
tracer.current_span().set_tag('subject', subject)
sleep(0.5)
quote = Thought.query.filter_by(subject=subject).first()
if quote is None:
return Thought(quote='Hmmm, that\'s something I\'ll need to think about.',
author='The Machine',
subject=subject)
return quote
@app.route('/')
def think_microservice():
subject = flask_request.args.get('subject')
thoughts = think(subject)
return jsonify(thoughts.serialize())
| true | true |
f72a02cc49ea1d37ac8dfd0596d8c565b17bf8e3 | 8,315 | py | Python | f1tenth-RL/f1tenth-rl/car/car_control.py | SidSong01/Deep_Reinforcement_Learning_on_F1_10th | cd869d52ada91d114fd0a905d47ce2a6982e061e | [
"MIT"
] | null | null | null | f1tenth-RL/f1tenth-rl/car/car_control.py | SidSong01/Deep_Reinforcement_Learning_on_F1_10th | cd869d52ada91d114fd0a905d47ce2a6982e061e | [
"MIT"
] | null | null | null | f1tenth-RL/f1tenth-rl/car/car_control.py | SidSong01/Deep_Reinforcement_Learning_on_F1_10th | cd869d52ada91d114fd0a905d47ce2a6982e061e | [
"MIT"
] | 3 | 2020-12-12T21:31:33.000Z | 2021-03-18T12:40:44.000Z | import rospy
from ackermann_msgs.msg import AckermannDriveStamped
from threading import Thread
import time
import argparse
import numpy as np
try:
from geometry_msgs.msg import PoseStamped
except ImportError:
pass
try:
from car.sensors import Sensors
except ImportError:
from sensors import Sensors
PUBLISHER_WAIT = 0.005
MAX_SPEED_REDUCTION = 8
STEERING_SPEED_REDUCTION = 8
BACKWARD_SPEED_REDUCTION = 8
LIGHTLY_STEERING_REDUCTION = 2.4
BACKWARD_SECONDS = 1.6
MAX_SPEED_REDUCTION_SIM = 3
STEERING_SPEED_REDUCTION_SIM = 3
BACKWARD_SPEED_REDUCTION_SIM = 3
LIGHTLY_STEERING_REDUCTION_SIM = 2.4
BACKWARD_SECONDS_SIM = 1.8
USE_RESET_INSTEAD_OF_BACKWARDS_SIM = False
class Drive():
def __init__(self, sensors, is_simulator=False):
self.is_simulator = is_simulator
if not is_simulator:
topic = "/vesc/high_level/ackermann_cmd_mux/input/nav_0"
max_steering = 0.34
self.max_speed_reduction = MAX_SPEED_REDUCTION
self.steering_speed_reduction = STEERING_SPEED_REDUCTION
self.backward_speed_reduction = BACKWARD_SPEED_REDUCTION
self.lightly_steering_reduction = LIGHTLY_STEERING_REDUCTION
self.backward_seconds = BACKWARD_SECONDS
else:
topic = "/drive"
max_steering = 0.4189
self.max_speed_reduction = MAX_SPEED_REDUCTION_SIM
self.steering_speed_reduction = STEERING_SPEED_REDUCTION_SIM
self.backward_speed_reduction = BACKWARD_SPEED_REDUCTION_SIM
self.lightly_steering_reduction = LIGHTLY_STEERING_REDUCTION_SIM
self.backward_seconds = BACKWARD_SECONDS_SIM
self.reset_publisher = rospy.Publisher("/pose", PoseStamped, queue_size=0)
self.max_speed = rospy.get_param("max_speed", 5)
# self.wheel_base = rospy.get_param("wheel_base")
self.max_steering = rospy.get_param("max_steering", max_steering)
self.drive_publisher = rospy.Publisher(topic, AckermannDriveStamped, queue_size=0)
self.sensors = sensors
self.stop()
process = Thread(target=self.drive_command_runner)
process.daemon = True
process.start()
print("max_speed: ", self.max_speed, ", max_steering: ", self.max_steering)
def forward(self):
steer = 0
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def backward(self):
self.send_drive_command(-self.max_speed/self.backward_speed_reduction, 0)
def stop(self):
self.send_drive_command(0, 0)
########################################################
def right_1(self):
steer = -self.max_steering*1/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def right_2(self):
steer = -self.max_steering*2/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def right_3(self):
steer = -self.max_steering*3/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def right_4(self):
steer = -self.max_steering*4/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def right_5(self):
steer = -self.max_steering*5/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def right_6(self):
steer = -self.max_steering*6/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def right_7(self):
steer = -self.max_steering
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
####################################################################
def left_1(self):
steer = self.max_steering*1/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def left_2(self):
steer = self.max_steering*2/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def left_3(self):
steer = self.max_steering*3/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def left_4(self):
steer = self.max_steering*4/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def left_5(self):
steer = self.max_steering*5/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def left_6(self):
steer = self.max_steering*6/7
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def left_7(self):
steer = self.max_steering
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
###########################################################
# def lightly_right(self):
# self.send_drive_command(self.max_speed/self.steering_speed_reduction, -self.max_steering/self.lightly_steering_reduction)
# def lightly_left(self):
# self.send_drive_command(self.max_speed/self.steering_speed_reduction, self.max_steering/self.lightly_steering_reduction)
def send_drive_command(self, speed, steering_angle):
ack_msg = AckermannDriveStamped()
ack_msg.drive.speed = speed
ack_msg.drive.steering_angle = steering_angle
self.ack_msg = ack_msg
def drive_command_runner(self):
while True:
self.drive_publisher.publish(self.ack_msg)
time.sleep(PUBLISHER_WAIT)
def backward_until_obstacle(self):
if USE_RESET_INSTEAD_OF_BACKWARDS_SIM and self.is_simulator:
self.reset_simulator()
else:
self.backward()
start = time.time()
while not self.sensors.back_obstacle() and time.time() - start < self.backward_seconds:
time.sleep(0.01)
self.stop()
time.sleep(0.1)
def reset_simulator(self):
if self.is_simulator:
self.reset_publisher.publish(PoseStamped())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--simulator", action='store_true', help="to set the use of the simulator")
args = parser.parse_args()
run_seconds = 0.3
rospy.init_node('drive_test')
drive = Drive(args.simulator)
while True:
print("Write command")
cmd = input()
start = time.time()
if cmd == "w":
while time.time() - start < run_seconds:
drive.forward()
if cmd == "s":
while time.time() - start < run_seconds:
drive.backward()
if cmd == "a":
while time.time() - start < run_seconds:
drive.lightly_left()
if cmd == "d":
while time.time() - start < run_seconds:
drive.lightly_right()
if cmd == "aa":
while time.time() - start < run_seconds:
drive.left()
if cmd == "dd":
while time.time() - start < run_seconds:
drive.right()
if cmd == " ":
while time.time() - start < run_seconds:
drive.stop()
if cmd == "buo":
drive.backward_until_obstacle()
if cmd == "q":
exit()
| 35.233051 | 131 | 0.626218 | import rospy
from ackermann_msgs.msg import AckermannDriveStamped
from threading import Thread
import time
import argparse
import numpy as np
try:
from geometry_msgs.msg import PoseStamped
except ImportError:
pass
try:
from car.sensors import Sensors
except ImportError:
from sensors import Sensors
PUBLISHER_WAIT = 0.005
MAX_SPEED_REDUCTION = 8
STEERING_SPEED_REDUCTION = 8
BACKWARD_SPEED_REDUCTION = 8
LIGHTLY_STEERING_REDUCTION = 2.4
BACKWARD_SECONDS = 1.6
MAX_SPEED_REDUCTION_SIM = 3
STEERING_SPEED_REDUCTION_SIM = 3
BACKWARD_SPEED_REDUCTION_SIM = 3
LIGHTLY_STEERING_REDUCTION_SIM = 2.4
BACKWARD_SECONDS_SIM = 1.8
USE_RESET_INSTEAD_OF_BACKWARDS_SIM = False
class Drive():
def __init__(self, sensors, is_simulator=False):
self.is_simulator = is_simulator
if not is_simulator:
topic = "/vesc/high_level/ackermann_cmd_mux/input/nav_0"
max_steering = 0.34
self.max_speed_reduction = MAX_SPEED_REDUCTION
self.steering_speed_reduction = STEERING_SPEED_REDUCTION
self.backward_speed_reduction = BACKWARD_SPEED_REDUCTION
self.lightly_steering_reduction = LIGHTLY_STEERING_REDUCTION
self.backward_seconds = BACKWARD_SECONDS
else:
topic = "/drive"
max_steering = 0.4189
self.max_speed_reduction = MAX_SPEED_REDUCTION_SIM
self.steering_speed_reduction = STEERING_SPEED_REDUCTION_SIM
self.backward_speed_reduction = BACKWARD_SPEED_REDUCTION_SIM
self.lightly_steering_reduction = LIGHTLY_STEERING_REDUCTION_SIM
self.backward_seconds = BACKWARD_SECONDS_SIM
self.reset_publisher = rospy.Publisher("/pose", PoseStamped, queue_size=0)
self.max_speed = rospy.get_param("max_speed", 5)
self.max_steering = rospy.get_param("max_steering", max_steering)
self.drive_publisher = rospy.Publisher(topic, AckermannDriveStamped, queue_size=0)
self.sensors = sensors
self.stop()
process = Thread(target=self.drive_command_runner)
process.daemon = True
process.start()
print("max_speed: ", self.max_speed, ", max_steering: ", self.max_steering)
def forward(self):
steer = 0
vel = (self.max_speed/self.max_speed_reduction) - (6.64853667702) * (steer)**2
self.send_drive_command(vel, steer)
return steer
def backward(self):
self.send_drive_command(-self.max_speed/self.backward_speed_reduction, 0)
def stop(self):
self.send_drive_command(0, 0)
| true | true |
f72a03452c1744c5931873010c359c8d1fbc0c34 | 2,940 | py | Python | oboe/Note.py | dapatil211/oboe | cd7047c8d71b1a488f7f732cab4beadfe82b26b7 | [
"MIT"
] | 89 | 2020-08-17T23:20:12.000Z | 2021-01-13T15:12:43.000Z | oboe/Note.py | dapatil211/oboe | cd7047c8d71b1a488f7f732cab4beadfe82b26b7 | [
"MIT"
] | 23 | 2020-10-01T00:51:29.000Z | 2021-01-15T10:44:06.000Z | oboe/Note.py | dapatil211/oboe | cd7047c8d71b1a488f7f732cab4beadfe82b26b7 | [
"MIT"
] | 14 | 2020-09-21T17:55:15.000Z | 2021-01-03T20:44:21.000Z | import os
import sys
import regex as re
from oboe.utils import slug_case, md_link, render_markdown, find_tags
from oboe.format import (
format_tags, format_blockrefs, format_highlights, format_links, format_code_blocks
)
from oboe.Link import Link
from oboe import LOG
from oboe import GLOBAL
import copy
class Note:
def __init__(self, path):
self.path = path
self.filename = os.path.split(path)[-1]
self.title = self.filename.replace(".md", "")
self.filename_html = slug_case(self.title) + ".html"
self.out_path = os.path.join(GLOBAL.OUTPUT_DIR, os.path.relpath(path, GLOBAL.VAULT_ROOT))
self.out_path = os.path.join(os.path.split(self.out_path)[0], self.filename_html)
self.link = Link(self.title)
with open(path, encoding="utf8") as f:
self.content = f.read()
self.backlink_html = ""
self.links = self.links_in_file()
self.tags = find_tags(self.content)
self.convert_obsidian_syntax()
def links_in_file(self):
"""Returns a list of all links in the note."""
matches = re.finditer(r"(!)?\[{2}(.*?)\]{2}", self.content)
links = []
for match in matches:
link = Link(match.group(2), embed=match.group(1))
links.append(link)
return links
def find_backlinks(self, others):
"""Returns a list of Link objects linking to all the notes in 'others' that reference self"""
backlinks = []
for other in others:
if self == other: continue
if self.link in other.links:
backlinks.append(other.link)
backlinks = sorted(backlinks, key=lambda link: link.path)
return backlinks
def convert_obsidian_syntax(self):
"""Converts Obsidian syntax into Markdown."""
self.content = format_code_blocks(self.content)
self.content = format_links(self.content, self.links)
self.content = format_tags(self.content, self.tags)
self.content = format_blockrefs(self.content)
self.content = format_highlights(self.content)
def html(self, pandoc=False):
"""Returns the note formatted as HTML. Will use markdown2 as default, with the option of pandoc (WIP)"""
# LOG.debug(f"Converting {self.title} into HTML...")
if pandoc:
# Still WIP
import pypandoc
filters = ['pandoc-xnos']
args = []
html = pypandoc.convert_text(self.content, 'html', format='md', filters=filters, extra_args=args)
else:
html = render_markdown(self.content)
# Wrapping converted markdown in a div for styling
html = f"<div id=\"content\">{html}</div>"
# LOG.debug(f"{self.title} converted into HTML and placed inside div with id=\"content\"")
return html
def __eq__(self, other):
return self.path == other.path
| 31.956522 | 112 | 0.626531 | import os
import sys
import regex as re
from oboe.utils import slug_case, md_link, render_markdown, find_tags
from oboe.format import (
format_tags, format_blockrefs, format_highlights, format_links, format_code_blocks
)
from oboe.Link import Link
from oboe import LOG
from oboe import GLOBAL
import copy
class Note:
def __init__(self, path):
self.path = path
self.filename = os.path.split(path)[-1]
self.title = self.filename.replace(".md", "")
self.filename_html = slug_case(self.title) + ".html"
self.out_path = os.path.join(GLOBAL.OUTPUT_DIR, os.path.relpath(path, GLOBAL.VAULT_ROOT))
self.out_path = os.path.join(os.path.split(self.out_path)[0], self.filename_html)
self.link = Link(self.title)
with open(path, encoding="utf8") as f:
self.content = f.read()
self.backlink_html = ""
self.links = self.links_in_file()
self.tags = find_tags(self.content)
self.convert_obsidian_syntax()
def links_in_file(self):
matches = re.finditer(r"(!)?\[{2}(.*?)\]{2}", self.content)
links = []
for match in matches:
link = Link(match.group(2), embed=match.group(1))
links.append(link)
return links
def find_backlinks(self, others):
backlinks = []
for other in others:
if self == other: continue
if self.link in other.links:
backlinks.append(other.link)
backlinks = sorted(backlinks, key=lambda link: link.path)
return backlinks
def convert_obsidian_syntax(self):
self.content = format_code_blocks(self.content)
self.content = format_links(self.content, self.links)
self.content = format_tags(self.content, self.tags)
self.content = format_blockrefs(self.content)
self.content = format_highlights(self.content)
def html(self, pandoc=False):
if pandoc:
import pypandoc
filters = ['pandoc-xnos']
args = []
html = pypandoc.convert_text(self.content, 'html', format='md', filters=filters, extra_args=args)
else:
html = render_markdown(self.content)
html = f"<div id=\"content\">{html}</div>"
return html
def __eq__(self, other):
return self.path == other.path
| true | true |
f72a0347ed4a8c5b147fbe4acb6b6a3b266add9d | 52,525 | py | Python | IRIS_data_download/IRIS_download_support/obspy/clients/fdsn/mass_downloader/download_helpers.py | earthinversion/Fnet_IRIS_data_automated_download | 09a6e0c992662feac95744935e038d1c68539fa1 | [
"MIT"
] | 2 | 2020-03-05T01:03:01.000Z | 2020-12-17T05:04:07.000Z | IRIS_data_download/IRIS_download_support/obspy/clients/fdsn/mass_downloader/download_helpers.py | earthinversion/Fnet_IRIS_data_automated_download | 09a6e0c992662feac95744935e038d1c68539fa1 | [
"MIT"
] | 4 | 2021-03-31T19:25:55.000Z | 2021-12-13T20:32:46.000Z | IRIS_data_download/IRIS_download_support/obspy/clients/fdsn/mass_downloader/download_helpers.py | earthinversion/Fnet_IRIS_data_automated_download | 09a6e0c992662feac95744935e038d1c68539fa1 | [
"MIT"
] | 2 | 2020-09-08T19:33:40.000Z | 2021-04-05T09:47:50.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Helpers for the mass downloader.
Intended to simplify and stabilize the logic of the mass downloader and make
it understandable in the first place.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014-2015
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
import collections
import copy
import fnmatch
import itertools
import sys
from multiprocessing.pool import ThreadPool
import os
import time
import timeit
if sys.version_info.major == 2:
from itertools import ifilterfalse as filterfalse
else:
from itertools import filterfalse
import numpy as np
from lxml.etree import XMLSyntaxError
import obspy
from obspy.core.util import Enum
from . import utils
# The current status of an entity.
STATUS = Enum(["none", "needs_downloading", "downloaded", "ignore", "exists",
"download_failed", "download_rejected",
"download_partially_failed"])
class _SlotsEqualityComparisionObject(object):
"""
Helper object with an equality comparision method simply comparing all
slotted attributes.
"""
__slots__ = []
def __eq__(self, other):
if type(self) != type(other):
return False
return all([getattr(self, _i) == getattr(other, _i)
for _i in self.__slots__])
class Station(_SlotsEqualityComparisionObject):
"""
Object representing a seismic station within the download helper classes.
It knows the coordinates of the station to perform the filtering,
its channels and the filename and status of the StationXML files.
:param network: The network code.
:type network: str
:param station: The station code.
:type station: str
:param latitude: The latitude of the station.
:type latitude: float
:param longitude: The longitude of the station.
:type longitude: float
:param channels: The channels of the station.
:type channels: list of :class:`~.Channel` objects
:param stationxml_filename: The filename of the StationXML file.
:type stationxml_filename: str
:param stationxml_status: The current status of the station.
:type stationxml_filename:
:class:`~.STATUS`
"""
__slots__ = ["network", "station", "latitude", "longitude", "channels",
"_stationxml_filename", "want_station_information",
"miss_station_information", "have_station_information",
"stationxml_status"]
def __init__(self, network, station, latitude, longitude, channels,
stationxml_filename=None, stationxml_status=None):
# Station attributes.
self.network = network
self.station = station
self.latitude = latitude
self.longitude = longitude
self.channels = channels
# Station information settings.
self.stationxml_filename = stationxml_filename
self.stationxml_status = stationxml_status and STATUS.NONE
# Internally keep track of which channels and time interval want
# station information, which miss station information and which
# already have some. want_station_information should always be the
# union of miss and have.
self.want_station_information = {}
self.miss_station_information = {}
self.have_station_information = {}
@property
def has_existing_or_downloaded_time_intervals(self):
"""
Returns true if any of the station's time intervals have status
"DOWNLOADED" or "EXISTS". Otherwise it returns False meaning it does
not have to be considered anymore.
"""
status = set()
for chan in self.channels:
for ti in chan.intervals:
status.add(ti.status)
if STATUS.EXISTS in status or STATUS.DOWNLOADED in status:
return True
return False
@property
def has_existing_time_intervals(self):
"""
Returns True if any of the station's time intervals already exist.
"""
for chan in self.channels:
for ti in chan.intervals:
if ti.status == STATUS.EXISTS:
return True
return False
def remove_files(self, logger, reason):
"""
Delete all files under it. Only delete stuff that actually has been
downloaded!
"""
for chan in self.channels:
for ti in chan.intervals:
if ti.status != STATUS.DOWNLOADED or not ti.filename:
continue
if os.path.exists(ti.filename):
logger.info("Deleting MiniSEED file '%s'. Reason: %s" % (
ti.filename, reason))
utils.safe_delete(ti.filename)
if self.stationxml_status == STATUS.DOWNLOADED and \
self.stationxml_filename and \
os.path.exists(self.stationxml_filename):
logger.info("Deleting StationXMl file '%s'. Reason: %s" %
(self.stationxml_filename, reason))
utils.safe_delete(self.stationxml_filename)
@property
def stationxml_filename(self):
return self._stationxml_filename
@stationxml_filename.setter
def stationxml_filename(self, value):
"""
Setter creating the directory for the file if it does not already
exist.
"""
self._stationxml_filename = value
if not value:
return
dirname = os.path.dirname(value)
if not os.path.exists(dirname):
os.makedirs(dirname)
@property
def temporal_bounds(self):
"""
Return the temporal bounds for the station.
"""
starttimes = []
endtimes = []
for channel in self.channels:
s, e = channel.temporal_bounds
starttimes.append(s)
endtimes.append(e)
return min(starttimes), max(endtimes)
def __str__(self):
channels = "\n".join(str(i) for i in self.channels)
channels = "\n\t".join(channels.splitlines())
return (
"Station '{network}.{station}' [Lat: {lat:.2f}, Lng: {lng:.2f}]\n"
"\t-> Filename: {filename} ({status})\n"
"\t-> Wants station information for channels: {want}\n"
"\t-> Has station information for channels: {has}\n"
"\t-> Misses station information for channels: {miss}\n"
"\t{channels}"
).format(
network=self.network,
station=self.station,
lat=self.latitude,
lng=self.longitude,
filename=self.stationxml_filename,
status="exists" if (self.stationxml_filename and os.path.exists(
self.stationxml_filename)) else "does not yet exist",
want=", ".join(["%s.%s" % (_i[0], _i[1]) for _i in
self.want_station_information.keys()]),
has=", ".join(["%s.%s" % (_i[0], _i[1]) for _i in
self.have_station_information.keys()]),
miss=", ".join(["%s.%s" % (_i[0], _i[1]) for _i in
self.miss_station_information.keys()]),
channels=channels)
def prepare_stationxml_download(self, stationxml_storage, logger):
"""
Figure out what to download.
:param stationxml_storage:
"""
# Determine what channels actually want to have station information.
# This will be a tuple of location code, channel code, starttime,
# and endtime.
self.want_station_information = {}
for channel in self.channels:
if channel.needs_station_file is False:
continue
self.want_station_information[
(channel.location, channel.channel)] = channel.temporal_bounds
# No channel has any data, thus nothing will happen.
if not self.want_station_information:
self.stationxml_status = STATUS.NONE
return
# Only those channels that now actually want station information
# will be treated in the following.
s, e = self.temporal_bounds
storage = utils.get_stationxml_filename(
stationxml_storage, self.network, self.station,
list(self.want_station_information.keys()),
starttime=s, endtime=e)
# The simplest case. The function returns a string. Now two things
# can happen.
if isinstance(storage, (str, bytes)):
filename = storage
self.stationxml_filename = filename
# 1. The file does not yet exist. Thus all channels must be
# downloaded.
if not os.path.exists(filename):
self.miss_station_information = \
copy.deepcopy(self.want_station_information)
self.have_station_information = {}
self.stationxml_status = STATUS.NEEDS_DOWNLOADING
return
# 2. The file does exist. It will be parsed. If it contains ALL
# necessary information, nothing will happen. Otherwise it will
# be overwritten.
else:
info = utils.get_stationxml_contents(filename)
for c_id, times in self.want_station_information.items():
# Get the temporal range of information in the file.
c_info = [_i for _i in info if
_i.network == self.network and
_i.station == self.station and
_i.location == c_id[0] and
_i.channel == c_id[1]]
if not c_info:
break
starttime = min([_i.starttime for _i in c_info])
endtime = max([_i.endtime for _i in c_info])
if starttime > times[0] or endtime < times[1]:
break
# All good if no break is called.
else:
self.have_station_information = \
copy.deepcopy(self.want_station_information)
self.miss_station_information = {}
self.stationxml_status = STATUS.EXISTS
return
# Otherwise everything will be downloaded.
self.miss_station_information = \
copy.deepcopy(self.want_station_information)
self.have_station_information = {}
self.stationxml_status = STATUS.NEEDS_DOWNLOADING
return
# The other possibility is that a dictionary is returned.
else:
# The types are already checked by the get_stationxml_filename()
# function.
missing_channels = storage["missing_channels"]
available_channels = storage["available_channels"]
# Get the channels wanting station information and filter them.
channels_wanting_station_information = copy.deepcopy(
self.want_station_information
)
# Figure out what channels are missing and will be downloaded.
self.miss_station_information = {}
for channel in missing_channels:
if channel not in channels_wanting_station_information:
continue
self.miss_station_information[channel] = \
channels_wanting_station_information[channel]
# Same thing but with the already available channels.
self.have_station_information = {}
for channel in available_channels:
if channel not in channels_wanting_station_information:
continue
self.have_station_information[channel] = \
channels_wanting_station_information[channel]
self.stationxml_filename = storage["filename"]
# Raise a warning if something is missing, but do not raise an
# exception or halt the program at this point.
have_channels = set(self.have_station_information.keys())
miss_channels = set(self.miss_station_information.keys())
want_channels = set(self.want_station_information.keys())
if have_channels.union(miss_channels) != want_channels:
logger.warning(
"The custom `stationxml_storage` did not return "
"information about channels %s" %
str(want_channels.difference(have_channels.union(
miss_channels))))
if self.miss_station_information:
self.stationxml_status = STATUS.NEEDS_DOWNLOADING
elif not self.miss_station_information and \
self.have_station_information:
self.stationxml_status = STATUS.EXISTS
else:
self.stationxml_status = STATUS.IGNORE
def prepare_mseed_download(self, mseed_storage):
"""
Loop through all channels of the station and distribute filenames
and the current status of the channel.
A MiniSEED interval will be ignored, if the `mseed_storage` function
returns `True`.
Possible statuses after method execution are IGNORE, EXISTS, and
NEEDS_DOWNLOADING.
:param mseed_storage:
"""
for channel in self.channels:
for interval in channel.intervals:
interval.filename = utils.get_mseed_filename(
mseed_storage, self.network, self.station,
channel.location, channel.channel, interval.start,
interval.end)
if interval.filename is True:
interval.status = STATUS.IGNORE
elif os.path.exists(interval.filename):
interval.status = STATUS.EXISTS
else:
if not os.path.exists(os.path.dirname(interval.filename)):
os.makedirs(os.path.dirname(interval.filename))
interval.status = STATUS.NEEDS_DOWNLOADING
def sanitize_downloads(self, logger):
"""
Should be run after the MiniSEED and StationXML downloads finished.
It will make sure that every MiniSEED file also has a corresponding
StationXML file.
It will delete MiniSEED files but never a StationXML file. The logic
of the download helpers does not allow for a StationXML file with no
data.
"""
from obspy.io.mseed.util import get_start_and_end_time
# All or nothing for each channel.
for id in self.miss_station_information.keys():
logger.warning("Station information could not be downloaded for "
"%s.%s.%s.%s. MiniSEED files outside of the "
"station information period "
"will be deleted!" % (
self.network, self.station, id[0], id[1]))
channel = [_i for _i in self.channels if
(_i.location, _i.channel) == id][0]
for time_interval in channel.intervals:
# Check that file exists before proceeding
if not time_interval.filename or \
not os.path.isfile(time_interval.filename):
continue
# Check that the time_interval.start and end are correct!
time_interval.start, time_interval.end = \
get_start_and_end_time(time_interval.filename)
# Only delete downloaded things!
if time_interval.status == STATUS.DOWNLOADED:
# Only delete if the station data are actually missing
# for this time
miss_start, miss_end = self.miss_station_information[id]
if miss_start <= time_interval.start <= miss_end and \
miss_start <= time_interval.end <= miss_end:
utils.safe_delete(time_interval.filename)
time_interval.status = STATUS.DOWNLOAD_REJECTED
class Channel(_SlotsEqualityComparisionObject):
"""
Object representing a Channel. Each time interval should end up in one
MiniSEED file.
"""
__slots__ = ["location", "channel", "intervals"]
def __init__(self, location, channel, intervals):
self.location = location
self.channel = channel
self.intervals = intervals
@property
def needs_station_file(self):
"""
Determine if the channel requires any station information.
As soon as the status of at least one interval is either
``DOWNLOADED`` or ``EXISTS`` the whole channel will be thought of as
requiring station information. This does not yet mean that station
information will be downloaded. That is decided at a later stage.
"""
status = set([_i.status for _i in self.intervals])
if STATUS.DOWNLOADED in status or STATUS.EXISTS in status:
return True
return False
@property
def temporal_bounds(self):
"""
Returns a tuple of the minimum start time and the maximum end time.
"""
return (min([_i.start for _i in self.intervals]),
max([_i.end for _i in self.intervals]))
def __str__(self):
return "Channel '{location}.{channel}':\n\t{intervals}".format(
location=self.location, channel=self.channel,
intervals="\n\t".join([str(i) for i in self.intervals]))
class TimeInterval(_SlotsEqualityComparisionObject):
"""
Simple object representing a time interval of a channel.
It knows the temporal bounds of the interval, the (desired) filename,
and the current status of the interval.
:param start: The start of the interval.
:type start: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param end: The end of the interval.
:type end: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param filename: The filename of the interval.
:type filename: str
:param status: The status of the time interval.
:param status: :class:`~.STATUS`
"""
__slots__ = ["start", "end", "filename", "status"]
def __init__(self, start, end, filename=None, status=None):
self.start = start
self.end = end
self.filename = filename
self.status = status if status is not None else STATUS.NONE
def __repr__(self):
return "TimeInterval(start={start}, end={end}, filename={filename}, " \
"status='{status}')".format(
start=repr(self.start),
end=repr(self.end),
filename="'%s'" % self.filename
if self.filename is not None else "None",
status=str(self.status))
class ClientDownloadHelper(object):
"""
:type client: :class:`obspy.fdsn.client.Client`
:param client: An initialized FDSN client.
:type client_name: str
:param client_name: The name of the client. Only used for logging.
:type restrictions: :class:`~.restrictions.Restrictions`
:param restrictions: The non-domain related restrictions for the query.
:type domain: :class:`~.domain.Domain` subclass
:param domain: The domain definition.
:param mseed_storage: The MiniSEED storage settings.
:param stationxml_storage: The StationXML storage settings.
:param logger: An active logger instance.
"""
def __init__(self, client, client_name, restrictions, domain,
mseed_storage, stationxml_storage, logger):
self.client = client
self.client_name = client_name
self.restrictions = restrictions
self.domain = domain
self.mseed_storage = mseed_storage
self.stationxml_storage = stationxml_storage
self.logger = logger
self.stations = {}
self.is_availability_reliable = None
def __bool__(self):
return bool(len(self))
def __str__(self):
avail_map = {
None: "Unknown reliability of availability information",
True: "Reliable availability information",
False: "Non-reliable availability information"
}
reliability = avail_map[self.is_availability_reliable]
return (
"ClientDownloadHelper object for client '{client}' ({url})\n"
"-> {reliability}\n"
"-> Manages {station_count} stations.\n{stations}").format(
client=self.client_name,
url=self.client.base_url,
reliability=reliability,
station_count=len(self),
stations="\n".join([str(_i) for _i in self.stations.values()]))
def __len__(self):
return len(self.stations)
def prepare_mseed_download(self):
"""
Prepare each Station for the MiniSEED downloading stage.
This will distribute filenames and identify files that require
downloading.
"""
for station in self.stations.values():
station.prepare_mseed_download(mseed_storage=self.mseed_storage)
def filter_stations_based_on_minimum_distance(
self, existing_client_dl_helpers):
"""
Removes stations until all stations have a certain minimum distance to
each other.
Returns the rejected stations which is mainly useful for testing.
:param existing_client_dl_helpers: Instances of already existing
client download helpers.
:type existing_client_dl_helpers: list of
:class:`~.ClientDownloadHelper`
"""
if not self.restrictions.minimum_interstation_distance_in_m:
# No rejected stations.
return []
# Create a sorted copy that will be used in the following. Make it
# more deterministic by sorting the stations based on the id.
stations = copy.copy(list(self.stations.values()))
stations = sorted(stations, key=lambda x: (x.network, x.station))
existing_stations = []
for dlh in existing_client_dl_helpers:
existing_stations.extend(list(dlh.stations.values()))
remaining_stations = []
rejected_stations = []
# There are essentially two possibilities. If no station exists yet,
# it will choose the largest subset of stations satisfying the
# minimum inter-station distance constraint.
if not existing_stations:
# Build k-d-tree and query for the neighbours of each point within
# the minimum distance.
kd_tree = utils.SphericalNearestNeighbour(stations)
nns = kd_tree.query_pairs(
self.restrictions.minimum_interstation_distance_in_m)
indexes_to_remove = []
# Keep removing the station with the most pairs until no pairs are
# left.
while nns:
most_common = collections.Counter(
itertools.chain.from_iterable(nns)).most_common()[0][0]
indexes_to_remove.append(most_common)
nns = list(filterfalse(lambda x: most_common in x, nns))
# Remove these indices this results in a set of stations we wish to
# keep.
new_remaining_stations = [_i[1] for _i in enumerate(stations)
if _i[0] not in indexes_to_remove]
new_rejected_stations = [_i[1] for _i in enumerate(stations)
if _i[0] in indexes_to_remove]
# Station objects are not hashable thus we have to go the long
# route.
for st in new_remaining_stations:
if st not in remaining_stations:
remaining_stations.append(st)
for st in new_rejected_stations:
if st not in rejected_stations:
rejected_stations.append(st)
# Otherwise it will add new stations approximating a Poisson disk
# distribution.
else:
while stations:
# kd-tree with all existing_stations
existing_kd_tree = utils.SphericalNearestNeighbour(
existing_stations)
# Now we have to get the distance to the closest existing
# station for all new stations.
distances = np.ma.array(existing_kd_tree.query(stations)[0])
if np.isinf(distances[0]):
break
distances.mask = False
# Step one is to get rid of all stations that are closer
# than the minimum distance to any existing station.
remove = np.where(
distances <
self.restrictions.minimum_interstation_distance_in_m)[0]
rejected_stations.extend([stations[_i] for _i in remove])
keep = np.where(
distances >=
self.restrictions.minimum_interstation_distance_in_m)[0]
distances.mask[remove] = True
if len(keep):
# Station with the largest distance to next closer station.
largest = np.argmax(distances)
remaining_stations.append(stations[largest])
existing_stations.append(stations[largest])
# Add all rejected stations here.
stations = [stations[_i] for _i in keep if _i != largest]
else:
stations = []
# Now actually delete the files and everything of the rejected
# stations.
for station in rejected_stations:
station.remove_files(logger=self.logger,
reason="Minimum distance filtering.")
self.stations = {}
for station in remaining_stations:
self.stations[(station.network, station.station)] = station
# Return the rejected stations.
return {(_i.network, _i.station): _i for _i in rejected_stations}
def prepare_stationxml_download(self):
"""
Prepare each Station for the StationXML downloading stage.
This will distribute filenames and identify files that require
downloading.
"""
for station in self.stations.values():
station.prepare_stationxml_download(
stationxml_storage=self.stationxml_storage,
logger=self.logger)
def download_stationxml(self, threads=3):
"""
Actually download the StationXML files.
:param threads: Limits the maximum number of threads for the client.
"""
def star_download_station(args):
"""
Maps arguments to the utils.download_stationxml() function.
:param args: The to-be mapped arguments.
"""
try:
ret_val = utils.download_stationxml(*args, logger=self.logger)
except utils.ERRORS as e:
self.logger.error(str(e))
return None
return ret_val
# Build up everything we want to download.
arguments = []
for station in self.stations.values():
if not station.miss_station_information:
continue
s, e = station.temporal_bounds
if self.restrictions.station_starttime:
s = self.restrictions.station_starttime
if self.restrictions.station_endtime:
e = self.restrictions.station_endtime
bulk = [(station.network, station.station, channel.location,
channel.channel, s, e) for channel in station.channels]
arguments.append((self.client, self.client_name, bulk,
station.stationxml_filename))
if not arguments:
self.logger.info("Client '%s' - No station information to "
"download." % self.client_name)
return
# Download it.
s_time = timeit.default_timer()
pool = ThreadPool(min(threads, len(arguments)))
results = pool.map(star_download_station, arguments)
pool.close()
e_time = timeit.default_timer()
results = [_i for _i in results if _i is not None]
# Check it.
filecount = 0
download_size = 0
# Update the station structures. Loop over each returned file.
for s_id, filename in results:
filecount += 1
station = self.stations[s_id]
size = os.path.getsize(filename)
download_size += size
# Extract information about that file.
try:
info = utils.get_stationxml_contents(filename)
# Sometimes some services choose to not return XML files - guard
# against it and just delete the file. At subsequent runs the
# mass downloader will attempt to download it again.
except XMLSyntaxError:
self.logger.info(
"Client '%s' - File %s is not an XML file - it will be "
"deleted." % (self.client_name, filename))
utils.safe_delete(filename)
continue
still_missing = {}
# Make sure all missing information has been downloaded by
# looping over each channel of the station that originally
# requested to be downloaded.
for c_id, times in station.miss_station_information.items():
# Get the temporal range of information in the file.
c_info = [_i for _i in info if
_i.network == station.network and
_i.station == station.station and
_i.location == c_id[0] and
_i.channel == c_id[1]]
if not c_info:
continue
starttime = min([_i.starttime for _i in c_info])
endtime = max([_i.endtime for _i in c_info])
if starttime > times[0] or endtime < times[1]:
# Cope with case that not full day of station info missing
if starttime < times[1]:
still_missing[c_id] = (times[0], starttime)
station.have_station_information[c_id] = (starttime,
times[1])
elif endtime > times[0]:
still_missing[c_id] = (endtime, times[1])
station.have_station_information[c_id] = (times[0],
endtime)
else:
still_missing[c_id] = times
continue
station.have_station_information[c_id] = times
station.miss_station_information = still_missing
if still_missing:
station.stationxml_status = STATUS.DOWNLOAD_PARTIALLY_FAILED
else:
station.stationxml_status = STATUS.DOWNLOADED
# Now loop over all stations and set the status of the ones that
# still need downloading to download failed.
for station in self.stations.values():
if station.stationxml_status == STATUS.NEEDS_DOWNLOADING:
station.stationxml_status = STATUS.DOWNLOAD_FAILED
self.logger.info("Client '%s' - Downloaded %i station files [%.1f MB] "
"in %.1f seconds [%.2f KB/sec]." % (
self.client_name, filecount,
download_size / 1024.0 ** 2,
e_time - s_time,
(download_size / 1024.0) / (e_time - s_time)))
def download_mseed(self, chunk_size_in_mb=25, threads_per_client=3):
"""
Actually download MiniSEED data.
:param chunk_size_in_mb: Attempt to download data in chunks of this
size.
:param threads_per_client: Threads to launch per client. 3 seems to
be a value in agreement with some data centers.
"""
# Estimate the download size to have equally sized chunks.
channel_sampling_rate = {
"F": 5000, "G": 5000, "D": 1000, "C": 1000, "E": 250, "S": 80,
"H": 250, "B": 80, "M": 10, "L": 1, "V": 0.1, "U": 0.01,
"R": 0.001, "P": 0.0001, "T": 0.00001, "Q": 0.000001, "A": 5000,
"O": 5000}
# Split into chunks of about equal size in terms of filesize.
chunks = []
chunks_curr = []
curr_chunks_mb = 0
# Don't request more than 50 chunks at once to not choke the servers.
max_chunk_length = 50
counter = collections.Counter()
# Keep track of attempted downloads.
for sta in self.stations.values():
for cha in sta.channels:
# The band code is used to estimate the sampling rate of the
# data to be downloaded.
band_code = cha.channel[0].upper()
try:
sr = channel_sampling_rate[band_code]
except KeyError:
# Generic sampling rate for exotic band codes.
sr = 1.0
for interval in cha.intervals:
counter[interval.status] += 1
# Only take those time intervals that actually require
# some downloading.
if interval.status != STATUS.NEEDS_DOWNLOADING:
continue
chunks_curr.append((
sta.network, sta.station, cha.location, cha.channel,
interval.start, interval.end, interval.filename))
# Assume that each sample needs 4 byte, STEIM
# compression reduces size to about a third.
# chunk size is in MB
duration = interval.end - interval.start
curr_chunks_mb += \
sr * duration * 4.0 / 3.0 / 1024.0 / 1024.0
if curr_chunks_mb >= chunk_size_in_mb or \
len(chunks_curr) >= max_chunk_length:
chunks.append(chunks_curr)
chunks_curr = []
curr_chunks_mb = 0
if chunks_curr:
chunks.append(chunks_curr)
keys = sorted(counter.keys())
for key in keys:
self.logger.info(
"Client '%s' - Status for %i time intervals/channels before "
"downloading: %s" % (self.client_name, counter[key],
key.upper()))
if not chunks:
return
def star_download_mseed(args):
"""
Star maps the arguments to the
utils.download_and_split_mseed_bulk() function.
:param args: The arguments to be passed.
"""
try:
ret_val = utils.download_and_split_mseed_bulk(
*args, logger=self.logger)
except utils.ERRORS as e:
msg = ("Client '%s' - " % args[1]) + str(e)
if "no data available" in msg.lower():
self.logger.info(msg.split("Detailed response")[0].strip())
else:
self.logger.error(msg)
return []
return ret_val
pool = ThreadPool(min(threads_per_client, len(chunks)))
d_start = timeit.default_timer()
pool.map(
star_download_mseed,
[(self.client, self.client_name, chunk) for chunk in chunks])
pool.close()
d_end = timeit.default_timer()
self.logger.info("Client '%s' - Launching basic QC checks..." %
self.client_name)
downloaded_bytes, discarded_bytes = self._check_downloaded_data()
total_bytes = downloaded_bytes + discarded_bytes
self.logger.info("Client '%s' - Downloaded %.1f MB [%.2f KB/sec] of "
"data, %.1f MB of which were discarded afterwards." %
(self.client_name, total_bytes / 1024.0 ** 2,
total_bytes / 1024.0 / (d_end - d_start),
discarded_bytes / 1024.0 ** 2))
# Recount everything to be able to emit some nice statistics.
counter = collections.Counter()
for sta in self.stations.values():
for chan in sta.channels:
for interval in chan.intervals:
counter[interval.status] += 1
keys = sorted(counter.keys())
for key in keys:
self.logger.info(
"Client '%s' - Status for %i time intervals/channels after "
"downloading: %s" % (
self.client_name, counter[key], key.upper()))
self._remove_failed_and_ignored_stations()
def _remove_failed_and_ignored_stations(self):
"""
Removes all stations that have no time interval with either exists
or downloaded status.
"""
to_be_removed_keys = []
for key, station in self.stations.items():
if station.has_existing_or_downloaded_time_intervals is True:
continue
to_be_removed_keys.append(key)
for key in to_be_removed_keys:
del self.stations[key]
def sanitize_downloads(self):
"""
Should be run after the MiniSEED and StationXML downloads finished.
It will make sure that every MiniSEED file also has a corresponding
StationXML file.
"""
for station in self.stations.values():
station.sanitize_downloads(logger=self.logger)
def _check_downloaded_data(self):
"""
Read the downloaded data, set the proper status flags and remove
data that does not meet the QC criteria. It just checks the
downloaded data for minimum length and gaps/overlaps.
Returns the downloaded_bytes and the discarded_bytes.
"""
downloaded_bytes = 0
discarded_bytes = 0
for sta in self.stations.values():
for cha in sta.channels:
for interval in cha.intervals:
# The status of the interval should not have changed if
# it did not require downloading in the first place.
if interval.status != STATUS.NEEDS_DOWNLOADING:
continue
# If the file does not exist, mark the time interval as
# download failed.
if not os.path.exists(interval.filename):
interval.status = STATUS.DOWNLOAD_FAILED
continue
size = os.path.getsize(interval.filename)
if size == 0:
self.logger.warning("Zero byte file '%s'. Will be "
"deleted." % interval.filename)
utils.safe_delete(interval.filename)
interval.status = STATUS.DOWNLOAD_FAILED
continue
# Guard against faulty files.
try:
st = obspy.read(interval.filename, headonly=True)
except Exception as e:
self.logger.warning(
"Could not read file '%s' due to: %s\n"
"Will be discarded." % (interval.filename, str(e)))
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_FAILED
continue
# Valid files with no data.
if len(st) == 0:
self.logger.warning(
"Empty file '%s'. Will be deleted." %
interval.filename)
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_FAILED
continue
# If user did not want gappy files, remove them.
if self.restrictions.reject_channels_with_gaps is True and\
len(st) > 1:
self.logger.info(
"File '%s' has %i traces and thus contains "
"gaps or overlaps. Will be deleted." % (
interval.filename, len(st)))
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_REJECTED
continue
if self.restrictions.minimum_length:
duration = sum([tr.stats.endtime - tr.stats.starttime
for tr in st])
expected_min_duration = \
self.restrictions.minimum_length * \
(interval.end - interval.start)
if duration < expected_min_duration:
self.logger.info(
"File '%s' has only %.2f seconds of data. "
"%.2f are required. File will be deleted." %
(interval.filename, duration,
expected_min_duration))
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_REJECTED
continue
downloaded_bytes += size
interval.status = STATUS.DOWNLOADED
return downloaded_bytes, discarded_bytes
def _parse_miniseed_filenames(self, filenames, restrictions):
time_range = restrictions.minimum_length * (restrictions.endtime -
restrictions.starttime)
channel_availability = []
for filename in filenames:
st = obspy.read(filename, format="MSEED", headonly=True)
if restrictions.reject_channels_with_gaps and len(st) > 1:
self.logger.warning("Channel %s has gap or overlap. Will be "
"removed." % st[0].id)
try:
os.remove(filename)
except OSError:
pass
continue
elif len(st) == 0:
self.logger.error("MiniSEED file with no data detected. "
"Should not happen!")
continue
tr = st[0]
duration = tr.stats.endtime - tr.stats.starttime
if restrictions.minimum_length and duration < time_range:
self.logger.warning("Channel %s does not satisfy the minimum "
"length requirement. %.2f seconds instead "
"of the required %.2f seconds." % (
tr.id, duration, time_range))
try:
os.remove(filename)
except OSError:
pass
continue
channel_availability.append(utils.ChannelAvailability(
tr.stats.network, tr.stats.station, tr.stats.location,
tr.stats.channel, tr.stats.starttime, tr.stats.endtime,
filename))
return channel_availability
def discard_stations(self, existing_client_dl_helpers):
"""
Discard all stations part of any of the already existing client
download helper instances. The station discarding happens purely
based on station ids.
:param existing_client_dl_helpers: Instances of already existing
client download helpers. All stations part of this will not be
downloaded anymore.
:type existing_client_dl_helpers: list of
:class:`~.ClientDownloadHelper`
"""
station_ids = []
for helper in existing_client_dl_helpers:
station_ids.extend(helper.stations.keys())
for station_id in station_ids:
try:
del self.stations[station_id]
except KeyError:
pass
def get_availability(self):
"""
Queries the current client for information on what stations are
available given the spatial and temporal restrictions.
"""
# Check if stations needs to be filtered after downloading or if the
# restrictions one can impose with the FDSN webservices queries are
# enough. This depends on the domain definition.
try:
self.domain.is_in_domain(0, 0)
needs_filtering = True
except NotImplementedError:
needs_filtering = False
arguments = {
"network": self.restrictions.network,
"station": self.restrictions.station,
"location": self.restrictions.location,
"channel": self.restrictions.channel,
"starttime": self.restrictions.starttime,
"endtime": self.restrictions.endtime,
# Request at the channel level.
"level": "channel"
}
# Add the domain specific query parameters.
arguments.update(self.domain.get_query_parameters())
# Check the capabilities of the service and see what is the most
# appropriate way of acquiring availability information. Some services
# right now require manual overriding of what they claim to be
# capable of.
if "matchtimeseries" in self.client.services["station"]:
arguments["matchtimeseries"] = True
if "format" in self.client.services["station"]:
arguments["format"] = "text"
self.is_availability_reliable = True
else:
if "format" in self.client.services["station"]:
arguments["format"] = "text"
self.is_availability_reliable = False
if self.is_availability_reliable:
self.logger.info("Client '%s' - Requesting reliable "
"availability." % self.client_name)
else:
self.logger.info(
"Client '%s' - Requesting unreliable availability." %
self.client_name)
try:
start = time.time()
inv = self.client.get_stations(**arguments)
end = time.time()
except utils.ERRORS as e:
if "no data available" in str(e).lower():
self.logger.info(
"Client '%s' - No data available for request." %
self.client_name)
return
self.logger.error(
"Client '{0}' - Failed getting availability: %s".format(
self.client_name), str(e))
return
# This sometimes fires if a service returns some random stuff which
# is not a valid station file.
except Exception as e:
self.logger.error(
"Client '{0}' - Failed getting availability due to "
"unexpected exception: %s".format(self.client_name), str(e))
return
self.logger.info("Client '%s' - Successfully requested availability "
"(%.2f seconds)" % (self.client_name, end - start))
# Get the time intervals from the restrictions.
intervals = [TimeInterval(start=_i[0], end=_i[1])
for _i in self.restrictions]
for network in inv:
# Skip network if so desired.
skip_network = False
for pattern in self.restrictions.exclude_networks:
if fnmatch.fnmatch(network.code, pattern):
skip_network = True
break
if skip_network:
continue
for station in network:
# Skip station if so desired.
skip_station = False
for pattern in self.restrictions.exclude_stations:
if fnmatch.fnmatch(station.code, pattern):
skip_station = True
break
if skip_station:
continue
# If an inventory is given, only keep stations part of the
# inventory.
if self.restrictions.limit_stations_to_inventory is not None \
and (network.code, station.code) not in \
self.restrictions.limit_stations_to_inventory:
continue
# Skip the station if it is not in the desired domain.
if needs_filtering is True and \
not self.domain.is_in_domain(station.latitude,
station.longitude):
continue
channels = []
for channel in station.channels:
# Remove channels that somehow slipped past the temporal
# constraints due to weird behaviour from the data center.
if (channel.start_date > self.restrictions.endtime) or \
(channel.end_date < self.restrictions.starttime):
continue
new_channel = Channel(
location=channel.location_code, channel=channel.code,
intervals=copy.deepcopy(intervals))
# Multiple channel epochs would result in duplicate
# channels which we don't want. Bit of a silly logic here
# to get rid of them.
if new_channel not in channels:
channels.append(new_channel)
if self.restrictions.channel is None:
# Group by locations and apply the channel priority filter
# to each.
filtered_channels = []
def get_loc(x):
return x.location
for location, _channels in itertools.groupby(
sorted(channels, key=get_loc), get_loc):
filtered_channels.extend(utils.filter_channel_priority(
list(_channels), key="channel",
priorities=self.restrictions.channel_priorities))
channels = filtered_channels
if self.restrictions.location is None:
# Filter to remove unwanted locations according to the
# priority list.
channels = utils.filter_channel_priority(
channels, key="location",
priorities=self.restrictions.location_priorities)
if not channels:
continue
self.stations[(network.code, station.code)] = Station(
network=network.code,
station=station.code,
latitude=station.latitude,
longitude=station.longitude,
channels=channels)
self.logger.info("Client '%s' - Found %i stations (%i channels)." % (
self.client_name, len(self.stations),
sum([len(_i.channels) for _i in self.stations.values()])))
if __name__ == '__main__':
import doctest
doctest.testmod(exclude_empty=True)
| 42.256637 | 79 | 0.563351 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import *
import collections
import copy
import fnmatch
import itertools
import sys
from multiprocessing.pool import ThreadPool
import os
import time
import timeit
if sys.version_info.major == 2:
from itertools import ifilterfalse as filterfalse
else:
from itertools import filterfalse
import numpy as np
from lxml.etree import XMLSyntaxError
import obspy
from obspy.core.util import Enum
from . import utils
STATUS = Enum(["none", "needs_downloading", "downloaded", "ignore", "exists",
"download_failed", "download_rejected",
"download_partially_failed"])
class _SlotsEqualityComparisionObject(object):
__slots__ = []
def __eq__(self, other):
if type(self) != type(other):
return False
return all([getattr(self, _i) == getattr(other, _i)
for _i in self.__slots__])
class Station(_SlotsEqualityComparisionObject):
__slots__ = ["network", "station", "latitude", "longitude", "channels",
"_stationxml_filename", "want_station_information",
"miss_station_information", "have_station_information",
"stationxml_status"]
def __init__(self, network, station, latitude, longitude, channels,
stationxml_filename=None, stationxml_status=None):
self.network = network
self.station = station
self.latitude = latitude
self.longitude = longitude
self.channels = channels
self.stationxml_filename = stationxml_filename
self.stationxml_status = stationxml_status and STATUS.NONE
self.want_station_information = {}
self.miss_station_information = {}
self.have_station_information = {}
@property
def has_existing_or_downloaded_time_intervals(self):
status = set()
for chan in self.channels:
for ti in chan.intervals:
status.add(ti.status)
if STATUS.EXISTS in status or STATUS.DOWNLOADED in status:
return True
return False
@property
def has_existing_time_intervals(self):
for chan in self.channels:
for ti in chan.intervals:
if ti.status == STATUS.EXISTS:
return True
return False
def remove_files(self, logger, reason):
for chan in self.channels:
for ti in chan.intervals:
if ti.status != STATUS.DOWNLOADED or not ti.filename:
continue
if os.path.exists(ti.filename):
logger.info("Deleting MiniSEED file '%s'. Reason: %s" % (
ti.filename, reason))
utils.safe_delete(ti.filename)
if self.stationxml_status == STATUS.DOWNLOADED and \
self.stationxml_filename and \
os.path.exists(self.stationxml_filename):
logger.info("Deleting StationXMl file '%s'. Reason: %s" %
(self.stationxml_filename, reason))
utils.safe_delete(self.stationxml_filename)
@property
def stationxml_filename(self):
return self._stationxml_filename
@stationxml_filename.setter
def stationxml_filename(self, value):
self._stationxml_filename = value
if not value:
return
dirname = os.path.dirname(value)
if not os.path.exists(dirname):
os.makedirs(dirname)
@property
def temporal_bounds(self):
starttimes = []
endtimes = []
for channel in self.channels:
s, e = channel.temporal_bounds
starttimes.append(s)
endtimes.append(e)
return min(starttimes), max(endtimes)
def __str__(self):
channels = "\n".join(str(i) for i in self.channels)
channels = "\n\t".join(channels.splitlines())
return (
"Station '{network}.{station}' [Lat: {lat:.2f}, Lng: {lng:.2f}]\n"
"\t-> Filename: {filename} ({status})\n"
"\t-> Wants station information for channels: {want}\n"
"\t-> Has station information for channels: {has}\n"
"\t-> Misses station information for channels: {miss}\n"
"\t{channels}"
).format(
network=self.network,
station=self.station,
lat=self.latitude,
lng=self.longitude,
filename=self.stationxml_filename,
status="exists" if (self.stationxml_filename and os.path.exists(
self.stationxml_filename)) else "does not yet exist",
want=", ".join(["%s.%s" % (_i[0], _i[1]) for _i in
self.want_station_information.keys()]),
has=", ".join(["%s.%s" % (_i[0], _i[1]) for _i in
self.have_station_information.keys()]),
miss=", ".join(["%s.%s" % (_i[0], _i[1]) for _i in
self.miss_station_information.keys()]),
channels=channels)
def prepare_stationxml_download(self, stationxml_storage, logger):
self.want_station_information = {}
for channel in self.channels:
if channel.needs_station_file is False:
continue
self.want_station_information[
(channel.location, channel.channel)] = channel.temporal_bounds
if not self.want_station_information:
self.stationxml_status = STATUS.NONE
return
s, e = self.temporal_bounds
storage = utils.get_stationxml_filename(
stationxml_storage, self.network, self.station,
list(self.want_station_information.keys()),
starttime=s, endtime=e)
if isinstance(storage, (str, bytes)):
filename = storage
self.stationxml_filename = filename
if not os.path.exists(filename):
self.miss_station_information = \
copy.deepcopy(self.want_station_information)
self.have_station_information = {}
self.stationxml_status = STATUS.NEEDS_DOWNLOADING
return
else:
info = utils.get_stationxml_contents(filename)
for c_id, times in self.want_station_information.items():
c_info = [_i for _i in info if
_i.network == self.network and
_i.station == self.station and
_i.location == c_id[0] and
_i.channel == c_id[1]]
if not c_info:
break
starttime = min([_i.starttime for _i in c_info])
endtime = max([_i.endtime for _i in c_info])
if starttime > times[0] or endtime < times[1]:
break
else:
self.have_station_information = \
copy.deepcopy(self.want_station_information)
self.miss_station_information = {}
self.stationxml_status = STATUS.EXISTS
return
self.miss_station_information = \
copy.deepcopy(self.want_station_information)
self.have_station_information = {}
self.stationxml_status = STATUS.NEEDS_DOWNLOADING
return
else:
missing_channels = storage["missing_channels"]
available_channels = storage["available_channels"]
channels_wanting_station_information = copy.deepcopy(
self.want_station_information
)
self.miss_station_information = {}
for channel in missing_channels:
if channel not in channels_wanting_station_information:
continue
self.miss_station_information[channel] = \
channels_wanting_station_information[channel]
self.have_station_information = {}
for channel in available_channels:
if channel not in channels_wanting_station_information:
continue
self.have_station_information[channel] = \
channels_wanting_station_information[channel]
self.stationxml_filename = storage["filename"]
have_channels = set(self.have_station_information.keys())
miss_channels = set(self.miss_station_information.keys())
want_channels = set(self.want_station_information.keys())
if have_channels.union(miss_channels) != want_channels:
logger.warning(
"The custom `stationxml_storage` did not return "
"information about channels %s" %
str(want_channels.difference(have_channels.union(
miss_channels))))
if self.miss_station_information:
self.stationxml_status = STATUS.NEEDS_DOWNLOADING
elif not self.miss_station_information and \
self.have_station_information:
self.stationxml_status = STATUS.EXISTS
else:
self.stationxml_status = STATUS.IGNORE
def prepare_mseed_download(self, mseed_storage):
for channel in self.channels:
for interval in channel.intervals:
interval.filename = utils.get_mseed_filename(
mseed_storage, self.network, self.station,
channel.location, channel.channel, interval.start,
interval.end)
if interval.filename is True:
interval.status = STATUS.IGNORE
elif os.path.exists(interval.filename):
interval.status = STATUS.EXISTS
else:
if not os.path.exists(os.path.dirname(interval.filename)):
os.makedirs(os.path.dirname(interval.filename))
interval.status = STATUS.NEEDS_DOWNLOADING
def sanitize_downloads(self, logger):
from obspy.io.mseed.util import get_start_and_end_time
for id in self.miss_station_information.keys():
logger.warning("Station information could not be downloaded for "
"%s.%s.%s.%s. MiniSEED files outside of the "
"station information period "
"will be deleted!" % (
self.network, self.station, id[0], id[1]))
channel = [_i for _i in self.channels if
(_i.location, _i.channel) == id][0]
for time_interval in channel.intervals:
if not time_interval.filename or \
not os.path.isfile(time_interval.filename):
continue
time_interval.start, time_interval.end = \
get_start_and_end_time(time_interval.filename)
if time_interval.status == STATUS.DOWNLOADED:
miss_start, miss_end = self.miss_station_information[id]
if miss_start <= time_interval.start <= miss_end and \
miss_start <= time_interval.end <= miss_end:
utils.safe_delete(time_interval.filename)
time_interval.status = STATUS.DOWNLOAD_REJECTED
class Channel(_SlotsEqualityComparisionObject):
__slots__ = ["location", "channel", "intervals"]
def __init__(self, location, channel, intervals):
self.location = location
self.channel = channel
self.intervals = intervals
@property
def needs_station_file(self):
status = set([_i.status for _i in self.intervals])
if STATUS.DOWNLOADED in status or STATUS.EXISTS in status:
return True
return False
@property
def temporal_bounds(self):
return (min([_i.start for _i in self.intervals]),
max([_i.end for _i in self.intervals]))
def __str__(self):
return "Channel '{location}.{channel}':\n\t{intervals}".format(
location=self.location, channel=self.channel,
intervals="\n\t".join([str(i) for i in self.intervals]))
class TimeInterval(_SlotsEqualityComparisionObject):
__slots__ = ["start", "end", "filename", "status"]
def __init__(self, start, end, filename=None, status=None):
self.start = start
self.end = end
self.filename = filename
self.status = status if status is not None else STATUS.NONE
def __repr__(self):
return "TimeInterval(start={start}, end={end}, filename={filename}, " \
"status='{status}')".format(
start=repr(self.start),
end=repr(self.end),
filename="'%s'" % self.filename
if self.filename is not None else "None",
status=str(self.status))
class ClientDownloadHelper(object):
def __init__(self, client, client_name, restrictions, domain,
mseed_storage, stationxml_storage, logger):
self.client = client
self.client_name = client_name
self.restrictions = restrictions
self.domain = domain
self.mseed_storage = mseed_storage
self.stationxml_storage = stationxml_storage
self.logger = logger
self.stations = {}
self.is_availability_reliable = None
def __bool__(self):
return bool(len(self))
def __str__(self):
avail_map = {
None: "Unknown reliability of availability information",
True: "Reliable availability information",
False: "Non-reliable availability information"
}
reliability = avail_map[self.is_availability_reliable]
return (
"ClientDownloadHelper object for client '{client}' ({url})\n"
"-> {reliability}\n"
"-> Manages {station_count} stations.\n{stations}").format(
client=self.client_name,
url=self.client.base_url,
reliability=reliability,
station_count=len(self),
stations="\n".join([str(_i) for _i in self.stations.values()]))
def __len__(self):
return len(self.stations)
def prepare_mseed_download(self):
for station in self.stations.values():
station.prepare_mseed_download(mseed_storage=self.mseed_storage)
def filter_stations_based_on_minimum_distance(
self, existing_client_dl_helpers):
if not self.restrictions.minimum_interstation_distance_in_m:
return []
stations = copy.copy(list(self.stations.values()))
stations = sorted(stations, key=lambda x: (x.network, x.station))
existing_stations = []
for dlh in existing_client_dl_helpers:
existing_stations.extend(list(dlh.stations.values()))
remaining_stations = []
rejected_stations = []
if not existing_stations:
kd_tree = utils.SphericalNearestNeighbour(stations)
nns = kd_tree.query_pairs(
self.restrictions.minimum_interstation_distance_in_m)
indexes_to_remove = []
while nns:
most_common = collections.Counter(
itertools.chain.from_iterable(nns)).most_common()[0][0]
indexes_to_remove.append(most_common)
nns = list(filterfalse(lambda x: most_common in x, nns))
new_remaining_stations = [_i[1] for _i in enumerate(stations)
if _i[0] not in indexes_to_remove]
new_rejected_stations = [_i[1] for _i in enumerate(stations)
if _i[0] in indexes_to_remove]
for st in new_remaining_stations:
if st not in remaining_stations:
remaining_stations.append(st)
for st in new_rejected_stations:
if st not in rejected_stations:
rejected_stations.append(st)
else:
while stations:
existing_kd_tree = utils.SphericalNearestNeighbour(
existing_stations)
distances = np.ma.array(existing_kd_tree.query(stations)[0])
if np.isinf(distances[0]):
break
distances.mask = False
remove = np.where(
distances <
self.restrictions.minimum_interstation_distance_in_m)[0]
rejected_stations.extend([stations[_i] for _i in remove])
keep = np.where(
distances >=
self.restrictions.minimum_interstation_distance_in_m)[0]
distances.mask[remove] = True
if len(keep):
largest = np.argmax(distances)
remaining_stations.append(stations[largest])
existing_stations.append(stations[largest])
stations = [stations[_i] for _i in keep if _i != largest]
else:
stations = []
for station in rejected_stations:
station.remove_files(logger=self.logger,
reason="Minimum distance filtering.")
self.stations = {}
for station in remaining_stations:
self.stations[(station.network, station.station)] = station
return {(_i.network, _i.station): _i for _i in rejected_stations}
def prepare_stationxml_download(self):
for station in self.stations.values():
station.prepare_stationxml_download(
stationxml_storage=self.stationxml_storage,
logger=self.logger)
def download_stationxml(self, threads=3):
def star_download_station(args):
try:
ret_val = utils.download_stationxml(*args, logger=self.logger)
except utils.ERRORS as e:
self.logger.error(str(e))
return None
return ret_val
arguments = []
for station in self.stations.values():
if not station.miss_station_information:
continue
s, e = station.temporal_bounds
if self.restrictions.station_starttime:
s = self.restrictions.station_starttime
if self.restrictions.station_endtime:
e = self.restrictions.station_endtime
bulk = [(station.network, station.station, channel.location,
channel.channel, s, e) for channel in station.channels]
arguments.append((self.client, self.client_name, bulk,
station.stationxml_filename))
if not arguments:
self.logger.info("Client '%s' - No station information to "
"download." % self.client_name)
return
s_time = timeit.default_timer()
pool = ThreadPool(min(threads, len(arguments)))
results = pool.map(star_download_station, arguments)
pool.close()
e_time = timeit.default_timer()
results = [_i for _i in results if _i is not None]
filecount = 0
download_size = 0
for s_id, filename in results:
filecount += 1
station = self.stations[s_id]
size = os.path.getsize(filename)
download_size += size
try:
info = utils.get_stationxml_contents(filename)
except XMLSyntaxError:
self.logger.info(
"Client '%s' - File %s is not an XML file - it will be "
"deleted." % (self.client_name, filename))
utils.safe_delete(filename)
continue
still_missing = {}
for c_id, times in station.miss_station_information.items():
c_info = [_i for _i in info if
_i.network == station.network and
_i.station == station.station and
_i.location == c_id[0] and
_i.channel == c_id[1]]
if not c_info:
continue
starttime = min([_i.starttime for _i in c_info])
endtime = max([_i.endtime for _i in c_info])
if starttime > times[0] or endtime < times[1]:
if starttime < times[1]:
still_missing[c_id] = (times[0], starttime)
station.have_station_information[c_id] = (starttime,
times[1])
elif endtime > times[0]:
still_missing[c_id] = (endtime, times[1])
station.have_station_information[c_id] = (times[0],
endtime)
else:
still_missing[c_id] = times
continue
station.have_station_information[c_id] = times
station.miss_station_information = still_missing
if still_missing:
station.stationxml_status = STATUS.DOWNLOAD_PARTIALLY_FAILED
else:
station.stationxml_status = STATUS.DOWNLOADED
for station in self.stations.values():
if station.stationxml_status == STATUS.NEEDS_DOWNLOADING:
station.stationxml_status = STATUS.DOWNLOAD_FAILED
self.logger.info("Client '%s' - Downloaded %i station files [%.1f MB] "
"in %.1f seconds [%.2f KB/sec]." % (
self.client_name, filecount,
download_size / 1024.0 ** 2,
e_time - s_time,
(download_size / 1024.0) / (e_time - s_time)))
def download_mseed(self, chunk_size_in_mb=25, threads_per_client=3):
channel_sampling_rate = {
"F": 5000, "G": 5000, "D": 1000, "C": 1000, "E": 250, "S": 80,
"H": 250, "B": 80, "M": 10, "L": 1, "V": 0.1, "U": 0.01,
"R": 0.001, "P": 0.0001, "T": 0.00001, "Q": 0.000001, "A": 5000,
"O": 5000}
chunks = []
chunks_curr = []
curr_chunks_mb = 0
max_chunk_length = 50
counter = collections.Counter()
# Keep track of attempted downloads.
for sta in self.stations.values():
for cha in sta.channels:
# The band code is used to estimate the sampling rate of the
# data to be downloaded.
band_code = cha.channel[0].upper()
try:
sr = channel_sampling_rate[band_code]
except KeyError:
# Generic sampling rate for exotic band codes.
sr = 1.0
for interval in cha.intervals:
counter[interval.status] += 1
# Only take those time intervals that actually require
# some downloading.
if interval.status != STATUS.NEEDS_DOWNLOADING:
continue
chunks_curr.append((
sta.network, sta.station, cha.location, cha.channel,
interval.start, interval.end, interval.filename))
# Assume that each sample needs 4 byte, STEIM
# compression reduces size to about a third.
# chunk size is in MB
duration = interval.end - interval.start
curr_chunks_mb += \
sr * duration * 4.0 / 3.0 / 1024.0 / 1024.0
if curr_chunks_mb >= chunk_size_in_mb or \
len(chunks_curr) >= max_chunk_length:
chunks.append(chunks_curr)
chunks_curr = []
curr_chunks_mb = 0
if chunks_curr:
chunks.append(chunks_curr)
keys = sorted(counter.keys())
for key in keys:
self.logger.info(
"Client '%s' - Status for %i time intervals/channels before "
"downloading: %s" % (self.client_name, counter[key],
key.upper()))
if not chunks:
return
def star_download_mseed(args):
try:
ret_val = utils.download_and_split_mseed_bulk(
*args, logger=self.logger)
except utils.ERRORS as e:
msg = ("Client '%s' - " % args[1]) + str(e)
if "no data available" in msg.lower():
self.logger.info(msg.split("Detailed response")[0].strip())
else:
self.logger.error(msg)
return []
return ret_val
pool = ThreadPool(min(threads_per_client, len(chunks)))
d_start = timeit.default_timer()
pool.map(
star_download_mseed,
[(self.client, self.client_name, chunk) for chunk in chunks])
pool.close()
d_end = timeit.default_timer()
self.logger.info("Client '%s' - Launching basic QC checks..." %
self.client_name)
downloaded_bytes, discarded_bytes = self._check_downloaded_data()
total_bytes = downloaded_bytes + discarded_bytes
self.logger.info("Client '%s' - Downloaded %.1f MB [%.2f KB/sec] of "
"data, %.1f MB of which were discarded afterwards." %
(self.client_name, total_bytes / 1024.0 ** 2,
total_bytes / 1024.0 / (d_end - d_start),
discarded_bytes / 1024.0 ** 2))
# Recount everything to be able to emit some nice statistics.
counter = collections.Counter()
for sta in self.stations.values():
for chan in sta.channels:
for interval in chan.intervals:
counter[interval.status] += 1
keys = sorted(counter.keys())
for key in keys:
self.logger.info(
"Client '%s' - Status for %i time intervals/channels after "
"downloading: %s" % (
self.client_name, counter[key], key.upper()))
self._remove_failed_and_ignored_stations()
def _remove_failed_and_ignored_stations(self):
to_be_removed_keys = []
for key, station in self.stations.items():
if station.has_existing_or_downloaded_time_intervals is True:
continue
to_be_removed_keys.append(key)
for key in to_be_removed_keys:
del self.stations[key]
def sanitize_downloads(self):
for station in self.stations.values():
station.sanitize_downloads(logger=self.logger)
def _check_downloaded_data(self):
downloaded_bytes = 0
discarded_bytes = 0
for sta in self.stations.values():
for cha in sta.channels:
for interval in cha.intervals:
# The status of the interval should not have changed if
# it did not require downloading in the first place.
if interval.status != STATUS.NEEDS_DOWNLOADING:
continue
# If the file does not exist, mark the time interval as
# download failed.
if not os.path.exists(interval.filename):
interval.status = STATUS.DOWNLOAD_FAILED
continue
size = os.path.getsize(interval.filename)
if size == 0:
self.logger.warning("Zero byte file '%s'. Will be "
"deleted." % interval.filename)
utils.safe_delete(interval.filename)
interval.status = STATUS.DOWNLOAD_FAILED
continue
# Guard against faulty files.
try:
st = obspy.read(interval.filename, headonly=True)
except Exception as e:
self.logger.warning(
"Could not read file '%s' due to: %s\n"
"Will be discarded." % (interval.filename, str(e)))
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_FAILED
continue
# Valid files with no data.
if len(st) == 0:
self.logger.warning(
"Empty file '%s'. Will be deleted." %
interval.filename)
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_FAILED
continue
# If user did not want gappy files, remove them.
if self.restrictions.reject_channels_with_gaps is True and\
len(st) > 1:
self.logger.info(
"File '%s' has %i traces and thus contains "
"gaps or overlaps. Will be deleted." % (
interval.filename, len(st)))
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_REJECTED
continue
if self.restrictions.minimum_length:
duration = sum([tr.stats.endtime - tr.stats.starttime
for tr in st])
expected_min_duration = \
self.restrictions.minimum_length * \
(interval.end - interval.start)
if duration < expected_min_duration:
self.logger.info(
"File '%s' has only %.2f seconds of data. "
"%.2f are required. File will be deleted." %
(interval.filename, duration,
expected_min_duration))
utils.safe_delete(interval.filename)
discarded_bytes += size
interval.status = STATUS.DOWNLOAD_REJECTED
continue
downloaded_bytes += size
interval.status = STATUS.DOWNLOADED
return downloaded_bytes, discarded_bytes
def _parse_miniseed_filenames(self, filenames, restrictions):
time_range = restrictions.minimum_length * (restrictions.endtime -
restrictions.starttime)
channel_availability = []
for filename in filenames:
st = obspy.read(filename, format="MSEED", headonly=True)
if restrictions.reject_channels_with_gaps and len(st) > 1:
self.logger.warning("Channel %s has gap or overlap. Will be "
"removed." % st[0].id)
try:
os.remove(filename)
except OSError:
pass
continue
elif len(st) == 0:
self.logger.error("MiniSEED file with no data detected. "
"Should not happen!")
continue
tr = st[0]
duration = tr.stats.endtime - tr.stats.starttime
if restrictions.minimum_length and duration < time_range:
self.logger.warning("Channel %s does not satisfy the minimum "
"length requirement. %.2f seconds instead "
"of the required %.2f seconds." % (
tr.id, duration, time_range))
try:
os.remove(filename)
except OSError:
pass
continue
channel_availability.append(utils.ChannelAvailability(
tr.stats.network, tr.stats.station, tr.stats.location,
tr.stats.channel, tr.stats.starttime, tr.stats.endtime,
filename))
return channel_availability
def discard_stations(self, existing_client_dl_helpers):
station_ids = []
for helper in existing_client_dl_helpers:
station_ids.extend(helper.stations.keys())
for station_id in station_ids:
try:
del self.stations[station_id]
except KeyError:
pass
def get_availability(self):
# Check if stations needs to be filtered after downloading or if the
# restrictions one can impose with the FDSN webservices queries are
# enough. This depends on the domain definition.
try:
self.domain.is_in_domain(0, 0)
needs_filtering = True
except NotImplementedError:
needs_filtering = False
arguments = {
"network": self.restrictions.network,
"station": self.restrictions.station,
"location": self.restrictions.location,
"channel": self.restrictions.channel,
"starttime": self.restrictions.starttime,
"endtime": self.restrictions.endtime,
# Request at the channel level.
"level": "channel"
}
# Add the domain specific query parameters.
arguments.update(self.domain.get_query_parameters())
# Check the capabilities of the service and see what is the most
# appropriate way of acquiring availability information. Some services
# right now require manual overriding of what they claim to be
# capable of.
if "matchtimeseries" in self.client.services["station"]:
arguments["matchtimeseries"] = True
if "format" in self.client.services["station"]:
arguments["format"] = "text"
self.is_availability_reliable = True
else:
if "format" in self.client.services["station"]:
arguments["format"] = "text"
self.is_availability_reliable = False
if self.is_availability_reliable:
self.logger.info("Client '%s' - Requesting reliable "
"availability." % self.client_name)
else:
self.logger.info(
"Client '%s' - Requesting unreliable availability." %
self.client_name)
try:
start = time.time()
inv = self.client.get_stations(**arguments)
end = time.time()
except utils.ERRORS as e:
if "no data available" in str(e).lower():
self.logger.info(
"Client '%s' - No data available for request." %
self.client_name)
return
self.logger.error(
"Client '{0}' - Failed getting availability: %s".format(
self.client_name), str(e))
return
# This sometimes fires if a service returns some random stuff which
# is not a valid station file.
except Exception as e:
self.logger.error(
"Client '{0}' - Failed getting availability due to "
"unexpected exception: %s".format(self.client_name), str(e))
return
self.logger.info("Client '%s' - Successfully requested availability "
"(%.2f seconds)" % (self.client_name, end - start))
# Get the time intervals from the restrictions.
intervals = [TimeInterval(start=_i[0], end=_i[1])
for _i in self.restrictions]
for network in inv:
# Skip network if so desired.
skip_network = False
for pattern in self.restrictions.exclude_networks:
if fnmatch.fnmatch(network.code, pattern):
skip_network = True
break
if skip_network:
continue
for station in network:
# Skip station if so desired.
skip_station = False
for pattern in self.restrictions.exclude_stations:
if fnmatch.fnmatch(station.code, pattern):
skip_station = True
break
if skip_station:
continue
# If an inventory is given, only keep stations part of the
# inventory.
if self.restrictions.limit_stations_to_inventory is not None \
and (network.code, station.code) not in \
self.restrictions.limit_stations_to_inventory:
continue
# Skip the station if it is not in the desired domain.
if needs_filtering is True and \
not self.domain.is_in_domain(station.latitude,
station.longitude):
continue
channels = []
for channel in station.channels:
# Remove channels that somehow slipped past the temporal
# constraints due to weird behaviour from the data center.
if (channel.start_date > self.restrictions.endtime) or \
(channel.end_date < self.restrictions.starttime):
continue
new_channel = Channel(
location=channel.location_code, channel=channel.code,
intervals=copy.deepcopy(intervals))
# Multiple channel epochs would result in duplicate
# channels which we don't want. Bit of a silly logic here
if new_channel not in channels:
channels.append(new_channel)
if self.restrictions.channel is None:
filtered_channels = []
def get_loc(x):
return x.location
for location, _channels in itertools.groupby(
sorted(channels, key=get_loc), get_loc):
filtered_channels.extend(utils.filter_channel_priority(
list(_channels), key="channel",
priorities=self.restrictions.channel_priorities))
channels = filtered_channels
if self.restrictions.location is None:
channels = utils.filter_channel_priority(
channels, key="location",
priorities=self.restrictions.location_priorities)
if not channels:
continue
self.stations[(network.code, station.code)] = Station(
network=network.code,
station=station.code,
latitude=station.latitude,
longitude=station.longitude,
channels=channels)
self.logger.info("Client '%s' - Found %i stations (%i channels)." % (
self.client_name, len(self.stations),
sum([len(_i.channels) for _i in self.stations.values()])))
if __name__ == '__main__':
import doctest
doctest.testmod(exclude_empty=True)
| true | true |
f72a03a0654ac8bf69ab756f2589b9ba01baa853 | 270 | py | Python | com/web/web_app.py | Alex-Ryj/amazon_backend | 96bdd8aacf2bdb545e430fd9f38298a42714e44a | [
"MIT"
] | 2 | 2019-08-29T17:38:32.000Z | 2020-01-05T04:57:17.000Z | com/web/web_app.py | Alex-Ryj/amazon_backend | 96bdd8aacf2bdb545e430fd9f38298a42714e44a | [
"MIT"
] | 6 | 2021-03-19T03:01:52.000Z | 2022-01-13T01:32:51.000Z | com/web/web_app.py | Alex-Ryj/python_backend | 96bdd8aacf2bdb545e430fd9f38298a42714e44a | [
"MIT"
] | null | null | null | from flask import Flask
import log_config
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id | 20.769231 | 59 | 0.681481 | from flask import Flask
import log_config
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id | true | true |
f72a0425cee32a9448bd24310af17396dd221dd4 | 5,716 | py | Python | nuplan/planning/metrics/metric_result.py | MCZhi/nuplan-devkit | 3c4f5b8dcd517b27cfd258915ca5fe5c54e3cb0c | [
"Apache-2.0"
] | null | null | null | nuplan/planning/metrics/metric_result.py | MCZhi/nuplan-devkit | 3c4f5b8dcd517b27cfd258915ca5fe5c54e3cb0c | [
"Apache-2.0"
] | null | null | null | nuplan/planning/metrics/metric_result.py | MCZhi/nuplan-devkit | 3c4f5b8dcd517b27cfd258915ca5fe5c54e3cb0c | [
"Apache-2.0"
] | null | null | null | from __future__ import annotations
from abc import ABC
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Optional
class MetricStatisticsType(Enum):
MAX: str = 'MAX'
MIN: str = 'MIN'
P90: str = 'P90'
MEAN: str = 'MEAN'
COUNT: str = 'COUNT'
VALUE: str = 'VALUE'
DISTANCE: str = 'DISTANCE'
VELOCITY: str = 'VELOCITY'
BOOLEAN: str = 'BOOLEAN'
def __repr__(self) -> str:
""" Metric type string representation. """
return self.value
def serialize(self) -> str:
""" Serialize the type when saving. """
return self.value
@classmethod
def deserialize(cls, key: str) -> MetricStatisticsType:
""" Deserialize the type when loading from a string. """
return MetricStatisticsType.__members__[key]
@dataclass
class MetricResult(ABC):
metric_computator: str # Name of metric computator
name: str # Name of the metric
metric_category: str # Category of metric
def serialize(self) -> Dict[str, Any]:
""" Serialize the metric result. """
pass
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> MetricResult:
"""
Deserialize the metric result when loading from a file.
:param data; A dictionary of data in loading.
"""
pass
@dataclass
class Statistic:
name: str # name of statistic
unit: str # unit of statistic
value: float # value of the statistic
def serialize(self) -> Dict[str, Any]:
""" Serialization of TimeSeries. """
return {'name': self.name,
'unit': self.unit,
'value': self.value}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> Statistic:
""" Deserialization of TimeSeries.
:param data: A dictionary of data,
:return A Statistic data class.
"""
return Statistic(name=data['name'], unit=data['unit'], value=data['value'])
@dataclass
class TimeSeries:
unit: str # unit of the time series
time_stamps: List[int] # time stamps of the time series [microseconds]
values: List[float] # values of the time series
def __post_init__(self) -> None:
assert len(self.time_stamps) == len(self.values)
def serialize(self) -> Dict[str, Any]:
""" Serialization of TimeSeries. """
return {'unit': self.unit,
'time_stamps': self.time_stamps,
'values': self.values}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> Optional[TimeSeries]:
""" Deserialization of TimeSeries.
:param data: A dictionary of data,
:return A TimeSeries dataclass.
"""
return TimeSeries(unit=data['unit'],
time_stamps=data['time_stamps'],
values=data['values']) if data is not None else None
@dataclass
class MetricStatistics(MetricResult):
statistics: Dict[MetricStatisticsType, Statistic] # Collection of statistics
time_series: Optional[TimeSeries] # time series data of the metric
def serialize(self) -> Dict[str, Any]:
""" Serialize the metric result. """
return {'metric_computator': self.metric_computator,
'name': self.name,
'statistics': {statistic_type.serialize(): statistics.serialize()
for statistic_type, statistics in self.statistics.items()},
'time_series': self.time_series.serialize() if self.time_series is not None else None,
'metric_category': self.metric_category
}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> MetricStatistics:
"""
Deserialize the metric result when loading from a file.
:param data; A dictionary of data in loading.
"""
return MetricStatistics(
metric_computator=data['metric_computator'],
name=data['name'],
statistics={MetricStatisticsType.deserialize(statistic_type): Statistic.deserialize(statistics)
for statistic_type, statistics in data['statistics'].items()},
time_series=TimeSeries.deserialize(data['time_series']),
metric_category=data['metric_category']
)
@dataclass
class MetricViolation(MetricResult):
unit: str # unit of the violation
start_timestamp: int # start time stamp of the violation [microseconds]
duration: int # duration of the violation [microseconds]
extremum: float # the most violating value of the violation
mean: float # The average violation level
def serialize(self) -> Dict[str, Any]:
""" Serialize the metric result. """
return {'metric_computator': self.metric_computator,
'name': self.name,
'unit': self.unit,
'start_timestamp': self.start_timestamp,
'duration': self.duration,
'extremum': self.extremum,
'metric_category': self.metric_category
}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> MetricViolation:
"""
Deserialize the metric result when loading from a file.
:param data; A dictionary of data in loading.
"""
return MetricViolation(
metric_computator=data['metric_computator'],
name=data['name'],
start_timestamp=data['start_timestamp'],
duration=data['duration'],
extremum=data['extremum'],
unit=data['unit'],
metric_category=data['metric_category'],
mean=data['mean']
)
| 31.58011 | 107 | 0.609692 | from __future__ import annotations
from abc import ABC
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Optional
class MetricStatisticsType(Enum):
MAX: str = 'MAX'
MIN: str = 'MIN'
P90: str = 'P90'
MEAN: str = 'MEAN'
COUNT: str = 'COUNT'
VALUE: str = 'VALUE'
DISTANCE: str = 'DISTANCE'
VELOCITY: str = 'VELOCITY'
BOOLEAN: str = 'BOOLEAN'
def __repr__(self) -> str:
return self.value
def serialize(self) -> str:
return self.value
@classmethod
def deserialize(cls, key: str) -> MetricStatisticsType:
return MetricStatisticsType.__members__[key]
@dataclass
class MetricResult(ABC):
metric_computator: str
name: str
metric_category: str
def serialize(self) -> Dict[str, Any]:
pass
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> MetricResult:
pass
@dataclass
class Statistic:
name: str
unit: str
value: float
def serialize(self) -> Dict[str, Any]:
return {'name': self.name,
'unit': self.unit,
'value': self.value}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> Statistic:
return Statistic(name=data['name'], unit=data['unit'], value=data['value'])
@dataclass
class TimeSeries:
unit: str
time_stamps: List[int]
values: List[float]
def __post_init__(self) -> None:
assert len(self.time_stamps) == len(self.values)
def serialize(self) -> Dict[str, Any]:
return {'unit': self.unit,
'time_stamps': self.time_stamps,
'values': self.values}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> Optional[TimeSeries]:
return TimeSeries(unit=data['unit'],
time_stamps=data['time_stamps'],
values=data['values']) if data is not None else None
@dataclass
class MetricStatistics(MetricResult):
statistics: Dict[MetricStatisticsType, Statistic]
time_series: Optional[TimeSeries]
def serialize(self) -> Dict[str, Any]:
return {'metric_computator': self.metric_computator,
'name': self.name,
'statistics': {statistic_type.serialize(): statistics.serialize()
for statistic_type, statistics in self.statistics.items()},
'time_series': self.time_series.serialize() if self.time_series is not None else None,
'metric_category': self.metric_category
}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> MetricStatistics:
return MetricStatistics(
metric_computator=data['metric_computator'],
name=data['name'],
statistics={MetricStatisticsType.deserialize(statistic_type): Statistic.deserialize(statistics)
for statistic_type, statistics in data['statistics'].items()},
time_series=TimeSeries.deserialize(data['time_series']),
metric_category=data['metric_category']
)
@dataclass
class MetricViolation(MetricResult):
unit: str
start_timestamp: int
duration: int
extremum: float
mean: float
def serialize(self) -> Dict[str, Any]:
return {'metric_computator': self.metric_computator,
'name': self.name,
'unit': self.unit,
'start_timestamp': self.start_timestamp,
'duration': self.duration,
'extremum': self.extremum,
'metric_category': self.metric_category
}
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> MetricViolation:
return MetricViolation(
metric_computator=data['metric_computator'],
name=data['name'],
start_timestamp=data['start_timestamp'],
duration=data['duration'],
extremum=data['extremum'],
unit=data['unit'],
metric_category=data['metric_category'],
mean=data['mean']
)
| true | true |
f72a07a60d7b9b98104ca5e01aff73e0b860b04e | 8,431 | py | Python | deepvoice3_pytorch/modules.py | tripzero/deepvoice3_pytorch | 6aef4c817745c58fe2fb56d36b533b86bd137fa3 | [
"MIT"
] | 6 | 2019-05-14T09:30:49.000Z | 2020-04-20T07:24:41.000Z | deepvoice3_pytorch/modules.py | theFong/deepvoice3_pytorch | 90027d27dab2889d856f9db9ffaf39d4f70b3067 | [
"MIT"
] | null | null | null | deepvoice3_pytorch/modules.py | theFong/deepvoice3_pytorch | 90027d27dab2889d856f9db9ffaf39d4f70b3067 | [
"MIT"
] | 2 | 2021-07-14T09:04:19.000Z | 2021-10-13T05:27:32.000Z | # coding: utf-8
import torch
from torch import nn
import math
import numpy as np
from torch.nn import functional as F
def position_encoding_init(n_position, d_pos_vec, position_rate=1.0,
sinusoidal=True):
''' Init the sinusoid position encoding table '''
# keep dim 0 for padding token position encoding zero vector
position_enc = np.array([
[position_rate * pos / np.power(10000, 2 * (i // 2) / d_pos_vec) for i in range(d_pos_vec)]
if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)])
position_enc = torch.from_numpy(position_enc).float()
if sinusoidal:
position_enc[1:, 0::2] = torch.sin(position_enc[1:, 0::2]) # dim 2i
position_enc[1:, 1::2] = torch.cos(position_enc[1:, 1::2]) # dim 2i+1
return position_enc
def sinusoidal_encode(x, w):
y = w * x
y[1:, 0::2] = torch.sin(y[1:, 0::2].clone())
y[1:, 1::2] = torch.cos(y[1:, 1::2].clone())
return y
class SinusoidalEncoding(nn.Embedding):
def __init__(self, num_embeddings, embedding_dim,
*args, **kwargs):
super(SinusoidalEncoding, self).__init__(num_embeddings, embedding_dim,
padding_idx=0,
*args, **kwargs)
self.weight.data = position_encoding_init(num_embeddings, embedding_dim,
position_rate=1.0,
sinusoidal=False)
def forward(self, x, w=1.0):
isscaler = np.isscalar(w)
assert self.padding_idx is not None
if isscaler or w.size(0) == 1:
weight = sinusoidal_encode(self.weight, w)
return F.embedding(
x, weight, self.padding_idx, self.max_norm,
self.norm_type, self.scale_grad_by_freq, self.sparse)
else:
# TODO: cannot simply apply for batch
# better to implement efficient function
pe = []
for batch_idx, we in enumerate(w):
weight = sinusoidal_encode(self.weight, we)
pe.append(F.embedding(
x[batch_idx], weight, self.padding_idx, self.max_norm,
self.norm_type, self.scale_grad_by_freq, self.sparse))
pe = torch.stack(pe)
return pe
class GradMultiply(torch.autograd.Function):
@staticmethod
def forward(ctx, x, scale):
ctx.scale = scale
res = x.new(x)
ctx.mark_shared_storage((x, res))
return res
@staticmethod
def backward(ctx, grad):
return grad * ctx.scale, None
def Linear(in_features, out_features, dropout=0):
"""Weight-normalized Linear layer (input: N x T x C)"""
m = nn.Linear(in_features, out_features)
m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))
m.bias.data.zero_()
return nn.utils.weight_norm(m)
def Embedding(num_embeddings, embedding_dim, padding_idx, std=0.01):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
m.weight.data.normal_(0, std)
return m
def Conv1d(in_channels, out_channels, kernel_size, dropout=0, std_mul=4.0, **kwargs):
from .conv import Conv1d
m = Conv1d(in_channels, out_channels, kernel_size, **kwargs)
std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
m.weight.data.normal_(mean=0, std=std)
m.bias.data.zero_()
return nn.utils.weight_norm(m)
def ConvTranspose1d(in_channels, out_channels, kernel_size, dropout=0,
std_mul=1.0, **kwargs):
m = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, **kwargs)
std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
m.weight.data.normal_(mean=0, std=std)
m.bias.data.zero_()
return nn.utils.weight_norm(m)
class Conv1dGLU(nn.Module):
"""(Dilated) Conv1d + Gated linear unit + (optionally) speaker embedding
"""
def __init__(self, n_speakers, speaker_embed_dim,
in_channels, out_channels, kernel_size,
dropout, padding=None, dilation=1, causal=False, residual=False,
*args, **kwargs):
super(Conv1dGLU, self).__init__()
self.dropout = dropout
self.residual = residual
if padding is None:
# no future time stamps available
if causal:
padding = (kernel_size - 1) * dilation
else:
padding = (kernel_size - 1) // 2 * dilation
self.causal = causal
self.conv = Conv1d(in_channels, 2 * out_channels, kernel_size,
dropout=dropout, padding=padding, dilation=dilation,
*args, **kwargs)
if n_speakers > 1:
self.speaker_proj = Linear(speaker_embed_dim, out_channels)
else:
self.speaker_proj = None
def forward(self, x, speaker_embed=None):
return self._forward(x, speaker_embed, False)
def incremental_forward(self, x, speaker_embed=None):
return self._forward(x, speaker_embed, True)
def _forward(self, x, speaker_embed, is_incremental):
residual = x
x = F.dropout(x, p=self.dropout, training=self.training)
if is_incremental:
splitdim = -1
x = self.conv.incremental_forward(x)
else:
splitdim = 1
x = self.conv(x)
# remove future time steps
x = x[:, :, :residual.size(-1)] if self.causal else x
a, b = x.split(x.size(splitdim) // 2, dim=splitdim)
if self.speaker_proj is not None:
softsign = F.softsign(self.speaker_proj(speaker_embed))
# Since conv layer assumes BCT, we need to transpose
softsign = softsign if is_incremental else softsign.transpose(1, 2)
a = a + softsign
x = a * torch.sigmoid(b)
return (x + residual) * math.sqrt(0.5) if self.residual else x
def clear_buffer(self):
self.conv.clear_buffer()
class HighwayConv1d(nn.Module):
"""Weight normzlized Conv1d + Highway network (support incremental forward)
"""
def __init__(self, in_channels, out_channels, kernel_size=1, padding=None,
dilation=1, causal=False, dropout=0, std_mul=None, glu=False):
super(HighwayConv1d, self).__init__()
if std_mul is None:
std_mul = 4.0 if glu else 1.0
if padding is None:
# no future time stamps available
if causal:
padding = (kernel_size - 1) * dilation
else:
padding = (kernel_size - 1) // 2 * dilation
self.causal = causal
self.dropout = dropout
self.glu = glu
self.conv = Conv1d(in_channels, 2 * out_channels,
kernel_size=kernel_size, padding=padding,
dilation=dilation, dropout=dropout,
std_mul=std_mul)
def forward(self, x):
return self._forward(x, False)
def incremental_forward(self, x):
return self._forward(x, True)
def _forward(self, x, is_incremental):
"""Forward
Args:
x: (B, in_channels, T)
returns:
(B, out_channels, T)
"""
residual = x
x = F.dropout(x, p=self.dropout, training=self.training)
if is_incremental:
splitdim = -1
x = self.conv.incremental_forward(x)
else:
splitdim = 1
x = self.conv(x)
# remove future time steps
x = x[:, :, :residual.size(-1)] if self.causal else x
if self.glu:
x = F.glu(x, dim=splitdim)
return (x + residual) * math.sqrt(0.5)
else:
a, b = x.split(x.size(splitdim) // 2, dim=splitdim)
T = torch.sigmoid(b)
return (T * a + (1 - T) * residual)
def clear_buffer(self):
self.conv.clear_buffer()
def get_mask_from_lengths(memory, memory_lengths):
"""Get mask tensor from list of length
Args:
memory: (batch, max_time, dim)
memory_lengths: array like
"""
mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_()
for idx, l in enumerate(memory_lengths):
mask[idx][:l] = 1
return ~mask
| 34.838843 | 99 | 0.582493 |
import torch
from torch import nn
import math
import numpy as np
from torch.nn import functional as F
def position_encoding_init(n_position, d_pos_vec, position_rate=1.0,
sinusoidal=True):
position_enc = np.array([
[position_rate * pos / np.power(10000, 2 * (i // 2) / d_pos_vec) for i in range(d_pos_vec)]
if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)])
position_enc = torch.from_numpy(position_enc).float()
if sinusoidal:
position_enc[1:, 0::2] = torch.sin(position_enc[1:, 0::2])
position_enc[1:, 1::2] = torch.cos(position_enc[1:, 1::2])
return position_enc
def sinusoidal_encode(x, w):
y = w * x
y[1:, 0::2] = torch.sin(y[1:, 0::2].clone())
y[1:, 1::2] = torch.cos(y[1:, 1::2].clone())
return y
class SinusoidalEncoding(nn.Embedding):
def __init__(self, num_embeddings, embedding_dim,
*args, **kwargs):
super(SinusoidalEncoding, self).__init__(num_embeddings, embedding_dim,
padding_idx=0,
*args, **kwargs)
self.weight.data = position_encoding_init(num_embeddings, embedding_dim,
position_rate=1.0,
sinusoidal=False)
def forward(self, x, w=1.0):
isscaler = np.isscalar(w)
assert self.padding_idx is not None
if isscaler or w.size(0) == 1:
weight = sinusoidal_encode(self.weight, w)
return F.embedding(
x, weight, self.padding_idx, self.max_norm,
self.norm_type, self.scale_grad_by_freq, self.sparse)
else:
pe = []
for batch_idx, we in enumerate(w):
weight = sinusoidal_encode(self.weight, we)
pe.append(F.embedding(
x[batch_idx], weight, self.padding_idx, self.max_norm,
self.norm_type, self.scale_grad_by_freq, self.sparse))
pe = torch.stack(pe)
return pe
class GradMultiply(torch.autograd.Function):
@staticmethod
def forward(ctx, x, scale):
ctx.scale = scale
res = x.new(x)
ctx.mark_shared_storage((x, res))
return res
@staticmethod
def backward(ctx, grad):
return grad * ctx.scale, None
def Linear(in_features, out_features, dropout=0):
m = nn.Linear(in_features, out_features)
m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))
m.bias.data.zero_()
return nn.utils.weight_norm(m)
def Embedding(num_embeddings, embedding_dim, padding_idx, std=0.01):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
m.weight.data.normal_(0, std)
return m
def Conv1d(in_channels, out_channels, kernel_size, dropout=0, std_mul=4.0, **kwargs):
from .conv import Conv1d
m = Conv1d(in_channels, out_channels, kernel_size, **kwargs)
std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
m.weight.data.normal_(mean=0, std=std)
m.bias.data.zero_()
return nn.utils.weight_norm(m)
def ConvTranspose1d(in_channels, out_channels, kernel_size, dropout=0,
std_mul=1.0, **kwargs):
m = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, **kwargs)
std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
m.weight.data.normal_(mean=0, std=std)
m.bias.data.zero_()
return nn.utils.weight_norm(m)
class Conv1dGLU(nn.Module):
def __init__(self, n_speakers, speaker_embed_dim,
in_channels, out_channels, kernel_size,
dropout, padding=None, dilation=1, causal=False, residual=False,
*args, **kwargs):
super(Conv1dGLU, self).__init__()
self.dropout = dropout
self.residual = residual
if padding is None:
if causal:
padding = (kernel_size - 1) * dilation
else:
padding = (kernel_size - 1) // 2 * dilation
self.causal = causal
self.conv = Conv1d(in_channels, 2 * out_channels, kernel_size,
dropout=dropout, padding=padding, dilation=dilation,
*args, **kwargs)
if n_speakers > 1:
self.speaker_proj = Linear(speaker_embed_dim, out_channels)
else:
self.speaker_proj = None
def forward(self, x, speaker_embed=None):
return self._forward(x, speaker_embed, False)
def incremental_forward(self, x, speaker_embed=None):
return self._forward(x, speaker_embed, True)
def _forward(self, x, speaker_embed, is_incremental):
residual = x
x = F.dropout(x, p=self.dropout, training=self.training)
if is_incremental:
splitdim = -1
x = self.conv.incremental_forward(x)
else:
splitdim = 1
x = self.conv(x)
x = x[:, :, :residual.size(-1)] if self.causal else x
a, b = x.split(x.size(splitdim) // 2, dim=splitdim)
if self.speaker_proj is not None:
softsign = F.softsign(self.speaker_proj(speaker_embed))
softsign = softsign if is_incremental else softsign.transpose(1, 2)
a = a + softsign
x = a * torch.sigmoid(b)
return (x + residual) * math.sqrt(0.5) if self.residual else x
def clear_buffer(self):
self.conv.clear_buffer()
class HighwayConv1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, padding=None,
dilation=1, causal=False, dropout=0, std_mul=None, glu=False):
super(HighwayConv1d, self).__init__()
if std_mul is None:
std_mul = 4.0 if glu else 1.0
if padding is None:
if causal:
padding = (kernel_size - 1) * dilation
else:
padding = (kernel_size - 1) // 2 * dilation
self.causal = causal
self.dropout = dropout
self.glu = glu
self.conv = Conv1d(in_channels, 2 * out_channels,
kernel_size=kernel_size, padding=padding,
dilation=dilation, dropout=dropout,
std_mul=std_mul)
def forward(self, x):
return self._forward(x, False)
def incremental_forward(self, x):
return self._forward(x, True)
def _forward(self, x, is_incremental):
residual = x
x = F.dropout(x, p=self.dropout, training=self.training)
if is_incremental:
splitdim = -1
x = self.conv.incremental_forward(x)
else:
splitdim = 1
x = self.conv(x)
x = x[:, :, :residual.size(-1)] if self.causal else x
if self.glu:
x = F.glu(x, dim=splitdim)
return (x + residual) * math.sqrt(0.5)
else:
a, b = x.split(x.size(splitdim) // 2, dim=splitdim)
T = torch.sigmoid(b)
return (T * a + (1 - T) * residual)
def clear_buffer(self):
self.conv.clear_buffer()
def get_mask_from_lengths(memory, memory_lengths):
mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_()
for idx, l in enumerate(memory_lengths):
mask[idx][:l] = 1
return ~mask
| true | true |
f72a081d8e8207ed9ff9da9bb124d0d211ba5629 | 28,886 | py | Python | python/base_agent/ttad/back_translation/modeling_gpt2.py | boldsort/craftassist | 8058d115a250e30deb60d969b7b1a5fefd6e974c | [
"MIT"
] | 626 | 2019-07-18T18:40:44.000Z | 2022-03-29T17:34:43.000Z | python/base_agent/ttad/back_translation/modeling_gpt2.py | boldsort/craftassist | 8058d115a250e30deb60d969b7b1a5fefd6e974c | [
"MIT"
] | 42 | 2019-07-27T11:04:15.000Z | 2021-02-23T03:15:14.000Z | python/base_agent/ttad/back_translation/modeling_gpt2.py | boldsort/craftassist | 8058d115a250e30deb60d969b7b1a5fefd6e974c | [
"MIT"
] | 89 | 2019-07-19T15:07:39.000Z | 2022-02-15T18:44:24.000Z | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch OpenAI GPT-2 model."""
import logging
import os
import warnings
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from transformers.modeling_gpt2 import PreTrainedModel, GPT2Config
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
GPT2DoubleHeadsModelOutput,
)
from transformers.activations import ACT2FN
from transformers.modeling_utils import (
Conv1D,
prune_conv1d_layer,
SequenceSummary,
find_pruneable_heads_and_indices,
)
logger = logging.getLogger(__name__)
_CONFIG_FOR_DOC = "GPT2Config"
_TOKENIZER_FOR_DOC = "GPT2Tokenizer"
GPT2_PRETRAINED_MODEL_ARCHIVE_LIST = [
"gpt2",
"gpt2-medium",
"gpt2-large",
"gpt2-xl",
"distilgpt2",
# See all GPT-2 models at https://huggingface.co/models?filter=gpt2
]
def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
""" Load tf checkpoints in a pytorch model
"""
try:
import re
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(gpt2_checkpoint_path)
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info("Loading TF weight {} with shape {}".format(name, shape))
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array.squeeze())
for name, array in zip(names, arrays):
name = name[6:] # skip "model/"
name = name.split("/")
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+\d+", m_name):
scope_names = re.split(r"(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "w" or scope_names[0] == "g":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "b":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "wpe" or scope_names[0] == "wte":
pointer = getattr(pointer, scope_names[0])
pointer = getattr(pointer, "weight")
else:
pointer = getattr(pointer, scope_names[0])
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info("Initialize PyTorch weight {}".format(name))
pointer.data = torch.from_numpy(array)
return model
class Attention(nn.Module):
def __init__(self, nx, n_ctx, config, scale=False):
super().__init__()
n_state = nx # in Attention: n_state=768 (nx=n_embd)
# [switch nx => n_state from Block to Attention to keep identical to TF implem]
assert n_state % config.n_head == 0
self.register_buffer(
"bias",
torch.tril(torch.ones((n_ctx, n_ctx), dtype=torch.uint8)).view(1, 1, n_ctx, n_ctx),
)
self.register_buffer("masked_bias", torch.tensor(-1e4))
self.n_head = config.n_head
self.split_size = n_state
self.scale = scale
self.c_attn = Conv1D(n_state * 3, nx)
# TODO: check config.hidden_size
self.query = nn.Linear(n_state, nx)
self.key = nn.Linear(n_state, nx)
self.value = nn.Linear(n_state, nx)
self.c_proj = Conv1D(n_state, nx)
self.attn_dropout = nn.Dropout(config.attn_pdrop)
self.resid_dropout = nn.Dropout(config.resid_pdrop)
self.pruned_heads = set()
self.config = config
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.n_head, self.split_size // self.n_head, self.pruned_heads
)
index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
# Prune conv1d layers
self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
# Update hyper params
self.split_size = (self.split_size // self.n_head) * (self.n_head - len(heads))
self.n_head = self.n_head - len(heads)
self.pruned_heads = self.pruned_heads.union(heads)
def _attn(self, q, k, v, attention_mask=None, head_mask=None, output_attentions=False):
w = torch.matmul(q, k)
if self.scale:
w = w / (float(v.size(-1)) ** 0.5)
nd, ns = w.size(-2), w.size(-1)
mask = self.bias[:, :, ns - nd : ns, :ns]
w = torch.where(mask.bool(), w, self.masked_bias.to(w.dtype))
if attention_mask is not None:
# Apply the attention mask
w = w + attention_mask
w = nn.Softmax(dim=-1)(w)
w = self.attn_dropout(w)
# Mask heads if we want to
if head_mask is not None:
w = w * head_mask
outputs = [torch.matmul(w, v)]
if output_attentions:
outputs.append(w)
return outputs
def merge_heads(self, x):
x = x.permute(0, 2, 1, 3).contiguous()
new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),)
return x.view(*new_x_shape) # in Tensorflow implem: fct merge_states
def split_heads(self, x, k=False):
new_x_shape = x.size()[:-1] + (self.n_head, x.size(-1) // self.n_head)
x = x.view(*new_x_shape) # in Tensorflow implem: fct split_states
if k:
return x.permute(0, 2, 3, 1) # (batch, head, head_features, seq_length)
else:
return x.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
def forward(
self,
x,
layer_past=None,
attention_mask=None,
head_mask=None,
use_cache=False,
output_attentions=False,
encoder_hidden_states=None,
encoder_attention_mask=None,
):
if self.config.is_decoder:
assert encoder_hidden_states is not None
key = self.key(encoder_hidden_states)
value = self.value(encoder_hidden_states)
query = self.query(x)
else:
x = self.c_attn(x)
query, key, value = x.split(self.split_size, dim=2)
query = self.split_heads(query)
key = self.split_heads(key, k=True)
value = self.split_heads(value)
if layer_past is not None:
past_key, past_value = (
layer_past[0].transpose(-2, -1),
layer_past[1],
) # transpose back cf below
key = torch.cat((past_key, key), dim=-1)
value = torch.cat((past_value, value), dim=-2)
if use_cache is True:
present = torch.stack(
(key.transpose(-2, -1), value)
) # transpose to have same shapes for stacking
else:
present = (None,)
if self.config.is_decoder:
attn_outputs = self._attn(
query, key, value, encoder_attention_mask, head_mask, output_attentions
)
else:
attn_outputs = self._attn(
query, key, value, attention_mask, head_mask, output_attentions
)
at = attn_outputs[0]
at = self.merge_heads(at)
at = self.c_proj(at)
at = self.resid_dropout(at)
outputs = [at, present] + attn_outputs[1:]
return outputs # a, present, (attentions)
class MLP(nn.Module):
def __init__(self, n_state, config): # in MLP: n_state=3072 (4 * n_embd)
super().__init__()
nx = config.n_embd
self.c_fc = Conv1D(n_state, nx)
self.c_proj = Conv1D(nx, n_state)
self.act = ACT2FN[config.activation_function]
self.dropout = nn.Dropout(config.resid_pdrop)
def forward(self, x):
h = self.act(self.c_fc(x))
h2 = self.c_proj(h)
return self.dropout(h2)
class Block(nn.Module):
def __init__(self, n_ctx, config, scale=False):
super().__init__()
nx = config.n_embd
inner_dim = config.n_inner if config.n_inner is not None else 4 * nx
self.ln_1 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
self.attn = Attention(nx, n_ctx, config, scale)
self.ln_2 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
self.mlp = MLP(inner_dim, config)
self.config = config
"""
TODO: add another self attention layer?
"""
def forward(
self,
x,
layer_past=None,
attention_mask=None,
head_mask=None,
use_cache=False,
output_attentions=False,
encoder_hidden_states=None,
encoder_attention_mask=None,
):
output_attn = self.attn(
self.ln_1(x),
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask,
use_cache=use_cache,
output_attentions=output_attentions,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
a = output_attn[0] # output_attn: a, present, (attentions)
x = x + a
m = self.mlp(self.ln_2(x))
x = x + m
outputs = [x] + output_attn[1:]
return outputs # x, present, (attentions)
class GPT2PreTrainedModel(PreTrainedModel):
""" An abstract class to handle weights initialization and
a simple interface for downloading and loading pretrained models.
"""
config_class = GPT2Config
load_tf_weights = load_tf_weights_in_gpt2
base_model_prefix = "transformer"
def __init__(self, *inputs, **kwargs):
super().__init__(*inputs, **kwargs)
def _init_weights(self, module):
""" Initialize the weights.
"""
if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if isinstance(module, (nn.Linear, Conv1D)) and module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
class GPT2Model(GPT2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
self.wpe = nn.Embedding(config.n_positions, config.n_embd)
self.drop = nn.Dropout(config.embd_pdrop)
self.h = nn.ModuleList(
[Block(config.n_ctx, config, scale=True) for _ in range(config.n_layer)]
)
self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
self.init_weights()
def get_input_embeddings(self):
return self.wte
def set_input_embeddings(self, new_embeddings):
self.wte = new_embeddings
def _prune_heads(self, heads_to_prune):
""" Prunes heads of the model.
heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
"""
for layer, heads in heads_to_prune.items():
self.h[layer].attn.prune_heads(heads)
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
use_cache=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
if "past" in kwargs:
warnings.warn(
"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.",
FutureWarning,
)
past_key_values = kwargs.pop("past")
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
output_attentions = (
output_attentions if output_attentions is not None else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError(
"You cannot specify both input_ids and inputs_embeds at the same time"
)
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
batch_size = input_ids.shape[0]
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
batch_size = inputs_embeds.shape[0]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
if token_type_ids is not None:
token_type_ids = token_type_ids.view(-1, input_shape[-1])
if position_ids is not None:
position_ids = position_ids.view(-1, input_shape[-1])
if past_key_values is None:
past_length = 0
past_key_values = [None] * len(self.h)
else:
past_length = past_key_values[0][0].size(-2)
if position_ids is None:
device = input_ids.device if input_ids is not None else inputs_embeds.device
position_ids = torch.arange(
past_length, input_shape[-1] + past_length, dtype=torch.long, device=device
)
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
# Attention mask.
if attention_mask is not None:
assert batch_size > 0, "batch_size has to be defined and > 0"
attention_mask = attention_mask.view(batch_size, -1)
# We create a 3D attention mask from a 2D tensor mask.
# Sizes are [batch_size, 1, 1, to_seq_length]
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
# this attention mask is more simple than the triangular masking of causal attention
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
attention_mask = attention_mask.to(
dtype=next(self.parameters()).dtype
) # fp16 compatibility
attention_mask = (1.0 - attention_mask) * -10000.0
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# head_mask has shape n_layer x batch x n_heads x N x N
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
if self.config.is_decoder and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape)
if inputs_embeds is None:
inputs_embeds = self.wte(input_ids)
position_embeds = self.wpe(position_ids)
if token_type_ids is not None:
token_type_embeds = self.wte(token_type_ids)
else:
token_type_embeds = 0
hidden_states = inputs_embeds + position_embeds + token_type_embeds
hidden_states = self.drop(hidden_states)
output_shape = input_shape + (hidden_states.size(-1),)
presents = () if use_cache else None
all_attentions = () if output_attentions else None
all_hidden_states = () if output_hidden_states else None
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states.view(*output_shape),)
outputs = block(
hidden_states,
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask[i],
use_cache=use_cache,
output_attentions=output_attentions,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
hidden_states, present = outputs[:2]
if use_cache is True:
presents = presents + (present,)
if output_attentions:
all_attentions = all_attentions + (outputs[2],)
hidden_states = self.ln_f(hidden_states)
hidden_states = hidden_states.view(*output_shape)
# Add last hidden state
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [hidden_states, presents, all_hidden_states, all_attentions]
if v is not None
)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=presents,
hidden_states=all_hidden_states,
attentions=all_attentions,
)
class GPT2LMHeadModel(GPT2PreTrainedModel):
authorized_missing_keys = [r"h\.\d+\.attn\.masked_bias", r"lm_head\.weight"]
def __init__(self, config):
super().__init__(config)
self.transformer = GPT2Model(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.init_weights()
def get_output_embeddings(self):
return self.lm_head
def prepare_inputs_for_generation(self, input_ids, past, **kwargs):
# only last token for inputs_ids if past is defined in kwargs
if past:
input_ids = input_ids[:, -1].unsqueeze(-1)
return {"input_ids": input_ids, "past_key_values": past, "use_cache": kwargs["use_cache"]}
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
use_cache=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Labels for language modeling.
Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``
Indices are selected in ``[-100, 0, ..., config.vocab_size]``
All labels set to ``-100`` are ignored (masked), the loss is only
computed for labels in ``[0, ..., config.vocab_size]``
"""
if "past" in kwargs:
warnings.warn(
"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.",
FutureWarning,
)
past_key_values = kwargs.pop("past")
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
lm_logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
# Shift so that tokens < n predict n
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=lm_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
class GPT2DoubleHeadsModel(GPT2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
config.num_labels = 1
self.transformer = GPT2Model(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.multiple_choice_head = SequenceSummary(config)
self.init_weights()
def get_output_embeddings(self):
return self.lm_head
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
mc_token_ids=None,
labels=None,
mc_labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
r"""
mc_token_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, num_choices)`, `optional`, default to index of the last token of the input)
Index of the classification token in each input sequence.
Selected in the range ``[0, input_ids.size(-1) - 1[``.
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`)
Labels for language modeling.
Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``
Indices are selected in ``[-1, 0, ..., config.vocab_size]``
All labels set to ``-100`` are ignored (masked), the loss is only
computed for labels in ``[0, ..., config.vocab_size]``
mc_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size)`, `optional`, defaults to :obj:`None`)
Labels for computing the multiple choice classification loss.
Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension
of the input tensors. (see `input_ids` above)
kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`):
Used to hide legacy arguments that have been deprecated.
Return:
Examples::
>>> import torch
>>> from transformers import GPT2Tokenizer, GPT2DoubleHeadsModel
>>> tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
>>> model = GPT2DoubleHeadsModel.from_pretrained('gpt2, return_dict=True)
>>> # Add a [CLS] to the vocabulary (we should train it also!)
>>> num_added_tokens = tokenizer.add_special_tokens({'cls_token': '[CLS]'})
>>> embedding_layer = model.resize_token_embeddings(len(tokenizer)) # Update the model embeddings with the new vocabulary size
>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> encoded_choices = [tokenizer.encode(s) for s in choices]
>>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]
>>> input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2
>>> mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1
>>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
>>> lm_logits = outputs.lm_logits
>>> mc_logits = outputs.mc_logits
"""
if "lm_labels" in kwargs:
warnings.warn(
"The `lm_labels` argument is deprecated and will be removed in a future version, use `labels` instead.",
FutureWarning,
)
labels = kwargs.pop("lm_labels")
if "past" in kwargs:
warnings.warn(
"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.",
FutureWarning,
)
past_key_values = kwargs.pop("past")
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
lm_logits = self.lm_head(hidden_states)
mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
mc_loss = None
if mc_labels is not None:
loss_fct = CrossEntropyLoss()
mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
lm_loss = None
if labels is not None:
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss_fct = CrossEntropyLoss()
lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits, mc_logits) + transformer_outputs[1:]
if mc_loss is not None:
output = (mc_loss,) + output
return ((lm_loss,) + output) if lm_loss is not None else output
return GPT2DoubleHeadsModelOutput(
lm_loss=lm_loss,
mc_loss=mc_loss,
lm_logits=lm_logits,
mc_logits=mc_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
| 38.669344 | 149 | 0.616562 |
import logging
import os
import warnings
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from transformers.modeling_gpt2 import PreTrainedModel, GPT2Config
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
GPT2DoubleHeadsModelOutput,
)
from transformers.activations import ACT2FN
from transformers.modeling_utils import (
Conv1D,
prune_conv1d_layer,
SequenceSummary,
find_pruneable_heads_and_indices,
)
logger = logging.getLogger(__name__)
_CONFIG_FOR_DOC = "GPT2Config"
_TOKENIZER_FOR_DOC = "GPT2Tokenizer"
GPT2_PRETRAINED_MODEL_ARCHIVE_LIST = [
"gpt2",
"gpt2-medium",
"gpt2-large",
"gpt2-xl",
"distilgpt2",
]
def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
try:
import re
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(gpt2_checkpoint_path)
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info("Loading TF weight {} with shape {}".format(name, shape))
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array.squeeze())
for name, array in zip(names, arrays):
name = name[6:]
name = name.split("/")
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+\d+", m_name):
scope_names = re.split(r"(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "w" or scope_names[0] == "g":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "b":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "wpe" or scope_names[0] == "wte":
pointer = getattr(pointer, scope_names[0])
pointer = getattr(pointer, "weight")
else:
pointer = getattr(pointer, scope_names[0])
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info("Initialize PyTorch weight {}".format(name))
pointer.data = torch.from_numpy(array)
return model
class Attention(nn.Module):
def __init__(self, nx, n_ctx, config, scale=False):
super().__init__()
n_state = nx
assert n_state % config.n_head == 0
self.register_buffer(
"bias",
torch.tril(torch.ones((n_ctx, n_ctx), dtype=torch.uint8)).view(1, 1, n_ctx, n_ctx),
)
self.register_buffer("masked_bias", torch.tensor(-1e4))
self.n_head = config.n_head
self.split_size = n_state
self.scale = scale
self.c_attn = Conv1D(n_state * 3, nx)
self.query = nn.Linear(n_state, nx)
self.key = nn.Linear(n_state, nx)
self.value = nn.Linear(n_state, nx)
self.c_proj = Conv1D(n_state, nx)
self.attn_dropout = nn.Dropout(config.attn_pdrop)
self.resid_dropout = nn.Dropout(config.resid_pdrop)
self.pruned_heads = set()
self.config = config
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.n_head, self.split_size // self.n_head, self.pruned_heads
)
index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
self.split_size = (self.split_size // self.n_head) * (self.n_head - len(heads))
self.n_head = self.n_head - len(heads)
self.pruned_heads = self.pruned_heads.union(heads)
def _attn(self, q, k, v, attention_mask=None, head_mask=None, output_attentions=False):
w = torch.matmul(q, k)
if self.scale:
w = w / (float(v.size(-1)) ** 0.5)
nd, ns = w.size(-2), w.size(-1)
mask = self.bias[:, :, ns - nd : ns, :ns]
w = torch.where(mask.bool(), w, self.masked_bias.to(w.dtype))
if attention_mask is not None:
w = w + attention_mask
w = nn.Softmax(dim=-1)(w)
w = self.attn_dropout(w)
if head_mask is not None:
w = w * head_mask
outputs = [torch.matmul(w, v)]
if output_attentions:
outputs.append(w)
return outputs
def merge_heads(self, x):
x = x.permute(0, 2, 1, 3).contiguous()
new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),)
return x.view(*new_x_shape)
def split_heads(self, x, k=False):
new_x_shape = x.size()[:-1] + (self.n_head, x.size(-1) // self.n_head)
x = x.view(*new_x_shape)
if k:
return x.permute(0, 2, 3, 1)
else:
return x.permute(0, 2, 1, 3)
def forward(
self,
x,
layer_past=None,
attention_mask=None,
head_mask=None,
use_cache=False,
output_attentions=False,
encoder_hidden_states=None,
encoder_attention_mask=None,
):
if self.config.is_decoder:
assert encoder_hidden_states is not None
key = self.key(encoder_hidden_states)
value = self.value(encoder_hidden_states)
query = self.query(x)
else:
x = self.c_attn(x)
query, key, value = x.split(self.split_size, dim=2)
query = self.split_heads(query)
key = self.split_heads(key, k=True)
value = self.split_heads(value)
if layer_past is not None:
past_key, past_value = (
layer_past[0].transpose(-2, -1),
layer_past[1],
)
key = torch.cat((past_key, key), dim=-1)
value = torch.cat((past_value, value), dim=-2)
if use_cache is True:
present = torch.stack(
(key.transpose(-2, -1), value)
)
else:
present = (None,)
if self.config.is_decoder:
attn_outputs = self._attn(
query, key, value, encoder_attention_mask, head_mask, output_attentions
)
else:
attn_outputs = self._attn(
query, key, value, attention_mask, head_mask, output_attentions
)
at = attn_outputs[0]
at = self.merge_heads(at)
at = self.c_proj(at)
at = self.resid_dropout(at)
outputs = [at, present] + attn_outputs[1:]
return outputs
class MLP(nn.Module):
def __init__(self, n_state, config):
super().__init__()
nx = config.n_embd
self.c_fc = Conv1D(n_state, nx)
self.c_proj = Conv1D(nx, n_state)
self.act = ACT2FN[config.activation_function]
self.dropout = nn.Dropout(config.resid_pdrop)
def forward(self, x):
h = self.act(self.c_fc(x))
h2 = self.c_proj(h)
return self.dropout(h2)
class Block(nn.Module):
def __init__(self, n_ctx, config, scale=False):
super().__init__()
nx = config.n_embd
inner_dim = config.n_inner if config.n_inner is not None else 4 * nx
self.ln_1 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
self.attn = Attention(nx, n_ctx, config, scale)
self.ln_2 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
self.mlp = MLP(inner_dim, config)
self.config = config
def forward(
self,
x,
layer_past=None,
attention_mask=None,
head_mask=None,
use_cache=False,
output_attentions=False,
encoder_hidden_states=None,
encoder_attention_mask=None,
):
output_attn = self.attn(
self.ln_1(x),
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask,
use_cache=use_cache,
output_attentions=output_attentions,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
a = output_attn[0]
x = x + a
m = self.mlp(self.ln_2(x))
x = x + m
outputs = [x] + output_attn[1:]
return outputs
class GPT2PreTrainedModel(PreTrainedModel):
config_class = GPT2Config
load_tf_weights = load_tf_weights_in_gpt2
base_model_prefix = "transformer"
def __init__(self, *inputs, **kwargs):
super().__init__(*inputs, **kwargs)
def _init_weights(self, module):
if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if isinstance(module, (nn.Linear, Conv1D)) and module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
class GPT2Model(GPT2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
self.wpe = nn.Embedding(config.n_positions, config.n_embd)
self.drop = nn.Dropout(config.embd_pdrop)
self.h = nn.ModuleList(
[Block(config.n_ctx, config, scale=True) for _ in range(config.n_layer)]
)
self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
self.init_weights()
def get_input_embeddings(self):
return self.wte
def set_input_embeddings(self, new_embeddings):
self.wte = new_embeddings
def _prune_heads(self, heads_to_prune):
for layer, heads in heads_to_prune.items():
self.h[layer].attn.prune_heads(heads)
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
use_cache=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
if "past" in kwargs:
warnings.warn(
"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.",
FutureWarning,
)
past_key_values = kwargs.pop("past")
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
output_attentions = (
output_attentions if output_attentions is not None else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError(
"You cannot specify both input_ids and inputs_embeds at the same time"
)
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
batch_size = input_ids.shape[0]
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
batch_size = inputs_embeds.shape[0]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
if token_type_ids is not None:
token_type_ids = token_type_ids.view(-1, input_shape[-1])
if position_ids is not None:
position_ids = position_ids.view(-1, input_shape[-1])
if past_key_values is None:
past_length = 0
past_key_values = [None] * len(self.h)
else:
past_length = past_key_values[0][0].size(-2)
if position_ids is None:
device = input_ids.device if input_ids is not None else inputs_embeds.device
position_ids = torch.arange(
past_length, input_shape[-1] + past_length, dtype=torch.long, device=device
)
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
if attention_mask is not None:
assert batch_size > 0, "batch_size has to be defined and > 0"
attention_mask = attention_mask.view(batch_size, -1)
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
attention_mask = attention_mask.to(
dtype=next(self.parameters()).dtype
)
attention_mask = (1.0 - attention_mask) * -10000.0
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
if self.config.is_decoder and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape)
if inputs_embeds is None:
inputs_embeds = self.wte(input_ids)
position_embeds = self.wpe(position_ids)
if token_type_ids is not None:
token_type_embeds = self.wte(token_type_ids)
else:
token_type_embeds = 0
hidden_states = inputs_embeds + position_embeds + token_type_embeds
hidden_states = self.drop(hidden_states)
output_shape = input_shape + (hidden_states.size(-1),)
presents = () if use_cache else None
all_attentions = () if output_attentions else None
all_hidden_states = () if output_hidden_states else None
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states.view(*output_shape),)
outputs = block(
hidden_states,
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask[i],
use_cache=use_cache,
output_attentions=output_attentions,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
hidden_states, present = outputs[:2]
if use_cache is True:
presents = presents + (present,)
if output_attentions:
all_attentions = all_attentions + (outputs[2],)
hidden_states = self.ln_f(hidden_states)
hidden_states = hidden_states.view(*output_shape)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [hidden_states, presents, all_hidden_states, all_attentions]
if v is not None
)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=presents,
hidden_states=all_hidden_states,
attentions=all_attentions,
)
class GPT2LMHeadModel(GPT2PreTrainedModel):
authorized_missing_keys = [r"h\.\d+\.attn\.masked_bias", r"lm_head\.weight"]
def __init__(self, config):
super().__init__(config)
self.transformer = GPT2Model(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.init_weights()
def get_output_embeddings(self):
return self.lm_head
def prepare_inputs_for_generation(self, input_ids, past, **kwargs):
if past:
input_ids = input_ids[:, -1].unsqueeze(-1)
return {"input_ids": input_ids, "past_key_values": past, "use_cache": kwargs["use_cache"]}
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
use_cache=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
if "past" in kwargs:
warnings.warn(
"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.",
FutureWarning,
)
past_key_values = kwargs.pop("past")
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
lm_logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=lm_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
class GPT2DoubleHeadsModel(GPT2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
config.num_labels = 1
self.transformer = GPT2Model(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.multiple_choice_head = SequenceSummary(config)
self.init_weights()
def get_output_embeddings(self):
return self.lm_head
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
mc_token_ids=None,
labels=None,
mc_labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
if "lm_labels" in kwargs:
warnings.warn(
"The `lm_labels` argument is deprecated and will be removed in a future version, use `labels` instead.",
FutureWarning,
)
labels = kwargs.pop("lm_labels")
if "past" in kwargs:
warnings.warn(
"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.",
FutureWarning,
)
past_key_values = kwargs.pop("past")
assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
lm_logits = self.lm_head(hidden_states)
mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
mc_loss = None
if mc_labels is not None:
loss_fct = CrossEntropyLoss()
mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
lm_loss = None
if labels is not None:
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss_fct = CrossEntropyLoss()
lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits, mc_logits) + transformer_outputs[1:]
if mc_loss is not None:
output = (mc_loss,) + output
return ((lm_loss,) + output) if lm_loss is not None else output
return GPT2DoubleHeadsModelOutput(
lm_loss=lm_loss,
mc_loss=mc_loss,
lm_logits=lm_logits,
mc_logits=mc_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
| true | true |
f72a08a72a1888f212ceb3df79de2a45c4365d09 | 6,475 | py | Python | test/functional/rpc_bind.py | WFLSCoin/wflscoin | 794eb115845c3e7d6b75cf40031568bf5329ee25 | [
"MIT"
] | null | null | null | test/functional/rpc_bind.py | WFLSCoin/wflscoin | 794eb115845c3e7d6b75cf40031568bf5329ee25 | [
"MIT"
] | null | null | null | test/functional/rpc_bind.py | WFLSCoin/wflscoin | 794eb115845c3e7d6b75cf40031568bf5329ee25 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Wflscoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test running wflscoind with the -rpcbind and -rpcallowip options."""
import sys
from test_framework.netutil import all_interfaces, addr_to_hex, get_bind_addrs, test_ipv6_local
from test_framework.test_framework import WflscoinTestFramework, SkipTest
from test_framework.util import assert_equal, assert_raises_rpc_error, get_rpc_proxy, rpc_port, rpc_url
class RPCBindTest(WflscoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.bind_to_localhost_only = False
self.num_nodes = 1
self.supports_cli = False
def setup_network(self):
self.add_nodes(self.num_nodes, None)
def add_options(self, parser):
parser.add_argument("--ipv4", action='store_true', dest="run_ipv4", help="Run ipv4 tests only", default=False)
parser.add_argument("--ipv6", action='store_true', dest="run_ipv6", help="Run ipv6 tests only", default=False)
parser.add_argument("--nonloopback", action='store_true', dest="run_nonloopback", help="Run non-loopback tests only", default=False)
def run_bind_test(self, allow_ips, connect_to, addresses, expected):
'''
Start a node with requested rpcallowip and rpcbind parameters,
then try to connect, and check if the set of bound addresses
matches the expected set.
'''
self.log.info("Bind test for %s" % str(addresses))
expected = [(addr_to_hex(addr), port) for (addr, port) in expected]
base_args = ['-disablewallet', '-nolisten']
if allow_ips:
base_args += ['-rpcallowip=' + x for x in allow_ips]
binds = ['-rpcbind='+addr for addr in addresses]
self.nodes[0].rpchost = connect_to
self.start_node(0, base_args + binds)
pid = self.nodes[0].process.pid
assert_equal(set(get_bind_addrs(pid)), set(expected))
self.stop_nodes()
def run_allowip_test(self, allow_ips, rpchost, rpcport):
'''
Start a node with rpcallow IP, and request getnetworkinfo
at a non-localhost IP.
'''
self.log.info("Allow IP test for %s:%d" % (rpchost, rpcport))
node_args = \
['-disablewallet', '-nolisten'] + \
['-rpcallowip='+x for x in allow_ips] + \
['-rpcbind='+addr for addr in ['127.0.0.1', "%s:%d" % (rpchost, rpcport)]] # Bind to localhost as well so start_nodes doesn't hang
self.nodes[0].rpchost = None
self.start_nodes([node_args])
# connect to node through non-loopback interface
node = get_rpc_proxy(rpc_url(self.nodes[0].datadir, 0, self.chain, "%s:%d" % (rpchost, rpcport)), 0, coveragedir=self.options.coveragedir)
node.getnetworkinfo()
self.stop_nodes()
def run_test(self):
# due to OS-specific network stats queries, this test works only on Linux
if sum([self.options.run_ipv4, self.options.run_ipv6, self.options.run_nonloopback]) > 1:
raise AssertionError("Only one of --ipv4, --ipv6 and --nonloopback can be set")
self.log.info("Check for linux")
if not sys.platform.startswith('linux'):
raise SkipTest("This test can only be run on linux.")
self.log.info("Check for ipv6")
have_ipv6 = test_ipv6_local()
if not have_ipv6 and not (self.options.run_ipv4 or self.options.run_nonloopback):
raise SkipTest("This test requires ipv6 support.")
self.log.info("Check for non-loopback interface")
self.non_loopback_ip = None
for name,ip in all_interfaces():
if ip != '127.0.0.1':
self.non_loopback_ip = ip
break
if self.non_loopback_ip is None and self.options.run_nonloopback:
raise SkipTest("This test requires a non-loopback ip address.")
self.defaultport = rpc_port(0)
if not self.options.run_nonloopback:
self._run_loopback_tests()
if not self.options.run_ipv4 and not self.options.run_ipv6:
self._run_nonloopback_tests()
def _run_loopback_tests(self):
if self.options.run_ipv4:
# check only IPv4 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
[('127.0.0.1', self.defaultport)])
# check only IPv4 localhost (explicit) with alternative port
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
[('127.0.0.1', 32171)])
# check only IPv4 localhost (explicit) with multiple alternative ports on same host
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],
[('127.0.0.1', 32171), ('127.0.0.1', 32172)])
else:
# check default without rpcallowip (IPv4 and IPv6 localhost)
self.run_bind_test(None, '127.0.0.1', [],
[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
# check default with rpcallowip (IPv4 and IPv6 localhost)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', [],
[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
# check only IPv6 localhost (explicit)
self.run_bind_test(['[::1]'], '[::1]', ['[::1]'],
[('::1', self.defaultport)])
# check both IPv4 and IPv6 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],
[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
def _run_nonloopback_tests(self):
self.log.info("Using interface %s for testing" % self.non_loopback_ip)
# check only non-loopback interface
self.run_bind_test([self.non_loopback_ip], self.non_loopback_ip, [self.non_loopback_ip],
[(self.non_loopback_ip, self.defaultport)])
# Check that with invalid rpcallowip, we are denied
self.run_allowip_test([self.non_loopback_ip], self.non_loopback_ip, self.defaultport)
assert_raises_rpc_error(-342, "non-JSON HTTP response with '403 Forbidden' from server", self.run_allowip_test, ['1.1.1.1'], self.non_loopback_ip, self.defaultport)
if __name__ == '__main__':
RPCBindTest().main()
| 49.427481 | 172 | 0.633514 |
import sys
from test_framework.netutil import all_interfaces, addr_to_hex, get_bind_addrs, test_ipv6_local
from test_framework.test_framework import WflscoinTestFramework, SkipTest
from test_framework.util import assert_equal, assert_raises_rpc_error, get_rpc_proxy, rpc_port, rpc_url
class RPCBindTest(WflscoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.bind_to_localhost_only = False
self.num_nodes = 1
self.supports_cli = False
def setup_network(self):
self.add_nodes(self.num_nodes, None)
def add_options(self, parser):
parser.add_argument("--ipv4", action='store_true', dest="run_ipv4", help="Run ipv4 tests only", default=False)
parser.add_argument("--ipv6", action='store_true', dest="run_ipv6", help="Run ipv6 tests only", default=False)
parser.add_argument("--nonloopback", action='store_true', dest="run_nonloopback", help="Run non-loopback tests only", default=False)
def run_bind_test(self, allow_ips, connect_to, addresses, expected):
self.log.info("Bind test for %s" % str(addresses))
expected = [(addr_to_hex(addr), port) for (addr, port) in expected]
base_args = ['-disablewallet', '-nolisten']
if allow_ips:
base_args += ['-rpcallowip=' + x for x in allow_ips]
binds = ['-rpcbind='+addr for addr in addresses]
self.nodes[0].rpchost = connect_to
self.start_node(0, base_args + binds)
pid = self.nodes[0].process.pid
assert_equal(set(get_bind_addrs(pid)), set(expected))
self.stop_nodes()
def run_allowip_test(self, allow_ips, rpchost, rpcport):
self.log.info("Allow IP test for %s:%d" % (rpchost, rpcport))
node_args = \
['-disablewallet', '-nolisten'] + \
['-rpcallowip='+x for x in allow_ips] + \
['-rpcbind='+addr for addr in ['127.0.0.1', "%s:%d" % (rpchost, rpcport)]]
self.nodes[0].rpchost = None
self.start_nodes([node_args])
# connect to node through non-loopback interface
node = get_rpc_proxy(rpc_url(self.nodes[0].datadir, 0, self.chain, "%s:%d" % (rpchost, rpcport)), 0, coveragedir=self.options.coveragedir)
node.getnetworkinfo()
self.stop_nodes()
def run_test(self):
# due to OS-specific network stats queries, this test works only on Linux
if sum([self.options.run_ipv4, self.options.run_ipv6, self.options.run_nonloopback]) > 1:
raise AssertionError("Only one of --ipv4, --ipv6 and --nonloopback can be set")
self.log.info("Check for linux")
if not sys.platform.startswith('linux'):
raise SkipTest("This test can only be run on linux.")
self.log.info("Check for ipv6")
have_ipv6 = test_ipv6_local()
if not have_ipv6 and not (self.options.run_ipv4 or self.options.run_nonloopback):
raise SkipTest("This test requires ipv6 support.")
self.log.info("Check for non-loopback interface")
self.non_loopback_ip = None
for name,ip in all_interfaces():
if ip != '127.0.0.1':
self.non_loopback_ip = ip
break
if self.non_loopback_ip is None and self.options.run_nonloopback:
raise SkipTest("This test requires a non-loopback ip address.")
self.defaultport = rpc_port(0)
if not self.options.run_nonloopback:
self._run_loopback_tests()
if not self.options.run_ipv4 and not self.options.run_ipv6:
self._run_nonloopback_tests()
def _run_loopback_tests(self):
if self.options.run_ipv4:
# check only IPv4 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
[('127.0.0.1', self.defaultport)])
# check only IPv4 localhost (explicit) with alternative port
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
[('127.0.0.1', 32171)])
# check only IPv4 localhost (explicit) with multiple alternative ports on same host
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],
[('127.0.0.1', 32171), ('127.0.0.1', 32172)])
else:
# check default without rpcallowip (IPv4 and IPv6 localhost)
self.run_bind_test(None, '127.0.0.1', [],
[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
# check default with rpcallowip (IPv4 and IPv6 localhost)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', [],
[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
# check only IPv6 localhost (explicit)
self.run_bind_test(['[::1]'], '[::1]', ['[::1]'],
[('::1', self.defaultport)])
# check both IPv4 and IPv6 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],
[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])
def _run_nonloopback_tests(self):
self.log.info("Using interface %s for testing" % self.non_loopback_ip)
# check only non-loopback interface
self.run_bind_test([self.non_loopback_ip], self.non_loopback_ip, [self.non_loopback_ip],
[(self.non_loopback_ip, self.defaultport)])
# Check that with invalid rpcallowip, we are denied
self.run_allowip_test([self.non_loopback_ip], self.non_loopback_ip, self.defaultport)
assert_raises_rpc_error(-342, "non-JSON HTTP response with '403 Forbidden' from server", self.run_allowip_test, ['1.1.1.1'], self.non_loopback_ip, self.defaultport)
if __name__ == '__main__':
RPCBindTest().main()
| true | true |
f72a08a78c04b21dcfa96e85e65cc6f2f670bc47 | 811 | py | Python | tests/test_signed_div.py | Kyle-Kyle/angr | 345b2131a7a67e3a6ffc7d9fd475146a3e12f837 | [
"BSD-2-Clause"
] | 6,132 | 2015-08-06T23:24:47.000Z | 2022-03-31T21:49:34.000Z | tests/test_signed_div.py | Kyle-Kyle/angr | 345b2131a7a67e3a6ffc7d9fd475146a3e12f837 | [
"BSD-2-Clause"
] | 2,272 | 2015-08-10T08:40:07.000Z | 2022-03-31T23:46:44.000Z | tests/test_signed_div.py | Kyle-Kyle/angr | 345b2131a7a67e3a6ffc7d9fd475146a3e12f837 | [
"BSD-2-Clause"
] | 1,155 | 2015-08-06T23:37:39.000Z | 2022-03-31T05:54:11.000Z | import nose
import angr
import subprocess
import sys
import logging
l = logging.getLogger('angr.tests.test_signed_div')
import os
test_location = os.path.dirname(os.path.realpath(__file__))
def test_signed_div():
if not sys.platform.startswith('linux'):
raise nose.SkipTest() # this is not technically required, the run result could just be inlined
test_bin = os.path.join(test_location, "..", "..", "binaries", "tests", "x86_64", "test_signed_div")
b = angr.Project(test_bin)
pg = b.factory.simulation_manager()
pg.explore()
out_angr = pg.deadended[0].posix.dumps(1)
proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE)
stdout_real, _ = proc.communicate()
nose.tools.assert_equal(out_angr, stdout_real)
if __name__ == "__main__":
test_signed_div()
| 27.965517 | 104 | 0.713933 | import nose
import angr
import subprocess
import sys
import logging
l = logging.getLogger('angr.tests.test_signed_div')
import os
test_location = os.path.dirname(os.path.realpath(__file__))
def test_signed_div():
if not sys.platform.startswith('linux'):
raise nose.SkipTest()
test_bin = os.path.join(test_location, "..", "..", "binaries", "tests", "x86_64", "test_signed_div")
b = angr.Project(test_bin)
pg = b.factory.simulation_manager()
pg.explore()
out_angr = pg.deadended[0].posix.dumps(1)
proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE)
stdout_real, _ = proc.communicate()
nose.tools.assert_equal(out_angr, stdout_real)
if __name__ == "__main__":
test_signed_div()
| true | true |
f72a08f672564050206b34774a4683b486883a04 | 1,134 | py | Python | ocrd_anybaseocr/cli/cli.py | syedsaqibbukhari/docanalysis | dfbafa582fb652dffa30fb188190cb98f26116a3 | [
"Apache-2.0"
] | 13 | 2018-11-06T10:18:09.000Z | 2021-12-14T08:14:09.000Z | ocrd_anybaseocr/cli/cli.py | syedsaqibbukhari/docanalysis | dfbafa582fb652dffa30fb188190cb98f26116a3 | [
"Apache-2.0"
] | 34 | 2018-11-06T11:30:21.000Z | 2019-07-31T17:18:30.000Z | ocrd_anybaseocr/cli/cli.py | syedsaqibbukhari/docanalysis | dfbafa582fb652dffa30fb188190cb98f26116a3 | [
"Apache-2.0"
] | 7 | 2018-11-06T11:30:23.000Z | 2021-12-14T08:14:13.000Z | import click
from ocrd.decorators import ocrd_cli_options, ocrd_cli_wrap_processor
from ocrd_anybaseocr.cli.ocrd_anybaseocr_cropping import OcrdAnybaseocrCropper
from ocrd_anybaseocr.cli.ocrd_anybaseocr_deskew import OcrdAnybaseocrDeskewer
from ocrd_anybaseocr.cli.ocrd_anybaseocr_binarize import OcrdAnybaseocrBinarizer
from ocrd_anybaseocr.cli.ocrd_anybaseocr_dewarp import OcrdAnybaseocrDewarper
@click.command()
@ocrd_cli_options
def ocrd_anybaseocr_cropping(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrCropper, *args, **kwargs)
@click.command()
@ocrd_cli_options
def ocrd_anybaseocr_deskew(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrDeskewer, *args, **kwargs)
@click.command()
@ocrd_cli_options
def ocrd_anybaseocr_binarize(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrBinarizer, *args, **kwargs)
@click.command()
# @click.option('--pix2pixhd',type=click.Path(), help="Path to pix2pixHD library.",required=True)
@ocrd_cli_options
def ocrd_anybaseocr_dewarp(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrDewarper, *args, **kwargs)
| 34.363636 | 97 | 0.826279 | import click
from ocrd.decorators import ocrd_cli_options, ocrd_cli_wrap_processor
from ocrd_anybaseocr.cli.ocrd_anybaseocr_cropping import OcrdAnybaseocrCropper
from ocrd_anybaseocr.cli.ocrd_anybaseocr_deskew import OcrdAnybaseocrDeskewer
from ocrd_anybaseocr.cli.ocrd_anybaseocr_binarize import OcrdAnybaseocrBinarizer
from ocrd_anybaseocr.cli.ocrd_anybaseocr_dewarp import OcrdAnybaseocrDewarper
@click.command()
@ocrd_cli_options
def ocrd_anybaseocr_cropping(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrCropper, *args, **kwargs)
@click.command()
@ocrd_cli_options
def ocrd_anybaseocr_deskew(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrDeskewer, *args, **kwargs)
@click.command()
@ocrd_cli_options
def ocrd_anybaseocr_binarize(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrBinarizer, *args, **kwargs)
@click.command()
@ocrd_cli_options
def ocrd_anybaseocr_dewarp(*args, **kwargs):
return ocrd_cli_wrap_processor(OcrdAnybaseocrDewarper, *args, **kwargs)
| true | true |
f72a0a6137a9d63eef214277f2b6c20c57c75e5e | 23,003 | py | Python | sdks/python/client/argo_workflows/model/github_com_argoproj_labs_argo_dataflow_api_v1alpha1_abstract_volume_source.py | parallel-domain/argo-workflows | c055b48b6e216dcdeb1c9840f14199a72329bdaf | [
"Apache-2.0"
] | 1 | 2022-02-24T01:45:03.000Z | 2022-02-24T01:45:03.000Z | sdks/python/client/argo_workflows/model/github_com_argoproj_labs_argo_dataflow_api_v1alpha1_abstract_volume_source.py | parallel-domain/argo-workflows | c055b48b6e216dcdeb1c9840f14199a72329bdaf | [
"Apache-2.0"
] | 18 | 2022-02-01T23:09:58.000Z | 2022-03-31T23:28:41.000Z | sdks/python/client/argo_workflows/model/github_com_argoproj_labs_argo_dataflow_api_v1alpha1_abstract_volume_source.py | parallel-domain/argo-workflows | c055b48b6e216dcdeb1c9840f14199a72329bdaf | [
"Apache-2.0"
] | null | null | null | """
Argo Workflows API
Argo Workflows is an open source container-native workflow engine for orchestrating parallel jobs on Kubernetes. For more information, please see https://argoproj.github.io/argo-workflows/ # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from argo_workflows.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
from ..model_utils import OpenApiModel
from argo_workflows.exceptions import ApiAttributeError
def lazy_import():
from argo_workflows.model.aws_elastic_block_store_volume_source import AWSElasticBlockStoreVolumeSource
from argo_workflows.model.azure_disk_volume_source import AzureDiskVolumeSource
from argo_workflows.model.azure_file_volume_source import AzureFileVolumeSource
from argo_workflows.model.ceph_fs_volume_source import CephFSVolumeSource
from argo_workflows.model.cinder_volume_source import CinderVolumeSource
from argo_workflows.model.config_map_volume_source import ConfigMapVolumeSource
from argo_workflows.model.csi_volume_source import CSIVolumeSource
from argo_workflows.model.downward_api_volume_source import DownwardAPIVolumeSource
from argo_workflows.model.empty_dir_volume_source import EmptyDirVolumeSource
from argo_workflows.model.ephemeral_volume_source import EphemeralVolumeSource
from argo_workflows.model.fc_volume_source import FCVolumeSource
from argo_workflows.model.flex_volume_source import FlexVolumeSource
from argo_workflows.model.flocker_volume_source import FlockerVolumeSource
from argo_workflows.model.gce_persistent_disk_volume_source import GCEPersistentDiskVolumeSource
from argo_workflows.model.git_repo_volume_source import GitRepoVolumeSource
from argo_workflows.model.glusterfs_volume_source import GlusterfsVolumeSource
from argo_workflows.model.host_path_volume_source import HostPathVolumeSource
from argo_workflows.model.iscsi_volume_source import ISCSIVolumeSource
from argo_workflows.model.nfs_volume_source import NFSVolumeSource
from argo_workflows.model.persistent_volume_claim_volume_source import PersistentVolumeClaimVolumeSource
from argo_workflows.model.photon_persistent_disk_volume_source import PhotonPersistentDiskVolumeSource
from argo_workflows.model.portworx_volume_source import PortworxVolumeSource
from argo_workflows.model.projected_volume_source import ProjectedVolumeSource
from argo_workflows.model.quobyte_volume_source import QuobyteVolumeSource
from argo_workflows.model.rbd_volume_source import RBDVolumeSource
from argo_workflows.model.scale_io_volume_source import ScaleIOVolumeSource
from argo_workflows.model.secret_volume_source import SecretVolumeSource
from argo_workflows.model.storage_os_volume_source import StorageOSVolumeSource
from argo_workflows.model.vsphere_virtual_disk_volume_source import VsphereVirtualDiskVolumeSource
globals()['AWSElasticBlockStoreVolumeSource'] = AWSElasticBlockStoreVolumeSource
globals()['AzureDiskVolumeSource'] = AzureDiskVolumeSource
globals()['AzureFileVolumeSource'] = AzureFileVolumeSource
globals()['CSIVolumeSource'] = CSIVolumeSource
globals()['CephFSVolumeSource'] = CephFSVolumeSource
globals()['CinderVolumeSource'] = CinderVolumeSource
globals()['ConfigMapVolumeSource'] = ConfigMapVolumeSource
globals()['DownwardAPIVolumeSource'] = DownwardAPIVolumeSource
globals()['EmptyDirVolumeSource'] = EmptyDirVolumeSource
globals()['EphemeralVolumeSource'] = EphemeralVolumeSource
globals()['FCVolumeSource'] = FCVolumeSource
globals()['FlexVolumeSource'] = FlexVolumeSource
globals()['FlockerVolumeSource'] = FlockerVolumeSource
globals()['GCEPersistentDiskVolumeSource'] = GCEPersistentDiskVolumeSource
globals()['GitRepoVolumeSource'] = GitRepoVolumeSource
globals()['GlusterfsVolumeSource'] = GlusterfsVolumeSource
globals()['HostPathVolumeSource'] = HostPathVolumeSource
globals()['ISCSIVolumeSource'] = ISCSIVolumeSource
globals()['NFSVolumeSource'] = NFSVolumeSource
globals()['PersistentVolumeClaimVolumeSource'] = PersistentVolumeClaimVolumeSource
globals()['PhotonPersistentDiskVolumeSource'] = PhotonPersistentDiskVolumeSource
globals()['PortworxVolumeSource'] = PortworxVolumeSource
globals()['ProjectedVolumeSource'] = ProjectedVolumeSource
globals()['QuobyteVolumeSource'] = QuobyteVolumeSource
globals()['RBDVolumeSource'] = RBDVolumeSource
globals()['ScaleIOVolumeSource'] = ScaleIOVolumeSource
globals()['SecretVolumeSource'] = SecretVolumeSource
globals()['StorageOSVolumeSource'] = StorageOSVolumeSource
globals()['VsphereVirtualDiskVolumeSource'] = VsphereVirtualDiskVolumeSource
class GithubComArgoprojLabsArgoDataflowApiV1alpha1AbstractVolumeSource(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'aws_elastic_block_store': (AWSElasticBlockStoreVolumeSource,), # noqa: E501
'azure_disk': (AzureDiskVolumeSource,), # noqa: E501
'azure_file': (AzureFileVolumeSource,), # noqa: E501
'cephfs': (CephFSVolumeSource,), # noqa: E501
'cinder': (CinderVolumeSource,), # noqa: E501
'config_map': (ConfigMapVolumeSource,), # noqa: E501
'csi': (CSIVolumeSource,), # noqa: E501
'downward_api': (DownwardAPIVolumeSource,), # noqa: E501
'empty_dir': (EmptyDirVolumeSource,), # noqa: E501
'ephemeral': (EphemeralVolumeSource,), # noqa: E501
'fc': (FCVolumeSource,), # noqa: E501
'flex_volume': (FlexVolumeSource,), # noqa: E501
'flocker': (FlockerVolumeSource,), # noqa: E501
'gce_persistent_disk': (GCEPersistentDiskVolumeSource,), # noqa: E501
'git_repo': (GitRepoVolumeSource,), # noqa: E501
'glusterfs': (GlusterfsVolumeSource,), # noqa: E501
'host_path': (HostPathVolumeSource,), # noqa: E501
'iscsi': (ISCSIVolumeSource,), # noqa: E501
'nfs': (NFSVolumeSource,), # noqa: E501
'persistent_volume_claim': (PersistentVolumeClaimVolumeSource,), # noqa: E501
'photon_persistent_disk': (PhotonPersistentDiskVolumeSource,), # noqa: E501
'portworx_volume': (PortworxVolumeSource,), # noqa: E501
'projected': (ProjectedVolumeSource,), # noqa: E501
'quobyte': (QuobyteVolumeSource,), # noqa: E501
'rbd': (RBDVolumeSource,), # noqa: E501
'scale_io': (ScaleIOVolumeSource,), # noqa: E501
'secret': (SecretVolumeSource,), # noqa: E501
'storageos': (StorageOSVolumeSource,), # noqa: E501
'vsphere_volume': (VsphereVirtualDiskVolumeSource,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'aws_elastic_block_store': 'awsElasticBlockStore', # noqa: E501
'azure_disk': 'azureDisk', # noqa: E501
'azure_file': 'azureFile', # noqa: E501
'cephfs': 'cephfs', # noqa: E501
'cinder': 'cinder', # noqa: E501
'config_map': 'configMap', # noqa: E501
'csi': 'csi', # noqa: E501
'downward_api': 'downwardAPI', # noqa: E501
'empty_dir': 'emptyDir', # noqa: E501
'ephemeral': 'ephemeral', # noqa: E501
'fc': 'fc', # noqa: E501
'flex_volume': 'flexVolume', # noqa: E501
'flocker': 'flocker', # noqa: E501
'gce_persistent_disk': 'gcePersistentDisk', # noqa: E501
'git_repo': 'gitRepo', # noqa: E501
'glusterfs': 'glusterfs', # noqa: E501
'host_path': 'hostPath', # noqa: E501
'iscsi': 'iscsi', # noqa: E501
'nfs': 'nfs', # noqa: E501
'persistent_volume_claim': 'persistentVolumeClaim', # noqa: E501
'photon_persistent_disk': 'photonPersistentDisk', # noqa: E501
'portworx_volume': 'portworxVolume', # noqa: E501
'projected': 'projected', # noqa: E501
'quobyte': 'quobyte', # noqa: E501
'rbd': 'rbd', # noqa: E501
'scale_io': 'scaleIO', # noqa: E501
'secret': 'secret', # noqa: E501
'storageos': 'storageos', # noqa: E501
'vsphere_volume': 'vsphereVolume', # noqa: E501
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, *args, **kwargs): # noqa: E501
"""GithubComArgoprojLabsArgoDataflowApiV1alpha1AbstractVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
aws_elastic_block_store (AWSElasticBlockStoreVolumeSource): [optional] # noqa: E501
azure_disk (AzureDiskVolumeSource): [optional] # noqa: E501
azure_file (AzureFileVolumeSource): [optional] # noqa: E501
cephfs (CephFSVolumeSource): [optional] # noqa: E501
cinder (CinderVolumeSource): [optional] # noqa: E501
config_map (ConfigMapVolumeSource): [optional] # noqa: E501
csi (CSIVolumeSource): [optional] # noqa: E501
downward_api (DownwardAPIVolumeSource): [optional] # noqa: E501
empty_dir (EmptyDirVolumeSource): [optional] # noqa: E501
ephemeral (EphemeralVolumeSource): [optional] # noqa: E501
fc (FCVolumeSource): [optional] # noqa: E501
flex_volume (FlexVolumeSource): [optional] # noqa: E501
flocker (FlockerVolumeSource): [optional] # noqa: E501
gce_persistent_disk (GCEPersistentDiskVolumeSource): [optional] # noqa: E501
git_repo (GitRepoVolumeSource): [optional] # noqa: E501
glusterfs (GlusterfsVolumeSource): [optional] # noqa: E501
host_path (HostPathVolumeSource): [optional] # noqa: E501
iscsi (ISCSIVolumeSource): [optional] # noqa: E501
nfs (NFSVolumeSource): [optional] # noqa: E501
persistent_volume_claim (PersistentVolumeClaimVolumeSource): [optional] # noqa: E501
photon_persistent_disk (PhotonPersistentDiskVolumeSource): [optional] # noqa: E501
portworx_volume (PortworxVolumeSource): [optional] # noqa: E501
projected (ProjectedVolumeSource): [optional] # noqa: E501
quobyte (QuobyteVolumeSource): [optional] # noqa: E501
rbd (RBDVolumeSource): [optional] # noqa: E501
scale_io (ScaleIOVolumeSource): [optional] # noqa: E501
secret (SecretVolumeSource): [optional] # noqa: E501
storageos (StorageOSVolumeSource): [optional] # noqa: E501
vsphere_volume (VsphereVirtualDiskVolumeSource): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""GithubComArgoprojLabsArgoDataflowApiV1alpha1AbstractVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
aws_elastic_block_store (AWSElasticBlockStoreVolumeSource): [optional] # noqa: E501
azure_disk (AzureDiskVolumeSource): [optional] # noqa: E501
azure_file (AzureFileVolumeSource): [optional] # noqa: E501
cephfs (CephFSVolumeSource): [optional] # noqa: E501
cinder (CinderVolumeSource): [optional] # noqa: E501
config_map (ConfigMapVolumeSource): [optional] # noqa: E501
csi (CSIVolumeSource): [optional] # noqa: E501
downward_api (DownwardAPIVolumeSource): [optional] # noqa: E501
empty_dir (EmptyDirVolumeSource): [optional] # noqa: E501
ephemeral (EphemeralVolumeSource): [optional] # noqa: E501
fc (FCVolumeSource): [optional] # noqa: E501
flex_volume (FlexVolumeSource): [optional] # noqa: E501
flocker (FlockerVolumeSource): [optional] # noqa: E501
gce_persistent_disk (GCEPersistentDiskVolumeSource): [optional] # noqa: E501
git_repo (GitRepoVolumeSource): [optional] # noqa: E501
glusterfs (GlusterfsVolumeSource): [optional] # noqa: E501
host_path (HostPathVolumeSource): [optional] # noqa: E501
iscsi (ISCSIVolumeSource): [optional] # noqa: E501
nfs (NFSVolumeSource): [optional] # noqa: E501
persistent_volume_claim (PersistentVolumeClaimVolumeSource): [optional] # noqa: E501
photon_persistent_disk (PhotonPersistentDiskVolumeSource): [optional] # noqa: E501
portworx_volume (PortworxVolumeSource): [optional] # noqa: E501
projected (ProjectedVolumeSource): [optional] # noqa: E501
quobyte (QuobyteVolumeSource): [optional] # noqa: E501
rbd (RBDVolumeSource): [optional] # noqa: E501
scale_io (ScaleIOVolumeSource): [optional] # noqa: E501
secret (SecretVolumeSource): [optional] # noqa: E501
storageos (StorageOSVolumeSource): [optional] # noqa: E501
vsphere_volume (VsphereVirtualDiskVolumeSource): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| 53.495349 | 206 | 0.638221 |
import re
import sys
from argo_workflows.model_utils import (
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
from ..model_utils import OpenApiModel
from argo_workflows.exceptions import ApiAttributeError
def lazy_import():
from argo_workflows.model.aws_elastic_block_store_volume_source import AWSElasticBlockStoreVolumeSource
from argo_workflows.model.azure_disk_volume_source import AzureDiskVolumeSource
from argo_workflows.model.azure_file_volume_source import AzureFileVolumeSource
from argo_workflows.model.ceph_fs_volume_source import CephFSVolumeSource
from argo_workflows.model.cinder_volume_source import CinderVolumeSource
from argo_workflows.model.config_map_volume_source import ConfigMapVolumeSource
from argo_workflows.model.csi_volume_source import CSIVolumeSource
from argo_workflows.model.downward_api_volume_source import DownwardAPIVolumeSource
from argo_workflows.model.empty_dir_volume_source import EmptyDirVolumeSource
from argo_workflows.model.ephemeral_volume_source import EphemeralVolumeSource
from argo_workflows.model.fc_volume_source import FCVolumeSource
from argo_workflows.model.flex_volume_source import FlexVolumeSource
from argo_workflows.model.flocker_volume_source import FlockerVolumeSource
from argo_workflows.model.gce_persistent_disk_volume_source import GCEPersistentDiskVolumeSource
from argo_workflows.model.git_repo_volume_source import GitRepoVolumeSource
from argo_workflows.model.glusterfs_volume_source import GlusterfsVolumeSource
from argo_workflows.model.host_path_volume_source import HostPathVolumeSource
from argo_workflows.model.iscsi_volume_source import ISCSIVolumeSource
from argo_workflows.model.nfs_volume_source import NFSVolumeSource
from argo_workflows.model.persistent_volume_claim_volume_source import PersistentVolumeClaimVolumeSource
from argo_workflows.model.photon_persistent_disk_volume_source import PhotonPersistentDiskVolumeSource
from argo_workflows.model.portworx_volume_source import PortworxVolumeSource
from argo_workflows.model.projected_volume_source import ProjectedVolumeSource
from argo_workflows.model.quobyte_volume_source import QuobyteVolumeSource
from argo_workflows.model.rbd_volume_source import RBDVolumeSource
from argo_workflows.model.scale_io_volume_source import ScaleIOVolumeSource
from argo_workflows.model.secret_volume_source import SecretVolumeSource
from argo_workflows.model.storage_os_volume_source import StorageOSVolumeSource
from argo_workflows.model.vsphere_virtual_disk_volume_source import VsphereVirtualDiskVolumeSource
globals()['AWSElasticBlockStoreVolumeSource'] = AWSElasticBlockStoreVolumeSource
globals()['AzureDiskVolumeSource'] = AzureDiskVolumeSource
globals()['AzureFileVolumeSource'] = AzureFileVolumeSource
globals()['CSIVolumeSource'] = CSIVolumeSource
globals()['CephFSVolumeSource'] = CephFSVolumeSource
globals()['CinderVolumeSource'] = CinderVolumeSource
globals()['ConfigMapVolumeSource'] = ConfigMapVolumeSource
globals()['DownwardAPIVolumeSource'] = DownwardAPIVolumeSource
globals()['EmptyDirVolumeSource'] = EmptyDirVolumeSource
globals()['EphemeralVolumeSource'] = EphemeralVolumeSource
globals()['FCVolumeSource'] = FCVolumeSource
globals()['FlexVolumeSource'] = FlexVolumeSource
globals()['FlockerVolumeSource'] = FlockerVolumeSource
globals()['GCEPersistentDiskVolumeSource'] = GCEPersistentDiskVolumeSource
globals()['GitRepoVolumeSource'] = GitRepoVolumeSource
globals()['GlusterfsVolumeSource'] = GlusterfsVolumeSource
globals()['HostPathVolumeSource'] = HostPathVolumeSource
globals()['ISCSIVolumeSource'] = ISCSIVolumeSource
globals()['NFSVolumeSource'] = NFSVolumeSource
globals()['PersistentVolumeClaimVolumeSource'] = PersistentVolumeClaimVolumeSource
globals()['PhotonPersistentDiskVolumeSource'] = PhotonPersistentDiskVolumeSource
globals()['PortworxVolumeSource'] = PortworxVolumeSource
globals()['ProjectedVolumeSource'] = ProjectedVolumeSource
globals()['QuobyteVolumeSource'] = QuobyteVolumeSource
globals()['RBDVolumeSource'] = RBDVolumeSource
globals()['ScaleIOVolumeSource'] = ScaleIOVolumeSource
globals()['SecretVolumeSource'] = SecretVolumeSource
globals()['StorageOSVolumeSource'] = StorageOSVolumeSource
globals()['VsphereVirtualDiskVolumeSource'] = VsphereVirtualDiskVolumeSource
class GithubComArgoprojLabsArgoDataflowApiV1alpha1AbstractVolumeSource(ModelNormal):
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
_nullable = False
@cached_property
def openapi_types():
lazy_import()
return {
'aws_elastic_block_store': (AWSElasticBlockStoreVolumeSource,),
'azure_disk': (AzureDiskVolumeSource,),
'azure_file': (AzureFileVolumeSource,),
'cephfs': (CephFSVolumeSource,),
'cinder': (CinderVolumeSource,),
'config_map': (ConfigMapVolumeSource,),
'csi': (CSIVolumeSource,),
'downward_api': (DownwardAPIVolumeSource,),
'empty_dir': (EmptyDirVolumeSource,),
'ephemeral': (EphemeralVolumeSource,),
'fc': (FCVolumeSource,),
'flex_volume': (FlexVolumeSource,),
'flocker': (FlockerVolumeSource,),
'gce_persistent_disk': (GCEPersistentDiskVolumeSource,),
'git_repo': (GitRepoVolumeSource,),
'glusterfs': (GlusterfsVolumeSource,),
'host_path': (HostPathVolumeSource,),
'iscsi': (ISCSIVolumeSource,),
'nfs': (NFSVolumeSource,),
'persistent_volume_claim': (PersistentVolumeClaimVolumeSource,),
'photon_persistent_disk': (PhotonPersistentDiskVolumeSource,),
'portworx_volume': (PortworxVolumeSource,),
'projected': (ProjectedVolumeSource,),
'quobyte': (QuobyteVolumeSource,),
'rbd': (RBDVolumeSource,),
'scale_io': (ScaleIOVolumeSource,),
'secret': (SecretVolumeSource,),
'storageos': (StorageOSVolumeSource,),
'vsphere_volume': (VsphereVirtualDiskVolumeSource,),
}
@cached_property
def discriminator():
return None
attribute_map = {
'aws_elastic_block_store': 'awsElasticBlockStore',
'azure_disk': 'azureDisk',
'azure_file': 'azureFile',
'cephfs': 'cephfs',
'cinder': 'cinder',
'config_map': 'configMap',
'csi': 'csi',
'downward_api': 'downwardAPI',
'empty_dir': 'emptyDir',
'ephemeral': 'ephemeral',
'fc': 'fc',
'flex_volume': 'flexVolume',
'flocker': 'flocker',
'gce_persistent_disk': 'gcePersistentDisk',
'git_repo': 'gitRepo',
'glusterfs': 'glusterfs',
'host_path': 'hostPath',
'iscsi': 'iscsi',
'nfs': 'nfs',
'persistent_volume_claim': 'persistentVolumeClaim',
'photon_persistent_disk': 'photonPersistentDisk',
'portworx_volume': 'portworxVolume',
'projected': 'projected',
'quobyte': 'quobyte',
'rbd': 'rbd',
'scale_io': 'scaleIO',
'secret': 'secret',
'storageos': 'storageos',
'vsphere_volume': 'vsphereVolume',
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, *args, **kwargs):
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| true | true |
f72a0ab6ac97478fa1a78bb583dacb7f9f8e3690 | 1,317 | py | Python | python/network/Foundations-of-Python-Network-Programming/foundations-of-python-network-programming/foundations-of-python-network-programming/python3/13/ehlo.py | bosserbosser/codetest | 987563900d912e891b53eeda8e2cf36f3c769430 | [
"Apache-2.0"
] | 1 | 2018-01-15T08:38:09.000Z | 2018-01-15T08:38:09.000Z | python/network/Foundations-of-Python-Network-Programming/foundations-of-python-network-programming/foundations-of-python-network-programming/python3/13/ehlo.py | bosserbosser/codetest | 987563900d912e891b53eeda8e2cf36f3c769430 | [
"Apache-2.0"
] | null | null | null | python/network/Foundations-of-Python-Network-Programming/foundations-of-python-network-programming/foundations-of-python-network-programming/python3/13/ehlo.py | bosserbosser/codetest | 987563900d912e891b53eeda8e2cf36f3c769430 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# SMTP transmission with manual EHLO - Chapter 13 - ehlo.py
import sys, smtplib, socket
if len(sys.argv) < 4:
print("usage: %s server fromaddr toaddr [toaddr...]" % sys.argv[0])
sys.exit(2)
server, fromaddr, toaddrs = sys.argv[1], sys.argv[2], sys.argv[3:]
message = """To: %s
From: %s
Subject: Test Message from simple.py
Hello,
This is a test message sent to you from the ehlo.py program
in Foundations of Python Network Programming.
""" % (', '.join(toaddrs), fromaddr)
try:
s = smtplib.SMTP(server)
code = s.ehlo()[0]
uses_esmtp = (200 <= code <= 299)
if not uses_esmtp:
code = s.helo()[0]
if not (200 <= code <= 299):
print("Remote server refused HELO; code:", code)
sys.exit(1)
if uses_esmtp and s.has_extn('size'):
print("Maximum message size is", s.esmtp_features['size'])
if len(message) > int(s.esmtp_features['size']):
print("Message too large; aborting.")
sys.exit(1)
s.sendmail(fromaddr, toaddrs, message)
except (socket.gaierror, socket.error, socket.herror,
smtplib.SMTPException) as e:
print(" *** Your message may not have been sent!")
print(e)
sys.exit(1)
else:
print("Message successfully sent to %d recipient(s)" % len(toaddrs))
| 28.021277 | 72 | 0.626424 |
import sys, smtplib, socket
if len(sys.argv) < 4:
print("usage: %s server fromaddr toaddr [toaddr...]" % sys.argv[0])
sys.exit(2)
server, fromaddr, toaddrs = sys.argv[1], sys.argv[2], sys.argv[3:]
message = """To: %s
From: %s
Subject: Test Message from simple.py
Hello,
This is a test message sent to you from the ehlo.py program
in Foundations of Python Network Programming.
""" % (', '.join(toaddrs), fromaddr)
try:
s = smtplib.SMTP(server)
code = s.ehlo()[0]
uses_esmtp = (200 <= code <= 299)
if not uses_esmtp:
code = s.helo()[0]
if not (200 <= code <= 299):
print("Remote server refused HELO; code:", code)
sys.exit(1)
if uses_esmtp and s.has_extn('size'):
print("Maximum message size is", s.esmtp_features['size'])
if len(message) > int(s.esmtp_features['size']):
print("Message too large; aborting.")
sys.exit(1)
s.sendmail(fromaddr, toaddrs, message)
except (socket.gaierror, socket.error, socket.herror,
smtplib.SMTPException) as e:
print(" *** Your message may not have been sent!")
print(e)
sys.exit(1)
else:
print("Message successfully sent to %d recipient(s)" % len(toaddrs))
| true | true |
f72a0bad6b85d668e5c4ae43b5b676d8ca9196fc | 1,556 | py | Python | setup.py | teakfi/imodels | 0144698c5c9b919b2640cb8e2caac3a9124a2a0e | [
"MIT"
] | null | null | null | setup.py | teakfi/imodels | 0144698c5c9b919b2640cb8e2caac3a9124a2a0e | [
"MIT"
] | null | null | null | setup.py | teakfi/imodels | 0144698c5c9b919b2640cb8e2caac3a9124a2a0e | [
"MIT"
] | null | null | null | import setuptools
from os import path
path_to_repo = path.abspath(path.dirname(__file__))
with open(path.join(path_to_repo, 'readme.md'), encoding='utf-8') as f:
long_description = f.read()
required_pypi = [
'corels==1.1.29', # we only provide a basic wrapper around corels
# optionally requires cvxpy for slim
# optionally requires gosdt
'mlxtend>=0.18.0', # some lower version are missing fpgrowth
'numpy',
'pandas',
'scipy',
'scikit-learn>=0.23.0', # 0.23+ only works on py3.6+
]
setuptools.setup(
name="imodels",
version="1.2.0",
author="Chandan Singh, Keyan Nasseri, Bin Yu, and others",
author_email="chandan_singh@berkeley.edu",
description="Implementations of various interpretable models",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/csinva/imodels",
packages=setuptools.find_packages(
exclude=['tests', 'tests.*', '*.test.*']
),
install_requires=required_pypi,
extras_require={
'dev': [
'dvu',
'gdown',
'jupyter',
'jupytext',
'matplotlib',
'pytest',
'pytest-cov',
'slurmpy',
'tqdm',
'pmlb',
# docs also require pdoc3, irf, torch
]
},
python_requires='>=3.6',
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| 28.290909 | 71 | 0.595116 | import setuptools
from os import path
path_to_repo = path.abspath(path.dirname(__file__))
with open(path.join(path_to_repo, 'readme.md'), encoding='utf-8') as f:
long_description = f.read()
required_pypi = [
'corels==1.1.29',
'mlxtend>=0.18.0',
'numpy',
'pandas',
'scipy',
'scikit-learn>=0.23.0',
]
setuptools.setup(
name="imodels",
version="1.2.0",
author="Chandan Singh, Keyan Nasseri, Bin Yu, and others",
author_email="chandan_singh@berkeley.edu",
description="Implementations of various interpretable models",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/csinva/imodels",
packages=setuptools.find_packages(
exclude=['tests', 'tests.*', '*.test.*']
),
install_requires=required_pypi,
extras_require={
'dev': [
'dvu',
'gdown',
'jupyter',
'jupytext',
'matplotlib',
'pytest',
'pytest-cov',
'slurmpy',
'tqdm',
'pmlb',
]
},
python_requires='>=3.6',
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| true | true |
f72a0be1d879b2f7d828562e7d4742f9459fae21 | 1,120 | py | Python | test/test_website_group.py | JeremyTangCD/lm-sdk-python | 2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983 | [
"Apache-2.0"
] | null | null | null | test/test_website_group.py | JeremyTangCD/lm-sdk-python | 2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983 | [
"Apache-2.0"
] | null | null | null | test/test_website_group.py | JeremyTangCD/lm-sdk-python | 2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
LogicMonitor REST API
LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account programmatically. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import logicmonitor_sdk
from logicmonitor_sdk.models.website_group import WebsiteGroup # noqa: E501
from logicmonitor_sdk.rest import ApiException
class TestWebsiteGroup(unittest.TestCase):
"""WebsiteGroup unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testWebsiteGroup(self):
"""Test WebsiteGroup"""
# FIXME: construct object with mandatory attributes with example values
# model = logicmonitor_sdk.models.website_group.WebsiteGroup() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| 27.317073 | 304 | 0.738393 |
from __future__ import absolute_import
import unittest
import logicmonitor_sdk
from logicmonitor_sdk.models.website_group import WebsiteGroup
from logicmonitor_sdk.rest import ApiException
class TestWebsiteGroup(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testWebsiteGroup(self):
s
if __name__ == '__main__':
unittest.main()
| true | true |
f72a0c82f7cfe696f88c2b9b07cb2123643e2f08 | 22,572 | py | Python | scripts/pl_sequence_train.py | louis2889184/sg2im | 6df2095bf58703c7d6d74bf47535a7cf45690bc0 | [
"Apache-2.0"
] | null | null | null | scripts/pl_sequence_train.py | louis2889184/sg2im | 6df2095bf58703c7d6d74bf47535a7cf45690bc0 | [
"Apache-2.0"
] | null | null | null | scripts/pl_sequence_train.py | louis2889184/sg2im | 6df2095bf58703c7d6d74bf47535a7cf45690bc0 | [
"Apache-2.0"
] | null | null | null | import os
import json
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from collections import OrderedDict
from sg2im.utils import timeit, bool_flag, LossManager
from sg2im.utils import int_tuple, float_tuple, str_tuple
from sg2im.data.vg import SequenceTransformerVgSceneGraphDataset
import pytorch_lightning as pl
from transformers import (
BertTokenizerFast,
BertTokenizer,
EncoderDecoderModel,
EncoderDecoderConfig,
AutoModel,
BertForSequenceClassification,
)
from pytorch_lightning.plugins import DDPPlugin
VG_DIR = os.path.expanduser('datasets/vg')
COCO_DIR = os.path.expanduser('datasets/coco')
parser = argparse.ArgumentParser()
parser.add_argument('--test', action='store_true', default=False)
parser.add_argument('--dataset', default='coco', choices=['vg', 'coco'])
parser.add_argument('--scene_graphs_json', default='scene_graphs/figure_6_sheep.json')
parser.add_argument('--load_checkpoint', default="")
# Optimization hyperparameters
parser.add_argument('--batch_size', default=32, type=int)
parser.add_argument('--num_iterations', default=1000000, type=int)
parser.add_argument('--learning_rate', default=1e-5, type=float)
parser.add_argument('--gpus', default=1, type=int)
# Switch the generator to eval mode after this many iterations
parser.add_argument('--eval_mode_after', default=100000, type=int)
# Dataset options common to both VG and COCO
parser.add_argument('--image_size', default='64,64', type=int_tuple)
parser.add_argument('--num_train_samples', default=None, type=int)
parser.add_argument('--num_val_samples', default=1024, type=int)
parser.add_argument('--shuffle_val', default=True, type=bool_flag)
parser.add_argument('--loader_num_workers', default=4, type=int)
parser.add_argument('--include_relationships', default=True, type=bool_flag)
# VG-specific options
parser.add_argument('--vg_image_dir', default=os.path.join(VG_DIR, 'images'))
parser.add_argument('--train_h5', default=os.path.join(VG_DIR, 'train.h5'))
parser.add_argument('--val_h5', default=os.path.join(VG_DIR, 'val.h5'))
parser.add_argument('--vocab_json', default=os.path.join(VG_DIR, 'vocab.json'))
parser.add_argument('--max_objects_per_image', default=10, type=int)
parser.add_argument('--vg_use_orphaned_objects', default=True, type=bool_flag)
# COCO-specific options
parser.add_argument('--coco_train_image_dir',
default=os.path.join(COCO_DIR, 'images/train2017'))
parser.add_argument('--coco_val_image_dir',
default=os.path.join(COCO_DIR, 'images/val2017'))
parser.add_argument('--coco_train_instances_json',
default=os.path.join(COCO_DIR, 'annotations/instances_train2017.json'))
parser.add_argument('--coco_train_stuff_json',
default=os.path.join(COCO_DIR, 'annotations/stuff_train2017.json'))
parser.add_argument('--coco_val_instances_json',
default=os.path.join(COCO_DIR, 'annotations/instances_val2017.json'))
parser.add_argument('--coco_val_stuff_json',
default=os.path.join(COCO_DIR, 'annotations/stuff_val2017.json'))
parser.add_argument('--instance_whitelist', default=None, type=str_tuple)
parser.add_argument('--stuff_whitelist', default=None, type=str_tuple)
parser.add_argument('--coco_include_other', default=False, type=bool_flag)
parser.add_argument('--min_object_size', default=0.02, type=float)
parser.add_argument('--min_objects_per_image', default=3, type=int)
parser.add_argument('--coco_stuff_only', default=True, type=bool_flag)
parser.add_argument('--max_lengths_for_image', default=1024, type=int)
# Generator options
parser.add_argument('--mask_size', default=16, type=int) # Set this to 0 to use no masks
parser.add_argument('--embedding_dim', default=128, type=int)
parser.add_argument('--gconv_dim', default=128, type=int)
parser.add_argument('--gconv_hidden_dim', default=512, type=int)
parser.add_argument('--gconv_num_layers', default=5, type=int)
parser.add_argument('--mlp_normalization', default='none', type=str)
parser.add_argument('--refinement_network_dims', default='1024,512,256,128,64', type=int_tuple)
parser.add_argument('--normalization', default='batch')
parser.add_argument('--activation', default='leakyrelu-0.2')
parser.add_argument('--layout_noise_dim', default=32, type=int)
parser.add_argument('--use_boxes_pred_after', default=-1, type=int)
# Generator losses
parser.add_argument('--mask_loss_weight', default=0, type=float)
parser.add_argument('--l1_pixel_loss_weight', default=1.0, type=float)
parser.add_argument('--bbox_pred_loss_weight', default=10, type=float)
parser.add_argument('--predicate_pred_loss_weight', default=0, type=float) # DEPRECATED
# Generic discriminator options
parser.add_argument('--discriminator_loss_weight', default=0.01, type=float)
parser.add_argument('--gan_loss_type', default='gan')
parser.add_argument('--d_clip', default=None, type=float)
parser.add_argument('--d_normalization', default='batch')
parser.add_argument('--d_padding', default='valid')
parser.add_argument('--d_activation', default='leakyrelu-0.2')
# Object discriminator
parser.add_argument('--d_obj_arch',
default='C4-64-2,C4-128-2,C4-256-2')
parser.add_argument('--crop_size', default=32, type=int)
parser.add_argument('--d_obj_weight', default=1.0, type=float) # multiplied by d_loss_weight
parser.add_argument('--ac_loss_weight', default=0.1, type=float)
# Image discriminator
parser.add_argument('--d_img_arch',
default='C4-64-2,C4-128-2,C4-256-2')
parser.add_argument('--d_img_weight', default=1.0, type=float) # multiplied by d_loss_weight
# Output options
parser.add_argument('--print_every', default=10, type=int)
parser.add_argument('--timing', default=False, type=bool_flag)
parser.add_argument('--checkpoint_every', default=10000, type=int)
parser.add_argument('--output_dir', default=os.getcwd())
parser.add_argument('--checkpoint_name', default='checkpoint')
parser.add_argument('--checkpoint_start_from', default=None)
parser.add_argument('--restore_from_checkpoint', default=False, type=bool_flag)
class VGDataModule(pl.LightningDataModule):
def __init__(self, args, tokenizer, num_workers=8):
super().__init__()
self.args = args
self.tokenizer = tokenizer
self.num_workers = num_workers
self.batch_size = args.batch_size
def setup(self, stage=None):
args = self.args
with open(args.vocab_json, 'r') as f:
vocab = json.load(f)
dset_kwargs = {
'vocab': vocab,
'h5_path': args.train_h5,
'image_dir': args.vg_image_dir,
'image_size': args.image_size,
'max_samples': args.num_train_samples,
'max_objects': args.max_objects_per_image,
'use_orphaned_objects': args.vg_use_orphaned_objects,
'include_relationships': args.include_relationships,
'max_lengths_for_image': args.max_lengths_for_image
}
train_dset = SequenceTransformerVgSceneGraphDataset(
**dset_kwargs, tokenizer=self.tokenizer
)
# iter_per_epoch = len(train_dset) // args.batch_size
# print('There are %d iterations per epoch' % iter_per_epoch)
dset_kwargs['h5_path'] = args.val_h5
del dset_kwargs['max_samples']
val_dset = SequenceTransformerVgSceneGraphDataset(
**dset_kwargs, tokenizer=self.tokenizer
)
self.train_dset = train_dset
self.val_dset = val_dset
def train_dataloader(self):
return DataLoader(
self.train_dset, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=True
)
def val_dataloader(self):
return DataLoader(self.val_dset, batch_size=self.batch_size, num_workers=self.num_workers)
def test_dataloader(self):
return DataLoader(self.val_dset, batch_size=self.batch_size, num_workers=self.num_workers)
class Discriminator(nn.Module):
def __init__(self, backbone):
super().__init__()
self.backbone = BertForSequenceClassification.from_pretrained(backbone)
def forward(self, *args, **kwargs):
outputs = self.backbone(*args, **kwargs)
return outputs["loss"]
def apply_word_embeddings(self, inputs):
"""
Because Gumbel softmax outputs cannot directly feed to huggingface model,
we have to compute the `input_embed` manually.
"""
word_embeddings = self.backbone.bert.embeddings.word_embeddings
return torch.matmul(inputs, word_embeddings.weight)
class Generator(nn.Module):
def __init__(self, backbone):
super().__init__()
self.backbone = EncoderDecoderModel.from_encoder_decoder_pretrained(
backbone, backbone, tie_encoder_decoder=True
)
def forward(self, *args, **kwargs):
return self.backbone(*args, **kwargs)
def forward_logits(self, *args, **kwargs):
return self.backbone(*args, **kwargs)["logits"]
def forward_loss(self, *args, **kwargs):
return self.backbone(*args, **kwargs)["loss"]
def apply_word_embeddings(self, inputs):
"""
Because Gumbel softmax outputs cannot directly feed to huggingface model,
we have to compute the `input_embed` manually.
"""
word_embeddings = self.backbone.encoder.embeddings.word_embeddings
return torch.matmul(inputs, word_embeddings.weight)
class GAN(pl.LightningModule):
def __init__(
self,
args,
tokenizer,
backbone=None,
):
super().__init__()
self.args = args
self.validation_z = torch.randn(8, 100)
self.tokenizer = tokenizer
self.discriminator = Discriminator(backbone)
self.generator = Generator(backbone)
self.graph_special_token = "[graph]"
self.image_special_token = "[image]"
self.tau = 1
self.image_token_id_list, self.text_token_id_list = self.retrieve_bad_image_text_tokens_ids()
def retrieve_bad_image_text_tokens_ids(self):
special_tokens_list = ["[CLS]", "[SEP]"]
image_tokens_list = [f"[itoken{i}]" for i in range(512)]
extra_image_tokens_list = [f"[itoken{i}]" for i in range(512, 32 * 32)]
vocab = self.tokenizer.get_vocab()
special_tokens_id_list = [vocab[token] for token in special_tokens_list]
image_token_id_list = [vocab[token] for token in image_tokens_list]
extra_image_tokens_id_list = [vocab[token] for token in extra_image_tokens_list]
text_token_id_list = [v for k, v in vocab.items()]
text_token_id_list = \
list(set(text_token_id_list) - set(image_token_id_list) - set(extra_image_tokens_id_list))
return image_token_id_list + extra_image_tokens_id_list, text_token_id_list + extra_image_tokens_id_list
def adversarial_loss(self, y_hat, y):
return F.binary_cross_entropy_with_logits(y_hat, y)
def training_step(self, batch, batch_idx, optimizer_idx):
# sample noise
# z = torch.randn(imgs.shape[0], self.hparams.latent_dim)
# z = z.type_as(imgs)
generator_batch = {
"input_ids": batch["sent_input/input_ids"],
"attention_mask": batch["sent_input/attention_mask"],
"decoder_input_ids": batch["code_output/input_ids"],
"decoder_attention_mask": batch["code_output/attention_mask"],
"labels": batch["code_output/input_ids"].clone()
}
# exlude the loss for padding tokens
generator_batch["labels"][generator_batch["labels"] == self.tokenizer.pad_token_id] = -100
# train generator
if optimizer_idx == 0:
logits = self.generator.forward_logits(**generator_batch)
predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)
# log sampled images
# sample_imgs = self.generated_imgs[:6]
# grid = torchvision.utils.make_grid(sample_imgs)
# self.logger.experiment.add_image('generated_images', grid, 0)
# ground truth result (ie: all fake)
# put on GPU because we created this tensor inside training_loop
predictions_embedding = self.generator.apply_word_embeddings(predictions)
fake_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"decoder_input_ids": batch["sent_output/input_ids"],
"decoder_attention_mask": batch["sent_output/attention_mask"],
"labels": batch["sent_output/input_ids"].clone()
}
fake_batch["labels"][fake_batch["labels"] == self.tokenizer.pad_token_id] = -100
ac_loss = self.generator.forward_loss(**fake_batch)
predictions_embedding = self.discriminator.apply_word_embeddings(predictions)
fake_dis_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"labels": torch.ones(predictions_embedding.shape[0]).type_as(predictions_embedding).long()
}
g_d_loss = self.discriminator(**fake_dis_batch)
g_loss = g_d_loss + ac_loss
# g_loss = ac_loss
self.log('g_ac_loss', ac_loss, prog_bar=True)
self.log('g_d_loss', g_d_loss, prog_bar=True)
# return {"loss": g_loss}
# train discriminator (inverse generator)
# if optimizer_idx == 1:
# Measure discriminator's ability to classify real from generated samples
logits = self.generator.forward_logits(**generator_batch)
predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)
# don't compute the gradients of the generator
predictions = predictions.detach()
predictions_embedding = self.generator.apply_word_embeddings(predictions)
fake_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"decoder_input_ids": batch["sent_output/input_ids"],
"decoder_attention_mask": batch["sent_output/attention_mask"],
"labels": batch["sent_output/input_ids"].clone()
}
fake_batch["labels"][fake_batch["labels"] == self.tokenizer.pad_token_id] = -100
fake_ac_loss = self.generator.forward_loss(**fake_batch)
# For real data
real_batch = {
"input_ids": batch["code_output/input_ids"],
"attention_mask": batch["code_output/attention_mask"],
"decoder_input_ids": batch["sent_output/input_ids"],
"decoder_attention_mask": batch["sent_output/attention_mask"],
"labels": batch["sent_output/input_ids"].clone()
}
real_batch["labels"][real_batch["labels"] == self.tokenizer.pad_token_id] = -100
real_ac_loss = self.generator.forward_loss(**real_batch)
ac_loss = (real_ac_loss + fake_ac_loss) / 2
self.log('ac_loss', ac_loss, prog_bar=True)
# return {"loss": ac_loss}
return g_loss + ac_loss
# train discriminator
if optimizer_idx == 1:
# Measure discriminator's ability to classify real from generated samples
logits = self.generator.forward_logits(**generator_batch)
# don't compute the gradients of the generator
predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)
predictions_embedding = self.discriminator.apply_word_embeddings(predictions)
fake_dis_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"labels": torch.zeros(predictions.shape[0]).type_as(predictions).long()
}
fake_loss = self.discriminator(**fake_dis_batch)
# fake = torch.zeros(fake_preds.shape)
# fake = fake.type_as(fake_preds)
# fake_loss = self.adversarial_loss(fake_preds, fake)
real_dis_batch = {
"input_ids": batch["code_output/input_ids"],
"attention_mask": batch["code_output/attention_mask"],
"labels": torch.ones(predictions.shape[0]).type_as(predictions).long()
}
real_loss = self.discriminator(**real_dis_batch)
# real = torch.ones(real_preds.shape)
# real = real.type_as(real_preds)
# real_loss = self.adversarial_loss(real_preds, real)
# discriminator loss is the average of these
d_loss = (real_loss + fake_loss) / 2
self.log('d_loss', d_loss, prog_bar=True)
return d_loss
def configure_optimizers(self):
lr = self.args.learning_rate
opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(
self.discriminator.parameters(),
lr=lr,
betas=(0.5, 0.999)
)
return [opt_g, opt_d], []
# def on_epoch_end(self):
# z = self.validation_z.type_as(self.generator.model[0].weight)
# # log sampled images
# sample_imgs = self(z)
# grid = torchvision.utils.make_grid(sample_imgs)
# self.logger.experiment.add_image('generated_images', grid, self.current_epoch)
def test_step(self, batch, batch_idx):
pass
def inference(self, scene_graphs_json):
scene_graphs = self.read_scene_graphs(scene_graphs_json)
image_tokens_generation = self.generator.backbone.generate(
scene_graphs["input_ids"],
max_length=66,
# num_beams=5,
# no_repeat_ngram_size=2,
# early_stopping=True,
do_sample=True,
top_p=0.92,
top_k=0,
decoder_start_token_id=self.generator.backbone.config.decoder.pad_token_id,
bad_words_ids=[[ids] for ids in self.text_token_id_list],
)
print(image_tokens_generation)
output = []
for data in image_tokens_generation:
output.append(self.tokenizer.decode(data, skip_special_tokens=True))
print(output[-1])
reconstructed_graph = self.generator.backbone.generate(
image_tokens_generation,
max_length=64,
# num_beams=5,
# no_repeat_ngram_size=2,
# early_stopping=True,
do_sample=True,
top_p=0.92,
top_k=0,
decoder_start_token_id=self.generator.backbone.config.decoder.pad_token_id,
bad_words_ids=[[ids]for ids in self.image_token_id_list],
)
for data in reconstructed_graph:
print(self.tokenizer.decode(data, skip_special_tokens=True))
if not os.path.exists(self.args.output_dir):
os.makedirs(self.args.output_dir)
itokens_output_file = os.path.join(self.args.output_dir, "itokens_output.json")
with open(itokens_output_file, "w") as f:
json.dump(output, f, indent=2)
def read_scene_graphs(self, scene_graphs_json):
with open(scene_graphs_json, 'r') as f:
scene_graphs = json.load(f)
if isinstance(scene_graphs, dict):
# We just got a single scene graph, so promote it to a list
scene_graphs = [scene_graphs]
objs, triples, obj_to_img = [], [], []
obj_offset = 0
sents_list = []
for i, sg in enumerate(scene_graphs):
# Insert dummy __image__ object and __in_image__ relationships
sents = []
for s, p, o in sg['relationships']:
sent = f"{sg['objects'][s]} {p} {sg['objects'][o]}."
sents.append(sent)
sent = " ".join(sents)
sent = f"{self.graph_special_token} {sent} {self.image_special_token}"
sents_list.append(sent)
print(sent)
sent_tensor = self.tokenizer(
sents_list,
return_tensors="pt",
padding="max_length",
max_length=64,
truncation=True,
add_special_tokens=False
)
device = next(self.parameters()).device
sent_tensor = {k: v.to(device) for k, v in sent_tensor.items()}
return sent_tensor
def main(args):
backbone = "bert-base-uncased-itokens"
tokenizer = BertTokenizerFast.from_pretrained(backbone)
# encoder_decoder_config = EncoderDecoderConfig.from_pretrained("bert-base-uncased-itokens")
# model = EncoderDecoderModel.from_pretrained(
# "bert-base-uncased-itokens", config=encoder_decoder_config
# )
# model = EncoderDecoderModel.from_encoder_decoder_pretrained(
# "bert-base-uncased-itokens", "bert-base-uncased-itokens", tie_encoder_decoder=True
# )
# generator = Generator(model)
# discriminator = Discriminator(
# AutoModel.from_pretrained("bert-base-uncased-itokens")
# )
if args.test:
model = GAN.load_from_checkpoint(
args.load_checkpoint,
args=args,
tokenizer=tokenizer,
backbone=backbone
)
model.cuda()
model.eval()
model.inference(args.scene_graphs_json)
return
# train
if args.gpus > 1:
dm = VGDataModule(args, tokenizer, 2)
else:
dm = VGDataModule(args, tokenizer)
if args.load_checkpoint != "":
model = GAN.load_from_checkpoint(
args.load_checkpoint,
args=args,
tokenizer=tokenizer,
backbone=backbone
)
else:
model = GAN(args, tokenizer, backbone)
training_args = {
"gpus": args.gpus,
"fast_dev_run": False,
"max_steps": args.num_iterations,
"precision": 32,
"gradient_clip_val": 1,
}
if args.gpus > 1:
additional_args = {
"accelerator": "ddp",
"plugins": [DDPPlugin(find_unused_parameters=True)]
# "plugins": [my_ddp]
}
training_args.update(additional_args)
trainer = pl.Trainer(**training_args)
trainer.fit(model, dm)
if __name__ == "__main__":
args = parser.parse_args()
main(args) | 37.557404 | 112 | 0.659357 | import os
import json
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from collections import OrderedDict
from sg2im.utils import timeit, bool_flag, LossManager
from sg2im.utils import int_tuple, float_tuple, str_tuple
from sg2im.data.vg import SequenceTransformerVgSceneGraphDataset
import pytorch_lightning as pl
from transformers import (
BertTokenizerFast,
BertTokenizer,
EncoderDecoderModel,
EncoderDecoderConfig,
AutoModel,
BertForSequenceClassification,
)
from pytorch_lightning.plugins import DDPPlugin
VG_DIR = os.path.expanduser('datasets/vg')
COCO_DIR = os.path.expanduser('datasets/coco')
parser = argparse.ArgumentParser()
parser.add_argument('--test', action='store_true', default=False)
parser.add_argument('--dataset', default='coco', choices=['vg', 'coco'])
parser.add_argument('--scene_graphs_json', default='scene_graphs/figure_6_sheep.json')
parser.add_argument('--load_checkpoint', default="")
parser.add_argument('--batch_size', default=32, type=int)
parser.add_argument('--num_iterations', default=1000000, type=int)
parser.add_argument('--learning_rate', default=1e-5, type=float)
parser.add_argument('--gpus', default=1, type=int)
parser.add_argument('--eval_mode_after', default=100000, type=int)
parser.add_argument('--image_size', default='64,64', type=int_tuple)
parser.add_argument('--num_train_samples', default=None, type=int)
parser.add_argument('--num_val_samples', default=1024, type=int)
parser.add_argument('--shuffle_val', default=True, type=bool_flag)
parser.add_argument('--loader_num_workers', default=4, type=int)
parser.add_argument('--include_relationships', default=True, type=bool_flag)
parser.add_argument('--vg_image_dir', default=os.path.join(VG_DIR, 'images'))
parser.add_argument('--train_h5', default=os.path.join(VG_DIR, 'train.h5'))
parser.add_argument('--val_h5', default=os.path.join(VG_DIR, 'val.h5'))
parser.add_argument('--vocab_json', default=os.path.join(VG_DIR, 'vocab.json'))
parser.add_argument('--max_objects_per_image', default=10, type=int)
parser.add_argument('--vg_use_orphaned_objects', default=True, type=bool_flag)
parser.add_argument('--coco_train_image_dir',
default=os.path.join(COCO_DIR, 'images/train2017'))
parser.add_argument('--coco_val_image_dir',
default=os.path.join(COCO_DIR, 'images/val2017'))
parser.add_argument('--coco_train_instances_json',
default=os.path.join(COCO_DIR, 'annotations/instances_train2017.json'))
parser.add_argument('--coco_train_stuff_json',
default=os.path.join(COCO_DIR, 'annotations/stuff_train2017.json'))
parser.add_argument('--coco_val_instances_json',
default=os.path.join(COCO_DIR, 'annotations/instances_val2017.json'))
parser.add_argument('--coco_val_stuff_json',
default=os.path.join(COCO_DIR, 'annotations/stuff_val2017.json'))
parser.add_argument('--instance_whitelist', default=None, type=str_tuple)
parser.add_argument('--stuff_whitelist', default=None, type=str_tuple)
parser.add_argument('--coco_include_other', default=False, type=bool_flag)
parser.add_argument('--min_object_size', default=0.02, type=float)
parser.add_argument('--min_objects_per_image', default=3, type=int)
parser.add_argument('--coco_stuff_only', default=True, type=bool_flag)
parser.add_argument('--max_lengths_for_image', default=1024, type=int)
parser.add_argument('--mask_size', default=16, type=int)
parser.add_argument('--embedding_dim', default=128, type=int)
parser.add_argument('--gconv_dim', default=128, type=int)
parser.add_argument('--gconv_hidden_dim', default=512, type=int)
parser.add_argument('--gconv_num_layers', default=5, type=int)
parser.add_argument('--mlp_normalization', default='none', type=str)
parser.add_argument('--refinement_network_dims', default='1024,512,256,128,64', type=int_tuple)
parser.add_argument('--normalization', default='batch')
parser.add_argument('--activation', default='leakyrelu-0.2')
parser.add_argument('--layout_noise_dim', default=32, type=int)
parser.add_argument('--use_boxes_pred_after', default=-1, type=int)
parser.add_argument('--mask_loss_weight', default=0, type=float)
parser.add_argument('--l1_pixel_loss_weight', default=1.0, type=float)
parser.add_argument('--bbox_pred_loss_weight', default=10, type=float)
parser.add_argument('--predicate_pred_loss_weight', default=0, type=float)
parser.add_argument('--discriminator_loss_weight', default=0.01, type=float)
parser.add_argument('--gan_loss_type', default='gan')
parser.add_argument('--d_clip', default=None, type=float)
parser.add_argument('--d_normalization', default='batch')
parser.add_argument('--d_padding', default='valid')
parser.add_argument('--d_activation', default='leakyrelu-0.2')
parser.add_argument('--d_obj_arch',
default='C4-64-2,C4-128-2,C4-256-2')
parser.add_argument('--crop_size', default=32, type=int)
parser.add_argument('--d_obj_weight', default=1.0, type=float)
parser.add_argument('--ac_loss_weight', default=0.1, type=float)
parser.add_argument('--d_img_arch',
default='C4-64-2,C4-128-2,C4-256-2')
parser.add_argument('--d_img_weight', default=1.0, type=float)
parser.add_argument('--print_every', default=10, type=int)
parser.add_argument('--timing', default=False, type=bool_flag)
parser.add_argument('--checkpoint_every', default=10000, type=int)
parser.add_argument('--output_dir', default=os.getcwd())
parser.add_argument('--checkpoint_name', default='checkpoint')
parser.add_argument('--checkpoint_start_from', default=None)
parser.add_argument('--restore_from_checkpoint', default=False, type=bool_flag)
class VGDataModule(pl.LightningDataModule):
def __init__(self, args, tokenizer, num_workers=8):
super().__init__()
self.args = args
self.tokenizer = tokenizer
self.num_workers = num_workers
self.batch_size = args.batch_size
def setup(self, stage=None):
args = self.args
with open(args.vocab_json, 'r') as f:
vocab = json.load(f)
dset_kwargs = {
'vocab': vocab,
'h5_path': args.train_h5,
'image_dir': args.vg_image_dir,
'image_size': args.image_size,
'max_samples': args.num_train_samples,
'max_objects': args.max_objects_per_image,
'use_orphaned_objects': args.vg_use_orphaned_objects,
'include_relationships': args.include_relationships,
'max_lengths_for_image': args.max_lengths_for_image
}
train_dset = SequenceTransformerVgSceneGraphDataset(
**dset_kwargs, tokenizer=self.tokenizer
)
dset_kwargs['h5_path'] = args.val_h5
del dset_kwargs['max_samples']
val_dset = SequenceTransformerVgSceneGraphDataset(
**dset_kwargs, tokenizer=self.tokenizer
)
self.train_dset = train_dset
self.val_dset = val_dset
def train_dataloader(self):
return DataLoader(
self.train_dset, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=True
)
def val_dataloader(self):
return DataLoader(self.val_dset, batch_size=self.batch_size, num_workers=self.num_workers)
def test_dataloader(self):
return DataLoader(self.val_dset, batch_size=self.batch_size, num_workers=self.num_workers)
class Discriminator(nn.Module):
def __init__(self, backbone):
super().__init__()
self.backbone = BertForSequenceClassification.from_pretrained(backbone)
def forward(self, *args, **kwargs):
outputs = self.backbone(*args, **kwargs)
return outputs["loss"]
def apply_word_embeddings(self, inputs):
word_embeddings = self.backbone.bert.embeddings.word_embeddings
return torch.matmul(inputs, word_embeddings.weight)
class Generator(nn.Module):
def __init__(self, backbone):
super().__init__()
self.backbone = EncoderDecoderModel.from_encoder_decoder_pretrained(
backbone, backbone, tie_encoder_decoder=True
)
def forward(self, *args, **kwargs):
return self.backbone(*args, **kwargs)
def forward_logits(self, *args, **kwargs):
return self.backbone(*args, **kwargs)["logits"]
def forward_loss(self, *args, **kwargs):
return self.backbone(*args, **kwargs)["loss"]
def apply_word_embeddings(self, inputs):
word_embeddings = self.backbone.encoder.embeddings.word_embeddings
return torch.matmul(inputs, word_embeddings.weight)
class GAN(pl.LightningModule):
def __init__(
self,
args,
tokenizer,
backbone=None,
):
super().__init__()
self.args = args
self.validation_z = torch.randn(8, 100)
self.tokenizer = tokenizer
self.discriminator = Discriminator(backbone)
self.generator = Generator(backbone)
self.graph_special_token = "[graph]"
self.image_special_token = "[image]"
self.tau = 1
self.image_token_id_list, self.text_token_id_list = self.retrieve_bad_image_text_tokens_ids()
def retrieve_bad_image_text_tokens_ids(self):
special_tokens_list = ["[CLS]", "[SEP]"]
image_tokens_list = [f"[itoken{i}]" for i in range(512)]
extra_image_tokens_list = [f"[itoken{i}]" for i in range(512, 32 * 32)]
vocab = self.tokenizer.get_vocab()
special_tokens_id_list = [vocab[token] for token in special_tokens_list]
image_token_id_list = [vocab[token] for token in image_tokens_list]
extra_image_tokens_id_list = [vocab[token] for token in extra_image_tokens_list]
text_token_id_list = [v for k, v in vocab.items()]
text_token_id_list = \
list(set(text_token_id_list) - set(image_token_id_list) - set(extra_image_tokens_id_list))
return image_token_id_list + extra_image_tokens_id_list, text_token_id_list + extra_image_tokens_id_list
def adversarial_loss(self, y_hat, y):
return F.binary_cross_entropy_with_logits(y_hat, y)
def training_step(self, batch, batch_idx, optimizer_idx):
generator_batch = {
"input_ids": batch["sent_input/input_ids"],
"attention_mask": batch["sent_input/attention_mask"],
"decoder_input_ids": batch["code_output/input_ids"],
"decoder_attention_mask": batch["code_output/attention_mask"],
"labels": batch["code_output/input_ids"].clone()
}
generator_batch["labels"][generator_batch["labels"] == self.tokenizer.pad_token_id] = -100
if optimizer_idx == 0:
logits = self.generator.forward_logits(**generator_batch)
predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)
predictions_embedding = self.generator.apply_word_embeddings(predictions)
fake_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"decoder_input_ids": batch["sent_output/input_ids"],
"decoder_attention_mask": batch["sent_output/attention_mask"],
"labels": batch["sent_output/input_ids"].clone()
}
fake_batch["labels"][fake_batch["labels"] == self.tokenizer.pad_token_id] = -100
ac_loss = self.generator.forward_loss(**fake_batch)
predictions_embedding = self.discriminator.apply_word_embeddings(predictions)
fake_dis_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"labels": torch.ones(predictions_embedding.shape[0]).type_as(predictions_embedding).long()
}
g_d_loss = self.discriminator(**fake_dis_batch)
g_loss = g_d_loss + ac_loss
self.log('g_ac_loss', ac_loss, prog_bar=True)
self.log('g_d_loss', g_d_loss, prog_bar=True)
logits = self.generator.forward_logits(**generator_batch)
predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)
# don't compute the gradients of the generator
predictions = predictions.detach()
predictions_embedding = self.generator.apply_word_embeddings(predictions)
fake_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"decoder_input_ids": batch["sent_output/input_ids"],
"decoder_attention_mask": batch["sent_output/attention_mask"],
"labels": batch["sent_output/input_ids"].clone()
}
fake_batch["labels"][fake_batch["labels"] == self.tokenizer.pad_token_id] = -100
fake_ac_loss = self.generator.forward_loss(**fake_batch)
real_batch = {
"input_ids": batch["code_output/input_ids"],
"attention_mask": batch["code_output/attention_mask"],
"decoder_input_ids": batch["sent_output/input_ids"],
"decoder_attention_mask": batch["sent_output/attention_mask"],
"labels": batch["sent_output/input_ids"].clone()
}
real_batch["labels"][real_batch["labels"] == self.tokenizer.pad_token_id] = -100
real_ac_loss = self.generator.forward_loss(**real_batch)
ac_loss = (real_ac_loss + fake_ac_loss) / 2
self.log('ac_loss', ac_loss, prog_bar=True)
return g_loss + ac_loss
if optimizer_idx == 1:
logits = self.generator.forward_logits(**generator_batch)
# don't compute the gradients of the generator
predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)
predictions_embedding = self.discriminator.apply_word_embeddings(predictions)
fake_dis_batch = {
"inputs_embeds": predictions_embedding,
"attention_mask": batch["code_output/attention_mask"],
"labels": torch.zeros(predictions.shape[0]).type_as(predictions).long()
}
fake_loss = self.discriminator(**fake_dis_batch)
real_dis_batch = {
"input_ids": batch["code_output/input_ids"],
"attention_mask": batch["code_output/attention_mask"],
"labels": torch.ones(predictions.shape[0]).type_as(predictions).long()
}
real_loss = self.discriminator(**real_dis_batch)
d_loss = (real_loss + fake_loss) / 2
self.log('d_loss', d_loss, prog_bar=True)
return d_loss
def configure_optimizers(self):
lr = self.args.learning_rate
opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(
self.discriminator.parameters(),
lr=lr,
betas=(0.5, 0.999)
)
return [opt_g, opt_d], []
def test_step(self, batch, batch_idx):
pass
def inference(self, scene_graphs_json):
scene_graphs = self.read_scene_graphs(scene_graphs_json)
image_tokens_generation = self.generator.backbone.generate(
scene_graphs["input_ids"],
max_length=66,
do_sample=True,
top_p=0.92,
top_k=0,
decoder_start_token_id=self.generator.backbone.config.decoder.pad_token_id,
bad_words_ids=[[ids] for ids in self.text_token_id_list],
)
print(image_tokens_generation)
output = []
for data in image_tokens_generation:
output.append(self.tokenizer.decode(data, skip_special_tokens=True))
print(output[-1])
reconstructed_graph = self.generator.backbone.generate(
image_tokens_generation,
max_length=64,
do_sample=True,
top_p=0.92,
top_k=0,
decoder_start_token_id=self.generator.backbone.config.decoder.pad_token_id,
bad_words_ids=[[ids]for ids in self.image_token_id_list],
)
for data in reconstructed_graph:
print(self.tokenizer.decode(data, skip_special_tokens=True))
if not os.path.exists(self.args.output_dir):
os.makedirs(self.args.output_dir)
itokens_output_file = os.path.join(self.args.output_dir, "itokens_output.json")
with open(itokens_output_file, "w") as f:
json.dump(output, f, indent=2)
def read_scene_graphs(self, scene_graphs_json):
with open(scene_graphs_json, 'r') as f:
scene_graphs = json.load(f)
if isinstance(scene_graphs, dict):
scene_graphs = [scene_graphs]
objs, triples, obj_to_img = [], [], []
obj_offset = 0
sents_list = []
for i, sg in enumerate(scene_graphs):
sents = []
for s, p, o in sg['relationships']:
sent = f"{sg['objects'][s]} {p} {sg['objects'][o]}."
sents.append(sent)
sent = " ".join(sents)
sent = f"{self.graph_special_token} {sent} {self.image_special_token}"
sents_list.append(sent)
print(sent)
sent_tensor = self.tokenizer(
sents_list,
return_tensors="pt",
padding="max_length",
max_length=64,
truncation=True,
add_special_tokens=False
)
device = next(self.parameters()).device
sent_tensor = {k: v.to(device) for k, v in sent_tensor.items()}
return sent_tensor
def main(args):
backbone = "bert-base-uncased-itokens"
tokenizer = BertTokenizerFast.from_pretrained(backbone)
if args.test:
model = GAN.load_from_checkpoint(
args.load_checkpoint,
args=args,
tokenizer=tokenizer,
backbone=backbone
)
model.cuda()
model.eval()
model.inference(args.scene_graphs_json)
return
if args.gpus > 1:
dm = VGDataModule(args, tokenizer, 2)
else:
dm = VGDataModule(args, tokenizer)
if args.load_checkpoint != "":
model = GAN.load_from_checkpoint(
args.load_checkpoint,
args=args,
tokenizer=tokenizer,
backbone=backbone
)
else:
model = GAN(args, tokenizer, backbone)
training_args = {
"gpus": args.gpus,
"fast_dev_run": False,
"max_steps": args.num_iterations,
"precision": 32,
"gradient_clip_val": 1,
}
if args.gpus > 1:
additional_args = {
"accelerator": "ddp",
"plugins": [DDPPlugin(find_unused_parameters=True)]
}
training_args.update(additional_args)
trainer = pl.Trainer(**training_args)
trainer.fit(model, dm)
if __name__ == "__main__":
args = parser.parse_args()
main(args) | true | true |
f72a0dd1e2be9b0b1602963b8427cf6c4cd7c37c | 10,533 | py | Python | src/thorax/affine/niftireg/tools/utils.py | MASILab/registration_tutorial | 8e6763fe0a49ae53211c62be113fcc13185f2b19 | [
"MIT"
] | 1 | 2021-07-25T16:24:27.000Z | 2021-07-25T16:24:27.000Z | src/thorax/affine/niftireg/tools/utils.py | MASILab/registration_tutorial | 8e6763fe0a49ae53211c62be113fcc13185f2b19 | [
"MIT"
] | null | null | null | src/thorax/affine/niftireg/tools/utils.py | MASILab/registration_tutorial | 8e6763fe0a49ae53211c62be113fcc13185f2b19 | [
"MIT"
] | null | null | null | import os
import errno
import math
import shutil
def get_range_paral_chunk(total_num_item, chunk_pair):
num_item_each_chunk = int(math.ceil(float(total_num_item) / float(chunk_pair[1])))
range_lower = num_item_each_chunk * (chunk_pair[0] - 1)
# range_upper = num_item_each_chunk * chunk_pair[0] - 1
range_upper = num_item_each_chunk * chunk_pair[0]
if range_upper > total_num_item:
range_upper = total_num_item
return [range_lower, range_upper]
def get_current_chunk(in_list, chunk_pair):
chunks_list = get_chunks_list(in_list, chunk_pair[1])
current_chunk = chunks_list[chunk_pair[0] - 1]
return current_chunk
def get_chunks_list(in_list, num_chunks):
return [in_list[i::num_chunks] for i in range(num_chunks)]
def get_nii_filepath_and_filename_list(dataset_root):
nii_file_path_list = []
subject_list = os.listdir(dataset_root)
for i in range(len(subject_list)):
subj = subject_list[i]
subj_path = dataset_root + '/' + subj
sess_list = os.listdir(subj_path)
for sess in sess_list:
sess_path = subj_path + '/' + sess
nii_files = os.listdir(sess_path)
for nii_file in nii_files:
nii_file_path = sess_path + '/' + nii_file
nii_file_path_list.append(nii_file_path)
# nii_file_name_list.append(nii_file)
return nii_file_path_list
def get_nii_filepath_and_filename_list_flat(dataset_root):
nii_file_path_list = []
nii_file_name_list = os.listdir(dataset_root)
for file_name in nii_file_name_list:
nii_file_path = os.path.join(dataset_root, file_name)
nii_file_path_list.append(nii_file_path)
return nii_file_path_list
def get_nii_filepath_and_filename_list_hierarchy(dataset_root):
nii_file_path_list = []
nii_file_name_list = []
subject_list = os.listdir(dataset_root)
for i in range(len(subject_list)):
subj = subject_list[i]
subj_path = dataset_root + '/' + subj
sess_list = os.listdir(subj_path)
for sess in sess_list:
sess_path = subj_path + '/' + sess
nii_files = os.listdir(sess_path)
for nii_file in nii_files:
nii_file_path = sess_path + '/' + nii_file
nii_file_path_list.append(nii_file_path)
nii_file_name_list.append(nii_file)
return nii_file_path_list
def get_dataset_path_list(dataset_root, dataset_type):
file_path_list = []
if dataset_type == 'flat':
file_path_list = get_nii_filepath_and_filename_list_flat(dataset_root)
elif dataset_type == 'hierarchy':
file_path_list = get_nii_filepath_and_filename_list(dataset_root)
else:
file_path_list = []
return file_path_list
def resample_spore_nifti(spore_nifti_root, spore_resample_root):
"""
Resample spore data, using c3d
:param spore_nifti_root:
:param spore_resample_root:
:return:
"""
spore_nii_file_path_list = []
spore_nii_file_name_list = []
subject_list = os.listdir(spore_nifti_root)
for i in range(len(subject_list)):
subj = subject_list[i]
subj_path = spore_nifti_root + '/' + subj
sess_list = os.listdir(subj_path)
for sess in sess_list:
sess_path = subj_path + '/' + sess
nii_files = os.listdir(sess_path)
for nii_file in nii_files:
nii_file_path = sess_path + '/' + nii_file
spore_nii_file_path_list.append(nii_file_path)
spore_nii_file_name_list.append(nii_file)
file_count = 1
for iFile in range(len(spore_nii_file_path_list)):
# if file_count > 3:
# break
file_path = spore_nii_file_path_list[iFile]
file_name = spore_nii_file_name_list[iFile]
output_path = spore_resample_root + '/' + file_name
print('Read image: ', file_path)
# command_read_info_str = 'c3d ' + file_path + ' -info-full'
# os.system(command_read_info_str)
command_str = 'c3d ' + file_path + ' -resample 256x256x180 -o ' + output_path
os.system(command_str)
print('Output file: ', file_name, " {}/{}".format(iFile, len(spore_nii_file_name_list)))
# command_image_info_str = 'c3d ' + output_path + ' -info-full'
#
# os.system(command_image_info_str)
file_count = file_count + 1
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def get_image_name_from_path(image_path):
return os.path.basename(image_path)
def dataset_hierarchy_to_flat(in_folder, out_folder):
file_path_list = get_nii_filepath_and_filename_list(in_folder)
for file_path in file_path_list:
file_name = get_image_name_from_path(file_path)
out_path = os.path.join(out_folder, file_name)
if os.path.exists(out_path):
print(out_path + ' already exist')
else:
print('Copy file %s to %s' % (file_path, out_path))
shutil.copyfile(file_path, out_path)
def get_extension(file_full_path):
filename, file_extension = os.path.splitext(file_full_path)
return file_extension
def get_registration_command(registration_method_name, reg_args, reg_tool_root, fixed_image, moving_image, output_image, output_mat):
command_list = []
actual_output_mat_path = output_mat + '_matrix.txt'
if registration_method_name == 'affine_flirt':
flirt_path = os.path.join(reg_tool_root, 'flirt')
command_str = f'{flirt_path} {reg_args} -dof 12 -in {moving_image} -ref {fixed_image} -out {output_image} -omat {output_mat} '
command_list.append(command_str)
elif registration_method_name == 'affine_flirt_zhoubing':
flirt_path = os.path.join(reg_tool_root, 'flirt')
# 1. Rigid.
mid_step_rigid_mat = output_mat + "_rigid.txt"
mid_step_rigid_im = output_mat + "_rigid.nii.gz"
command_list.append(f'{flirt_path} -v -dof 6 -in {moving_image} -ref {fixed_image} -omat {mid_step_rigid_mat} -out {mid_step_rigid_im} -nosearch')
# 2. DOF 9 Affine.
command_list.append(f'{flirt_path} -v -dof 9 -in {moving_image} -ref {fixed_image} -init {mid_step_rigid_mat} -omat {output_mat} -out {output_image} -nosearch')
elif registration_method_name == 'affine_nifty_reg':
# reg_aladin_path = os.path.join(reg_tool_root, 'reg_aladin')
# reg_resample_path = os.path.join(reg_tool_root, 'reg_resample')
# output_mat_real = output_mat.replace('.nii.gz', '.txt')
# output_intensity_clipped = output_image.replace('/reg/', '/temp/').replace('.nii.gz', '_intens_clip_affine.nii.gz')
# preprocessed_image_without_intens_clip = output_image.replace('/reg/', '/temp/sub_1k/')
# output_affine_real = output_image
# command_list.append(f'{reg_aladin_path} -ln 5 -ref {fixed_image} -flo {moving_image} -res {output_intensity_clipped} -aff {output_mat_real}')
# command_list.append(f'{reg_resample_path} -inter 0 -pad -1000 -ref {fixed_image} -flo {preprocessed_image_without_intens_clip} -trans {output_mat_real} -res {output_affine_real}')
reg_aladin_path = os.path.join(reg_tool_root, 'reg_aladin')
# reg_resample_path = os.path.join(reg_tool_root, 'reg_resample')
output_mat_real = output_mat.replace('.nii.gz', '.txt')
# output_intensity_clipped = output_image.replace('/reg/', '/temp/').replace('.nii.gz', '_intens_clip_affine.nii.gz')
# preprocessed_image_without_intens_clip = output_image.replace('/reg/', '/temp/sub_1k/')
command_list.append(f'{reg_aladin_path} -ln 5 -ref {fixed_image} -flo {moving_image} -res {output_image} -aff {output_mat_real}')
# command_list.append(f'{reg_resample_path} -inter 0 -pad -1000 -ref {fixed_image} -flo {preprocessed_image_without_intens_clip} -trans {output_mat_real} -res {output_affine_real}')
elif registration_method_name == 'rigid_nifty_reg':
reg_aladin_path = os.path.join(reg_tool_root, 'reg_aladin')
output_mat_real = output_mat.replace('.nii.gz', '.txt')
command_list.append(
f'{reg_aladin_path} -rigOnly -ln 5 -ref {fixed_image} -flo {moving_image} -res {output_image} -aff {output_mat_real}')
elif registration_method_name == 'affine_deedsBCV':
linearBCVslow_path = os.path.join(reg_tool_root, 'linearBCVslow')
applyLinearBCVfloat_path = os.path.join(reg_tool_root, 'applyLinearBCVfloat')
command_list.append(f'{linearBCVslow_path} -F {fixed_image} -M {moving_image} -O {output_mat}')
command_list.append(f'{applyLinearBCVfloat_path} -M {moving_image} -A {actual_output_mat_path} -D {output_image}')
elif registration_method_name == 'deformable_deedsBCV':
linearBCVslow_path = os.path.join(reg_tool_root, 'linearBCVslow')
deedsBCVslow_path = os.path.join(reg_tool_root, 'deedsBCVslow')
command_list.append(f'{linearBCVslow_path} -F {fixed_image} -M {moving_image} -O {output_mat}')
command_list.append(f'{deedsBCVslow_path} {reg_args} -F {fixed_image} -M {moving_image} -O {output_image} -A {actual_output_mat_path}')
elif registration_method_name == 'deformable_deedsBCV_paral':
linearBCV_path = os.path.join(reg_tool_root, 'linearBCV')
deedsBCV_path = os.path.join(reg_tool_root, 'deedsBCV')
command_list.append(f'{linearBCV_path} -F {fixed_image} -M {moving_image} -O {output_mat}')
command_list.append(f'{deedsBCV_path} {reg_args} -F {fixed_image} -M {moving_image} -O {output_image} -A {actual_output_mat_path}')
else:
command_list.append('TODO')
return command_list
def get_interpolation_command(interp_type_name, bash_config, src_root, moving_image):
command_list = []
file_name = moving_image
real_mat_name = file_name.replace('nii.gz', 'txt')
bash_script_path = ''
if interp_type_name == 'clipped_ori':
bash_script_path = os.path.join(src_root, 'tools/interp_clipped_roi.sh')
elif interp_type_name == 'full_ori':
bash_script_path = os.path.join(src_root, 'tools/interp_full_ori.sh')
elif interp_type_name == 'roi_lung_mask':
bash_script_path = os.path.join(src_root, 'tools/interp_ori_lung_mask.sh')
command_list.append(f'{bash_script_path} {bash_config} {file_name} {real_mat_name}')
return command_list
| 43.168033 | 189 | 0.690686 | import os
import errno
import math
import shutil
def get_range_paral_chunk(total_num_item, chunk_pair):
num_item_each_chunk = int(math.ceil(float(total_num_item) / float(chunk_pair[1])))
range_lower = num_item_each_chunk * (chunk_pair[0] - 1)
range_upper = num_item_each_chunk * chunk_pair[0]
if range_upper > total_num_item:
range_upper = total_num_item
return [range_lower, range_upper]
def get_current_chunk(in_list, chunk_pair):
chunks_list = get_chunks_list(in_list, chunk_pair[1])
current_chunk = chunks_list[chunk_pair[0] - 1]
return current_chunk
def get_chunks_list(in_list, num_chunks):
return [in_list[i::num_chunks] for i in range(num_chunks)]
def get_nii_filepath_and_filename_list(dataset_root):
nii_file_path_list = []
subject_list = os.listdir(dataset_root)
for i in range(len(subject_list)):
subj = subject_list[i]
subj_path = dataset_root + '/' + subj
sess_list = os.listdir(subj_path)
for sess in sess_list:
sess_path = subj_path + '/' + sess
nii_files = os.listdir(sess_path)
for nii_file in nii_files:
nii_file_path = sess_path + '/' + nii_file
nii_file_path_list.append(nii_file_path)
return nii_file_path_list
def get_nii_filepath_and_filename_list_flat(dataset_root):
nii_file_path_list = []
nii_file_name_list = os.listdir(dataset_root)
for file_name in nii_file_name_list:
nii_file_path = os.path.join(dataset_root, file_name)
nii_file_path_list.append(nii_file_path)
return nii_file_path_list
def get_nii_filepath_and_filename_list_hierarchy(dataset_root):
nii_file_path_list = []
nii_file_name_list = []
subject_list = os.listdir(dataset_root)
for i in range(len(subject_list)):
subj = subject_list[i]
subj_path = dataset_root + '/' + subj
sess_list = os.listdir(subj_path)
for sess in sess_list:
sess_path = subj_path + '/' + sess
nii_files = os.listdir(sess_path)
for nii_file in nii_files:
nii_file_path = sess_path + '/' + nii_file
nii_file_path_list.append(nii_file_path)
nii_file_name_list.append(nii_file)
return nii_file_path_list
def get_dataset_path_list(dataset_root, dataset_type):
file_path_list = []
if dataset_type == 'flat':
file_path_list = get_nii_filepath_and_filename_list_flat(dataset_root)
elif dataset_type == 'hierarchy':
file_path_list = get_nii_filepath_and_filename_list(dataset_root)
else:
file_path_list = []
return file_path_list
def resample_spore_nifti(spore_nifti_root, spore_resample_root):
spore_nii_file_path_list = []
spore_nii_file_name_list = []
subject_list = os.listdir(spore_nifti_root)
for i in range(len(subject_list)):
subj = subject_list[i]
subj_path = spore_nifti_root + '/' + subj
sess_list = os.listdir(subj_path)
for sess in sess_list:
sess_path = subj_path + '/' + sess
nii_files = os.listdir(sess_path)
for nii_file in nii_files:
nii_file_path = sess_path + '/' + nii_file
spore_nii_file_path_list.append(nii_file_path)
spore_nii_file_name_list.append(nii_file)
file_count = 1
for iFile in range(len(spore_nii_file_path_list)):
file_path = spore_nii_file_path_list[iFile]
file_name = spore_nii_file_name_list[iFile]
output_path = spore_resample_root + '/' + file_name
print('Read image: ', file_path)
command_str = 'c3d ' + file_path + ' -resample 256x256x180 -o ' + output_path
os.system(command_str)
print('Output file: ', file_name, " {}/{}".format(iFile, len(spore_nii_file_name_list)))
file_count = file_count + 1
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def get_image_name_from_path(image_path):
return os.path.basename(image_path)
def dataset_hierarchy_to_flat(in_folder, out_folder):
file_path_list = get_nii_filepath_and_filename_list(in_folder)
for file_path in file_path_list:
file_name = get_image_name_from_path(file_path)
out_path = os.path.join(out_folder, file_name)
if os.path.exists(out_path):
print(out_path + ' already exist')
else:
print('Copy file %s to %s' % (file_path, out_path))
shutil.copyfile(file_path, out_path)
def get_extension(file_full_path):
filename, file_extension = os.path.splitext(file_full_path)
return file_extension
def get_registration_command(registration_method_name, reg_args, reg_tool_root, fixed_image, moving_image, output_image, output_mat):
command_list = []
actual_output_mat_path = output_mat + '_matrix.txt'
if registration_method_name == 'affine_flirt':
flirt_path = os.path.join(reg_tool_root, 'flirt')
command_str = f'{flirt_path} {reg_args} -dof 12 -in {moving_image} -ref {fixed_image} -out {output_image} -omat {output_mat} '
command_list.append(command_str)
elif registration_method_name == 'affine_flirt_zhoubing':
flirt_path = os.path.join(reg_tool_root, 'flirt')
mid_step_rigid_mat = output_mat + "_rigid.txt"
mid_step_rigid_im = output_mat + "_rigid.nii.gz"
command_list.append(f'{flirt_path} -v -dof 6 -in {moving_image} -ref {fixed_image} -omat {mid_step_rigid_mat} -out {mid_step_rigid_im} -nosearch')
command_list.append(f'{flirt_path} -v -dof 9 -in {moving_image} -ref {fixed_image} -init {mid_step_rigid_mat} -omat {output_mat} -out {output_image} -nosearch')
elif registration_method_name == 'affine_nifty_reg':
reg_aladin_path = os.path.join(reg_tool_root, 'reg_aladin')
output_mat_real = output_mat.replace('.nii.gz', '.txt')
command_list.append(f'{reg_aladin_path} -ln 5 -ref {fixed_image} -flo {moving_image} -res {output_image} -aff {output_mat_real}')
elif registration_method_name == 'rigid_nifty_reg':
reg_aladin_path = os.path.join(reg_tool_root, 'reg_aladin')
output_mat_real = output_mat.replace('.nii.gz', '.txt')
command_list.append(
f'{reg_aladin_path} -rigOnly -ln 5 -ref {fixed_image} -flo {moving_image} -res {output_image} -aff {output_mat_real}')
elif registration_method_name == 'affine_deedsBCV':
linearBCVslow_path = os.path.join(reg_tool_root, 'linearBCVslow')
applyLinearBCVfloat_path = os.path.join(reg_tool_root, 'applyLinearBCVfloat')
command_list.append(f'{linearBCVslow_path} -F {fixed_image} -M {moving_image} -O {output_mat}')
command_list.append(f'{applyLinearBCVfloat_path} -M {moving_image} -A {actual_output_mat_path} -D {output_image}')
elif registration_method_name == 'deformable_deedsBCV':
linearBCVslow_path = os.path.join(reg_tool_root, 'linearBCVslow')
deedsBCVslow_path = os.path.join(reg_tool_root, 'deedsBCVslow')
command_list.append(f'{linearBCVslow_path} -F {fixed_image} -M {moving_image} -O {output_mat}')
command_list.append(f'{deedsBCVslow_path} {reg_args} -F {fixed_image} -M {moving_image} -O {output_image} -A {actual_output_mat_path}')
elif registration_method_name == 'deformable_deedsBCV_paral':
linearBCV_path = os.path.join(reg_tool_root, 'linearBCV')
deedsBCV_path = os.path.join(reg_tool_root, 'deedsBCV')
command_list.append(f'{linearBCV_path} -F {fixed_image} -M {moving_image} -O {output_mat}')
command_list.append(f'{deedsBCV_path} {reg_args} -F {fixed_image} -M {moving_image} -O {output_image} -A {actual_output_mat_path}')
else:
command_list.append('TODO')
return command_list
def get_interpolation_command(interp_type_name, bash_config, src_root, moving_image):
command_list = []
file_name = moving_image
real_mat_name = file_name.replace('nii.gz', 'txt')
bash_script_path = ''
if interp_type_name == 'clipped_ori':
bash_script_path = os.path.join(src_root, 'tools/interp_clipped_roi.sh')
elif interp_type_name == 'full_ori':
bash_script_path = os.path.join(src_root, 'tools/interp_full_ori.sh')
elif interp_type_name == 'roi_lung_mask':
bash_script_path = os.path.join(src_root, 'tools/interp_ori_lung_mask.sh')
command_list.append(f'{bash_script_path} {bash_config} {file_name} {real_mat_name}')
return command_list
| true | true |
f72a0ecb61686900af2bb5227449d8a70ca7b103 | 104 | py | Python | src/lib/models/fastreid/utils/__init__.py | wisematch/KDMOT | 03be0a148fc5d5a43c13a0427c429305b92e6838 | [
"MIT"
] | null | null | null | src/lib/models/fastreid/utils/__init__.py | wisematch/KDMOT | 03be0a148fc5d5a43c13a0427c429305b92e6838 | [
"MIT"
] | null | null | null | src/lib/models/fastreid/utils/__init__.py | wisematch/KDMOT | 03be0a148fc5d5a43c13a0427c429305b92e6838 | [
"MIT"
] | null | null | null | # encoding: utf-8
"""
@author: sherlock
@contact: sherlockliao01@gmail.com
"""
from .registry import * | 14.857143 | 34 | 0.701923 |
from .registry import * | true | true |
f72a0f17a8dcbb9af0ab216980c0570646e12b4d | 17,842 | py | Python | plaso/cli/log2timeline_tool.py | infosecjosh/plaso | 7b5fc33591c60e89afc231a451449d40e02d8985 | [
"Apache-2.0"
] | null | null | null | plaso/cli/log2timeline_tool.py | infosecjosh/plaso | 7b5fc33591c60e89afc231a451449d40e02d8985 | [
"Apache-2.0"
] | null | null | null | plaso/cli/log2timeline_tool.py | infosecjosh/plaso | 7b5fc33591c60e89afc231a451449d40e02d8985 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""The log2timeline CLI tool."""
from __future__ import unicode_literals
import argparse
import os
import sys
import time
import textwrap
from dfvfs.lib import definitions as dfvfs_definitions
import plaso
# The following import makes sure the output modules are registered.
from plaso import output # pylint: disable=unused-import
from plaso.analyzers.hashers import manager as hashers_manager
from plaso.cli import extraction_tool
from plaso.cli import logger
from plaso.cli import status_view
from plaso.cli import tools
from plaso.cli import views
from plaso.cli.helpers import manager as helpers_manager
from plaso.engine import engine
from plaso.engine import single_process as single_process_engine
from plaso.lib import definitions
from plaso.lib import errors
from plaso.lib import loggers
from plaso.multi_processing import task_engine as multi_process_engine
from plaso.parsers import manager as parsers_manager
from plaso.storage import factory as storage_factory
class Log2TimelineTool(extraction_tool.ExtractionTool):
"""Log2timeline CLI tool.
Attributes:
dependencies_check (bool): True if the availability and versions of
dependencies should be checked.
list_hashers (bool): True if the hashers should be listed.
list_parsers_and_plugins (bool): True if the parsers and plugins should
be listed.
list_profilers (bool): True if the profilers should be listed.
show_info (bool): True if information about hashers, parsers, plugins,
etc. should be shown.
"""
NAME = 'log2timeline'
DESCRIPTION = textwrap.dedent('\n'.join([
'',
('log2timeline is a command line tool to extract events from '
'individual '),
'files, recursing a directory (e.g. mount point) or storage media ',
'image or device.',
'',
'More information can be gathered from here:',
' https://plaso.readthedocs.io/en/latest/sources/user/'
'Using-log2timeline.html',
'']))
EPILOG = textwrap.dedent('\n'.join([
'',
'Example usage:',
'',
'Run the tool against a storage media image (full kitchen sink)',
' log2timeline.py /cases/mycase/storage.plaso ímynd.dd',
'',
'Instead of answering questions, indicate some of the options on the',
'command line (including data from particular VSS stores).',
(' log2timeline.py -o 63 --vss_stores 1,2 /cases/plaso_vss.plaso '
'image.E01'),
'',
'And that is how you build a timeline using log2timeline...',
'']))
_SOURCE_TYPES_TO_PREPROCESS = frozenset([
dfvfs_definitions.SOURCE_TYPE_DIRECTORY,
dfvfs_definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE,
dfvfs_definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE])
def __init__(self, input_reader=None, output_writer=None):
"""Initializes a log2timeline CLI tool.
Args:
input_reader (Optional[InputReader]): input reader, where None indicates
that the stdin input reader should be used.
output_writer (Optional[OutputWriter]): output writer, where None
indicates that the stdout output writer should be used.
"""
super(Log2TimelineTool, self).__init__(
input_reader=input_reader, output_writer=output_writer)
self._command_line_arguments = None
self._enable_sigsegv_handler = False
self._number_of_extraction_workers = 0
self._storage_serializer_format = definitions.SERIALIZER_FORMAT_JSON
self._source_type = None
self._status_view = status_view.StatusView(self._output_writer, self.NAME)
self._status_view_mode = status_view.StatusView.MODE_WINDOW
self._stdout_output_writer = isinstance(
self._output_writer, tools.StdoutOutputWriter)
self._worker_memory_limit = None
self.dependencies_check = True
self.list_hashers = False
self.list_parsers_and_plugins = False
self.list_profilers = False
self.show_info = False
def _GetPluginData(self):
"""Retrieves the version and various plugin information.
Returns:
dict[str, list[str]]: available parsers and plugins.
"""
return_dict = {}
return_dict['Versions'] = [
('plaso engine', plaso.__version__),
('python', sys.version)]
hashers_information = hashers_manager.HashersManager.GetHashersInformation()
parsers_information = parsers_manager.ParsersManager.GetParsersInformation()
plugins_information = (
parsers_manager.ParsersManager.GetParserPluginsInformation())
presets_information = self._GetParserPresetsInformation()
return_dict['Hashers'] = hashers_information
return_dict['Parsers'] = parsers_information
return_dict['Parser Plugins'] = plugins_information
return_dict['Parser Presets'] = presets_information
return return_dict
def ParseArguments(self):
"""Parses the command line arguments.
Returns:
bool: True if the arguments were successfully parsed.
"""
loggers.ConfigureLogging()
argument_parser = argparse.ArgumentParser(
description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False,
formatter_class=argparse.RawDescriptionHelpFormatter)
self.AddBasicOptions(argument_parser)
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
argument_parser, names=['storage_file'])
data_location_group = argument_parser.add_argument_group(
'data location arguments')
argument_helper_names = ['artifact_definitions', 'data_location']
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
data_location_group, names=argument_helper_names)
extraction_group = argument_parser.add_argument_group(
'extraction arguments')
argument_helper_names = [
'artifact_filters', 'extraction', 'filter_file', 'hashers',
'parsers', 'yara_rules']
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
extraction_group, names=argument_helper_names)
self.AddStorageMediaImageOptions(extraction_group)
self.AddTimeZoneOption(extraction_group)
self.AddVSSProcessingOptions(extraction_group)
self.AddCredentialOptions(extraction_group)
info_group = argument_parser.add_argument_group('informational arguments')
self.AddInformationalOptions(info_group)
info_group.add_argument(
'--info', dest='show_info', action='store_true', default=False,
help='Print out information about supported plugins and parsers.')
info_group.add_argument(
'--use_markdown', '--use-markdown', dest='use_markdown',
action='store_true', default=False, help=(
'Output lists in Markdown format use in combination with '
'"--hashers list", "--parsers list" or "--timezone list"'))
info_group.add_argument(
'--no_dependencies_check', '--no-dependencies-check',
dest='dependencies_check', action='store_false', default=True,
help='Disable the dependencies check.')
self.AddLogFileOptions(info_group)
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
info_group, names=['status_view'])
output_group = argument_parser.add_argument_group('output arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
output_group, names=['text_prepend'])
processing_group = argument_parser.add_argument_group(
'processing arguments')
self.AddPerformanceOptions(processing_group)
self.AddProcessingOptions(processing_group)
processing_group.add_argument(
'--sigsegv_handler', '--sigsegv-handler', dest='sigsegv_handler',
action='store_true', default=False, help=(
'Enables the SIGSEGV handler. WARNING this functionality is '
'experimental and will a deadlock worker process if a real '
'segfault is caught, but not signal SIGSEGV. This functionality '
'is therefore primarily intended for debugging purposes'))
profiling_group = argument_parser.add_argument_group('profiling arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
profiling_group, names=['profiling'])
storage_group = argument_parser.add_argument_group('storage arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
storage_group, names=['storage_format'])
argument_parser.add_argument(
self._SOURCE_OPTION, action='store', metavar='SOURCE', nargs='?',
default=None, type=str, help=(
'Path to a source device, file or directory. If the source is '
'a supported storage media device or image file, archive file '
'or a directory, the files within are processed recursively.'))
try:
options = argument_parser.parse_args()
except UnicodeEncodeError:
# If we get here we are attempting to print help in a non-Unicode
# terminal.
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_help())
return False
# Properly prepare the attributes according to local encoding.
if self.preferred_encoding == 'ascii':
logger.warning(
'The preferred encoding of your system is ASCII, which is not '
'optimal for the typically non-ASCII characters that need to be '
'parsed and processed. The tool will most likely crash and die, '
'perhaps in a way that may not be recoverable. A five second delay '
'is introduced to give you time to cancel the runtime and '
'reconfigure your preferred encoding, otherwise continue at own '
'risk.')
time.sleep(5)
if self._process_archives:
logger.warning(
'Scanning archive files currently can cause deadlock. Continue at '
'your own risk.')
time.sleep(5)
try:
self.ParseOptions(options)
except errors.BadConfigOption as exception:
self._output_writer.Write('ERROR: {0!s}\n'.format(exception))
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_usage())
return False
self._command_line_arguments = self.GetCommandLineArguments()
loggers.ConfigureLogging(
debug_output=self._debug_mode, filename=self._log_file,
quiet_mode=self._quiet_mode)
return True
def ParseOptions(self, options):
"""Parses the options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The extraction options are dependent on the data location.
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['data_location'])
presets_file = os.path.join(self._data_location, 'presets.yaml')
if not os.path.isfile(presets_file):
raise errors.BadConfigOption(
'No such parser presets file: {0:s}.'.format(presets_file))
parsers_manager.ParsersManager.ReadPresetsFromFile(presets_file)
# Check the list options first otherwise required options will raise.
argument_helper_names = ['hashers', 'parsers', 'profiling']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument_helper_names)
self._ParseTimezoneOption(options)
self.list_hashers = self._hasher_names_string == 'list'
self.list_parsers_and_plugins = self._parser_filter_expression == 'list'
self.list_profilers = self._profilers == 'list'
self.show_info = getattr(options, 'show_info', False)
if getattr(options, 'use_markdown', False):
self._views_format_type = views.ViewsFactory.FORMAT_TYPE_MARKDOWN
self.dependencies_check = getattr(options, 'dependencies_check', True)
if (self.list_hashers or self.list_parsers_and_plugins or
self.list_profilers or self.list_timezones or self.show_info):
return
self._ParseInformationalOptions(options)
argument_helper_names = [
'artifact_definitions', 'artifact_filters', 'extraction',
'filter_file', 'status_view', 'storage_file', 'storage_format',
'text_prepend', 'yara_rules']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument_helper_names)
self._ParseLogFileOptions(options)
self._ParseStorageMediaOptions(options)
self._ParsePerformanceOptions(options)
self._ParseProcessingOptions(options)
if not self._storage_file_path:
raise errors.BadConfigOption('Missing storage file option.')
serializer_format = getattr(
options, 'serializer_format', definitions.SERIALIZER_FORMAT_JSON)
if serializer_format not in definitions.SERIALIZER_FORMATS:
raise errors.BadConfigOption(
'Unsupported storage serializer format: {0:s}.'.format(
serializer_format))
self._storage_serializer_format = serializer_format
# TODO: where is this defined?
self._operating_system = getattr(options, 'os', None)
if self._operating_system:
self._mount_path = getattr(options, 'filename', None)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['status_view'])
self._enable_sigsegv_handler = getattr(options, 'sigsegv_handler', False)
self._EnforceProcessMemoryLimit(self._process_memory_limit)
def ExtractEventsFromSources(self):
"""Processes the sources and extracts events.
Raises:
BadConfigOption: if the storage file path is invalid or the storage
format not supported or an invalid filter was specified.
SourceScannerError: if the source scanner could not find a supported
file system.
UserAbort: if the user initiated an abort.
"""
self._CheckStorageFile(self._storage_file_path, warn_about_existing=True)
scan_context = self.ScanSource(self._source_path)
self._source_type = scan_context.source_type
self._status_view.SetMode(self._status_view_mode)
self._status_view.SetSourceInformation(
self._source_path, self._source_type,
artifact_filters=self._artifact_filters,
filter_file=self._filter_file)
status_update_callback = (
self._status_view.GetExtractionStatusUpdateCallback())
self._output_writer.Write('\n')
self._status_view.PrintExtractionStatusHeader(None)
self._output_writer.Write('Processing started.\n')
session = engine.BaseEngine.CreateSession(
artifact_filter_names=self._artifact_filters,
command_line_arguments=self._command_line_arguments,
debug_mode=self._debug_mode,
filter_file_path=self._filter_file,
preferred_encoding=self.preferred_encoding,
preferred_time_zone=self._preferred_time_zone,
preferred_year=self._preferred_year)
storage_writer = storage_factory.StorageFactory.CreateStorageWriter(
self._storage_format, session, self._storage_file_path)
if not storage_writer:
raise errors.BadConfigOption(
'Unsupported storage format: {0:s}'.format(self._storage_format))
single_process_mode = self._single_process_mode
if self._source_type == dfvfs_definitions.SOURCE_TYPE_FILE:
# No need to multi process a single file source.
single_process_mode = True
if single_process_mode:
extraction_engine = single_process_engine.SingleProcessEngine()
else:
extraction_engine = multi_process_engine.TaskMultiProcessEngine(
use_zeromq=self._use_zeromq)
# If the source is a directory or a storage media image
# run pre-processing.
if self._source_type in self._SOURCE_TYPES_TO_PREPROCESS:
self._PreprocessSources(extraction_engine)
configuration = self._CreateProcessingConfiguration(
extraction_engine.knowledge_base)
self._SetExtractionParsersAndPlugins(configuration, session)
self._SetExtractionPreferredTimeZone(extraction_engine.knowledge_base)
try:
filter_find_specs = engine.BaseEngine.BuildFilterFindSpecs(
self._artifact_definitions_path, self._custom_artifacts_path,
extraction_engine.knowledge_base, self._artifact_filters,
self._filter_file)
except errors.InvalidFilter as exception:
raise errors.BadConfigOption(
'Unable to build filter specification: {0!s}'.format(exception))
processing_status = None
if single_process_mode:
logger.debug('Starting extraction in single process mode.')
processing_status = extraction_engine.ProcessSources(
self._source_path_specs, storage_writer, self._resolver_context,
configuration, filter_find_specs=filter_find_specs,
status_update_callback=status_update_callback)
else:
logger.debug('Starting extraction in multi process mode.')
processing_status = extraction_engine.ProcessSources(
session.identifier, self._source_path_specs, storage_writer,
configuration, enable_sigsegv_handler=self._enable_sigsegv_handler,
filter_find_specs=filter_find_specs,
number_of_worker_processes=self._number_of_extraction_workers,
status_update_callback=status_update_callback,
worker_memory_limit=self._worker_memory_limit)
self._status_view.PrintExtractionSummary(processing_status)
def ShowInfo(self):
"""Shows information about available hashers, parsers, plugins, etc."""
self._output_writer.Write(
'{0:=^80s}\n'.format(' log2timeline/plaso information '))
plugin_list = self._GetPluginData()
for header, data in plugin_list.items():
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, column_names=['Name', 'Description'],
title=header)
for entry_header, entry_data in sorted(data):
table_view.AddRow([entry_header, entry_data])
table_view.Write(self._output_writer)
| 38.123932 | 80 | 0.729403 |
from __future__ import unicode_literals
import argparse
import os
import sys
import time
import textwrap
from dfvfs.lib import definitions as dfvfs_definitions
import plaso
from plaso import output
from plaso.analyzers.hashers import manager as hashers_manager
from plaso.cli import extraction_tool
from plaso.cli import logger
from plaso.cli import status_view
from plaso.cli import tools
from plaso.cli import views
from plaso.cli.helpers import manager as helpers_manager
from plaso.engine import engine
from plaso.engine import single_process as single_process_engine
from plaso.lib import definitions
from plaso.lib import errors
from plaso.lib import loggers
from plaso.multi_processing import task_engine as multi_process_engine
from plaso.parsers import manager as parsers_manager
from plaso.storage import factory as storage_factory
class Log2TimelineTool(extraction_tool.ExtractionTool):
NAME = 'log2timeline'
DESCRIPTION = textwrap.dedent('\n'.join([
'',
('log2timeline is a command line tool to extract events from '
'individual '),
'files, recursing a directory (e.g. mount point) or storage media ',
'image or device.',
'',
'More information can be gathered from here:',
' https://plaso.readthedocs.io/en/latest/sources/user/'
'Using-log2timeline.html',
'']))
EPILOG = textwrap.dedent('\n'.join([
'',
'Example usage:',
'',
'Run the tool against a storage media image (full kitchen sink)',
' log2timeline.py /cases/mycase/storage.plaso ímynd.dd',
'',
'Instead of answering questions, indicate some of the options on the',
'command line (including data from particular VSS stores).',
(' log2timeline.py -o 63 --vss_stores 1,2 /cases/plaso_vss.plaso '
'image.E01'),
'',
'And that is how you build a timeline using log2timeline...',
'']))
_SOURCE_TYPES_TO_PREPROCESS = frozenset([
dfvfs_definitions.SOURCE_TYPE_DIRECTORY,
dfvfs_definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE,
dfvfs_definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE])
def __init__(self, input_reader=None, output_writer=None):
super(Log2TimelineTool, self).__init__(
input_reader=input_reader, output_writer=output_writer)
self._command_line_arguments = None
self._enable_sigsegv_handler = False
self._number_of_extraction_workers = 0
self._storage_serializer_format = definitions.SERIALIZER_FORMAT_JSON
self._source_type = None
self._status_view = status_view.StatusView(self._output_writer, self.NAME)
self._status_view_mode = status_view.StatusView.MODE_WINDOW
self._stdout_output_writer = isinstance(
self._output_writer, tools.StdoutOutputWriter)
self._worker_memory_limit = None
self.dependencies_check = True
self.list_hashers = False
self.list_parsers_and_plugins = False
self.list_profilers = False
self.show_info = False
def _GetPluginData(self):
return_dict = {}
return_dict['Versions'] = [
('plaso engine', plaso.__version__),
('python', sys.version)]
hashers_information = hashers_manager.HashersManager.GetHashersInformation()
parsers_information = parsers_manager.ParsersManager.GetParsersInformation()
plugins_information = (
parsers_manager.ParsersManager.GetParserPluginsInformation())
presets_information = self._GetParserPresetsInformation()
return_dict['Hashers'] = hashers_information
return_dict['Parsers'] = parsers_information
return_dict['Parser Plugins'] = plugins_information
return_dict['Parser Presets'] = presets_information
return return_dict
def ParseArguments(self):
loggers.ConfigureLogging()
argument_parser = argparse.ArgumentParser(
description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False,
formatter_class=argparse.RawDescriptionHelpFormatter)
self.AddBasicOptions(argument_parser)
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
argument_parser, names=['storage_file'])
data_location_group = argument_parser.add_argument_group(
'data location arguments')
argument_helper_names = ['artifact_definitions', 'data_location']
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
data_location_group, names=argument_helper_names)
extraction_group = argument_parser.add_argument_group(
'extraction arguments')
argument_helper_names = [
'artifact_filters', 'extraction', 'filter_file', 'hashers',
'parsers', 'yara_rules']
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
extraction_group, names=argument_helper_names)
self.AddStorageMediaImageOptions(extraction_group)
self.AddTimeZoneOption(extraction_group)
self.AddVSSProcessingOptions(extraction_group)
self.AddCredentialOptions(extraction_group)
info_group = argument_parser.add_argument_group('informational arguments')
self.AddInformationalOptions(info_group)
info_group.add_argument(
'--info', dest='show_info', action='store_true', default=False,
help='Print out information about supported plugins and parsers.')
info_group.add_argument(
'--use_markdown', '--use-markdown', dest='use_markdown',
action='store_true', default=False, help=(
'Output lists in Markdown format use in combination with '
'"--hashers list", "--parsers list" or "--timezone list"'))
info_group.add_argument(
'--no_dependencies_check', '--no-dependencies-check',
dest='dependencies_check', action='store_false', default=True,
help='Disable the dependencies check.')
self.AddLogFileOptions(info_group)
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
info_group, names=['status_view'])
output_group = argument_parser.add_argument_group('output arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
output_group, names=['text_prepend'])
processing_group = argument_parser.add_argument_group(
'processing arguments')
self.AddPerformanceOptions(processing_group)
self.AddProcessingOptions(processing_group)
processing_group.add_argument(
'--sigsegv_handler', '--sigsegv-handler', dest='sigsegv_handler',
action='store_true', default=False, help=(
'Enables the SIGSEGV handler. WARNING this functionality is '
'experimental and will a deadlock worker process if a real '
'segfault is caught, but not signal SIGSEGV. This functionality '
'is therefore primarily intended for debugging purposes'))
profiling_group = argument_parser.add_argument_group('profiling arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
profiling_group, names=['profiling'])
storage_group = argument_parser.add_argument_group('storage arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
storage_group, names=['storage_format'])
argument_parser.add_argument(
self._SOURCE_OPTION, action='store', metavar='SOURCE', nargs='?',
default=None, type=str, help=(
'Path to a source device, file or directory. If the source is '
'a supported storage media device or image file, archive file '
'or a directory, the files within are processed recursively.'))
try:
options = argument_parser.parse_args()
except UnicodeEncodeError:
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_help())
return False
if self.preferred_encoding == 'ascii':
logger.warning(
'The preferred encoding of your system is ASCII, which is not '
'optimal for the typically non-ASCII characters that need to be '
'parsed and processed. The tool will most likely crash and die, '
'perhaps in a way that may not be recoverable. A five second delay '
'is introduced to give you time to cancel the runtime and '
'reconfigure your preferred encoding, otherwise continue at own '
'risk.')
time.sleep(5)
if self._process_archives:
logger.warning(
'Scanning archive files currently can cause deadlock. Continue at '
'your own risk.')
time.sleep(5)
try:
self.ParseOptions(options)
except errors.BadConfigOption as exception:
self._output_writer.Write('ERROR: {0!s}\n'.format(exception))
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_usage())
return False
self._command_line_arguments = self.GetCommandLineArguments()
loggers.ConfigureLogging(
debug_output=self._debug_mode, filename=self._log_file,
quiet_mode=self._quiet_mode)
return True
def ParseOptions(self, options):
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['data_location'])
presets_file = os.path.join(self._data_location, 'presets.yaml')
if not os.path.isfile(presets_file):
raise errors.BadConfigOption(
'No such parser presets file: {0:s}.'.format(presets_file))
parsers_manager.ParsersManager.ReadPresetsFromFile(presets_file)
argument_helper_names = ['hashers', 'parsers', 'profiling']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument_helper_names)
self._ParseTimezoneOption(options)
self.list_hashers = self._hasher_names_string == 'list'
self.list_parsers_and_plugins = self._parser_filter_expression == 'list'
self.list_profilers = self._profilers == 'list'
self.show_info = getattr(options, 'show_info', False)
if getattr(options, 'use_markdown', False):
self._views_format_type = views.ViewsFactory.FORMAT_TYPE_MARKDOWN
self.dependencies_check = getattr(options, 'dependencies_check', True)
if (self.list_hashers or self.list_parsers_and_plugins or
self.list_profilers or self.list_timezones or self.show_info):
return
self._ParseInformationalOptions(options)
argument_helper_names = [
'artifact_definitions', 'artifact_filters', 'extraction',
'filter_file', 'status_view', 'storage_file', 'storage_format',
'text_prepend', 'yara_rules']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument_helper_names)
self._ParseLogFileOptions(options)
self._ParseStorageMediaOptions(options)
self._ParsePerformanceOptions(options)
self._ParseProcessingOptions(options)
if not self._storage_file_path:
raise errors.BadConfigOption('Missing storage file option.')
serializer_format = getattr(
options, 'serializer_format', definitions.SERIALIZER_FORMAT_JSON)
if serializer_format not in definitions.SERIALIZER_FORMATS:
raise errors.BadConfigOption(
'Unsupported storage serializer format: {0:s}.'.format(
serializer_format))
self._storage_serializer_format = serializer_format
self._operating_system = getattr(options, 'os', None)
if self._operating_system:
self._mount_path = getattr(options, 'filename', None)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['status_view'])
self._enable_sigsegv_handler = getattr(options, 'sigsegv_handler', False)
self._EnforceProcessMemoryLimit(self._process_memory_limit)
def ExtractEventsFromSources(self):
self._CheckStorageFile(self._storage_file_path, warn_about_existing=True)
scan_context = self.ScanSource(self._source_path)
self._source_type = scan_context.source_type
self._status_view.SetMode(self._status_view_mode)
self._status_view.SetSourceInformation(
self._source_path, self._source_type,
artifact_filters=self._artifact_filters,
filter_file=self._filter_file)
status_update_callback = (
self._status_view.GetExtractionStatusUpdateCallback())
self._output_writer.Write('\n')
self._status_view.PrintExtractionStatusHeader(None)
self._output_writer.Write('Processing started.\n')
session = engine.BaseEngine.CreateSession(
artifact_filter_names=self._artifact_filters,
command_line_arguments=self._command_line_arguments,
debug_mode=self._debug_mode,
filter_file_path=self._filter_file,
preferred_encoding=self.preferred_encoding,
preferred_time_zone=self._preferred_time_zone,
preferred_year=self._preferred_year)
storage_writer = storage_factory.StorageFactory.CreateStorageWriter(
self._storage_format, session, self._storage_file_path)
if not storage_writer:
raise errors.BadConfigOption(
'Unsupported storage format: {0:s}'.format(self._storage_format))
single_process_mode = self._single_process_mode
if self._source_type == dfvfs_definitions.SOURCE_TYPE_FILE:
single_process_mode = True
if single_process_mode:
extraction_engine = single_process_engine.SingleProcessEngine()
else:
extraction_engine = multi_process_engine.TaskMultiProcessEngine(
use_zeromq=self._use_zeromq)
if self._source_type in self._SOURCE_TYPES_TO_PREPROCESS:
self._PreprocessSources(extraction_engine)
configuration = self._CreateProcessingConfiguration(
extraction_engine.knowledge_base)
self._SetExtractionParsersAndPlugins(configuration, session)
self._SetExtractionPreferredTimeZone(extraction_engine.knowledge_base)
try:
filter_find_specs = engine.BaseEngine.BuildFilterFindSpecs(
self._artifact_definitions_path, self._custom_artifacts_path,
extraction_engine.knowledge_base, self._artifact_filters,
self._filter_file)
except errors.InvalidFilter as exception:
raise errors.BadConfigOption(
'Unable to build filter specification: {0!s}'.format(exception))
processing_status = None
if single_process_mode:
logger.debug('Starting extraction in single process mode.')
processing_status = extraction_engine.ProcessSources(
self._source_path_specs, storage_writer, self._resolver_context,
configuration, filter_find_specs=filter_find_specs,
status_update_callback=status_update_callback)
else:
logger.debug('Starting extraction in multi process mode.')
processing_status = extraction_engine.ProcessSources(
session.identifier, self._source_path_specs, storage_writer,
configuration, enable_sigsegv_handler=self._enable_sigsegv_handler,
filter_find_specs=filter_find_specs,
number_of_worker_processes=self._number_of_extraction_workers,
status_update_callback=status_update_callback,
worker_memory_limit=self._worker_memory_limit)
self._status_view.PrintExtractionSummary(processing_status)
def ShowInfo(self):
self._output_writer.Write(
'{0:=^80s}\n'.format(' log2timeline/plaso information '))
plugin_list = self._GetPluginData()
for header, data in plugin_list.items():
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, column_names=['Name', 'Description'],
title=header)
for entry_header, entry_data in sorted(data):
table_view.AddRow([entry_header, entry_data])
table_view.Write(self._output_writer)
| true | true |
f72a117fd491be4a83bc01b0a9c8a1fe778df379 | 1,630 | py | Python | stanCode Projects/campy_projects/bouncing_ball.py | ruby-pan/Stanford-Coding-Projects | c3e5ddb53d2742a745eba22f70b8fb0d24d787e8 | [
"MIT"
] | null | null | null | stanCode Projects/campy_projects/bouncing_ball.py | ruby-pan/Stanford-Coding-Projects | c3e5ddb53d2742a745eba22f70b8fb0d24d787e8 | [
"MIT"
] | null | null | null | stanCode Projects/campy_projects/bouncing_ball.py | ruby-pan/Stanford-Coding-Projects | c3e5ddb53d2742a745eba22f70b8fb0d24d787e8 | [
"MIT"
] | null | null | null | """
File: bouncing_ball.py
Name: Ruby
-------------------------
This file uses campy module to
simulate ball bouncing on a GWindow object
"""
from campy.graphics.gobjects import GOval
from campy.graphics.gwindow import GWindow
from campy.gui.events.timer import pause
from campy.gui.events.mouse import onmouseclicked
VX = 5
DELAY = 10
GRAVITY = 1
SIZE = 20
REDUCE = 0.9
START_X = 30
START_Y = 40
window = GWindow(800, 500, title='bouncing_ball.py')
ball = GOval(SIZE, SIZE)
num = 0
def main():
"""
This program simulates a bouncing ball at (START_X, START_Y)
that has VX as x velocity and 0 as y velocity. Each bounce reduces
y velocity to REDUCE of itself.
"""
ball.filled = True
ball.fill_color = 'black'
window.add(ball, START_X, START_Y)
onmouseclicked(drop)
def drop(m):
"""
To initiate the drop of ball.
"""
global num
shift = 0
if num >= 3: # If num equals 3 times, then the function 'drop' stops
pass
else:
while True:
ball.move(VX, shift)
if ball.y >= window.height-2*SIZE: # If ball touches bottom, change the direction of speed.
shift = -shift
shift = REDUCE*shift
elif ball.x >= window.width : # If ball exceeds window width, start at beginning.
ball.x = START_X
ball.y = START_Y
num += 1
break
else:
pass
shift += GRAVITY
pause(DELAY)
if __name__ == "__main__":
main()
| 25.46875 | 105 | 0.566258 |
from campy.graphics.gobjects import GOval
from campy.graphics.gwindow import GWindow
from campy.gui.events.timer import pause
from campy.gui.events.mouse import onmouseclicked
VX = 5
DELAY = 10
GRAVITY = 1
SIZE = 20
REDUCE = 0.9
START_X = 30
START_Y = 40
window = GWindow(800, 500, title='bouncing_ball.py')
ball = GOval(SIZE, SIZE)
num = 0
def main():
ball.filled = True
ball.fill_color = 'black'
window.add(ball, START_X, START_Y)
onmouseclicked(drop)
def drop(m):
global num
shift = 0
if num >= 3:
pass
else:
while True:
ball.move(VX, shift)
if ball.y >= window.height-2*SIZE:
shift = -shift
shift = REDUCE*shift
elif ball.x >= window.width :
ball.x = START_X
ball.y = START_Y
num += 1
break
else:
pass
shift += GRAVITY
pause(DELAY)
if __name__ == "__main__":
main()
| true | true |
f72a12b58edcb73c4679ecca5af53b3f3cb22bd2 | 6,980 | py | Python | pandas/__init__.py | katieyounglove/pandas | 8841969eea43fa34c84c9cdc2d7f286fcc5e76e5 | [
"BSD-3-Clause"
] | null | null | null | pandas/__init__.py | katieyounglove/pandas | 8841969eea43fa34c84c9cdc2d7f286fcc5e76e5 | [
"BSD-3-Clause"
] | null | null | null | pandas/__init__.py | katieyounglove/pandas | 8841969eea43fa34c84c9cdc2d7f286fcc5e76e5 | [
"BSD-3-Clause"
] | null | null | null | # flake8: noqa
__docformat__ = "restructuredtext"
# Let users know if they're missing any of our hard dependencies
hard_dependencies = ("numpy", "pytz", "dateutil")
missing_dependencies = []
for dependency in hard_dependencies:
try:
__import__(dependency)
except ImportError as e:
missing_dependencies.append("{0}: {1}".format(dependency, str(e)))
if missing_dependencies:
raise ImportError(
"Unable to import required dependencies:\n" + "\n".join(missing_dependencies)
)
del hard_dependencies, dependency, missing_dependencies
# numpy compat
from pandas.compat.numpy import (
_np_version_under1p14,
_np_version_under1p15,
_np_version_under1p16,
_np_version_under1p17,
_np_version_under1p18,
)
try:
from pandas._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib
except ImportError as e: # pragma: no cover
# hack but overkill to use re
module = str(e).replace("cannot import name ", "")
raise ImportError(
"C extension: {0} not built. If you want to import "
"pandas from the source directory, you may need to run "
"'python setup.py build_ext --inplace --force' to build "
"the C extensions first.".format(module)
)
from datetime import datetime
from pandas._config import (
get_option,
set_option,
reset_option,
describe_option,
option_context,
options,
)
# let init-time option registration happen
import pandas.core.config_init
from pandas.core.api import (
# dtype
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
UInt8Dtype,
UInt16Dtype,
UInt32Dtype,
UInt64Dtype,
CategoricalDtype,
PeriodDtype,
IntervalDtype,
DatetimeTZDtype,
StringDtype,
BooleanDtype,
# missing
NA,
isna,
isnull,
notna,
notnull,
# indexes
Index,
CategoricalIndex,
Int64Index,
UInt64Index,
RangeIndex,
Float64Index,
MultiIndex,
IntervalIndex,
TimedeltaIndex,
DatetimeIndex,
PeriodIndex,
IndexSlice,
# tseries
NaT,
Period,
period_range,
Timedelta,
timedelta_range,
Timestamp,
date_range,
bdate_range,
Interval,
interval_range,
DateOffset,
# conversion
to_numeric,
to_datetime,
to_timedelta,
# misc
np,
Grouper,
factorize,
unique,
value_counts,
NamedAgg,
array,
Categorical,
set_eng_float_format,
Series,
DataFrame,
)
from pandas.core.arrays.sparse import SparseArray, SparseDtype
from pandas.tseries.api import infer_freq
from pandas.tseries import offsets
from pandas.core.computation.api import eval
from pandas.core.reshape.api import (
concat,
lreshape,
melt,
wide_to_long,
merge,
merge_asof,
merge_ordered,
crosstab,
pivot,
pivot_table,
get_dummies,
cut,
qcut,
)
from pandas.util._print_versions import show_versions
from pandas.io.api import (
# excel
ExcelFile,
ExcelWriter,
read_excel,
# packers
read_msgpack,
to_msgpack,
# parsers
read_csv,
read_fwf,
read_table,
# pickle
read_pickle,
to_pickle,
# pytables
HDFStore,
read_hdf,
# sql
read_sql,
read_sql_query,
read_sql_table,
# misc
read_clipboard,
read_parquet,
read_orc,
read_feather,
read_gbq,
read_html,
read_json,
read_stata,
read_sas,
read_spss,
)
from pandas.util._tester import test
import pandas.testing
import pandas.arrays
# use the closest tagged version if possible
from ._version import get_versions
v = get_versions()
__version__ = v.get("closest-tag", v["version"])
__git_version__ = v.get("full-revisionid")
del get_versions, v
# GH 27101
# TODO: remove Panel compat in 1.0
if pandas.compat.PY37:
def __getattr__(name):
import warnings
if name == "Panel":
warnings.warn(
"The Panel class is removed from pandas. Accessing it "
"from the top-level namespace will also be removed in "
"the next version",
FutureWarning,
stacklevel=2,
)
class Panel:
pass
return Panel
elif name in {"SparseSeries", "SparseDataFrame"}:
warnings.warn(
"The {} class is removed from pandas. Accessing it from "
"the top-level namespace will also be removed in the next "
"version".format(name),
FutureWarning,
stacklevel=2,
)
return type(name, (), {})
raise AttributeError("module 'pandas' has no attribute '{}'".format(name))
else:
class Panel:
pass
class SparseDataFrame:
pass
class SparseSeries:
pass
# module level doc-string
__doc__ = """
pandas - a powerful data analysis and manipulation library for Python
=====================================================================
**pandas** is a Python package providing fast, flexible, and expressive data
structures designed to make working with "relational" or "labeled" data both
easy and intuitive. It aims to be the fundamental high-level building block for
doing practical, **real world** data analysis in Python. Additionally, it has
the broader goal of becoming **the most powerful and flexible open source data
analysis / manipulation tool available in any language**. It is already well on
its way toward this goal.
Main Features
-------------
Here are just a few of the things that pandas does well:
- Easy handling of missing data in floating point as well as non-floating
point data.
- Size mutability: columns can be inserted and deleted from DataFrame and
higher dimensional objects
- Automatic and explicit data alignment: objects can be explicitly aligned
to a set of labels, or the user can simply ignore the labels and let
`Series`, `DataFrame`, etc. automatically align the data for you in
computations.
- Powerful, flexible group by functionality to perform split-apply-combine
operations on data sets, for both aggregating and transforming data.
- Make it easy to convert ragged, differently-indexed data in other Python
and NumPy data structures into DataFrame objects.
- Intelligent label-based slicing, fancy indexing, and subsetting of large
data sets.
- Intuitive merging and joining data sets.
- Flexible reshaping and pivoting of data sets.
- Hierarchical labeling of axes (possible to have multiple labels per tick).
- Robust IO tools for loading data from flat files (CSV and delimited),
Excel files, databases, and saving/loading data from the ultrafast HDF5
format.
- Time series-specific functionality: date range generation and frequency
conversion, moving window statistics, moving window linear regressions,
date shifting and lagging, etc.
"""
| 24.751773 | 85 | 0.669198 |
__docformat__ = "restructuredtext"
hard_dependencies = ("numpy", "pytz", "dateutil")
missing_dependencies = []
for dependency in hard_dependencies:
try:
__import__(dependency)
except ImportError as e:
missing_dependencies.append("{0}: {1}".format(dependency, str(e)))
if missing_dependencies:
raise ImportError(
"Unable to import required dependencies:\n" + "\n".join(missing_dependencies)
)
del hard_dependencies, dependency, missing_dependencies
# numpy compat
from pandas.compat.numpy import (
_np_version_under1p14,
_np_version_under1p15,
_np_version_under1p16,
_np_version_under1p17,
_np_version_under1p18,
)
try:
from pandas._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib
except ImportError as e: # pragma: no cover
# hack but overkill to use re
module = str(e).replace("cannot import name ", "")
raise ImportError(
"C extension: {0} not built. If you want to import "
"pandas from the source directory, you may need to run "
"'python setup.py build_ext --inplace --force' to build "
"the C extensions first.".format(module)
)
from datetime import datetime
from pandas._config import (
get_option,
set_option,
reset_option,
describe_option,
option_context,
options,
)
# let init-time option registration happen
import pandas.core.config_init
from pandas.core.api import (
# dtype
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
UInt8Dtype,
UInt16Dtype,
UInt32Dtype,
UInt64Dtype,
CategoricalDtype,
PeriodDtype,
IntervalDtype,
DatetimeTZDtype,
StringDtype,
BooleanDtype,
# missing
NA,
isna,
isnull,
notna,
notnull,
# indexes
Index,
CategoricalIndex,
Int64Index,
UInt64Index,
RangeIndex,
Float64Index,
MultiIndex,
IntervalIndex,
TimedeltaIndex,
DatetimeIndex,
PeriodIndex,
IndexSlice,
# tseries
NaT,
Period,
period_range,
Timedelta,
timedelta_range,
Timestamp,
date_range,
bdate_range,
Interval,
interval_range,
DateOffset,
# conversion
to_numeric,
to_datetime,
to_timedelta,
# misc
np,
Grouper,
factorize,
unique,
value_counts,
NamedAgg,
array,
Categorical,
set_eng_float_format,
Series,
DataFrame,
)
from pandas.core.arrays.sparse import SparseArray, SparseDtype
from pandas.tseries.api import infer_freq
from pandas.tseries import offsets
from pandas.core.computation.api import eval
from pandas.core.reshape.api import (
concat,
lreshape,
melt,
wide_to_long,
merge,
merge_asof,
merge_ordered,
crosstab,
pivot,
pivot_table,
get_dummies,
cut,
qcut,
)
from pandas.util._print_versions import show_versions
from pandas.io.api import (
# excel
ExcelFile,
ExcelWriter,
read_excel,
# packers
read_msgpack,
to_msgpack,
# parsers
read_csv,
read_fwf,
read_table,
# pickle
read_pickle,
to_pickle,
# pytables
HDFStore,
read_hdf,
# sql
read_sql,
read_sql_query,
read_sql_table,
# misc
read_clipboard,
read_parquet,
read_orc,
read_feather,
read_gbq,
read_html,
read_json,
read_stata,
read_sas,
read_spss,
)
from pandas.util._tester import test
import pandas.testing
import pandas.arrays
# use the closest tagged version if possible
from ._version import get_versions
v = get_versions()
__version__ = v.get("closest-tag", v["version"])
__git_version__ = v.get("full-revisionid")
del get_versions, v
# GH 27101
# TODO: remove Panel compat in 1.0
if pandas.compat.PY37:
def __getattr__(name):
import warnings
if name == "Panel":
warnings.warn(
"The Panel class is removed from pandas. Accessing it "
"from the top-level namespace will also be removed in "
"the next version",
FutureWarning,
stacklevel=2,
)
class Panel:
pass
return Panel
elif name in {"SparseSeries", "SparseDataFrame"}:
warnings.warn(
"The {} class is removed from pandas. Accessing it from "
"the top-level namespace will also be removed in the next "
"version".format(name),
FutureWarning,
stacklevel=2,
)
return type(name, (), {})
raise AttributeError("module 'pandas' has no attribute '{}'".format(name))
else:
class Panel:
pass
class SparseDataFrame:
pass
class SparseSeries:
pass
# module level doc-string
__doc__ = """
pandas - a powerful data analysis and manipulation library for Python
=====================================================================
**pandas** is a Python package providing fast, flexible, and expressive data
structures designed to make working with "relational" or "labeled" data both
easy and intuitive. It aims to be the fundamental high-level building block for
doing practical, **real world** data analysis in Python. Additionally, it has
the broader goal of becoming **the most powerful and flexible open source data
analysis / manipulation tool available in any language**. It is already well on
its way toward this goal.
Main Features
-------------
Here are just a few of the things that pandas does well:
- Easy handling of missing data in floating point as well as non-floating
point data.
- Size mutability: columns can be inserted and deleted from DataFrame and
higher dimensional objects
- Automatic and explicit data alignment: objects can be explicitly aligned
to a set of labels, or the user can simply ignore the labels and let
`Series`, `DataFrame`, etc. automatically align the data for you in
computations.
- Powerful, flexible group by functionality to perform split-apply-combine
operations on data sets, for both aggregating and transforming data.
- Make it easy to convert ragged, differently-indexed data in other Python
and NumPy data structures into DataFrame objects.
- Intelligent label-based slicing, fancy indexing, and subsetting of large
data sets.
- Intuitive merging and joining data sets.
- Flexible reshaping and pivoting of data sets.
- Hierarchical labeling of axes (possible to have multiple labels per tick).
- Robust IO tools for loading data from flat files (CSV and delimited),
Excel files, databases, and saving/loading data from the ultrafast HDF5
format.
- Time series-specific functionality: date range generation and frequency
conversion, moving window statistics, moving window linear regressions,
date shifting and lagging, etc.
"""
| true | true |
f72a12f058bc37d00289a2d8e5e7ef554d3aedf9 | 2,337 | py | Python | kabutobashi/domain/page/page.py | gsy0911/kabutobashi | 0be36a41333c3fd0cb59b1d35edee7db4de4a989 | [
"MIT"
] | null | null | null | kabutobashi/domain/page/page.py | gsy0911/kabutobashi | 0be36a41333c3fd0cb59b1d35edee7db4de4a989 | [
"MIT"
] | 65 | 2020-06-20T00:33:12.000Z | 2022-03-30T14:41:50.000Z | kabutobashi/domain/page/page.py | gsy0911/kabutobashi | 0be36a41333c3fd0cb59b1d35edee7db4de4a989 | [
"MIT"
] | null | null | null | from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from functools import reduce
from typing import List, Optional, Union
import requests # type: ignore
from bs4 import BeautifulSoup
from kabutobashi.errors import KabutobashiPageError
from .user_agent import UserAgent
@dataclass(frozen=True)
class PageDecoder:
tag1: Optional[str] = None
class1: Optional[str] = None
id1: Optional[str] = None
default: str = ""
def _decode(self, value):
class1 = {"class": self.class1}
set_value = None
# tag1から取得
if self.tag1 is not None:
if class1["class"] is not None:
set_value = value.find(self.tag1, self.class1)
else:
set_value = value.find(self.tag1)
if set_value is None:
return self.default
# 文字列を置換して保持
return self.replace(set_value.get_text())
def decode(self, bs: BeautifulSoup) -> Union[str, List[str]]:
return self._decode(value=bs)
@staticmethod
def replace(input_text: str) -> str:
target_list = [" ", "\t", "\n", "\r", "円"]
def remove_of(_input: str, target: str):
return _input.replace(target, "")
result = reduce(remove_of, target_list, input_text)
return result.replace("\xa0", " ")
@dataclass(frozen=True) # type: ignore
class Page(metaclass=ABCMeta):
@abstractmethod
def url(self) -> str:
raise NotImplementedError()
@abstractmethod
def _get(self) -> dict:
raise NotImplementedError()
def get(self) -> dict:
data = self._get()
data.update({"crawl_datetime": self.crawl_datetime()})
return data
@staticmethod
def get_url_text(url: str) -> str:
"""
requestsを使って、webからページを取得し、htmlを返す
"""
user_agent = UserAgent.get_user_agent_header()
r = requests.get(url, headers=user_agent)
if r.status_code != 200:
raise KabutobashiPageError(url=url)
# 日本語に対応
r.encoding = r.apparent_encoding
return r.text
@staticmethod
def crawl_datetime() -> str:
jst = timezone(timedelta(hours=+9), "JST")
now = datetime.now(jst)
return now.strftime("%Y-%m-%dT%H:%M:%S")
| 26.556818 | 65 | 0.619598 | from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from functools import reduce
from typing import List, Optional, Union
import requests
from bs4 import BeautifulSoup
from kabutobashi.errors import KabutobashiPageError
from .user_agent import UserAgent
@dataclass(frozen=True)
class PageDecoder:
tag1: Optional[str] = None
class1: Optional[str] = None
id1: Optional[str] = None
default: str = ""
def _decode(self, value):
class1 = {"class": self.class1}
set_value = None
if self.tag1 is not None:
if class1["class"] is not None:
set_value = value.find(self.tag1, self.class1)
else:
set_value = value.find(self.tag1)
if set_value is None:
return self.default
return self.replace(set_value.get_text())
def decode(self, bs: BeautifulSoup) -> Union[str, List[str]]:
return self._decode(value=bs)
@staticmethod
def replace(input_text: str) -> str:
target_list = [" ", "\t", "\n", "\r", "円"]
def remove_of(_input: str, target: str):
return _input.replace(target, "")
result = reduce(remove_of, target_list, input_text)
return result.replace("\xa0", " ")
@dataclass(frozen=True)
class Page(metaclass=ABCMeta):
@abstractmethod
def url(self) -> str:
raise NotImplementedError()
@abstractmethod
def _get(self) -> dict:
raise NotImplementedError()
def get(self) -> dict:
data = self._get()
data.update({"crawl_datetime": self.crawl_datetime()})
return data
@staticmethod
def get_url_text(url: str) -> str:
user_agent = UserAgent.get_user_agent_header()
r = requests.get(url, headers=user_agent)
if r.status_code != 200:
raise KabutobashiPageError(url=url)
r.encoding = r.apparent_encoding
return r.text
@staticmethod
def crawl_datetime() -> str:
jst = timezone(timedelta(hours=+9), "JST")
now = datetime.now(jst)
return now.strftime("%Y-%m-%dT%H:%M:%S")
| true | true |
f72a1413848ce1eae8308309d1a389688e408204 | 7,059 | py | Python | tests/test_util.py | sthagen/pantsbuild-pex | bffe6c3641b809cd3b20adbc7fdb2cf7e5f54309 | [
"Apache-2.0"
] | null | null | null | tests/test_util.py | sthagen/pantsbuild-pex | bffe6c3641b809cd3b20adbc7fdb2cf7e5f54309 | [
"Apache-2.0"
] | null | null | null | tests/test_util.py | sthagen/pantsbuild-pex | bffe6c3641b809cd3b20adbc7fdb2cf7e5f54309 | [
"Apache-2.0"
] | null | null | null | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import subprocess
from hashlib import sha1
from textwrap import dedent
from pex.common import safe_mkdir, safe_open, temporary_dir, touch
from pex.compatibility import to_bytes
from pex.pex import PEX
from pex.pex_builder import PEXBuilder
from pex.typing import TYPE_CHECKING, cast
from pex.util import CacheHelper, DistributionHelper, iter_pth_paths, named_temporary_file
try:
from unittest import mock
except ImportError:
import mock # type: ignore[no-redef,import]
if TYPE_CHECKING:
from typing import Any, Dict, List
def test_access_zipped_assets():
# type: (...) -> None
pex_third_party_asset_dir = DistributionHelper.access_zipped_assets("pex", "third_party")
resources = os.listdir(pex_third_party_asset_dir)
assert (
len(resources) > 0
), "The pex.third_party package should contain at least an __init__.py file."
resources.remove("__init__.py")
for path in resources:
assert path in (
"__init__.pyc",
"__init__.pyo",
"__pycache__",
), "Expected only __init__.py (and its compilations) in the pex.third_party package."
def test_hash():
# type: () -> None
empty_hash_digest = sha1().hexdigest()
with named_temporary_file() as fp:
fp.flush()
assert empty_hash_digest == CacheHelper.hash(fp.name)
with named_temporary_file() as fp:
string = b"asdf" * 1024 * sha1().block_size + b"extra padding"
fp.write(string)
fp.flush()
assert sha1(string).hexdigest() == CacheHelper.hash(fp.name)
with named_temporary_file() as fp:
empty_hash = sha1()
fp.write(b"asdf")
fp.flush()
hash_output = CacheHelper.hash(fp.name, digest=empty_hash)
assert hash_output == empty_hash.hexdigest()
def test_dir_hash():
# type: () -> None
with temporary_dir() as tmp_dir:
safe_mkdir(os.path.join(tmp_dir, "a", "b"))
with safe_open(os.path.join(tmp_dir, "c", "d", "e.py"), "w") as fp:
fp.write("contents1")
with safe_open(os.path.join(tmp_dir, "f.py"), "w") as fp:
fp.write("contents2")
hash1 = CacheHelper.dir_hash(tmp_dir)
os.rename(os.path.join(tmp_dir, "c"), os.path.join(tmp_dir, "c-renamed"))
assert hash1 != CacheHelper.dir_hash(tmp_dir)
os.rename(os.path.join(tmp_dir, "c-renamed"), os.path.join(tmp_dir, "c"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(tmp_dir, "c", "d", "e.pyc"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(tmp_dir, "c", "d", "e.pyc.123456789"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
pycache_dir = os.path.join(tmp_dir, "__pycache__")
safe_mkdir(pycache_dir)
touch(os.path.join(pycache_dir, "f.pyc"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(pycache_dir, "f.pyc.123456789"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(pycache_dir, "f.py"))
assert hash1 == CacheHelper.dir_hash(
tmp_dir
), "All content under __pycache__ directories should be ignored."
try:
import __builtin__ as python_builtins # type: ignore[import]
except ImportError:
import builtins as python_builtins # type: ignore[no-redef]
def assert_access_zipped_assets(distribution_helper_import):
# type: (str) -> bytes
test_executable = dedent(
"""
import os
{distribution_helper_import}
temp_dir = DistributionHelper.access_zipped_assets('my_package', 'submodule')
with open(os.path.join(temp_dir, 'mod.py'), 'r') as fp:
for line in fp:
print(line)
""".format(
distribution_helper_import=distribution_helper_import
)
)
with temporary_dir() as td1, temporary_dir() as td2:
pb = PEXBuilder(path=td1)
with open(os.path.join(td1, "exe.py"), "w") as fp:
fp.write(test_executable)
pb.set_executable(fp.name)
submodule = os.path.join(td1, "my_package", "submodule")
safe_mkdir(submodule)
mod_path = os.path.join(submodule, "mod.py")
with open(mod_path, "w") as fp:
fp.write("accessed")
pb.add_source(fp.name, "my_package/submodule/mod.py")
pb.add_source(None, "my_package/__init__.py")
pb.add_source(None, "my_package/submodule/__init__.py")
pex = os.path.join(td2, "app.pex")
pb.build(pex)
process = PEX(pex, interpreter=pb.interpreter).run(
blocking=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
assert process.returncode == 0
assert b"accessed\n" == stdout
return cast(bytes, stderr)
def test_access_zipped_assets_integration():
# type: () -> None
stderr = assert_access_zipped_assets("from pex.util import DistributionHelper")
assert b"" == stderr.strip()
def test_named_temporary_file():
# type: () -> None
with named_temporary_file() as fp:
name = fp.name
fp.write(b"hi")
fp.flush()
assert os.path.exists(name)
with open(name) as new_fp:
assert new_fp.read() == "hi"
assert not os.path.exists(name)
@mock.patch("os.path.exists", autospec=True, spec_set=True)
def test_iter_pth_paths(mock_exists):
# type: (Any) -> None
# Ensure path checking always returns True for dummy paths.
mock_exists.return_value = True
with temporary_dir() as tmpdir:
in_tmp = lambda f: os.path.join(tmpdir, f)
PTH_TEST_MAPPING = {
# A mapping of .pth file content -> expected paths.
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python\n": [
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"
],
"relative_path\nrelative_path2\n\nrelative_path3": [
in_tmp("relative_path"),
in_tmp("relative_path2"),
in_tmp("relative_path3"),
],
"duplicate_path\nduplicate_path": [in_tmp("duplicate_path")],
"randompath\nimport nosuchmodule\n": [in_tmp("randompath")],
"import sys\nfoo\n/bar/baz": [in_tmp("foo"), "/bar/baz"],
"import nosuchmodule\nfoo": [],
"import nosuchmodule\n": [],
"import bad)syntax\n": [],
} # type: Dict[str, List[str]]
for i, pth_content in enumerate(PTH_TEST_MAPPING):
pth_tmp_path = os.path.abspath(os.path.join(tmpdir, "test%s.pth" % i))
with open(pth_tmp_path, "wb") as f:
f.write(to_bytes(pth_content))
assert sorted(PTH_TEST_MAPPING[pth_content]) == sorted(
list(iter_pth_paths(pth_tmp_path))
)
| 35.832487 | 93 | 0.632243 |
import os
import subprocess
from hashlib import sha1
from textwrap import dedent
from pex.common import safe_mkdir, safe_open, temporary_dir, touch
from pex.compatibility import to_bytes
from pex.pex import PEX
from pex.pex_builder import PEXBuilder
from pex.typing import TYPE_CHECKING, cast
from pex.util import CacheHelper, DistributionHelper, iter_pth_paths, named_temporary_file
try:
from unittest import mock
except ImportError:
import mock
if TYPE_CHECKING:
from typing import Any, Dict, List
def test_access_zipped_assets():
pex_third_party_asset_dir = DistributionHelper.access_zipped_assets("pex", "third_party")
resources = os.listdir(pex_third_party_asset_dir)
assert (
len(resources) > 0
), "The pex.third_party package should contain at least an __init__.py file."
resources.remove("__init__.py")
for path in resources:
assert path in (
"__init__.pyc",
"__init__.pyo",
"__pycache__",
), "Expected only __init__.py (and its compilations) in the pex.third_party package."
def test_hash():
empty_hash_digest = sha1().hexdigest()
with named_temporary_file() as fp:
fp.flush()
assert empty_hash_digest == CacheHelper.hash(fp.name)
with named_temporary_file() as fp:
string = b"asdf" * 1024 * sha1().block_size + b"extra padding"
fp.write(string)
fp.flush()
assert sha1(string).hexdigest() == CacheHelper.hash(fp.name)
with named_temporary_file() as fp:
empty_hash = sha1()
fp.write(b"asdf")
fp.flush()
hash_output = CacheHelper.hash(fp.name, digest=empty_hash)
assert hash_output == empty_hash.hexdigest()
def test_dir_hash():
with temporary_dir() as tmp_dir:
safe_mkdir(os.path.join(tmp_dir, "a", "b"))
with safe_open(os.path.join(tmp_dir, "c", "d", "e.py"), "w") as fp:
fp.write("contents1")
with safe_open(os.path.join(tmp_dir, "f.py"), "w") as fp:
fp.write("contents2")
hash1 = CacheHelper.dir_hash(tmp_dir)
os.rename(os.path.join(tmp_dir, "c"), os.path.join(tmp_dir, "c-renamed"))
assert hash1 != CacheHelper.dir_hash(tmp_dir)
os.rename(os.path.join(tmp_dir, "c-renamed"), os.path.join(tmp_dir, "c"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(tmp_dir, "c", "d", "e.pyc"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(tmp_dir, "c", "d", "e.pyc.123456789"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
pycache_dir = os.path.join(tmp_dir, "__pycache__")
safe_mkdir(pycache_dir)
touch(os.path.join(pycache_dir, "f.pyc"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(pycache_dir, "f.pyc.123456789"))
assert hash1 == CacheHelper.dir_hash(tmp_dir)
touch(os.path.join(pycache_dir, "f.py"))
assert hash1 == CacheHelper.dir_hash(
tmp_dir
), "All content under __pycache__ directories should be ignored."
try:
import __builtin__ as python_builtins
except ImportError:
import builtins as python_builtins
def assert_access_zipped_assets(distribution_helper_import):
test_executable = dedent(
"""
import os
{distribution_helper_import}
temp_dir = DistributionHelper.access_zipped_assets('my_package', 'submodule')
with open(os.path.join(temp_dir, 'mod.py'), 'r') as fp:
for line in fp:
print(line)
""".format(
distribution_helper_import=distribution_helper_import
)
)
with temporary_dir() as td1, temporary_dir() as td2:
pb = PEXBuilder(path=td1)
with open(os.path.join(td1, "exe.py"), "w") as fp:
fp.write(test_executable)
pb.set_executable(fp.name)
submodule = os.path.join(td1, "my_package", "submodule")
safe_mkdir(submodule)
mod_path = os.path.join(submodule, "mod.py")
with open(mod_path, "w") as fp:
fp.write("accessed")
pb.add_source(fp.name, "my_package/submodule/mod.py")
pb.add_source(None, "my_package/__init__.py")
pb.add_source(None, "my_package/submodule/__init__.py")
pex = os.path.join(td2, "app.pex")
pb.build(pex)
process = PEX(pex, interpreter=pb.interpreter).run(
blocking=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
assert process.returncode == 0
assert b"accessed\n" == stdout
return cast(bytes, stderr)
def test_access_zipped_assets_integration():
stderr = assert_access_zipped_assets("from pex.util import DistributionHelper")
assert b"" == stderr.strip()
def test_named_temporary_file():
with named_temporary_file() as fp:
name = fp.name
fp.write(b"hi")
fp.flush()
assert os.path.exists(name)
with open(name) as new_fp:
assert new_fp.read() == "hi"
assert not os.path.exists(name)
@mock.patch("os.path.exists", autospec=True, spec_set=True)
def test_iter_pth_paths(mock_exists):
mock_exists.return_value = True
with temporary_dir() as tmpdir:
in_tmp = lambda f: os.path.join(tmpdir, f)
PTH_TEST_MAPPING = {
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python\n": [
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"
],
"relative_path\nrelative_path2\n\nrelative_path3": [
in_tmp("relative_path"),
in_tmp("relative_path2"),
in_tmp("relative_path3"),
],
"duplicate_path\nduplicate_path": [in_tmp("duplicate_path")],
"randompath\nimport nosuchmodule\n": [in_tmp("randompath")],
"import sys\nfoo\n/bar/baz": [in_tmp("foo"), "/bar/baz"],
"import nosuchmodule\nfoo": [],
"import nosuchmodule\n": [],
"import bad)syntax\n": [],
}
for i, pth_content in enumerate(PTH_TEST_MAPPING):
pth_tmp_path = os.path.abspath(os.path.join(tmpdir, "test%s.pth" % i))
with open(pth_tmp_path, "wb") as f:
f.write(to_bytes(pth_content))
assert sorted(PTH_TEST_MAPPING[pth_content]) == sorted(
list(iter_pth_paths(pth_tmp_path))
)
| true | true |
f72a1466c5c327c241f566cd6b2993fbe8a7d9b2 | 2,373 | py | Python | test/eval_fingerprint.py | arthurtofani/footprint | 572401d4cba3299ae9915fca2a7d08ea1a3a9bc4 | [
"MIT"
] | null | null | null | test/eval_fingerprint.py | arthurtofani/footprint | 572401d4cba3299ae9915fca2a7d08ea1a3a9bc4 | [
"MIT"
] | null | null | null | test/eval_fingerprint.py | arthurtofani/footprint | 572401d4cba3299ae9915fca2a7d08ea1a3a9bc4 | [
"MIT"
] | null | null | null | import unittest
import logging
from footprint.models import Audio
from footprint.models import Project
import footprint.clients as db
import os
import random
import footprint.tokenizers as tokenizers
import footprint.evaluators as evaluators
import librosa
class TestEvalFingerprintDummy(unittest.TestCase):
'''
Tests fingerprint evaluator with dummy database
'''
def test_smoke(self):
random.seed(30)
filename = '/dataset/YTCdataset/letitbe/test.mp3'
bucket_name = 'test'
p = load_project(cache=True)
set_dummy_connection(p)
evaluator = evaluators.Fingerprint(p)
entries = abs_path('fixtures/fgpt_entries.txt')
#queries_txt = abs_path('fixtures/queries.txt')
queries_path = abs_path('/cache/queries')
evaluator.build(entries)
queries_list_path = '/cache/queries.txt'
expect_path = '/cache/expect.txt'
evaluator.generate_queries(entries, 5, duration=40, queries_path=queries_path, queries_list_path=queries_list_path, results=expect_path)
evaluator.match(queries_list_path)
result = evaluator.result()
r = compare_results(result, expect_path)
self.assertEqual(r, 1)
# import code; code.interact(local=dict(globals(), **locals()))
def compare_results(result, expectation_path):
file = open(expectation_path, 'r')
fil = file.read()
expected = dict([x.split('\t') for x in fil.split('\n')])
file.close()
comparisons = [expected[query]==found for query, found in result]
return sum(comparisons)/len(comparisons)
def abs_path(path):
dirname = os.path.dirname(os.path.abspath(__file__))
return os.path.join(dirname, path)
def naive_tokenizer_for_chroma(audio):
return tokenizers.naive_tokenizer(audio.features['chroma_cens'], pace=30)
def feat_chroma_cens(audio):
print('running chroma for ', audio.filename)
return librosa.feature.chroma_cens(audio.y, audio.sr)
def set_dummy_connection(p):
cli = db.dummy.Connection(**{'var1': True})
p.set_connection(cli)
def load_project(cache=True):
p = Project(cache=cache, cache_folder='/cache')
p.process_feature('chroma_cens', feat_chroma_cens)
p.use_tokenizer('chroma_naive', naive_tokenizer_for_chroma)
return p
if __name__ == '__main__':
unittest.main()
# import code; code.interact(local=dict(globals(), **locals()))
# python3 -m unittest test.eval_fingerprint.TestEvalFingerprintDummy.test_smoke
| 32.958333 | 140 | 0.747577 | import unittest
import logging
from footprint.models import Audio
from footprint.models import Project
import footprint.clients as db
import os
import random
import footprint.tokenizers as tokenizers
import footprint.evaluators as evaluators
import librosa
class TestEvalFingerprintDummy(unittest.TestCase):
def test_smoke(self):
random.seed(30)
filename = '/dataset/YTCdataset/letitbe/test.mp3'
bucket_name = 'test'
p = load_project(cache=True)
set_dummy_connection(p)
evaluator = evaluators.Fingerprint(p)
entries = abs_path('fixtures/fgpt_entries.txt')
queries_path = abs_path('/cache/queries')
evaluator.build(entries)
queries_list_path = '/cache/queries.txt'
expect_path = '/cache/expect.txt'
evaluator.generate_queries(entries, 5, duration=40, queries_path=queries_path, queries_list_path=queries_list_path, results=expect_path)
evaluator.match(queries_list_path)
result = evaluator.result()
r = compare_results(result, expect_path)
self.assertEqual(r, 1)
def compare_results(result, expectation_path):
file = open(expectation_path, 'r')
fil = file.read()
expected = dict([x.split('\t') for x in fil.split('\n')])
file.close()
comparisons = [expected[query]==found for query, found in result]
return sum(comparisons)/len(comparisons)
def abs_path(path):
dirname = os.path.dirname(os.path.abspath(__file__))
return os.path.join(dirname, path)
def naive_tokenizer_for_chroma(audio):
return tokenizers.naive_tokenizer(audio.features['chroma_cens'], pace=30)
def feat_chroma_cens(audio):
print('running chroma for ', audio.filename)
return librosa.feature.chroma_cens(audio.y, audio.sr)
def set_dummy_connection(p):
cli = db.dummy.Connection(**{'var1': True})
p.set_connection(cli)
def load_project(cache=True):
p = Project(cache=cache, cache_folder='/cache')
p.process_feature('chroma_cens', feat_chroma_cens)
p.use_tokenizer('chroma_naive', naive_tokenizer_for_chroma)
return p
if __name__ == '__main__':
unittest.main()
| true | true |
f72a14cfa2d25b558ea211b3bf08c71152c5cdcc | 8,959 | py | Python | src/sage/knots/knot.py | saraedum/sage-renamed | d2da67b14da2ad766a5906425d60d43a3b3e1270 | [
"BSL-1.0"
] | null | null | null | src/sage/knots/knot.py | saraedum/sage-renamed | d2da67b14da2ad766a5906425d60d43a3b3e1270 | [
"BSL-1.0"
] | null | null | null | src/sage/knots/knot.py | saraedum/sage-renamed | d2da67b14da2ad766a5906425d60d43a3b3e1270 | [
"BSL-1.0"
] | null | null | null | r"""
Knots
AUTHORS:
- Miguel Angel Marco Buzunariz
- Amit Jamadagni
"""
#*****************************************************************************
# Copyright (C) 2014 Travis Scrimshaw <tscrim at ucdavis.edu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.knots.link import Link
from sage.rings.integer import Integer
from sage.rings.finite_rings.integer_mod import Mod
class Knot(Link):
"""
A knot.
A knot is defined as embedding of the circle `\mathbb{S}^1` in the
3-dimensional sphere `\mathbb{S}^3`, considered up to ambient isotopy.
They represent the physical idea of a knotted rope, but with the
particularity that the rope is closed. That is, the ends of the rope
are joined.
.. SEEALSO::
:class:`Link`
INPUT:
- ``data`` -- see :class:`Link` for the allowable inputs
- ``check`` -- optional, default ``True``. If ``True``, make sure
that the data define a knot, not a link
EXAMPLES:
We construct the knot `8_{14}` and compute some invariants::
sage: B = BraidGroup(4)
sage: K = Knot(B([1,1,1,2,-1,2,-3,2,-3]))
.. PLOT::
:width: 300 px
B = BraidGroup(4)
K = Knot(B([1,1,1,2,-1,2,-3,2,-3]))
sphinx_plot(K.plot())
::
sage: K.alexander_polynomial()
-2*t^-2 + 8*t^-1 - 11 + 8*t - 2*t^2
sage: K.jones_polynomial()
t^7 - 3*t^6 + 4*t^5 - 5*t^4 + 6*t^3 - 5*t^2 + 4*t + 1/t - 2
sage: K.determinant()
31
sage: K.signature()
-2
REFERENCES:
- :wikipedia:`Knot_(mathematics)`
.. TODO::
- Make a class Knots for the monoid of all knots and have this be an
element in that monoid.
"""
def __init__(self, data, check=True):
"""
Initialize ``self``.
TESTS::
sage: B = BraidGroup(8)
sage: K = Knot(B([-1, -1, -1, 2, 1, -2, 3, -2, 3]))
sage: TestSuite(K).run()
sage: K = Knot(B([1, -2, 1, -2]))
sage: TestSuite(K).run()
sage: K = Knot([[1, 1, 2, 2]])
sage: TestSuite(K).run()
The following is not a knot: it has two components. ::
sage: Knot([[[1, 2], [-2, -1]], [1, -1]])
Traceback (most recent call last):
...
ValueError: the input has more than 1 connected component
sage: Knot([[[1, 2], [-2, -1]], [1, -1]], check=False)
Knot represented by 2 crossings
"""
Link.__init__(self, data)
if check:
if self.number_of_components() != 1:
raise ValueError("the input has more than 1 connected component")
def __repr__(self):
"""
Return a string representation.
EXAMPLES::
sage: B = BraidGroup(8)
sage: K = Knot(B([1, 2, 1, 2]))
sage: K
Knot represented by 4 crossings
sage: K = Knot([[1, 7, 2, 6], [7, 3, 8, 2], [3, 11, 4, 10], [11, 5, 12, 4], [14, 5, 1, 6], [13, 9, 14, 8], [12, 9, 13, 10]])
sage: K
Knot represented by 7 crossings
"""
pd_len = len(self.pd_code())
return 'Knot represented by {} crossings'.format(pd_len)
def dt_code(self):
"""
Return the DT code of ``self``.
ALGORITHM:
The DT code is generated by the following way:
Start moving along the knot, as we encounter the crossings we
start numbering them, so every crossing has two numbers assigned to
it once we have traced the entire knot. Now we take the even number
associated with every crossing.
The following sign convention is to be followed:
Take the even number with a negative sign if it is an overcrossing
that we are encountering.
OUTPUT: DT code representation of the knot
EXAMPLES::
sage: K = Knot([[1,5,2,4],[5,3,6,2],[3,1,4,6]])
sage: K.dt_code()
[4, 6, 2]
sage: B = BraidGroup(4)
sage: K = Knot(B([1, 2, 1, 2]))
sage: K.dt_code()
[4, -6, 8, -2]
sage: K = Knot([[[1, -2, 3, -4, 5, -1, 2, -3, 4, -5]], [1, 1, 1, 1, 1]])
sage: K.dt_code()
[6, 8, 10, 2, 4]
"""
b = self.braid().Tietze()
N = len(b)
label = [0 for i in range(2 * N)]
string = 1
next_label = 1
type1 = 0
crossing = 0
while next_label <= 2 * N:
string_found = False
for i in range(crossing, N):
if abs(b[i]) == string or abs(b[i]) == string - 1:
string_found = True
crossing = i
break
if not string_found:
for i in range(0, crossing):
if abs(b[i]) == string or abs(b[i]) == string - 1:
string_found = True
crossing = i
break
assert label[2 * crossing + next_label % 2] != 1, "invalid knot"
label[2 * crossing + next_label % 2] = next_label
next_label = next_label + 1
if type1 == 0:
if b[crossing] < 0:
type1 = 1
else:
type1 = -1
else:
type1 = -1 * type1
if ((abs(b[crossing]) == string and b[crossing] * type1 > 0)
or (abs(b[crossing]) != string and b[crossing] * type1 < 0)):
if next_label % 2 == 1:
label[2 * crossing] = label[2 * crossing] * -1
if abs(b[crossing]) == string:
string = string + 1
else:
string = string - 1
crossing = crossing + 1
code = [0 for i in range(N)]
for i in range(N):
for j in range(N):
if label[2 * j + 1] == 2 * i + 1:
code[i] = label[2 * j]
break
return code
def arf_invariant(self):
"""
Return the Arf invariant.
EXAMPLES::
sage: B = BraidGroup(4)
sage: K = Knot(B([-1, 2, 1, 2]))
sage: K.arf_invariant()
0
sage: B = BraidGroup(8)
sage: K = Knot(B([-2, 3, 1, 2, 1, 4]))
sage: K.arf_invariant()
0
sage: K = Knot(B([1, 2, 1, 2]))
sage: K.arf_invariant()
1
"""
a = self.alexander_polynomial()
if Mod(a(-1), 8) == 1 or Mod(a(-1), 8) == 7:
return 0
return 1
def connected_sum(self, other):
r"""
Return the oriented connected sum of ``self`` and ``other``.
.. NOTE::
We give the knots an orientation based upon the braid
representation.
INPUT:
- ``other`` -- a knot
OUTPUT:
A knot equivalent to the connected sum of ``self`` and ``other``.
EXAMPLES::
sage: B = BraidGroup(2)
sage: trefoil = Knot(B([1,1,1]))
sage: K = trefoil.connected_sum(trefoil); K
Knot represented by 6 crossings
sage: K.braid()
s0^3*s1*s0^3*s1^-1
.. PLOT::
:width: 300 px
B = BraidGroup(2)
trefoil = Knot(B([1,1,1]))
K = trefoil.connected_sum(trefoil)
sphinx_plot(K.plot())
::
sage: rev_trefoil = Knot(B([-1,-1,-1]))
sage: K = trefoil.connected_sum(rev_trefoil); K
Knot represented by 6 crossings
sage: K.braid()
s0^3*s1*s0^-3*s1^-1
.. PLOT::
:width: 300 px
B = BraidGroup(2)
t = Knot(B([1,1,1]))
tr = Knot(B([-1,-1,-1]))
K = t.connected_sum(tr)
sphinx_plot(K.plot())
REFERENCES:
- :wikipedia:`Connected_sum`
"""
from copy import deepcopy
from sage.functions.generalized import sign
ogc1 = deepcopy(self.oriented_gauss_code())
ogc2 = deepcopy(other.oriented_gauss_code())
# how much we have to "displace" the numbering of the crossings of other
m1 = max([abs(i) for i in ogc1[0][0]])
m2 = min([abs(i) for i in ogc2[0][0]])
n = m1 - m2 + 1
# construct the oriented gauss code of the result
ogc2[0][0] = [a+int(sign(a))*n for a in ogc2[0][0]]
nogc = [[ogc1[0][0]+ogc2[0][0]],ogc1[1]+ogc2[1]]
return Knot(nogc)
| 30.063758 | 136 | 0.480076 |
from sage.knots.link import Link
from sage.rings.integer import Integer
from sage.rings.finite_rings.integer_mod import Mod
class Knot(Link):
def __init__(self, data, check=True):
Link.__init__(self, data)
if check:
if self.number_of_components() != 1:
raise ValueError("the input has more than 1 connected component")
def __repr__(self):
pd_len = len(self.pd_code())
return 'Knot represented by {} crossings'.format(pd_len)
def dt_code(self):
b = self.braid().Tietze()
N = len(b)
label = [0 for i in range(2 * N)]
string = 1
next_label = 1
type1 = 0
crossing = 0
while next_label <= 2 * N:
string_found = False
for i in range(crossing, N):
if abs(b[i]) == string or abs(b[i]) == string - 1:
string_found = True
crossing = i
break
if not string_found:
for i in range(0, crossing):
if abs(b[i]) == string or abs(b[i]) == string - 1:
string_found = True
crossing = i
break
assert label[2 * crossing + next_label % 2] != 1, "invalid knot"
label[2 * crossing + next_label % 2] = next_label
next_label = next_label + 1
if type1 == 0:
if b[crossing] < 0:
type1 = 1
else:
type1 = -1
else:
type1 = -1 * type1
if ((abs(b[crossing]) == string and b[crossing] * type1 > 0)
or (abs(b[crossing]) != string and b[crossing] * type1 < 0)):
if next_label % 2 == 1:
label[2 * crossing] = label[2 * crossing] * -1
if abs(b[crossing]) == string:
string = string + 1
else:
string = string - 1
crossing = crossing + 1
code = [0 for i in range(N)]
for i in range(N):
for j in range(N):
if label[2 * j + 1] == 2 * i + 1:
code[i] = label[2 * j]
break
return code
def arf_invariant(self):
a = self.alexander_polynomial()
if Mod(a(-1), 8) == 1 or Mod(a(-1), 8) == 7:
return 0
return 1
def connected_sum(self, other):
from copy import deepcopy
from sage.functions.generalized import sign
ogc1 = deepcopy(self.oriented_gauss_code())
ogc2 = deepcopy(other.oriented_gauss_code())
m1 = max([abs(i) for i in ogc1[0][0]])
m2 = min([abs(i) for i in ogc2[0][0]])
n = m1 - m2 + 1
ogc2[0][0] = [a+int(sign(a))*n for a in ogc2[0][0]]
nogc = [[ogc1[0][0]+ogc2[0][0]],ogc1[1]+ogc2[1]]
return Knot(nogc)
| true | true |
f72a14f414a54cde57d44cf0105f7d6ea3a142f8 | 3,674 | py | Python | matplotlib2tikz/patch.py | jameshensman/matplotlib2tikz | 53cd52529c13b08221f962f1a338d33c055132ee | [
"MIT"
] | 1 | 2021-05-25T20:47:41.000Z | 2021-05-25T20:47:41.000Z | matplotlib2tikz/patch.py | jameshensman/matplotlib2tikz | 53cd52529c13b08221f962f1a338d33c055132ee | [
"MIT"
] | null | null | null | matplotlib2tikz/patch.py | jameshensman/matplotlib2tikz | 53cd52529c13b08221f962f1a338d33c055132ee | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
import matplotlib as mpl
from . import path as mypath
def draw_patch(data, obj):
"""Return the PGFPlots code for patches.
"""
# Gather the draw options.
data, draw_options = mypath.get_draw_options(
data, obj.get_edgecolor(), obj.get_facecolor()
)
if isinstance(obj, mpl.patches.Rectangle):
# rectangle specialization
return _draw_rectangle(data, obj, draw_options)
elif isinstance(obj, mpl.patches.Ellipse):
# ellipse specialization
return _draw_ellipse(data, obj, draw_options)
# regular patch
return mypath.draw_path(data, obj.get_path(), draw_options=draw_options)
def draw_patchcollection(data, obj):
"""Returns PGFPlots code for a number of patch objects.
"""
content = []
# Gather the draw options.
try:
edge_color = obj.get_edgecolor()[0]
except IndexError:
edge_color = None
try:
face_color = obj.get_facecolor()[0]
except IndexError:
face_color = None
data, draw_options = mypath.get_draw_options(data, edge_color, face_color)
for path in obj.get_paths():
data, cont = mypath.draw_path(data, path, draw_options=draw_options)
content.append(cont)
return data, content
def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc).
# Even those without labels explicitly set have a label of
# "_nolegend_". Everything else should be skipped because
# they likely correspong to axis/legend objects which are
# handled by PGFPlots
label = obj.get_label()
if label == "":
return data, []
# get real label, bar charts by default only give rectangles
# labels of "_nolegend_"
# See
# <http://stackoverflow.com/questions/35881290/how-to-get-the-label-on-bar-plot-stacked-bar-plot-in-matplotlib>
handles, labels = obj.axes.get_legend_handles_labels()
labelsFound = [
label for h, label in zip(handles, labels) if obj in h.get_children()
]
if len(labelsFound) == 1:
label = labelsFound[0]
legend = ""
if label != "_nolegend_" and label not in data["rectangle_legends"]:
data["rectangle_legends"].add(label)
legend = ("\\addlegendimage{ybar,ybar legend,%s};\n") % (",".join(draw_options))
left_lower_x = obj.get_x()
left_lower_y = obj.get_y()
cont = (
"%s\\draw[%s] (axis cs:%.15g,%.15g) " "rectangle (axis cs:%.15g,%.15g);\n"
) % (
legend,
",".join(draw_options),
left_lower_x,
left_lower_y,
left_lower_x + obj.get_width(),
left_lower_y + obj.get_height(),
)
return data, cont
def _draw_ellipse(data, obj, draw_options):
"""Return the PGFPlots code for ellipses.
"""
if isinstance(obj, mpl.patches.Circle):
# circle specialization
return _draw_circle(data, obj, draw_options)
x, y = obj.center
cont = (
"\\draw[%s, rotate around={%.15g:(%.15g,%.15g)}] (axis cs:%.15g,%.15g) ellipse (%.15g and %.15g);\n"
% (
",".join(draw_options),
obj.angle,
x,
y,
x,
y,
0.5 * obj.width,
0.5 * obj.height,
)
)
return data, cont
def _draw_circle(data, obj, draw_options):
"""Return the PGFPlots code for circles.
"""
x, y = obj.center
cont = "\\draw[%s] (axis cs:%.15g,%.15g) circle (%.15g);\n" % (
",".join(draw_options),
x,
y,
obj.get_radius(),
)
return data, cont
| 28.929134 | 115 | 0.60724 |
import matplotlib as mpl
from . import path as mypath
def draw_patch(data, obj):
data, draw_options = mypath.get_draw_options(
data, obj.get_edgecolor(), obj.get_facecolor()
)
if isinstance(obj, mpl.patches.Rectangle):
return _draw_rectangle(data, obj, draw_options)
elif isinstance(obj, mpl.patches.Ellipse):
return _draw_ellipse(data, obj, draw_options)
return mypath.draw_path(data, obj.get_path(), draw_options=draw_options)
def draw_patchcollection(data, obj):
content = []
try:
edge_color = obj.get_edgecolor()[0]
except IndexError:
edge_color = None
try:
face_color = obj.get_facecolor()[0]
except IndexError:
face_color = None
data, draw_options = mypath.get_draw_options(data, edge_color, face_color)
for path in obj.get_paths():
data, cont = mypath.draw_path(data, path, draw_options=draw_options)
content.append(cont)
return data, content
def _draw_rectangle(data, obj, draw_options):
label = obj.get_label()
if label == "":
return data, []
handles, labels = obj.axes.get_legend_handles_labels()
labelsFound = [
label for h, label in zip(handles, labels) if obj in h.get_children()
]
if len(labelsFound) == 1:
label = labelsFound[0]
legend = ""
if label != "_nolegend_" and label not in data["rectangle_legends"]:
data["rectangle_legends"].add(label)
legend = ("\\addlegendimage{ybar,ybar legend,%s};\n") % (",".join(draw_options))
left_lower_x = obj.get_x()
left_lower_y = obj.get_y()
cont = (
"%s\\draw[%s] (axis cs:%.15g,%.15g) " "rectangle (axis cs:%.15g,%.15g);\n"
) % (
legend,
",".join(draw_options),
left_lower_x,
left_lower_y,
left_lower_x + obj.get_width(),
left_lower_y + obj.get_height(),
)
return data, cont
def _draw_ellipse(data, obj, draw_options):
if isinstance(obj, mpl.patches.Circle):
return _draw_circle(data, obj, draw_options)
x, y = obj.center
cont = (
"\\draw[%s, rotate around={%.15g:(%.15g,%.15g)}] (axis cs:%.15g,%.15g) ellipse (%.15g and %.15g);\n"
% (
",".join(draw_options),
obj.angle,
x,
y,
x,
y,
0.5 * obj.width,
0.5 * obj.height,
)
)
return data, cont
def _draw_circle(data, obj, draw_options):
x, y = obj.center
cont = "\\draw[%s] (axis cs:%.15g,%.15g) circle (%.15g);\n" % (
",".join(draw_options),
x,
y,
obj.get_radius(),
)
return data, cont
| true | true |
f72a15f6519d5b0f2de8510193883522c725a840 | 2,207 | py | Python | run/test_set_get_delete.py | JSeam2/Boopy | fc601e362947242b80bcc5c0a2de838e02ef3f1b | [
"MIT"
] | 3 | 2020-03-18T12:51:01.000Z | 2021-12-01T20:01:17.000Z | run/test_set_get_delete.py | JSeam2/Boopy | fc601e362947242b80bcc5c0a2de838e02ef3f1b | [
"MIT"
] | null | null | null | run/test_set_get_delete.py | JSeam2/Boopy | fc601e362947242b80bcc5c0a2de838e02ef3f1b | [
"MIT"
] | 4 | 2020-02-25T12:27:31.000Z | 2020-06-02T19:49:15.000Z | import os
import time
import subprocess
import signal
import requests
import secrets
print('='*81)
print("Running Integration Test: {}".format(__file__))
nodes = [
['1', '0.0.0.0:8001', '0.0.0.0:81'],
['2', '0.0.0.0:8002', '0.0.0.0:82'],
['3', '0.0.0.0:8003', '0.0.0.0:83'],
['4', '0.0.0.0:8004', '0.0.0.0:84'],
['5', '0.0.0.0:8005', '0.0.0.0:85'],
]
proc_list = []
print('-'*81)
print("Initializing nodes")
for node in nodes:
proc = subprocess.Popen([
'nohup', './boop_node', node[0], node[1], node[2]
])
proc_list.append(proc)
time.sleep(1)
print("Completed Initialization")
print('-'*81)
# Run Routine
# Join
for node in nodes:
id = int(node[0]) % len(nodes)
res = requests.post('http://' + node[2] + '/join',
json={
'id': nodes[id][0],
'address': nodes[id][1]
}
)
# Set value
id = 1
test_dict = {}
for node in nodes:
v = secrets.token_urlsafe(5)
test_dict[id] = v
res = requests.post('http://' + node[2] + '/set',
json={
"key": str(id),
"value": v
}
)
data = res.json()
print(data)
if not data['error']:
print("Test Passed For Node {}".format(node[0]))
else:
print("Test Failed For Node {}".format(node[0]))
id += 1
print('-'*81)
id = 1
for node in nodes:
res = requests.post('http://' + node[2] + '/get',
json={
"key": str(id),
}
)
data = res.json()
print(data)
if data['value'] == test_dict[id]:
print("Test Passed For Node {}".format(node[0]))
else:
print("Test Failed For Node {}".format(node[0]))
id += 1
print('-'*81)
id = 1
for node in nodes:
res = requests.post('http://' + node[2] + '/delete',
json={
"key": str(id),
}
)
data = res.json()
print(data)
if not data['error']:
print("Test Passed For Node {}".format(node[0]))
else:
print("Test Failed For Node {}".format(node[0]))
id += 1
print('-'*81)
print("Completed Integration test")
for proc in proc_list:
print("Kill PID: {}".format(proc.pid))
proc.terminate()
print('='*81) | 19.882883 | 57 | 0.515632 | import os
import time
import subprocess
import signal
import requests
import secrets
print('='*81)
print("Running Integration Test: {}".format(__file__))
nodes = [
['1', '0.0.0.0:8001', '0.0.0.0:81'],
['2', '0.0.0.0:8002', '0.0.0.0:82'],
['3', '0.0.0.0:8003', '0.0.0.0:83'],
['4', '0.0.0.0:8004', '0.0.0.0:84'],
['5', '0.0.0.0:8005', '0.0.0.0:85'],
]
proc_list = []
print('-'*81)
print("Initializing nodes")
for node in nodes:
proc = subprocess.Popen([
'nohup', './boop_node', node[0], node[1], node[2]
])
proc_list.append(proc)
time.sleep(1)
print("Completed Initialization")
print('-'*81)
for node in nodes:
id = int(node[0]) % len(nodes)
res = requests.post('http://' + node[2] + '/join',
json={
'id': nodes[id][0],
'address': nodes[id][1]
}
)
id = 1
test_dict = {}
for node in nodes:
v = secrets.token_urlsafe(5)
test_dict[id] = v
res = requests.post('http://' + node[2] + '/set',
json={
"key": str(id),
"value": v
}
)
data = res.json()
print(data)
if not data['error']:
print("Test Passed For Node {}".format(node[0]))
else:
print("Test Failed For Node {}".format(node[0]))
id += 1
print('-'*81)
id = 1
for node in nodes:
res = requests.post('http://' + node[2] + '/get',
json={
"key": str(id),
}
)
data = res.json()
print(data)
if data['value'] == test_dict[id]:
print("Test Passed For Node {}".format(node[0]))
else:
print("Test Failed For Node {}".format(node[0]))
id += 1
print('-'*81)
id = 1
for node in nodes:
res = requests.post('http://' + node[2] + '/delete',
json={
"key": str(id),
}
)
data = res.json()
print(data)
if not data['error']:
print("Test Passed For Node {}".format(node[0]))
else:
print("Test Failed For Node {}".format(node[0]))
id += 1
print('-'*81)
print("Completed Integration test")
for proc in proc_list:
print("Kill PID: {}".format(proc.pid))
proc.terminate()
print('='*81) | true | true |
f72a1694183b61ee3827e0b4a3909cca8c657eca | 32,592 | py | Python | lib/googlecloudsdk/core/console/console_io.py | ianel20/google-cloud-sdk | 36ed4e06ba3961d0a8fbf30a3eaabf7db6d4e9c3 | [
"Apache-2.0"
] | null | null | null | lib/googlecloudsdk/core/console/console_io.py | ianel20/google-cloud-sdk | 36ed4e06ba3961d0a8fbf30a3eaabf7db6d4e9c3 | [
"Apache-2.0"
] | null | null | null | lib/googlecloudsdk/core/console/console_io.py | ianel20/google-cloud-sdk | 36ed4e06ba3961d0a8fbf30a3eaabf7db6d4e9c3 | [
"Apache-2.0"
] | 1 | 2020-07-25T12:23:41.000Z | 2020-07-25T12:23:41.000Z | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""General console printing utilities used by the Cloud SDK."""
import logging
import os
import re
import sys
import textwrap
import threading
import time
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_attr
from googlecloudsdk.core.console import console_pager
from googlecloudsdk.core.util import files
from googlecloudsdk.third_party.py27 import py27_subprocess as subprocess
FLOAT_COMPARE_EPSILON = 1e-6
class Error(exceptions.Error):
"""Base exception for the module."""
pass
class UnattendedPromptError(Error):
"""An exception for when a prompt cannot be answered."""
def __init__(self):
super(UnattendedPromptError, self).__init__(
'This prompt could not be answered because you are not in an '
'interactive session. You can re-run the command with the --quiet '
'flag to accept default answers for all prompts.')
class OperationCancelledError(Error):
"""An exception for when a prompt cannot be answered."""
def __init__(self):
super(OperationCancelledError, self).__init__('Operation cancelled.')
class TablePrinter(object):
"""Provides the ability to print a list of items as a formatted table.
Using this class helps you adhere to the gcloud style guide.
The table will auto size the columns to fit the maximum item length for that
column. You can also choose how to justify each column and to add extra
padding to each column.
"""
JUSTIFY_LEFT = '<'
JUSTIFY_RIGHT = '>'
JUSTIFY_CENTER = '^'
def __init__(self, headers, title=None,
justification=None, column_padding=None):
"""Creates a new TablePrinter.
Args:
headers: A tuple of strings that represent the column headers titles.
This can be a tuple of empty strings or None's if you do not want
headers displayed. The number of empty elements in the tuple must match
the number of columns you want to display.
title: str, An optional title for the table.
justification: A tuple of JUSTIFY_LEFT, JUSTIFY_RIGHT, JUSTIFY_CENTER that
describes the justification for each column. This must have the same
number of items as the headers tuple.
column_padding: A tuple of ints that describes the extra padding that
should be added to each column. This must have the same
number of items as the headers tuple.
Raises:
ValueError: If the justification or column_padding tuples are not of the
correct type or length.
"""
self.__headers = [h if h else '' for h in headers]
self.__title = title
self.__num_columns = len(self.__headers)
self.__header_widths = [len(str(x)) for x in self.__headers]
self.__column_padding = column_padding
if self.__column_padding is None:
self.__column_padding = tuple([0] * self.__num_columns)
if (not isinstance(self.__column_padding, (tuple)) or
len(self.__column_padding) != self.__num_columns):
raise ValueError('Column padding tuple does not have {0} columns'
.format(self.__num_columns))
self.__justification = justification
if self.__justification is None:
self.__justification = tuple([TablePrinter.JUSTIFY_LEFT] *
self.__num_columns)
if (not isinstance(self.__justification, tuple) or
len(self.__justification) != self.__num_columns):
raise ValueError('Justification tuple does not have {0} columns'
.format(self.__num_columns))
for value in self.__justification:
if not (value is TablePrinter.JUSTIFY_LEFT or
value is TablePrinter.JUSTIFY_RIGHT or
value is TablePrinter.JUSTIFY_CENTER):
raise ValueError('Justification values must be one of JUSTIFY_LEFT, '
'JUSTIFY_RIGHT, or JUSTIFY_CENTER')
def SetTitle(self, title):
"""Sets the title of the table.
Args:
title: str, The new title.
"""
self.__title = title
def Log(self, rows, logger=None, level=logging.INFO):
"""Logs the given rows to the given logger.
Args:
rows: list of tuples, The rows to log the formatted table for.
logger: logging.Logger, The logger to do the logging. If None, the root
logger will be used.
level: logging level, An optional override for the logging level, INFO by
default.
"""
if not logger:
logger = log.getLogger()
lines = self.GetLines(rows)
for line in lines:
logger.log(level, line)
def Print(self, rows, output_stream=None, indent=0):
"""Prints the given rows to stdout.
Args:
rows: list of tuples, The rows to print the formatted table for.
output_stream: file-like object, The stream to wire the rows to. Defaults
to log.out if not given.
indent: int, The number of spaces to indent all lines of the table.
"""
if not output_stream:
output_stream = log.out
lines = self.GetLines(rows, indent=indent)
for line in lines:
output_stream.write(line + '\n')
def GetLines(self, rows, indent=0):
"""Gets a list of strings of formatted lines for the given rows.
Args:
rows: list of tuples, The rows to get the formatted table for.
indent: int, The number of spaces to indent all lines of the table.
Returns:
list of str, The lines of the formatted table that can be printed.
Raises:
ValueError: If any row does not have the correct number of columns.
"""
column_widths = list(self.__header_widths)
for row in rows:
if len(row) != self.__num_columns:
raise ValueError('Row [{row}] does not have {rows} columns'
.format(row=row, rows=self.__num_columns))
# Find the max width of each column
for i in range(self.__num_columns):
column_widths[i] = max(column_widths[i], len(str(row[i])))
# Add padding
column_widths = [column_widths[i] + self.__column_padding[i]
for i in range(self.__num_columns)]
total_width = (len(column_widths) - 1) * 3
for width in column_widths:
total_width += width
edge_line = ('--' +
'---'.join(['-' * width for width in column_widths]) +
'--')
title_divider_line = ('|-' +
'---'.join(['-' * width for width in column_widths]) +
'-|')
divider_line = ('|-' +
'-+-'.join(['-' * width for width in column_widths]) +
'-|')
lines = [edge_line]
if self.__title:
title_line = '| {{title:{justify}{width}s}} |'.format(
justify=TablePrinter.JUSTIFY_CENTER, width=total_width).format(
title=self.__title)
lines.append(title_line)
lines.append(title_divider_line)
# Generate format strings with the correct width for each column
column_formats = []
for i in range(self.__num_columns):
column_formats.append('{{i{i}:{justify}{width}s}}'.format(
i=i, justify=self.__justification[i], width=column_widths[i]))
pattern = '| ' + ' | '.join(column_formats) + ' |'
def _ParameterizedArrayDict(array):
return dict(('i{i}'.format(i=i), array[i]) for i in range(len(array)))
if [h for h in self.__headers if h]:
# Only print headers if there is at least one non-empty header
lines.append(pattern.format(**_ParameterizedArrayDict(self.__headers)))
lines.append(divider_line)
lines.extend([pattern.format(**_ParameterizedArrayDict(row))
for row in rows])
lines.append(edge_line)
if indent:
return [(' ' * indent) + l for l in lines]
return lines
class ListPrinter(object):
"""Provides the ability to print a list of items as a formatted list.
Using this class helps you adhere to the gcloud style guide.
"""
def __init__(self, title):
"""Create a titled list printer that can print rows to stdout.
Args:
title: A string for the title of the list.
"""
self.__title = title
def Print(self, rows, output_stream=None):
"""Print this list with the provided rows to stdout.
Args:
rows: A list of objects representing the rows of this list. Before being
printed, they will be converted to strings.
output_stream: file-like object, The stream to wire the rows to. Defaults
to log.out if not given.
"""
if not output_stream:
output_stream = log.out
output_stream.write(self.__title + '\n')
for row in rows:
output_stream.write(' - ' + str(row) + '\n')
TEXTWRAP = textwrap.TextWrapper(replace_whitespace=False,
drop_whitespace=False,
break_on_hyphens=False)
def _DoWrap(message):
"""Text wrap the given message and correctly handle newlines in the middle.
Args:
message: str, The message to wrap. It may have newlines in the middle of
it.
Returns:
str, The wrapped message.
"""
return '\n'.join([TEXTWRAP.fill(line) for line in message.splitlines()])
def _RawInput(prompt=None):
"""A simple redirect to the built-in raw_input function.
If the prompt is given, it is correctly line wrapped.
Args:
prompt: str, An optional prompt.
Returns:
The input from stdin.
"""
if prompt:
sys.stderr.write(_DoWrap(prompt))
try:
return raw_input()
except EOFError:
return None
def IsInteractive(output=False, error=False, heuristic=False):
"""Determines if the current terminal session is interactive.
sys.stdin must be a terminal input stream.
Args:
output: If True then sys.stdout must also be a terminal output stream.
error: If True then sys.stderr must also be a terminal output stream.
heuristic: If True then we also do some additional heuristics to check if
we are in an interactive context. Checking home path for example.
Returns:
True if the current terminal session is interactive.
"""
if not sys.stdin.isatty():
return False
if output and not sys.stdout.isatty():
return False
if error and not sys.stderr.isatty():
return False
if heuristic:
# Check the home path. Most startup scripts for example are executed by
# users that don't have a home path set. Home is OS dependent though, so
# check everything.
# *NIX OS usually sets the HOME env variable. It is usually '/home/user',
# but can also be '/root'. If it's just '/' we are most likely in an init
# script.
# Windows usually sets HOMEDRIVE and HOMEPATH. If they don't exist we are
# probably being run from a task scheduler context. HOMEPATH can be '\'
# when a user has a network mapped home directory.
# Cygwin has it all! Both Windows and Linux. Checking both is perfect.
home = os.getenv('HOME')
homepath = os.getenv('HOMEPATH')
if not homepath and (not home or home == '/'):
return False
return True
def CanPrompt():
"""Returns true if we can prompt the user for information.
This combines all checks (IsInteractive(), disable_prompts is False) to
verify that we can prompt the user for information.
Returns:
bool, True if we can prompt the user for information.
"""
return (IsInteractive(error=True) and
not properties.VALUES.core.disable_prompts.GetBool())
def PromptContinue(message=None, prompt_string=None, default=True,
throw_if_unattended=False, cancel_on_no=False):
"""Prompts the user a yes or no question and asks if they want to continue.
Args:
message: str, The prompt to print before the question.
prompt_string: str, An alternate yes/no prompt to display. If None, it
defaults to 'Do you want to continue'.
default: bool, What the default answer should be. True for yes, False for
no.
throw_if_unattended: bool, If True, this will throw if there was nothing
to consume on stdin and stdin is not a tty.
cancel_on_no: bool, If True and the user answers no, throw an exception to
cancel the entire operation. Useful if you know you don't want to
continue doing anything and don't want to have to raise your own
exception.
Raises:
UnattendedPromptError: If there is no input to consume and this is not
running in an interactive terminal.
OperationCancelledError: If the user answers no and cancel_on_no is True.
Returns:
bool, False if the user said no, True if the user said anything else or if
prompts are disabled.
"""
if properties.VALUES.core.disable_prompts.GetBool():
if not default and cancel_on_no:
raise OperationCancelledError()
return default
if message:
sys.stderr.write(_DoWrap(message) + '\n\n')
if not prompt_string:
prompt_string = 'Do you want to continue'
if default:
prompt_string += ' (Y/n)? '
else:
prompt_string += ' (y/N)? '
sys.stderr.write(_DoWrap(prompt_string))
def GetAnswer():
while True:
answer = _RawInput()
# pylint:disable=g-explicit-bool-comparison, We explicitly want to
# distinguish between empty string and None.
if answer == '':
# User just hit enter, return default.
sys.stderr.write('\n')
return default
elif answer is None:
# This means we hit EOF, no input or user closed the stream.
if throw_if_unattended and not IsInteractive():
sys.stderr.write('\n')
raise UnattendedPromptError()
else:
sys.stderr.write('\n')
return default
elif answer.lower() in ['y', 'yes']:
sys.stderr.write('\n')
return True
elif answer.lower() in ['n', 'no']:
sys.stderr.write('\n')
return False
else:
sys.stderr.write("Please enter 'y' or 'n': ")
answer = GetAnswer()
if not answer and cancel_on_no:
raise OperationCancelledError()
return answer
def PromptResponse(message):
"""Prompts the user for a string.
Args:
message: str, The prompt to print before the question.
Returns:
str, The string entered by the user, or None if prompts are disabled.
"""
if properties.VALUES.core.disable_prompts.GetBool():
return None
response = _RawInput(message)
return response
def PromptWithDefault(message, default=None):
"""Prompts the user for a string, allowing a default.
Unlike PromptResponse, this also appends a ': ' to the prompt. If 'default'
is specified, the default is also written written into the prompt (e.g.
if message is "message" and default is "default", the prompt would be
"message (default): ").
The default is returned if the user simply presses enter (no input) or an
EOF is received.
Args:
message: str, The prompt to print before the question.
default: str, The default value (if any).
Returns:
str, The string entered by the user, or the default if no value was
entered or prompts are disabled.
"""
if properties.VALUES.core.disable_prompts.GetBool():
return default
if default:
message += ' ({default}): '.format(default=default)
else:
message += ': '
response = _RawInput(message)
if not response:
response = default
return response
def PromptChoice(options, default=None, message=None, prompt_string=None):
"""Prompt the user to select a choice from a list of items.
Args:
options: [object], A list of objects to print as choices. Their str()
method will be used to display them.
default: int, The default index to return if prompting is disabled or if
they do not enter a choice.
message: str, An optional message to print before the choices are displayed.
prompt_string: str, A string to print when prompting the user to enter a
choice. If not given, a default prompt is used.
Raises:
ValueError: If no options are given or if the default is not in the range of
available options.
Returns:
The index of the item in the list that was chosen, or the default if prompts
are disabled.
"""
if not options:
raise ValueError('You must provide at least one option.')
maximum = len(options)
if default is not None and not 0 <= default < maximum:
raise ValueError(
'Default option [{default}] is not a valid index for the options list '
'[{maximum} options given]'.format(default=default, maximum=maximum))
if properties.VALUES.core.disable_prompts.GetBool():
return default
if message:
sys.stderr.write(_DoWrap(message) + '\n')
for i, option in enumerate(options):
sys.stderr.write(' [{index}] {option}\n'.format(
index=i + 1, option=str(option)))
if not prompt_string:
prompt_string = 'Please enter your numeric choice'
if default is None:
suffix_string = ': '
else:
suffix_string = ' ({default}): '.format(default=default + 1)
sys.stderr.write(_DoWrap(prompt_string + suffix_string))
while True:
answer = _RawInput()
if answer is None or (answer is '' and default is not None):
# Return default if we failed to read from stdin
# Return default if the user hit enter and there is a valid default
# Prompt again otherwise
sys.stderr.write('\n')
return default
try:
num_choice = int(answer)
if num_choice < 1 or num_choice > maximum:
raise ValueError('Choice must be between 1 and {maximum}'.format(
maximum=maximum))
sys.stderr.write('\n')
return num_choice - 1
except ValueError:
sys.stderr.write('Please enter a value between 1 and {maximum}: '
.format(maximum=maximum))
def LazyFormat(s, **kwargs):
"""Converts {key} => value for key, value in kwargs.iteritems().
After the {key} converstions it converts {{<identifier>}} => {<identifier>}.
Args:
s: str, The string to format.
**kwargs: {str:str}, A dict of strings for named parameters.
Returns:
str, The lazily-formatted string.
"""
for key, value in kwargs.iteritems():
fmt = '{' + key + '}'
start = 0
while True:
start = s.find(fmt, start)
if start == -1:
break
if (start and s[start - 1] == '{' and
len(fmt) < len(s[start:]) and s[start + len(fmt)] == '}'):
# {{key}} => {key}
s = s[0:start - 1] + fmt + s[start + len(fmt) + 1:]
start += len(fmt)
else:
# {key} => value
s = s[0:start] + value + s[start + len(fmt):]
start += len(value)
# {{unknown}} => {unknown}
return re.sub(r'{({\w+})}', r'\1', s)
def PrintExtendedList(items, col_fetchers):
"""Print a properly formated extended list for some set of resources.
If items is a generator, this function may elect to only request those rows
that it is ready to display.
Args:
items: [resource] or a generator producing resources, The objects
representing cloud resources.
col_fetchers: [(string, func(resource))], A list of tuples, one for each
column, in the order that they should appear. The string is the title
of that column which will be printed in a header. The func is a function
that will fetch a row-value for that column, given the resource
corresponding to the row.
"""
total_items = 0
rows = [[title for (title, unused_func) in col_fetchers]]
for item in items:
total_items += 1
row = []
for (unused_title, func) in col_fetchers:
value = func(item)
if value is None:
row.append('-')
else:
row.append(value)
rows.append(row)
attr = console_attr.GetConsoleAttr()
max_col_widths = [0] * len(col_fetchers)
for row in rows:
for col in range(len(row)):
max_col_widths[col] = max(max_col_widths[col],
attr.DisplayWidth(unicode(row[col]))+2)
for row in rows:
for col in range(len(row)):
width = max_col_widths[col]
item = unicode(row[col])
item_width = attr.DisplayWidth(item)
if item_width < width and col != len(row) - 1:
item += u' ' * (width - item_width)
log.out.write(item)
log.out.write('\n')
if not total_items:
log.status.write('Listed 0 items.\n')
class ProgressTracker(object):
"""A context manager for telling the user about long-running progress."""
SPIN_MARKS = [
'|',
'/',
'-',
'\\',
]
def __init__(self, message, autotick=True, detail_message_callback=None,
tick_delay=1):
self._message = message
self._prefix = message + '...'
self._ticks = 0
self._autotick = autotick
self._done = False
self._lock = threading.Lock()
self._detail_message_callback = detail_message_callback
self._last_message_size = 0
self._tick_delay = tick_delay
self._is_tty = IsInteractive(output=True, error=True)
def _GetPrefix(self):
if self._detail_message_callback:
detail_message = self._detail_message_callback()
if detail_message:
return self._prefix + ' ' + detail_message + '...'
return self._prefix
def __enter__(self):
log.file_only_logger.info(self._GetPrefix())
self._Print()
if self._autotick:
def Ticker():
while True:
time.sleep(self._tick_delay)
if self.Tick():
return
threading.Thread(target=Ticker).start()
return self
def Tick(self):
"""Give a visual indication to the user that some progress has been made.
Output is sent to sys.stderr. Nothing is shown if output is not a TTY.
Returns:
Whether progress has completed.
"""
if self._is_tty:
with self._lock:
if not self._done:
self._ticks += 1
self._Print(ProgressTracker.SPIN_MARKS[
self._ticks % len(ProgressTracker.SPIN_MARKS)])
return self._done
def _Print(self, message=''):
"""Reprints the prefix followed by an optional message."""
display_message = self._GetPrefix()
if message:
display_message += message
# This is to clear the display buffer, otherwise it would display the
# trailing parts of the previous line
if self._last_message_size > 0:
sys.stderr.write('\r' + self._last_message_size * ' ')
self._last_message_size = len(display_message)
sys.stderr.write('\r' + display_message)
sys.stderr.flush()
def __exit__(self, ex_type, unused_value, unused_traceback):
with self._lock:
self._done = True
# If an exception was raised during progress tracking, exit silently here
# and let the appropriate exception handler tell the user what happened.
if ex_type:
# This is to prevent the tick character from appearing before 'failed.'
# (ex. 'message...failed' instead of 'message.../failed.')
self._Print('failed.\n')
return False
self._Print('done.\n')
class DelayedProgressTracker(ProgressTracker):
"""A progress tracker that only appears during a long running operation.
Waits for the given timeout, then displays a progress tacker.
"""
class TrackerState(object):
"""Enum representing the current state of the progress tracker."""
class _TrackerStateTuple(object):
def __init__(self, name):
self.name = name
WAITING = _TrackerStateTuple('Waiting')
STARTED = _TrackerStateTuple('Started')
FINISHED = _TrackerStateTuple('Finished')
def __init__(self, message, timeout, autotick=True,
detail_message_callback=None):
super(DelayedProgressTracker, self).__init__(
message, autotick=autotick,
detail_message_callback=detail_message_callback)
self._timeout = timeout
self._state = self.TrackerState.WAITING
self._state_lock = threading.Lock()
def _SleepWhileNotFinished(self, timeout, increment=0.1):
"""Sleep for the given time unless the tracker enters the FINISHED state.
Args:
timeout: number, the total time for which to sleep
increment: number, the increment at which to check whether the tracker is
FINISHED
Returns:
bool, True unless the tracker reached the FINISHED state before the total
sleep time elapsed
"""
elapsed_time = 0
while (elapsed_time + FLOAT_COMPARE_EPSILON) <= timeout:
time.sleep(increment)
elapsed_time += increment
if self._state is self.TrackerState.FINISHED:
return False
return True
def __enter__(self):
def StartTracker():
if not self._SleepWhileNotFinished(self._timeout):
# If we aborted sleep early, return. We exited the progress tracker
# before the delay finished.
return
with self._state_lock:
if self._state is not self.TrackerState.FINISHED:
self._state = self.TrackerState.STARTED
super(DelayedProgressTracker, self).__enter__()
threading.Thread(target=StartTracker).start()
return self
def __exit__(self, exc_type, exc_value, traceback):
with self._state_lock:
if self._state is self.TrackerState.STARTED:
super(DelayedProgressTracker, self).__exit__(exc_type, exc_value,
traceback)
self._state = self.TrackerState.FINISHED
def Tick(self):
with self._state_lock:
if self._state is self.TrackerState.STARTED:
return super(DelayedProgressTracker, self).Tick()
return self._state is self.TrackerState.FINISHED
class ProgressBar(object):
"""A simple progress bar for tracking completion of an action.
This progress bar works without having to use any control characters. It
prints the action that is being done, and then fills a progress bar below it.
You should not print anything else on the output stream during this time as it
will cause the progress bar to break on lines.
Progress bars can be stacked into a group. first=True marks the first bar in
the group and last=True marks the last bar in the group. The default assumes
a singleton bar with first=True and last=True.
This class can also be used in a context manager.
"""
@staticmethod
def _DefaultCallback(progress_factor):
pass
DEFAULT_CALLBACK = _DefaultCallback
@staticmethod
def SplitProgressBar(original_callback, weights):
"""Splits a progress bar into logical sections.
Wraps the original callback so that each of the subsections can use the full
range of 0 to 1 to indicate its progress. The overall progress bar will
display total progress based on the weights of the tasks.
Args:
original_callback: f(float), The original callback for the progress bar.
weights: [float], The weights of the tasks to create. These can be any
numbers you want and the split will be based on their proportions to
each other.
Raises:
ValueError: If the weights don't add up to 1.
Returns:
(f(float), ), A tuple of callback functions, in order, for the subtasks.
"""
if (original_callback is None or
original_callback == ProgressBar.DEFAULT_CALLBACK):
return tuple([ProgressBar.DEFAULT_CALLBACK for _ in range(len(weights))])
def MakeCallback(already_done, weight):
def Callback(done_fraction):
original_callback(already_done + (done_fraction * weight))
return Callback
total = float(sum(weights))
callbacks = []
already_done = 0
for weight in weights:
normalized_weight = weight / total
callbacks.append(MakeCallback(already_done, normalized_weight))
already_done += normalized_weight
return tuple(callbacks)
def __init__(self, label, stream=log.status, total_ticks=60, first=True,
last=True):
"""Creates a progress bar for the given action.
Args:
label: str, The action that is being performed.
stream: The output stream to write to, stderr by default.
total_ticks: int, The number of ticks wide to make the progress bar.
first: bool, True if this is the first bar in a stacked group.
last: bool, True if this is the last bar in a stacked group.
"""
self._stream = stream
self._ticks_written = 0
self._total_ticks = total_ticks
self._first = first
self._last = last
attr = console_attr.ConsoleAttr()
self._box = attr.GetBoxLineCharacters()
self._redraw = (self._box.d_dr != self._box.d_vr or
self._box.d_dl != self._box.d_vl)
max_label_width = self._total_ticks - 4
if len(label) > max_label_width:
label = label[:max_label_width - 3] + '...'
elif len(label) < max_label_width:
diff = max_label_width - len(label)
label += ' ' * diff
left = self._box.d_vr + self._box.d_h
right = self._box.d_h + self._box.d_vl
self._label = u'{left} {label} {right}'.format(left=left, label=label,
right=right)
def Start(self):
"""Starts the progress bar by writing the top rule and label."""
if self._first or self._redraw:
left = self._box.d_dr if self._first else self._box.d_vr
right = self._box.d_dl if self._first else self._box.d_vl
rule = u'{left}{middle}{right}\n'.format(
left=left, middle=self._box.d_h * self._total_ticks, right=right)
self._stream.write(rule)
self._stream.write(self._label + '\n')
self._stream.write(self._box.d_ur)
self._ticks_written = 0
def SetProgress(self, progress_factor):
"""Sets the current progress of the task.
This method has no effect if the progress bar has already progressed past
the progress you call it with (since the progress bar cannot back up).
Args:
progress_factor: float, The current progress as a float between 0 and 1.
"""
expected_ticks = int(self._total_ticks * progress_factor)
new_ticks = expected_ticks - self._ticks_written
# Don't allow us to go over 100%.
new_ticks = min(new_ticks, self._total_ticks - self._ticks_written)
if new_ticks > 0:
self._stream.write(self._box.d_h * new_ticks)
self._ticks_written += new_ticks
if expected_ticks == self._total_ticks:
end = '\n' if self._last or not self._redraw else '\r'
self._stream.write(self._box.d_ul + end)
self._stream.flush()
def Finish(self):
"""Mark the progress as done."""
self.SetProgress(1)
def __enter__(self):
self.Start()
return self
def __exit__(self, *args):
self.Finish()
def More(contents, out=None, prompt=None, check_pager=True):
"""Run a user specified pager or fall back to the internal pager.
Args:
contents: The entire contents of the text lines to page.
out: The output stream, log.out (effectively) if None.
prompt: The page break prompt.
check_pager: Checks the PAGER env var and uses it if True.
"""
if not IsInteractive(output=True):
if not out:
out = log.out
out.write(contents)
return
if not out:
# Rendered help to the log file.
log.file_only_logger.info(contents)
# Paging shenanigans to stdout.
out = sys.stdout
if check_pager:
pager = os.environ.get('PAGER', None)
if pager == '-':
# Use the fallback Pager.
pager = None
elif not pager:
# Search for a pager that handles ANSI escapes.
for command in ('less', 'pager'):
if files.FindExecutableOnPath(command):
pager = command
break
if pager:
less = os.environ.get('LESS', None)
if less is None:
os.environ['LESS'] = '-R'
p = subprocess.Popen(pager, stdin=subprocess.PIPE, shell=True)
encoding = console_attr.GetConsoleAttr().GetEncoding()
p.communicate(input=contents.encode(encoding))
p.wait()
if less is None:
os.environ.pop('LESS')
return
# Fall back to the internal pager.
console_pager.Pager(contents, out, prompt).Run()
| 34.020877 | 80 | 0.665777 |
import logging
import os
import re
import sys
import textwrap
import threading
import time
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_attr
from googlecloudsdk.core.console import console_pager
from googlecloudsdk.core.util import files
from googlecloudsdk.third_party.py27 import py27_subprocess as subprocess
FLOAT_COMPARE_EPSILON = 1e-6
class Error(exceptions.Error):
pass
class UnattendedPromptError(Error):
def __init__(self):
super(UnattendedPromptError, self).__init__(
'This prompt could not be answered because you are not in an '
'interactive session. You can re-run the command with the --quiet '
'flag to accept default answers for all prompts.')
class OperationCancelledError(Error):
def __init__(self):
super(OperationCancelledError, self).__init__('Operation cancelled.')
class TablePrinter(object):
JUSTIFY_LEFT = '<'
JUSTIFY_RIGHT = '>'
JUSTIFY_CENTER = '^'
def __init__(self, headers, title=None,
justification=None, column_padding=None):
self.__headers = [h if h else '' for h in headers]
self.__title = title
self.__num_columns = len(self.__headers)
self.__header_widths = [len(str(x)) for x in self.__headers]
self.__column_padding = column_padding
if self.__column_padding is None:
self.__column_padding = tuple([0] * self.__num_columns)
if (not isinstance(self.__column_padding, (tuple)) or
len(self.__column_padding) != self.__num_columns):
raise ValueError('Column padding tuple does not have {0} columns'
.format(self.__num_columns))
self.__justification = justification
if self.__justification is None:
self.__justification = tuple([TablePrinter.JUSTIFY_LEFT] *
self.__num_columns)
if (not isinstance(self.__justification, tuple) or
len(self.__justification) != self.__num_columns):
raise ValueError('Justification tuple does not have {0} columns'
.format(self.__num_columns))
for value in self.__justification:
if not (value is TablePrinter.JUSTIFY_LEFT or
value is TablePrinter.JUSTIFY_RIGHT or
value is TablePrinter.JUSTIFY_CENTER):
raise ValueError('Justification values must be one of JUSTIFY_LEFT, '
'JUSTIFY_RIGHT, or JUSTIFY_CENTER')
def SetTitle(self, title):
self.__title = title
def Log(self, rows, logger=None, level=logging.INFO):
if not logger:
logger = log.getLogger()
lines = self.GetLines(rows)
for line in lines:
logger.log(level, line)
def Print(self, rows, output_stream=None, indent=0):
if not output_stream:
output_stream = log.out
lines = self.GetLines(rows, indent=indent)
for line in lines:
output_stream.write(line + '\n')
def GetLines(self, rows, indent=0):
column_widths = list(self.__header_widths)
for row in rows:
if len(row) != self.__num_columns:
raise ValueError('Row [{row}] does not have {rows} columns'
.format(row=row, rows=self.__num_columns))
for i in range(self.__num_columns):
column_widths[i] = max(column_widths[i], len(str(row[i])))
column_widths = [column_widths[i] + self.__column_padding[i]
for i in range(self.__num_columns)]
total_width = (len(column_widths) - 1) * 3
for width in column_widths:
total_width += width
edge_line = ('--' +
'---'.join(['-' * width for width in column_widths]) +
'--')
title_divider_line = ('|-' +
'---'.join(['-' * width for width in column_widths]) +
'-|')
divider_line = ('|-' +
'-+-'.join(['-' * width for width in column_widths]) +
'-|')
lines = [edge_line]
if self.__title:
title_line = '| {{title:{justify}{width}s}} |'.format(
justify=TablePrinter.JUSTIFY_CENTER, width=total_width).format(
title=self.__title)
lines.append(title_line)
lines.append(title_divider_line)
column_formats = []
for i in range(self.__num_columns):
column_formats.append('{{i{i}:{justify}{width}s}}'.format(
i=i, justify=self.__justification[i], width=column_widths[i]))
pattern = '| ' + ' | '.join(column_formats) + ' |'
def _ParameterizedArrayDict(array):
return dict(('i{i}'.format(i=i), array[i]) for i in range(len(array)))
if [h for h in self.__headers if h]:
lines.append(pattern.format(**_ParameterizedArrayDict(self.__headers)))
lines.append(divider_line)
lines.extend([pattern.format(**_ParameterizedArrayDict(row))
for row in rows])
lines.append(edge_line)
if indent:
return [(' ' * indent) + l for l in lines]
return lines
class ListPrinter(object):
def __init__(self, title):
self.__title = title
def Print(self, rows, output_stream=None):
if not output_stream:
output_stream = log.out
output_stream.write(self.__title + '\n')
for row in rows:
output_stream.write(' - ' + str(row) + '\n')
TEXTWRAP = textwrap.TextWrapper(replace_whitespace=False,
drop_whitespace=False,
break_on_hyphens=False)
def _DoWrap(message):
return '\n'.join([TEXTWRAP.fill(line) for line in message.splitlines()])
def _RawInput(prompt=None):
if prompt:
sys.stderr.write(_DoWrap(prompt))
try:
return raw_input()
except EOFError:
return None
def IsInteractive(output=False, error=False, heuristic=False):
if not sys.stdin.isatty():
return False
if output and not sys.stdout.isatty():
return False
if error and not sys.stderr.isatty():
return False
if heuristic:
# check everything.
# *NIX OS usually sets the HOME env variable. It is usually '/home/user',
# but can also be '/root'. If it's just '/' we are most likely in an init
# probably being run from a task scheduler context. HOMEPATH can be '\'
# when a user has a network mapped home directory.
# Cygwin has it all! Both Windows and Linux. Checking both is perfect.
home = os.getenv('HOME')
homepath = os.getenv('HOMEPATH')
if not homepath and (not home or home == '/'):
return False
return True
def CanPrompt():
return (IsInteractive(error=True) and
not properties.VALUES.core.disable_prompts.GetBool())
def PromptContinue(message=None, prompt_string=None, default=True,
throw_if_unattended=False, cancel_on_no=False):
if properties.VALUES.core.disable_prompts.GetBool():
if not default and cancel_on_no:
raise OperationCancelledError()
return default
if message:
sys.stderr.write(_DoWrap(message) + '\n\n')
if not prompt_string:
prompt_string = 'Do you want to continue'
if default:
prompt_string += ' (Y/n)? '
else:
prompt_string += ' (y/N)? '
sys.stderr.write(_DoWrap(prompt_string))
def GetAnswer():
while True:
answer = _RawInput()
# pylint:disable=g-explicit-bool-comparison, We explicitly want to
# distinguish between empty string and None.
if answer == '':
# User just hit enter, return default.
sys.stderr.write('\n')
return default
elif answer is None:
# This means we hit EOF, no input or user closed the stream.
if throw_if_unattended and not IsInteractive():
sys.stderr.write('\n')
raise UnattendedPromptError()
else:
sys.stderr.write('\n')
return default
elif answer.lower() in ['y', 'yes']:
sys.stderr.write('\n')
return True
elif answer.lower() in ['n', 'no']:
sys.stderr.write('\n')
return False
else:
sys.stderr.write("Please enter 'y' or 'n': ")
answer = GetAnswer()
if not answer and cancel_on_no:
raise OperationCancelledError()
return answer
def PromptResponse(message):
if properties.VALUES.core.disable_prompts.GetBool():
return None
response = _RawInput(message)
return response
def PromptWithDefault(message, default=None):
if properties.VALUES.core.disable_prompts.GetBool():
return default
if default:
message += ' ({default}): '.format(default=default)
else:
message += ': '
response = _RawInput(message)
if not response:
response = default
return response
def PromptChoice(options, default=None, message=None, prompt_string=None):
if not options:
raise ValueError('You must provide at least one option.')
maximum = len(options)
if default is not None and not 0 <= default < maximum:
raise ValueError(
'Default option [{default}] is not a valid index for the options list '
'[{maximum} options given]'.format(default=default, maximum=maximum))
if properties.VALUES.core.disable_prompts.GetBool():
return default
if message:
sys.stderr.write(_DoWrap(message) + '\n')
for i, option in enumerate(options):
sys.stderr.write(' [{index}] {option}\n'.format(
index=i + 1, option=str(option)))
if not prompt_string:
prompt_string = 'Please enter your numeric choice'
if default is None:
suffix_string = ': '
else:
suffix_string = ' ({default}): '.format(default=default + 1)
sys.stderr.write(_DoWrap(prompt_string + suffix_string))
while True:
answer = _RawInput()
if answer is None or (answer is '' and default is not None):
# Return default if we failed to read from stdin
# Return default if the user hit enter and there is a valid default
# Prompt again otherwise
sys.stderr.write('\n')
return default
try:
num_choice = int(answer)
if num_choice < 1 or num_choice > maximum:
raise ValueError('Choice must be between 1 and {maximum}'.format(
maximum=maximum))
sys.stderr.write('\n')
return num_choice - 1
except ValueError:
sys.stderr.write('Please enter a value between 1 and {maximum}: '
.format(maximum=maximum))
def LazyFormat(s, **kwargs):
for key, value in kwargs.iteritems():
fmt = '{' + key + '}'
start = 0
while True:
start = s.find(fmt, start)
if start == -1:
break
if (start and s[start - 1] == '{' and
len(fmt) < len(s[start:]) and s[start + len(fmt)] == '}'):
# {{key}} => {key}
s = s[0:start - 1] + fmt + s[start + len(fmt) + 1:]
start += len(fmt)
else:
# {key} => value
s = s[0:start] + value + s[start + len(fmt):]
start += len(value)
# {{unknown}} => {unknown}
return re.sub(r'{({\w+})}', r'\1', s)
def PrintExtendedList(items, col_fetchers):
total_items = 0
rows = [[title for (title, unused_func) in col_fetchers]]
for item in items:
total_items += 1
row = []
for (unused_title, func) in col_fetchers:
value = func(item)
if value is None:
row.append('-')
else:
row.append(value)
rows.append(row)
attr = console_attr.GetConsoleAttr()
max_col_widths = [0] * len(col_fetchers)
for row in rows:
for col in range(len(row)):
max_col_widths[col] = max(max_col_widths[col],
attr.DisplayWidth(unicode(row[col]))+2)
for row in rows:
for col in range(len(row)):
width = max_col_widths[col]
item = unicode(row[col])
item_width = attr.DisplayWidth(item)
if item_width < width and col != len(row) - 1:
item += u' ' * (width - item_width)
log.out.write(item)
log.out.write('\n')
if not total_items:
log.status.write('Listed 0 items.\n')
class ProgressTracker(object):
SPIN_MARKS = [
'|',
'/',
'-',
'\\',
]
def __init__(self, message, autotick=True, detail_message_callback=None,
tick_delay=1):
self._message = message
self._prefix = message + '...'
self._ticks = 0
self._autotick = autotick
self._done = False
self._lock = threading.Lock()
self._detail_message_callback = detail_message_callback
self._last_message_size = 0
self._tick_delay = tick_delay
self._is_tty = IsInteractive(output=True, error=True)
def _GetPrefix(self):
if self._detail_message_callback:
detail_message = self._detail_message_callback()
if detail_message:
return self._prefix + ' ' + detail_message + '...'
return self._prefix
def __enter__(self):
log.file_only_logger.info(self._GetPrefix())
self._Print()
if self._autotick:
def Ticker():
while True:
time.sleep(self._tick_delay)
if self.Tick():
return
threading.Thread(target=Ticker).start()
return self
def Tick(self):
if self._is_tty:
with self._lock:
if not self._done:
self._ticks += 1
self._Print(ProgressTracker.SPIN_MARKS[
self._ticks % len(ProgressTracker.SPIN_MARKS)])
return self._done
def _Print(self, message=''):
display_message = self._GetPrefix()
if message:
display_message += message
# This is to clear the display buffer, otherwise it would display the
# trailing parts of the previous line
if self._last_message_size > 0:
sys.stderr.write('\r' + self._last_message_size * ' ')
self._last_message_size = len(display_message)
sys.stderr.write('\r' + display_message)
sys.stderr.flush()
def __exit__(self, ex_type, unused_value, unused_traceback):
with self._lock:
self._done = True
# If an exception was raised during progress tracking, exit silently here
# and let the appropriate exception handler tell the user what happened.
if ex_type:
# This is to prevent the tick character from appearing before 'failed.'
# (ex. 'message...failed' instead of 'message.../failed.')
self._Print('failed.\n')
return False
self._Print('done.\n')
class DelayedProgressTracker(ProgressTracker):
class TrackerState(object):
class _TrackerStateTuple(object):
def __init__(self, name):
self.name = name
WAITING = _TrackerStateTuple('Waiting')
STARTED = _TrackerStateTuple('Started')
FINISHED = _TrackerStateTuple('Finished')
def __init__(self, message, timeout, autotick=True,
detail_message_callback=None):
super(DelayedProgressTracker, self).__init__(
message, autotick=autotick,
detail_message_callback=detail_message_callback)
self._timeout = timeout
self._state = self.TrackerState.WAITING
self._state_lock = threading.Lock()
def _SleepWhileNotFinished(self, timeout, increment=0.1):
elapsed_time = 0
while (elapsed_time + FLOAT_COMPARE_EPSILON) <= timeout:
time.sleep(increment)
elapsed_time += increment
if self._state is self.TrackerState.FINISHED:
return False
return True
def __enter__(self):
def StartTracker():
if not self._SleepWhileNotFinished(self._timeout):
# If we aborted sleep early, return. We exited the progress tracker
# before the delay finished.
return
with self._state_lock:
if self._state is not self.TrackerState.FINISHED:
self._state = self.TrackerState.STARTED
super(DelayedProgressTracker, self).__enter__()
threading.Thread(target=StartTracker).start()
return self
def __exit__(self, exc_type, exc_value, traceback):
with self._state_lock:
if self._state is self.TrackerState.STARTED:
super(DelayedProgressTracker, self).__exit__(exc_type, exc_value,
traceback)
self._state = self.TrackerState.FINISHED
def Tick(self):
with self._state_lock:
if self._state is self.TrackerState.STARTED:
return super(DelayedProgressTracker, self).Tick()
return self._state is self.TrackerState.FINISHED
class ProgressBar(object):
@staticmethod
def _DefaultCallback(progress_factor):
pass
DEFAULT_CALLBACK = _DefaultCallback
@staticmethod
def SplitProgressBar(original_callback, weights):
if (original_callback is None or
original_callback == ProgressBar.DEFAULT_CALLBACK):
return tuple([ProgressBar.DEFAULT_CALLBACK for _ in range(len(weights))])
def MakeCallback(already_done, weight):
def Callback(done_fraction):
original_callback(already_done + (done_fraction * weight))
return Callback
total = float(sum(weights))
callbacks = []
already_done = 0
for weight in weights:
normalized_weight = weight / total
callbacks.append(MakeCallback(already_done, normalized_weight))
already_done += normalized_weight
return tuple(callbacks)
def __init__(self, label, stream=log.status, total_ticks=60, first=True,
last=True):
self._stream = stream
self._ticks_written = 0
self._total_ticks = total_ticks
self._first = first
self._last = last
attr = console_attr.ConsoleAttr()
self._box = attr.GetBoxLineCharacters()
self._redraw = (self._box.d_dr != self._box.d_vr or
self._box.d_dl != self._box.d_vl)
max_label_width = self._total_ticks - 4
if len(label) > max_label_width:
label = label[:max_label_width - 3] + '...'
elif len(label) < max_label_width:
diff = max_label_width - len(label)
label += ' ' * diff
left = self._box.d_vr + self._box.d_h
right = self._box.d_h + self._box.d_vl
self._label = u'{left} {label} {right}'.format(left=left, label=label,
right=right)
def Start(self):
if self._first or self._redraw:
left = self._box.d_dr if self._first else self._box.d_vr
right = self._box.d_dl if self._first else self._box.d_vl
rule = u'{left}{middle}{right}\n'.format(
left=left, middle=self._box.d_h * self._total_ticks, right=right)
self._stream.write(rule)
self._stream.write(self._label + '\n')
self._stream.write(self._box.d_ur)
self._ticks_written = 0
def SetProgress(self, progress_factor):
expected_ticks = int(self._total_ticks * progress_factor)
new_ticks = expected_ticks - self._ticks_written
# Don't allow us to go over 100%.
new_ticks = min(new_ticks, self._total_ticks - self._ticks_written)
if new_ticks > 0:
self._stream.write(self._box.d_h * new_ticks)
self._ticks_written += new_ticks
if expected_ticks == self._total_ticks:
end = '\n' if self._last or not self._redraw else '\r'
self._stream.write(self._box.d_ul + end)
self._stream.flush()
def Finish(self):
self.SetProgress(1)
def __enter__(self):
self.Start()
return self
def __exit__(self, *args):
self.Finish()
def More(contents, out=None, prompt=None, check_pager=True):
if not IsInteractive(output=True):
if not out:
out = log.out
out.write(contents)
return
if not out:
log.file_only_logger.info(contents)
out = sys.stdout
if check_pager:
pager = os.environ.get('PAGER', None)
if pager == '-':
pager = None
elif not pager:
for command in ('less', 'pager'):
if files.FindExecutableOnPath(command):
pager = command
break
if pager:
less = os.environ.get('LESS', None)
if less is None:
os.environ['LESS'] = '-R'
p = subprocess.Popen(pager, stdin=subprocess.PIPE, shell=True)
encoding = console_attr.GetConsoleAttr().GetEncoding()
p.communicate(input=contents.encode(encoding))
p.wait()
if less is None:
os.environ.pop('LESS')
return
console_pager.Pager(contents, out, prompt).Run()
| true | true |
f72a16a88bd2e7f2a04565212dbdc6829381ba8b | 11,244 | py | Python | src/openfermion/utils/_grid.py | mpharrigan/OpenFermion | ae5bbaed60faa019fae9d47d6e578933874e074d | [
"Apache-2.0"
] | null | null | null | src/openfermion/utils/_grid.py | mpharrigan/OpenFermion | ae5bbaed60faa019fae9d47d6e578933874e074d | [
"Apache-2.0"
] | null | null | null | src/openfermion/utils/_grid.py | mpharrigan/OpenFermion | ae5bbaed60faa019fae9d47d6e578933874e074d | [
"Apache-2.0"
] | null | null | null | # 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 itertools
import numpy
import scipy
import scipy.linalg
# Exceptions.
class OrbitalSpecificationError(Exception):
pass
class Grid:
"""
A multi-dimension grid of points with an assigned length scale.
This grid acts as a helper class for parallelpiped super cells. It
tracks a mapping from indices to grid points and stores the associated
reciprocal lattice with respect to the original real-space lattice.
This enables calculations with non-trivial unit cells.
Attributes:
dimensions (int): Number of spatial dimensions the grid occupys
length (tuple of ints): d-length tuple specifying number of points
along each dimension.
shifts (list of ints): Integer shifts in position to center grid.
scale (ndarray): Vectors defining the super cell being simulated,
vectors are stored as columns in the matrix.
volume (float): Total volume of the supercell parallelpiped.
num_points (int): Total number of points in the grid.
reciprocal_scale (ndarray): Vectors defining the reciprocal lattice.
The vectors are stored as the columns in the matrix.
"""
def __init__(self, dimensions, length, scale):
"""
Args:
dimensions (int): The number of dimensions the grid lives in.
length (int or tuple): The number of points along each grid axis
that will be taken in both reciprocal and real space.
If tuple, it is read for each dimension, otherwise assumed
uniform.
scale (float or ndarray): The total length of each grid dimension.
If a float is passed, the uniform cubic unit cell is assumed.
For an ndarray, dimensions independent vectors of the correct
dimension must be passed. We assume column vectors define
the supercell vectors.
"""
if not isinstance(dimensions, int) or dimensions <= 0:
raise ValueError(
'dimensions must be a positive int but was {} {}'.format(
type(dimensions), repr(dimensions)))
if ((not isinstance(length, int) or length < 0) and
(not isinstance(length, tuple)) and
(not isinstance(length, list))):
raise ValueError(
'length must be a non-negative int or tuple '
'but was {} {}'.format(
type(length), repr(length)))
if ((not isinstance(scale, float) or not scale > 0) and
(not isinstance(scale, numpy.ndarray))):
raise ValueError(
'scale must be a positive float or ndarray but was '
'{} {}'.format(
type(scale), repr(scale)))
self.dimensions = dimensions
# If single integer, assume uniform
if isinstance(length, int):
self.length = (length, ) * dimensions
else:
self.length = length
self.shifts = [self.length[i] // 2 for i in range(dimensions)]
# If single float, construct cubic unit cell
if isinstance(scale, float):
self.scale = numpy.diag([scale] * self.dimensions)
else:
self.scale = scale
# Compute the volume of the super cell
self.volume = numpy.abs(scipy.linalg.det(self.scale))
# Compute total number of points
self.num_points = numpy.prod(self.length)
# Compute the reciprocal lattice basis
self.reciprocal_scale = 2 * numpy.pi * scipy.linalg.inv(self.scale).T
def volume_scale(self):
"""
Returns:
float: The volume of a length-scale hypercube within the grid.
"""
return self.volume
def all_points_indices(self):
"""
Returns:
iterable[tuple[int]]:
The index-coordinate tuple of each point in the grid.
"""
return itertools.product(*[range(self.length[i])
for i in range(self.dimensions)])
def position_vector(self, position_indices):
"""Given grid point coordinate, return position vector with dimensions.
Args:
position_indices (int|iterable[int]):
List or tuple of integers giving grid point coordinate.
Allowed values are ints in [0, grid_length).
Returns:
position_vector (numpy.ndarray[float])
"""
# Raise exceptions.
if isinstance(position_indices, int):
position_indices = [position_indices]
if not all(0 <= e < self.length[i]
for i, e in enumerate(position_indices)):
raise OrbitalSpecificationError(
'Position indices must be integers in [0, grid_length).')
# Compute position vector
vector = sum([(float(n - self.shifts[i]) /
self.length[i]) * self.scale[:, i]
for i, n in enumerate(position_indices)])
return vector
def momentum_vector(self, momentum_indices, periodic=True):
"""Given grid point coordinate, return momentum vector with dimensions.
Args:
momentum_indices (list): integers giving momentum
indices. Allowed values are ints in [0, grid_length).
periodic (bool): Wrap the momentum indices according to periodicity
Returns:
momentum_vector: A numpy array giving the momentum vector with
dimensions.
"""
# Raise exceptions.
if isinstance(momentum_indices, int):
momentum_indices = [momentum_indices]
if (not all(0 <= e < self.length[i]
for i, e in enumerate(momentum_indices))):
raise OrbitalSpecificationError(
'Momentum indices must be integers in [0, grid_length).')
# Compute momentum vector.
momentum_ints = self.index_to_momentum_ints(momentum_indices)
vector = self.momentum_ints_to_value(momentum_ints, periodic)
return vector
def index_to_momentum_ints(self, index):
"""
Args:
index (tuple): d-dimensional tuple specifying index in the grid
Returns:
Integer momentum vector
"""
# Set baseline for grid between [-N//2, N//2]
momentum_int = [index[i] - self.shifts[i]
for i in range(self.dimensions)]
return numpy.array(momentum_int, dtype=int)
def momentum_ints_to_index(self, momentum_ints):
"""
Args:
momentum_ints (tuple): d-dimensional tuple momentum integers
Returns:
d-dimensional tuples of indices
"""
indices = momentum_ints
# Shift to indices
indices = [n + self.shifts[i] for i, n in enumerate(indices)]
# Wrap dimensions
indices = [n % self.length[i] for i, n in enumerate(indices)]
return indices
def momentum_ints_to_value(self, momentum_ints, periodic=True):
"""
Args:
momentum_ints (tuple): d-dimensional tuple momentum integers
periodic (bool): Alias the momentum
Returns:
ndarray containing the momentum vector.
"""
# Alias the higher momentum modes
if periodic:
momentum_ints = self.index_to_momentum_ints(
self.momentum_ints_to_index(momentum_ints))
momentum_vector = sum([n * self.reciprocal_scale[:, i]
for i, n in enumerate(momentum_ints)])
return momentum_vector
def orbital_id(self, grid_coordinates, spin=None):
"""Return the tensor factor of a orbital with given coordinates and spin.
Args:
grid_coordinates: List or tuple of ints giving coordinates of grid
element. Acceptable to provide an int(instead of tuple or list)
for 1D case.
spin (bool): 0 means spin down and 1 means spin up.
If None, assume spinless model.
Returns:
tensor_factor (int):
tensor factor associated with provided orbital label.
"""
# Initialize.
if isinstance(grid_coordinates, int):
grid_coordinates = [grid_coordinates]
# Loop through dimensions of coordinate tuple.
tensor_factor = 0
for dimension, grid_coordinate in enumerate(grid_coordinates):
# Make sure coordinate is an integer in the correct bounds.
if (isinstance(grid_coordinate, int) and
grid_coordinate < self.length[dimension]):
tensor_factor += (grid_coordinate *
int(numpy.product(self.length[:dimension])))
else:
# Raise for invalid model.
raise OrbitalSpecificationError(
'Invalid orbital coordinates provided.')
# Account for spin and return.
if spin is None:
return tensor_factor
else:
tensor_factor *= 2
tensor_factor += spin
return tensor_factor
def grid_indices(self, qubit_id, spinless):
"""This function is the inverse of orbital_id.
Args:
qubit_id (int): The tensor factor to map to grid indices.
spinless (bool): Whether to use the spinless model or not.
Returns:
grid_indices (numpy.ndarray[int]):
The location of the qubit on the grid.
"""
if not (numpy.product(self.length) * (2 - spinless) > qubit_id >= 0):
raise OrbitalSpecificationError('Invalid qubit_id provided.')
# Remove spin degree of freedom if it exists.
orbital_id = qubit_id
if not spinless:
orbital_id //= 2
# Get grid indices.
grid_indices = []
for dimension in range(self.dimensions):
remainder = (orbital_id %
int(numpy.product(self.length[:dimension + 1])))
grid_index = (remainder //
int(numpy.product(self.length[:dimension])))
grid_indices += [grid_index]
return grid_indices
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return (self.dimensions == other.dimensions and
(self.scale == other.scale).all() and
self.length == other.length)
def __ne__(self, other):
return not self == other
| 37.605351 | 81 | 0.596852 |
import itertools
import numpy
import scipy
import scipy.linalg
class OrbitalSpecificationError(Exception):
pass
class Grid:
def __init__(self, dimensions, length, scale):
if not isinstance(dimensions, int) or dimensions <= 0:
raise ValueError(
'dimensions must be a positive int but was {} {}'.format(
type(dimensions), repr(dimensions)))
if ((not isinstance(length, int) or length < 0) and
(not isinstance(length, tuple)) and
(not isinstance(length, list))):
raise ValueError(
'length must be a non-negative int or tuple '
'but was {} {}'.format(
type(length), repr(length)))
if ((not isinstance(scale, float) or not scale > 0) and
(not isinstance(scale, numpy.ndarray))):
raise ValueError(
'scale must be a positive float or ndarray but was '
'{} {}'.format(
type(scale), repr(scale)))
self.dimensions = dimensions
if isinstance(length, int):
self.length = (length, ) * dimensions
else:
self.length = length
self.shifts = [self.length[i] // 2 for i in range(dimensions)]
if isinstance(scale, float):
self.scale = numpy.diag([scale] * self.dimensions)
else:
self.scale = scale
self.volume = numpy.abs(scipy.linalg.det(self.scale))
self.num_points = numpy.prod(self.length)
self.reciprocal_scale = 2 * numpy.pi * scipy.linalg.inv(self.scale).T
def volume_scale(self):
return self.volume
def all_points_indices(self):
return itertools.product(*[range(self.length[i])
for i in range(self.dimensions)])
def position_vector(self, position_indices):
if isinstance(position_indices, int):
position_indices = [position_indices]
if not all(0 <= e < self.length[i]
for i, e in enumerate(position_indices)):
raise OrbitalSpecificationError(
'Position indices must be integers in [0, grid_length).')
vector = sum([(float(n - self.shifts[i]) /
self.length[i]) * self.scale[:, i]
for i, n in enumerate(position_indices)])
return vector
def momentum_vector(self, momentum_indices, periodic=True):
if isinstance(momentum_indices, int):
momentum_indices = [momentum_indices]
if (not all(0 <= e < self.length[i]
for i, e in enumerate(momentum_indices))):
raise OrbitalSpecificationError(
'Momentum indices must be integers in [0, grid_length).')
momentum_ints = self.index_to_momentum_ints(momentum_indices)
vector = self.momentum_ints_to_value(momentum_ints, periodic)
return vector
def index_to_momentum_ints(self, index):
momentum_int = [index[i] - self.shifts[i]
for i in range(self.dimensions)]
return numpy.array(momentum_int, dtype=int)
def momentum_ints_to_index(self, momentum_ints):
indices = momentum_ints
indices = [n + self.shifts[i] for i, n in enumerate(indices)]
indices = [n % self.length[i] for i, n in enumerate(indices)]
return indices
def momentum_ints_to_value(self, momentum_ints, periodic=True):
if periodic:
momentum_ints = self.index_to_momentum_ints(
self.momentum_ints_to_index(momentum_ints))
momentum_vector = sum([n * self.reciprocal_scale[:, i]
for i, n in enumerate(momentum_ints)])
return momentum_vector
def orbital_id(self, grid_coordinates, spin=None):
if isinstance(grid_coordinates, int):
grid_coordinates = [grid_coordinates]
tensor_factor = 0
for dimension, grid_coordinate in enumerate(grid_coordinates):
if (isinstance(grid_coordinate, int) and
grid_coordinate < self.length[dimension]):
tensor_factor += (grid_coordinate *
int(numpy.product(self.length[:dimension])))
else:
raise OrbitalSpecificationError(
'Invalid orbital coordinates provided.')
if spin is None:
return tensor_factor
else:
tensor_factor *= 2
tensor_factor += spin
return tensor_factor
def grid_indices(self, qubit_id, spinless):
if not (numpy.product(self.length) * (2 - spinless) > qubit_id >= 0):
raise OrbitalSpecificationError('Invalid qubit_id provided.')
orbital_id = qubit_id
if not spinless:
orbital_id //= 2
grid_indices = []
for dimension in range(self.dimensions):
remainder = (orbital_id %
int(numpy.product(self.length[:dimension + 1])))
grid_index = (remainder //
int(numpy.product(self.length[:dimension])))
grid_indices += [grid_index]
return grid_indices
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return (self.dimensions == other.dimensions and
(self.scale == other.scale).all() and
self.length == other.length)
def __ne__(self, other):
return not self == other
| true | true |
f72a1840be2b7b6a8d90b8ea7f88260d3394c345 | 390 | py | Python | api/ver1/offices/strings.py | pcf26536/politico-api | 1c9b8755ddad2baf0bfdeab4aa0674e4197a0d7c | [
"MIT"
] | 1 | 2019-02-22T19:34:32.000Z | 2019-02-22T19:34:32.000Z | api/ver1/offices/strings.py | pcf26536/politico-api | 1c9b8755ddad2baf0bfdeab4aa0674e4197a0d7c | [
"MIT"
] | null | null | null | api/ver1/offices/strings.py | pcf26536/politico-api | 1c9b8755ddad2baf0bfdeab4aa0674e4197a0d7c | [
"MIT"
] | 1 | 2019-02-07T22:12:25.000Z | 2019-02-07T22:12:25.000Z | """ string constants for office module """
fed_type = 'federal'
leg_type = 'legislative'
state_type = 'state'
loc_gov_type = 'local government'
office_type_list = [fed_type, leg_type, state_type, loc_gov_type]
office_id_str = 'Office ID '
office_key = 'office'
prezzo = 'President'
mca = 'Member of County Assembly'
wr = 'Women Representative'
gov = 'Governer'
sen = 'Senator'
| 27.857143 | 66 | 0.715385 | fed_type = 'federal'
leg_type = 'legislative'
state_type = 'state'
loc_gov_type = 'local government'
office_type_list = [fed_type, leg_type, state_type, loc_gov_type]
office_id_str = 'Office ID '
office_key = 'office'
prezzo = 'President'
mca = 'Member of County Assembly'
wr = 'Women Representative'
gov = 'Governer'
sen = 'Senator'
| true | true |
f72a18619bff18684364dfb679729a22a85ad5ff | 2,217 | py | Python | tools/telemetry/telemetry/core/platform/android_device.py | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | tools/telemetry/telemetry/core/platform/android_device.py | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | tools/telemetry/telemetry/core/platform/android_device.py | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
from telemetry.core import util
from telemetry.core.backends import adb_commands
from telemetry.core.platform import device
from telemetry.core.platform.profiler import monsoon
class AndroidDevice(device.Device):
""" Class represents information for connecting to an android device.
Attributes:
device_id: the device's serial string created by adb to uniquely
identify an emulator/device instance. This string can be found by running
'adb devices' command
enable_performance_mode: when this is set to True, android platform will be
set to high performance mode after browser is started.
"""
def __init__(self, device_id, enable_performance_mode=False):
super(AndroidDevice, self).__init__(
name='Android device %s' % device_id, guid=device_id)
self._device_id = device_id
self._enable_performance_mode = enable_performance_mode
@classmethod
def GetAllConnectedDevices(cls):
device_serials = adb_commands.GetAttachedDevices()
# The monsoon provides power for the device, so for devices with no
# real battery, we need to turn them on after the monsoon enables voltage
# output to the device.
if not device_serials:
try:
m = monsoon.Monsoon(wait=False)
m.SetUsbPassthrough(1)
m.SetVoltage(3.8)
m.SetMaxCurrent(8)
logging.warn("""
Monsoon power monitor detected, but no Android devices.
The Monsoon's power output has been enabled. Please now ensure that:
1. The Monsoon's front and back USB are connected to the host.
2. The device is connected to the Monsoon's main and USB channels.
3. The device is turned on.
Waiting for device...
""")
util.WaitFor(adb_commands.GetAttachedDevices, 600)
device_serials = adb_commands.GetAttachedDevices()
except IOError:
return []
return [AndroidDevice(s) for s in device_serials]
@property
def device_id(self):
return self._device_id
@property
def enable_performance_mode(self):
return self._enable_performance_mode
| 34.640625 | 79 | 0.738385 |
import logging
from telemetry.core import util
from telemetry.core.backends import adb_commands
from telemetry.core.platform import device
from telemetry.core.platform.profiler import monsoon
class AndroidDevice(device.Device):
def __init__(self, device_id, enable_performance_mode=False):
super(AndroidDevice, self).__init__(
name='Android device %s' % device_id, guid=device_id)
self._device_id = device_id
self._enable_performance_mode = enable_performance_mode
@classmethod
def GetAllConnectedDevices(cls):
device_serials = adb_commands.GetAttachedDevices()
if not device_serials:
try:
m = monsoon.Monsoon(wait=False)
m.SetUsbPassthrough(1)
m.SetVoltage(3.8)
m.SetMaxCurrent(8)
logging.warn("""
Monsoon power monitor detected, but no Android devices.
The Monsoon's power output has been enabled. Please now ensure that:
1. The Monsoon's front and back USB are connected to the host.
2. The device is connected to the Monsoon's main and USB channels.
3. The device is turned on.
Waiting for device...
""")
util.WaitFor(adb_commands.GetAttachedDevices, 600)
device_serials = adb_commands.GetAttachedDevices()
except IOError:
return []
return [AndroidDevice(s) for s in device_serials]
@property
def device_id(self):
return self._device_id
@property
def enable_performance_mode(self):
return self._enable_performance_mode
| true | true |
f72a1afc1bd1464461d901edc69d6b82a2642d50 | 13,446 | py | Python | test/functional/decodescript.py | IDC-Group/VHKD | 0256ddf1477439ebc84e97132d3673aa61c39b73 | [
"MIT"
] | 3 | 2018-06-23T10:04:45.000Z | 2018-06-25T02:22:01.000Z | test/functional/decodescript.py | IDC-Group/VHKD | 0256ddf1477439ebc84e97132d3673aa61c39b73 | [
"MIT"
] | null | null | null | test/functional/decodescript.py | IDC-Group/VHKD | 0256ddf1477439ebc84e97132d3673aa61c39b73 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The vhkdCoin Core vhkd
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test decoding scripts via decodescript RPC command."""
from test_framework.test_framework import vhkdCoinTestFramework
from test_framework.util import *
from test_framework.mininode import *
from io import BytesIO
class DecodeScriptTest(vhkdCoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def decodescript_script_sig(self):
signature = '304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c509001'
push_signature = '48' + signature
public_key = '03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2'
push_public_key = '21' + public_key
# below are test cases for all of the standard transaction types
# 1) P2PK scriptSig
# the scriptSig of a public key scriptPubKey simply pushes a signature onto the stack
rpc_result = self.nodes[0].decodescript(push_signature)
assert_equal(signature, rpc_result['asm'])
# 2) P2PKH scriptSig
rpc_result = self.nodes[0].decodescript(push_signature + push_public_key)
assert_equal(signature + ' ' + public_key, rpc_result['asm'])
# 3) multisig scriptSig
# this also tests the leading portion of a P2SH multisig scriptSig
# OP_0 <A sig> <B sig>
rpc_result = self.nodes[0].decodescript('00' + push_signature + push_signature)
assert_equal('0 ' + signature + ' ' + signature, rpc_result['asm'])
# 4) P2SH scriptSig
# an empty P2SH redeemScript is valid and makes for a very simple test case.
# thus, such a spending scriptSig would just need to pass the outer redeemScript
# hash test and leave true on the top of the stack.
rpc_result = self.nodes[0].decodescript('5100')
assert_equal('1 0', rpc_result['asm'])
# 5) null data scriptSig - no such thing because null data scripts can not be spent.
# thus, no test case for that standard transaction type is here.
def decodescript_script_pub_key(self):
public_key = '03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2'
push_public_key = '21' + public_key
public_key_hash = '11695b6cd891484c2d49ec5aa738ec2b2f897777'
push_public_key_hash = '14' + public_key_hash
# below are test cases for all of the standard transaction types
# 1) P2PK scriptPubKey
# <pubkey> OP_CHECKSIG
rpc_result = self.nodes[0].decodescript(push_public_key + 'ac')
assert_equal(public_key + ' OP_CHECKSIG', rpc_result['asm'])
# 2) P2PKH scriptPubKey
# OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
rpc_result = self.nodes[0].decodescript('76a9' + push_public_key_hash + '88ac')
assert_equal('OP_DUP OP_HASH160 ' + public_key_hash + ' OP_EQUALVERIFY OP_CHECKSIG', rpc_result['asm'])
# 3) multisig scriptPubKey
# <m> <A pubkey> <B pubkey> <C pubkey> <n> OP_CHECKMULTISIG
# just imagine that the pub keys used below are different.
# for our purposes here it does not matter that they are the same even though it is unrealistic.
rpc_result = self.nodes[0].decodescript('52' + push_public_key + push_public_key + push_public_key + '53ae')
assert_equal('2 ' + public_key + ' ' + public_key + ' ' + public_key + ' 3 OP_CHECKMULTISIG', rpc_result['asm'])
# 4) P2SH scriptPubKey
# OP_HASH160 <Hash160(redeemScript)> OP_EQUAL.
# push_public_key_hash here should actually be the hash of a redeem script.
# but this works the same for purposes of this test.
rpc_result = self.nodes[0].decodescript('a9' + push_public_key_hash + '87')
assert_equal('OP_HASH160 ' + public_key_hash + ' OP_EQUAL', rpc_result['asm'])
# 5) null data scriptPubKey
# use a signature look-alike here to make sure that we do not decode random data as a signature.
# this matters if/when signature sighash decoding comes along.
# would want to make sure that no such decoding takes place in this case.
signature_imposter = '48304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c509001'
# OP_RETURN <data>
rpc_result = self.nodes[0].decodescript('6a' + signature_imposter)
assert_equal('OP_RETURN ' + signature_imposter[2:], rpc_result['asm'])
# 6) a CLTV redeem script. redeem scripts are in-effect scriptPubKey scripts, so adding a test here.
# OP_NOP2 is also known as OP_CHECKLOCKTIMEVERIFY.
# just imagine that the pub keys used below are different.
# for our purposes here it does not matter that they are the same even though it is unrealistic.
#
# OP_IF
# <receiver-pubkey> OP_CHECKSIGVERIFY
# OP_ELSE
# <lock-until> OP_CHECKLOCKTIMEVERIFY OP_DROP
# OP_ENDIF
# <sender-pubkey> OP_CHECKSIG
#
# lock until block 500,000
rpc_result = self.nodes[0].decodescript('63' + push_public_key + 'ad670320a107b17568' + push_public_key + 'ac')
assert_equal('OP_IF ' + public_key + ' OP_CHECKSIGVERIFY OP_ELSE 500000 OP_CHECKLOCKTIMEVERIFY OP_DROP OP_ENDIF ' + public_key + ' OP_CHECKSIG', rpc_result['asm'])
def decoderawtransaction_asm_sighashtype(self):
"""Test decoding scripts via RPC command "decoderawtransaction".
This test is in with the "decodescript" tests because they are testing the same "asm" script decodes.
"""
# this test case uses a random plain vanilla mainnet transaction with a single P2PKH input and output
tx = '0100000001696a20784a2c70143f634e95227dbdfdf0ecd51647052e70854512235f5986ca010000008a47304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb014104d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536ffffffff0100e1f505000000001976a914eb6c6e0cdb2d256a32d97b8df1fc75d1920d9bca88ac00000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb[ALL] 04d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536', rpc_result['vin'][0]['scriptSig']['asm'])
# this test case uses a mainnet transaction that has a P2SH input and both P2PKH and P2SH outputs.
# it's from James D'Angelo's awesome introductory videos about multisig: https://www.youtube.com/watch?v=zIbUSaZBJgU and https://www.youtube.com/watch?v=OSA1pwlaypc
# verify that we have not altered scriptPubKey decoding.
tx = '01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914dc863734a218bfe83ef770ee9d41a27f824a6e5688acee2a02000000000017a9142a5edea39971049a540474c6a99edf0aa4074c588700000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('8e3730608c3b0bb5df54f09076e196bc292a8e39a78e73b44b6ba08c78f5cbb0', rpc_result['txid'])
assert_equal('0 3045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea[ALL] 3045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75[ALL] 5221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53ae', rpc_result['vin'][0]['scriptSig']['asm'])
assert_equal('OP_DUP OP_HASH160 dc863734a218bfe83ef770ee9d41a27f824a6e56 OP_EQUALVERIFY OP_CHECKSIG', rpc_result['vout'][0]['scriptPubKey']['asm'])
assert_equal('OP_HASH160 2a5edea39971049a540474c6a99edf0aa4074c58 OP_EQUAL', rpc_result['vout'][1]['scriptPubKey']['asm'])
txSave = CTransaction()
txSave.deserialize(BytesIO(hex_str_to_bytes(tx)))
# make sure that a specifically crafted op_return value will not pass all the IsDERSignature checks and then get decoded as a sighash type
tx = '01000000015ded05872fdbda629c7d3d02b194763ce3b9b1535ea884e3c8e765d42e316724020000006b48304502204c10d4064885c42638cbff3585915b322de33762598321145ba033fc796971e2022100bb153ad3baa8b757e30a2175bd32852d2e1cb9080f84d7e32fcdfd667934ef1b012103163c0ff73511ea1743fb5b98384a2ff09dd06949488028fd819f4d83f56264efffffffff0200000000000000000b6a0930060201000201000180380100000000001976a9141cabd296e753837c086da7a45a6c2fe0d49d7b7b88ac00000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('OP_RETURN 300602010002010001', rpc_result['vout'][0]['scriptPubKey']['asm'])
# verify that we have not altered scriptPubKey processing even of a specially crafted P2PKH pubkeyhash and P2SH redeem script hash that is made to pass the der signature checks
tx = '01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914301102070101010101010102060101010101010188acee2a02000000000017a91430110207010101010101010206010101010101018700000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('OP_DUP OP_HASH160 3011020701010101010101020601010101010101 OP_EQUALVERIFY OP_CHECKSIG', rpc_result['vout'][0]['scriptPubKey']['asm'])
assert_equal('OP_HASH160 3011020701010101010101020601010101010101 OP_EQUAL', rpc_result['vout'][1]['scriptPubKey']['asm'])
# some more full transaction tests of varying specific scriptSigs. used instead of
# tests in decodescript_script_sig because the decodescript RPC is specifically
# for working on scriptPubKeys (argh!).
push_signature = bytes_to_hex_str(txSave.vin[0].scriptSig)[2:(0x48*2+4)]
signature = push_signature[2:]
der_signature = signature[:-2]
signature_sighash_decoded = der_signature + '[ALL]'
signature_2 = der_signature + '82'
push_signature_2 = '48' + signature_2
signature_2_sighash_decoded = der_signature + '[NONE|ANYONECANPAY]'
# 1) P2PK scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal(signature_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# make sure that the sighash decodes come out correctly for a more complex / lesser used case.
txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature_2)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal(signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# 2) multisig scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes('00' + push_signature + push_signature_2)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal('0 ' + signature_sighash_decoded + ' ' + signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# 3) test a scriptSig that contains more than push operations.
# in fact, it contains an OP_RETURN with data specially crafted to cause improper decode if the code does not catch it.
txSave.vin[0].scriptSig = hex_str_to_bytes('6a143011020701010101010101020601010101010101')
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal('OP_RETURN 3011020701010101010101020601010101010101', rpc_result['vin'][0]['scriptSig']['asm'])
def run_test(self):
self.decodescript_script_sig()
self.decodescript_script_pub_key()
self.decoderawtransaction_asm_sighashtype()
if __name__ == '__main__':
DecodeScriptTest().main()
| 74.7 | 761 | 0.7751 |
from test_framework.test_framework import vhkdCoinTestFramework
from test_framework.util import *
from test_framework.mininode import *
from io import BytesIO
class DecodeScriptTest(vhkdCoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def decodescript_script_sig(self):
signature = '304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c509001'
push_signature = '48' + signature
public_key = '03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2'
push_public_key = '21' + public_key
rpc_result = self.nodes[0].decodescript(push_signature)
assert_equal(signature, rpc_result['asm'])
rpc_result = self.nodes[0].decodescript(push_signature + push_public_key)
assert_equal(signature + ' ' + public_key, rpc_result['asm'])
rpc_result = self.nodes[0].decodescript('00' + push_signature + push_signature)
assert_equal('0 ' + signature + ' ' + signature, rpc_result['asm'])
rpc_result = self.nodes[0].decodescript('5100')
assert_equal('1 0', rpc_result['asm'])
def decodescript_script_pub_key(self):
public_key = '03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2'
push_public_key = '21' + public_key
public_key_hash = '11695b6cd891484c2d49ec5aa738ec2b2f897777'
push_public_key_hash = '14' + public_key_hash
rpc_result = self.nodes[0].decodescript(push_public_key + 'ac')
assert_equal(public_key + ' OP_CHECKSIG', rpc_result['asm'])
rpc_result = self.nodes[0].decodescript('76a9' + push_public_key_hash + '88ac')
assert_equal('OP_DUP OP_HASH160 ' + public_key_hash + ' OP_EQUALVERIFY OP_CHECKSIG', rpc_result['asm'])
rpc_result = self.nodes[0].decodescript('52' + push_public_key + push_public_key + push_public_key + '53ae')
assert_equal('2 ' + public_key + ' ' + public_key + ' ' + public_key + ' 3 OP_CHECKMULTISIG', rpc_result['asm'])
rpc_result = self.nodes[0].decodescript('a9' + push_public_key_hash + '87')
assert_equal('OP_HASH160 ' + public_key_hash + ' OP_EQUAL', rpc_result['asm'])
signature_imposter = '48304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c509001'
rpc_result = self.nodes[0].decodescript('6a' + signature_imposter)
assert_equal('OP_RETURN ' + signature_imposter[2:], rpc_result['asm'])
rpc_result = self.nodes[0].decodescript('63' + push_public_key + 'ad670320a107b17568' + push_public_key + 'ac')
assert_equal('OP_IF ' + public_key + ' OP_CHECKSIGVERIFY OP_ELSE 500000 OP_CHECKLOCKTIMEVERIFY OP_DROP OP_ENDIF ' + public_key + ' OP_CHECKSIG', rpc_result['asm'])
def decoderawtransaction_asm_sighashtype(self):
tx = '0100000001696a20784a2c70143f634e95227dbdfdf0ecd51647052e70854512235f5986ca010000008a47304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb014104d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536ffffffff0100e1f505000000001976a914eb6c6e0cdb2d256a32d97b8df1fc75d1920d9bca88ac00000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb[ALL] 04d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536', rpc_result['vin'][0]['scriptSig']['asm'])
# verify that we have not altered scriptPubKey decoding.
tx = '01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914dc863734a218bfe83ef770ee9d41a27f824a6e5688acee2a02000000000017a9142a5edea39971049a540474c6a99edf0aa4074c588700000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('8e3730608c3b0bb5df54f09076e196bc292a8e39a78e73b44b6ba08c78f5cbb0', rpc_result['txid'])
assert_equal('0 3045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea[ALL] 3045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75[ALL] 5221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53ae', rpc_result['vin'][0]['scriptSig']['asm'])
assert_equal('OP_DUP OP_HASH160 dc863734a218bfe83ef770ee9d41a27f824a6e56 OP_EQUALVERIFY OP_CHECKSIG', rpc_result['vout'][0]['scriptPubKey']['asm'])
assert_equal('OP_HASH160 2a5edea39971049a540474c6a99edf0aa4074c58 OP_EQUAL', rpc_result['vout'][1]['scriptPubKey']['asm'])
txSave = CTransaction()
txSave.deserialize(BytesIO(hex_str_to_bytes(tx)))
# make sure that a specifically crafted op_return value will not pass all the IsDERSignature checks and then get decoded as a sighash type
tx = '01000000015ded05872fdbda629c7d3d02b194763ce3b9b1535ea884e3c8e765d42e316724020000006b48304502204c10d4064885c42638cbff3585915b322de33762598321145ba033fc796971e2022100bb153ad3baa8b757e30a2175bd32852d2e1cb9080f84d7e32fcdfd667934ef1b012103163c0ff73511ea1743fb5b98384a2ff09dd06949488028fd819f4d83f56264efffffffff0200000000000000000b6a0930060201000201000180380100000000001976a9141cabd296e753837c086da7a45a6c2fe0d49d7b7b88ac00000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('OP_RETURN 300602010002010001', rpc_result['vout'][0]['scriptPubKey']['asm'])
# verify that we have not altered scriptPubKey processing even of a specially crafted P2PKH pubkeyhash and P2SH redeem script hash that is made to pass the der signature checks
tx = '01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914301102070101010101010102060101010101010188acee2a02000000000017a91430110207010101010101010206010101010101018700000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('OP_DUP OP_HASH160 3011020701010101010101020601010101010101 OP_EQUALVERIFY OP_CHECKSIG', rpc_result['vout'][0]['scriptPubKey']['asm'])
assert_equal('OP_HASH160 3011020701010101010101020601010101010101 OP_EQUAL', rpc_result['vout'][1]['scriptPubKey']['asm'])
# some more full transaction tests of varying specific scriptSigs. used instead of
# tests in decodescript_script_sig because the decodescript RPC is specifically
# for working on scriptPubKeys (argh!).
push_signature = bytes_to_hex_str(txSave.vin[0].scriptSig)[2:(0x48*2+4)]
signature = push_signature[2:]
der_signature = signature[:-2]
signature_sighash_decoded = der_signature + '[ALL]'
signature_2 = der_signature + '82'
push_signature_2 = '48' + signature_2
signature_2_sighash_decoded = der_signature + '[NONE|ANYONECANPAY]'
# 1) P2PK scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal(signature_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# make sure that the sighash decodes come out correctly for a more complex / lesser used case.
txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature_2)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal(signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# 2) multisig scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes('00' + push_signature + push_signature_2)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal('0 ' + signature_sighash_decoded + ' ' + signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# 3) test a scriptSig that contains more than push operations.
# in fact, it contains an OP_RETURN with data specially crafted to cause improper decode if the code does not catch it.
txSave.vin[0].scriptSig = hex_str_to_bytes('6a143011020701010101010101020601010101010101')
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal('OP_RETURN 3011020701010101010101020601010101010101', rpc_result['vin'][0]['scriptSig']['asm'])
def run_test(self):
self.decodescript_script_sig()
self.decodescript_script_pub_key()
self.decoderawtransaction_asm_sighashtype()
if __name__ == '__main__':
DecodeScriptTest().main()
| true | true |
f72a1b89963a4a3a6d1bf9e9c6daa16de82b1501 | 177 | py | Python | seglossbias/data/__init__.py | by-liu/SegLossBia | 9cc639c04084cda9d5fb20ea34699db7e0beaf5c | [
"MIT"
] | 18 | 2021-04-20T17:03:20.000Z | 2022-03-12T05:56:24.000Z | seglossbias/data/__init__.py | by-liu/SegLossBia | 9cc639c04084cda9d5fb20ea34699db7e0beaf5c | [
"MIT"
] | null | null | null | seglossbias/data/__init__.py | by-liu/SegLossBia | 9cc639c04084cda9d5fb20ea34699db7e0beaf5c | [
"MIT"
] | 1 | 2021-07-08T17:44:15.000Z | 2021-07-08T17:44:15.000Z | from .retinal_lesion_dataset import RetinalLesionsDataset
from .cityscapes import CityscapesDataset
from .image_folder import ImageFolder
from .build import build_data_pipeline
| 35.4 | 57 | 0.887006 | from .retinal_lesion_dataset import RetinalLesionsDataset
from .cityscapes import CityscapesDataset
from .image_folder import ImageFolder
from .build import build_data_pipeline
| true | true |
f72a1bdff1a726f89b33188978307242dbacf3ef | 8,753 | py | Python | var/spack/repos/builtin/packages/ferret/package.py | kkauder/spack | 6ae8d5c380c1f42094b05d38be26b03650aafb39 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2 | 2019-02-10T13:47:48.000Z | 2019-04-17T13:05:17.000Z | var/spack/repos/builtin/packages/ferret/package.py | kkauder/spack | 6ae8d5c380c1f42094b05d38be26b03650aafb39 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 17 | 2019-03-21T15:54:00.000Z | 2022-03-29T19:34:28.000Z | var/spack/repos/builtin/packages/ferret/package.py | kkauder/spack | 6ae8d5c380c1f42094b05d38be26b03650aafb39 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2 | 2021-04-07T18:27:09.000Z | 2022-03-31T22:52:38.000Z | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import os
class Ferret(Package):
"""Ferret is an interactive computer visualization and analysis environment
designed to meet the needs of oceanographers and meteorologists
analyzing large and complex gridded data sets."""
homepage = "http://ferret.pmel.noaa.gov/Ferret/home"
url = "https://github.com/NOAA-PMEL/Ferret/archive/v7.6.0.tar.gz"
maintainers = ['RemiLacroix-IDRIS']
version('7.6.0', sha256='69832d740bd44c9eadd198a5de4d96c4c01ae90ae28c2c3414c1bb9f43e475d1')
version('7.5.0', sha256='2a038c547e6e80e6bd0645a374c3247360cf8c94ea56f6f3444b533257eb16db')
version('7.4', sha256='5167bb9e6ef441ae9cf90da555203d2155e3fcf929e7b8dddb237de0d58c5e5f')
version('7.3', sha256='ae80a732c34156b5287a23696cf4ae4faf4de1dd705ff43cbb4168b05c6faaf4')
version('7.2', sha256='21c339b1bafa6939fc869428d906451f130f7e77e828c532ab9488d51cf43095')
version('6.96', sha256='7eb87156aa586cfe838ab83f08b2102598f9ab62062d540a5da8c9123816331a')
variant('datasets', default=False, description="Install Ferret standard datasets")
depends_on("hdf5+hl")
depends_on("netcdf-c")
depends_on("netcdf-fortran")
depends_on("readline")
depends_on("zlib")
depends_on("libx11")
depends_on("curl")
# Make Java dependency optional with older versions of Ferret
patch('https://github.com/NOAA-PMEL/Ferret/commit/c7eb70a0b17045c8ca7207d586bfea77a5340668.patch',
sha256='5bd581db4578c013faed375844b206fbe71f93fe9ce60f8f9f41d64abc6a5972',
level=1, working_dir='FERRET', when='@:6.99')
resource(name='datasets',
url='https://github.com/NOAA-PMEL/FerretDatasets/archive/v7.6.tar.gz',
sha256='b2fef758ec1817c1c19e6225857ca3a82c727d209ed7fd4697d45c5533bb2c72',
placement='fer_dsets', when='+datasets')
def url_for_version(self, version):
if version <= Version('7.2'):
return 'ftp://ftp.pmel.noaa.gov/ferret/pub/source/fer_source.v{0}.tar.gz'.format(
version.joined)
else:
return 'https://github.com/NOAA-PMEL/Ferret/archive/v{0}.tar.gz'.format(version)
def patch(self):
spec = self.spec
hdf5_prefix = spec['hdf5'].prefix
netcdff_prefix = spec['netcdf-fortran'].prefix
readline_prefix = spec['readline'].prefix
libz_prefix = spec['zlib'].prefix
work_dir = 'FERRET' if '@:7.2' in spec else '.'
with working_dir(work_dir, create=False):
if '@7.3:' in spec:
copy('site_specific.mk.in', 'site_specific.mk')
copy('external_functions/ef_utility/site_specific.mk.in',
'external_functions/ef_utility/site_specific.mk')
filter_file(r'^DIR_PREFIX.+',
'DIR_PREFIX = %s' % self.stage.source_path,
'site_specific.mk')
# Setting this to blank not to force
# using the static version of readline
filter_file(r'^(READLINE_(LIB)?DIR).+',
'\\1 = ',
'site_specific.mk')
else:
filter_file(r'^LIBZ_DIR.+',
'LIBZ_DIR = %s' % libz_prefix,
'site_specific.mk')
filter_file(r'^JAVA_HOME.+',
' ',
'site_specific.mk')
filter_file(r'^READLINE_DIR.+',
'READLINE_DIR = %s' % readline_prefix,
'site_specific.mk')
filter_file(r'^BUILDTYPE.+',
'BUILDTYPE = x86_64-linux',
'site_specific.mk')
filter_file(r'^INSTALL_FER_DIR.+',
'INSTALL_FER_DIR = %s' % spec.prefix,
'site_specific.mk')
filter_file(r'^(HDF5_(LIB)?DIR).+',
'\\1 = %s' % hdf5_prefix,
'site_specific.mk')
filter_file(r'^(NETCDF4?_(LIB)?DIR).+',
'\\1 = %s' % netcdff_prefix,
'site_specific.mk')
if '@:7.3' in spec:
# Don't force using the static version of libz
filter_file(r'\$\(LIBZ_DIR\)/lib64/libz.a',
'-lz',
'platform_specific.mk.x86_64-linux')
# Don't force using the static version of libgfortran
filter_file(r'-Wl,-Bstatic -lgfortran -Wl,-Bdynamic',
'-lgfortran',
'platform_specific.mk.x86_64-linux')
# This prevents the rpaths to be properly set
# by Spack's compiler wrappers
filter_file(r'-v --verbose',
'',
'platform_specific.mk.x86_64-linux')
filter_file(r'^[ \t]*LD[ \t]*=.+',
'LD = %s' % spack_cc,
'platform_specific.mk.x86_64-linux')
else:
# Don't force using the static version of libgfortran
filter_file(r'-static-libgfortran',
'',
'platform_specific.mk.x86_64-linux')
if '@:7.4' in spec:
compilers_spec_file = 'platform_specific.mk.x86_64-linux'
else:
compilers_spec_file = 'site_specific.mk'
# Make sure Ferret uses Spack's compiler wrappers
filter_file(r'^[ \t]*CC[ \t]*=.+',
'CC = %s' % spack_cc,
compilers_spec_file)
filter_file(r'^[ \t]*CXX[ \t]*=.+',
'CXX = %s' % spack_cxx,
compilers_spec_file)
filter_file(r'^[ \t]*FC[ \t]*=.+',
'FC = %s' % spack_fc,
compilers_spec_file)
filter_file(r'^[ \t]*F77[ \t]*=.+',
'F77 = %s' % spack_f77,
compilers_spec_file)
filter_file(r'\$\(NETCDF4?_(LIB)?DIR\).*/libnetcdff.a',
"-L%s -lnetcdff" % spec['netcdf-fortran'].prefix.lib,
'platform_specific.mk.x86_64-linux')
filter_file(r'\$\(NETCDF4?_(LIB)?DIR\).*/libnetcdf.a',
"-L%s -lnetcdf" % spec['netcdf-c'].prefix.lib,
'platform_specific.mk.x86_64-linux')
filter_file(r'\$\(HDF5_(LIB)?DIR\).*/libhdf5_hl.a',
"-L%s -lhdf5_hl" % spec['hdf5'].prefix.lib,
'platform_specific.mk.x86_64-linux')
filter_file(r'\$\(HDF5_(LIB)?DIR\).*/libhdf5.a',
"-L%s -lhdf5" % spec['hdf5'].prefix.lib,
'platform_specific.mk.x86_64-linux')
def install(self, spec, prefix):
if 'LDFLAGS' in env and env['LDFLAGS']:
env['LDFLAGS'] += ' ' + '-lquadmath'
else:
env['LDFLAGS'] = '-lquadmath'
work_dir = 'FERRET' if '@:7.2' in self.spec else '.'
with working_dir(work_dir, create=False):
os.environ['LD_X11'] = '-L%s -lX11' % spec['libx11'].prefix.lib
os.environ['HOSTTYPE'] = 'x86_64-linux'
make(parallel=False)
make("install")
if '+datasets' in self.spec:
mkdir(self.prefix.fer_dsets)
install_tree('fer_dsets', self.prefix.fer_dsets)
def setup_run_environment(self, env):
env.set('FER_DIR', self.prefix)
env.set('FER_GO', ' '.join(['.', self.prefix.go, self.prefix.examples,
self.prefix.contrib]))
env.set('FER_EXTERNAL_FUNCTIONS', self.prefix.ext_func.libs)
env.set('FER_PALETTE', ' '.join(['.', self.prefix.ppl]))
env.set('FER_FONTS', self.prefix.ppl.fonts)
fer_data = ['.']
fer_descr = ['.']
fer_grids = ['.']
if '+datasets' in self.spec:
env.set('FER_DSETS', self.prefix.fer_dsets)
fer_data.append(self.prefix.fer_dsets.data)
fer_descr.append(self.prefix.fer_dsets.descr)
fer_grids.append(self.prefix.fer_dsets.grids)
fer_data.extend([self.prefix.go, self.prefix.examples])
env.set('FER_DATA', ' '.join(fer_data))
env.set('FER_DESCR', ' '.join(fer_descr))
env.set('FER_GRIDS', ' '.join(fer_grids))
| 44.207071 | 102 | 0.540272 |
from spack import *
import os
class Ferret(Package):
homepage = "http://ferret.pmel.noaa.gov/Ferret/home"
url = "https://github.com/NOAA-PMEL/Ferret/archive/v7.6.0.tar.gz"
maintainers = ['RemiLacroix-IDRIS']
version('7.6.0', sha256='69832d740bd44c9eadd198a5de4d96c4c01ae90ae28c2c3414c1bb9f43e475d1')
version('7.5.0', sha256='2a038c547e6e80e6bd0645a374c3247360cf8c94ea56f6f3444b533257eb16db')
version('7.4', sha256='5167bb9e6ef441ae9cf90da555203d2155e3fcf929e7b8dddb237de0d58c5e5f')
version('7.3', sha256='ae80a732c34156b5287a23696cf4ae4faf4de1dd705ff43cbb4168b05c6faaf4')
version('7.2', sha256='21c339b1bafa6939fc869428d906451f130f7e77e828c532ab9488d51cf43095')
version('6.96', sha256='7eb87156aa586cfe838ab83f08b2102598f9ab62062d540a5da8c9123816331a')
variant('datasets', default=False, description="Install Ferret standard datasets")
depends_on("hdf5+hl")
depends_on("netcdf-c")
depends_on("netcdf-fortran")
depends_on("readline")
depends_on("zlib")
depends_on("libx11")
depends_on("curl")
patch('https://github.com/NOAA-PMEL/Ferret/commit/c7eb70a0b17045c8ca7207d586bfea77a5340668.patch',
sha256='5bd581db4578c013faed375844b206fbe71f93fe9ce60f8f9f41d64abc6a5972',
level=1, working_dir='FERRET', when='@:6.99')
resource(name='datasets',
url='https://github.com/NOAA-PMEL/FerretDatasets/archive/v7.6.tar.gz',
sha256='b2fef758ec1817c1c19e6225857ca3a82c727d209ed7fd4697d45c5533bb2c72',
placement='fer_dsets', when='+datasets')
def url_for_version(self, version):
if version <= Version('7.2'):
return 'ftp://ftp.pmel.noaa.gov/ferret/pub/source/fer_source.v{0}.tar.gz'.format(
version.joined)
else:
return 'https://github.com/NOAA-PMEL/Ferret/archive/v{0}.tar.gz'.format(version)
def patch(self):
spec = self.spec
hdf5_prefix = spec['hdf5'].prefix
netcdff_prefix = spec['netcdf-fortran'].prefix
readline_prefix = spec['readline'].prefix
libz_prefix = spec['zlib'].prefix
work_dir = 'FERRET' if '@:7.2' in spec else '.'
with working_dir(work_dir, create=False):
if '@7.3:' in spec:
copy('site_specific.mk.in', 'site_specific.mk')
copy('external_functions/ef_utility/site_specific.mk.in',
'external_functions/ef_utility/site_specific.mk')
filter_file(r'^DIR_PREFIX.+',
'DIR_PREFIX = %s' % self.stage.source_path,
'site_specific.mk')
filter_file(r'^(READLINE_(LIB)?DIR).+',
'\\1 = ',
'site_specific.mk')
else:
filter_file(r'^LIBZ_DIR.+',
'LIBZ_DIR = %s' % libz_prefix,
'site_specific.mk')
filter_file(r'^JAVA_HOME.+',
' ',
'site_specific.mk')
filter_file(r'^READLINE_DIR.+',
'READLINE_DIR = %s' % readline_prefix,
'site_specific.mk')
filter_file(r'^BUILDTYPE.+',
'BUILDTYPE = x86_64-linux',
'site_specific.mk')
filter_file(r'^INSTALL_FER_DIR.+',
'INSTALL_FER_DIR = %s' % spec.prefix,
'site_specific.mk')
filter_file(r'^(HDF5_(LIB)?DIR).+',
'\\1 = %s' % hdf5_prefix,
'site_specific.mk')
filter_file(r'^(NETCDF4?_(LIB)?DIR).+',
'\\1 = %s' % netcdff_prefix,
'site_specific.mk')
if '@:7.3' in spec:
filter_file(r'\$\(LIBZ_DIR\)/lib64/libz.a',
'-lz',
'platform_specific.mk.x86_64-linux')
# Don't force using the static version of libgfortran
filter_file(r'-Wl,-Bstatic -lgfortran -Wl,-Bdynamic',
'-lgfortran',
'platform_specific.mk.x86_64-linux')
filter_file(r'-v --verbose',
'',
'platform_specific.mk.x86_64-linux')
filter_file(r'^[ \t]*LD[ \t]*=.+',
'LD = %s' % spack_cc,
'platform_specific.mk.x86_64-linux')
else:
# Don't force using the static version of libgfortran
filter_file(r'-static-libgfortran',
'',
'platform_specific.mk.x86_64-linux')
if '@:7.4' in spec:
compilers_spec_file = 'platform_specific.mk.x86_64-linux'
else:
compilers_spec_file = 'site_specific.mk'
filter_file(r'^[ \t]*CC[ \t]*=.+',
'CC = %s' % spack_cc,
compilers_spec_file)
filter_file(r'^[ \t]*CXX[ \t]*=.+',
'CXX = %s' % spack_cxx,
compilers_spec_file)
filter_file(r'^[ \t]*FC[ \t]*=.+',
'FC = %s' % spack_fc,
compilers_spec_file)
filter_file(r'^[ \t]*F77[ \t]*=.+',
'F77 = %s' % spack_f77,
compilers_spec_file)
filter_file(r'\$\(NETCDF4?_(LIB)?DIR\).*/libnetcdff.a',
"-L%s -lnetcdff" % spec['netcdf-fortran'].prefix.lib,
'platform_specific.mk.x86_64-linux')
filter_file(r'\$\(NETCDF4?_(LIB)?DIR\).*/libnetcdf.a',
"-L%s -lnetcdf" % spec['netcdf-c'].prefix.lib,
'platform_specific.mk.x86_64-linux')
filter_file(r'\$\(HDF5_(LIB)?DIR\).*/libhdf5_hl.a',
"-L%s -lhdf5_hl" % spec['hdf5'].prefix.lib,
'platform_specific.mk.x86_64-linux')
filter_file(r'\$\(HDF5_(LIB)?DIR\).*/libhdf5.a',
"-L%s -lhdf5" % spec['hdf5'].prefix.lib,
'platform_specific.mk.x86_64-linux')
def install(self, spec, prefix):
if 'LDFLAGS' in env and env['LDFLAGS']:
env['LDFLAGS'] += ' ' + '-lquadmath'
else:
env['LDFLAGS'] = '-lquadmath'
work_dir = 'FERRET' if '@:7.2' in self.spec else '.'
with working_dir(work_dir, create=False):
os.environ['LD_X11'] = '-L%s -lX11' % spec['libx11'].prefix.lib
os.environ['HOSTTYPE'] = 'x86_64-linux'
make(parallel=False)
make("install")
if '+datasets' in self.spec:
mkdir(self.prefix.fer_dsets)
install_tree('fer_dsets', self.prefix.fer_dsets)
def setup_run_environment(self, env):
env.set('FER_DIR', self.prefix)
env.set('FER_GO', ' '.join(['.', self.prefix.go, self.prefix.examples,
self.prefix.contrib]))
env.set('FER_EXTERNAL_FUNCTIONS', self.prefix.ext_func.libs)
env.set('FER_PALETTE', ' '.join(['.', self.prefix.ppl]))
env.set('FER_FONTS', self.prefix.ppl.fonts)
fer_data = ['.']
fer_descr = ['.']
fer_grids = ['.']
if '+datasets' in self.spec:
env.set('FER_DSETS', self.prefix.fer_dsets)
fer_data.append(self.prefix.fer_dsets.data)
fer_descr.append(self.prefix.fer_dsets.descr)
fer_grids.append(self.prefix.fer_dsets.grids)
fer_data.extend([self.prefix.go, self.prefix.examples])
env.set('FER_DATA', ' '.join(fer_data))
env.set('FER_DESCR', ' '.join(fer_descr))
env.set('FER_GRIDS', ' '.join(fer_grids))
| true | true |
f72a1d7dd4c80ce0ed01d5ce8dc4f4809a465124 | 212 | py | Python | Webscraping_and_Automation/web-automation.py | Ruban2205/Python-Projects | 6c0444784b3be1356d43c70ca544e01e97158d0a | [
"MIT"
] | 1 | 2022-01-17T06:52:29.000Z | 2022-01-17T06:52:29.000Z | Webscraping_and_Automation/web-automation.py | Ruban2205/Python-Projects | 6c0444784b3be1356d43c70ca544e01e97158d0a | [
"MIT"
] | null | null | null | Webscraping_and_Automation/web-automation.py | Ruban2205/Python-Projects | 6c0444784b3be1356d43c70ca544e01e97158d0a | [
"MIT"
] | null | null | null | from webbot import Browser
import time
web = Browser()
web.go_to('https://www.rubangino.in/')
web.click('ABOUT')
web.click('SKILLS')
web.click('PORTFOLIO')
web.go_to('https://www.rubangino.in/android-app.html')
| 21.2 | 54 | 0.731132 | from webbot import Browser
import time
web = Browser()
web.go_to('https://www.rubangino.in/')
web.click('ABOUT')
web.click('SKILLS')
web.click('PORTFOLIO')
web.go_to('https://www.rubangino.in/android-app.html')
| true | true |
f72a1f0c23b646477e269707c49f7c4f891d2af1 | 446 | py | Python | External/__init__.py | QIB-Sheffield/WEASEL | e4dad345fd6f347cfac990708252844a7cbcd025 | [
"Apache-2.0"
] | 2 | 2021-02-10T09:07:15.000Z | 2021-03-16T17:05:24.000Z | External/__init__.py | QIB-Sheffield/WEASEL | e4dad345fd6f347cfac990708252844a7cbcd025 | [
"Apache-2.0"
] | 102 | 2021-01-20T11:14:21.000Z | 2021-12-12T17:34:42.000Z | External/__init__.py | QIB-Sheffield/WEASEL | e4dad345fd6f347cfac990708252844a7cbcd025 | [
"Apache-2.0"
] | 1 | 2021-01-29T09:28:05.000Z | 2021-01-29T09:28:05.000Z | """
This folder contains 3rd party packages that are used in this Weasel project.
You can find a list of these below with their respective version.
Each one has a folder allocated, which contains their own README.md file with their licensing details (all open-source)
- dcm4che Version 5.23.1
- pyqtgraph Version 0.9.11
It also contains a folder named "Tools" that consists of python scripts that can be auxiliary in pipelines development.
""" | 44.6 | 119 | 0.784753 | true | true | |
f72a205db5af6129fef3b71373688885867a2642 | 285 | py | Python | fbchat_archive_parser/writers/json.py | alvin-c/fbmessenger-visualizer | f89988720b2af79832a60824dce969f20b0ebb59 | [
"MIT"
] | 356 | 2016-01-25T23:57:57.000Z | 2022-02-20T18:39:22.000Z | fbchat_archive_parser/writers/json.py | alvin-c/fbmessenger-visualizer | f89988720b2af79832a60824dce969f20b0ebb59 | [
"MIT"
] | 78 | 2016-05-13T19:41:38.000Z | 2018-11-12T17:55:30.000Z | fbchat_archive_parser/writers/json.py | alvin-c/fbmessenger-visualizer | f89988720b2af79832a60824dce969f20b0ebb59 | [
"MIT"
] | 57 | 2016-09-09T15:19:57.000Z | 2022-03-24T19:29:59.000Z | from __future__ import unicode_literals, absolute_import
from .dict import DictWriter
import json
class JsonWriter(DictWriter):
def serialize_content(self, data):
return json.dumps(data, ensure_ascii=False)
@property
def extension(self):
return 'json'
| 19 | 56 | 0.729825 | from __future__ import unicode_literals, absolute_import
from .dict import DictWriter
import json
class JsonWriter(DictWriter):
def serialize_content(self, data):
return json.dumps(data, ensure_ascii=False)
@property
def extension(self):
return 'json'
| true | true |
f72a21ace7280d3d195e7c570c8971b756c0bb85 | 10,355 | py | Python | tests/user_test.py | maerifat/django-DefectDojo | ba1a415219ff20e8b4e909ef14f750de9b80297e | [
"BSD-3-Clause"
] | null | null | null | tests/user_test.py | maerifat/django-DefectDojo | ba1a415219ff20e8b4e909ef14f750de9b80297e | [
"BSD-3-Clause"
] | 206 | 2020-04-20T16:03:18.000Z | 2022-01-15T23:07:48.000Z | tests/user_test.py | maerifat/django-DefectDojo | ba1a415219ff20e8b4e909ef14f750de9b80297e | [
"BSD-3-Clause"
] | 1 | 2020-12-06T15:44:44.000Z | 2020-12-06T15:44:44.000Z | import time
import unittest
import sys
from pathlib import Path
from base_test_class import BaseTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
class UserTest(BaseTestCase):
@staticmethod
def add_user_read_only_parameter():
f = open('dojo/settings/local_settings.py', 'w')
f.write("USER_PROFILE_EDITABLE=False")
f.close()
@staticmethod
def unset_user_read_only_parameter():
f = open('dojo/settings/local_settings.py', 'w')
f.write("USER_PROFILE_EDITABLE=True")
f.close()
@staticmethod
def reload_service():
Path("dojo/settings/settings.py").touch()
def test_create_user(self):
# Login to the site.
driver = self.driver
# Navigate to the User managegement page
driver.get(self.base_url + "user")
# "Click" the dropdown button to see options
driver.find_element(By.ID, "dropdownMenu1").click()
# "Click" the add prodcut button
driver.find_element(By.LINK_TEXT, "New User").click()
# Fill in the Necessary User Details
# username, first name, last name, email, and permissions
# Don't forget to clear before inserting
# username
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys("propersahm")
# password
driver.find_element(By.ID, "id_password").clear()
driver.find_element(By.ID, "id_password").send_keys("Def3ctD0jo&")
# First Name
driver.find_element(By.ID, "id_first_name").clear()
driver.find_element(By.ID, "id_first_name").send_keys("Proper")
# Last Name
driver.find_element(By.ID, "id_last_name").clear()
driver.find_element(By.ID, "id_last_name").send_keys("Samuel")
# Email Address
driver.find_element(By.ID, "id_email").clear()
driver.find_element(By.ID, "id_email").send_keys("propersam@example.com")
# "Click" the submit button to complete the transaction
driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary").click()
# Query the site to determine if the user has been created
# Assert ot the query to dtermine status of failure
self.assertTrue(self.is_success_message_present(text='User added successfully.') or
self.is_help_message_present(text='A user with that username already exists.'))
def login_standard_page(self):
driver = self.driver
driver.get(self.base_url + "login")
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys('propersahm')
driver.find_element(By.ID, "id_password").clear()
driver.find_element(By.ID, "id_password").send_keys('Def3ctD0jo&')
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-success").click()
self.assertFalse(self.is_element_by_css_selector_present('.alert-danger', 'Please enter a correct username and password'))
return driver
def test_user_edit_permissions(self):
# Login to the site. Password will have to be modified
# to match an admin password in your own container
driver = self.driver
# Navigate to User Management page
driver.get(self.base_url + "user")
# Select the previously created user to edit
# The User name is not clickable
# so we would have to select specific user by filtering list of users
driver.find_element(By.ID, "show-filters").click() # open d filters
# Insert username to filter by into user name box
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys("propersahm")
# click on 'apply filter' button
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-sm.btn-secondary").click()
# only the needed user is now available, proceed with opening the context menu and clicking 'Edit' button
driver.find_element(By.ID, "dropdownMenuUser").click()
driver.find_element(By.ID, "editUser").click()
# Select Superuser and Staff Permission
driver.find_element(By.NAME, "is_superuser").click()
driver.find_element(By.NAME, "is_staff").click()
# "Click" the submit button to complete the transaction
driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary").click()
# Query the site to determine if the User permission has been changed
# Assert ot the query to dtermine status of failure
self.assertTrue(self.is_success_message_present(text='User saved successfully.'))
def test_user_delete(self):
# Login to the site. Password will have to be modified
# to match an admin password in your own container
driver = self.driver
# Navigate to the product page
driver.get(self.base_url + "user")
# Select A user to edit
# The User name is not clickable
# so we would have to select specific user by filtering list of users
driver.find_element(By.ID, "show-filters").click() # open d filters
# Insert username to filter by into user name box
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys("propersahm")
# click on 'apply filter' button
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-sm.btn-secondary").click()
# only the needed user is now available, proceed with clicking 'View' button
driver.find_element(By.ID, "dropdownMenuUser").click()
driver.find_element(By.ID, "viewUser").click()
# in View User dialog open the menu to click the delete entry
driver.find_element(By.ID, "dropdownMenu1").click()
driver.find_element(By.ID, "deleteUser").click()
# confirm deletion, by clicking delete a second time
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-danger").click()
# Query the site to determine if the User has been deleted
# Assert ot the query to dtermine status of failure
self.assertTrue(self.is_success_message_present(text='User and relationships removed.'))
def test_user_notifications_change(self):
# Login to the site. Password will have to be modified
# to match an admin password in your own container
driver = self.driver
wait = WebDriverWait(driver, 5)
actions = ActionChains(driver)
configuration_menu = driver.find_element(By.ID, 'menu_configuration')
actions.move_to_element(configuration_menu).perform()
wait.until(EC.visibility_of_element_located((By.LINK_TEXT, "Notifications"))).click()
originally_selected = {
'product_added': driver.find_element(By.XPATH, "//input[@name='product_added' and @value='mail']").is_selected(),
'scan_added': driver.find_element(By.XPATH, "//input[@name='scan_added' and @value='mail']").is_selected()
}
driver.find_element(By.XPATH, "//input[@name='product_added' and @value='mail']").click()
driver.find_element(By.XPATH, "//input[@name='scan_added' and @value='mail']").click()
driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary").click()
self.assertTrue(self.is_success_message_present(text='Settings saved'))
self.assertNotEqual(originally_selected['product_added'],
driver.find_element(By.XPATH, "//input[@name='product_added' and @value='mail']").is_selected())
self.assertNotEqual(originally_selected['scan_added'],
driver.find_element(By.XPATH, "//input[@name='scan_added' and @value='mail']").is_selected())
def test_standard_user_login(self):
self.login_standard_page()
def test_admin_profile_form(self):
self.add_user_read_only_parameter()
self.reload_service()
self.driver.get(self.base_url + "profile")
self.assertTrue(self.driver.find_element(By.ID, 'id_first_name').is_enabled())
def test_user_profile_form_disabled(self):
self.driver.get(self.base_url + "profile")
self.assertFalse(self.driver.find_element(By.ID, 'id_first_name').is_enabled())
def test_user_profile_form_enabled(self):
self.unset_user_read_only_parameter()
# Do not do function reload to avoid double reloading
time.sleep(5)
self.driver.get(self.base_url + "profile")
self.assertTrue(self.driver.find_element(By.ID, 'id_first_name').is_enabled())
def test_forgot_password(self):
driver = self.driver
driver.get(self.base_url + "login")
# Click on link on login screen
driver.find_element_by_id("reset-password").click()
# Submit "Forgot password" form
driver.find_element_by_id("id_email").send_keys("propersam@example.com")
driver.find_element_by_id("reset-password").click()
self.assertTrue(self.is_text_present_on_page(text='We’ve emailed you instructions for setting your password'))
def suite():
suite = unittest.TestSuite()
# Add each test the the suite to be run
# success and failure is output by the test
suite.addTest(BaseTestCase('test_login'))
suite.addTest(UserTest('test_create_user'))
suite.addTest(UserTest('test_admin_profile_form'))
suite.addTest(BaseTestCase('test_logout'))
suite.addTest(UserTest('test_standard_user_login'))
suite.addTest(UserTest('test_user_profile_form_disabled'))
suite.addTest(UserTest('test_user_profile_form_enabled'))
suite.addTest(BaseTestCase('test_logout'))
suite.addTest(UserTest('test_forgot_password'))
suite.addTest(BaseTestCase('test_login'))
suite.addTest(UserTest('test_user_edit_permissions'))
suite.addTest(UserTest('test_user_delete'))
# not really for the user we created, but still related to user settings
suite.addTest(UserTest('test_user_notifications_change'))
return suite
if __name__ == "__main__":
runner = unittest.TextTestRunner(descriptions=True, failfast=True, verbosity=2)
ret = not runner.run(suite()).wasSuccessful()
BaseTestCase.tearDownDriver()
sys.exit(ret)
| 47.068182 | 130 | 0.689039 | import time
import unittest
import sys
from pathlib import Path
from base_test_class import BaseTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
class UserTest(BaseTestCase):
@staticmethod
def add_user_read_only_parameter():
f = open('dojo/settings/local_settings.py', 'w')
f.write("USER_PROFILE_EDITABLE=False")
f.close()
@staticmethod
def unset_user_read_only_parameter():
f = open('dojo/settings/local_settings.py', 'w')
f.write("USER_PROFILE_EDITABLE=True")
f.close()
@staticmethod
def reload_service():
Path("dojo/settings/settings.py").touch()
def test_create_user(self):
driver = self.driver
driver.get(self.base_url + "user")
driver.find_element(By.ID, "dropdownMenu1").click()
driver.find_element(By.LINK_TEXT, "New User").click()
# username
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys("propersahm")
# password
driver.find_element(By.ID, "id_password").clear()
driver.find_element(By.ID, "id_password").send_keys("Def3ctD0jo&")
# First Name
driver.find_element(By.ID, "id_first_name").clear()
driver.find_element(By.ID, "id_first_name").send_keys("Proper")
# Last Name
driver.find_element(By.ID, "id_last_name").clear()
driver.find_element(By.ID, "id_last_name").send_keys("Samuel")
# Email Address
driver.find_element(By.ID, "id_email").clear()
driver.find_element(By.ID, "id_email").send_keys("propersam@example.com")
# "Click" the submit button to complete the transaction
driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary").click()
# Query the site to determine if the user has been created
# Assert ot the query to dtermine status of failure
self.assertTrue(self.is_success_message_present(text='User added successfully.') or
self.is_help_message_present(text='A user with that username already exists.'))
def login_standard_page(self):
driver = self.driver
driver.get(self.base_url + "login")
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys('propersahm')
driver.find_element(By.ID, "id_password").clear()
driver.find_element(By.ID, "id_password").send_keys('Def3ctD0jo&')
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-success").click()
self.assertFalse(self.is_element_by_css_selector_present('.alert-danger', 'Please enter a correct username and password'))
return driver
def test_user_edit_permissions(self):
# Login to the site. Password will have to be modified
# to match an admin password in your own container
driver = self.driver
# Navigate to User Management page
driver.get(self.base_url + "user")
# Select the previously created user to edit
# The User name is not clickable
# so we would have to select specific user by filtering list of users
driver.find_element(By.ID, "show-filters").click() # open d filters
# Insert username to filter by into user name box
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys("propersahm")
# click on 'apply filter' button
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-sm.btn-secondary").click()
# only the needed user is now available, proceed with opening the context menu and clicking 'Edit' button
driver.find_element(By.ID, "dropdownMenuUser").click()
driver.find_element(By.ID, "editUser").click()
# Select Superuser and Staff Permission
driver.find_element(By.NAME, "is_superuser").click()
driver.find_element(By.NAME, "is_staff").click()
# "Click" the submit button to complete the transaction
driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary").click()
# Query the site to determine if the User permission has been changed
# Assert ot the query to dtermine status of failure
self.assertTrue(self.is_success_message_present(text='User saved successfully.'))
def test_user_delete(self):
# Login to the site. Password will have to be modified
# to match an admin password in your own container
driver = self.driver
# Navigate to the product page
driver.get(self.base_url + "user")
# Select A user to edit
# The User name is not clickable
# so we would have to select specific user by filtering list of users
driver.find_element(By.ID, "show-filters").click() # open d filters
# Insert username to filter by into user name box
driver.find_element(By.ID, "id_username").clear()
driver.find_element(By.ID, "id_username").send_keys("propersahm")
# click on 'apply filter' button
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-sm.btn-secondary").click()
# only the needed user is now available, proceed with clicking 'View' button
driver.find_element(By.ID, "dropdownMenuUser").click()
driver.find_element(By.ID, "viewUser").click()
# in View User dialog open the menu to click the delete entry
driver.find_element(By.ID, "dropdownMenu1").click()
driver.find_element(By.ID, "deleteUser").click()
# confirm deletion, by clicking delete a second time
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-danger").click()
# Query the site to determine if the User has been deleted
# Assert ot the query to dtermine status of failure
self.assertTrue(self.is_success_message_present(text='User and relationships removed.'))
def test_user_notifications_change(self):
# Login to the site. Password will have to be modified
# to match an admin password in your own container
driver = self.driver
wait = WebDriverWait(driver, 5)
actions = ActionChains(driver)
configuration_menu = driver.find_element(By.ID, 'menu_configuration')
actions.move_to_element(configuration_menu).perform()
wait.until(EC.visibility_of_element_located((By.LINK_TEXT, "Notifications"))).click()
originally_selected = {
'product_added': driver.find_element(By.XPATH, "//input[@name='product_added' and @value='mail']").is_selected(),
'scan_added': driver.find_element(By.XPATH, "//input[@name='scan_added' and @value='mail']").is_selected()
}
driver.find_element(By.XPATH, "//input[@name='product_added' and @value='mail']").click()
driver.find_element(By.XPATH, "//input[@name='scan_added' and @value='mail']").click()
driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary").click()
self.assertTrue(self.is_success_message_present(text='Settings saved'))
self.assertNotEqual(originally_selected['product_added'],
driver.find_element(By.XPATH, "//input[@name='product_added' and @value='mail']").is_selected())
self.assertNotEqual(originally_selected['scan_added'],
driver.find_element(By.XPATH, "//input[@name='scan_added' and @value='mail']").is_selected())
def test_standard_user_login(self):
self.login_standard_page()
def test_admin_profile_form(self):
self.add_user_read_only_parameter()
self.reload_service()
self.driver.get(self.base_url + "profile")
self.assertTrue(self.driver.find_element(By.ID, 'id_first_name').is_enabled())
def test_user_profile_form_disabled(self):
self.driver.get(self.base_url + "profile")
self.assertFalse(self.driver.find_element(By.ID, 'id_first_name').is_enabled())
def test_user_profile_form_enabled(self):
self.unset_user_read_only_parameter()
# Do not do function reload to avoid double reloading
time.sleep(5)
self.driver.get(self.base_url + "profile")
self.assertTrue(self.driver.find_element(By.ID, 'id_first_name').is_enabled())
def test_forgot_password(self):
driver = self.driver
driver.get(self.base_url + "login")
# Click on link on login screen
driver.find_element_by_id("reset-password").click()
# Submit "Forgot password" form
driver.find_element_by_id("id_email").send_keys("propersam@example.com")
driver.find_element_by_id("reset-password").click()
self.assertTrue(self.is_text_present_on_page(text='We’ve emailed you instructions for setting your password'))
def suite():
suite = unittest.TestSuite()
# Add each test the the suite to be run
# success and failure is output by the test
suite.addTest(BaseTestCase('test_login'))
suite.addTest(UserTest('test_create_user'))
suite.addTest(UserTest('test_admin_profile_form'))
suite.addTest(BaseTestCase('test_logout'))
suite.addTest(UserTest('test_standard_user_login'))
suite.addTest(UserTest('test_user_profile_form_disabled'))
suite.addTest(UserTest('test_user_profile_form_enabled'))
suite.addTest(BaseTestCase('test_logout'))
suite.addTest(UserTest('test_forgot_password'))
suite.addTest(BaseTestCase('test_login'))
suite.addTest(UserTest('test_user_edit_permissions'))
suite.addTest(UserTest('test_user_delete'))
# not really for the user we created, but still related to user settings
suite.addTest(UserTest('test_user_notifications_change'))
return suite
if __name__ == "__main__":
runner = unittest.TextTestRunner(descriptions=True, failfast=True, verbosity=2)
ret = not runner.run(suite()).wasSuccessful()
BaseTestCase.tearDownDriver()
sys.exit(ret)
| true | true |
f72a21f6c715e3e5ea77580a68578caf14684d15 | 15,231 | py | Python | ginga/canvas/transform.py | profxj/ginga | a5f447b760ac38dafa52181b3f99156545a6f2e7 | [
"BSD-3-Clause"
] | null | null | null | ginga/canvas/transform.py | profxj/ginga | a5f447b760ac38dafa52181b3f99156545a6f2e7 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T15:22:13.000Z | 2020-04-25T19:34:30.000Z | ginga/canvas/transform.py | profxj/ginga | a5f447b760ac38dafa52181b3f99156545a6f2e7 | [
"BSD-3-Clause"
] | 3 | 2018-02-09T20:06:30.000Z | 2020-03-30T02:31:44.000Z | #
# transform.py -- coordinate transforms for Ginga
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import numpy as np
from ginga import trcalc
from ginga.misc import Bunch
__all__ = ['TransformError', 'BaseTransform', 'ComposedTransform',
'InvertedTransform', 'PassThruTransform',
'WindowNativeTransform', 'CartesianWindowTransform',
'CartesianNativeTransform',
'RotationTransform', 'ScaleTransform',
'DataCartesianTransform', 'OffsetDataTransform',
'WCSDataTransform', 'get_catalog'
]
class TransformError(Exception):
pass
class BaseTransform(object):
def __init__(self):
super(BaseTransform, self).__init__()
def to_(self, x, y):
raise TransformError("subclass should override this method")
def from_(self, tx, ty):
raise TransformError("subclass should override this method")
def __add__(self, trans):
return ComposedTransform(self, trans)
def invert(self):
return InvertedTransform(self)
class ComposedTransform(BaseTransform):
"""
A transform that composes two other transforms to make a new one.
"""
def __init__(self, tform1, tform2):
super(ComposedTransform, self).__init__()
self.tform1 = tform1
self.tform2 = tform2
def to_(self, pts, **kwargs):
return self.tform2.to_(self.tform1.to_(pts, **kwargs))
def from_(self, pts, **kwargs):
return self.tform1.from_(self.tform2.from_(pts), **kwargs)
class InvertedTransform(BaseTransform):
"""
A transform that inverts another transform.
"""
def __init__(self, tform):
super(InvertedTransform, self).__init__()
self.tform = tform
def to_(self, pts, **kwargs):
return self.tform.from_(pts, **kwargs)
def from_(self, pts, **kwargs):
return self.tform.to_(pts, **kwargs)
class PassThruTransform(BaseTransform):
"""
A transform that essentially acts as a no-op.
"""
def __init__(self, viewer):
super(PassThruTransform, self).__init__()
def to_(self, pts, **kwargs):
return pts
def from_(self, pts, **kwargs):
return pts
class WindowNativeTransform(BaseTransform):
"""
A transform from a typical window standard coordinate space with the
upper left at (0, 0) to the viewer back end native pixel space.
"""
def __init__(self, viewer):
super(WindowNativeTransform, self).__init__()
self.viewer = viewer
def to_(self, win_pts):
if self.viewer.origin_upper:
return win_pts
win_pts = np.asarray(win_pts)
has_z = (win_pts.shape[-1] > 2)
# invert Y coord for backends that have the origin in the lower left
win_wd, win_ht = self.viewer.get_window_size()
# win_x, win_y = cvs_x, win_ht - cvs_y
mpy_pt = [1.0, -1.0]
if has_z:
mpy_pt.append(1.0)
add_pt = [0.0, win_ht]
if has_z:
add_pt.append(0.0)
ntv_pts = np.add(np.multiply(win_pts, mpy_pt), add_pt)
return ntv_pts
def from_(self, ntv_pts):
return self.to_(ntv_pts)
class WindowPercentageTransform(BaseTransform):
"""
A transform from standard window coordinates of a viewer
to percentage coordinates.
"""
def __init__(self, viewer, as_int=True):
super(WindowPercentageTransform, self).__init__()
self.viewer = viewer
self.as_int = as_int
def to_(self, win_pts):
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
max_pt = list(self.viewer.get_window_size())
if has_z:
max_pt.append(0.0)
pct_pts = np.divide(win_pts, max_pt)
return pct_pts
def from_(self, pct_pts):
"""Reverse of :meth:`to_`."""
pct_pts = np.asarray(pct_pts, dtype=np.float)
has_z = (pct_pts.shape[-1] > 2)
max_pt = list(self.viewer.get_window_size())
if has_z:
max_pt.append(0.0)
win_pts = np.multiply(pct_pts, max_pt)
# round to pixel units, if asked
if self.as_int:
win_pts = np.rint(win_pts).astype(np.int, copy=False)
return win_pts
class CartesianWindowTransform(BaseTransform):
"""
A transform from cartesian coordinates to standard window coordinates
of a viewer.
"""
def __init__(self, viewer, as_int=True):
super(CartesianWindowTransform, self).__init__()
self.viewer = viewer
self.as_int = as_int
def to_(self, off_pts):
# add center pixel to convert from X/Y coordinate space to
# window graphics space
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
# win_x = off_x + ctr_x
# win_y = ctr_y - off_y
mpy_pt = [1.0, -1.0]
if has_z:
mpy_pt.append(1.0)
win_pts = np.add(np.multiply(off_pts, mpy_pt), ctr_pt)
# round to pixel units, if asked
if self.as_int:
win_pts = np.rint(win_pts).astype(np.int, copy=False)
return win_pts
def from_(self, win_pts):
"""Reverse of :meth:`to_`."""
# make relative to center pixel to convert from window
# graphics space to standard X/Y coordinate space
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
mpy_pt = [1.0, -1.0]
if has_z:
mpy_pt.append(1.0)
# off_x = win_x - ctr_x
# = win_x + -ctr_x
# off_y = ctr_y - win_y
# = -win_y + ctr_y
ctr_pt[0] = -ctr_pt[0]
off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt)
return off_pts
class CartesianNativeTransform(BaseTransform):
"""
A transform from cartesian coordinates to the native pixel coordinates
of a viewer.
"""
def __init__(self, viewer, as_int=True):
super(CartesianNativeTransform, self).__init__()
self.viewer = viewer
self.as_int = as_int
def to_(self, off_pts):
# add center pixel to convert from X/Y coordinate space to
# back end graphics space
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
if self.viewer.origin_upper:
mpy_pt = [1.0, -1.0]
else:
mpy_pt = [1.0, 1.0]
if has_z:
mpy_pt.append(1.0)
win_pts = np.add(np.multiply(off_pts, mpy_pt), ctr_pt)
# round to pixel units, if asked
if self.as_int:
win_pts = np.rint(win_pts).astype(np.int, copy=False)
return win_pts
def from_(self, win_pts):
"""Reverse of :meth:`to_`."""
# make relative to center pixel to convert from back end
# graphics space to standard X/Y coordinate space
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
ctr_pt[0] = -ctr_pt[0]
if self.viewer.origin_upper:
mpy_pt = [1.0, -1.0]
else:
ctr_pt[1] = -ctr_pt[1]
mpy_pt = [1.0, 1.0]
if has_z:
mpy_pt.append(1.0)
off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt)
return off_pts
class RotationTransform(BaseTransform):
"""
A transform in cartesian coordinates based on the flip/swap setting and
rotation setting of a viewer.
"""
def __init__(self, viewer):
super(RotationTransform, self).__init__()
self.viewer = viewer
def to_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
t_ = self.viewer.t_
# flip
flip_pt = [1.0, 1.0]
if t_['flip_x']:
flip_pt[0] = -1.0
if t_['flip_y']:
flip_pt[1] = -1.0
if has_z:
# no flip_z at the moment
flip_pt.append(1.0)
off_pts = np.multiply(off_pts, flip_pt)
# swap
if t_['swap_xy']:
p = list(off_pts.T)
off_pts = np.asarray([p[1], p[0]] + list(p[2:])).T
# rotate
if t_['rot_deg'] != 0:
thetas = [t_['rot_deg']]
offset = [0.0, 0.0]
if has_z:
offset.append(0.0)
off_pts = trcalc.rotate_coord(off_pts, thetas, offset)
return off_pts
def from_(self, off_pts):
"""Reverse of :meth:`to_`."""
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
t_ = self.viewer.t_
# rotate
if t_['rot_deg'] != 0:
thetas = [- t_['rot_deg']]
offset = [0.0, 0.0]
if has_z:
offset.append(0.0)
off_pts = trcalc.rotate_coord(off_pts, thetas, offset)
# swap
if t_['swap_xy']:
p = list(off_pts.T)
off_pts = np.asarray([p[1], p[0]] + list(p[2:])).T
# flip
flip_pt = [1.0, 1.0]
if t_['flip_x']:
flip_pt[0] = -1.0
if t_['flip_y']:
flip_pt[1] = -1.0
if has_z:
# no flip_z at the moment
flip_pt.append(1.0)
off_pts = np.multiply(off_pts, flip_pt)
return off_pts
class ScaleTransform(BaseTransform):
"""
A transform in cartesian coordinates based on the scale of a viewer.
"""
def __init__(self, viewer):
super(ScaleTransform, self).__init__()
self.viewer = viewer
def to_(self, off_pts):
"""Reverse of :meth:`from_`."""
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
# scale according to current settings
scale_pt = [self.viewer._org_scale_x, self.viewer._org_scale_y]
if has_z:
scale_pt.append(self.viewer._org_scale_z)
off_pts = np.multiply(off_pts, scale_pt)
return off_pts
def from_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
scale_pt = [1.0 / self.viewer._org_scale_x,
1.0 / self.viewer._org_scale_y]
if has_z:
scale_pt.append(1.0 / self.viewer._org_scale_z)
# Reverse scaling
off_pts = np.multiply(off_pts, scale_pt)
return off_pts
class DataCartesianTransform(BaseTransform):
"""
A transform from data coordinates to cartesian coordinates based on
a viewer's pan position.
"""
def __init__(self, viewer, use_center=True):
super(DataCartesianTransform, self).__init__()
self.viewer = viewer
# If use_center is True, then the coordinates are mapped such that the
# pixel is centered on the square when the image is zoomed in past
# 1X. This is the specification of the FITS image standard,
# that the pixel is centered on the integer row/column.
self.use_center = use_center
def to_(self, data_pts):
"""Reverse of :meth:`from_`."""
data_pts = np.asarray(data_pts, dtype=np.float)
has_z = (data_pts.shape[-1] > 2)
if self.use_center:
data_pts = data_pts - self.viewer.data_off
# subtract data indexes at center reference pixel
ref_pt = [self.viewer._org_x, self.viewer._org_y]
if has_z:
ref_pt.append(self.viewer._org_z)
off_pts = np.subtract(data_pts, ref_pt)
return off_pts
def from_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
# Add data index at center to offset
# subtract data indexes at center reference pixel
ref_pt = [self.viewer._org_x, self.viewer._org_y]
if has_z:
ref_pt.append(self.viewer._org_z)
data_pts = np.add(off_pts, ref_pt)
if self.use_center:
data_pts = data_pts + self.viewer.data_off
return data_pts
class OffsetDataTransform(BaseTransform):
"""
A transform whose coordinate space is offsets from a point in
data space.
"""
def __init__(self, pt):
super(OffsetDataTransform, self).__init__()
self.pt = pt
def to_(self, delta_pts):
delta_x, delta_y = np.asarray(delta_pts, dtype=np.float).T
ref_x, ref_y = self.pt[:2]
res_x, res_y = ref_x + delta_x, ref_y + delta_y
return np.asarray((res_x, res_y)).T
def from_(self, data_pts):
data_x, data_y = np.asarray(data_pts, dtype=np.float).T
ref_x, ref_y = self.pt[:2]
res_x, res_y = data_x - ref_x, data_y - ref_y
return np.asarray((res_x, res_y)).T
class WCSDataTransform(BaseTransform):
"""
A transform whose coordinate space is based on the WCS of the primary
image loaded in a viewer.
"""
def __init__(self, viewer):
super(WCSDataTransform, self).__init__()
self.viewer = viewer
def to_(self, wcs_pts):
wcs_pts = np.asarray(wcs_pts)
# hack to work around passing singleton pt vs. array of pts
unpack = False
if len(wcs_pts.shape) < 2:
# passed a single coordinate
wcs_pts = np.asarray([wcs_pts])
unpack = True
image = self.viewer.get_image()
if image is None:
raise TransformError("No image, no WCS")
wcs = image.wcs
if wcs is None:
raise TransformError("No valid WCS found in image")
naxispath = image.naxispath
res = wcs.wcspt_to_datapt(wcs_pts, naxispath=naxispath)
if unpack:
return res[0]
return res
def from_(self, data_pts):
data_pts = np.asarray(data_pts)
# hack to work around passing singleton pt vs. array of pts
unpack = False
if len(data_pts.shape) < 2:
# passed a single coordinate
data_pts = np.asarray([data_pts])
unpack = True
image = self.viewer.get_image()
if image is None:
raise TransformError("No image, no WCS")
wcs = image.wcs
if wcs is None:
raise TransformError("No valid WCS found in image")
naxispath = image.naxispath
res = wcs.datapt_to_wcspt(data_pts, naxispath=naxispath)
if unpack:
return res[0]
return res
def get_catalog():
"""Returns a catalog of available transforms. These are used to
build chains for rendering with different back ends.
"""
tforms = {}
for name, value in list(globals().items()):
if name.endswith('Transform'):
tforms[name] = value
return Bunch.Bunch(tforms, caseless=True)
#END
| 27.743169 | 78 | 0.589653 |
import numpy as np
from ginga import trcalc
from ginga.misc import Bunch
__all__ = ['TransformError', 'BaseTransform', 'ComposedTransform',
'InvertedTransform', 'PassThruTransform',
'WindowNativeTransform', 'CartesianWindowTransform',
'CartesianNativeTransform',
'RotationTransform', 'ScaleTransform',
'DataCartesianTransform', 'OffsetDataTransform',
'WCSDataTransform', 'get_catalog'
]
class TransformError(Exception):
pass
class BaseTransform(object):
def __init__(self):
super(BaseTransform, self).__init__()
def to_(self, x, y):
raise TransformError("subclass should override this method")
def from_(self, tx, ty):
raise TransformError("subclass should override this method")
def __add__(self, trans):
return ComposedTransform(self, trans)
def invert(self):
return InvertedTransform(self)
class ComposedTransform(BaseTransform):
def __init__(self, tform1, tform2):
super(ComposedTransform, self).__init__()
self.tform1 = tform1
self.tform2 = tform2
def to_(self, pts, **kwargs):
return self.tform2.to_(self.tform1.to_(pts, **kwargs))
def from_(self, pts, **kwargs):
return self.tform1.from_(self.tform2.from_(pts), **kwargs)
class InvertedTransform(BaseTransform):
def __init__(self, tform):
super(InvertedTransform, self).__init__()
self.tform = tform
def to_(self, pts, **kwargs):
return self.tform.from_(pts, **kwargs)
def from_(self, pts, **kwargs):
return self.tform.to_(pts, **kwargs)
class PassThruTransform(BaseTransform):
def __init__(self, viewer):
super(PassThruTransform, self).__init__()
def to_(self, pts, **kwargs):
return pts
def from_(self, pts, **kwargs):
return pts
class WindowNativeTransform(BaseTransform):
def __init__(self, viewer):
super(WindowNativeTransform, self).__init__()
self.viewer = viewer
def to_(self, win_pts):
if self.viewer.origin_upper:
return win_pts
win_pts = np.asarray(win_pts)
has_z = (win_pts.shape[-1] > 2)
win_wd, win_ht = self.viewer.get_window_size()
mpy_pt = [1.0, -1.0]
if has_z:
mpy_pt.append(1.0)
add_pt = [0.0, win_ht]
if has_z:
add_pt.append(0.0)
ntv_pts = np.add(np.multiply(win_pts, mpy_pt), add_pt)
return ntv_pts
def from_(self, ntv_pts):
return self.to_(ntv_pts)
class WindowPercentageTransform(BaseTransform):
def __init__(self, viewer, as_int=True):
super(WindowPercentageTransform, self).__init__()
self.viewer = viewer
self.as_int = as_int
def to_(self, win_pts):
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
max_pt = list(self.viewer.get_window_size())
if has_z:
max_pt.append(0.0)
pct_pts = np.divide(win_pts, max_pt)
return pct_pts
def from_(self, pct_pts):
pct_pts = np.asarray(pct_pts, dtype=np.float)
has_z = (pct_pts.shape[-1] > 2)
max_pt = list(self.viewer.get_window_size())
if has_z:
max_pt.append(0.0)
win_pts = np.multiply(pct_pts, max_pt)
if self.as_int:
win_pts = np.rint(win_pts).astype(np.int, copy=False)
return win_pts
class CartesianWindowTransform(BaseTransform):
def __init__(self, viewer, as_int=True):
super(CartesianWindowTransform, self).__init__()
self.viewer = viewer
self.as_int = as_int
def to_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
mpy_pt = [1.0, -1.0]
if has_z:
mpy_pt.append(1.0)
win_pts = np.add(np.multiply(off_pts, mpy_pt), ctr_pt)
if self.as_int:
win_pts = np.rint(win_pts).astype(np.int, copy=False)
return win_pts
def from_(self, win_pts):
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
mpy_pt = [1.0, -1.0]
if has_z:
mpy_pt.append(1.0)
ctr_pt[0] = -ctr_pt[0]
off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt)
return off_pts
class CartesianNativeTransform(BaseTransform):
def __init__(self, viewer, as_int=True):
super(CartesianNativeTransform, self).__init__()
self.viewer = viewer
self.as_int = as_int
def to_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
if self.viewer.origin_upper:
mpy_pt = [1.0, -1.0]
else:
mpy_pt = [1.0, 1.0]
if has_z:
mpy_pt.append(1.0)
win_pts = np.add(np.multiply(off_pts, mpy_pt), ctr_pt)
if self.as_int:
win_pts = np.rint(win_pts).astype(np.int, copy=False)
return win_pts
def from_(self, win_pts):
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_center())
if has_z:
ctr_pt.append(0.0)
ctr_pt[0] = -ctr_pt[0]
if self.viewer.origin_upper:
mpy_pt = [1.0, -1.0]
else:
ctr_pt[1] = -ctr_pt[1]
mpy_pt = [1.0, 1.0]
if has_z:
mpy_pt.append(1.0)
off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt)
return off_pts
class RotationTransform(BaseTransform):
def __init__(self, viewer):
super(RotationTransform, self).__init__()
self.viewer = viewer
def to_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
t_ = self.viewer.t_
flip_pt = [1.0, 1.0]
if t_['flip_x']:
flip_pt[0] = -1.0
if t_['flip_y']:
flip_pt[1] = -1.0
if has_z:
flip_pt.append(1.0)
off_pts = np.multiply(off_pts, flip_pt)
if t_['swap_xy']:
p = list(off_pts.T)
off_pts = np.asarray([p[1], p[0]] + list(p[2:])).T
if t_['rot_deg'] != 0:
thetas = [t_['rot_deg']]
offset = [0.0, 0.0]
if has_z:
offset.append(0.0)
off_pts = trcalc.rotate_coord(off_pts, thetas, offset)
return off_pts
def from_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
t_ = self.viewer.t_
if t_['rot_deg'] != 0:
thetas = [- t_['rot_deg']]
offset = [0.0, 0.0]
if has_z:
offset.append(0.0)
off_pts = trcalc.rotate_coord(off_pts, thetas, offset)
if t_['swap_xy']:
p = list(off_pts.T)
off_pts = np.asarray([p[1], p[0]] + list(p[2:])).T
flip_pt = [1.0, 1.0]
if t_['flip_x']:
flip_pt[0] = -1.0
if t_['flip_y']:
flip_pt[1] = -1.0
if has_z:
flip_pt.append(1.0)
off_pts = np.multiply(off_pts, flip_pt)
return off_pts
class ScaleTransform(BaseTransform):
def __init__(self, viewer):
super(ScaleTransform, self).__init__()
self.viewer = viewer
def to_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
scale_pt = [self.viewer._org_scale_x, self.viewer._org_scale_y]
if has_z:
scale_pt.append(self.viewer._org_scale_z)
off_pts = np.multiply(off_pts, scale_pt)
return off_pts
def from_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
scale_pt = [1.0 / self.viewer._org_scale_x,
1.0 / self.viewer._org_scale_y]
if has_z:
scale_pt.append(1.0 / self.viewer._org_scale_z)
off_pts = np.multiply(off_pts, scale_pt)
return off_pts
class DataCartesianTransform(BaseTransform):
def __init__(self, viewer, use_center=True):
super(DataCartesianTransform, self).__init__()
self.viewer = viewer
self.use_center = use_center
def to_(self, data_pts):
data_pts = np.asarray(data_pts, dtype=np.float)
has_z = (data_pts.shape[-1] > 2)
if self.use_center:
data_pts = data_pts - self.viewer.data_off
ref_pt = [self.viewer._org_x, self.viewer._org_y]
if has_z:
ref_pt.append(self.viewer._org_z)
off_pts = np.subtract(data_pts, ref_pt)
return off_pts
def from_(self, off_pts):
off_pts = np.asarray(off_pts, dtype=np.float)
has_z = (off_pts.shape[-1] > 2)
ref_pt = [self.viewer._org_x, self.viewer._org_y]
if has_z:
ref_pt.append(self.viewer._org_z)
data_pts = np.add(off_pts, ref_pt)
if self.use_center:
data_pts = data_pts + self.viewer.data_off
return data_pts
class OffsetDataTransform(BaseTransform):
def __init__(self, pt):
super(OffsetDataTransform, self).__init__()
self.pt = pt
def to_(self, delta_pts):
delta_x, delta_y = np.asarray(delta_pts, dtype=np.float).T
ref_x, ref_y = self.pt[:2]
res_x, res_y = ref_x + delta_x, ref_y + delta_y
return np.asarray((res_x, res_y)).T
def from_(self, data_pts):
data_x, data_y = np.asarray(data_pts, dtype=np.float).T
ref_x, ref_y = self.pt[:2]
res_x, res_y = data_x - ref_x, data_y - ref_y
return np.asarray((res_x, res_y)).T
class WCSDataTransform(BaseTransform):
def __init__(self, viewer):
super(WCSDataTransform, self).__init__()
self.viewer = viewer
def to_(self, wcs_pts):
wcs_pts = np.asarray(wcs_pts)
unpack = False
if len(wcs_pts.shape) < 2:
wcs_pts = np.asarray([wcs_pts])
unpack = True
image = self.viewer.get_image()
if image is None:
raise TransformError("No image, no WCS")
wcs = image.wcs
if wcs is None:
raise TransformError("No valid WCS found in image")
naxispath = image.naxispath
res = wcs.wcspt_to_datapt(wcs_pts, naxispath=naxispath)
if unpack:
return res[0]
return res
def from_(self, data_pts):
data_pts = np.asarray(data_pts)
unpack = False
if len(data_pts.shape) < 2:
data_pts = np.asarray([data_pts])
unpack = True
image = self.viewer.get_image()
if image is None:
raise TransformError("No image, no WCS")
wcs = image.wcs
if wcs is None:
raise TransformError("No valid WCS found in image")
naxispath = image.naxispath
res = wcs.datapt_to_wcspt(data_pts, naxispath=naxispath)
if unpack:
return res[0]
return res
def get_catalog():
tforms = {}
for name, value in list(globals().items()):
if name.endswith('Transform'):
tforms[name] = value
return Bunch.Bunch(tforms, caseless=True)
| true | true |
f72a2370017c122159ed563919fd31b5e3d7c7ad | 165 | py | Python | Python/Strings/StringSplitAndJoin.py | devansh-pratap-singh/hackerrank-solutions | 227817d90846424cd3078e60b225eb201e906cf9 | [
"MIT"
] | 1 | 2020-10-15T14:03:52.000Z | 2020-10-15T14:03:52.000Z | Python/Strings/StringSplitAndJoin.py | devansh-pratap-singh/HackerRank-Solutions | 227817d90846424cd3078e60b225eb201e906cf9 | [
"MIT"
] | null | null | null | Python/Strings/StringSplitAndJoin.py | devansh-pratap-singh/HackerRank-Solutions | 227817d90846424cd3078e60b225eb201e906cf9 | [
"MIT"
] | null | null | null | def split_and_join(line):
new = line.split(" ")
return "-".join(new)
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) | 20.625 | 31 | 0.654545 | def split_and_join(line):
new = line.split(" ")
return "-".join(new)
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) | true | true |
f72a24ac56b6a4a8bd16cd8ff8d1ab866e7cbece | 263 | py | Python | PyLibvirt/test.py | flyflyinit/libvirt-GUI-using-python | 4793ac8e581e2c75d42cd7966bae75cc792c3522 | [
"MIT"
] | null | null | null | PyLibvirt/test.py | flyflyinit/libvirt-GUI-using-python | 4793ac8e581e2c75d42cd7966bae75cc792c3522 | [
"MIT"
] | null | null | null | PyLibvirt/test.py | flyflyinit/libvirt-GUI-using-python | 4793ac8e581e2c75d42cd7966bae75cc792c3522 | [
"MIT"
] | null | null | null | from PIL import Image,ImageDraw
import os
########### showing the image on the screen
image1 = Image.open('icons/io.png')
drawing_object=ImageDraw.Draw(image1)
drawing_object.rectangle((50,0,190,150), fill = None, outline ='red')
image1.show()
#display(image1) | 23.909091 | 69 | 0.730038 | from PIL import Image,ImageDraw
import os
| true | true |
f72a26135e2d57e4c45bf036bf1bf49ac9d741c1 | 1,804 | py | Python | aliyun-python-sdk-iot/aliyunsdkiot/request/v20180120/CreateProductTagsRequest.py | sdk-team/aliyun-openapi-python-sdk | 384730d707e6720d1676ccb8f552e6a7b330ec86 | [
"Apache-2.0"
] | null | null | null | aliyun-python-sdk-iot/aliyunsdkiot/request/v20180120/CreateProductTagsRequest.py | sdk-team/aliyun-openapi-python-sdk | 384730d707e6720d1676ccb8f552e6a7b330ec86 | [
"Apache-2.0"
] | null | null | null | aliyun-python-sdk-iot/aliyunsdkiot/request/v20180120/CreateProductTagsRequest.py | sdk-team/aliyun-openapi-python-sdk | 384730d707e6720d1676ccb8f552e6a7b330ec86 | [
"Apache-2.0"
] | null | null | null | # 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 aliyunsdkcore.request import RpcRequest
class CreateProductTagsRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Iot', '2018-01-20', 'CreateProductTags','iot')
def get_ProductTags(self):
return self.get_query_params().get('ProductTags')
def set_ProductTags(self,ProductTags):
for i in range(len(ProductTags)):
if ProductTags[i].get('TagValue') is not None:
self.add_query_param('ProductTag.' + str(i + 1) + '.TagValue' , ProductTags[i].get('TagValue'))
if ProductTags[i].get('TagKey') is not None:
self.add_query_param('ProductTag.' + str(i + 1) + '.TagKey' , ProductTags[i].get('TagKey'))
def get_IotInstanceId(self):
return self.get_query_params().get('IotInstanceId')
def set_IotInstanceId(self,IotInstanceId):
self.add_query_param('IotInstanceId',IotInstanceId)
def get_ProductKey(self):
return self.get_query_params().get('ProductKey')
def set_ProductKey(self,ProductKey):
self.add_query_param('ProductKey',ProductKey) | 38.382979 | 100 | 0.745011 |
from aliyunsdkcore.request import RpcRequest
class CreateProductTagsRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Iot', '2018-01-20', 'CreateProductTags','iot')
def get_ProductTags(self):
return self.get_query_params().get('ProductTags')
def set_ProductTags(self,ProductTags):
for i in range(len(ProductTags)):
if ProductTags[i].get('TagValue') is not None:
self.add_query_param('ProductTag.' + str(i + 1) + '.TagValue' , ProductTags[i].get('TagValue'))
if ProductTags[i].get('TagKey') is not None:
self.add_query_param('ProductTag.' + str(i + 1) + '.TagKey' , ProductTags[i].get('TagKey'))
def get_IotInstanceId(self):
return self.get_query_params().get('IotInstanceId')
def set_IotInstanceId(self,IotInstanceId):
self.add_query_param('IotInstanceId',IotInstanceId)
def get_ProductKey(self):
return self.get_query_params().get('ProductKey')
def set_ProductKey(self,ProductKey):
self.add_query_param('ProductKey',ProductKey) | true | true |
f72a263618701ae1fe6cb1a521bcae84e7789cff | 52,716 | py | Python | wildlifecompliance/components/legal_case/serializers.py | preranaandure/wildlifecompliance | bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5 | [
"Apache-2.0"
] | 1 | 2020-12-07T17:12:40.000Z | 2020-12-07T17:12:40.000Z | wildlifecompliance/components/legal_case/serializers.py | preranaandure/wildlifecompliance | bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5 | [
"Apache-2.0"
] | 14 | 2020-01-08T08:08:26.000Z | 2021-03-19T22:59:46.000Z | wildlifecompliance/components/legal_case/serializers.py | preranaandure/wildlifecompliance | bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5 | [
"Apache-2.0"
] | 15 | 2020-01-08T08:02:28.000Z | 2021-11-03T06:48:32.000Z | import datetime
import traceback
import pytz
from rest_framework.fields import CharField
from ledger.accounts.models import EmailUser, Address
from wildlifecompliance.components.legal_case.models import (
LegalCase,
LegalCaseUserAction,
LegalCaseCommsLogEntry,
LegalCasePriority,
LegalCaseRunningSheetEntry,
LegalCasePerson,
CourtProceedingsJournalEntry,
CourtProceedings,
BriefOfEvidence,
ProsecutionBrief,
CourtDate, Court, CourtOutcomeType)
from wildlifecompliance.components.call_email.serializers import EmailUserSerializer
from wildlifecompliance.components.main.related_item import get_related_items
from wildlifecompliance.components.main.serializers import CommunicationLogEntrySerializer
from wildlifecompliance.components.users.serializers import (
ComplianceUserDetailsOptimisedSerializer,
CompliancePermissionGroupMembersSerializer
)
from rest_framework import serializers
from django.core.exceptions import ValidationError
from wildlifecompliance.components.main.fields import CustomChoiceField
from wildlifecompliance.components.offence.serializers import OffenceSerializer
from wildlifecompliance.components.users.serializers import (
ComplianceUserDetailsOptimisedSerializer,
CompliancePermissionGroupMembersSerializer,
UserAddressSerializer,
)
from wildlifecompliance.components.artifact.serializers import (
DocumentArtifactStatementSerializer,
PhysicalArtifactSerializer,
BriefOfEvidenceRecordOfInterviewSerializer,
BriefOfEvidenceOtherStatementsSerializer,
BriefOfEvidenceDocumentArtifactsSerializer,
BriefOfEvidencePhysicalArtifactsSerializer,
ProsecutionBriefRecordOfInterviewSerializer,
ProsecutionBriefOtherStatementsSerializer,
ProsecutionBriefDocumentArtifactsSerializer,
ProsecutionBriefPhysicalArtifactsSerializer,
)
from reversion.models import Version
from django.utils import timezone
class LegalCasePrioritySerializer(serializers.ModelSerializer):
class Meta:
model = LegalCasePriority
fields = ('__all__')
read_only_fields = (
'id',
)
class LegalCasePersonSerializer(serializers.ModelSerializer):
class Meta:
model = LegalCasePerson
fields = (
'id',
'legal_case_id',
)
read_only_fields = (
'id',
'legal_case_id',
)
class CreateLegalCasePersonSerializer(serializers.ModelSerializer):
legal_case_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCasePerson
fields = (
'id',
'legal_case_id',
)
read_only_fields = (
'id',
)
class VersionSerializer(serializers.ModelSerializer):
#serializable_value = serializers.JSONField()
entry_fields = serializers.SerializerMethodField()
date_modified = serializers.SerializerMethodField()
class Meta:
model = Version
#fields = '__all__'
fields = (
'id',
'revision',
'serialized_data',
'entry_fields',
'date_modified',
)
read_only_fields = (
'id',
'revision',
'serialized_data',
'entry_fields',
'date_modified',
)
def get_date_modified(self, obj):
date_modified = None
modified_fields = obj.field_dict
if modified_fields.get('date_modified'):
date_modified_utc = modified_fields.get('date_modified')
date_modified = timezone.localtime(date_modified_utc)
return date_modified
def get_entry_fields(self, obj):
modified_fields = obj.field_dict
user_full_name = ''
if modified_fields and obj.field_dict.get('user_id'):
user_obj = EmailUser.objects.get(id=obj.field_dict.get('user_id'))
user_full_name = user_obj.get_full_name()
modified_fields['user_full_name'] = user_full_name
if modified_fields.get('date_modified'):
date_modified_utc = modified_fields.get('date_modified')
date_modified = timezone.localtime(date_modified_utc)
modified_fields['date_mod'] = date_modified.strftime('%d/%m/%Y')
modified_fields['time_mod'] = date_modified.strftime('%I:%M:%S %p')
else:
modified_fields['date_mod'] = ''
modified_fields['time_mod'] = ''
return modified_fields
class JournalEntryHistorySerializer(serializers.ModelSerializer):
versions = serializers.SerializerMethodField()
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'versions',
)
def get_versions(self, obj):
entry_versions = VersionSerializer(
Version.objects.get_for_object(obj),
many=True)
return entry_versions.data
class CourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
user_full_name = serializers.SerializerMethodField()
date_mod = serializers.SerializerMethodField()
time_mod = serializers.SerializerMethodField()
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'court_proceedings_id',
'number',
'date_modified',
'date_mod',
'time_mod',
'user_full_name',
'user_id',
'description',
'deleted',
)
read_only_fields = (
'id',
)
def get_date_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%d/%m/%Y')
def get_time_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%I:%M:%S %p')
def get_user_full_name(self, obj):
user_full_name = ''
if obj.user:
user_full_name = obj.user.get_full_name()
return user_full_name
class SaveCourtDateEntrySerializer(serializers.ModelSerializer):
court_proceedings_id = serializers.IntegerField(required=False, write_only=True, allow_null=True)
court_id = serializers.IntegerField(required=False, write_only=True, allow_null=True)
class Meta:
model = CourtDate
fields = (
'court_proceedings_id',
'court_id',
'court_datetime',
'comments',
)
class SaveCourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'number',
'court_proceedings_id',
'user_id',
'description',
)
read_only_fields = (
'id',
'number',
'court_proceedings_id',
)
class DeleteReinstateCourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'number',
'court_proceedings_id',
'deleted',
)
read_only_fields = (
'id',
'number',
'court_proceedings_id',
)
class CreateCourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
court_proceedings_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'court_proceedings_id',
'user_id',
)
def create(self, validated_data):
court_proceedings_id = validated_data.get('court_proceedings_id')
user_id = validated_data.get('user_id')
new_entry = CourtProceedingsJournalEntry.objects.create_journal_entry(
court_proceedings_id=court_proceedings_id,
user_id=user_id)
return new_entry
class CourtSerializer(serializers.ModelSerializer):
class Meta:
model = Court
fields = (
'id',
'identifier',
'location',
'description',
)
class CourtOutcomeTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CourtOutcomeType
fields = (
'id',
'identifier',
'description',
)
class CourtOutcomeTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CourtOutcomeType
fields = (
'id',
'identifier',
'description',
)
class CourtProceedingsCourtDateSerializer(serializers.ModelSerializer):
court = CourtSerializer(read_only=True)
court_in_future = serializers.SerializerMethodField()
def get_court_in_future(self, obj):
if not obj.court_datetime:
return True
else:
now = datetime.datetime.now(pytz.utc)
return True if obj.court_datetime > now else False
class Meta:
model = CourtDate
fields = (
'id',
'court_datetime',
'comments',
'court',
'court_in_future',
)
class CourtProceedingsJournalSerializer(serializers.ModelSerializer):
journal_entries = CourtProceedingsJournalEntrySerializer(many=True, read_only=True)
court_outcome_type = CourtOutcomeTypeSerializer(read_only=True)
court_outcome_type_id = serializers.IntegerField(required=False, write_only=True, allow_null=True)
court_dates = serializers.SerializerMethodField()
class Meta:
model = CourtProceedings
fields = (
'id',
'court_outcome_details',
'journal_entries',
'court_dates',
'court_outcome_fines',
'court_outcome_costs',
'court_outcome_type',
'court_outcome_type_id',
)
read_only_fields = (
'id',
)
def get_court_dates(self, instance):
# Return court dates ordered by court_datetime
dates = instance.court_dates.all().order_by('court_datetime')
return CourtProceedingsCourtDateSerializer(dates, many=True).data
def validate(self, attrs):
return attrs
class RunningSheetEntryHistorySerializer(serializers.ModelSerializer):
versions = serializers.SerializerMethodField()
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'versions',
)
def get_versions(self, obj):
entry_versions = VersionSerializer(
Version.objects.get_for_object(obj),
many=True)
return entry_versions.data
class LegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
user_full_name = serializers.SerializerMethodField()
date_mod = serializers.SerializerMethodField()
time_mod = serializers.SerializerMethodField()
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'legal_case_id',
'number',
'date_modified',
'date_mod',
'time_mod',
'user_full_name',
'user_id',
'description',
'deleted',
)
read_only_fields = (
'id',
)
def get_date_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%d/%m/%Y')
def get_time_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%I:%M:%S %p')
def get_user_full_name(self, obj):
user_full_name = ''
if obj.user:
user_full_name = obj.user.get_full_name()
return user_full_name
class SaveLegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'number',
'legal_case_id',
'user_id',
'description',
)
read_only_fields = (
'id',
'number',
'legal_case_id',
)
class DeleteReinstateLegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'number',
'legal_case_id',
'deleted',
)
read_only_fields = (
'id',
'number',
'legal_case_id',
)
class CreateLegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
legal_case_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'legal_case_id',
'user_id',
)
def create(self, validated_data):
legal_case_id = validated_data.get('legal_case_id')
user_id = validated_data.get('user_id')
new_entry = LegalCaseRunningSheetEntry.objects.create_running_sheet_entry(
legal_case_id=legal_case_id,
user_id=user_id)
return new_entry
class LegalCaseRunningSheetSerializer(serializers.ModelSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
class Meta:
model = LegalCase
fields = (
'id',
'running_sheet_entries',
)
read_only_fields = (
'id',
)
class BriefOfEvidenceSerializer(serializers.ModelSerializer):
class Meta:
model = BriefOfEvidence
fields = (
'id',
'legal_case_id',
'statement_of_facts',
'victim_impact_statement_taken',
'statements_pending',
'vulnerable_hostile_witnesses',
'witness_refusing_statement',
'problems_needs_prosecution_witnesses',
'accused_bad_character',
'further_persons_interviews_pending',
'other_interviews',
'relevant_persons_pending_charges',
'other_persons_receiving_sanction_outcome',
'local_public_interest',
'applications_orders_requests',
'applications_orders_required',
'other_legal_matters',
'victim_impact_statement_taken_details',
'statements_pending_details',
'vulnerable_hostile_witnesses_details',
'witness_refusing_statement_details',
'problems_needs_prosecution_witnesses_details',
'accused_bad_character_details',
'further_persons_interviews_pending_details',
'other_interviews_details',
'relevant_persons_pending_charges_details',
'other_persons_receiving_sanction_outcome_details',
'local_public_interest_details',
'applications_orders_requests_details',
'applications_orders_required_details',
'other_legal_matters_details',
)
read_only_fields = (
'id',
'legal_case_id',
)
class ProsecutionBriefSerializer(serializers.ModelSerializer):
class Meta:
model = ProsecutionBrief
fields = (
'id',
'legal_case_id',
'statement_of_facts',
'victim_impact_statement_taken',
'statements_pending',
'vulnerable_hostile_witnesses',
'witness_refusing_statement',
'problems_needs_prosecution_witnesses',
'accused_bad_character',
'further_persons_interviews_pending',
'other_interviews',
'relevant_persons_pending_charges',
'other_persons_receiving_sanction_outcome',
'local_public_interest',
'applications_orders_requests',
'applications_orders_required',
'other_legal_matters',
'victim_impact_statement_taken_details',
'statements_pending_details',
'vulnerable_hostile_witnesses_details',
'witness_refusing_statement_details',
'problems_needs_prosecution_witnesses_details',
'accused_bad_character_details',
'further_persons_interviews_pending_details',
'other_interviews_details',
'relevant_persons_pending_charges_details',
'other_persons_receiving_sanction_outcome_details',
'local_public_interest_details',
'applications_orders_requests_details',
'applications_orders_required_details',
'other_legal_matters_details',
)
read_only_fields = (
'id',
'legal_case_id',
)
class LegalCaseNoRunningSheetSerializer(serializers.ModelSerializer):
#running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
legal_case_person = EmailUserSerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
#'running_sheet_entries',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
)
read_only_fields = (
'id',
)
def get_offence_list(self, obj):
offence_list = [{
'id': '',
'lodgement_number': '',
'identifier': '',
}]
offence_queryset = obj.offence_legal_case.all()
if offence_queryset and offence_queryset.first().id:
serializer = OffenceSerializer(offence_queryset, many=True, context=self.context)
offence_list.extend(serializer.data)
return offence_list
def get_statement_artifacts(self, obj):
artifact_list = []
for link in obj.documentartifactlegalcases_set.all():
if (link.primary and link.document_artifact.document_type and
link.document_artifact.document_type in [
'record_of_interview',
'witness_statement',
'expert_statement',
'officer_statement'
]):
serialized_artifact = DocumentArtifactStatementSerializer(link.document_artifact)
artifact_list.append(serialized_artifact.data)
return artifact_list
def get_related_items(self, obj):
return get_related_items(obj)
def get_user_in_group(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if obj.allocated_group:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_can_user_action(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
elif obj.allocated_group and not obj.assigned_to_id:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_user_is_assignee(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
return return_val
def get_allocated_group(self, obj):
allocated_group = [{
'email': '',
'first_name': '',
'full_name': '',
'id': None,
'last_name': '',
'title': '',
}]
returned_allocated_group = CompliancePermissionGroupMembersSerializer(instance=obj.allocated_group)
for member in returned_allocated_group.data['members']:
allocated_group.append(member)
return allocated_group
class BaseLegalCaseSerializer(serializers.ModelSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
legal_case_person = EmailUserSerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
'running_sheet_entries',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
)
read_only_fields = (
'id',
)
def get_offence_list(self, obj):
offence_list = [{
'id': '',
'lodgement_number': '',
'identifier': '',
}]
offence_queryset = obj.offence_legal_case.all()
if offence_queryset and offence_queryset.first().id:
serializer = OffenceSerializer(offence_queryset, many=True, context=self.context)
offence_list.extend(serializer.data)
return offence_list
def get_statement_artifacts(self, obj):
artifact_list = []
for link in obj.documentartifactlegalcases_set.all():
if (link.primary and link.document_artifact.document_type and
link.document_artifact.document_type in [
'record_of_interview',
'witness_statement',
'expert_statement',
'officer_statement'
]):
serialized_artifact = DocumentArtifactStatementSerializer(link.document_artifact)
artifact_list.append(serialized_artifact.data)
return artifact_list
def get_related_items(self, obj):
return get_related_items(obj)
def get_user_in_group(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if obj.allocated_group:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_can_user_action(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
elif obj.allocated_group and not obj.assigned_to_id:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_user_is_assignee(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
return return_val
def get_allocated_group(self, obj):
allocated_group = [{
'email': '',
'first_name': '',
'full_name': '',
'id': None,
'last_name': '',
'title': '',
}]
returned_allocated_group = CompliancePermissionGroupMembersSerializer(instance=obj.allocated_group)
for member in returned_allocated_group.data['members']:
allocated_group.append(member)
return allocated_group
class LegalCaseBriefOfEvidenceSerializer(BaseLegalCaseSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
boe_roi_ticked = serializers.SerializerMethodField()
boe_roi_options = serializers.SerializerMethodField()
boe_other_statements_ticked = serializers.SerializerMethodField()
boe_other_statements_options = serializers.SerializerMethodField()
legal_case_boe_other_statements = BriefOfEvidenceOtherStatementsSerializer(many=True)
legal_case_boe_roi = BriefOfEvidenceRecordOfInterviewSerializer(many=True)
brief_of_evidence = BriefOfEvidenceSerializer()
boe_physical_artifacts_used = serializers.SerializerMethodField()
boe_physical_artifacts_sensitive_unused = serializers.SerializerMethodField()
boe_physical_artifacts_non_sensitive_unused = serializers.SerializerMethodField()
boe_document_artifacts = serializers.SerializerMethodField()
boe_roi_readonly = serializers.SerializerMethodField()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
'running_sheet_entries',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
#'id',
#'running_sheet_entries',
##'legal_case_person',
#'allocated_group',
#'allocated_group_id',
#'user_in_group',
#'can_user_action',
#'user_is_assignee',
#'status',
#'related_items',
#'statement_artifacts',
#'legal_case_priority',
#'offence_list',
#'brief_of_evidence',
#'prosecution_brief',
#'court_proceedings',
#'district_id',
#'region_id',
'boe_roi_ticked',
'boe_roi_options',
'legal_case_boe_roi',
'boe_other_statements_ticked',
'boe_other_statements_options',
'legal_case_boe_other_statements',
'boe_physical_artifacts_used',
'boe_physical_artifacts_sensitive_unused',
'boe_physical_artifacts_non_sensitive_unused',
'boe_document_artifacts',
'boe_roi_readonly',
)
read_only_fields = (
'id',
)
def get_boe_document_artifacts(self, obj):
artifact_list = []
for artifact in obj.briefofevidencedocumentartifacts_set.all():
artifact_serializer = BriefOfEvidenceDocumentArtifactsSerializer(artifact)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
# used physical artifacts
def get_boe_physical_artifacts_used(self, obj):
artifact_list = []
for record in obj.briefofevidencephysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if legal_case_physical_artifact_link.used_within_case:
artifact_serializer = BriefOfEvidencePhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
# sensitive unused physical artifacts
def get_boe_physical_artifacts_sensitive_unused(self, obj):
artifact_list = []
for record in obj.briefofevidencephysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = BriefOfEvidencePhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
# non sensitive unused physical artifacts
def get_boe_physical_artifacts_non_sensitive_unused(self, obj):
artifact_list = []
for record in obj.briefofevidencephysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and not
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = BriefOfEvidencePhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_boe_other_statements_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_boe_other_statements.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_boe_other_statements_options(self, obj):
person_list = []
for person_level_record in obj.legal_case_boe_other_statements.filter(statement=None):
person_serializer = BriefOfEvidenceOtherStatementsSerializer(
person_level_record)
serialized_person = person_serializer.data
person_children = []
for statement_level_record in person_level_record.children.all():
statement_serializer = BriefOfEvidenceOtherStatementsSerializer(
statement_level_record)
serialized_statement = statement_serializer.data
statement_children = []
for doc_level_record in statement_level_record.children.all():
doc_serializer = BriefOfEvidenceOtherStatementsSerializer(
doc_level_record)
serialized_doc = doc_serializer.data
if serialized_doc:
statement_children.append(serialized_doc)
serialized_statement['children'] = statement_children
if serialized_statement:
person_children.append(serialized_statement)
serialized_person['children'] = person_children
person_list.append(serialized_person)
return person_list
def get_boe_roi_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_boe_roi.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_boe_roi_options(self, obj):
offence_list = []
for offence_level_record in obj.legal_case_boe_roi.filter(offender=None):
offence_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
offence_level_record)
serialized_offence = offence_serializer.data
offence_children = []
for offender_level_record in offence_level_record.children.all():
offender_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
offender_level_record)
serialized_offender = offender_serializer.data
offender_children = []
for roi_level_record in offender_level_record.children.all():
roi_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
roi_level_record)
serialized_roi = roi_serializer.data
roi_children = []
for doc_artifact_level_record in roi_level_record.children.all():
# check for associated docs and add to serialized_roi
doc_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
doc_artifact_level_record)
serialized_doc_artifact = doc_serializer.data
if serialized_doc_artifact:
roi_children.append(serialized_doc_artifact)
serialized_roi['children'] = roi_children
# add roi to offender_children
if serialized_roi:
#serialized_offender['children'] = serialized_roi
offender_children.append(serialized_roi)
# add roi list to offender
serialized_offender['children'] = offender_children
## add offender to offence_list
# add offender to offence
if serialized_offender:
offence_children.append(serialized_offender)
serialized_offence['children'] = offence_children
offence_list.append(serialized_offence)
return offence_list
def get_boe_roi_readonly(self, obj):
return '<a href="www.google.com">something</a>'
#class LegalCaseProsecutionBriefSerializer(BaseLegalCaseSerializer):
class LegalCaseProsecutionBriefSerializer(LegalCaseBriefOfEvidenceSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
pb_roi_ticked = serializers.SerializerMethodField()
pb_roi_options = serializers.SerializerMethodField()
pb_other_statements_ticked = serializers.SerializerMethodField()
pb_other_statements_options = serializers.SerializerMethodField()
legal_case_pb_other_statements = BriefOfEvidenceOtherStatementsSerializer(many=True)
legal_case_pb_roi = BriefOfEvidenceRecordOfInterviewSerializer(many=True)
brief_of_evidence = BriefOfEvidenceSerializer()
pb_physical_artifacts_used = serializers.SerializerMethodField()
pb_physical_artifacts_sensitive_unused = serializers.SerializerMethodField()
pb_physical_artifacts_non_sensitive_unused = serializers.SerializerMethodField()
pb_document_artifacts = serializers.SerializerMethodField()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
'running_sheet_entries',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
#'id',
#'running_sheet_entries',
##'legal_case_person',
#'allocated_group',
#'allocated_group_id',
#'user_in_group',
#'can_user_action',
#'user_is_assignee',
#'status',
#'related_items',
#'statement_artifacts',
#'legal_case_priority',
#'offence_list',
#'brief_of_evidence',
#'prosecution_brief',
#'court_proceedings',
#'district_id',
#'region_id',
'pb_roi_ticked',
'pb_roi_options',
'legal_case_pb_roi',
'pb_other_statements_ticked',
'pb_other_statements_options',
'legal_case_pb_other_statements',
'pb_physical_artifacts_used',
'pb_physical_artifacts_sensitive_unused',
'pb_physical_artifacts_non_sensitive_unused',
'pb_document_artifacts',
'boe_roi_ticked',
'boe_roi_options',
'boe_roi_readonly',
'legal_case_boe_roi',
'boe_other_statements_ticked',
'boe_other_statements_options',
'legal_case_boe_other_statements',
'boe_physical_artifacts_used',
'boe_physical_artifacts_sensitive_unused',
'boe_physical_artifacts_non_sensitive_unused',
'boe_document_artifacts',
)
read_only_fields = (
'id',
)
def get_pb_document_artifacts(self, obj):
artifact_list = []
for artifact in obj.prosecutionbriefdocumentartifacts_set.all():
artifact_serializer = ProsecutionBriefDocumentArtifactsSerializer(artifact)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
# used physical artifacts
def get_pb_physical_artifacts_used(self, obj):
artifact_list = []
for record in obj.prosecutionbriefphysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if legal_case_physical_artifact_link.used_within_case:
artifact_serializer = ProsecutionBriefPhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
# sensitive unused physical artifacts
def get_pb_physical_artifacts_sensitive_unused(self, obj):
artifact_list = []
for record in obj.prosecutionbriefphysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = ProsecutionBriefPhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
# non sensitive unused physical artifacts
def get_pb_physical_artifacts_non_sensitive_unused(self, obj):
artifact_list = []
for record in obj.prosecutionbriefphysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and not
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = ProsecutionBriefPhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_pb_other_statements_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_pb_other_statements.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_pb_other_statements_options(self, obj):
person_list = []
for person_level_record in obj.legal_case_pb_other_statements.filter(statement=None):
person_serializer = ProsecutionBriefOtherStatementsSerializer(
person_level_record)
serialized_person = person_serializer.data
person_children = []
for statement_level_record in person_level_record.children.all():
statement_serializer = ProsecutionBriefOtherStatementsSerializer(
statement_level_record)
serialized_statement = statement_serializer.data
statement_children = []
for doc_level_record in statement_level_record.children.all():
doc_serializer = ProsecutionBriefOtherStatementsSerializer(
doc_level_record)
serialized_doc = doc_serializer.data
if serialized_doc:
statement_children.append(serialized_doc)
serialized_statement['children'] = statement_children
if serialized_statement:
person_children.append(serialized_statement)
serialized_person['children'] = person_children
person_list.append(serialized_person)
return person_list
def get_pb_roi_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_pb_roi.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_pb_roi_options(self, obj):
offence_list = []
for offence_level_record in obj.legal_case_pb_roi.filter(offender=None):
offence_serializer = ProsecutionBriefRecordOfInterviewSerializer(
offence_level_record)
serialized_offence = offence_serializer.data
offence_children = []
for offender_level_record in offence_level_record.children.all():
offender_serializer = ProsecutionBriefRecordOfInterviewSerializer(
offender_level_record)
serialized_offender = offender_serializer.data
offender_children = []
for roi_level_record in offender_level_record.children.all():
roi_serializer = ProsecutionBriefRecordOfInterviewSerializer(
roi_level_record)
serialized_roi = roi_serializer.data
roi_children = []
for doc_artifact_level_record in roi_level_record.children.all():
# check for associated docs and add to serialized_roi
doc_serializer = ProsecutionBriefRecordOfInterviewSerializer(
doc_artifact_level_record)
serialized_doc_artifact = doc_serializer.data
if serialized_doc_artifact:
roi_children.append(serialized_doc_artifact)
serialized_roi['children'] = roi_children
# add roi to offender_children
if serialized_roi:
offender_children.append(serialized_roi)
# add roi list to offender
serialized_offender['children'] = offender_children
## add offender to offence_list
# add offender to offence
if serialized_offender:
offence_children.append(serialized_offender)
serialized_offence['children'] = offence_children
offence_list.append(serialized_offence)
return offence_list
def get_pb_roi_read_only(self, obj):
pass
class SaveLegalCaseSerializer(serializers.ModelSerializer):
#running_sheet_entries = SaveLegalCaseRunningSheetEntrySerializer(many=True)
assigned_to_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
allocated_group_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
call_email_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
legal_case_priority_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
def create(self, validated_data):
instance = super(SaveLegalCaseSerializer, self).create(validated_data)
return instance
class Meta:
model = LegalCase
fields = (
'id',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group_id',
'call_email_id',
'legal_case_priority_id',
)
read_only_fields = (
'id',
)
class LegalCaseUserActionSerializer(serializers.ModelSerializer):
who = serializers.CharField(source='who.get_full_name')
class Meta:
model = LegalCaseUserAction
fields = '__all__'
class LegalCaseCommsLogEntrySerializer(CommunicationLogEntrySerializer):
documents = serializers.SerializerMethodField()
class Meta:
model = LegalCaseCommsLogEntry
fields = '__all__'
read_only_fields = (
'customer',
)
def get_documents(self, obj):
return [[d.name, d._file.url] for d in obj.documents.all()]
class LegalCaseDatatableSerializer(serializers.ModelSerializer):
user_action = serializers.SerializerMethodField()
created_date = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
assigned_to = ComplianceUserDetailsOptimisedSerializer(read_only=True)
class Meta:
model = LegalCase
fields = (
'number',
'title',
'status',
'created_date',
'user_action',
'assigned_to',
'assigned_to_id',
)
def get_user_action(self, obj):
user_id = self.context.get('request', {}).user.id
view_url = '<a href=/internal/legal_case/' + str(obj.id) + '>View</a>'
process_url = '<a href=/internal/legal_case/' + str(obj.id) + '>Process</a>'
returned_url = ''
if obj.status == 'closed':
returned_url = view_url
elif user_id == obj.assigned_to_id:
returned_url = process_url
elif (obj.allocated_group
and not obj.assigned_to_id):
for member in obj.allocated_group.members:
if user_id == member.id:
returned_url = process_url
if not returned_url:
returned_url = view_url
return returned_url
def get_created_date(self, obj):
if obj.case_created_date:
if obj.case_created_time:
return obj.case_created_date.strftime("%d/%m/%Y") + ' ' + obj.case_created_time.strftime('%H:%M')
else:
return obj.case_created_date.strftime("%d/%m/%Y")
else:
return None
class UpdateAssignedToIdSerializer(serializers.ModelSerializer):
assigned_to_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCase
fields = (
'assigned_to_id',
)
| 37.92518 | 114 | 0.612471 | import datetime
import traceback
import pytz
from rest_framework.fields import CharField
from ledger.accounts.models import EmailUser, Address
from wildlifecompliance.components.legal_case.models import (
LegalCase,
LegalCaseUserAction,
LegalCaseCommsLogEntry,
LegalCasePriority,
LegalCaseRunningSheetEntry,
LegalCasePerson,
CourtProceedingsJournalEntry,
CourtProceedings,
BriefOfEvidence,
ProsecutionBrief,
CourtDate, Court, CourtOutcomeType)
from wildlifecompliance.components.call_email.serializers import EmailUserSerializer
from wildlifecompliance.components.main.related_item import get_related_items
from wildlifecompliance.components.main.serializers import CommunicationLogEntrySerializer
from wildlifecompliance.components.users.serializers import (
ComplianceUserDetailsOptimisedSerializer,
CompliancePermissionGroupMembersSerializer
)
from rest_framework import serializers
from django.core.exceptions import ValidationError
from wildlifecompliance.components.main.fields import CustomChoiceField
from wildlifecompliance.components.offence.serializers import OffenceSerializer
from wildlifecompliance.components.users.serializers import (
ComplianceUserDetailsOptimisedSerializer,
CompliancePermissionGroupMembersSerializer,
UserAddressSerializer,
)
from wildlifecompliance.components.artifact.serializers import (
DocumentArtifactStatementSerializer,
PhysicalArtifactSerializer,
BriefOfEvidenceRecordOfInterviewSerializer,
BriefOfEvidenceOtherStatementsSerializer,
BriefOfEvidenceDocumentArtifactsSerializer,
BriefOfEvidencePhysicalArtifactsSerializer,
ProsecutionBriefRecordOfInterviewSerializer,
ProsecutionBriefOtherStatementsSerializer,
ProsecutionBriefDocumentArtifactsSerializer,
ProsecutionBriefPhysicalArtifactsSerializer,
)
from reversion.models import Version
from django.utils import timezone
class LegalCasePrioritySerializer(serializers.ModelSerializer):
class Meta:
model = LegalCasePriority
fields = ('__all__')
read_only_fields = (
'id',
)
class LegalCasePersonSerializer(serializers.ModelSerializer):
class Meta:
model = LegalCasePerson
fields = (
'id',
'legal_case_id',
)
read_only_fields = (
'id',
'legal_case_id',
)
class CreateLegalCasePersonSerializer(serializers.ModelSerializer):
legal_case_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCasePerson
fields = (
'id',
'legal_case_id',
)
read_only_fields = (
'id',
)
class VersionSerializer(serializers.ModelSerializer):
entry_fields = serializers.SerializerMethodField()
date_modified = serializers.SerializerMethodField()
class Meta:
model = Version
fields = (
'id',
'revision',
'serialized_data',
'entry_fields',
'date_modified',
)
read_only_fields = (
'id',
'revision',
'serialized_data',
'entry_fields',
'date_modified',
)
def get_date_modified(self, obj):
date_modified = None
modified_fields = obj.field_dict
if modified_fields.get('date_modified'):
date_modified_utc = modified_fields.get('date_modified')
date_modified = timezone.localtime(date_modified_utc)
return date_modified
def get_entry_fields(self, obj):
modified_fields = obj.field_dict
user_full_name = ''
if modified_fields and obj.field_dict.get('user_id'):
user_obj = EmailUser.objects.get(id=obj.field_dict.get('user_id'))
user_full_name = user_obj.get_full_name()
modified_fields['user_full_name'] = user_full_name
if modified_fields.get('date_modified'):
date_modified_utc = modified_fields.get('date_modified')
date_modified = timezone.localtime(date_modified_utc)
modified_fields['date_mod'] = date_modified.strftime('%d/%m/%Y')
modified_fields['time_mod'] = date_modified.strftime('%I:%M:%S %p')
else:
modified_fields['date_mod'] = ''
modified_fields['time_mod'] = ''
return modified_fields
class JournalEntryHistorySerializer(serializers.ModelSerializer):
versions = serializers.SerializerMethodField()
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'versions',
)
def get_versions(self, obj):
entry_versions = VersionSerializer(
Version.objects.get_for_object(obj),
many=True)
return entry_versions.data
class CourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
user_full_name = serializers.SerializerMethodField()
date_mod = serializers.SerializerMethodField()
time_mod = serializers.SerializerMethodField()
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'court_proceedings_id',
'number',
'date_modified',
'date_mod',
'time_mod',
'user_full_name',
'user_id',
'description',
'deleted',
)
read_only_fields = (
'id',
)
def get_date_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%d/%m/%Y')
def get_time_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%I:%M:%S %p')
def get_user_full_name(self, obj):
user_full_name = ''
if obj.user:
user_full_name = obj.user.get_full_name()
return user_full_name
class SaveCourtDateEntrySerializer(serializers.ModelSerializer):
court_proceedings_id = serializers.IntegerField(required=False, write_only=True, allow_null=True)
court_id = serializers.IntegerField(required=False, write_only=True, allow_null=True)
class Meta:
model = CourtDate
fields = (
'court_proceedings_id',
'court_id',
'court_datetime',
'comments',
)
class SaveCourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'number',
'court_proceedings_id',
'user_id',
'description',
)
read_only_fields = (
'id',
'number',
'court_proceedings_id',
)
class DeleteReinstateCourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'id',
'number',
'court_proceedings_id',
'deleted',
)
read_only_fields = (
'id',
'number',
'court_proceedings_id',
)
class CreateCourtProceedingsJournalEntrySerializer(serializers.ModelSerializer):
court_proceedings_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = CourtProceedingsJournalEntry
fields = (
'court_proceedings_id',
'user_id',
)
def create(self, validated_data):
court_proceedings_id = validated_data.get('court_proceedings_id')
user_id = validated_data.get('user_id')
new_entry = CourtProceedingsJournalEntry.objects.create_journal_entry(
court_proceedings_id=court_proceedings_id,
user_id=user_id)
return new_entry
class CourtSerializer(serializers.ModelSerializer):
class Meta:
model = Court
fields = (
'id',
'identifier',
'location',
'description',
)
class CourtOutcomeTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CourtOutcomeType
fields = (
'id',
'identifier',
'description',
)
class CourtOutcomeTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CourtOutcomeType
fields = (
'id',
'identifier',
'description',
)
class CourtProceedingsCourtDateSerializer(serializers.ModelSerializer):
court = CourtSerializer(read_only=True)
court_in_future = serializers.SerializerMethodField()
def get_court_in_future(self, obj):
if not obj.court_datetime:
return True
else:
now = datetime.datetime.now(pytz.utc)
return True if obj.court_datetime > now else False
class Meta:
model = CourtDate
fields = (
'id',
'court_datetime',
'comments',
'court',
'court_in_future',
)
class CourtProceedingsJournalSerializer(serializers.ModelSerializer):
journal_entries = CourtProceedingsJournalEntrySerializer(many=True, read_only=True)
court_outcome_type = CourtOutcomeTypeSerializer(read_only=True)
court_outcome_type_id = serializers.IntegerField(required=False, write_only=True, allow_null=True)
court_dates = serializers.SerializerMethodField()
class Meta:
model = CourtProceedings
fields = (
'id',
'court_outcome_details',
'journal_entries',
'court_dates',
'court_outcome_fines',
'court_outcome_costs',
'court_outcome_type',
'court_outcome_type_id',
)
read_only_fields = (
'id',
)
def get_court_dates(self, instance):
dates = instance.court_dates.all().order_by('court_datetime')
return CourtProceedingsCourtDateSerializer(dates, many=True).data
def validate(self, attrs):
return attrs
class RunningSheetEntryHistorySerializer(serializers.ModelSerializer):
versions = serializers.SerializerMethodField()
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'versions',
)
def get_versions(self, obj):
entry_versions = VersionSerializer(
Version.objects.get_for_object(obj),
many=True)
return entry_versions.data
class LegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
user_full_name = serializers.SerializerMethodField()
date_mod = serializers.SerializerMethodField()
time_mod = serializers.SerializerMethodField()
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'legal_case_id',
'number',
'date_modified',
'date_mod',
'time_mod',
'user_full_name',
'user_id',
'description',
'deleted',
)
read_only_fields = (
'id',
)
def get_date_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%d/%m/%Y')
def get_time_mod(self, obj):
date_modified_loc = timezone.localtime(obj.date_modified)
return date_modified_loc.strftime('%I:%M:%S %p')
def get_user_full_name(self, obj):
user_full_name = ''
if obj.user:
user_full_name = obj.user.get_full_name()
return user_full_name
class SaveLegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'number',
'legal_case_id',
'user_id',
'description',
)
read_only_fields = (
'id',
'number',
'legal_case_id',
)
class DeleteReinstateLegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'id',
'number',
'legal_case_id',
'deleted',
)
read_only_fields = (
'id',
'number',
'legal_case_id',
)
class CreateLegalCaseRunningSheetEntrySerializer(serializers.ModelSerializer):
legal_case_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
user_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCaseRunningSheetEntry
fields = (
'legal_case_id',
'user_id',
)
def create(self, validated_data):
legal_case_id = validated_data.get('legal_case_id')
user_id = validated_data.get('user_id')
new_entry = LegalCaseRunningSheetEntry.objects.create_running_sheet_entry(
legal_case_id=legal_case_id,
user_id=user_id)
return new_entry
class LegalCaseRunningSheetSerializer(serializers.ModelSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
class Meta:
model = LegalCase
fields = (
'id',
'running_sheet_entries',
)
read_only_fields = (
'id',
)
class BriefOfEvidenceSerializer(serializers.ModelSerializer):
class Meta:
model = BriefOfEvidence
fields = (
'id',
'legal_case_id',
'statement_of_facts',
'victim_impact_statement_taken',
'statements_pending',
'vulnerable_hostile_witnesses',
'witness_refusing_statement',
'problems_needs_prosecution_witnesses',
'accused_bad_character',
'further_persons_interviews_pending',
'other_interviews',
'relevant_persons_pending_charges',
'other_persons_receiving_sanction_outcome',
'local_public_interest',
'applications_orders_requests',
'applications_orders_required',
'other_legal_matters',
'victim_impact_statement_taken_details',
'statements_pending_details',
'vulnerable_hostile_witnesses_details',
'witness_refusing_statement_details',
'problems_needs_prosecution_witnesses_details',
'accused_bad_character_details',
'further_persons_interviews_pending_details',
'other_interviews_details',
'relevant_persons_pending_charges_details',
'other_persons_receiving_sanction_outcome_details',
'local_public_interest_details',
'applications_orders_requests_details',
'applications_orders_required_details',
'other_legal_matters_details',
)
read_only_fields = (
'id',
'legal_case_id',
)
class ProsecutionBriefSerializer(serializers.ModelSerializer):
class Meta:
model = ProsecutionBrief
fields = (
'id',
'legal_case_id',
'statement_of_facts',
'victim_impact_statement_taken',
'statements_pending',
'vulnerable_hostile_witnesses',
'witness_refusing_statement',
'problems_needs_prosecution_witnesses',
'accused_bad_character',
'further_persons_interviews_pending',
'other_interviews',
'relevant_persons_pending_charges',
'other_persons_receiving_sanction_outcome',
'local_public_interest',
'applications_orders_requests',
'applications_orders_required',
'other_legal_matters',
'victim_impact_statement_taken_details',
'statements_pending_details',
'vulnerable_hostile_witnesses_details',
'witness_refusing_statement_details',
'problems_needs_prosecution_witnesses_details',
'accused_bad_character_details',
'further_persons_interviews_pending_details',
'other_interviews_details',
'relevant_persons_pending_charges_details',
'other_persons_receiving_sanction_outcome_details',
'local_public_interest_details',
'applications_orders_requests_details',
'applications_orders_required_details',
'other_legal_matters_details',
)
read_only_fields = (
'id',
'legal_case_id',
)
class LegalCaseNoRunningSheetSerializer(serializers.ModelSerializer):
legal_case_person = EmailUserSerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
)
read_only_fields = (
'id',
)
def get_offence_list(self, obj):
offence_list = [{
'id': '',
'lodgement_number': '',
'identifier': '',
}]
offence_queryset = obj.offence_legal_case.all()
if offence_queryset and offence_queryset.first().id:
serializer = OffenceSerializer(offence_queryset, many=True, context=self.context)
offence_list.extend(serializer.data)
return offence_list
def get_statement_artifacts(self, obj):
artifact_list = []
for link in obj.documentartifactlegalcases_set.all():
if (link.primary and link.document_artifact.document_type and
link.document_artifact.document_type in [
'record_of_interview',
'witness_statement',
'expert_statement',
'officer_statement'
]):
serialized_artifact = DocumentArtifactStatementSerializer(link.document_artifact)
artifact_list.append(serialized_artifact.data)
return artifact_list
def get_related_items(self, obj):
return get_related_items(obj)
def get_user_in_group(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if obj.allocated_group:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_can_user_action(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
elif obj.allocated_group and not obj.assigned_to_id:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_user_is_assignee(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
return return_val
def get_allocated_group(self, obj):
allocated_group = [{
'email': '',
'first_name': '',
'full_name': '',
'id': None,
'last_name': '',
'title': '',
}]
returned_allocated_group = CompliancePermissionGroupMembersSerializer(instance=obj.allocated_group)
for member in returned_allocated_group.data['members']:
allocated_group.append(member)
return allocated_group
class BaseLegalCaseSerializer(serializers.ModelSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
legal_case_person = EmailUserSerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
'running_sheet_entries',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
)
read_only_fields = (
'id',
)
def get_offence_list(self, obj):
offence_list = [{
'id': '',
'lodgement_number': '',
'identifier': '',
}]
offence_queryset = obj.offence_legal_case.all()
if offence_queryset and offence_queryset.first().id:
serializer = OffenceSerializer(offence_queryset, many=True, context=self.context)
offence_list.extend(serializer.data)
return offence_list
def get_statement_artifacts(self, obj):
artifact_list = []
for link in obj.documentartifactlegalcases_set.all():
if (link.primary and link.document_artifact.document_type and
link.document_artifact.document_type in [
'record_of_interview',
'witness_statement',
'expert_statement',
'officer_statement'
]):
serialized_artifact = DocumentArtifactStatementSerializer(link.document_artifact)
artifact_list.append(serialized_artifact.data)
return artifact_list
def get_related_items(self, obj):
return get_related_items(obj)
def get_user_in_group(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if obj.allocated_group:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_can_user_action(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
elif obj.allocated_group and not obj.assigned_to_id:
for member in obj.allocated_group.members:
if user_id == member.id:
return_val = True
return return_val
def get_user_is_assignee(self, obj):
return_val = False
user_id = self.context.get('request', {}).user.id
if user_id == obj.assigned_to_id:
return_val = True
return return_val
def get_allocated_group(self, obj):
allocated_group = [{
'email': '',
'first_name': '',
'full_name': '',
'id': None,
'last_name': '',
'title': '',
}]
returned_allocated_group = CompliancePermissionGroupMembersSerializer(instance=obj.allocated_group)
for member in returned_allocated_group.data['members']:
allocated_group.append(member)
return allocated_group
class LegalCaseBriefOfEvidenceSerializer(BaseLegalCaseSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
boe_roi_ticked = serializers.SerializerMethodField()
boe_roi_options = serializers.SerializerMethodField()
boe_other_statements_ticked = serializers.SerializerMethodField()
boe_other_statements_options = serializers.SerializerMethodField()
legal_case_boe_other_statements = BriefOfEvidenceOtherStatementsSerializer(many=True)
legal_case_boe_roi = BriefOfEvidenceRecordOfInterviewSerializer(many=True)
brief_of_evidence = BriefOfEvidenceSerializer()
boe_physical_artifacts_used = serializers.SerializerMethodField()
boe_physical_artifacts_sensitive_unused = serializers.SerializerMethodField()
boe_physical_artifacts_non_sensitive_unused = serializers.SerializerMethodField()
boe_document_artifacts = serializers.SerializerMethodField()
boe_roi_readonly = serializers.SerializerMethodField()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
'running_sheet_entries',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
'boe_roi_ticked',
'boe_roi_options',
'legal_case_boe_roi',
'boe_other_statements_ticked',
'boe_other_statements_options',
'legal_case_boe_other_statements',
'boe_physical_artifacts_used',
'boe_physical_artifacts_sensitive_unused',
'boe_physical_artifacts_non_sensitive_unused',
'boe_document_artifacts',
'boe_roi_readonly',
)
read_only_fields = (
'id',
)
def get_boe_document_artifacts(self, obj):
artifact_list = []
for artifact in obj.briefofevidencedocumentartifacts_set.all():
artifact_serializer = BriefOfEvidenceDocumentArtifactsSerializer(artifact)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_boe_physical_artifacts_used(self, obj):
artifact_list = []
for record in obj.briefofevidencephysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if legal_case_physical_artifact_link.used_within_case:
artifact_serializer = BriefOfEvidencePhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_boe_physical_artifacts_sensitive_unused(self, obj):
artifact_list = []
for record in obj.briefofevidencephysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = BriefOfEvidencePhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_boe_physical_artifacts_non_sensitive_unused(self, obj):
artifact_list = []
for record in obj.briefofevidencephysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and not
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = BriefOfEvidencePhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_boe_other_statements_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_boe_other_statements.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_boe_other_statements_options(self, obj):
person_list = []
for person_level_record in obj.legal_case_boe_other_statements.filter(statement=None):
person_serializer = BriefOfEvidenceOtherStatementsSerializer(
person_level_record)
serialized_person = person_serializer.data
person_children = []
for statement_level_record in person_level_record.children.all():
statement_serializer = BriefOfEvidenceOtherStatementsSerializer(
statement_level_record)
serialized_statement = statement_serializer.data
statement_children = []
for doc_level_record in statement_level_record.children.all():
doc_serializer = BriefOfEvidenceOtherStatementsSerializer(
doc_level_record)
serialized_doc = doc_serializer.data
if serialized_doc:
statement_children.append(serialized_doc)
serialized_statement['children'] = statement_children
if serialized_statement:
person_children.append(serialized_statement)
serialized_person['children'] = person_children
person_list.append(serialized_person)
return person_list
def get_boe_roi_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_boe_roi.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_boe_roi_options(self, obj):
offence_list = []
for offence_level_record in obj.legal_case_boe_roi.filter(offender=None):
offence_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
offence_level_record)
serialized_offence = offence_serializer.data
offence_children = []
for offender_level_record in offence_level_record.children.all():
offender_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
offender_level_record)
serialized_offender = offender_serializer.data
offender_children = []
for roi_level_record in offender_level_record.children.all():
roi_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
roi_level_record)
serialized_roi = roi_serializer.data
roi_children = []
for doc_artifact_level_record in roi_level_record.children.all():
doc_serializer = BriefOfEvidenceRecordOfInterviewSerializer(
doc_artifact_level_record)
serialized_doc_artifact = doc_serializer.data
if serialized_doc_artifact:
roi_children.append(serialized_doc_artifact)
serialized_roi['children'] = roi_children
if serialized_roi:
offender_children.append(serialized_roi)
serialized_offender['children'] = offender_children
if serialized_offender:
offence_children.append(serialized_offender)
serialized_offence['children'] = offence_children
offence_list.append(serialized_offence)
return offence_list
def get_boe_roi_readonly(self, obj):
return '<a href="www.google.com">something</a>'
class LegalCaseProsecutionBriefSerializer(LegalCaseBriefOfEvidenceSerializer):
running_sheet_entries = LegalCaseRunningSheetEntrySerializer(many=True)
allocated_group = serializers.SerializerMethodField()
user_in_group = serializers.SerializerMethodField()
can_user_action = serializers.SerializerMethodField()
user_is_assignee = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
related_items = serializers.SerializerMethodField()
statement_artifacts = serializers.SerializerMethodField()
legal_case_priority = LegalCasePrioritySerializer()
offence_list = serializers.SerializerMethodField()
brief_of_evidence = BriefOfEvidenceSerializer()
prosecution_brief = ProsecutionBriefSerializer()
court_proceedings = CourtProceedingsJournalSerializer()
pb_roi_ticked = serializers.SerializerMethodField()
pb_roi_options = serializers.SerializerMethodField()
pb_other_statements_ticked = serializers.SerializerMethodField()
pb_other_statements_options = serializers.SerializerMethodField()
legal_case_pb_other_statements = BriefOfEvidenceOtherStatementsSerializer(many=True)
legal_case_pb_roi = BriefOfEvidenceRecordOfInterviewSerializer(many=True)
brief_of_evidence = BriefOfEvidenceSerializer()
pb_physical_artifacts_used = serializers.SerializerMethodField()
pb_physical_artifacts_sensitive_unused = serializers.SerializerMethodField()
pb_physical_artifacts_non_sensitive_unused = serializers.SerializerMethodField()
pb_document_artifacts = serializers.SerializerMethodField()
class Meta:
model = LegalCase
fields = (
'id',
'number',
'status',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group',
'allocated_group_id',
'user_in_group',
'can_user_action',
'user_is_assignee',
'related_items',
'call_email_id',
'region_id',
'district_id',
'legal_case_priority',
'legal_case_priority_id',
'running_sheet_entries',
'statement_artifacts',
'legal_case_person',
'offence_list',
'brief_of_evidence',
'prosecution_brief',
'court_proceedings',
'pb_roi_ticked',
'pb_roi_options',
'legal_case_pb_roi',
'pb_other_statements_ticked',
'pb_other_statements_options',
'legal_case_pb_other_statements',
'pb_physical_artifacts_used',
'pb_physical_artifacts_sensitive_unused',
'pb_physical_artifacts_non_sensitive_unused',
'pb_document_artifacts',
'boe_roi_ticked',
'boe_roi_options',
'boe_roi_readonly',
'legal_case_boe_roi',
'boe_other_statements_ticked',
'boe_other_statements_options',
'legal_case_boe_other_statements',
'boe_physical_artifacts_used',
'boe_physical_artifacts_sensitive_unused',
'boe_physical_artifacts_non_sensitive_unused',
'boe_document_artifacts',
)
read_only_fields = (
'id',
)
def get_pb_document_artifacts(self, obj):
artifact_list = []
for artifact in obj.prosecutionbriefdocumentartifacts_set.all():
artifact_serializer = ProsecutionBriefDocumentArtifactsSerializer(artifact)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_pb_physical_artifacts_used(self, obj):
artifact_list = []
for record in obj.prosecutionbriefphysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if legal_case_physical_artifact_link.used_within_case:
artifact_serializer = ProsecutionBriefPhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_pb_physical_artifacts_sensitive_unused(self, obj):
artifact_list = []
for record in obj.prosecutionbriefphysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = ProsecutionBriefPhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_pb_physical_artifacts_non_sensitive_unused(self, obj):
artifact_list = []
for record in obj.prosecutionbriefphysicalartifacts_set.all():
legal_case_physical_artifact_link = obj.physicalartifactlegalcases_set.get(
legal_case_id=obj.id,
physical_artifact_id=record.physical_artifact.id)
if (not legal_case_physical_artifact_link.used_within_case and not
legal_case_physical_artifact_link.sensitive_non_disclosable
):
artifact_serializer = ProsecutionBriefPhysicalArtifactsSerializer(record)
serialized_artifact = artifact_serializer.data
artifact_list.append(serialized_artifact)
return artifact_list
def get_pb_other_statements_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_pb_other_statements.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_pb_other_statements_options(self, obj):
person_list = []
for person_level_record in obj.legal_case_pb_other_statements.filter(statement=None):
person_serializer = ProsecutionBriefOtherStatementsSerializer(
person_level_record)
serialized_person = person_serializer.data
person_children = []
for statement_level_record in person_level_record.children.all():
statement_serializer = ProsecutionBriefOtherStatementsSerializer(
statement_level_record)
serialized_statement = statement_serializer.data
statement_children = []
for doc_level_record in statement_level_record.children.all():
doc_serializer = ProsecutionBriefOtherStatementsSerializer(
doc_level_record)
serialized_doc = doc_serializer.data
if serialized_doc:
statement_children.append(serialized_doc)
serialized_statement['children'] = statement_children
if serialized_statement:
person_children.append(serialized_statement)
serialized_person['children'] = person_children
person_list.append(serialized_person)
return person_list
def get_pb_roi_ticked(self, obj):
ticked_list = []
for record in obj.legal_case_pb_roi.all():
if record.ticked:
ticked_list.append(record.id)
return ticked_list
def get_pb_roi_options(self, obj):
offence_list = []
for offence_level_record in obj.legal_case_pb_roi.filter(offender=None):
offence_serializer = ProsecutionBriefRecordOfInterviewSerializer(
offence_level_record)
serialized_offence = offence_serializer.data
offence_children = []
for offender_level_record in offence_level_record.children.all():
offender_serializer = ProsecutionBriefRecordOfInterviewSerializer(
offender_level_record)
serialized_offender = offender_serializer.data
offender_children = []
for roi_level_record in offender_level_record.children.all():
roi_serializer = ProsecutionBriefRecordOfInterviewSerializer(
roi_level_record)
serialized_roi = roi_serializer.data
roi_children = []
for doc_artifact_level_record in roi_level_record.children.all():
doc_serializer = ProsecutionBriefRecordOfInterviewSerializer(
doc_artifact_level_record)
serialized_doc_artifact = doc_serializer.data
if serialized_doc_artifact:
roi_children.append(serialized_doc_artifact)
serialized_roi['children'] = roi_children
if serialized_roi:
offender_children.append(serialized_roi)
serialized_offender['children'] = offender_children
if serialized_offender:
offence_children.append(serialized_offender)
serialized_offence['children'] = offence_children
offence_list.append(serialized_offence)
return offence_list
def get_pb_roi_read_only(self, obj):
pass
class SaveLegalCaseSerializer(serializers.ModelSerializer):
assigned_to_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
allocated_group_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
call_email_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
legal_case_priority_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
def create(self, validated_data):
instance = super(SaveLegalCaseSerializer, self).create(validated_data)
return instance
class Meta:
model = LegalCase
fields = (
'id',
'title',
'details',
'case_created_date',
'case_created_time',
'assigned_to_id',
'allocated_group_id',
'call_email_id',
'legal_case_priority_id',
)
read_only_fields = (
'id',
)
class LegalCaseUserActionSerializer(serializers.ModelSerializer):
who = serializers.CharField(source='who.get_full_name')
class Meta:
model = LegalCaseUserAction
fields = '__all__'
class LegalCaseCommsLogEntrySerializer(CommunicationLogEntrySerializer):
documents = serializers.SerializerMethodField()
class Meta:
model = LegalCaseCommsLogEntry
fields = '__all__'
read_only_fields = (
'customer',
)
def get_documents(self, obj):
return [[d.name, d._file.url] for d in obj.documents.all()]
class LegalCaseDatatableSerializer(serializers.ModelSerializer):
user_action = serializers.SerializerMethodField()
created_date = serializers.SerializerMethodField()
status = CustomChoiceField(read_only=True)
assigned_to = ComplianceUserDetailsOptimisedSerializer(read_only=True)
class Meta:
model = LegalCase
fields = (
'number',
'title',
'status',
'created_date',
'user_action',
'assigned_to',
'assigned_to_id',
)
def get_user_action(self, obj):
user_id = self.context.get('request', {}).user.id
view_url = '<a href=/internal/legal_case/' + str(obj.id) + '>View</a>'
process_url = '<a href=/internal/legal_case/' + str(obj.id) + '>Process</a>'
returned_url = ''
if obj.status == 'closed':
returned_url = view_url
elif user_id == obj.assigned_to_id:
returned_url = process_url
elif (obj.allocated_group
and not obj.assigned_to_id):
for member in obj.allocated_group.members:
if user_id == member.id:
returned_url = process_url
if not returned_url:
returned_url = view_url
return returned_url
def get_created_date(self, obj):
if obj.case_created_date:
if obj.case_created_time:
return obj.case_created_date.strftime("%d/%m/%Y") + ' ' + obj.case_created_time.strftime('%H:%M')
else:
return obj.case_created_date.strftime("%d/%m/%Y")
else:
return None
class UpdateAssignedToIdSerializer(serializers.ModelSerializer):
assigned_to_id = serializers.IntegerField(
required=False, write_only=True, allow_null=True)
class Meta:
model = LegalCase
fields = (
'assigned_to_id',
)
| true | true |
f72a264bb94bb5718618a67a096c5366fb3374f5 | 2,620 | py | Python | google/cloud/speech/v1p1beta1/speech-v1p1beta1-py/google/cloud/speech_v1p1beta1/types/__init__.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/speech/v1p1beta1/speech-v1p1beta1-py/google/cloud/speech_v1p1beta1/types/__init__.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/speech/v1p1beta1/speech-v1p1beta1-py/google/cloud/speech_v1p1beta1/types/__init__.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 .cloud_speech import (
LongRunningRecognizeMetadata,
LongRunningRecognizeRequest,
LongRunningRecognizeResponse,
RecognitionAudio,
RecognitionConfig,
RecognitionMetadata,
RecognizeRequest,
RecognizeResponse,
SpeakerDiarizationConfig,
SpeechContext,
SpeechRecognitionAlternative,
SpeechRecognitionResult,
StreamingRecognitionConfig,
StreamingRecognitionResult,
StreamingRecognizeRequest,
StreamingRecognizeResponse,
TranscriptOutputConfig,
WordInfo,
)
from .cloud_speech_adaptation import (
CreateCustomClassRequest,
CreatePhraseSetRequest,
DeleteCustomClassRequest,
DeletePhraseSetRequest,
GetCustomClassRequest,
GetPhraseSetRequest,
ListCustomClassesRequest,
ListCustomClassesResponse,
ListPhraseSetRequest,
ListPhraseSetResponse,
UpdateCustomClassRequest,
UpdatePhraseSetRequest,
)
from .resource import (
CustomClass,
PhraseSet,
SpeechAdaptation,
TranscriptNormalization,
)
__all__ = (
'LongRunningRecognizeMetadata',
'LongRunningRecognizeRequest',
'LongRunningRecognizeResponse',
'RecognitionAudio',
'RecognitionConfig',
'RecognitionMetadata',
'RecognizeRequest',
'RecognizeResponse',
'SpeakerDiarizationConfig',
'SpeechContext',
'SpeechRecognitionAlternative',
'SpeechRecognitionResult',
'StreamingRecognitionConfig',
'StreamingRecognitionResult',
'StreamingRecognizeRequest',
'StreamingRecognizeResponse',
'TranscriptOutputConfig',
'WordInfo',
'CreateCustomClassRequest',
'CreatePhraseSetRequest',
'DeleteCustomClassRequest',
'DeletePhraseSetRequest',
'GetCustomClassRequest',
'GetPhraseSetRequest',
'ListCustomClassesRequest',
'ListCustomClassesResponse',
'ListPhraseSetRequest',
'ListPhraseSetResponse',
'UpdateCustomClassRequest',
'UpdatePhraseSetRequest',
'CustomClass',
'PhraseSet',
'SpeechAdaptation',
'TranscriptNormalization',
)
| 28.172043 | 74 | 0.748092 |
from .cloud_speech import (
LongRunningRecognizeMetadata,
LongRunningRecognizeRequest,
LongRunningRecognizeResponse,
RecognitionAudio,
RecognitionConfig,
RecognitionMetadata,
RecognizeRequest,
RecognizeResponse,
SpeakerDiarizationConfig,
SpeechContext,
SpeechRecognitionAlternative,
SpeechRecognitionResult,
StreamingRecognitionConfig,
StreamingRecognitionResult,
StreamingRecognizeRequest,
StreamingRecognizeResponse,
TranscriptOutputConfig,
WordInfo,
)
from .cloud_speech_adaptation import (
CreateCustomClassRequest,
CreatePhraseSetRequest,
DeleteCustomClassRequest,
DeletePhraseSetRequest,
GetCustomClassRequest,
GetPhraseSetRequest,
ListCustomClassesRequest,
ListCustomClassesResponse,
ListPhraseSetRequest,
ListPhraseSetResponse,
UpdateCustomClassRequest,
UpdatePhraseSetRequest,
)
from .resource import (
CustomClass,
PhraseSet,
SpeechAdaptation,
TranscriptNormalization,
)
__all__ = (
'LongRunningRecognizeMetadata',
'LongRunningRecognizeRequest',
'LongRunningRecognizeResponse',
'RecognitionAudio',
'RecognitionConfig',
'RecognitionMetadata',
'RecognizeRequest',
'RecognizeResponse',
'SpeakerDiarizationConfig',
'SpeechContext',
'SpeechRecognitionAlternative',
'SpeechRecognitionResult',
'StreamingRecognitionConfig',
'StreamingRecognitionResult',
'StreamingRecognizeRequest',
'StreamingRecognizeResponse',
'TranscriptOutputConfig',
'WordInfo',
'CreateCustomClassRequest',
'CreatePhraseSetRequest',
'DeleteCustomClassRequest',
'DeletePhraseSetRequest',
'GetCustomClassRequest',
'GetPhraseSetRequest',
'ListCustomClassesRequest',
'ListCustomClassesResponse',
'ListPhraseSetRequest',
'ListPhraseSetResponse',
'UpdateCustomClassRequest',
'UpdatePhraseSetRequest',
'CustomClass',
'PhraseSet',
'SpeechAdaptation',
'TranscriptNormalization',
)
| true | true |
f72a26dfc31e2ceb7e66c055421e71cb651c6797 | 3,810 | py | Python | Beams/Cantilever Beam - End Loaded.py | vsriv90/mechanical_engineering | c922cdce1a595e9acb6a87cf415fb3685caf51a3 | [
"MIT"
] | 1 | 2021-11-03T06:37:44.000Z | 2021-11-03T06:37:44.000Z | Beams/Cantilever Beam - End Loaded.py | vsriv90/mechanical_engineering | c922cdce1a595e9acb6a87cf415fb3685caf51a3 | [
"MIT"
] | null | null | null | Beams/Cantilever Beam - End Loaded.py | vsriv90/mechanical_engineering | c922cdce1a595e9acb6a87cf415fb3685caf51a3 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
# # Cantilever beams - End Loaded
# 
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn # to draw plots
# import plotly.express as px
# import csv
# import sympy
from PIL import Image
# SIMPLY SUPPORTED BEAM - Single Load: PARAMETERS
f = 700 # Value of load
l = 100 # Total length of beam
UnitF = str('N') # To show units of force
UnitL = str("mm") # To show units of length
# In[16]:
x = [0,l]
y = [0,0]
# plotting the points on X axis
plt.plot(x, y,label = "Beam", color='green', linewidth = 10,marker='o', markerfacecolor='blue', markersize=15)
plt.legend() # giving a legend to my graph
##################### ENTERING LOADS TO GRAPH #####################
# fig,ax = plt.subplots(1)
AvX = [0,0] # x-axis values
AvY = [f/2,-f/2] # corresponding y-axis values
plt.plot(AvX, AvY, linestyle='--',marker='s',markersize=10, color='grey') # To create the reaction line
plt.text(1,-f,str(round(f,2))+UnitF) # To show the values on the points
LoadX = [l,l]
LoadY = [0,f]
plt.plot(LoadX, LoadY, linestyle='--',marker='v',markersize=10) # To create the force line
plt.text(l,f+1,str(round(f,2))+UnitF) # (Coordiante x, Coordinate y,the value in text+Unit)
SupportX = [0]
SupportY = [0]
plt.plot(SupportX, SupportX,marker='s',markersize=25) # To create the force line
plt.text(-2,20,"RIGID") # (Coordiante x, Coordinate y,the text)
#################### End of load entering ###########################
# AXIS LEGENDS
plt.xlabel('Beam length in '+ UnitL)
plt.title('Loads on beam') # giving a title to graph
plt.ylim(top=1.5*f) # to set maximum y-axis value
plt.ylim(bottom=-1.5*f) # to set minimum y-axis value
plt.gca().axes.get_yaxis().set_visible(False) # Make y-aixs values visible or invisible
plt.show() # function to show the plot
# ---------------------------------------------------------------------
# SHEAR FORCE DIAGRAM
ShearX = [0,0,l,l]
ShearY = [0,f,f,0]
plt.plot(ShearX, ShearY, linestyle='--', marker='o') #plotting the points on X axis
# To show the values on the points
plt.text(0,0,str(0)+UnitF) # (Coordiante x, Coordinate y,the value in text+Unit) # point 1
plt.text(0,f,str(round(f,2))+UnitF) # point 2, with integers rounded off
plt.text(l,f,str(round(f,2))+UnitF) # point 3
plt.text(l,0,str(0)+UnitF) # point 4
# Plotting the 0 line
ZeroLX = [0,l]
ZeroLY = [0,0]
plt.plot(ZeroLX, ZeroLY, color='black') # plotting the line 2 points
# OVERALL DETAILS FOR THE GRAPH
plt.xlabel('Position along the beam')
plt.title('Shear/Transverse Force Diagram') # giving a title to graph
plt.gca().axes.get_yaxis().set_visible(False) # Make y-aixs values visible or invisible
plt.show() # function to show the plot
# ---------------------------------------------------------------------
# BENDING MOMENT DIAGRAM
MomX = [0,0,l]
MomY = [0,f*l,0]
plt.plot(MomX, MomY, linestyle=':', marker='o', label="Moment direction = Counter-clockwise") # plotting the points on X axis
plt.legend() #legend to show direction of moment
plt.text(0,0,str((0))) # (Coordiante x, Coordinate y,the value in text+Unit) # point 1
plt.text(0,f*l,str(round((f*l),2))+UnitF+UnitL) # To SHOW the Moment value at the point # point 2
plt.text(l,-10,str((0))) # point 3
plt.plot(ZeroLX, ZeroLY, color='black')
# OVERALL DETAILS FOR THE GRAPH
plt.xlabel('Position along the beam')
plt.title('Bending Moment Diagram') # giving a title to graph
plt.gca().axes.get_yaxis().set_visible(False) # Make y-aixs values visible or invisible
plt.show() # function to show the plot
# https://www.geeksforgeeks.org/graph-plotting-in-python-set-1/
# In[ ]:
# In[49]:
# help(plt.plot)
# In[ ]:
| 28.014706 | 125 | 0.645407 |
t pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
from PIL import Image
f = 700
l = 100
UnitF = str('N')
UnitL = str("mm")
x = [0,l]
y = [0,0]
plt.plot(x, y,label = "Beam", color='green', linewidth = 10,marker='o', markerfacecolor='blue', markersize=15)
plt.legend()
| true | true |
f72a27bac82a4eddc6703adc1c7ebd25659b4aad | 2,192 | py | Python | razor/version.py | SRI-CSL/OCCAM | 8c498301f658fd3c158ffb6aad36dc0dd57c6239 | [
"BSD-3-Clause"
] | 17 | 2015-11-23T17:19:54.000Z | 2022-03-18T23:55:29.000Z | razor/version.py | SRI-CSL/application-specialization | 6e3efd1431195ccb4afd0801caa8cc825931197f | [
"BSD-3-Clause"
] | 58 | 2015-11-26T17:24:12.000Z | 2021-11-30T12:47:31.000Z | razor/version.py | SRI-CSL/application-specialization | 6e3efd1431195ccb4afd0801caa8cc825931197f | [
"BSD-3-Clause"
] | 10 | 2015-09-03T14:54:27.000Z | 2020-11-13T14:02:11.000Z | """
OCCAM
Copyright (c) 2011-2017, SRI International
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of SRI International nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
Feeping Creaturism:
This is the all important version number used by pip.
Version History:
1.0.0 - 11/15/2016 initial birth as a pip package.
1.0.1 - 11/16/2016 decided to enforce the new manifesto, now that it is documented.
1.0.2 - 11/16/2016 forgot to pull before publishing. D'oh.
1.0.3 - 11/23/2016 push with an auto generated rst file.
1.0.4 - 11/29/2016 razor requires protobuf.
1.1.0 - 4/30/2019 Large leap in development. Lots of new command line arguments.
1.1.1 - 3/10/2021 Large leap in development. Lots of new command line arguments.
1.1.2 - 3/10/2021 format fix in setup.py
"""
razor_version = '1.1.2'
| 36.533333 | 86 | 0.764142 |
razor_version = '1.1.2'
| true | true |
f72a27db8ed137ada094f4964a806b163f22f0f6 | 19,877 | py | Python | tests/cases/mount_test.py | RemiCecchinato/girder | 455d5c60d59112b65b45daf51c2d2ccda2e84a9a | [
"Apache-2.0"
] | null | null | null | tests/cases/mount_test.py | RemiCecchinato/girder | 455d5c60d59112b65b45daf51c2d2ccda2e84a9a | [
"Apache-2.0"
] | null | null | null | tests/cases/mount_test.py | RemiCecchinato/girder | 455d5c60d59112b65b45daf51c2d2ccda2e84a9a | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import datetime
import fuse
import mock
import os
import six
import stat
import tempfile
import threading
import time
from girder.cli import mount
from girder.exceptions import ValidationException
from girder.models.file import File
from girder.models.setting import Setting
from girder.models.user import User
from girder.settings import SettingKey
from tests import base
class ServerFuseTestCase(base.TestCase):
def _mountServer(self, path, shouldSucceed=True, maxWait=10, options=None):
"""
For testing, run the mount in the foreground in a thread. If the mount
should succeed, wait a short time for a mount to be ready. In local
testing, this can take 8 to 10 milliseconds.
:param path: the mount path. This waits for <path>/user to exist
:param maxWait: the maximum wait time in seconds.
:param options: fuseOptions to use in the mount. This should include
'foreground' for testing.
"""
kwargs = {
'fuseOptions': options or 'foreground',
'quiet': True,
}
mountThread = threading.Thread(target=mount.mountServer, args=(path, ), kwargs=kwargs)
mountThread.daemon = True
mountThread.start()
if shouldSucceed:
userPath = os.path.join(path, 'user')
endTime = time.time() + maxWait
while time.time() < endTime and not os.path.exists(userPath):
time.sleep(0.001)
self._mountThreads.append(mountThread)
else:
mountThread.join()
return mountThread
def setUp(self):
super(ServerFuseTestCase, self).setUp()
self._mountThreads = []
self.admin = User().findOne({'login': 'admin'})
self.user = User().findOne({'login': 'user'})
self.user2 = User().findOne({'login': 'second'})
self.mountPath = tempfile.mkdtemp()
self._mountServer(path=self.mountPath)
self.extraMountPath = tempfile.mkdtemp()
self.knownPaths = {
'user/admin/Private/Item 1/File 1A': 'File 1A',
'user/admin/Private/Item 1/File 1B': 'File 1B',
'user/admin/Private/Item 2/File 2': 'File 2',
'user/admin/Private/Item Without File/': None,
'user/user/Public/Item 3/File 3': 'File 3',
'user/user/Private/Item 4/File 4': 'File 4',
'user/user/Private/Folder/Item 5/File 5': 'File 5',
'collection/Test Collection/Private/Collection Item/Collection File': 'File 1A',
u'collection/Test Collection/Private/Collection Item/'
u'\u0444\u0430\u0439\u043b \u043a\u043e\u043b\u043b\u0435\u043a'
u'\u0446\u0438\u0438': 'File 1A',
}
self.adminFileName = 'user/admin/Private/Item 1/File 1A'
self.publicFileName = 'user/user/Public/Item 3/File 3'
self.privateFileName = 'user/user/Private/Item 4/File 4'
def tearDown(self):
super(ServerFuseTestCase, self).tearDown()
mount.unmountServer(self.mountPath, quiet=True)
mount.unmountServer(self.extraMountPath, quiet=True)
os.rmdir(self.mountPath)
os.rmdir(self.extraMountPath)
# Join threads that are done
for thread in self._mountThreads:
thread.join()
self._mountThreads = []
def testMainMount(self):
"""
Test the default mount point has access to all of the expected files.
"""
mountpath = self.mountPath
# Check that the mount lists users and collections
self.assertEqual(sorted(os.listdir(mountpath)), sorted(['user', 'collection']))
# Check that all known paths exist and that arbitrary other paths don't
for testpath, contents in six.iteritems(self.knownPaths):
localpath = os.path.join(mountpath, testpath)
# The path must exist
self.assertTrue(os.path.exists(localpath))
# The path plus an arbitrary string must not exist
self.assertFalse(os.path.exists(localpath + '.other'))
# If the path is a file, check that it equals the expected value
# and reports a non-zero size
if contents:
size = os.path.getsize(localpath)
with open(localpath) as file1:
self.assertEqual(file1.read().strip(), contents)
self.assertGreater(size, 0)
# The mtime should be recent
stat = os.stat(localpath)
self.assertGreater(stat.st_mtime, time.time() - 1e5)
# All parents should be folders and have zero size.
subpath = testpath
while '/' in subpath:
subpath = subpath.rsplit('/')[0]
localpath = os.path.join(mountpath, subpath)
self.assertTrue(os.path.isdir(localpath))
self.assertEqual(os.path.getsize(localpath), 0)
# An arbitrary alternate file should not exist
self.assertFalse(os.path.exists(localpath + '.other'))
def testBlockedMount(self):
"""
Test that when a mount point is non-empty the mount fails.
"""
blockFile = os.path.join(self.extraMountPath, 'block')
open(blockFile, 'wb').close()
with mock.patch('girder.plugin.logprint.error') as logprint:
self._mountServer(path=self.extraMountPath, shouldSucceed=False)
logprint.assert_called_once()
os.unlink(blockFile)
def testRWMountWarns(self):
"""
Test that when asking for an RW mount, a warning is issued.
"""
with mock.patch('girder.plugin.logprint.warning') as logprint:
self._mountServer(path=self.extraMountPath, options='foreground,rw=true')
logprint.assert_called_once()
logprint.assert_called_with('Ignoring the rw=True option')
def testFilePath(self):
"""
Test that all files report a FUSE path, and that this results in the
same file as the non-fuse path.
"""
files = list(File().find())
for file in files:
adapter = File().getAssetstoreAdapter(file)
filesystempath = adapter.fullPath(file)
filepath = File().getLocalFilePath(file)
fusepath = File().getGirderMountFilePath(file)
self.assertTrue(os.path.exists(filesystempath))
self.assertTrue(os.path.exists(filepath))
self.assertTrue(os.path.exists(fusepath))
self.assertEqual(filesystempath, filepath)
self.assertNotEqual(filesystempath, fusepath)
self.assertEqual(fusepath[:len(self.mountPath)], self.mountPath)
with open(filepath) as file1:
with open(fusepath) as file2:
self.assertEqual(file1.read(), file2.read())
subpath = fusepath[len(self.mountPath):].lstrip('/')
if self.knownPaths.get(subpath):
with open(fusepath) as file1:
self.assertEqual(file1.read().strip(), self.knownPaths[subpath])
def testFilePathNoLocalPath(self):
"""
Test that if an assetstore adapter doesn't respond to getLocalFilePath,
we always get the fuse path.
"""
from girder.utility.filesystem_assetstore_adapter import FilesystemAssetstoreAdapter
def getLocalFilePath(self, file):
return super(FilesystemAssetstoreAdapter, self).getLocalFilePath(file)
file = File().findOne()
origGetLocalFilePath = FilesystemAssetstoreAdapter.getLocalFilePath
FilesystemAssetstoreAdapter.getLocalFilePath = getLocalFilePath
filepath = File().getLocalFilePath(file)
fusepath = File().getGirderMountFilePath(file)
FilesystemAssetstoreAdapter.getLocalFilePath = origGetLocalFilePath
self.assertTrue(os.path.exists(filepath))
self.assertTrue(os.path.exists(fusepath))
self.assertEqual(filepath, fusepath)
def testRemountAndSetting(self):
"""
Test remounting to a different location.
"""
# Check that the setting for the mount location matches the current
# mount and a file is reachable where we expect.
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
self.assertEqual(setting['path'], self.mountPath)
self.assertTrue(os.path.exists(os.path.join(self.mountPath, self.publicFileName)))
self.assertFalse(os.path.exists(os.path.join(self.extraMountPath, self.publicFileName)))
mount.unmountServer(self.mountPath)
# After unmounting, the setting should be cleared (though perhaps not
# instantly) and files shouldn't be reachable.
endTime = time.time() + 10 # maximum time to wait
while time.time() < endTime:
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
if setting is None:
break
time.sleep(0.05)
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
self.assertIsNone(setting)
self.assertFalse(os.path.exists(os.path.join(self.mountPath, self.publicFileName)))
self.assertFalse(os.path.exists(os.path.join(self.extraMountPath, self.publicFileName)))
# Remounting to a different path should update the setting and make
# files visible again.
self._mountServer(path=self.extraMountPath)
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
self.assertEqual(setting['path'], self.extraMountPath)
self.assertFalse(os.path.exists(os.path.join(self.mountPath, self.publicFileName)))
self.assertTrue(os.path.exists(os.path.join(self.extraMountPath, self.publicFileName)))
def testUnmountWithOpenFiles(self):
"""
Unmounting with open files will return a non-zero value.
"""
path = os.path.join(self.mountPath, self.publicFileName)
fh = open(path)
fh.read(1)
self.assertNotEqual(mount.unmountServer(self.mountPath, quiet=True), 0)
# We should still be able to read from the file.
fh.read(1)
fh.close()
# Now we can unmount successefully
self.assertEqual(mount.unmountServer(self.mountPath, quiet=True), 0)
def testLazyUnmountWithOpenFiles(self):
"""
Lazy unmounting with open files will return a non-zero value.
"""
path = os.path.join(self.mountPath, self.publicFileName)
fh = open(path)
fh.read(1)
self.assertEqual(mount.unmountServer(self.mountPath, lazy=True, quiet=True), 0)
# We should still be able to read from the file.
fh.read(1)
fh.close()
# If we wait, the mount will close
endTime = time.time() + 10 # maximum time to wait
while time.time() < endTime:
if not os.path.exists(path):
break
time.sleep(0.05)
self.assertFalse(os.path.exists(path))
def testSettingValidation(self):
# Mounting and unmounting test valid use, so this just tests invalid
# values.
with six.assertRaisesRegex(self, ValidationException, 'must be a dict'):
Setting().set(SettingKey.GIRDER_MOUNT_INFORMATION, 'not a dict')
with six.assertRaisesRegex(self, ValidationException, 'with the "path" key'):
Setting().set(SettingKey.GIRDER_MOUNT_INFORMATION, {'no path': 'key'})
# Although other tests excerise the individual functions in the FUSE,
# coverage is not reported since it is run in a separate process. Each of
# the operation class functions is tested here.
def testFunctionCall(self):
op = mount.ServerFuse()
self.assertEqual(op.__call__('access', self.publicFileName, os.F_OK), 0)
self.assertEqual(op.__call__('access', self.privateFileName, os.F_OK), 0)
self.assertEqual(op.__call__('access', 'nosuchpath', os.F_OK), 0)
with self.assertRaises(fuse.FuseOSError):
self.assertTrue(op.__call__('read', self.publicFileName, 10, 0, None))
def testFunctionGetPath(self):
op = mount.ServerFuse()
resource = op._getPath(self.publicFileName)
self.assertEqual(resource['model'], 'file')
resource = op._getPath(os.path.dirname(self.publicFileName))
self.assertEqual(resource['model'], 'item')
resource = op._getPath(os.path.dirname(os.path.dirname(self.publicFileName)))
self.assertEqual(resource['model'], 'folder')
resource = op._getPath(self.privateFileName)
self.assertEqual(resource['model'], 'file')
with self.assertRaises(fuse.FuseOSError):
op._getPath('nosuchpath')
def testFunctionStat(self):
op = mount.ServerFuse()
resource = op._getPath(self.publicFileName)
attr = op._stat(resource['document'], resource['model'])
self.assertEqual(attr['st_ino'], -1)
self.assertEqual(attr['st_nlink'], 1)
self.assertGreater(attr['st_mtime'], time.time() - 1e5)
self.assertEqual(attr['st_ctime'], attr['st_mtime'])
self.assertEqual(attr['st_mode'], 0o400 | stat.S_IFREG)
self.assertGreater(attr['st_size'], len(self.knownPaths[self.publicFileName]))
resource['document']['updated'] = datetime.datetime.utcfromtimestamp(time.time() + 1)
File().save(resource['document'])
oldmtime = attr['st_mtime']
resource = op._getPath(self.publicFileName)
attr = op._stat(resource['document'], resource['model'])
self.assertGreater(attr['st_mtime'], oldmtime)
resource = op._getPath(os.path.dirname(self.publicFileName))
attr = op._stat(resource['document'], resource['model'])
self.assertEqual(attr['st_mode'], 0o500 | stat.S_IFDIR)
self.assertEqual(attr['st_size'], 0)
resource = op._getPath(os.path.dirname(os.path.dirname(self.publicFileName)))
attr = op._stat(resource['document'], resource['model'])
self.assertEqual(attr['st_mode'], 0o500 | stat.S_IFDIR)
self.assertEqual(attr['st_size'], 0)
def testFunctionName(self):
op = mount.ServerFuse()
resource = op._getPath(self.publicFileName)
name = op._name(resource['document'], resource['model'])
self.assertEqual(name, os.path.basename(self.publicFileName))
resource = op._getPath(os.path.dirname(self.publicFileName))
name = op._name(resource['document'], resource['model'])
self.assertEqual(name, os.path.basename(os.path.dirname(self.publicFileName)))
def testFunctionList(self):
op = mount.ServerFuse()
resource = op._getPath(os.path.dirname(self.publicFileName))
filelist = op._list(resource['document'], resource['model'])
self.assertIn(os.path.basename(self.publicFileName), filelist)
resource2 = op._getPath(os.path.dirname(os.path.dirname(self.publicFileName)))
filelist = op._list(resource2['document'], resource2['model'])
self.assertIn(os.path.basename(os.path.dirname(self.publicFileName)), filelist)
resource3 = op._getPath(os.path.dirname(self.adminFileName))
filelist = op._list(resource3['document'], resource3['model'])
self.assertIn(os.path.basename(self.adminFileName), filelist)
resource4 = op._getPath(os.path.dirname(os.path.dirname(self.adminFileName)))
filelist = op._list(resource4['document'], resource4['model'])
self.assertIn(os.path.basename(os.path.dirname(self.adminFileName)), filelist)
resource5 = op._getPath(os.path.dirname(os.path.dirname(
os.path.dirname(self.adminFileName))))
filelist = op._list(resource5['document'], resource5['model'])
self.assertIn(os.path.basename(os.path.dirname(
os.path.dirname(self.adminFileName))), filelist)
def testFunctionAccess(self):
op = mount.ServerFuse()
self.assertEqual(op.access(self.publicFileName, os.F_OK), 0)
self.assertEqual(op.access(self.publicFileName, os.R_OK | os.W_OK | os.X_OK), 0)
self.assertEqual(op.access(self.adminFileName, os.F_OK), 0)
self.assertEqual(op.access(self.adminFileName, os.R_OK), 0)
self.assertEqual(op.access('/user', os.F_OK), 0)
def testFunctionGetattr(self):
op = mount.ServerFuse()
attr = op.getattr('/user')
self.assertEqual(attr['st_mode'], 0o500 | stat.S_IFDIR)
self.assertEqual(attr['st_size'], 0)
attr = op.getattr(self.publicFileName)
self.assertEqual(attr['st_ino'], -1)
self.assertEqual(attr['st_nlink'], 1)
self.assertGreater(attr['st_mtime'], time.time() - 1e5)
self.assertEqual(attr['st_ctime'], attr['st_mtime'])
self.assertEqual(attr['st_mode'], 0o400 | stat.S_IFREG)
self.assertGreater(attr['st_size'], len(self.knownPaths[self.publicFileName]))
with self.assertRaises(fuse.FuseOSError):
op.getattr('/user/nosuchuser')
def testFunctionRead(self):
op = mount.ServerFuse()
fh = op.open(self.publicFileName, os.O_RDONLY)
data = op.read(self.publicFileName, 200, 0, fh)
if (isinstance(data, six.binary_type) and
not isinstance(self.knownPaths[self.publicFileName], six.binary_type)):
self.assertEqual(data.decode('utf8').strip(), self.knownPaths[self.publicFileName])
else:
self.assertEqual(data.strip(), self.knownPaths[self.publicFileName])
data2 = op.read(self.publicFileName, 4, 2, fh)
self.assertEqual(data[2:6], data2)
op.release(self.publicFileName, fh)
with self.assertRaises(fuse.FuseOSError):
op.read(self.publicFileName, 4, 2, fh)
def testFunctionReaddir(self):
op = mount.ServerFuse()
path = os.path.dirname(self.publicFileName)
data = op.readdir(path, 0)
self.assertIn(os.path.basename(self.publicFileName), data)
data = op.readdir('/user', 0)
self.assertIn('admin', data)
data = op.readdir('', 0)
self.assertIn('user', data)
self.assertIn('collection', data)
self.assertIn('.', data)
self.assertIn('..', data)
data = op.readdir('/collection', 0)
self.assertEqual(len(data), 3)
def testFunctionOpen(self):
op = mount.ServerFuse()
fh = op.open(self.publicFileName, os.O_RDONLY)
self.assertTrue(isinstance(fh, int))
self.assertIn(fh, op.openFiles)
op.release(self.publicFileName, fh)
path = os.path.dirname(self.publicFileName)
fh = op.open(path, os.O_RDONLY)
self.assertTrue(isinstance(fh, int))
self.assertNotIn(fh, op.openFiles)
for flag in (os.O_APPEND, os.O_ASYNC, os.O_CREAT, os.O_DIRECTORY,
os.O_EXCL, os.O_RDWR, os.O_TRUNC, os.O_WRONLY):
with self.assertRaises(fuse.FuseOSError):
op.open(self.publicFileName, flag)
def testFunctionCreate(self):
op = mount.ServerFuse()
with self.assertRaises(fuse.FuseOSError):
op.create(self.publicFileName, 0)
def testFunctionFlush(self):
op = mount.ServerFuse()
self.assertEqual(op.flush('/user'), 0)
def testFunctionRelease(self):
op = mount.ServerFuse()
fh = op.open(self.publicFileName, os.O_RDONLY)
self.assertIn(fh, op.openFiles)
self.assertEqual(op.release(self.publicFileName, fh), 0)
self.assertNotIn(fh, op.openFiles)
path = os.path.dirname(self.publicFileName)
fh = op.open(path, os.O_RDONLY)
self.assertNotIn(fh, op.openFiles)
self.assertEqual(op.release(path, fh), 0)
def testFunctionDestroy(self):
op = mount.ServerFuse()
self.assertIsNone(op.destroy('/'))
| 46.118329 | 96 | 0.640992 |
import datetime
import fuse
import mock
import os
import six
import stat
import tempfile
import threading
import time
from girder.cli import mount
from girder.exceptions import ValidationException
from girder.models.file import File
from girder.models.setting import Setting
from girder.models.user import User
from girder.settings import SettingKey
from tests import base
class ServerFuseTestCase(base.TestCase):
def _mountServer(self, path, shouldSucceed=True, maxWait=10, options=None):
kwargs = {
'fuseOptions': options or 'foreground',
'quiet': True,
}
mountThread = threading.Thread(target=mount.mountServer, args=(path, ), kwargs=kwargs)
mountThread.daemon = True
mountThread.start()
if shouldSucceed:
userPath = os.path.join(path, 'user')
endTime = time.time() + maxWait
while time.time() < endTime and not os.path.exists(userPath):
time.sleep(0.001)
self._mountThreads.append(mountThread)
else:
mountThread.join()
return mountThread
def setUp(self):
super(ServerFuseTestCase, self).setUp()
self._mountThreads = []
self.admin = User().findOne({'login': 'admin'})
self.user = User().findOne({'login': 'user'})
self.user2 = User().findOne({'login': 'second'})
self.mountPath = tempfile.mkdtemp()
self._mountServer(path=self.mountPath)
self.extraMountPath = tempfile.mkdtemp()
self.knownPaths = {
'user/admin/Private/Item 1/File 1A': 'File 1A',
'user/admin/Private/Item 1/File 1B': 'File 1B',
'user/admin/Private/Item 2/File 2': 'File 2',
'user/admin/Private/Item Without File/': None,
'user/user/Public/Item 3/File 3': 'File 3',
'user/user/Private/Item 4/File 4': 'File 4',
'user/user/Private/Folder/Item 5/File 5': 'File 5',
'collection/Test Collection/Private/Collection Item/Collection File': 'File 1A',
u'collection/Test Collection/Private/Collection Item/'
u'\u0444\u0430\u0439\u043b \u043a\u043e\u043b\u043b\u0435\u043a'
u'\u0446\u0438\u0438': 'File 1A',
}
self.adminFileName = 'user/admin/Private/Item 1/File 1A'
self.publicFileName = 'user/user/Public/Item 3/File 3'
self.privateFileName = 'user/user/Private/Item 4/File 4'
def tearDown(self):
super(ServerFuseTestCase, self).tearDown()
mount.unmountServer(self.mountPath, quiet=True)
mount.unmountServer(self.extraMountPath, quiet=True)
os.rmdir(self.mountPath)
os.rmdir(self.extraMountPath)
for thread in self._mountThreads:
thread.join()
self._mountThreads = []
def testMainMount(self):
mountpath = self.mountPath
self.assertEqual(sorted(os.listdir(mountpath)), sorted(['user', 'collection']))
for testpath, contents in six.iteritems(self.knownPaths):
localpath = os.path.join(mountpath, testpath)
# The path must exist
self.assertTrue(os.path.exists(localpath))
# The path plus an arbitrary string must not exist
self.assertFalse(os.path.exists(localpath + '.other'))
# If the path is a file, check that it equals the expected value
# and reports a non-zero size
if contents:
size = os.path.getsize(localpath)
with open(localpath) as file1:
self.assertEqual(file1.read().strip(), contents)
self.assertGreater(size, 0)
# The mtime should be recent
stat = os.stat(localpath)
self.assertGreater(stat.st_mtime, time.time() - 1e5)
# All parents should be folders and have zero size.
subpath = testpath
while '/' in subpath:
subpath = subpath.rsplit('/')[0]
localpath = os.path.join(mountpath, subpath)
self.assertTrue(os.path.isdir(localpath))
self.assertEqual(os.path.getsize(localpath), 0)
# An arbitrary alternate file should not exist
self.assertFalse(os.path.exists(localpath + '.other'))
def testBlockedMount(self):
blockFile = os.path.join(self.extraMountPath, 'block')
open(blockFile, 'wb').close()
with mock.patch('girder.plugin.logprint.error') as logprint:
self._mountServer(path=self.extraMountPath, shouldSucceed=False)
logprint.assert_called_once()
os.unlink(blockFile)
def testRWMountWarns(self):
with mock.patch('girder.plugin.logprint.warning') as logprint:
self._mountServer(path=self.extraMountPath, options='foreground,rw=true')
logprint.assert_called_once()
logprint.assert_called_with('Ignoring the rw=True option')
def testFilePath(self):
files = list(File().find())
for file in files:
adapter = File().getAssetstoreAdapter(file)
filesystempath = adapter.fullPath(file)
filepath = File().getLocalFilePath(file)
fusepath = File().getGirderMountFilePath(file)
self.assertTrue(os.path.exists(filesystempath))
self.assertTrue(os.path.exists(filepath))
self.assertTrue(os.path.exists(fusepath))
self.assertEqual(filesystempath, filepath)
self.assertNotEqual(filesystempath, fusepath)
self.assertEqual(fusepath[:len(self.mountPath)], self.mountPath)
with open(filepath) as file1:
with open(fusepath) as file2:
self.assertEqual(file1.read(), file2.read())
subpath = fusepath[len(self.mountPath):].lstrip('/')
if self.knownPaths.get(subpath):
with open(fusepath) as file1:
self.assertEqual(file1.read().strip(), self.knownPaths[subpath])
def testFilePathNoLocalPath(self):
from girder.utility.filesystem_assetstore_adapter import FilesystemAssetstoreAdapter
def getLocalFilePath(self, file):
return super(FilesystemAssetstoreAdapter, self).getLocalFilePath(file)
file = File().findOne()
origGetLocalFilePath = FilesystemAssetstoreAdapter.getLocalFilePath
FilesystemAssetstoreAdapter.getLocalFilePath = getLocalFilePath
filepath = File().getLocalFilePath(file)
fusepath = File().getGirderMountFilePath(file)
FilesystemAssetstoreAdapter.getLocalFilePath = origGetLocalFilePath
self.assertTrue(os.path.exists(filepath))
self.assertTrue(os.path.exists(fusepath))
self.assertEqual(filepath, fusepath)
def testRemountAndSetting(self):
# Check that the setting for the mount location matches the current
# mount and a file is reachable where we expect.
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
self.assertEqual(setting['path'], self.mountPath)
self.assertTrue(os.path.exists(os.path.join(self.mountPath, self.publicFileName)))
self.assertFalse(os.path.exists(os.path.join(self.extraMountPath, self.publicFileName)))
mount.unmountServer(self.mountPath)
# After unmounting, the setting should be cleared (though perhaps not
# instantly) and files shouldn't be reachable.
endTime = time.time() + 10
while time.time() < endTime:
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
if setting is None:
break
time.sleep(0.05)
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
self.assertIsNone(setting)
self.assertFalse(os.path.exists(os.path.join(self.mountPath, self.publicFileName)))
self.assertFalse(os.path.exists(os.path.join(self.extraMountPath, self.publicFileName)))
self._mountServer(path=self.extraMountPath)
setting = Setting().get(SettingKey.GIRDER_MOUNT_INFORMATION)
self.assertEqual(setting['path'], self.extraMountPath)
self.assertFalse(os.path.exists(os.path.join(self.mountPath, self.publicFileName)))
self.assertTrue(os.path.exists(os.path.join(self.extraMountPath, self.publicFileName)))
def testUnmountWithOpenFiles(self):
path = os.path.join(self.mountPath, self.publicFileName)
fh = open(path)
fh.read(1)
self.assertNotEqual(mount.unmountServer(self.mountPath, quiet=True), 0)
fh.read(1)
fh.close()
self.assertEqual(mount.unmountServer(self.mountPath, quiet=True), 0)
def testLazyUnmountWithOpenFiles(self):
path = os.path.join(self.mountPath, self.publicFileName)
fh = open(path)
fh.read(1)
self.assertEqual(mount.unmountServer(self.mountPath, lazy=True, quiet=True), 0)
fh.read(1)
fh.close()
endTime = time.time() + 10
while time.time() < endTime:
if not os.path.exists(path):
break
time.sleep(0.05)
self.assertFalse(os.path.exists(path))
def testSettingValidation(self):
with six.assertRaisesRegex(self, ValidationException, 'must be a dict'):
Setting().set(SettingKey.GIRDER_MOUNT_INFORMATION, 'not a dict')
with six.assertRaisesRegex(self, ValidationException, 'with the "path" key'):
Setting().set(SettingKey.GIRDER_MOUNT_INFORMATION, {'no path': 'key'})
def testFunctionCall(self):
op = mount.ServerFuse()
self.assertEqual(op.__call__('access', self.publicFileName, os.F_OK), 0)
self.assertEqual(op.__call__('access', self.privateFileName, os.F_OK), 0)
self.assertEqual(op.__call__('access', 'nosuchpath', os.F_OK), 0)
with self.assertRaises(fuse.FuseOSError):
self.assertTrue(op.__call__('read', self.publicFileName, 10, 0, None))
def testFunctionGetPath(self):
op = mount.ServerFuse()
resource = op._getPath(self.publicFileName)
self.assertEqual(resource['model'], 'file')
resource = op._getPath(os.path.dirname(self.publicFileName))
self.assertEqual(resource['model'], 'item')
resource = op._getPath(os.path.dirname(os.path.dirname(self.publicFileName)))
self.assertEqual(resource['model'], 'folder')
resource = op._getPath(self.privateFileName)
self.assertEqual(resource['model'], 'file')
with self.assertRaises(fuse.FuseOSError):
op._getPath('nosuchpath')
def testFunctionStat(self):
op = mount.ServerFuse()
resource = op._getPath(self.publicFileName)
attr = op._stat(resource['document'], resource['model'])
self.assertEqual(attr['st_ino'], -1)
self.assertEqual(attr['st_nlink'], 1)
self.assertGreater(attr['st_mtime'], time.time() - 1e5)
self.assertEqual(attr['st_ctime'], attr['st_mtime'])
self.assertEqual(attr['st_mode'], 0o400 | stat.S_IFREG)
self.assertGreater(attr['st_size'], len(self.knownPaths[self.publicFileName]))
resource['document']['updated'] = datetime.datetime.utcfromtimestamp(time.time() + 1)
File().save(resource['document'])
oldmtime = attr['st_mtime']
resource = op._getPath(self.publicFileName)
attr = op._stat(resource['document'], resource['model'])
self.assertGreater(attr['st_mtime'], oldmtime)
resource = op._getPath(os.path.dirname(self.publicFileName))
attr = op._stat(resource['document'], resource['model'])
self.assertEqual(attr['st_mode'], 0o500 | stat.S_IFDIR)
self.assertEqual(attr['st_size'], 0)
resource = op._getPath(os.path.dirname(os.path.dirname(self.publicFileName)))
attr = op._stat(resource['document'], resource['model'])
self.assertEqual(attr['st_mode'], 0o500 | stat.S_IFDIR)
self.assertEqual(attr['st_size'], 0)
def testFunctionName(self):
op = mount.ServerFuse()
resource = op._getPath(self.publicFileName)
name = op._name(resource['document'], resource['model'])
self.assertEqual(name, os.path.basename(self.publicFileName))
resource = op._getPath(os.path.dirname(self.publicFileName))
name = op._name(resource['document'], resource['model'])
self.assertEqual(name, os.path.basename(os.path.dirname(self.publicFileName)))
def testFunctionList(self):
op = mount.ServerFuse()
resource = op._getPath(os.path.dirname(self.publicFileName))
filelist = op._list(resource['document'], resource['model'])
self.assertIn(os.path.basename(self.publicFileName), filelist)
resource2 = op._getPath(os.path.dirname(os.path.dirname(self.publicFileName)))
filelist = op._list(resource2['document'], resource2['model'])
self.assertIn(os.path.basename(os.path.dirname(self.publicFileName)), filelist)
resource3 = op._getPath(os.path.dirname(self.adminFileName))
filelist = op._list(resource3['document'], resource3['model'])
self.assertIn(os.path.basename(self.adminFileName), filelist)
resource4 = op._getPath(os.path.dirname(os.path.dirname(self.adminFileName)))
filelist = op._list(resource4['document'], resource4['model'])
self.assertIn(os.path.basename(os.path.dirname(self.adminFileName)), filelist)
resource5 = op._getPath(os.path.dirname(os.path.dirname(
os.path.dirname(self.adminFileName))))
filelist = op._list(resource5['document'], resource5['model'])
self.assertIn(os.path.basename(os.path.dirname(
os.path.dirname(self.adminFileName))), filelist)
def testFunctionAccess(self):
op = mount.ServerFuse()
self.assertEqual(op.access(self.publicFileName, os.F_OK), 0)
self.assertEqual(op.access(self.publicFileName, os.R_OK | os.W_OK | os.X_OK), 0)
self.assertEqual(op.access(self.adminFileName, os.F_OK), 0)
self.assertEqual(op.access(self.adminFileName, os.R_OK), 0)
self.assertEqual(op.access('/user', os.F_OK), 0)
def testFunctionGetattr(self):
op = mount.ServerFuse()
attr = op.getattr('/user')
self.assertEqual(attr['st_mode'], 0o500 | stat.S_IFDIR)
self.assertEqual(attr['st_size'], 0)
attr = op.getattr(self.publicFileName)
self.assertEqual(attr['st_ino'], -1)
self.assertEqual(attr['st_nlink'], 1)
self.assertGreater(attr['st_mtime'], time.time() - 1e5)
self.assertEqual(attr['st_ctime'], attr['st_mtime'])
self.assertEqual(attr['st_mode'], 0o400 | stat.S_IFREG)
self.assertGreater(attr['st_size'], len(self.knownPaths[self.publicFileName]))
with self.assertRaises(fuse.FuseOSError):
op.getattr('/user/nosuchuser')
def testFunctionRead(self):
op = mount.ServerFuse()
fh = op.open(self.publicFileName, os.O_RDONLY)
data = op.read(self.publicFileName, 200, 0, fh)
if (isinstance(data, six.binary_type) and
not isinstance(self.knownPaths[self.publicFileName], six.binary_type)):
self.assertEqual(data.decode('utf8').strip(), self.knownPaths[self.publicFileName])
else:
self.assertEqual(data.strip(), self.knownPaths[self.publicFileName])
data2 = op.read(self.publicFileName, 4, 2, fh)
self.assertEqual(data[2:6], data2)
op.release(self.publicFileName, fh)
with self.assertRaises(fuse.FuseOSError):
op.read(self.publicFileName, 4, 2, fh)
def testFunctionReaddir(self):
op = mount.ServerFuse()
path = os.path.dirname(self.publicFileName)
data = op.readdir(path, 0)
self.assertIn(os.path.basename(self.publicFileName), data)
data = op.readdir('/user', 0)
self.assertIn('admin', data)
data = op.readdir('', 0)
self.assertIn('user', data)
self.assertIn('collection', data)
self.assertIn('.', data)
self.assertIn('..', data)
data = op.readdir('/collection', 0)
self.assertEqual(len(data), 3)
def testFunctionOpen(self):
op = mount.ServerFuse()
fh = op.open(self.publicFileName, os.O_RDONLY)
self.assertTrue(isinstance(fh, int))
self.assertIn(fh, op.openFiles)
op.release(self.publicFileName, fh)
path = os.path.dirname(self.publicFileName)
fh = op.open(path, os.O_RDONLY)
self.assertTrue(isinstance(fh, int))
self.assertNotIn(fh, op.openFiles)
for flag in (os.O_APPEND, os.O_ASYNC, os.O_CREAT, os.O_DIRECTORY,
os.O_EXCL, os.O_RDWR, os.O_TRUNC, os.O_WRONLY):
with self.assertRaises(fuse.FuseOSError):
op.open(self.publicFileName, flag)
def testFunctionCreate(self):
op = mount.ServerFuse()
with self.assertRaises(fuse.FuseOSError):
op.create(self.publicFileName, 0)
def testFunctionFlush(self):
op = mount.ServerFuse()
self.assertEqual(op.flush('/user'), 0)
def testFunctionRelease(self):
op = mount.ServerFuse()
fh = op.open(self.publicFileName, os.O_RDONLY)
self.assertIn(fh, op.openFiles)
self.assertEqual(op.release(self.publicFileName, fh), 0)
self.assertNotIn(fh, op.openFiles)
path = os.path.dirname(self.publicFileName)
fh = op.open(path, os.O_RDONLY)
self.assertNotIn(fh, op.openFiles)
self.assertEqual(op.release(path, fh), 0)
def testFunctionDestroy(self):
op = mount.ServerFuse()
self.assertIsNone(op.destroy('/'))
| true | true |
f72a2a7c5923c797d3dd68abb92ef1c14020412e | 199 | py | Python | apirel/users/tests/test_models.py | scottBowles/apirel | 597d66eaf65ed9caced411d10c1d8a51f2b76f8f | [
"MIT"
] | null | null | null | apirel/users/tests/test_models.py | scottBowles/apirel | 597d66eaf65ed9caced411d10c1d8a51f2b76f8f | [
"MIT"
] | 10 | 2022-01-05T01:26:19.000Z | 2022-03-28T02:06:15.000Z | apirel/users/tests/test_models.py | scottBowles/apirel | 597d66eaf65ed9caced411d10c1d8a51f2b76f8f | [
"MIT"
] | null | null | null | import pytest
from apirel.users.models import User
pytestmark = pytest.mark.django_db
def test_user_get_absolute_url(user: User):
assert user.get_absolute_url() == f"/users/{user.username}/"
| 19.9 | 64 | 0.768844 | import pytest
from apirel.users.models import User
pytestmark = pytest.mark.django_db
def test_user_get_absolute_url(user: User):
assert user.get_absolute_url() == f"/users/{user.username}/"
| true | true |
f72a2cdaf83462439b996bbb10ea5e4ee8322bf5 | 22,331 | py | Python | aetros/utils/image.py | aetros/aetros-cli | a2a1f38d6af1660e1e2680c7d413ec2aef45faab | [
"MIT"
] | 120 | 2016-07-26T16:06:14.000Z | 2021-07-19T03:26:07.000Z | aetros/utils/image.py | maxpumperla/aetros-cli | a2a1f38d6af1660e1e2680c7d413ec2aef45faab | [
"MIT"
] | 30 | 2016-08-15T22:21:54.000Z | 2018-03-14T08:52:46.000Z | aetros/utils/image.py | maxpumperla/aetros-cli | a2a1f38d6af1660e1e2680c7d413ec2aef45faab | [
"MIT"
] | 30 | 2016-07-31T20:54:48.000Z | 2019-10-17T11:20:18.000Z | # Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
# BSD 3-clause license
from __future__ import absolute_import
from __future__ import print_function
import math
from six.moves import range
# Find the best implementation available
from aetros.utils.pilutil import imresize
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import numpy as np
import PIL.Image
# Library defaults:
# PIL.Image:
# size -- (width, height)
# np.array:
# shape -- (height, width, channels)
# range -- [0-255]
# dtype -- uint8
# channels -- RGB
# caffe.datum:
# datum.data type -- bytes (uint8)
# datum.float_data type -- float32
# when decoding images, channels are BGR
# DIGITS:
# image_dims -- (height, width, channels)
# List of supported file extensions
# Use like "if filename.endswith(SUPPORTED_EXTENSIONS)"
SUPPORTED_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.bmp', '.ppm')
def upscale(image, ratio):
"""
return upscaled image array
Arguments:
image -- a (H,W,C) numpy.ndarray
ratio -- scaling factor (>1)
"""
if not isinstance(image, np.ndarray):
raise ValueError('Expected ndarray')
if ratio < 1:
raise ValueError('Ratio must be greater than 1 (ratio=%f)' % ratio)
width = int(math.floor(image.shape[1] * ratio))
height = int(math.floor(image.shape[0] * ratio))
channels = image.shape[2]
out = np.ndarray((height, width, channels), dtype=np.uint8)
for x, y in np.ndindex((width, height)):
out[y, x] = image[int(math.floor(y / ratio)), int(math.floor(x / ratio))]
return out
def resize_image(image, height, width,
channels=None,
resize_mode=None
):
"""
Resizes an image and returns it as a np.array
Arguments:
image -- a PIL.Image or numpy.ndarray
height -- height of new image
width -- width of new image
Keyword Arguments:
channels -- channels of new image (stays unchanged if not specified)
resize_mode -- can be crop, squash, fill or half_crop
"""
if resize_mode is None:
resize_mode = 'squash'
if resize_mode not in ['crop', 'squash', 'fill', 'half_crop']:
raise ValueError('resize_mode "%s" not supported' % resize_mode)
if channels not in [None, 1, 3]:
raise ValueError('unsupported number of channels: %s' % channels)
if isinstance(image, PIL.Image.Image):
# Convert image mode (channels)
if channels is None:
image_mode = image.mode
if image_mode == 'L':
channels = 1
elif image_mode == 'RGB':
channels = 3
else:
raise ValueError('unknown image mode "%s"' % image_mode)
elif channels == 1:
# 8-bit pixels, black and white
image_mode = 'L'
elif channels == 3:
# 3x8-bit pixels, true color
image_mode = 'RGB'
if image.mode != image_mode:
image = image.convert(image_mode)
image = np.array(image)
elif isinstance(image, np.ndarray):
if image.dtype != np.uint8:
image = image.astype(np.uint8)
if image.ndim == 3 and image.shape[2] == 1:
image = image.reshape(image.shape[:2])
if channels is None:
if image.ndim == 2:
channels = 1
elif image.ndim == 3 and image.shape[2] == 3:
channels = 3
else:
raise ValueError('invalid image shape: %s' % (image.shape,))
elif channels == 1:
if image.ndim != 2:
if image.ndim == 3 and image.shape[2] == 3:
# color to grayscale
image = np.dot(image, [0.299, 0.587, 0.114]).astype(np.uint8)
else:
raise ValueError('invalid image shape: %s' % (image.shape,))
elif channels == 3:
if image.ndim == 2:
# grayscale to color
image = np.repeat(image, 3).reshape(image.shape + (3,))
elif image.shape[2] != 3:
raise ValueError('invalid image shape: %s' % (image.shape,))
else:
raise ValueError('resize_image() expected a PIL.Image.Image or a numpy.ndarray')
# No need to resize
if image.shape[0] == height and image.shape[1] == width:
return image
# Resize
interp = 'bilinear'
width_ratio = float(image.shape[1]) / width
height_ratio = float(image.shape[0]) / height
if resize_mode == 'squash' or width_ratio == height_ratio:
return imresize(image, (height, width), interp=interp)
elif resize_mode == 'crop':
# resize to smallest of ratios (relatively larger image), keeping aspect ratio
if width_ratio > height_ratio:
resize_height = height
resize_width = int(round(image.shape[1] / height_ratio))
else:
resize_width = width
resize_height = int(round(image.shape[0] / width_ratio))
image = imresize(image, (resize_height, resize_width), interp=interp)
# chop off ends of dimension that is still too long
if width_ratio > height_ratio:
start = int(round((resize_width - width) / 2.0))
return image[:, start:start + width]
else:
start = int(round((resize_height - height) / 2.0))
return image[start:start + height, :]
else:
if resize_mode == 'fill':
# resize to biggest of ratios (relatively smaller image), keeping aspect ratio
if width_ratio > height_ratio:
resize_width = width
resize_height = int(round(image.shape[0] / width_ratio))
if (height - resize_height) % 2 == 1:
resize_height += 1
else:
resize_height = height
resize_width = int(round(image.shape[1] / height_ratio))
if (width - resize_width) % 2 == 1:
resize_width += 1
image = imresize(image, (resize_height, resize_width), interp=interp)
elif resize_mode == 'half_crop':
# resize to average ratio keeping aspect ratio
new_ratio = (width_ratio + height_ratio) / 2.0
resize_width = int(round(image.shape[1] / new_ratio))
resize_height = int(round(image.shape[0] / new_ratio))
if width_ratio > height_ratio and (height - resize_height) % 2 == 1:
resize_height += 1
elif width_ratio < height_ratio and (width - resize_width) % 2 == 1:
resize_width += 1
image = imresize(image, (resize_height, resize_width), interp=interp)
# chop off ends of dimension that is still too long
if width_ratio > height_ratio:
start = int(round((resize_width - width) / 2.0))
image = image[:, start:start + width]
else:
start = int(round((resize_height - height) / 2.0))
image = image[start:start + height, :]
else:
raise Exception('unrecognized resize_mode "%s"' % resize_mode)
# fill ends of dimension that is too short with random noise
if width_ratio > height_ratio:
padding = (height - resize_height) / 2
noise_size = (padding, width)
if channels > 1:
noise_size += (channels,)
noise = np.random.randint(0, 255, noise_size).astype('uint8')
image = np.concatenate((noise, image, noise), axis=0)
else:
padding = (width - resize_width) / 2
noise_size = (height, padding)
if channels > 1:
noise_size += (channels,)
noise = np.random.randint(0, 255, noise_size).astype('uint8')
image = np.concatenate((noise, image, noise), axis=1)
return image
def embed_image_html(image):
"""
Returns an image embedded in HTML base64 format
(Based on Caffe's web_demo)
Arguments:
image -- a PIL.Image or np.ndarray
"""
if image is None:
return None
elif isinstance(image, PIL.Image.Image):
pass
elif isinstance(image, np.ndarray):
image = PIL.Image.fromarray(image)
else:
raise ValueError('image must be a PIL.Image or a np.ndarray')
# Read format from the image
fmt = image.format
if not fmt:
# default to JPEG
fmt = 'jpeg'
else:
fmt = fmt.lower()
string_buf = StringIO()
image.save(string_buf, format=fmt)
data = string_buf.getvalue().encode('base64').replace('\n', '')
return 'data:image/%s;base64,%s' % (fmt, data)
def add_bboxes_to_image(image, bboxes, color='red', width=1):
"""
Draw rectangles on the image for the bounding boxes
Returns a PIL.Image
Arguments:
image -- input image
bboxes -- bounding boxes in the [((l, t), (r, b)), ...] format
Keyword arguments:
color -- color to draw the rectangles
width -- line width of the rectangles
Example:
image = Image.open(filename)
add_bboxes_to_image(image, bboxes[filename], width=2, color='#FF7700')
image.show()
"""
def expanded_bbox(bbox, n):
"""
Grow the bounding box by n pixels
"""
l = min(bbox[0][0], bbox[1][0])
r = max(bbox[0][0], bbox[1][0])
t = min(bbox[0][1], bbox[1][1])
b = max(bbox[0][1], bbox[1][1])
return ((l - n, t - n), (r + n, b + n))
from PIL import Image, ImageDraw
draw = ImageDraw.Draw(image)
for bbox in bboxes:
for n in range(width):
draw.rectangle(expanded_bbox(bbox, n), outline=color)
return image
def get_layer_vis_square(data,
allow_heatmap=True,
normalize=True,
min_img_dim=100,
max_width=1200,
channel_order='RGB',
colormap='jet',
):
"""
Returns a vis_square for the given layer data
Arguments:
data -- a np.ndarray
Keyword arguments:
allow_heatmap -- if True, convert single channel images to heatmaps
normalize -- whether to normalize the data when visualizing
max_width -- maximum width for the vis_square
"""
if channel_order not in ['RGB', 'BGR']:
raise ValueError('Unsupported channel_order %s' % channel_order)
if data.ndim == 1:
# interpret as 1x1 grayscale images
# (N, 1, 1)
data = data[:, np.newaxis, np.newaxis]
elif data.ndim == 2:
# interpret as 1x1 grayscale images
# (N, 1, 1)
data = data.reshape((data.shape[0] * data.shape[1], 1, 1))
elif data.ndim == 3:
if data.shape[0] == 3:
# interpret as a color image
# (1, H, W,3)
if channel_order == 'BGR':
data = data[[2, 1, 0], ...] # BGR to RGB (see issue #59)
data = data.transpose(1, 2, 0)
data = data[np.newaxis, ...]
else:
# interpret as grayscale images
# (N, H, W)
pass
elif data.ndim == 4:
if data.shape[0] == 3:
# interpret as HxW color images
# (N, H, W, 3)
data = data.transpose(1, 2, 3, 0)
if channel_order == 'BGR':
data = data[:, :, :, [2, 1, 0]] # BGR to RGB (see issue #59)
elif data.shape[1] == 3:
# interpret as HxW color images
# (N, H, W, 3)
data = data.transpose(0, 2, 3, 1)
if channel_order == 'BGR':
data = data[:, :, :, [2, 1, 0]] # BGR to RGB (see issue #59)
else:
# interpret as HxW grayscale images
# (N, H, W)
data = data.reshape((data.shape[0] * data.shape[1], data.shape[2], data.shape[3]))
else:
raise RuntimeError('unrecognized data shape: %s' % (data.shape,))
return get_layer_vis_square_raw(data,
allow_heatmap,
normalize,
min_img_dim,
max_width,
colormap,
)
def get_image_tales(images, colormap='jet', min_img_dim=100, max_width=1000):
padsize = 1
# convert to float since we're going to do some math
images = images.astype('float32')
images -= images.min()
if images.max() > 0:
images /= images.max()
images *= 255
if images.ndim == 3:
# they're grayscale - convert to a colormap
redmap, greenmap, bluemap = get_color_map(colormap)
red = np.interp(images * (len(redmap) - 1) / 255.0, range(len(redmap)), redmap)
green = np.interp(images * (len(greenmap) - 1) / 255.0, range(len(greenmap)), greenmap)
blue = np.interp(images * (len(bluemap) - 1) / 255.0, range(len(bluemap)), bluemap)
# Slap the channels back together
images = np.concatenate(
(red[..., np.newaxis], green[..., np.newaxis], blue[..., np.newaxis]), axis=3)
images = np.minimum(images, 255)
images = np.maximum(images, 0)
# convert back to uint8
images = images.astype('uint8')
# Compute the output image matrix dimensions
n = int(np.ceil(np.sqrt(images.shape[0])))
ny = n
nx = n
length = images.shape[0]
if n * (n - 1) >= length:
nx = n - 1
# Add padding between the images
padding = ((0, nx * ny - length), (0, padsize), (0, padsize)) + ((0, 0),) * (images.ndim - 3)
padded = np.pad(images, padding, mode='constant', constant_values=0)
# Tile the images beside each other
tiles = padded.reshape(
(ny, nx) + padded.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded.ndim + 1)))
tiles = tiles.reshape((ny * tiles.shape[1], nx * tiles.shape[3]) + tiles.shape[4:])
return tiles
def get_layer_vis_square_raw(data,
allow_heatmap=True,
normalize=True,
min_img_dim=100,
max_width=1200,
colormap='jet',
):
# chop off data so that it will fit within max_width
padsize = 0
width = data.shape[2]
if width > max_width:
data = data[:1, :max_width, :max_width]
else:
if width > 1:
padsize = 1
width += 1
n = max(max_width // width, 1)
n *= n
data = data[:n]
if not allow_heatmap and data.ndim == 3:
data = data[..., np.newaxis]
vis = vis_square(data,
padsize=padsize,
normalize=normalize,
colormap=colormap
)
# find minimum dimension and upscale if necessary
_min = sorted(vis.shape[:2])[0]
if _min < min_img_dim:
# upscale image
ratio = min_img_dim / float(_min)
vis = upscale(vis, ratio)
return vis
def vis_square(images,
padsize=1,
normalize=False,
colormap='jet',
):
"""
Visualize each image in a grid of size approx sqrt(n) by sqrt(n)
Returns a np.array image
(Based on Caffe's filter_visualization notebook)
Arguments:
images -- an array of shape (N, H, W) or (N, H, W, C)
if C is not set, a heatmap is computed for the result
Keyword arguments:
padsize -- how many pixels go inbetween the tiles
normalize -- if true, scales (min, max) across all images out to (0, 1)
colormap -- a string representing one of the supported colormaps
"""
assert 3 <= images.ndim <= 4, 'images.ndim must be 3 or 4'
# convert to float since we're going to do some math
images = images.astype('float32')
if normalize:
images -= images.min()
if images.max() > 0:
images /= images.max()
images *= 255
if images.ndim == 3:
# they're grayscale - convert to a colormap
redmap, greenmap, bluemap = get_color_map(colormap)
red = np.interp(images * (len(redmap) - 1) / 255.0, range(len(redmap)), redmap)
green = np.interp(images * (len(greenmap) - 1) / 255.0, range(len(greenmap)), greenmap)
blue = np.interp(images * (len(bluemap) - 1) / 255.0, range(len(bluemap)), bluemap)
# Slap the channels back together
images = np.concatenate(
(red[..., np.newaxis], green[..., np.newaxis], blue[..., np.newaxis]), axis=3)
images = np.minimum(images, 255)
images = np.maximum(images, 0)
# convert back to uint8
images = images.astype('uint8')
# Compute the output image matrix dimensions
n = int(np.ceil(np.sqrt(images.shape[0])))
ny = n
nx = n
length = images.shape[0]
if n * (n - 1) >= length:
nx = n - 1
# Add padding between the images
padding = ((0, nx * ny - length), (0, padsize), (0, padsize)) + ((0, 0),) * (images.ndim - 3)
padded = np.pad(images, padding, mode='constant', constant_values=255)
# Tile the images beside each other
tiles = padded.reshape(
(ny, nx) + padded.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded.ndim + 1)))
tiles = tiles.reshape((ny * tiles.shape[1], nx * tiles.shape[3]) + tiles.shape[4:])
if tiles.shape[-1] == 1:
# grayscale to color
tiles = np.dstack([tiles.squeeze()] * 3)
return tiles
def get_color_map(name):
"""
Return a colormap as (redmap, greenmap, bluemap)
Arguments:
name -- the name of the colormap. If unrecognized, will default to 'jet'.
"""
redmap = [0]
greenmap = [0]
bluemap = [0]
if name == 'white':
# essentially a noop
redmap = [0, 1]
greenmap = [0, 1]
bluemap = [0, 1]
elif name == 'simple':
redmap = [0, 1, 1, 1]
greenmap = [0, 0, 1, 1]
bluemap = [0, 0, 0, 1]
elif name == 'hot':
redmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952,
0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936, 0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
greenmap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603163, 0.0714285714285714, 0.1111111111111112, 0.1507936507936507, 0.1904761904761905, 0.23015873015873, 0.2698412698412698, 0.3095238095238093, 0.3492063492063491, 0.3888888888888888, 0.4285714285714284,
0.4682539682539679, 0.5079365079365079, 0.5476190476190477, 0.5873015873015872, 0.6269841269841268, 0.6666666666666665, 0.7063492063492065, 0.746031746031746, 0.7857142857142856, 0.8253968253968254, 0.8650793650793651, 0.9047619047619047, 0.9444444444444442, 0.984126984126984, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904761904745, 0.1269841269841265,
0.2063492063492056, 0.2857142857142856, 0.3650793650793656, 0.4444444444444446, 0.5238095238095237, 0.6031746031746028, 0.6825396825396828, 0.7619047619047619, 0.8412698412698409, 0.92063492063492, 1]
elif name == 'rainbow':
redmap = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9365079365079367, 0.8571428571428572, 0.7777777777777777, 0.6984126984126986, 0.6190476190476191, 0.53968253968254, 0.4603174603174605, 0.3809523809523814, 0.3015873015873018, 0.2222222222222223, 0.1428571428571432,
0.06349206349206415, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603208, 0.08465608465608465, 0.1375661375661377, 0.1904761904761907, 0.2433862433862437, 0.2962962962962963, 0.3492063492063493, 0.4021164021164023, 0.4550264550264553, 0.5079365079365079, 0.5608465608465609, 0.6137566137566139, 0.666666666666667]
greenmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952, 0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936,
0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9841269841269842, 0.9047619047619047, 0.8253968253968256, 0.7460317460317465, 0.666666666666667, 0.587301587301587, 0.5079365079365079, 0.4285714285714288, 0.3492063492063493, 0.2698412698412698, 0.1904761904761907, 0.1111111111111116, 0.03174603174603208, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01587301587301582, 0.09523809523809534, 0.1746031746031744, 0.2539682539682535,
0.333333333333333, 0.412698412698413, 0.4920634920634921, 0.5714285714285712, 0.6507936507936507, 0.7301587301587302, 0.8095238095238093, 0.8888888888888884, 0.9682539682539679, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
elif name == 'winter':
greenmap = [0, 1]
bluemap = [1, 0.5]
else:
if name != 'jet':
print('Warning: colormap "%s" not supported. Using jet instead.' % name)
redmap = [0, 0, 0, 0, 0.5, 1, 1, 1, 0.5]
greenmap = [0, 0, 0.5, 1, 1, 1, 0.5, 0, 0]
bluemap = [0.5, 1, 1, 1, 0.5, 0, 0, 0, 0]
return 255.0 * np.array(redmap), 255.0 * np.array(greenmap), 255.0 * np.array(bluemap)
| 41.740187 | 451 | 0.579553 |
from __future__ import absolute_import
from __future__ import print_function
import math
from six.moves import range
from aetros.utils.pilutil import imresize
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import numpy as np
import PIL.Image
SUPPORTED_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.bmp', '.ppm')
def upscale(image, ratio):
if not isinstance(image, np.ndarray):
raise ValueError('Expected ndarray')
if ratio < 1:
raise ValueError('Ratio must be greater than 1 (ratio=%f)' % ratio)
width = int(math.floor(image.shape[1] * ratio))
height = int(math.floor(image.shape[0] * ratio))
channels = image.shape[2]
out = np.ndarray((height, width, channels), dtype=np.uint8)
for x, y in np.ndindex((width, height)):
out[y, x] = image[int(math.floor(y / ratio)), int(math.floor(x / ratio))]
return out
def resize_image(image, height, width,
channels=None,
resize_mode=None
):
if resize_mode is None:
resize_mode = 'squash'
if resize_mode not in ['crop', 'squash', 'fill', 'half_crop']:
raise ValueError('resize_mode "%s" not supported' % resize_mode)
if channels not in [None, 1, 3]:
raise ValueError('unsupported number of channels: %s' % channels)
if isinstance(image, PIL.Image.Image):
if channels is None:
image_mode = image.mode
if image_mode == 'L':
channels = 1
elif image_mode == 'RGB':
channels = 3
else:
raise ValueError('unknown image mode "%s"' % image_mode)
elif channels == 1:
image_mode = 'L'
elif channels == 3:
image_mode = 'RGB'
if image.mode != image_mode:
image = image.convert(image_mode)
image = np.array(image)
elif isinstance(image, np.ndarray):
if image.dtype != np.uint8:
image = image.astype(np.uint8)
if image.ndim == 3 and image.shape[2] == 1:
image = image.reshape(image.shape[:2])
if channels is None:
if image.ndim == 2:
channels = 1
elif image.ndim == 3 and image.shape[2] == 3:
channels = 3
else:
raise ValueError('invalid image shape: %s' % (image.shape,))
elif channels == 1:
if image.ndim != 2:
if image.ndim == 3 and image.shape[2] == 3:
image = np.dot(image, [0.299, 0.587, 0.114]).astype(np.uint8)
else:
raise ValueError('invalid image shape: %s' % (image.shape,))
elif channels == 3:
if image.ndim == 2:
image = np.repeat(image, 3).reshape(image.shape + (3,))
elif image.shape[2] != 3:
raise ValueError('invalid image shape: %s' % (image.shape,))
else:
raise ValueError('resize_image() expected a PIL.Image.Image or a numpy.ndarray')
if image.shape[0] == height and image.shape[1] == width:
return image
interp = 'bilinear'
width_ratio = float(image.shape[1]) / width
height_ratio = float(image.shape[0]) / height
if resize_mode == 'squash' or width_ratio == height_ratio:
return imresize(image, (height, width), interp=interp)
elif resize_mode == 'crop':
if width_ratio > height_ratio:
resize_height = height
resize_width = int(round(image.shape[1] / height_ratio))
else:
resize_width = width
resize_height = int(round(image.shape[0] / width_ratio))
image = imresize(image, (resize_height, resize_width), interp=interp)
if width_ratio > height_ratio:
start = int(round((resize_width - width) / 2.0))
return image[:, start:start + width]
else:
start = int(round((resize_height - height) / 2.0))
return image[start:start + height, :]
else:
if resize_mode == 'fill':
if width_ratio > height_ratio:
resize_width = width
resize_height = int(round(image.shape[0] / width_ratio))
if (height - resize_height) % 2 == 1:
resize_height += 1
else:
resize_height = height
resize_width = int(round(image.shape[1] / height_ratio))
if (width - resize_width) % 2 == 1:
resize_width += 1
image = imresize(image, (resize_height, resize_width), interp=interp)
elif resize_mode == 'half_crop':
new_ratio = (width_ratio + height_ratio) / 2.0
resize_width = int(round(image.shape[1] / new_ratio))
resize_height = int(round(image.shape[0] / new_ratio))
if width_ratio > height_ratio and (height - resize_height) % 2 == 1:
resize_height += 1
elif width_ratio < height_ratio and (width - resize_width) % 2 == 1:
resize_width += 1
image = imresize(image, (resize_height, resize_width), interp=interp)
if width_ratio > height_ratio:
start = int(round((resize_width - width) / 2.0))
image = image[:, start:start + width]
else:
start = int(round((resize_height - height) / 2.0))
image = image[start:start + height, :]
else:
raise Exception('unrecognized resize_mode "%s"' % resize_mode)
if width_ratio > height_ratio:
padding = (height - resize_height) / 2
noise_size = (padding, width)
if channels > 1:
noise_size += (channels,)
noise = np.random.randint(0, 255, noise_size).astype('uint8')
image = np.concatenate((noise, image, noise), axis=0)
else:
padding = (width - resize_width) / 2
noise_size = (height, padding)
if channels > 1:
noise_size += (channels,)
noise = np.random.randint(0, 255, noise_size).astype('uint8')
image = np.concatenate((noise, image, noise), axis=1)
return image
def embed_image_html(image):
if image is None:
return None
elif isinstance(image, PIL.Image.Image):
pass
elif isinstance(image, np.ndarray):
image = PIL.Image.fromarray(image)
else:
raise ValueError('image must be a PIL.Image or a np.ndarray')
fmt = image.format
if not fmt:
fmt = 'jpeg'
else:
fmt = fmt.lower()
string_buf = StringIO()
image.save(string_buf, format=fmt)
data = string_buf.getvalue().encode('base64').replace('\n', '')
return 'data:image/%s;base64,%s' % (fmt, data)
def add_bboxes_to_image(image, bboxes, color='red', width=1):
def expanded_bbox(bbox, n):
l = min(bbox[0][0], bbox[1][0])
r = max(bbox[0][0], bbox[1][0])
t = min(bbox[0][1], bbox[1][1])
b = max(bbox[0][1], bbox[1][1])
return ((l - n, t - n), (r + n, b + n))
from PIL import Image, ImageDraw
draw = ImageDraw.Draw(image)
for bbox in bboxes:
for n in range(width):
draw.rectangle(expanded_bbox(bbox, n), outline=color)
return image
def get_layer_vis_square(data,
allow_heatmap=True,
normalize=True,
min_img_dim=100,
max_width=1200,
channel_order='RGB',
colormap='jet',
):
if channel_order not in ['RGB', 'BGR']:
raise ValueError('Unsupported channel_order %s' % channel_order)
if data.ndim == 1:
data = data[:, np.newaxis, np.newaxis]
elif data.ndim == 2:
data = data.reshape((data.shape[0] * data.shape[1], 1, 1))
elif data.ndim == 3:
if data.shape[0] == 3:
if channel_order == 'BGR':
data = data[[2, 1, 0], ...] data = data.transpose(1, 2, 0)
data = data[np.newaxis, ...]
else:
pass
elif data.ndim == 4:
if data.shape[0] == 3:
data = data.transpose(1, 2, 3, 0)
if channel_order == 'BGR':
data = data[:, :, :, [2, 1, 0]] elif data.shape[1] == 3:
data = data.transpose(0, 2, 3, 1)
if channel_order == 'BGR':
data = data[:, :, :, [2, 1, 0]] else:
data = data.reshape((data.shape[0] * data.shape[1], data.shape[2], data.shape[3]))
else:
raise RuntimeError('unrecognized data shape: %s' % (data.shape,))
return get_layer_vis_square_raw(data,
allow_heatmap,
normalize,
min_img_dim,
max_width,
colormap,
)
def get_image_tales(images, colormap='jet', min_img_dim=100, max_width=1000):
padsize = 1
images = images.astype('float32')
images -= images.min()
if images.max() > 0:
images /= images.max()
images *= 255
if images.ndim == 3:
# they're grayscale - convert to a colormap
redmap, greenmap, bluemap = get_color_map(colormap)
red = np.interp(images * (len(redmap) - 1) / 255.0, range(len(redmap)), redmap)
green = np.interp(images * (len(greenmap) - 1) / 255.0, range(len(greenmap)), greenmap)
blue = np.interp(images * (len(bluemap) - 1) / 255.0, range(len(bluemap)), bluemap)
images = np.concatenate(
(red[..., np.newaxis], green[..., np.newaxis], blue[..., np.newaxis]), axis=3)
images = np.minimum(images, 255)
images = np.maximum(images, 0)
images = images.astype('uint8')
n = int(np.ceil(np.sqrt(images.shape[0])))
ny = n
nx = n
length = images.shape[0]
if n * (n - 1) >= length:
nx = n - 1
padding = ((0, nx * ny - length), (0, padsize), (0, padsize)) + ((0, 0),) * (images.ndim - 3)
padded = np.pad(images, padding, mode='constant', constant_values=0)
tiles = padded.reshape(
(ny, nx) + padded.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded.ndim + 1)))
tiles = tiles.reshape((ny * tiles.shape[1], nx * tiles.shape[3]) + tiles.shape[4:])
return tiles
def get_layer_vis_square_raw(data,
allow_heatmap=True,
normalize=True,
min_img_dim=100,
max_width=1200,
colormap='jet',
):
padsize = 0
width = data.shape[2]
if width > max_width:
data = data[:1, :max_width, :max_width]
else:
if width > 1:
padsize = 1
width += 1
n = max(max_width // width, 1)
n *= n
data = data[:n]
if not allow_heatmap and data.ndim == 3:
data = data[..., np.newaxis]
vis = vis_square(data,
padsize=padsize,
normalize=normalize,
colormap=colormap
)
_min = sorted(vis.shape[:2])[0]
if _min < min_img_dim:
ratio = min_img_dim / float(_min)
vis = upscale(vis, ratio)
return vis
def vis_square(images,
padsize=1,
normalize=False,
colormap='jet',
):
assert 3 <= images.ndim <= 4, 'images.ndim must be 3 or 4'
images = images.astype('float32')
if normalize:
images -= images.min()
if images.max() > 0:
images /= images.max()
images *= 255
if images.ndim == 3:
# they're grayscale - convert to a colormap
redmap, greenmap, bluemap = get_color_map(colormap)
red = np.interp(images * (len(redmap) - 1) / 255.0, range(len(redmap)), redmap)
green = np.interp(images * (len(greenmap) - 1) / 255.0, range(len(greenmap)), greenmap)
blue = np.interp(images * (len(bluemap) - 1) / 255.0, range(len(bluemap)), bluemap)
images = np.concatenate(
(red[..., np.newaxis], green[..., np.newaxis], blue[..., np.newaxis]), axis=3)
images = np.minimum(images, 255)
images = np.maximum(images, 0)
images = images.astype('uint8')
n = int(np.ceil(np.sqrt(images.shape[0])))
ny = n
nx = n
length = images.shape[0]
if n * (n - 1) >= length:
nx = n - 1
padding = ((0, nx * ny - length), (0, padsize), (0, padsize)) + ((0, 0),) * (images.ndim - 3)
padded = np.pad(images, padding, mode='constant', constant_values=255)
tiles = padded.reshape(
(ny, nx) + padded.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded.ndim + 1)))
tiles = tiles.reshape((ny * tiles.shape[1], nx * tiles.shape[3]) + tiles.shape[4:])
if tiles.shape[-1] == 1:
tiles = np.dstack([tiles.squeeze()] * 3)
return tiles
def get_color_map(name):
redmap = [0]
greenmap = [0]
bluemap = [0]
if name == 'white':
redmap = [0, 1]
greenmap = [0, 1]
bluemap = [0, 1]
elif name == 'simple':
redmap = [0, 1, 1, 1]
greenmap = [0, 0, 1, 1]
bluemap = [0, 0, 0, 1]
elif name == 'hot':
redmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952,
0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936, 0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
greenmap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603163, 0.0714285714285714, 0.1111111111111112, 0.1507936507936507, 0.1904761904761905, 0.23015873015873, 0.2698412698412698, 0.3095238095238093, 0.3492063492063491, 0.3888888888888888, 0.4285714285714284,
0.4682539682539679, 0.5079365079365079, 0.5476190476190477, 0.5873015873015872, 0.6269841269841268, 0.6666666666666665, 0.7063492063492065, 0.746031746031746, 0.7857142857142856, 0.8253968253968254, 0.8650793650793651, 0.9047619047619047, 0.9444444444444442, 0.984126984126984, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904761904745, 0.1269841269841265,
0.2063492063492056, 0.2857142857142856, 0.3650793650793656, 0.4444444444444446, 0.5238095238095237, 0.6031746031746028, 0.6825396825396828, 0.7619047619047619, 0.8412698412698409, 0.92063492063492, 1]
elif name == 'rainbow':
redmap = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9365079365079367, 0.8571428571428572, 0.7777777777777777, 0.6984126984126986, 0.6190476190476191, 0.53968253968254, 0.4603174603174605, 0.3809523809523814, 0.3015873015873018, 0.2222222222222223, 0.1428571428571432,
0.06349206349206415, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603208, 0.08465608465608465, 0.1375661375661377, 0.1904761904761907, 0.2433862433862437, 0.2962962962962963, 0.3492063492063493, 0.4021164021164023, 0.4550264550264553, 0.5079365079365079, 0.5608465608465609, 0.6137566137566139, 0.666666666666667]
greenmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952, 0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936,
0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9841269841269842, 0.9047619047619047, 0.8253968253968256, 0.7460317460317465, 0.666666666666667, 0.587301587301587, 0.5079365079365079, 0.4285714285714288, 0.3492063492063493, 0.2698412698412698, 0.1904761904761907, 0.1111111111111116, 0.03174603174603208, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01587301587301582, 0.09523809523809534, 0.1746031746031744, 0.2539682539682535,
0.333333333333333, 0.412698412698413, 0.4920634920634921, 0.5714285714285712, 0.6507936507936507, 0.7301587301587302, 0.8095238095238093, 0.8888888888888884, 0.9682539682539679, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
elif name == 'winter':
greenmap = [0, 1]
bluemap = [1, 0.5]
else:
if name != 'jet':
print('Warning: colormap "%s" not supported. Using jet instead.' % name)
redmap = [0, 0, 0, 0, 0.5, 1, 1, 1, 0.5]
greenmap = [0, 0, 0.5, 1, 1, 1, 0.5, 0, 0]
bluemap = [0.5, 1, 1, 1, 0.5, 0, 0, 0, 0]
return 255.0 * np.array(redmap), 255.0 * np.array(greenmap), 255.0 * np.array(bluemap)
| true | true |
f72a2d4074dad48939a61e0cf5afc75f21b803b0 | 4,053 | py | Python | configs/Misc/torchvision_imagenet_R_50.py | lkeab/detectron2 | d4d2948aed6c0c73558da10f8647661f61470e37 | [
"Apache-2.0"
] | 4 | 2021-05-24T04:43:33.000Z | 2022-03-29T04:59:31.000Z | configs/Misc/torchvision_imagenet_R_50.py | lkeab/detectron2 | d4d2948aed6c0c73558da10f8647661f61470e37 | [
"Apache-2.0"
] | 1 | 2021-06-16T07:01:43.000Z | 2021-11-09T03:48:47.000Z | configs/Misc/torchvision_imagenet_R_50.py | lkeab/detectron2 | d4d2948aed6c0c73558da10f8647661f61470e37 | [
"Apache-2.0"
] | 2 | 2022-03-13T09:35:32.000Z | 2022-03-29T05:04:08.000Z | """
An example config file to train a ImageNet classifier with detectron2.
Model and dataloader both come from torchvision.
This shows how to use detectron2 as a general engine for any new models and tasks.
To run, use the following command:
python tools/lazyconfig_train_net.py --config-file configs/Misc/torchvision_imagenet_R_50.py \
--num-gpus 8 dataloader.train.dataset.root=/path/to/imagenet/
"""
import torch
from torch import nn
from torch.nn import functional as F
from omegaconf import OmegaConf
import torchvision
from torchvision.transforms import transforms as T
from torchvision.models.resnet import ResNet, Bottleneck
from fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2.solver import WarmupParamScheduler
from detectron2.solver.build import get_default_optimizer_params
from detectron2.config import LazyCall as L
from detectron2.model_zoo import get_config
from detectron2.data.samplers import TrainingSampler, InferenceSampler
from detectron2.evaluation import DatasetEvaluator
from detectron2.utils import comm
def build_data_loader(dataset, batch_size, num_workers, training=True):
return torch.utils.data.DataLoader(
dataset,
sampler=(TrainingSampler if training else InferenceSampler)(len(dataset)),
batch_size=batch_size,
num_workers=num_workers,
pin_memory=True,
)
class ClassificationNet(nn.Module):
def __init__(self, model: nn.Module):
super().__init__()
self.model = model
@property
def device(self):
return list(self.model.parameters())[0].device
def forward(self, inputs):
image, label = inputs
pred = self.model(image.to(self.device))
if self.training:
label = label.to(self.device)
return F.cross_entropy(pred, label)
else:
return pred
class ClassificationAcc(DatasetEvaluator):
def reset(self):
self.corr = self.total = 0
def process(self, inputs, outputs):
image, label = inputs
self.corr += (outputs.argmax(dim=1).cpu() == label.cpu()).sum().item()
self.total += len(label)
def evaluate(self):
all_corr_total = comm.all_gather([self.corr, self.total])
corr = sum(x[0] for x in all_corr_total)
total = sum(x[1] for x in all_corr_total)
return {"accuracy": corr / total}
dataloader = OmegaConf.create()
dataloader.train = L(build_data_loader)(
dataset=L(torchvision.datasets.ImageNet)(
root="/path/to/imagenet",
split="train",
transform=L(T.Compose)(
transforms=[
L(T.RandomResizedCrop)(size=224),
L(T.RandomHorizontalFlip)(),
T.ToTensor(),
L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
]
),
),
batch_size=256 // 8,
num_workers=4,
training=True,
)
dataloader.test = L(build_data_loader)(
dataset=L(torchvision.datasets.ImageNet)(
root="${...train.dataset.root}",
split="val",
transform=L(T.Compose)(
transforms=[
L(T.Resize)(size=256),
L(T.CenterCrop)(size=224),
T.ToTensor(),
L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
]
),
),
batch_size=256 // 8,
num_workers=4,
training=False,
)
dataloader.evaluator = L(ClassificationAcc)()
model = L(ClassificationNet)(
model=(ResNet)(block=Bottleneck, layers=[3, 4, 6, 3], zero_init_residual=True)
)
optimizer = L(torch.optim.SGD)(
params=L(get_default_optimizer_params)(),
lr=0.1,
momentum=0.9,
weight_decay=1e-4,
)
lr_multiplier = L(WarmupParamScheduler)(
scheduler=L(MultiStepParamScheduler)(
values=[1.0, 0.1, 0.01, 0.001], milestones=[30, 60, 90, 100]
),
warmup_length=1 / 100,
warmup_factor=0.1,
)
train = get_config("common/train.py").train
train.init_checkpoint = None
train.max_iter = 100 * 1281167 // 256
| 29.369565 | 94 | 0.658278 |
import torch
from torch import nn
from torch.nn import functional as F
from omegaconf import OmegaConf
import torchvision
from torchvision.transforms import transforms as T
from torchvision.models.resnet import ResNet, Bottleneck
from fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2.solver import WarmupParamScheduler
from detectron2.solver.build import get_default_optimizer_params
from detectron2.config import LazyCall as L
from detectron2.model_zoo import get_config
from detectron2.data.samplers import TrainingSampler, InferenceSampler
from detectron2.evaluation import DatasetEvaluator
from detectron2.utils import comm
def build_data_loader(dataset, batch_size, num_workers, training=True):
return torch.utils.data.DataLoader(
dataset,
sampler=(TrainingSampler if training else InferenceSampler)(len(dataset)),
batch_size=batch_size,
num_workers=num_workers,
pin_memory=True,
)
class ClassificationNet(nn.Module):
def __init__(self, model: nn.Module):
super().__init__()
self.model = model
@property
def device(self):
return list(self.model.parameters())[0].device
def forward(self, inputs):
image, label = inputs
pred = self.model(image.to(self.device))
if self.training:
label = label.to(self.device)
return F.cross_entropy(pred, label)
else:
return pred
class ClassificationAcc(DatasetEvaluator):
def reset(self):
self.corr = self.total = 0
def process(self, inputs, outputs):
image, label = inputs
self.corr += (outputs.argmax(dim=1).cpu() == label.cpu()).sum().item()
self.total += len(label)
def evaluate(self):
all_corr_total = comm.all_gather([self.corr, self.total])
corr = sum(x[0] for x in all_corr_total)
total = sum(x[1] for x in all_corr_total)
return {"accuracy": corr / total}
dataloader = OmegaConf.create()
dataloader.train = L(build_data_loader)(
dataset=L(torchvision.datasets.ImageNet)(
root="/path/to/imagenet",
split="train",
transform=L(T.Compose)(
transforms=[
L(T.RandomResizedCrop)(size=224),
L(T.RandomHorizontalFlip)(),
T.ToTensor(),
L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
]
),
),
batch_size=256 // 8,
num_workers=4,
training=True,
)
dataloader.test = L(build_data_loader)(
dataset=L(torchvision.datasets.ImageNet)(
root="${...train.dataset.root}",
split="val",
transform=L(T.Compose)(
transforms=[
L(T.Resize)(size=256),
L(T.CenterCrop)(size=224),
T.ToTensor(),
L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
]
),
),
batch_size=256 // 8,
num_workers=4,
training=False,
)
dataloader.evaluator = L(ClassificationAcc)()
model = L(ClassificationNet)(
model=(ResNet)(block=Bottleneck, layers=[3, 4, 6, 3], zero_init_residual=True)
)
optimizer = L(torch.optim.SGD)(
params=L(get_default_optimizer_params)(),
lr=0.1,
momentum=0.9,
weight_decay=1e-4,
)
lr_multiplier = L(WarmupParamScheduler)(
scheduler=L(MultiStepParamScheduler)(
values=[1.0, 0.1, 0.01, 0.001], milestones=[30, 60, 90, 100]
),
warmup_length=1 / 100,
warmup_factor=0.1,
)
train = get_config("common/train.py").train
train.init_checkpoint = None
train.max_iter = 100 * 1281167 // 256
| true | true |
f72a2ec186c24a531378756e12879ab2a4ae97af | 60,347 | py | Python | python/GafferUI/UIEditor.py | hypothetical-inc/gaffer | 7da631400cfac5399255d23ff296f677e96c7540 | [
"BSD-3-Clause"
] | 49 | 2018-08-27T07:52:25.000Z | 2022-02-08T13:54:05.000Z | python/GafferUI/UIEditor.py | hypothetical-inc/gaffer | 7da631400cfac5399255d23ff296f677e96c7540 | [
"BSD-3-Clause"
] | 21 | 2018-11-27T16:00:32.000Z | 2022-03-23T20:01:55.000Z | python/GafferUI/UIEditor.py | themissingcow/gaffer | b636debeb2c918fde55b3f4ef53fbc2e1e9ab78a | [
"BSD-3-Clause"
] | 4 | 2018-12-23T16:16:41.000Z | 2021-06-16T09:04:01.000Z | ##########################################################################
#
# Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import weakref
import functools
import types
import re
import six
import collections
import imath
import inspect
import string
import IECore
import Gaffer
import GafferUI
from . import MetadataWidget
## The UIEditor class allows the user to edit the interfaces for nodes.
class UIEditor( GafferUI.NodeSetEditor ) :
def __init__( self, scriptNode, **kw ) :
self.__frame = GafferUI.Frame( borderWidth = 0, borderStyle = GafferUI.Frame.BorderStyle.None_ )
GafferUI.NodeSetEditor.__init__( self, self.__frame, scriptNode, **kw )
# Build the UI. Initially this isn't connected up to any node - we'll
# perform the connections in _updateFromSet().
######################################################################
self.__nodeMetadataWidgets = []
self.__plugMetadataWidgets = []
with self.__frame :
self.__tabbedContainer = GafferUI.TabbedContainer()
with self.__tabbedContainer :
# Node tab
with GafferUI.ListContainer( spacing = 4, borderWidth = 8, parenting = { "label" : "Node" } ) as self.__nodeTab :
with _Row() :
_Label( "Name" )
self.__nodeNameWidget = GafferUI.NameWidget( None )
with _Row() :
_Label( "Description", parenting = { "verticalAlignment" : GafferUI.ListContainer.VerticalAlignment.Top } )
self.__nodeMetadataWidgets.append(
MetadataWidget.MultiLineStringMetadataWidget( key = "description" )
)
with _Row() :
_Label( "Documentation URL" )
self.__nodeMetadataWidgets.append(
MetadataWidget.StringMetadataWidget( key = "documentation:url" )
)
with _Row() :
_Label( "Color" )
self.__nodeMetadataWidgets.append(
MetadataWidget.ColorSwatchMetadataWidget( key = "nodeGadget:color", defaultValue = imath.Color3f( 0.4 ) )
)
with _Row() as self.__iconRow :
_Label( "Icon" )
self.__nodeMetadataWidgets.append(
MetadataWidget.FileSystemPathMetadataWidget( key = "icon" )
)
with _Row() as self.__plugAddButtons :
_Label( "Plug Creators" )
for side in ( "Top", "Bottom", "Left", "Right" ) :
_Label( side )._qtWidget().setFixedWidth( 40 )
self.__nodeMetadataWidgets.append( MetadataWidget.BoolMetadataWidget(
key = "noduleLayout:customGadget:addButton%s:visible" % side,
defaultValue = True
) )
# Plugs tab
with GafferUI.SplitContainer( orientation=GafferUI.SplitContainer.Orientation.Horizontal, borderWidth = 8, parenting = { "label" : "Plugs" } ) as self.__plugTab :
self.__plugListing = _PlugListing()
self.__plugListing.selectionChangedSignal().connect( Gaffer.WeakMethod( self.__plugListingSelectionChanged ), scoped = False )
with GafferUI.TabbedContainer() as self.__plugAndSectionEditorsContainer :
self.__plugEditor = _PlugEditor()
self.__sectionEditor = _SectionEditor()
self.__sectionEditor.nameChangedSignal().connect( Gaffer.WeakMethod( self.__sectionEditorNameChanged ), scoped = False )
self.__plugAndSectionEditorsContainer.setTabsVisible( False )
self.__plugTab.setSizes( [ 0.3, 0.7 ] )
# initialise our selection to nothing
self.__node = None
self.__selectedPlug = None
# call __updateFromSetInternal() to populate our selection and connect
# the ui to it. we pass lazy==False to avoid the early out if
# there is no currently selected node.
self.__updateFromSetInternal( lazy=False )
# Selection can be None, a Plug, or the name of a section.
def setSelection( self, selection ) :
self.__plugListing.setSelection( selection )
def getSelection( self ) :
return self.__plugListing.getSelection()
## Returns the widget layout responsible for editing the node as a whole.
def nodeEditor( self ) :
return self.__nodeTab
## Returns the widget layout responsible for editing individual plugs.
def plugEditor( self ) :
return self.__plugTab
@classmethod
def appendNodeContextMenuDefinitions( cls, graphEditor, node, menuDefinition ) :
menuDefinition.append( "/UIEditorDivider", { "divider" : True } )
menuDefinition.append(
"/Set Color...",
{
"command" : functools.partial( cls.__setColor, node = node ),
"active" : not Gaffer.MetadataAlgo.readOnly( node ),
}
)
nodeGadgetTypes = Gaffer.Metadata.value( node, "uiEditor:nodeGadgetTypes" )
if nodeGadgetTypes :
nodeGadgetTypes = set( nodeGadgetTypes )
if nodeGadgetTypes == { "GafferUI::AuxiliaryNodeGadget", "GafferUI::StandardNodeGadget" } :
nodeGadgetType = Gaffer.Metadata.value( node, "nodeGadget:type" ) or "GafferUI::StandardNodeGadget"
menuDefinition.append(
"/Show Name",
{
"command" : functools.partial( cls.__setNameVisible, node ),
"checkBox" : nodeGadgetType == "GafferUI::StandardNodeGadget",
"active" : not Gaffer.MetadataAlgo.readOnly( node ),
}
)
else :
# We want to present the options above as a simple "Show Name" checkbox, and haven't yet
# decided how to present other combinations of allowable gadgets.
IECore.msg( IECore.msg.Warning, "UIEditor", 'Unknown combination of "uiEditor:nodeGadgetTypes"' )
@classmethod
def appendNodeEditorToolMenuDefinitions( cls, nodeEditor, node, menuDefinition ) :
menuDefinition.append( "/Edit UI Divider", { "divider" : True } )
menuDefinition.append(
"/Edit UI...",
{
"command" : functools.partial( GafferUI.UIEditor.acquire, node ),
"active" : (
( isinstance( node, Gaffer.Box ) or nodeEditor.nodeUI().plugValueWidget( node["user"] ) is not None ) and
not Gaffer.MetadataAlgo.readOnly( node )
)
}
)
## Registers a custom PlugValueWidget type for a plug type, so it can be selected in the UIEditor
# label: String with the label to be displayed for this widget.
# plugType: Gaffer.Plug class that can use the widget being registered.
# metadata: String with associated metadata for the widget. Usually the python identifier for the widget (ex: "GafferUI.BoolPlugValueWidget").
@classmethod
def registerPlugValueWidget( cls, label, plugType, metadata ) :
# simply calls protected _PlugEditor implementation
_PlugEditor.registerPlugValueWidget( label, plugType, metadata )
## Register additional metadata for PlugValueWidgets
# label: string with the label to be displayed for this widget
# plugValueWidgetType: string with the "plugValueWidget:type" metadata value where this settings applies, or a pattern for it.
# widgetCreator: callable that receives the plug and returns a MetadataWidget (or another widget) to edit the metadata
@classmethod
def registerWidgetSetting( cls, label, plugValueWidgetType, widgetCreator ) :
# simply calls protected _PlugEditor implementation
_PlugEditor.registerWidgetSetting( label, plugValueWidgetType, widgetCreator )
## Utility to quickly register widgets to edit metadata for PlugValueWidgets
# It uses the defaultValue provided in order to determine the appropriate widget to be used
# label: string with the label to be displayed for this widget
# plugValueWidgetType: string with the "plugValueWidget:type" metadata value where this settings applies, or a pattern for it.
# key: metadata key to be set by the widget
# defaultValue: default value for the metadata
@classmethod
def registerWidgetMetadata( cls, label, plugValueWidgetType, key, defaultValue ) :
if isinstance( defaultValue, bool ) :
widgetClass = MetadataWidget.BoolMetadataWidget
elif isinstance( defaultValue, six.string_types ) :
widgetClass = MetadataWidget.StringMetadataWidget
elif isinstance( defaultValue, imath.Color4f ) :
widgetClass = MetadataWidget.ColorSwatchMetadataWidget
else :
raise Exception( "Could not determine the widget to use from defaultValue: {}.".format( repr( defaultValue ) ) )
cls.registerWidgetSetting(
label,
plugValueWidgetType,
lambda plug : widgetClass( key, target=plug, defaultValue=defaultValue )
)
def _updateFromSet( self ) :
GafferUI.NodeSetEditor._updateFromSet( self )
self.__updateFromSetInternal()
def __updateFromSetInternal( self, lazy=True ) :
node = self._lastAddedNode()
if lazy and node == self.__node :
return
self.__node = node
self.__nodeNameWidget.setGraphComponent( self.__node )
self.__nodeTab.setEnabled( self.__node is not None )
self.__plugAddButtons.setVisible( False )
if self.__node is None :
self.__plugListing.setPlugParent( None )
self.__sectionEditor.setPlugParent( None )
else :
plugParent = self.__node["user"]
if isinstance( self.__node, Gaffer.Box ) :
# For Boxes we want the user to edit the plugs directly
# parented to the Box, because that is where promoted plugs go,
# and because we want to leave the "user" plug empty so that it
# is available for use by the user on Reference nodes once a Box has
# been exported and referenced.
plugParent = self.__node
self.__plugAddButtons.setVisible( True )
self.__plugListing.setPlugParent( plugParent )
self.__sectionEditor.setPlugParent( plugParent )
for widget in self.__nodeMetadataWidgets :
widget.setTarget( self.__node )
self.setSelection( None )
def __plugListingSelectionChanged( self, listing ) :
selection = listing.getSelection()
if selection is None or isinstance( selection, Gaffer.Plug ) :
self.__plugEditor.setPlug( selection )
self.__plugAndSectionEditorsContainer.setCurrent( self.__plugEditor )
elif isinstance( selection, six.string_types ) :
self.__plugEditor.setPlug( None )
self.__sectionEditor.setSection( selection )
self.__plugAndSectionEditorsContainer.setCurrent( self.__sectionEditor )
def __sectionEditorNameChanged( self, sectionEditor, oldName, newName ) :
# When the name changed, our plug listing will have lost its
# selection. So give it a helping hand.
self.__plugListing.setSelection( newName )
def __repr__( self ) :
return "GafferUI.UIEditor( scriptNode )"
@classmethod
def __setColor( cls, menu, node ) :
color = Gaffer.Metadata.value( node, "nodeGadget:color" ) or imath.Color3f( 1 )
dialogue = GafferUI.ColorChooserDialogue( color = color, useDisplayTransform = False )
color = dialogue.waitForColor( parentWindow = menu.ancestor( GafferUI.Window ) )
if color is not None :
with Gaffer.UndoScope( node.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue( node, "nodeGadget:color", color )
@staticmethod
def __setNameVisible( node, nameVisible ) :
with Gaffer.UndoScope( node.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue(
node, "nodeGadget:type",
"GafferUI::StandardNodeGadget" if nameVisible else "GafferUI::AuxiliaryNodeGadget"
)
GafferUI.Editor.registerType( "UIEditor", UIEditor )
##########################################################################
# PlugValueWidget popup menu
##########################################################################
def __editPlugUI( node, plug ) :
editor = GafferUI.UIEditor.acquire( node )
editor.setSelection( plug )
editor.plugEditor().reveal()
def __plugPopupMenu( menuDefinition, plugValueWidget ) :
plug = plugValueWidget.getPlug()
node = plug.node()
if node is None :
return
if isinstance( node, Gaffer.Box ) :
if not plug.parent().isSame( node ) :
return
else :
if not plug.parent().isSame( node["user"] ) :
return
menuDefinition.append( "/EditUIDivider", { "divider" : True } )
menuDefinition.append( "/Edit UI...",
{
"command" : functools.partial( __editPlugUI, node, plug ),
"active" : not plugValueWidget.getReadOnly() and not Gaffer.MetadataAlgo.readOnly( plug )
}
)
GafferUI.PlugValueWidget.popupMenuSignal().connect( __plugPopupMenu, scoped = False )
##########################################################################
# Simple fixed width label and row classes
##########################################################################
class _Label( GafferUI.Label ) :
def __init__( self, *args, **kw ) :
GafferUI.Label.__init__(
self,
horizontalAlignment = GafferUI.Label.HorizontalAlignment.Right,
*args, **kw
)
self._qtWidget().setFixedWidth( 110 )
class _Row( GafferUI.ListContainer ) :
def __init__( self, *args, **kw ) :
GafferUI.ListContainer.__init__( self, GafferUI.ListContainer.Orientation.Horizontal, spacing = 4, *args, **kw )
##########################################################################
# Hierarchical representation of a plug layout, suitable for manipulating
# by the _PlugListing.
# \todo Consider sharing this data structure with the PlugLayout itself,
# rather than each using a different internal representation. If we did
# this then the data structure itself should take care of the mapping
# to/from metadata.
##########################################################################
class _LayoutItem( object ) :
def __init__( self ) :
self.__parent = None
self.__children = []
def parent( self ) :
if self.__parent is None :
return None
else :
return self.__parent()
def child( self, name ) :
for c in self.__children :
if c.name() == name :
return c
return None
def isAncestorOf( self, item ) :
while item is not None :
parent = item.parent()
if parent is self :
return True
item = parent
return False
def append( self, child ) :
self.insert( len( self ), child )
def insert( self, index, child ) :
assert( child.parent() is None )
self.__children.insert( index, child )
child.__parent = weakref.ref( self )
def remove( self, child ) :
assert( child.parent() is self )
self.__children.remove( child )
child.__parent = None
def index( self, child ) :
return self.__children.index( child )
def name( self ) :
raise NotImplementedError
def fullName( self ) :
result = ""
item = self
while item.parent() is not None :
if result :
result = item.name() + "." + result
else :
result = item.name()
item = item.parent()
return result
def __len__( self ) :
return len( self.__children )
def __getitem__( self, index ) :
return self.__children[index]
class _SectionLayoutItem( _LayoutItem ) :
def __init__( self, sectionName ) :
_LayoutItem.__init__( self )
self.__sectionName = sectionName
def name( self ) :
return self.__sectionName
class _PlugLayoutItem( _LayoutItem ) :
def __init__( self, plug ) :
_LayoutItem.__init__( self )
self.plug = plug
self.__name = plug.getName()
def name( self ) :
return self.__name
##########################################################################
# _PlugListing. This is used to list the plugs in the UIEditor,
# organised into their respective sections.
##########################################################################
class _PlugListing( GafferUI.Widget ) :
class __LayoutPath( Gaffer.Path ) :
def __init__( self, rootItem, path, root="/", filter = None ) :
Gaffer.Path.__init__( self, path, root, filter )
self.__rootItem = rootItem
def rootItem( self ) :
return self.__rootItem
def item( self ) :
result = self.__rootItem
for name in self :
result = result.child( name )
if result is None :
return None
return result
def copy( self ) :
return self.__class__( self.__rootItem, self[:], self.root(), self.getFilter() )
def isLeaf( self ) :
return not isinstance( self.item(), _SectionLayoutItem )
def isValid( self ) :
return self.item() is not None
def _children( self ) :
item = self.item()
if item is None :
return []
result = [
self.__class__( self.__rootItem, self[:] + [ c.name() ], self.root(), self.getFilter() )
for c in item
]
# Add a placeholder child into empty sections, to be used as a drag target
# in __dragMove()
if len( result ) == 0 and isinstance( item, _SectionLayoutItem ) :
result.append( self.__class__( self.__rootItem, self[:] + [ " " ], self.root(), self.getFilter() ) )
return result
def __init__( self, **kw ) :
column = GafferUI.ListContainer( spacing = 4 )
GafferUI.Widget.__init__( self, column, **kw )
# We don't have a way to do this with Widget directly at present, this
# stops the preset name/value fields being off-screen.
column._qtWidget().setMinimumWidth( 650 )
with column :
self.__pathListing = GafferUI.PathListingWidget(
self.__LayoutPath( _SectionLayoutItem( "" ), "/" ),
# listing displays the plug name and automatically sorts based on plug index
columns = ( GafferUI.PathListingWidget.defaultNameColumn, ),
displayMode = GafferUI.PathListingWidget.DisplayMode.Tree,
)
self.__pathListing.setDragPointer( "" )
self.__pathListing.setSortable( False )
self.__pathListing.setHeaderVisible( False )
with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) :
GafferUI.MenuButton(
image = "plus.png",
hasFrame = False,
menu = GafferUI.Menu(
definition = Gaffer.WeakMethod( self.__addMenuDefinition )
)
)
self.__deleteButton = GafferUI.Button( image = "minus.png", hasFrame = False )
self.__deleteButton.clickedSignal().connect( Gaffer.WeakMethod( self.__deleteButtonClicked ), scoped = False )
self.__parent = None # the parent of the plugs we're listing
self.__dragItem = None
self.__selectionChangedSignal = Gaffer.Signal1()
self.__pathListing.dragEnterSignal().connect( Gaffer.WeakMethod( self.__dragEnter ), scoped = False )
self.__pathListing.dragMoveSignal().connect( Gaffer.WeakMethod( self.__dragMove ), scoped = False )
self.__pathListing.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False )
self.__pathListing.selectionChangedSignal().connect( Gaffer.WeakMethod( self.__selectionChanged ), scoped = False )
self.keyPressSignal().connect( Gaffer.WeakMethod( self.__keyPress ), scoped = False )
def setPlugParent( self, parent ) :
assert( isinstance( parent, ( Gaffer.Plug, Gaffer.Node, type( None ) ) ) )
self.__parent = parent
self.__childAddedConnection = None
self.__childRemovedConnection = None
self.__childNameChangedConnections = {}
self.__metadataChangedConnections = []
if self.__parent is not None :
self.__childAddedConnection = self.__parent.childAddedSignal().connect( Gaffer.WeakMethod( self.__childAddedOrRemoved ) )
self.__childRemovedConnection = self.__parent.childRemovedSignal().connect( Gaffer.WeakMethod( self.__childAddedOrRemoved ) )
node = self.__parent if isinstance( self.__parent, Gaffer.Node ) else self.__parent.node()
self.__metadataChangedConnections = [
Gaffer.Metadata.nodeValueChangedSignal( node ).connect( Gaffer.WeakMethod( self.__nodeMetadataChanged ) ),
Gaffer.Metadata.plugValueChangedSignal( node ).connect( Gaffer.WeakMethod( self.__plugMetadataChanged ) )
]
for child in self.__parent.children() :
self.__updateChildNameChangedConnection( child )
self.__updatePath()
def getPlugParent( self ) :
return self.__parent
# Selection can be None, a Plug, or the name of a section.
def setSelection( self, selection ) :
self.__updatePathLazily.flush( self )
def findPlugPath( path, plug ) :
item = path.item()
if isinstance( item, _PlugLayoutItem ) and item.plug.isSame( plug ) :
return path
else :
for child in path.children() :
r = findPlugPath( child, plug )
if r is not None :
return r
return None
if isinstance( selection, Gaffer.Plug ) :
path = findPlugPath( self.__pathListing.getPath(), selection )
if path is None :
self.__pathListing.setSelectedPaths( [] )
else :
self.__pathListing.setSelectedPaths( [ path ] )
elif isinstance( selection, six.string_types ) :
path = self.__pathListing.getPath().copy()
path[:] = selection.split( "." )
self.__pathListing.setSelectedPaths( [ path ] )
else :
assert( selection is None )
self.__pathListing.setSelectedPaths( [] )
def getSelection( self ) :
item = self.__selectedItem()
if item is None :
return None
elif isinstance( item, _PlugLayoutItem ) :
return item.plug
elif isinstance( item, _SectionLayoutItem ) :
return item.fullName()
else :
return None
def selectionChangedSignal( self ) :
return self.__selectionChangedSignal
# Updates the path we show in the listing by building a layout based
# on the metadata.
def __updatePath( self ) :
if self.__parent is None :
# we have nothing to show - early out.
self.__pathListing.setPath( self.__LayoutPath( _SectionLayoutItem( "" ), "/" ) )
return
def section( rootLayoutItem, sectionPath ) :
sectionItem = rootLayoutItem
if sectionPath != "" :
for sectionName in sectionPath.split( "." ) :
childSectionItem = sectionItem.child( sectionName )
if childSectionItem is None :
childSectionItem = _SectionLayoutItem( sectionName )
sectionItem.append( childSectionItem )
sectionItem = childSectionItem
return sectionItem
layout = _SectionLayoutItem( "" )
for sectionPath in GafferUI.PlugLayout.layoutSections( self.__parent ) :
if sectionPath == "User" and isinstance( self.__parent, Gaffer.Node ) :
continue
sectionItem = section( layout, sectionPath )
for plug in GafferUI.PlugLayout.layoutOrder( self.__parent, section = sectionPath ) :
sectionItem.append( _PlugLayoutItem( plug ) )
emptySections = Gaffer.Metadata.value( self.getPlugParent(), "uiEditor:emptySections" )
emptySectionIndices = Gaffer.Metadata.value( self.getPlugParent(), "uiEditor:emptySectionIndices" )
if emptySections and emptySectionIndices :
for sectionPath, sectionIndex in zip( emptySections, emptySectionIndices ) :
parentPath, unused, sectionName = sectionPath.rpartition( "." )
parentSection = section( layout, parentPath )
if parentSection.child( sectionName ) is None :
parentSection.insert( sectionIndex, _SectionLayoutItem( sectionName ) )
if len( layout ) == 0 and isinstance( self.__parent, Gaffer.Node ) :
layout.append( _SectionLayoutItem( "Settings" ) )
expandedPaths = self.__pathListing.getExpandedPaths()
self.__pathListing.setPath( self.__LayoutPath( layout, "/" ) )
self.__pathListing.setExpandedPaths( expandedPaths )
@GafferUI.LazyMethod()
def __updatePathLazily( self ) :
self.__updatePath()
# Updates the metadata that controls the plug layout from the layout
# we show in the listing.
def __updateMetadata( self ) :
# Because sections only really exist by virtue of being requested
# by a plug, we must store empty sections separately for ourselves.
emptySections = IECore.StringVectorData()
emptySectionIndices = IECore.IntVectorData()
def walk( layoutItem, path = "", index = 0 ) :
for childItem in layoutItem :
if isinstance( childItem, _PlugLayoutItem ) :
Gaffer.Metadata.registerValue( childItem.plug, "layout:section", path )
Gaffer.Metadata.registerValue( childItem.plug, "layout:index", index )
index += 1
elif isinstance( childItem, _SectionLayoutItem ) :
childPath = path + "." + childItem.name() if path else childItem.name()
if len( childItem ) :
index = walk( childItem, childPath, index )
else :
emptySections.append( childPath )
emptySectionIndices.append( layoutItem.index( childItem ) )
return index
with Gaffer.BlockedConnection( self.__metadataChangedConnections ) :
walk( self.__pathListing.getPath().copy().setFromString( "/" ).item() )
Gaffer.Metadata.registerValue( self.getPlugParent(), "uiEditor:emptySections", emptySections )
Gaffer.Metadata.registerValue( self.getPlugParent(), "uiEditor:emptySectionIndices", emptySectionIndices )
def __childAddedOrRemoved( self, parent, child ) :
assert( parent.isSame( self.__parent ) )
self.__updateChildNameChangedConnection( child )
self.__updatePathLazily()
def __childNameChanged( self, child ) :
selection = self.getSelection()
self.__updatePath()
if isinstance( selection, Gaffer.Plug ) and child.isSame( selection ) :
# because the plug's name has changed. the path needed to
# keep it selected is different too, so we have to manually
# restore the selection.
self.setSelection( selection )
def __updateChildNameChangedConnection( self, child ) :
if self.__parent.isSame( child.parent() ) :
if child not in self.__childNameChangedConnections :
self.__childNameChangedConnections[child] = child.nameChangedSignal().connect( Gaffer.WeakMethod( self.__childNameChanged ) )
else :
if child in self.__childNameChangedConnections :
del self.__childNameChangedConnections[child]
def __dragEnter( self, listing, event ) :
# accept the drag if it originates with us,
# so __dragMove and __drop can implement
# drag and drop reordering of plugs.
if event.sourceWidget is not self.__pathListing :
return False
if not isinstance( event.data, IECore.StringVectorData ) :
return False
dragPath = self.__pathListing.getPath().copy().setFromString( event.data[0] )
self.__dragItem = dragPath.item()
# dragging around entire open sections is a bit confusing, so don't
self.__pathListing.setPathExpanded( dragPath, False )
return True
def __dragMove( self, listing, event ) :
if self.__dragItem is None :
return False
# update our layout structure to reflect the drag
#################################################
# find newParent and newIndex - variables specifying
# the new location for the dragged item.
targetPath = self.__pathListing.pathAt( event.line.p0 )
if targetPath is not None :
targetItem = targetPath.item()
if targetItem is not None :
if isinstance( targetItem, _SectionLayoutItem ) and self.__pathListing.getPathExpanded( targetPath ) and targetItem.parent() is self.__dragItem.parent() :
newParent = targetItem
newIndex = 0
else :
newParent = targetItem.parent()
newIndex = newParent.index( targetItem )
else :
# target is a placeholder added into an empty
# section by __LayoutPath._children().
newParent = targetPath.copy().truncateUntilValid().item()
newIndex = 0
else :
# drag has gone above or below all listed items
newParent = self.__pathListing.getPath().rootItem()
newIndex = 0 if event.line.p0.y < 1 else len( newParent )
# skip any attempted circular reparenting
if newParent is self.__dragItem or self.__dragItem.isAncestorOf( newParent ) :
return True
# disallow drags that would place a plug below a section
firstNonPlugIndex = next(
( x[0] for x in enumerate( newParent ) if not isinstance( x[1], _PlugLayoutItem ) ),
len( newParent )
)
if self.__dragItem.parent() is newParent and newParent.index( self.__dragItem ) < firstNonPlugIndex :
firstNonPlugIndex -= 1
if isinstance( self.__dragItem, _PlugLayoutItem ) :
if newIndex > firstNonPlugIndex :
return True
else :
if newIndex < firstNonPlugIndex :
newIndex = max( newIndex, firstNonPlugIndex )
self.__dragItem.parent().remove( self.__dragItem )
newParent.insert( newIndex, self.__dragItem )
# let the listing know we've been monkeying behind the scenes.
# we need to update the selection, because when we reparented
# the drag item its path will have changed.
##############################################################
self.__pathListing.getPath().pathChangedSignal()( self.__pathListing.getPath() )
selection = self.__pathListing.getPath().copy()
selection[:] = self.__dragItem.fullName().split( "." )
self.__pathListing.setSelectedPaths( [ selection ], scrollToFirst = False, expandNonLeaf = False )
return True
def __dragEnd( self, listing, event ) :
if self.__dragItem is None :
return False
with Gaffer.UndoScope( self.__parent.ancestor( Gaffer.ScriptNode ) ) :
self.__updateMetadata()
self.__dragItem = None
return True
def __selectionChanged( self, pathListing ) :
self.__deleteButton.setEnabled( bool( pathListing.getSelectedPaths() ) )
self.__selectionChangedSignal( self )
def __deleteButtonClicked( self, button ) :
self.__deleteSelected()
def __nodeMetadataChanged( self, node, key, reason ) :
if node != self.__parent :
return
if key in ( "uiEditor:emptySections", "uiEditor:emptySectionIndices" ) :
self.__updatePathLazily()
def __plugMetadataChanged( self, plug, key, reason ) :
if ( plug != self.__parent and plug.parent() != self.__parent ) :
return
if key in ( "layout:index", "layout:section", "uiEditor:emptySections", "uiEditor:emptySectionIndices" ) :
self.__updatePathLazily()
def __keyPress( self, widget, event ) :
assert( widget is self )
if event.key == "Backspace" or event.key == "Delete" :
self.__deleteSelected()
return True
return False
def __addMenuDefinition( self ) :
m = IECore.MenuDefinition()
m.append( "/Add Plug/Bool", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.BoolPlug ) } )
m.append( "/Add Plug/Float", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.FloatPlug ) } )
m.append( "/Add Plug/Int", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.IntPlug ) } )
m.append( "/Add Plug/NumericDivider", { "divider" : True } )
m.append( "/Add Plug/String", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.StringPlug ) } )
m.append( "/Add Plug/StringDivider", { "divider" : True } )
m.append( "/Add Plug/V2i", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V2iPlug ) } )
m.append( "/Add Plug/V3i", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V3iPlug ) } )
m.append( "/Add Plug/V2f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V2fPlug ) } )
m.append( "/Add Plug/V3f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V3fPlug ) } )
m.append( "/Add Plug/VectorDivider", { "divider" : True } )
m.append( "/Add Plug/Color3f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.Color3fPlug ) } )
m.append( "/Add Plug/Color4f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.Color4fPlug ) } )
m.append( "/Add Plug/ColorDivider", { "divider" : True } )
for label, plugType in [
( "Float", Gaffer.FloatVectorDataPlug ),
( "Int", Gaffer.IntVectorDataPlug ),
( "NumericDivider", None ),
( "String", Gaffer.StringVectorDataPlug ),
] :
if plugType is not None :
m.append(
"/Add Plug/Array/" + label,
{
"command" : functools.partial(
Gaffer.WeakMethod( self.__addPlug ),
plugCreator = functools.partial( plugType, defaultValue = plugType.ValueType() )
)
}
)
else :
m.append( "/Add Plug/Array/" + label, { "divider" : True } )
m.append( "/Add Plug Divider", { "divider" : True } )
m.append( "/Add Section", { "command" : Gaffer.WeakMethod( self.__addSection ) } )
return m
def __addPlug( self, plugCreator ) :
plug = plugCreator( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
Gaffer.Metadata.registerValue( plug, "nodule:type", "" )
parentItem = self.__selectedItem()
if parentItem is not None :
while not isinstance( parentItem, _SectionLayoutItem ) :
parentItem = parentItem.parent()
else :
parentItem = self.__pathListing.getPath().rootItem()
parentItem = next(
( c for c in parentItem if isinstance( c, _SectionLayoutItem ) ),
parentItem
)
Gaffer.Metadata.registerValue( plug, "layout:section", parentItem.fullName() )
with Gaffer.UndoScope( self.__parent.ancestor( Gaffer.ScriptNode ) ) :
self.getPlugParent().addChild( plug )
self.__updatePathLazily.flush( self )
self.setSelection( plug )
def __addSection( self ) :
rootItem = self.__pathListing.getPath().rootItem()
existingSectionNames = set( c.name() for c in rootItem if isinstance( c, _SectionLayoutItem ) )
name = "New Section"
index = 1
while name in existingSectionNames :
name = "New Section %d" % index
index += 1
rootItem.append( _SectionLayoutItem( name ) )
self.__pathListing.getPath().pathChangedSignal()( self.__pathListing.getPath() )
with Gaffer.UndoScope( self.__parent.ancestor( Gaffer.ScriptNode ) ) :
self.__updateMetadata()
self.__pathListing.setSelectedPaths(
self.__pathListing.getPath().copy().setFromString( "/" + name )
)
def __selectedItem( self ) :
selectedPaths = self.__pathListing.getSelectedPaths()
if not len( selectedPaths ) :
return None
assert( len( selectedPaths ) == 1 )
return selectedPaths[0].item()
def __deleteSelected( self ) :
selectedItem = self.__selectedItem()
if selectedItem is None :
return
selectedItem.parent().remove( selectedItem )
def deletePlugsWalk( item ) :
if isinstance( item, _PlugLayoutItem ) :
item.plug.parent().removeChild( item.plug )
else :
for childItem in item :
deletePlugsWalk( childItem )
with Gaffer.UndoScope( self.__parent.ancestor( Gaffer.ScriptNode ) ) :
deletePlugsWalk( selectedItem )
self.__updateMetadata()
##########################################################################
# _PresetsEditor. This provides a ui for editing the presets for a plug.
##########################################################################
class _PresetsEditor( GafferUI.Widget ) :
def __init__( self, **kw ) :
row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 8 )
GafferUI.Widget.__init__( self, row, **kw )
with row :
with GafferUI.ListContainer( spacing = 4 ) :
self.__pathListing = GafferUI.PathListingWidget(
Gaffer.DictPath( collections.OrderedDict(), "/" ),
columns = ( GafferUI.PathListingWidget.defaultNameColumn, ),
)
self.__pathListing.setDragPointer( "" )
self.__pathListing.setSortable( False )
self.__pathListing.setHeaderVisible( False )
self.__pathListing._qtWidget().setFixedWidth( 200 )
self.__pathListing._qtWidget().setFixedHeight( 200 )
self.__pathListing.selectionChangedSignal().connect( Gaffer.WeakMethod( self.__selectionChanged ), scoped = False )
self.__pathListing.dragEnterSignal().connect( Gaffer.WeakMethod( self.__dragEnter ), scoped = False )
self.__pathListing.dragMoveSignal().connect( Gaffer.WeakMethod( self.__dragMove ), scoped = False )
self.__pathListing.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False )
with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) :
self.__addButton = GafferUI.Button( image = "plus.png", hasFrame = False )
self.__addButton.clickedSignal().connect( Gaffer.WeakMethod( self.__addButtonClicked ), scoped = False )
self.__deleteButton = GafferUI.Button( image = "minus.png", hasFrame = False )
self.__deleteButton.clickedSignal().connect( Gaffer.WeakMethod( self.__deleteButtonClicked ), scoped = False )
with GafferUI.ListContainer( spacing = 4 ) as self.__editingColumn :
GafferUI.Label( "Name" )
self.__nameWidget = GafferUI.TextWidget()
self.__nameWidget.editingFinishedSignal().connect( Gaffer.WeakMethod( self.__nameEditingFinished ), scoped = False )
GafferUI.Spacer( imath.V2i( 4 ), maximumSize = imath.V2i( 4 ) )
GafferUI.Label( "Value" )
# We make a UI for editing preset values by copying the plug
# onto this node and then making a PlugValueWidget for it.
self.__valueNode = Gaffer.Node( "PresetEditor" )
self.__valuePlugSetConnection = self.__valueNode.plugSetSignal().connect( Gaffer.WeakMethod( self.__valuePlugSet ) )
def setPlug( self, plug ) :
self.__plug = plug
self.__plugMetadataChangedConnection = None
del self.__editingColumn[4:]
plugValueWidget = None
if self.__plug is not None :
self.__plugMetadataChangedConnection = Gaffer.Metadata.plugValueChangedSignal( plug.node() ).connect( Gaffer.WeakMethod( self.__plugMetadataChanged ) )
self.__valueNode["presetValue"] = plug.createCounterpart( "presetValue", plug.Direction.In )
if hasattr( self.__plug, "getValue" ) :
plugValueWidget = GafferUI.PlugValueWidget.create( self.__valueNode["presetValue"], useTypeOnly = True )
self.__editingColumn.append( plugValueWidget if plugValueWidget is not None else GafferUI.TextWidget() )
self.__editingColumn.append( GafferUI.Spacer( imath.V2i( 0 ), parenting = { "expand" : True } ) )
self.__updatePath()
self.__addButton.setEnabled( hasattr( self.__plug, "getValue" ) )
def getPlug( self ) :
return self.__plug
def __updatePath( self ) :
d = self.__pathListing.getPath().dict()
d.clear()
if self.__plug is not None :
for name in Gaffer.Metadata.registeredValues( self.__plug, instanceOnly = True, persistentOnly = True ) :
if name.startswith( "preset:" ) :
d[name[7:]] = Gaffer.Metadata.value( self.__plug, name )
self.__pathListing.getPath().pathChangedSignal()( self.__pathListing.getPath() )
def __plugMetadataChanged( self, plug, key, reason ) :
if plug == self.__plug and key.startswith( "preset:" ) :
self.__updatePath()
def __selectionChanged( self, listing ) :
selectedPaths = listing.getSelectedPaths()
self.__nameWidget.setText( selectedPaths[0][0] if selectedPaths else "" )
if selectedPaths :
with Gaffer.BlockedConnection( self.__valuePlugSetConnection ) :
self.__valueNode["presetValue"].setValue(
Gaffer.Metadata.value( self.getPlug(), "preset:" + selectedPaths[0][0] )
)
self.__editingColumn.setEnabled( bool( selectedPaths ) )
self.__deleteButton.setEnabled( bool( selectedPaths ) )
def __dragEnter( self, listing, event ) :
if event.sourceWidget is not self.__pathListing :
return False
if not isinstance( event.data, IECore.StringVectorData ) :
return False
return True
def __dragMove( self, listing, event ) :
d = self.__pathListing.getPath().dict()
srcPath = self.__pathListing.getPath().copy().setFromString( event.data[0] )
srcIndex = list( d.keys() ).index( srcPath[0] )
targetPath = self.__pathListing.pathAt( event.line.p0 )
if targetPath is not None :
targetIndex = list( d.keys() ).index( targetPath[0] )
else :
targetIndex = 0 if event.line.p0.y < 1 else len( d )
if srcIndex == targetIndex :
return True
items = list( d.items() )
item = items[srcIndex]
del items[srcIndex]
items.insert( targetIndex, item )
d.clear()
d.update( items )
self.__pathListing.getPath().pathChangedSignal()( self.__pathListing.getPath() )
return True
def __dragEnd( self, listing, event ) :
d = self.__pathListing.getPath().dict()
with Gaffer.BlockedConnection( self.__plugMetadataChangedConnection ) :
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
# reorder by removing everything and reregistering in the order we want
for item in d.items() :
Gaffer.Metadata.deregisterValue( self.getPlug(), "preset:" + item[0] )
for item in d.items() :
Gaffer.Metadata.registerValue( self.getPlug(), "preset:" + item[0], item[1] )
self.__updatePath()
return True
def __addButtonClicked( self, button ) :
existingNames = [ p[0] for p in self.__pathListing.getPath().children() ]
name = "New Preset"
index = 1
while name in existingNames :
name = "New Preset %d" % index
index += 1
with Gaffer.UndoScope( self.__plug.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue( self.__plug, "preset:" + name, self.__plug.getValue() )
self.__pathListing.setSelectedPaths(
self.__pathListing.getPath().copy().setFromString( "/" + name )
)
self.__nameWidget.grabFocus()
self.__nameWidget.setSelection( 0, len( name ) )
return True
def __deleteButtonClicked( self, button ) :
paths = self.__pathListing.getPath().children()
selectedPreset = self.__pathListing.getSelectedPaths()[0][0]
selectedIndex = [ p[0] for p in paths ].index( selectedPreset )
with Gaffer.UndoScope( self.__plug.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.deregisterValue( self.__plug, "preset:" + selectedPreset )
del paths[selectedIndex]
if len( paths ) :
self.__pathListing.setSelectedPaths( [ paths[min(selectedIndex,len( paths )-1)] ] )
return True
def __nameEditingFinished( self, nameWidget ) :
selectedPaths = self.__pathListing.getSelectedPaths()
if not len( selectedPaths ) :
return True
oldName = selectedPaths[0][0]
newName = nameWidget.getText()
if oldName == newName :
return True
if newName == "" :
# Empty names are not allowed, so revert to previous
nameWidget.setText( oldName )
return True
# Sanitize name. Strictly speaking we should only need to replace '/',
# but PathListingWidget has a bug handling wildcards in selections, so
# we replace those too.
maketrans = str.maketrans if six.PY3 else string.maketrans
newName = newName.translate( maketrans( "/*?\\[", "_____" ) )
items = self.__pathListing.getPath().dict().items()
with Gaffer.BlockedConnection( self.__plugMetadataChangedConnection ) :
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
# retain order by removing and reregistering everything
for item in items :
Gaffer.Metadata.deregisterValue( self.getPlug(), "preset:" + item[0] )
for item in items :
Gaffer.Metadata.registerValue( self.getPlug(), "preset:" + (item[0] if item[0] != oldName else newName), item[1] )
self.__updatePath()
self.__pathListing.setSelectedPaths( [ self.__pathListing.getPath().copy().setFromString( "/" + newName ) ] )
return True
def __valuePlugSet( self, plug ) :
if not plug.isSame( self.__valueNode["presetValue"] ) :
return
selectedPaths = self.__pathListing.getSelectedPaths()
preset = selectedPaths[0][0]
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue( self.getPlug(), "preset:" + preset, plug.getValue() )
##########################################################################
# _PlugEditor. This provides a panel for editing a specific plug's name,
# description, etc.
##########################################################################
class _PlugEditor( GafferUI.Widget ) :
def __init__( self, **kw ) :
scrolledContainer = GafferUI.ScrolledContainer( horizontalMode = GafferUI.ScrollMode.Never, borderWidth = 8 )
GafferUI.Widget.__init__( self, scrolledContainer, **kw )
self.__metadataWidgets = {}
scrolledContainer.setChild( GafferUI.ListContainer( spacing = 4 ) )
with scrolledContainer.getChild() :
with _Row() :
_Label( "Name" )
self.__nameWidget = GafferUI.NameWidget( None )
with _Row() :
_Label( "Label" )
self.__metadataWidgets["label"] = MetadataWidget.StringMetadataWidget( key = "label", acceptEmptyString = False )
with _Row() :
_Label( "Description", parenting = { "verticalAlignment" : GafferUI.ListContainer.VerticalAlignment.Top } )
self.__metadataWidgets["description"] = MetadataWidget.MultiLineStringMetadataWidget( key = "description" )
self.__metadataWidgets["description"].textWidget().setFixedLineHeight( 10 )
with _Row() :
_Label( "Widget" )
self.__widgetMenu = GafferUI.MenuButton(
menu = GafferUI.Menu( Gaffer.WeakMethod( self.__widgetMenuDefinition ) )
)
with GafferUI.Collapsible( "Presets", collapsed = True ) :
with _Row() :
_Label( "" )
self.__presetsEditor = _PresetsEditor()
with GafferUI.Collapsible( "Widget Settings", collapsed = True ) :
self.__widgetSettingsContainer = GafferUI.ListContainer( spacing = 4 )
with GafferUI.Collapsible( "Graph Editor", collapsed = True ) :
with GafferUI.ListContainer( spacing = 4 ) as self.__graphEditorSection :
with _Row() :
_Label( "Gadget" )
self.__gadgetMenu = GafferUI.MenuButton(
menu = GafferUI.Menu( Gaffer.WeakMethod( self.__gadgetMenuDefinition ) )
)
with _Row() :
_Label( "Position" )
self.__metadataWidgets["noduleLayout:section"] = MetadataWidget.MenuMetadataWidget(
key = "noduleLayout:section",
labelsAndValues = [
( "Default", None ),
( "Top", "top" ),
( "Bottom", "bottom" ),
( "Left", "left" ),
( "Right", "right" ),
]
)
with _Row() :
_Label( "Color" )
self.__metadataWidgets["nodule:color"] = MetadataWidget.ColorSwatchMetadataWidget( key = "nodule:color", defaultValue = imath.Color3f( 0.4 ) )
with _Row() :
_Label( "Connection Color" )
self.__metadataWidgets["connectionGadget:color"] = MetadataWidget.ColorSwatchMetadataWidget( key = "connectionGadget:color", defaultValue = imath.Color3f( 0.125 ) )
GafferUI.Spacer( imath.V2i( 0 ), parenting = { "expand" : True } )
self.__plug = None
def setPlug( self, plug ) :
self.__plug = plug
self.__nameWidget.setGraphComponent( self.__plug )
for widget in self.__metadataWidgets.values() :
widget.setTarget( self.__plug )
self.__plugMetadataChangedConnection = None
if self.__plug is not None :
self.__plugMetadataChangedConnection = Gaffer.Metadata.plugValueChangedSignal( self.__plug.node() ).connect(
Gaffer.WeakMethod( self.__plugMetadataChanged )
)
self.__updateWidgetMenuText()
self.__updateWidgetSettings()
self.__updateGadgetMenuText()
self.__presetsEditor.setPlug( plug )
self.__graphEditorSection.setEnabled( self.__plug is not None and self.__plug.parent().isSame( self.__plug.node() ) )
self.setEnabled( self.__plug is not None )
def getPlug( self ) :
return self.__plug
__plugValueWidgets = {}
## Registers a custom PlugValueWidget type for a plug type, so it can be selected in the UIEditor
# label: String with the label to be displayed for this widget.
# plugType: Gaffer.Plug class that can use the widget being registered.
# metadata: String with associated metadata for the widget. Usually the python identifier for the widget (ex: "GafferUI.BoolPlugValueWidget").
@classmethod
def registerPlugValueWidget( cls, label, plugType, metadata ) :
if plugType not in cls.__plugValueWidgets :
cls.__plugValueWidgets[plugType] = {}
cls.__plugValueWidgets[plugType][label] = metadata
__widgetSettings = []
## Register additional metadata for PlugValueWidgets
# label: string with the label to be displayed for this widget
# plugValueWidgetType: string with the "plugValueWidget:type" metadata value where this settings applies, or a pattern for it.
# widgetCreator: callable that receives the plug and returns a MetadataWidget (or another widget) to edit the metadata
@classmethod
def registerWidgetSetting( cls, label, plugValueWidgetType, widgetCreator ) :
cls.__widgetSettings.append( ( label, plugValueWidgetType, widgetCreator ) )
## Returns a dictionary with the registered PlugValueWidgets for the given plug object or type
# the dictionary keys will be labels, and the values strings with the widget metadata
@classmethod
def __registeredPlugValueWidgets( cls, plugOrPlugType ) :
result = {}
plugType = plugOrPlugType
if not inspect.isclass( plugType ) :
plugType = type( plugOrPlugType )
# consider base classes for the plug
for baseClass in plugType.__bases__ :
if not issubclass( baseClass, Gaffer.Plug ) :
continue
result.update( cls.__registeredPlugValueWidgets( baseClass ) )
# consider itself
result.update( cls.__plugValueWidgets.get( plugType, {} ) )
return result
def __plugMetadataChanged( self, plug, key, reason ) :
if plug != self.getPlug() :
return
if key == "plugValueWidget:type" :
self.__updateWidgetMenuText()
self.__updateWidgetSettings()
elif key == "nodule:type" :
self.__updateGadgetMenuText()
def __updateWidgetMenuText( self ) :
if self.getPlug() is None :
self.__widgetMenu.setText( "" )
return
metadata = Gaffer.Metadata.value( self.getPlug(), "plugValueWidget:type" )
registeredWidgets = self.__registeredPlugValueWidgets( self.getPlug() )
for label, widgetMetadata in registeredWidgets.items() :
if widgetMetadata == metadata :
self.__widgetMenu.setText( label )
return
self.__widgetMenu.setText( metadata )
def __updateWidgetSettings( self ) :
del self.__widgetSettingsContainer[:]
if self.getPlug() is None :
return
widgetType = Gaffer.Metadata.value( self.getPlug(), "plugValueWidget:type" ) or ""
with self.__widgetSettingsContainer :
for label, plugValueWidgetType, widgetCreator in self.__widgetSettings :
if not IECore.StringAlgo.match( widgetType, plugValueWidgetType ) :
continue
with _Row() :
_Label( label )
widgetCreator( self.getPlug() )
self.__metadataWidgets["connectionGadget:color"].parent().setEnabled(
self.getPlug() is not None and self.getPlug().direction() == Gaffer.Plug.Direction.In
)
def __widgetMenuDefinition( self ) :
result = IECore.MenuDefinition()
if self.getPlug() is None :
return result
metadata = Gaffer.Metadata.value( self.getPlug(), "plugValueWidget:type" )
registeredWidgets = self.__registeredPlugValueWidgets( self.getPlug() )
labels = list( registeredWidgets.keys() )
# sort labels so that they are alphabetical, but with "Default" first, and "None" last
labels.sort()
labels.sort( key=lambda l: 0 if l == "Default" else 2 if l == "None" else 1 )
for label in labels :
result.append(
"/" + label,
{
"command" : functools.partial(
Gaffer.WeakMethod( self.__registerOrDeregisterMetadata ),
key = "plugValueWidget:type",
value = registeredWidgets[label]
),
"checkBox" : metadata == registeredWidgets[label],
}
)
return result
def __updateGadgetMenuText( self ) :
if self.getPlug() is None :
self.__gadgetMenu.setText( "" )
return
metadata = Gaffer.Metadata.value( self.getPlug(), "nodule:type" )
metadata = None if metadata == "GafferUI::StandardNodule" else metadata
for g in self.__gadgetDefinitions :
if g.metadata == metadata :
self.__gadgetMenu.setText( g.label )
return
self.__gadgetMenu.setText( metadata )
def __gadgetMenuDefinition( self ) :
result = IECore.MenuDefinition()
if self.getPlug() is None :
return result
metadata = Gaffer.Metadata.value( self.getPlug(), "nodule:type" )
for g in self.__gadgetDefinitions :
if not isinstance( self.getPlug(), g.plugType ) :
continue
result.append(
"/" + g.label,
{
"command" : functools.partial( Gaffer.WeakMethod( self.__registerOrDeregisterMetadata ), key = "nodule:type", value = g.metadata ),
"checkBox" : metadata == g.metadata,
}
)
return result
def __registerOrDeregisterMetadata( self, unused, key, value ) :
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
if value is not None :
Gaffer.Metadata.registerValue( self.getPlug(), key, value )
else :
Gaffer.Metadata.deregisterValue( self.getPlug(), key )
__GadgetDefinition = collections.namedtuple( "GadgetDefinition", ( "label", "plugType", "metadata" ) )
__gadgetDefinitions = (
__GadgetDefinition( "Default", Gaffer.Plug, None ),
__GadgetDefinition( "Array", Gaffer.ArrayPlug, "GafferUI::CompoundNodule" ),
__GadgetDefinition( "None", Gaffer.Plug, "" ),
)
##########################################################################
# _SectionEditor. This provides a panel for editing the details of
# a specific section.
##########################################################################
class _SectionEditor( GafferUI.Widget ) :
def __init__( self, **kw ) :
column = GafferUI.ListContainer( spacing = 4, borderWidth = 8 )
GafferUI.Widget.__init__( self, column, **kw )
with column :
with _Row() :
_Label( "Name" )
self.__nameWidget = GafferUI.TextWidget()
self.__nameWidget.editingFinishedSignal().connect( Gaffer.WeakMethod( self.__nameWidgetEditingFinished ), scoped = False )
with _Row() :
_Label( "Summary", parenting = { "verticalAlignment" : GafferUI.ListContainer.VerticalAlignment.Top } )
self.__summaryMetadataWidget = MetadataWidget.MultiLineStringMetadataWidget( key = "" )
self.__section = ""
self.__plugParent = None
self.__nameChangedSignal = Gaffer.Signal3()
def setPlugParent( self, plugParent ) :
self.__plugParent = plugParent
self.__summaryMetadataWidget.setTarget( self.__plugParent )
def getPlugParent( self ) :
return self.__plugParent
def setSection( self, section ) :
assert( isinstance( section, six.string_types ) )
self.__section = section
self.__nameWidget.setText( section.rpartition( "." )[-1] )
self.__summaryMetadataWidget.setKey( "layout:section:" + self.__section + ":summary" )
def getSection( self ) :
return self.__section
def nameChangedSignal( self ) :
return self.__nameChangedSignal
def __nameWidgetEditingFinished( self, nameWidget ) :
if nameWidget.getText() == "" :
# Can't rename to the empty string - abandon the edit.
self.setSection( self.__section )
return
oldSectionPath = self.__section.split( "." )
newSectionPath = oldSectionPath[:]
newSectionPath[-1] = nameWidget.getText().replace( ".", "" )
if oldSectionPath == newSectionPath :
return
def newSection( oldSection ) :
s = oldSection.split( "." )
if s[:len(oldSectionPath)] == oldSectionPath :
s[:len(oldSectionPath)] = newSectionPath
return ".".join( s )
else :
return oldSection
with Gaffer.UndoScope( self.__plugParent.ancestor( Gaffer.ScriptNode ) ) :
for plug in self.__plugParent.children( Gaffer.Plug ) :
s = Gaffer.Metadata.value( plug, "layout:section" )
if s is not None :
Gaffer.Metadata.registerValue( plug, "layout:section", newSection( s ) )
emptySections = Gaffer.Metadata.value( self.getPlugParent(), "uiEditor:emptySections" )
if emptySections :
for i in range( 0, len( emptySections ) ) :
emptySections[i] = newSection( emptySections[i] )
Gaffer.Metadata.registerValue( self.getPlugParent(), "uiEditor:emptySections", emptySections )
for name in Gaffer.Metadata.registeredValues( self.getPlugParent(), instanceOnly = True, persistentOnly = True ) :
m = re.match( "(layout:section:)(.*)(:.*)", name )
if m :
if newSection( m.group( 2 ) ) != m.group( 2 ) :
Gaffer.Metadata.registerValue(
self.getPlugParent(),
m.group( 1 ) + newSection( m.group( 2 ) ) + m.group( 3 ),
Gaffer.Metadata.value( self.getPlugParent(), name )
)
Gaffer.Metadata.deregisterValue( self.getPlugParent(), name )
self.setSection( ".".join( newSectionPath ) )
self.nameChangedSignal()( self, ".".join( oldSectionPath ), ".".join( newSectionPath ) )
##########################################################################
# Registering custom PlugValueWidgets for the UIEditor
##########################################################################
UIEditor.registerPlugValueWidget( "Default", Gaffer.Plug, None )
UIEditor.registerPlugValueWidget( "None", Gaffer.Plug, "" )
UIEditor.registerPlugValueWidget( "Checkbox", Gaffer.IntPlug, "GafferUI.BoolPlugValueWidget" )
UIEditor.registerPlugValueWidget( "Text Region", Gaffer.StringPlug, "GafferUI.MultiLineStringPlugValueWidget" )
UIEditor.registerPlugValueWidget( "File Chooser", Gaffer.StringPlug, "GafferUI.FileSystemPathPlugValueWidget" )
UIEditor.registerPlugValueWidget( "File Chooser", Gaffer.StringVectorDataPlug, "GafferUI.FileSystemPathVectorDataPlugValueWidget" )
UIEditor.registerPlugValueWidget( "Presets Menu", Gaffer.ValuePlug, "GafferUI.PresetsPlugValueWidget" )
UIEditor.registerPlugValueWidget( "Connection", Gaffer.Plug, "GafferUI.ConnectionPlugValueWidget" )
UIEditor.registerPlugValueWidget( "Button", Gaffer.Plug, "GafferUI.ButtonPlugValueWidget" )
##########################################################################
# Registering standard Widget Settings for the UIEditor
##########################################################################
class _ButtonCodeMetadataWidget( GafferUI.MetadataWidget.MetadataWidget ) :
def __init__( self, target = None, **kw ) :
self.__codeWidget = GafferUI.CodeWidget()
GafferUI.MetadataWidget.MetadataWidget.__init__( self, self.__codeWidget, "buttonPlugValueWidget:clicked", target, defaultValue = "", **kw )
## \todo Qt 5.6 can't deal with multiline placeholder text. In Qt 5.12
# we should be able to provide a little more detail here.
self.__codeWidget._qtWidget().setPlaceholderText(
"# Access the node graph via `plug`, and the UI via `button`"
)
self.__codeWidget.setHighlighter( GafferUI.CodeWidget.PythonHighlighter() )
self.__codeWidget.editingFinishedSignal().connect(
Gaffer.WeakMethod( self.__editingFinished ), scoped = False
)
def setTarget( self, target ) :
GafferUI.MetadataWidget.MetadataWidget.setTarget( self, target )
if target is not None :
self.__codeWidget.setCompleter(
GafferUI.CodeWidget.PythonCompleter( {
"IECore" : IECore,
"Gaffer" : Gaffer,
"plug" : target,
"button" : GafferUI.ButtonPlugValueWidget( target ),
} )
)
else :
self.__codeWidget.setCompleter( None )
def _updateFromValue( self, value ) :
self.__codeWidget.setText( str( value ) )
def __editingFinished( self, *unused ) :
self._updateFromWidget( self.__codeWidget.getText() )
UIEditor.registerWidgetMetadata( "File Extensions", "GafferUI.FileSystemPath*PlugValueWidget", "fileSystemPath:extensions", "" )
UIEditor.registerWidgetMetadata( "Bookmarks Category", "GafferUI.FileSystemPath*PlugValueWidget", "path:bookmarks", "" )
UIEditor.registerWidgetMetadata( "File Must Exist", "GafferUI.FileSystemPath*PlugValueWidget", "path:valid", False )
UIEditor.registerWidgetMetadata( "No Directories", "GafferUI.FileSystemPath*PlugValueWidget", "path:leaf", False )
UIEditor.registerWidgetMetadata( "Allow sequences", "GafferUI.FileSystemPath*PlugValueWidget", "fileSystemPath:includeSequences", False )
# Note that includeSequenceFrameRange is primarily used by GafferCortex.
# Think twice before using it elsewhere as it may not exist in the future.
UIEditor.registerWidgetMetadata( "Sequences include frame range", "GafferUI.FileSystemPath*PlugValueWidget", "fileSystemPath:includeSequenceFrameRange", False )
UIEditor.registerWidgetSetting(
"Button Click Code",
"GafferUI.ButtonPlugValueWidget",
_ButtonCodeMetadataWidget,
)
UIEditor.registerWidgetMetadata( "Inline", "GafferUI.ButtonPlugValueWidget", "layout:accessory", False )
UIEditor.registerWidgetMetadata( "Divider", "*", "divider", False )
| 33.675781 | 170 | 0.698013 | " plug empty so that it
# is available for use by the user on Reference nodes once a Box has
# been exported and referenced.
plugParent = self.__node
self.__plugAddButtons.setVisible( True )
self.__plugListing.setPlugParent( plugParent )
self.__sectionEditor.setPlugParent( plugParent )
for widget in self.__nodeMetadataWidgets :
widget.setTarget( self.__node )
self.setSelection( None )
def __plugListingSelectionChanged( self, listing ) :
selection = listing.getSelection()
if selection is None or isinstance( selection, Gaffer.Plug ) :
self.__plugEditor.setPlug( selection )
self.__plugAndSectionEditorsContainer.setCurrent( self.__plugEditor )
elif isinstance( selection, six.string_types ) :
self.__plugEditor.setPlug( None )
self.__sectionEditor.setSection( selection )
self.__plugAndSectionEditorsContainer.setCurrent( self.__sectionEditor )
def __sectionEditorNameChanged( self, sectionEditor, oldName, newName ) :
# When the name changed, our plug listing will have lost its
# selection. So give it a helping hand.
self.__plugListing.setSelection( newName )
def __repr__( self ) :
return "GafferUI.UIEditor( scriptNode )"
@classmethod
def __setColor( cls, menu, node ) :
color = Gaffer.Metadata.value( node, "nodeGadget:color" ) or imath.Color3f( 1 )
dialogue = GafferUI.ColorChooserDialogue( color = color, useDisplayTransform = False )
color = dialogue.waitForColor( parentWindow = menu.ancestor( GafferUI.Window ) )
if color is not None :
with Gaffer.UndoScope( node.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue( node, "nodeGadget:color", color )
@staticmethod
def __setNameVisible( node, nameVisible ) :
with Gaffer.UndoScope( node.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue(
node, "nodeGadget:type",
"GafferUI::StandardNodeGadget" if nameVisible else "GafferUI::AuxiliaryNodeGadget"
)
GafferUI.Editor.registerType( "UIEditor", UIEditor )
##########################################################################
# PlugValueWidget popup menu
##########################################################################
def __editPlugUI( node, plug ) :
editor = GafferUI.UIEditor.acquire( node )
editor.setSelection( plug )
editor.plugEditor().reveal()
def __plugPopupMenu( menuDefinition, plugValueWidget ) :
plug = plugValueWidget.getPlug()
node = plug.node()
if node is None :
return
if isinstance( node, Gaffer.Box ) :
if not plug.parent().isSame( node ) :
return
else :
if not plug.parent().isSame( node["user"] ) :
return
menuDefinition.append( "/EditUIDivider", { "divider" : True } )
menuDefinition.append( "/Edit UI...",
{
"command" : functools.partial( __editPlugUI, node, plug ),
"active" : not plugValueWidget.getReadOnly() and not Gaffer.MetadataAlgo.readOnly( plug )
}
)
GafferUI.PlugValueWidget.popupMenuSignal().connect( __plugPopupMenu, scoped = False )
##########################################################################
# Simple fixed width label and row classes
##########################################################################
class _Label( GafferUI.Label ) :
def __init__( self, *args, **kw ) :
GafferUI.Label.__init__(
self,
horizontalAlignment = GafferUI.Label.HorizontalAlignment.Right,
*args, **kw
)
self._qtWidget().setFixedWidth( 110 )
class _Row( GafferUI.ListContainer ) :
def __init__( self, *args, **kw ) :
GafferUI.ListContainer.__init__( self, GafferUI.ListContainer.Orientation.Horizontal, spacing = 4, *args, **kw )
##########################################################################
# Hierarchical representation of a plug layout, suitable for manipulating
# by the _PlugListing.
# \todo Consider sharing this data structure with the PlugLayout itself,
# rather than each using a different internal representation. If we did
# this then the data structure itself should take care of the mapping
# to/from metadata.
##########################################################################
class _LayoutItem( object ) :
def __init__( self ) :
self.__parent = None
self.__children = []
def parent( self ) :
if self.__parent is None :
return None
else :
return self.__parent()
def child( self, name ) :
for c in self.__children :
if c.name() == name :
return c
return None
def isAncestorOf( self, item ) :
while item is not None :
parent = item.parent()
if parent is self :
return True
item = parent
return False
def append( self, child ) :
self.insert( len( self ), child )
def insert( self, index, child ) :
assert( child.parent() is None )
self.__children.insert( index, child )
child.__parent = weakref.ref( self )
def remove( self, child ) :
assert( child.parent() is self )
self.__children.remove( child )
child.__parent = None
def index( self, child ) :
return self.__children.index( child )
def name( self ) :
raise NotImplementedError
def fullName( self ) :
result = ""
item = self
while item.parent() is not None :
if result :
result = item.name() + "." + result
else :
result = item.name()
item = item.parent()
return result
def __len__( self ) :
return len( self.__children )
def __getitem__( self, index ) :
return self.__children[index]
class _SectionLayoutItem( _LayoutItem ) :
def __init__( self, sectionName ) :
_LayoutItem.__init__( self )
self.__sectionName = sectionName
def name( self ) :
return self.__sectionName
class _PlugLayoutItem( _LayoutItem ) :
def __init__( self, plug ) :
_LayoutItem.__init__( self )
self.plug = plug
self.__name = plug.getName()
def name( self ) :
return self.__name
##########################################################################
# _PlugListing. This is used to list the plugs in the UIEditor,
# organised into their respective sections.
##########################################################################
class _PlugListing( GafferUI.Widget ) :
class __LayoutPath( Gaffer.Path ) :
def __init__( self, rootItem, path, root="/", filter = None ) :
Gaffer.Path.__init__( self, path, root, filter )
self.__rootItem = rootItem
def rootItem( self ) :
return self.__rootItem
def item( self ) :
result = self.__rootItem
for name in self :
result = result.child( name )
if result is None :
return None
return result
def copy( self ) :
return self.__class__( self.__rootItem, self[:], self.root(), self.getFilter() )
def isLeaf( self ) :
return not isinstance( self.item(), _SectionLayoutItem )
def isValid( self ) :
return self.item() is not None
def _children( self ) :
item = self.item()
if item is None :
return []
result = [
self.__class__( self.__rootItem, self[:] + [ c.name() ], self.root(), self.getFilter() )
for c in item
]
# Add a placeholder child into empty sections, to be used as a drag target
# in __dragMove()
if len( result ) == 0 and isinstance( item, _SectionLayoutItem ) :
result.append( self.__class__( self.__rootItem, self[:] + [ " " ], self.root(), self.getFilter() ) )
return result
def __init__( self, **kw ) :
column = GafferUI.ListContainer( spacing = 4 )
GafferUI.Widget.__init__( self, column, **kw )
# We don't have a way to do this with Widget directly at present, this
column._qtWidget().setMinimumWidth( 650 )
with column :
self.__pathListing = GafferUI.PathListingWidget(
self.__LayoutPath( _SectionLayoutItem( "" ), "/" ),
columns = ( GafferUI.PathListingWidget.defaultNameColumn, ),
displayMode = GafferUI.PathListingWidget.DisplayMode.Tree,
)
self.__pathListing.setDragPointer( "" )
self.__pathListing.setSortable( False )
self.__pathListing.setHeaderVisible( False )
with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) :
GafferUI.MenuButton(
image = "plus.png",
hasFrame = False,
menu = GafferUI.Menu(
definition = Gaffer.WeakMethod( self.__addMenuDefinition )
)
)
self.__deleteButton = GafferUI.Button( image = "minus.png", hasFrame = False )
self.__deleteButton.clickedSignal().connect( Gaffer.WeakMethod( self.__deleteButtonClicked ), scoped = False )
self.__parent = None
self.__dragItem = None
self.__selectionChangedSignal = Gaffer.Signal1()
self.__pathListing.dragEnterSignal().connect( Gaffer.WeakMethod( self.__dragEnter ), scoped = False )
self.__pathListing.dragMoveSignal().connect( Gaffer.WeakMethod( self.__dragMove ), scoped = False )
self.__pathListing.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False )
self.__pathListing.selectionChangedSignal().connect( Gaffer.WeakMethod( self.__selectionChanged ), scoped = False )
self.keyPressSignal().connect( Gaffer.WeakMethod( self.__keyPress ), scoped = False )
def setPlugParent( self, parent ) :
assert( isinstance( parent, ( Gaffer.Plug, Gaffer.Node, type( None ) ) ) )
self.__parent = parent
self.__childAddedConnection = None
self.__childRemovedConnection = None
self.__childNameChangedConnections = {}
self.__metadataChangedConnections = []
if self.__parent is not None :
self.__childAddedConnection = self.__parent.childAddedSignal().connect( Gaffer.WeakMethod( self.__childAddedOrRemoved ) )
self.__childRemovedConnection = self.__parent.childRemovedSignal().connect( Gaffer.WeakMethod( self.__childAddedOrRemoved ) )
node = self.__parent if isinstance( self.__parent, Gaffer.Node ) else self.__parent.node()
self.__metadataChangedConnections = [
Gaffer.Metadata.nodeValueChangedSignal( node ).connect( Gaffer.WeakMethod( self.__nodeMetadataChanged ) ),
Gaffer.Metadata.plugValueChangedSignal( node ).connect( Gaffer.WeakMethod( self.__plugMetadataChanged ) )
]
for child in self.__parent.children() :
self.__updateChildNameChangedConnection( child )
self.__updatePath()
def getPlugParent( self ) :
return self.__parent
# Selection can be None, a Plug, or the name of a section.
def setSelection( self, selection ) :
self.__updatePathLazily.flush( self )
def findPlugPath( path, plug ) :
item = path.item()
if isinstance( item, _PlugLayoutItem ) and item.plug.isSame( plug ) :
return path
else :
for child in path.children() :
r = findPlugPath( child, plug )
if r is not None :
return r
return None
if isinstance( selection, Gaffer.Plug ) :
path = findPlugPath( self.__pathListing.getPath(), selection )
if path is None :
self.__pathListing.setSelectedPaths( [] )
else :
self.__pathListing.setSelectedPaths( [ path ] )
elif isinstance( selection, six.string_types ) :
path = self.__pathListing.getPath().copy()
path[:] = selection.split( "." )
self.__pathListing.setSelectedPaths( [ path ] )
else :
assert( selection is None )
self.__pathListing.setSelectedPaths( [] )
def getSelection( self ) :
item = self.__selectedItem()
if item is None :
return None
elif isinstance( item, _PlugLayoutItem ) :
return item.plug
elif isinstance( item, _SectionLayoutItem ) :
return item.fullName()
else :
return None
def selectionChangedSignal( self ) :
return self.__selectionChangedSignal
# Updates the path we show in the listing by building a layout based
# on the metadata.
def __updatePath( self ) :
if self.__parent is None :
# we have nothing to show - early out.
self.__pathListing.setPath( self.__LayoutPath( _SectionLayoutItem( "" ), "/" ) )
return
def section( rootLayoutItem, sectionPath ) :
sectionItem = rootLayoutItem
if sectionPath != "" :
for sectionName in sectionPath.split( "." ) :
childSectionItem = sectionItem.child( sectionName )
if childSectionItem is None :
childSectionItem = _SectionLayoutItem( sectionName )
sectionItem.append( childSectionItem )
sectionItem = childSectionItem
return sectionItem
layout = _SectionLayoutItem( "" )
for sectionPath in GafferUI.PlugLayout.layoutSections( self.__parent ) :
if sectionPath == "User" and isinstance( self.__parent, Gaffer.Node ) :
continue
sectionItem = section( layout, sectionPath )
for plug in GafferUI.PlugLayout.layoutOrder( self.__parent, section = sectionPath ) :
sectionItem.append( _PlugLayoutItem( plug ) )
emptySections = Gaffer.Metadata.value( self.getPlugParent(), "uiEditor:emptySections" )
emptySectionIndices = Gaffer.Metadata.value( self.getPlugParent(), "uiEditor:emptySectionIndices" )
if emptySections and emptySectionIndices :
for sectionPath, sectionIndex in zip( emptySections, emptySectionIndices ) :
parentPath, unused, sectionName = sectionPath.rpartition( "." )
parentSection = section( layout, parentPath )
if parentSection.child( sectionName ) is None :
parentSection.insert( sectionIndex, _SectionLayoutItem( sectionName ) )
if len( layout ) == 0 and isinstance( self.__parent, Gaffer.Node ) :
layout.append( _SectionLayoutItem( "Settings" ) )
expandedPaths = self.__pathListing.getExpandedPaths()
self.__pathListing.setPath( self.__LayoutPath( layout, "/" ) )
self.__pathListing.setExpandedPaths( expandedPaths )
@GafferUI.LazyMethod()
def __updatePathLazily( self ) :
self.__updatePath()
# Updates the metadata that controls the plug layout from the layout
# we show in the listing.
def __updateMetadata( self ) :
# Because sections only really exist by virtue of being requested
# by a plug, we must store empty sections separately for ourselves.
emptySections = IECore.StringVectorData()
emptySectionIndices = IECore.IntVectorData()
def walk( layoutItem, path = "", index = 0 ) :
for childItem in layoutItem :
if isinstance( childItem, _PlugLayoutItem ) :
Gaffer.Metadata.registerValue( childItem.plug, "layout:section", path )
Gaffer.Metadata.registerValue( childItem.plug, "layout:index", index )
index += 1
elif isinstance( childItem, _SectionLayoutItem ) :
childPath = path + "." + childItem.name() if path else childItem.name()
if len( childItem ) :
index = walk( childItem, childPath, index )
else :
emptySections.append( childPath )
emptySectionIndices.append( layoutItem.index( childItem ) )
return index
with Gaffer.BlockedConnection( self.__metadataChangedConnections ) :
walk( self.__pathListing.getPath().copy().setFromString( "/" ).item() )
Gaffer.Metadata.registerValue( self.getPlugParent(), "uiEditor:emptySections", emptySections )
Gaffer.Metadata.registerValue( self.getPlugParent(), "uiEditor:emptySectionIndices", emptySectionIndices )
def __childAddedOrRemoved( self, parent, child ) :
assert( parent.isSame( self.__parent ) )
self.__updateChildNameChangedConnection( child )
self.__updatePathLazily()
def __childNameChanged( self, child ) :
selection = self.getSelection()
self.__updatePath()
if isinstance( selection, Gaffer.Plug ) and child.isSame( selection ) :
# because the plug's name has changed. the path needed to
self.setSelection( selection )
def __updateChildNameChangedConnection( self, child ) :
if self.__parent.isSame( child.parent() ) :
if child not in self.__childNameChangedConnections :
self.__childNameChangedConnections[child] = child.nameChangedSignal().connect( Gaffer.WeakMethod( self.__childNameChanged ) )
else :
if child in self.__childNameChangedConnections :
del self.__childNameChangedConnections[child]
def __dragEnter( self, listing, event ) :
if event.sourceWidget is not self.__pathListing :
return False
if not isinstance( event.data, IECore.StringVectorData ) :
return False
dragPath = self.__pathListing.getPath().copy().setFromString( event.data[0] )
self.__dragItem = dragPath.item()
self.__pathListing.setPathExpanded( dragPath, False )
return True
def __dragMove( self, listing, event ) :
if self.__dragItem is None :
return False
# update our layout structure to reflect the drag
#################################################
# find newParent and newIndex - variables specifying
# the new location for the dragged item.
targetPath = self.__pathListing.pathAt( event.line.p0 )
if targetPath is not None :
targetItem = targetPath.item()
if targetItem is not None :
if isinstance( targetItem, _SectionLayoutItem ) and self.__pathListing.getPathExpanded( targetPath ) and targetItem.parent() is self.__dragItem.parent() :
newParent = targetItem
newIndex = 0
else :
newParent = targetItem.parent()
newIndex = newParent.index( targetItem )
else :
# target is a placeholder added into an empty
# section by __LayoutPath._children().
newParent = targetPath.copy().truncateUntilValid().item()
newIndex = 0
else :
# drag has gone above or below all listed items
newParent = self.__pathListing.getPath().rootItem()
newIndex = 0 if event.line.p0.y < 1 else len( newParent )
# skip any attempted circular reparenting
if newParent is self.__dragItem or self.__dragItem.isAncestorOf( newParent ) :
return True
# disallow drags that would place a plug below a section
firstNonPlugIndex = next(
( x[0] for x in enumerate( newParent ) if not isinstance( x[1], _PlugLayoutItem ) ),
len( newParent )
)
if self.__dragItem.parent() is newParent and newParent.index( self.__dragItem ) < firstNonPlugIndex :
firstNonPlugIndex -= 1
if isinstance( self.__dragItem, _PlugLayoutItem ) :
if newIndex > firstNonPlugIndex :
return True
else :
if newIndex < firstNonPlugIndex :
newIndex = max( newIndex, firstNonPlugIndex )
self.__dragItem.parent().remove( self.__dragItem )
newParent.insert( newIndex, self.__dragItem )
# let the listing know we've been monkeying behind the scenes.
d Plug/NumericDivider", { "divider" : True } )
m.append( "/Add Plug/String", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.StringPlug ) } )
m.append( "/Add Plug/StringDivider", { "divider" : True } )
m.append( "/Add Plug/V2i", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V2iPlug ) } )
m.append( "/Add Plug/V3i", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V3iPlug ) } )
m.append( "/Add Plug/V2f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V2fPlug ) } )
m.append( "/Add Plug/V3f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.V3fPlug ) } )
m.append( "/Add Plug/VectorDivider", { "divider" : True } )
m.append( "/Add Plug/Color3f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.Color3fPlug ) } )
m.append( "/Add Plug/Color4f", { "command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), Gaffer.Color4fPlug ) } )
m.append( "/Add Plug/ColorDivider", { "divider" : True } )
for label, plugType in [
( "Float", Gaffer.FloatVectorDataPlug ),
( "Int", Gaffer.IntVectorDataPlug ),
( "NumericDivider", None ),
( "String", Gaffer.StringVectorDataPlug ),
] :
if plugType is not None :
m.append(
"/Add Plug/Array/" + label,
{
"command" : functools.partial(
Gaffer.WeakMethod( self.__addPlug ),
plugCreator = functools.partial( plugType, defaultValue = plugType.ValueType() )
)
}
)
else :
m.append( "/Add Plug/Array/" + label, { "divider" : True } )
m.append( "/Add Plug Divider", { "divider" : True } )
m.append( "/Add Section", { "command" : Gaffer.WeakMethod( self.__addSection ) } )
return m
def __addPlug( self, plugCreator ) :
plug = plugCreator( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
Gaffer.Metadata.registerValue( plug, "nodule:type", "" )
parentItem = self.__selectedItem()
if parentItem is not None :
while not isinstance( parentItem, _SectionLayoutItem ) :
parentItem = parentItem.parent()
else :
parentItem = self.__pathListing.getPath().rootItem()
parentItem = next(
( c for c in parentItem if isinstance( c, _SectionLayoutItem ) ),
parentItem
)
Gaffer.Metadata.registerValue( plug, "layout:section", parentItem.fullName() )
with Gaffer.UndoScope( self.__parent.ancestor( Gaffer.ScriptNode ) ) :
self.getPlugParent().addChild( plug )
self.__updatePathLazily.flush( self )
self.setSelection( plug )
def __addSection( self ) :
rootItem = self.__pathListing.getPath().rootItem()
existingSectionNames = set( c.name() for c in rootItem if isinstance( c, _SectionLayoutItem ) )
name = "New Section"
index = 1
while name in existingSectionNames :
name = "New Section %d" % index
index += 1
rootItem.append( _SectionLayoutItem( name ) )
self.__pathListing.getPath().pathChangedSignal()( self.__pathListing.getPath() )
with Gaffer.UndoScope( self.__parent.ancestor( Gaffer.ScriptNode ) ) :
self.__updateMetadata()
self.__pathListing.setSelectedPaths(
self.__pathListing.getPath().copy().setFromString( "/" + name )
)
def __selectedItem( self ) :
selectedPaths = self.__pathListing.getSelectedPaths()
if not len( selectedPaths ) :
return None
assert( len( selectedPaths ) == 1 )
return selectedPaths[0].item()
def __deleteSelected( self ) :
selectedItem = self.__selectedItem()
if selectedItem is None :
return
selectedItem.parent().remove( selectedItem )
def deletePlugsWalk( item ) :
if isinstance( item, _PlugLayoutItem ) :
item.plug.parent().removeChild( item.plug )
else :
for childItem in item :
deletePlugsWalk( childItem )
with Gaffer.UndoScope( self.__parent.ancestor( Gaffer.ScriptNode ) ) :
deletePlugsWalk( selectedItem )
self.__updateMetadata()
f.getPlug(), "preset:" + item[0] )
for item in d.items() :
Gaffer.Metadata.registerValue( self.getPlug(), "preset:" + item[0], item[1] )
self.__updatePath()
return True
def __addButtonClicked( self, button ) :
existingNames = [ p[0] for p in self.__pathListing.getPath().children() ]
name = "New Preset"
index = 1
while name in existingNames :
name = "New Preset %d" % index
index += 1
with Gaffer.UndoScope( self.__plug.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue( self.__plug, "preset:" + name, self.__plug.getValue() )
self.__pathListing.setSelectedPaths(
self.__pathListing.getPath().copy().setFromString( "/" + name )
)
self.__nameWidget.grabFocus()
self.__nameWidget.setSelection( 0, len( name ) )
return True
def __deleteButtonClicked( self, button ) :
paths = self.__pathListing.getPath().children()
selectedPreset = self.__pathListing.getSelectedPaths()[0][0]
selectedIndex = [ p[0] for p in paths ].index( selectedPreset )
with Gaffer.UndoScope( self.__plug.ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.deregisterValue( self.__plug, "preset:" + selectedPreset )
del paths[selectedIndex]
if len( paths ) :
self.__pathListing.setSelectedPaths( [ paths[min(selectedIndex,len( paths )-1)] ] )
return True
def __nameEditingFinished( self, nameWidget ) :
selectedPaths = self.__pathListing.getSelectedPaths()
if not len( selectedPaths ) :
return True
oldName = selectedPaths[0][0]
newName = nameWidget.getText()
if oldName == newName :
return True
if newName == "" :
nameWidget.setText( oldName )
return True
maketrans = str.maketrans if six.PY3 else string.maketrans
newName = newName.translate( maketrans( "/*?\\[", "_____" ) )
items = self.__pathListing.getPath().dict().items()
with Gaffer.BlockedConnection( self.__plugMetadataChangedConnection ) :
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
for item in items :
Gaffer.Metadata.deregisterValue( self.getPlug(), "preset:" + item[0] )
for item in items :
Gaffer.Metadata.registerValue( self.getPlug(), "preset:" + (item[0] if item[0] != oldName else newName), item[1] )
self.__updatePath()
self.__pathListing.setSelectedPaths( [ self.__pathListing.getPath().copy().setFromString( "/" + newName ) ] )
return True
def __valuePlugSet( self, plug ) :
if not plug.isSame( self.__valueNode["presetValue"] ) :
return
selectedPaths = self.__pathListing.getSelectedPaths()
preset = selectedPaths[0][0]
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
Gaffer.Metadata.registerValue( self.getPlug(), "preset:" + preset, plug.getValue() )
} )
self.__plug = None
def setPlug( self, plug ) :
self.__plug = plug
self.__nameWidget.setGraphComponent( self.__plug )
for widget in self.__metadataWidgets.values() :
widget.setTarget( self.__plug )
self.__plugMetadataChangedConnection = None
if self.__plug is not None :
self.__plugMetadataChangedConnection = Gaffer.Metadata.plugValueChangedSignal( self.__plug.node() ).connect(
Gaffer.WeakMethod( self.__plugMetadataChanged )
)
self.__updateWidgetMenuText()
self.__updateWidgetSettings()
self.__updateGadgetMenuText()
self.__presetsEditor.setPlug( plug )
self.__graphEditorSection.setEnabled( self.__plug is not None and self.__plug.parent().isSame( self.__plug.node() ) )
self.setEnabled( self.__plug is not None )
def getPlug( self ) :
return self.__plug
__plugValueWidgets = {}
## Registers a custom PlugValueWidget type for a plug type, so it can be selected in the UIEditor
# label: String with the label to be displayed for this widget.
# plugType: Gaffer.Plug class that can use the widget being registered.
# metadata: String with associated metadata for the widget. Usually the python identifier for the widget (ex: "GafferUI.BoolPlugValueWidget").
@classmethod
def registerPlugValueWidget( cls, label, plugType, metadata ) :
if plugType not in cls.__plugValueWidgets :
cls.__plugValueWidgets[plugType] = {}
cls.__plugValueWidgets[plugType][label] = metadata
__widgetSettings = []
## Register additional metadata for PlugValueWidgets
# label: string with the label to be displayed for this widget
# plugValueWidgetType: string with the "plugValueWidget:type" metadata value where this settings applies, or a pattern for it.
# widgetCreator: callable that receives the plug and returns a MetadataWidget (or another widget) to edit the metadata
@classmethod
def registerWidgetSetting( cls, label, plugValueWidgetType, widgetCreator ) :
cls.__widgetSettings.append( ( label, plugValueWidgetType, widgetCreator ) )
## Returns a dictionary with the registered PlugValueWidgets for the given plug object or type
# the dictionary keys will be labels, and the values strings with the widget metadata
@classmethod
def __registeredPlugValueWidgets( cls, plugOrPlugType ) :
result = {}
plugType = plugOrPlugType
if not inspect.isclass( plugType ) :
plugType = type( plugOrPlugType )
# consider base classes for the plug
for baseClass in plugType.__bases__ :
if not issubclass( baseClass, Gaffer.Plug ) :
continue
result.update( cls.__registeredPlugValueWidgets( baseClass ) )
# consider itself
result.update( cls.__plugValueWidgets.get( plugType, {} ) )
return result
def __plugMetadataChanged( self, plug, key, reason ) :
if plug != self.getPlug() :
return
if key == "plugValueWidget:type" :
self.__updateWidgetMenuText()
self.__updateWidgetSettings()
elif key == "nodule:type" :
self.__updateGadgetMenuText()
def __updateWidgetMenuText( self ) :
if self.getPlug() is None :
self.__widgetMenu.setText( "" )
return
metadata = Gaffer.Metadata.value( self.getPlug(), "plugValueWidget:type" )
registeredWidgets = self.__registeredPlugValueWidgets( self.getPlug() )
for label, widgetMetadata in registeredWidgets.items() :
if widgetMetadata == metadata :
self.__widgetMenu.setText( label )
return
self.__widgetMenu.setText( metadata )
def __updateWidgetSettings( self ) :
del self.__widgetSettingsContainer[:]
if self.getPlug() is None :
return
widgetType = Gaffer.Metadata.value( self.getPlug(), "plugValueWidget:type" ) or ""
with self.__widgetSettingsContainer :
for label, plugValueWidgetType, widgetCreator in self.__widgetSettings :
if not IECore.StringAlgo.match( widgetType, plugValueWidgetType ) :
continue
with _Row() :
_Label( label )
widgetCreator( self.getPlug() )
self.__metadataWidgets["connectionGadget:color"].parent().setEnabled(
self.getPlug() is not None and self.getPlug().direction() == Gaffer.Plug.Direction.In
)
def __widgetMenuDefinition( self ) :
result = IECore.MenuDefinition()
if self.getPlug() is None :
return result
metadata = Gaffer.Metadata.value( self.getPlug(), "plugValueWidget:type" )
registeredWidgets = self.__registeredPlugValueWidgets( self.getPlug() )
labels = list( registeredWidgets.keys() )
# sort labels so that they are alphabetical, but with "Default" first, and "None" last
labels.sort()
labels.sort( key=lambda l: 0 if l == "Default" else 2 if l == "None" else 1 )
for label in labels :
result.append(
"/" + label,
{
"command" : functools.partial(
Gaffer.WeakMethod( self.__registerOrDeregisterMetadata ),
key = "plugValueWidget:type",
value = registeredWidgets[label]
),
"checkBox" : metadata == registeredWidgets[label],
}
)
return result
def __updateGadgetMenuText( self ) :
if self.getPlug() is None :
self.__gadgetMenu.setText( "" )
return
metadata = Gaffer.Metadata.value( self.getPlug(), "nodule:type" )
metadata = None if metadata == "GafferUI::StandardNodule" else metadata
for g in self.__gadgetDefinitions :
if g.metadata == metadata :
self.__gadgetMenu.setText( g.label )
return
self.__gadgetMenu.setText( metadata )
def __gadgetMenuDefinition( self ) :
result = IECore.MenuDefinition()
if self.getPlug() is None :
return result
metadata = Gaffer.Metadata.value( self.getPlug(), "nodule:type" )
for g in self.__gadgetDefinitions :
if not isinstance( self.getPlug(), g.plugType ) :
continue
result.append(
"/" + g.label,
{
"command" : functools.partial( Gaffer.WeakMethod( self.__registerOrDeregisterMetadata ), key = "nodule:type", value = g.metadata ),
"checkBox" : metadata == g.metadata,
}
)
return result
def __registerOrDeregisterMetadata( self, unused, key, value ) :
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
if value is not None :
Gaffer.Metadata.registerValue( self.getPlug(), key, value )
else :
Gaffer.Metadata.deregisterValue( self.getPlug(), key )
__GadgetDefinition = collections.namedtuple( "GadgetDefinition", ( "label", "plugType", "metadata" ) )
__gadgetDefinitions = (
__GadgetDefinition( "Default", Gaffer.Plug, None ),
__GadgetDefinition( "Array", Gaffer.ArrayPlug, "GafferUI::CompoundNodule" ),
__GadgetDefinition( "None", Gaffer.Plug, "" ),
)
##########################################################################
# _SectionEditor. This provides a panel for editing the details of
# a specific section.
##########################################################################
class _SectionEditor( GafferUI.Widget ) :
def __init__( self, **kw ) :
column = GafferUI.ListContainer( spacing = 4, borderWidth = 8 )
GafferUI.Widget.__init__( self, column, **kw )
with column :
with _Row() :
_Label( "Name" )
self.__nameWidget = GafferUI.TextWidget()
self.__nameWidget.editingFinishedSignal().connect( Gaffer.WeakMethod( self.__nameWidgetEditingFinished ), scoped = False )
with _Row() :
_Label( "Summary", parenting = { "verticalAlignment" : GafferUI.ListContainer.VerticalAlignment.Top } )
self.__summaryMetadataWidget = MetadataWidget.MultiLineStringMetadataWidget( key = "" )
self.__section = ""
self.__plugParent = None
self.__nameChangedSignal = Gaffer.Signal3()
def setPlugParent( self, plugParent ) :
self.__plugParent = plugParent
self.__summaryMetadataWidget.setTarget( self.__plugParent )
def getPlugParent( self ) :
return self.__plugParent
def setSection( self, section ) :
assert( isinstance( section, six.string_types ) )
self.__section = section
self.__nameWidget.setText( section.rpartition( "." )[-1] )
self.__summaryMetadataWidget.setKey( "layout:section:" + self.__section + ":summary" )
def getSection( self ) :
return self.__section
def nameChangedSignal( self ) :
return self.__nameChangedSignal
def __nameWidgetEditingFinished( self, nameWidget ) :
if nameWidget.getText() == "" :
# Can't rename to the empty string - abandon the edit.
self.setSection( self.__section )
return
oldSectionPath = self.__section.split( "." )
newSectionPath = oldSectionPath[:]
newSectionPath[-1] = nameWidget.getText().replace( ".", "" )
if oldSectionPath == newSectionPath :
return
def newSection( oldSection ) :
s = oldSection.split( "." )
if s[:len(oldSectionPath)] == oldSectionPath :
s[:len(oldSectionPath)] = newSectionPath
return ".".join( s )
else :
return oldSection
with Gaffer.UndoScope( self.__plugParent.ancestor( Gaffer.ScriptNode ) ) :
for plug in self.__plugParent.children( Gaffer.Plug ) :
s = Gaffer.Metadata.value( plug, "layout:section" )
if s is not None :
Gaffer.Metadata.registerValue( plug, "layout:section", newSection( s ) )
emptySections = Gaffer.Metadata.value( self.getPlugParent(), "uiEditor:emptySections" )
if emptySections :
for i in range( 0, len( emptySections ) ) :
emptySections[i] = newSection( emptySections[i] )
Gaffer.Metadata.registerValue( self.getPlugParent(), "uiEditor:emptySections", emptySections )
for name in Gaffer.Metadata.registeredValues( self.getPlugParent(), instanceOnly = True, persistentOnly = True ) :
m = re.match( "(layout:section:)(.*)(:.*)", name )
if m :
if newSection( m.group( 2 ) ) != m.group( 2 ) :
Gaffer.Metadata.registerValue(
self.getPlugParent(),
m.group( 1 ) + newSection( m.group( 2 ) ) + m.group( 3 ),
Gaffer.Metadata.value( self.getPlugParent(), name )
)
Gaffer.Metadata.deregisterValue( self.getPlugParent(), name )
self.setSection( ".".join( newSectionPath ) )
self.nameChangedSignal()( self, ".".join( oldSectionPath ), ".".join( newSectionPath ) )
| true | true |
f72a2f12d14736f1dea5052023ae58272f1954cd | 2,905 | py | Python | miniFawn/models.py | FelixTheC/allSales | 76d955b80bf9b5bb58bd53d8ee644249cf04e1a3 | [
"Apache-2.0"
] | null | null | null | miniFawn/models.py | FelixTheC/allSales | 76d955b80bf9b5bb58bd53d8ee644249cf04e1a3 | [
"Apache-2.0"
] | null | null | null | miniFawn/models.py | FelixTheC/allSales | 76d955b80bf9b5bb58bd53d8ee644249cf04e1a3 | [
"Apache-2.0"
] | null | null | null | from django.db import models
from django.urls import reverse
from ordercontact.models import Ordercontactinvoiceaddresse
from ordercontact.models import Ordercontactdeliveryaddresse
from sales.models import ProductionRecordInputMiniGL
from sales.models import BaseModelWithoutBeltDesign
class Minifawnordermodel(BaseModelWithoutBeltDesign):
min_belt_circumference = models.CharField(null=True, blank=True, max_length=100)
max_belt_circumference = models.CharField(null=True, blank=True, max_length=100)
skip_count = models.CharField(null=True, blank=True, max_length=255)
customer_invoice_address = models.ForeignKey(Ordercontactinvoiceaddresse, blank=True, null=True)
delivery_addresse = models.ForeignKey(Ordercontactdeliveryaddresse, blank=True, null=True)
class Meta:
managed = False
db_table = 'miniFawnOrderModel'
app_label = 'sales'
def get_back_to_list(self):
return reverse('sales:listsorders')
def get_delete_url(self):
return reverse('sales:minifawndelete', kwargs={'pk': self.pk})
def get_sells_update_url(self):
return reverse('sales:updateminifawn', kwargs={'pk': self.pk})
def get_sells_detail_url(self):
return reverse('sales:detailminifawn', kwargs={'pk': self.pk})
def get_prod_rec(self):
return reverse('sales:mfprodrec', kwargs={'pk': self.pk})
def get_accept_url(self):
return reverse('sales:acceptminifawn', kwargs={'pk': self.pk})
def get_pdf(self):
return reverse('sales:minifawnorderpdf', kwargs={'pk': self.pk})
def get_origin_pdf(self):
return reverse('sales:minifawnoriginpdf', kwargs={'pk': self.pk})
def get_prod_rec_pdf(self):
return reverse('sales:mfprodrecpdf', kwargs={'pk': self.pk})
def write_into_priolist(self):
return reverse('sales:acceptminifawnwriteprioliste', kwargs={'pk': self.pk})
def get_model_type(self):
return 'Mini Fawn'
def get_co_worker(self):
salesinput = SalesSalesinputminifawn.objects.filter(order__pk=self.pk)
try:
return str(salesinput[0].co_worker)
except IndexError:
return ''
def get_operation_number(self):
return self.operation_number
def check_for_prod_rec(self):
prod_recs = SalesSalesinputminifawn.objects.filter(order__pk=self.pk)
if len(prod_recs) < 1:
return False
else:
return True
def __str__(self):
return self.operation_number
class SalesSalesinputminifawn(ProductionRecordInputMiniGL):
order = models.ForeignKey(Minifawnordermodel, blank=True, null=True)
class Meta:
managed = True
app_label = 'sales'
def __str__(self):
return str(self.order.operation_number)
def get_update_url(self):
return reverse('sales:updateprodrecmf', kwargs={'pk': self.pk}) | 33.390805 | 100 | 0.703614 | from django.db import models
from django.urls import reverse
from ordercontact.models import Ordercontactinvoiceaddresse
from ordercontact.models import Ordercontactdeliveryaddresse
from sales.models import ProductionRecordInputMiniGL
from sales.models import BaseModelWithoutBeltDesign
class Minifawnordermodel(BaseModelWithoutBeltDesign):
min_belt_circumference = models.CharField(null=True, blank=True, max_length=100)
max_belt_circumference = models.CharField(null=True, blank=True, max_length=100)
skip_count = models.CharField(null=True, blank=True, max_length=255)
customer_invoice_address = models.ForeignKey(Ordercontactinvoiceaddresse, blank=True, null=True)
delivery_addresse = models.ForeignKey(Ordercontactdeliveryaddresse, blank=True, null=True)
class Meta:
managed = False
db_table = 'miniFawnOrderModel'
app_label = 'sales'
def get_back_to_list(self):
return reverse('sales:listsorders')
def get_delete_url(self):
return reverse('sales:minifawndelete', kwargs={'pk': self.pk})
def get_sells_update_url(self):
return reverse('sales:updateminifawn', kwargs={'pk': self.pk})
def get_sells_detail_url(self):
return reverse('sales:detailminifawn', kwargs={'pk': self.pk})
def get_prod_rec(self):
return reverse('sales:mfprodrec', kwargs={'pk': self.pk})
def get_accept_url(self):
return reverse('sales:acceptminifawn', kwargs={'pk': self.pk})
def get_pdf(self):
return reverse('sales:minifawnorderpdf', kwargs={'pk': self.pk})
def get_origin_pdf(self):
return reverse('sales:minifawnoriginpdf', kwargs={'pk': self.pk})
def get_prod_rec_pdf(self):
return reverse('sales:mfprodrecpdf', kwargs={'pk': self.pk})
def write_into_priolist(self):
return reverse('sales:acceptminifawnwriteprioliste', kwargs={'pk': self.pk})
def get_model_type(self):
return 'Mini Fawn'
def get_co_worker(self):
salesinput = SalesSalesinputminifawn.objects.filter(order__pk=self.pk)
try:
return str(salesinput[0].co_worker)
except IndexError:
return ''
def get_operation_number(self):
return self.operation_number
def check_for_prod_rec(self):
prod_recs = SalesSalesinputminifawn.objects.filter(order__pk=self.pk)
if len(prod_recs) < 1:
return False
else:
return True
def __str__(self):
return self.operation_number
class SalesSalesinputminifawn(ProductionRecordInputMiniGL):
order = models.ForeignKey(Minifawnordermodel, blank=True, null=True)
class Meta:
managed = True
app_label = 'sales'
def __str__(self):
return str(self.order.operation_number)
def get_update_url(self):
return reverse('sales:updateprodrecmf', kwargs={'pk': self.pk}) | true | true |
f72a2fc7d90882bd0cd97ea02adabacff7fe8dea | 2,126 | py | Python | ml/myscript/Logisticegression.py | miraclestatus/mllearning | f5db6642e8c05488b133ee627e5f63c92e45ff6e | [
"Apache-2.0"
] | 1 | 2020-06-24T12:44:21.000Z | 2020-06-24T12:44:21.000Z | ml/myscript/Logisticegression.py | miraclestatus/mllearning | f5db6642e8c05488b133ee627e5f63c92e45ff6e | [
"Apache-2.0"
] | null | null | null | ml/myscript/Logisticegression.py | miraclestatus/mllearning | f5db6642e8c05488b133ee627e5f63c92e45ff6e | [
"Apache-2.0"
] | null | null | null | import numpy as np
from .metrics import accuracy_score
class Logisticegression():
def __init__(self):
# 系数
self.coef_ = None
# 截距
self.intercept_ = None
# 向量
self._theta = None
def _sigmoid(self, t):
return 1./(1. + np.exp(-t))
def fit(self, X_train, y_train, eta=0.01, n_iters=1e4):
"""根据训练数据集X_train, y_train, 使用梯度下降法训练Linear Regression模型"""
assert X_train.shape[0] == y_train.shape[0], \
"the size of X_train must be equal to the size of y_train"
def J(theta, X_b, y):
y_hat = self._sigmoid(X_b.dot(theta))
try:
return - np.sum(y*np.log(y_hat) + (1-y)*np.log(1-y_hat)) / len(y)
except:
return float('inf')
def dJ(theta, X_b, y):
return X_b.T.dot(self._sigmoid(X_b.dot(theta))-y) /len(y)
def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):
theta = initial_theta
cur_iter = 0
while cur_iter < n_iters:
gradient = dJ(theta, X_b, y)
last_theta = theta
theta = theta - eta * gradient
if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):
break
cur_iter += 1
return theta
X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
initial_theta = np.zeros(X_b.shape[1])
self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)
self.intercept_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
def predict_proba(self,X_predict):
X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
return self._sigmoid(X_b.dot(self._theta))
def predict(self, X_predict):
proba = self.predict_proba(X_predict)
return np.array(proba >= 0.5, dtype='int')
def score(self, X_test, y_test):
y_predict = self.predict(X_test)
return accuracy_score(y_test, y_predict)
def __repr__(self):
return "Logisticegression()" | 33.746032 | 84 | 0.562088 | import numpy as np
from .metrics import accuracy_score
class Logisticegression():
def __init__(self):
self.coef_ = None
self.intercept_ = None
self._theta = None
def _sigmoid(self, t):
return 1./(1. + np.exp(-t))
def fit(self, X_train, y_train, eta=0.01, n_iters=1e4):
assert X_train.shape[0] == y_train.shape[0], \
"the size of X_train must be equal to the size of y_train"
def J(theta, X_b, y):
y_hat = self._sigmoid(X_b.dot(theta))
try:
return - np.sum(y*np.log(y_hat) + (1-y)*np.log(1-y_hat)) / len(y)
except:
return float('inf')
def dJ(theta, X_b, y):
return X_b.T.dot(self._sigmoid(X_b.dot(theta))-y) /len(y)
def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):
theta = initial_theta
cur_iter = 0
while cur_iter < n_iters:
gradient = dJ(theta, X_b, y)
last_theta = theta
theta = theta - eta * gradient
if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):
break
cur_iter += 1
return theta
X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
initial_theta = np.zeros(X_b.shape[1])
self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)
self.intercept_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
def predict_proba(self,X_predict):
X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
return self._sigmoid(X_b.dot(self._theta))
def predict(self, X_predict):
proba = self.predict_proba(X_predict)
return np.array(proba >= 0.5, dtype='int')
def score(self, X_test, y_test):
y_predict = self.predict(X_test)
return accuracy_score(y_test, y_predict)
def __repr__(self):
return "Logisticegression()" | true | true |
f72a2ff159f35066264c6696680d05775e13ffd9 | 125,019 | py | Python | flare_emu.py | mr-tz/flare-emu | 0cc6b0b73feba3ffdd83e0892b18b9b4fcbe0403 | [
"Apache-2.0"
] | null | null | null | flare_emu.py | mr-tz/flare-emu | 0cc6b0b73feba3ffdd83e0892b18b9b4fcbe0403 | [
"Apache-2.0"
] | null | null | null | flare_emu.py | mr-tz/flare-emu | 0cc6b0b73feba3ffdd83e0892b18b9b4fcbe0403 | [
"Apache-2.0"
] | null | null | null | ############################################
# Copyright (C) 2018 FireEye, Inc.
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-BSD-3-CLAUSE or
# https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be
# copied, modified, or distributed except according to those terms.
#
# Author: James T. Bennett
#
# flare-emu combines Unicorn and IDA to provide emulation support for
# reverse engineers
# Currently supports 32-bit and 64-bit x86, ARM, and ARM64
# Dependencies:
# https://github.com/unicorn-engine/unicorn
############################################
from __future__ import print_function
import idc
import idaapi
import idautils
import unicorn
import unicorn.x86_const
import unicorn.arm_const
import unicorn.arm64_const
from copy import deepcopy
import logging
import struct
import re
IDADIR = idc.idadir()
PAGESIZE = 0x1000
PAGEALIGNCHECK = 0xfff
X86NOP = "\x90"
ARMTHUMBNOP = "\x00\xbf"
ARMNOP = "\x00\xf0\x20\xe3"
ARM64NOP = "\x1f\x20\x03\xd5"
MAX_ALLOC_SIZE = 10 * 1024 * 1024
MAXCODEPATHS = 20
try:
long # Python 2
except NameError:
long = int # Python 3
class EmuHelper():
def __init__(self, verbose = 0):
self.verbose = verbose
self.stack = 0
self.stackSize = 0x2000
self.size_DWORD = 4
self.size_pointer = 0
self.callMnems = ["call", "BL", "BLX", "BLR",
"BLXEQ", "BLEQ", "BLREQ"]
self.paths = {}
self.filetype = "UNKNOWN"
self.uc = None
self.h_userhook = None
self.h_memaccesshook = None
self.h_codehook = None
self.h_memhook = None
self.h_inthook = None
self.enteredBlock = False
self.initEmuHelper()
self.reloadBinary()
# startAddr: address to start emulation
# endAddr: address to end emulation, this instruction is not executed.
# if not provided, emulation stops when starting function is exited
# (function must end with a return instruction)
# registers: a dict whose keys are register names and values are
# register values, all unspecified registers will be initialized to 0
# stack: a list of values to be setup on the stack before emulation.
# if X86 you must account for SP+0 (return address).
# for the stack and registers parameters, specifying a string will
# allocate memory, write the string to it, and write a pointer to that
# memory in the specified register/arg
# instructionHook: instruction hook func that runs AFTER emulateRange's hook
# hookData: user-defined data to be made available in instruction hook
# function, care must be taken to not use key names already used by
# flare_emu in userData dictionary
# skipCalls: emulator will skip over call instructions and adjust the
# stack accordingly, defaults to True
# emulateRange will always skip over calls to empty memory
# callHook: callback function that will be called whenever the emulator
# encounters a "call" instruction. keep in mind your skipCalls value
# and that emulateRange will always skip over calls to empty memory
# memAccessHook: hook function that runs when the emulator encounters a
# memory read or write
# hookApis: set to False if you don't want flare-emu to emulate common
# runtime memory and string functions, defaults to True
# returns the emulation object in its state after the emulation completes
# count: Value passed to unicorn's uc_emu_start to indicate max number of
# instructions to emulate, Defaults to 0 (all code available).
def emulateRange(self, startAddr, endAddr=None, registers=None, stack=None, instructionHook=None, callHook=None,
memAccessHook=None, hookData=None, skipCalls=True, hookApis=True, count=0):
if registers is None:
registers = {}
if stack is None:
stack = []
userData = {"EmuHelper": self, "funcStart": idc.get_func_attr(startAddr, idc.FUNCATTR_START),
"funcEnd": idc.get_func_attr(startAddr, idc.FUNCATTR_END), "skipCalls": skipCalls,
"endAddr": endAddr, "func_t": idaapi.get_func(startAddr), "callHook": callHook, "hookApis": hookApis, "count": count}
if hookData:
userData.update(hookData)
mu = self.uc
self._prepEmuContext(registers, stack)
self.resetEmuHooks()
self.h_codehook = mu.hook_add(
unicorn.UC_HOOK_CODE, self._emulateRangeCodeHook, userData)
if instructionHook:
self.h_userhook = mu.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE, memAccessHook,
userData)
self.h_memhook = mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = mu.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
mu.emu_start(startAddr, userData["funcEnd"], count=count)
return mu
# call emulateRange using selected instructions in IDA Pro as start/end addresses
def emulateSelection(self, registers=None, stack=None, instructionHook=None, callHook=None,
memAccessHook=None, hookData=None, skipCalls=True, hookApis=True, count=0):
selection = idaapi.read_selection()
if selection[0]:
self.emulateRange(selection[1], selection[2], registers, stack, instructionHook,
callHook, memAccessHook, hookData, skipCalls, hookApis, count=count)
# target: finds first path through function to target using depth first
# search for each address in list, if a single address is specified,
# does so for each xref to target address
# emulates each target's function, forcing path to target, then
# executes callback function providing emu object and arguments
# instructionHook: user-defined instruction hook to run AFTER guidedHook that
# forces execution
# hookData: user-defined data to be made available in instruction hook
# function, care must be taken to not use key names already used by
# flare_emu in userData dictionary
# preEmuCallback: a callback that is called BEFORE each emulation run
# callHook: a callback that is called whenever the emulator encounters a
# "call" instruction. hook or no, after a call instruction, the
# program counter is advanced to the next instruction and the stack is
# automatically cleaned up
# resetEmuMem: if set to True, unmaps all allocated emulator memory and
# reloads the binary from the IDB into emulator memory before each
# emulation run. can significantly increase script run time, defaults
# to False
# hookApis: set to False if you don't want flare-emu to emulate common
# runtime memory and string functions, defaults to True
# memAccessHook: hook function that runs when the emulator encounters a
# memory read or write
def iterate(self, target, targetCallback, preEmuCallback=None, callHook=None, instructionHook=None,
hookData=None, resetEmuMem=False, hookApis=True, memAccessHook=None):
if target is None:
return
targetInfo = {}
if type(target) in [int, long]:
logging.debug("iterate target function: %s" %
self.hexString(target))
xrefs = list(idautils.XrefsTo(target))
for i, x in enumerate(xrefs):
# get unique functions from xrefs that we need to emulate
funcStart = idc.get_func_attr(x.frm, idc.FUNCATTR_START)
if funcStart == idc.BADADDR:
continue
if idc.print_insn_mnem(x.frm) not in ["call", "jmp", "BL", "BLX", "B", "BLR"]:
continue
logging.debug("getting a path to %s, %d of %d" %
(self.hexString(x.frm), i + 1, len(xrefs)))
flow, paths = self.getPath(x.frm)
if flow is not None:
targetInfo[x.frm] = (flow, paths)
elif isinstance(target, list):
for i, t in enumerate(target):
logging.debug("getting a path to %s, %d of %d" %
(self.hexString(t), i + 1, len(target)))
flow, paths = self.getPath(t)
if flow is not None:
targetInfo[t] = (flow, paths)
if len(targetInfo) <= 0:
logging.debug("no targets to iterate")
return
userData = {}
userData["targetInfo"] = targetInfo
userData["targetCallback"] = targetCallback
userData["callHook"] = callHook
userData["EmuHelper"] = self
userData["hookApis"] = hookApis
if hookData:
userData.update(hookData)
self.internalRun = False
self.resetEmuHooks()
self.h_codehook = self.uc.hook_add(
unicorn.UC_HOOK_CODE, self._guidedHook, userData)
if instructionHook:
self.h_userhook = self.uc.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE, memAccessHook,
userData)
self.h_memhook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = self.uc.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
self.blockIdx = 0
cnt = 1
# read targets from dict to go from higher to lower addresses
# this is done to optimize loop by allowing hook to check for and remove other targets visited en route to
# current target
while len(userData["targetInfo"]) > 0:
userData["targetVA"] = targetVA = sorted(
userData["targetInfo"].keys(), reverse=True)[0]
flow, paths = userData["targetInfo"][targetVA]
funcStart = flow[0][0]
userData["func_t"] = idaapi.get_func(funcStart)
self.pathIdx = 0
numTargets = len(userData["targetInfo"])
logging.debug("run #%d, %d targets remaining: %s (%d paths)" % (
cnt, numTargets, self.hexString(targetVA), len(paths)))
cnt2 = 1
numPaths = len(paths)
for path in paths:
logging.debug("emulating path #%d of %d from %s to %s via basic blocks: %s" % (
cnt2, numPaths, self.hexString(funcStart), self.hexString(targetVA), repr(path)))
for reg in self.regs:
self.uc.reg_write(self.regs[reg], 0)
if resetEmuMem:
self.reloadBinary()
self.uc.reg_write(self.regs["sp"], self.stack)
self.enteredBlock = False
userData["visitedTargets"] = []
if preEmuCallback:
preEmuCallback(self, userData, funcStart)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
self.uc.emu_start(funcStart, idc.get_func_attr(
funcStart, idc.FUNCATTR_END))
self.pathIdx += 1
self.blockIdx = 0
cnt2 += 1
# remove visited targets during this run from our dict
for addr in userData["visitedTargets"]:
del(userData["targetInfo"][addr])
cnt += 1
# simply emulates to the end of whatever bytes are provided
# these bytes are not loaded into IDB, only emulator memory; IDA APIs are not available for use in hooks here
def emulateBytes(self, bytes, registers=None, stack=None, baseAddr=0x400000, instructionHook=None,
memAccessHook=None, hookData=None):
if registers is None:
registers = {}
if stack is None:
stack = []
userData = {}
if hookData:
userData.update(hookData)
baseAddr = self.loadBytes(bytes, baseAddr)
endAddr = baseAddr + len(bytes)
userData["endAddr"] = endAddr
mu = self.uc
self._prepEmuContext(registers, stack)
self.resetEmuHooks()
self.h_codehook = mu.hook_add(
unicorn.UC_HOOK_CODE, self._emulateBytesCodeHook, userData)
if instructionHook:
self.h_userhook = mu.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE, memAccessHook,
userData)
self.h_memhook = mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = mu.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
mu.emu_start(baseAddr, endAddr)
return mu
def hexString(self, va):
if va > 0xffffffff:
return "%016X" % va
else:
return "%08X" % va
def pageAlignUp(self, v):
if v & PAGEALIGNCHECK != 0:
v += PAGESIZE - (v % PAGESIZE)
return v
# returns string of bytes from the IDB up to a null terminator, starting at addr, do not necessarily need to be printable
# characters
def getIDBString(self, addr):
buf = ""
while idc.get_bytes(addr, 1, False) != "\x00" and idc.get_bytes(addr, 1, False) is not None:
buf += idc.get_bytes(addr, 1, False)
addr += 1
return buf
# determines if the instruction at addr is for returning from a function call
def isRetInstruction(self, addr):
if idc.print_insn_mnem(addr)[:3].lower() == "ret":
return True
if idc.print_insn_mnem(addr) in ["BX", "B"] and idc.print_operand(addr, 0) == "LR":
return True
return False
# call from an emulation hook to skip the current instruction, moving pc to next instruction
# useIDA option was added to handle cases where IDA folds multiple instructions
# do not call multiple times in a row, depends on userData being updated by hook
def skipInstruction(self, userData, useIDA=False):
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
if useIDA:
self.uc.reg_write(self.regs["pc"], idc.next_head(
userData["currAddr"], idc.get_inf_attr(idc.INF_MAX_EA)))
else:
self.uc.reg_write(
self.regs["pc"], userData["currAddr"] + userData["currAddrSize"])
# get IDA's SP delta value for next instruction to adjust stack accordingly since we are skipping
# this instruction
self.uc.reg_write(self.regs["sp"], self.getRegVal(
"sp") + idaapi.get_sp_delta(userData["func_t"], idc.next_head(
userData["currAddr"], idc.get_inf_attr(idc.INF_MAX_EA))))
# call from an emulation hook to change program counter
def changeProgramCounter(self, userData, newPC):
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
self.uc.reg_write(self.regs["pc"], newPC)
# retrieves the value of a register, handling subregister addressing
def getRegVal(self, regName):
regVal = self.uc.reg_read(self.regs[regName])
# handle various subregister addressing
if self.arch == unicorn.UC_ARCH_X86:
if regName[:-1] in ["l", "b"]:
regVal = regVal & 0xFF
elif regName[:-1] == "h":
regVal = (regVal & 0xFF00) >> 8
elif len(regName) == 2 and regName[:-1] == "x":
regVal = regVal & 0xFFFF
elif self.arch == unicorn.UC_ARCH_ARM64:
if regName[0] == "W":
regVal = regVal & 0xFFFFFFFF
return regVal
def stopEmulation(self, userData):
self.enteredBlock = False
if "visitedTargets" in userData and userData["targetVA"] not in userData["visitedTargets"]:
userData["visitedTargets"].append(
userData["targetVA"])
self.uc.emu_stop()
def resetEmuHooks(self):
if self.uc is None:
logging.debug(
"resetEmuHooks: no hooks to reset, emulator has not been initialized yet")
return
if self.h_userhook:
self.uc.hook_del(self.h_userhook)
self.h_userhook = None
if self.h_memaccesshook:
self.uc.hook_del(self.h_memaccesshook)
self.h_memaccesshook = None
if self.h_codehook:
self.uc.hook_del(self.h_codehook)
self.h_codehook = None
if self.h_memhook:
self.uc.hook_del(self.h_memhook)
self.h_memhook = None
if self.h_inthook:
self.uc.hook_del(self.h_inthook)
self.h_inthook = None
# for debugging purposes
def getEmuState(self):
if self.arch == unicorn.UC_ARCH_X86:
if self.uc._mode == unicorn.UC_MODE_64:
out = "RAX: %016X\tRBX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RAX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RBX))
out += "RCX: %016X\tRDX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RCX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RDX))
out += "RDI: %016X\tRSI: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RDI), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RSI))
out += "R8: %016X\tR9: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_R8), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_R9))
out += "RBP: %016X\tRSP: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RBP), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RSP))
out += "RIP: %016X\n" % (self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RIP))
elif self.uc._mode == unicorn.UC_MODE_32:
out = "EAX: %016X\tEBX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EAX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EBX))
out += "ECX: %016X\tEDX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_ECX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EDX))
out += "EDI: %016X\tESI: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EDI), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_ESI))
out += "EBP: %016X\tESP: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EBP), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_ESP))
out += "EIP: %016X\n" % (self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EIP))
elif self.arch == unicorn.UC_ARCH_ARM64:
out = "X0: %016X\tX1: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X0), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X1))
out += "X2: %016X\tX3: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X2), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X3))
out += "X4: %016X\tX5: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X4), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X5))
out += "X6: %016X\tX7: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X6), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X7))
out += "X8: %016X\tX9: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X8), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X9))
out += "X10: %016X\tX11: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X10), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X11))
out += "X12: %016X\tX13: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X12), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X13))
out += "X14: %016X\tX15: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X14), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X15))
out += "X16: %016X\tX17: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X16), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X17))
out += "X18: %016X\tX19: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X18), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X19))
out += "X20: %016X\tX21: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X20), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X21))
out += "X22: %016X\tX23: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X22), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X23))
out += "X24: %016X\tX25: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X24), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X25))
out += "X26: %016X\tX27: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X26), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X27))
out += "X28: %016X\tX29: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X28), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X29))
out += "X30: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X30))
out += "PC: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_PC))
out += "SP: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_SP))
elif self.arch == unicorn.UC_ARCH_ARM:
out = "R0: %08X\tR1: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R0), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R1))
out += "R2: %08X\tR3: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R2), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R3))
out += "R4: %08X\tR5: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R4), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R5))
out += "R6: %08X\tR7: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R6), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R7))
out += "R8: %08X\tR9: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R8), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R9))
out += "R10: %08X\tR11: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R10), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R11))
out += "R12: %08X\tR13: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R12), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R13))
out += "R14: %08X\tR15: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R14), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R15))
out += "PC: %08X\n" % self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R15)
out += "SP: %08X\n" % self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R13)
else:
return ""
return out
# returns null-terminated string of bytes from the emulator's memory, starting at addr, do not necessarily need
# to be printable characters
def getEmuString(self, addr):
out = ""
while str(self.uc.mem_read(addr, 1)) != "\x00":
out += str(self.uc.mem_read(addr, 1))
addr += 1
return out
def getEmuWideString(self, addr):
out = ""
while str(self.uc.mem_read(addr, 2)) != "\x00\x00":
out += str(self.uc.mem_read(addr, 2))
addr += 2
return out
# returns a <size> string of bytes read from <addr>
def getEmuBytes(self, addr, size):
return str(self.uc.mem_read(addr, size))
# reads pointer value in emulator's memory
def getEmuPtr(self, va):
return struct.unpack(self.pack_fmt, self.uc.mem_read(va, self.size_pointer))[0]
# writes a pointer value in emulator's memory
def writeEmuPtr(self, va, value):
self.uc.mem_write(va, struct.pack(self.pack_fmt, value))
# for debugging
def formatBB(self, bb):
bbtype = {0: "fcb_normal", 1: "idaapi.fcb_indjump", 2: "idaapi.fcb_ret", 3: "fcb_cndret",
4: "idaapi.fcb_noret", 5: "fcb_enoret", 6: "idaapi.fcb_extern", 7: "fcb_error"}
return("ID: %d, Start: 0x%x, End: 0x%x, Last instruction: 0x%x, Size: %d, "
"Type: %s" % (bb.id, bb.start_ea, bb.end_ea, idc.idc.prev_head(bb.end_ea,
idc.get_inf_attr(idc.INF_MIN_EA)), (bb.end_ea - bb.start_ea), bbtype[bb.type]))
def getSegSize(self, ea, segEnd):
size = 0
while idc.has_value(idc.get_full_flags(ea)):
if ea >= segEnd:
break
size += 1
ea += 1
return size
# returns True if ea is in an area designated by IDA to be in thumb mode
def isThumbMode(self, ea):
return idc.get_sreg(ea, "T") == 1
def pageAlign(self, addr):
return addr & 0xfffffffffffff000
# get first path to target found during exploration
def getPath(self, targetVA):
function = idaapi.get_func(targetVA)
flowchart = idaapi.FlowChart(function)
target_bb = self.getBlockByVA(targetVA, flowchart)
start_bb = self.getStartBB(function, flowchart)
if target_bb.id != 0:
if self.verbose > 0:
logging.debug("exploring function with %d blocks" % flowchart.size)
graph = self._explore(start_bb, target_bb)
if graph is None:
logging.debug(
"graph for target %s could not be traversed, skipping" % self.hexString(targetVA))
return None, None
if self.verbose > 0:
logging.debug("graph for target:\n%s" % repr(graph))
path = [0]
if not self._findPathFromGraph(path, graph, 0, target_bb.id):
logging.debug(
"path for target %s could not be discovered, skipping" % self.hexString(targetVA))
return None, None
else:
path = [0]
if self.verbose > 0:
logging.debug("code path to target: %s" % repr(path))
# create my own idaapi.FlowChart object so it can be pickled for debugging purposes
flow = {}
for bb in flowchart:
flow[bb.id] = (bb.start_ea, bb.end_ea)
return flow, [path]
def getStartBB(self, function, flowchart):
for bb in flowchart:
if bb.start_ea == function.start_ea:
return bb
def getBlockIdByVA(self, targetVA, flowchart):
return self.getBlockByVA(targetVA, flowchart).id
def getBlockByVA(self, targetVA, flowchart):
for bb in flowchart:
if targetVA >= bb.start_ea and targetVA < bb.end_ea:
return bb
def getBlockById(self, id, flowchart):
for bb in flowchart:
if bb.id == id:
return bb
def isTerminatingBB(self, bb):
if (bb.type == idaapi.fcb_ret or bb.type == idaapi.fcb_noret or
(bb.type == idaapi.fcb_indjump and len(list(bb.succs())) == 0)):
return True
for b in bb.succs():
if b.type == idaapi.fcb_extern:
return True
return False
# sets up arch/mode specific variables, initializes emulator
def initEmuHelper(self):
info = idaapi.get_inf_structure()
if info.procName == "metapc":
self.arch = unicorn.UC_ARCH_X86
arch = "X86"
if info.is_64bit():
self.mode = unicorn.UC_MODE_64
self.derefPtr = idc.get_qword
mode = "64-bit"
self.size_pointer = 8
self.pack_fmt = "<Q"
self.pageMask = 0xfffffffffffff000
self.regs = {"ax": unicorn.x86_const.UC_X86_REG_RAX, "bx": unicorn.x86_const.UC_X86_REG_RBX,
"cx": unicorn.x86_const.UC_X86_REG_RCX, "dx": unicorn.x86_const.UC_X86_REG_RDX,
"di": unicorn.x86_const.UC_X86_REG_RDI, "si": unicorn.x86_const.UC_X86_REG_RSI,
"bp": unicorn.x86_const.UC_X86_REG_RBP, "sp": unicorn.x86_const.UC_X86_REG_RSP,
"ip": unicorn.x86_const.UC_X86_REG_RIP, "pc": unicorn.x86_const.UC_X86_REG_RIP,
"rax": unicorn.x86_const.UC_X86_REG_RAX, "rbx": unicorn.x86_const.UC_X86_REG_RBX,
"rcx": unicorn.x86_const.UC_X86_REG_RCX, "rdx": unicorn.x86_const.UC_X86_REG_RDX,
"rdi": unicorn.x86_const.UC_X86_REG_RDI, "rsi": unicorn.x86_const.UC_X86_REG_RSI,
"rbp": unicorn.x86_const.UC_X86_REG_RBP, "rsp": unicorn.x86_const.UC_X86_REG_RSP,
"r8": unicorn.x86_const.UC_X86_REG_R8, "r9": unicorn.x86_const.UC_X86_REG_R9,
"r10": unicorn.x86_const.UC_X86_REG_R10, "r11": unicorn.x86_const.UC_X86_REG_R11,
"r12": unicorn.x86_const.UC_X86_REG_R12, "r13": unicorn.x86_const.UC_X86_REG_R13,
"r14": unicorn.x86_const.UC_X86_REG_R14, "r15": unicorn.x86_const.UC_X86_REG_R15,
"ret": unicorn.x86_const.UC_X86_REG_RAX}
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk_win7"
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RCX,
"arg2": unicorn.x86_const.UC_X86_REG_RDX,
"arg3": unicorn.x86_const.UC_X86_REG_R8,
"arg4": unicorn.x86_const.UC_X86_REG_R9})
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx64"
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RDI,
"arg2": unicorn.x86_const.UC_X86_REG_RSI,
"arg3": unicorn.x86_const.UC_X86_REG_RDX,
"arg4": unicorn.x86_const.UC_X86_REG_RCX})
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x64"
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RDI,
"arg2": unicorn.x86_const.UC_X86_REG_RSI,
"arg3": unicorn.x86_const.UC_X86_REG_RDX,
"arg4": unicorn.x86_const.UC_X86_REG_RCX})
else:
self.filetype = "UNKNOWN"
# assume PE for mem dumps
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RCX,
"arg2": unicorn.x86_const.UC_X86_REG_RDX,
"arg3": unicorn.x86_const.UC_X86_REG_R8,
"arg4": unicorn.x86_const.UC_X86_REG_R9})
elif info.is_32bit():
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk"
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx"
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x86"
else:
self.filetype = "UNKNOWN"
self.mode = unicorn.UC_MODE_32
self.derefPtr = idc.get_wide_dword
mode = "32-bit"
self.size_pointer = 4
self.pack_fmt = "<I"
self.pageMask = 0xfffff000
self.regs = {"ax": unicorn.x86_const.UC_X86_REG_EAX, "bx": unicorn.x86_const.UC_X86_REG_EBX,
"cx": unicorn.x86_const.UC_X86_REG_ECX, "dx": unicorn.x86_const.UC_X86_REG_EDX,
"di": unicorn.x86_const.UC_X86_REG_EDI, "si": unicorn.x86_const.UC_X86_REG_ESI,
"bp": unicorn.x86_const.UC_X86_REG_EBP, "sp": unicorn.x86_const.UC_X86_REG_ESP,
"ip": unicorn.x86_const.UC_X86_REG_EIP, "pc": unicorn.x86_const.UC_X86_REG_EIP,
"eax": unicorn.x86_const.UC_X86_REG_EAX, "ebx": unicorn.x86_const.UC_X86_REG_EBX,
"ecx": unicorn.x86_const.UC_X86_REG_ECX, "edx": unicorn.x86_const.UC_X86_REG_EDX,
"edi": unicorn.x86_const.UC_X86_REG_EDI, "esi": unicorn.x86_const.UC_X86_REG_ESI,
"ebp": unicorn.x86_const.UC_X86_REG_EBP, "esp": unicorn.x86_const.UC_X86_REG_ESP,
"ret": unicorn.x86_const.UC_X86_REG_EAX}
else:
logging.debug(
"sample contains code for unsupported processor architecture")
return
elif info.procName == "ARM":
self.mode = unicorn.UC_MODE_ARM
mode = "ARM"
if info.is_64bit():
self.arch = unicorn.UC_ARCH_ARM64
arch = "ARM64"
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk_win7"
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx64"
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x64"
else:
self.filetype = "UNKNOWN"
self.size_pointer = 8
self.pack_fmt = "<Q"
self.derefPtr = idc.get_qword
self.pageMask = 0xfffffffffffff000
self.regs = {"R0": unicorn.arm64_const.UC_ARM64_REG_X0, "R1": unicorn.arm64_const.UC_ARM64_REG_X1,
"R2": unicorn.arm64_const.UC_ARM64_REG_X2, "R3": unicorn.arm64_const.UC_ARM64_REG_X3,
"R4": unicorn.arm64_const.UC_ARM64_REG_X4, "R5": unicorn.arm64_const.UC_ARM64_REG_X5,
"R6": unicorn.arm64_const.UC_ARM64_REG_X6, "R7": unicorn.arm64_const.UC_ARM64_REG_X7,
"R8": unicorn.arm64_const.UC_ARM64_REG_X8, "R9": unicorn.arm64_const.UC_ARM64_REG_X9,
"R10": unicorn.arm64_const.UC_ARM64_REG_X10, "R11": unicorn.arm64_const.UC_ARM64_REG_X11,
"R12": unicorn.arm64_const.UC_ARM64_REG_X12, "R13": unicorn.arm64_const.UC_ARM64_REG_X13,
"R14": unicorn.arm64_const.UC_ARM64_REG_X14, "R15": unicorn.arm64_const.UC_ARM64_REG_X15,
"X0": unicorn.arm64_const.UC_ARM64_REG_X0, "X1": unicorn.arm64_const.UC_ARM64_REG_X1,
"X2": unicorn.arm64_const.UC_ARM64_REG_X2, "X3": unicorn.arm64_const.UC_ARM64_REG_X3,
"X4": unicorn.arm64_const.UC_ARM64_REG_X4, "X5": unicorn.arm64_const.UC_ARM64_REG_X5,
"X6": unicorn.arm64_const.UC_ARM64_REG_X6, "X7": unicorn.arm64_const.UC_ARM64_REG_X7,
"X8": unicorn.arm64_const.UC_ARM64_REG_X8, "X9": unicorn.arm64_const.UC_ARM64_REG_X9,
"X10": unicorn.arm64_const.UC_ARM64_REG_X10, "X11": unicorn.arm64_const.UC_ARM64_REG_X11,
"X12": unicorn.arm64_const.UC_ARM64_REG_X12, "X13": unicorn.arm64_const.UC_ARM64_REG_X13,
"X14": unicorn.arm64_const.UC_ARM64_REG_X14, "X15": unicorn.arm64_const.UC_ARM64_REG_X15,
"X16": unicorn.arm64_const.UC_ARM64_REG_X16, "X17": unicorn.arm64_const.UC_ARM64_REG_X17,
"X18": unicorn.arm64_const.UC_ARM64_REG_X18, "X19": unicorn.arm64_const.UC_ARM64_REG_X19,
"X20": unicorn.arm64_const.UC_ARM64_REG_X20, "X21": unicorn.arm64_const.UC_ARM64_REG_X21,
"X22": unicorn.arm64_const.UC_ARM64_REG_X22, "X23": unicorn.arm64_const.UC_ARM64_REG_X23,
"X24": unicorn.arm64_const.UC_ARM64_REG_X24, "X25": unicorn.arm64_const.UC_ARM64_REG_X25,
"X26": unicorn.arm64_const.UC_ARM64_REG_X26, "X27": unicorn.arm64_const.UC_ARM64_REG_X27,
"X28": unicorn.arm64_const.UC_ARM64_REG_X28, "X29": unicorn.arm64_const.UC_ARM64_REG_X29,
"X30": unicorn.arm64_const.UC_ARM64_REG_X30, "W0": unicorn.arm64_const.UC_ARM64_REG_X0,
"W1": unicorn.arm64_const.UC_ARM64_REG_X1, "W2": unicorn.arm64_const.UC_ARM64_REG_X2,
"W3": unicorn.arm64_const.UC_ARM64_REG_X3, "W4": unicorn.arm64_const.UC_ARM64_REG_X4,
"W5": unicorn.arm64_const.UC_ARM64_REG_X5, "W6": unicorn.arm64_const.UC_ARM64_REG_X6,
"W7": unicorn.arm64_const.UC_ARM64_REG_X7, "W8": unicorn.arm64_const.UC_ARM64_REG_X8,
"W9": unicorn.arm64_const.UC_ARM64_REG_X9, "W10": unicorn.arm64_const.UC_ARM64_REG_X10,
"W11": unicorn.arm64_const.UC_ARM64_REG_X11, "W12": unicorn.arm64_const.UC_ARM64_REG_X12,
"W13": unicorn.arm64_const.UC_ARM64_REG_X13, "W14": unicorn.arm64_const.UC_ARM64_REG_X14,
"W15": unicorn.arm64_const.UC_ARM64_REG_X15, "W16": unicorn.arm64_const.UC_ARM64_REG_X16,
"W17": unicorn.arm64_const.UC_ARM64_REG_X17, "W18": unicorn.arm64_const.UC_ARM64_REG_X18,
"W19": unicorn.arm64_const.UC_ARM64_REG_X19, "W20": unicorn.arm64_const.UC_ARM64_REG_X20,
"W21": unicorn.arm64_const.UC_ARM64_REG_X21, "W22": unicorn.arm64_const.UC_ARM64_REG_X22,
"W23": unicorn.arm64_const.UC_ARM64_REG_X23, "W24": unicorn.arm64_const.UC_ARM64_REG_X24,
"W25": unicorn.arm64_const.UC_ARM64_REG_X25, "W26": unicorn.arm64_const.UC_ARM64_REG_X26,
"W27": unicorn.arm64_const.UC_ARM64_REG_X27, "W28": unicorn.arm64_const.UC_ARM64_REG_X28,
"W29": unicorn.arm64_const.UC_ARM64_REG_X29, "W30": unicorn.arm64_const.UC_ARM64_REG_X30,
"PC": unicorn.arm64_const.UC_ARM64_REG_PC, "pc": unicorn.arm64_const.UC_ARM64_REG_PC,
"LR": unicorn.arm64_const.UC_ARM64_REG_X30, "SP": unicorn.arm64_const.UC_ARM64_REG_SP,
"sp": unicorn.arm64_const.UC_ARM64_REG_SP, "ret": unicorn.arm64_const.UC_ARM64_REG_X0,
"S0": unicorn.arm64_const.UC_ARM64_REG_S0, "S1": unicorn.arm64_const.UC_ARM64_REG_S1,
"S2": unicorn.arm64_const.UC_ARM64_REG_S2, "S3": unicorn.arm64_const.UC_ARM64_REG_S3,
"S4": unicorn.arm64_const.UC_ARM64_REG_S4, "S5": unicorn.arm64_const.UC_ARM64_REG_S5,
"S6": unicorn.arm64_const.UC_ARM64_REG_S6, "S7": unicorn.arm64_const.UC_ARM64_REG_S7,
"S8": unicorn.arm64_const.UC_ARM64_REG_S8, "S9": unicorn.arm64_const.UC_ARM64_REG_S9,
"S10": unicorn.arm64_const.UC_ARM64_REG_S10, "S11": unicorn.arm64_const.UC_ARM64_REG_S11,
"S12": unicorn.arm64_const.UC_ARM64_REG_S12, "S13": unicorn.arm64_const.UC_ARM64_REG_S13,
"S14": unicorn.arm64_const.UC_ARM64_REG_S14, "S15": unicorn.arm64_const.UC_ARM64_REG_S15,
"S16": unicorn.arm64_const.UC_ARM64_REG_S16, "S17": unicorn.arm64_const.UC_ARM64_REG_S17,
"S18": unicorn.arm64_const.UC_ARM64_REG_S18, "S19": unicorn.arm64_const.UC_ARM64_REG_S19,
"S20": unicorn.arm64_const.UC_ARM64_REG_S20, "S21": unicorn.arm64_const.UC_ARM64_REG_S21,
"S22": unicorn.arm64_const.UC_ARM64_REG_S22, "S23": unicorn.arm64_const.UC_ARM64_REG_S23,
"S24": unicorn.arm64_const.UC_ARM64_REG_S24, "S25": unicorn.arm64_const.UC_ARM64_REG_S25,
"S26": unicorn.arm64_const.UC_ARM64_REG_S26, "S27": unicorn.arm64_const.UC_ARM64_REG_S27,
"S28": unicorn.arm64_const.UC_ARM64_REG_S28, "S29": unicorn.arm64_const.UC_ARM64_REG_S29,
"S30": unicorn.arm64_const.UC_ARM64_REG_S30, "S31": unicorn.arm64_const.UC_ARM64_REG_S31,
"D0": unicorn.arm64_const.UC_ARM64_REG_D0, "D1": unicorn.arm64_const.UC_ARM64_REG_D1,
"D2": unicorn.arm64_const.UC_ARM64_REG_D2, "D3": unicorn.arm64_const.UC_ARM64_REG_D3,
"D4": unicorn.arm64_const.UC_ARM64_REG_D4, "D5": unicorn.arm64_const.UC_ARM64_REG_D5,
"D6": unicorn.arm64_const.UC_ARM64_REG_D6, "D7": unicorn.arm64_const.UC_ARM64_REG_D7,
"D8": unicorn.arm64_const.UC_ARM64_REG_D8, "D9": unicorn.arm64_const.UC_ARM64_REG_D9,
"D10": unicorn.arm64_const.UC_ARM64_REG_D10, "D11": unicorn.arm64_const.UC_ARM64_REG_D11,
"D12": unicorn.arm64_const.UC_ARM64_REG_D12, "D13": unicorn.arm64_const.UC_ARM64_REG_D13,
"D14": unicorn.arm64_const.UC_ARM64_REG_D14, "D15": unicorn.arm64_const.UC_ARM64_REG_D15,
"D16": unicorn.arm64_const.UC_ARM64_REG_D16, "D17": unicorn.arm64_const.UC_ARM64_REG_D17,
"D18": unicorn.arm64_const.UC_ARM64_REG_D18, "D19": unicorn.arm64_const.UC_ARM64_REG_D19,
"D20": unicorn.arm64_const.UC_ARM64_REG_D20, "D21": unicorn.arm64_const.UC_ARM64_REG_D21,
"D22": unicorn.arm64_const.UC_ARM64_REG_D22, "D23": unicorn.arm64_const.UC_ARM64_REG_D23,
"D24": unicorn.arm64_const.UC_ARM64_REG_D24, "D25": unicorn.arm64_const.UC_ARM64_REG_D25,
"D26": unicorn.arm64_const.UC_ARM64_REG_D26, "D27": unicorn.arm64_const.UC_ARM64_REG_D27,
"D28": unicorn.arm64_const.UC_ARM64_REG_D28, "D29": unicorn.arm64_const.UC_ARM64_REG_D29,
"D30": unicorn.arm64_const.UC_ARM64_REG_D30, "D31": unicorn.arm64_const.UC_ARM64_REG_D31,
"H0": unicorn.arm64_const.UC_ARM64_REG_H0, "H1": unicorn.arm64_const.UC_ARM64_REG_H1,
"H2": unicorn.arm64_const.UC_ARM64_REG_H2, "H3": unicorn.arm64_const.UC_ARM64_REG_H3,
"H4": unicorn.arm64_const.UC_ARM64_REG_H4, "H5": unicorn.arm64_const.UC_ARM64_REG_H5,
"H6": unicorn.arm64_const.UC_ARM64_REG_H6, "H7": unicorn.arm64_const.UC_ARM64_REG_H7,
"H8": unicorn.arm64_const.UC_ARM64_REG_H8, "H9": unicorn.arm64_const.UC_ARM64_REG_H9,
"H10": unicorn.arm64_const.UC_ARM64_REG_H10, "H11": unicorn.arm64_const.UC_ARM64_REG_H11,
"H12": unicorn.arm64_const.UC_ARM64_REG_H12, "H13": unicorn.arm64_const.UC_ARM64_REG_H13,
"H14": unicorn.arm64_const.UC_ARM64_REG_H14, "H15": unicorn.arm64_const.UC_ARM64_REG_H15,
"H16": unicorn.arm64_const.UC_ARM64_REG_H16, "H17": unicorn.arm64_const.UC_ARM64_REG_H17,
"H18": unicorn.arm64_const.UC_ARM64_REG_H18, "H19": unicorn.arm64_const.UC_ARM64_REG_H19,
"H20": unicorn.arm64_const.UC_ARM64_REG_H20, "H21": unicorn.arm64_const.UC_ARM64_REG_H21,
"H22": unicorn.arm64_const.UC_ARM64_REG_H22, "H23": unicorn.arm64_const.UC_ARM64_REG_H23,
"H24": unicorn.arm64_const.UC_ARM64_REG_H24, "H25": unicorn.arm64_const.UC_ARM64_REG_H25,
"H26": unicorn.arm64_const.UC_ARM64_REG_H26, "H27": unicorn.arm64_const.UC_ARM64_REG_H27,
"H28": unicorn.arm64_const.UC_ARM64_REG_H28, "H29": unicorn.arm64_const.UC_ARM64_REG_H29,
"H30": unicorn.arm64_const.UC_ARM64_REG_H30, "H31": unicorn.arm64_const.UC_ARM64_REG_H31,
"Q0": unicorn.arm64_const.UC_ARM64_REG_Q0, "Q1": unicorn.arm64_const.UC_ARM64_REG_Q1,
"Q2": unicorn.arm64_const.UC_ARM64_REG_Q2, "Q3": unicorn.arm64_const.UC_ARM64_REG_Q3,
"Q4": unicorn.arm64_const.UC_ARM64_REG_Q4, "Q5": unicorn.arm64_const.UC_ARM64_REG_Q5,
"Q6": unicorn.arm64_const.UC_ARM64_REG_Q6, "Q7": unicorn.arm64_const.UC_ARM64_REG_Q7,
"Q8": unicorn.arm64_const.UC_ARM64_REG_Q8, "Q9": unicorn.arm64_const.UC_ARM64_REG_Q9,
"Q10": unicorn.arm64_const.UC_ARM64_REG_Q10, "Q11": unicorn.arm64_const.UC_ARM64_REG_Q11,
"Q12": unicorn.arm64_const.UC_ARM64_REG_Q12, "Q13": unicorn.arm64_const.UC_ARM64_REG_Q13,
"Q14": unicorn.arm64_const.UC_ARM64_REG_Q14, "Q15": unicorn.arm64_const.UC_ARM64_REG_Q15,
"Q16": unicorn.arm64_const.UC_ARM64_REG_Q16, "Q17": unicorn.arm64_const.UC_ARM64_REG_Q17,
"Q18": unicorn.arm64_const.UC_ARM64_REG_Q18, "Q19": unicorn.arm64_const.UC_ARM64_REG_Q19,
"Q20": unicorn.arm64_const.UC_ARM64_REG_Q20, "Q21": unicorn.arm64_const.UC_ARM64_REG_Q21,
"Q22": unicorn.arm64_const.UC_ARM64_REG_Q22, "Q23": unicorn.arm64_const.UC_ARM64_REG_Q23,
"Q24": unicorn.arm64_const.UC_ARM64_REG_Q24, "Q25": unicorn.arm64_const.UC_ARM64_REG_Q25,
"Q26": unicorn.arm64_const.UC_ARM64_REG_Q26, "Q27": unicorn.arm64_const.UC_ARM64_REG_Q27,
"Q28": unicorn.arm64_const.UC_ARM64_REG_Q28, "Q29": unicorn.arm64_const.UC_ARM64_REG_Q29,
"Q30": unicorn.arm64_const.UC_ARM64_REG_Q30, "Q31": unicorn.arm64_const.UC_ARM64_REG_Q31}
self.regs.update({"arg1": unicorn.arm64_const.UC_ARM64_REG_X0,
"arg2": unicorn.arm64_const.UC_ARM64_REG_X1,
"arg3": unicorn.arm64_const.UC_ARM64_REG_X2,
"arg4": unicorn.arm64_const.UC_ARM64_REG_X3})
elif info.is_32bit():
self.arch = unicorn.UC_ARCH_ARM
arch = "ARM"
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk"
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx"
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x86"
else:
self.filetype = "UNKNOWN"
self.size_pointer = 4
self.pack_fmt = "<I"
self.derefPtr = idc.get_wide_dword
self.pageMask = 0xfffff000
self.regs = {"R0": unicorn.arm_const.UC_ARM_REG_R0, "R1": unicorn.arm_const.UC_ARM_REG_R1,
"R2": unicorn.arm_const.UC_ARM_REG_R2, "R3": unicorn.arm_const.UC_ARM_REG_R3,
"R4": unicorn.arm_const.UC_ARM_REG_R4, "R5": unicorn.arm_const.UC_ARM_REG_R5,
"R6": unicorn.arm_const.UC_ARM_REG_R6, "R7": unicorn.arm_const.UC_ARM_REG_R7,
"R8": unicorn.arm_const.UC_ARM_REG_R8, "R9": unicorn.arm_const.UC_ARM_REG_R9,
"R10": unicorn.arm_const.UC_ARM_REG_R10, "R11": unicorn.arm_const.UC_ARM_REG_R11,
"R12": unicorn.arm_const.UC_ARM_REG_R12, "R13": unicorn.arm_const.UC_ARM_REG_R13,
"R14": unicorn.arm_const.UC_ARM_REG_R14, "R15": unicorn.arm_const.UC_ARM_REG_R15,
"PC": unicorn.arm_const.UC_ARM_REG_R15, "pc": unicorn.arm_const.UC_ARM_REG_R15,
"LR": unicorn.arm_const.UC_ARM_REG_R14, "SP": unicorn.arm_const.UC_ARM_REG_R13,
"sp": unicorn.arm_const.UC_ARM_REG_R13, "apsr": unicorn.arm_const.UC_ARM_REG_APSR,
"APSR": unicorn.arm_const.UC_ARM_REG_APSR, "ret": unicorn.arm_const.UC_ARM_REG_R0,
"S0": unicorn.arm_const.UC_ARM_REG_S0, "S1": unicorn.arm_const.UC_ARM_REG_S1,
"S2": unicorn.arm_const.UC_ARM_REG_S2, "S3": unicorn.arm_const.UC_ARM_REG_S3,
"S4": unicorn.arm_const.UC_ARM_REG_S4, "S5": unicorn.arm_const.UC_ARM_REG_S5,
"S6": unicorn.arm_const.UC_ARM_REG_S6, "S7": unicorn.arm_const.UC_ARM_REG_S7,
"S8": unicorn.arm_const.UC_ARM_REG_S8, "S9": unicorn.arm_const.UC_ARM_REG_S9,
"S10": unicorn.arm_const.UC_ARM_REG_S10, "S11": unicorn.arm_const.UC_ARM_REG_S11,
"S12": unicorn.arm_const.UC_ARM_REG_S12, "S13": unicorn.arm_const.UC_ARM_REG_S13,
"S14": unicorn.arm_const.UC_ARM_REG_S14, "S15": unicorn.arm_const.UC_ARM_REG_S15,
"S16": unicorn.arm_const.UC_ARM_REG_S16, "S17": unicorn.arm_const.UC_ARM_REG_S17,
"S18": unicorn.arm_const.UC_ARM_REG_S18, "S19": unicorn.arm_const.UC_ARM_REG_S19,
"S20": unicorn.arm_const.UC_ARM_REG_S20, "S21": unicorn.arm_const.UC_ARM_REG_S21,
"S22": unicorn.arm_const.UC_ARM_REG_S22, "S23": unicorn.arm_const.UC_ARM_REG_S23,
"S24": unicorn.arm_const.UC_ARM_REG_S24, "S25": unicorn.arm_const.UC_ARM_REG_S25,
"S26": unicorn.arm_const.UC_ARM_REG_S26, "S27": unicorn.arm_const.UC_ARM_REG_S27,
"S28": unicorn.arm_const.UC_ARM_REG_S28, "S29": unicorn.arm_const.UC_ARM_REG_S29,
"S30": unicorn.arm_const.UC_ARM_REG_S30, "S31": unicorn.arm_const.UC_ARM_REG_S31}
self.regs.update({"arg1": unicorn.arm_const.UC_ARM_REG_R0, "arg2": unicorn.arm_const.UC_ARM_REG_R1,
"arg3": unicorn.arm_const.UC_ARM_REG_R2, "arg4": unicorn.arm_const.UC_ARM_REG_R3})
else:
logging.debug(
"sample contains code for unsupported processor architecture")
return
else:
logging.debug(
"sample contains code for unsupported processor architecture")
return
# naive API hooks
self.apiHooks = {}
self.apiHooks["GetProcessHeap"] = self._returnHandleHook
self.apiHooks["HeapCreate"] = self._returnHandleHook
self.apiHooks["HeapAlloc"] = self._allocMem3Hook
self.apiHooks["HeapReAlloc"] = self._heapReAllocHook
self.apiHooks["RtlAllocateHeap"] = self._allocMem3Hook
self.apiHooks["AllocateHeap"] = self._allocMem1Hook
# ignore LMEM_MOVEABLE flag, return mem ptr anyway, have Lock return ptr param
self.apiHooks["LocalAlloc"] = self._allocMem2Hook
self.apiHooks["LocalLock"] = self._returnParam1Hook
self.apiHooks["GlobalAlloc"] = self._allocMem2Hook
self.apiHooks["GlobalLock"] = self._returnParam1Hook
# these ignore flags for now
self.apiHooks["LocalReAlloc"] = self._reallocHook
self.apiHooks["GlobalReAlloc"] = self._reallocHook
self.apiHooks["VirtualAlloc"] = self._virtualAllocHook
self.apiHooks["VirtualAllocEx"] = self._virtualAllocExHook
self.apiHooks["malloc"] = self._allocMem1Hook
self.apiHooks["calloc"] = self._callocHook
self.apiHooks["realloc"] = self._reallocHook
self.apiHooks["memcpy"] = self._memcpyHook
self.apiHooks["memmove"] = self._memcpyHook
self.apiHooks["strlen"] = self._strlenHook
self.apiHooks["lstrlenA"] = self._strlenHook
self.apiHooks["strnlen"] = self._strnlenHook
self.apiHooks["strnlen_s"] = self._strnlenHook
self.apiHooks["strcmp"] = self._strcmpHook
self.apiHooks["lstrcmpA"] = self._strcmpHook
self.apiHooks["strncmp"] = self._strncmpHook
self.apiHooks["stricmp"] = self._stricmpHook
self.apiHooks["lstrcmpiA"] = self._stricmpHook
self.apiHooks["strnicmp"] = self._strnicmpHook
self.apiHooks["wcscmp"] = self._wcscmpHook
self.apiHooks["lstrcmpW"] = self._wcscmpHook
self.apiHooks["wcsncmp"] = self._wcsncmpHook
self.apiHooks["wcsicmp"] = self._wcsicmpHook
self.apiHooks["lstrcmpiW"] = self._wcsicmpHook
self.apiHooks["wcsnicmp"] = self._wcsnicmpHook
self.apiHooks["mbscmp"] = self._strcmpHook
self.apiHooks["mbsncmp"] = self._strncmpHook
self.apiHooks["mbsicmp"] = self._stricmpHook
self.apiHooks["mbsnicmp"] = self._strnicmpHook
self.apiHooks["strcpy"] = self._strcpyHook
self.apiHooks["strncpy"] = self._strncpyHook
self.apiHooks["lstrcpyA"] = self._strcpyHook
self.apiHooks["lstrcpynA"] = self._strncpyHook
self.apiHooks["strncpy_s"] = self._strncpysHook
self.apiHooks["wcscpy"] = self._wcscpyHook
self.apiHooks["wcsncpy"] = self._wcsncpyHook
self.apiHooks["lstrcpyW"] = self._wcscpyHook
self.apiHooks["lstrcpynW"] = self._wcsncpyHook
self.apiHooks["wcsncpy_s"] = self._wcsncpysHook
self.apiHooks["mbscpy"] = self._strcpyHook
self.apiHooks["mbsncpy"] = self._strncpyHook
self.apiHooks["mbsncpy_s"] = self._strncpysHook
self.apiHooks["memchr"] = self._memchrHook
self.apiHooks["strchr"] = self._strchrHook
self.apiHooks["wcschr"] = self._wcschrHook
self.apiHooks["mbschr"] = self._strchrHook
self.apiHooks["strrchr"] = self._strrchrHook
self.apiHooks["wcsrchr"] = self._wcsrchrHook
self.apiHooks["mbsrchr"] = self._strrchrHook
self.apiHooks["wcslen"] = self._wcslenHook
self.apiHooks["lstrlenW"] = self._wcslenHook
self.apiHooks["mbslen"] = self._strlenHook
self.apiHooks["mbstrlen"] = self._strlenHook
self.apiHooks["wcsnlen"] = self._wcsnlenHook
self.apiHooks["wcsnlen_s"] = self._wcsnlenHook
self.apiHooks["mbsnlen"] = self._strnlenHook
self.apiHooks["mbstrnlen"] = self._strnlenHook
self.apiHooks["strcat"] = self._strcatHook
self.apiHooks["lstrcatA"] = self._strcatHook
self.apiHooks["strncat"] = self._strncatHook
self.apiHooks["wcscat"] = self._wcscatHook
self.apiHooks["lstrcatW"] = self._wcscatHook
self.apiHooks["wcsncat"] = self._wcsncatHook
self.apiHooks["mbscat"] = self._strcatHook
self.apiHooks["mbsncat"] = self._strncatHook
self.apiHooks["strlwr"] = self._strlwrHook
self.apiHooks["strupr"] = self._struprHook
self.apiHooks["wcslwr"] = self._wcslwrHook
self.apiHooks["wcsupr"] = self._wcsuprHook
self.apiHooks["mbslwr"] = self._strlwrHook
self.apiHooks["mbsupr"] = self._struprHook
self.apiHooks["strdup"] = self._strdupHook
self.apiHooks["wcsdup"] = self._wcsdupHook
self.apiHooks["mbsdup"] = self._strdupHook
self.apiHooks["mbtowc"] = self._mbtowcHook
self.apiHooks["mbstowcs"] = self._mbstowcsHook
self.apiHooks["wctomb"] = self._wctombHook
self.apiHooks["wcstombs"] = self._wcstombsHook
self.apiHooks["MultiByteToWideChar"] = self._multiByteToWideCharHook
self.apiHooks["WideCharToMultiByte"] = self._wideCharToMultiByteHook
self.apiHooks["memset"] = self._memsetHook
self.apiHooks["ZeroMemory"] = self._bzeroHook
self.apiHooks["bzero"] = self._bzeroHook
# builtins
self.apiHooks["umodsi3"] = self._modHook
self.allocMap = {}
# Initialize emulator
mu = unicorn.Uc(self.arch, self.mode)
logging.debug("initialized emulator for %s with %s architecture in %s mode" % (
self.filetype, arch, mode))
self.uc = mu
if self.arch == unicorn.UC_ARCH_ARM or self.arch == unicorn.UC_ARCH_ARM64:
self._enableVFP()
# unmap all emulator memory
def resetEmulatorMemory(self):
for region in self.uc.mem_regions():
self.uc.mem_unmap(region[0], region[1] - region[0] + 1)
def resetEmulatorHeapAndStack(self):
for region in self.uc.mem_regions():
if region[0] != self.baseAddr:
self.uc.mem_unmap(region[0], region[1] - region[0] + 1)
logging.debug("unmapped %s to %s" % (
self.hexString(region[0]), self.hexString(region[1])))
self._buildStack()
# reset emulator memory and rewrite binary segments to emulator memory, build new stack
def reloadBinary(self):
self.resetEmulatorMemory()
baseAddr = idc.get_inf_attr(idc.INF_MIN_EA)
endAddr = idc.get_inf_attr(idc.INF_MAX_EA)
self.baseAddr = baseAddr
memsize = endAddr - baseAddr
memsize = self.pageAlignUp(memsize)
# map all binary segments as one memory region for easier management
self.uc.mem_map(baseAddr & self.pageMask, memsize)
for segVA in idautils.Segments():
segName = idc.get_segm_name(segVA)
endVA = idc.get_segm_end(segVA)
segSizeTotal = endVA - segVA
segSize = self.getSegSize(segVA, endVA)
logging.debug("bytes in seg: %s" % self.hexString(segSize))
logging.debug("mapping segment %s: %s - %s" %
(segName, self.hexString(segVA), self.hexString(endVA)))
if segSize > 0:
segBytes = idc.get_bytes(segVA, segSize, False)
self.uc.mem_write(segVA, segBytes)
segLeftover = segSizeTotal - segSize
if segLeftover > 0:
self.uc.mem_write(segVA + segSize, "\x00" * segLeftover)
self._buildStack()
# allocs mem and writes bytes into it
def loadBytes(self, bytes, addr=None):
mem = self.allocEmuMem(len(bytes), addr)
self.uc.mem_write(mem, bytes)
return mem
def isValidEmuPtr(self, ptr):
for region in self.uc.mem_regions():
if ptr >= region[0] and ptr < region[1]:
return True
return False
def getEmuMemRegion(self, addr):
for region in self.uc.mem_regions():
if addr >= region[0] and addr < region[1]:
return (region[0], region[1] + 1)
return None
# allocate emulator memory, attempts to honor specified address, otherwise begins allocations
# at the next page
# aligned address above the highest, returns address, rebased if necessary
def allocEmuMem(self, size, addr=None):
allocSize = self.pageAlignUp(size)
if addr is None:
baseAddr = addr = self._findUnusedMemRegion()
else:
isValid = True
baseAddr = self.pageAlign(addr)
offs = addr - baseAddr
for region in self.uc.mem_regions():
# if start or end of region falls in range of a previous region
if ((baseAddr >= region[0] and baseAddr < region[1]) or
(baseAddr + allocSize >= region[0] and baseAddr + allocSize < region[1])):
isValid = False
break
# if region completely envelopes a previous region
if baseAddr < region[0] and baseAddr + allocSize > region[1]:
isValid = False
break
if isValid is False:
baseAddr = self._findUnusedMemRegion()
addr = baseAddr + offs
logging.debug("mapping %s bytes @%s" %
(self.hexString(allocSize), self.hexString(baseAddr)))
self.uc.mem_map(baseAddr, allocSize)
return addr
def copyEmuMem(self, dstAddr, srcAddr, size, userData):
size = self._checkMemSize(size, userData)
try:
mem = str(self.uc.mem_read(srcAddr, size))
self.uc.mem_write(dstAddr, mem)
except Exception as e:
logging.debug("exception in copyEmuMem @%s: %s" % (self.hexString(address), str(e)))
def getCallTargetName(self, address):
if idc.get_operand_type(address, 0) == 1:
funcName = idc.get_name(self.uc.reg_read(
self.regs[idc.print_operand(address, 0)]), idc.ida_name.GN_VISIBLE)
# elif idc.get_operand_type(address, 0) == 2:
# funcName = idc.get_name(self.getEmuPtr(idc.get_operand_value(address, 0)),
# idc.ida_name.GN_VISIBLE)
else:
funcName = idc.get_name(idc.get_operand_value(address, 0), idc.ida_name.GN_VISIBLE)
return funcName
# we don't know the number of args to a given function and we're not considering SSE args
# this is just a convenience, use the emulator object if you have specific needs
def getArgv(self):
if self.arch == unicorn.UC_ARCH_X86:
if self.mode == unicorn.UC_MODE_64:
if self.filetype == "MACHO" or self.filetype == "ELF":
argv = [
self.getRegVal("rdi"),
self.getRegVal("rsi"),
self.getRegVal("rdx"),
self.getRegVal("rcx"),
self.getRegVal("r8"),
self.getRegVal("r9")]
else:
argv = [
self.getRegVal("rcx"),
self.getRegVal("rdx"),
self.getRegVal("r8"),
self.getRegVal("r9")]
else:
sp = self.getRegVal("esp")
argv = [
struct.unpack("<I", str(self.uc.mem_read(sp, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 4, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 8, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 12, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 16, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 20, 4)))[0]]
elif self.arch == unicorn.UC_ARCH_ARM:
argv = [
self.getRegVal("R0"),
self.getRegVal("R1"),
self.getRegVal("R2"),
self.getRegVal("R3")]
elif self.arch == unicorn.UC_ARCH_ARM64:
argv = [
self.getRegVal("X0"),
self.getRegVal("X1"),
self.getRegVal("X2"),
self.getRegVal("X3"),
self.getRegVal("X4"),
self.getRegVal("X5"),
self.getRegVal("X6"),
self.getRegVal("X7")]
else:
argv = None
return argv
def _checkMemSize(self, size, userData):
if size > MAX_ALLOC_SIZE:
logging.debug("allocation size (%s) truncated @%s" %
(self.hexString(size), self.hexString(userData["currAddr"])))
size = MAX_ALLOC_SIZE
return size
############################################
# BEGIN API HOOKS
############################################
# return a fake handle value
def _returnHandleHook(self, address, argv, funcName, userData):
self.uc.reg_write(self.regs["ret"], 42)
def _returnParam1Hook(self, address, argv, funcName, userData):
self.uc.reg_write(self.regs["ret"], argv[0])
def _allocMem1Hook(self, address, argv, funcName, userData):
allocSize = argv[0]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
def _allocMem2Hook(self, address, argv, funcName, userData):
allocSize = argv[1]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
def _allocMem3Hook(self, address, argv, funcName, userData):
allocSize = argv[2]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
def _callocHook(self, address, argv, funcName, userData):
allocSize = argv[0] * argv[1]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
# deny "in place only" flag
def _heapReAllocHook(self, address, argv, funcName, userData):
HEAP_REALLOC_IN_PLACE_ONLY = 0x10
if argv[1] & HEAP_REALLOC_IN_PLACE_ONLY:
self.uc.reg_write(self.regs["ret"], 0)
else:
allocSize = argv[3]
allocSize = self._checkMemSize(allocSize, userData)
region = self.getEmuMemRegion(argv[2])
if region is not None:
allocSize = max(region[1] - region[0], allocSize)
memAddr = self.allocEmuMem(allocSize)
self.copyEmuMem(memAddr, region[0], region[1] - region[0], userData)
else:
memAddr = self.allocEmuMem(allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
def _reallocHook(self, address, argv, funcName, userData):
allocSize = argv[1]
allocSize = self._checkMemSize(allocSize, userData)
region = self.getEmuMemRegion(argv[0])
if region is not None:
allocSize = max(region[1] - region[0], allocSize)
memAddr = self.allocEmuMem(allocSize)
self.copyEmuMem(memAddr, region[0], region[1] - region[0], userData)
else:
memAddr = self.allocEmuMem(allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
# allocate regardless of commit flag, keep a mapping of requested addr -> actual addr
def _virtualAllocHook(self, address, argv, funcName, userData):
allocAddr = argv[0]
if allocAddr in self.allocMap:
self.uc.reg_write(self.regs["ret"], self.allocMap[allocAddr][0])
return
allocSize = argv[1]
allocSize = self._checkMemSize(allocSize, userData)
memAddr = self.allocEmuMem(allocSize, allocAddr)
self.allocMap[allocAddr] = (memAddr, allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
# handle same as VirtualAlloc hook, just with different argument placement
def _virtualAllocExHook(self, address, argv, funcName, userData):
allocAddr = argv[1]
if allocAddr in self.allocMap:
self.uc.reg_write(self.regs["ret"], self.allocMap[allocAddr][0])
return
allocSize = argv[2]
allocSize = self._checkMemSize(allocSize, userData)
memAddr = self.allocEmuMem(allocSize, allocAddr)
self.allocMap[allocAddr] = (memAddr, allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
def _memcpyHook(self, address, argv, funcName, userData):
copySize = argv[2]
copySize = self._checkMemSize(copySize, userData)
srcRegion = self.getEmuMemRegion(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for memcpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(copySize))
argv[0] = dstRegion[0]
if srcRegion is None:
logging.debug("source memory does not exist for memcpy @%s" % self.hexString(address))
else:
if copySize <= srcRegion[1] - argv[1] and copySize <= dstRegion[1] - argv[0]:
self.copyEmuMem(argv[0], argv[1], copySize, userData)
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], argv[0])
def _strlenHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
self.uc.reg_write(self.regs["ret"], len(self.getEmuString(argv[0])))
else:
self.uc.reg_write(self.regs["ret"], 0)
def _wcslenHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
self.uc.reg_write(self.regs["ret"], len(self.getEmuWideString(argv[0]).decode("utf-16")))
else:
self.uc.reg_write(self.regs["ret"], 0)
def _strnlenHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[1], userData)
if self.isValidEmuPtr(argv[0]):
strlen = len(self.getEmuString(argv[0]))
strlen = min(strlen, strnlen)
self.uc.reg_write(self.regs["ret"], strlen)
else:
self.uc.reg_write(self.regs["ret"], 0)
def _wcsnlenHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[1], userData)
if self.isValidEmuPtr(argv[0]):
strlen = len(self.getEmuWideString(argv[0]).decode("utf-16"))
if strlen > strnlen:
strlen = argv[1]
self.uc.reg_write(self.regs["ret"], strnlen)
else:
self.uc.reg_write(self.regs["ret"], 0)
def _strcmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1 == str2:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strncmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1[:strnlen] == str2[:strnlen]:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _stricmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1.lower() == str2.lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strnicmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1[:strnlen].lower() == str2[:strnlen].lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcscmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1 == str2:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsncmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1[:strnlen] == str2[:strnlen]:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsicmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1.lower() == str2.lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsnicmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1[:strnlen].lower() == str2[:strnlen].lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strcpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuString(argv[1]) + "\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strcpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src)))
argv[0] = dstRegion[0]
if len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strncpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2], userData)
src = self.getEmuString(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strncpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
if strnlen <= dstRegion[1] - argv[0]:
if strnlen > len(src):
src = src.ljust(strnlen, "\x00")
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strncpysHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
strnlen = self._checkMemSize(argv[3], userData)
src = self.getEmuString(argv[2])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strncpy_s @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
strnlen = min(strnlen, len(src))
if strnlen + 1 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src + "\x00")
self.uc.reg_write(self.regs["ret"], 0)
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcscpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuWideString(argv[1]) + "\x00\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcscpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src)))
argv[0] = dstRegion[0]
if len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsncpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2] * 2, userData)
src = self.getEmuWideString(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcsncpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
if strnlen <= dstRegion[1] - argv[0]:
if strnlen > len(src):
src = src.ljust(strnlen, "\x00")
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsncpysHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
strnlen = self._checkMemSize(argv[3] * 2, userData)
src = self.getEmuWideString(argv[2])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcsncpy_s @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
strnlen = min(strnlen, len(src))
if strnlen + 2 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src[:strnlen] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], 0)
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _memchrHook(self, address, argv, funcName, userData):
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is not None:
srch = chr(argv[1] & 0xFF)
srchlen = argv[2]
# truncate search to end of region
if argv[0] + srchlen > dstRegion[1]:
srchlen = dstRegion[1] - argv[0]
buf = str(self.uc.mem_read(argv[0], srchlen))
offs = buf.find(srch)
if offs > -1:
self.uc.reg_write(self.regs["ret"], argv[0] + offs)
return
self.uc.reg_write(self.regs["ret"], 0)
def _mbstowcsHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
bufSize = self._checkMemSize(argv[2] * 2, userData)
src = self.getEmuString(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(bufSize))
argv[0] = dstRegion[0]
if argv[2] > len(src):
src = src.ljust(argv[2], "\x00")
else:
src += "\x00"
if len(src.encode("utf-16")[2:]) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src.encode("utf-16")[2:])
self.uc.reg_write(self.regs["ret"], len(src))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _mbtowcHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuString(argv[1])[0]
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(0x1000))
argv[0] = dstRegion[0]
self.uc.mem_write(argv[0], src.encode("utf-16")[2:4])
self.uc.reg_write(self.regs["ret"], 1)
return
self.uc.reg_write(self.regs["ret"], 0)
def _mbstowcsHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
maxBufSize = self._checkMemSize(argv[2] * 2, userData)
src = self.getEmuString(argv[1])
if len(src) < argv[2]:
src += "\x00"
else:
src = src[:argv[2]]
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(maxBufSize))
argv[0] = dstRegion[0]
if len(src) * 2 + 2 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src.encode("utf-16")[2:] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], len(src.replace("\x00", "")))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _wctombHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuWideString(argv[1]).decode("utf-16")
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wctomb variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(0x1000))
argv[0] = dstRegion[0]
self.uc.mem_write(argv[0], src[0])
self.uc.reg_write(self.regs["ret"], 1)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcstombsHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
bufSize = self._checkMemSize(argv[2], userData)
src = self.getEmuWideString(argv[1]).decode("utf-16")
if len(src) < argv[2]:
src += "\x00"
else:
src = src[:argv[2]]
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wctomb variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(bufSize))
argv[0] = dstRegion[0]
if bufSize + 1 <= dstRegion[1] - argv[0]:
if bufSize > len(src):
src = src.ljust(bufSize, "\x00")
self.uc.mem_write(argv[0], src + "\x00")
self.uc.reg_write(self.regs["ret"], len(src.replace("\x00", "")))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _multiByteToWideCharHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
src = self.getEmuString(argv[2])
if argv[3] == -1:
src += "\x00"
maxBufSize = self._checkMemSize(len(src) * 2, userData)
else:
maxBufSize = self._checkMemSize(argv[3] * 2, userData)
if len(src) < argv[3]:
src += "\x00"
elif argv[3] != -1:
src = src[:argv[3]]
if argv[5] == 0:
self.uc.reg_write(self.regs["ret"], len(src) * 2)
return
dstRegion = self.getEmuMemRegion(argv[4])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(maxBufSize))
argv[4] = dstRegion[0]
if len(src) * 2 + 2 <= dstRegion[1] - argv[4]:
self.uc.mem_write(argv[4], src.encode("utf-16")[2:] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], len(src))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _wideCharToMultiByteHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
src = self.getEmuWideString(argv[2]).decode("utf-16")
if argv[3] == -1:
src += "\x00"
maxBufSize = self._checkMemSize(len(src), userData)
else:
maxBufSize = self._checkMemSize(argv[3], userData)
if len(src) < argv[3]:
src += "\x00"
elif argv[3] != -1:
src = src[:argv[3]]
if argv[5] == 0:
self.uc.reg_write(self.regs["ret"], len(src))
return
dstRegion = self.getEmuMemRegion(argv[4])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(maxBufSize))
argv[4] = dstRegion[0]
if len(src) + 1 <= dstRegion[1] - argv[4]:
self.uc.mem_write(argv[4], src + "\x00")
self.uc.reg_write(self.regs["ret"], len(src))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _memsetHook(self, address, argv, funcName, userData):
setSize = argv[2]
setSize = self._checkMemSize(setSize, userData)
dstRegion = self.getEmuMemRegion(argv[0])
src = chr(argv[1] & 0xFF)
if dstRegion is None:
logging.debug("dest memory does not exist for memset @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(setSize))
argv[0] = dstRegion[0]
if setSize <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src * setSize)
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], argv[0])
def _bzeroHook(self, address, argv, funcName, userData):
setSize = argv[1]
setSize = self._checkMemSize(setSize, userData)
dstRegion = self.getEmuMemRegion(argv[0])
src = "\x00"
if dstRegion is None:
logging.debug("dest memory does not exist for memset @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(setSize))
argv[0] = dstRegion[0]
if setSize <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src * setSize)
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], argv[0])
def _strcatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuString(argv[1]) + "\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strcat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src) + 1))
argv[0] = dstRegion[0]
dst = self.getEmuString(argv[0])
if len(dst) + len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _strncatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2], userData)
src = self.getEmuString(argv[1])
strnlen = min(strnlen, len(src))
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strncat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen + 1))
argv[0] = dstRegion[0]
dst = self.getEmuString(argv[0])
if len(dst) + strnlen + 1 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src[:strnlen] + "\x00")
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcscatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuWideString(argv[1]) + "\x00\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcscat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src)))
argv[0] = dstRegion[0]
dst = self.getEmuWideString(argv[0])
if len(dst) + len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsncatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2], userData)
src = self.getEmuWideString(argv[1])
strnlen = min(strnlen * 2, len(src))
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcsncat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen + 2))
argv[0] = dstRegion[0]
dst = self.getEmuWideString(argv[0])
if len(dst) + strnlen + 2 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src[:strnlen] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _strchrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
idx = s.find(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcschrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
idx = s.find(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx * 2)
return
self.uc.reg_write(self.regs["ret"], 0)
def _strrchrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
idx = s.rfind(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsrchrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
idx = s.rfind(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx * 2)
return
self.uc.reg_write(self.regs["ret"], 0)
def _strlwrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
self.uc.mem_write(argv[0], s.lower())
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _struprHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
self.uc.mem_write(argv[0], s.upper())
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcslwrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
self.uc.mem_write(argv[0], s.lower().encode("utf-16")[2:])
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsuprHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
self.uc.mem_write(argv[0], s.upper().encode("utf-16")[2:])
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _strdupHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
memAddr = self.allocEmuMem(len(s) + 1)
self.uc.mem_write(memAddr, s)
self.uc.reg_write(self.regs["ret"], memAddr)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsdupHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0])
memAddr = self.allocEmuMem(len(s) + 2)
self.uc.mem_write(memAddr, s)
self.uc.reg_write(self.regs["ret"], memAddr)
return
self.uc.reg_write(self.regs["ret"], 0)
def _modHook(self, address, argv, funcName, userData):
self.uc.reg_write(self.regs["ret"], argv[0] % argv[1])
############################################
# END API HOOKS
############################################
# maps null memory as requested during emulation
def _hookMemInvalid(self, uc, access, address, size, value, userData):
logging.debug("invalid memory operation for %s @%s" %
(self.hexString(address), self.hexString(userData['currAddr'])))
try:
uc.mem_map(address & self.pageMask, PAGESIZE)
uc.mem_write(address & self.pageMask, "\x00" * PAGESIZE)
except Exception:
logging.debug("error writing to %s, changing IP from %s to %s" % (self.hexString(address), self.hexString(
userData['currAddr']), self.hexString(userData['currAddr'] + userData['currAddrSize'])))
uc.reg_write(
self.regs["pc"], userData['currAddr'] + userData['currAddrSize'])
return True
# cannot seem to move IP forward from this hook for some reason..
# patches current instruction with NOPs
def _hookInterrupt(self, uc, intno, userData):
logging.debug("interrupt #%d received @%s" % ((intno), self.hexString(userData["currAddr"])))
if self.arch == unicorn.UC_ARCH_X86:
uc.mem_write(userData["currAddr"], X86NOP *
userData["currAddrSize"])
elif self.arch == unicorn.UC_ARCH_ARM:
if self.mode == unicorn.UC_MODE_THUMB:
uc.mem_write(userData["currAddr"],
ARMTHUMBNOP * (userData["currAddrSize"] / 2))
else:
uc.mem_write(
userData["currAddr"], ARMNOP * (userData["currAddrSize"] / 4))
elif self.arch == unicorn.UC_ARCH_ARM64:
uc.mem_write(
userData["currAddr"], ARM64NOP * (userData["currAddrSize"] / 4))
self.enteredBlock = False
return True
# handle common runtime functions
def _handleApiHooks(self, address, argv, funcName, userData):
# normalize funcName
# remove appended _n from IDA Pro names
funcName = re.sub(r"_[\d]+$", "", funcName)
# remove appended _l for locale flavors of string functions
funcName = re.sub(r"_l$", "", funcName)
# remove IDA Pro's j_ prefix
if funcName[:2] == "j_":
funcName = funcName[2:]
# remove prepended underscores
funcName = re.sub(r"^_+", "", funcName)
if funcName not in self.apiHooks:
return False
try:
self.apiHooks[funcName](address, argv, funcName, userData)
except Exception as e:
logging.debug("error handling API hook: %s @%s" % (e, self.hexString(address)))
self.skipInstruction(userData)
return True
# instruction hook used by emulateRange function
# implements bare bones instrumentation to handle basic code flow
def _emulateRangeCodeHook(self, uc, address, size, userData):
try:
userData['currAddr'] = address
userData['currAddrSize'] = size
if self.arch == unicorn.UC_ARCH_ARM and userData["changeThumbMode"]:
self._handleThumbMode(address)
userData["changeThumbMode"] = False
return
if self.verbose > 0:
if self.verbose > 1:
logging.debug(self.getEmuState())
dis = idc.generate_disasm_line(address, 0)
logging.debug("%s: %s" % (self.hexString(address), dis))
# stop emulation if specified endAddr is reached
if userData["endAddr"] is not None:
if address == userData["endAddr"]:
self.stopEmulation(userData)
return
if self._isBadBranch(userData):
self.skipInstruction(userData)
return
# stop annoying run ons if we end up somewhere we dont belong
if str(self.uc.mem_read(address, size)) == "\x00" * size:
logging.debug("pc ended up in null memory @%s" %
self.hexString(address))
self.stopEmulation(userData)
return
# otherwise, stop emulation when returning from function emulation began in
elif (self.isRetInstruction(address) and
idc.get_func_attr(address, idc.FUNCATTR_START) ==
userData["funcStart"]):
self.stopEmulation(userData)
return
elif self.isRetInstruction(address) and self.arch == unicorn.UC_ARCH_ARM:
# check mode of return address if ARM
retAddr = self.getEmuPtr(self.getRegVal("LR"))
if self.isThumbMode(retAddr):
userData["changeThumbMode"] = True
if (idc.print_insn_mnem(address) in self.callMnems or
(idc.print_insn_mnem(address) == "B" and
idc.get_name_ea_simple(idc.print_operand(address, 0)) ==
idc.get_func_attr(
idc.get_name_ea_simple(idc.print_operand(address, 0)),
idc.FUNCATTR_START))):
funcName = self.getCallTargetName(address)
if userData["callHook"]:
userData["callHook"](address, self.getArgv(), funcName, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
# if the pc has been changed by the hook, don't skip instruction and undo the change
if self.getRegVal("pc") != userData["currAddr"]:
# get IDA's SP delta value for next instruction to adjust stack accordingly since we are skipping this
# instruction
uc.reg_write(self.regs["sp"], self.getRegVal("sp") +
idaapi.get_sp_delta(userData["func_t"], self.getRegVal("pc")))
return
if userData["hookApis"] and self._handleApiHooks(address, self.getArgv(), funcName, userData):
return
# skip calls if specified or there are no instructions to emulate at destination address
if (userData["skipCalls"] is True or
(idc.get_operand_type(address, 0) == 7 and
str(uc.mem_read(idc.get_operand_value(address, 0), self.size_pointer)) ==
"\x00" * self.size_pointer)):
self.skipInstruction(userData)
# handle x86 instructions moving import pointers to a register
elif (idc.print_insn_mnem(address) == "mov" and
idc.get_operand_type(address, 1) == 2 and
idc.get_operand_type(address, 0) == 1 and
idc.print_operand(address, 1)[:3] == "ds:" and
str(uc.mem_read(idc.get_operand_value(address, 1), self.size_pointer)) ==
"\x00" * self.size_pointer):
uc.reg_write(self.regs[idc.print_operand(address, 0)], idc.get_operand_value(address, 1))
self.skipInstruction(userData)
except Exception as err:
logging.debug("exception in emulateRange_codehook @%s: %s" % (self.hexString(address), str(err)))
print("exception in emulateRange_codehook @%s: %s" % (self.hexString(address), str(err)))
self.stopEmulation(userData)
# instruction hook used by emulateBytes function
# implements bare bones instrumentation to handle basic code flow
def _emulateBytesCodeHook(self, uc, address, size, userData):
try:
userData['currAddr'] = address
userData['currAddrSize'] = size
# stop emulation if specified endAddr is reached
if userData["endAddr"] is not None:
if address == userData["endAddr"]:
self.stopEmulation(userData)
return
# stop annoying run ons if we end up somewhere we dont belong
if str(self.uc.mem_read(address, 0x10)) == "\x00" * 0x10:
self.stopEmulation(userData)
logging.debug("pc ended up in null memory @%s" %
self.hexString(address))
return
except Exception as err:
logging.debug("exception in emulateBytes_codehook @%s: %s" % (self.hexString(address), str(err)))
print("exception in emulateBytes_codehook @%s: %s" % (self.hexString(address), str(err)))
self.stopEmulation(userData)
# this instruction hook is used by the iterate feature, forces execution down a specified path
def _guidedHook(self, uc, address, size, userData):
try:
userData['currAddr'] = address
userData['currAddrSize'] = size
if self.arch == unicorn.UC_ARCH_ARM and userData["changeThumbMode"]:
self._handleThumbMode(address)
userData["changeThumbMode"] = False
return
if self.verbose > 0:
if self.verbose > 1:
logging.debug(self.getEmuState())
dis = idc.generate_disasm_line(address, 0)
logging.debug("%s: %s" % (self.hexString(address), dis))
if self.arch == unicorn.UC_ARCH_ARM:
# since there are lots of bad branches during emulation and we are forcing it anyways
if idc.print_insn_mnem(address)[:3] in ["TBB", "TBH"]:
# skip over interleaved jump table
nextInsnAddr = self._scanForCode(address + size)
self.changeProgramCounter(userData, nextInsnAddr)
return
elif self._isBadBranch(userData):
self.skipInstruction(userData)
return
flow, paths = userData["targetInfo"][userData["targetVA"]]
# check if we are out of our block bounds or re-entering our block in a loop
bbEnd = idc.prev_head(
flow[paths[self.pathIdx][self.blockIdx]][1], idc.get_inf_attr(idc.INF_MIN_EA))
bbStart = flow[paths[self.pathIdx][self.blockIdx]][0]
if address == bbStart and self.enteredBlock is True:
if self.blockIdx < len(paths[self.pathIdx]) - 1:
logging.debug("loop re-entering block #%d (%s -> %s), forcing PC to %s" %
(self.blockIdx, self.hexString(bbStart), self.hexString(bbEnd),
self.hexString(flow[paths[self.pathIdx][self.blockIdx + 1]][0])))
# force PC to follow paths
uc.reg_write(self.regs["pc"], flow[paths[self.pathIdx][self.blockIdx + 1]][0])
self.blockIdx += 1
self.enteredBlock = False
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
return
else:
logging.debug(
"loop re-entering block #%d (%s -> %s), but no more blocks! bailing out of this function.." %
(self.blockIdx, self.hexString(bbStart), self.hexString(bbEnd)))
self.stopEmulation(userData)
return
elif (address > bbEnd or address < bbStart):
# check if we skipped over our target (our next block index is out of range), this can happen in ARM
# with conditional instructions
if self.blockIdx + 1 >= len(paths[self.pathIdx]):
logging.debug(
"we missed our target! bailing out of this function..")
self.stopEmulation(userData)
return
logging.debug("%s is outside of block #%d (%s -> %s), forcing PC to %s" %
(self.hexString(address),
self.blockIdx, self.hexString(bbStart),
self.hexString(bbEnd), self.hexString(flow[paths[self.pathIdx][self.blockIdx + 1]][0])))
# force PC to follow paths
uc.reg_write(self.regs["pc"], flow[paths[self.pathIdx][self.blockIdx + 1]][0])
self.blockIdx += 1
self.enteredBlock = False
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
return
if address == bbStart:
self.enteredBlock = True
# possibly a folded instruction or invalid instruction
if idc.print_insn_mnem(address) == "":
if idc.print_insn_mnem(address + size) == "":
if idc.print_insn_mnem(address + size * 2) == "":
logging.debug(
"invalid instruction encountered @%s, bailing.." % self.hexString(address))
self.stopEmulation(userData)
return
return
# stop annoying run ons if we end up somewhere we dont belong
if str(self.uc.mem_read(address, 0x10)) == "\x00" * 0x10:
logging.debug("pc ended up in null memory @%s" %
self.hexString(address))
self.stopEmulation(userData)
return
# this is our stop, this is where we trigger user-defined callback with our info
if address == userData["targetVA"]:
logging.debug("target %s hit" %
self.hexString(userData["targetVA"]))
self._targetHit(address, userData)
self.stopEmulation(userData)
elif address in userData["targetInfo"]:
# this address is another target in the dict, process it and continue onward
logging.debug("target %s found on the way to %s" % (
self.hexString(address), self.hexString(userData["targetVA"])))
self._targetHit(address, userData)
if (idc.print_insn_mnem(address) in self.callMnems or
(idc.print_insn_mnem(address) == "B" and
idc.get_name_ea_simple(idc.print_operand(address, 0)) ==
idc.get_func_attr(
idc.get_name_ea_simple(idc.print_operand(address, 0)),
idc.FUNCATTR_START))):
funcName = self.getCallTargetName(address)
if userData["callHook"]:
userData["callHook"](address, self.getArgv(), funcName, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
# if the pc has been changed by the hook, don't skip instruction and undo the change
if self.getRegVal("pc") != userData["currAddr"]:
# get IDA's SP delta value for next instruction to adjust stack accordingly since we are skipping this
# instruction
uc.reg_write(self.regs["sp"], self.getRegVal("sp") +
idaapi.get_sp_delta(userData["func_t"], self.getRegVal("pc")))
return
if userData["hookApis"] and self._handleApiHooks(address, self.getArgv(), funcName, userData):
return
# if you change the program counter, it undoes your call to emu_stop()
if address != userData["targetVA"]:
self.skipInstruction(userData)
elif self.isRetInstruction(address):
# self.stopEmulation(userData)
self.skipInstruction(userData)
return
except Exception as e:
logging.debug("exception in _guidedHook @%s: %s" % (self.hexString(address), e))
print("exception in _guidedHook @%s: %s" % (self.hexString(address), e))
self.stopEmulation(userData)
# scans ahead from address until IDA finds an instruction
def _scanForCode(self, address):
while idc.print_insn_mnem(address) == "":
address = idc.next_head(address, idc.get_inf_attr(idc.INF_MAX_EA))
return address
# checks ARM mode for address and aligns address accordingly
def _handleThumbMode(self, address):
if self.isThumbMode(address):
self.uc.reg_write(self.regs["pc"], self.getRegVal("pc") | 1)
self.mode = unicorn.UC_MODE_THUMB
else:
self.uc.reg_write(self.regs["pc"], self.getRegVal("pc") & ~1)
self.mode = unicorn.UC_MODE_ARM
# called when an iterate target is reached
def _targetHit(self, address, userData):
try:
argv = self.getArgv()
userData["targetCallback"](self, address, argv, userData)
except Exception as e:
logging.debug("exception in targetCallback function @%s: %s" % (self.hexString(address), str(e)))
print("exception in targetCallback function @%s: %s" % (self.hexString(address), str(e)))
userData["visitedTargets"].append(address)
def _isBadBranch(self, userData):
if self.arch == unicorn.UC_ARCH_ARM64:
if (idc.print_insn_mnem(userData["currAddr"]) in ["BR", "BREQ"] and
idc.get_operand_type(userData["currAddr"], 0) == 1):
if (idc.print_insn_mnem(
self.uc.reg_read(
self.regs[idc.print_operand(userData["currAddr"], 0)]
))) == "":
return True
elif self.arch == unicorn.UC_ARCH_X86:
if (idc.print_insn_mnem(userData["currAddr"]) == "jmp" and
idc.get_operand_type(userData["currAddr"], 0) == 1):
if (idc.print_insn_mnem
(self.uc.reg_read(self.regs[idc.print_operand(userData["currAddr"], 0)])) == ""):
logging.debug("bad branch detected @%s" % self.hexString(userData["currAddr"]))
return True
# recursively searches control flow graph dict returned by _explore for a
# single path from currentNode to target basic block, check path parameter upon return
def _findPathFromGraph(self, path, graph, currentNode, target):
if currentNode not in graph:
return False
for node in graph[currentNode]:
if node in path:
continue
path.append(node)
if node == target:
return True
if self._findPathFromGraph(path, graph, node, target):
return True
else:
path.pop()
return False
# recursively searches control flow graph dict returned by _explore for
# up to maxPaths from currentNode to target basic block, check paths parameter upon return
def _findPathsFromGraph(self, paths, path, graph, currentNode, target, maxPaths=MAXCODEPATHS):
if currentNode not in graph:
return
if len(paths) >= maxPaths:
return
for node in graph[currentNode]:
if node in path:
continue
path.append(node)
if node == target:
paths.append(deepcopy(path))
path.pop()
return
self._findPathsFromGraph(paths, path, graph, node, target)
path.pop()
# returns a dictionary where the key is a node in the control flow graph
# and its value is a list of its successor nodes
def _explore(self, start_bb, end_bb=None):
stack = []
discovered = []
graph = {}
stack.append(start_bb)
while len(stack) > 0:
bb = stack.pop()
if bb.id not in discovered:
discovered.append(bb.id)
graph[bb.id] = []
for block in bb.succs():
stack.append(block)
graph[bb.id].append(block.id)
if end_bb is not None and block.id == end_bb.id:
return graph
return graph
def _findUnusedMemRegion(self):
# start at 0x10000 to avoid collision with null mem references during emulation
highest = 0x10000
for region in self.uc.mem_regions():
if region[1] > highest:
highest = region[1]
for segVA in idautils.Segments():
endVA = idc.get_segm_end(segVA)
if endVA > highest:
highest = endVA
highest += PAGESIZE
return self.pageAlignUp(highest)
# stack setup
# stack pointer will begin in the middle of allocated stack size
def _buildStack(self):
self.stack = self.allocEmuMem(self.stackSize) + self.stackSize / 2
self.uc.mem_write(self.stack - self.stackSize /
2, "\x00" * self.stackSize)
def _enableVFP(self):
if self.arch == unicorn.UC_ARCH_ARM:
# for ARM, we must run this code in order to enable vector instructions in our emulator
"""
mov.w r0, #0xf00000
mcr p15, #0x0, r0, c1, c0, #0x2
isb sy
mov.w r3, #0x40000000
vmsr fpexc, r3
"""
# ENABLE_VFP_CODE = "\x0f\x06\xa0\xe3\x50\x0f\x01\xee\x6f\xf0\x7f\xf5\x01\x31\xa0\xe3\x10\x3a\xe8\xee"
# self.emulateBytes(ENABLE_VFP_CODE, {}, [])
tmp = self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_C1_C0_2)
self.uc.reg_write(unicorn.arm_const.UC_ARM_REG_C1_C0_2, tmp | (0xf << 20))
self.uc.reg_write(unicorn.arm_const.UC_ARM_REG_FPEXC, 0x40000000)
elif self.arch == unicorn.UC_ARCH_ARM64:
"""
https://static.docs.arm.com/ddi0487/ca/DDI0487C_a_armv8_arm.pdf
MRS X2, CPACR_EL1
ORR X2, X2, #0x300000 # <-- set bits 20,21 to disable trapping for FP related instructions
MSR CPACR_EL1, X2
NOP # <-- handle Unicorn bug
"""
ENABLE_VFP_CODE = "\x42\x10\x38\xd5\x42\x04\x6c\xb2\x42\x10\x18\xd5\x1f\x20\x03\xd5"
self.emulateBytes(ENABLE_VFP_CODE)
# prepare thread context
def _prepEmuContext(self, registers, stack):
mu = self.uc
for reg in self.regs:
mu.reg_write(self.regs[reg], 0)
mu.reg_write(self.regs["sp"], self.stack)
for reg in registers:
val = registers[reg]
if isinstance(val, str):
mem = self.allocEmuMem(len(val))
mu.mem_write(mem, val)
val = mem
elif isinstance(val, (int, long)):
pass
else:
logging.debug("incorrect type for %s" % reg)
return None
mu.reg_write(self.regs[reg], val)
registers[reg] = val
# setup stack
for i in range(0, len(stack)):
if isinstance(stack[i], str):
mem = self.allocEmuMem(len(stack[i]))
mu.mem_write(mem, stack[i])
stack[i] = mem
val = mem
elif isinstance(stack[i], (int, long)):
val = stack[i]
else:
logging.debug("incorrect type for stack[%d]" % (i))
return None
mu.mem_write(self.getRegVal("sp") + i *
self.size_pointer, struct.pack(self.pack_fmt, val))
| 52.462862 | 138 | 0.562091 | ry read or write
# hookApis: set to False if you don't want flare-emu to emulate common
# instructions to emulate, Defaults to 0 (all code available).
def emulateRange(self, startAddr, endAddr=None, registers=None, stack=None, instructionHook=None, callHook=None,
memAccessHook=None, hookData=None, skipCalls=True, hookApis=True, count=0):
if registers is None:
registers = {}
if stack is None:
stack = []
userData = {"EmuHelper": self, "funcStart": idc.get_func_attr(startAddr, idc.FUNCATTR_START),
"funcEnd": idc.get_func_attr(startAddr, idc.FUNCATTR_END), "skipCalls": skipCalls,
"endAddr": endAddr, "func_t": idaapi.get_func(startAddr), "callHook": callHook, "hookApis": hookApis, "count": count}
if hookData:
userData.update(hookData)
mu = self.uc
self._prepEmuContext(registers, stack)
self.resetEmuHooks()
self.h_codehook = mu.hook_add(
unicorn.UC_HOOK_CODE, self._emulateRangeCodeHook, userData)
if instructionHook:
self.h_userhook = mu.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE, memAccessHook,
userData)
self.h_memhook = mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = mu.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
mu.emu_start(startAddr, userData["funcEnd"], count=count)
return mu
# call emulateRange using selected instructions in IDA Pro as start/end addresses
def emulateSelection(self, registers=None, stack=None, instructionHook=None, callHook=None,
memAccessHook=None, hookData=None, skipCalls=True, hookApis=True, count=0):
selection = idaapi.read_selection()
if selection[0]:
self.emulateRange(selection[1], selection[2], registers, stack, instructionHook,
callHook, memAccessHook, hookData, skipCalls, hookApis, count=count)
# target: finds first path through function to target using depth first
# search for each address in list, if a single address is specified,
# does so for each xref to target address
# emulates each target's function, forcing path to target, then
# runtime memory and string functions, defaults to True
# memAccessHook: hook function that runs when the emulator encounters a
# memory read or write
def iterate(self, target, targetCallback, preEmuCallback=None, callHook=None, instructionHook=None,
hookData=None, resetEmuMem=False, hookApis=True, memAccessHook=None):
if target is None:
return
targetInfo = {}
if type(target) in [int, long]:
logging.debug("iterate target function: %s" %
self.hexString(target))
xrefs = list(idautils.XrefsTo(target))
for i, x in enumerate(xrefs):
# get unique functions from xrefs that we need to emulate
funcStart = idc.get_func_attr(x.frm, idc.FUNCATTR_START)
if funcStart == idc.BADADDR:
continue
if idc.print_insn_mnem(x.frm) not in ["call", "jmp", "BL", "BLX", "B", "BLR"]:
continue
logging.debug("getting a path to %s, %d of %d" %
(self.hexString(x.frm), i + 1, len(xrefs)))
flow, paths = self.getPath(x.frm)
if flow is not None:
targetInfo[x.frm] = (flow, paths)
elif isinstance(target, list):
for i, t in enumerate(target):
logging.debug("getting a path to %s, %d of %d" %
(self.hexString(t), i + 1, len(target)))
flow, paths = self.getPath(t)
if flow is not None:
targetInfo[t] = (flow, paths)
if len(targetInfo) <= 0:
logging.debug("no targets to iterate")
return
userData = {}
userData["targetInfo"] = targetInfo
userData["targetCallback"] = targetCallback
userData["callHook"] = callHook
userData["EmuHelper"] = self
userData["hookApis"] = hookApis
if hookData:
userData.update(hookData)
self.internalRun = False
self.resetEmuHooks()
self.h_codehook = self.uc.hook_add(
unicorn.UC_HOOK_CODE, self._guidedHook, userData)
if instructionHook:
self.h_userhook = self.uc.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE, memAccessHook,
userData)
self.h_memhook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = self.uc.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
self.blockIdx = 0
cnt = 1
# read targets from dict to go from higher to lower addresses
# this is done to optimize loop by allowing hook to check for and remove other targets visited en route to
# current target
while len(userData["targetInfo"]) > 0:
userData["targetVA"] = targetVA = sorted(
userData["targetInfo"].keys(), reverse=True)[0]
flow, paths = userData["targetInfo"][targetVA]
funcStart = flow[0][0]
userData["func_t"] = idaapi.get_func(funcStart)
self.pathIdx = 0
numTargets = len(userData["targetInfo"])
logging.debug("run #%d, %d targets remaining: %s (%d paths)" % (
cnt, numTargets, self.hexString(targetVA), len(paths)))
cnt2 = 1
numPaths = len(paths)
for path in paths:
logging.debug("emulating path #%d of %d from %s to %s via basic blocks: %s" % (
cnt2, numPaths, self.hexString(funcStart), self.hexString(targetVA), repr(path)))
for reg in self.regs:
self.uc.reg_write(self.regs[reg], 0)
if resetEmuMem:
self.reloadBinary()
self.uc.reg_write(self.regs["sp"], self.stack)
self.enteredBlock = False
userData["visitedTargets"] = []
if preEmuCallback:
preEmuCallback(self, userData, funcStart)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
self.uc.emu_start(funcStart, idc.get_func_attr(
funcStart, idc.FUNCATTR_END))
self.pathIdx += 1
self.blockIdx = 0
cnt2 += 1
# remove visited targets during this run from our dict
for addr in userData["visitedTargets"]:
del(userData["targetInfo"][addr])
cnt += 1
# simply emulates to the end of whatever bytes are provided
# these bytes are not loaded into IDB, only emulator memory; IDA APIs are not available for use in hooks here
def emulateBytes(self, bytes, registers=None, stack=None, baseAddr=0x400000, instructionHook=None,
memAccessHook=None, hookData=None):
if registers is None:
registers = {}
if stack is None:
stack = []
userData = {}
if hookData:
userData.update(hookData)
baseAddr = self.loadBytes(bytes, baseAddr)
endAddr = baseAddr + len(bytes)
userData["endAddr"] = endAddr
mu = self.uc
self._prepEmuContext(registers, stack)
self.resetEmuHooks()
self.h_codehook = mu.hook_add(
unicorn.UC_HOOK_CODE, self._emulateBytesCodeHook, userData)
if instructionHook:
self.h_userhook = mu.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE, memAccessHook,
userData)
self.h_memhook = mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = mu.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
mu.emu_start(baseAddr, endAddr)
return mu
def hexString(self, va):
if va > 0xffffffff:
return "%016X" % va
else:
return "%08X" % va
def pageAlignUp(self, v):
if v & PAGEALIGNCHECK != 0:
v += PAGESIZE - (v % PAGESIZE)
return v
# returns string of bytes from the IDB up to a null terminator, starting at addr, do not necessarily need to be printable
# characters
def getIDBString(self, addr):
buf = ""
while idc.get_bytes(addr, 1, False) != "\x00" and idc.get_bytes(addr, 1, False) is not None:
buf += idc.get_bytes(addr, 1, False)
addr += 1
return buf
# determines if the instruction at addr is for returning from a function call
def isRetInstruction(self, addr):
if idc.print_insn_mnem(addr)[:3].lower() == "ret":
return True
if idc.print_insn_mnem(addr) in ["BX", "B"] and idc.print_operand(addr, 0) == "LR":
return True
return False
# call from an emulation hook to skip the current instruction, moving pc to next instruction
# useIDA option was added to handle cases where IDA folds multiple instructions
# do not call multiple times in a row, depends on userData being updated by hook
def skipInstruction(self, userData, useIDA=False):
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
if useIDA:
self.uc.reg_write(self.regs["pc"], idc.next_head(
userData["currAddr"], idc.get_inf_attr(idc.INF_MAX_EA)))
else:
self.uc.reg_write(
self.regs["pc"], userData["currAddr"] + userData["currAddrSize"])
# get IDA's SP delta value for next instruction to adjust stack accordingly since we are skipping
self.uc.reg_write(self.regs["sp"], self.getRegVal(
"sp") + idaapi.get_sp_delta(userData["func_t"], idc.next_head(
userData["currAddr"], idc.get_inf_attr(idc.INF_MAX_EA))))
def changeProgramCounter(self, userData, newPC):
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
self.uc.reg_write(self.regs["pc"], newPC)
def getRegVal(self, regName):
regVal = self.uc.reg_read(self.regs[regName])
if self.arch == unicorn.UC_ARCH_X86:
if regName[:-1] in ["l", "b"]:
regVal = regVal & 0xFF
elif regName[:-1] == "h":
regVal = (regVal & 0xFF00) >> 8
elif len(regName) == 2 and regName[:-1] == "x":
regVal = regVal & 0xFFFF
elif self.arch == unicorn.UC_ARCH_ARM64:
if regName[0] == "W":
regVal = regVal & 0xFFFFFFFF
return regVal
def stopEmulation(self, userData):
self.enteredBlock = False
if "visitedTargets" in userData and userData["targetVA"] not in userData["visitedTargets"]:
userData["visitedTargets"].append(
userData["targetVA"])
self.uc.emu_stop()
def resetEmuHooks(self):
if self.uc is None:
logging.debug(
"resetEmuHooks: no hooks to reset, emulator has not been initialized yet")
return
if self.h_userhook:
self.uc.hook_del(self.h_userhook)
self.h_userhook = None
if self.h_memaccesshook:
self.uc.hook_del(self.h_memaccesshook)
self.h_memaccesshook = None
if self.h_codehook:
self.uc.hook_del(self.h_codehook)
self.h_codehook = None
if self.h_memhook:
self.uc.hook_del(self.h_memhook)
self.h_memhook = None
if self.h_inthook:
self.uc.hook_del(self.h_inthook)
self.h_inthook = None
def getEmuState(self):
if self.arch == unicorn.UC_ARCH_X86:
if self.uc._mode == unicorn.UC_MODE_64:
out = "RAX: %016X\tRBX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RAX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RBX))
out += "RCX: %016X\tRDX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RCX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RDX))
out += "RDI: %016X\tRSI: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RDI), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RSI))
out += "R8: %016X\tR9: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_R8), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_R9))
out += "RBP: %016X\tRSP: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RBP), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RSP))
out += "RIP: %016X\n" % (self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RIP))
elif self.uc._mode == unicorn.UC_MODE_32:
out = "EAX: %016X\tEBX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EAX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EBX))
out += "ECX: %016X\tEDX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_ECX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EDX))
out += "EDI: %016X\tESI: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EDI), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_ESI))
out += "EBP: %016X\tESP: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EBP), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_ESP))
out += "EIP: %016X\n" % (self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EIP))
elif self.arch == unicorn.UC_ARCH_ARM64:
out = "X0: %016X\tX1: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X0), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X1))
out += "X2: %016X\tX3: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X2), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X3))
out += "X4: %016X\tX5: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X4), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X5))
out += "X6: %016X\tX7: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X6), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X7))
out += "X8: %016X\tX9: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X8), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X9))
out += "X10: %016X\tX11: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X10), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X11))
out += "X12: %016X\tX13: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X12), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X13))
out += "X14: %016X\tX15: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X14), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X15))
out += "X16: %016X\tX17: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X16), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X17))
out += "X18: %016X\tX19: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X18), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X19))
out += "X20: %016X\tX21: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X20), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X21))
out += "X22: %016X\tX23: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X22), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X23))
out += "X24: %016X\tX25: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X24), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X25))
out += "X26: %016X\tX27: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X26), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X27))
out += "X28: %016X\tX29: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X28), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X29))
out += "X30: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X30))
out += "PC: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_PC))
out += "SP: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_SP))
elif self.arch == unicorn.UC_ARCH_ARM:
out = "R0: %08X\tR1: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R0), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R1))
out += "R2: %08X\tR3: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R2), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R3))
out += "R4: %08X\tR5: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R4), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R5))
out += "R6: %08X\tR7: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R6), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R7))
out += "R8: %08X\tR9: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R8), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R9))
out += "R10: %08X\tR11: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R10), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R11))
out += "R12: %08X\tR13: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R12), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R13))
out += "R14: %08X\tR15: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R14), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R15))
out += "PC: %08X\n" % self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R15)
out += "SP: %08X\n" % self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R13)
else:
return ""
return out
# to be printable characters
def getEmuString(self, addr):
out = ""
while str(self.uc.mem_read(addr, 1)) != "\x00":
out += str(self.uc.mem_read(addr, 1))
addr += 1
return out
def getEmuWideString(self, addr):
out = ""
while str(self.uc.mem_read(addr, 2)) != "\x00\x00":
out += str(self.uc.mem_read(addr, 2))
addr += 2
return out
# returns a <size> string of bytes read from <addr>
def getEmuBytes(self, addr, size):
return str(self.uc.mem_read(addr, size))
# reads pointer value in emulator's memory
def getEmuPtr(self, va):
return struct.unpack(self.pack_fmt, self.uc.mem_read(va, self.size_pointer))[0]
def writeEmuPtr(self, va, value):
self.uc.mem_write(va, struct.pack(self.pack_fmt, value))
# for debugging
def formatBB(self, bb):
bbtype = {0: "fcb_normal", 1: "idaapi.fcb_indjump", 2: "idaapi.fcb_ret", 3: "fcb_cndret",
4: "idaapi.fcb_noret", 5: "fcb_enoret", 6: "idaapi.fcb_extern", 7: "fcb_error"}
return("ID: %d, Start: 0x%x, End: 0x%x, Last instruction: 0x%x, Size: %d, "
"Type: %s" % (bb.id, bb.start_ea, bb.end_ea, idc.idc.prev_head(bb.end_ea,
idc.get_inf_attr(idc.INF_MIN_EA)), (bb.end_ea - bb.start_ea), bbtype[bb.type]))
def getSegSize(self, ea, segEnd):
size = 0
while idc.has_value(idc.get_full_flags(ea)):
if ea >= segEnd:
break
size += 1
ea += 1
return size
# returns True if ea is in an area designated by IDA to be in thumb mode
def isThumbMode(self, ea):
return idc.get_sreg(ea, "T") == 1
def pageAlign(self, addr):
return addr & 0xfffffffffffff000
# get first path to target found during exploration
def getPath(self, targetVA):
function = idaapi.get_func(targetVA)
flowchart = idaapi.FlowChart(function)
target_bb = self.getBlockByVA(targetVA, flowchart)
start_bb = self.getStartBB(function, flowchart)
if target_bb.id != 0:
if self.verbose > 0:
logging.debug("exploring function with %d blocks" % flowchart.size)
graph = self._explore(start_bb, target_bb)
if graph is None:
logging.debug(
"graph for target %s could not be traversed, skipping" % self.hexString(targetVA))
return None, None
if self.verbose > 0:
logging.debug("graph for target:\n%s" % repr(graph))
path = [0]
if not self._findPathFromGraph(path, graph, 0, target_bb.id):
logging.debug(
"path for target %s could not be discovered, skipping" % self.hexString(targetVA))
return None, None
else:
path = [0]
if self.verbose > 0:
logging.debug("code path to target: %s" % repr(path))
# create my own idaapi.FlowChart object so it can be pickled for debugging purposes
flow = {}
for bb in flowchart:
flow[bb.id] = (bb.start_ea, bb.end_ea)
return flow, [path]
def getStartBB(self, function, flowchart):
for bb in flowchart:
if bb.start_ea == function.start_ea:
return bb
def getBlockIdByVA(self, targetVA, flowchart):
return self.getBlockByVA(targetVA, flowchart).id
def getBlockByVA(self, targetVA, flowchart):
for bb in flowchart:
if targetVA >= bb.start_ea and targetVA < bb.end_ea:
return bb
def getBlockById(self, id, flowchart):
for bb in flowchart:
if bb.id == id:
return bb
def isTerminatingBB(self, bb):
if (bb.type == idaapi.fcb_ret or bb.type == idaapi.fcb_noret or
(bb.type == idaapi.fcb_indjump and len(list(bb.succs())) == 0)):
return True
for b in bb.succs():
if b.type == idaapi.fcb_extern:
return True
return False
# sets up arch/mode specific variables, initializes emulator
def initEmuHelper(self):
info = idaapi.get_inf_structure()
if info.procName == "metapc":
self.arch = unicorn.UC_ARCH_X86
arch = "X86"
if info.is_64bit():
self.mode = unicorn.UC_MODE_64
self.derefPtr = idc.get_qword
mode = "64-bit"
self.size_pointer = 8
self.pack_fmt = "<Q"
self.pageMask = 0xfffffffffffff000
self.regs = {"ax": unicorn.x86_const.UC_X86_REG_RAX, "bx": unicorn.x86_const.UC_X86_REG_RBX,
"cx": unicorn.x86_const.UC_X86_REG_RCX, "dx": unicorn.x86_const.UC_X86_REG_RDX,
"di": unicorn.x86_const.UC_X86_REG_RDI, "si": unicorn.x86_const.UC_X86_REG_RSI,
"bp": unicorn.x86_const.UC_X86_REG_RBP, "sp": unicorn.x86_const.UC_X86_REG_RSP,
"ip": unicorn.x86_const.UC_X86_REG_RIP, "pc": unicorn.x86_const.UC_X86_REG_RIP,
"rax": unicorn.x86_const.UC_X86_REG_RAX, "rbx": unicorn.x86_const.UC_X86_REG_RBX,
"rcx": unicorn.x86_const.UC_X86_REG_RCX, "rdx": unicorn.x86_const.UC_X86_REG_RDX,
"rdi": unicorn.x86_const.UC_X86_REG_RDI, "rsi": unicorn.x86_const.UC_X86_REG_RSI,
"rbp": unicorn.x86_const.UC_X86_REG_RBP, "rsp": unicorn.x86_const.UC_X86_REG_RSP,
"r8": unicorn.x86_const.UC_X86_REG_R8, "r9": unicorn.x86_const.UC_X86_REG_R9,
"r10": unicorn.x86_const.UC_X86_REG_R10, "r11": unicorn.x86_const.UC_X86_REG_R11,
"r12": unicorn.x86_const.UC_X86_REG_R12, "r13": unicorn.x86_const.UC_X86_REG_R13,
"r14": unicorn.x86_const.UC_X86_REG_R14, "r15": unicorn.x86_const.UC_X86_REG_R15,
"ret": unicorn.x86_const.UC_X86_REG_RAX}
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk_win7"
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RCX,
"arg2": unicorn.x86_const.UC_X86_REG_RDX,
"arg3": unicorn.x86_const.UC_X86_REG_R8,
"arg4": unicorn.x86_const.UC_X86_REG_R9})
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx64"
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RDI,
"arg2": unicorn.x86_const.UC_X86_REG_RSI,
"arg3": unicorn.x86_const.UC_X86_REG_RDX,
"arg4": unicorn.x86_const.UC_X86_REG_RCX})
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x64"
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RDI,
"arg2": unicorn.x86_const.UC_X86_REG_RSI,
"arg3": unicorn.x86_const.UC_X86_REG_RDX,
"arg4": unicorn.x86_const.UC_X86_REG_RCX})
else:
self.filetype = "UNKNOWN"
# assume PE for mem dumps
self.regs.update({"arg1": unicorn.x86_const.UC_X86_REG_RCX,
"arg2": unicorn.x86_const.UC_X86_REG_RDX,
"arg3": unicorn.x86_const.UC_X86_REG_R8,
"arg4": unicorn.x86_const.UC_X86_REG_R9})
elif info.is_32bit():
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk"
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx"
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x86"
else:
self.filetype = "UNKNOWN"
self.mode = unicorn.UC_MODE_32
self.derefPtr = idc.get_wide_dword
mode = "32-bit"
self.size_pointer = 4
self.pack_fmt = "<I"
self.pageMask = 0xfffff000
self.regs = {"ax": unicorn.x86_const.UC_X86_REG_EAX, "bx": unicorn.x86_const.UC_X86_REG_EBX,
"cx": unicorn.x86_const.UC_X86_REG_ECX, "dx": unicorn.x86_const.UC_X86_REG_EDX,
"di": unicorn.x86_const.UC_X86_REG_EDI, "si": unicorn.x86_const.UC_X86_REG_ESI,
"bp": unicorn.x86_const.UC_X86_REG_EBP, "sp": unicorn.x86_const.UC_X86_REG_ESP,
"ip": unicorn.x86_const.UC_X86_REG_EIP, "pc": unicorn.x86_const.UC_X86_REG_EIP,
"eax": unicorn.x86_const.UC_X86_REG_EAX, "ebx": unicorn.x86_const.UC_X86_REG_EBX,
"ecx": unicorn.x86_const.UC_X86_REG_ECX, "edx": unicorn.x86_const.UC_X86_REG_EDX,
"edi": unicorn.x86_const.UC_X86_REG_EDI, "esi": unicorn.x86_const.UC_X86_REG_ESI,
"ebp": unicorn.x86_const.UC_X86_REG_EBP, "esp": unicorn.x86_const.UC_X86_REG_ESP,
"ret": unicorn.x86_const.UC_X86_REG_EAX}
else:
logging.debug(
"sample contains code for unsupported processor architecture")
return
elif info.procName == "ARM":
self.mode = unicorn.UC_MODE_ARM
mode = "ARM"
if info.is_64bit():
self.arch = unicorn.UC_ARCH_ARM64
arch = "ARM64"
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk_win7"
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx64"
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x64"
else:
self.filetype = "UNKNOWN"
self.size_pointer = 8
self.pack_fmt = "<Q"
self.derefPtr = idc.get_qword
self.pageMask = 0xfffffffffffff000
self.regs = {"R0": unicorn.arm64_const.UC_ARM64_REG_X0, "R1": unicorn.arm64_const.UC_ARM64_REG_X1,
"R2": unicorn.arm64_const.UC_ARM64_REG_X2, "R3": unicorn.arm64_const.UC_ARM64_REG_X3,
"R4": unicorn.arm64_const.UC_ARM64_REG_X4, "R5": unicorn.arm64_const.UC_ARM64_REG_X5,
"R6": unicorn.arm64_const.UC_ARM64_REG_X6, "R7": unicorn.arm64_const.UC_ARM64_REG_X7,
"R8": unicorn.arm64_const.UC_ARM64_REG_X8, "R9": unicorn.arm64_const.UC_ARM64_REG_X9,
"R10": unicorn.arm64_const.UC_ARM64_REG_X10, "R11": unicorn.arm64_const.UC_ARM64_REG_X11,
"R12": unicorn.arm64_const.UC_ARM64_REG_X12, "R13": unicorn.arm64_const.UC_ARM64_REG_X13,
"R14": unicorn.arm64_const.UC_ARM64_REG_X14, "R15": unicorn.arm64_const.UC_ARM64_REG_X15,
"X0": unicorn.arm64_const.UC_ARM64_REG_X0, "X1": unicorn.arm64_const.UC_ARM64_REG_X1,
"X2": unicorn.arm64_const.UC_ARM64_REG_X2, "X3": unicorn.arm64_const.UC_ARM64_REG_X3,
"X4": unicorn.arm64_const.UC_ARM64_REG_X4, "X5": unicorn.arm64_const.UC_ARM64_REG_X5,
"X6": unicorn.arm64_const.UC_ARM64_REG_X6, "X7": unicorn.arm64_const.UC_ARM64_REG_X7,
"X8": unicorn.arm64_const.UC_ARM64_REG_X8, "X9": unicorn.arm64_const.UC_ARM64_REG_X9,
"X10": unicorn.arm64_const.UC_ARM64_REG_X10, "X11": unicorn.arm64_const.UC_ARM64_REG_X11,
"X12": unicorn.arm64_const.UC_ARM64_REG_X12, "X13": unicorn.arm64_const.UC_ARM64_REG_X13,
"X14": unicorn.arm64_const.UC_ARM64_REG_X14, "X15": unicorn.arm64_const.UC_ARM64_REG_X15,
"X16": unicorn.arm64_const.UC_ARM64_REG_X16, "X17": unicorn.arm64_const.UC_ARM64_REG_X17,
"X18": unicorn.arm64_const.UC_ARM64_REG_X18, "X19": unicorn.arm64_const.UC_ARM64_REG_X19,
"X20": unicorn.arm64_const.UC_ARM64_REG_X20, "X21": unicorn.arm64_const.UC_ARM64_REG_X21,
"X22": unicorn.arm64_const.UC_ARM64_REG_X22, "X23": unicorn.arm64_const.UC_ARM64_REG_X23,
"X24": unicorn.arm64_const.UC_ARM64_REG_X24, "X25": unicorn.arm64_const.UC_ARM64_REG_X25,
"X26": unicorn.arm64_const.UC_ARM64_REG_X26, "X27": unicorn.arm64_const.UC_ARM64_REG_X27,
"X28": unicorn.arm64_const.UC_ARM64_REG_X28, "X29": unicorn.arm64_const.UC_ARM64_REG_X29,
"X30": unicorn.arm64_const.UC_ARM64_REG_X30, "W0": unicorn.arm64_const.UC_ARM64_REG_X0,
"W1": unicorn.arm64_const.UC_ARM64_REG_X1, "W2": unicorn.arm64_const.UC_ARM64_REG_X2,
"W3": unicorn.arm64_const.UC_ARM64_REG_X3, "W4": unicorn.arm64_const.UC_ARM64_REG_X4,
"W5": unicorn.arm64_const.UC_ARM64_REG_X5, "W6": unicorn.arm64_const.UC_ARM64_REG_X6,
"W7": unicorn.arm64_const.UC_ARM64_REG_X7, "W8": unicorn.arm64_const.UC_ARM64_REG_X8,
"W9": unicorn.arm64_const.UC_ARM64_REG_X9, "W10": unicorn.arm64_const.UC_ARM64_REG_X10,
"W11": unicorn.arm64_const.UC_ARM64_REG_X11, "W12": unicorn.arm64_const.UC_ARM64_REG_X12,
"W13": unicorn.arm64_const.UC_ARM64_REG_X13, "W14": unicorn.arm64_const.UC_ARM64_REG_X14,
"W15": unicorn.arm64_const.UC_ARM64_REG_X15, "W16": unicorn.arm64_const.UC_ARM64_REG_X16,
"W17": unicorn.arm64_const.UC_ARM64_REG_X17, "W18": unicorn.arm64_const.UC_ARM64_REG_X18,
"W19": unicorn.arm64_const.UC_ARM64_REG_X19, "W20": unicorn.arm64_const.UC_ARM64_REG_X20,
"W21": unicorn.arm64_const.UC_ARM64_REG_X21, "W22": unicorn.arm64_const.UC_ARM64_REG_X22,
"W23": unicorn.arm64_const.UC_ARM64_REG_X23, "W24": unicorn.arm64_const.UC_ARM64_REG_X24,
"W25": unicorn.arm64_const.UC_ARM64_REG_X25, "W26": unicorn.arm64_const.UC_ARM64_REG_X26,
"W27": unicorn.arm64_const.UC_ARM64_REG_X27, "W28": unicorn.arm64_const.UC_ARM64_REG_X28,
"W29": unicorn.arm64_const.UC_ARM64_REG_X29, "W30": unicorn.arm64_const.UC_ARM64_REG_X30,
"PC": unicorn.arm64_const.UC_ARM64_REG_PC, "pc": unicorn.arm64_const.UC_ARM64_REG_PC,
"LR": unicorn.arm64_const.UC_ARM64_REG_X30, "SP": unicorn.arm64_const.UC_ARM64_REG_SP,
"sp": unicorn.arm64_const.UC_ARM64_REG_SP, "ret": unicorn.arm64_const.UC_ARM64_REG_X0,
"S0": unicorn.arm64_const.UC_ARM64_REG_S0, "S1": unicorn.arm64_const.UC_ARM64_REG_S1,
"S2": unicorn.arm64_const.UC_ARM64_REG_S2, "S3": unicorn.arm64_const.UC_ARM64_REG_S3,
"S4": unicorn.arm64_const.UC_ARM64_REG_S4, "S5": unicorn.arm64_const.UC_ARM64_REG_S5,
"S6": unicorn.arm64_const.UC_ARM64_REG_S6, "S7": unicorn.arm64_const.UC_ARM64_REG_S7,
"S8": unicorn.arm64_const.UC_ARM64_REG_S8, "S9": unicorn.arm64_const.UC_ARM64_REG_S9,
"S10": unicorn.arm64_const.UC_ARM64_REG_S10, "S11": unicorn.arm64_const.UC_ARM64_REG_S11,
"S12": unicorn.arm64_const.UC_ARM64_REG_S12, "S13": unicorn.arm64_const.UC_ARM64_REG_S13,
"S14": unicorn.arm64_const.UC_ARM64_REG_S14, "S15": unicorn.arm64_const.UC_ARM64_REG_S15,
"S16": unicorn.arm64_const.UC_ARM64_REG_S16, "S17": unicorn.arm64_const.UC_ARM64_REG_S17,
"S18": unicorn.arm64_const.UC_ARM64_REG_S18, "S19": unicorn.arm64_const.UC_ARM64_REG_S19,
"S20": unicorn.arm64_const.UC_ARM64_REG_S20, "S21": unicorn.arm64_const.UC_ARM64_REG_S21,
"S22": unicorn.arm64_const.UC_ARM64_REG_S22, "S23": unicorn.arm64_const.UC_ARM64_REG_S23,
"S24": unicorn.arm64_const.UC_ARM64_REG_S24, "S25": unicorn.arm64_const.UC_ARM64_REG_S25,
"S26": unicorn.arm64_const.UC_ARM64_REG_S26, "S27": unicorn.arm64_const.UC_ARM64_REG_S27,
"S28": unicorn.arm64_const.UC_ARM64_REG_S28, "S29": unicorn.arm64_const.UC_ARM64_REG_S29,
"S30": unicorn.arm64_const.UC_ARM64_REG_S30, "S31": unicorn.arm64_const.UC_ARM64_REG_S31,
"D0": unicorn.arm64_const.UC_ARM64_REG_D0, "D1": unicorn.arm64_const.UC_ARM64_REG_D1,
"D2": unicorn.arm64_const.UC_ARM64_REG_D2, "D3": unicorn.arm64_const.UC_ARM64_REG_D3,
"D4": unicorn.arm64_const.UC_ARM64_REG_D4, "D5": unicorn.arm64_const.UC_ARM64_REG_D5,
"D6": unicorn.arm64_const.UC_ARM64_REG_D6, "D7": unicorn.arm64_const.UC_ARM64_REG_D7,
"D8": unicorn.arm64_const.UC_ARM64_REG_D8, "D9": unicorn.arm64_const.UC_ARM64_REG_D9,
"D10": unicorn.arm64_const.UC_ARM64_REG_D10, "D11": unicorn.arm64_const.UC_ARM64_REG_D11,
"D12": unicorn.arm64_const.UC_ARM64_REG_D12, "D13": unicorn.arm64_const.UC_ARM64_REG_D13,
"D14": unicorn.arm64_const.UC_ARM64_REG_D14, "D15": unicorn.arm64_const.UC_ARM64_REG_D15,
"D16": unicorn.arm64_const.UC_ARM64_REG_D16, "D17": unicorn.arm64_const.UC_ARM64_REG_D17,
"D18": unicorn.arm64_const.UC_ARM64_REG_D18, "D19": unicorn.arm64_const.UC_ARM64_REG_D19,
"D20": unicorn.arm64_const.UC_ARM64_REG_D20, "D21": unicorn.arm64_const.UC_ARM64_REG_D21,
"D22": unicorn.arm64_const.UC_ARM64_REG_D22, "D23": unicorn.arm64_const.UC_ARM64_REG_D23,
"D24": unicorn.arm64_const.UC_ARM64_REG_D24, "D25": unicorn.arm64_const.UC_ARM64_REG_D25,
"D26": unicorn.arm64_const.UC_ARM64_REG_D26, "D27": unicorn.arm64_const.UC_ARM64_REG_D27,
"D28": unicorn.arm64_const.UC_ARM64_REG_D28, "D29": unicorn.arm64_const.UC_ARM64_REG_D29,
"D30": unicorn.arm64_const.UC_ARM64_REG_D30, "D31": unicorn.arm64_const.UC_ARM64_REG_D31,
"H0": unicorn.arm64_const.UC_ARM64_REG_H0, "H1": unicorn.arm64_const.UC_ARM64_REG_H1,
"H2": unicorn.arm64_const.UC_ARM64_REG_H2, "H3": unicorn.arm64_const.UC_ARM64_REG_H3,
"H4": unicorn.arm64_const.UC_ARM64_REG_H4, "H5": unicorn.arm64_const.UC_ARM64_REG_H5,
"H6": unicorn.arm64_const.UC_ARM64_REG_H6, "H7": unicorn.arm64_const.UC_ARM64_REG_H7,
"H8": unicorn.arm64_const.UC_ARM64_REG_H8, "H9": unicorn.arm64_const.UC_ARM64_REG_H9,
"H10": unicorn.arm64_const.UC_ARM64_REG_H10, "H11": unicorn.arm64_const.UC_ARM64_REG_H11,
"H12": unicorn.arm64_const.UC_ARM64_REG_H12, "H13": unicorn.arm64_const.UC_ARM64_REG_H13,
"H14": unicorn.arm64_const.UC_ARM64_REG_H14, "H15": unicorn.arm64_const.UC_ARM64_REG_H15,
"H16": unicorn.arm64_const.UC_ARM64_REG_H16, "H17": unicorn.arm64_const.UC_ARM64_REG_H17,
"H18": unicorn.arm64_const.UC_ARM64_REG_H18, "H19": unicorn.arm64_const.UC_ARM64_REG_H19,
"H20": unicorn.arm64_const.UC_ARM64_REG_H20, "H21": unicorn.arm64_const.UC_ARM64_REG_H21,
"H22": unicorn.arm64_const.UC_ARM64_REG_H22, "H23": unicorn.arm64_const.UC_ARM64_REG_H23,
"H24": unicorn.arm64_const.UC_ARM64_REG_H24, "H25": unicorn.arm64_const.UC_ARM64_REG_H25,
"H26": unicorn.arm64_const.UC_ARM64_REG_H26, "H27": unicorn.arm64_const.UC_ARM64_REG_H27,
"H28": unicorn.arm64_const.UC_ARM64_REG_H28, "H29": unicorn.arm64_const.UC_ARM64_REG_H29,
"H30": unicorn.arm64_const.UC_ARM64_REG_H30, "H31": unicorn.arm64_const.UC_ARM64_REG_H31,
"Q0": unicorn.arm64_const.UC_ARM64_REG_Q0, "Q1": unicorn.arm64_const.UC_ARM64_REG_Q1,
"Q2": unicorn.arm64_const.UC_ARM64_REG_Q2, "Q3": unicorn.arm64_const.UC_ARM64_REG_Q3,
"Q4": unicorn.arm64_const.UC_ARM64_REG_Q4, "Q5": unicorn.arm64_const.UC_ARM64_REG_Q5,
"Q6": unicorn.arm64_const.UC_ARM64_REG_Q6, "Q7": unicorn.arm64_const.UC_ARM64_REG_Q7,
"Q8": unicorn.arm64_const.UC_ARM64_REG_Q8, "Q9": unicorn.arm64_const.UC_ARM64_REG_Q9,
"Q10": unicorn.arm64_const.UC_ARM64_REG_Q10, "Q11": unicorn.arm64_const.UC_ARM64_REG_Q11,
"Q12": unicorn.arm64_const.UC_ARM64_REG_Q12, "Q13": unicorn.arm64_const.UC_ARM64_REG_Q13,
"Q14": unicorn.arm64_const.UC_ARM64_REG_Q14, "Q15": unicorn.arm64_const.UC_ARM64_REG_Q15,
"Q16": unicorn.arm64_const.UC_ARM64_REG_Q16, "Q17": unicorn.arm64_const.UC_ARM64_REG_Q17,
"Q18": unicorn.arm64_const.UC_ARM64_REG_Q18, "Q19": unicorn.arm64_const.UC_ARM64_REG_Q19,
"Q20": unicorn.arm64_const.UC_ARM64_REG_Q20, "Q21": unicorn.arm64_const.UC_ARM64_REG_Q21,
"Q22": unicorn.arm64_const.UC_ARM64_REG_Q22, "Q23": unicorn.arm64_const.UC_ARM64_REG_Q23,
"Q24": unicorn.arm64_const.UC_ARM64_REG_Q24, "Q25": unicorn.arm64_const.UC_ARM64_REG_Q25,
"Q26": unicorn.arm64_const.UC_ARM64_REG_Q26, "Q27": unicorn.arm64_const.UC_ARM64_REG_Q27,
"Q28": unicorn.arm64_const.UC_ARM64_REG_Q28, "Q29": unicorn.arm64_const.UC_ARM64_REG_Q29,
"Q30": unicorn.arm64_const.UC_ARM64_REG_Q30, "Q31": unicorn.arm64_const.UC_ARM64_REG_Q31}
self.regs.update({"arg1": unicorn.arm64_const.UC_ARM64_REG_X0,
"arg2": unicorn.arm64_const.UC_ARM64_REG_X1,
"arg3": unicorn.arm64_const.UC_ARM64_REG_X2,
"arg4": unicorn.arm64_const.UC_ARM64_REG_X3})
elif info.is_32bit():
self.arch = unicorn.UC_ARCH_ARM
arch = "ARM"
if info.filetype == 11:
self.filetype = "PE"
self.tilName = "mssdk"
elif info.filetype == 25:
self.filetype = "MACHO"
self.tilName = "macosx"
elif info.filetype == 18:
self.filetype = "ELF"
self.tilName = "gnulnx_x86"
else:
self.filetype = "UNKNOWN"
self.size_pointer = 4
self.pack_fmt = "<I"
self.derefPtr = idc.get_wide_dword
self.pageMask = 0xfffff000
self.regs = {"R0": unicorn.arm_const.UC_ARM_REG_R0, "R1": unicorn.arm_const.UC_ARM_REG_R1,
"R2": unicorn.arm_const.UC_ARM_REG_R2, "R3": unicorn.arm_const.UC_ARM_REG_R3,
"R4": unicorn.arm_const.UC_ARM_REG_R4, "R5": unicorn.arm_const.UC_ARM_REG_R5,
"R6": unicorn.arm_const.UC_ARM_REG_R6, "R7": unicorn.arm_const.UC_ARM_REG_R7,
"R8": unicorn.arm_const.UC_ARM_REG_R8, "R9": unicorn.arm_const.UC_ARM_REG_R9,
"R10": unicorn.arm_const.UC_ARM_REG_R10, "R11": unicorn.arm_const.UC_ARM_REG_R11,
"R12": unicorn.arm_const.UC_ARM_REG_R12, "R13": unicorn.arm_const.UC_ARM_REG_R13,
"R14": unicorn.arm_const.UC_ARM_REG_R14, "R15": unicorn.arm_const.UC_ARM_REG_R15,
"PC": unicorn.arm_const.UC_ARM_REG_R15, "pc": unicorn.arm_const.UC_ARM_REG_R15,
"LR": unicorn.arm_const.UC_ARM_REG_R14, "SP": unicorn.arm_const.UC_ARM_REG_R13,
"sp": unicorn.arm_const.UC_ARM_REG_R13, "apsr": unicorn.arm_const.UC_ARM_REG_APSR,
"APSR": unicorn.arm_const.UC_ARM_REG_APSR, "ret": unicorn.arm_const.UC_ARM_REG_R0,
"S0": unicorn.arm_const.UC_ARM_REG_S0, "S1": unicorn.arm_const.UC_ARM_REG_S1,
"S2": unicorn.arm_const.UC_ARM_REG_S2, "S3": unicorn.arm_const.UC_ARM_REG_S3,
"S4": unicorn.arm_const.UC_ARM_REG_S4, "S5": unicorn.arm_const.UC_ARM_REG_S5,
"S6": unicorn.arm_const.UC_ARM_REG_S6, "S7": unicorn.arm_const.UC_ARM_REG_S7,
"S8": unicorn.arm_const.UC_ARM_REG_S8, "S9": unicorn.arm_const.UC_ARM_REG_S9,
"S10": unicorn.arm_const.UC_ARM_REG_S10, "S11": unicorn.arm_const.UC_ARM_REG_S11,
"S12": unicorn.arm_const.UC_ARM_REG_S12, "S13": unicorn.arm_const.UC_ARM_REG_S13,
"S14": unicorn.arm_const.UC_ARM_REG_S14, "S15": unicorn.arm_const.UC_ARM_REG_S15,
"S16": unicorn.arm_const.UC_ARM_REG_S16, "S17": unicorn.arm_const.UC_ARM_REG_S17,
"S18": unicorn.arm_const.UC_ARM_REG_S18, "S19": unicorn.arm_const.UC_ARM_REG_S19,
"S20": unicorn.arm_const.UC_ARM_REG_S20, "S21": unicorn.arm_const.UC_ARM_REG_S21,
"S22": unicorn.arm_const.UC_ARM_REG_S22, "S23": unicorn.arm_const.UC_ARM_REG_S23,
"S24": unicorn.arm_const.UC_ARM_REG_S24, "S25": unicorn.arm_const.UC_ARM_REG_S25,
"S26": unicorn.arm_const.UC_ARM_REG_S26, "S27": unicorn.arm_const.UC_ARM_REG_S27,
"S28": unicorn.arm_const.UC_ARM_REG_S28, "S29": unicorn.arm_const.UC_ARM_REG_S29,
"S30": unicorn.arm_const.UC_ARM_REG_S30, "S31": unicorn.arm_const.UC_ARM_REG_S31}
self.regs.update({"arg1": unicorn.arm_const.UC_ARM_REG_R0, "arg2": unicorn.arm_const.UC_ARM_REG_R1,
"arg3": unicorn.arm_const.UC_ARM_REG_R2, "arg4": unicorn.arm_const.UC_ARM_REG_R3})
else:
logging.debug(
"sample contains code for unsupported processor architecture")
return
else:
logging.debug(
"sample contains code for unsupported processor architecture")
return
# naive API hooks
self.apiHooks = {}
self.apiHooks["GetProcessHeap"] = self._returnHandleHook
self.apiHooks["HeapCreate"] = self._returnHandleHook
self.apiHooks["HeapAlloc"] = self._allocMem3Hook
self.apiHooks["HeapReAlloc"] = self._heapReAllocHook
self.apiHooks["RtlAllocateHeap"] = self._allocMem3Hook
self.apiHooks["AllocateHeap"] = self._allocMem1Hook
# ignore LMEM_MOVEABLE flag, return mem ptr anyway, have Lock return ptr param
self.apiHooks["LocalAlloc"] = self._allocMem2Hook
self.apiHooks["LocalLock"] = self._returnParam1Hook
self.apiHooks["GlobalAlloc"] = self._allocMem2Hook
self.apiHooks["GlobalLock"] = self._returnParam1Hook
# these ignore flags for now
self.apiHooks["LocalReAlloc"] = self._reallocHook
self.apiHooks["GlobalReAlloc"] = self._reallocHook
self.apiHooks["VirtualAlloc"] = self._virtualAllocHook
self.apiHooks["VirtualAllocEx"] = self._virtualAllocExHook
self.apiHooks["malloc"] = self._allocMem1Hook
self.apiHooks["calloc"] = self._callocHook
self.apiHooks["realloc"] = self._reallocHook
self.apiHooks["memcpy"] = self._memcpyHook
self.apiHooks["memmove"] = self._memcpyHook
self.apiHooks["strlen"] = self._strlenHook
self.apiHooks["lstrlenA"] = self._strlenHook
self.apiHooks["strnlen"] = self._strnlenHook
self.apiHooks["strnlen_s"] = self._strnlenHook
self.apiHooks["strcmp"] = self._strcmpHook
self.apiHooks["lstrcmpA"] = self._strcmpHook
self.apiHooks["strncmp"] = self._strncmpHook
self.apiHooks["stricmp"] = self._stricmpHook
self.apiHooks["lstrcmpiA"] = self._stricmpHook
self.apiHooks["strnicmp"] = self._strnicmpHook
self.apiHooks["wcscmp"] = self._wcscmpHook
self.apiHooks["lstrcmpW"] = self._wcscmpHook
self.apiHooks["wcsncmp"] = self._wcsncmpHook
self.apiHooks["wcsicmp"] = self._wcsicmpHook
self.apiHooks["lstrcmpiW"] = self._wcsicmpHook
self.apiHooks["wcsnicmp"] = self._wcsnicmpHook
self.apiHooks["mbscmp"] = self._strcmpHook
self.apiHooks["mbsncmp"] = self._strncmpHook
self.apiHooks["mbsicmp"] = self._stricmpHook
self.apiHooks["mbsnicmp"] = self._strnicmpHook
self.apiHooks["strcpy"] = self._strcpyHook
self.apiHooks["strncpy"] = self._strncpyHook
self.apiHooks["lstrcpyA"] = self._strcpyHook
self.apiHooks["lstrcpynA"] = self._strncpyHook
self.apiHooks["strncpy_s"] = self._strncpysHook
self.apiHooks["wcscpy"] = self._wcscpyHook
self.apiHooks["wcsncpy"] = self._wcsncpyHook
self.apiHooks["lstrcpyW"] = self._wcscpyHook
self.apiHooks["lstrcpynW"] = self._wcsncpyHook
self.apiHooks["wcsncpy_s"] = self._wcsncpysHook
self.apiHooks["mbscpy"] = self._strcpyHook
self.apiHooks["mbsncpy"] = self._strncpyHook
self.apiHooks["mbsncpy_s"] = self._strncpysHook
self.apiHooks["memchr"] = self._memchrHook
self.apiHooks["strchr"] = self._strchrHook
self.apiHooks["wcschr"] = self._wcschrHook
self.apiHooks["mbschr"] = self._strchrHook
self.apiHooks["strrchr"] = self._strrchrHook
self.apiHooks["wcsrchr"] = self._wcsrchrHook
self.apiHooks["mbsrchr"] = self._strrchrHook
self.apiHooks["wcslen"] = self._wcslenHook
self.apiHooks["lstrlenW"] = self._wcslenHook
self.apiHooks["mbslen"] = self._strlenHook
self.apiHooks["mbstrlen"] = self._strlenHook
self.apiHooks["wcsnlen"] = self._wcsnlenHook
self.apiHooks["wcsnlen_s"] = self._wcsnlenHook
self.apiHooks["mbsnlen"] = self._strnlenHook
self.apiHooks["mbstrnlen"] = self._strnlenHook
self.apiHooks["strcat"] = self._strcatHook
self.apiHooks["lstrcatA"] = self._strcatHook
self.apiHooks["strncat"] = self._strncatHook
self.apiHooks["wcscat"] = self._wcscatHook
self.apiHooks["lstrcatW"] = self._wcscatHook
self.apiHooks["wcsncat"] = self._wcsncatHook
self.apiHooks["mbscat"] = self._strcatHook
self.apiHooks["mbsncat"] = self._strncatHook
self.apiHooks["strlwr"] = self._strlwrHook
self.apiHooks["strupr"] = self._struprHook
self.apiHooks["wcslwr"] = self._wcslwrHook
self.apiHooks["wcsupr"] = self._wcsuprHook
self.apiHooks["mbslwr"] = self._strlwrHook
self.apiHooks["mbsupr"] = self._struprHook
self.apiHooks["strdup"] = self._strdupHook
self.apiHooks["wcsdup"] = self._wcsdupHook
self.apiHooks["mbsdup"] = self._strdupHook
self.apiHooks["mbtowc"] = self._mbtowcHook
self.apiHooks["mbstowcs"] = self._mbstowcsHook
self.apiHooks["wctomb"] = self._wctombHook
self.apiHooks["wcstombs"] = self._wcstombsHook
self.apiHooks["MultiByteToWideChar"] = self._multiByteToWideCharHook
self.apiHooks["WideCharToMultiByte"] = self._wideCharToMultiByteHook
self.apiHooks["memset"] = self._memsetHook
self.apiHooks["ZeroMemory"] = self._bzeroHook
self.apiHooks["bzero"] = self._bzeroHook
# builtins
self.apiHooks["umodsi3"] = self._modHook
self.allocMap = {}
# Initialize emulator
mu = unicorn.Uc(self.arch, self.mode)
logging.debug("initialized emulator for %s with %s architecture in %s mode" % (
self.filetype, arch, mode))
self.uc = mu
if self.arch == unicorn.UC_ARCH_ARM or self.arch == unicorn.UC_ARCH_ARM64:
self._enableVFP()
# unmap all emulator memory
def resetEmulatorMemory(self):
for region in self.uc.mem_regions():
self.uc.mem_unmap(region[0], region[1] - region[0] + 1)
def resetEmulatorHeapAndStack(self):
for region in self.uc.mem_regions():
if region[0] != self.baseAddr:
self.uc.mem_unmap(region[0], region[1] - region[0] + 1)
logging.debug("unmapped %s to %s" % (
self.hexString(region[0]), self.hexString(region[1])))
self._buildStack()
# reset emulator memory and rewrite binary segments to emulator memory, build new stack
def reloadBinary(self):
self.resetEmulatorMemory()
baseAddr = idc.get_inf_attr(idc.INF_MIN_EA)
endAddr = idc.get_inf_attr(idc.INF_MAX_EA)
self.baseAddr = baseAddr
memsize = endAddr - baseAddr
memsize = self.pageAlignUp(memsize)
# map all binary segments as one memory region for easier management
self.uc.mem_map(baseAddr & self.pageMask, memsize)
for segVA in idautils.Segments():
segName = idc.get_segm_name(segVA)
endVA = idc.get_segm_end(segVA)
segSizeTotal = endVA - segVA
segSize = self.getSegSize(segVA, endVA)
logging.debug("bytes in seg: %s" % self.hexString(segSize))
logging.debug("mapping segment %s: %s - %s" %
(segName, self.hexString(segVA), self.hexString(endVA)))
if segSize > 0:
segBytes = idc.get_bytes(segVA, segSize, False)
self.uc.mem_write(segVA, segBytes)
segLeftover = segSizeTotal - segSize
if segLeftover > 0:
self.uc.mem_write(segVA + segSize, "\x00" * segLeftover)
self._buildStack()
# allocs mem and writes bytes into it
def loadBytes(self, bytes, addr=None):
mem = self.allocEmuMem(len(bytes), addr)
self.uc.mem_write(mem, bytes)
return mem
def isValidEmuPtr(self, ptr):
for region in self.uc.mem_regions():
if ptr >= region[0] and ptr < region[1]:
return True
return False
def getEmuMemRegion(self, addr):
for region in self.uc.mem_regions():
if addr >= region[0] and addr < region[1]:
return (region[0], region[1] + 1)
return None
# allocate emulator memory, attempts to honor specified address, otherwise begins allocations
# at the next page
# aligned address above the highest, returns address, rebased if necessary
def allocEmuMem(self, size, addr=None):
allocSize = self.pageAlignUp(size)
if addr is None:
baseAddr = addr = self._findUnusedMemRegion()
else:
isValid = True
baseAddr = self.pageAlign(addr)
offs = addr - baseAddr
for region in self.uc.mem_regions():
# if start or end of region falls in range of a previous region
if ((baseAddr >= region[0] and baseAddr < region[1]) or
(baseAddr + allocSize >= region[0] and baseAddr + allocSize < region[1])):
isValid = False
break
# if region completely envelopes a previous region
if baseAddr < region[0] and baseAddr + allocSize > region[1]:
isValid = False
break
if isValid is False:
baseAddr = self._findUnusedMemRegion()
addr = baseAddr + offs
logging.debug("mapping %s bytes @%s" %
(self.hexString(allocSize), self.hexString(baseAddr)))
self.uc.mem_map(baseAddr, allocSize)
return addr
def copyEmuMem(self, dstAddr, srcAddr, size, userData):
size = self._checkMemSize(size, userData)
try:
mem = str(self.uc.mem_read(srcAddr, size))
self.uc.mem_write(dstAddr, mem)
except Exception as e:
logging.debug("exception in copyEmuMem @%s: %s" % (self.hexString(address), str(e)))
def getCallTargetName(self, address):
if idc.get_operand_type(address, 0) == 1:
funcName = idc.get_name(self.uc.reg_read(
self.regs[idc.print_operand(address, 0)]), idc.ida_name.GN_VISIBLE)
# elif idc.get_operand_type(address, 0) == 2:
# funcName = idc.get_name(self.getEmuPtr(idc.get_operand_value(address, 0)),
# idc.ida_name.GN_VISIBLE)
else:
funcName = idc.get_name(idc.get_operand_value(address, 0), idc.ida_name.GN_VISIBLE)
return funcName
# we don't know the number of args to a given function and we're not considering SSE args
# this is just a convenience, use the emulator object if you have specific needs
def getArgv(self):
if self.arch == unicorn.UC_ARCH_X86:
if self.mode == unicorn.UC_MODE_64:
if self.filetype == "MACHO" or self.filetype == "ELF":
argv = [
self.getRegVal("rdi"),
self.getRegVal("rsi"),
self.getRegVal("rdx"),
self.getRegVal("rcx"),
self.getRegVal("r8"),
self.getRegVal("r9")]
else:
argv = [
self.getRegVal("rcx"),
self.getRegVal("rdx"),
self.getRegVal("r8"),
self.getRegVal("r9")]
else:
sp = self.getRegVal("esp")
argv = [
struct.unpack("<I", str(self.uc.mem_read(sp, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 4, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 8, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 12, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 16, 4)))[0],
struct.unpack("<I", str(self.uc.mem_read(sp + 20, 4)))[0]]
elif self.arch == unicorn.UC_ARCH_ARM:
argv = [
self.getRegVal("R0"),
self.getRegVal("R1"),
self.getRegVal("R2"),
self.getRegVal("R3")]
elif self.arch == unicorn.UC_ARCH_ARM64:
argv = [
self.getRegVal("X0"),
self.getRegVal("X1"),
self.getRegVal("X2"),
self.getRegVal("X3"),
self.getRegVal("X4"),
self.getRegVal("X5"),
self.getRegVal("X6"),
self.getRegVal("X7")]
else:
argv = None
return argv
def _checkMemSize(self, size, userData):
if size > MAX_ALLOC_SIZE:
logging.debug("allocation size (%s) truncated @%s" %
(self.hexString(size), self.hexString(userData["currAddr"])))
size = MAX_ALLOC_SIZE
return size
############################################
# BEGIN API HOOKS
############################################
# return a fake handle value
def _returnHandleHook(self, address, argv, funcName, userData):
self.uc.reg_write(self.regs["ret"], 42)
def _returnParam1Hook(self, address, argv, funcName, userData):
self.uc.reg_write(self.regs["ret"], argv[0])
def _allocMem1Hook(self, address, argv, funcName, userData):
allocSize = argv[0]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
def _allocMem2Hook(self, address, argv, funcName, userData):
allocSize = argv[1]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
def _allocMem3Hook(self, address, argv, funcName, userData):
allocSize = argv[2]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
def _callocHook(self, address, argv, funcName, userData):
allocSize = argv[0] * argv[1]
allocSize = self._checkMemSize(allocSize, userData)
self.uc.reg_write(self.regs["ret"], self.allocEmuMem(allocSize))
# deny "in place only" flag
def _heapReAllocHook(self, address, argv, funcName, userData):
HEAP_REALLOC_IN_PLACE_ONLY = 0x10
if argv[1] & HEAP_REALLOC_IN_PLACE_ONLY:
self.uc.reg_write(self.regs["ret"], 0)
else:
allocSize = argv[3]
allocSize = self._checkMemSize(allocSize, userData)
region = self.getEmuMemRegion(argv[2])
if region is not None:
allocSize = max(region[1] - region[0], allocSize)
memAddr = self.allocEmuMem(allocSize)
self.copyEmuMem(memAddr, region[0], region[1] - region[0], userData)
else:
memAddr = self.allocEmuMem(allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
def _reallocHook(self, address, argv, funcName, userData):
allocSize = argv[1]
allocSize = self._checkMemSize(allocSize, userData)
region = self.getEmuMemRegion(argv[0])
if region is not None:
allocSize = max(region[1] - region[0], allocSize)
memAddr = self.allocEmuMem(allocSize)
self.copyEmuMem(memAddr, region[0], region[1] - region[0], userData)
else:
memAddr = self.allocEmuMem(allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
# allocate regardless of commit flag, keep a mapping of requested addr -> actual addr
def _virtualAllocHook(self, address, argv, funcName, userData):
allocAddr = argv[0]
if allocAddr in self.allocMap:
self.uc.reg_write(self.regs["ret"], self.allocMap[allocAddr][0])
return
allocSize = argv[1]
allocSize = self._checkMemSize(allocSize, userData)
memAddr = self.allocEmuMem(allocSize, allocAddr)
self.allocMap[allocAddr] = (memAddr, allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
# handle same as VirtualAlloc hook, just with different argument placement
def _virtualAllocExHook(self, address, argv, funcName, userData):
allocAddr = argv[1]
if allocAddr in self.allocMap:
self.uc.reg_write(self.regs["ret"], self.allocMap[allocAddr][0])
return
allocSize = argv[2]
allocSize = self._checkMemSize(allocSize, userData)
memAddr = self.allocEmuMem(allocSize, allocAddr)
self.allocMap[allocAddr] = (memAddr, allocSize)
self.uc.reg_write(self.regs["ret"], memAddr)
def _memcpyHook(self, address, argv, funcName, userData):
copySize = argv[2]
copySize = self._checkMemSize(copySize, userData)
srcRegion = self.getEmuMemRegion(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for memcpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(copySize))
argv[0] = dstRegion[0]
if srcRegion is None:
logging.debug("source memory does not exist for memcpy @%s" % self.hexString(address))
else:
if copySize <= srcRegion[1] - argv[1] and copySize <= dstRegion[1] - argv[0]:
self.copyEmuMem(argv[0], argv[1], copySize, userData)
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], argv[0])
def _strlenHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
self.uc.reg_write(self.regs["ret"], len(self.getEmuString(argv[0])))
else:
self.uc.reg_write(self.regs["ret"], 0)
def _wcslenHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
self.uc.reg_write(self.regs["ret"], len(self.getEmuWideString(argv[0]).decode("utf-16")))
else:
self.uc.reg_write(self.regs["ret"], 0)
def _strnlenHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[1], userData)
if self.isValidEmuPtr(argv[0]):
strlen = len(self.getEmuString(argv[0]))
strlen = min(strlen, strnlen)
self.uc.reg_write(self.regs["ret"], strlen)
else:
self.uc.reg_write(self.regs["ret"], 0)
def _wcsnlenHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[1], userData)
if self.isValidEmuPtr(argv[0]):
strlen = len(self.getEmuWideString(argv[0]).decode("utf-16"))
if strlen > strnlen:
strlen = argv[1]
self.uc.reg_write(self.regs["ret"], strnlen)
else:
self.uc.reg_write(self.regs["ret"], 0)
def _strcmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1 == str2:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strncmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1[:strnlen] == str2[:strnlen]:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _stricmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1.lower() == str2.lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strnicmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuString(argv[1])
str2 = self.getEmuString(argv[0])
if str1[:strnlen].lower() == str2[:strnlen].lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcscmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1 == str2:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsncmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1[:strnlen] == str2[:strnlen]:
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsicmpHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1.lower() == str2.lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsnicmpHook(self, address, argv, funcName, userData):
strnlen = self._checkMemSize(argv[2], userData)
if self.isValidEmuPtr(argv[0]) and self.isValidEmuPtr(argv[1]):
str1 = self.getEmuWideString(argv[1]).decode("utf-16")
str2 = self.getEmuWideString(argv[0]).decode("utf-16")
if str1[:strnlen].lower() == str2[:strnlen].lower():
self.uc.reg_write(self.regs["ret"], 0)
return
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strcpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuString(argv[1]) + "\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strcpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src)))
argv[0] = dstRegion[0]
if len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strncpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2], userData)
src = self.getEmuString(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strncpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
if strnlen <= dstRegion[1] - argv[0]:
if strnlen > len(src):
src = src.ljust(strnlen, "\x00")
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _strncpysHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
strnlen = self._checkMemSize(argv[3], userData)
src = self.getEmuString(argv[2])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strncpy_s @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
strnlen = min(strnlen, len(src))
if strnlen + 1 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src + "\x00")
self.uc.reg_write(self.regs["ret"], 0)
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcscpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuWideString(argv[1]) + "\x00\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcscpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src)))
argv[0] = dstRegion[0]
if len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsncpyHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2] * 2, userData)
src = self.getEmuWideString(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcsncpy @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
if strnlen <= dstRegion[1] - argv[0]:
if strnlen > len(src):
src = src.ljust(strnlen, "\x00")
self.uc.mem_write(argv[0], src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _wcsncpysHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
strnlen = self._checkMemSize(argv[3] * 2, userData)
src = self.getEmuWideString(argv[2])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcsncpy_s @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen))
argv[0] = dstRegion[0]
strnlen = min(strnlen, len(src))
if strnlen + 2 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src[:strnlen] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], 0)
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
if self.size_pointer == 8:
val = 0xffffffffffffffff
else:
val = 0xffffffff
self.uc.reg_write(self.regs["ret"], val)
def _memchrHook(self, address, argv, funcName, userData):
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is not None:
srch = chr(argv[1] & 0xFF)
srchlen = argv[2]
# truncate search to end of region
if argv[0] + srchlen > dstRegion[1]:
srchlen = dstRegion[1] - argv[0]
buf = str(self.uc.mem_read(argv[0], srchlen))
offs = buf.find(srch)
if offs > -1:
self.uc.reg_write(self.regs["ret"], argv[0] + offs)
return
self.uc.reg_write(self.regs["ret"], 0)
def _mbstowcsHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
bufSize = self._checkMemSize(argv[2] * 2, userData)
src = self.getEmuString(argv[1])
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(bufSize))
argv[0] = dstRegion[0]
if argv[2] > len(src):
src = src.ljust(argv[2], "\x00")
else:
src += "\x00"
if len(src.encode("utf-16")[2:]) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src.encode("utf-16")[2:])
self.uc.reg_write(self.regs["ret"], len(src))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _mbtowcHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuString(argv[1])[0]
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(0x1000))
argv[0] = dstRegion[0]
self.uc.mem_write(argv[0], src.encode("utf-16")[2:4])
self.uc.reg_write(self.regs["ret"], 1)
return
self.uc.reg_write(self.regs["ret"], 0)
def _mbstowcsHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
maxBufSize = self._checkMemSize(argv[2] * 2, userData)
src = self.getEmuString(argv[1])
if len(src) < argv[2]:
src += "\x00"
else:
src = src[:argv[2]]
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(maxBufSize))
argv[0] = dstRegion[0]
if len(src) * 2 + 2 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src.encode("utf-16")[2:] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], len(src.replace("\x00", "")))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _wctombHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuWideString(argv[1]).decode("utf-16")
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wctomb variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(0x1000))
argv[0] = dstRegion[0]
self.uc.mem_write(argv[0], src[0])
self.uc.reg_write(self.regs["ret"], 1)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcstombsHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
bufSize = self._checkMemSize(argv[2], userData)
src = self.getEmuWideString(argv[1]).decode("utf-16")
if len(src) < argv[2]:
src += "\x00"
else:
src = src[:argv[2]]
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wctomb variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(bufSize))
argv[0] = dstRegion[0]
if bufSize + 1 <= dstRegion[1] - argv[0]:
if bufSize > len(src):
src = src.ljust(bufSize, "\x00")
self.uc.mem_write(argv[0], src + "\x00")
self.uc.reg_write(self.regs["ret"], len(src.replace("\x00", "")))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _multiByteToWideCharHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
src = self.getEmuString(argv[2])
if argv[3] == -1:
src += "\x00"
maxBufSize = self._checkMemSize(len(src) * 2, userData)
else:
maxBufSize = self._checkMemSize(argv[3] * 2, userData)
if len(src) < argv[3]:
src += "\x00"
elif argv[3] != -1:
src = src[:argv[3]]
if argv[5] == 0:
self.uc.reg_write(self.regs["ret"], len(src) * 2)
return
dstRegion = self.getEmuMemRegion(argv[4])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(maxBufSize))
argv[4] = dstRegion[0]
if len(src) * 2 + 2 <= dstRegion[1] - argv[4]:
self.uc.mem_write(argv[4], src.encode("utf-16")[2:] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], len(src))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _wideCharToMultiByteHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[2]):
src = self.getEmuWideString(argv[2]).decode("utf-16")
if argv[3] == -1:
src += "\x00"
maxBufSize = self._checkMemSize(len(src), userData)
else:
maxBufSize = self._checkMemSize(argv[3], userData)
if len(src) < argv[3]:
src += "\x00"
elif argv[3] != -1:
src = src[:argv[3]]
if argv[5] == 0:
self.uc.reg_write(self.regs["ret"], len(src))
return
dstRegion = self.getEmuMemRegion(argv[4])
if dstRegion is None:
logging.debug("dest memory does not exist for mbtowc variant @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(maxBufSize))
argv[4] = dstRegion[0]
if len(src) + 1 <= dstRegion[1] - argv[4]:
self.uc.mem_write(argv[4], src + "\x00")
self.uc.reg_write(self.regs["ret"], len(src))
return
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], 0)
def _memsetHook(self, address, argv, funcName, userData):
setSize = argv[2]
setSize = self._checkMemSize(setSize, userData)
dstRegion = self.getEmuMemRegion(argv[0])
src = chr(argv[1] & 0xFF)
if dstRegion is None:
logging.debug("dest memory does not exist for memset @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(setSize))
argv[0] = dstRegion[0]
if setSize <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src * setSize)
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], argv[0])
def _bzeroHook(self, address, argv, funcName, userData):
setSize = argv[1]
setSize = self._checkMemSize(setSize, userData)
dstRegion = self.getEmuMemRegion(argv[0])
src = "\x00"
if dstRegion is None:
logging.debug("dest memory does not exist for memset @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(setSize))
argv[0] = dstRegion[0]
if setSize <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], src * setSize)
else:
logging.debug("dest memory not large enough @%s" % self.hexString(address))
self.uc.reg_write(self.regs["ret"], argv[0])
def _strcatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuString(argv[1]) + "\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strcat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src) + 1))
argv[0] = dstRegion[0]
dst = self.getEmuString(argv[0])
if len(dst) + len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _strncatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2], userData)
src = self.getEmuString(argv[1])
strnlen = min(strnlen, len(src))
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for strncat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen + 1))
argv[0] = dstRegion[0]
dst = self.getEmuString(argv[0])
if len(dst) + strnlen + 1 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src[:strnlen] + "\x00")
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcscatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
src = self.getEmuWideString(argv[1]) + "\x00\x00"
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcscat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(len(src)))
argv[0] = dstRegion[0]
dst = self.getEmuWideString(argv[0])
if len(dst) + len(src) <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src)
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsncatHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[1]):
strnlen = self._checkMemSize(argv[2], userData)
src = self.getEmuWideString(argv[1])
strnlen = min(strnlen * 2, len(src))
dstRegion = self.getEmuMemRegion(argv[0])
if dstRegion is None:
logging.debug("dest memory does not exist for wcsncat @%s" % self.hexString(address))
dstRegion = self.getEmuMemRegion(self.allocEmuMem(strnlen + 2))
argv[0] = dstRegion[0]
dst = self.getEmuWideString(argv[0])
if len(dst) + strnlen + 2 <= dstRegion[1] - argv[0]:
self.uc.mem_write(argv[0], dst + src[:strnlen] + "\x00\x00")
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _strchrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
idx = s.find(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcschrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
idx = s.find(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx * 2)
return
self.uc.reg_write(self.regs["ret"], 0)
def _strrchrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
idx = s.rfind(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsrchrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
idx = s.rfind(chr(argv[1] & 0xFF))
if idx != -1:
self.uc.reg_write(self.regs["ret"], argv[0] + idx * 2)
return
self.uc.reg_write(self.regs["ret"], 0)
def _strlwrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
self.uc.mem_write(argv[0], s.lower())
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _struprHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
self.uc.mem_write(argv[0], s.upper())
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcslwrHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
self.uc.mem_write(argv[0], s.lower().encode("utf-16")[2:])
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsuprHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0]).decode("utf-16")
self.uc.mem_write(argv[0], s.upper().encode("utf-16")[2:])
self.uc.reg_write(self.regs["ret"], argv[0])
return
self.uc.reg_write(self.regs["ret"], 0)
def _strdupHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuString(argv[0])
memAddr = self.allocEmuMem(len(s) + 1)
self.uc.mem_write(memAddr, s)
self.uc.reg_write(self.regs["ret"], memAddr)
return
self.uc.reg_write(self.regs["ret"], 0)
def _wcsdupHook(self, address, argv, funcName, userData):
if self.isValidEmuPtr(argv[0]):
s = self.getEmuWideString(argv[0])
memAddr = self.allocEmuMem(len(s) + 2)
self.uc.mem_write(memAddr, s)
self.uc.reg_write(self.regs["ret"], memAddr)
return
self.uc.reg_write(self.regs["ret"], 0)
def _modHook(self, address, argv, funcName, userData):
self.uc.reg_write(self.regs["ret"], argv[0] % argv[1])
############################################
# END API HOOKS
############################################
# maps null memory as requested during emulation
def _hookMemInvalid(self, uc, access, address, size, value, userData):
logging.debug("invalid memory operation for %s @%s" %
(self.hexString(address), self.hexString(userData['currAddr'])))
try:
uc.mem_map(address & self.pageMask, PAGESIZE)
uc.mem_write(address & self.pageMask, "\x00" * PAGESIZE)
except Exception:
logging.debug("error writing to %s, changing IP from %s to %s" % (self.hexString(address), self.hexString(
userData['currAddr']), self.hexString(userData['currAddr'] + userData['currAddrSize'])))
uc.reg_write(
self.regs["pc"], userData['currAddr'] + userData['currAddrSize'])
return True
# cannot seem to move IP forward from this hook for some reason..
# patches current instruction with NOPs
def _hookInterrupt(self, uc, intno, userData):
logging.debug("interrupt #%d received @%s" % ((intno), self.hexString(userData["currAddr"])))
if self.arch == unicorn.UC_ARCH_X86:
uc.mem_write(userData["currAddr"], X86NOP *
userData["currAddrSize"])
elif self.arch == unicorn.UC_ARCH_ARM:
if self.mode == unicorn.UC_MODE_THUMB:
uc.mem_write(userData["currAddr"],
ARMTHUMBNOP * (userData["currAddrSize"] / 2))
else:
uc.mem_write(
userData["currAddr"], ARMNOP * (userData["currAddrSize"] / 4))
elif self.arch == unicorn.UC_ARCH_ARM64:
uc.mem_write(
userData["currAddr"], ARM64NOP * (userData["currAddrSize"] / 4))
self.enteredBlock = False
return True
# handle common runtime functions
def _handleApiHooks(self, address, argv, funcName, userData):
# normalize funcName
# remove appended _n from IDA Pro names
funcName = re.sub(r"_[\d]+$", "", funcName)
# remove appended _l for locale flavors of string functions
funcName = re.sub(r"_l$", "", funcName)
# remove IDA Pro's j_ prefix
if funcName[:2] == "j_":
funcName = funcName[2:]
funcName = re.sub(r"^_+", "", funcName)
if funcName not in self.apiHooks:
return False
try:
self.apiHooks[funcName](address, argv, funcName, userData)
except Exception as e:
logging.debug("error handling API hook: %s @%s" % (e, self.hexString(address)))
self.skipInstruction(userData)
return True
def _emulateRangeCodeHook(self, uc, address, size, userData):
try:
userData['currAddr'] = address
userData['currAddrSize'] = size
if self.arch == unicorn.UC_ARCH_ARM and userData["changeThumbMode"]:
self._handleThumbMode(address)
userData["changeThumbMode"] = False
return
if self.verbose > 0:
if self.verbose > 1:
logging.debug(self.getEmuState())
dis = idc.generate_disasm_line(address, 0)
logging.debug("%s: %s" % (self.hexString(address), dis))
if userData["endAddr"] is not None:
if address == userData["endAddr"]:
self.stopEmulation(userData)
return
if self._isBadBranch(userData):
self.skipInstruction(userData)
return
if str(self.uc.mem_read(address, size)) == "\x00" * size:
logging.debug("pc ended up in null memory @%s" %
self.hexString(address))
self.stopEmulation(userData)
return
elif (self.isRetInstruction(address) and
idc.get_func_attr(address, idc.FUNCATTR_START) ==
userData["funcStart"]):
self.stopEmulation(userData)
return
elif self.isRetInstruction(address) and self.arch == unicorn.UC_ARCH_ARM:
retAddr = self.getEmuPtr(self.getRegVal("LR"))
if self.isThumbMode(retAddr):
userData["changeThumbMode"] = True
if (idc.print_insn_mnem(address) in self.callMnems or
(idc.print_insn_mnem(address) == "B" and
idc.get_name_ea_simple(idc.print_operand(address, 0)) ==
idc.get_func_attr(
idc.get_name_ea_simple(idc.print_operand(address, 0)),
idc.FUNCATTR_START))):
funcName = self.getCallTargetName(address)
if userData["callHook"]:
userData["callHook"](address, self.getArgv(), funcName, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
if self.getRegVal("pc") != userData["currAddr"]:
# get IDA's SP delta value for next instruction to adjust stack accordingly since we are skipping this
uc.reg_write(self.regs["sp"], self.getRegVal("sp") +
idaapi.get_sp_delta(userData["func_t"], self.getRegVal("pc")))
return
if userData["hookApis"] and self._handleApiHooks(address, self.getArgv(), funcName, userData):
return
if (userData["skipCalls"] is True or
(idc.get_operand_type(address, 0) == 7 and
str(uc.mem_read(idc.get_operand_value(address, 0), self.size_pointer)) ==
"\x00" * self.size_pointer)):
self.skipInstruction(userData)
elif (idc.print_insn_mnem(address) == "mov" and
idc.get_operand_type(address, 1) == 2 and
idc.get_operand_type(address, 0) == 1 and
idc.print_operand(address, 1)[:3] == "ds:" and
str(uc.mem_read(idc.get_operand_value(address, 1), self.size_pointer)) ==
"\x00" * self.size_pointer):
uc.reg_write(self.regs[idc.print_operand(address, 0)], idc.get_operand_value(address, 1))
self.skipInstruction(userData)
except Exception as err:
logging.debug("exception in emulateRange_codehook @%s: %s" % (self.hexString(address), str(err)))
print("exception in emulateRange_codehook @%s: %s" % (self.hexString(address), str(err)))
self.stopEmulation(userData)
def _emulateBytesCodeHook(self, uc, address, size, userData):
try:
userData['currAddr'] = address
userData['currAddrSize'] = size
if userData["endAddr"] is not None:
if address == userData["endAddr"]:
self.stopEmulation(userData)
return
if str(self.uc.mem_read(address, 0x10)) == "\x00" * 0x10:
self.stopEmulation(userData)
logging.debug("pc ended up in null memory @%s" %
self.hexString(address))
return
except Exception as err:
logging.debug("exception in emulateBytes_codehook @%s: %s" % (self.hexString(address), str(err)))
print("exception in emulateBytes_codehook @%s: %s" % (self.hexString(address), str(err)))
self.stopEmulation(userData)
def _guidedHook(self, uc, address, size, userData):
try:
userData['currAddr'] = address
userData['currAddrSize'] = size
if self.arch == unicorn.UC_ARCH_ARM and userData["changeThumbMode"]:
self._handleThumbMode(address)
userData["changeThumbMode"] = False
return
if self.verbose > 0:
if self.verbose > 1:
logging.debug(self.getEmuState())
dis = idc.generate_disasm_line(address, 0)
logging.debug("%s: %s" % (self.hexString(address), dis))
if self.arch == unicorn.UC_ARCH_ARM:
if idc.print_insn_mnem(address)[:3] in ["TBB", "TBH"]:
nextInsnAddr = self._scanForCode(address + size)
self.changeProgramCounter(userData, nextInsnAddr)
return
elif self._isBadBranch(userData):
self.skipInstruction(userData)
return
flow, paths = userData["targetInfo"][userData["targetVA"]]
bbEnd = idc.prev_head(
flow[paths[self.pathIdx][self.blockIdx]][1], idc.get_inf_attr(idc.INF_MIN_EA))
bbStart = flow[paths[self.pathIdx][self.blockIdx]][0]
if address == bbStart and self.enteredBlock is True:
if self.blockIdx < len(paths[self.pathIdx]) - 1:
logging.debug("loop re-entering block #%d (%s -> %s), forcing PC to %s" %
(self.blockIdx, self.hexString(bbStart), self.hexString(bbEnd),
self.hexString(flow[paths[self.pathIdx][self.blockIdx + 1]][0])))
uc.reg_write(self.regs["pc"], flow[paths[self.pathIdx][self.blockIdx + 1]][0])
self.blockIdx += 1
self.enteredBlock = False
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
return
else:
logging.debug(
"loop re-entering block #%d (%s -> %s), but no more blocks! bailing out of this function.." %
(self.blockIdx, self.hexString(bbStart), self.hexString(bbEnd)))
self.stopEmulation(userData)
return
elif (address > bbEnd or address < bbStart):
if self.blockIdx + 1 >= len(paths[self.pathIdx]):
logging.debug(
"we missed our target! bailing out of this function..")
self.stopEmulation(userData)
return
logging.debug("%s is outside of block #%d (%s -> %s), forcing PC to %s" %
(self.hexString(address),
self.blockIdx, self.hexString(bbStart),
self.hexString(bbEnd), self.hexString(flow[paths[self.pathIdx][self.blockIdx + 1]][0])))
uc.reg_write(self.regs["pc"], flow[paths[self.pathIdx][self.blockIdx + 1]][0])
self.blockIdx += 1
self.enteredBlock = False
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
return
if address == bbStart:
self.enteredBlock = True
if idc.print_insn_mnem(address) == "":
if idc.print_insn_mnem(address + size) == "":
if idc.print_insn_mnem(address + size * 2) == "":
logging.debug(
"invalid instruction encountered @%s, bailing.." % self.hexString(address))
self.stopEmulation(userData)
return
return
if str(self.uc.mem_read(address, 0x10)) == "\x00" * 0x10:
logging.debug("pc ended up in null memory @%s" %
self.hexString(address))
self.stopEmulation(userData)
return
if address == userData["targetVA"]:
logging.debug("target %s hit" %
self.hexString(userData["targetVA"]))
self._targetHit(address, userData)
self.stopEmulation(userData)
elif address in userData["targetInfo"]:
logging.debug("target %s found on the way to %s" % (
self.hexString(address), self.hexString(userData["targetVA"])))
self._targetHit(address, userData)
if (idc.print_insn_mnem(address) in self.callMnems or
(idc.print_insn_mnem(address) == "B" and
idc.get_name_ea_simple(idc.print_operand(address, 0)) ==
idc.get_func_attr(
idc.get_name_ea_simple(idc.print_operand(address, 0)),
idc.FUNCATTR_START))):
funcName = self.getCallTargetName(address)
if userData["callHook"]:
userData["callHook"](address, self.getArgv(), funcName, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
if self.getRegVal("pc") != userData["currAddr"]:
# get IDA's SP delta value for next instruction to adjust stack accordingly since we are skipping this
uc.reg_write(self.regs["sp"], self.getRegVal("sp") +
idaapi.get_sp_delta(userData["func_t"], self.getRegVal("pc")))
return
if userData["hookApis"] and self._handleApiHooks(address, self.getArgv(), funcName, userData):
return
if address != userData["targetVA"]:
self.skipInstruction(userData)
elif self.isRetInstruction(address):
self.skipInstruction(userData)
return
except Exception as e:
logging.debug("exception in _guidedHook @%s: %s" % (self.hexString(address), e))
print("exception in _guidedHook @%s: %s" % (self.hexString(address), e))
self.stopEmulation(userData)
def _scanForCode(self, address):
while idc.print_insn_mnem(address) == "":
address = idc.next_head(address, idc.get_inf_attr(idc.INF_MAX_EA))
return address
def _handleThumbMode(self, address):
if self.isThumbMode(address):
self.uc.reg_write(self.regs["pc"], self.getRegVal("pc") | 1)
self.mode = unicorn.UC_MODE_THUMB
else:
self.uc.reg_write(self.regs["pc"], self.getRegVal("pc") & ~1)
self.mode = unicorn.UC_MODE_ARM
def _targetHit(self, address, userData):
try:
argv = self.getArgv()
userData["targetCallback"](self, address, argv, userData)
except Exception as e:
logging.debug("exception in targetCallback function @%s: %s" % (self.hexString(address), str(e)))
print("exception in targetCallback function @%s: %s" % (self.hexString(address), str(e)))
userData["visitedTargets"].append(address)
def _isBadBranch(self, userData):
if self.arch == unicorn.UC_ARCH_ARM64:
if (idc.print_insn_mnem(userData["currAddr"]) in ["BR", "BREQ"] and
idc.get_operand_type(userData["currAddr"], 0) == 1):
if (idc.print_insn_mnem(
self.uc.reg_read(
self.regs[idc.print_operand(userData["currAddr"], 0)]
))) == "":
return True
elif self.arch == unicorn.UC_ARCH_X86:
if (idc.print_insn_mnem(userData["currAddr"]) == "jmp" and
idc.get_operand_type(userData["currAddr"], 0) == 1):
if (idc.print_insn_mnem
(self.uc.reg_read(self.regs[idc.print_operand(userData["currAddr"], 0)])) == ""):
logging.debug("bad branch detected @%s" % self.hexString(userData["currAddr"]))
return True
def _findPathFromGraph(self, path, graph, currentNode, target):
if currentNode not in graph:
return False
for node in graph[currentNode]:
if node in path:
continue
path.append(node)
if node == target:
return True
if self._findPathFromGraph(path, graph, node, target):
return True
else:
path.pop()
return False
def _findPathsFromGraph(self, paths, path, graph, currentNode, target, maxPaths=MAXCODEPATHS):
if currentNode not in graph:
return
if len(paths) >= maxPaths:
return
for node in graph[currentNode]:
if node in path:
continue
path.append(node)
if node == target:
paths.append(deepcopy(path))
path.pop()
return
self._findPathsFromGraph(paths, path, graph, node, target)
path.pop()
def _explore(self, start_bb, end_bb=None):
stack = []
discovered = []
graph = {}
stack.append(start_bb)
while len(stack) > 0:
bb = stack.pop()
if bb.id not in discovered:
discovered.append(bb.id)
graph[bb.id] = []
for block in bb.succs():
stack.append(block)
graph[bb.id].append(block.id)
if end_bb is not None and block.id == end_bb.id:
return graph
return graph
def _findUnusedMemRegion(self):
highest = 0x10000
for region in self.uc.mem_regions():
if region[1] > highest:
highest = region[1]
for segVA in idautils.Segments():
endVA = idc.get_segm_end(segVA)
if endVA > highest:
highest = endVA
highest += PAGESIZE
return self.pageAlignUp(highest)
def _buildStack(self):
self.stack = self.allocEmuMem(self.stackSize) + self.stackSize / 2
self.uc.mem_write(self.stack - self.stackSize /
2, "\x00" * self.stackSize)
def _enableVFP(self):
if self.arch == unicorn.UC_ARCH_ARM:
tmp = self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_C1_C0_2)
self.uc.reg_write(unicorn.arm_const.UC_ARM_REG_C1_C0_2, tmp | (0xf << 20))
self.uc.reg_write(unicorn.arm_const.UC_ARM_REG_FPEXC, 0x40000000)
elif self.arch == unicorn.UC_ARCH_ARM64:
"""
https://static.docs.arm.com/ddi0487/ca/DDI0487C_a_armv8_arm.pdf
MRS X2, CPACR_EL1
ORR X2, X2, #0x300000 # <-- set bits 20,21 to disable trapping for FP related instructions
MSR CPACR_EL1, X2
NOP # <-- handle Unicorn bug
"""
ENABLE_VFP_CODE = "\x42\x10\x38\xd5\x42\x04\x6c\xb2\x42\x10\x18\xd5\x1f\x20\x03\xd5"
self.emulateBytes(ENABLE_VFP_CODE)
def _prepEmuContext(self, registers, stack):
mu = self.uc
for reg in self.regs:
mu.reg_write(self.regs[reg], 0)
mu.reg_write(self.regs["sp"], self.stack)
for reg in registers:
val = registers[reg]
if isinstance(val, str):
mem = self.allocEmuMem(len(val))
mu.mem_write(mem, val)
val = mem
elif isinstance(val, (int, long)):
pass
else:
logging.debug("incorrect type for %s" % reg)
return None
mu.reg_write(self.regs[reg], val)
registers[reg] = val
for i in range(0, len(stack)):
if isinstance(stack[i], str):
mem = self.allocEmuMem(len(stack[i]))
mu.mem_write(mem, stack[i])
stack[i] = mem
val = mem
elif isinstance(stack[i], (int, long)):
val = stack[i]
else:
logging.debug("incorrect type for stack[%d]" % (i))
return None
mu.mem_write(self.getRegVal("sp") + i *
self.size_pointer, struct.pack(self.pack_fmt, val))
| true | true |
f72a30b3cc3869b03198bc2b6d011b858ede7e71 | 1,027 | py | Python | examples/rename_part.py | mradway/hycohanz | 717f1c84a8a6b555b4327b868aa5968a9a717a74 | [
"BSD-2-Clause"
] | 76 | 2015-07-13T19:56:25.000Z | 2022-03-29T08:53:56.000Z | examples/rename_part.py | zxzion/hycohanz | 717f1c84a8a6b555b4327b868aa5968a9a717a74 | [
"BSD-2-Clause"
] | 2 | 2016-09-12T14:13:17.000Z | 2020-03-23T17:57:30.000Z | examples/rename_part.py | zxzion/hycohanz | 717f1c84a8a6b555b4327b868aa5968a9a717a74 | [
"BSD-2-Clause"
] | 44 | 2015-01-10T12:43:37.000Z | 2022-03-27T14:13:00.000Z | import hycohanz as hfss
raw_input('Press "Enter" to connect to HFSS.>')
[oAnsoftApp, oDesktop] = hfss.setup_interface()
raw_input('Press "Enter" to create a new project.>')
oProject = hfss.new_project(oDesktop)
raw_input('Press "Enter" to insert a new DrivenModal design named HFSSDesign1.>')
oDesign = hfss.insert_design(oProject, "HFSSDesign1", "DrivenModal")
raw_input('Press "Enter" to set the active editor to "3D Modeler" (The default and only known correct value).>')
oEditor = hfss.set_active_editor(oDesign)
raw_input('Press "Enter" to draw a red three-vertex polyline named Triangle1.>')
objname = hfss.create_polyline(
oEditor, [1, 0, -1],
[0, 1, 0],
[0, 0, 0],
Name='Triangle1',
Color="(255 0 0)",
)
raw_input('Press "Enter" to rename the part as T1.>')
result = hfss.rename_part(oEditor, objname, 'T1')
print('result: ' + str(res))
raw_input('Press "Enter" to quit HFSS.>')
hfss.quit_application(oDesktop)
del oEditor
del oDesign
del oProject
del oDesktop
del oAnsoftApp
| 23.340909 | 112 | 0.708861 | import hycohanz as hfss
raw_input('Press "Enter" to connect to HFSS.>')
[oAnsoftApp, oDesktop] = hfss.setup_interface()
raw_input('Press "Enter" to create a new project.>')
oProject = hfss.new_project(oDesktop)
raw_input('Press "Enter" to insert a new DrivenModal design named HFSSDesign1.>')
oDesign = hfss.insert_design(oProject, "HFSSDesign1", "DrivenModal")
raw_input('Press "Enter" to set the active editor to "3D Modeler" (The default and only known correct value).>')
oEditor = hfss.set_active_editor(oDesign)
raw_input('Press "Enter" to draw a red three-vertex polyline named Triangle1.>')
objname = hfss.create_polyline(
oEditor, [1, 0, -1],
[0, 1, 0],
[0, 0, 0],
Name='Triangle1',
Color="(255 0 0)",
)
raw_input('Press "Enter" to rename the part as T1.>')
result = hfss.rename_part(oEditor, objname, 'T1')
print('result: ' + str(res))
raw_input('Press "Enter" to quit HFSS.>')
hfss.quit_application(oDesktop)
del oEditor
del oDesign
del oProject
del oDesktop
del oAnsoftApp
| true | true |
f72a3134f48e05427d75ca4ce77b2fb29d5b6bdf | 12,006 | py | Python | api_1.3/containerd/services/leases/v1/leases_pb2_grpc.py | siemens/pycontainerd | 9b1184ecbcc91144ad6903403818b5b8989a32f3 | [
"Apache-2.0"
] | 24 | 2019-12-16T12:38:51.000Z | 2022-02-16T18:44:20.000Z | api_1.5/containerd/services/leases/v1/leases_pb2_grpc.py | siemens/pycontainerd | 9b1184ecbcc91144ad6903403818b5b8989a32f3 | [
"Apache-2.0"
] | 9 | 2020-03-03T07:42:40.000Z | 2021-09-01T10:11:18.000Z | api_1.3/containerd/services/leases/v1/leases_pb2_grpc.py | siemens/pycontainerd | 9b1184ecbcc91144ad6903403818b5b8989a32f3 | [
"Apache-2.0"
] | 10 | 2019-12-16T11:20:23.000Z | 2022-01-24T01:53:13.000Z | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from containerd.services.leases.v1 import leases_pb2 as containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
class LeasesStub(object):
"""Leases service manages resources leases within the metadata store.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Create = channel.unary_unary(
'/containerd.services.leases.v1.Leases/Create',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateRequest.SerializeToString,
response_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateResponse.FromString,
)
self.Delete = channel.unary_unary(
'/containerd.services.leases.v1.Leases/Delete',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.List = channel.unary_unary(
'/containerd.services.leases.v1.Leases/List',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListRequest.SerializeToString,
response_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResponse.FromString,
)
self.AddResource = channel.unary_unary(
'/containerd.services.leases.v1.Leases/AddResource',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.AddResourceRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.DeleteResource = channel.unary_unary(
'/containerd.services.leases.v1.Leases/DeleteResource',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteResourceRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.ListResources = channel.unary_unary(
'/containerd.services.leases.v1.Leases/ListResources',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesRequest.SerializeToString,
response_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesResponse.FromString,
)
class LeasesServicer(object):
"""Leases service manages resources leases within the metadata store.
"""
def Create(self, request, context):
"""Create creates a new lease for managing changes to metadata. A lease
can be used to protect objects from being removed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Delete(self, request, context):
"""Delete deletes the lease and makes any unreferenced objects created
during the lease eligible for garbage collection if not referenced
or retained by other resources during the lease.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def List(self, request, context):
"""List lists all active leases, returning the full list of
leases and optionally including the referenced resources.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def AddResource(self, request, context):
"""AddResource references the resource by the provided lease.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def DeleteResource(self, request, context):
"""DeleteResource dereferences the resource by the provided lease.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListResources(self, request, context):
"""ListResources lists all the resources referenced by the lease.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_LeasesServicer_to_server(servicer, server):
rpc_method_handlers = {
'Create': grpc.unary_unary_rpc_method_handler(
servicer.Create,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateRequest.FromString,
response_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateResponse.SerializeToString,
),
'Delete': grpc.unary_unary_rpc_method_handler(
servicer.Delete,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'List': grpc.unary_unary_rpc_method_handler(
servicer.List,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListRequest.FromString,
response_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResponse.SerializeToString,
),
'AddResource': grpc.unary_unary_rpc_method_handler(
servicer.AddResource,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.AddResourceRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'DeleteResource': grpc.unary_unary_rpc_method_handler(
servicer.DeleteResource,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteResourceRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'ListResources': grpc.unary_unary_rpc_method_handler(
servicer.ListResources,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesRequest.FromString,
response_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'containerd.services.leases.v1.Leases', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class Leases(object):
"""Leases service manages resources leases within the metadata store.
"""
@staticmethod
def Create(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/Create',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateRequest.SerializeToString,
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Delete(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/Delete',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def List(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/List',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListRequest.SerializeToString,
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def AddResource(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/AddResource',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.AddResourceRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def DeleteResource(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/DeleteResource',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteResourceRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def ListResources(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/ListResources',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesRequest.SerializeToString,
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| 48.804878 | 138 | 0.693487 |
import grpc
from containerd.services.leases.v1 import leases_pb2 as containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
class LeasesStub(object):
def __init__(self, channel):
self.Create = channel.unary_unary(
'/containerd.services.leases.v1.Leases/Create',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateRequest.SerializeToString,
response_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateResponse.FromString,
)
self.Delete = channel.unary_unary(
'/containerd.services.leases.v1.Leases/Delete',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.List = channel.unary_unary(
'/containerd.services.leases.v1.Leases/List',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListRequest.SerializeToString,
response_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResponse.FromString,
)
self.AddResource = channel.unary_unary(
'/containerd.services.leases.v1.Leases/AddResource',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.AddResourceRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.DeleteResource = channel.unary_unary(
'/containerd.services.leases.v1.Leases/DeleteResource',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteResourceRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.ListResources = channel.unary_unary(
'/containerd.services.leases.v1.Leases/ListResources',
request_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesRequest.SerializeToString,
response_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesResponse.FromString,
)
class LeasesServicer(object):
def Create(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Delete(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def List(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def AddResource(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def DeleteResource(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListResources(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_LeasesServicer_to_server(servicer, server):
rpc_method_handlers = {
'Create': grpc.unary_unary_rpc_method_handler(
servicer.Create,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateRequest.FromString,
response_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateResponse.SerializeToString,
),
'Delete': grpc.unary_unary_rpc_method_handler(
servicer.Delete,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'List': grpc.unary_unary_rpc_method_handler(
servicer.List,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListRequest.FromString,
response_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResponse.SerializeToString,
),
'AddResource': grpc.unary_unary_rpc_method_handler(
servicer.AddResource,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.AddResourceRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'DeleteResource': grpc.unary_unary_rpc_method_handler(
servicer.DeleteResource,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteResourceRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'ListResources': grpc.unary_unary_rpc_method_handler(
servicer.ListResources,
request_deserializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesRequest.FromString,
response_serializer=containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'containerd.services.leases.v1.Leases', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class Leases(object):
@staticmethod
def Create(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/Create',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateRequest.SerializeToString,
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.CreateResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Delete(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/Delete',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def List(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/List',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListRequest.SerializeToString,
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def AddResource(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/AddResource',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.AddResourceRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def DeleteResource(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/DeleteResource',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.DeleteResourceRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def ListResources(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/containerd.services.leases.v1.Leases/ListResources',
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesRequest.SerializeToString,
containerd_dot_services_dot_leases_dot_v1_dot_leases__pb2.ListResourcesResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| true | true |
f72a323e448cb0a9fa157ef9d9d8c7e1cb25daf0 | 28,211 | py | Python | envbuilder.py | lurman/envbulder | 01dd05809e0a4558131bd6574186744364a08045 | [
"Apache-2.0"
] | null | null | null | envbuilder.py | lurman/envbulder | 01dd05809e0a4558131bd6574186744364a08045 | [
"Apache-2.0"
] | null | null | null | envbuilder.py | lurman/envbulder | 01dd05809e0a4558131bd6574186744364a08045 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
import subprocess
from snc_config import SncConfig
from datetime import datetime, timedelta
import argparse
from argparse import RawTextHelpFormatter
from color_print import ColorPrint
from plugins import PluginsLoader
import os
from multiprocessing import Pool
import copy_reg
import types
from itertools import repeat
import time
from functools import partial
from notification_manager import NotificationManager
ENVB_PATH = 'ENVB_PATH'
def _reduce_method(m):
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name)
copy_reg.pickle(types.MethodType, _reduce_method)
class EnvironmentBuilder(object):
"""
This class is main class of SNC Env builder
"""
def __init__(self, release_name):
self.release = release_name
self.config = SncConfig()
self.git_url = self.config.getstring('git_repo', 'git_url')
self.base_dir = self.config.getstring('git_repo', 'base_dir');
self.path_to_workspace = self.base_dir + os.sep + release_name
self.abort_on_error = self.config.getboolean('envbuilder', 'abort_on_error')
self.parallel_run = self.config.getboolean('envbuilder', 'parallel_run')
self.print_cmd_output = self.config.getboolean('envbuilder', 'print_cmd_output')
self.print_cmd = self.config.getboolean('envbuilder', 'print_cmd')
self.repo_status = {}
self.notif_mgr = NotificationManager(None, None, None)
if os.path.exists("errors.txt"):
os.remove("errors.txt")
def run_commands_in_current_release(self, commands):
final_status = True
final_error = ''
final_output = ''
for command in commands:
p_status, output, error = self.run_command_and_collect_errors("cd {0};{1}".format(self.path_to_workspace, str(command)))
if p_status != 0:
final_status = False
final_error = final_error + ' ' + str(error)
final_output = final_output + ' ' + str(output)
break
return final_status, final_output, final_error
def run_command_in_background(self, command):
b_command = "cd {0};{1} &".format(self.path_to_workspace, command)
os.system(b_command)
def run_command_and_collect_errors(self, command):
p_status, output, error = EnvironmentBuilder.handle_command(command, True, True, self.print_cmd_output, self.print_cmd)
if p_status != 0:
current_error = "Failed command: [{0}] Error: [{1}], Output: [{2}]".format(command, error, output)
filename = 'errors.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
error_file = open(filename,append_write)
error_file.write(current_error + '\n')
error_file.close()
return p_status, output, error
def clone_env(self):
now = time.time()
if not os.path.exists(self.path_to_workspace):
os.makedirs(self.path_to_workspace)
list_of_repos = self.config.getlist('git_repo', 'repo');
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(self._clone_env, list_of_repos)
else:
for repo in list_of_repos:
self._clone_env(repo)
later = time.time()
difference = int(later - now)
log_message = "Clone operation for release [{0}] took [{1}] seconds".format(self.release,difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'clone_env', log_message)
def _clone_env(self, repo):
if not os.path.exists(self.path_to_workspace + os.sep + repo):
clone_cmd ='cd {0};git clone https://{1}/{2}'.format(self.path_to_workspace, self.git_url, repo)
self.run_command_and_collect_errors(clone_cmd)
def copy_local_env(self, new_release_name):
path_to_new_release = self.base_dir + os.sep + new_release_name
copy_cmdb = 'cp -rp ' + self.path_to_workspace + ' ' + path_to_new_release
ColorPrint.blue_highlight("Copying environment [{0}] to [{1}] ".format(self.release, new_release_name))
if os.path.exists(self.path_to_workspace):
self.run_command_and_collect_errors(copy_cmdb)
else:
ColorPrint.err("Can't copy due to invalid path: [{0}] ".format(self.path_to_workspace))
def show_my_commits(self, show_sha, since_days):
list_of_repos = self.config.getlist('git_repo','repo');
for repo in list_of_repos:
current_repo_path = self.path_to_workspace + os.sep + repo;
if os.path.exists(current_repo_path):
if since_days is None:
commit_since_days = self.config.getint('git_repo','commit_since_days');
else:
commit_since_days = int(since_days)
since_date = datetime.now() - timedelta(days=commit_since_days)
show_commit = ''
if not show_sha:
show_commit = '\|commit ';
cmd_commits = 'cd ' + current_repo_path + ';git log --author="$(git config user.name)" --since "{0} {1} {2}"|grep -v "Author:\|Date:{3}"'.\
format(since_date.strftime("%B"), since_date.day, since_date.year, show_commit)
commits_output = EnvironmentBuilder.handle_command(cmd_commits, False, True, self.print_cmd_output, self.print_cmd)
p_status, output, err = commits_output;
if p_status == 0 and not (output.rstrip('\n').isspace()):
output = os.linesep.join(['\t' + s.strip() for s in output.splitlines() if s])
ColorPrint.blue_highlight("Commits for repository [{0}]".format(repo.upper()))
ColorPrint.info(output)
unpushed_commits = self.get_unpushed_commits(current_repo_path)
if unpushed_commits and not unpushed_commits.rstrip('\n').isspace():
ColorPrint.err("\tUnpushed commits!!!")
ColorPrint.warn(unpushed_commits)
def get_branch_name(self, repository_path):
cmd_get_branch = 'cd {0};git rev-parse --abbrev-ref HEAD'.format(repository_path)
result = self.run_command_and_collect_errors(cmd_get_branch)
p_status, branch_name, err = result;
branch_name = branch_name.rstrip('\n')
if p_status == 0:
return branch_name
return None
def get_unpushed_commits(self, repository_path):
current_branch = self.get_branch_name(repository_path)
cmd_commits = 'cd {0};git log origin/{1}..{2}|grep -v "Author:\|Date:"'.format(repository_path, current_branch, current_branch)
commits_output = EnvironmentBuilder.handle_command(cmd_commits, False, True, False)
p_status, output, err = commits_output;
if p_status == 0 and not (output.rstrip('\n').isspace()):
output = os.linesep.join(['\t' + s.strip() for s in output.splitlines() if s])
return output
return None
def switch_track(self, track_name):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
now = time.time()
list_of_repos = self.config.getlist('git_repo','repo');
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(self._switch_repo, zip(list_of_repos, repeat(track_name)))
else:
for repo in list_of_repos:
self._switch_repo([repo, track_name])
later = time.time()
difference = int(later - now)
log_message = "Switch operation for release [{0}] took [{1}] seconds".format(self.release, difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, "Switch branch", log_message)
def _switch_repo(self, args):
repo, track_name = args
ColorPrint.blue_highlight("Trying to switch the repository [{0}] to [{1}]".format(repo, track_name))
if os.path.exists(self.path_to_workspace + os.sep + repo):
p_status, out, err = self.run_command_and_collect_errors('cd {0};git rev-parse --abbrev-ref HEAD'.format(self.path_to_workspace + os.sep + repo))
if out == track_name:
ColorPrint.warn("The current repository [{0}] already switched to [{1}], skipping".format(repo, track_name))
else:
self.run_command_and_collect_errors('cd {0};git checkout {1}'.format(self.path_to_workspace + os.sep + repo, track_name))
def mvn_build(self):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
project_per_repo = self.config.getsection('projects')
for repo_name, projects in project_per_repo:
ColorPrint.blue_highlight("Starting mvn install for repository {0}".format(repo_name))
for project_name in projects.split(','):
project_path = self.path_to_workspace + os.sep + repo_name + os.sep + project_name
java_env = 'source ~/.bash_profile'
cmd = java_env + ';cd {0};mvn clean install -DskipTests'.format(project_path)
self.run_command_and_collect_errors(cmd)
log_message = "Maven build operation for release completed".format(self.release)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'Maven Build', log_message)
def mvn_clean(self):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
project_per_repo = self.config.getsection('projects')
for repo_name, projects in project_per_repo:
ColorPrint.blue_highlight("Starting mvn clean for repository {0}".format(repo_name))
for project_name in projects.split(','):
project_path = self.path_to_workspace + os.sep + repo_name + os.sep + project_name
java_env = 'source ~/.bash_profile'
cmd = java_env + ';cd {0};mvn clean'.format(project_path)
self.run_command_and_collect_errors(cmd)
log_message = "Maven clean operation for release completed".format(self.release)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'Maven Clean', log_message)
def run_git_pull(self):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
now = time.time()
list_of_repos = self.config.getlist('git_repo', 'repo');
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(self._git_pull, list_of_repos)
else:
for repo in list_of_repos:
self._git_pull(repo)
later = time.time()
difference = int(later - now)
log_message = "Pull operation for release [{0}] took [{1}] seconds".format(self.release, difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'git pull', log_message)
def run_git_custom(self,git_command):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
now = time.time()
list_of_repos = self.config.getlist('git_repo', 'repo');
func = partial(self._git_custom, git_command)
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(func, list_of_repos)
else:
for repo in list_of_repos:
self._git_custom(git_command, repo)
later = time.time()
difference = int(later - now)
log_message = "Git custom operation for release [{0}] took [{1}] seconds".format(self.release, difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, git_command, log_message)
def _git_pull(self, repo):
ColorPrint.blue_highlight("Pulling the repository [{0}]".format(repo))
repo_path = self.path_to_workspace + os.sep + repo
is_git_pull_ran = False
if os.path.exists(repo_path):
current_branch = self.get_branch_name(repo_path)
if self._is_branch_up_to_date(repo_path):
if repo in self.repo_status and self.repo_status[repo]:
ColorPrint.blue_highlight('Your repository [{0}] is up-to-date, skipping [git pull]'.format(repo))
else:
p_status, output, error = self.run_command_and_collect_errors('cd {0};git pull origin {1}'.format(repo_path, current_branch))
is_git_pull_ran = True
else:
self.run_git_stash(repo_path)
if self._is_ready_to_pull(repo_path):
if repo in self.repo_status and self.repo_status[repo]:
ColorPrint.blue_highlight('Your repository [{0}] is up-to-date, skipping [git pull]'.format(repo))
else:
p_status, output, error = self.run_command_and_collect_errors('cd {0};git pull origin {1}'.format(repo_path, current_branch))
is_git_pull_ran = True
self.run_git_unstash(repo_path)
else:
ColorPrint.warn( "The repository path [{0}] is not available".format(repo))
if is_git_pull_ran and p_status == 0:
if 'up to date' in output or 'Successfully rebased and updated' or 'Fast-forward' in output:
ColorPrint.blue_highlight("Pull for repository {0} finished successfully".format(repo))
else:
current_error = "Your repository {0} is broken, try to run 'git gc --prune=now' and 'git remote prune origin' to fix it".format(repo)
ColorPrint.err(current_error)
filename = 'errors.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
error_file = open(filename, append_write)
error_file.write(current_error + '\n')
error_file.close()
def _git_custom(self, git_command, repo):
ColorPrint.blue_highlight("Running custom git command on repository [{0}]".format(repo))
repo_path = self.path_to_workspace + os.sep + repo
if os.path.exists(repo_path):
self.run_command_and_collect_errors('cd {0};git {1}'.format(repo_path, git_command ))
else:
ColorPrint.warn( "The repository path [{0}] is not available".format(repo))
def run_git_stash(self, repo_path):
if os.path.exists(repo_path):
ColorPrint.blue_highlight( "Stashing the repository [{0}]".format(repo_path))
self.run_command_and_collect_errors('cd {0};git stash'.format(repo_path))
else:
ColorPrint.warn( "The repository path [{0}] is not available".format(repo_path))
def run_git_unstash(self, repo_path):
if os.path.exists(repo_path):
ColorPrint.blue_highlight("Unstashing the repository [{0}]".format(repo_path))
self.run_command_and_collect_errors('cd {0};git stash pop'.format(repo_path))
else:
ColorPrint.warn("The repository path [{0}] is not available".format(repo_path))
def _is_ready_to_pull(self, repo_path):
ColorPrint.blue_highlight("Checking repository status [{0}]".format(repo_path))
p_status, cmd_out, err = self.run_command_and_collect_errors('cd {0};git status -uno'.format(repo_path))
ColorPrint.info(cmd_out)
repo = os.path.basename(os.path.normpath(repo_path))
if 'Your branch is up-to-date' in str(cmd_out):
self.repo_status[repo] = True
else:
self.repo_status[repo] = False
if 'nothing to commit' in str(cmd_out):
return True
else:
return False
def _is_branch_up_to_date(self, repo_path):
ColorPrint.blue_highlight("Checking repository status [{0}]".format(repo_path))
self.run_command_and_collect_errors('cd {0};git remote update'.format(repo_path))
if self._is_ready_to_pull(repo_path):
return True
else:
repo = os.path.basename(os.path.normpath(repo_path))
if repo in self.repo_status and self.repo_status[repo]:
return True
else:
return False
@staticmethod
def print_list_avalable_versions(current_release):
base_dir = SncConfig().getstring('git_repo', 'base_dir');
if current_release is not None:
ColorPrint.blue_highlight('================' + current_release.upper() + '================')
EnvironmentBuilder.print_release_branch_per_repository(current_release)
exit(0)
for dir in os.listdir(base_dir):
if os.path.isdir(base_dir + os.sep + dir) and not dir.startswith('.'):
if EnvironmentBuilder.is_release_direcrory(dir):
ColorPrint.blue_highlight('================' + dir.upper() + '================')
EnvironmentBuilder.print_release_branch_per_repository(dir)
@staticmethod
def print_release_branch_per_repository(current_release):
"""git remote prune origin"""
base_dir = SncConfig().getstring('git_repo','base_dir');
list_of_repos = SncConfig().getlist('git_repo', 'repo');
list_of_messages = {}
brunches_d = {}
for repository in list_of_repos:
path_to_repository = base_dir + os.sep + current_release + os.sep + repository
if os.path.exists(path_to_repository + os.sep + '.git'):
cmd_get_branch = 'cd {0};git rev-parse --abbrev-ref HEAD'.format(path_to_repository)
status, current_brunch, error = EnvironmentBuilder.handle_command(cmd_get_branch, True, True, False)
current_brunch = current_brunch.rstrip();
current_message = "Release: [{0}] Repository: [{1}], Branch: [{2}]".rstrip().format(current_release, repository, current_brunch)
list_of_messages[current_message] = current_brunch
if current_brunch in brunches_d:
brunches_d[current_brunch] += 1
else:
brunches_d[current_brunch] = 0
if brunches_d.values():
max_brunch = max(brunches_d.values())
for message, branch in list_of_messages.iteritems():
if brunches_d[branch] < max_brunch:
ColorPrint.err(message)
else:
ColorPrint.info(message)
@staticmethod
def is_release_direcrory(release_dir):
base_dir = SncConfig().getstring('git_repo','base_dir');
full_path = base_dir + os.sep + release_dir
list_of_dirs = os.listdir(full_path)
list_of_repos = SncConfig().getlist('git_repo','repo');
return not set(list_of_repos).isdisjoint(list_of_dirs)
def print_execution_error_summary(self):
if not os.path.exists("errors.txt"):
exit(0)
with open('errors.txt', 'r') as error_file:
all_errors=error_file.read()
if all_errors:
ColorPrint.blue_highlight("Fix the following errors and run again")
ColorPrint.err('\n' + all_errors)
else:
ColorPrint.blue_highlight("Execution complited without errors")
@staticmethod
def handle_command(cmd, check_rc=True, get_output=True, print_output=False, print_cmd=False, background=False):
"""
Executes command
:param cmd: command string to be executed
:return: rc, stdout, stderr
"""
stdout_flag = None
if get_output:
stdout_flag = subprocess.PIPE
if print_cmd:
ColorPrint.info("[handle_command] running {0}".format(cmd))
p = subprocess.Popen(cmd,
stdout=stdout_flag,
stderr=subprocess.STDOUT,
shell=True)
out, err = p.communicate()
p_status = p.wait()
if check_rc:
if p_status != 0:
ColorPrint.err("[handle_command] failed executing: {0}".format(cmd))
ColorPrint.err(str(err) + ' ' + str(out))
else:
if print_output:
ColorPrint.info("[handle_command] Command output: {0} ".format(str(out)))
abort_on_error = SncConfig().getboolean('envbuilder', 'abort_on_error')
if abort_on_error and p_status != 0:
ColorPrint.err("EnvironmentBuilder: Execution aborted due to error[s]")
exit(1)
return p_status, out, err
if __name__ == '__main__':
#Font Name: Big
#http://patorjk.com/software/taag
ColorPrint.blue_highlight("""
# ______ ____ _ _ _ __ _ _
# | ____| | _ \ (_) | | | /_ | || |
# | |__ _ ____ _| |_) |_ _ _| | __| | ___ _ __ | | || |_
# | __| | '_ \ \ / / _ <| | | | | |/ _` |/ _ \ '__| | |__ _|
# | |____| | | \ V /| |_) | |_| | | | (_| | __/ | | |_ | |
# |______|_| |_|\_/ |____/ \__,_|_|_|\__,_|\___|_| |_(_)|_|
#""");
parser = argparse.ArgumentParser(prog='envbuilder.py',
description='Build environment tool',
formatter_class=RawTextHelpFormatter)
parser.add_argument('-clone', help='Clone defined repositories in the conf file to the specifed release directory', action="store_true")
parser.add_argument('-pull', help='run git pull for all or specified repositories \n ./envbuilder.py -pull -r release',action="store_true")
parser.add_argument('-sw', help='switch all repositories to relevant track \n /envbuilder.py -sw -t trackname -r release', action="store_true")
parser.add_argument('-t', help='track to switch', nargs='?',dest="track")
parser.add_argument('-r', help='release name', nargs='?', dest="release")
parser.add_argument('-copy', help='Copy local release to the new one. Useful for Intellij developers', action="store_true")
parser.add_argument('-nr', help='new release name', nargs='?', dest="new_release")
parser.add_argument('-commits', help='Show my release commits', action="store_true")
parser.add_argument('-sha', help='SHA key as part of commit message', action="store_true")
parser.add_argument('-days', help='Commit since days ago', nargs='?',dest="since_days")
parser.add_argument('-status', help='Status of the current local branches', action="store_true")
parser.add_argument('-mvn', help='Run maven install -DskipTests for the specified release', action="store_true")
parser.add_argument('-mvn_clean', help='Run maven clean for the specified release', action="store_true")
parser.add_argument('-git', help='Run custom git command', nargs='?',dest="git_command")
config = SncConfig()
default_release = config.getstring('envbuilder', 'release')
pl = PluginsLoader(os.environ[ENVB_PATH] + os.sep + "plugins")
plugins = pl.load_plugins()
for flag in plugins:
plugin = plugins[flag]
if plugin['active'] is True:
parser.add_argument('-{0}'.format(plugin['flag']),
help='{0}'.format(plugin['description']), action="store_true")
args = parser.parse_args()
# print str(args)
if not args.release:
ColorPrint.info("The -r [release] option is not provided, using default [{0}] from envbuilder.conf".format(default_release))
if not default_release:
ColorPrint.err('\n' + "The [release] parameter is not defined under [enbuilder] section in enbuilder.conf")
args.release = default_release
if args.status and args.release:
EnvironmentBuilder.print_list_avalable_versions(args.release)
exit(0)
if args.status:
EnvironmentBuilder.print_list_avalable_versions(None)
exit(0)
if args.mvn and args.release:
builder = EnvironmentBuilder(args.release)
builder.mvn_build()
builder.print_execution_error_summary()
exit(0)
if args.mvn_clean and args.release:
builder = EnvironmentBuilder(args.release)
builder.mvn_clean()
builder.print_execution_error_summary()
exit(0)
if args.commits and args.release:
builder = EnvironmentBuilder(args.release)
builder.show_my_commits(args.sha, args.since_days)
exit(0)
if args.copy and args.release and args.new_release:
builder = EnvironmentBuilder(args.release)
builder.copy_local_env(args.new_release)
builder.print_execution_error_summary()
exit(0)
if args.sw and args.release and args.track:
builder = EnvironmentBuilder(args.release)
builder.switch_track(args.track)
builder.print_execution_error_summary()
exit(0)
if args.pull and args.release:
builder = EnvironmentBuilder(args.release)
builder.run_git_pull()
builder.print_execution_error_summary()
exit(0)
if args.git_command and args.release:
builder = EnvironmentBuilder(args.release)
builder.run_git_custom(args.git_command)
builder.print_execution_error_summary()
exit(0)
if args.clone and args.release:
builder = EnvironmentBuilder(args.release)
builder.clone_env()
if args.track:
builder.switch_track(args.track)
builder.print_execution_error_summary()
exit(0)
for option in plugins:
try:
current_arg = getattr(args, option)
if current_arg is True:
plugin = plugins[option]
builder = EnvironmentBuilder(args.release)
commands_to_run = plugin['commands']
if plugin['type'] == 'group':
plugins_to_run = plugin['plugins']
for run_plugin_flag in plugins_to_run:
run_plugin = plugins[run_plugin_flag]
commands_to_run.extend(run_plugin['commands'])
is_background = False
if plugin['background'] is True:
is_background = True
last_command = commands_to_run.pop()
final_status, final_output, final_error = builder.run_commands_in_current_release(commands_to_run)
if is_background:
builder.run_command_in_background(last_command)
if final_output is None:
final_output = ''
if final_error is None:
final_error = ''
if plugin['notify'] is True:
notifier = NotificationManager(None, None, None)
if final_status is True:
command_status = 'completed successfully'
final_result = final_output
else:
command_status = 'execution failed'
final_result = final_output + final_error
notif_msg = "Command: [{0}] Status: {1} Result: {2}".format(plugin['description'],
command_status, final_result)
notifier.send_notification(final_status,plugin['name'], notif_msg)
exit(0)
except AttributeError:
continue
else:
parser.print_help()
| 47.096828 | 157 | 0.618092 |
import subprocess
from snc_config import SncConfig
from datetime import datetime, timedelta
import argparse
from argparse import RawTextHelpFormatter
from color_print import ColorPrint
from plugins import PluginsLoader
import os
from multiprocessing import Pool
import copy_reg
import types
from itertools import repeat
import time
from functools import partial
from notification_manager import NotificationManager
ENVB_PATH = 'ENVB_PATH'
def _reduce_method(m):
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name)
copy_reg.pickle(types.MethodType, _reduce_method)
class EnvironmentBuilder(object):
def __init__(self, release_name):
self.release = release_name
self.config = SncConfig()
self.git_url = self.config.getstring('git_repo', 'git_url')
self.base_dir = self.config.getstring('git_repo', 'base_dir');
self.path_to_workspace = self.base_dir + os.sep + release_name
self.abort_on_error = self.config.getboolean('envbuilder', 'abort_on_error')
self.parallel_run = self.config.getboolean('envbuilder', 'parallel_run')
self.print_cmd_output = self.config.getboolean('envbuilder', 'print_cmd_output')
self.print_cmd = self.config.getboolean('envbuilder', 'print_cmd')
self.repo_status = {}
self.notif_mgr = NotificationManager(None, None, None)
if os.path.exists("errors.txt"):
os.remove("errors.txt")
def run_commands_in_current_release(self, commands):
final_status = True
final_error = ''
final_output = ''
for command in commands:
p_status, output, error = self.run_command_and_collect_errors("cd {0};{1}".format(self.path_to_workspace, str(command)))
if p_status != 0:
final_status = False
final_error = final_error + ' ' + str(error)
final_output = final_output + ' ' + str(output)
break
return final_status, final_output, final_error
def run_command_in_background(self, command):
b_command = "cd {0};{1} &".format(self.path_to_workspace, command)
os.system(b_command)
def run_command_and_collect_errors(self, command):
p_status, output, error = EnvironmentBuilder.handle_command(command, True, True, self.print_cmd_output, self.print_cmd)
if p_status != 0:
current_error = "Failed command: [{0}] Error: [{1}], Output: [{2}]".format(command, error, output)
filename = 'errors.txt'
if os.path.exists(filename):
append_write = 'a'
else:
append_write = 'w'
error_file = open(filename,append_write)
error_file.write(current_error + '\n')
error_file.close()
return p_status, output, error
def clone_env(self):
now = time.time()
if not os.path.exists(self.path_to_workspace):
os.makedirs(self.path_to_workspace)
list_of_repos = self.config.getlist('git_repo', 'repo');
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(self._clone_env, list_of_repos)
else:
for repo in list_of_repos:
self._clone_env(repo)
later = time.time()
difference = int(later - now)
log_message = "Clone operation for release [{0}] took [{1}] seconds".format(self.release,difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'clone_env', log_message)
def _clone_env(self, repo):
if not os.path.exists(self.path_to_workspace + os.sep + repo):
clone_cmd ='cd {0};git clone https://{1}/{2}'.format(self.path_to_workspace, self.git_url, repo)
self.run_command_and_collect_errors(clone_cmd)
def copy_local_env(self, new_release_name):
path_to_new_release = self.base_dir + os.sep + new_release_name
copy_cmdb = 'cp -rp ' + self.path_to_workspace + ' ' + path_to_new_release
ColorPrint.blue_highlight("Copying environment [{0}] to [{1}] ".format(self.release, new_release_name))
if os.path.exists(self.path_to_workspace):
self.run_command_and_collect_errors(copy_cmdb)
else:
ColorPrint.err("Can't copy due to invalid path: [{0}] ".format(self.path_to_workspace))
def show_my_commits(self, show_sha, since_days):
list_of_repos = self.config.getlist('git_repo','repo');
for repo in list_of_repos:
current_repo_path = self.path_to_workspace + os.sep + repo;
if os.path.exists(current_repo_path):
if since_days is None:
commit_since_days = self.config.getint('git_repo','commit_since_days');
else:
commit_since_days = int(since_days)
since_date = datetime.now() - timedelta(days=commit_since_days)
show_commit = ''
if not show_sha:
show_commit = '\|commit ';
cmd_commits = 'cd ' + current_repo_path + ';git log --author="$(git config user.name)" --since "{0} {1} {2}"|grep -v "Author:\|Date:{3}"'.\
format(since_date.strftime("%B"), since_date.day, since_date.year, show_commit)
commits_output = EnvironmentBuilder.handle_command(cmd_commits, False, True, self.print_cmd_output, self.print_cmd)
p_status, output, err = commits_output;
if p_status == 0 and not (output.rstrip('\n').isspace()):
output = os.linesep.join(['\t' + s.strip() for s in output.splitlines() if s])
ColorPrint.blue_highlight("Commits for repository [{0}]".format(repo.upper()))
ColorPrint.info(output)
unpushed_commits = self.get_unpushed_commits(current_repo_path)
if unpushed_commits and not unpushed_commits.rstrip('\n').isspace():
ColorPrint.err("\tUnpushed commits!!!")
ColorPrint.warn(unpushed_commits)
def get_branch_name(self, repository_path):
cmd_get_branch = 'cd {0};git rev-parse --abbrev-ref HEAD'.format(repository_path)
result = self.run_command_and_collect_errors(cmd_get_branch)
p_status, branch_name, err = result;
branch_name = branch_name.rstrip('\n')
if p_status == 0:
return branch_name
return None
def get_unpushed_commits(self, repository_path):
current_branch = self.get_branch_name(repository_path)
cmd_commits = 'cd {0};git log origin/{1}..{2}|grep -v "Author:\|Date:"'.format(repository_path, current_branch, current_branch)
commits_output = EnvironmentBuilder.handle_command(cmd_commits, False, True, False)
p_status, output, err = commits_output;
if p_status == 0 and not (output.rstrip('\n').isspace()):
output = os.linesep.join(['\t' + s.strip() for s in output.splitlines() if s])
return output
return None
def switch_track(self, track_name):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
now = time.time()
list_of_repos = self.config.getlist('git_repo','repo');
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(self._switch_repo, zip(list_of_repos, repeat(track_name)))
else:
for repo in list_of_repos:
self._switch_repo([repo, track_name])
later = time.time()
difference = int(later - now)
log_message = "Switch operation for release [{0}] took [{1}] seconds".format(self.release, difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, "Switch branch", log_message)
def _switch_repo(self, args):
repo, track_name = args
ColorPrint.blue_highlight("Trying to switch the repository [{0}] to [{1}]".format(repo, track_name))
if os.path.exists(self.path_to_workspace + os.sep + repo):
p_status, out, err = self.run_command_and_collect_errors('cd {0};git rev-parse --abbrev-ref HEAD'.format(self.path_to_workspace + os.sep + repo))
if out == track_name:
ColorPrint.warn("The current repository [{0}] already switched to [{1}], skipping".format(repo, track_name))
else:
self.run_command_and_collect_errors('cd {0};git checkout {1}'.format(self.path_to_workspace + os.sep + repo, track_name))
def mvn_build(self):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
project_per_repo = self.config.getsection('projects')
for repo_name, projects in project_per_repo:
ColorPrint.blue_highlight("Starting mvn install for repository {0}".format(repo_name))
for project_name in projects.split(','):
project_path = self.path_to_workspace + os.sep + repo_name + os.sep + project_name
java_env = 'source ~/.bash_profile'
cmd = java_env + ';cd {0};mvn clean install -DskipTests'.format(project_path)
self.run_command_and_collect_errors(cmd)
log_message = "Maven build operation for release completed".format(self.release)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'Maven Build', log_message)
def mvn_clean(self):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
project_per_repo = self.config.getsection('projects')
for repo_name, projects in project_per_repo:
ColorPrint.blue_highlight("Starting mvn clean for repository {0}".format(repo_name))
for project_name in projects.split(','):
project_path = self.path_to_workspace + os.sep + repo_name + os.sep + project_name
java_env = 'source ~/.bash_profile'
cmd = java_env + ';cd {0};mvn clean'.format(project_path)
self.run_command_and_collect_errors(cmd)
log_message = "Maven clean operation for release completed".format(self.release)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'Maven Clean', log_message)
def run_git_pull(self):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
now = time.time()
list_of_repos = self.config.getlist('git_repo', 'repo');
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(self._git_pull, list_of_repos)
else:
for repo in list_of_repos:
self._git_pull(repo)
later = time.time()
difference = int(later - now)
log_message = "Pull operation for release [{0}] took [{1}] seconds".format(self.release, difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, 'git pull', log_message)
def run_git_custom(self,git_command):
if not os.path.exists(self.path_to_workspace):
ColorPrint.err("Invalid release name: [{0}]".format(self.release))
exit(1)
now = time.time()
list_of_repos = self.config.getlist('git_repo', 'repo');
func = partial(self._git_custom, git_command)
if self.parallel_run:
pool = Pool(len(list_of_repos))
pool.map(func, list_of_repos)
else:
for repo in list_of_repos:
self._git_custom(git_command, repo)
later = time.time()
difference = int(later - now)
log_message = "Git custom operation for release [{0}] took [{1}] seconds".format(self.release, difference)
ColorPrint.blue_highlight(log_message)
self.notif_mgr.send_notification(True, git_command, log_message)
def _git_pull(self, repo):
ColorPrint.blue_highlight("Pulling the repository [{0}]".format(repo))
repo_path = self.path_to_workspace + os.sep + repo
is_git_pull_ran = False
if os.path.exists(repo_path):
current_branch = self.get_branch_name(repo_path)
if self._is_branch_up_to_date(repo_path):
if repo in self.repo_status and self.repo_status[repo]:
ColorPrint.blue_highlight('Your repository [{0}] is up-to-date, skipping [git pull]'.format(repo))
else:
p_status, output, error = self.run_command_and_collect_errors('cd {0};git pull origin {1}'.format(repo_path, current_branch))
is_git_pull_ran = True
else:
self.run_git_stash(repo_path)
if self._is_ready_to_pull(repo_path):
if repo in self.repo_status and self.repo_status[repo]:
ColorPrint.blue_highlight('Your repository [{0}] is up-to-date, skipping [git pull]'.format(repo))
else:
p_status, output, error = self.run_command_and_collect_errors('cd {0};git pull origin {1}'.format(repo_path, current_branch))
is_git_pull_ran = True
self.run_git_unstash(repo_path)
else:
ColorPrint.warn( "The repository path [{0}] is not available".format(repo))
if is_git_pull_ran and p_status == 0:
if 'up to date' in output or 'Successfully rebased and updated' or 'Fast-forward' in output:
ColorPrint.blue_highlight("Pull for repository {0} finished successfully".format(repo))
else:
current_error = "Your repository {0} is broken, try to run 'git gc --prune=now' and 'git remote prune origin' to fix it".format(repo)
ColorPrint.err(current_error)
filename = 'errors.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
error_file = open(filename, append_write)
error_file.write(current_error + '\n')
error_file.close()
def _git_custom(self, git_command, repo):
ColorPrint.blue_highlight("Running custom git command on repository [{0}]".format(repo))
repo_path = self.path_to_workspace + os.sep + repo
if os.path.exists(repo_path):
self.run_command_and_collect_errors('cd {0};git {1}'.format(repo_path, git_command ))
else:
ColorPrint.warn( "The repository path [{0}] is not available".format(repo))
def run_git_stash(self, repo_path):
if os.path.exists(repo_path):
ColorPrint.blue_highlight( "Stashing the repository [{0}]".format(repo_path))
self.run_command_and_collect_errors('cd {0};git stash'.format(repo_path))
else:
ColorPrint.warn( "The repository path [{0}] is not available".format(repo_path))
def run_git_unstash(self, repo_path):
if os.path.exists(repo_path):
ColorPrint.blue_highlight("Unstashing the repository [{0}]".format(repo_path))
self.run_command_and_collect_errors('cd {0};git stash pop'.format(repo_path))
else:
ColorPrint.warn("The repository path [{0}] is not available".format(repo_path))
def _is_ready_to_pull(self, repo_path):
ColorPrint.blue_highlight("Checking repository status [{0}]".format(repo_path))
p_status, cmd_out, err = self.run_command_and_collect_errors('cd {0};git status -uno'.format(repo_path))
ColorPrint.info(cmd_out)
repo = os.path.basename(os.path.normpath(repo_path))
if 'Your branch is up-to-date' in str(cmd_out):
self.repo_status[repo] = True
else:
self.repo_status[repo] = False
if 'nothing to commit' in str(cmd_out):
return True
else:
return False
def _is_branch_up_to_date(self, repo_path):
ColorPrint.blue_highlight("Checking repository status [{0}]".format(repo_path))
self.run_command_and_collect_errors('cd {0};git remote update'.format(repo_path))
if self._is_ready_to_pull(repo_path):
return True
else:
repo = os.path.basename(os.path.normpath(repo_path))
if repo in self.repo_status and self.repo_status[repo]:
return True
else:
return False
@staticmethod
def print_list_avalable_versions(current_release):
base_dir = SncConfig().getstring('git_repo', 'base_dir');
if current_release is not None:
ColorPrint.blue_highlight('================' + current_release.upper() + '================')
EnvironmentBuilder.print_release_branch_per_repository(current_release)
exit(0)
for dir in os.listdir(base_dir):
if os.path.isdir(base_dir + os.sep + dir) and not dir.startswith('.'):
if EnvironmentBuilder.is_release_direcrory(dir):
ColorPrint.blue_highlight('================' + dir.upper() + '================')
EnvironmentBuilder.print_release_branch_per_repository(dir)
@staticmethod
def print_release_branch_per_repository(current_release):
base_dir = SncConfig().getstring('git_repo','base_dir');
list_of_repos = SncConfig().getlist('git_repo', 'repo');
list_of_messages = {}
brunches_d = {}
for repository in list_of_repos:
path_to_repository = base_dir + os.sep + current_release + os.sep + repository
if os.path.exists(path_to_repository + os.sep + '.git'):
cmd_get_branch = 'cd {0};git rev-parse --abbrev-ref HEAD'.format(path_to_repository)
status, current_brunch, error = EnvironmentBuilder.handle_command(cmd_get_branch, True, True, False)
current_brunch = current_brunch.rstrip();
current_message = "Release: [{0}] Repository: [{1}], Branch: [{2}]".rstrip().format(current_release, repository, current_brunch)
list_of_messages[current_message] = current_brunch
if current_brunch in brunches_d:
brunches_d[current_brunch] += 1
else:
brunches_d[current_brunch] = 0
if brunches_d.values():
max_brunch = max(brunches_d.values())
for message, branch in list_of_messages.iteritems():
if brunches_d[branch] < max_brunch:
ColorPrint.err(message)
else:
ColorPrint.info(message)
@staticmethod
def is_release_direcrory(release_dir):
base_dir = SncConfig().getstring('git_repo','base_dir');
full_path = base_dir + os.sep + release_dir
list_of_dirs = os.listdir(full_path)
list_of_repos = SncConfig().getlist('git_repo','repo');
return not set(list_of_repos).isdisjoint(list_of_dirs)
def print_execution_error_summary(self):
if not os.path.exists("errors.txt"):
exit(0)
with open('errors.txt', 'r') as error_file:
all_errors=error_file.read()
if all_errors:
ColorPrint.blue_highlight("Fix the following errors and run again")
ColorPrint.err('\n' + all_errors)
else:
ColorPrint.blue_highlight("Execution complited without errors")
@staticmethod
def handle_command(cmd, check_rc=True, get_output=True, print_output=False, print_cmd=False, background=False):
stdout_flag = None
if get_output:
stdout_flag = subprocess.PIPE
if print_cmd:
ColorPrint.info("[handle_command] running {0}".format(cmd))
p = subprocess.Popen(cmd,
stdout=stdout_flag,
stderr=subprocess.STDOUT,
shell=True)
out, err = p.communicate()
p_status = p.wait()
if check_rc:
if p_status != 0:
ColorPrint.err("[handle_command] failed executing: {0}".format(cmd))
ColorPrint.err(str(err) + ' ' + str(out))
else:
if print_output:
ColorPrint.info("[handle_command] Command output: {0} ".format(str(out)))
abort_on_error = SncConfig().getboolean('envbuilder', 'abort_on_error')
if abort_on_error and p_status != 0:
ColorPrint.err("EnvironmentBuilder: Execution aborted due to error[s]")
exit(1)
return p_status, out, err
if __name__ == '__main__':
#Font Name: Big
#http://patorjk.com/software/taag
ColorPrint.blue_highlight("""
# ______ ____ _ _ _ __ _ _
# | ____| | _ \ (_) | | | /_ | || |
# | |__ _ ____ _| |_) |_ _ _| | __| | ___ _ __ | | || |_
# | __| | '_ \ \ / / _ <| | | | | |/ _` |/ _ \ '__| | |__ _|
# | |____| | | \ V /| |_) | |_| | | | (_| | __/ | | |_ | |
# |______|_| |_|\_/ |____/ \__,_|_|_|\__,_|\___|_| |_(_)|_|
#""");
parser = argparse.ArgumentParser(prog='envbuilder.py',
description='Build environment tool',
formatter_class=RawTextHelpFormatter)
parser.add_argument('-clone', help='Clone defined repositories in the conf file to the specifed release directory', action="store_true")
parser.add_argument('-pull', help='run git pull for all or specified repositories \n ./envbuilder.py -pull -r release',action="store_true")
parser.add_argument('-sw', help='switch all repositories to relevant track \n /envbuilder.py -sw -t trackname -r release', action="store_true")
parser.add_argument('-t', help='track to switch', nargs='?',dest="track")
parser.add_argument('-r', help='release name', nargs='?', dest="release")
parser.add_argument('-copy', help='Copy local release to the new one. Useful for Intellij developers', action="store_true")
parser.add_argument('-nr', help='new release name', nargs='?', dest="new_release")
parser.add_argument('-commits', help='Show my release commits', action="store_true")
parser.add_argument('-sha', help='SHA key as part of commit message', action="store_true")
parser.add_argument('-days', help='Commit since days ago', nargs='?',dest="since_days")
parser.add_argument('-status', help='Status of the current local branches', action="store_true")
parser.add_argument('-mvn', help='Run maven install -DskipTests for the specified release', action="store_true")
parser.add_argument('-mvn_clean', help='Run maven clean for the specified release', action="store_true")
parser.add_argument('-git', help='Run custom git command', nargs='?',dest="git_command")
config = SncConfig()
default_release = config.getstring('envbuilder', 'release')
pl = PluginsLoader(os.environ[ENVB_PATH] + os.sep + "plugins")
plugins = pl.load_plugins()
for flag in plugins:
plugin = plugins[flag]
if plugin['active'] is True:
parser.add_argument('-{0}'.format(plugin['flag']),
help='{0}'.format(plugin['description']), action="store_true")
args = parser.parse_args()
# print str(args)
if not args.release:
ColorPrint.info("The -r [release] option is not provided, using default [{0}] from envbuilder.conf".format(default_release))
if not default_release:
ColorPrint.err('\n' + "The [release] parameter is not defined under [enbuilder] section in enbuilder.conf")
args.release = default_release
if args.status and args.release:
EnvironmentBuilder.print_list_avalable_versions(args.release)
exit(0)
if args.status:
EnvironmentBuilder.print_list_avalable_versions(None)
exit(0)
if args.mvn and args.release:
builder = EnvironmentBuilder(args.release)
builder.mvn_build()
builder.print_execution_error_summary()
exit(0)
if args.mvn_clean and args.release:
builder = EnvironmentBuilder(args.release)
builder.mvn_clean()
builder.print_execution_error_summary()
exit(0)
if args.commits and args.release:
builder = EnvironmentBuilder(args.release)
builder.show_my_commits(args.sha, args.since_days)
exit(0)
if args.copy and args.release and args.new_release:
builder = EnvironmentBuilder(args.release)
builder.copy_local_env(args.new_release)
builder.print_execution_error_summary()
exit(0)
if args.sw and args.release and args.track:
builder = EnvironmentBuilder(args.release)
builder.switch_track(args.track)
builder.print_execution_error_summary()
exit(0)
if args.pull and args.release:
builder = EnvironmentBuilder(args.release)
builder.run_git_pull()
builder.print_execution_error_summary()
exit(0)
if args.git_command and args.release:
builder = EnvironmentBuilder(args.release)
builder.run_git_custom(args.git_command)
builder.print_execution_error_summary()
exit(0)
if args.clone and args.release:
builder = EnvironmentBuilder(args.release)
builder.clone_env()
if args.track:
builder.switch_track(args.track)
builder.print_execution_error_summary()
exit(0)
for option in plugins:
try:
current_arg = getattr(args, option)
if current_arg is True:
plugin = plugins[option]
builder = EnvironmentBuilder(args.release)
commands_to_run = plugin['commands']
if plugin['type'] == 'group':
plugins_to_run = plugin['plugins']
for run_plugin_flag in plugins_to_run:
run_plugin = plugins[run_plugin_flag]
commands_to_run.extend(run_plugin['commands'])
is_background = False
if plugin['background'] is True:
is_background = True
last_command = commands_to_run.pop()
final_status, final_output, final_error = builder.run_commands_in_current_release(commands_to_run)
if is_background:
builder.run_command_in_background(last_command)
if final_output is None:
final_output = ''
if final_error is None:
final_error = ''
if plugin['notify'] is True:
notifier = NotificationManager(None, None, None)
if final_status is True:
command_status = 'completed successfully'
final_result = final_output
else:
command_status = 'execution failed'
final_result = final_output + final_error
notif_msg = "Command: [{0}] Status: {1} Result: {2}".format(plugin['description'],
command_status, final_result)
notifier.send_notification(final_status,plugin['name'], notif_msg)
exit(0)
except AttributeError:
continue
else:
parser.print_help()
| true | true |
f72a3383995074634d5dafb504c727c501dbf175 | 3,484 | py | Python | tests/manage/rgw/test_bucket_deletion.py | prsurve/ocs-ci | a8e229755e1f9d43c8c71e5ba693cb14bfb38aed | [
"MIT"
] | null | null | null | tests/manage/rgw/test_bucket_deletion.py | prsurve/ocs-ci | a8e229755e1f9d43c8c71e5ba693cb14bfb38aed | [
"MIT"
] | null | null | null | tests/manage/rgw/test_bucket_deletion.py | prsurve/ocs-ci | a8e229755e1f9d43c8c71e5ba693cb14bfb38aed | [
"MIT"
] | null | null | null | import logging
import botocore
import pytest
from flaky import flaky
from ocs_ci.ocs.bucket_utils import retrieve_test_objects_to_pod, sync_object_directory
from ocs_ci.framework import config
from ocs_ci.framework.pytest_customization.marks import acceptance, tier1, tier3
from ocs_ci.ocs.exceptions import CommandFailed
from ocs_ci.ocs.ocp import OCP
from ocs_ci.ocs.resources.objectbucket import OBC
logger = logging.getLogger(__name__)
class TestBucketDeletion:
"""
Test deletion of RGW buckets
"""
@pytest.mark.parametrize(
argnames="amount,interface",
argvalues=[
pytest.param(
*[3, "RGW-OC"],
marks=[tier1, acceptance, pytest.mark.polarion_id("2248")],
),
],
)
def test_bucket_delete(self, rgw_bucket_factory, amount, interface):
"""
Test deletion of buckets using OC commands
"""
for bucket in rgw_bucket_factory(amount, interface):
logger.info(f"Deleting bucket: {bucket.name}")
bucket.delete()
@pytest.mark.parametrize(
argnames="interface",
argvalues=[
pytest.param(
*["RGW-OC"], marks=[tier1, pytest.mark.polarion_id("OCS-2249")]
),
],
)
@flaky
def test_bucket_delete_with_objects(
self, rgw_bucket_factory, interface, awscli_pod
):
"""
Negative test with deletion of bucket has objects stored in.
"""
bucket = rgw_bucket_factory(1, interface)[0]
bucketname = bucket.name
obc_obj = OBC(bucketname)
try:
data_dir = "/data"
full_object_path = f"s3://{bucketname}"
retrieve_test_objects_to_pod(awscli_pod, data_dir)
sync_object_directory(awscli_pod, data_dir, full_object_path, obc_obj)
logger.info(f"Deleting bucket: {bucketname}")
if interface == "S3":
try:
s3_del = obc_obj.s3_resource.Bucket(bucketname).delete()
assert (
not s3_del
), "Unexpected issue: Successfully deleted a bucket containing objects via S3"
except botocore.exceptions.ClientError as err:
assert "BucketNotEmpty" in str(
err
), "Couldn't verify delete non-empty OBC with s3"
logger.info(f"Delete non-empty OBC {bucketname} failed as expected")
finally:
bucket.delete()
@pytest.mark.parametrize(
argnames="interface",
argvalues=[
pytest.param(
*["RGW-OC"], marks=[tier3, pytest.mark.polarion_id("OCS-2244")]
),
],
)
def test_nonexist_bucket_delete(self, interface):
"""
Negative test with deletion of a non-existent OBC.
"""
name = "test_nonexist_bucket_name"
if interface == "RGW-OC":
try:
oc_del = OCP(
kind="obc", namespace=config.ENV_DATA["cluster_namespace"]
).delete(resource_name=name)
assert oc_del, "Unexpected oc delete non-exist OBC succeed"
except CommandFailed as err:
assert "NotFound" in str(
err
), "Couldn't verify delete non-exist OBC with oc"
logger.info(f"Delete non-exist OBC {name} failed as expected")
| 34.156863 | 98 | 0.581803 | import logging
import botocore
import pytest
from flaky import flaky
from ocs_ci.ocs.bucket_utils import retrieve_test_objects_to_pod, sync_object_directory
from ocs_ci.framework import config
from ocs_ci.framework.pytest_customization.marks import acceptance, tier1, tier3
from ocs_ci.ocs.exceptions import CommandFailed
from ocs_ci.ocs.ocp import OCP
from ocs_ci.ocs.resources.objectbucket import OBC
logger = logging.getLogger(__name__)
class TestBucketDeletion:
@pytest.mark.parametrize(
argnames="amount,interface",
argvalues=[
pytest.param(
*[3, "RGW-OC"],
marks=[tier1, acceptance, pytest.mark.polarion_id("2248")],
),
],
)
def test_bucket_delete(self, rgw_bucket_factory, amount, interface):
for bucket in rgw_bucket_factory(amount, interface):
logger.info(f"Deleting bucket: {bucket.name}")
bucket.delete()
@pytest.mark.parametrize(
argnames="interface",
argvalues=[
pytest.param(
*["RGW-OC"], marks=[tier1, pytest.mark.polarion_id("OCS-2249")]
),
],
)
@flaky
def test_bucket_delete_with_objects(
self, rgw_bucket_factory, interface, awscli_pod
):
bucket = rgw_bucket_factory(1, interface)[0]
bucketname = bucket.name
obc_obj = OBC(bucketname)
try:
data_dir = "/data"
full_object_path = f"s3://{bucketname}"
retrieve_test_objects_to_pod(awscli_pod, data_dir)
sync_object_directory(awscli_pod, data_dir, full_object_path, obc_obj)
logger.info(f"Deleting bucket: {bucketname}")
if interface == "S3":
try:
s3_del = obc_obj.s3_resource.Bucket(bucketname).delete()
assert (
not s3_del
), "Unexpected issue: Successfully deleted a bucket containing objects via S3"
except botocore.exceptions.ClientError as err:
assert "BucketNotEmpty" in str(
err
), "Couldn't verify delete non-empty OBC with s3"
logger.info(f"Delete non-empty OBC {bucketname} failed as expected")
finally:
bucket.delete()
@pytest.mark.parametrize(
argnames="interface",
argvalues=[
pytest.param(
*["RGW-OC"], marks=[tier3, pytest.mark.polarion_id("OCS-2244")]
),
],
)
def test_nonexist_bucket_delete(self, interface):
name = "test_nonexist_bucket_name"
if interface == "RGW-OC":
try:
oc_del = OCP(
kind="obc", namespace=config.ENV_DATA["cluster_namespace"]
).delete(resource_name=name)
assert oc_del, "Unexpected oc delete non-exist OBC succeed"
except CommandFailed as err:
assert "NotFound" in str(
err
), "Couldn't verify delete non-exist OBC with oc"
logger.info(f"Delete non-exist OBC {name} failed as expected")
| true | true |
f72a33b918735569e106f2221c7a10a6e1392d92 | 1,864 | py | Python | tests/test_transforms_resize_modulo_pad_crop.py | civodlu/trw | b9a1cf045f61d6df9c65c014ef63b4048972dcdc | [
"MIT"
] | 3 | 2019-07-04T01:20:41.000Z | 2020-01-27T02:36:12.000Z | tests/test_transforms_resize_modulo_pad_crop.py | civodlu/trw | b9a1cf045f61d6df9c65c014ef63b4048972dcdc | [
"MIT"
] | null | null | null | tests/test_transforms_resize_modulo_pad_crop.py | civodlu/trw | b9a1cf045f61d6df9c65c014ef63b4048972dcdc | [
"MIT"
] | 2 | 2020-10-19T13:46:06.000Z | 2021-12-27T02:18:10.000Z | import unittest
import trw
import torch
import numpy as np
class TestTransformsResizeModuloPadCrop(unittest.TestCase):
def test_crop_mode_torch(self):
batch = {
'images': torch.rand([2, 3, 64, 64], dtype=torch.float32)
}
tfm = trw.transforms.TransformResizeModuloCropPad(60)
transformed = tfm(batch)
assert transformed['images'].shape == (2, 3, 60, 60)
def test_crop_mode_torch_multiples(self):
# test with multiple of `multiples_of` shape
batch = {
'images': torch.rand([2, 3, 64, 64], dtype=torch.float32)
}
tfm = trw.transforms.TransformResizeModuloCropPad(10)
transformed = tfm(batch)
assert transformed['images'].shape == (2, 3, 60, 60)
def test_crop_mode_torch_different_shape(self):
batch = {
'images': torch.rand([2, 3, 64, 64], dtype=torch.float32),
'images2': torch.rand([2, 1, 64, 64], dtype=torch.float32)
}
batch['images'][0, 0, 32, 32] = 42.0
batch['images2'][0, 0, 32, 32] = 42.0
tfm = trw.transforms.TransformResizeModuloCropPad(60)
transformed = tfm(batch)
# make sure we can handle different shapes of the same dimension
assert transformed['images'].shape == (2, 3, 60, 60)
assert transformed['images2'].shape == (2, 1, 60, 60)
# make sure the crop/pad are the same for the different images
indices = np.where(batch['images'].numpy() == 42)
assert (batch['images2'][indices] == 42.0).all()
def test_pad_mode_torch(self):
batch = {
'images': torch.rand([2, 3, 65, 65], dtype=torch.float32)
}
tfm = trw.transforms.TransformResizeModuloCropPad(32, mode='pad')
transformed = tfm(batch)
assert transformed['images'].shape == (2, 3, 96, 96)
| 34.518519 | 73 | 0.603541 | import unittest
import trw
import torch
import numpy as np
class TestTransformsResizeModuloPadCrop(unittest.TestCase):
def test_crop_mode_torch(self):
batch = {
'images': torch.rand([2, 3, 64, 64], dtype=torch.float32)
}
tfm = trw.transforms.TransformResizeModuloCropPad(60)
transformed = tfm(batch)
assert transformed['images'].shape == (2, 3, 60, 60)
def test_crop_mode_torch_multiples(self):
batch = {
'images': torch.rand([2, 3, 64, 64], dtype=torch.float32)
}
tfm = trw.transforms.TransformResizeModuloCropPad(10)
transformed = tfm(batch)
assert transformed['images'].shape == (2, 3, 60, 60)
def test_crop_mode_torch_different_shape(self):
batch = {
'images': torch.rand([2, 3, 64, 64], dtype=torch.float32),
'images2': torch.rand([2, 1, 64, 64], dtype=torch.float32)
}
batch['images'][0, 0, 32, 32] = 42.0
batch['images2'][0, 0, 32, 32] = 42.0
tfm = trw.transforms.TransformResizeModuloCropPad(60)
transformed = tfm(batch)
assert transformed['images'].shape == (2, 3, 60, 60)
assert transformed['images2'].shape == (2, 1, 60, 60)
indices = np.where(batch['images'].numpy() == 42)
assert (batch['images2'][indices] == 42.0).all()
def test_pad_mode_torch(self):
batch = {
'images': torch.rand([2, 3, 65, 65], dtype=torch.float32)
}
tfm = trw.transforms.TransformResizeModuloCropPad(32, mode='pad')
transformed = tfm(batch)
assert transformed['images'].shape == (2, 3, 96, 96)
| true | true |
f72a348b9cd34cfd35f617a68b5a5d79dd7ba065 | 1,758 | py | Python | biokit/services/coding_sequences/gc_content_second_position.py | JLSteenwyk/BioKIT | 9ca31d8003dc845bf56b2c56c87820c0b05021c4 | [
"MIT"
] | 8 | 2021-10-03T21:08:33.000Z | 2021-12-02T17:15:32.000Z | biokit/services/coding_sequences/gc_content_second_position.py | JLSteenwyk/BioKIT | 9ca31d8003dc845bf56b2c56c87820c0b05021c4 | [
"MIT"
] | null | null | null | biokit/services/coding_sequences/gc_content_second_position.py | JLSteenwyk/BioKIT | 9ca31d8003dc845bf56b2c56c87820c0b05021c4 | [
"MIT"
] | 5 | 2021-10-05T06:25:03.000Z | 2022-01-04T11:01:09.000Z | import re
from .base import CodingSequence
from ...helpers.files import read_and_parse_fasta_seqio
class GCContentSecondPosition(CodingSequence):
def __init__(self, args) -> None:
super().__init__(**self.process_args(args))
def run(self):
# create biopython object of sequences
records = read_and_parse_fasta_seqio(self.fasta)
if self.verbose:
for record in records:
second_position_char = []
second_position_char = self.get_second_position_char(
record, second_position_char
)
_, matches = self.find_matches("".join(second_position_char))
print(
f"{record.id}\t{round(len(matches)/len(second_position_char), 4)}"
)
else:
second_position_char = []
for record in records:
second_position_char = []
second_position_char = self.get_second_position_char(
record, second_position_char
)
_, matches = self.find_matches("".join(second_position_char))
print(f"{round(len(matches)/len(second_position_char), 4)}")
def process_args(self, args):
return dict(fasta=args.fasta, verbose=args.verbose)
def find_matches(self, seq: str):
regex_pattern = re.compile("[GgCc]")
matches = regex_pattern.findall(seq)
return seq, matches
def get_second_position_char(self, record, second_position_char: list):
length_of_coding_seq = len(record._seq)
for i in range(0, length_of_coding_seq, 3):
second_position_char.append(record._seq[i:i + 3][1])
return second_position_char
| 32.555556 | 86 | 0.612628 | import re
from .base import CodingSequence
from ...helpers.files import read_and_parse_fasta_seqio
class GCContentSecondPosition(CodingSequence):
def __init__(self, args) -> None:
super().__init__(**self.process_args(args))
def run(self):
records = read_and_parse_fasta_seqio(self.fasta)
if self.verbose:
for record in records:
second_position_char = []
second_position_char = self.get_second_position_char(
record, second_position_char
)
_, matches = self.find_matches("".join(second_position_char))
print(
f"{record.id}\t{round(len(matches)/len(second_position_char), 4)}"
)
else:
second_position_char = []
for record in records:
second_position_char = []
second_position_char = self.get_second_position_char(
record, second_position_char
)
_, matches = self.find_matches("".join(second_position_char))
print(f"{round(len(matches)/len(second_position_char), 4)}")
def process_args(self, args):
return dict(fasta=args.fasta, verbose=args.verbose)
def find_matches(self, seq: str):
regex_pattern = re.compile("[GgCc]")
matches = regex_pattern.findall(seq)
return seq, matches
def get_second_position_char(self, record, second_position_char: list):
length_of_coding_seq = len(record._seq)
for i in range(0, length_of_coding_seq, 3):
second_position_char.append(record._seq[i:i + 3][1])
return second_position_char
| true | true |
f72a34a439b3448174e70d31de729aeadbb9686e | 187 | py | Python | PCTC/2018 R2/Q5.py | object-oriented-human/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | 1 | 2022-02-21T15:43:01.000Z | 2022-02-21T15:43:01.000Z | PCTC/2018 R2/Q5.py | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | PCTC/2018 R2/Q5.py | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | d = dict()
l = []
for i in range(int(input())):
x, y = input().split()
d[y] = x
l.append(y)
l.sort()
for i in range(len(l)):
if d[l[i]] == "Percy":
print(i+1)
break
| 13.357143 | 29 | 0.481283 | d = dict()
l = []
for i in range(int(input())):
x, y = input().split()
d[y] = x
l.append(y)
l.sort()
for i in range(len(l)):
if d[l[i]] == "Percy":
print(i+1)
break
| true | true |
f72a34a70be9391c0ff557e2faf72cca8765883e | 2,747 | py | Python | challenge.py | DaneliaSanchz/challenge-python-07 | 73b11936bf8fff81f99c271b2bf1c244706af207 | [
"MIT"
] | null | null | null | challenge.py | DaneliaSanchz/challenge-python-07 | 73b11936bf8fff81f99c271b2bf1c244706af207 | [
"MIT"
] | null | null | null | challenge.py | DaneliaSanchz/challenge-python-07 | 73b11936bf8fff81f99c271b2bf1c244706af207 | [
"MIT"
] | null | null | null | DATA = [
{
'name': 'Facundo',
'age': 72,
'organization': 'Platzi',
'position': 'Technical Mentor',
'language': 'python',
},
{
'name': 'Luisana',
'age': 33,
'organization': 'Globant',
'position': 'UX Designer',
'language': 'javascript',
},
{
'name': 'Héctor',
'age': 19,
'organization': 'Platzi',
'position': 'Associate',
'language': 'ruby',
},
{
'name': 'Gabriel',
'age': 20,
'organization': 'Platzi',
'position': 'Associate',
'language': 'javascript',
},
{
'name': 'Mariandrea',
'age': 30,
'organization': 'Platzi',
'position': 'QA Manager',
'language': 'java',
},
{
'name': 'Karo',
'age': 23,
'organization': 'Everis',
'position': 'Backend Developer',
'language': 'python',
},
{
'name': 'Ariel',
'age': 32,
'organization': 'Rappi',
'position': 'Support',
'language': '',
},
{
'name': 'Juan',
'age': 17,
'organization': '',
'position': 'Student',
'language': 'go',
},
{
'name': 'Pablo',
'age': 32,
'organization': 'Master',
'position': 'Human Resources Manager',
'language': 'python',
},
{
'name': 'Lorena',
'age': 56,
'organization': 'Python Organization',
'position': 'Language Maker',
'language': 'python',
},
]
def homeless(data):
person = data.copy()
if data['organization'] == '':
person['homeless'] = True
else:
person['homeless'] = False
return person
def old(data):
person = data.copy()
if data['age'] > 30:
person['old'] = True
else:
person['old'] = 'False'
return person
def run():
all_python_devs = list(filter(lambda dev: dev['language'] == 'python' , DATA))
all_Platzi_workers = list(filter(lambda worker: worker['organization'] == 'Platzi', DATA))
adults = list(filter(lambda person: person['age'] > 18, DATA))
workers = list(map(homeless, DATA))
old_people = list(map(old, DATA))
print('Python devs: ')
for dev in all_python_devs:
print(dev['name'])
print('\n\n')
print('Platzi workers: ')
for worker in all_Platzi_workers:
print(worker['name'])
print('\n\n')
print('Adults: ')
for adult in adults:
print(adult['name'])
print('\n\n')
print(workers)
print('\n\n')
print(old_people)
print('\n\n')
# Remember: when possible, use lambdas
if __name__ == '__main__':
run()
| 21.801587 | 94 | 0.486713 | DATA = [
{
'name': 'Facundo',
'age': 72,
'organization': 'Platzi',
'position': 'Technical Mentor',
'language': 'python',
},
{
'name': 'Luisana',
'age': 33,
'organization': 'Globant',
'position': 'UX Designer',
'language': 'javascript',
},
{
'name': 'Héctor',
'age': 19,
'organization': 'Platzi',
'position': 'Associate',
'language': 'ruby',
},
{
'name': 'Gabriel',
'age': 20,
'organization': 'Platzi',
'position': 'Associate',
'language': 'javascript',
},
{
'name': 'Mariandrea',
'age': 30,
'organization': 'Platzi',
'position': 'QA Manager',
'language': 'java',
},
{
'name': 'Karo',
'age': 23,
'organization': 'Everis',
'position': 'Backend Developer',
'language': 'python',
},
{
'name': 'Ariel',
'age': 32,
'organization': 'Rappi',
'position': 'Support',
'language': '',
},
{
'name': 'Juan',
'age': 17,
'organization': '',
'position': 'Student',
'language': 'go',
},
{
'name': 'Pablo',
'age': 32,
'organization': 'Master',
'position': 'Human Resources Manager',
'language': 'python',
},
{
'name': 'Lorena',
'age': 56,
'organization': 'Python Organization',
'position': 'Language Maker',
'language': 'python',
},
]
def homeless(data):
person = data.copy()
if data['organization'] == '':
person['homeless'] = True
else:
person['homeless'] = False
return person
def old(data):
person = data.copy()
if data['age'] > 30:
person['old'] = True
else:
person['old'] = 'False'
return person
def run():
all_python_devs = list(filter(lambda dev: dev['language'] == 'python' , DATA))
all_Platzi_workers = list(filter(lambda worker: worker['organization'] == 'Platzi', DATA))
adults = list(filter(lambda person: person['age'] > 18, DATA))
workers = list(map(homeless, DATA))
old_people = list(map(old, DATA))
print('Python devs: ')
for dev in all_python_devs:
print(dev['name'])
print('\n\n')
print('Platzi workers: ')
for worker in all_Platzi_workers:
print(worker['name'])
print('\n\n')
print('Adults: ')
for adult in adults:
print(adult['name'])
print('\n\n')
print(workers)
print('\n\n')
print(old_people)
print('\n\n')
if __name__ == '__main__':
run()
| true | true |
f72a34fcaec6d61776028925ec6417f22ff909c9 | 30,977 | py | Python | flask/lib/python3.4/site-packages/babel/messages/catalog.py | ddayguerrero/blogme | e6ee6a47310c382648eefd96634630c3bceb864f | [
"MIT"
] | null | null | null | flask/lib/python3.4/site-packages/babel/messages/catalog.py | ddayguerrero/blogme | e6ee6a47310c382648eefd96634630c3bceb864f | [
"MIT"
] | null | null | null | flask/lib/python3.4/site-packages/babel/messages/catalog.py | ddayguerrero/blogme | e6ee6a47310c382648eefd96634630c3bceb864f | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
babel.messages.catalog
~~~~~~~~~~~~~~~~~~~~~~
Data structures for message catalogs.
:copyright: (c) 2013 by the Babel Team.
:license: BSD, see LICENSE for more details.
"""
import re
import time
from cgi import parse_header
from datetime import datetime, time as time_
from difflib import get_close_matches
from email import message_from_string
from copy import copy
from babel import __version__ as VERSION
from babel.core import Locale
from babel.dates import format_datetime
from babel.messages.plurals import get_plural
from babel.util import odict, distinct, LOCALTZ, FixedOffsetTimezone
from babel._compat import string_types, number_types, PY2, cmp
__all__ = ['Message', 'Catalog', 'TranslationError']
PYTHON_FORMAT = re.compile(r'''(?x)
\%
(?:\(([\w]*)\))?
(
[-#0\ +]?(?:\*|[\d]+)?
(?:\.(?:\*|[\d]+))?
[hlL]?
)
([diouxXeEfFgGcrs%])
''')
def _parse_datetime_header(value):
match = re.match(r'^(?P<datetime>.*?)(?P<tzoffset>[+-]\d{4})?$', value)
tt = time.strptime(match.group('datetime'), '%Y-%m-%d %H:%M')
ts = time.mktime(tt)
dt = datetime.fromtimestamp(ts)
# Separate the offset into a sign component, hours, and # minutes
tzoffset = match.group('tzoffset')
if tzoffset is not None:
plus_minus_s, rest = tzoffset[0], tzoffset[1:]
hours_offset_s, mins_offset_s = rest[:2], rest[2:]
# Make them all integers
plus_minus = int(plus_minus_s + '1')
hours_offset = int(hours_offset_s)
mins_offset = int(mins_offset_s)
# Calculate net offset
net_mins_offset = hours_offset * 60
net_mins_offset += mins_offset
net_mins_offset *= plus_minus
# Create an offset object
tzoffset = FixedOffsetTimezone(net_mins_offset)
# Store the offset in a datetime object
dt = dt.replace(tzinfo=tzoffset)
return dt
class Message(object):
"""Representation of a single message in a catalog."""
def __init__(self, id, string=u'', locations=(), flags=(), auto_comments=(),
user_comments=(), previous_id=(), lineno=None, context=None):
"""Create the message object.
:param id: the message ID, or a ``(singular, plural)`` tuple for
pluralizable messages
:param string: the translated message string, or a
``(singular, plural)`` tuple for pluralizable messages
:param locations: a sequence of ``(filenname, lineno)`` tuples
:param flags: a set or sequence of flags
:param auto_comments: a sequence of automatic comments for the message
:param user_comments: a sequence of user comments for the message
:param previous_id: the previous message ID, or a ``(singular, plural)``
tuple for pluralizable messages
:param lineno: the line number on which the msgid line was found in the
PO file, if any
:param context: the message context
"""
self.id = id
if not string and self.pluralizable:
string = (u'', u'')
self.string = string
self.locations = list(distinct(locations))
self.flags = set(flags)
if id and self.python_format:
self.flags.add('python-format')
else:
self.flags.discard('python-format')
self.auto_comments = list(distinct(auto_comments))
self.user_comments = list(distinct(user_comments))
if isinstance(previous_id, string_types):
self.previous_id = [previous_id]
else:
self.previous_id = list(previous_id)
self.lineno = lineno
self.context = context
def __repr__(self):
return '<%s %r (flags: %r)>' % (type(self).__name__, self.id,
list(self.flags))
def __cmp__(self, obj):
"""Compare Messages, taking into account plural ids"""
def values_to_compare():
if isinstance(obj, Message):
plural = self.pluralizable
obj_plural = obj.pluralizable
if plural and obj_plural:
return self.id[0], obj.id[0]
elif plural:
return self.id[0], obj.id
elif obj_plural:
return self.id, obj.id[0]
return self.id, obj.id
this, other = values_to_compare()
return cmp(this, other)
def __gt__(self, other):
return self.__cmp__(other) > 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __ge__(self, other):
return self.__cmp__(other) >= 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def clone(self):
return Message(*map(copy, (self.id, self.string, self.locations,
self.flags, self.auto_comments,
self.user_comments, self.previous_id,
self.lineno, self.context)))
def check(self, catalog=None):
"""Run various validation checks on the message. Some validations
are only performed if the catalog is provided. This method returns
a sequence of `TranslationError` objects.
:rtype: ``iterator``
:param catalog: A catalog instance that is passed to the checkers
:see: `Catalog.check` for a way to perform checks for all messages
in a catalog.
"""
from babel.messages.checkers import checkers
errors = []
for checker in checkers:
try:
checker(catalog, self)
except TranslationError as e:
errors.append(e)
return errors
@property
def fuzzy(self):
"""Whether the translation is fuzzy.
>>> Message('foo').fuzzy
False
>>> msg = Message('foo', 'foo', flags=['fuzzy'])
>>> msg.fuzzy
True
>>> msg
<Message 'foo' (flags: ['fuzzy'])>
:type: `bool`"""
return 'fuzzy' in self.flags
@property
def pluralizable(self):
"""Whether the message is plurizable.
>>> Message('foo').pluralizable
False
>>> Message(('foo', 'bar')).pluralizable
True
:type: `bool`"""
return isinstance(self.id, (list, tuple))
@property
def python_format(self):
"""Whether the message contains Python-style parameters.
>>> Message('foo %(name)s bar').python_format
True
>>> Message(('foo %(name)s', 'foo %(name)s')).python_format
True
:type: `bool`"""
ids = self.id
if not isinstance(ids, (list, tuple)):
ids = [ids]
return any(PYTHON_FORMAT.search(id) for id in ids)
class TranslationError(Exception):
"""Exception thrown by translation checkers when invalid message
translations are encountered."""
DEFAULT_HEADER = u"""\
# Translations template for PROJECT.
# Copyright (C) YEAR ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#"""
if PY2:
def _parse_header(header_string):
# message_from_string only works for str, not for unicode
headers = message_from_string(header_string.encode('utf8'))
decoded_headers = {}
for name, value in headers.items():
name = name.decode('utf8')
value = value.decode('utf8')
decoded_headers[name] = value
return decoded_headers
else:
_parse_header = message_from_string
class Catalog(object):
"""Representation of a message catalog."""
def __init__(self, locale=None, domain=None, header_comment=DEFAULT_HEADER,
project=None, version=None, copyright_holder=None,
msgid_bugs_address=None, creation_date=None,
revision_date=None, last_translator=None, language_team=None,
charset=None, fuzzy=True):
"""Initialize the catalog object.
:param locale: the locale identifier or `Locale` object, or `None`
if the catalog is not bound to a locale (which basically
means it's a template)
:param domain: the message domain
:param header_comment: the header comment as string, or `None` for the
default header
:param project: the project's name
:param version: the project's version
:param copyright_holder: the copyright holder of the catalog
:param msgid_bugs_address: the email address or URL to submit bug
reports to
:param creation_date: the date the catalog was created
:param revision_date: the date the catalog was revised
:param last_translator: the name and email of the last translator
:param language_team: the name and email of the language team
:param charset: the encoding to use in the output (defaults to utf-8)
:param fuzzy: the fuzzy bit on the catalog header
"""
self.domain = domain
if locale:
locale = Locale.parse(locale)
self.locale = locale
self._header_comment = header_comment
self._messages = odict()
self.project = project or 'PROJECT'
self.version = version or 'VERSION'
self.copyright_holder = copyright_holder or 'ORGANIZATION'
self.msgid_bugs_address = msgid_bugs_address or 'EMAIL@ADDRESS'
self.last_translator = last_translator or 'FULL NAME <EMAIL@ADDRESS>'
"""Name and email address of the last translator."""
self.language_team = language_team or 'LANGUAGE <LL@li.org>'
"""Name and email address of the language team."""
self.charset = charset or 'utf-8'
if creation_date is None:
creation_date = datetime.now(LOCALTZ)
elif isinstance(creation_date, datetime) and not creation_date.tzinfo:
creation_date = creation_date.replace(tzinfo=LOCALTZ)
self.creation_date = creation_date
if revision_date is None:
revision_date = 'YEAR-MO-DA HO:MI+ZONE'
elif isinstance(revision_date, datetime) and not revision_date.tzinfo:
revision_date = revision_date.replace(tzinfo=LOCALTZ)
self.revision_date = revision_date
self.fuzzy = fuzzy
self.obsolete = odict() # Dictionary of obsolete messages
self._num_plurals = None
self._plural_expr = None
def _get_header_comment(self):
comment = self._header_comment
year = datetime.now(LOCALTZ).strftime('%Y')
if hasattr(self.revision_date, 'strftime'):
year = self.revision_date.strftime('%Y')
comment = comment.replace('PROJECT', self.project) \
.replace('VERSION', self.version) \
.replace('YEAR', year) \
.replace('ORGANIZATION', self.copyright_holder)
if self.locale:
comment = comment.replace('Translations template', '%s translations'
% self.locale.english_name)
return comment
def _set_header_comment(self, string):
self._header_comment = string
header_comment = property(_get_header_comment, _set_header_comment, doc="""\
The header comment for the catalog.
>>> catalog = Catalog(project='Foobar', version='1.0',
... copyright_holder='Foo Company')
>>> print(catalog.header_comment) #doctest: +ELLIPSIS
# Translations template for Foobar.
# Copyright (C) ... Foo Company
# This file is distributed under the same license as the Foobar project.
# FIRST AUTHOR <EMAIL@ADDRESS>, ....
#
The header can also be set from a string. Any known upper-case variables
will be replaced when the header is retrieved again:
>>> catalog = Catalog(project='Foobar', version='1.0',
... copyright_holder='Foo Company')
>>> catalog.header_comment = '''\\
... # The POT for my really cool PROJECT project.
... # Copyright (C) 1990-2003 ORGANIZATION
... # This file is distributed under the same license as the PROJECT
... # project.
... #'''
>>> print(catalog.header_comment)
# The POT for my really cool Foobar project.
# Copyright (C) 1990-2003 Foo Company
# This file is distributed under the same license as the Foobar
# project.
#
:type: `unicode`
""")
def _get_mime_headers(self):
headers = []
headers.append(('Project-Id-Version',
'%s %s' % (self.project, self.version)))
headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address))
headers.append(('POT-Creation-Date',
format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ',
locale='en')))
if isinstance(self.revision_date, (datetime, time_) + number_types):
headers.append(('PO-Revision-Date',
format_datetime(self.revision_date,
'yyyy-MM-dd HH:mmZ', locale='en')))
else:
headers.append(('PO-Revision-Date', self.revision_date))
headers.append(('Last-Translator', self.last_translator))
if self.locale is not None:
headers.append(('Language', str(self.locale)))
if (self.locale is not None) and ('LANGUAGE' in self.language_team):
headers.append(('Language-Team',
self.language_team.replace('LANGUAGE',
str(self.locale))))
else:
headers.append(('Language-Team', self.language_team))
if self.locale is not None:
headers.append(('Plural-Forms', self.plural_forms))
headers.append(('MIME-Version', '1.0'))
headers.append(('Content-Type',
'text/plain; charset=%s' % self.charset))
headers.append(('Content-Transfer-Encoding', '8bit'))
headers.append(('Generated-By', 'Babel %s\n' % VERSION))
return headers
def _set_mime_headers(self, headers):
for name, value in headers:
name = name.lower()
if name == 'project-id-version':
parts = value.split(' ')
self.project = u' '.join(parts[:-1])
self.version = parts[-1]
elif name == 'report-msgid-bugs-to':
self.msgid_bugs_address = value
elif name == 'last-translator':
self.last_translator = value
elif name == 'language-team':
self.language_team = value
elif name == 'content-type':
mimetype, params = parse_header(value)
if 'charset' in params:
self.charset = params['charset'].lower()
elif name == 'plural-forms':
_, params = parse_header(' ;' + value)
self._num_plurals = int(params.get('nplurals', 2))
self._plural_expr = params.get('plural', '(n != 1)')
elif name == 'pot-creation-date':
self.creation_date = _parse_datetime_header(value)
elif name == 'po-revision-date':
# Keep the value if it's not the default one
if 'YEAR' not in value:
self.revision_date = _parse_datetime_header(value)
mime_headers = property(_get_mime_headers, _set_mime_headers, doc="""\
The MIME headers of the catalog, used for the special ``msgid ""`` entry.
The behavior of this property changes slightly depending on whether a locale
is set or not, the latter indicating that the catalog is actually a template
for actual translations.
Here's an example of the output for such a catalog template:
>>> from babel.dates import UTC
>>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
>>> catalog = Catalog(project='Foobar', version='1.0',
... creation_date=created)
>>> for name, value in catalog.mime_headers:
... print('%s: %s' % (name, value))
Project-Id-Version: Foobar 1.0
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 1990-04-01 15:30+0000
PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
Last-Translator: FULL NAME <EMAIL@ADDRESS>
Language-Team: LANGUAGE <LL@li.org>
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel ...
And here's an example of the output when the locale is set:
>>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
>>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
... creation_date=created, revision_date=revised,
... last_translator='John Doe <jd@example.com>',
... language_team='de_DE <de@example.com>')
>>> for name, value in catalog.mime_headers:
... print('%s: %s' % (name, value))
Project-Id-Version: Foobar 1.0
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 1990-04-01 15:30+0000
PO-Revision-Date: 1990-08-03 12:00+0000
Last-Translator: John Doe <jd@example.com>
Language: de_DE
Language-Team: de_DE <de@example.com>
Plural-Forms: nplurals=2; plural=(n != 1)
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel ...
:type: `list`
""")
@property
def num_plurals(self):
"""The number of plurals used by the catalog or locale.
>>> Catalog(locale='en').num_plurals
2
>>> Catalog(locale='ga').num_plurals
3
:type: `int`"""
if self._num_plurals is None:
num = 2
if self.locale:
num = get_plural(self.locale)[0]
self._num_plurals = num
return self._num_plurals
@property
def plural_expr(self):
"""The plural expression used by the catalog or locale.
>>> Catalog(locale='en').plural_expr
'(n != 1)'
>>> Catalog(locale='ga').plural_expr
'(n==1 ? 0 : n==2 ? 1 : 2)'
:type: `string_types`"""
if self._plural_expr is None:
expr = '(n != 1)'
if self.locale:
expr = get_plural(self.locale)[1]
self._plural_expr = expr
return self._plural_expr
@property
def plural_forms(self):
"""Return the plural forms declaration for the locale.
>>> Catalog(locale='en').plural_forms
'nplurals=2; plural=(n != 1)'
>>> Catalog(locale='pt_BR').plural_forms
'nplurals=2; plural=(n > 1)'
:type: `str`"""
return 'nplurals=%s; plural=%s' % (self.num_plurals, self.plural_expr)
def __contains__(self, id):
"""Return whether the catalog has a message with the specified ID."""
return self._key_for(id) in self._messages
def __len__(self):
"""The number of messages in the catalog.
This does not include the special ``msgid ""`` entry."""
return len(self._messages)
def __iter__(self):
"""Iterates through all the entries in the catalog, in the order they
were added, yielding a `Message` object for every entry.
:rtype: ``iterator``"""
buf = []
for name, value in self.mime_headers:
buf.append('%s: %s' % (name, value))
flags = set()
if self.fuzzy:
flags |= set(['fuzzy'])
yield Message(u'', '\n'.join(buf), flags=flags)
for key in self._messages:
yield self._messages[key]
def __repr__(self):
locale = ''
if self.locale:
locale = ' %s' % self.locale
return '<%s %r%s>' % (type(self).__name__, self.domain, locale)
def __delitem__(self, id):
"""Delete the message with the specified ID."""
self.delete(id)
def __getitem__(self, id):
"""Return the message with the specified ID.
:param id: the message ID
"""
return self.get(id)
def __setitem__(self, id, message):
"""Add or update the message with the specified ID.
>>> catalog = Catalog()
>>> catalog[u'foo'] = Message(u'foo')
>>> catalog[u'foo']
<Message u'foo' (flags: [])>
If a message with that ID is already in the catalog, it is updated
to include the locations and flags of the new message.
>>> catalog = Catalog()
>>> catalog[u'foo'] = Message(u'foo', locations=[('main.py', 1)])
>>> catalog[u'foo'].locations
[('main.py', 1)]
>>> catalog[u'foo'] = Message(u'foo', locations=[('utils.py', 5)])
>>> catalog[u'foo'].locations
[('main.py', 1), ('utils.py', 5)]
:param id: the message ID
:param message: the `Message` object
"""
assert isinstance(message, Message), 'expected a Message object'
key = self._key_for(id, message.context)
current = self._messages.get(key)
if current:
if message.pluralizable and not current.pluralizable:
# The new message adds pluralization
current.id = message.id
current.string = message.string
current.locations = list(distinct(current.locations +
message.locations))
current.auto_comments = list(distinct(current.auto_comments +
message.auto_comments))
current.user_comments = list(distinct(current.user_comments +
message.user_comments))
current.flags |= message.flags
message = current
elif id == '':
# special treatment for the header message
self.mime_headers = _parse_header(message.string).items()
self.header_comment = '\n'.join([('# %s' % c).rstrip() for c
in message.user_comments])
self.fuzzy = message.fuzzy
else:
if isinstance(id, (list, tuple)):
assert isinstance(message.string, (list, tuple)), \
'Expected sequence but got %s' % type(message.string)
self._messages[key] = message
def add(self, id, string=None, locations=(), flags=(), auto_comments=(),
user_comments=(), previous_id=(), lineno=None, context=None):
"""Add or update the message with the specified ID.
>>> catalog = Catalog()
>>> catalog.add(u'foo')
<Message ...>
>>> catalog[u'foo']
<Message u'foo' (flags: [])>
This method simply constructs a `Message` object with the given
arguments and invokes `__setitem__` with that object.
:param id: the message ID, or a ``(singular, plural)`` tuple for
pluralizable messages
:param string: the translated message string, or a
``(singular, plural)`` tuple for pluralizable messages
:param locations: a sequence of ``(filenname, lineno)`` tuples
:param flags: a set or sequence of flags
:param auto_comments: a sequence of automatic comments
:param user_comments: a sequence of user comments
:param previous_id: the previous message ID, or a ``(singular, plural)``
tuple for pluralizable messages
:param lineno: the line number on which the msgid line was found in the
PO file, if any
:param context: the message context
"""
message = Message(id, string, list(locations), flags, auto_comments,
user_comments, previous_id, lineno=lineno,
context=context)
self[id] = message
return message
def check(self):
"""Run various validation checks on the translations in the catalog.
For every message which fails validation, this method yield a
``(message, errors)`` tuple, where ``message`` is the `Message` object
and ``errors`` is a sequence of `TranslationError` objects.
:rtype: ``iterator``
"""
for message in self._messages.values():
errors = message.check(catalog=self)
if errors:
yield message, errors
def get(self, id, context=None):
"""Return the message with the specified ID and context.
:param id: the message ID
:param context: the message context, or ``None`` for no context
"""
return self._messages.get(self._key_for(id, context))
def delete(self, id, context=None):
"""Delete the message with the specified ID and context.
:param id: the message ID
:param context: the message context, or ``None`` for no context
"""
key = self._key_for(id, context)
if key in self._messages:
del self._messages[key]
def update(self, template, no_fuzzy_matching=False):
"""Update the catalog based on the given template catalog.
>>> from babel.messages import Catalog
>>> template = Catalog()
>>> template.add('green', locations=[('main.py', 99)])
<Message ...>
>>> template.add('blue', locations=[('main.py', 100)])
<Message ...>
>>> template.add(('salad', 'salads'), locations=[('util.py', 42)])
<Message ...>
>>> catalog = Catalog(locale='de_DE')
>>> catalog.add('blue', u'blau', locations=[('main.py', 98)])
<Message ...>
>>> catalog.add('head', u'Kopf', locations=[('util.py', 33)])
<Message ...>
>>> catalog.add(('salad', 'salads'), (u'Salat', u'Salate'),
... locations=[('util.py', 38)])
<Message ...>
>>> catalog.update(template)
>>> len(catalog)
3
>>> msg1 = catalog['green']
>>> msg1.string
>>> msg1.locations
[('main.py', 99)]
>>> msg2 = catalog['blue']
>>> msg2.string
u'blau'
>>> msg2.locations
[('main.py', 100)]
>>> msg3 = catalog['salad']
>>> msg3.string
(u'Salat', u'Salate')
>>> msg3.locations
[('util.py', 42)]
Messages that are in the catalog but not in the template are removed
from the main collection, but can still be accessed via the `obsolete`
member:
>>> 'head' in catalog
False
>>> list(catalog.obsolete.values())
[<Message 'head' (flags: [])>]
:param template: the reference catalog, usually read from a POT file
:param no_fuzzy_matching: whether to use fuzzy matching of message IDs
"""
messages = self._messages
remaining = messages.copy()
self._messages = odict()
# Prepare for fuzzy matching
fuzzy_candidates = []
if not no_fuzzy_matching:
fuzzy_candidates = dict([
(self._key_for(msgid), messages[msgid].context)
for msgid in messages if msgid and messages[msgid].string
])
fuzzy_matches = set()
def _merge(message, oldkey, newkey):
message = message.clone()
fuzzy = False
if oldkey != newkey:
fuzzy = True
fuzzy_matches.add(oldkey)
oldmsg = messages.get(oldkey)
if isinstance(oldmsg.id, string_types):
message.previous_id = [oldmsg.id]
else:
message.previous_id = list(oldmsg.id)
else:
oldmsg = remaining.pop(oldkey, None)
message.string = oldmsg.string
if isinstance(message.id, (list, tuple)):
if not isinstance(message.string, (list, tuple)):
fuzzy = True
message.string = tuple(
[message.string] + ([u''] * (len(message.id) - 1))
)
elif len(message.string) != self.num_plurals:
fuzzy = True
message.string = tuple(message.string[:len(oldmsg.string)])
elif isinstance(message.string, (list, tuple)):
fuzzy = True
message.string = message.string[0]
message.flags |= oldmsg.flags
if fuzzy:
message.flags |= set([u'fuzzy'])
self[message.id] = message
for message in template:
if message.id:
key = self._key_for(message.id, message.context)
if key in messages:
_merge(message, key, key)
else:
if no_fuzzy_matching is False:
# do some fuzzy matching with difflib
if isinstance(key, tuple):
matchkey = key[0] # just the msgid, no context
else:
matchkey = key
matches = get_close_matches(matchkey.lower().strip(),
fuzzy_candidates.keys(), 1)
if matches:
newkey = matches[0]
newctxt = fuzzy_candidates[newkey]
if newctxt is not None:
newkey = newkey, newctxt
_merge(message, newkey, key)
continue
self[message.id] = message
for msgid in remaining:
if no_fuzzy_matching or msgid not in fuzzy_matches:
self.obsolete[msgid] = remaining[msgid]
# Allow the updated catalog's header to be rewritten based on the
# template's header
self.header_comment = template.header_comment
# Make updated catalog's POT-Creation-Date equal to the template
# used to update the catalog
self.creation_date = template.creation_date
def _key_for(self, id, context=None):
"""The key for a message is just the singular ID even for pluralizable
messages, but is a ``(msgid, msgctxt)`` tuple for context-specific
messages.
"""
key = id
if isinstance(key, (list, tuple)):
key = id[0]
if context is not None:
key = (key, context)
return key
| 37.776829 | 80 | 0.569067 |
import re
import time
from cgi import parse_header
from datetime import datetime, time as time_
from difflib import get_close_matches
from email import message_from_string
from copy import copy
from babel import __version__ as VERSION
from babel.core import Locale
from babel.dates import format_datetime
from babel.messages.plurals import get_plural
from babel.util import odict, distinct, LOCALTZ, FixedOffsetTimezone
from babel._compat import string_types, number_types, PY2, cmp
__all__ = ['Message', 'Catalog', 'TranslationError']
PYTHON_FORMAT = re.compile(r'''(?x)
\%
(?:\(([\w]*)\))?
(
[-#0\ +]?(?:\*|[\d]+)?
(?:\.(?:\*|[\d]+))?
[hlL]?
)
([diouxXeEfFgGcrs%])
''')
def _parse_datetime_header(value):
match = re.match(r'^(?P<datetime>.*?)(?P<tzoffset>[+-]\d{4})?$', value)
tt = time.strptime(match.group('datetime'), '%Y-%m-%d %H:%M')
ts = time.mktime(tt)
dt = datetime.fromtimestamp(ts)
fset = match.group('tzoffset')
if tzoffset is not None:
plus_minus_s, rest = tzoffset[0], tzoffset[1:]
hours_offset_s, mins_offset_s = rest[:2], rest[2:]
plus_minus = int(plus_minus_s + '1')
hours_offset = int(hours_offset_s)
mins_offset = int(mins_offset_s)
net_mins_offset = hours_offset * 60
net_mins_offset += mins_offset
net_mins_offset *= plus_minus
tzoffset = FixedOffsetTimezone(net_mins_offset)
dt = dt.replace(tzinfo=tzoffset)
return dt
class Message(object):
def __init__(self, id, string=u'', locations=(), flags=(), auto_comments=(),
user_comments=(), previous_id=(), lineno=None, context=None):
self.id = id
if not string and self.pluralizable:
string = (u'', u'')
self.string = string
self.locations = list(distinct(locations))
self.flags = set(flags)
if id and self.python_format:
self.flags.add('python-format')
else:
self.flags.discard('python-format')
self.auto_comments = list(distinct(auto_comments))
self.user_comments = list(distinct(user_comments))
if isinstance(previous_id, string_types):
self.previous_id = [previous_id]
else:
self.previous_id = list(previous_id)
self.lineno = lineno
self.context = context
def __repr__(self):
return '<%s %r (flags: %r)>' % (type(self).__name__, self.id,
list(self.flags))
def __cmp__(self, obj):
def values_to_compare():
if isinstance(obj, Message):
plural = self.pluralizable
obj_plural = obj.pluralizable
if plural and obj_plural:
return self.id[0], obj.id[0]
elif plural:
return self.id[0], obj.id
elif obj_plural:
return self.id, obj.id[0]
return self.id, obj.id
this, other = values_to_compare()
return cmp(this, other)
def __gt__(self, other):
return self.__cmp__(other) > 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __ge__(self, other):
return self.__cmp__(other) >= 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def clone(self):
return Message(*map(copy, (self.id, self.string, self.locations,
self.flags, self.auto_comments,
self.user_comments, self.previous_id,
self.lineno, self.context)))
def check(self, catalog=None):
from babel.messages.checkers import checkers
errors = []
for checker in checkers:
try:
checker(catalog, self)
except TranslationError as e:
errors.append(e)
return errors
@property
def fuzzy(self):
return 'fuzzy' in self.flags
@property
def pluralizable(self):
return isinstance(self.id, (list, tuple))
@property
def python_format(self):
ids = self.id
if not isinstance(ids, (list, tuple)):
ids = [ids]
return any(PYTHON_FORMAT.search(id) for id in ids)
class TranslationError(Exception):
DEFAULT_HEADER = u"""\
# Translations template for PROJECT.
# Copyright (C) YEAR ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#"""
if PY2:
def _parse_header(header_string):
headers = message_from_string(header_string.encode('utf8'))
decoded_headers = {}
for name, value in headers.items():
name = name.decode('utf8')
value = value.decode('utf8')
decoded_headers[name] = value
return decoded_headers
else:
_parse_header = message_from_string
class Catalog(object):
def __init__(self, locale=None, domain=None, header_comment=DEFAULT_HEADER,
project=None, version=None, copyright_holder=None,
msgid_bugs_address=None, creation_date=None,
revision_date=None, last_translator=None, language_team=None,
charset=None, fuzzy=True):
self.domain = domain
if locale:
locale = Locale.parse(locale)
self.locale = locale
self._header_comment = header_comment
self._messages = odict()
self.project = project or 'PROJECT'
self.version = version or 'VERSION'
self.copyright_holder = copyright_holder or 'ORGANIZATION'
self.msgid_bugs_address = msgid_bugs_address or 'EMAIL@ADDRESS'
self.last_translator = last_translator or 'FULL NAME <EMAIL@ADDRESS>'
self.language_team = language_team or 'LANGUAGE <LL@li.org>'
self.charset = charset or 'utf-8'
if creation_date is None:
creation_date = datetime.now(LOCALTZ)
elif isinstance(creation_date, datetime) and not creation_date.tzinfo:
creation_date = creation_date.replace(tzinfo=LOCALTZ)
self.creation_date = creation_date
if revision_date is None:
revision_date = 'YEAR-MO-DA HO:MI+ZONE'
elif isinstance(revision_date, datetime) and not revision_date.tzinfo:
revision_date = revision_date.replace(tzinfo=LOCALTZ)
self.revision_date = revision_date
self.fuzzy = fuzzy
self.obsolete = odict()
self._num_plurals = None
self._plural_expr = None
def _get_header_comment(self):
comment = self._header_comment
year = datetime.now(LOCALTZ).strftime('%Y')
if hasattr(self.revision_date, 'strftime'):
year = self.revision_date.strftime('%Y')
comment = comment.replace('PROJECT', self.project) \
.replace('VERSION', self.version) \
.replace('YEAR', year) \
.replace('ORGANIZATION', self.copyright_holder)
if self.locale:
comment = comment.replace('Translations template', '%s translations'
% self.locale.english_name)
return comment
def _set_header_comment(self, string):
self._header_comment = string
header_comment = property(_get_header_comment, _set_header_comment, doc="""\
The header comment for the catalog.
>>> catalog = Catalog(project='Foobar', version='1.0',
... copyright_holder='Foo Company')
>>> print(catalog.header_comment) #doctest: +ELLIPSIS
# Translations template for Foobar.
# Copyright (C) ... Foo Company
# This file is distributed under the same license as the Foobar project.
# FIRST AUTHOR <EMAIL@ADDRESS>, ....
#
The header can also be set from a string. Any known upper-case variables
will be replaced when the header is retrieved again:
>>> catalog = Catalog(project='Foobar', version='1.0',
... copyright_holder='Foo Company')
>>> catalog.header_comment = '''\\
... # The POT for my really cool PROJECT project.
... # Copyright (C) 1990-2003 ORGANIZATION
... # This file is distributed under the same license as the PROJECT
... # project.
... #'''
>>> print(catalog.header_comment)
# The POT for my really cool Foobar project.
# Copyright (C) 1990-2003 Foo Company
# This file is distributed under the same license as the Foobar
# project.
#
:type: `unicode`
""")
def _get_mime_headers(self):
headers = []
headers.append(('Project-Id-Version',
'%s %s' % (self.project, self.version)))
headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address))
headers.append(('POT-Creation-Date',
format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ',
locale='en')))
if isinstance(self.revision_date, (datetime, time_) + number_types):
headers.append(('PO-Revision-Date',
format_datetime(self.revision_date,
'yyyy-MM-dd HH:mmZ', locale='en')))
else:
headers.append(('PO-Revision-Date', self.revision_date))
headers.append(('Last-Translator', self.last_translator))
if self.locale is not None:
headers.append(('Language', str(self.locale)))
if (self.locale is not None) and ('LANGUAGE' in self.language_team):
headers.append(('Language-Team',
self.language_team.replace('LANGUAGE',
str(self.locale))))
else:
headers.append(('Language-Team', self.language_team))
if self.locale is not None:
headers.append(('Plural-Forms', self.plural_forms))
headers.append(('MIME-Version', '1.0'))
headers.append(('Content-Type',
'text/plain; charset=%s' % self.charset))
headers.append(('Content-Transfer-Encoding', '8bit'))
headers.append(('Generated-By', 'Babel %s\n' % VERSION))
return headers
def _set_mime_headers(self, headers):
for name, value in headers:
name = name.lower()
if name == 'project-id-version':
parts = value.split(' ')
self.project = u' '.join(parts[:-1])
self.version = parts[-1]
elif name == 'report-msgid-bugs-to':
self.msgid_bugs_address = value
elif name == 'last-translator':
self.last_translator = value
elif name == 'language-team':
self.language_team = value
elif name == 'content-type':
mimetype, params = parse_header(value)
if 'charset' in params:
self.charset = params['charset'].lower()
elif name == 'plural-forms':
_, params = parse_header(' ;' + value)
self._num_plurals = int(params.get('nplurals', 2))
self._plural_expr = params.get('plural', '(n != 1)')
elif name == 'pot-creation-date':
self.creation_date = _parse_datetime_header(value)
elif name == 'po-revision-date':
if 'YEAR' not in value:
self.revision_date = _parse_datetime_header(value)
mime_headers = property(_get_mime_headers, _set_mime_headers, doc="""\
The MIME headers of the catalog, used for the special ``msgid ""`` entry.
The behavior of this property changes slightly depending on whether a locale
is set or not, the latter indicating that the catalog is actually a template
for actual translations.
Here's an example of the output for such a catalog template:
>>> from babel.dates import UTC
>>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
>>> catalog = Catalog(project='Foobar', version='1.0',
... creation_date=created)
>>> for name, value in catalog.mime_headers:
... print('%s: %s' % (name, value))
Project-Id-Version: Foobar 1.0
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 1990-04-01 15:30+0000
PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
Last-Translator: FULL NAME <EMAIL@ADDRESS>
Language-Team: LANGUAGE <LL@li.org>
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel ...
And here's an example of the output when the locale is set:
>>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
>>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
... creation_date=created, revision_date=revised,
... last_translator='John Doe <jd@example.com>',
... language_team='de_DE <de@example.com>')
>>> for name, value in catalog.mime_headers:
... print('%s: %s' % (name, value))
Project-Id-Version: Foobar 1.0
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 1990-04-01 15:30+0000
PO-Revision-Date: 1990-08-03 12:00+0000
Last-Translator: John Doe <jd@example.com>
Language: de_DE
Language-Team: de_DE <de@example.com>
Plural-Forms: nplurals=2; plural=(n != 1)
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel ...
:type: `list`
""")
@property
def num_plurals(self):
if self._num_plurals is None:
num = 2
if self.locale:
num = get_plural(self.locale)[0]
self._num_plurals = num
return self._num_plurals
@property
def plural_expr(self):
if self._plural_expr is None:
expr = '(n != 1)'
if self.locale:
expr = get_plural(self.locale)[1]
self._plural_expr = expr
return self._plural_expr
@property
def plural_forms(self):
return 'nplurals=%s; plural=%s' % (self.num_plurals, self.plural_expr)
def __contains__(self, id):
return self._key_for(id) in self._messages
def __len__(self):
return len(self._messages)
def __iter__(self):
buf = []
for name, value in self.mime_headers:
buf.append('%s: %s' % (name, value))
flags = set()
if self.fuzzy:
flags |= set(['fuzzy'])
yield Message(u'', '\n'.join(buf), flags=flags)
for key in self._messages:
yield self._messages[key]
def __repr__(self):
locale = ''
if self.locale:
locale = ' %s' % self.locale
return '<%s %r%s>' % (type(self).__name__, self.domain, locale)
def __delitem__(self, id):
self.delete(id)
def __getitem__(self, id):
return self.get(id)
def __setitem__(self, id, message):
assert isinstance(message, Message), 'expected a Message object'
key = self._key_for(id, message.context)
current = self._messages.get(key)
if current:
if message.pluralizable and not current.pluralizable:
# The new message adds pluralization
current.id = message.id
current.string = message.string
current.locations = list(distinct(current.locations +
message.locations))
current.auto_comments = list(distinct(current.auto_comments +
message.auto_comments))
current.user_comments = list(distinct(current.user_comments +
message.user_comments))
current.flags |= message.flags
message = current
elif id == '':
# special treatment for the header message
self.mime_headers = _parse_header(message.string).items()
self.header_comment = '\n'.join([('
in message.user_comments])
self.fuzzy = message.fuzzy
else:
if isinstance(id, (list, tuple)):
assert isinstance(message.string, (list, tuple)), \
'Expected sequence but got %s' % type(message.string)
self._messages[key] = message
def add(self, id, string=None, locations=(), flags=(), auto_comments=(),
user_comments=(), previous_id=(), lineno=None, context=None):
message = Message(id, string, list(locations), flags, auto_comments,
user_comments, previous_id, lineno=lineno,
context=context)
self[id] = message
return message
def check(self):
for message in self._messages.values():
errors = message.check(catalog=self)
if errors:
yield message, errors
def get(self, id, context=None):
return self._messages.get(self._key_for(id, context))
def delete(self, id, context=None):
key = self._key_for(id, context)
if key in self._messages:
del self._messages[key]
def update(self, template, no_fuzzy_matching=False):
messages = self._messages
remaining = messages.copy()
self._messages = odict()
# Prepare for fuzzy matching
fuzzy_candidates = []
if not no_fuzzy_matching:
fuzzy_candidates = dict([
(self._key_for(msgid), messages[msgid].context)
for msgid in messages if msgid and messages[msgid].string
])
fuzzy_matches = set()
def _merge(message, oldkey, newkey):
message = message.clone()
fuzzy = False
if oldkey != newkey:
fuzzy = True
fuzzy_matches.add(oldkey)
oldmsg = messages.get(oldkey)
if isinstance(oldmsg.id, string_types):
message.previous_id = [oldmsg.id]
else:
message.previous_id = list(oldmsg.id)
else:
oldmsg = remaining.pop(oldkey, None)
message.string = oldmsg.string
if isinstance(message.id, (list, tuple)):
if not isinstance(message.string, (list, tuple)):
fuzzy = True
message.string = tuple(
[message.string] + ([u''] * (len(message.id) - 1))
)
elif len(message.string) != self.num_plurals:
fuzzy = True
message.string = tuple(message.string[:len(oldmsg.string)])
elif isinstance(message.string, (list, tuple)):
fuzzy = True
message.string = message.string[0]
message.flags |= oldmsg.flags
if fuzzy:
message.flags |= set([u'fuzzy'])
self[message.id] = message
for message in template:
if message.id:
key = self._key_for(message.id, message.context)
if key in messages:
_merge(message, key, key)
else:
if no_fuzzy_matching is False:
# do some fuzzy matching with difflib
if isinstance(key, tuple):
matchkey = key[0] # just the msgid, no context
else:
matchkey = key
matches = get_close_matches(matchkey.lower().strip(),
fuzzy_candidates.keys(), 1)
if matches:
newkey = matches[0]
newctxt = fuzzy_candidates[newkey]
if newctxt is not None:
newkey = newkey, newctxt
_merge(message, newkey, key)
continue
self[message.id] = message
for msgid in remaining:
if no_fuzzy_matching or msgid not in fuzzy_matches:
self.obsolete[msgid] = remaining[msgid]
# Allow the updated catalog's header to be rewritten based on the
self.header_comment = template.header_comment
# Make updated catalog's POT-Creation-Date equal to the template
self.creation_date = template.creation_date
def _key_for(self, id, context=None):
key = id
if isinstance(key, (list, tuple)):
key = id[0]
if context is not None:
key = (key, context)
return key
| true | true |
f72a350db1ba57a29e227da4a2688911fa9f59a9 | 1,600 | py | Python | app/api/db_config.py | gatemadavid/iReporter2 | 31ee2295a10c074bbf3b5b857240ec65ca9689e9 | [
"MIT"
] | null | null | null | app/api/db_config.py | gatemadavid/iReporter2 | 31ee2295a10c074bbf3b5b857240ec65ca9689e9 | [
"MIT"
] | null | null | null | app/api/db_config.py | gatemadavid/iReporter2 | 31ee2295a10c074bbf3b5b857240ec65ca9689e9 | [
"MIT"
] | null | null | null | import psycopg2
import psycopg2.extras
import os
url = os.getenv('DATABASE_URL')
def connection(url):
conn = psycopg2.connect(url)
return conn
def init_db():
con = connection(url)
return con
def create_tables():
conn = connection(url)
curr = conn.cursor()
queries = tables()
for query in queries:
curr.execute(query)
conn.commit()
def tables():
users_table = '''CREATE TABLE IF NOT EXISTS users(
id serial PRIMARY KEY,
firstname char(20) NOT NULL,
lastname char(20) NOT NULL,
email char(50) NOT NULL,
username char(20) NOT NULL,
phone char(14) NOT NULL,
isAdmin BOOLEAN DEFAULT False,
password char(100) NOT NULL,
registered DATE NOT NULL DEFAULT CURRENT_DATE)
'''
incidents_table = '''CREATE TABLE IF NOT EXISTS incidents(
id serial PRIMARY KEY,
title char(100) NOT NULL,
incident char(50) NOT NULL,
location char(100) NOT NULL,
status char(30) DEFAULT 'Draft',
description char(200) NOT NULL,
images char(100) NOT NULL,
createdBy char(100) NOT NULL,
createdOn DATE NOT NULL DEFAULT CURRENT_DATE) '''
queries = [users_table, incidents_table]
return queries
def destroy_tables():
conn = connection(url)
curr = conn.cursor()
users_table = ''' DROP TABLE IF EXISTS users CASCADE'''
incidents_table = ''' DROP TABLE IF EXISTS incidents CASCADE'''
queries = [users_table, incidents_table]
for query in queries:
curr.execute(query)
conn.commit()
| 25.396825 | 67 | 0.636875 | import psycopg2
import psycopg2.extras
import os
url = os.getenv('DATABASE_URL')
def connection(url):
conn = psycopg2.connect(url)
return conn
def init_db():
con = connection(url)
return con
def create_tables():
conn = connection(url)
curr = conn.cursor()
queries = tables()
for query in queries:
curr.execute(query)
conn.commit()
def tables():
users_table = '''CREATE TABLE IF NOT EXISTS users(
id serial PRIMARY KEY,
firstname char(20) NOT NULL,
lastname char(20) NOT NULL,
email char(50) NOT NULL,
username char(20) NOT NULL,
phone char(14) NOT NULL,
isAdmin BOOLEAN DEFAULT False,
password char(100) NOT NULL,
registered DATE NOT NULL DEFAULT CURRENT_DATE)
'''
incidents_table = '''CREATE TABLE IF NOT EXISTS incidents(
id serial PRIMARY KEY,
title char(100) NOT NULL,
incident char(50) NOT NULL,
location char(100) NOT NULL,
status char(30) DEFAULT 'Draft',
description char(200) NOT NULL,
images char(100) NOT NULL,
createdBy char(100) NOT NULL,
createdOn DATE NOT NULL DEFAULT CURRENT_DATE) '''
queries = [users_table, incidents_table]
return queries
def destroy_tables():
conn = connection(url)
curr = conn.cursor()
users_table = ''' DROP TABLE IF EXISTS users CASCADE'''
incidents_table = ''' DROP TABLE IF EXISTS incidents CASCADE'''
queries = [users_table, incidents_table]
for query in queries:
curr.execute(query)
conn.commit()
| true | true |
f72a355540cc984f158300eaacfdbb6e9b3587e6 | 2,682 | py | Python | apps/points/models.py | stasm/akupunktura | 5cf8b98dbb01a65db48c8f582f1592c680c47eba | [
"BSD-3-Clause"
] | 1 | 2015-05-14T19:10:29.000Z | 2015-05-14T19:10:29.000Z | apps/points/models.py | stasm/akupunktura | 5cf8b98dbb01a65db48c8f582f1592c680c47eba | [
"BSD-3-Clause"
] | null | null | null | apps/points/models.py | stasm/akupunktura | 5cf8b98dbb01a65db48c8f582f1592c680c47eba | [
"BSD-3-Clause"
] | null | null | null | from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class PointManager(models.Manager):
"""Manager for Pressure Points."""
def recently_added(self, count=10):
return self.order_by('-time_added')[:count]
class City(models.Model):
"""City the Pressure Point belong to."""
name = models.CharField(max_length=200)
slug = models.SlugField()
lat = models.FloatField()
lon = models.FloatField()
def __unicode__(self):
return self.name
class Point(models.Model):
"""Pressure Point model.
The pressure points are the core concept of the app. They're small cases
that the community shares, discusses about and eventually, take action
upon in order to improve the quality of life.
"""
title = models.CharField(max_length=200)
lat = models.FloatField()
lon = models.FloatField()
description = models.TextField()
# descriptive address or directions on how to find the Point
directions = models.TextField()
time_added = models.DateTimeField()
# simple voting mechanism (like/dislike)
thumbsup = models.IntegerField()
thumbsdown = models.IntegerField()
# foreign keys
poster = models.ForeignKey(User)
city = models.ForeignKey(City)
# managers
objects = PointManager()
def __unicode__(self):
return "%s x %s" % (self.lat, self.lon)
class Photo(models.Model):
"""Photo objects illustrating Pressure Points."""
time_added = models.DateTimeField()
thumbnail = models.ImageField(upload_to='upload/thumbnails', blank=True)
original = models.ImageField(upload_to='upload/original')
is_main = models.BooleanField()
poster = models.ForeignKey(User)
point = models.ForeignKey(Point, related_name='photos')
def save(self, *args, **kwargs):
if self.id is None:
self.thumbnail = self.original
super(Photo, self).save(*args, **kwargs)
class FeatureManager(models.Manager):
"""Manager for Feature objects."""
def current(self):
now = datetime.now()
return self.filter(start_time__lt=now, end_time__gt=now)
class Feature(models.Model):
"""Pressure Point features on the home page."""
start_time = models.DateTimeField()
end_time = models.DateTimeField()
point = models.ForeignKey(Point, related_name='features')
objects = FeatureManager()
class Resolution(models.Model):
"""Resolution objects describe how a Pressure Point was closed."""
description = models.TextField()
time_resolved = models.DateTimeField()
point = models.OneToOneField(Point, related_name='resolution')
| 30.827586 | 76 | 0.690902 | from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class PointManager(models.Manager):
def recently_added(self, count=10):
return self.order_by('-time_added')[:count]
class City(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField()
lat = models.FloatField()
lon = models.FloatField()
def __unicode__(self):
return self.name
class Point(models.Model):
title = models.CharField(max_length=200)
lat = models.FloatField()
lon = models.FloatField()
description = models.TextField()
directions = models.TextField()
time_added = models.DateTimeField()
thumbsup = models.IntegerField()
thumbsdown = models.IntegerField()
poster = models.ForeignKey(User)
city = models.ForeignKey(City)
objects = PointManager()
def __unicode__(self):
return "%s x %s" % (self.lat, self.lon)
class Photo(models.Model):
time_added = models.DateTimeField()
thumbnail = models.ImageField(upload_to='upload/thumbnails', blank=True)
original = models.ImageField(upload_to='upload/original')
is_main = models.BooleanField()
poster = models.ForeignKey(User)
point = models.ForeignKey(Point, related_name='photos')
def save(self, *args, **kwargs):
if self.id is None:
self.thumbnail = self.original
super(Photo, self).save(*args, **kwargs)
class FeatureManager(models.Manager):
def current(self):
now = datetime.now()
return self.filter(start_time__lt=now, end_time__gt=now)
class Feature(models.Model):
start_time = models.DateTimeField()
end_time = models.DateTimeField()
point = models.ForeignKey(Point, related_name='features')
objects = FeatureManager()
class Resolution(models.Model):
description = models.TextField()
time_resolved = models.DateTimeField()
point = models.OneToOneField(Point, related_name='resolution')
| true | true |
f72a35b4e1de51ead743b2099fba5d0628b7e0b3 | 214 | py | Python | app/api.py | jecklgamis/flask-example-app | 025f60d812acae1eb33263de3339ac8e37096a54 | [
"Apache-2.0"
] | 6 | 2019-11-25T08:46:03.000Z | 2021-12-28T07:30:50.000Z | app/api.py | jecklgamis/flask-example-app | 025f60d812acae1eb33263de3339ac8e37096a54 | [
"Apache-2.0"
] | null | null | null | app/api.py | jecklgamis/flask-example-app | 025f60d812acae1eb33263de3339ac8e37096a54 | [
"Apache-2.0"
] | 1 | 2021-12-26T21:36:51.000Z | 2021-12-26T21:36:51.000Z | from flask import Blueprint
bp = Blueprint('api', __name__, url_prefix='/api')
from flask import jsonify
@bp.route('/', methods=['GET'])
def index():
return jsonify({"message": "This is the /api endpoint"})
| 21.4 | 60 | 0.682243 | from flask import Blueprint
bp = Blueprint('api', __name__, url_prefix='/api')
from flask import jsonify
@bp.route('/', methods=['GET'])
def index():
return jsonify({"message": "This is the /api endpoint"})
| true | true |
f72a37822a8c5d59218999e0dc281e80546e9c72 | 5,010 | py | Python | cmatch.py | kitneylab/cmatch | 6c804c2ca58f5e8ccde68c14182bebcb43ad69b4 | [
"MIT"
] | null | null | null | cmatch.py | kitneylab/cmatch | 6c804c2ca58f5e8ccde68c14182bebcb43ad69b4 | [
"MIT"
] | null | null | null | cmatch.py | kitneylab/cmatch | 6c804c2ca58f5e8ccde68c14182bebcb43ad69b4 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import json
import logging
import os
from os import path
from pathlib import Path
import time
from reconstruction import reconstruct
from futils import timeit
from tqdm import tqdm
from matching import Library, Sequence, match_library
import plac
# Logging configuration
current_file = path.basename(__file__).split(".")[0]
@timeit
def match_libs(seq, libs, threshold=0.5):
"""
Match libs with the sequence
"""
result = []
for lib in tqdm(libs):
pop = {}
pop["library"] = lib["name"]
# See algo1_lycopene for the parameter below in the template
# threshold = lib["score_threshold"]
candidates = match_library(seq, Library(lib), threshold, direction53=True)
cl = []
for candidate in candidates:
for c in candidate:
cl.append(
{
"name": c.name,
"score": c.score,
"start": c.start,
"length": c.length,
"end": c.end,
}
)
pop["candidates"] = cl
result.append(pop)
return result
def get_sequences(dir_dict):
"""
Return list of sequences
"""
SEQUENCES_EXTENSION = dir_dict["extension"]
SEQUENCES_PATH = dir_dict["sequences_path"]
seq_dir_names = dir_dict["seq_dir_names"]
sequences = []
for seq_dir in seq_dir_names:
seqs = Path(path.join(SEQUENCES_PATH, seq_dir)).rglob(
"*{0}".format(SEQUENCES_EXTENSION)
)
sequences.append(seqs)
return sequences
def get_slices_libs(template):
"""
Get slices libraries
Args:
template (dict): Template JSON data as a dict structure
Returns:
dict of slices libraries
"""
slices_libs = {}
for sli in template["template_slices"]:
libs = []
for pos in sli["template_slice"]:
lib = template["template"]["structure"][pos - 1]["library_source"]
libs.append(template["component_sources"][lib])
slices_libs[sli["name"]] = libs
return slices_libs
@timeit
def iter_all_seq(
input_sequences,
template_json_file,
match_output_filename,
reconstruction_output_filename,
threshold=0.99,
):
"""
Iterate over sequences
Args:
input_sequences (dict): Input dictionary with info about the input sequences:
output_filename (str): Output filename
Example:
input_sequences = {
'extension' = ".seq"
'sequences_path' = "/data/Imperial/src/lyc-basic-ass-ind/"
'seq_dir_names' = ["output"]
}
"""
# Get sequences to match
sequences = get_sequences(input_sequences)
# Get the filenames in a list and not this freakin generator
seq_filenames = []
for seq in sequences:
for filename in seq:
seq_filenames.append(filename)
# Loop over the sequences
r = []
for filename in seq_filenames:
sq = Sequence(filename)
json_to_output = {}
json_to_output["target"] = sq.name
# Logging
logging.info(f"Target sequence: {sq.name}")
with open(template_json_file) as json_file:
template = json.load(json_file)
# Get libs from template
template["template"]
libs = get_slices_libs(template)
libs_to_match = libs["construct"] # name of the fake primer
# Match sequence
matches = match_libs(sq, libs_to_match, threshold=threshold)
json_to_output["matches"] = matches
r.append(json_to_output)
# Write output result in JSON file
with open(match_output_filename, "w") as filename:
json.dump(r, filename, indent=2, separators=(",", ":"))
def match(template, threshold=0.99, *targets):
"""
Match
"""
# Load JSON template
with open(template) as json_file:
template = json.load(json_file)
r = []
# Matching
for target in targets:
sq = Sequence(target)
json_to_output = {}
json_to_output["target"] = sq.name
libs = get_slices_libs(template)
libs_to_match = libs["construct"] # name of the fake primer
matches = match_libs(sq, libs_to_match, threshold=threshold)
json_to_output["matches"] = matches
r.append(json_to_output)
s = json.dumps(r, indent=2, separators=(",", ":"))
reconstruction_result = reconstruct(r)
ss = json.dumps(reconstruction_result, indent=2, separators=(",", ":"))
return ss
@plac.pos("template", "JSON construct template. Example: consruct_template.json")
@plac.pos("targets", f"Target sequence files. Example: Sanger008.seq", type=str)
@plac.opt("threshold", "Threshold", type=float)
def main(template, threshold=0.99, *targets):
"""
cMatch command line tool
"""
result = match(template, threshold, *targets)
print(result)
if __name__ == "__main__":
plac.call(main)
| 26.368421 | 85 | 0.612774 |
import json
import logging
import os
from os import path
from pathlib import Path
import time
from reconstruction import reconstruct
from futils import timeit
from tqdm import tqdm
from matching import Library, Sequence, match_library
import plac
current_file = path.basename(__file__).split(".")[0]
@timeit
def match_libs(seq, libs, threshold=0.5):
result = []
for lib in tqdm(libs):
pop = {}
pop["library"] = lib["name"]
candidates = match_library(seq, Library(lib), threshold, direction53=True)
cl = []
for candidate in candidates:
for c in candidate:
cl.append(
{
"name": c.name,
"score": c.score,
"start": c.start,
"length": c.length,
"end": c.end,
}
)
pop["candidates"] = cl
result.append(pop)
return result
def get_sequences(dir_dict):
SEQUENCES_EXTENSION = dir_dict["extension"]
SEQUENCES_PATH = dir_dict["sequences_path"]
seq_dir_names = dir_dict["seq_dir_names"]
sequences = []
for seq_dir in seq_dir_names:
seqs = Path(path.join(SEQUENCES_PATH, seq_dir)).rglob(
"*{0}".format(SEQUENCES_EXTENSION)
)
sequences.append(seqs)
return sequences
def get_slices_libs(template):
slices_libs = {}
for sli in template["template_slices"]:
libs = []
for pos in sli["template_slice"]:
lib = template["template"]["structure"][pos - 1]["library_source"]
libs.append(template["component_sources"][lib])
slices_libs[sli["name"]] = libs
return slices_libs
@timeit
def iter_all_seq(
input_sequences,
template_json_file,
match_output_filename,
reconstruction_output_filename,
threshold=0.99,
):
sequences = get_sequences(input_sequences)
seq_filenames = []
for seq in sequences:
for filename in seq:
seq_filenames.append(filename)
r = []
for filename in seq_filenames:
sq = Sequence(filename)
json_to_output = {}
json_to_output["target"] = sq.name
logging.info(f"Target sequence: {sq.name}")
with open(template_json_file) as json_file:
template = json.load(json_file)
template["template"]
libs = get_slices_libs(template)
libs_to_match = libs["construct"]
matches = match_libs(sq, libs_to_match, threshold=threshold)
json_to_output["matches"] = matches
r.append(json_to_output)
with open(match_output_filename, "w") as filename:
json.dump(r, filename, indent=2, separators=(",", ":"))
def match(template, threshold=0.99, *targets):
with open(template) as json_file:
template = json.load(json_file)
r = []
for target in targets:
sq = Sequence(target)
json_to_output = {}
json_to_output["target"] = sq.name
libs = get_slices_libs(template)
libs_to_match = libs["construct"]
matches = match_libs(sq, libs_to_match, threshold=threshold)
json_to_output["matches"] = matches
r.append(json_to_output)
s = json.dumps(r, indent=2, separators=(",", ":"))
reconstruction_result = reconstruct(r)
ss = json.dumps(reconstruction_result, indent=2, separators=(",", ":"))
return ss
@plac.pos("template", "JSON construct template. Example: consruct_template.json")
@plac.pos("targets", f"Target sequence files. Example: Sanger008.seq", type=str)
@plac.opt("threshold", "Threshold", type=float)
def main(template, threshold=0.99, *targets):
result = match(template, threshold, *targets)
print(result)
if __name__ == "__main__":
plac.call(main)
| true | true |
f72a37e5373aa4e623b73750d93d8aba42a35bcd | 929 | py | Python | jobs/pitch_deformer.py | nSimonFR/spoken_language_dataset | 07c018f28be72cec3ba5e9ec07608f79a6d32031 | [
"MIT"
] | 23 | 2018-06-25T10:22:57.000Z | 2021-07-09T09:53:47.000Z | jobs/pitch_deformer.py | nSimonFR/spoken_language_dataset | 07c018f28be72cec3ba5e9ec07608f79a6d32031 | [
"MIT"
] | 3 | 2018-07-19T18:47:07.000Z | 2021-06-01T22:11:53.000Z | jobs/pitch_deformer.py | nSimonFR/spoken_language_dataset | 07c018f28be72cec3ba5e9ec07608f79a6d32031 | [
"MIT"
] | 6 | 2018-07-14T17:48:51.000Z | 2020-12-24T01:31:41.000Z | from . import common
from audio_toolbox import sox
class PitchDeformer:
SUFFIX = '.pitch@n'
def __init__(self, input_files_key, output_files_key, semitones):
self.input_files_key = input_files_key
self.output_files_key = output_files_key
self.semitones = semitones
def execute(self, context):
input_files = context[self.input_files_key]
output_files = context[self.output_files_key] = []
for input_file in input_files:
output_pattern = common.append_suffix_to_filename(
input_file, PitchDeformer.SUFFIX)
for index, semitone in enumerate(self.semitones):
# start indexing with 1 to be compatible with sox
output_file = output_pattern.replace('@n', str(index + 1))
output_files.append(output_file)
sox.adjust_pitch(input_file, output_file, semitone=semitone)
| 33.178571 | 76 | 0.665231 | from . import common
from audio_toolbox import sox
class PitchDeformer:
SUFFIX = '.pitch@n'
def __init__(self, input_files_key, output_files_key, semitones):
self.input_files_key = input_files_key
self.output_files_key = output_files_key
self.semitones = semitones
def execute(self, context):
input_files = context[self.input_files_key]
output_files = context[self.output_files_key] = []
for input_file in input_files:
output_pattern = common.append_suffix_to_filename(
input_file, PitchDeformer.SUFFIX)
for index, semitone in enumerate(self.semitones):
output_file = output_pattern.replace('@n', str(index + 1))
output_files.append(output_file)
sox.adjust_pitch(input_file, output_file, semitone=semitone)
| true | true |
f72a37ebb93db977a1a827e2699a50ef563720f7 | 4,654 | py | Python | app/user/tests/test_user_api.py | gmarshall142/appservices | 2dae37dfe6693a3f61f3561cabfaff78ad7616e4 | [
"MIT"
] | null | null | null | app/user/tests/test_user_api.py | gmarshall142/appservices | 2dae37dfe6693a3f61f3561cabfaff78ad7616e4 | [
"MIT"
] | null | null | null | app/user/tests/test_user_api.py | gmarshall142/appservices | 2dae37dfe6693a3f61f3561cabfaff78ad7616e4 | [
"MIT"
] | null | null | null | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reverse('user:me')
def create_user(**params):
return get_user_model().objects.create_user(**params)
class PublicUserApiTests(TestCase):
"""Test the users API (public)"""
def setup(self):
self.client = APIClient()
def test_create_valid_user_success(self):
"""Test creating user with valid payload is successful"""
payload = {
'email': 'test@londonappdev.com',
'password': 'testpass',
'name': 'Test name'
}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
user = get_user_model().objects.get(**res.data)
self.assertTrue(user.check_password(payload['password']))
self.assertNotIn('password', res.data)
def test_user_exists(self):
"""Test creating a user that already exists fails"""
payload = {'email': 'test@londonappdev.com', 'password': 'testpass'}
create_user(**payload)
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_password_too_short(self):
"""Test that the password must be more than 5 characters"""
payload = {'email': 'test@londonappdev.com', 'password': 'pw'}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
user_exists = get_user_model().objects.filter(
email=payload['email']
).exists()
self.assertFalse(user_exists)
def test_create_token_for_user(self):
"""Test that a token is created for the user"""
payload = {'email': 'test@londonappdev.com', 'password': 'testpass'}
create_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_200_OK)
def test_create_token_invalid_credentials(self):
"""Test that token is not created if invalid credentials are given"""
create_user(email='test@londeonappdev.com', password='testpass')
payload = {'email': 'test@londonappdev.com', 'password': 'wrong'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_token_no_user(self):
"""Test that token is not created if user doesn't exist"""
payload = {'email': 'test@londonappdev.com', 'password': 'testpass'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_token_missing_field(self):
"""Test that email and password are required"""
res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''})
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
class PrivateUserApiTests(TestCase):
"""Test API requests that require authentication"""
def setUp(self):
self.user = create_user(
email='test@londonappdev.com',
password='testpass',
name='name'
)
self.client = APIClient()
self.client.force_authenticate(user=self.user)
def test_retrieve_profile_success(self):
"""Test retrieving profile for logged in used"""
res = self.client.get(ME_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, {
'name': self.user.name,
'email': self.user.email
})
def test_post_me_not_allowed(self):
"""Test that POST is not allowed on the me url"""
res = self.client.post(ME_URL, {})
self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_update_user_profile(self):
"""Test updating the user profile for authenticated user"""
payload = {'name': 'new name', 'password': 'newpassword123'}
res = self.client.patch(ME_URL, payload)
self.user.refresh_from_db()
self.assertEqual(self.user.name, payload['name'])
self.assertTrue(self.user.check_password(payload['password']))
self.assertEqual(res.status_code, status.HTTP_200_OK)
| 37.232 | 77 | 0.662226 | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reverse('user:me')
def create_user(**params):
return get_user_model().objects.create_user(**params)
class PublicUserApiTests(TestCase):
def setup(self):
self.client = APIClient()
def test_create_valid_user_success(self):
payload = {
'email': 'test@londonappdev.com',
'password': 'testpass',
'name': 'Test name'
}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
user = get_user_model().objects.get(**res.data)
self.assertTrue(user.check_password(payload['password']))
self.assertNotIn('password', res.data)
def test_user_exists(self):
payload = {'email': 'test@londonappdev.com', 'password': 'testpass'}
create_user(**payload)
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_password_too_short(self):
payload = {'email': 'test@londonappdev.com', 'password': 'pw'}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
user_exists = get_user_model().objects.filter(
email=payload['email']
).exists()
self.assertFalse(user_exists)
def test_create_token_for_user(self):
payload = {'email': 'test@londonappdev.com', 'password': 'testpass'}
create_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_200_OK)
def test_create_token_invalid_credentials(self):
create_user(email='test@londeonappdev.com', password='testpass')
payload = {'email': 'test@londonappdev.com', 'password': 'wrong'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_token_no_user(self):
payload = {'email': 'test@londonappdev.com', 'password': 'testpass'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_token_missing_field(self):
res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''})
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
class PrivateUserApiTests(TestCase):
def setUp(self):
self.user = create_user(
email='test@londonappdev.com',
password='testpass',
name='name'
)
self.client = APIClient()
self.client.force_authenticate(user=self.user)
def test_retrieve_profile_success(self):
res = self.client.get(ME_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, {
'name': self.user.name,
'email': self.user.email
})
def test_post_me_not_allowed(self):
res = self.client.post(ME_URL, {})
self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_update_user_profile(self):
payload = {'name': 'new name', 'password': 'newpassword123'}
res = self.client.patch(ME_URL, payload)
self.user.refresh_from_db()
self.assertEqual(self.user.name, payload['name'])
self.assertTrue(self.user.check_password(payload['password']))
self.assertEqual(res.status_code, status.HTTP_200_OK)
| true | true |
f72a38772dfca7924eadc81291de0091589ed69c | 1,788 | py | Python | samples/generated_samples/aiplatform_generated_aiplatform_v1_job_service_delete_hyperparameter_tuning_job_async.py | lclc19/python-aiplatform | d8da2e365277441abadb04328943f23345d72b0e | [
"Apache-2.0"
] | 180 | 2020-09-23T17:21:15.000Z | 2022-03-30T17:25:47.000Z | samples/generated_samples/aiplatform_generated_aiplatform_v1_job_service_delete_hyperparameter_tuning_job_async.py | lclc19/python-aiplatform | d8da2e365277441abadb04328943f23345d72b0e | [
"Apache-2.0"
] | 601 | 2020-09-23T16:23:44.000Z | 2022-03-31T19:08:23.000Z | samples/generated_samples/aiplatform_generated_aiplatform_v1_job_service_delete_hyperparameter_tuning_job_async.py | lclc19/python-aiplatform | d8da2e365277441abadb04328943f23345d72b0e | [
"Apache-2.0"
] | 109 | 2020-09-23T16:22:04.000Z | 2022-03-28T21:18:29.000Z | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteHyperparameterTuningJob
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_generated_aiplatform_v1_JobService_DeleteHyperparameterTuningJob_async]
from google.cloud import aiplatform_v1
async def sample_delete_hyperparameter_tuning_job():
"""Snippet for delete_hyperparameter_tuning_job"""
# Create a client
client = aiplatform_v1.JobServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1.DeleteHyperparameterTuningJobRequest(
name="projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}",
)
# Make the request
operation = client.delete_hyperparameter_tuning_job(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
print(response)
# [END aiplatform_generated_aiplatform_v1_JobService_DeleteHyperparameterTuningJob_async]
| 35.76 | 108 | 0.779083 |
from google.cloud import aiplatform_v1
async def sample_delete_hyperparameter_tuning_job():
client = aiplatform_v1.JobServiceAsyncClient()
request = aiplatform_v1.DeleteHyperparameterTuningJobRequest(
name="projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}",
)
operation = client.delete_hyperparameter_tuning_job(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
print(response)
| true | true |
f72a38aef278e33aedce4abdf04469c32de8d0bd | 1,510 | py | Python | minecraft/config.py | leosumi/Minecraft | 4215bf0fe0b0e2fd386b1990a4589afc239879a7 | [
"MIT"
] | null | null | null | minecraft/config.py | leosumi/Minecraft | 4215bf0fe0b0e2fd386b1990a4589afc239879a7 | [
"MIT"
] | null | null | null | minecraft/config.py | leosumi/Minecraft | 4215bf0fe0b0e2fd386b1990a4589afc239879a7 | [
"MIT"
] | null | null | null | import math
import configparser
from util import tex_coords
CONFIG_PATH = "config.ini"
config = configparser.ConfigParser()
config.read(CONFIG_PATH)
WIDTH = config.getint("window", "width")
HEIGHT = config.getint("window", "height")
CAPTION = config["window"]["caption"]
TICKS_PER_SEC = config.getint("game", "ticks_per_sec")
# Size of sectors used to ease block loading.
SECTOR_SIZE = config.getint("game", "sector_size")
WALKING_SPEED = config.getint("player", "walking_speed")
FLYING_SPEED = config.getint("player", "flying_speed")
GRAVITY = config.getfloat("world", "gravity")
MAX_JUMP_HEIGHT = config.getfloat("player", "max_jump_height") # About the height of a block.
# To derive the formula for calculating jump speed, first solve
# v_t = v_0 + a * t
# for the time at which you achieve maximum height, where a is the acceleration
# due to gravity and v_t = 0. This gives:
# t = - v_0 / a
# Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in
# s = s_0 + v_0 * t + (a * t^2) / 2
JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT)
TERMINAL_VELOCITY = config.getint("world", "terminal_velocity")
PLAYER_HEIGHT = config.getint("player", "player_height")
TEXTURE_PATH = 'texture.png'
GRASS = tex_coords((1, 0), (0, 1), (0, 0))
SAND = tex_coords((1, 1), (1, 1), (1, 1))
BRICK = tex_coords((2, 0), (2, 0), (2, 0))
STONE = tex_coords((2, 1), (2, 1), (2, 1))
FACES = [
( 0, 1, 0),
( 0,-1, 0),
(-1, 0, 0),
( 1, 0, 0),
( 0, 0, 1),
( 0, 0,-1),
]
| 29.038462 | 93 | 0.662252 | import math
import configparser
from util import tex_coords
CONFIG_PATH = "config.ini"
config = configparser.ConfigParser()
config.read(CONFIG_PATH)
WIDTH = config.getint("window", "width")
HEIGHT = config.getint("window", "height")
CAPTION = config["window"]["caption"]
TICKS_PER_SEC = config.getint("game", "ticks_per_sec")
SECTOR_SIZE = config.getint("game", "sector_size")
WALKING_SPEED = config.getint("player", "walking_speed")
FLYING_SPEED = config.getint("player", "flying_speed")
GRAVITY = config.getfloat("world", "gravity")
MAX_JUMP_HEIGHT = config.getfloat("player", "max_jump_height")
JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT)
TERMINAL_VELOCITY = config.getint("world", "terminal_velocity")
PLAYER_HEIGHT = config.getint("player", "player_height")
TEXTURE_PATH = 'texture.png'
GRASS = tex_coords((1, 0), (0, 1), (0, 0))
SAND = tex_coords((1, 1), (1, 1), (1, 1))
BRICK = tex_coords((2, 0), (2, 0), (2, 0))
STONE = tex_coords((2, 1), (2, 1), (2, 1))
FACES = [
( 0, 1, 0),
( 0,-1, 0),
(-1, 0, 0),
( 1, 0, 0),
( 0, 0, 1),
( 0, 0,-1),
]
| true | true |
f72a39b2dc13c27df0c09468e6d52f23ae747f9d | 10,696 | py | Python | packages/amplify-graphql-searchable-transformer/streaming-lambda/python_streaming_function.py | jcbdev/amplify-cli | 08f7a3c45b2e98535ef325eb0a97c5bc4d3008c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | packages/amplify-graphql-searchable-transformer/streaming-lambda/python_streaming_function.py | jcbdev/amplify-cli | 08f7a3c45b2e98535ef325eb0a97c5bc4d3008c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | packages/amplify-graphql-searchable-transformer/streaming-lambda/python_streaming_function.py | jcbdev/amplify-cli | 08f7a3c45b2e98535ef325eb0a97c5bc4d3008c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | import base64
import json
import logging
import os
import time
import traceback
from urllib.parse import urlparse, quote
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import get_credentials
from botocore.endpoint import BotocoreHTTPSession
from botocore.session import Session
from boto3.dynamodb.types import TypeDeserializer
# The following parameters are required to configure the ES cluster
ES_ENDPOINT = os.environ['ES_ENDPOINT']
ES_REGION = os.environ['ES_REGION']
DEBUG = True if os.environ['DEBUG'] == "1" else False
ES_USE_EXTERNAL_VERSIONING = True if os.environ['ES_USE_EXTERNAL_VERSIONING'] == "true" else False
# ElasticSearch 6 deprecated having multiple mapping types in an index. Default to doc.
DOC_TYPE = 'doc'
ES_MAX_RETRIES = 3 # Max number of retries for exponential backoff
logger = logging.getLogger()
logger.setLevel(logging.DEBUG if DEBUG else logging.INFO)
logger.info("Streaming to ElasticSearch")
# custom encoder changes
# - sets to lists
class DDBTypesEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
# Subclass of boto's TypeDeserializer for DynamoDB to adjust for DynamoDB Stream format.
class StreamTypeDeserializer(TypeDeserializer):
def _deserialize_n(self, value):
return float(value)
def _deserialize_b(self, value):
return value # Already in Base64
class ES_Exception(Exception):
'''Capture status_code from request'''
status_code = 0
payload = ''
def __init__(self, status_code, payload):
self.status_code = status_code
self.payload = payload
Exception.__init__(
self, 'ES_Exception: status_code={}, payload={}'.format(status_code, payload))
# Low-level POST data to Amazon Elasticsearch Service generating a Sigv4 signed request
def post_data_to_es(payload, region, creds, host, path, method='POST', proto='https://'):
'''Post data to ES endpoint with SigV4 signed http headers'''
req = AWSRequest(method=method, url=proto + host +
quote(path), data=payload, headers={'Host': host, 'Content-Type': 'application/json'})
SigV4Auth(creds, 'es', region).add_auth(req)
http_session = BotocoreHTTPSession()
res = http_session.send(req.prepare())
if res.status_code >= 200 and res.status_code <= 299:
return res._content
else:
raise ES_Exception(res.status_code, res._content)
# High-level POST data to Amazon Elasticsearch Service with exponential backoff
# according to suggested algorithm: http://docs.aws.amazon.com/general/latest/gr/api-retries.html
def post_to_es(payload):
'''Post data to ES cluster with exponential backoff'''
# Get aws_region and credentials to post signed URL to ES
es_region = ES_REGION or os.environ['AWS_REGION']
session = Session({'region': es_region})
creds = get_credentials(session)
es_url = urlparse(ES_ENDPOINT)
# Extract the domain name in ES_ENDPOINT
es_endpoint = es_url.netloc or es_url.path
# Post data with exponential backoff
retries = 0
while retries < ES_MAX_RETRIES:
if retries > 0:
seconds = (2 ** retries) * .1
logger.debug('Waiting for %.1f seconds', seconds)
time.sleep(seconds)
try:
es_ret_str = post_data_to_es(
payload, es_region, creds, es_endpoint, '/_bulk')
logger.debug('Return from ES: %s', es_ret_str)
es_ret = json.loads(es_ret_str)
if es_ret['errors']:
logger.error(
'ES post unsuccessful, errors present, took=%sms', es_ret['took'])
# Filter errors
es_errors = [item for item in es_ret['items']
if item.get('index', {}).get('error')]
logger.error('List of items with errors: %s',
json.dumps(es_errors))
else:
logger.info('ES post successful, took=%sms', es_ret['took'])
break # Sending to ES was ok, break retry loop
except ES_Exception as e:
if (e.status_code >= 500) and (e.status_code <= 599):
retries += 1 # Candidate for retry
else:
raise # Stop retrying, re-raise exception
# Extracts the DynamoDB table from an ARN
# ex: arn:aws:dynamodb:eu-west-1:123456789012:table/table-name/stream/2015-11-13T09:23:17.104 should return 'table-name'
def get_table_name_from_arn(arn):
return arn.split(':')[5].split('/')[1]
# Compute a compound doc index from the key(s) of the object in lexicographic order: "k1=key_val1|k2=key_val2"
def compute_doc_index(keys_raw, deserializer, formatIndex=False):
index = []
for key in sorted(keys_raw):
if formatIndex:
index.append('{}={}'.format(
key, deserializer.deserialize(keys_raw[key])))
else:
index.append(deserializer.deserialize(keys_raw[key]))
return '|'.join(map(str,index))
def _lambda_handler(event, context):
logger.debug('Event: %s', event)
records = event['Records']
ddb_deserializer = StreamTypeDeserializer()
es_actions = [] # Items to be added/updated/removed from ES - for bulk API
cnt_insert = cnt_modify = cnt_remove = 0
for record in records:
# Handle both native DynamoDB Streams or Streams data from Kinesis (for manual replay)
logger.debug('Record: %s', record)
if record.get('eventSource') == 'aws:dynamodb':
ddb = record['dynamodb']
ddb_table_name = get_table_name_from_arn(record['eventSourceARN'])
doc_seq = ddb['SequenceNumber']
elif record.get('eventSource') == 'aws:kinesis':
ddb = json.loads(base64.b64decode(record['kinesis']['data']))
ddb_table_name = ddb['SourceTable']
doc_seq = record['kinesis']['sequenceNumber']
else:
logger.error('Ignoring non-DynamoDB event sources: %s',
record.get('eventSource'))
continue
# Compute DynamoDB table, type and index for item
doc_table = ddb_table_name.lower()
doc_type = DOC_TYPE
doc_table_parts = doc_table.split('-')
doc_es_index_name = doc_table_parts[0] if len(doc_table_parts) > 0 else doc_table
# Dispatch according to event TYPE
event_name = record['eventName'].upper() # INSERT, MODIFY, REMOVE
logger.debug('doc_table=%s, event_name=%s, seq=%s',
doc_table, event_name, doc_seq)
# Treat events from a Kinesis stream as INSERTs
if event_name == 'AWS:KINESIS:RECORD':
event_name = 'INSERT'
is_ddb_insert_or_update = (event_name == 'INSERT') or (event_name == 'MODIFY')
is_ddb_delete = event_name == 'REMOVE'
image_name = 'NewImage' if is_ddb_insert_or_update else 'OldImage'
if image_name not in ddb:
logger.warning(
'Cannot process stream if it does not contain ' + image_name)
continue
logger.debug(image_name + ': %s', ddb[image_name])
# Deserialize DynamoDB type to Python types
doc_fields = ddb_deserializer.deserialize({'M': ddb[image_name]})
# Sync enabled APIs do soft delete. We need to delete the record in ES if _deleted field is set
if ES_USE_EXTERNAL_VERSIONING and event_name == 'MODIFY' and '_deleted' in doc_fields and doc_fields['_deleted']:
is_ddb_insert_or_update = False
is_ddb_delete = True
# Update counters
if event_name == 'INSERT':
cnt_insert += 1
elif event_name == 'MODIFY':
cnt_modify += 1
elif event_name == 'REMOVE':
cnt_remove += 1
else:
logger.warning('Unsupported event_name: %s', event_name)
logger.debug('Deserialized doc_fields: %s', doc_fields)
if ('Keys' in ddb):
doc_id = compute_doc_index(ddb['Keys'], ddb_deserializer)
else:
logger.error('Cannot find keys in ddb record')
# If DynamoDB INSERT or MODIFY, send 'index' to ES
if is_ddb_insert_or_update:
# Generate ES payload for item
action = {'index': {'_index': doc_es_index_name,
'_type': doc_type,
'_id': doc_id}}
# Add external versioning if necessary
if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields:
action['index'].update([
('version_type', 'external'),
('_version', doc_fields['_version'])
])
doc_fields.pop('_ttl', None)
doc_fields.pop('_version', None)
# Append ES Action line with 'index' directive
es_actions.append(json.dumps(action))
# Append JSON payload
es_actions.append(json.dumps(doc_fields, cls=DDBTypesEncoder))
# migration step remove old key if it exists
if ('id' in doc_fields) and (event_name == 'MODIFY') :
action = {'delete': {'_index': doc_es_index_name, '_type': doc_type,
'_id': compute_doc_index(ddb['Keys'], ddb_deserializer, True)}}
es_actions.append(json.dumps(action))
# If DynamoDB REMOVE, send 'delete' to ES
elif is_ddb_delete:
action = {'delete': {'_index': doc_es_index_name,
'_type': doc_type, '_id': doc_id}}
if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields:
action['delete'].update([
('version_type', 'external'),
('_version', doc_fields['_version'])
])
# Action line with 'delete' directive
es_actions.append(json.dumps(action))
# Prepare bulk payload
es_actions.append('') # Add one empty line to force final \n
es_payload = '\n'.join(es_actions)
logger.info('Posting to ES: inserts=%s updates=%s deletes=%s, total_lines=%s, bytes_total=%s',
cnt_insert, cnt_modify, cnt_remove, len(es_actions) - 1, len(es_payload))
post_to_es(es_payload) # Post to ES with exponential backoff
# Global lambda handler - catches all exceptions to avoid dead letter in the DynamoDB Stream
def lambda_handler(event, context):
try:
return _lambda_handler(event, context)
except Exception:
logger.error(traceback.format_exc())
| 41.457364 | 122 | 0.63089 | import base64
import json
import logging
import os
import time
import traceback
from urllib.parse import urlparse, quote
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import get_credentials
from botocore.endpoint import BotocoreHTTPSession
from botocore.session import Session
from boto3.dynamodb.types import TypeDeserializer
ES_ENDPOINT = os.environ['ES_ENDPOINT']
ES_REGION = os.environ['ES_REGION']
DEBUG = True if os.environ['DEBUG'] == "1" else False
ES_USE_EXTERNAL_VERSIONING = True if os.environ['ES_USE_EXTERNAL_VERSIONING'] == "true" else False
DOC_TYPE = 'doc'
ES_MAX_RETRIES = 3
logger = logging.getLogger()
logger.setLevel(logging.DEBUG if DEBUG else logging.INFO)
logger.info("Streaming to ElasticSearch")
class DDBTypesEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
class StreamTypeDeserializer(TypeDeserializer):
def _deserialize_n(self, value):
return float(value)
def _deserialize_b(self, value):
return value # Already in Base64
class ES_Exception(Exception):
status_code = 0
payload = ''
def __init__(self, status_code, payload):
self.status_code = status_code
self.payload = payload
Exception.__init__(
self, 'ES_Exception: status_code={}, payload={}'.format(status_code, payload))
# Low-level POST data to Amazon Elasticsearch Service generating a Sigv4 signed request
def post_data_to_es(payload, region, creds, host, path, method='POST', proto='https://'):
req = AWSRequest(method=method, url=proto + host +
quote(path), data=payload, headers={'Host': host, 'Content-Type': 'application/json'})
SigV4Auth(creds, 'es', region).add_auth(req)
http_session = BotocoreHTTPSession()
res = http_session.send(req.prepare())
if res.status_code >= 200 and res.status_code <= 299:
return res._content
else:
raise ES_Exception(res.status_code, res._content)
# High-level POST data to Amazon Elasticsearch Service with exponential backoff
# according to suggested algorithm: http://docs.aws.amazon.com/general/latest/gr/api-retries.html
def post_to_es(payload):
# Get aws_region and credentials to post signed URL to ES
es_region = ES_REGION or os.environ['AWS_REGION']
session = Session({'region': es_region})
creds = get_credentials(session)
es_url = urlparse(ES_ENDPOINT)
# Extract the domain name in ES_ENDPOINT
es_endpoint = es_url.netloc or es_url.path
# Post data with exponential backoff
retries = 0
while retries < ES_MAX_RETRIES:
if retries > 0:
seconds = (2 ** retries) * .1
logger.debug('Waiting for %.1f seconds', seconds)
time.sleep(seconds)
try:
es_ret_str = post_data_to_es(
payload, es_region, creds, es_endpoint, '/_bulk')
logger.debug('Return from ES: %s', es_ret_str)
es_ret = json.loads(es_ret_str)
if es_ret['errors']:
logger.error(
'ES post unsuccessful, errors present, took=%sms', es_ret['took'])
# Filter errors
es_errors = [item for item in es_ret['items']
if item.get('index', {}).get('error')]
logger.error('List of items with errors: %s',
json.dumps(es_errors))
else:
logger.info('ES post successful, took=%sms', es_ret['took'])
break # Sending to ES was ok, break retry loop
except ES_Exception as e:
if (e.status_code >= 500) and (e.status_code <= 599):
retries += 1 # Candidate for retry
else:
raise # Stop retrying, re-raise exception
# Extracts the DynamoDB table from an ARN
# ex: arn:aws:dynamodb:eu-west-1:123456789012:table/table-name/stream/2015-11-13T09:23:17.104 should return 'table-name'
def get_table_name_from_arn(arn):
return arn.split(':')[5].split('/')[1]
# Compute a compound doc index from the key(s) of the object in lexicographic order: "k1=key_val1|k2=key_val2"
def compute_doc_index(keys_raw, deserializer, formatIndex=False):
index = []
for key in sorted(keys_raw):
if formatIndex:
index.append('{}={}'.format(
key, deserializer.deserialize(keys_raw[key])))
else:
index.append(deserializer.deserialize(keys_raw[key]))
return '|'.join(map(str,index))
def _lambda_handler(event, context):
logger.debug('Event: %s', event)
records = event['Records']
ddb_deserializer = StreamTypeDeserializer()
es_actions = [] # Items to be added/updated/removed from ES - for bulk API
cnt_insert = cnt_modify = cnt_remove = 0
for record in records:
# Handle both native DynamoDB Streams or Streams data from Kinesis (for manual replay)
logger.debug('Record: %s', record)
if record.get('eventSource') == 'aws:dynamodb':
ddb = record['dynamodb']
ddb_table_name = get_table_name_from_arn(record['eventSourceARN'])
doc_seq = ddb['SequenceNumber']
elif record.get('eventSource') == 'aws:kinesis':
ddb = json.loads(base64.b64decode(record['kinesis']['data']))
ddb_table_name = ddb['SourceTable']
doc_seq = record['kinesis']['sequenceNumber']
else:
logger.error('Ignoring non-DynamoDB event sources: %s',
record.get('eventSource'))
continue
# Compute DynamoDB table, type and index for item
doc_table = ddb_table_name.lower()
doc_type = DOC_TYPE
doc_table_parts = doc_table.split('-')
doc_es_index_name = doc_table_parts[0] if len(doc_table_parts) > 0 else doc_table
# Dispatch according to event TYPE
event_name = record['eventName'].upper() # INSERT, MODIFY, REMOVE
logger.debug('doc_table=%s, event_name=%s, seq=%s',
doc_table, event_name, doc_seq)
# Treat events from a Kinesis stream as INSERTs
if event_name == 'AWS:KINESIS:RECORD':
event_name = 'INSERT'
is_ddb_insert_or_update = (event_name == 'INSERT') or (event_name == 'MODIFY')
is_ddb_delete = event_name == 'REMOVE'
image_name = 'NewImage' if is_ddb_insert_or_update else 'OldImage'
if image_name not in ddb:
logger.warning(
'Cannot process stream if it does not contain ' + image_name)
continue
logger.debug(image_name + ': %s', ddb[image_name])
# Deserialize DynamoDB type to Python types
doc_fields = ddb_deserializer.deserialize({'M': ddb[image_name]})
# Sync enabled APIs do soft delete. We need to delete the record in ES if _deleted field is set
if ES_USE_EXTERNAL_VERSIONING and event_name == 'MODIFY' and '_deleted' in doc_fields and doc_fields['_deleted']:
is_ddb_insert_or_update = False
is_ddb_delete = True
# Update counters
if event_name == 'INSERT':
cnt_insert += 1
elif event_name == 'MODIFY':
cnt_modify += 1
elif event_name == 'REMOVE':
cnt_remove += 1
else:
logger.warning('Unsupported event_name: %s', event_name)
logger.debug('Deserialized doc_fields: %s', doc_fields)
if ('Keys' in ddb):
doc_id = compute_doc_index(ddb['Keys'], ddb_deserializer)
else:
logger.error('Cannot find keys in ddb record')
# If DynamoDB INSERT or MODIFY, send 'index' to ES
if is_ddb_insert_or_update:
# Generate ES payload for item
action = {'index': {'_index': doc_es_index_name,
'_type': doc_type,
'_id': doc_id}}
# Add external versioning if necessary
if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields:
action['index'].update([
('version_type', 'external'),
('_version', doc_fields['_version'])
])
doc_fields.pop('_ttl', None)
doc_fields.pop('_version', None)
# Append ES Action line with 'index' directive
es_actions.append(json.dumps(action))
# Append JSON payload
es_actions.append(json.dumps(doc_fields, cls=DDBTypesEncoder))
# migration step remove old key if it exists
if ('id' in doc_fields) and (event_name == 'MODIFY') :
action = {'delete': {'_index': doc_es_index_name, '_type': doc_type,
'_id': compute_doc_index(ddb['Keys'], ddb_deserializer, True)}}
es_actions.append(json.dumps(action))
# If DynamoDB REMOVE, send 'delete' to ES
elif is_ddb_delete:
action = {'delete': {'_index': doc_es_index_name,
'_type': doc_type, '_id': doc_id}}
if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields:
action['delete'].update([
('version_type', 'external'),
('_version', doc_fields['_version'])
])
# Action line with 'delete' directive
es_actions.append(json.dumps(action))
# Prepare bulk payload
es_actions.append('') # Add one empty line to force final \n
es_payload = '\n'.join(es_actions)
logger.info('Posting to ES: inserts=%s updates=%s deletes=%s, total_lines=%s, bytes_total=%s',
cnt_insert, cnt_modify, cnt_remove, len(es_actions) - 1, len(es_payload))
post_to_es(es_payload) # Post to ES with exponential backoff
# Global lambda handler - catches all exceptions to avoid dead letter in the DynamoDB Stream
def lambda_handler(event, context):
try:
return _lambda_handler(event, context)
except Exception:
logger.error(traceback.format_exc())
| true | true |
f72a3a7ba2336005b049f9e3a57c4f4b44ad48b8 | 47 | py | Python | docs/test-dataset/code/some-code.py | slugb0t/SODA-for-SPARC | f2dd5f5817984ca0a500dd628f8055a6a0d1ff48 | [
"MIT"
] | 16 | 2019-11-19T02:19:16.000Z | 2022-01-09T04:51:50.000Z | docs/test-dataset/code/some-code.py | slugb0t/SODA-for-SPARC | f2dd5f5817984ca0a500dd628f8055a6a0d1ff48 | [
"MIT"
] | 6 | 2020-06-17T19:37:08.000Z | 2021-08-03T21:01:25.000Z | docs/test-dataset/code/some-code.py | slugb0t/SODA-for-SPARC | f2dd5f5817984ca0a500dd628f8055a6a0d1ff48 | [
"MIT"
] | 7 | 2019-11-08T20:45:32.000Z | 2021-09-15T22:45:18.000Z | print('Hello! This is an example python file.') | 47 | 47 | 0.744681 | print('Hello! This is an example python file.') | true | true |
f72a3bfc43a32b945e3678a36f687019936e886c | 2,966 | py | Python | nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py | nicholsn/nipype | 6601b00aac39d17bb9fb3a6801f5a740a6ebb1e3 | [
"BSD-3-Clause"
] | 1 | 2018-04-18T12:13:37.000Z | 2018-04-18T12:13:37.000Z | nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py | ito-takuya/nipype | 9099a5809487b55868cdec82a719030419cbd6ba | [
"BSD-3-Clause"
] | null | null | null | nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py | ito-takuya/nipype | 9099a5809487b55868cdec82a719030419cbd6ba | [
"BSD-3-Clause"
] | 1 | 2021-09-08T14:31:47.000Z | 2021-09-08T14:31:47.000Z | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.freesurfer.utils import SurfaceSnapshots
def test_SurfaceSnapshots_inputs():
input_map = dict(annot_file=dict(argstr='-annotation %s',
xor=['annot_name'],
),
annot_name=dict(argstr='-annotation %s',
xor=['annot_file'],
),
args=dict(argstr='%s',
),
colortable=dict(argstr='-colortable %s',
),
demean_overlay=dict(argstr='-zm',
),
environ=dict(nohash=True,
usedefault=True,
),
hemi=dict(argstr='%s',
mandatory=True,
position=2,
),
identity_reg=dict(argstr='-overlay-reg-identity',
xor=['overlay_reg', 'identity_reg', 'mni152_reg'],
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
invert_overlay=dict(argstr='-invphaseflag 1',
),
label_file=dict(argstr='-label %s',
xor=['label_name'],
),
label_name=dict(argstr='-label %s',
xor=['label_file'],
),
label_outline=dict(argstr='-label-outline',
),
label_under=dict(argstr='-labels-under',
),
mni152_reg=dict(argstr='-mni152reg',
xor=['overlay_reg', 'identity_reg', 'mni152_reg'],
),
orig_suffix=dict(argstr='-orig %s',
),
overlay=dict(argstr='-overlay %s',
requires=['overlay_range'],
),
overlay_range=dict(argstr='%s',
),
overlay_range_offset=dict(argstr='-foffset %.3f',
),
overlay_reg=dict(argstr='-overlay-reg %s',
xor=['overlay_reg', 'identity_reg', 'mni152_reg'],
),
patch_file=dict(argstr='-patch %s',
),
reverse_overlay=dict(argstr='-revphaseflag 1',
),
screenshot_stem=dict(),
show_color_scale=dict(argstr='-colscalebarflag 1',
),
show_color_text=dict(argstr='-colscaletext 1',
),
show_curv=dict(argstr='-curv',
xor=['show_gray_curv'],
),
show_gray_curv=dict(argstr='-gray',
xor=['show_curv'],
),
six_images=dict(),
sphere_suffix=dict(argstr='-sphere %s',
),
stem_template_args=dict(requires=['screenshot_stem'],
),
subject_id=dict(argstr='%s',
mandatory=True,
position=1,
),
subjects_dir=dict(),
surface=dict(argstr='%s',
mandatory=True,
position=3,
),
tcl_script=dict(argstr='%s',
genfile=True,
),
terminal_output=dict(mandatory=True,
nohash=True,
),
truncate_overlay=dict(argstr='-truncphaseflag 1',
),
)
inputs = SurfaceSnapshots.input_spec()
for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_SurfaceSnapshots_outputs():
output_map = dict(snapshots=dict(),
)
outputs = SurfaceSnapshots.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| 26.720721 | 78 | 0.631827 |
from nipype.testing import assert_equal
from nipype.interfaces.freesurfer.utils import SurfaceSnapshots
def test_SurfaceSnapshots_inputs():
input_map = dict(annot_file=dict(argstr='-annotation %s',
xor=['annot_name'],
),
annot_name=dict(argstr='-annotation %s',
xor=['annot_file'],
),
args=dict(argstr='%s',
),
colortable=dict(argstr='-colortable %s',
),
demean_overlay=dict(argstr='-zm',
),
environ=dict(nohash=True,
usedefault=True,
),
hemi=dict(argstr='%s',
mandatory=True,
position=2,
),
identity_reg=dict(argstr='-overlay-reg-identity',
xor=['overlay_reg', 'identity_reg', 'mni152_reg'],
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
invert_overlay=dict(argstr='-invphaseflag 1',
),
label_file=dict(argstr='-label %s',
xor=['label_name'],
),
label_name=dict(argstr='-label %s',
xor=['label_file'],
),
label_outline=dict(argstr='-label-outline',
),
label_under=dict(argstr='-labels-under',
),
mni152_reg=dict(argstr='-mni152reg',
xor=['overlay_reg', 'identity_reg', 'mni152_reg'],
),
orig_suffix=dict(argstr='-orig %s',
),
overlay=dict(argstr='-overlay %s',
requires=['overlay_range'],
),
overlay_range=dict(argstr='%s',
),
overlay_range_offset=dict(argstr='-foffset %.3f',
),
overlay_reg=dict(argstr='-overlay-reg %s',
xor=['overlay_reg', 'identity_reg', 'mni152_reg'],
),
patch_file=dict(argstr='-patch %s',
),
reverse_overlay=dict(argstr='-revphaseflag 1',
),
screenshot_stem=dict(),
show_color_scale=dict(argstr='-colscalebarflag 1',
),
show_color_text=dict(argstr='-colscaletext 1',
),
show_curv=dict(argstr='-curv',
xor=['show_gray_curv'],
),
show_gray_curv=dict(argstr='-gray',
xor=['show_curv'],
),
six_images=dict(),
sphere_suffix=dict(argstr='-sphere %s',
),
stem_template_args=dict(requires=['screenshot_stem'],
),
subject_id=dict(argstr='%s',
mandatory=True,
position=1,
),
subjects_dir=dict(),
surface=dict(argstr='%s',
mandatory=True,
position=3,
),
tcl_script=dict(argstr='%s',
genfile=True,
),
terminal_output=dict(mandatory=True,
nohash=True,
),
truncate_overlay=dict(argstr='-truncphaseflag 1',
),
)
inputs = SurfaceSnapshots.input_spec()
for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_SurfaceSnapshots_outputs():
output_map = dict(snapshots=dict(),
)
outputs = SurfaceSnapshots.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| true | true |
f72a3c91953b5858fea12c86441ca8a3375897bc | 420 | py | Python | examples/quantum/hydrogen.py | olivierverdier/sfepy | 83aefb7b33ea17f4acb83388ba8bc7314c77616c | [
"BSD-3-Clause"
] | 1 | 2015-07-30T13:47:23.000Z | 2015-07-30T13:47:23.000Z | examples/quantum/hydrogen.py | olivierverdier/sfepy | 83aefb7b33ea17f4acb83388ba8bc7314c77616c | [
"BSD-3-Clause"
] | null | null | null | examples/quantum/hydrogen.py | olivierverdier/sfepy | 83aefb7b33ea17f4acb83388ba8bc7314c77616c | [
"BSD-3-Clause"
] | null | null | null | from sfepy.linalg import norm_l2_along_axis
from quantum_common import common
def fun_v(ts, coor, mode=None, region=None, ig=None):
from numpy import sqrt
if not mode == 'qp': return
out = {}
C = 0.5
r = norm_l2_along_axis(coor, axis=1)
V = - C * 1.0 / r
V.shape = (V.shape[0], 1, 1)
out['V'] = V
return out
def define():
l = common(fun_v, n_eigs=5, tau=-1.0)
return l
| 18.26087 | 53 | 0.597619 | from sfepy.linalg import norm_l2_along_axis
from quantum_common import common
def fun_v(ts, coor, mode=None, region=None, ig=None):
from numpy import sqrt
if not mode == 'qp': return
out = {}
C = 0.5
r = norm_l2_along_axis(coor, axis=1)
V = - C * 1.0 / r
V.shape = (V.shape[0], 1, 1)
out['V'] = V
return out
def define():
l = common(fun_v, n_eigs=5, tau=-1.0)
return l
| true | true |
f72a3ca047444fe42cfb054b4d7ce31ac8ea8792 | 322 | py | Python | djthia/dashboard/urls.py | carthage-college/django-djthia | a10026b305aa75e20d2ea8c5d3e7ad03c05f10f5 | [
"MIT"
] | null | null | null | djthia/dashboard/urls.py | carthage-college/django-djthia | a10026b305aa75e20d2ea8c5d3e7ad03c05f10f5 | [
"MIT"
] | 9 | 2020-08-02T13:58:23.000Z | 2022-02-15T15:30:58.000Z | djthia/dashboard/urls.py | carthage-college/django-djthia | a10026b305aa75e20d2ea8c5d3e7ad03c05f10f5 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""URLs for all views."""
from django.urls import path
from djthia.dashboard import views
urlpatterns = [
path('<str:oid>/detail/', views.detail, name='gearup_detail'),
path('search/', views.search, name='gearup_search'),
path('', views.home, name='dashboard_home'),
]
| 23 | 67 | 0.630435 |
from django.urls import path
from djthia.dashboard import views
urlpatterns = [
path('<str:oid>/detail/', views.detail, name='gearup_detail'),
path('search/', views.search, name='gearup_search'),
path('', views.home, name='dashboard_home'),
]
| true | true |
f72a3ce19ca0b74533a7945aaed6c0b03ba83aa2 | 33,034 | py | Python | optuna/storages/rdb/storage.py | scouvreur/optuna | 41716fe394aca87e5dce465443ac72ed53891a44 | [
"MIT"
] | null | null | null | optuna/storages/rdb/storage.py | scouvreur/optuna | 41716fe394aca87e5dce465443ac72ed53891a44 | [
"MIT"
] | null | null | null | optuna/storages/rdb/storage.py | scouvreur/optuna | 41716fe394aca87e5dce465443ac72ed53891a44 | [
"MIT"
] | null | null | null | import alembic.command
import alembic.config
import alembic.migration
import alembic.script
from collections import defaultdict
import copy
from datetime import datetime
import json
import logging
import os
import six
from sqlalchemy.engine import create_engine
from sqlalchemy.engine import Engine # NOQA
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import orm
import sys
import threading
import uuid
import optuna
from optuna import distributions
from optuna.storages.base import BaseStorage
from optuna.storages.base import DEFAULT_STUDY_NAME_PREFIX
from optuna.storages.rdb import models
from optuna import structs
from optuna import type_checking
from optuna import version
if type_checking.TYPE_CHECKING:
from typing import Any # NOQA
from typing import Dict # NOQA
from typing import List # NOQA
from typing import Optional # NOQA
class RDBStorage(BaseStorage):
"""Storage class for RDB backend.
This class is not supposed to be directly accessed by library users.
Args:
url: URL of the storage.
engine_kwargs:
A dictionary of keyword arguments that is passed to
:func:`sqlalchemy.engine.create_engine`.
enable_cache:
Flag to control whether to enable storage layer caching.
If this flag is set to :obj:`True` (the default), the finished trials are
cached on memory and never re-fetched from the storage.
Otherwise, the trials are fetched from the storage whenever they are needed.
"""
def __init__(self, url, engine_kwargs=None, enable_cache=True, skip_compatibility_check=False):
# type: (str, Optional[Dict[str, Any]], bool, bool) -> None
engine_kwargs = engine_kwargs or {}
url = self._fill_storage_url_template(url)
try:
self.engine = create_engine(url, **engine_kwargs)
except ImportError as e:
raise ImportError('Failed to import DB access module for the specified storage URL. '
'Please install appropriate one. (The actual import error is: ' +
str(e) + '.)')
self.scoped_session = orm.scoped_session(orm.sessionmaker(bind=self.engine))
models.BaseModel.metadata.create_all(self.engine)
self.logger = optuna.logging.get_logger(__name__)
self._version_manager = _VersionManager(url, self.engine, self.scoped_session)
if not skip_compatibility_check:
self._version_manager.check_table_schema_compatibility()
self._finished_trials_cache = _FinishedTrialsCache(enable_cache)
def create_new_study_id(self, study_name=None):
# type: (Optional[str]) -> int
session = self.scoped_session()
if study_name is None:
study_name = self._create_unique_study_name(session)
study = models.StudyModel(study_name=study_name, direction=structs.StudyDirection.NOT_SET)
session.add(study)
if not self._commit_with_integrity_check(session):
raise structs.DuplicatedStudyError(
"Another study with name '{}' already exists. "
"Please specify a different name, or reuse the existing one "
"by setting `load_if_exists` (for Python API) or "
"`--skip-if-exists` flag (for CLI).".format(study_name))
self.logger.info('A new study created with name: {}'.format(study.study_name))
return study.study_id
@staticmethod
def _create_unique_study_name(session):
# type: (orm.Session) -> str
while True:
study_uuid = str(uuid.uuid4())
study_name = DEFAULT_STUDY_NAME_PREFIX + study_uuid
study = models.StudyModel.find_by_name(study_name, session)
if study is None:
break
return study_name
# TODO(sano): Prevent simultaneously setting different direction in distributed environments.
def set_study_direction(self, study_id, direction):
# type: (int, structs.StudyDirection) -> None
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
if study.direction != structs.StudyDirection.NOT_SET and study.direction != direction:
raise ValueError('Cannot overwrite study direction from {} to {}.'.format(
study.direction, direction))
study.direction = direction
self._commit(session)
def set_study_user_attr(self, study_id, key, value):
# type: (int, str, Any) -> None
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
attribute = models.StudyUserAttributeModel.find_by_study_and_key(study, key, session)
if attribute is None:
attribute = models.StudyUserAttributeModel(
study_id=study_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def set_study_system_attr(self, study_id, key, value):
# type: (int, str, Any) -> None
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
attribute = models.StudySystemAttributeModel.find_by_study_and_key(study, key, session)
if attribute is None:
attribute = models.StudySystemAttributeModel(
study_id=study_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def get_study_id_from_name(self, study_name):
# type: (str) -> int
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_name(study_name, session)
return study.study_id
def get_study_id_from_trial_id(self, trial_id):
# type: (int) -> int
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
return trial.study_id
def get_study_name_from_id(self, study_id):
# type: (int) -> str
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return study.study_name
def get_study_direction(self, study_id):
# type: (int) -> structs.StudyDirection
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return study.direction
def get_study_user_attrs(self, study_id):
# type: (int) -> Dict[str, Any]
session = self.scoped_session()
attributes = models.StudyUserAttributeModel.where_study_id(study_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
def get_study_system_attrs(self, study_id):
# type: (int) -> Dict[str, Any]
session = self.scoped_session()
attributes = models.StudySystemAttributeModel.where_study_id(study_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
def get_trial_user_attrs(self, trial_id):
# type: (int) -> Dict[str, Any]
session = self.scoped_session()
attributes = models.TrialUserAttributeModel.where_trial_id(trial_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
def get_trial_system_attrs(self, trial_id):
# type: (int) -> Dict[str, Any]
session = self.scoped_session()
attributes = models.TrialSystemAttributeModel.where_trial_id(trial_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
# TODO(sano): Optimize this method to reduce the number of queries.
def get_all_study_summaries(self):
# type: () -> List[structs.StudySummary]
session = self.scoped_session()
study_models = models.StudyModel.all(session)
trial_models = models.TrialModel.all(session)
param_models = models.TrialParamModel.all(session)
value_models = models.TrialValueModel.all(session)
trial_user_attribute_models = models.TrialUserAttributeModel.all(session)
trial_system_attribute_models = models.TrialSystemAttributeModel.all(session)
study_sumarries = []
for study_model in study_models:
# Filter model objects by study.
study_trial_models = [t for t in trial_models if t.study_id == study_model.study_id]
# Get best trial.
completed_trial_models = [
t for t in study_trial_models if t.state is structs.TrialState.COMPLETE
]
best_trial = None
if len(completed_trial_models) > 0:
if study_model.direction == structs.StudyDirection.MAXIMIZE:
best_trial_model = max(completed_trial_models, key=lambda t: t.value)
else:
best_trial_model = min(completed_trial_models, key=lambda t: t.value)
best_param_models = [
p for p in param_models if p.trial_id == best_trial_model.trial_id
]
best_value_models = [
v for v in value_models if v.trial_id == best_trial_model.trial_id
]
best_trial_user_models = [
u for u in trial_user_attribute_models
if u.trial_id == best_trial_model.trial_id
]
best_trial_system_models = [
s for s in trial_system_attribute_models
if s.trial_id == best_trial_model.trial_id
]
# Merge model objects related to the best trial.
best_trial = self._merge_trials_orm([best_trial_model], best_param_models,
best_value_models, best_trial_user_models,
best_trial_system_models)[0]
# Find datetime_start.
datetime_start = None
if len(study_trial_models) > 0:
datetime_start = min([t.datetime_start for t in study_trial_models])
attributes = models.StudySystemAttributeModel.where_study_id(
study_model.study_id, session)
system_attrs = {attr.key: json.loads(attr.value_json) for attr in attributes}
# Consolidate StudySummary.
study_sumarries.append(
structs.StudySummary(
study_id=study_model.study_id,
study_name=study_model.study_name,
direction=self.get_study_direction(study_model.study_id),
best_trial=best_trial,
user_attrs=self.get_study_user_attrs(study_model.study_id),
system_attrs=system_attrs,
n_trials=len(study_trial_models),
datetime_start=datetime_start))
return study_sumarries
def create_new_trial_id(self, study_id):
# type: (int) -> int
session = self.scoped_session()
trial = models.TrialModel(study_id=study_id, state=structs.TrialState.RUNNING)
session.add(trial)
self._commit(session)
self._create_new_trial_number(trial.trial_id)
return trial.trial_id
def _create_new_trial_number(self, trial_id):
# type: (int) -> int
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
trial_number = trial.count_past_trials(session)
self.set_trial_system_attr(trial.trial_id, '_number', trial_number)
return trial_number
def set_trial_state(self, trial_id, state):
# type: (int, structs.TrialState) -> None
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial.state = state
if state.is_finished():
trial.datetime_complete = datetime.now()
self._commit(session)
def set_trial_param(self, trial_id, param_name, param_value_internal, distribution):
# type: (int, str, float, distributions.BaseDistribution) -> bool
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial_param = \
models.TrialParamModel.find_by_trial_and_param_name(trial, param_name, session)
if trial_param is not None:
# Raise error in case distribution is incompatible.
distributions.check_distribution_compatibility(
distributions.json_to_distribution(trial_param.distribution_json), distribution)
# Return False when distribution is compatible but parameter has already been set.
return False
param = models.TrialParamModel(
trial_id=trial_id,
param_name=param_name,
param_value=param_value_internal,
distribution_json=distributions.distribution_to_json(distribution))
param.check_and_add(session)
commit_success = self._commit_with_integrity_check(session)
return commit_success
def get_trial_param(self, trial_id, param_name):
# type: (int, str) -> float
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
trial_param = models.TrialParamModel.find_or_raise_by_trial_and_param_name(
trial, param_name, session)
return trial_param.param_value
def set_trial_value(self, trial_id, value):
# type: (int, float) -> None
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial.value = value
self._commit(session)
def set_trial_intermediate_value(self, trial_id, step, intermediate_value):
# type: (int, int, float) -> bool
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial_value = models.TrialValueModel.find_by_trial_and_step(trial, step, session)
if trial_value is not None:
return False
trial_value = models.TrialValueModel(
trial_id=trial_id, step=step, value=intermediate_value)
session.add(trial_value)
commit_success = self._commit_with_integrity_check(session)
return commit_success
def set_trial_user_attr(self, trial_id, key, value):
# type: (int, str, Any) -> None
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
attribute = models.TrialUserAttributeModel.find_by_trial_and_key(trial, key, session)
if attribute is None:
attribute = models.TrialUserAttributeModel(
trial_id=trial_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def set_trial_system_attr(self, trial_id, key, value):
# type: (int, str, Any) -> None
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
if key == '_number':
# `_number` attribute may be set even after a trial is finished.
# This happens if the trial was created before v0.9.0,
# where a trial didn't have `_number` attribute.
# In this case, `check_trial_is_updatable` is skipped to avoid the `RuntimeError`.
#
# TODO(ohta): Remove this workaround when `number` field is added to `TrialModel`.
pass
else:
self.check_trial_is_updatable(trial_id, trial.state)
attribute = models.TrialSystemAttributeModel.find_by_trial_and_key(trial, key, session)
if attribute is None:
attribute = models.TrialSystemAttributeModel(
trial_id=trial_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def get_trial_number_from_id(self, trial_id):
# type: (int) -> int
trial_number = self.get_trial_system_attrs(trial_id).get('_number')
if trial_number is None:
# If a study is created by optuna<=0.8.0, trial number is not found.
# Create new one.
return self._create_new_trial_number(trial_id)
return trial_number
def get_trial(self, trial_id):
# type: (int) -> structs.FrozenTrial
cached_trial = self._finished_trials_cache.get_cached_trial(trial_id)
if cached_trial is not None:
return copy.deepcopy(cached_trial)
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
params = models.TrialParamModel.where_trial(trial, session)
values = models.TrialValueModel.where_trial(trial, session)
user_attributes = models.TrialUserAttributeModel.where_trial(trial, session)
system_attributes = models.TrialSystemAttributeModel.where_trial(trial, session)
frozen_trial = self._merge_trials_orm([trial], params, values, user_attributes,
system_attributes)[0]
self._finished_trials_cache.cache_trial_if_finished(frozen_trial)
return frozen_trial
def get_all_trials(self, study_id):
# type: (int) -> List[structs.FrozenTrial]
if self._finished_trials_cache.is_empty():
trials = self._get_all_trials_without_cache(study_id)
for trial in trials:
self._finished_trials_cache.cache_trial_if_finished(trial)
return trials
trial_ids = self._get_all_trial_ids(study_id)
trials = [self.get_trial(trial_id) for trial_id in trial_ids]
return trials
def _get_all_trial_ids(self, study_id):
# type: (int) -> List[int]
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return models.TrialModel.get_all_trial_ids_where_study(study, session)
def _get_all_trials_without_cache(self, study_id):
# type: (int) -> List[structs.FrozenTrial]
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
trials = models.TrialModel.where_study(study, session)
params = models.TrialParamModel.where_study(study, session)
values = models.TrialValueModel.where_study(study, session)
user_attributes = models.TrialUserAttributeModel.where_study(study, session)
system_attributes = models.TrialSystemAttributeModel.where_study(study, session)
return self._merge_trials_orm(trials, params, values, user_attributes, system_attributes)
def get_n_trials(self, study_id, state=None):
# type: (int, Optional[structs.TrialState]) -> int
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return models.TrialModel.count(session, study, state)
def _merge_trials_orm(
self,
trials, # type: List[models.TrialModel]
trial_params, # type: List[models.TrialParamModel]
trial_intermediate_values, # type: List[models.TrialValueModel]
trial_user_attrs, # type: List[models.TrialUserAttributeModel]
trial_system_attrs # type: List[models.TrialSystemAttributeModel]
):
# type: (...) -> List[structs.FrozenTrial]
id_to_trial = {}
for trial in trials:
id_to_trial[trial.trial_id] = trial
id_to_params = defaultdict(list) # type: Dict[int, List[models.TrialParamModel]]
for param in trial_params:
id_to_params[param.trial_id].append(param)
id_to_values = defaultdict(list) # type: Dict[int, List[models.TrialValueModel]]
for value in trial_intermediate_values:
id_to_values[value.trial_id].append(value)
id_to_user_attrs = \
defaultdict(list) # type: Dict[int, List[models.TrialUserAttributeModel]]
for user_attr in trial_user_attrs:
id_to_user_attrs[user_attr.trial_id].append(user_attr)
id_to_system_attrs = \
defaultdict(list) # type: Dict[int, List[models.TrialSystemAttributeModel]]
for system_attr in trial_system_attrs:
id_to_system_attrs[system_attr.trial_id].append(system_attr)
temp_trials = []
for trial_id, trial in id_to_trial.items():
params = {}
param_distributions = {}
for param in id_to_params[trial_id]:
distribution = distributions.json_to_distribution(param.distribution_json)
params[param.param_name] = distribution.to_external_repr(param.param_value)
param_distributions[param.param_name] = distribution
intermediate_values = {}
for value in id_to_values[trial_id]:
intermediate_values[value.step] = value.value
user_attrs = {}
for user_attr in id_to_user_attrs[trial_id]:
user_attrs[user_attr.key] = json.loads(user_attr.value_json)
system_attrs = {}
for system_attr in id_to_system_attrs[trial_id]:
system_attrs[system_attr.key] = json.loads(system_attr.value_json)
# `-1` is a dummy value.
# It will be replaced by a proper value before returned to the caller.
#
# TODO(ohta): Use trial.number after TrialModel.number is added.
trial_number = -1
temp_trials.append(
structs.FrozenTrial(
number=trial_number,
state=trial.state,
params=params,
distributions=param_distributions,
user_attrs=user_attrs,
system_attrs=system_attrs,
value=trial.value,
intermediate_values=intermediate_values,
datetime_start=trial.datetime_start,
datetime_complete=trial.datetime_complete,
trial_id=trial_id))
result = []
for temp_trial in temp_trials:
# [NOTE]
# We set actual trial numbers here to avoid calling `self.get_trial_number_from_id()`
# within the above loop.
#
# This is because `self.get_trial_number_from_id()` may call `session.commit()`
# internally, which causes unintended changes of the states of `trials`.
# (see https://github.com/pfnet/optuna/pull/349#issuecomment-475086642 for details)
trial_number = self.get_trial_number_from_id(temp_trial.trial_id)
result.append(temp_trial._replace(number=trial_number))
return result
@staticmethod
def _fill_storage_url_template(template):
# type: (str) -> str
return template.format(SCHEMA_VERSION=models.SCHEMA_VERSION)
@staticmethod
def _commit_with_integrity_check(session):
# type: (orm.Session) -> bool
try:
session.commit()
except IntegrityError as e:
logger = optuna.logging.get_logger(__name__)
logger.debug(
'Ignoring {}. This happens due to a timing issue among threads/processes/nodes. '
'Another one might have committed a record with the same key(s).'.format(repr(e)))
session.rollback()
return False
return True
@staticmethod
def _commit(session):
# type: (orm.Session) -> None
try:
session.commit()
except SQLAlchemyError as e:
session.rollback()
message = \
'An exception is raised during the commit. ' \
'This typically happens due to invalid data in the commit, ' \
'e.g. exceeding max length. ' \
'(The actual exception is as follows: {})'.format(repr(e))
six.reraise(structs.StorageInternalError, structs.StorageInternalError(message),
sys.exc_info()[2])
def remove_session(self):
# type: () -> None
"""Removes the current session.
A session is stored in SQLAlchemy's ThreadLocalRegistry for each thread. This method
closes and removes the session which is associated to the current thread. Particularly,
under multi-thread use cases, it is important to call this method *from each thread*.
Otherwise, all sessions and their associated DB connections are destructed by a thread
that occasionally invoked the garbage collector. By default, it is not allowed to touch
a SQLite connection from threads other than the thread that created the connection.
Therefore, we need to explicitly close the connection from each thread.
"""
self.scoped_session.remove()
def __del__(self):
# type: () -> None
# This destructor calls remove_session to explicitly close the DB connection. We need this
# because DB connections created in SQLAlchemy are not automatically closed by reference
# counters, so it is not guaranteed that they are released by correct threads (for more
# information, please see the docstring of remove_session).
if hasattr(self, 'scoped_session'):
self.remove_session()
def upgrade(self):
# type: () -> None
"""Upgrade the storage schema."""
self._version_manager.upgrade()
def get_current_version(self):
# type: () -> str
"""Return the schema version currently used by this storage."""
return self._version_manager.get_current_version()
def get_head_version(self):
# type: () -> str
"""Return the latest schema version."""
return self._version_manager.get_head_version()
def get_all_versions(self):
# type: () -> List[str]
"""Return the schema version list."""
return self._version_manager.get_all_versions()
class _VersionManager(object):
def __init__(self, url, engine, scoped_session):
# type: (str, Engine, orm.scoped_session) -> None
self.url = url
self.engine = engine
self.scoped_session = scoped_session
self._init_version_info_model()
self._init_alembic()
def _init_version_info_model(self):
# type: () -> None
session = self.scoped_session()
version_info = models.VersionInfoModel.find(session)
if version_info is not None:
return
version_info = models.VersionInfoModel(
schema_version=models.SCHEMA_VERSION, library_version=version.__version__)
session.add(version_info)
RDBStorage._commit_with_integrity_check(session)
def _init_alembic(self):
# type: () -> None
logging.getLogger('alembic').setLevel(logging.WARN)
context = alembic.migration.MigrationContext.configure(self.engine.connect())
is_initialized = context.get_current_revision() is not None
if is_initialized:
# The `alembic_version` table already exists and is not empty.
return
if self._is_alembic_supported():
revision = self.get_head_version()
else:
# The storage has been created before alembic is introduced.
revision = self._get_base_version()
self._set_alembic_revision(revision)
def _set_alembic_revision(self, revision):
# type: (str) -> None
context = alembic.migration.MigrationContext.configure(self.engine.connect())
script = self._create_alembic_script()
context.stamp(script, revision)
def check_table_schema_compatibility(self):
# type: () -> None
session = self.scoped_session()
# NOTE: After invocation of `_init_version_info_model` method,
# it is ensured that a `VersionInfoModel` entry exists.
version_info = models.VersionInfoModel.find(session)
assert version_info is not None
current_version = self.get_current_version()
head_version = self.get_head_version()
if current_version == head_version:
return
message = 'The runtime optuna version {} is no longer compatible with the table schema ' \
'(set up by optuna {}). '.format(version.__version__,
version_info.library_version)
known_versions = self.get_all_versions()
if current_version in known_versions:
message += 'Please execute `$ optuna storage upgrade --storage $STORAGE_URL` ' \
'for upgrading the storage.'
else:
message += 'Please try updating optuna to the latest version by '\
'`$ pip install -U optuna`.'
raise RuntimeError(message)
def get_current_version(self):
# type: () -> str
context = alembic.migration.MigrationContext.configure(self.engine.connect())
version = context.get_current_revision()
assert version is not None
return version
def get_head_version(self):
# type: () -> str
script = self._create_alembic_script()
return script.get_current_head()
def _get_base_version(self):
# type: () -> str
script = self._create_alembic_script()
return script.get_base()
def get_all_versions(self):
# type: () -> List[str]
script = self._create_alembic_script()
return [r.revision for r in script.walk_revisions()]
def upgrade(self):
# type: () -> None
config = self._create_alembic_config()
alembic.command.upgrade(config, 'head')
def _is_alembic_supported(self):
# type: () -> bool
session = self.scoped_session()
version_info = models.VersionInfoModel.find(session)
if version_info is None:
# `None` means this storage was created just now.
return True
return version_info.schema_version == models.SCHEMA_VERSION
def _create_alembic_script(self):
# type: () -> alembic.script.ScriptDirectory
config = self._create_alembic_config()
script = alembic.script.ScriptDirectory.from_config(config)
return script
def _create_alembic_config(self):
# type: () -> alembic.config.Config
alembic_dir = os.path.join(os.path.dirname(__file__), 'alembic')
config = alembic.config.Config(os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option('script_location', escape_alembic_config_value(alembic_dir))
config.set_main_option('sqlalchemy.url', escape_alembic_config_value(self.url))
return config
class _FinishedTrialsCache(object):
def __init__(self, enabled):
# type: (bool) -> None
self._finished_trials = {} # type: Dict[int, structs.FrozenTrial]
self._enabled = enabled
self._lock = threading.Lock()
def is_empty(self):
# type: () -> bool
if not self._enabled:
return True
with self._lock:
return len(self._finished_trials) == 0
def cache_trial_if_finished(self, trial):
# type: (structs.FrozenTrial) -> None
if not self._enabled:
return
if trial.state.is_finished():
with self._lock:
self._finished_trials[trial.trial_id] = copy.deepcopy(trial)
def get_cached_trial(self, trial_id):
# type: (int) -> Optional[structs.FrozenTrial]
if not self._enabled:
return None
with self._lock:
return self._finished_trials.get(trial_id)
def escape_alembic_config_value(value):
# type: (str) -> str
# We must escape '%' in a value string because the character
# is regarded as the trigger of variable expansion.
# Please see the documentation of `configparser.BasicInterpolation` for more details.
return value.replace('%', '%%')
| 36.62306 | 99 | 0.647908 | import alembic.command
import alembic.config
import alembic.migration
import alembic.script
from collections import defaultdict
import copy
from datetime import datetime
import json
import logging
import os
import six
from sqlalchemy.engine import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import orm
import sys
import threading
import uuid
import optuna
from optuna import distributions
from optuna.storages.base import BaseStorage
from optuna.storages.base import DEFAULT_STUDY_NAME_PREFIX
from optuna.storages.rdb import models
from optuna import structs
from optuna import type_checking
from optuna import version
if type_checking.TYPE_CHECKING:
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
class RDBStorage(BaseStorage):
def __init__(self, url, engine_kwargs=None, enable_cache=True, skip_compatibility_check=False):
engine_kwargs = engine_kwargs or {}
url = self._fill_storage_url_template(url)
try:
self.engine = create_engine(url, **engine_kwargs)
except ImportError as e:
raise ImportError('Failed to import DB access module for the specified storage URL. '
'Please install appropriate one. (The actual import error is: ' +
str(e) + '.)')
self.scoped_session = orm.scoped_session(orm.sessionmaker(bind=self.engine))
models.BaseModel.metadata.create_all(self.engine)
self.logger = optuna.logging.get_logger(__name__)
self._version_manager = _VersionManager(url, self.engine, self.scoped_session)
if not skip_compatibility_check:
self._version_manager.check_table_schema_compatibility()
self._finished_trials_cache = _FinishedTrialsCache(enable_cache)
def create_new_study_id(self, study_name=None):
session = self.scoped_session()
if study_name is None:
study_name = self._create_unique_study_name(session)
study = models.StudyModel(study_name=study_name, direction=structs.StudyDirection.NOT_SET)
session.add(study)
if not self._commit_with_integrity_check(session):
raise structs.DuplicatedStudyError(
"Another study with name '{}' already exists. "
"Please specify a different name, or reuse the existing one "
"by setting `load_if_exists` (for Python API) or "
"`--skip-if-exists` flag (for CLI).".format(study_name))
self.logger.info('A new study created with name: {}'.format(study.study_name))
return study.study_id
@staticmethod
def _create_unique_study_name(session):
while True:
study_uuid = str(uuid.uuid4())
study_name = DEFAULT_STUDY_NAME_PREFIX + study_uuid
study = models.StudyModel.find_by_name(study_name, session)
if study is None:
break
return study_name
def set_study_direction(self, study_id, direction):
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
if study.direction != structs.StudyDirection.NOT_SET and study.direction != direction:
raise ValueError('Cannot overwrite study direction from {} to {}.'.format(
study.direction, direction))
study.direction = direction
self._commit(session)
def set_study_user_attr(self, study_id, key, value):
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
attribute = models.StudyUserAttributeModel.find_by_study_and_key(study, key, session)
if attribute is None:
attribute = models.StudyUserAttributeModel(
study_id=study_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def set_study_system_attr(self, study_id, key, value):
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
attribute = models.StudySystemAttributeModel.find_by_study_and_key(study, key, session)
if attribute is None:
attribute = models.StudySystemAttributeModel(
study_id=study_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def get_study_id_from_name(self, study_name):
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_name(study_name, session)
return study.study_id
def get_study_id_from_trial_id(self, trial_id):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
return trial.study_id
def get_study_name_from_id(self, study_id):
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return study.study_name
def get_study_direction(self, study_id):
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return study.direction
def get_study_user_attrs(self, study_id):
session = self.scoped_session()
attributes = models.StudyUserAttributeModel.where_study_id(study_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
def get_study_system_attrs(self, study_id):
session = self.scoped_session()
attributes = models.StudySystemAttributeModel.where_study_id(study_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
def get_trial_user_attrs(self, trial_id):
session = self.scoped_session()
attributes = models.TrialUserAttributeModel.where_trial_id(trial_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
def get_trial_system_attrs(self, trial_id):
session = self.scoped_session()
attributes = models.TrialSystemAttributeModel.where_trial_id(trial_id, session)
return {attr.key: json.loads(attr.value_json) for attr in attributes}
def get_all_study_summaries(self):
session = self.scoped_session()
study_models = models.StudyModel.all(session)
trial_models = models.TrialModel.all(session)
param_models = models.TrialParamModel.all(session)
value_models = models.TrialValueModel.all(session)
trial_user_attribute_models = models.TrialUserAttributeModel.all(session)
trial_system_attribute_models = models.TrialSystemAttributeModel.all(session)
study_sumarries = []
for study_model in study_models:
study_trial_models = [t for t in trial_models if t.study_id == study_model.study_id]
completed_trial_models = [
t for t in study_trial_models if t.state is structs.TrialState.COMPLETE
]
best_trial = None
if len(completed_trial_models) > 0:
if study_model.direction == structs.StudyDirection.MAXIMIZE:
best_trial_model = max(completed_trial_models, key=lambda t: t.value)
else:
best_trial_model = min(completed_trial_models, key=lambda t: t.value)
best_param_models = [
p for p in param_models if p.trial_id == best_trial_model.trial_id
]
best_value_models = [
v for v in value_models if v.trial_id == best_trial_model.trial_id
]
best_trial_user_models = [
u for u in trial_user_attribute_models
if u.trial_id == best_trial_model.trial_id
]
best_trial_system_models = [
s for s in trial_system_attribute_models
if s.trial_id == best_trial_model.trial_id
]
best_trial = self._merge_trials_orm([best_trial_model], best_param_models,
best_value_models, best_trial_user_models,
best_trial_system_models)[0]
datetime_start = None
if len(study_trial_models) > 0:
datetime_start = min([t.datetime_start for t in study_trial_models])
attributes = models.StudySystemAttributeModel.where_study_id(
study_model.study_id, session)
system_attrs = {attr.key: json.loads(attr.value_json) for attr in attributes}
study_sumarries.append(
structs.StudySummary(
study_id=study_model.study_id,
study_name=study_model.study_name,
direction=self.get_study_direction(study_model.study_id),
best_trial=best_trial,
user_attrs=self.get_study_user_attrs(study_model.study_id),
system_attrs=system_attrs,
n_trials=len(study_trial_models),
datetime_start=datetime_start))
return study_sumarries
def create_new_trial_id(self, study_id):
session = self.scoped_session()
trial = models.TrialModel(study_id=study_id, state=structs.TrialState.RUNNING)
session.add(trial)
self._commit(session)
self._create_new_trial_number(trial.trial_id)
return trial.trial_id
def _create_new_trial_number(self, trial_id):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
trial_number = trial.count_past_trials(session)
self.set_trial_system_attr(trial.trial_id, '_number', trial_number)
return trial_number
def set_trial_state(self, trial_id, state):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial.state = state
if state.is_finished():
trial.datetime_complete = datetime.now()
self._commit(session)
def set_trial_param(self, trial_id, param_name, param_value_internal, distribution):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial_param = \
models.TrialParamModel.find_by_trial_and_param_name(trial, param_name, session)
if trial_param is not None:
distributions.check_distribution_compatibility(
distributions.json_to_distribution(trial_param.distribution_json), distribution)
return False
param = models.TrialParamModel(
trial_id=trial_id,
param_name=param_name,
param_value=param_value_internal,
distribution_json=distributions.distribution_to_json(distribution))
param.check_and_add(session)
commit_success = self._commit_with_integrity_check(session)
return commit_success
def get_trial_param(self, trial_id, param_name):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
trial_param = models.TrialParamModel.find_or_raise_by_trial_and_param_name(
trial, param_name, session)
return trial_param.param_value
def set_trial_value(self, trial_id, value):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial.value = value
self._commit(session)
def set_trial_intermediate_value(self, trial_id, step, intermediate_value):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
trial_value = models.TrialValueModel.find_by_trial_and_step(trial, step, session)
if trial_value is not None:
return False
trial_value = models.TrialValueModel(
trial_id=trial_id, step=step, value=intermediate_value)
session.add(trial_value)
commit_success = self._commit_with_integrity_check(session)
return commit_success
def set_trial_user_attr(self, trial_id, key, value):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
self.check_trial_is_updatable(trial_id, trial.state)
attribute = models.TrialUserAttributeModel.find_by_trial_and_key(trial, key, session)
if attribute is None:
attribute = models.TrialUserAttributeModel(
trial_id=trial_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def set_trial_system_attr(self, trial_id, key, value):
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
if key == '_number':
# In this case, `check_trial_is_updatable` is skipped to avoid the `RuntimeError`.
#
# TODO(ohta): Remove this workaround when `number` field is added to `TrialModel`.
pass
else:
self.check_trial_is_updatable(trial_id, trial.state)
attribute = models.TrialSystemAttributeModel.find_by_trial_and_key(trial, key, session)
if attribute is None:
attribute = models.TrialSystemAttributeModel(
trial_id=trial_id, key=key, value_json=json.dumps(value))
session.add(attribute)
else:
attribute.value_json = json.dumps(value)
self._commit_with_integrity_check(session)
def get_trial_number_from_id(self, trial_id):
# type: (int) -> int
trial_number = self.get_trial_system_attrs(trial_id).get('_number')
if trial_number is None:
# If a study is created by optuna<=0.8.0, trial number is not found.
# Create new one.
return self._create_new_trial_number(trial_id)
return trial_number
def get_trial(self, trial_id):
# type: (int) -> structs.FrozenTrial
cached_trial = self._finished_trials_cache.get_cached_trial(trial_id)
if cached_trial is not None:
return copy.deepcopy(cached_trial)
session = self.scoped_session()
trial = models.TrialModel.find_or_raise_by_id(trial_id, session)
params = models.TrialParamModel.where_trial(trial, session)
values = models.TrialValueModel.where_trial(trial, session)
user_attributes = models.TrialUserAttributeModel.where_trial(trial, session)
system_attributes = models.TrialSystemAttributeModel.where_trial(trial, session)
frozen_trial = self._merge_trials_orm([trial], params, values, user_attributes,
system_attributes)[0]
self._finished_trials_cache.cache_trial_if_finished(frozen_trial)
return frozen_trial
def get_all_trials(self, study_id):
# type: (int) -> List[structs.FrozenTrial]
if self._finished_trials_cache.is_empty():
trials = self._get_all_trials_without_cache(study_id)
for trial in trials:
self._finished_trials_cache.cache_trial_if_finished(trial)
return trials
trial_ids = self._get_all_trial_ids(study_id)
trials = [self.get_trial(trial_id) for trial_id in trial_ids]
return trials
def _get_all_trial_ids(self, study_id):
# type: (int) -> List[int]
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return models.TrialModel.get_all_trial_ids_where_study(study, session)
def _get_all_trials_without_cache(self, study_id):
# type: (int) -> List[structs.FrozenTrial]
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
trials = models.TrialModel.where_study(study, session)
params = models.TrialParamModel.where_study(study, session)
values = models.TrialValueModel.where_study(study, session)
user_attributes = models.TrialUserAttributeModel.where_study(study, session)
system_attributes = models.TrialSystemAttributeModel.where_study(study, session)
return self._merge_trials_orm(trials, params, values, user_attributes, system_attributes)
def get_n_trials(self, study_id, state=None):
# type: (int, Optional[structs.TrialState]) -> int
session = self.scoped_session()
study = models.StudyModel.find_or_raise_by_id(study_id, session)
return models.TrialModel.count(session, study, state)
def _merge_trials_orm(
self,
trials, # type: List[models.TrialModel]
trial_params, # type: List[models.TrialParamModel]
trial_intermediate_values, # type: List[models.TrialValueModel]
trial_user_attrs, # type: List[models.TrialUserAttributeModel]
trial_system_attrs # type: List[models.TrialSystemAttributeModel]
):
# type: (...) -> List[structs.FrozenTrial]
id_to_trial = {}
for trial in trials:
id_to_trial[trial.trial_id] = trial
id_to_params = defaultdict(list) # type: Dict[int, List[models.TrialParamModel]]
for param in trial_params:
id_to_params[param.trial_id].append(param)
id_to_values = defaultdict(list) # type: Dict[int, List[models.TrialValueModel]]
for value in trial_intermediate_values:
id_to_values[value.trial_id].append(value)
id_to_user_attrs = \
defaultdict(list) # type: Dict[int, List[models.TrialUserAttributeModel]]
for user_attr in trial_user_attrs:
id_to_user_attrs[user_attr.trial_id].append(user_attr)
id_to_system_attrs = \
defaultdict(list) # type: Dict[int, List[models.TrialSystemAttributeModel]]
for system_attr in trial_system_attrs:
id_to_system_attrs[system_attr.trial_id].append(system_attr)
temp_trials = []
for trial_id, trial in id_to_trial.items():
params = {}
param_distributions = {}
for param in id_to_params[trial_id]:
distribution = distributions.json_to_distribution(param.distribution_json)
params[param.param_name] = distribution.to_external_repr(param.param_value)
param_distributions[param.param_name] = distribution
intermediate_values = {}
for value in id_to_values[trial_id]:
intermediate_values[value.step] = value.value
user_attrs = {}
for user_attr in id_to_user_attrs[trial_id]:
user_attrs[user_attr.key] = json.loads(user_attr.value_json)
system_attrs = {}
for system_attr in id_to_system_attrs[trial_id]:
system_attrs[system_attr.key] = json.loads(system_attr.value_json)
# `-1` is a dummy value.
# It will be replaced by a proper value before returned to the caller.
#
# TODO(ohta): Use trial.number after TrialModel.number is added.
trial_number = -1
temp_trials.append(
structs.FrozenTrial(
number=trial_number,
state=trial.state,
params=params,
distributions=param_distributions,
user_attrs=user_attrs,
system_attrs=system_attrs,
value=trial.value,
intermediate_values=intermediate_values,
datetime_start=trial.datetime_start,
datetime_complete=trial.datetime_complete,
trial_id=trial_id))
result = []
for temp_trial in temp_trials:
# [NOTE]
# We set actual trial numbers here to avoid calling `self.get_trial_number_from_id()`
# within the above loop.
#
# This is because `self.get_trial_number_from_id()` may call `session.commit()`
# internally, which causes unintended changes of the states of `trials`.
# (see https://github.com/pfnet/optuna/pull/349#issuecomment-475086642 for details)
trial_number = self.get_trial_number_from_id(temp_trial.trial_id)
result.append(temp_trial._replace(number=trial_number))
return result
@staticmethod
def _fill_storage_url_template(template):
# type: (str) -> str
return template.format(SCHEMA_VERSION=models.SCHEMA_VERSION)
@staticmethod
def _commit_with_integrity_check(session):
# type: (orm.Session) -> bool
try:
session.commit()
except IntegrityError as e:
logger = optuna.logging.get_logger(__name__)
logger.debug(
'Ignoring {}. This happens due to a timing issue among threads/processes/nodes. '
'Another one might have committed a record with the same key(s).'.format(repr(e)))
session.rollback()
return False
return True
@staticmethod
def _commit(session):
# type: (orm.Session) -> None
try:
session.commit()
except SQLAlchemyError as e:
session.rollback()
message = \
'An exception is raised during the commit. ' \
'This typically happens due to invalid data in the commit, ' \
'e.g. exceeding max length. ' \
'(The actual exception is as follows: {})'.format(repr(e))
six.reraise(structs.StorageInternalError, structs.StorageInternalError(message),
sys.exc_info()[2])
def remove_session(self):
# type: () -> None
self.scoped_session.remove()
def __del__(self):
# type: () -> None
# This destructor calls remove_session to explicitly close the DB connection. We need this
# because DB connections created in SQLAlchemy are not automatically closed by reference
# counters, so it is not guaranteed that they are released by correct threads (for more
# information, please see the docstring of remove_session).
if hasattr(self, 'scoped_session'):
self.remove_session()
def upgrade(self):
# type: () -> None
self._version_manager.upgrade()
def get_current_version(self):
# type: () -> str
return self._version_manager.get_current_version()
def get_head_version(self):
# type: () -> str
return self._version_manager.get_head_version()
def get_all_versions(self):
# type: () -> List[str]
return self._version_manager.get_all_versions()
class _VersionManager(object):
def __init__(self, url, engine, scoped_session):
# type: (str, Engine, orm.scoped_session) -> None
self.url = url
self.engine = engine
self.scoped_session = scoped_session
self._init_version_info_model()
self._init_alembic()
def _init_version_info_model(self):
# type: () -> None
session = self.scoped_session()
version_info = models.VersionInfoModel.find(session)
if version_info is not None:
return
version_info = models.VersionInfoModel(
schema_version=models.SCHEMA_VERSION, library_version=version.__version__)
session.add(version_info)
RDBStorage._commit_with_integrity_check(session)
def _init_alembic(self):
# type: () -> None
logging.getLogger('alembic').setLevel(logging.WARN)
context = alembic.migration.MigrationContext.configure(self.engine.connect())
is_initialized = context.get_current_revision() is not None
if is_initialized:
# The `alembic_version` table already exists and is not empty.
return
if self._is_alembic_supported():
revision = self.get_head_version()
else:
# The storage has been created before alembic is introduced.
revision = self._get_base_version()
self._set_alembic_revision(revision)
def _set_alembic_revision(self, revision):
# type: (str) -> None
context = alembic.migration.MigrationContext.configure(self.engine.connect())
script = self._create_alembic_script()
context.stamp(script, revision)
def check_table_schema_compatibility(self):
# type: () -> None
session = self.scoped_session()
# NOTE: After invocation of `_init_version_info_model` method,
# it is ensured that a `VersionInfoModel` entry exists.
version_info = models.VersionInfoModel.find(session)
assert version_info is not None
current_version = self.get_current_version()
head_version = self.get_head_version()
if current_version == head_version:
return
message = 'The runtime optuna version {} is no longer compatible with the table schema ' \
'(set up by optuna {}). '.format(version.__version__,
version_info.library_version)
known_versions = self.get_all_versions()
if current_version in known_versions:
message += 'Please execute `$ optuna storage upgrade --storage $STORAGE_URL` ' \
'for upgrading the storage.'
else:
message += 'Please try updating optuna to the latest version by '\
'`$ pip install -U optuna`.'
raise RuntimeError(message)
def get_current_version(self):
# type: () -> str
context = alembic.migration.MigrationContext.configure(self.engine.connect())
version = context.get_current_revision()
assert version is not None
return version
def get_head_version(self):
# type: () -> str
script = self._create_alembic_script()
return script.get_current_head()
def _get_base_version(self):
# type: () -> str
script = self._create_alembic_script()
return script.get_base()
def get_all_versions(self):
# type: () -> List[str]
script = self._create_alembic_script()
return [r.revision for r in script.walk_revisions()]
def upgrade(self):
# type: () -> None
config = self._create_alembic_config()
alembic.command.upgrade(config, 'head')
def _is_alembic_supported(self):
# type: () -> bool
session = self.scoped_session()
version_info = models.VersionInfoModel.find(session)
if version_info is None:
# `None` means this storage was created just now.
return True
return version_info.schema_version == models.SCHEMA_VERSION
def _create_alembic_script(self):
# type: () -> alembic.script.ScriptDirectory
config = self._create_alembic_config()
script = alembic.script.ScriptDirectory.from_config(config)
return script
def _create_alembic_config(self):
# type: () -> alembic.config.Config
alembic_dir = os.path.join(os.path.dirname(__file__), 'alembic')
config = alembic.config.Config(os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option('script_location', escape_alembic_config_value(alembic_dir))
config.set_main_option('sqlalchemy.url', escape_alembic_config_value(self.url))
return config
class _FinishedTrialsCache(object):
def __init__(self, enabled):
# type: (bool) -> None
self._finished_trials = {} # type: Dict[int, structs.FrozenTrial]
self._enabled = enabled
self._lock = threading.Lock()
def is_empty(self):
# type: () -> bool
if not self._enabled:
return True
with self._lock:
return len(self._finished_trials) == 0
def cache_trial_if_finished(self, trial):
# type: (structs.FrozenTrial) -> None
if not self._enabled:
return
if trial.state.is_finished():
with self._lock:
self._finished_trials[trial.trial_id] = copy.deepcopy(trial)
def get_cached_trial(self, trial_id):
# type: (int) -> Optional[structs.FrozenTrial]
if not self._enabled:
return None
with self._lock:
return self._finished_trials.get(trial_id)
def escape_alembic_config_value(value):
# type: (str) -> str
# We must escape '%' in a value string because the character
# is regarded as the trigger of variable expansion.
# Please see the documentation of `configparser.BasicInterpolation` for more details.
return value.replace('%', '%%')
| true | true |
f72a3dab5f6feb060e408b3588fb869452950336 | 1,352 | py | Python | src/main.py | dex73r/ghdown | b1e72b95e10d8d7d2d41cb4e8558cb29c018ac81 | [
"MIT"
] | null | null | null | src/main.py | dex73r/ghdown | b1e72b95e10d8d7d2d41cb4e8558cb29c018ac81 | [
"MIT"
] | null | null | null | src/main.py | dex73r/ghdown | b1e72b95e10d8d7d2d41cb4e8558cb29c018ac81 | [
"MIT"
] | null | null | null | import argparse
import os
import requests
from git import Repo
def main():
parser = argparse.ArgumentParser(description="A tool to clone github only repositories of user or group")
parser.add_argument("--u", help="target of massive download",
dest='target', required=True)
parser.add_argument("--o", help="Directory to save repos at",
dest='out', required=False)
args = parser.parse_args()
target = args.target
if not target:
print("ERROR: You need to specify target, ex: gitdown -u dex73r")
return 1
output = args.out
if not output:
output = target
pageNumber = 1
while (pageNumber > 0):
url = ("https://api.github.com/users/%s/repos?page=%i&per_page=100" % (target, pageNumber))
j = requests.get(url).json()
pageCount = len(j)
if (pageCount < 1):
pageNumber = -1
for el in j:
print(el["git_url"])
gitlink = el["git_url"]
out_name = os.path.join(output, el["name"])
if os.path.isdir(out_name):
repo = Repo(out_name)
repo.remotes.origin.pull()
else:
Repo.clone_from(gitlink, out_name)
pageNumber = pageNumber + 1
return 1337
if __name__ == "__main__":
main()
| 30.727273 | 109 | 0.572485 | import argparse
import os
import requests
from git import Repo
def main():
parser = argparse.ArgumentParser(description="A tool to clone github only repositories of user or group")
parser.add_argument("--u", help="target of massive download",
dest='target', required=True)
parser.add_argument("--o", help="Directory to save repos at",
dest='out', required=False)
args = parser.parse_args()
target = args.target
if not target:
print("ERROR: You need to specify target, ex: gitdown -u dex73r")
return 1
output = args.out
if not output:
output = target
pageNumber = 1
while (pageNumber > 0):
url = ("https://api.github.com/users/%s/repos?page=%i&per_page=100" % (target, pageNumber))
j = requests.get(url).json()
pageCount = len(j)
if (pageCount < 1):
pageNumber = -1
for el in j:
print(el["git_url"])
gitlink = el["git_url"]
out_name = os.path.join(output, el["name"])
if os.path.isdir(out_name):
repo = Repo(out_name)
repo.remotes.origin.pull()
else:
Repo.clone_from(gitlink, out_name)
pageNumber = pageNumber + 1
return 1337
if __name__ == "__main__":
main()
| true | true |
f72a3ef23ff298d116c3a38c8d217d46311ba4f3 | 789 | py | Python | socialcops/api/config.py | yutiansut/Long-Running-Jobs-Manager | ed12bebb7872b95e1f65548be4a00715f2ad47a6 | [
"MIT"
] | 1 | 2019-09-15T19:52:10.000Z | 2019-09-15T19:52:10.000Z | socialcops/api/config.py | yutiansut/Long-Running-Jobs-Manager | ed12bebb7872b95e1f65548be4a00715f2ad47a6 | [
"MIT"
] | null | null | null | socialcops/api/config.py | yutiansut/Long-Running-Jobs-Manager | ed12bebb7872b95e1f65548be4a00715f2ad47a6 | [
"MIT"
] | 1 | 2019-09-15T19:53:04.000Z | 2019-09-15T19:53:04.000Z | import os
basedir = os.path.abspath(os.path.dirname(__file__))
# Keeping track of various configurations of the Flask app
class Config(object):
ALLOWED_EXTENSIONS = set(['csv'])
UPLOAD_FOLDER = './files/uploads/'
DOWNLOAD_FOLDER = './files/downloads/'
SECRET_KEY = os.environ.get('SECRET_KEY') or \
'uUHQMFSPB9H7G4bGwzFLDetrIyb4M8tj'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
REDIS_URL = os.environ.get('REDIS_URL') or 'redis://'
CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') or \
'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND') or \
'redis://localhost:6379/0'
| 41.526316 | 72 | 0.695817 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
ALLOWED_EXTENSIONS = set(['csv'])
UPLOAD_FOLDER = './files/uploads/'
DOWNLOAD_FOLDER = './files/downloads/'
SECRET_KEY = os.environ.get('SECRET_KEY') or \
'uUHQMFSPB9H7G4bGwzFLDetrIyb4M8tj'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
REDIS_URL = os.environ.get('REDIS_URL') or 'redis://'
CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') or \
'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND') or \
'redis://localhost:6379/0'
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.