body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
d157e6d52a6274273e5bfebc0b8bc09eb0ef023a135c8c01569e128c1a8c6020 | def test_upload_image_to_movie(self):
'Test uploading an image to movie\n '
url = image_upload_url(self.movie.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(ur... | Test uploading an image to movie | backend/movie/tests/test_movie_api.py | test_upload_image_to_movie | BAXTOR95/movie-rental-api | 0 | python | def test_upload_image_to_movie(self):
'\n '
url = image_upload_url(self.movie.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multi... | def test_upload_image_to_movie(self):
'\n '
url = image_upload_url(self.movie.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multi... |
1259e2b23efac85cd6226c9b1f512b4ee0eec981d0218e1143781bcfb616d517 | def test_upload_image_bad_request(self):
'Test uploading an invalid image\n '
url = image_upload_url(self.movie.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test uploading an invalid image | backend/movie/tests/test_movie_api.py | test_upload_image_bad_request | BAXTOR95/movie-rental-api | 0 | python | def test_upload_image_bad_request(self):
'\n '
url = image_upload_url(self.movie.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_upload_image_bad_request(self):
'\n '
url = image_upload_url(self.movie.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test uploading an invalid image<|endoftext|> |
981d3bc99c32e745c89faf36dfb89dbe13c813278a9f798b1a5eccafb156d2c9 | def list_(name, archive_format=None, options=None, clean=False, verbose=False, saltenv='base'):
"\n .. versionadded:: 2016.11.0\n\n List the files and directories in an tar, zip, or rar archive.\n\n .. note::\n This function will only provide results for XZ-compressed archives if\n the xz_ CL... | .. versionadded:: 2016.11.0
List the files and directories in an tar, zip, or rar archive.
.. note::
This function will only provide results for XZ-compressed archives if
the xz_ CLI command is available, as Python does not at this time
natively support XZ compression in its tarfile_ module. Keep in mind
... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | list_ | codebergau/salt-formula-odoo9 | 0 | python | def list_(name, archive_format=None, options=None, clean=False, verbose=False, saltenv='base'):
"\n .. versionadded:: 2016.11.0\n\n List the files and directories in an tar, zip, or rar archive.\n\n .. note::\n This function will only provide results for XZ-compressed archives if\n the xz_ CL... | def list_(name, archive_format=None, options=None, clean=False, verbose=False, saltenv='base'):
"\n .. versionadded:: 2016.11.0\n\n List the files and directories in an tar, zip, or rar archive.\n\n .. note::\n This function will only provide results for XZ-compressed archives if\n the xz_ CL... |
fa263ea534067b1056ad78f2fbb3321b1e7ce4465d68cc4a6b336c8b5dfc27b2 | @salt.utils.decorators.which('tar')
def tar(options, tarfile, sources=None, dest=None, cwd=None, template=None, runas=None):
"\n .. note::\n\n This function has changed for version 0.17.0. In prior versions, the\n ``cwd`` and ``template`` arguments must be specified, with the source\n direct... | .. note::
This function has changed for version 0.17.0. In prior versions, the
``cwd`` and ``template`` arguments must be specified, with the source
directories/files coming as a space-separated list at the end of the
command. Beginning with 0.17.0, ``sources`` must be a comma-separated
list, and t... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | tar | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.which('tar')
def tar(options, tarfile, sources=None, dest=None, cwd=None, template=None, runas=None):
"\n .. note::\n\n This function has changed for version 0.17.0. In prior versions, the\n ``cwd`` and ``template`` arguments must be specified, with the source\n direct... | @salt.utils.decorators.which('tar')
def tar(options, tarfile, sources=None, dest=None, cwd=None, template=None, runas=None):
"\n .. note::\n\n This function has changed for version 0.17.0. In prior versions, the\n ``cwd`` and ``template`` arguments must be specified, with the source\n direct... |
43a449dc1b0d028fe86a1d3e225fccfa4a7724826f255a1dc5a584b1eacaaa80 | @salt.utils.decorators.which('gzip')
def gzip(sourcefile, template=None, runas=None, options=None):
"\n Uses the gzip command to create gzip files\n\n template : None\n Can be set to 'jinja' or another supported template engine to render\n the command arguments before execution:\n\n .. co... | Uses the gzip command to create gzip files
template : None
Can be set to 'jinja' or another supported template engine to render
the command arguments before execution:
.. code-block:: bash
salt '*' archive.gzip template=jinja /tmp/{{grains.id}}.txt
runas : None
The user with which to run the... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | gzip | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.which('gzip')
def gzip(sourcefile, template=None, runas=None, options=None):
"\n Uses the gzip command to create gzip files\n\n template : None\n Can be set to 'jinja' or another supported template engine to render\n the command arguments before execution:\n\n .. co... | @salt.utils.decorators.which('gzip')
def gzip(sourcefile, template=None, runas=None, options=None):
"\n Uses the gzip command to create gzip files\n\n template : None\n Can be set to 'jinja' or another supported template engine to render\n the command arguments before execution:\n\n .. co... |
e2b6ff3a6dad19fd19f5c845690a012ab71bef43e9bd398434304d17d3852d83 | @salt.utils.decorators.which('gunzip')
def gunzip(gzipfile, template=None, runas=None, options=None):
"\n Uses the gunzip command to unpack gzip files\n\n template : None\n Can be set to 'jinja' or another supported template engine to render\n the command arguments before execution:\n\n .... | Uses the gunzip command to unpack gzip files
template : None
Can be set to 'jinja' or another supported template engine to render
the command arguments before execution:
.. code-block:: bash
salt '*' archive.gunzip template=jinja /tmp/{{grains.id}}.txt.gz
runas : None
The user with which to ... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | gunzip | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.which('gunzip')
def gunzip(gzipfile, template=None, runas=None, options=None):
"\n Uses the gunzip command to unpack gzip files\n\n template : None\n Can be set to 'jinja' or another supported template engine to render\n the command arguments before execution:\n\n .... | @salt.utils.decorators.which('gunzip')
def gunzip(gzipfile, template=None, runas=None, options=None):
"\n Uses the gunzip command to unpack gzip files\n\n template : None\n Can be set to 'jinja' or another supported template engine to render\n the command arguments before execution:\n\n .... |
2523841d992e3333c450ea2edf7fe66b2bc081c8676289e1c493e9ea0fc6f29d | @salt.utils.decorators.which('zip')
def cmd_zip(zip_file, sources, template=None, cwd=None, runas=None):
"\n .. versionadded:: 2015.5.0\n In versions 2014.7.x and earlier, this function was known as\n ``archive.zip``.\n\n Uses the ``zip`` command to create zip files. This command is part of the\... | .. versionadded:: 2015.5.0
In versions 2014.7.x and earlier, this function was known as
``archive.zip``.
Uses the ``zip`` command to create zip files. This command is part of the
`Info-ZIP`_ suite of tools, and is typically packaged as simply ``zip``.
.. _`Info-ZIP`: http://www.info-zip.org/
zip_file
Pat... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | cmd_zip | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.which('zip')
def cmd_zip(zip_file, sources, template=None, cwd=None, runas=None):
"\n .. versionadded:: 2015.5.0\n In versions 2014.7.x and earlier, this function was known as\n ``archive.zip``.\n\n Uses the ``zip`` command to create zip files. This command is part of the\... | @salt.utils.decorators.which('zip')
def cmd_zip(zip_file, sources, template=None, cwd=None, runas=None):
"\n .. versionadded:: 2015.5.0\n In versions 2014.7.x and earlier, this function was known as\n ``archive.zip``.\n\n Uses the ``zip`` command to create zip files. This command is part of the\... |
0d6ea34bc00538966baf5534d7658ae82de3b28f5e2c95f4e64a109de9a7887d | @salt.utils.decorators.depends('zipfile', fallback_function=cmd_zip)
def zip_(zip_file, sources, template=None, cwd=None, runas=None):
"\n Uses the ``zipfile`` Python module to create zip files\n\n .. versionchanged:: 2015.5.0\n This function was rewritten to use Python's native zip file support.\n ... | Uses the ``zipfile`` Python module to create zip files
.. versionchanged:: 2015.5.0
This function was rewritten to use Python's native zip file support.
The old functionality has been preserved in the new function
:mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>`. For versions
2014.7.x and earlier,... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | zip_ | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.depends('zipfile', fallback_function=cmd_zip)
def zip_(zip_file, sources, template=None, cwd=None, runas=None):
"\n Uses the ``zipfile`` Python module to create zip files\n\n .. versionchanged:: 2015.5.0\n This function was rewritten to use Python's native zip file support.\n ... | @salt.utils.decorators.depends('zipfile', fallback_function=cmd_zip)
def zip_(zip_file, sources, template=None, cwd=None, runas=None):
"\n Uses the ``zipfile`` Python module to create zip files\n\n .. versionchanged:: 2015.5.0\n This function was rewritten to use Python's native zip file support.\n ... |
849e0dd84fac4ebeb240e12f80cf0088b5537e699c5de29761764efeed409267 | @salt.utils.decorators.which('unzip')
def cmd_unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None):
"\n .. versionadded:: 2015.5.0\n In versions 2014.7.x and earlier, this function was known as\n ``archive.unzip``.\n\n Uses the ``unzip``... | .. versionadded:: 2015.5.0
In versions 2014.7.x and earlier, this function was known as
``archive.unzip``.
Uses the ``unzip`` command to unpack zip files. This command is part of the
`Info-ZIP`_ suite of tools, and is typically packaged as simply ``unzip``.
.. _`Info-ZIP`: http://www.info-zip.org/
zip_file
... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | cmd_unzip | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.which('unzip')
def cmd_unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None):
"\n .. versionadded:: 2015.5.0\n In versions 2014.7.x and earlier, this function was known as\n ``archive.unzip``.\n\n Uses the ``unzip``... | @salt.utils.decorators.which('unzip')
def cmd_unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None):
"\n .. versionadded:: 2015.5.0\n In versions 2014.7.x and earlier, this function was known as\n ``archive.unzip``.\n\n Uses the ``unzip``... |
55bec6d58eb3769748de6bd29da8e8cb589e3e36c5b8f482489f3836d8f1c4e5 | def unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None, extract_perms=True):
"\n Uses the ``zipfile`` Python module to unpack zip files\n\n .. versionchanged:: 2015.5.0\n This function was rewritten to use Python's native zip file support.\n ... | Uses the ``zipfile`` Python module to unpack zip files
.. versionchanged:: 2015.5.0
This function was rewritten to use Python's native zip file support.
The old functionality has been preserved in the new function
:mod:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`. For versions
2014.7.x and earl... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | unzip | codebergau/salt-formula-odoo9 | 0 | python | def unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None, extract_perms=True):
"\n Uses the ``zipfile`` Python module to unpack zip files\n\n .. versionchanged:: 2015.5.0\n This function was rewritten to use Python's native zip file support.\n ... | def unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None, extract_perms=True):
"\n Uses the ``zipfile`` Python module to unpack zip files\n\n .. versionchanged:: 2015.5.0\n This function was rewritten to use Python's native zip file support.\n ... |
13fca9d0ee784efbe06a50f98102fa87afcc59875230f0328f966239cf845962 | def is_encrypted(name, clean=False, saltenv='base'):
"\n .. versionadded:: 2016.11.0\n\n Returns ``True`` if the zip archive is password-protected, ``False`` if\n not. If the specified file is not a ZIP archive, an error will be raised.\n\n clean : False\n Set this value to ``True`` to delete the... | .. versionadded:: 2016.11.0
Returns ``True`` if the zip archive is password-protected, ``False`` if
not. If the specified file is not a ZIP archive, an error will be raised.
clean : False
Set this value to ``True`` to delete the path referred to by ``name``
once the contents have been listed. This option shou... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | is_encrypted | codebergau/salt-formula-odoo9 | 0 | python | def is_encrypted(name, clean=False, saltenv='base'):
"\n .. versionadded:: 2016.11.0\n\n Returns ``True`` if the zip archive is password-protected, ``False`` if\n not. If the specified file is not a ZIP archive, an error will be raised.\n\n clean : False\n Set this value to ``True`` to delete the... | def is_encrypted(name, clean=False, saltenv='base'):
"\n .. versionadded:: 2016.11.0\n\n Returns ``True`` if the zip archive is password-protected, ``False`` if\n not. If the specified file is not a ZIP archive, an error will be raised.\n\n clean : False\n Set this value to ``True`` to delete the... |
82454be1c9c6910b1ed9fba8b3e2604d0ce48d4d7dddcb285cf2b6fcda352883 | @salt.utils.decorators.which('rar')
def rar(rarfile, sources, template=None, cwd=None, runas=None):
"\n Uses `rar for Linux`_ to create rar files\n\n .. _`rar for Linux`: http://www.rarlab.com/\n\n rarfile\n Path of rar file to be created\n\n sources\n Comma-separated list of sources to in... | Uses `rar for Linux`_ to create rar files
.. _`rar for Linux`: http://www.rarlab.com/
rarfile
Path of rar file to be created
sources
Comma-separated list of sources to include in the rar file. Sources can
also be passed in a Python list.
cwd : None
Run the rar command from the specified directory. U... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | rar | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.which('rar')
def rar(rarfile, sources, template=None, cwd=None, runas=None):
"\n Uses `rar for Linux`_ to create rar files\n\n .. _`rar for Linux`: http://www.rarlab.com/\n\n rarfile\n Path of rar file to be created\n\n sources\n Comma-separated list of sources to in... | @salt.utils.decorators.which('rar')
def rar(rarfile, sources, template=None, cwd=None, runas=None):
"\n Uses `rar for Linux`_ to create rar files\n\n .. _`rar for Linux`: http://www.rarlab.com/\n\n rarfile\n Path of rar file to be created\n\n sources\n Comma-separated list of sources to in... |
8a84a8bd00a31b17b5c0f6c217aa85d1fa870c60f0ccd0c54bec8ed136bba698 | @salt.utils.decorators.which_bin(('unrar', 'rar'))
def unrar(rarfile, dest, excludes=None, template=None, runas=None, trim_output=False):
"\n Uses `rar for Linux`_ to unpack rar files\n\n .. _`rar for Linux`: http://www.rarlab.com/\n\n rarfile\n Name of rar file to be unpacked\n\n dest\n T... | Uses `rar for Linux`_ to unpack rar files
.. _`rar for Linux`: http://www.rarlab.com/
rarfile
Name of rar file to be unpacked
dest
The destination directory into which to **unpack** the rar file
template : None
Can be set to 'jinja' or another supported template engine to render
the command argument... | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | unrar | codebergau/salt-formula-odoo9 | 0 | python | @salt.utils.decorators.which_bin(('unrar', 'rar'))
def unrar(rarfile, dest, excludes=None, template=None, runas=None, trim_output=False):
"\n Uses `rar for Linux`_ to unpack rar files\n\n .. _`rar for Linux`: http://www.rarlab.com/\n\n rarfile\n Name of rar file to be unpacked\n\n dest\n T... | @salt.utils.decorators.which_bin(('unrar', 'rar'))
def unrar(rarfile, dest, excludes=None, template=None, runas=None, trim_output=False):
"\n Uses `rar for Linux`_ to unpack rar files\n\n .. _`rar for Linux`: http://www.rarlab.com/\n\n rarfile\n Name of rar file to be unpacked\n\n dest\n T... |
7f1532b62186e7a0279be469e7f85b3c93f70d471b2ddc212eb9b9ab548ce320 | def _render_filenames(filenames, zip_file, saltenv, template):
'\n Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the\n files under the paths they ultimately point to) according to the markup\n format provided by :param:`template`.\n '
if (not template):
return ... | Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the
files under the paths they ultimately point to) according to the markup
format provided by :param:`template`. | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | _render_filenames | codebergau/salt-formula-odoo9 | 0 | python | def _render_filenames(filenames, zip_file, saltenv, template):
'\n Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the\n files under the paths they ultimately point to) according to the markup\n format provided by :param:`template`.\n '
if (not template):
return ... | def _render_filenames(filenames, zip_file, saltenv, template):
'\n Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the\n files under the paths they ultimately point to) according to the markup\n format provided by :param:`template`.\n '
if (not template):
return ... |
880c9f4cf6596a16b5cf9d0b6213675ab759377d01d9cd3f784accb18ea59d9d | def _render(contents):
'\n Render :param:`contents` into a literal pathname by writing it to a\n temp file, rendering that file, and returning the result.\n '
tmp_path_fn = salt.utils.mkstemp()
with salt.utils.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(contents)
data = salt.... | Render :param:`contents` into a literal pathname by writing it to a
temp file, rendering that file, and returning the result. | tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/archive.py | _render | codebergau/salt-formula-odoo9 | 0 | python | def _render(contents):
'\n Render :param:`contents` into a literal pathname by writing it to a\n temp file, rendering that file, and returning the result.\n '
tmp_path_fn = salt.utils.mkstemp()
with salt.utils.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(contents)
data = salt.... | def _render(contents):
'\n Render :param:`contents` into a literal pathname by writing it to a\n temp file, rendering that file, and returning the result.\n '
tmp_path_fn = salt.utils.mkstemp()
with salt.utils.fopen(tmp_path_fn, 'w+') as fp_:
fp_.write(contents)
data = salt.... |
1fc2c71a04ef8a921057edc5870e6602f6a14e75e96284af166035d08010785b | def add_context_to_points(self, point_feats, l_1=None, l_2=None):
'Add self-attention context across every selected and deformed point'
global context_points
if ((l_1 is None) and (l_2 is None)):
context_points = self.self_attn1(point_feats)
context_points = self.self_attn2(context_points)
... | Add self-attention context across every selected and deformed point | src/models/backbones_3d/cfe/point_dsa.py | add_context_to_points | reinforcementdriving/SA-Det3D | 134 | python | def add_context_to_points(self, point_feats, l_1=None, l_2=None):
global context_points
if ((l_1 is None) and (l_2 is None)):
context_points = self.self_attn1(point_feats)
context_points = self.self_attn2(context_points)
if ((l_1 is not None) and (l_2 is None)):
context_points =... | def add_context_to_points(self, point_feats, l_1=None, l_2=None):
global context_points
if ((l_1 is None) and (l_2 is None)):
context_points = self.self_attn1(point_feats)
context_points = self.self_attn2(context_points)
if ((l_1 is not None) and (l_2 is None)):
context_points =... |
889a956f3a2db4668b0b2c8b9d215a7aeca7434ba6ba3c6f366bf6680cb5f3a0 | def forward(self, batch_size, l_features, l_xyz, l_conv1=None, l_conv2=None):
'\n Args:\n :param l_conv2:\n :param l_conv1:\n :param batch_size:\n :param l_xyz:\n :param l_features:\n '
l_features_red = self.reduce_dim(l_features)
point_co... | Args:
:param l_conv2:
:param l_conv1:
:param batch_size:
:param l_xyz:
:param l_features: | src/models/backbones_3d/cfe/point_dsa.py | forward | reinforcementdriving/SA-Det3D | 134 | python | def forward(self, batch_size, l_features, l_xyz, l_conv1=None, l_conv2=None):
'\n Args:\n :param l_conv2:\n :param l_conv1:\n :param batch_size:\n :param l_xyz:\n :param l_features:\n '
l_features_red = self.reduce_dim(l_features)
point_co... | def forward(self, batch_size, l_features, l_xyz, l_conv1=None, l_conv2=None):
'\n Args:\n :param l_conv2:\n :param l_conv1:\n :param batch_size:\n :param l_xyz:\n :param l_features:\n '
l_features_red = self.reduce_dim(l_features)
point_co... |
347ea1831ce43de4aaff75c27684e9c7a075ee57aae45ec3e67dca19ce52b5a3 | def __init__(self, app):
' Implements the Flask extension pattern.\n\n .. versionchanged:: 0.2\n Explicit initialize self.driver to None.\n '
self.driver = None
if (app is not None):
self.app = app
self.init_app(self.app)
else:
self.app = None | Implements the Flask extension pattern.
.. versionchanged:: 0.2
Explicit initialize self.driver to None. | eve/io/base.py | __init__ | touilleMan/eve | 2 | python | def __init__(self, app):
' Implements the Flask extension pattern.\n\n .. versionchanged:: 0.2\n Explicit initialize self.driver to None.\n '
self.driver = None
if (app is not None):
self.app = app
self.init_app(self.app)
else:
self.app = None | def __init__(self, app):
' Implements the Flask extension pattern.\n\n .. versionchanged:: 0.2\n Explicit initialize self.driver to None.\n '
self.driver = None
if (app is not None):
self.app = app
self.init_app(self.app)
else:
self.app = None<|docstring|>... |
6f9e9510d2e037016adce3b0d1e48e9e98239acdf7232a5bb7efbce3e2e8256b | def init_app(self, app):
' This is where you want to initialize the db driver so it will be\n alive through the whole instance lifespan.\n '
raise NotImplementedError | This is where you want to initialize the db driver so it will be
alive through the whole instance lifespan. | eve/io/base.py | init_app | touilleMan/eve | 2 | python | def init_app(self, app):
' This is where you want to initialize the db driver so it will be\n alive through the whole instance lifespan.\n '
raise NotImplementedError | def init_app(self, app):
' This is where you want to initialize the db driver so it will be\n alive through the whole instance lifespan.\n '
raise NotImplementedError<|docstring|>This is where you want to initialize the db driver so it will be
alive through the whole instance lifespan.<|endoftext|... |
04ea16a2e3c00a2663ef4375e6e68f825df165d9712730e8bbf9aaf7a9777163 | def find(self, resource, req, sub_resource_lookup):
' Retrieves a set of documents (rows), matching the current request.\n Consumed when a request hits a collection/document endpoint\n (`/people/`).\n\n :param resource: resource being accessed. You should then use\n the ... | Retrieves a set of documents (rows), matching the current request.
Consumed when a request hits a collection/document endpoint
(`/people/`).
:param resource: resource being accessed. You should then use
the ``_datasource`` helper function to retrieve both
the db collection/table and b... | eve/io/base.py | find | touilleMan/eve | 2 | python | def find(self, resource, req, sub_resource_lookup):
' Retrieves a set of documents (rows), matching the current request.\n Consumed when a request hits a collection/document endpoint\n (`/people/`).\n\n :param resource: resource being accessed. You should then use\n the ... | def find(self, resource, req, sub_resource_lookup):
' Retrieves a set of documents (rows), matching the current request.\n Consumed when a request hits a collection/document endpoint\n (`/people/`).\n\n :param resource: resource being accessed. You should then use\n the ... |
ad1fa019a343610184c85be59928c127b32ac63fae0be60837c59c131bc9ae0f | def find_one(self, resource, req, **lookup):
" Retrieves a single document/record. Consumed when a request hits an\n item endpoint (`/people/id/`).\n\n :param resource: resource being accessed. You should then use the\n ``_datasource`` helper function to retrieve both the\n ... | Retrieves a single document/record. Consumed when a request hits an
item endpoint (`/people/id/`).
:param resource: resource being accessed. You should then use the
``_datasource`` helper function to retrieve both the
db collection/table and base query (filter), if any.
:param req: an... | eve/io/base.py | find_one | touilleMan/eve | 2 | python | def find_one(self, resource, req, **lookup):
" Retrieves a single document/record. Consumed when a request hits an\n item endpoint (`/people/id/`).\n\n :param resource: resource being accessed. You should then use the\n ``_datasource`` helper function to retrieve both the\n ... | def find_one(self, resource, req, **lookup):
" Retrieves a single document/record. Consumed when a request hits an\n item endpoint (`/people/id/`).\n\n :param resource: resource being accessed. You should then use the\n ``_datasource`` helper function to retrieve both the\n ... |
2f90ecffa592ec585229ab59cece8c204efa61bf2a6646c888482a9ad95f366f | def find_one_raw(self, resource, _id):
' Retrieves a single, raw document. No projections or datasource\n filters are being applied here. Just looking up the document by unique\n id.\n\n :param resource: resource name.\n :param id: unique id.\n\n .. versionadded:: 0.4\n '
... | Retrieves a single, raw document. No projections or datasource
filters are being applied here. Just looking up the document by unique
id.
:param resource: resource name.
:param id: unique id.
.. versionadded:: 0.4 | eve/io/base.py | find_one_raw | touilleMan/eve | 2 | python | def find_one_raw(self, resource, _id):
' Retrieves a single, raw document. No projections or datasource\n filters are being applied here. Just looking up the document by unique\n id.\n\n :param resource: resource name.\n :param id: unique id.\n\n .. versionadded:: 0.4\n '
... | def find_one_raw(self, resource, _id):
' Retrieves a single, raw document. No projections or datasource\n filters are being applied here. Just looking up the document by unique\n id.\n\n :param resource: resource name.\n :param id: unique id.\n\n .. versionadded:: 0.4\n '
... |
ee14d1a8b60121256d5f5e9db6a48ec9368dd2e7933fc46e8cfc7c9dda61aa8f | def find_list_of_ids(self, resource, ids, client_projection=None):
' Retrieves a list of documents based on a list of primary keys\n The primary key is the field defined in `ID_FIELD`.\n This is a separate function to allow us to use per-database\n optimizations for this type of query.\n\n ... | Retrieves a list of documents based on a list of primary keys
The primary key is the field defined in `ID_FIELD`.
This is a separate function to allow us to use per-database
optimizations for this type of query.
:param resource: resource name.
:param ids: a list of ids corresponding to the documents
to retrieve
:param... | eve/io/base.py | find_list_of_ids | touilleMan/eve | 2 | python | def find_list_of_ids(self, resource, ids, client_projection=None):
' Retrieves a list of documents based on a list of primary keys\n The primary key is the field defined in `ID_FIELD`.\n This is a separate function to allow us to use per-database\n optimizations for this type of query.\n\n ... | def find_list_of_ids(self, resource, ids, client_projection=None):
' Retrieves a list of documents based on a list of primary keys\n The primary key is the field defined in `ID_FIELD`.\n This is a separate function to allow us to use per-database\n optimizations for this type of query.\n\n ... |
84060195c2e010d10dd1755c412d20c27fb46f39b71d20dbe09c2c8fb94ee206 | def insert(self, resource, doc_or_docs):
" Inserts a document into a resource collection/table.\n\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve both\n the actual datasource name.\n :para... | Inserts a document into a resource collection/table.
:param resource: resource being accessed. You should then use
the ``_datasource`` helper function to retrieve both
the actual datasource name.
:param doc_or_docs: json document or list of json documents to be added
... | eve/io/base.py | insert | touilleMan/eve | 2 | python | def insert(self, resource, doc_or_docs):
" Inserts a document into a resource collection/table.\n\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve both\n the actual datasource name.\n :para... | def insert(self, resource, doc_or_docs):
" Inserts a document into a resource collection/table.\n\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve both\n the actual datasource name.\n :para... |
ae6a3b27ef08c277ed41cd0c7e35b21a130520ea73d885a7cffe8b34031bd44e | def update(self, resource, id_, updates):
' Updates a collection/table document/row.\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n the actual datasource name.\n :param id_: the unique ... | Updates a collection/table document/row.
:param resource: resource being accessed. You should then use
the ``_datasource`` helper function to retrieve
the actual datasource name.
:param id_: the unique id of the document.
:param updates: json updates to be performed on the database doc... | eve/io/base.py | update | touilleMan/eve | 2 | python | def update(self, resource, id_, updates):
' Updates a collection/table document/row.\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n the actual datasource name.\n :param id_: the unique ... | def update(self, resource, id_, updates):
' Updates a collection/table document/row.\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n the actual datasource name.\n :param id_: the unique ... |
1b5a006c403cdd3f379782c447822bf56e0c60121a0c59d27f256d3c3588f83d | def replace(self, resource, id_, document):
' Replaces a collection/table document/row.\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n the actual datasource name.\n :param id_: the uniq... | Replaces a collection/table document/row.
:param resource: resource being accessed. You should then use
the ``_datasource`` helper function to retrieve
the actual datasource name.
:param id_: the unique id of the document.
:param document: the new json document
.. versionadded:: 0.1.0 | eve/io/base.py | replace | touilleMan/eve | 2 | python | def replace(self, resource, id_, document):
' Replaces a collection/table document/row.\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n the actual datasource name.\n :param id_: the uniq... | def replace(self, resource, id_, document):
' Replaces a collection/table document/row.\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n the actual datasource name.\n :param id_: the uniq... |
f4c5c924ff45311d6845717391bfa5abdf1ea5a78881d66f8dcb498b75cffb68 | def remove(self, resource, lookup={}):
" Removes a document/row or an entire set of documents/rows from a\n database collection/table.\n\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n t... | Removes a document/row or an entire set of documents/rows from a
database collection/table.
:param resource: resource being accessed. You should then use
the ``_datasource`` helper function to retrieve
the actual datasource name.
:param lookup: a dict with the query that documents mus... | eve/io/base.py | remove | touilleMan/eve | 2 | python | def remove(self, resource, lookup={}):
" Removes a document/row or an entire set of documents/rows from a\n database collection/table.\n\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n t... | def remove(self, resource, lookup={}):
" Removes a document/row or an entire set of documents/rows from a\n database collection/table.\n\n :param resource: resource being accessed. You should then use\n the ``_datasource`` helper function to retrieve\n t... |
83ba1d81b31519c4e05085c28f91ed71575662945724db18b07f32336cf2b7a5 | def combine_queries(self, query_a, query_b):
' Takes two db queries and applies db-specific syntax to produce\n the intersection.\n\n .. versionadded: 0.1.0\n Support for intelligent combination of db queries\n '
raise NotImplementedError | Takes two db queries and applies db-specific syntax to produce
the intersection.
.. versionadded: 0.1.0
Support for intelligent combination of db queries | eve/io/base.py | combine_queries | touilleMan/eve | 2 | python | def combine_queries(self, query_a, query_b):
' Takes two db queries and applies db-specific syntax to produce\n the intersection.\n\n .. versionadded: 0.1.0\n Support for intelligent combination of db queries\n '
raise NotImplementedError | def combine_queries(self, query_a, query_b):
' Takes two db queries and applies db-specific syntax to produce\n the intersection.\n\n .. versionadded: 0.1.0\n Support for intelligent combination of db queries\n '
raise NotImplementedError<|docstring|>Takes two db queries and appli... |
2e2351077c6078f3806376cd2d67b6408999903847de1b8c8720e0cb7a4d906b | def get_value_from_query(self, query, field_name):
' Parses the given potentially-complex query and returns the value\n being assigned to the field given in `field_name`.\n\n This mainly exists to deal with more complicated compound queries\n\n .. versionadded: 0.1.0\n Support for par... | Parses the given potentially-complex query and returns the value
being assigned to the field given in `field_name`.
This mainly exists to deal with more complicated compound queries
.. versionadded: 0.1.0
Support for parsing values embedded in compound db queries | eve/io/base.py | get_value_from_query | touilleMan/eve | 2 | python | def get_value_from_query(self, query, field_name):
' Parses the given potentially-complex query and returns the value\n being assigned to the field given in `field_name`.\n\n This mainly exists to deal with more complicated compound queries\n\n .. versionadded: 0.1.0\n Support for par... | def get_value_from_query(self, query, field_name):
' Parses the given potentially-complex query and returns the value\n being assigned to the field given in `field_name`.\n\n This mainly exists to deal with more complicated compound queries\n\n .. versionadded: 0.1.0\n Support for par... |
5f9e7e706bb9e8a01c7c32b34c7dda669009343d3b8aa89e41059800630f6d56 | def query_contains_field(self, query, field_name):
' For the specified field name, does the query contain it?\n Used know whether we need to parse a compound query.\n\n .. versionadded: 0.1.0\n Support for parsing values embedded in compound db queries\n '
raise NotImplementedErro... | For the specified field name, does the query contain it?
Used know whether we need to parse a compound query.
.. versionadded: 0.1.0
Support for parsing values embedded in compound db queries | eve/io/base.py | query_contains_field | touilleMan/eve | 2 | python | def query_contains_field(self, query, field_name):
' For the specified field name, does the query contain it?\n Used know whether we need to parse a compound query.\n\n .. versionadded: 0.1.0\n Support for parsing values embedded in compound db queries\n '
raise NotImplementedErro... | def query_contains_field(self, query, field_name):
' For the specified field name, does the query contain it?\n Used know whether we need to parse a compound query.\n\n .. versionadded: 0.1.0\n Support for parsing values embedded in compound db queries\n '
raise NotImplementedErro... |
e5707d1686b5d8229ac1aa867af6b7a7e5d20087c34af56530d49ebeaf41d3dc | def is_empty(self, resource):
" Returns True if the collection is empty; False otherwise. While\n a user could rely on self.find() method to achieve the same result,\n this method can probably take advantage of specific datastore features\n to provide better perfomance.\n\n Don't forget,... | Returns True if the collection is empty; False otherwise. While
a user could rely on self.find() method to achieve the same result,
this method can probably take advantage of specific datastore features
to provide better perfomance.
Don't forget, a 'resource' could have a pre-defined filter. If that is
the case, it wi... | eve/io/base.py | is_empty | touilleMan/eve | 2 | python | def is_empty(self, resource):
" Returns True if the collection is empty; False otherwise. While\n a user could rely on self.find() method to achieve the same result,\n this method can probably take advantage of specific datastore features\n to provide better perfomance.\n\n Don't forget,... | def is_empty(self, resource):
" Returns True if the collection is empty; False otherwise. While\n a user could rely on self.find() method to achieve the same result,\n this method can probably take advantage of specific datastore features\n to provide better perfomance.\n\n Don't forget,... |
1f5ea73797054b1ee42061f27f054e209ee4a23b01d7e53345ee56f84ccb9f7b | def _datasource(self, resource):
" Returns a tuple with the actual name of the database\n collection/table, base query and projection for the resource being\n accessed.\n\n :param resource: resource being accessed.\n\n .. versionchanged:: 0.5\n If allow_unknown is enabled for t... | Returns a tuple with the actual name of the database
collection/table, base query and projection for the resource being
accessed.
:param resource: resource being accessed.
.. versionchanged:: 0.5
If allow_unknown is enabled for the resource, don't return any
projection for the document. Addresses #397 and #250.... | eve/io/base.py | _datasource | touilleMan/eve | 2 | python | def _datasource(self, resource):
" Returns a tuple with the actual name of the database\n collection/table, base query and projection for the resource being\n accessed.\n\n :param resource: resource being accessed.\n\n .. versionchanged:: 0.5\n If allow_unknown is enabled for t... | def _datasource(self, resource):
" Returns a tuple with the actual name of the database\n collection/table, base query and projection for the resource being\n accessed.\n\n :param resource: resource being accessed.\n\n .. versionchanged:: 0.5\n If allow_unknown is enabled for t... |
34f3614903b71747422449b74590c6cf84ddc9dd4b261c1fc474ff3b7b50198f | def _datasource_ex(self, resource, query=None, client_projection=None, client_sort=None):
' Returns both db collection and exact query (base filter included)\n to which an API resource refers to.\n\n .. versionchanged:: 0.5.2\n Make User Restricted Resource Access work with HMAC Auth too.\n\... | Returns both db collection and exact query (base filter included)
to which an API resource refers to.
.. versionchanged:: 0.5.2
Make User Restricted Resource Access work with HMAC Auth too.
.. versionchanged:: 0.5
Let client projection work when 'allow_unknown' is active (#497).
.. versionchanged:: 0.4
Alwa... | eve/io/base.py | _datasource_ex | touilleMan/eve | 2 | python | def _datasource_ex(self, resource, query=None, client_projection=None, client_sort=None):
' Returns both db collection and exact query (base filter included)\n to which an API resource refers to.\n\n .. versionchanged:: 0.5.2\n Make User Restricted Resource Access work with HMAC Auth too.\n\... | def _datasource_ex(self, resource, query=None, client_projection=None, client_sort=None):
' Returns both db collection and exact query (base filter included)\n to which an API resource refers to.\n\n .. versionchanged:: 0.5.2\n Make User Restricted Resource Access work with HMAC Auth too.\n\... |
f27166d21c09a3505419f5a9c3b6ef80dcdc0abfbba53bfbb33983697a347140 | def get_data(input_file):
'\n reading the DIAL data, removing dups\n :param input_file: path to the DIAL data\n :return: a cleaned dataframe\n '
df = pd.read_csv(input_file, sep='\t', names=['tid', 'tts', 'uid', 'tll', 'tcb', 'text', 'aa', 'i2', 'i3', 'wh'], usecols=['uid', 'text', 'aa', 'i2', 'i3',... | reading the DIAL data, removing dups
:param input_file: path to the DIAL data
:return: a cleaned dataframe | src/data/data_utils.py | get_data | yanaiela/demog-text-removal | 42 | python | def get_data(input_file):
'\n reading the DIAL data, removing dups\n :param input_file: path to the DIAL data\n :return: a cleaned dataframe\n '
df = pd.read_csv(input_file, sep='\t', names=['tid', 'tts', 'uid', 'tll', 'tcb', 'text', 'aa', 'i2', 'i3', 'wh'], usecols=['uid', 'text', 'aa', 'i2', 'i3',... | def get_data(input_file):
'\n reading the DIAL data, removing dups\n :param input_file: path to the DIAL data\n :return: a cleaned dataframe\n '
df = pd.read_csv(input_file, sep='\t', names=['tid', 'tts', 'uid', 'tll', 'tcb', 'text', 'aa', 'i2', 'i3', 'wh'], usecols=['uid', 'text', 'aa', 'i2', 'i3',... |
24a6c981dfbd70b13a38d2a3c66d4406535a4f82994f0fc2467aa9b9da49838e | def mention_split(data, min_len=1):
"\n creating pos and neg examples for the `tweet-mention-prediction'\n :param data: words array\n :param min_len: minimum length of sentence to keep\n :return: positive and negative lists\n "
pos = []
neg = []
for sen in tqdm(data):
clean = [x f... | creating pos and neg examples for the `tweet-mention-prediction'
:param data: words array
:param min_len: minimum length of sentence to keep
:return: positive and negative lists | src/data/data_utils.py | mention_split | yanaiela/demog-text-removal | 42 | python | def mention_split(data, min_len=1):
"\n creating pos and neg examples for the `tweet-mention-prediction'\n :param data: words array\n :param min_len: minimum length of sentence to keep\n :return: positive and negative lists\n "
pos = []
neg = []
for sen in tqdm(data):
clean = [x f... | def mention_split(data, min_len=1):
"\n creating pos and neg examples for the `tweet-mention-prediction'\n :param data: words array\n :param min_len: minimum length of sentence to keep\n :return: positive and negative lists\n "
pos = []
neg = []
for sen in tqdm(data):
clean = [x f... |
de7efce45bf4b7f576a368dc853e58880bdee583a52c9a0d3e95f418d120af04 | def get_race(df, min_len=1):
'\n creating pos and neg examples for the binary race prediction\n :param df: dataframe with the race probabilities\n :param min_len: minimum length of sentence to keep\n :return: positive and negative lists\n '
wh_data = []
aa_data = []
white = df[(df.wh > CO... | creating pos and neg examples for the binary race prediction
:param df: dataframe with the race probabilities
:param min_len: minimum length of sentence to keep
:return: positive and negative lists | src/data/data_utils.py | get_race | yanaiela/demog-text-removal | 42 | python | def get_race(df, min_len=1):
'\n creating pos and neg examples for the binary race prediction\n :param df: dataframe with the race probabilities\n :param min_len: minimum length of sentence to keep\n :return: positive and negative lists\n '
wh_data = []
aa_data = []
white = df[(df.wh > CO... | def get_race(df, min_len=1):
'\n creating pos and neg examples for the binary race prediction\n :param df: dataframe with the race probabilities\n :param min_len: minimum length of sentence to keep\n :return: positive and negative lists\n '
wh_data = []
aa_data = []
white = df[(df.wh > CO... |
ec152e09ada21c693675db5e3ec6e992ace106f4e8c7605242f830fdc45e2008 | def get_sentiment(df, emotions, other_emotions, min_len=1):
'\n creating pos examples for the binary emoji-based sentiment prediction\n :param df: dataframe\n :param emotions: list of possible emotions for the current class\n :param other_emotions: list of emotions for the other class, of which, upon\n ... | creating pos examples for the binary emoji-based sentiment prediction
:param df: dataframe
:param emotions: list of possible emotions for the current class
:param other_emotions: list of emotions for the other class, of which, upon
a shared emoji, the example will be discarded
:param min_len: mi... | src/data/data_utils.py | get_sentiment | yanaiela/demog-text-removal | 42 | python | def get_sentiment(df, emotions, other_emotions, min_len=1):
'\n creating pos examples for the binary emoji-based sentiment prediction\n :param df: dataframe\n :param emotions: list of possible emotions for the current class\n :param other_emotions: list of emotions for the other class, of which, upon\n ... | def get_sentiment(df, emotions, other_emotions, min_len=1):
'\n creating pos examples for the binary emoji-based sentiment prediction\n :param df: dataframe\n :param emotions: list of possible emotions for the current class\n :param other_emotions: list of emotions for the other class, of which, upon\n ... |
669319678d252925b49d5c4b64ba5a0559e8c17759fcea7a956642a737a101ff | def makeThreadUseBlock(self, cmd, name, functionprefix):
'Generate C function pointer typedef for <command> Element'
paramdecl = ''
params = cmd.findall('param')
for param in params:
paramname = param.find('name')
if False:
paramdecl += ((' // not watching use of pointer '... | Generate C function pointer typedef for <command> Element | scripts/thread_safety_generator.py | makeThreadUseBlock | larsivarsimonsen-arm/Vulkan-ValidationLayers | 1 | python | def makeThreadUseBlock(self, cmd, name, functionprefix):
paramdecl =
params = cmd.findall('param')
for param in params:
paramname = param.find('name')
if False:
paramdecl += ((' // not watching use of pointer ' + paramname.text) + '\n')
else:
externsy... | def makeThreadUseBlock(self, cmd, name, functionprefix):
paramdecl =
params = cmd.findall('param')
for param in params:
paramname = param.find('name')
if False:
paramdecl += ((' // not watching use of pointer ' + paramname.text) + '\n')
else:
externsy... |
f83cedfaf0c76c6b7b99c5c79a597e18a5f2e16d15d8753eb201695c412a3f68 | def __init__(self, session):
"A channel is an environment bound to a session in which commands can be run.\n\n Args:\n session: the libssh's session instance the channel will be bound to\n "
self._session = session
self._channel = None
self._stdout = None
self._stderr = None... | A channel is an environment bound to a session in which commands can be run.
Args:
session: the libssh's session instance the channel will be bound to | pystassh/channel.py | __init__ | julienc91/pystassh | 3 | python | def __init__(self, session):
"A channel is an environment bound to a session in which commands can be run.\n\n Args:\n session: the libssh's session instance the channel will be bound to\n "
self._session = session
self._channel = None
self._stdout = None
self._stderr = None... | def __init__(self, session):
"A channel is an environment bound to a session in which commands can be run.\n\n Args:\n session: the libssh's session instance the channel will be bound to\n "
self._session = session
self._channel = None
self._stdout = None
self._stderr = None... |
8ae926f6e9e11a3b60c648ecd5c8d53da4229d83d1497e4c8f7728c77251467c | def open(self):
'Open a new channel.\n\n Raises:\n ChannelException: if the channel could not be correctly initialized\n '
if self._is_open():
return
channel = api.Api.ssh_channel_new(self._session)
if (channel is None):
raise exceptions.ChannelException('Channel... | Open a new channel.
Raises:
ChannelException: if the channel could not be correctly initialized | pystassh/channel.py | open | julienc91/pystassh | 3 | python | def open(self):
'Open a new channel.\n\n Raises:\n ChannelException: if the channel could not be correctly initialized\n '
if self._is_open():
return
channel = api.Api.ssh_channel_new(self._session)
if (channel is None):
raise exceptions.ChannelException('Channel... | def open(self):
'Open a new channel.\n\n Raises:\n ChannelException: if the channel could not be correctly initialized\n '
if self._is_open():
return
channel = api.Api.ssh_channel_new(self._session)
if (channel is None):
raise exceptions.ChannelException('Channel... |
99b9e2864607a0194f7b85d59106c455e8d59d0a731c93ebc438d9daa24e3fb9 | def close(self):
'Close the current channel.'
if self._is_open():
api.Api.ssh_channel_send_eof(self._channel)
api.Api.ssh_channel_free(self._channel)
self._shell_requested = False
self._channel = None | Close the current channel. | pystassh/channel.py | close | julienc91/pystassh | 3 | python | def close(self):
if self._is_open():
api.Api.ssh_channel_send_eof(self._channel)
api.Api.ssh_channel_free(self._channel)
self._shell_requested = False
self._channel = None | def close(self):
if self._is_open():
api.Api.ssh_channel_send_eof(self._channel)
api.Api.ssh_channel_free(self._channel)
self._shell_requested = False
self._channel = None<|docstring|>Close the current channel.<|endoftext|> |
3f6e115577595bb2737dd2598b2af433bf01cca83c69865d42bf85c967a796b7 | def request_shell(self, request_pty=False):
'Request a shell and optionally a PTY.'
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not open.')
if request_pty:
ret = api.Api.ssh_channel_request_pty(self._channel)
if (ret != api.SSH_OK):
raise e... | Request a shell and optionally a PTY. | pystassh/channel.py | request_shell | julienc91/pystassh | 3 | python | def request_shell(self, request_pty=False):
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not open.')
if request_pty:
ret = api.Api.ssh_channel_request_pty(self._channel)
if (ret != api.SSH_OK):
raise exceptions.ChannelException('Request a p... | def request_shell(self, request_pty=False):
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not open.')
if request_pty:
ret = api.Api.ssh_channel_request_pty(self._channel)
if (ret != api.SSH_OK):
raise exceptions.ChannelException('Request a p... |
dd13c9de8f0591086ee7610cf482008278f630aa7ad0df3f10a1f7c7c2dd8b37 | def read_nonblocking(self, size=2048, from_stderr=False):
'Do a nonblocking read on the channel.\n\n Args:\n size (int): bytes to try to read atomically and without blocking.\n from_stderr (bool): read from standard error instead from stdout.\n\n Returns:\n string (str... | Do a nonblocking read on the channel.
Args:
size (int): bytes to try to read atomically and without blocking.
from_stderr (bool): read from standard error instead from stdout.
Returns:
string (str): the string read. It may be shorter than the expected size.
An empty string does not imply... | pystassh/channel.py | read_nonblocking | julienc91/pystassh | 3 | python | def read_nonblocking(self, size=2048, from_stderr=False):
'Do a nonblocking read on the channel.\n\n Args:\n size (int): bytes to try to read atomically and without blocking.\n from_stderr (bool): read from standard error instead from stdout.\n\n Returns:\n string (str... | def read_nonblocking(self, size=2048, from_stderr=False):
'Do a nonblocking read on the channel.\n\n Args:\n size (int): bytes to try to read atomically and without blocking.\n from_stderr (bool): read from standard error instead from stdout.\n\n Returns:\n string (str... |
81c2a4adc95ee923e9afa52c6832eb044cf2f584e0cd5d5e94f2e654b4dd53be | def read(self, size=2048, from_stderr=False):
'Reads data from a channel. The read will block.\n\n Args:\n size (int): bytes to read.\n from_stderr (bool): read from standard error instead from stdout.\n\n Returns:\n string (str): the string read. Returns an empty stri... | Reads data from a channel. The read will block.
Args:
size (int): bytes to read.
from_stderr (bool): read from standard error instead from stdout.
Returns:
string (str): the string read. Returns an empty string on EOF. | pystassh/channel.py | read | julienc91/pystassh | 3 | python | def read(self, size=2048, from_stderr=False):
'Reads data from a channel. The read will block.\n\n Args:\n size (int): bytes to read.\n from_stderr (bool): read from standard error instead from stdout.\n\n Returns:\n string (str): the string read. Returns an empty stri... | def read(self, size=2048, from_stderr=False):
'Reads data from a channel. The read will block.\n\n Args:\n size (int): bytes to read.\n from_stderr (bool): read from standard error instead from stdout.\n\n Returns:\n string (str): the string read. Returns an empty stri... |
bd2f57a79dc86d1c0e8ae773f0f843b4bd16d417dcfd070371f5bc9dbf4488c9 | def write(self, data):
'Blocking write on a channel.\n\n Args:\n data (str): data to encode (to bytes) and write (not binary safe).\n\n Results:\n The number of bytes written.\n '
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not o... | Blocking write on a channel.
Args:
data (str): data to encode (to bytes) and write (not binary safe).
Results:
The number of bytes written. | pystassh/channel.py | write | julienc91/pystassh | 3 | python | def write(self, data):
'Blocking write on a channel.\n\n Args:\n data (str): data to encode (to bytes) and write (not binary safe).\n\n Results:\n The number of bytes written.\n '
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not o... | def write(self, data):
'Blocking write on a channel.\n\n Args:\n data (str): data to encode (to bytes) and write (not binary safe).\n\n Results:\n The number of bytes written.\n '
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not o... |
f9ad70a645abff571f400b0dd8a42d465034c21b861534da986fb08ec071e971 | def is_eof(self):
'Check if remote has sent an EOF.'
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not open.')
ret = api.Api.ssh_channel_is_eof(self._channel)
return bool(ret) | Check if remote has sent an EOF. | pystassh/channel.py | is_eof | julienc91/pystassh | 3 | python | def is_eof(self):
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not open.')
ret = api.Api.ssh_channel_is_eof(self._channel)
return bool(ret) | def is_eof(self):
if (not self._is_open()):
raise exceptions.ChannelException('The channel is not open.')
ret = api.Api.ssh_channel_is_eof(self._channel)
return bool(ret)<|docstring|>Check if remote has sent an EOF.<|endoftext|> |
3b3f759fec20dfdcbdc053eff29a0147b8cf9c0ed29875ad155c41e0969de77f | def execute(self, command):
'Execute a command.\n\n Args:\n command (str): the command to run\n\n Returns:\n Result: the Result object for this command\n '
with self:
ret = api.Api.ssh_channel_request_exec(self._channel, str.encode(command))
if (ret != ... | Execute a command.
Args:
command (str): the command to run
Returns:
Result: the Result object for this command | pystassh/channel.py | execute | julienc91/pystassh | 3 | python | def execute(self, command):
'Execute a command.\n\n Args:\n command (str): the command to run\n\n Returns:\n Result: the Result object for this command\n '
with self:
ret = api.Api.ssh_channel_request_exec(self._channel, str.encode(command))
if (ret != ... | def execute(self, command):
'Execute a command.\n\n Args:\n command (str): the command to run\n\n Returns:\n Result: the Result object for this command\n '
with self:
ret = api.Api.ssh_channel_request_exec(self._channel, str.encode(command))
if (ret != ... |
6b3bc6208857f81b5e3234206af1007f65e740cda412e45e7dc4f614ee90ddea | def get_error_message(self):
'Tries to retrieve an error message in case of error.\n\n Returns:\n str: An error message\n '
try:
return api.Api.get_error_message(self._session)
except exceptions.UnknownException:
return '<error message irrecoverable>' | Tries to retrieve an error message in case of error.
Returns:
str: An error message | pystassh/channel.py | get_error_message | julienc91/pystassh | 3 | python | def get_error_message(self):
'Tries to retrieve an error message in case of error.\n\n Returns:\n str: An error message\n '
try:
return api.Api.get_error_message(self._session)
except exceptions.UnknownException:
return '<error message irrecoverable>' | def get_error_message(self):
'Tries to retrieve an error message in case of error.\n\n Returns:\n str: An error message\n '
try:
return api.Api.get_error_message(self._session)
except exceptions.UnknownException:
return '<error message irrecoverable>'<|docstring|>Tri... |
0af11e8196785374a791c0e84b9730a3db8cf30ba333150632ae35ba51fa705b | def build_response(self):
'Iterates over the response data. This avoids reading the content\n at once into memory for large responses. The chunk size is the\n number of bytes it should read into memory on each iteration. The last\n Chunk will contain < chunk_size and trigger the EOF for a resp... | Iterates over the response data. This avoids reading the content
at once into memory for large responses. The chunk size is the
number of bytes it should read into memory on each iteration. The last
Chunk will contain < chunk_size and trigger the EOF for a response. | lib/APIResponse.py | build_response | Qualys/qPyMultiThread | 1 | python | def build_response(self):
'Iterates over the response data. This avoids reading the content\n at once into memory for large responses. The chunk size is the\n number of bytes it should read into memory on each iteration. The last\n Chunk will contain < chunk_size and trigger the EOF for a resp... | def build_response(self):
'Iterates over the response data. This avoids reading the content\n at once into memory for large responses. The chunk size is the\n number of bytes it should read into memory on each iteration. The last\n Chunk will contain < chunk_size and trigger the EOF for a resp... |
51a5e33e352baefe320d31db34d69890cdef06797102ac22bd71aec79a14f271 | def _set_active_tetramino_position(self, rnum=0, cnum=0):
'\n Changes the position of active tetramino if possible.\n :param rnum:\n The row index of the new position of the active tetramino\n :param cnum:\n The column index of the new position of the active tetramino\n ... | Changes the position of active tetramino if possible.
:param rnum:
The row index of the new position of the active tetramino
:param cnum:
The column index of the new position of the active tetramino | source/Game.py | _set_active_tetramino_position | nityeshaga/learntrisPy | 0 | python | def _set_active_tetramino_position(self, rnum=0, cnum=0):
'\n Changes the position of active tetramino if possible.\n :param rnum:\n The row index of the new position of the active tetramino\n :param cnum:\n The column index of the new position of the active tetramino\n ... | def _set_active_tetramino_position(self, rnum=0, cnum=0):
'\n Changes the position of active tetramino if possible.\n :param rnum:\n The row index of the new position of the active tetramino\n :param cnum:\n The column index of the new position of the active tetramino\n ... |
e7b2940e5e6552e0b073985c89555a123d87b6fe5f324d4c1f2767f31f933ca8 | def _get_MDP_name(data_dir):
'\n Args:\n data_dir (str)\n\n Returns:\n (list)\n '
try:
params_file = open(os.path.join(data_dir, 'parameters.txt'), 'r')
except IOError:
return [agent_file.replace('.csv', '') for agent_file in os.listdir(data_dir) if (os.path.isfile(os.... | Args:
data_dir (str)
Returns:
(list) | SR-LLRL/result_show_task.py | _get_MDP_name | Kchu/LifelongRL | 10 | python | def _get_MDP_name(data_dir):
'\n Args:\n data_dir (str)\n\n Returns:\n (list)\n '
try:
params_file = open(os.path.join(data_dir, 'parameters.txt'), 'r')
except IOError:
return [agent_file.replace('.csv', ) for agent_file in os.listdir(data_dir) if (os.path.isfile(os.pa... | def _get_MDP_name(data_dir):
'\n Args:\n data_dir (str)\n\n Returns:\n (list)\n '
try:
params_file = open(os.path.join(data_dir, 'parameters.txt'), 'r')
except IOError:
return [agent_file.replace('.csv', ) for agent_file in os.listdir(data_dir) if (os.path.isfile(os.pa... |
e7704a6a9717ea0762a0f8e7e6d65baa0b39d3c31b490191ff18709cd5021f08 | def main():
'\n Summary:\n For manual plotting.\n '
data_dir = ['.\\results\\lifelong-four_room_h-11_w-11-q-learning-vs_task\\\\']
output_dir = '.\\plots\\\\'
for index in range(len(data_dir)):
print((('Plotting ' + str((index + 1))) + 'th figure.'))
agent_names = chart_util... | Summary:
For manual plotting. | SR-LLRL/result_show_task.py | main | Kchu/LifelongRL | 10 | python | def main():
'\n Summary:\n For manual plotting.\n '
data_dir = ['.\\results\\lifelong-four_room_h-11_w-11-q-learning-vs_task\\\\']
output_dir = '.\\plots\\\\'
for index in range(len(data_dir)):
print((('Plotting ' + str((index + 1))) + 'th figure.'))
agent_names = chart_util... | def main():
'\n Summary:\n For manual plotting.\n '
data_dir = ['.\\results\\lifelong-four_room_h-11_w-11-q-learning-vs_task\\\\']
output_dir = '.\\plots\\\\'
for index in range(len(data_dir)):
print((('Plotting ' + str((index + 1))) + 'th figure.'))
agent_names = chart_util... |
ca2619cd43af9d5fe52d7986131379ebc850c1c8df672b592ece1bb33a6a93d9 | def restore_snapshot(model, snapshot, load_fn=None):
'Extension to restore snapshot.\n\n Returns:\n An extension function.\n\n '
import chainer
from chainer import training
if (load_fn is None):
load_fn = chainer.serializers.load_npz
@training.make_extension(trigger=(1, 'epoch'... | Extension to restore snapshot.
Returns:
An extension function. | espnet/asr/asr_utils.py | restore_snapshot | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def restore_snapshot(model, snapshot, load_fn=None):
'Extension to restore snapshot.\n\n Returns:\n An extension function.\n\n '
import chainer
from chainer import training
if (load_fn is None):
load_fn = chainer.serializers.load_npz
@training.make_extension(trigger=(1, 'epoch'... | def restore_snapshot(model, snapshot, load_fn=None):
'Extension to restore snapshot.\n\n Returns:\n An extension function.\n\n '
import chainer
from chainer import training
if (load_fn is None):
load_fn = chainer.serializers.load_npz
@training.make_extension(trigger=(1, 'epoch'... |
e3e9fd59fe258bfc3e0e5fd094cb07c145085ebc9a77be8d20828493a7b40701 | def adadelta_eps_decay(eps_decay):
'Extension to perform adadelta eps decay.\n\n Args:\n eps_decay (float): Decay rate of eps.\n\n Returns:\n An extension function.\n\n '
from chainer import training
@training.make_extension(trigger=(1, 'epoch'))
def adadelta_eps_decay(trainer):
... | Extension to perform adadelta eps decay.
Args:
eps_decay (float): Decay rate of eps.
Returns:
An extension function. | espnet/asr/asr_utils.py | adadelta_eps_decay | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def adadelta_eps_decay(eps_decay):
'Extension to perform adadelta eps decay.\n\n Args:\n eps_decay (float): Decay rate of eps.\n\n Returns:\n An extension function.\n\n '
from chainer import training
@training.make_extension(trigger=(1, 'epoch'))
def adadelta_eps_decay(trainer):
... | def adadelta_eps_decay(eps_decay):
'Extension to perform adadelta eps decay.\n\n Args:\n eps_decay (float): Decay rate of eps.\n\n Returns:\n An extension function.\n\n '
from chainer import training
@training.make_extension(trigger=(1, 'epoch'))
def adadelta_eps_decay(trainer):
... |
4609382cd2467685381f8ba85cced227d2ae2dede6e57a3a6b246df72ab0a8a3 | def adam_lr_decay(eps_decay):
'Extension to perform adam lr decay.\n\n Args:\n eps_decay (float): Decay rate of lr.\n\n Returns:\n An extension function.\n\n '
from chainer import training
@training.make_extension(trigger=(1, 'epoch'))
def adam_lr_decay(trainer):
_adam_lr... | Extension to perform adam lr decay.
Args:
eps_decay (float): Decay rate of lr.
Returns:
An extension function. | espnet/asr/asr_utils.py | adam_lr_decay | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def adam_lr_decay(eps_decay):
'Extension to perform adam lr decay.\n\n Args:\n eps_decay (float): Decay rate of lr.\n\n Returns:\n An extension function.\n\n '
from chainer import training
@training.make_extension(trigger=(1, 'epoch'))
def adam_lr_decay(trainer):
_adam_lr... | def adam_lr_decay(eps_decay):
'Extension to perform adam lr decay.\n\n Args:\n eps_decay (float): Decay rate of lr.\n\n Returns:\n An extension function.\n\n '
from chainer import training
@training.make_extension(trigger=(1, 'epoch'))
def adam_lr_decay(trainer):
_adam_lr... |
77c16bcf9be95fd19724d7039f2c41ef1028bcd20015f772efedf0d5e9f0d388 | def torch_snapshot(savefun=torch.save, filename='snapshot.ep.{.updater.epoch}'):
'Extension to take snapshot of the trainer for pytorch.\n\n Returns:\n An extension function.\n\n '
from chainer.training import extension
@extension.make_extension(trigger=(1, 'epoch'), priority=(- 100))
def ... | Extension to take snapshot of the trainer for pytorch.
Returns:
An extension function. | espnet/asr/asr_utils.py | torch_snapshot | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def torch_snapshot(savefun=torch.save, filename='snapshot.ep.{.updater.epoch}'):
'Extension to take snapshot of the trainer for pytorch.\n\n Returns:\n An extension function.\n\n '
from chainer.training import extension
@extension.make_extension(trigger=(1, 'epoch'), priority=(- 100))
def ... | def torch_snapshot(savefun=torch.save, filename='snapshot.ep.{.updater.epoch}'):
'Extension to take snapshot of the trainer for pytorch.\n\n Returns:\n An extension function.\n\n '
from chainer.training import extension
@extension.make_extension(trigger=(1, 'epoch'), priority=(- 100))
def ... |
0f0a8866d4a990eb781f2236ae5cf142fae1885edf7c9f58d87bf12db4af7841 | def add_gradient_noise(model, iteration, duration=100, eta=1.0, scale_factor=0.55):
'Adds noise from a standard normal distribution to the gradients.\n\n The standard deviation (`sigma`) is controlled by the three hyper-parameters below.\n `sigma` goes to zero (no noise) with more iterations.\n\n Args:\n ... | Adds noise from a standard normal distribution to the gradients.
The standard deviation (`sigma`) is controlled by the three hyper-parameters below.
`sigma` goes to zero (no noise) with more iterations.
Args:
model (torch.nn.model): Model.
iteration (int): Number of iterations.
duration (int) {100, 1000}:... | espnet/asr/asr_utils.py | add_gradient_noise | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def add_gradient_noise(model, iteration, duration=100, eta=1.0, scale_factor=0.55):
'Adds noise from a standard normal distribution to the gradients.\n\n The standard deviation (`sigma`) is controlled by the three hyper-parameters below.\n `sigma` goes to zero (no noise) with more iterations.\n\n Args:\n ... | def add_gradient_noise(model, iteration, duration=100, eta=1.0, scale_factor=0.55):
'Adds noise from a standard normal distribution to the gradients.\n\n The standard deviation (`sigma`) is controlled by the three hyper-parameters below.\n `sigma` goes to zero (no noise) with more iterations.\n\n Args:\n ... |
d304ce5505239f2bbe7af4973e2b600957815531437b2def92add12e89ff1e29 | def get_model_conf(model_path, conf_path=None):
'Get model config information by reading a model config file (model.json).\n\n Args:\n model_path (str): Model path.\n conf_path (str): Optional model config path.\n\n Returns:\n list[int, int, dict[str, Any]]: Config information loaded from... | Get model config information by reading a model config file (model.json).
Args:
model_path (str): Model path.
conf_path (str): Optional model config path.
Returns:
list[int, int, dict[str, Any]]: Config information loaded from json file. | espnet/asr/asr_utils.py | get_model_conf | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def get_model_conf(model_path, conf_path=None):
'Get model config information by reading a model config file (model.json).\n\n Args:\n model_path (str): Model path.\n conf_path (str): Optional model config path.\n\n Returns:\n list[int, int, dict[str, Any]]: Config information loaded from... | def get_model_conf(model_path, conf_path=None):
'Get model config information by reading a model config file (model.json).\n\n Args:\n model_path (str): Model path.\n conf_path (str): Optional model config path.\n\n Returns:\n list[int, int, dict[str, Any]]: Config information loaded from... |
5774ff82fc98cf294300bf6fe195f1ed579b972d2f2477e9e290299923203495 | def chainer_load(path, model):
'Load chainer model parameters.\n\n Args:\n path (str): Model path or snapshot file path to be loaded.\n model (chainer.Chain): Chainer model.\n\n '
import chainer
if ('snapshot' in os.path.basename(path)):
chainer.serializers.load_npz(path, model, ... | Load chainer model parameters.
Args:
path (str): Model path or snapshot file path to be loaded.
model (chainer.Chain): Chainer model. | espnet/asr/asr_utils.py | chainer_load | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def chainer_load(path, model):
'Load chainer model parameters.\n\n Args:\n path (str): Model path or snapshot file path to be loaded.\n model (chainer.Chain): Chainer model.\n\n '
import chainer
if ('snapshot' in os.path.basename(path)):
chainer.serializers.load_npz(path, model, ... | def chainer_load(path, model):
'Load chainer model parameters.\n\n Args:\n path (str): Model path or snapshot file path to be loaded.\n model (chainer.Chain): Chainer model.\n\n '
import chainer
if ('snapshot' in os.path.basename(path)):
chainer.serializers.load_npz(path, model, ... |
ab08f95006cdd2a95fa817c0eb17d872d7a9a65c255d5b155025a0258814f24b | def torch_save(path, model):
'Save torch model states.\n\n Args:\n path (str): Model path to be saved.\n model (torch.nn.Module): Torch model.\n\n '
if hasattr(model, 'module'):
torch.save(model.module.state_dict(), path)
else:
torch.save(model.state_dict(), path) | Save torch model states.
Args:
path (str): Model path to be saved.
model (torch.nn.Module): Torch model. | espnet/asr/asr_utils.py | torch_save | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def torch_save(path, model):
'Save torch model states.\n\n Args:\n path (str): Model path to be saved.\n model (torch.nn.Module): Torch model.\n\n '
if hasattr(model, 'module'):
torch.save(model.module.state_dict(), path)
else:
torch.save(model.state_dict(), path) | def torch_save(path, model):
'Save torch model states.\n\n Args:\n path (str): Model path to be saved.\n model (torch.nn.Module): Torch model.\n\n '
if hasattr(model, 'module'):
torch.save(model.module.state_dict(), path)
else:
torch.save(model.state_dict(), path)<|docstr... |
617d74ecd7ce28098b4bc02dc0f32380dd4e02022e46a223389c7dca21cc2267 | def snapshot_object(target, filename):
"Returns a trainer extension to take snapshots of a given object.\n\n Args:\n target (model): Object to serialize.\n filename (str): Name of the file into which the object is serialized.It can\n be a format string, where the trainer object is passed... | Returns a trainer extension to take snapshots of a given object.
Args:
target (model): Object to serialize.
filename (str): Name of the file into which the object is serialized.It can
be a format string, where the trainer object is passed to
the :meth: `str.format` method. For example,
... | espnet/asr/asr_utils.py | snapshot_object | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def snapshot_object(target, filename):
"Returns a trainer extension to take snapshots of a given object.\n\n Args:\n target (model): Object to serialize.\n filename (str): Name of the file into which the object is serialized.It can\n be a format string, where the trainer object is passed... | def snapshot_object(target, filename):
"Returns a trainer extension to take snapshots of a given object.\n\n Args:\n target (model): Object to serialize.\n filename (str): Name of the file into which the object is serialized.It can\n be a format string, where the trainer object is passed... |
06b700e729f58ffdad6fc59a847d6a1b30dee9c46a150acba4fb76eb37a7d40b | def torch_load(path, model):
'Load torch model states.\n\n Args:\n path (str): Model path or snapshot file path to be loaded.\n model (torch.nn.Module): Torch model.\n\n '
if ('snapshot' in os.path.basename(path)):
model_state_dict = torch.load(path, map_location=(lambda storage, loc... | Load torch model states.
Args:
path (str): Model path or snapshot file path to be loaded.
model (torch.nn.Module): Torch model. | espnet/asr/asr_utils.py | torch_load | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def torch_load(path, model):
'Load torch model states.\n\n Args:\n path (str): Model path or snapshot file path to be loaded.\n model (torch.nn.Module): Torch model.\n\n '
if ('snapshot' in os.path.basename(path)):
model_state_dict = torch.load(path, map_location=(lambda storage, loc... | def torch_load(path, model):
'Load torch model states.\n\n Args:\n path (str): Model path or snapshot file path to be loaded.\n model (torch.nn.Module): Torch model.\n\n '
if ('snapshot' in os.path.basename(path)):
model_state_dict = torch.load(path, map_location=(lambda storage, loc... |
2d23b8fc99b2c14ffc3f8753df4da6dc9ec3ca6f7fcad896bd0533a7f3d30351 | def torch_resume(snapshot_path, trainer):
"Resume from snapshot for pytorch.\n\n Args:\n snapshot_path (str): Snapshot file path.\n trainer (chainer.training.Trainer): Chainer's trainer instance.\n\n "
from chainer.serializers import NpzDeserializer
snapshot_dict = torch.load(snapshot_pa... | Resume from snapshot for pytorch.
Args:
snapshot_path (str): Snapshot file path.
trainer (chainer.training.Trainer): Chainer's trainer instance. | espnet/asr/asr_utils.py | torch_resume | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def torch_resume(snapshot_path, trainer):
"Resume from snapshot for pytorch.\n\n Args:\n snapshot_path (str): Snapshot file path.\n trainer (chainer.training.Trainer): Chainer's trainer instance.\n\n "
from chainer.serializers import NpzDeserializer
snapshot_dict = torch.load(snapshot_pa... | def torch_resume(snapshot_path, trainer):
"Resume from snapshot for pytorch.\n\n Args:\n snapshot_path (str): Snapshot file path.\n trainer (chainer.training.Trainer): Chainer's trainer instance.\n\n "
from chainer.serializers import NpzDeserializer
snapshot_dict = torch.load(snapshot_pa... |
97cafd187fdfe9fc74a337b077a2e0e225c0546887f5a69b2f81e5741c3d2edd | def parse_hypothesis(hyp, char_list):
'Parse hypothesis.\n\n Args:\n hyp (list[dict[str, Any]]): Recognition hypothesis.\n char_list (list[str]): List of characters.\n\n Returns:\n tuple(str, str, str, float)\n\n '
tokenid_as_list = list(map(int, hyp['yseq'][1:]))
token_as_list... | Parse hypothesis.
Args:
hyp (list[dict[str, Any]]): Recognition hypothesis.
char_list (list[str]): List of characters.
Returns:
tuple(str, str, str, float) | espnet/asr/asr_utils.py | parse_hypothesis | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def parse_hypothesis(hyp, char_list):
'Parse hypothesis.\n\n Args:\n hyp (list[dict[str, Any]]): Recognition hypothesis.\n char_list (list[str]): List of characters.\n\n Returns:\n tuple(str, str, str, float)\n\n '
tokenid_as_list = list(map(int, hyp['yseq'][1:]))
token_as_list... | def parse_hypothesis(hyp, char_list):
'Parse hypothesis.\n\n Args:\n hyp (list[dict[str, Any]]): Recognition hypothesis.\n char_list (list[str]): List of characters.\n\n Returns:\n tuple(str, str, str, float)\n\n '
tokenid_as_list = list(map(int, hyp['yseq'][1:]))
token_as_list... |
cac817f82b14105a0f5d8ea1e2f2c20578bce1dffbce9f43b562d05c0a956ae6 | def add_results_to_json(js, nbest_hyps, char_list):
'Add N-best results to json.\n\n Args:\n js (dict[str, Any]): Groundtruth utterance dict.\n nbest_hyps_sd (list[dict[str, Any]]):\n List of hypothesis for multi_speakers: nutts x nspkrs.\n char_list (list[str]): List of character... | Add N-best results to json.
Args:
js (dict[str, Any]): Groundtruth utterance dict.
nbest_hyps_sd (list[dict[str, Any]]):
List of hypothesis for multi_speakers: nutts x nspkrs.
char_list (list[str]): List of characters.
Returns:
dict[str, Any]: N-best results added utterance dict. | espnet/asr/asr_utils.py | add_results_to_json | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def add_results_to_json(js, nbest_hyps, char_list):
'Add N-best results to json.\n\n Args:\n js (dict[str, Any]): Groundtruth utterance dict.\n nbest_hyps_sd (list[dict[str, Any]]):\n List of hypothesis for multi_speakers: nutts x nspkrs.\n char_list (list[str]): List of character... | def add_results_to_json(js, nbest_hyps, char_list):
'Add N-best results to json.\n\n Args:\n js (dict[str, Any]): Groundtruth utterance dict.\n nbest_hyps_sd (list[dict[str, Any]]):\n List of hypothesis for multi_speakers: nutts x nspkrs.\n char_list (list[str]): List of character... |
e44f87bb13980cd37207575330def290c2ae020e8a79b61d63018dc35ba4b2a1 | def plot_spectrogram(plt, spec, mode='db', fs=None, frame_shift=None, bottom=True, left=True, right=True, top=False, labelbottom=True, labelleft=True, labelright=True, labeltop=False, cmap='inferno'):
'Plot spectrogram using matplotlib.\n\n Args:\n plt (matplotlib.pyplot): pyplot object.\n spec (nu... | Plot spectrogram using matplotlib.
Args:
plt (matplotlib.pyplot): pyplot object.
spec (numpy.ndarray): Input stft (Freq, Time)
mode (str): db or linear.
fs (int): Sample frequency. To convert y-axis to kHz unit.
frame_shift (int): The frame shift of stft. To convert x-axis to second unit.
botto... | espnet/asr/asr_utils.py | plot_spectrogram | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def plot_spectrogram(plt, spec, mode='db', fs=None, frame_shift=None, bottom=True, left=True, right=True, top=False, labelbottom=True, labelleft=True, labelright=True, labeltop=False, cmap='inferno'):
'Plot spectrogram using matplotlib.\n\n Args:\n plt (matplotlib.pyplot): pyplot object.\n spec (nu... | def plot_spectrogram(plt, spec, mode='db', fs=None, frame_shift=None, bottom=True, left=True, right=True, top=False, labelbottom=True, labelleft=True, labelright=True, labeltop=False, cmap='inferno'):
'Plot spectrogram using matplotlib.\n\n Args:\n plt (matplotlib.pyplot): pyplot object.\n spec (nu... |
d389f86f218a5beb096106e68c031f46826dd67105b33d0ed84f45e1afe46e4c | def format_mulenc_args(args):
'Format args for multi-encoder setup.\n\n It deals with following situations: (when args.num_encs=2):\n 1. args.elayers = None -> args.elayers = [4, 4];\n 2. args.elayers = 4 -> args.elayers = [4, 4];\n 3. args.elayers = [4, 4, 4] -> args.elayers = [4, 4].\n\n '
def... | Format args for multi-encoder setup.
It deals with following situations: (when args.num_encs=2):
1. args.elayers = None -> args.elayers = [4, 4];
2. args.elayers = 4 -> args.elayers = [4, 4];
3. args.elayers = [4, 4, 4] -> args.elayers = [4, 4]. | espnet/asr/asr_utils.py | format_mulenc_args | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def format_mulenc_args(args):
'Format args for multi-encoder setup.\n\n It deals with following situations: (when args.num_encs=2):\n 1. args.elayers = None -> args.elayers = [4, 4];\n 2. args.elayers = 4 -> args.elayers = [4, 4];\n 3. args.elayers = [4, 4, 4] -> args.elayers = [4, 4].\n\n '
def... | def format_mulenc_args(args):
'Format args for multi-encoder setup.\n\n It deals with following situations: (when args.num_encs=2):\n 1. args.elayers = None -> args.elayers = [4, 4];\n 2. args.elayers = 4 -> args.elayers = [4, 4];\n 3. args.elayers = [4, 4, 4] -> args.elayers = [4, 4].\n\n '
def... |
ea15d98ec9031253d5b12bd34389f8d7e6e7ee912647dc21be0eca515d1c72f1 | def __call__(self, trainer):
'Get value related to the key and compare with current value.'
observation = trainer.observation
summary = self._summary
key = self._key
if (key in observation):
summary.add({key: observation[key]})
if (not self._interval_trigger(trainer)):
return Fal... | Get value related to the key and compare with current value. | espnet/asr/asr_utils.py | __call__ | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def __call__(self, trainer):
observation = trainer.observation
summary = self._summary
key = self._key
if (key in observation):
summary.add({key: observation[key]})
if (not self._interval_trigger(trainer)):
return False
stats = summary.compute_mean()
value = float(stats[... | def __call__(self, trainer):
observation = trainer.observation
summary = self._summary
key = self._key
if (key in observation):
summary.add({key: observation[key]})
if (not self._interval_trigger(trainer)):
return False
stats = summary.compute_mean()
value = float(stats[... |
374a1b2010a9cfcbbb558de985b08f8a5855b469b826432b48fd77776891e923 | def __call__(self, trainer):
'Plot and save image file of att_ws matrix.'
(att_ws, uttid_list) = self.get_attention_weights()
if isinstance(att_ws, list):
num_encs = (len(att_ws) - 1)
for i in range(num_encs):
for (idx, att_w) in enumerate(att_ws[i]):
filename = (... | Plot and save image file of att_ws matrix. | espnet/asr/asr_utils.py | __call__ | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def __call__(self, trainer):
(att_ws, uttid_list) = self.get_attention_weights()
if isinstance(att_ws, list):
num_encs = (len(att_ws) - 1)
for i in range(num_encs):
for (idx, att_w) in enumerate(att_ws[i]):
filename = ('%s/%s.ep.{.updater.epoch}.att%d.png' % (sel... | def __call__(self, trainer):
(att_ws, uttid_list) = self.get_attention_weights()
if isinstance(att_ws, list):
num_encs = (len(att_ws) - 1)
for i in range(num_encs):
for (idx, att_w) in enumerate(att_ws[i]):
filename = ('%s/%s.ep.{.updater.epoch}.att%d.png' % (sel... |
d4bec5d6d335e71ac952c9a066cdecbeb478b9c63b2aec3b8a959d52ee7f6986 | def log_attentions(self, logger, step):
'Add image files of att_ws matrix to the tensorboard.'
(att_ws, uttid_list) = self.get_attention_weights()
if isinstance(att_ws, list):
num_encs = (len(att_ws) - 1)
for i in range(num_encs):
for (idx, att_w) in enumerate(att_ws[i]):
... | Add image files of att_ws matrix to the tensorboard. | espnet/asr/asr_utils.py | log_attentions | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def log_attentions(self, logger, step):
(att_ws, uttid_list) = self.get_attention_weights()
if isinstance(att_ws, list):
num_encs = (len(att_ws) - 1)
for i in range(num_encs):
for (idx, att_w) in enumerate(att_ws[i]):
att_w = self.trim_attention_weight(uttid_list... | def log_attentions(self, logger, step):
(att_ws, uttid_list) = self.get_attention_weights()
if isinstance(att_ws, list):
num_encs = (len(att_ws) - 1)
for i in range(num_encs):
for (idx, att_w) in enumerate(att_ws[i]):
att_w = self.trim_attention_weight(uttid_list... |
9fdd2735bc64366cba702afd03e3b629a76b69d07a6d191767024615ecc011ac | def get_attention_weights(self):
'Return attention weights.\n\n Returns:\n numpy.ndarray: attention weights. float. Its shape would be\n differ from backend.\n * pytorch-> 1) multi-head case => (B, H, Lmax, Tmax), 2)\n other case =... | Return attention weights.
Returns:
numpy.ndarray: attention weights. float. Its shape would be
differ from backend.
* pytorch-> 1) multi-head case => (B, H, Lmax, Tmax), 2)
other case => (B, Lmax, Tmax).
* chainer-> (B, Lmax, Tmax) | espnet/asr/asr_utils.py | get_attention_weights | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def get_attention_weights(self):
'Return attention weights.\n\n Returns:\n numpy.ndarray: attention weights. float. Its shape would be\n differ from backend.\n * pytorch-> 1) multi-head case => (B, H, Lmax, Tmax), 2)\n other case =... | def get_attention_weights(self):
'Return attention weights.\n\n Returns:\n numpy.ndarray: attention weights. float. Its shape would be\n differ from backend.\n * pytorch-> 1) multi-head case => (B, H, Lmax, Tmax), 2)\n other case =... |
f93f72fa0cb18467a3116f88c30fb05a2e0e2f4d08df4d2d845b6ec7087361c9 | def trim_attention_weight(self, uttid, att_w):
'Transform attention matrix with regard to self.reverse.'
if self.reverse:
(enc_key, enc_axis) = (self.okey, self.oaxis)
(dec_key, dec_axis) = (self.ikey, self.iaxis)
else:
(enc_key, enc_axis) = (self.ikey, self.iaxis)
(dec_key, ... | Transform attention matrix with regard to self.reverse. | espnet/asr/asr_utils.py | trim_attention_weight | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def trim_attention_weight(self, uttid, att_w):
if self.reverse:
(enc_key, enc_axis) = (self.okey, self.oaxis)
(dec_key, dec_axis) = (self.ikey, self.iaxis)
else:
(enc_key, enc_axis) = (self.ikey, self.iaxis)
(dec_key, dec_axis) = (self.okey, self.oaxis)
dec_len = int(sel... | def trim_attention_weight(self, uttid, att_w):
if self.reverse:
(enc_key, enc_axis) = (self.okey, self.oaxis)
(dec_key, dec_axis) = (self.ikey, self.iaxis)
else:
(enc_key, enc_axis) = (self.ikey, self.iaxis)
(dec_key, dec_axis) = (self.okey, self.oaxis)
dec_len = int(sel... |
4b0bb988cf7b18e3e73132b952a54f59601e661c8b7f9084dd3ab23112abf927 | def draw_attention_plot(self, att_w):
'Plot the att_w matrix.\n\n Returns:\n matplotlib.pyplot: pyplot object with attention matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.clf()
att_w = att_w.astype(np.float32)... | Plot the att_w matrix.
Returns:
matplotlib.pyplot: pyplot object with attention matrix image. | espnet/asr/asr_utils.py | draw_attention_plot | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def draw_attention_plot(self, att_w):
'Plot the att_w matrix.\n\n Returns:\n matplotlib.pyplot: pyplot object with attention matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.clf()
att_w = att_w.astype(np.float32)... | def draw_attention_plot(self, att_w):
'Plot the att_w matrix.\n\n Returns:\n matplotlib.pyplot: pyplot object with attention matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.clf()
att_w = att_w.astype(np.float32)... |
5bc4bf7ea9b95e2db6ce1ac43c5325e23f1cb4b1f80cd4115e3d5e77422ced10 | def draw_han_plot(self, att_w):
'Plot the att_w matrix for hierarchical attention.\n\n Returns:\n matplotlib.pyplot: pyplot object with attention matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.clf()
if (len(att... | Plot the att_w matrix for hierarchical attention.
Returns:
matplotlib.pyplot: pyplot object with attention matrix image. | espnet/asr/asr_utils.py | draw_han_plot | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def draw_han_plot(self, att_w):
'Plot the att_w matrix for hierarchical attention.\n\n Returns:\n matplotlib.pyplot: pyplot object with attention matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.clf()
if (len(att... | def draw_han_plot(self, att_w):
'Plot the att_w matrix for hierarchical attention.\n\n Returns:\n matplotlib.pyplot: pyplot object with attention matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.clf()
if (len(att... |
ee59148bd0656f6d3ecbe563d2db7811a0913ae8a270ca42c74578133d374355 | def __call__(self, trainer):
'Plot and save image file of ctc prob.'
(ctc_probs, uttid_list) = self.get_ctc_probs()
if isinstance(ctc_probs, list):
num_encs = (len(ctc_probs) - 1)
for i in range(num_encs):
for (idx, ctc_prob) in enumerate(ctc_probs[i]):
filename =... | Plot and save image file of ctc prob. | espnet/asr/asr_utils.py | __call__ | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def __call__(self, trainer):
(ctc_probs, uttid_list) = self.get_ctc_probs()
if isinstance(ctc_probs, list):
num_encs = (len(ctc_probs) - 1)
for i in range(num_encs):
for (idx, ctc_prob) in enumerate(ctc_probs[i]):
filename = ('%s/%s.ep.{.updater.epoch}.ctc%d.png'... | def __call__(self, trainer):
(ctc_probs, uttid_list) = self.get_ctc_probs()
if isinstance(ctc_probs, list):
num_encs = (len(ctc_probs) - 1)
for i in range(num_encs):
for (idx, ctc_prob) in enumerate(ctc_probs[i]):
filename = ('%s/%s.ep.{.updater.epoch}.ctc%d.png'... |
dea19c95e91c20c59ca8d3864e6731307b96b1f57b94b18af9fa762df0d6ebbd | def log_ctc_probs(self, logger, step):
'Add image files of ctc probs to the tensorboard.'
(ctc_probs, uttid_list) = self.get_ctc_probs()
if isinstance(ctc_probs, list):
num_encs = (len(ctc_probs) - 1)
for i in range(num_encs):
for (idx, ctc_prob) in enumerate(ctc_probs[i]):
... | Add image files of ctc probs to the tensorboard. | espnet/asr/asr_utils.py | log_ctc_probs | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def log_ctc_probs(self, logger, step):
(ctc_probs, uttid_list) = self.get_ctc_probs()
if isinstance(ctc_probs, list):
num_encs = (len(ctc_probs) - 1)
for i in range(num_encs):
for (idx, ctc_prob) in enumerate(ctc_probs[i]):
ctc_prob = self.trim_ctc_prob(uttid_lis... | def log_ctc_probs(self, logger, step):
(ctc_probs, uttid_list) = self.get_ctc_probs()
if isinstance(ctc_probs, list):
num_encs = (len(ctc_probs) - 1)
for i in range(num_encs):
for (idx, ctc_prob) in enumerate(ctc_probs[i]):
ctc_prob = self.trim_ctc_prob(uttid_lis... |
8053189815aee8b8fd07d35da206e2529bb4f70eed42f7886e01d76113da7287 | def get_ctc_probs(self):
'Return CTC probs.\n\n Returns:\n numpy.ndarray: CTC probs. float. Its shape would be\n differ from backend. (B, Tmax, vocab).\n\n '
(return_batch, uttid_list) = self.transform(self.data, return_uttid=True)
batch = self.convert... | Return CTC probs.
Returns:
numpy.ndarray: CTC probs. float. Its shape would be
differ from backend. (B, Tmax, vocab). | espnet/asr/asr_utils.py | get_ctc_probs | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def get_ctc_probs(self):
'Return CTC probs.\n\n Returns:\n numpy.ndarray: CTC probs. float. Its shape would be\n differ from backend. (B, Tmax, vocab).\n\n '
(return_batch, uttid_list) = self.transform(self.data, return_uttid=True)
batch = self.convert... | def get_ctc_probs(self):
'Return CTC probs.\n\n Returns:\n numpy.ndarray: CTC probs. float. Its shape would be\n differ from backend. (B, Tmax, vocab).\n\n '
(return_batch, uttid_list) = self.transform(self.data, return_uttid=True)
batch = self.convert... |
fdbfc177dab05267edb9ea8ed8edf12ba04f6ff0dab7396e8f554adc6e86fc0b | def trim_ctc_prob(self, uttid, prob):
'Trim CTC posteriors accoding to input lengths.'
enc_len = int(self.data_dict[uttid][self.ikey][self.iaxis]['shape'][0])
if (self.factor > 1):
enc_len //= self.factor
prob = prob[:enc_len]
return prob | Trim CTC posteriors accoding to input lengths. | espnet/asr/asr_utils.py | trim_ctc_prob | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def trim_ctc_prob(self, uttid, prob):
enc_len = int(self.data_dict[uttid][self.ikey][self.iaxis]['shape'][0])
if (self.factor > 1):
enc_len //= self.factor
prob = prob[:enc_len]
return prob | def trim_ctc_prob(self, uttid, prob):
enc_len = int(self.data_dict[uttid][self.ikey][self.iaxis]['shape'][0])
if (self.factor > 1):
enc_len //= self.factor
prob = prob[:enc_len]
return prob<|docstring|>Trim CTC posteriors accoding to input lengths.<|endoftext|> |
70c4821d9d69fd51dcb7917b0573c0c444a8f69eb88b58759803922886e6fe2b | def draw_ctc_plot(self, ctc_prob):
'Plot the ctc_prob matrix.\n\n Returns:\n matplotlib.pyplot: pyplot object with CTC prob matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ctc_prob = ctc_prob.astype(np.float32)
plt.... | Plot the ctc_prob matrix.
Returns:
matplotlib.pyplot: pyplot object with CTC prob matrix image. | espnet/asr/asr_utils.py | draw_ctc_plot | arceushui/Keyword-Spotting-Alibaba | 5,053 | python | def draw_ctc_plot(self, ctc_prob):
'Plot the ctc_prob matrix.\n\n Returns:\n matplotlib.pyplot: pyplot object with CTC prob matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ctc_prob = ctc_prob.astype(np.float32)
plt.... | def draw_ctc_plot(self, ctc_prob):
'Plot the ctc_prob matrix.\n\n Returns:\n matplotlib.pyplot: pyplot object with CTC prob matrix image.\n\n '
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ctc_prob = ctc_prob.astype(np.float32)
plt.... |
eb0fe50a5fe94be3e033d8a7518d335a722e7c41321f625153bfa8b1f3608645 | def create(self, validated_data):
'Create and return a new user'
user = models.UserProfile.objects.create_user(name=validated_data['name'], email=validated_data['email'], password=validated_data['password'])
return user | Create and return a new user | profiles_api/serializers.py | create | CSElonewolf/profiles_rest_api_project | 1 | python | def create(self, validated_data):
user = models.UserProfile.objects.create_user(name=validated_data['name'], email=validated_data['email'], password=validated_data['password'])
return user | def create(self, validated_data):
user = models.UserProfile.objects.create_user(name=validated_data['name'], email=validated_data['email'], password=validated_data['password'])
return user<|docstring|>Create and return a new user<|endoftext|> |
0d9fad8251573800db862d2e65d584f7c59096e393a60635c711ef088ae52926 | def __init__(self, input: Union[(List[Tuple[(str, str)]], None)]=None, show_printmessages: bool=True) -> None:
'delivers suggestions to which entity(ies) refers the input string(s)\n\n input:\n contains a list of tuples, which themself consists of a name and a type string\n show_printmessag... | delivers suggestions to which entity(ies) refers the input string(s)
input:
contains a list of tuples, which themself consists of a name and a type string
show_printmessages:
show class internal printmessages on runtime or not
current_wikidata_query_result_data:
buffer to save and print current wikidata_qu... | tei_entity_enricher/interface/postprocessing/identifier.py | __init__ | NEISSproject/TEIEntityEnricher | 0 | python | def __init__(self, input: Union[(List[Tuple[(str, str)]], None)]=None, show_printmessages: bool=True) -> None:
'delivers suggestions to which entity(ies) refers the input string(s)\n\n input:\n contains a list of tuples, which themself consists of a name and a type string\n show_printmessag... | def __init__(self, input: Union[(List[Tuple[(str, str)]], None)]=None, show_printmessages: bool=True) -> None:
'delivers suggestions to which entity(ies) refers the input string(s)\n\n input:\n contains a list of tuples, which themself consists of a name and a type string\n show_printmessag... |
05c1ca56b2a8f40238d433e6f21531b8cc153d5aa6febd2adb4e702a31cdd42c | def check_entity_library(self, input_tuple: tuple=None, loaded_library: EntityLibrary=None, query_by_type: bool=True) -> List[dict]:
'checks name, furtherNames and possibly type values of loaded_library\n for input_tuple and returns a list of entity dicts as value;\n a found entity must be of the corr... | checks name, furtherNames and possibly type values of loaded_library
for input_tuple and returns a list of entity dicts as value;
a found entity must be of the correct type (this can be deactivated by query_by_type parameter)
and has to have the name either in the name key or in the furtherNames key | tei_entity_enricher/interface/postprocessing/identifier.py | check_entity_library | NEISSproject/TEIEntityEnricher | 0 | python | def check_entity_library(self, input_tuple: tuple=None, loaded_library: EntityLibrary=None, query_by_type: bool=True) -> List[dict]:
'checks name, furtherNames and possibly type values of loaded_library\n for input_tuple and returns a list of entity dicts as value;\n a found entity must be of the corr... | def check_entity_library(self, input_tuple: tuple=None, loaded_library: EntityLibrary=None, query_by_type: bool=True) -> List[dict]:
'checks name, furtherNames and possibly type values of loaded_library\n for input_tuple and returns a list of entity dicts as value;\n a found entity must be of the corr... |
1de8ae71049d30d8fe7745a328906e6010dfd504c57f0814ba3936f68b6b6c5f | def check_query_results_with_wikidata_ids_of_entity_library(self, loaded_library: EntityLibrary=None, library_files: List[str]=None) -> Union[(Dict[(str, dict)], dict)]:
'checks results of self.query() by wikidata_id value refering to entity library\n and returns a dict with name values as keys and entity di... | checks results of self.query() by wikidata_id value refering to entity library
and returns a dict with name values as keys and entity dicts as values | tei_entity_enricher/interface/postprocessing/identifier.py | check_query_results_with_wikidata_ids_of_entity_library | NEISSproject/TEIEntityEnricher | 0 | python | def check_query_results_with_wikidata_ids_of_entity_library(self, loaded_library: EntityLibrary=None, library_files: List[str]=None) -> Union[(Dict[(str, dict)], dict)]:
'checks results of self.query() by wikidata_id value refering to entity library\n and returns a dict with name values as keys and entity di... | def check_query_results_with_wikidata_ids_of_entity_library(self, loaded_library: EntityLibrary=None, library_files: List[str]=None) -> Union[(Dict[(str, dict)], dict)]:
'checks results of self.query() by wikidata_id value refering to entity library\n and returns a dict with name values as keys and entity di... |
d574c2aa1d7cfbe3b8f1dabfc3c25ebee53f105d0f9c2aa3e8e9a39cc81536f1 | def check_wikidata_result_has_data(self, wikidata_result: Dict[(Tuple[(str, str)], list)]) -> bool:
'checks length of dict and integer in dict[key] list on index 0,\n which shows the length of the list in dict[key][1] (the amount of entity dicts in dict[key][1])'
result = False
if (len(wikidata_resul... | checks length of dict and integer in dict[key] list on index 0,
which shows the length of the list in dict[key][1] (the amount of entity dicts in dict[key][1]) | tei_entity_enricher/interface/postprocessing/identifier.py | check_wikidata_result_has_data | NEISSproject/TEIEntityEnricher | 0 | python | def check_wikidata_result_has_data(self, wikidata_result: Dict[(Tuple[(str, str)], list)]) -> bool:
'checks length of dict and integer in dict[key] list on index 0,\n which shows the length of the list in dict[key][1] (the amount of entity dicts in dict[key][1])'
result = False
if (len(wikidata_resul... | def check_wikidata_result_has_data(self, wikidata_result: Dict[(Tuple[(str, str)], list)]) -> bool:
'checks length of dict and integer in dict[key] list on index 0,\n which shows the length of the list in dict[key][1] (the amount of entity dicts in dict[key][1])'
result = False
if (len(wikidata_resul... |
fd39786298859d45d34d5036add106df54b419b9c470991ca95cebf6deba96c3 | def suggest(self, query_entity_library: Union[(EntityLibrary, None)]=None, entity_library_filter_for_correct_type: bool=True, do_wikidata_query: bool=True, wikidata_filter_for_precise_spelling: bool=True, wikidata_filter_for_correct_type: bool=True, wikidata_web_api_language: str='de', wikidata_web_api_limit: str='50',... | delivers entity suggestions to tuples in self.input,
returns dict with tuples as keys and entity list (list of dicts, whoses structure corresponds
to entity library entity structure) as values or returns an empty dict, if no suggestions could be made,
uses entity library query and wikidata queries,
if no reference to a... | tei_entity_enricher/interface/postprocessing/identifier.py | suggest | NEISSproject/TEIEntityEnricher | 0 | python | def suggest(self, query_entity_library: Union[(EntityLibrary, None)]=None, entity_library_filter_for_correct_type: bool=True, do_wikidata_query: bool=True, wikidata_filter_for_precise_spelling: bool=True, wikidata_filter_for_correct_type: bool=True, wikidata_web_api_language: str='de', wikidata_web_api_limit: str='50',... | def suggest(self, query_entity_library: Union[(EntityLibrary, None)]=None, entity_library_filter_for_correct_type: bool=True, do_wikidata_query: bool=True, wikidata_filter_for_precise_spelling: bool=True, wikidata_filter_for_correct_type: bool=True, wikidata_web_api_language: str='de', wikidata_web_api_limit: str='50',... |
150f513a61fbf221edd2f1e6b2ba1fe7e41e21a1557e1227cf81df3aa31aaa33 | def wikidata_query(self, filter_for_precise_spelling: bool=True, filter_for_correct_type: bool=True, wikidata_web_api_language: str='de', wikidata_web_api_limit: str='50', check_connectivity: bool=False) -> Union[(Dict[(Tuple[(str, str)], list)], bool)]:
'starts wikidata query and saves results in self.current_wiki... | starts wikidata query and saves results in self.current_wikidata_query_result_data
filter_for_precise_spelling:
variable determines wheather only exact matches
between the search string and the label value in the search list returned by
api are returned (filtering is executed only if there are more than 5 ... | tei_entity_enricher/interface/postprocessing/identifier.py | wikidata_query | NEISSproject/TEIEntityEnricher | 0 | python | def wikidata_query(self, filter_for_precise_spelling: bool=True, filter_for_correct_type: bool=True, wikidata_web_api_language: str='de', wikidata_web_api_limit: str='50', check_connectivity: bool=False) -> Union[(Dict[(Tuple[(str, str)], list)], bool)]:
'starts wikidata query and saves results in self.current_wiki... | def wikidata_query(self, filter_for_precise_spelling: bool=True, filter_for_correct_type: bool=True, wikidata_web_api_language: str='de', wikidata_web_api_limit: str='50', check_connectivity: bool=False) -> Union[(Dict[(Tuple[(str, str)], list)], bool)]:
'starts wikidata query and saves results in self.current_wiki... |
3df01964bc33f0abba09be2f76883117de4c1d409842aaab5d3a9aaf5da3c1dd | def summarize_current_wikidata_query_results(self) -> None:
'prints found entities (entity name and description) to all tuples in self.input list,\n to deliver a human readable overview over self.current_wikidata_query_result_data'
for key in self.current_wikidata_query_result_data:
print(f'{key}... | prints found entities (entity name and description) to all tuples in self.input list,
to deliver a human readable overview over self.current_wikidata_query_result_data | tei_entity_enricher/interface/postprocessing/identifier.py | summarize_current_wikidata_query_results | NEISSproject/TEIEntityEnricher | 0 | python | def summarize_current_wikidata_query_results(self) -> None:
'prints found entities (entity name and description) to all tuples in self.input list,\n to deliver a human readable overview over self.current_wikidata_query_result_data'
for key in self.current_wikidata_query_result_data:
print(f'{key}... | def summarize_current_wikidata_query_results(self) -> None:
'prints found entities (entity name and description) to all tuples in self.input list,\n to deliver a human readable overview over self.current_wikidata_query_result_data'
for key in self.current_wikidata_query_result_data:
print(f'{key}... |
cfdf503a8dc2448911ee185825474879d3d96dcf98f9ae688e215749fea26792 | def summarize_current_suggest_results(self) -> None:
'prints found entities (entity name and description) to all tuples in self.input list,\n to deliver a human readable overview over self.current_suggest_result_data'
for key in self.current_suggest_result_data:
print(f'{key}: {len(self.current_s... | prints found entities (entity name and description) to all tuples in self.input list,
to deliver a human readable overview over self.current_suggest_result_data | tei_entity_enricher/interface/postprocessing/identifier.py | summarize_current_suggest_results | NEISSproject/TEIEntityEnricher | 0 | python | def summarize_current_suggest_results(self) -> None:
'prints found entities (entity name and description) to all tuples in self.input list,\n to deliver a human readable overview over self.current_suggest_result_data'
for key in self.current_suggest_result_data:
print(f'{key}: {len(self.current_s... | def summarize_current_suggest_results(self) -> None:
'prints found entities (entity name and description) to all tuples in self.input list,\n to deliver a human readable overview over self.current_suggest_result_data'
for key in self.current_suggest_result_data:
print(f'{key}: {len(self.current_s... |
c765facae35df9baf5b3af91af6d12606294ccb61c0ae541c6bb7eaeeb12e910 | def check_test_broken(test_directory):
' A crude method to see if we have an e1000 issue. It\'d be better to use\n the dmesg output, but we don\'t have that for a bunch of existing data. This\n checks the apache bench file, and uses the crude metric of "is the maximum\n more than 10x then median, and is th... | A crude method to see if we have an e1000 issue. It'd be better to use
the dmesg output, but we don't have that for a bunch of existing data. This
checks the apache bench file, and uses the crude metric of "is the maximum
more than 10x then median, and is the maximum more than 1 second". | tools/utils.py | check_test_broken | jcrussell/que-ldrd-tools | 0 | python | def check_test_broken(test_directory):
' A crude method to see if we have an e1000 issue. It\'d be better to use\n the dmesg output, but we don\'t have that for a bunch of existing data. This\n checks the apache bench file, and uses the crude metric of "is the maximum\n more than 10x then median, and is th... | def check_test_broken(test_directory):
' A crude method to see if we have an e1000 issue. It\'d be better to use\n the dmesg output, but we don\'t have that for a bunch of existing data. This\n checks the apache bench file, and uses the crude metric of "is the maximum\n more than 10x then median, and is th... |
7560d960790be32cbd4b74f8705d5e437c6510473cb64c7b871ac1ca4ff49543 | def guess_test_parameters(fname):
' Guesses the test parameters from the directories a file is in '
environment = None
mixed_split = ('mixed' if ('mixed' in fname) else 'split')
cluster = 'ccc'
broken_test = 'unknown'
path = fname
path = path.replace('virtio-net-pci', 'virtio')
prev_path... | Guesses the test parameters from the directories a file is in | tools/utils.py | guess_test_parameters | jcrussell/que-ldrd-tools | 0 | python | def guess_test_parameters(fname):
' '
environment = None
mixed_split = ('mixed' if ('mixed' in fname) else 'split')
cluster = 'ccc'
broken_test = 'unknown'
path = fname
path = path.replace('virtio-net-pci', 'virtio')
prev_path = None
instrumentation = 'disabled'
pinning = 'disab... | def guess_test_parameters(fname):
' '
environment = None
mixed_split = ('mixed' if ('mixed' in fname) else 'split')
cluster = 'ccc'
broken_test = 'unknown'
path = fname
path = path.replace('virtio-net-pci', 'virtio')
prev_path = None
instrumentation = 'disabled'
pinning = 'disab... |
f89e9b1db18b401ce7d99fbe5c0b6b93f07495c6909e1481acb2218a8e62890e | def columns(exemplar, skipCols):
'\n columns returns a list of tuples for column name and type from the\n exemplar, skipping any columns from skipCols.\n '
cols = []
for (k, v) in exemplar.items():
if (k in skipCols):
continue
if ((type(v) is str) or (type(v) is unicode)... | columns returns a list of tuples for column name and type from the
exemplar, skipping any columns from skipCols. | tools/utils.py | columns | jcrussell/que-ldrd-tools | 0 | python | def columns(exemplar, skipCols):
'\n columns returns a list of tuples for column name and type from the\n exemplar, skipping any columns from skipCols.\n '
cols = []
for (k, v) in exemplar.items():
if (k in skipCols):
continue
if ((type(v) is str) or (type(v) is unicode)... | def columns(exemplar, skipCols):
'\n columns returns a list of tuples for column name and type from the\n exemplar, skipping any columns from skipCols.\n '
cols = []
for (k, v) in exemplar.items():
if (k in skipCols):
continue
if ((type(v) is str) or (type(v) is unicode)... |
346a552bcda2bec73cb93268580677a3e9ff39a52a8f552f7a3eab3fa16323c2 | def create_table_stmt(name, exemplar, skipCols=[]):
'\n create_table creates a database table with the specified name for the given\n exemplar. It returns an insert statement for that table.\n '
cols = columns(exemplar, skipCols)
create = 'CREATE TABLE {} ({})'.format(name, ','.join([((x + ' ') + y... | create_table creates a database table with the specified name for the given
exemplar. It returns an insert statement for that table. | tools/utils.py | create_table_stmt | jcrussell/que-ldrd-tools | 0 | python | def create_table_stmt(name, exemplar, skipCols=[]):
'\n create_table creates a database table with the specified name for the given\n exemplar. It returns an insert statement for that table.\n '
cols = columns(exemplar, skipCols)
create = 'CREATE TABLE {} ({})'.format(name, ','.join([((x + ' ') + y... | def create_table_stmt(name, exemplar, skipCols=[]):
'\n create_table creates a database table with the specified name for the given\n exemplar. It returns an insert statement for that table.\n '
cols = columns(exemplar, skipCols)
create = 'CREATE TABLE {} ({})'.format(name, ','.join([((x + ' ') + y... |
3ec731668d0959a641d87e052137399025a382581ee69374fa94b9a435b8ade8 | def insert_stmt(name, exemplar, skipCols=[]):
'\n insert_stmt returns a statement to insert the exemplar into the specified\n table, skipping any columns in skipCols.\n '
cols = columns(exemplar, skipCols)
insert = 'INSERT INTO {} ({}) VALUES ({})'.format(name, ','.join([v for (v, _) in cols]), ','... | insert_stmt returns a statement to insert the exemplar into the specified
table, skipping any columns in skipCols. | tools/utils.py | insert_stmt | jcrussell/que-ldrd-tools | 0 | python | def insert_stmt(name, exemplar, skipCols=[]):
'\n insert_stmt returns a statement to insert the exemplar into the specified\n table, skipping any columns in skipCols.\n '
cols = columns(exemplar, skipCols)
insert = 'INSERT INTO {} ({}) VALUES ({})'.format(name, ','.join([v for (v, _) in cols]), ','... | def insert_stmt(name, exemplar, skipCols=[]):
'\n insert_stmt returns a statement to insert the exemplar into the specified\n table, skipping any columns in skipCols.\n '
cols = columns(exemplar, skipCols)
insert = 'INSERT INTO {} ({}) VALUES ({})'.format(name, ','.join([v for (v, _) in cols]), ','... |
1b797d0887e10ad67b7c058c79fd5dff3d3666adcb824c93fd6ad23c039c6051 | def __init__(self, name, height=1.0, location=None):
'\n Builds a new ARMI block\n\n caseSettings : Settings object, optional\n The settings object to use to build the block\n\n name : str, optional\n The name of this block\n\n height : float, optional\n ... | Builds a new ARMI block
caseSettings : Settings object, optional
The settings object to use to build the block
name : str, optional
The name of this block
height : float, optional
The height of the block in cm. Defaults to 1.0 so that
`getVolume` assumes unit height. | armi/reactor/blocks.py | __init__ | crisobg1/armi | 1 | python | def __init__(self, name, height=1.0, location=None):
'\n Builds a new ARMI block\n\n caseSettings : Settings object, optional\n The settings object to use to build the block\n\n name : str, optional\n The name of this block\n\n height : float, optional\n ... | def __init__(self, name, height=1.0, location=None):
'\n Builds a new ARMI block\n\n caseSettings : Settings object, optional\n The settings object to use to build the block\n\n name : str, optional\n The name of this block\n\n height : float, optional\n ... |
04321676cb1a45a71685af48ccc026c7ab2c3618d3c49e7535928889595d32d5 | def __deepcopy__(self, memo):
'\n Custom deepcopy behavior to prevent duplication of macros and _lumpedFissionProducts.\n\n We detach the recursive links to the parent and the reactor to prevent blocks carrying large\n independent copies of stale reactors in memory. If you make a new block, you... | Custom deepcopy behavior to prevent duplication of macros and _lumpedFissionProducts.
We detach the recursive links to the parent and the reactor to prevent blocks carrying large
independent copies of stale reactors in memory. If you make a new block, you must add it to
an assembly and a reactor. | armi/reactor/blocks.py | __deepcopy__ | crisobg1/armi | 1 | python | def __deepcopy__(self, memo):
'\n Custom deepcopy behavior to prevent duplication of macros and _lumpedFissionProducts.\n\n We detach the recursive links to the parent and the reactor to prevent blocks carrying large\n independent copies of stale reactors in memory. If you make a new block, you... | def __deepcopy__(self, memo):
'\n Custom deepcopy behavior to prevent duplication of macros and _lumpedFissionProducts.\n\n We detach the recursive links to the parent and the reactor to prevent blocks carrying large\n independent copies of stale reactors in memory. If you make a new block, you... |
f91cb13aeba11cf5a56e3f7596e0785f2e759db20eb36610a54a72991285b4b5 | @property
def r(self):
"\n A block should only have a reactor through a parent assembly.\n\n It may make sense to try to factor out usage of ``b.r``.\n\n For now, this is presumptive of the structure of the composite hierarchy; i.e.\n the parent of a CORE must be the reactor. Fortunately... | A block should only have a reactor through a parent assembly.
It may make sense to try to factor out usage of ``b.r``.
For now, this is presumptive of the structure of the composite hierarchy; i.e.
the parent of a CORE must be the reactor. Fortunately, we probably don't
ultimately want to return the reactor in the fi... | armi/reactor/blocks.py | r | crisobg1/armi | 1 | python | @property
def r(self):
"\n A block should only have a reactor through a parent assembly.\n\n It may make sense to try to factor out usage of ``b.r``.\n\n For now, this is presumptive of the structure of the composite hierarchy; i.e.\n the parent of a CORE must be the reactor. Fortunately... | @property
def r(self):
"\n A block should only have a reactor through a parent assembly.\n\n It may make sense to try to factor out usage of ``b.r``.\n\n For now, this is presumptive of the structure of the composite hierarchy; i.e.\n the parent of a CORE must be the reactor. Fortunately... |
d0dbfdc56f515264895df39b56278185bf516cc5d65728ce795f59edf71c5b31 | @property
def location(self):
'\n Patch to keep code working while location system is refactored to use spatialLocators.\n\n Just creates a new location object based on current spatialLocator.\n '
return self.getLocationObject() | Patch to keep code working while location system is refactored to use spatialLocators.
Just creates a new location object based on current spatialLocator. | armi/reactor/blocks.py | location | crisobg1/armi | 1 | python | @property
def location(self):
'\n Patch to keep code working while location system is refactored to use spatialLocators.\n\n Just creates a new location object based on current spatialLocator.\n '
return self.getLocationObject() | @property
def location(self):
'\n Patch to keep code working while location system is refactored to use spatialLocators.\n\n Just creates a new location object based on current spatialLocator.\n '
return self.getLocationObject()<|docstring|>Patch to keep code working while location system i... |
e73a9fa06119f2c1ecbfdbb8e908eb1e1f1c1b314c781f5c4eb8bdec121244c5 | @location.setter
def location(self, value):
'\n Set spatialLocator based on a (old-style) location object.\n\n Patch to keep code working while location system is refactored to use spatialLocators.\n\n Blocks only have 1-D grid info so we only look at the axial portion.\n '
k = value... | Set spatialLocator based on a (old-style) location object.
Patch to keep code working while location system is refactored to use spatialLocators.
Blocks only have 1-D grid info so we only look at the axial portion. | armi/reactor/blocks.py | location | crisobg1/armi | 1 | python | @location.setter
def location(self, value):
'\n Set spatialLocator based on a (old-style) location object.\n\n Patch to keep code working while location system is refactored to use spatialLocators.\n\n Blocks only have 1-D grid info so we only look at the axial portion.\n '
k = value... | @location.setter
def location(self, value):
'\n Set spatialLocator based on a (old-style) location object.\n\n Patch to keep code working while location system is refactored to use spatialLocators.\n\n Blocks only have 1-D grid info so we only look at the axial portion.\n '
k = value... |
7b78bf977dd6d52ded20b6a232c3b53f57d11be9fa5d507fd3409ce6c3b6e728 | def makeName(self, assemNum, axialIndex):
"\n Generate a standard block from assembly number.\n\n This also sets the block-level assembly-num param.\n\n Examples\n --------\n >>> makeName(120, 5)\n 'B0120E'\n "
self.p.assemNum = assemNum
return 'B{0:04d}{1}'.... | Generate a standard block from assembly number.
This also sets the block-level assembly-num param.
Examples
--------
>>> makeName(120, 5)
'B0120E' | armi/reactor/blocks.py | makeName | crisobg1/armi | 1 | python | def makeName(self, assemNum, axialIndex):
"\n Generate a standard block from assembly number.\n\n This also sets the block-level assembly-num param.\n\n Examples\n --------\n >>> makeName(120, 5)\n 'B0120E'\n "
self.p.assemNum = assemNum
return 'B{0:04d}{1}'.... | def makeName(self, assemNum, axialIndex):
"\n Generate a standard block from assembly number.\n\n This also sets the block-level assembly-num param.\n\n Examples\n --------\n >>> makeName(120, 5)\n 'B0120E'\n "
self.p.assemNum = assemNum
return 'B{0:04d}{1}'.... |
03537b82841648e2a2f0a9f36643f3bbdc99bc58537d8185e26cd596e41c886e | def makeUnique(self):
"\n Assign a unique id (integer value) for each block.\n\n This should be called whenever creating a block that is intended to be treated\n as a unique object. For example, if you were to broadcast or pickle a block it\n should have the same ID across all nodes. Lik... | Assign a unique id (integer value) for each block.
This should be called whenever creating a block that is intended to be treated
as a unique object. For example, if you were to broadcast or pickle a block it
should have the same ID across all nodes. Likewise, if you deepcopy a block for
a temporary purpose to it shou... | armi/reactor/blocks.py | makeUnique | crisobg1/armi | 1 | python | def makeUnique(self):
"\n Assign a unique id (integer value) for each block.\n\n This should be called whenever creating a block that is intended to be treated\n as a unique object. For example, if you were to broadcast or pickle a block it\n should have the same ID across all nodes. Lik... | def makeUnique(self):
"\n Assign a unique id (integer value) for each block.\n\n This should be called whenever creating a block that is intended to be treated\n as a unique object. For example, if you were to broadcast or pickle a block it\n should have the same ID across all nodes. Lik... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.