uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31c7693b53c36d187f791cac | train | function | @_refresh_mine_cache
@_ensure_exists
def start(name, validate_ip_addrs=True, **kwargs):
'''
Start a container
name
Container name or ID
validate_ip_addrs : True
For parameters which accept IP addresses as input, IP address
validation will be performed. To disable, set this to `... | @_refresh_mine_cache
@_ensure_exists
def start(name, validate_ip_addrs=True, **kwargs):
| '''
Start a container
name
Container name or ID
validate_ip_addrs : True
For parameters which accept IP addresses as input, IP address
validation will be performed. To disable, set this to ``False``
binds
Files/directories to bind mount. Each bind mount should be p... | minion dockerng.restart mycontainer
salt myminion dockerng.restart mycontainer timeout=20
'''
ret = _change_state(name, 'restart', 'running', timeout=timeout)
if ret['result']:
ret['restarted'] = True
return ret
@_refresh_mine_cache
@_ensure_exists
def signal_(name, signal):
'''
... | 256 | 256 | 1,908 | 25 | 230 | tinyclues/salt | salt/modules/dockerng.py | Python | start | start | 4,161 | 4,373 | 4,161 | 4,163 | ed80e8eb97ca14d9d49570a1ab174898e46c10bc | bigcode/the-stack | train |
13b972ba280343cfc873274f | train | function | def _push_status(data, item):
'''
Process a status update from a docker push, updating the data structure
'''
status = item['status']
if 'id' in item:
if 'already pushed' in status:
# Layer already exists
already_pushed = data.setdefault('Layers', {}).setdefault(
... | def _push_status(data, item):
| '''
Process a status update from a docker push, updating the data structure
'''
status = item['status']
if 'id' in item:
if 'already pushed' in status:
# Layer already exists
already_pushed = data.setdefault('Layers', {}).setdefault(
'Already_Pushed', ... | if __context__['dockerng._pull_status'] is not NOTSET:
id_ = item['id']
if id_ in __context__['dockerng._pull_status']:
_already_exists(id_)
else:
_new_layer(id_)
def _push_status(data, item):
| 63 | 64 | 191 | 8 | 55 | tinyclues/salt | salt/modules/dockerng.py | Python | _push_status | _push_status | 999 | 1,024 | 999 | 999 | de76e606242ddfee8280ffc4350d3c7f72dfa9b2 | bigcode/the-stack | train |
797dbc22f79e45485370db12 | train | function | @_refresh_mine_cache
@_ensure_exists
def signal_(name, signal):
'''
Send a signal to a container. Signals can be either strings or numbers, and
are defined in the **Standard Signals** section of the ``signal(7)``
manpage. Run ``man 7 signal`` on a Linux host to browse this manpage.
name
Con... | @_refresh_mine_cache
@_ensure_exists
def signal_(name, signal):
| '''
Send a signal to a container. Signals can be either strings or numbers, and
are defined in the **Standard Signals** section of the ``signal(7)``
manpage. Run ``man 7 signal`` on a Linux host to browse this manpage.
name
Container name or ID
signal
Signal to send to containe... | mycontainer timeout=20
'''
ret = _change_state(name, 'restart', 'running', timeout=timeout)
if ret['result']:
ret['restarted'] = True
return ret
@_refresh_mine_cache
@_ensure_exists
def signal_(name, signal):
| 64 | 64 | 170 | 19 | 44 | tinyclues/salt | salt/modules/dockerng.py | Python | signal_ | signal_ | 4,132 | 4,158 | 4,132 | 4,134 | 9c95645748e9191fcc65eae4143b4f6d3b6f8862 | bigcode/the-stack | train |
93f415ef914f467aa8f481eb | train | function | def _error_detail(data, item):
'''
Process an API error, updating the data structure
'''
err = item['errorDetail']
if 'code' in err:
msg = '{1}: {2}'.format(
item['errorDetail']['code'],
item['errorDetail']['message'],
)
else:
msg = item['errorDeta... | def _error_detail(data, item):
| '''
Process an API error, updating the data structure
'''
err = item['errorDetail']
if 'code' in err:
msg = '{1}: {2}'.format(
item['errorDetail']['code'],
item['errorDetail']['message'],
)
else:
msg = item['errorDetail']['message']
data.append... | :
image_id = re.match(
r'Pushing tags? for rev \[([0-9a-f]+)',
status
).group(1)
except AttributeError:
return
else:
data['Id'] = image_id
def _error_detail(data, item):
| 64 | 64 | 86 | 8 | 55 | tinyclues/salt | salt/modules/dockerng.py | Python | _error_detail | _error_detail | 1,027 | 1,039 | 1,027 | 1,027 | 4bebc180c480659dcc556091c95707a058f8b517 | bigcode/the-stack | train |
6902402339206f0f52909e95 | train | function | def _refresh_mine_cache(wrapped):
'''
Decorator to trig a refresh of salt mine data.
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
'''
refresh salt mine on exit.
'''
returned = wrapped(*args, **salt.utils.clean_kwargs(**kwargs))
__salt__['mine.se... | def _refresh_mine_cache(wrapped):
| '''
Decorator to trig a refresh of salt mine data.
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
'''
refresh salt mine on exit.
'''
returned = wrapped(*args, **salt.utils.clean_kwargs(**kwargs))
__salt__['mine.send']('dockerng.ps', verbose=True, ... | does not exist
'''
if not exists(name):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
return wrapped(name, *args, **salt.utils.clean_kwargs(**kwargs))
return wrapper
def _refresh_mine_cache(wrapped):
| 64 | 64 | 100 | 9 | 54 | tinyclues/salt | salt/modules/dockerng.py | Python | _refresh_mine_cache | _refresh_mine_cache | 587 | 599 | 587 | 587 | 48ce3c76a23834684c1680bff2787b5039b74372 | bigcode/the-stack | train |
da9fb0d78147edcc90896c50 | train | function | def commit(name,
image,
message=None,
author=None):
'''
Commits a container, thereby promoting it to an image. Equivalent to
running the ``docker commit`` Docker CLI command.
name
Container name or ID to commit
image
Image to be committed, in ``repo... | def commit(name,
image,
message=None,
author=None):
| '''
Commits a container, thereby promoting it to an image. Equivalent to
running the ``docker commit`` Docker CLI command.
name
Container name or ID to commit
image
Image to be committed, in ``repo:tag`` notation. If just the repository
name is passed, a tag name of ``lates... | image_id, image_info in six.iteritems(images()):
if image_id.startswith(ret['Id']):
if image in image_info.get('RepoTags', []):
ret['Image'] = image
else:
ret['Warning'] = \
'Failed to tag image as {0}'.format(image)
if api_respon... | 111 | 111 | 370 | 15 | 95 | tinyclues/salt | salt/modules/dockerng.py | Python | commit | commit | 3,216 | 3,277 | 3,216 | 3,219 | bb14b82c0b365015c6a49233105740b5f3555aa2 | bigcode/the-stack | train |
d765013f52dbfcb80154f995 | train | function | def _get_exec_driver():
'''
Get the method to be used in shell commands
'''
contextkey = 'docker.exec_driver'
'''
docker-exec won't be used by default until we reach a version where it
supports running commands as a user other than the effective user of the
container.
See: https://g... | def _get_exec_driver():
| '''
Get the method to be used in shell commands
'''
contextkey = 'docker.exec_driver'
'''
docker-exec won't be used by default until we reach a version where it
supports running commands as a user other than the effective user of the
container.
See: https://groups.google.com/forum/#... | not defined by user.
client_kwargs['version'] = 'auto'
__context__['docker.client'] = docker.Client(**client_kwargs)
# Set a new timeout if one was passed
if timeout is not None and __context__['docker.client'].timeout != timeout:
__context__['docker.client'].timeout = timeout
d... | 162 | 162 | 541 | 6 | 155 | tinyclues/salt | salt/modules/dockerng.py | Python | _get_exec_driver | _get_exec_driver | 698 | 750 | 698 | 698 | f34da427003d4c332f93b52d92edf3ec4d6497b5 | bigcode/the-stack | train |
489f0500369c7a914c4286ec | train | function | def __virtual__():
'''
Only load if docker libs are present
'''
if HAS_DOCKER_PY:
try:
docker_py_versioninfo = _get_docker_py_versioninfo()
except CommandExecutionError:
docker_py_versioninfo = None
# Don't let a failure to interpret the version keep this ... | def __virtual__():
| '''
Only load if docker libs are present
'''
if HAS_DOCKER_PY:
try:
docker_py_versioninfo = _get_docker_py_versioninfo()
except CommandExecutionError:
docker_py_versioninfo = None
# Don't let a failure to interpret the version keep this module from
... | 'path': 'HostConfig:ExtraHosts',
'min_docker': (1, 3, 0)
},
'pid_mode': {
'path': 'HostConfig:PidMode',
'min_docker': (1, 5, 0)
},
}
def __virtual__():
| 67 | 67 | 226 | 5 | 62 | tinyclues/salt | salt/modules/dockerng.py | Python | __virtual__ | __virtual__ | 481 | 508 | 481 | 481 | 7f07e603ee3c435d5ef0e97a11c96ed06f991844 | bigcode/the-stack | train |
a6d88bd3b6922852dce2bedd | train | function | def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name,
'md5sum {0}'.format(pipes.quote(path)),
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination ... | def _get_md5(name, path):
| '''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name,
'md5sum {0}'.format(pipes.quote(path)),
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or cou... | __context__['docker.client'] = docker.Client(**client_kwargs)
# Set a new timeout if one was passed
if timeout is not None and __context__['docker.client'].timeout != timeout:
__context__['docker.client'].timeout = timeout
def _get_md5(name, path):
| 64 | 64 | 85 | 9 | 54 | tinyclues/salt | salt/modules/dockerng.py | Python | _get_md5 | _get_md5 | 684 | 695 | 684 | 684 | 58d55dbc84732123bbfd17bc208f19616c594ac8 | bigcode/the-stack | train |
e6c3f030d8215139c3499a68 | train | function | def rmi(*names, **kwargs):
'''
Removes an image
name
Name (in ``repo:tag`` notation) or ID of image.
force : False
If ``True``, the image will be removed even if the Minion has
containers created from that image
prune : True
If ``True``, untagged parent image layer... | def rmi(*names, **kwargs):
| '''
Removes an image
name
Name (in ``repo:tag`` notation) or ID of image.
force : False
If ``True``, the image will be removed even if the Minion has
containers created from that image
prune : True
If ``True``, untagged parent image layers will be removed as well, ... | item in response:
item_type = next(iter(item))
if item_type == 'status':
_push_status(ret, item)
elif item_type == 'errorDetail':
_error_detail(errors, item)
if 'Id' not in ret:
# API returned information, but there was no confirmation of a
# success... | 154 | 154 | 516 | 9 | 144 | tinyclues/salt | salt/modules/dockerng.py | Python | rmi | rmi | 3,718 | 3,788 | 3,718 | 3,718 | 251b9598367142a30185296ce1c6460f6c35fdcd | bigcode/the-stack | train |
187b49138837b032e091cae0 | train | function | def _get_top_level_images(imagedata, subset=None):
'''
Returns a list of the top-level images (those which are not parents). If
``subset`` (an iterable) is passed, the top-level images in the subset will
be returned, otherwise all top-level images will be returned.
'''
try:
parents = [im... | def _get_top_level_images(imagedata, subset=None):
| '''
Returns a list of the top-level images (those which are not parents). If
``subset`` (an iterable) is passed, the top-level images in the subset will
be returned, otherwise all top-level images will be returned.
'''
try:
parents = [imagedata[x]['ParentId'] for x in imagedata]
... | }\' for repo \'{1}\''
.format(default_tag, image)
)
r_tag = default_tag
else:
r_name = image
r_tag = default_tag
return r_name, r_tag
def _get_top_level_images(imagedata, subset=None):
| 64 | 64 | 170 | 13 | 50 | tinyclues/salt | salt/modules/dockerng.py | Python | _get_top_level_images | _get_top_level_images | 773 | 787 | 773 | 773 | 0cac77964bc274c2752d1714bb4a52425911acaf | bigcode/the-stack | train |
ff496333417d97e3a0382202 | train | function | @_ensure_exists
def pid(name):
'''
Returns the PID of a container
name
Container name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.pid mycontainer
salt myminion dockerng.pid 0123456789ab
'''
return inspect_container(name)['State']['Pid']
| @_ensure_exists
def pid(name):
| '''
Returns the PID of a container
name
Container name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.pid mycontainer
salt myminion dockerng.pid 0123456789ab
'''
return inspect_container(name)['State']['Pid']
| running the ``docker
logs`` Docker CLI command.
name
Container name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.logs mycontainer
'''
return _client_wrapper('logs', name)
@_ensure_exists
def pid(name):
| 64 | 64 | 77 | 9 | 55 | tinyclues/salt | salt/modules/dockerng.py | Python | pid | pid | 2,174 | 2,189 | 2,174 | 2,175 | 59d8977a422527193e7e4f11616f4426d1363df6 | bigcode/the-stack | train |
dbe5c89ade6d5d67afd54483 | train | function | def _clear_context():
'''
Clear the state/exists values stored in context
'''
# Can't use 'for key in __context__' or six.iterkeys(__context__) because
# an exception will be raised if the size of the dict is modified during
# iteration.
keep_context = (
'docker.client', 'docker.exec... | def _clear_context():
| '''
Clear the state/exists values stored in context
'''
# Can't use 'for key in __context__' or six.iterkeys(__context__) because
# an exception will be raised if the size of the dict is modified during
# iteration.
keep_context = (
'docker.client', 'docker.exec_driver', 'dockerng._p... | ExecutionError:
# Container doesn't exist anymore
post = None
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
if action == 'wait':
ret['exit_status'] = response
return ret
def _clear_context():
| 64 | 64 | 141 | 5 | 58 | tinyclues/salt | salt/modules/dockerng.py | Python | _clear_context | _clear_context | 627 | 643 | 627 | 627 | be4b8c3c0f77ac24cb662a9a89a19ab06eeca4c1 | bigcode/the-stack | train |
94bca08b5c33d43dfa70bf36 | train | function | def search(name, official=False, trusted=False):
'''
Searches the registry for an image
name
Search keyword
official : False
Limit results to official builds
trusted : False
Limit results to `trusted builds`_
.. _`trusted builds`: https://blog.docker.com/2013/11/intro... | def search(name, official=False, trusted=False):
| '''
Searches the registry for an image
name
Search keyword
official : False
Limit results to official builds
trusted : False
Limit results to `trusted builds`_
.. _`trusted builds`: https://blog.docker.com/2013/11/introducing-trusted-builds/
**RETURN DATA**
... | .state mycontainer
'''
contextkey = 'docker.state.{0}'.format(name)
if contextkey in __context__:
return __context__[contextkey]
c_info = inspect_container(name)
if c_info.get('State', {}).get('Paused', False):
__context__[contextkey] = 'paused'
elif c_info.get('State', {}).get('... | 129 | 129 | 433 | 10 | 119 | tinyclues/salt | salt/modules/dockerng.py | Python | search | search | 2,359 | 2,429 | 2,359 | 2,359 | 2819bf794e834f799815d181a2bb35a89da8b3ea | bigcode/the-stack | train |
808a23bb974688b076630d32 | train | function | def logs(name):
'''
Returns the logs for the container. Equivalent to running the ``docker
logs`` Docker CLI command.
name
Container name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.logs mycontainer
'''
return _client_wrapper('logs', name)
| def logs(name):
| '''
Returns the logs for the container. Equivalent to running the ``docker
logs`` Docker CLI command.
name
Container name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.logs mycontainer
'''
return _client_wrapper('logs', name)
|
CLI Example:
.. code-block:: bash
salt myminion dockerng.list_tags
'''
ret = set()
for item in six.itervalues(images()):
for repo_tag in item['RepoTags']:
ret.add(repo_tag)
return sorted(ret)
def logs(name):
| 64 | 64 | 71 | 4 | 60 | tinyclues/salt | salt/modules/dockerng.py | Python | logs | logs | 2,157 | 2,171 | 2,157 | 2,157 | 3d876bb88ed0b510cd96c29f0169b26dffcafd98 | bigcode/the-stack | train |
087e8f22c39a3b9b027c26fc | train | function | def script(name,
source,
saltenv='base',
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
''... | def script(name,
source,
saltenv='base',
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
| '''
Run :py:func:`cmd.script <salt.modules.cmdmod.script>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
name
Container name or ... | variables will be kept.
CLI Example:
.. code-block:: bash
salt myminion dockerng.run_stdout mycontainer 'ls -l /etc'
'''
return _run(name,
cmd,
exec_driver=exec_driver,
output='stdout',
stdin=stdin,
python_shell=... | 166 | 166 | 554 | 61 | 105 | tinyclues/salt | salt/modules/dockerng.py | Python | script | script | 4,906 | 4,981 | 4,906 | 4,917 | 0eaab980aa0f0b89efd875f5c100b2d2eeb1a3e0 | bigcode/the-stack | train |
d41f245698aece5cbece2355 | train | function | @_ensure_exists
def diff(name):
'''
Get information on changes made to container's filesystem since it was
created. Equivalent to running the ``docker diff`` Docker CLI command.
name
Container name or ID
**RETURN DATA**
A dictionary containing any of the following keys:
- ``Adde... | @_ensure_exists
def diff(name):
| '''
Get information on changes made to container's filesystem since it was
created. Equivalent to running the ``docker diff`` Docker CLI command.
name
Container name or ID
**RETURN DATA**
A dictionary containing any of the following keys:
- ``Added`` - A list of paths that were ... | if container['Info']['Image'] == image_id:
container_depends.extend(
[x.lstrip('/') for x in container['Names']]
)
return {
'Containers': container_depends,
'Images': [x[:12] for x, y in six.iteritems(images(all=True))
if y['ParentId'] == ... | 85 | 85 | 286 | 9 | 76 | tinyclues/salt | salt/modules/dockerng.py | Python | diff | diff | 1,776 | 1,816 | 1,776 | 1,777 | 18125814422010d9847c3a33ba6433c456c6f7b6 | bigcode/the-stack | train |
9a29c6757b7d1aa63d861c99 | train | function | @_refresh_mine_cache
@_ensure_exists
def kill(name):
'''
Kill all processes in a running container instead of performing a graceful
shutdown
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing... | @_refresh_mine_cache
@_ensure_exists
def kill(name):
| '''
Kill all processes in a running container instead of performing a graceful
shutdown
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing the prior state of the container as
well as th... | repo_name,
tag=repo_tag,
force=force)
_clear_context()
# Only non-error return case is a True return, so just return the response
return response
# Functions to manage container state
@_refresh_mine_cache
@_ensure_exists
def kill(name):
| 64 | 64 | 155 | 16 | 47 | tinyclues/salt | salt/modules/dockerng.py | Python | kill | kill | 4,028 | 4,054 | 4,028 | 4,030 | 14751142d1c9f5a7a313d2e82e1eaa088b153093 | bigcode/the-stack | train |
26b281f1a5c937fdd6493720 | train | function | def push(image,
insecure_registry=False,
api_response=False,
client_timeout=CLIENT_TIMEOUT):
'''
Pushes an image to a Docker registry. See the documentation at top of this
page to configure authenticated access.
image
Image to be pushed, in ``repo:tag`` notation. If j... | def push(image,
insecure_registry=False,
api_response=False,
client_timeout=CLIENT_TIMEOUT):
| '''
Pushes an image to a Docker registry. See the documentation at top of this
page to configure authenticated access.
image
Image to be pushed, in ``repo:tag`` notation. If just the repository
name is passed, a tag name of ``latest`` will be assumed.
insecure_registry : False
... | 0}, no response returned from Docker API'
.format(image)
)
elif api_response:
ret['API_Response'] = response
errors = []
# Iterate through API response and collect information
for item in response:
item_type = next(iter(item))
if item_type == 'status':
... | 195 | 195 | 651 | 21 | 173 | tinyclues/salt | salt/modules/dockerng.py | Python | push | push | 3,629 | 3,715 | 3,629 | 3,632 | 719d9fd847f2c9874b98ac715846a698e307d9ee | bigcode/the-stack | train |
3d47ff4cd8a093bba20341e1 | train | function | @_ensure_exists
def copy_from(name, source, dest, overwrite=False, makedirs=False):
'''
Copy a file from inside a container to the Minion
name
Container name
source
Path of the file on the container's filesystem
dest
Destination on the Minion. Must be an absolute path. If ... | @_ensure_exists
def copy_from(name, source, dest, overwrite=False, makedirs=False):
| '''
Copy a file from inside a container to the Minion
name
Container name
source
Path of the file on the container's filesystem
dest
Destination on the Minion. Must be an absolute path. If the destination
is a directory, the file will be copied into that directory.... | if salt.utils.version_cmp(version()['ApiVersion'], '1.18') == 1:
create_kwargs['host_config'] = docker.utils.create_host_config(mem_limit=create_kwargs.get('mem_limit'),
memswap_limit=create_kwargs.get('memswap_limit'))
if 'mem_limi... | 243 | 243 | 810 | 22 | 220 | tinyclues/salt | salt/modules/dockerng.py | Python | copy_from | copy_from | 2,703 | 2,804 | 2,703 | 2,704 | 0fb7797d7cd1691dd68a77cec9191b11944838e3 | bigcode/the-stack | train |
9cadafb23778425469954c51 | train | function | def _validate_input(action,
kwargs,
validate_ip_addrs=True):
'''
Perform validation on kwargs. Checks each key in kwargs against the
VALID_CONTAINER_OPTS dict and if the value is None, looks for a local
function named in the format _valid_<kwarg> and calls that.
... | def _validate_input(action,
kwargs,
validate_ip_addrs=True):
| '''
Perform validation on kwargs. Checks each key in kwargs against the
VALID_CONTAINER_OPTS dict and if the value is None, looks for a local
function named in the format _valid_<kwarg> and calls that.
The validation functions don't need to return anything, they just need to
raise a SaltInvocat... | id' in item:
if 'already pushed' in status:
# Layer already exists
already_pushed = data.setdefault('Layers', {}).setdefault(
'Already_Pushed', [])
already_pushed.append(item['id'])
elif 'successfully pushed' in status:
# Pushed a new layer... | 256 | 256 | 5,433 | 16 | 240 | tinyclues/salt | salt/modules/dockerng.py | Python | _validate_input | _validate_input | 1,042 | 1,732 | 1,042 | 1,044 | e4cae2b1e6f8dd7d262e898a98a0dbfbb485bd3a | bigcode/the-stack | train |
0ee406008968f0dfc8441596 | train | function | def run_stdout(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
'''
Run :py:func:`cmd.run_stdout <salt.m... | def run_stdout(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
| '''
Run :py:func:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a
container
name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described
:ref:`above <dock... | cmd,
exec_driver=exec_driver,
output='stderr',
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
keep_env=k... | 110 | 110 | 369 | 47 | 63 | tinyclues/salt | salt/modules/dockerng.py | Python | run_stdout | run_stdout | 4,848 | 4,903 | 4,848 | 4,856 | 30b7cdd9a2ef7af63bac1f52f3ddd032a7d17872 | bigcode/the-stack | train |
5dc43087f615a35d4dfce5c6 | train | function | def wait(name):
'''
Wait for the container to exit gracefully, and return its exit code
.. note::
This function will block until the container is stopped.
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status... | def wait(name):
| '''
Wait for the container to exit gracefully, and return its exit code
.. note::
This function will block until the container is stopped.
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionar... | ,
'state': {'old': orig_state, 'new': orig_state},
'comment': ('Container \'{0}\' is stopped, cannot unpause'
.format(name))}
return _change_state(name, 'unpause', 'running')
unfreeze = unpause
def wait(name):
| 64 | 64 | 169 | 4 | 59 | tinyclues/salt | salt/modules/dockerng.py | Python | wait | wait | 4,470 | 4,499 | 4,470 | 4,470 | bddda282e9f674a6e3b5fb796b55fbe748893e0d | bigcode/the-stack | train |
e3a2ce43f56baf1bbff58bca | train | function | def _get_docker_py_versioninfo():
'''
Returns a version_info tuple for docker-py
'''
contextkey = 'docker.docker_py_version'
if contextkey in __context__:
return __context__[contextkey]
match = re.match(VERSION_RE, str(docker.__version__))
if match:
__context__[contextkey] = ... | def _get_docker_py_versioninfo():
| '''
Returns a version_info tuple for docker-py
'''
contextkey = 'docker.docker_py_version'
if contextkey in __context__:
return __context__[contextkey]
match = re.match(VERSION_RE, str(docker.__version__))
if match:
__context__[contextkey] = tuple(
[int(x) for x i... | log.warning(
'Insufficient Docker version for dockerng (required: '
'{0}, installed: {1})'.format(
'.'.join(docker_versioninfo),
'.'.join(MIN_DOCKER)
)
)
return False
def _get_docker_py_versi... | 64 | 64 | 132 | 9 | 54 | tinyclues/salt | salt/modules/dockerng.py | Python | _get_docker_py_versioninfo | _get_docker_py_versioninfo | 511 | 526 | 511 | 511 | fb9d0005388696a25d29e5c155d612fef1e81dc2 | bigcode/the-stack | train |
3228e906db7d6db8cf6e9e44 | train | function | def layers(name):
'''
Returns a list of the IDs of layers belonging to the specified image, with
the top-most layer (the one correspnding to the passed name) appearing
last.
name
Image name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.layers centos:7
... | def layers(name):
| '''
Returns a list of the IDs of layers belonging to the specified image, with
the top-most layer (the one correspnding to the passed name) appearing
last.
name
Image name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.layers centos:7
'''
ret = []
... | ('No top-level image layers were loaded, no '
'image was tagged')
except Exception as exc:
ret['Warning'] = ('Failed to tag {0} as {1}: {2}'
.format(top_level_images[0], image, exc))
return ret
def layers(name):
| 64 | 64 | 155 | 4 | 59 | tinyclues/salt | salt/modules/dockerng.py | Python | layers | layers | 3,508 | 3,530 | 3,508 | 3,508 | 772222fb55d40f6e289d2ca48bd9751952c8bf70 | bigcode/the-stack | train |
3e8eb1f929d81d10d06e4683 | train | function | def script_retcode(name,
source,
saltenv='base',
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
... | def script_retcode(name,
source,
saltenv='base',
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
... | '''
Run :py:func:`cmd.script_retcode <salt.modules.cmdmod.script_retcode>`
within a container
name
Container name or ID
source
Path to the script. Can be a local path on the Minion or a remote file
from the Salt fileserver.
args
A string containing additional c... | ive\\n' output_loglevel=quiet
'''
return _script(name,
source,
saltenv=saltenv,
args=args,
template=template,
exec_driver=exec_driver,
stdin=stdin,
python_shell=python_shell,
... | 158 | 158 | 527 | 63 | 95 | tinyclues/salt | salt/modules/dockerng.py | Python | script_retcode | script_retcode | 4,984 | 5,054 | 4,984 | 4,995 | ae9a95ef3811a5df41c811cce73afd0f62ade709 | bigcode/the-stack | train |
6f5dc12b0d863e885e1c4c62 | train | function | @_ensure_exists
def state(name):
'''
Returns the state of the container
name
Container name or ID
**RETURN DATA**
A string representing the current state of the container (either
``running``, ``paused``, or ``stopped``)
CLI Example:
.. code-block:: bash
salt mymin... | @_ensure_exists
def state(name):
| '''
Returns the state of the container
name
Container name or ID
**RETURN DATA**
A string representing the current state of the container (either
``running``, ``paused``, or ``stopped``)
CLI Example:
.. code-block:: bash
salt myminion dockerng.state mycontainer
... | in ret:
ret[c_id]['Info'] = inspect_container(c_id)
if kwargs.get('host', False):
ret.setdefault(
'host', {}).setdefault(
'interfaces', {}).update(__salt__['network.interfaces']())
return ret
@_ensure_exists
def state(name):
| 64 | 64 | 198 | 9 | 54 | tinyclues/salt | salt/modules/dockerng.py | Python | state | state | 2,325 | 2,356 | 2,325 | 2,326 | 3cffebb1766bd3e4b27728617273f7b008ae60df | bigcode/the-stack | train |
a8f249753c04e200fbb52d2d | train | function | @_refresh_mine_cache
@_ensure_exists
def rm_(name, force=False, volumes=False):
'''
Removes a container
name
Container name or ID
force : False
If ``True``, the container will be killed first before removal, as the
Docker API will not permit a running container to be removed. T... | @_refresh_mine_cache
@_ensure_exists
def rm_(name, force=False, volumes=False):
| '''
Removes a container
name
Container name or ID
force : False
If ``True``, the container will be killed first before removal, as the
Docker API will not permit a running container to be removed. This
option is set to ``False`` by default to prevent accidental removal ... | os.stat(path).st_size
ret['Size_Human'] = _size_fmt(ret['Size'])
# Process push
if kwargs.get(push, False):
ret['Push'] = __salt__['cp.push'](path)
return ret
@_refresh_mine_cache
@_ensure_exists
def rm_(name, force=False, volumes=False):
| 78 | 78 | 261 | 23 | 54 | tinyclues/salt | salt/modules/dockerng.py | Python | rm_ | rm_ | 3,048 | 3,087 | 3,048 | 3,050 | 42bb35fadb9b3337498de9461006015ccd3658a6 | bigcode/the-stack | train |
a463ddd1dfb1b6bd2f56efba | train | function | def save(name,
path,
overwrite=False,
makedirs=False,
compression=None,
**kwargs):
'''
Saves an image and to a file on the minion. Equivalent to running the
``docker save`` Docker CLI command, but unlike ``docker save`` this will
also work on named images ins... | def save(name,
path,
overwrite=False,
makedirs=False,
compression=None,
**kwargs):
| '''
Saves an image and to a file on the minion. Equivalent to running the
``docker save`` Docker CLI command, but unlike ``docker save`` this will
also work on named images instead of just images IDs.
name
Name or ID of image. Specify a specific tag by using the ``repo:tag``
notatio... | image_id,
force=force,
noprune=noprune,
catch_api_errors=False)
except docker.errors.APIError as exc:
if exc.response.status_code == 409:
err = ('Unable to remove image \'{... | 256 | 256 | 1,579 | 25 | 230 | tinyclues/salt | salt/modules/dockerng.py | Python | save | save | 3,791 | 3,990 | 3,791 | 3,796 | fb5921c3abd5251f761598c213aa987f94a2124e | bigcode/the-stack | train |
703527adccd799a7d02975a0 | train | function | @_ensure_exists
def port(name, private_port=None):
'''
Returns port mapping information for a given container. Equivalent to
running the ``docker port`` Docker CLI command.
name
Container name or ID
private_port : None
If specified, get information for that specific port. Can be sp... | @_ensure_exists
def port(name, private_port=None):
| '''
Returns port mapping information for a given container. Equivalent to
running the ``docker port`` Docker CLI command.
name
Container name or ID
private_port : None
If specified, get information for that specific port. Can be specified
either as a port number (i.e. ``500... | Docker CLI command.
name
Container name or ID
CLI Example:
.. code-block:: bash
salt myminion dockerng.logs mycontainer
'''
return _client_wrapper('logs', name)
@_ensure_exists
def pid(name):
'''
Returns the PID of a container
name
Container name or ID
... | 137 | 137 | 457 | 13 | 124 | tinyclues/salt | salt/modules/dockerng.py | Python | port | port | 2,192 | 2,252 | 2,192 | 2,193 | b4f3222f09d41897e79638b5bcf76d8854654666 | bigcode/the-stack | train |
81b54f4bfda1dd914e9e9da3 | train | function | @_ensure_exists
def copy_to(name,
source,
dest,
exec_driver=None,
overwrite=False,
makedirs=False):
'''
Copy a file from the host into a container
name
Container name
source
File to be copied to the container. Can be a local p... | @_ensure_exists
def copy_to(name,
source,
dest,
exec_driver=None,
overwrite=False,
makedirs=False):
| '''
Copy a file from the host into a container
name
Container name
source
File to be copied to the container. Can be a local path on the Minion
or a remote file from the Salt fileserver.
dest
Destination on the container. Must be an absolute path. If the
de... | }'.format(name, source), dest_dir]
__salt__['cmd.run'](cmd, python_shell=False)
return source_md5 == __salt__['file.get_sum'](dest, 'md5')
# Docker cp gets a file from the container, alias this to copy_from
cp = copy_from
@_ensure_exists
def copy_to(name,
source,
dest,
exec... | 97 | 97 | 326 | 31 | 65 | tinyclues/salt | salt/modules/dockerng.py | Python | copy_to | copy_to | 2,811 | 2,864 | 2,811 | 2,817 | 297a221e065cb6857ce88396b731c350f2423b94 | bigcode/the-stack | train |
a3ef069dad605c1ece94d564 | train | function | def pull(image,
insecure_registry=False,
api_response=False,
client_timeout=CLIENT_TIMEOUT):
'''
Pulls an image from a Docker registry. See the documentation at the top of
this page to configure authenticated access.
image
Image to be pulled, in ``repo:tag`` notation.... | def pull(image,
insecure_registry=False,
api_response=False,
client_timeout=CLIENT_TIMEOUT):
| '''
Pulls an image from a Docker registry. See the documentation at the top of
this page to configure authenticated access.
image
Image to be pulled, in ``repo:tag`` notation. If just the repository
name is passed, a tag name of ``latest`` will be assumed.
insecure_registry : False... | as {1}: {2}'
.format(top_level_images[0], image, exc))
return ret
def layers(name):
'''
Returns a list of the IDs of layers belonging to the specified image, with
the top-most layer (the one correspnding to the passed name) appearing
last.
name
Image... | 200 | 200 | 669 | 21 | 178 | tinyclues/salt | salt/modules/dockerng.py | Python | pull | pull | 3,533 | 3,626 | 3,533 | 3,536 | 6276ab81324e7b24b658404290be6e2aed124cab | bigcode/the-stack | train |
622864128a717189d9f26c29 | train | class | class Font(MarshalByRefObject,ICloneable,ISerializable,IDisposable):
"""
Defines a particular format for text,including font face,size,and style attributes. This class cannot be inherited.
Font(prototype: Font,newStyle: FontStyle)
Font(family: FontFamily,emSize: Single,style: FontStyle,unit: GraphicsUnit,... | class Font(MarshalByRefObject,ICloneable,ISerializable,IDisposable):
| """
Defines a particular format for text,including font face,size,and style attributes. This class cannot be inherited.
Font(prototype: Font,newStyle: FontStyle)
Font(family: FontFamily,emSize: Single,style: FontStyle,unit: GraphicsUnit,gdiCharSet: Byte,gdiVerticalFont: bool)
Font(family: FontFamily,emS... | class Font(MarshalByRefObject,ICloneable,ISerializable,IDisposable):
| 19 | 256 | 3,043 | 19 | 0 | hdm-dt-fb/ironpython-stubs | stubs.min/System/Drawing/__init___parts/Font.py | Python | Font | Font | 1 | 534 | 1 | 1 | 7b6a2948675b541fcf67de015670aeda256bbfaa | bigcode/the-stack | train |
dc6bd0b0ecb0179a8899ee42 | train | class | class _TypeDependency(object):
"""Contains information about a dependency a namespace has on a type: the
type's model, and whether that dependency is "hard" meaning that it cannot be
forward declared.
"""
def __init__(self, type_, hard=False):
self.type_ = type_
self.hard = hard
def GetSortKey(self... | class _TypeDependency(object):
| """Contains information about a dependency a namespace has on a type: the
type's model, and whether that dependency is "hard" meaning that it cannot be
forward declared.
"""
def __init__(self, type_, hard=False):
self.type_ = type_
self.hard = hard
def GetSortKey(self):
return '%s.%s' % (self.t... | The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from code import Code
from model import PropertyType
import cpp_util
from json_parse import OrderedDict
import schema_util
class _TypeDependency(object):
| 64 | 64 | 100 | 6 | 57 | 7kbird/chrome | tools/json_schema_compiler/cpp_type_generator.py | Python | _TypeDependency | _TypeDependency | 11 | 21 | 11 | 11 | f2fcf8164c855a01aa0432cc94143805c5583f4b | bigcode/the-stack | train |
f93c73cbbb3c93926c566cb7 | train | class | class CppTypeGenerator(object):
"""Manages the types of properties and provides utilities for getting the
C++ type out of a model.Property
"""
def __init__(self, model, schema_loader, default_namespace=None):
"""Creates a cpp_type_generator. The given root_namespace should be of the
format extensions::a... | class CppTypeGenerator(object):
| """Manages the types of properties and provides utilities for getting the
C++ type out of a model.Property
"""
def __init__(self, model, schema_loader, default_namespace=None):
"""Creates a cpp_type_generator. The given root_namespace should be of the
format extensions::api::sub. The generator will gene... | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from code import Code
from model import PropertyType
import cpp_util
from json_parse import OrderedDict
import schema_util
class _TypeDependency(object)... | 173 | 256 | 2,289 | 7 | 166 | 7kbird/chrome | tools/json_schema_compiler/cpp_type_generator.py | Python | CppTypeGenerator | CppTypeGenerator | 24 | 269 | 24 | 24 | de76bdf74e9af1aa1270b10663a0ad20704ff5ad | bigcode/the-stack | train |
c640f65c71917c997b00c8f2 | train | function | def logout(host,token):
client = httplib2.Http()
token_header = {'Authorization': 'Bearer {}'.format(token)}
url = 'http://{}{}{}'.format(host,uriBase,'/auth/logout')
r, c = client.request(url,method=POST, headers=token_header)
status = None
logger.debug(r)
logger.debug(c)
#data = json... | def logout(host,token):
| client = httplib2.Http()
token_header = {'Authorization': 'Bearer {}'.format(token)}
url = 'http://{}{}{}'.format(host,uriBase,'/auth/logout')
r, c = client.request(url,method=POST, headers=token_header)
status = None
logger.debug(r)
logger.debug(c)
#data = json.loads(c)
#logger.de... | data = response.BaseResponse(c)
if data.get_payload_type() == _AUTH_TYPE:
token = data.get_payload_value('token')
else:
pass
except:
logger.warn("Error Connecting to LOGIN API: %s", url)
return token
def logout(host,token):
| 64 | 64 | 189 | 6 | 57 | OSADP/SEMI-ODE | ode-clients/Libraries/odeClient/restApi.py | Python | logout | logout | 43 | 63 | 43 | 43 | 5fca17a5dab1f549d2ade46d68e7db1228bdc182 | bigcode/the-stack | train |
6ec497ee3a32ef1e78d91ff6 | train | function | def login(host,username,password):
client = httplib2.Http()
client.add_credentials(username,password)
url = 'http://{}{}{}'.format(host,uriBase,'/auth/login')
auth = base64.encodestring(username + ':' + password)
auth_header = { 'Authorization' : 'Basic ' + auth }
logger.debug("URL: %s", url)... | def login(host,username,password):
| client = httplib2.Http()
client.add_credentials(username,password)
url = 'http://{}{}{}'.format(host,uriBase,'/auth/login')
auth = base64.encodestring(username + ':' + password)
auth_header = { 'Authorization' : 'Basic ' + auth }
logger.debug("URL: %s", url)
token = None
try:
r... | import json
import logging
import httplib2
import base64
logger = logging.getLogger('odeClient.restAPI')
import response
uriBase = "/api"
POST = 'POST'
GET = 'GET'
DELETE = 'DELETE'
_AUTH_TYPE = 'auth'
def login(host,username,password):
| 63 | 64 | 200 | 7 | 56 | OSADP/SEMI-ODE | ode-clients/Libraries/odeClient/restApi.py | Python | login | login | 17 | 41 | 17 | 18 | 8e707d46a7b5c46c7ff43263f1eaaa08d31806d2 | bigcode/the-stack | train |
18779a00112d507e77601625 | train | class | class Comment(CommonDateTimeInfo):
commenter = models.ForeignKey('auth.user')
comment_text = models.TextField(max_length = 50)
blogpost = models.ForeignKey(BlogPost,
related_name = 'comments')
class Meta:
verbose_name = 'Comment'
verbose_name_plural = 'Comments'
def __str_... | class Comment(CommonDateTimeInfo):
| commenter = models.ForeignKey('auth.user')
comment_text = models.TextField(max_length = 50)
blogpost = models.ForeignKey(BlogPost,
related_name = 'comments')
class Meta:
verbose_name = 'Comment'
verbose_name_plural = 'Comments'
def __str__(self):
return self.commen... | .ImageField(upload_to = 'blogs')
text = models.TextField()
class Meta:
ordering = ('-created_on',)
verbose_name = 'Blogpost'
verbose_name_plural = 'Blogposts'
def __str__(self):
return self.title
class Comment(CommonDateTimeInfo):
| 64 | 64 | 80 | 7 | 56 | poshan0126/class-ultimate-classof2020 | ultimatewebsite/blogs/models.py | Python | Comment | Comment | 31 | 42 | 31 | 31 | 85c0707373acf2760671d686b6f0993a18504a8d | bigcode/the-stack | train |
ccfe6a8ce964c58c1e8a6fbd | train | class | class CommonDateTimeInfo(models.Model):
created_on = models.DateTimeField(auto_now_add = True)
modified_on = models.DateTimeField(auto_now = True)
class Meta:
abstract = True
| class CommonDateTimeInfo(models.Model):
| created_on = models.DateTimeField(auto_now_add = True)
modified_on = models.DateTimeField(auto_now = True)
class Meta:
abstract = True
| from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
# Create your models here.
class CommonDateTimeInfo(models.Model):
| 34 | 64 | 44 | 8 | 26 | poshan0126/class-ultimate-classof2020 | ultimatewebsite/blogs/models.py | Python | CommonDateTimeInfo | CommonDateTimeInfo | 7 | 12 | 7 | 7 | cc5259043a60de17469068002049ef18704e4139 | bigcode/the-stack | train |
f5c10f95fadf6a9f72b5c32d | train | class | class BlogPost(CommonDateTimeInfo):
title = models.CharField(max_length = 100, unique = True)
slug = models.SlugField()
author = models.ForeignKey('auth.user', related_name = 'uploaded_blogpost')
main_image = models.ImageField(upload_to = 'blogs')
text = models.TextField()
class Meta:
o... | class BlogPost(CommonDateTimeInfo):
| title = models.CharField(max_length = 100, unique = True)
slug = models.SlugField()
author = models.ForeignKey('auth.user', related_name = 'uploaded_blogpost')
main_image = models.ImageField(upload_to = 'blogs')
text = models.TextField()
class Meta:
ordering = ('-created_on',)
v... | from django.utils import timezone
# Create your models here.
class CommonDateTimeInfo(models.Model):
created_on = models.DateTimeField(auto_now_add = True)
modified_on = models.DateTimeField(auto_now = True)
class Meta:
abstract = True
class BlogPost(CommonDateTimeInfo):
| 64 | 64 | 112 | 8 | 55 | poshan0126/class-ultimate-classof2020 | ultimatewebsite/blogs/models.py | Python | BlogPost | BlogPost | 14 | 27 | 14 | 14 | 674becc8611ae9b089b22a5bc1fa86dbf3903891 | bigcode/the-stack | train |
16212b7be0facd3a784de444 | train | class | class JSONHandlerWS(TextBaseHandlerWS):
"""WebSocket media handler for de(serializing) JSON to/from TEXT payloads.
This handler uses Python's standard :py:mod:`json` library by default, but
can be easily configured to use any of a number of third-party JSON
libraries, depending on your needs. For examp... | class JSONHandlerWS(TextBaseHandlerWS):
| """WebSocket media handler for de(serializing) JSON to/from TEXT payloads.
This handler uses Python's standard :py:mod:`json` library by default, but
can be easily configured to use any of a number of third-party JSON
libraries, depending on your needs. For example, you can often
realize a signific... | JSON body - {0}'.format(err)
)
def serialize(self, media, content_type):
result = self.dumps(media)
try:
result = result.encode('utf-8')
except AttributeError: # pragma: nocover
# NOTE(kgriffs): Assume that dumps() is non-standard in that it
... | 161 | 161 | 537 | 9 | 151 | adsahay/falcon | falcon/media/json.py | Python | JSONHandlerWS | JSONHandlerWS | 115 | 181 | 115 | 115 | b2b909c21151ad3e8a0a2472488af69f33ea1a9f | bigcode/the-stack | train |
e1fec5537deecb7128973dae | train | class | class JSONHandler(BaseHandler):
"""JSON media handler.
This handler uses Python's standard :py:mod:`json` library by default, but
can be easily configured to use any of a number of third-party JSON
libraries, depending on your needs. For example, you can often
realize a significant performance boos... | class JSONHandler(BaseHandler):
| """JSON media handler.
This handler uses Python's standard :py:mod:`json` library by default, but
can be easily configured to use any of a number of third-party JSON
libraries, depending on your needs. For example, you can often
realize a significant performance boost under CPython by using an
... | from functools import partial
from falcon import errors
from falcon.media.base import BaseHandler, TextBaseHandlerWS
from falcon.util import json
class JSONHandler(BaseHandler):
| 38 | 230 | 769 | 6 | 31 | adsahay/falcon | falcon/media/json.py | Python | JSONHandler | JSONHandler | 8 | 112 | 8 | 8 | 44299a8b8c4855243edfd3b782e256021a5f0130 | bigcode/the-stack | train |
422ebad3ccd9b7822d8dd964 | train | class | class DriverInterface:
"""Interfaz que deben cumplir las impresoras fiscales."""
# Documentos no fiscales
def close(self):
"""Cierra recurso de conexion con impresora"""
raise NotImplementedError
def sendCommand(self, commandNumber, parameters, skipStatusErrors):
"""... | class DriverInterface:
| """Interfaz que deben cumplir las impresoras fiscales."""
# Documentos no fiscales
def close(self):
"""Cierra recurso de conexion con impresora"""
raise NotImplementedError
def sendCommand(self, commandNumber, parameters, skipStatusErrors):
"""Envia comando a impresor... | # -*- coding: iso-8859-1 -*-
class DriverInterface:
| 15 | 64 | 76 | 4 | 11 | ssaid/fiscalberry | DriverInterface.py | Python | DriverInterface | DriverInterface | 4 | 15 | 4 | 4 | 3c4f0a9c9c6f78e3eac70d763e931f72dcd0f118 | bigcode/the-stack | train |
d4f68d8c5674db70cf837db0 | train | function | def validate(config):
"""
Validate the beacon configuration
"""
VALID_ITEMS = [
"type",
"bytes_sent",
"bytes_recv",
"packets_sent",
"packets_recv",
"errin",
"errout",
"dropin",
"dropout",
]
# Configuration for load beacon ... | def validate(config):
| """
Validate the beacon configuration
"""
VALID_ITEMS = [
"type",
"bytes_sent",
"bytes_recv",
"packets_sent",
"packets_recv",
"errin",
"errout",
"dropin",
"dropout",
]
# Configuration for load beacon should be a list of di... | return ret
def __virtual__():
if not HAS_PSUTIL:
err_msg = "psutil not available"
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg
return __virtualname__
def validate(config):
| 63 | 64 | 213 | 4 | 59 | tomdoherty/salt | salt/beacons/network_info.py | Python | validate | validate | 54 | 91 | 54 | 54 | 26598be2e7aeeac1f1ab56eafe610647c2551d20 | bigcode/the-stack | train |
e0a5aa3ae6d8efd803727904 | train | function | def __virtual__():
if not HAS_PSUTIL:
err_msg = "psutil not available"
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg
return __virtualname__
| def __virtual__():
| if not HAS_PSUTIL:
err_msg = "psutil not available"
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg
return __virtualname__
| in",
"dropout",
]
def _to_list(obj):
"""
Convert snetinfo object to list
"""
ret = {}
for attr in __attrs:
if hasattr(obj, attr):
ret[attr] = getattr(obj, attr)
return ret
def __virtual__():
| 64 | 64 | 56 | 5 | 58 | tomdoherty/salt | salt/beacons/network_info.py | Python | __virtual__ | __virtual__ | 46 | 51 | 46 | 46 | 99e93bab38faf6f07ab06d6715f0c3b0278cc3ff | bigcode/the-stack | train |
179c98efff03d7c5ebeb6dc7 | train | function | def _to_list(obj):
"""
Convert snetinfo object to list
"""
ret = {}
for attr in __attrs:
if hasattr(obj, attr):
ret[attr] = getattr(obj, attr)
return ret
| def _to_list(obj):
| """
Convert snetinfo object to list
"""
ret = {}
for attr in __attrs:
if hasattr(obj, attr):
ret[attr] = getattr(obj, attr)
return ret
| name__)
__virtualname__ = "network_info"
__attrs = [
"bytes_sent",
"bytes_recv",
"packets_sent",
"packets_recv",
"errin",
"errout",
"dropin",
"dropout",
]
def _to_list(obj):
| 64 | 64 | 51 | 6 | 58 | tomdoherty/salt | salt/beacons/network_info.py | Python | _to_list | _to_list | 34 | 43 | 34 | 34 | 51d88735308d5b1dbd57a0f7a07ecc21f218198a | bigcode/the-stack | train |
f88bfa368541538717d547ec | train | function | def beacon(config):
"""
Emit the network statistics of this host.
Specify thresholds for each network stat
and only emit a beacon if any of them are
exceeded.
Emit beacon when any values are equal to
configured values.
.. code-block:: yaml
beacons:
network_info:
... | def beacon(config):
| """
Emit the network statistics of this host.
Specify thresholds for each network stat
and only emit a beacon if any of them are
exceeded.
Emit beacon when any values are equal to
configured values.
.. code-block:: yaml
beacons:
network_info:
- interface... | "dropin",
"dropout",
]
# Configuration for load beacon should be a list of dicts
if not isinstance(config, list):
return False, "Configuration for network_info beacon must be a list."
else:
config = salt.utils.beacons.list_to_dict(config)
for item in config.get... | 162 | 162 | 541 | 4 | 158 | tomdoherty/salt | salt/beacons/network_info.py | Python | beacon | beacon | 94 | 183 | 94 | 94 | 20bc7f26ae3a934b45ba884af4592920f9998d7d | bigcode/the-stack | train |
ce23bc29580bfb0b9357eae8 | train | class | class HistogramValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name='histogram', parent_name='', **kwargs):
super(HistogramValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop('data_cl... | class HistogramValidator(_plotly_utils.basevalidators.CompoundValidator):
| def __init__(self, plotly_name='histogram', parent_name='', **kwargs):
super(HistogramValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop('data_class_str', 'Histogram'),
data_docs=kwargs.pop(
'... | import _plotly_utils.basevalidators
class HistogramValidator(_plotly_utils.basevalidators.CompoundValidator):
| 21 | 256 | 1,703 | 13 | 7 | gnestor/plotly.py | plotly/validators/_histogram.py | Python | HistogramValidator | HistogramValidator | 4 | 194 | 4 | 5 | d50ee4a4355d5e3cea40e44cd8b0cd442539320e | bigcode/the-stack | train |
4fef161ba82ef18c51a9f59b | train | function | def get_alternate_from_mutation(mutation:str)->str:
unknown_value = "N/A"
if '-' in mutation and len(mutation) == 3:
result = mutation.split('-')[-1]
elif mutation.startswith('+'):
result = mutation[1]
elif mutation.startswith('D'):
result = mutation
else:
result = unknown_value
return result
| def get_alternate_from_mutation(mutation:str)->str:
| unknown_value = "N/A"
if '-' in mutation and len(mutation) == 3:
result = mutation.split('-')[-1]
elif mutation.startswith('+'):
result = mutation[1]
elif mutation.startswith('D'):
result = mutation
else:
result = unknown_value
return result
| ref = "".join([i for i in mutation if i in "ACGT"])
logger.warning(ref)
elif annotation.startswith('D'):
# It's a deletion
ref = "."
else:
ref = '.'
return ref
def get_alternate_from_mutation(mutation:str)->str:
| 64 | 64 | 78 | 13 | 50 | cdeitrick/isolate_parsers | isolateparser/resultparser/breseq_folder_parser.py | Python | get_alternate_from_mutation | get_alternate_from_mutation | 118 | 128 | 118 | 118 | be45454a84870dbbc87eb6072f8fd5c75e6c2cc3 | bigcode/the-stack | train |
42a144e7e1c5243fbe207db1 | train | function | def _filter_bp(raw_df: pandas.DataFrame) -> pandas.DataFrame:
# TODO: This should only be done for sequences on the same chrom.
""" Filters out variants that occur within 1000bp of each other."""
forward: pandas.Series = raw_df[IsolateTableColumns.position].diff().abs()
reverse: pandas.Series = raw_df[IsolateTableC... | def _filter_bp(raw_df: pandas.DataFrame) -> pandas.DataFrame:
# TODO: This should only be done for sequences on the same chrom.
| """ Filters out variants that occur within 1000bp of each other."""
forward: pandas.Series = raw_df[IsolateTableColumns.position].diff().abs()
reverse: pandas.Series = raw_df[IsolateTableColumns.position][::-1].diff()[::-1].abs()
# noinspection PyTypeChecker
fdf: pandas.DataFrame = raw_df[(forward > 1000) & (reve... | result = length > 8 and len([i for i in value if i.isdigit()]) > (len(value) / 2)
return result
def _filter_bp(raw_df: pandas.DataFrame) -> pandas.DataFrame:
# TODO: This should only be done for sequences on the same chrom.
| 64 | 64 | 140 | 32 | 31 | cdeitrick/isolate_parsers | isolateparser/resultparser/breseq_folder_parser.py | Python | _filter_bp | _filter_bp | 57 | 66 | 57 | 58 | b3a4c399e72cd4ad530f5653b923e81d5ad9479f | bigcode/the-stack | train |
18b3806c6570c4993ebc9a19 | train | function | def get_sample_name(folder: Path) -> Optional[str]:
""" Attempt to extract the sample name from a folder."""
return [i for i in folder.parts if 'breseq' not in i][-1]
| def get_sample_name(folder: Path) -> Optional[str]:
| """ Attempt to extract the sample name from a folder."""
return [i for i in folder.parts if 'breseq' not in i][-1]
| from pathlib import Path
from typing import *
import pandas
from loguru import logger
from .parsers import GDParser, IndexParser, parse_summary_file, parse_vcf_file, GDToTable
from ..tableformat import IsolateTableColumns
def get_sample_name(folder: Path) -> Optional[str]:
| 64 | 64 | 43 | 12 | 51 | cdeitrick/isolate_parsers | isolateparser/resultparser/breseq_folder_parser.py | Python | get_sample_name | get_sample_name | 46 | 48 | 46 | 46 | 3d493a6a36a8b3e953d84465b35c0cc017ef4d8d | bigcode/the-stack | train |
1d846f4b7688d0324c94e2a5 | train | function | def string_is_date(value: str) -> bool:
length = len(value)
result = length > 8 and len([i for i in value if i.isdigit()]) > (len(value) / 2)
return result
| def string_is_date(value: str) -> bool:
| length = len(value)
result = length > 8 and len([i for i in value if i.isdigit()]) > (len(value) / 2)
return result
| from ..tableformat import IsolateTableColumns
def get_sample_name(folder: Path) -> Optional[str]:
""" Attempt to extract the sample name from a folder."""
return [i for i in folder.parts if 'breseq' not in i][-1]
def string_is_date(value: str) -> bool:
| 64 | 64 | 48 | 11 | 53 | cdeitrick/isolate_parsers | isolateparser/resultparser/breseq_folder_parser.py | Python | string_is_date | string_is_date | 51 | 54 | 51 | 51 | 720aa6c037a768dd7909fb090ed2023c2182a8bd | bigcode/the-stack | train |
01ce477f72c292fce701860c | train | function | def get_reference_from_mutation(mutation:str, annotation:str)->str:
if '-' in mutation and len(mutation) == 3:
ref = mutation.split('-')[0]
elif mutation.startswith('+'):
# An insertion
ref = "."
elif mutation.startswith('('):
# Should be an insertion
ref = "".join([i for i in mutation if i in "ACGT"])
l... | def get_reference_from_mutation(mutation:str, annotation:str)->str:
| if '-' in mutation and len(mutation) == 3:
ref = mutation.split('-')[0]
elif mutation.startswith('+'):
# An insertion
ref = "."
elif mutation.startswith('('):
# Should be an insertion
ref = "".join([i for i in mutation if i in "ACGT"])
logger.warning(ref)
elif annotation.startswith('D'):
# It's a dele... | length < 100:
result = 'deletion'
else:
result = "large_deletion"
else:
logger.debug(f"Could not categorize '{mutation}', '{annotation}'")
result = "unknown"
return result
def get_reference_from_mutation(mutation:str, annotation:str)->str:
| 64 | 64 | 118 | 15 | 48 | cdeitrick/isolate_parsers | isolateparser/resultparser/breseq_folder_parser.py | Python | get_reference_from_mutation | get_reference_from_mutation | 100 | 116 | 100 | 100 | 3c62602f54d9fb9b6f2f02f9454da777dc99b723 | bigcode/the-stack | train |
5a0becfd509d429c7ff31b54 | train | class | class BreseqFolderParser:
"""
Parses the contents of a breseq run folder.
"""
def __init__(self, use_filter: bool = False):
self._set_table_index = True
self.use_filter = use_filter
self.index_columns = []
# We only want a subset of the columns available from the gd and vcf files.
self.gd_columns = ['a... | class BreseqFolderParser:
| """
Parses the contents of a breseq run folder.
"""
def __init__(self, use_filter: bool = False):
self._set_table_index = True
self.use_filter = use_filter
self.index_columns = []
# We only want a subset of the columns available from the gd and vcf files.
self.gd_columns = ['aminoAlt', 'aminoRef', 'cod... | join(numbers))
if length < 100:
result = 'deletion'
else:
result = "large_deletion"
else:
logger.debug(f"Could not categorize '{mutation}', '{annotation}'")
result = "unknown"
return result
def get_reference_from_mutation(mutation:str, annotation:str)->str:
if '-' in mutation and len(mutation) == 3:... | 256 | 256 | 1,510 | 6 | 249 | cdeitrick/isolate_parsers | isolateparser/resultparser/breseq_folder_parser.py | Python | BreseqFolderParser | BreseqFolderParser | 131 | 265 | 131 | 131 | 68b1032aa9e7891c619283a50ae8f197899fdcce | bigcode/the-stack | train |
92e9816d74f086f920cb9f70 | train | function | def catagorize_mutation(annotation:str, mutation:str)->str:
""" Used when the mutation category is not available from the gd file."""
if '-' in annotation:
# is a SNP
if 'intergenic' in annotation:
result = "snp_intergenic"
else:
# Should be an amino acid annotation
# Ex. G117G (GGC→GGG)
aminoannota... | def catagorize_mutation(annotation:str, mutation:str)->str:
| """ Used when the mutation category is not available from the gd file."""
if '-' in annotation:
# is a SNP
if 'intergenic' in annotation:
result = "snp_intergenic"
else:
# Should be an amino acid annotation
# Ex. G117G (GGC→GGG)
aminoannotation = annotation.split(' ')[0]
result = "snp_synonymous"... | .Series = raw_df[IsolateTableColumns.position][::-1].diff()[::-1].abs()
# noinspection PyTypeChecker
fdf: pandas.DataFrame = raw_df[(forward > 1000) & (reverse > 1000) | (forward.isna() | reverse.isna())]
return fdf
def catagorize_mutation(annotation:str, mutation:str)->str:
| 84 | 84 | 283 | 15 | 68 | cdeitrick/isolate_parsers | isolateparser/resultparser/breseq_folder_parser.py | Python | catagorize_mutation | catagorize_mutation | 68 | 98 | 68 | 68 | 0171b99cfcbb046fe964f7e1ff53a9f4d4f85311 | bigcode/the-stack | train |
32cc8d2cc0c595c53bbfbdc2 | train | function | def test_segwit_bumpfee_succeeds(rbf_node, dest_address):
# Create a transaction with segwit output, then create an RBF transaction
# which spends it, and make sure bumpfee can be called on it.
segwit_in = next(u for u in rbf_node.listunspent() if u["amount"] == Decimal("0.001"))
segwit_out = rbf_node.... | def test_segwit_bumpfee_succeeds(rbf_node, dest_address):
# Create a transaction with segwit output, then create an RBF transaction
# which spends it, and make sure bumpfee can be called on it.
| segwit_in = next(u for u in rbf_node.listunspent() if u["amount"] == Decimal("0.001"))
segwit_out = rbf_node.getaddressinfo(rbf_node.getnewaddress(address_type='p2sh-segwit'))
segwitid = send_to_witness(
use_p2wsh=False,
node=rbf_node,
utxo=segwit_in,
pubkey=segwit_out["pubke... | tx = rbf_node.gettransaction(bumped_tx["txid"])
assert_equal(oldwtx["replaced_by_txid"], bumped_tx["txid"])
assert_equal(bumpedwtx["replaces_txid"], rbfid)
def test_segwit_bumpfee_succeeds(rbf_node, dest_address):
# Create a transaction with segwit output, then create an RBF transaction
# which spends i... | 102 | 102 | 341 | 52 | 50 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_segwit_bumpfee_succeeds | test_segwit_bumpfee_succeeds | 105 | 132 | 105 | 108 | b6da608765b862639922dfbfb1f737cb7b296351 | bigcode/the-stack | train |
abba6811148a75345036faab | train | function | def test_bumpfee_metadata(rbf_node, dest_address):
rbfid = rbf_node.sendtoaddress(dest_address, Decimal("0.00100000"), "comment value", "to value")
bumped_tx = rbf_node.bumpfee(rbfid)
bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"])
assert_equal(bumped_wtx["comment"], "comment value")
assert_... | def test_bumpfee_metadata(rbf_node, dest_address):
| rbfid = rbf_node.sendtoaddress(dest_address, Decimal("0.00100000"), "comment value", "to value")
bumped_tx = rbf_node.bumpfee(rbfid)
bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"])
assert_equal(bumped_wtx["comment"], "comment value")
assert_equal(bumped_wtx["to"], "to value")
| 1 for t in rbf_node.listunspent(minconf=0, include_unsafe=False)
if t["txid"] == rbfid and t["address"] == rbf_node_address and t["spendable"]), 1)
def test_bumpfee_metadata(rbf_node, dest_address):
| 64 | 64 | 101 | 13 | 51 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_bumpfee_metadata | test_bumpfee_metadata | 266 | 271 | 266 | 266 | 208e1553767c7cc38c35dbe782a405ab3b281351 | bigcode/the-stack | train |
4779ec85a840d55f123012e7 | train | function | def test_small_output_fails(rbf_node, dest_address):
# cannot bump fee with a too-small output
rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.bumpfee(rbfid, {"totalFee": 50000})
rbfid = spend_one_input(rbf_node, dest_address)
assert_raises_rpc_error(-4, "Change output is too small", rbf_n... | def test_small_output_fails(rbf_node, dest_address):
# cannot bump fee with a too-small output
| rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.bumpfee(rbfid, {"totalFee": 50000})
rbfid = spend_one_input(rbf_node, dest_address)
assert_raises_rpc_error(-4, "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 50001})
| wallet(tx)
rbf_node.sendrawtransaction(tx["hex"])
assert_raises_rpc_error(-8, "Transaction has descendants in the wallet", rbf_node.bumpfee, parent_id)
def test_small_output_fails(rbf_node, dest_address):
# cannot bump fee with a too-small output
| 64 | 64 | 106 | 24 | 40 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_small_output_fails | test_small_output_fails | 172 | 178 | 172 | 173 | 57bb189ad4cb903c35f0fe0c57d9c0bc0a6dde2c | bigcode/the-stack | train |
67e1b8fc1724cf864213cbde | train | function | def test_settxfee(rbf_node, dest_address):
assert_raises_rpc_error(-8, "txfee cannot be less than min relay tx fee", rbf_node.settxfee, Decimal('0.000005'))
assert_raises_rpc_error(-8, "txfee cannot be less than wallet min fee", rbf_node.settxfee, Decimal('0.000015'))
# check that bumpfee reacts correctly t... | def test_settxfee(rbf_node, dest_address):
| assert_raises_rpc_error(-8, "txfee cannot be less than min relay tx fee", rbf_node.settxfee, Decimal('0.000005'))
assert_raises_rpc_error(-8, "txfee cannot be less than wallet min fee", rbf_node.settxfee, Decimal('0.000015'))
# check that bumpfee reacts correctly to the use of settxfee (paytxfee)
rbfid ... | rbf_node.getrawtransaction(bumped_tx["txid"], 1)
assert_equal(bumped_tx["fee"], Decimal("0.00050000"))
assert_equal(len(fulltx["vout"]), 2)
assert_equal(len(full_bumped_tx["vout"]), 1) # change output is eliminated
def test_settxfee(rbf_node, dest_address):
| 80 | 80 | 267 | 12 | 67 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_settxfee | test_settxfee | 196 | 208 | 196 | 196 | 653ea9e19a61b8493f4440d5cec1cc8de383d546 | bigcode/the-stack | train |
000085f022fac7f8f52081ed | train | function | def test_unconfirmed_not_spendable(rbf_node, rbf_node_address):
# check that unconfirmed outputs from bumped transactions are not spendable
rbfid = spend_one_input(rbf_node, rbf_node_address)
rbftx = rbf_node.gettransaction(rbfid)["hex"]
assert rbfid in rbf_node.getrawmempool()
bumpid = rbf_node.bum... | def test_unconfirmed_not_spendable(rbf_node, rbf_node_address):
# check that unconfirmed outputs from bumped transactions are not spendable
| rbfid = spend_one_input(rbf_node, rbf_node_address)
rbftx = rbf_node.gettransaction(rbfid)["hex"]
assert rbfid in rbf_node.getrawmempool()
bumpid = rbf_node.bumpfee(rbfid)["txid"]
assert bumpid in rbf_node.getrawmempool()
assert rbfid not in rbf_node.getrawmempool()
# check that outputs fro... | 3000})
rbf_node.bumpfee(bumped["txid"], {"totalFee": 3000})
def test_rebumping_not_replaceable(rbf_node, dest_address):
# check that re-bumping a non-replaceable bump tx fails
rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 10000, "replaceable": False})
... | 167 | 167 | 557 | 32 | 135 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_unconfirmed_not_spendable | test_unconfirmed_not_spendable | 227 | 263 | 227 | 228 | 14b37bc7ae34415047148edbc059e2e97447b513 | bigcode/the-stack | train |
c68c08d23ecc83e58ad48603 | train | function | def test_nonrbf_bumpfee_fails(peer_node, dest_address):
# cannot replace a non RBF transaction (from node which did not enable RBF)
not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.00090000"))
assert_raises_rpc_error(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid)
| def test_nonrbf_bumpfee_fails(peer_node, dest_address):
# cannot replace a non RBF transaction (from node which did not enable RBF)
| not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.00090000"))
assert_raises_rpc_error(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid)
| txid"] in rbf_node.getrawmempool()
assert rbfid not in rbf_node.getrawmempool()
def test_nonrbf_bumpfee_fails(peer_node, dest_address):
# cannot replace a non RBF transaction (from node which did not enable RBF)
| 64 | 64 | 85 | 35 | 29 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_nonrbf_bumpfee_fails | test_nonrbf_bumpfee_fails | 135 | 138 | 135 | 136 | 900fbf4ac105b28227a2e59f9b8b39d5cfc76b1b | bigcode/the-stack | train |
ffdf1af35c182507bd8c780d | train | function | def test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address):
rbfid = spend_one_input(rbf_node, dest_address)
rbftx = rbf_node.gettransaction(rbfid)
sync_mempools((rbf_node, peer_node))
assert rbfid in rbf_node.getrawmempool() and rbfid in peer_node.getrawmempool()
bumped_tx = rbf_node.bumpfe... | def test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address):
| rbfid = spend_one_input(rbf_node, dest_address)
rbftx = rbf_node.gettransaction(rbfid)
sync_mempools((rbf_node, peer_node))
assert rbfid in rbf_node.getrawmempool() and rbfid in peer_node.getrawmempool()
bumped_tx = rbf_node.bumpfee(rbfid)
assert_equal(bumped_tx["errors"], [])
assert bumped_... | test_rebumping(rbf_node, dest_address)
test_rebumping_not_replaceable(rbf_node, dest_address)
test_unconfirmed_not_spendable(rbf_node, rbf_node_address)
test_bumpfee_metadata(rbf_node, dest_address)
test_locked_wallet_fails(rbf_node, dest_address)
self.log.info("Success")... | 96 | 96 | 323 | 19 | 77 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_simple_bumpfee_succeeds | test_simple_bumpfee_succeeds | 83 | 102 | 83 | 83 | cb2402c21e4d2fe143ab5e665c860c7095eaa220 | bigcode/the-stack | train |
b9925ff10b4d147594301a9c | train | function | def test_rebumping_not_replaceable(rbf_node, dest_address):
# check that re-bumping a non-replaceable bump tx fails
rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 10000, "replaceable": False})
assert_raises_rpc_error(-4, "Transaction is not BIP 125 replacea... | def test_rebumping_not_replaceable(rbf_node, dest_address):
# check that re-bumping a non-replaceable bump tx fails
| rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 10000, "replaceable": False})
assert_raises_rpc_error(-4, "Transaction is not BIP 125 replaceable", rbf_node.bumpfee, bumped["txid"],
{"totalFee": 20000})
| , rbfid, {"totalFee": 3000})
rbf_node.bumpfee(bumped["txid"], {"totalFee": 3000})
def test_rebumping_not_replaceable(rbf_node, dest_address):
# check that re-bumping a non-replaceable bump tx fails
| 64 | 64 | 112 | 31 | 33 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_rebumping_not_replaceable | test_rebumping_not_replaceable | 219 | 224 | 219 | 220 | 676a80b0b88845ff0c8f619e234422300f88d8b7 | bigcode/the-stack | train |
9b83130fe629c80767d7cae7 | train | function | def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address):
# cannot bump fee if the transaction has a descendant
# parent is send-to-self, so we don't have to check which output is change when creating the child tx
parent_id = spend_one_input(rbf_node, rbf_node_address)
tx = rbf_n... | def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address):
# cannot bump fee if the transaction has a descendant
# parent is send-to-self, so we don't have to check which output is change when creating the child tx
| parent_id = spend_one_input(rbf_node, rbf_node_address)
tx = rbf_node.createrawtransaction([{"txid": parent_id, "vout": 0}], {dest_address: 0.00020000})
tx = rbf_node.signrawtransactionwithwallet(tx)
rbf_node.sendrawtransaction(tx["hex"])
assert_raises_rpc_error(-8, "Transaction has descendants in t... | fee, rbfid)
def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address):
# cannot bump fee if the transaction has a descendant
# parent is send-to-self, so we don't have to check which output is change when creating the child tx
| 64 | 64 | 160 | 58 | 6 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_bumpfee_with_descendant_fails | test_bumpfee_with_descendant_fails | 162 | 169 | 162 | 164 | a9ae838c4e3f2fa948223a5b9dbe027d70f01d3e | bigcode/the-stack | train |
7793ee84deaebccaec165875 | train | function | def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address):
# cannot bump fee unless the tx has only inputs that we own.
# here, the rbftx has a peer_node coin and then adds a rbf_node input
# Note that this test depends upon the RPC code checking input ownership prior to change outputs
# (since ... | def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address):
# cannot bump fee unless the tx has only inputs that we own.
# here, the rbftx has a peer_node coin and then adds a rbf_node input
# Note that this test depends upon the RPC code checking input ownership prior to change outputs
# (since ... | utxos = [node.listunspent()[-1] for node in (rbf_node, peer_node)]
inputs = [{
"txid": utxo["txid"],
"vout": utxo["vout"],
"address": utxo["address"],
"sequence": BIP125_SEQUENCE_NUMBER
} for utxo in utxos]
output_val = sum(utxo["amount"] for utxo in utxos) - Decimal("0.0... | def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address):
# cannot bump fee unless the tx has only inputs that we own.
# here, the rbftx has a peer_node coin and then adds a rbf_node input
# Note that this test depends upon the RPC code checking input ownership prior to change outputs
# (since ... | 93 | 89 | 299 | 93 | 0 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_notmine_bumpfee_fails | test_notmine_bumpfee_fails | 141 | 159 | 141 | 145 | 11dd72f7ec69b876059a9dba573547e582eb93b5 | bigcode/the-stack | train |
3c695519bec33e0ea610b09e | train | function | def spend_one_input(node, dest_address):
tx_input = dict(
sequence=BIP125_SEQUENCE_NUMBER, **next(u for u in node.listunspent() if u["amount"] == Decimal("0.00100000")))
rawtx = node.createrawtransaction(
[tx_input], {dest_address: Decimal("0.00050000"),
node.getrawchangeadd... | def spend_one_input(node, dest_address):
| tx_input = dict(
sequence=BIP125_SEQUENCE_NUMBER, **next(u for u in node.listunspent() if u["amount"] == Decimal("0.00100000")))
rawtx = node.createrawtransaction(
[tx_input], {dest_address: Decimal("0.00050000"),
node.getrawchangeaddress(): Decimal("0.00049000")})
signe... | rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first.",
rbf_node.bumpfee, rbfid)
def spend_one_input(node, dest_address):
| 64 | 64 | 123 | 9 | 55 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | spend_one_input | spend_one_input | 281 | 289 | 281 | 281 | 0c5099cfc6461a45052cf292e386326b418f2de5 | bigcode/the-stack | train |
ffca38f0cda394d2a23b365a | train | function | def submit_block_with_tx(node, tx):
ctx = CTransaction()
ctx.deserialize(io.BytesIO(hex_str_to_bytes(tx)))
tip = node.getbestblockhash()
height = node.getblockcount() + 1
block_time = node.getblockheader(tip)["mediantime"] + 1
block = create_block(int(tip, 16), create_coinbase(height), block_ti... | def submit_block_with_tx(node, tx):
| ctx = CTransaction()
ctx.deserialize(io.BytesIO(hex_str_to_bytes(tx)))
tip = node.getbestblockhash()
height = node.getblockcount() + 1
block_time = node.getblockheader(tip)["mediantime"] + 1
block = create_block(int(tip, 16), create_coinbase(height), block_time, version=0x20000000)
block.vt... | ("0.00050000"),
node.getrawchangeaddress(): Decimal("0.00049000")})
signedtx = node.signrawtransactionwithwallet(rawtx)
txid = node.sendrawtransaction(signedtx["hex"])
return txid
def submit_block_with_tx(node, tx):
| 64 | 64 | 148 | 9 | 54 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | submit_block_with_tx | submit_block_with_tx | 292 | 306 | 292 | 292 | 3d840ce1b83972bbcf5c9b27ea20497616418683 | bigcode/the-stack | train |
b2355677bbf5640cfdd58bdb | train | class | class BumpFeeTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[
"-walletrbf={}".format(i),
"-mintxfee=0.00002",
"-mempoolreplacement=1",
] for i in range(self.num_nodes)]
... | class BumpFeeTest(BitcoinTestFramework):
| def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[
"-walletrbf={}".format(i),
"-mintxfee=0.00002",
"-mempoolreplacement=1",
] for i in range(self.num_nodes)]
def skip_test_if_missing_module(self):
... | new test cases are
added in the future, they should try to follow the same convention and not
make assumptions about execution order.
"""
from decimal import Decimal
import io
from test_framework.blocktools import add_witness_commitment, create_block, create_coinbase, send_to_witness
from test_framework.messages impo... | 164 | 164 | 548 | 10 | 153 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | BumpFeeTest | BumpFeeTest | 27 | 80 | 27 | 27 | a506936c677bc228a1ad11674bfd1e2c8fd2c53b | bigcode/the-stack | train |
566198cbc6ef526dabd34719 | train | function | def test_rebumping(rbf_node, dest_address):
# check that re-bumping the original tx fails, but bumping the bumper succeeds
rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 2000})
assert_raises_rpc_error(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFe... | def test_rebumping(rbf_node, dest_address):
# check that re-bumping the original tx fails, but bumping the bumper succeeds
| rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 2000})
assert_raises_rpc_error(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFee": 3000})
rbf_node.bumpfee(bumped["txid"], {"totalFee": 3000})
| ed_feerate - actual_feerate))
rbf_node.settxfee(Decimal("0.00000000")) # unset paytxfee
def test_rebumping(rbf_node, dest_address):
# check that re-bumping the original tx fails, but bumping the bumper succeeds
| 64 | 64 | 117 | 31 | 32 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_rebumping | test_rebumping | 211 | 216 | 211 | 212 | cb1f4822f77ccb39ae7284fcfadeb7bd93e430cf | bigcode/the-stack | train |
d0835aad7234c77a98d74fc6 | train | function | def test_dust_to_fee(rbf_node, dest_address):
# check that if output is reduced to dust, it will be converted to fee
# the bumped tx sets fee=49,900, but it converts to 50,000
rbfid = spend_one_input(rbf_node, dest_address)
fulltx = rbf_node.getrawtransaction(rbfid, 1)
# (32-byte p2sh-pwpkh output s... | def test_dust_to_fee(rbf_node, dest_address):
# check that if output is reduced to dust, it will be converted to fee
# the bumped tx sets fee=49,900, but it converts to 50,000
| rbfid = spend_one_input(rbf_node, dest_address)
fulltx = rbf_node.getrawtransaction(rbfid, 1)
# (32-byte p2sh-pwpkh output size + 148 p2pkh spend estimate) * 10k(discard_rate) / 1000 = 1800
# P2SH outputs are slightly "over-discarding" due to the IsDust calculation assuming it will
# be spent as a P... | "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 50001})
def test_dust_to_fee(rbf_node, dest_address):
# check that if output is reduced to dust, it will be converted to fee
# the bumped tx sets fee=49,900, but it converts to 50,000
| 77 | 77 | 259 | 52 | 25 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_dust_to_fee | test_dust_to_fee | 181 | 193 | 181 | 183 | 66a26d8a57e13340f6a3e65de0ca67ed6efdf908 | bigcode/the-stack | train |
e303c3e3a1f2abaa72f964d6 | train | function | def test_locked_wallet_fails(rbf_node, dest_address):
rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first.",
rbf_node.bumpfee, rbfid)
| def test_locked_wallet_fails(rbf_node, dest_address):
| rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first.",
rbf_node.bumpfee, rbfid)
| .bumpfee(rbfid)
bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"])
assert_equal(bumped_wtx["comment"], "comment value")
assert_equal(bumped_wtx["to"], "to value")
def test_locked_wallet_fails(rbf_node, dest_address):
| 64 | 64 | 68 | 13 | 51 | minblock/Blackcoin | test/functional/wallet_bumpfee.py | Python | test_locked_wallet_fails | test_locked_wallet_fails | 274 | 278 | 274 | 274 | 9ba96db792a37d8794149595da0915bb7bfc7feb | bigcode/the-stack | train |
952a2ada5885b2906e0e215d | train | function | def dataset_exists(dataset_name):
'''If a dataset with the given name exists, return its absolute path; otherwise return None'''
dataset_dir = os.path.join(LIB_DIR, 'datasets')
dataset_path = os.path.join(dataset_dir, dataset_name)
return dataset_path if os.path.isdir(dataset_path) else None
| def dataset_exists(dataset_name):
| '''If a dataset with the given name exists, return its absolute path; otherwise return None'''
dataset_dir = os.path.join(LIB_DIR, 'datasets')
dataset_path = os.path.join(dataset_dir, dataset_name)
return dataset_path if os.path.isdir(dataset_path) else None
| .join(dataset_dir, d))]
if not datasets:
print("No available datasets; try creating one by processing a corpus with 'dsrt dataset prepare'")
return
print("Available datasets:")
for d in datasets:
print("\t* " + d)
def dataset_exists(dataset_name):
| 63 | 64 | 68 | 6 | 57 | sbarham/dsrt | dsrt/application/utils.py | Python | dataset_exists | dataset_exists | 40 | 45 | 40 | 40 | 4582567f8cbb4af3873b70c39bec16ca65bd113f | bigcode/the-stack | train |
88a857d919d89a752ccbddd9 | train | function | def import_corpus(src, new_name):
if not os.path.exists(src):
raise Error("Unable to locate corpus at '{}'".format(src))
dst = os.path.join(LIB_DIR, 'corpora', new_name)
if os.path.exists(dst):
choice = input("Corpus '{}' already exists; overwrite it? y(es) | n(o): ".format(new_name))
... | def import_corpus(src, new_name):
| if not os.path.exists(src):
raise Error("Unable to locate corpus at '{}'".format(src))
dst = os.path.join(LIB_DIR, 'corpora', new_name)
if os.path.exists(dst):
choice = input("Corpus '{}' already exists; overwrite it? y(es) | n(o): ".format(new_name))
while True:
if cho... | given name exists, return its absolute path; otherwise return None'''
dataset_dir = os.path.join(LIB_DIR, 'datasets')
dataset_path = os.path.join(dataset_dir, dataset_name)
return dataset_path if os.path.isdir(dataset_path) else None
def import_corpus(src, new_name):
| 64 | 64 | 172 | 9 | 54 | sbarham/dsrt | dsrt/application/utils.py | Python | import_corpus | import_corpus | 48 | 68 | 48 | 48 | 96ff3d05bd1302a386d34275e088080365ef626d | bigcode/the-stack | train |
d417e6fd65daec5335259175 | train | function | def list_corpus():
corpus_dir = os.path.join(LIB_DIR, 'corpora')
corpora = [f for f in os.listdir(corpus_dir) if os.path.isfile(os.path.join(corpus_dir, f))]
if not corpora:
print("No available corpora; try importing one with 'dsrt corpus add'")
return
print("Available corpora:")
f... | def list_corpus():
| corpus_dir = os.path.join(LIB_DIR, 'corpora')
corpora = [f for f in os.listdir(corpus_dir) if os.path.isfile(os.path.join(corpus_dir, f))]
if not corpora:
print("No available corpora; try importing one with 'dsrt corpus add'")
return
print("Available corpora:")
for f in corpora:
... | '''
This script contains miscellaneous utilities needed by the command-line
application.
'''
from dsrt.definitions import LIB_DIR
import os
from shutil import copyfile
from os.path import isfile, join
########################
# Corpus Utilities #
########################
def list_corpus():
| 59 | 64 | 99 | 5 | 53 | sbarham/dsrt | dsrt/application/utils.py | Python | list_corpus | list_corpus | 16 | 26 | 16 | 16 | 891229ee3bd984adaf827a481d4968059faaa5ea | bigcode/the-stack | train |
608d835fd88c20d29806c7aa | train | function | def list_dataset():
dataset_dir = os.path.join(LIB_DIR, 'datasets')
datasets = [d for d in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, d))]
if not datasets:
print("No available datasets; try creating one by processing a corpus with 'dsrt dataset prepare'")
return
... | def list_dataset():
| dataset_dir = os.path.join(LIB_DIR, 'datasets')
datasets = [d for d in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, d))]
if not datasets:
print("No available datasets; try creating one by processing a corpus with 'dsrt dataset prepare'")
return
print("Available da... | (os.path.join(corpus_dir, f))]
if not corpora:
print("No available corpora; try importing one with 'dsrt corpus add'")
return
print("Available corpora:")
for f in corpora:
print("\t* " + f)
def list_dataset():
| 64 | 64 | 94 | 4 | 60 | sbarham/dsrt | dsrt/application/utils.py | Python | list_dataset | list_dataset | 28 | 38 | 28 | 28 | da86f213be2881644432395ae7a287a689121c71 | bigcode/the-stack | train |
89e92de97ff44c7e0da64cb8 | train | class | class ParallelModel(KM.Model):
"""Subclasses the standard Keras Model and adds multi-GPU support.
It works by creating a copy of the model on each GPU. Then it slices
the inputs and sends a slice to each copy of the model, and then
merges the outputs together and applies the loss on the combined
out... | class ParallelModel(KM.Model):
| """Subclasses the standard Keras Model and adds multi-GPU support.
It works by creating a copy of the model on each GPU. Then it slices
the inputs and sends a slice to each copy of the model, and then
merges the outputs together and applies the loss on the combined
outputs.
"""
def __init__... | """
Mask R-CNN
Multi-GPU Support for Keras.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
Ideas and a small code snippets from these sources:
https://github.com/fchollet/keras/issues/2436
https://medium.com/@kuza55/transparent-multi-gpu-training... | 186 | 234 | 781 | 7 | 179 | davidamom/Mask_RCNN | mrcnn/parallel_model.py | Python | ParallelModel | ParallelModel | 24 | 106 | 24 | 24 | bba0b72c8aaee7748d5457355e9db9dc9b391303 | bigcode/the-stack | train |
40356ae718a53d52d7c71f2f | train | class | class ModelSignature(BaseModel):
input: Optional[Any]
output: Optional[Any] | class ModelSignature(BaseModel):
| input: Optional[Any]
output: Optional[Any] | from typing import Any, Optional
from pydantic import BaseModel
class ModelSignature(BaseModel):
| 21 | 64 | 18 | 6 | 14 | fhswf/tagflip-autonlp | packages/auto-nlp-deployment/src/deployments/entities/model_signature.py | Python | ModelSignature | ModelSignature | 6 | 8 | 6 | 6 | dacde6a394da5bcfc052be663c3c6cde60bc7e0e | bigcode/the-stack | train |
a7be9ec1dc4951718a7d3ab9 | train | function | def interpolate_masked_data(data, mask, error=None, background=None):
"""
Interpolate over masked pixels in data and optional error or
background images.
The value of masked pixels are replaced by the mean value of the
8-connected neighboring non-masked pixels. This function is intended
for si... | def interpolate_masked_data(data, mask, error=None, background=None):
| """
Interpolate over masked pixels in data and optional error or
background images.
The value of masked pixels are replaced by the mean value of the
8-connected neighboring non-masked pixels. This function is intended
for single, isolated masked pixels (e.g. hot/warm pixels).
Parameters
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import warnings
from astropy.utils.exceptions import AstropyUserWarning
__all__ = ['interpolate_masked_data', 'mask_to_mirrore... | 88 | 221 | 738 | 15 | 73 | fred3m/photutils | photutils/utils/interpolation.py | Python | interpolate_masked_data | interpolate_masked_data | 12 | 88 | 12 | 12 | bcac05c0a1dbff060f86af42a696068e0a488e27 | bigcode/the-stack | train |
fd53fd499642b232545c4b51 | train | function | def mask_to_mirrored_num(image, mask_image, center_position, bbox=None):
"""
Replace masked pixels with the value of the pixel mirrored across a
given ``center_position``. If the mirror pixel is unavailable (i.e.
itself masked or outside of the image), then the masked pixel value
is set to zero.
... | def mask_to_mirrored_num(image, mask_image, center_position, bbox=None):
| """
Replace masked pixels with the value of the pixel mirrored across a
given ``center_position``. If the mirror pixel is unavailable (i.e.
itself masked or outside of the image), then the masked pixel value
is set to zero.
Parameters
----------
image : `numpy.ndarray`, 2D
The ... | }, {1})" is completely '
'surrounded by (8-connected) masked pixels, '
'thus unable to interpolate'.format(i, j),
AstropyUserWarning)
continue
data_out[j, i] = np.mean(data[y0:y1, x0:x1][goodpix])
if background is... | 248 | 248 | 829 | 18 | 229 | fred3m/photutils | photutils/utils/interpolation.py | Python | mask_to_mirrored_num | mask_to_mirrored_num | 91 | 167 | 91 | 91 | f4cd5061b94d0e7c860a53a1f594c097e4b1469d | bigcode/the-stack | train |
0390f46ef47f4039cf838e2a | train | class | class CfgNode(_CfgNode):
"""
Our own extended version of :class:`yacs.config.CfgNode`.
It contains the following extra features:
1. The :meth:`merge_from_file` method supports the "_BASE_" key,
which allows the new CfgNode to inherit all the attributes from the
base configuration file.
... | class CfgNode(_CfgNode):
| """
Our own extended version of :class:`yacs.config.CfgNode`.
It contains the following extra features:
1. The :meth:`merge_from_file` method supports the "_BASE_" key,
which allows the new CfgNode to inherit all the attributes from the
base configuration file.
2. Keys that start with... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
from typing import IO, Any, Callable, Dict, List, Union
import yaml
from fvcore.common.file_io import PathManager
from yacs.config import CfgNode as _CfgNode
BASE_KEY = "_BASE_"
class CfgNode(_CfgNode):
| 79 | 256 | 1,199 | 8 | 70 | amtagrwl/fvcore | fvcore/common/config.py | Python | CfgNode | CfgNode | 15 | 149 | 15 | 15 | 4ea051b84165283833795ce574f8000f961adae8 | bigcode/the-stack | train |
08b0344918a19a3ff34882bb | train | class | class SpeechRecognizer2(nn.Module):
def __init__(self, rnn_type, input_size, hidden_size, vocab_size, nlayers, dropout_all):
super(SpeechRecognizer2, self).__init__()
self.nlayers = nlayers
# Extract features using CNN.
self.feat_extractor = CnnBlock(input_size, hidden_size)
... | class SpeechRecognizer2(nn.Module):
| def __init__(self, rnn_type, input_size, hidden_size, vocab_size, nlayers, dropout_all):
super(SpeechRecognizer2, self).__init__()
self.nlayers = nlayers
# Extract features using CNN.
self.feat_extractor = CnnBlock(input_size, hidden_size)
# Pass sequence features through RNN... | Gal and Ghahramani / Merity
# https://medium.com/@bingobee01/a-review-of-dropout-as-applied-to-rnns-72e79ecd5b7b
class LockedDropout(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, train, dropout=0.5):
# x: (L, B, C)
if dropout == 0 or not train:
re... | 176 | 176 | 587 | 7 | 169 | anjandeepsahni/speech_phoneme_prediction | unaligned/Code/model.py | Python | SpeechRecognizer2 | SpeechRecognizer2 | 82 | 132 | 82 | 82 | a0c54ded8704922eafb803829508996496b10cbc | bigcode/the-stack | train |
b2ac3edd23f372e3d331052e | train | class | class SpeechRecognizer(nn.Module):
def __init__(self, input_size, hidden_size, vocab_size, nlayers, bidirectional, dropout):
super(SpeechRecognizer, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.vocab_size = vocab_size
self.nlayers = nlayer... | class SpeechRecognizer(nn.Module):
| def __init__(self, input_size, hidden_size, vocab_size, nlayers, bidirectional, dropout):
super(SpeechRecognizer, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.vocab_size = vocab_size
self.nlayers = nlayers
self.bidirectional = bidi... | import torch
import numpy as np
import torch.nn as nn
from phoneme_list import *
import torch.nn.utils.rnn as rnn
from torch.autograd import Variable
#RNN only.
class SpeechRecognizer(nn.Module):
| 48 | 70 | 236 | 6 | 42 | anjandeepsahni/speech_phoneme_prediction | unaligned/Code/model.py | Python | SpeechRecognizer | SpeechRecognizer | 9 | 29 | 9 | 9 | ebc4216e9a46b276c1a5e61691afe62dffa0a090 | bigcode/the-stack | train |
f378086420a6c18d88fd5e82 | train | class | class LockedDropout(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, train, dropout=0.5):
# x: (L, B, C)
if dropout == 0 or not train:
return x
mask = x.data.new(1, x.size(1), x.size(2))
mask = mask.bernoulli_(1 - dropout)
mask... | class LockedDropout(nn.Module):
| def __init__(self):
super().__init__()
def forward(self, x, train, dropout=0.5):
# x: (L, B, C)
if dropout == 0 or not train:
return x
mask = x.data.new(1, x.size(1), x.size(2))
mask = mask.bernoulli_(1 - dropout)
mask = Variable(mask, requires_grad=... | ):
return self.layers(x)
# Locked dropout.
# Borrowed from Gal and Ghahramani / Merity
# https://medium.com/@bingobee01/a-review-of-dropout-as-applied-to-rnns-72e79ecd5b7b
class LockedDropout(nn.Module):
| 64 | 64 | 121 | 7 | 56 | anjandeepsahni/speech_phoneme_prediction | unaligned/Code/model.py | Python | LockedDropout | LockedDropout | 67 | 79 | 67 | 67 | 95c0b83046513ebc3fc9f4df8a8e4d46288c2c08 | bigcode/the-stack | train |
623beabc0e74a17ac5873b23 | train | class | class BiRnnBlock(nn.Module):
def __init__(self, input_size, hidden_size, rnn_type='lstm', nlayers=1):
super(BiRnnBlock, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.nlayers = nlayers
self.rnn_type = nn.LSTM if rnn_type == 'lstm' else nn.GR... | class BiRnnBlock(nn.Module):
| def __init__(self, input_size, hidden_size, rnn_type='lstm', nlayers=1):
super(BiRnnBlock, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.nlayers = nlayers
self.rnn_type = nn.LSTM if rnn_type == 'lstm' else nn.GRU
self.rnn = self.rnn... | _padded_sequence(in_pad, lens)
out_pkd, (h, c) = self.rnn(in_pkd, self.hidden)
scores = self.scoring(out_pkd) # Predict the scores.
return scores
# Bidirectional RNN block.
class BiRnnBlock(nn.Module):
| 64 | 64 | 177 | 8 | 56 | anjandeepsahni/speech_phoneme_prediction | unaligned/Code/model.py | Python | BiRnnBlock | BiRnnBlock | 32 | 46 | 32 | 32 | ba523eccc3bcb1dbd418b9f52d5d754874f4c4ee | bigcode/the-stack | train |
8f9eaa747da5dd691dc41b70 | train | class | class CnnBlock(nn.Module):
def __init__(self, input_size, hidden_size):
super(CnnBlock, self).__init__()
# Input Dim: [batch_size, feat_size, max_seq_len]
self.layers = nn.Sequential(
nn.BatchNorm1d(input_size),
nn.Conv1d(in_channels=input_size, out_channels=hidden_si... | class CnnBlock(nn.Module):
| def __init__(self, input_size, hidden_size):
super(CnnBlock, self).__init__()
# Input Dim: [batch_size, feat_size, max_seq_len]
self.layers = nn.Sequential(
nn.BatchNorm1d(input_size),
nn.Conv1d(in_channels=input_size, out_channels=hidden_size,
... | forward(self, seq, seq_len):
out = rnn.pack_padded_sequence(seq, seq_len)
out, h = self.rnn(out)
out, _ = rnn.pad_packed_sequence(out)
return out, h
# CNN to extract features.
class CnnBlock(nn.Module):
| 64 | 64 | 133 | 7 | 57 | anjandeepsahni/speech_phoneme_prediction | unaligned/Code/model.py | Python | CnnBlock | CnnBlock | 49 | 62 | 49 | 49 | 7dcf56ba56476a7e0522eacb06a93fe25aa3e995 | bigcode/the-stack | train |
a363ec1ad0ef8aa6cde12275 | train | class | class ProbconsApplication(unittest.TestCase):
def setUp(self):
self.infile1 = "Fasta/fa01"
self.annotation_outfile = "Fasta/probcons_annot.out"
def tearDown(self):
if os.path.isfile(self.annotation_outfile):
os.remove(self.annotation_outfile)
def test_Probcons_alignmen... | class ProbconsApplication(unittest.TestCase):
| def setUp(self):
self.infile1 = "Fasta/fa01"
self.annotation_outfile = "Fasta/probcons_annot.out"
def tearDown(self):
if os.path.isfile(self.annotation_outfile):
os.remove(self.annotation_outfile)
def test_Probcons_alignment_fasta(self):
"""Round-trip through ap... | ests for Bio.Align.Applications interface for PROBCONS."""
import sys
import os
import unittest
import subprocess
from cStringIO import StringIO
from Bio import AlignIO, SeqIO, MissingExternalDependencyError
from Bio.Align.Applications import ProbconsCommandline
#Try to avoid problems when the OS is in another langua... | 193 | 193 | 644 | 8 | 185 | JackCurragh/DARNED | CodonSubstitution/build/biopython/Tests/test_Probcons_tool.py | Python | ProbconsApplication | ProbconsApplication | 31 | 87 | 31 | 32 | 2d2cfe8cbbb5d401aba100a2d4389d02fc956a77 | bigcode/the-stack | train |
034682d424959cfa1778e4f7 | train | function | @pytest.fixture
def mock_mail():
return MockMail()
| @pytest.fixture
def mock_mail():
| return MockMail()
| po import load_hpo
log = logging.getLogger(__name__)
class MockMail:
_send_was_called = False
_message = None
def send(self, message):
self._send_was_called = True
self._message = message
@pytest.fixture
def mock_mail():
| 64 | 64 | 12 | 7 | 56 | CHRUdeLille/scout | tests/server/blueprints/variants/conftest.py | Python | mock_mail | mock_mail | 24 | 26 | 24 | 25 | b996a832667f280b7cda8d348b59b9f5b87214c1 | bigcode/the-stack | train |
c9c8c89c80d258584623f85d | train | class | class MockMail:
_send_was_called = False
_message = None
def send(self, message):
self._send_was_called = True
self._message = message
| class MockMail:
| _send_was_called = False
_message = None
def send(self, message):
self._send_was_called = True
self._message = message
| 8 -*-
import logging
import pytest
import pymongo
from scout.server.app import create_app
from scout.adapter import MongoAdapter
from scout.load.hgnc_gene import load_hgnc_genes
from scout.load.hpo import load_hpo
log = logging.getLogger(__name__)
class MockMail:
| 64 | 64 | 43 | 4 | 60 | CHRUdeLille/scout | tests/server/blueprints/variants/conftest.py | Python | MockMail | MockMail | 16 | 22 | 16 | 16 | 4b7a0401190cbf2ef1f8d382980baad17ef449f4 | bigcode/the-stack | train |
1fb229476c64a2e6396b6dea | train | function | @pytest.fixture
def mock_sender():
return 'mock_sender'
| @pytest.fixture
def mock_sender():
| return 'mock_sender'
| name__)
class MockMail:
_send_was_called = False
_message = None
def send(self, message):
self._send_was_called = True
self._message = message
@pytest.fixture
def mock_mail():
return MockMail()
@pytest.fixture
def mock_sender():
| 64 | 64 | 13 | 7 | 57 | CHRUdeLille/scout | tests/server/blueprints/variants/conftest.py | Python | mock_sender | mock_sender | 28 | 30 | 28 | 29 | 7e0f9a358d6249b85ee07ebfa2e1c590f7be1c25 | bigcode/the-stack | train |
b43847f790e88033630dcb0f | train | function | def Main():
global guessGesture, visualize, mod, binaryMode, bkgrndSubMode, mask, takebkgrndSubMask, x0, y0, width, height, saveImg, gestname, path
quietMode = False
font = cv2.FONT_HERSHEY_SIMPLEX
size = 0.5
fx = 10
fy = 350
fh = 18
#Call CNN model loading callback
wh... | def Main():
| global guessGesture, visualize, mod, binaryMode, bkgrndSubMode, mask, takebkgrndSubMask, x0, y0, width, height, saveImg, gestname, path
quietMode = False
font = cv2.FONT_HERSHEY_SIMPLEX
size = 0.5
fx = 10
fy = 350
fh = 18
#Call CNN model loading callback
while True:
... | ("Refreshing background image for mask...")
#Take a diff between roi & bkgrnd image contents
diff = cv2.absdiff(roi, bkgrnd)
_, diff = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
mask = cv2.GaussianBlur(diff, (3,3), 5)
mask = cv2.erode(diff, skinkernel, iterations = 1)
mask... | 256 | 256 | 1,553 | 3 | 253 | OmarTaherSaad/gesture-control-system | Data Preparation/shallow_detector.py | Python | Main | Main | 189 | 370 | 189 | 189 | 27a062f102f6bd5adb292c9b86681a65879acba7 | bigcode/the-stack | train |
751aaff1c0aeda737236c814 | train | function | def saveROIImg(img):
global counter, gestname, path, saveImg
if counter > (numOfSamples - 1):
# Reset the parameters
saveImg = False
gestname = ''
counter = 0
return
counter = counter + 1
name = gestname + str(counter)
print("Saving img:",name)
cv2.im... | def saveROIImg(img):
| global counter, gestname, path, saveImg
if counter > (numOfSamples - 1):
# Reset the parameters
saveImg = False
gestname = ''
counter = 0
return
counter = counter + 1
name = gestname + str(counter)
print("Saving img:",name)
cv2.imwrite(path+name + ".j... | - Use pretrained model for gesture recognition & layer visualization
2- Train the model (you will require image samples for training under .\imgfolder)
3- Visualize feature maps of different layers of trained model
4- Exit
'''
#%%
def saveROIImg(img):
| 64 | 64 | 102 | 6 | 58 | OmarTaherSaad/gesture-control-system | Data Preparation/shallow_detector.py | Python | saveROIImg | saveROIImg | 46 | 59 | 46 | 46 | c19efa0f43cf932cc14f80038f802292e7b0d441 | bigcode/the-stack | train |
5ece027b6f8a31c36fa5b427 | train | function | def bkgrndSubMask(frame, x0, y0, width, height, framecount, plot):
global guessGesture, takebkgrndSubMask, visualize, mod, bkgrnd, saveImg
cv2.rectangle(frame, (x0,y0),(x0+width,y0+height),(0,255,0),1)
roi = frame[y0:y0+height, x0:x0+width]
#roi = cv2.UMat(frame[y0:y0+height, x0:x0+width])
... | def bkgrndSubMask(frame, x0, y0, width, height, framecount, plot):
| global guessGesture, takebkgrndSubMask, visualize, mod, bkgrnd, saveImg
cv2.rectangle(frame, (x0,y0),(x0+width,y0+height),(0,255,0),1)
roi = frame[y0:y0+height, x0:x0+width]
#roi = cv2.UMat(frame[y0:y0+height, x0:x0+width])
roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
#Take back... | '''
return res
#%%
# This is the new mask mode. It simply tries to remove the background content by taking a image of the
# background and subtracts it from the new frame contents of the ROI window.
# So in order to use it correctly, keep the contents of ROI window stable and without your hand in it
# and then p... | 126 | 126 | 421 | 23 | 102 | OmarTaherSaad/gesture-control-system | Data Preparation/shallow_detector.py | Python | bkgrndSubMask | bkgrndSubMask | 143 | 184 | 143 | 143 | dbf23feeb3042cd80135ea6baeb45b36fdb83f8b | bigcode/the-stack | train |
1f8850dad9116faf2ddc2fa9 | train | function | def skinMask(frame, x0, y0, width, height, framecount, plot):
global guessGesture, visualize, mod, saveImg
# HSV values
low_range = np.array([0, 50, 80])
upper_range = np.array([30, 200, 255])
cv2.rectangle(frame, (x0,y0),(x0+width,y0+height),(0,255,0),1)
#roi = cv2.UMat(frame[y0:y0+height,... | def skinMask(frame, x0, y0, width, height, framecount, plot):
| global guessGesture, visualize, mod, saveImg
# HSV values
low_range = np.array([0, 50, 80])
upper_range = np.array([30, 200, 255])
cv2.rectangle(frame, (x0,y0),(x0+width,y0+height),(0,255,0),1)
#roi = cv2.UMat(frame[y0:y0+height, x0:x0+width])
roi = frame[y0:y0+height, x0:x0+width]
... | ROIImg(img):
global counter, gestname, path, saveImg
if counter > (numOfSamples - 1):
# Reset the parameters
saveImg = False
gestname = ''
counter = 0
return
counter = counter + 1
name = gestname + str(counter)
print("Saving img:",name)
cv2.imwrite(pa... | 122 | 122 | 409 | 20 | 102 | OmarTaherSaad/gesture-control-system | Data Preparation/shallow_detector.py | Python | skinMask | skinMask | 63 | 102 | 63 | 63 | e4d2b6d16d6e178c99d70e911088eeb50f302b1a | bigcode/the-stack | train |
c0cbc82ad1d4506f5f867c11 | train | function | def binaryMask(frame, x0, y0, width, height, framecount, plot ):
global guessGesture, visualize, mod, saveImg
#cv2.rectangle(frame, (x0,y0),(x0+width,y0+height),(0,255,0),1)
#roi = cv2.UMat(frame[y0:y0+height, x0:x0+width])
roi = frame
'''
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
bl... | def binaryMask(frame, x0, y0, width, height, framecount, plot ):
| global guessGesture, visualize, mod, saveImg
#cv2.rectangle(frame, (x0,y0),(x0+width,y0+height),(0,255,0),1)
#roi = cv2.UMat(frame[y0:y0+height, x0:x0+width])
roi = frame
'''
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),2)
th3 = cv2.adaptiveTh... | )
t = threading.Thread(target=myNN.guessGesture, args = [mod, res])
t.start()
elif visualize == True:
layer = int(input("Enter which layer to visualize "))
cv2.waitKey(0)
#myNN.visualizeLayers(mod, res, layer)
visualize = False
'''
return res
#%%
def binaryM... | 96 | 96 | 321 | 20 | 76 | OmarTaherSaad/gesture-control-system | Data Preparation/shallow_detector.py | Python | binaryMask | binaryMask | 106 | 135 | 106 | 106 | 78053f1d508865735aae43f15b752e2bada8ac56 | bigcode/the-stack | train |
2960cac1a33a13b147922b4e | train | function | def get_industry_systems(
callbacks: Optional[List[models.JobCallback]] = None,
):
if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs={"file_path_template": "data/industry-systems-... | def get_industry_systems(
callbacks: Optional[List[models.JobCallback]] = None,
):
| if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs={"file_path_template": "data/industry-systems-esi-job.json"},
)
)
callbacks.append(
models.Jo... | "},
)
)
job = models.EsiJob(
op_id="get_industry_facilities",
name="get_industry_facilities",
callbacks=callbacks,
)
return job
def get_industry_systems(
callbacks: Optional[List[models.JobCallback]] = None,
):
| 64 | 64 | 150 | 21 | 42 | DonalChilde/eve-esi | src/eve_esi_jobs/examples/jobs.py | Python | get_industry_systems | get_industry_systems | 85 | 107 | 85 | 87 | a23ad222e2be7179cee40a2f8002ccdf7682c464 | bigcode/the-stack | train |
46b2b474ce548f4791e7249a | train | function | def post_universe_names(
callbacks: Optional[List[models.JobCallback]] = None,
):
if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs={
"file_path_template": "da... | def post_universe_names(
callbacks: Optional[List[models.JobCallback]] = None,
):
| if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs={
"file_path_template": "data/post_universe_names-${esi_job_uid}-esi-job.json"
},
)
... | .json"},
)
)
job = models.EsiJob(
op_id="get_industry_systems",
name="get_industry_systems",
callbacks=callbacks,
)
return job
def post_universe_names(
callbacks: Optional[List[models.JobCallback]] = None,
):
| 64 | 64 | 181 | 20 | 43 | DonalChilde/eve-esi | src/eve_esi_jobs/examples/jobs.py | Python | post_universe_names | post_universe_names | 110 | 137 | 110 | 112 | 2b4ca516b9d7cef0ea9d5e1b724e060f3447a2d1 | bigcode/the-stack | train |
cee92af1013a8257224850ca | train | function | def get_industry_facilities(
callbacks: Optional[List[models.JobCallback]] = None,
):
if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs={"file_path_template": "data/industry-facil... | def get_industry_facilities(
callbacks: Optional[List[models.JobCallback]] = None,
):
| if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs={"file_path_template": "data/industry-facilities-esi-job.json"},
)
)
callbacks.append(
models... | _region_id_history",
name="get_markets_region_id_history",
callbacks=callbacks,
)
job.parameters = {"region_id": region_id, "type_id": type_id}
return job
def get_industry_facilities(
callbacks: Optional[List[models.JobCallback]] = None,
):
| 64 | 64 | 152 | 21 | 42 | DonalChilde/eve-esi | src/eve_esi_jobs/examples/jobs.py | Python | get_industry_facilities | get_industry_facilities | 60 | 82 | 60 | 62 | a60bfec21036b4a77a91de4c290de0e3ad8acff0 | bigcode/the-stack | train |
7be34f887b1cbf49aee7c9b6 | train | function | def get_markets_region_id_history(
region_id: int,
type_id: int,
callbacks: Optional[List[models.JobCallback]] = None,
):
if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs... | def get_markets_region_id_history(
region_id: int,
type_id: int,
callbacks: Optional[List[models.JobCallback]] = None,
):
| if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_esi_job_to_json_file",
kwargs={
"file_path_template": "data/market-history-${region_id}-${type_id}-esi-job.json"
},
... | ="get_contracts_public_region_id",
callbacks=callbacks,
)
job.parameters = {"region_id": region_id}
return job
def get_markets_region_id_history(
region_id: int,
type_id: int,
callbacks: Optional[List[models.JobCallback]] = None,
):
| 64 | 64 | 202 | 34 | 29 | DonalChilde/eve-esi | src/eve_esi_jobs/examples/jobs.py | Python | get_markets_region_id_history | get_markets_region_id_history | 28 | 57 | 28 | 32 | 1b15469404a1925781302e986ad8dad6b3afcccd | bigcode/the-stack | train |
cf4d909ae4e13f67497576c5 | train | function | def get_contracts_public_region_id(
region_id: int, callbacks: Optional[List[models.JobCallback]] = None
):
if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_result_to_json_file",
kwargs={
... | def get_contracts_public_region_id(
region_id: int, callbacks: Optional[List[models.JobCallback]] = None
):
| if callbacks is None:
callbacks = []
callbacks.append(
models.JobCallback(
callback_id="save_result_to_json_file",
kwargs={
"file_path_template": "data/contracts-public-${region_id}.json"
},
)
)
j... | from typing import List, Optional
from eve_esi_jobs import models
def get_contracts_public_region_id(
region_id: int, callbacks: Optional[List[models.JobCallback]] = None
):
| 42 | 64 | 132 | 27 | 14 | DonalChilde/eve-esi | src/eve_esi_jobs/examples/jobs.py | Python | get_contracts_public_region_id | get_contracts_public_region_id | 6 | 25 | 6 | 8 | 3255b3a11df956b4cedda7b971de54fa7d38e0bb | bigcode/the-stack | train |
f4033211c2a9fdc9b5873b5a | train | class | class Command(ScrapyCommand):
requires_project = True
def syntax(self):
return "[options] <spider>"
def short_desc(self):
return "Run a spider with validations, or validate all changed spiders in a PR"
def add_options(self, parser):
ScrapyCommand.add_options(self, parser)
... | class Command(ScrapyCommand):
| requires_project = True
def syntax(self):
return "[options] <spider>"
def short_desc(self):
return "Run a spider with validations, or validate all changed spiders in a PR"
def add_options(self, parser):
ScrapyCommand.add_options(self, parser)
parser.add_option(
... | import os
import re
import subprocess
from importlib import import_module
from scrapy.commands import ScrapyCommand
from scrapy.exceptions import UsageError
from ..pipelines import ValidationPipeline
class Command(ScrapyCommand):
| 46 | 194 | 647 | 7 | 38 | jtotoole/city-scrapers-core | city_scrapers_core/commands/validate.py | Python | Command | Command | 12 | 92 | 12 | 12 | b24dd0b98103212fd8ea8fce1a931cd521437e91 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.