code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_route_edge_attributes(G, route, attribute=None, minimize_key='length', retrieve_default=None):
"""
Get a list of attribute values for each edge in a path.
Parameters
----------
G : networkx multidigraph
route : list
list of nodes in the path
attribute : string
the na... | Get a list of attribute values for each edge in a path.
Parameters
----------
G : networkx multidigraph
route : list
list of nodes in the path
attribute : string
the name of the attribute to get the value of for each edge.
If not specified, the complete data dict is returned... | Below is the the instruction that describes the task:
### Input:
Get a list of attribute values for each edge in a path.
Parameters
----------
G : networkx multidigraph
route : list
list of nodes in the path
attribute : string
the name of the attribute to get the value of for ea... |
def curl_remote_name(cls, file_url):
"""Download file_url, and save as a file name of the URL.
It behaves like "curl -O or --remote-name".
It raises HTTPError if the file_url not found.
"""
tar_gz_file_name = file_url.split('/')[-1]
if sys.version_info >= (3, 2):
... | Download file_url, and save as a file name of the URL.
It behaves like "curl -O or --remote-name".
It raises HTTPError if the file_url not found. | Below is the the instruction that describes the task:
### Input:
Download file_url, and save as a file name of the URL.
It behaves like "curl -O or --remote-name".
It raises HTTPError if the file_url not found.
### Response:
def curl_remote_name(cls, file_url):
"""Download file_url, and sa... |
def get_language_and_region(self):
"""
Returns the combined language+region string or \x00\x00 for the default locale
:return:
"""
if self.locale != 0:
_language = self._unpack_language_or_region([self.locale & 0xff, (self.locale & 0xff00) >> 8, ], ord('a'))
... | Returns the combined language+region string or \x00\x00 for the default locale
:return: | Below is the the instruction that describes the task:
### Input:
Returns the combined language+region string or \x00\x00 for the default locale
:return:
### Response:
def get_language_and_region(self):
"""
Returns the combined language+region string or \x00\x00 for the default locale
... |
def load_favorites(self):
"""Fetches the MAL character favorites page and sets the current character's favorites attributes.
:rtype: :class:`.Character`
:return: Current character object.
"""
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilitie... | Fetches the MAL character favorites page and sets the current character's favorites attributes.
:rtype: :class:`.Character`
:return: Current character object. | Below is the the instruction that describes the task:
### Input:
Fetches the MAL character favorites page and sets the current character's favorites attributes.
:rtype: :class:`.Character`
:return: Current character object.
### Response:
def load_favorites(self):
"""Fetches the MAL character favorites... |
def check_attr(node, n):
""" Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
"""
if len(node.children) > n:
return node.children[n] | Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code. | Below is the the instruction that describes the task:
### Input:
Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
### Response:
def check_attr(node, n):
""" Check if ATTR has to be normalized
after this instruction has been translat... |
def get_context(self, name, value, attrs):
"""Missing method of django.forms.widgets.Widget class."""
context = {}
context['widget'] = {
'name': name,
'type': 'text',
'is_hidden': self.is_hidden,
'required': self.is_required,
'value': s... | Missing method of django.forms.widgets.Widget class. | Below is the the instruction that describes the task:
### Input:
Missing method of django.forms.widgets.Widget class.
### Response:
def get_context(self, name, value, attrs):
"""Missing method of django.forms.widgets.Widget class."""
context = {}
context['widget'] = {
'name': na... |
def get_content_macro_by_hash(self, content_id, version, macro_hash, callback=None):
"""
Returns the body of a macro (in storage format) with the given hash.
This resource is primarily used by connect applications that require the body of macro to perform their work.
The hash is generat... | Returns the body of a macro (in storage format) with the given hash.
This resource is primarily used by connect applications that require the body of macro to perform their work.
The hash is generated by connect during render time of the local macro holder and
is usually only relevant during th... | Below is the the instruction that describes the task:
### Input:
Returns the body of a macro (in storage format) with the given hash.
This resource is primarily used by connect applications that require the body of macro to perform their work.
The hash is generated by connect during render time of ... |
def add_to_tor(self, protocol):
'''
Returns a Deferred which fires with 'self' after at least one
descriptor has been uploaded. Errback if no descriptor upload
succeeds.
'''
upload_d = _await_descriptor_upload(protocol, self, progress=None, await_all_uploads=False)
... | Returns a Deferred which fires with 'self' after at least one
descriptor has been uploaded. Errback if no descriptor upload
succeeds. | Below is the the instruction that describes the task:
### Input:
Returns a Deferred which fires with 'self' after at least one
descriptor has been uploaded. Errback if no descriptor upload
succeeds.
### Response:
def add_to_tor(self, protocol):
'''
Returns a Deferred which fires wit... |
def delete_entry(sender, instance, **kwargs):
"""
Deletes Entry instance corresponding to specified instance.
:param sender: the sending class.
:param instance: the instance being deleted.
"""
from ..models import Entry
Entry.objects.get_for_model(instance)[0].delete() | Deletes Entry instance corresponding to specified instance.
:param sender: the sending class.
:param instance: the instance being deleted. | Below is the the instruction that describes the task:
### Input:
Deletes Entry instance corresponding to specified instance.
:param sender: the sending class.
:param instance: the instance being deleted.
### Response:
def delete_entry(sender, instance, **kwargs):
"""
Deletes Entry instance corresp... |
def write_acceptance_criteria_to_file(self):
"""
Writes current GUI acceptance criteria to criteria.txt or
pmag_criteria.txt depending on data model
"""
crit_list = list(self.acceptance_criteria.keys())
crit_list.sort()
rec = {}
rec['pmag_criteria_code'] =... | Writes current GUI acceptance criteria to criteria.txt or
pmag_criteria.txt depending on data model | Below is the the instruction that describes the task:
### Input:
Writes current GUI acceptance criteria to criteria.txt or
pmag_criteria.txt depending on data model
### Response:
def write_acceptance_criteria_to_file(self):
"""
Writes current GUI acceptance criteria to criteria.txt or
... |
def action_rename(self):
"""
Rename a shortcut
"""
# get old and new name from args
old = self.args['<old>']
new = self.args['<new>']
# select the old shortcut
self.db_query('''
SELECT id FROM shortcuts WHERE name=?
''', (old,))
... | Rename a shortcut | Below is the the instruction that describes the task:
### Input:
Rename a shortcut
### Response:
def action_rename(self):
"""
Rename a shortcut
"""
# get old and new name from args
old = self.args['<old>']
new = self.args['<new>']
# select the old shortcut
... |
def _get_pika_properties(properties_in):
"""Return a :class:`pika.spec.BasicProperties` object for a
:class:`rejected.data.Properties` object.
:param dict properties_in: Properties to convert
:rtype: :class:`pika.spec.BasicProperties`
"""
properties = pika.BasicProperti... | Return a :class:`pika.spec.BasicProperties` object for a
:class:`rejected.data.Properties` object.
:param dict properties_in: Properties to convert
:rtype: :class:`pika.spec.BasicProperties` | Below is the the instruction that describes the task:
### Input:
Return a :class:`pika.spec.BasicProperties` object for a
:class:`rejected.data.Properties` object.
:param dict properties_in: Properties to convert
:rtype: :class:`pika.spec.BasicProperties`
### Response:
def _get_pika_proper... |
def timeout(seconds):
"""
Raises a TimeoutError if a function does not terminate within
specified seconds.
"""
def _timeout_error(signal, frame):
raise TimeoutError("Operation did not finish within \
{} seconds".format(seconds))
def timeout_decorator(func):
@wraps(func)... | Raises a TimeoutError if a function does not terminate within
specified seconds. | Below is the the instruction that describes the task:
### Input:
Raises a TimeoutError if a function does not terminate within
specified seconds.
### Response:
def timeout(seconds):
"""
Raises a TimeoutError if a function does not terminate within
specified seconds.
"""
def _timeout_error(s... |
def define_from_values(cls, xdtu, ydtu, zdtu, xdtu_0, ydtu_0, zdtu_0):
"""Define class object from from provided values.
Parameters
----------
xdtu : float
XDTU fits keyword value.
ydtu : float
YDTU fits keyword value.
zdtu : float
ZDT... | Define class object from from provided values.
Parameters
----------
xdtu : float
XDTU fits keyword value.
ydtu : float
YDTU fits keyword value.
zdtu : float
ZDTU fits keyword value.
xdtu_0 : float
XDTU_0 fits keyword value... | Below is the the instruction that describes the task:
### Input:
Define class object from from provided values.
Parameters
----------
xdtu : float
XDTU fits keyword value.
ydtu : float
YDTU fits keyword value.
zdtu : float
ZDTU fits keywor... |
def __pathToTuple(self, path):
"""
Convert directory or file path to its tuple identifier.
Parameters
----------
path : str
Path to convert. It can look like /, /directory, /directory/ or /directory/filename.
Returns
-------
tup_id : tuple
... | Convert directory or file path to its tuple identifier.
Parameters
----------
path : str
Path to convert. It can look like /, /directory, /directory/ or /directory/filename.
Returns
-------
tup_id : tuple
Two element tuple identifier of directory... | Below is the the instruction that describes the task:
### Input:
Convert directory or file path to its tuple identifier.
Parameters
----------
path : str
Path to convert. It can look like /, /directory, /directory/ or /directory/filename.
Returns
-------
... |
def hacking_import_rules(logical_line, filename, noqa):
r"""Check for imports.
OpenStack HACKING guide recommends one import per line:
Do not import more than one module per line
Examples:
Okay: from nova.compute import api
H301: from nova.compute import api, utils
Do not use wildcard im... | r"""Check for imports.
OpenStack HACKING guide recommends one import per line:
Do not import more than one module per line
Examples:
Okay: from nova.compute import api
H301: from nova.compute import api, utils
Do not use wildcard import
Do not make relative imports
Examples:
Ok... | Below is the the instruction that describes the task:
### Input:
r"""Check for imports.
OpenStack HACKING guide recommends one import per line:
Do not import more than one module per line
Examples:
Okay: from nova.compute import api
H301: from nova.compute import api, utils
Do not use wi... |
def findConfigFile(cls, filename):
""" Search the configuration path (specified via the NTA_CONF_PATH
environment variable) for the given filename. If found, return the complete
path to the file.
:param filename: (string) name of file to locate
"""
paths = cls.getConfigPaths()
for p in pat... | Search the configuration path (specified via the NTA_CONF_PATH
environment variable) for the given filename. If found, return the complete
path to the file.
:param filename: (string) name of file to locate | Below is the the instruction that describes the task:
### Input:
Search the configuration path (specified via the NTA_CONF_PATH
environment variable) for the given filename. If found, return the complete
path to the file.
:param filename: (string) name of file to locate
### Response:
def findConfigFil... |
def _stage_from_version(version):
"""return "prd", "stg", or "dev" for the given version string. A value is always returned"""
if version:
m = re.match(r"^(?P<xyz>\d+\.\d+\.\d+)(?P<extra>.*)", version)
if m:
return "stg" if m.group("extra") else "prd"
return "dev" | return "prd", "stg", or "dev" for the given version string. A value is always returned | Below is the the instruction that describes the task:
### Input:
return "prd", "stg", or "dev" for the given version string. A value is always returned
### Response:
def _stage_from_version(version):
"""return "prd", "stg", or "dev" for the given version string. A value is always returned"""
if version:
... |
def _get_session_cookies(session, access_token):
"""Use the access token to get session cookies.
Raises GoogleAuthError if session cookies could not be loaded.
Returns dict of cookies.
"""
headers = {'Authorization': 'Bearer {}'.format(access_token)}
try:
r = session.get(('https://acc... | Use the access token to get session cookies.
Raises GoogleAuthError if session cookies could not be loaded.
Returns dict of cookies. | Below is the the instruction that describes the task:
### Input:
Use the access token to get session cookies.
Raises GoogleAuthError if session cookies could not be loaded.
Returns dict of cookies.
### Response:
def _get_session_cookies(session, access_token):
"""Use the access token to get session c... |
def save(self):
"""
:return: save this environment on Ariane server (create or update)
"""
LOGGER.debug("Environment.save")
post_payload = {}
consolidated_osi_id = []
if self.id is not None:
post_payload['environmentID'] = self.id
if self.nam... | :return: save this environment on Ariane server (create or update) | Below is the the instruction that describes the task:
### Input:
:return: save this environment on Ariane server (create or update)
### Response:
def save(self):
"""
:return: save this environment on Ariane server (create or update)
"""
LOGGER.debug("Environment.save")
post_... |
def _apply_rate(self, max_rate, aggressive=False):
"""
Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
... | Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
the faster current one.
If ``aggressive`` is ``True``,
... | Below is the the instruction that describes the task:
### Input:
Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
th... |
def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
... | Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
... | Below is the the instruction that describes the task:
### Input:
Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry chi... |
def apply_status_code(self, status_code):
"""
When a trace entity is generated under the http context,
the status code will affect this entity's fault/error/throttle flags.
Flip these flags based on status code.
"""
self._check_ended()
if not status_code:
... | When a trace entity is generated under the http context,
the status code will affect this entity's fault/error/throttle flags.
Flip these flags based on status code. | Below is the the instruction that describes the task:
### Input:
When a trace entity is generated under the http context,
the status code will affect this entity's fault/error/throttle flags.
Flip these flags based on status code.
### Response:
def apply_status_code(self, status_code):
"""
... |
def scan(self):
"""Trigger the wifi interface to scan."""
self._logger.info("iface '%s' scans", self.name())
self._wifi_ctrl.scan(self._raw_obj) | Trigger the wifi interface to scan. | Below is the the instruction that describes the task:
### Input:
Trigger the wifi interface to scan.
### Response:
def scan(self):
"""Trigger the wifi interface to scan."""
self._logger.info("iface '%s' scans", self.name())
self._wifi_ctrl.scan(self._raw_obj) |
def register_rpc(name=None):
"""Decorator. Allows registering a function for RPC.
* http://uwsgi.readthedocs.io/en/latest/RPC.html
Example:
.. code-block:: python
@register_rpc()
def expose_me():
do()
:param str|unicode name: RPC function name to ass... | Decorator. Allows registering a function for RPC.
* http://uwsgi.readthedocs.io/en/latest/RPC.html
Example:
.. code-block:: python
@register_rpc()
def expose_me():
do()
:param str|unicode name: RPC function name to associate
with decorated functi... | Below is the the instruction that describes the task:
### Input:
Decorator. Allows registering a function for RPC.
* http://uwsgi.readthedocs.io/en/latest/RPC.html
Example:
.. code-block:: python
@register_rpc()
def expose_me():
do()
:param str|unico... |
def escape_vals(vals, escape_numerics=True):
"""
Escapes a list of values to a string, converting to
unicode for safety.
"""
# Ints formatted as floats to disambiguate with counter mode
ints, floats = "%.1f", "%.10f"
escaped = []
for v in vals:
if isinstance(v, np.timedelta64):
... | Escapes a list of values to a string, converting to
unicode for safety. | Below is the the instruction that describes the task:
### Input:
Escapes a list of values to a string, converting to
unicode for safety.
### Response:
def escape_vals(vals, escape_numerics=True):
"""
Escapes a list of values to a string, converting to
unicode for safety.
"""
# Ints formatte... |
def add_mapping(agent, prefix, ip):
"""Adds a mapping with a contract.
It has high latency but gives some kind of guarantee."""
return _broadcast(agent, AddMappingManager, RecordType.record_A,
prefix, ip) | Adds a mapping with a contract.
It has high latency but gives some kind of guarantee. | Below is the the instruction that describes the task:
### Input:
Adds a mapping with a contract.
It has high latency but gives some kind of guarantee.
### Response:
def add_mapping(agent, prefix, ip):
"""Adds a mapping with a contract.
It has high latency but gives some kind of guarantee."""
return... |
def _set_flow_rate(pipette, params) -> None:
"""
Set flow rate in uL/mm, to value obtained from command's params.
"""
flow_rate_param = params['flowRate']
if not (flow_rate_param > 0):
raise RuntimeError('Positive flowRate param required')
pipette.flow_rate = {
'aspirate': flow... | Set flow rate in uL/mm, to value obtained from command's params. | Below is the the instruction that describes the task:
### Input:
Set flow rate in uL/mm, to value obtained from command's params.
### Response:
def _set_flow_rate(pipette, params) -> None:
"""
Set flow rate in uL/mm, to value obtained from command's params.
"""
flow_rate_param = params['flowRate']
... |
def get_filtered_dfs(lib, expr):
"""
Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered)
"""
logger_dataframes.info("enter get_filtered_dfs")
dfs = {}
tt = None
# Process all lipds files or one lipds file?
specific_files = _c... | Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered) | Below is the the instruction that describes the task:
### Input:
Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered)
### Response:
def get_filtered_dfs(lib, expr):
"""
Main: Get all data frames that match the given expression
:return dict: Fi... |
def _get_type(self, s):
"""
Converts a string from Scratch to its proper type in Python. Expects a
string with its delimiting quotes in place. Returns either a string,
int or float.
"""
# TODO: what if the number is bigger than an int or float?
if s.startswith('... | Converts a string from Scratch to its proper type in Python. Expects a
string with its delimiting quotes in place. Returns either a string,
int or float. | Below is the the instruction that describes the task:
### Input:
Converts a string from Scratch to its proper type in Python. Expects a
string with its delimiting quotes in place. Returns either a string,
int or float.
### Response:
def _get_type(self, s):
"""
Converts a string fro... |
def check_completeness_table(completeness_table, catalogue):
'''
Check to ensure completeness table is in the correct format
`completeness_table = np.array([[year_, mag_i]]) for i in number of bins`
:param np.ndarray completeness_table:
Completeness table in format [[year, mag]]
:param cat... | Check to ensure completeness table is in the correct format
`completeness_table = np.array([[year_, mag_i]]) for i in number of bins`
:param np.ndarray completeness_table:
Completeness table in format [[year, mag]]
:param catalogue:
Instance of openquake.hmtk.seismicity.catalogue.Catalogue... | Below is the the instruction that describes the task:
### Input:
Check to ensure completeness table is in the correct format
`completeness_table = np.array([[year_, mag_i]]) for i in number of bins`
:param np.ndarray completeness_table:
Completeness table in format [[year, mag]]
:param catalog... |
def remove_role_from_user(user, role):
"""
Remove a role from a user.
"""
user = _query_to_user(user)
role = _query_to_role(role)
if click.confirm(f'Are you sure you want to remove {role!r} from {user!r}?'):
user.roles.remove(role)
user_manager.save(user, commit=True)
cli... | Remove a role from a user. | Below is the the instruction that describes the task:
### Input:
Remove a role from a user.
### Response:
def remove_role_from_user(user, role):
"""
Remove a role from a user.
"""
user = _query_to_user(user)
role = _query_to_role(role)
if click.confirm(f'Are you sure you want to remove {rol... |
def _extract_table_root(d, current, pc):
"""
Extract data from the root level of a paleoData table.
:param dict d: paleoData table
:param dict current: Current root data
:param str pc: paleoData or chronData
:return dict current: Current root data
"""
logger_ts.info("enter extract_table_... | Extract data from the root level of a paleoData table.
:param dict d: paleoData table
:param dict current: Current root data
:param str pc: paleoData or chronData
:return dict current: Current root data | Below is the the instruction that describes the task:
### Input:
Extract data from the root level of a paleoData table.
:param dict d: paleoData table
:param dict current: Current root data
:param str pc: paleoData or chronData
:return dict current: Current root data
### Response:
def _extract_tabl... |
def set_urn(self,urn):
"""
Change the CTS URN of the author or adds a new one (if no URN is assigned).
"""
Type = self.session.get_class(surf.ns.ECRM['E55_Type'])
Identifier = self.session.get_class(surf.ns.ECRM['E42_Identifier'])
id_uri = "%s/cts_urn"%str(self.subject)
... | Change the CTS URN of the author or adds a new one (if no URN is assigned). | Below is the the instruction that describes the task:
### Input:
Change the CTS URN of the author or adds a new one (if no URN is assigned).
### Response:
def set_urn(self,urn):
"""
Change the CTS URN of the author or adds a new one (if no URN is assigned).
"""
Type = self.session.g... |
def _create_scsi_devices(scsi_devices):
'''
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
SCSI controllers
scsi_devices:
List of SCSI device properties
'''
keys = range(-1000, -1050, -1)
scsi_specs = []
if scsi_devices:
devs = [scsi['adapter'] fo... | Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
SCSI controllers
scsi_devices:
List of SCSI device properties | Below is the the instruction that describes the task:
### Input:
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
SCSI controllers
scsi_devices:
List of SCSI device properties
### Response:
def _create_scsi_devices(scsi_devices):
'''
Returns a list of vim.vm.device.Vi... |
def last_modified(self) -> Optional[datetime.datetime]:
"""The value of Last-Modified HTTP header, or None.
This header is represented as a `datetime` object.
"""
httpdate = self._headers.get(hdrs.LAST_MODIFIED)
if httpdate is not None:
timetuple = parsedate(httpdate... | The value of Last-Modified HTTP header, or None.
This header is represented as a `datetime` object. | Below is the the instruction that describes the task:
### Input:
The value of Last-Modified HTTP header, or None.
This header is represented as a `datetime` object.
### Response:
def last_modified(self) -> Optional[datetime.datetime]:
"""The value of Last-Modified HTTP header, or None.
Th... |
def send(self, topic, value=None, timeout=60, key=None, partition=None, timestamp_ms=None):
"""Publish a message to a topic.
- ``topic`` (str): topic where the message will be published
- ``value``: message value. Must be type bytes, or be serializable to bytes via configured value_serializer.
... | Publish a message to a topic.
- ``topic`` (str): topic where the message will be published
- ``value``: message value. Must be type bytes, or be serializable to bytes via configured value_serializer.
If value is None, key is required and message acts as a `delete`.
- ``timeout``
... | Below is the the instruction that describes the task:
### Input:
Publish a message to a topic.
- ``topic`` (str): topic where the message will be published
- ``value``: message value. Must be type bytes, or be serializable to bytes via configured value_serializer.
If value is None, key is... |
def build_cpp(build_context, target, compiler_config, workspace_dir):
"""Compile and link a C++ binary for `target`."""
rmtree(workspace_dir)
binary = join(*split(target.name))
objects = link_cpp_artifacts(build_context, target, workspace_dir, True)
buildenv_workspace = build_context.conf.host_to_bu... | Compile and link a C++ binary for `target`. | Below is the the instruction that describes the task:
### Input:
Compile and link a C++ binary for `target`.
### Response:
def build_cpp(build_context, target, compiler_config, workspace_dir):
"""Compile and link a C++ binary for `target`."""
rmtree(workspace_dir)
binary = join(*split(target.name))
... |
def get_full_path(request):
"""Return the current relative path including the query string.
Eg: “/foo/bar/?page=1”
"""
path = request.fullpath
query_string = request.environ.get('QUERY_STRING')
if query_string:
path += '?' + to_native(query_string)
return path | Return the current relative path including the query string.
Eg: “/foo/bar/?page=1” | Below is the the instruction that describes the task:
### Input:
Return the current relative path including the query string.
Eg: “/foo/bar/?page=1”
### Response:
def get_full_path(request):
"""Return the current relative path including the query string.
Eg: “/foo/bar/?page=1”
"""
path = reques... |
def load_tile_lowres(self, tile):
'''load a lower resolution tile from cache to fill in a
map while waiting for a higher resolution tile'''
if tile.zoom == self.min_zoom:
return None
# find the equivalent lower res tile
(lat,lon) = tile.coord()
width2 = TILE... | load a lower resolution tile from cache to fill in a
map while waiting for a higher resolution tile | Below is the the instruction that describes the task:
### Input:
load a lower resolution tile from cache to fill in a
map while waiting for a higher resolution tile
### Response:
def load_tile_lowres(self, tile):
'''load a lower resolution tile from cache to fill in a
map while waiting for ... |
def self_if_parameters(func):
"""
If any parameter is given, the method's binded object is returned after
executing the function. Else the function's result is returned.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if args or kwargs:
... | If any parameter is given, the method's binded object is returned after
executing the function. Else the function's result is returned. | Below is the the instruction that describes the task:
### Input:
If any parameter is given, the method's binded object is returned after
executing the function. Else the function's result is returned.
### Response:
def self_if_parameters(func):
"""
If any parameter is given, the method's binded object ... |
def _parse_info(line):
"""
The output can be:
- [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)]
- [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)]
"""
re_info = re.compile(
r'\[(?P<name>\w+).(?P<ver>.*) ' +
r'\((?P<rfm1name>\w+) (\w+):(?P<rfm1fre... | The output can be:
- [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)]
- [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)] | Below is the the instruction that describes the task:
### Input:
The output can be:
- [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)]
- [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)]
### Response:
def _parse_info(line):
"""
The output can be:
- [LaCrosseITPlusReader.10.1... |
def _on_change(self):
"""Callback if any of the values are changed."""
font = self.__generate_font_tuple()
self._example_label.configure(font=font) | Callback if any of the values are changed. | Below is the the instruction that describes the task:
### Input:
Callback if any of the values are changed.
### Response:
def _on_change(self):
"""Callback if any of the values are changed."""
font = self.__generate_font_tuple()
self._example_label.configure(font=font) |
def _get_data(self):
"""Process the IGRA2 text file for observations at site_id matching time.
Return:
-------
:class: `pandas.DataFrame` containing the body data.
:class: `pandas.DataFrame` containing the header data.
"""
# Split the list of times into b... | Process the IGRA2 text file for observations at site_id matching time.
Return:
-------
:class: `pandas.DataFrame` containing the body data.
:class: `pandas.DataFrame` containing the header data. | Below is the the instruction that describes the task:
### Input:
Process the IGRA2 text file for observations at site_id matching time.
Return:
-------
:class: `pandas.DataFrame` containing the body data.
:class: `pandas.DataFrame` containing the header data.
### Response:
... |
def StopService(service_name, service_binary_name=None):
"""Stop a Windows service with the given name.
Args:
service_name: string The name of the service to be stopped.
service_binary_name: string If given, also kill this binary as a best effort
fallback solution.
"""
# QueryServiceStatus retu... | Stop a Windows service with the given name.
Args:
service_name: string The name of the service to be stopped.
service_binary_name: string If given, also kill this binary as a best effort
fallback solution. | Below is the the instruction that describes the task:
### Input:
Stop a Windows service with the given name.
Args:
service_name: string The name of the service to be stopped.
service_binary_name: string If given, also kill this binary as a best effort
fallback solution.
### Response:
def StopSer... |
def path_is_inside(path, dirname):
"""Return True if path is under dirname."""
path = os.path.abspath(path)
dirname = os.path.abspath(dirname)
while len(path) >= len(dirname):
if path == dirname:
return True
newpath = os.path.dirname(path)
if newpath == path:
... | Return True if path is under dirname. | Below is the the instruction that describes the task:
### Input:
Return True if path is under dirname.
### Response:
def path_is_inside(path, dirname):
"""Return True if path is under dirname."""
path = os.path.abspath(path)
dirname = os.path.abspath(dirname)
while len(path) >= len(dirname):
... |
def get_defaults_file(*a, **kw):
"""Get a file object with YAML data of configuration defaults.
Arguments are passed through to :func:`get_defaults_str`.
"""
fd = StringIO()
fd.write(get_defaults_str(*a, **kw))
fd.seek(0)
return fd | Get a file object with YAML data of configuration defaults.
Arguments are passed through to :func:`get_defaults_str`. | Below is the the instruction that describes the task:
### Input:
Get a file object with YAML data of configuration defaults.
Arguments are passed through to :func:`get_defaults_str`.
### Response:
def get_defaults_file(*a, **kw):
"""Get a file object with YAML data of configuration defaults.
Argument... |
def areas_of_code(git_enrich, in_conn, out_conn, block_size=100):
"""Build and index for areas of code from a given Perceval RAW index.
:param block_size: size of items block.
:param git_enrich: GitEnrich object to deal with SortingHat affiliations.
:param in_conn: ESPandasConnector to read from.
:... | Build and index for areas of code from a given Perceval RAW index.
:param block_size: size of items block.
:param git_enrich: GitEnrich object to deal with SortingHat affiliations.
:param in_conn: ESPandasConnector to read from.
:param out_conn: ESPandasConnector to write to.
:return: number of doc... | Below is the the instruction that describes the task:
### Input:
Build and index for areas of code from a given Perceval RAW index.
:param block_size: size of items block.
:param git_enrich: GitEnrich object to deal with SortingHat affiliations.
:param in_conn: ESPandasConnector to read from.
:para... |
def fetch_async(self, limit=None, **q_options):
"""Fetch a list of query results, up to a limit.
This is the asynchronous version of Query.fetch().
"""
if limit is None:
default_options = self._make_options(q_options)
if default_options is not None and default_options.limit is not None:
... | Fetch a list of query results, up to a limit.
This is the asynchronous version of Query.fetch(). | Below is the the instruction that describes the task:
### Input:
Fetch a list of query results, up to a limit.
This is the asynchronous version of Query.fetch().
### Response:
def fetch_async(self, limit=None, **q_options):
"""Fetch a list of query results, up to a limit.
This is the asynchronous ver... |
def _prepare_pyshell_blocks(self, text):
"""Ensure that Python interactive shell sessions are put in
code blocks -- even if not properly indented.
"""
if ">>>" not in text:
return text
less_than_tab = self.tab_width - 1
_pyshell_block_re = re.compile(r"""
... | Ensure that Python interactive shell sessions are put in
code blocks -- even if not properly indented. | Below is the the instruction that describes the task:
### Input:
Ensure that Python interactive shell sessions are put in
code blocks -- even if not properly indented.
### Response:
def _prepare_pyshell_blocks(self, text):
"""Ensure that Python interactive shell sessions are put in
code blo... |
def _createunbound(kls, **info):
"""Create a new UnboundNode representing a given class."""
if issubclass(kls, Bitfield):
nodetype = UnboundBitfieldNode
elif hasattr(kls, '_fields_'):
nodetype = UnboundStructureNode
elif issubclass(kls, ctypes.Array):
nodetype = UnboundArray... | Create a new UnboundNode representing a given class. | Below is the the instruction that describes the task:
### Input:
Create a new UnboundNode representing a given class.
### Response:
def _createunbound(kls, **info):
"""Create a new UnboundNode representing a given class."""
if issubclass(kls, Bitfield):
nodetype = UnboundBitfieldNode
elif ... |
def CreateWithLock(self,
urn,
aff4_type,
token=None,
age=NEWEST_TIME,
force_new_version=True,
blocking=True,
blocking_lock_timeout=10,
blocking_sleep_in... | Creates a new object and locks it.
Similar to OpenWithLock below, this creates a locked object. The difference
is that when you call CreateWithLock, the object does not yet have to exist
in the data store.
Args:
urn: The object to create.
aff4_type: The desired type for this object.
... | Below is the the instruction that describes the task:
### Input:
Creates a new object and locks it.
Similar to OpenWithLock below, this creates a locked object. The difference
is that when you call CreateWithLock, the object does not yet have to exist
in the data store.
Args:
urn: The object... |
def radec_hmstodd(ra, dec):
""" Function to convert HMS values into decimal degrees.
This function relies on the astropy.coordinates package to perform the
conversion to decimal degrees.
Parameters
----------
ra : list or array
List or array of input RA positio... | Function to convert HMS values into decimal degrees.
This function relies on the astropy.coordinates package to perform the
conversion to decimal degrees.
Parameters
----------
ra : list or array
List or array of input RA positions
dec : list or array
... | Below is the the instruction that describes the task:
### Input:
Function to convert HMS values into decimal degrees.
This function relies on the astropy.coordinates package to perform the
conversion to decimal degrees.
Parameters
----------
ra : list or array
... |
def msg(self, level, s, *args):
"""
Print a debug message with the given level
"""
if s and level <= self.debug:
print "%s%s %s" % (" " * self.indent, s, ' '.join(map(repr, args))) | Print a debug message with the given level | Below is the the instruction that describes the task:
### Input:
Print a debug message with the given level
### Response:
def msg(self, level, s, *args):
"""
Print a debug message with the given level
"""
if s and level <= self.debug:
print "%s%s %s" % (" " * self.inden... |
def walnut_data():
"""Tomographic X-ray data of a walnut.
Notes
-----
See the article `Tomographic X-ray data of a walnut`_ for further
information.
See Also
--------
walnut_geometry
References
----------
.. _Tomographic X-ray data of a walnut: https://arxiv.org/abs/1502.0... | Tomographic X-ray data of a walnut.
Notes
-----
See the article `Tomographic X-ray data of a walnut`_ for further
information.
See Also
--------
walnut_geometry
References
----------
.. _Tomographic X-ray data of a walnut: https://arxiv.org/abs/1502.04064 | Below is the the instruction that describes the task:
### Input:
Tomographic X-ray data of a walnut.
Notes
-----
See the article `Tomographic X-ray data of a walnut`_ for further
information.
See Also
--------
walnut_geometry
References
----------
.. _Tomographic X-ray dat... |
def p_parallelblock(self, p):
'parallelblock : FORK block_statements JOIN'
p[0] = ParallelBlock(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | parallelblock : FORK block_statements JOIN | Below is the the instruction that describes the task:
### Input:
parallelblock : FORK block_statements JOIN
### Response:
def p_parallelblock(self, p):
'parallelblock : FORK block_statements JOIN'
p[0] = ParallelBlock(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
dist... | Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CA... | Below is the the instruction that describes the task:
### Input:
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, an... |
def list_hosts(kwargs=None, call=None):
'''
List all the hosts for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_hosts function must be called with... | List all the hosts for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts my-vmware-config | Below is the the instruction that describes the task:
### Input:
List all the hosts for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts my-vmware-config
### Response:
def list_hosts(kwargs=None, call=None):
'''
List all the hosts for this VMware environ... |
def get_columns(self, index, columns=None, as_dict=False):
"""
For a single index and list of column names return a DataFrame of the values in that index as either a dict
or a DataFrame
:param index: single index value
:param columns: list of column names
:param as_dict:... | For a single index and list of column names return a DataFrame of the values in that index as either a dict
or a DataFrame
:param index: single index value
:param columns: list of column names
:param as_dict: if True then return the result as a dictionary
:return: DataFrame or d... | Below is the the instruction that describes the task:
### Input:
For a single index and list of column names return a DataFrame of the values in that index as either a dict
or a DataFrame
:param index: single index value
:param columns: list of column names
:param as_dict: if True t... |
def request_homescreen(blink):
"""Request homescreen info."""
url = "{}/api/v3/accounts/{}/homescreen".format(blink.urls.base_url,
blink.account_id)
return http_get(blink, url) | Request homescreen info. | Below is the the instruction that describes the task:
### Input:
Request homescreen info.
### Response:
def request_homescreen(blink):
"""Request homescreen info."""
url = "{}/api/v3/accounts/{}/homescreen".format(blink.urls.base_url,
blink.account_id)
... |
def mkRepr(instance, *argls, **kwargs):
r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):... | r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):
... self.color, self.shape,... | Below is the the instruction that describes the task:
### Input:
r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, c... |
def destroy(self):
""" A reimplemented destructor that cancels
the dialog before destroying.
"""
super(AndroidPopupWindow, self).destroy()
window = self.window
if window:
#: Clear the dismiss listener
#: (or we get an error during the ca... | A reimplemented destructor that cancels
the dialog before destroying. | Below is the the instruction that describes the task:
### Input:
A reimplemented destructor that cancels
the dialog before destroying.
### Response:
def destroy(self):
""" A reimplemented destructor that cancels
the dialog before destroying.
"""
super(AndroidPopu... |
def _parse_result(result):
"""
Parse ``clamscan`` output into same dictionary structured used by
``pyclamd``.
Input example::
/home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND
Output dict::
{
"/home/bystrousak/Plocha/prace/test/eicar.com": (
... | Parse ``clamscan`` output into same dictionary structured used by
``pyclamd``.
Input example::
/home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND
Output dict::
{
"/home/bystrousak/Plocha/prace/test/eicar.com": (
"FOUND",
"Ei... | Below is the the instruction that describes the task:
### Input:
Parse ``clamscan`` output into same dictionary structured used by
``pyclamd``.
Input example::
/home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND
Output dict::
{
"/home/bystrousak/Plocha/... |
def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded."""
print('Connected to %s' % link_uri)
mems = self._cf.mem.get_mems(MemoryElement.TYPE_I2C)
print('Found {} EEPOM(s)'.format(... | This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded. | Below is the the instruction that describes the task:
### Input:
This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded.
### Response:
def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
... |
def is_empty(self):
'''Returns True if all titleInfo subfields are not set or
empty; returns False if any of the fields are not empty.'''
return not bool(self.title or self.subtitle or self.part_number \
or self.part_name or self.non_sort or self.type) | Returns True if all titleInfo subfields are not set or
empty; returns False if any of the fields are not empty. | Below is the the instruction that describes the task:
### Input:
Returns True if all titleInfo subfields are not set or
empty; returns False if any of the fields are not empty.
### Response:
def is_empty(self):
'''Returns True if all titleInfo subfields are not set or
empty; returns False i... |
def fftr(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the real part of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less... | r"""
Return the real part of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
... | Below is the the instruction that describes the task:
### Input:
r"""
Return the real part of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is l... |
def open(self):
"""
Opens the port.
:returns: Deferred that callbacks when we are ready to make and receive calls.
"""
logging.debug("Opening rpc system")
d = self._connectionpool.open(self._packet_received)
def opened(_):
logging.deb... | Opens the port.
:returns: Deferred that callbacks when we are ready to make and receive calls. | Below is the the instruction that describes the task:
### Input:
Opens the port.
:returns: Deferred that callbacks when we are ready to make and receive calls.
### Response:
def open(self):
"""
Opens the port.
:returns: Deferred that callbacks when we are ready to ... |
def t_ID(self, token):
r'[a-zA-Z_][a-zA-Z0-9_-]*'
if token.value in self.KEYWORDS:
token.type = self.KEYWORDS[token.value]
return token
else:
return token | r'[a-zA-Z_][a-zA-Z0-9_-]* | Below is the the instruction that describes the task:
### Input:
r'[a-zA-Z_][a-zA-Z0-9_-]*
### Response:
def t_ID(self, token):
r'[a-zA-Z_][a-zA-Z0-9_-]*'
if token.value in self.KEYWORDS:
token.type = self.KEYWORDS[token.value]
return token
else:
return t... |
def search_tag(self, tag, symbols=True, feeds=False):
""" Get a list of Symbols by searching a tag or partial tag.
Parameters
----------
tag : str
The tag to search. Appending '%' will use SQL's "LIKE"
functionality.
symbols : bool, optional
... | Get a list of Symbols by searching a tag or partial tag.
Parameters
----------
tag : str
The tag to search. Appending '%' will use SQL's "LIKE"
functionality.
symbols : bool, optional
Search for Symbol's based on their tags.
feeds : ... | Below is the the instruction that describes the task:
### Input:
Get a list of Symbols by searching a tag or partial tag.
Parameters
----------
tag : str
The tag to search. Appending '%' will use SQL's "LIKE"
functionality.
symbols : bool, optional
... |
def exterior_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):
"""
Estimate if this and other polygon's exterior are almost identical.
The two exteriors can have different numbers of points, but any point
randomly sampled on the exterior of one polygon should be close to... | Estimate if this and other polygon's exterior are almost identical.
The two exteriors can have different numbers of points, but any point
randomly sampled on the exterior of one polygon should be close to the
closest point on the exterior of the other polygon.
Note that this method wor... | Below is the the instruction that describes the task:
### Input:
Estimate if this and other polygon's exterior are almost identical.
The two exteriors can have different numbers of points, but any point
randomly sampled on the exterior of one polygon should be close to the
closest point on ... |
def to_simple_dict(self):
"""Return a dict of only the basic data about the release"""
return {
'version': self.version,
'product': self.product,
'channel': self.channel,
'is_public': self.is_public,
'slug': self.slug,
'title': unic... | Return a dict of only the basic data about the release | Below is the the instruction that describes the task:
### Input:
Return a dict of only the basic data about the release
### Response:
def to_simple_dict(self):
"""Return a dict of only the basic data about the release"""
return {
'version': self.version,
'product': self.prod... |
def lonely_buckets(self):
"""
Get all of the buckets that haven't been updated in over
an hour.
"""
hrago = time.monotonic() - 3600
return [b for b in self.buckets if b.last_updated < hrago] | Get all of the buckets that haven't been updated in over
an hour. | Below is the the instruction that describes the task:
### Input:
Get all of the buckets that haven't been updated in over
an hour.
### Response:
def lonely_buckets(self):
"""
Get all of the buckets that haven't been updated in over
an hour.
"""
hrago = time.monotonic... |
def remove_from_queue(self, index):
"""Remove a track from the queue by index. The index number is
required as an argument, where the first index is 0.
Args:
index (int): The (0-based) index of the track to remove
"""
# TODO: what do these parameters actually do?
... | Remove a track from the queue by index. The index number is
required as an argument, where the first index is 0.
Args:
index (int): The (0-based) index of the track to remove | Below is the the instruction that describes the task:
### Input:
Remove a track from the queue by index. The index number is
required as an argument, where the first index is 0.
Args:
index (int): The (0-based) index of the track to remove
### Response:
def remove_from_queue(self, inde... |
def get_seqstarts(bamfile, N):
""" Go through the SQ headers and pull out all sequences with size
greater than the resolution settings, i.e. contains at least a few cells
"""
import pysam
bamfile = pysam.AlignmentFile(bamfile, "rb")
seqsize = {}
for kv in bamfile.header["SQ"]:
if kv[... | Go through the SQ headers and pull out all sequences with size
greater than the resolution settings, i.e. contains at least a few cells | Below is the the instruction that describes the task:
### Input:
Go through the SQ headers and pull out all sequences with size
greater than the resolution settings, i.e. contains at least a few cells
### Response:
def get_seqstarts(bamfile, N):
""" Go through the SQ headers and pull out all sequences with... |
def remove(self, key):
"""T.remove(key) <==> del T[key], remove item <key> from tree."""
if self._root is None:
raise KeyError(str(key))
head = Node() # False tree root
node = head
node.right = self._root
parent = None
grand_parent = None
foun... | T.remove(key) <==> del T[key], remove item <key> from tree. | Below is the the instruction that describes the task:
### Input:
T.remove(key) <==> del T[key], remove item <key> from tree.
### Response:
def remove(self, key):
"""T.remove(key) <==> del T[key], remove item <key> from tree."""
if self._root is None:
raise KeyError(str(key))
hea... |
def from_table(fileobj=None, url='http://hgdownload.cse.ucsc.edu/goldenpath/hg19/database/knownGene.txt.gz',
parser=UCSCTable.KNOWN_GENE, mode='tx', decompress=None):
'''
UCSC Genome project provides several tables with gene coordinates (https://genome.ucsc.edu/cgi-bin/hgTables),
... | UCSC Genome project provides several tables with gene coordinates (https://genome.ucsc.edu/cgi-bin/hgTables),
such as knownGene, refGene, ensGene, wgEncodeGencodeBasicV19, etc.
Indexing the rows of those tables into a ``GenomeIntervalTree`` is a common task, implemented in this method.
The tabl... | Below is the the instruction that describes the task:
### Input:
UCSC Genome project provides several tables with gene coordinates (https://genome.ucsc.edu/cgi-bin/hgTables),
such as knownGene, refGene, ensGene, wgEncodeGencodeBasicV19, etc.
Indexing the rows of those tables into a ``GenomeIntervalT... |
def _log_phi(z):
"""Stable computation of the log of the Normal CDF and its derivative."""
# Adapted from the GPML function `logphi.m`.
if z * z < 0.0492:
# First case: z close to zero.
coef = -z / SQRT2PI
val = functools.reduce(lambda acc, c: coef * (c + acc), CS, 0)
res = -... | Stable computation of the log of the Normal CDF and its derivative. | Below is the the instruction that describes the task:
### Input:
Stable computation of the log of the Normal CDF and its derivative.
### Response:
def _log_phi(z):
"""Stable computation of the log of the Normal CDF and its derivative."""
# Adapted from the GPML function `logphi.m`.
if z * z < 0.0492:
... |
def update_reduced_metric(self, name, value, key=None):
"""Update the value of ReducedMetric or MultiReducedMetric
:type name: str
:param name: name of the registered metric to be updated.
:param value: specifies a value to be reduced.
:type key: str or None
:param key: specifies a key for Mult... | Update the value of ReducedMetric or MultiReducedMetric
:type name: str
:param name: name of the registered metric to be updated.
:param value: specifies a value to be reduced.
:type key: str or None
:param key: specifies a key for MultiReducedMetric. Needs to be `None` for updating
... | Below is the the instruction that describes the task:
### Input:
Update the value of ReducedMetric or MultiReducedMetric
:type name: str
:param name: name of the registered metric to be updated.
:param value: specifies a value to be reduced.
:type key: str or None
:param key: specifies a key fo... |
def to_parameter_specs(self, name_prefix=""):
"""To list of dicts suitable for Cloud ML Engine hyperparameter tuning."""
specs = []
for name, categories, _ in self._categorical_params.values():
spec = {
"parameterName": name_prefix + name,
"type": "CATEGORICAL",
"categori... | To list of dicts suitable for Cloud ML Engine hyperparameter tuning. | Below is the the instruction that describes the task:
### Input:
To list of dicts suitable for Cloud ML Engine hyperparameter tuning.
### Response:
def to_parameter_specs(self, name_prefix=""):
"""To list of dicts suitable for Cloud ML Engine hyperparameter tuning."""
specs = []
for name, categories, _... |
def strSlist(string):
""" Converts angle string to signed list. """
sign = '-' if string[0] == '-' else '+'
values = [abs(int(x)) for x in string.split(':')]
return _fixSlist(list(sign) + values) | Converts angle string to signed list. | Below is the the instruction that describes the task:
### Input:
Converts angle string to signed list.
### Response:
def strSlist(string):
""" Converts angle string to signed list. """
sign = '-' if string[0] == '-' else '+'
values = [abs(int(x)) for x in string.split(':')]
return _fixSlist(list(si... |
def match_window(in_data, offset):
'''Find the longest match for the string starting at offset in the preceeding data
'''
window_start = max(offset - WINDOW_MASK, 0)
for n in range(MAX_LEN, THRESHOLD-1, -1):
window_end = min(offset + n, len(in_data))
# we've not got enough data left for... | Find the longest match for the string starting at offset in the preceeding data | Below is the the instruction that describes the task:
### Input:
Find the longest match for the string starting at offset in the preceeding data
### Response:
def match_window(in_data, offset):
'''Find the longest match for the string starting at offset in the preceeding data
'''
window_start = max(off... |
def K_globe_stop_check_valve_Crane(D1, D2, fd=None, style=0):
r'''Returns the loss coefficient for a globe stop check valve as shown in
[1]_.
If β = 1:
.. math::
K = K_1 = K_2 = N\cdot f_d
Otherwise:
.. math::
K_2 = \frac{K + \left[0.5(1-\beta^2) ... | r'''Returns the loss coefficient for a globe stop check valve as shown in
[1]_.
If β = 1:
.. math::
K = K_1 = K_2 = N\cdot f_d
Otherwise:
.. math::
K_2 = \frac{K + \left[0.5(1-\beta^2) + (1-\beta^2)^2\right]}{\beta^4}
Style 0 is the stand... | Below is the the instruction that describes the task:
### Input:
r'''Returns the loss coefficient for a globe stop check valve as shown in
[1]_.
If β = 1:
.. math::
K = K_1 = K_2 = N\cdot f_d
Otherwise:
.. math::
K_2 = \frac{K + \left[0.5(1-\beta^... |
def _oauth_tokengetter(token=None):
"""
Default function to return the current user oauth token
from session cookie.
"""
token = session.get("oauth")
log.debug("Token Get: {0}".format(token))
return token | Default function to return the current user oauth token
from session cookie. | Below is the the instruction that describes the task:
### Input:
Default function to return the current user oauth token
from session cookie.
### Response:
def _oauth_tokengetter(token=None):
"""
Default function to return the current user oauth token
from session cookie.
"""
to... |
def dataset(self):
"""A Tablib Dataset containing the row."""
data = tablib.Dataset()
data.headers = self.keys()
row = _reduce_datetimes(self.values())
data.append(row)
return data | A Tablib Dataset containing the row. | Below is the the instruction that describes the task:
### Input:
A Tablib Dataset containing the row.
### Response:
def dataset(self):
"""A Tablib Dataset containing the row."""
data = tablib.Dataset()
data.headers = self.keys()
row = _reduce_datetimes(self.values())
data.a... |
def _quantile_function(self, alpha=0.5, smallest_count=None):
"""Return a function that returns the quantile values for this
histogram.
"""
total = float(self.total())
smallest_observed_count = min(itervalues(self))
if smallest_count is None:
smallest_count ... | Return a function that returns the quantile values for this
histogram. | Below is the the instruction that describes the task:
### Input:
Return a function that returns the quantile values for this
histogram.
### Response:
def _quantile_function(self, alpha=0.5, smallest_count=None):
"""Return a function that returns the quantile values for this
histogram.
... |
def check_contiguity(w, neighbors, leaver):
"""Check if contiguity is maintained if leaver is removed from neighbors
Parameters
----------
w : spatial weights object
simple contiguity based weights
neighbors : list
nodes that are to be checked if th... | Check if contiguity is maintained if leaver is removed from neighbors
Parameters
----------
w : spatial weights object
simple contiguity based weights
neighbors : list
nodes that are to be checked if they form a single \
connec... | Below is the the instruction that describes the task:
### Input:
Check if contiguity is maintained if leaver is removed from neighbors
Parameters
----------
w : spatial weights object
simple contiguity based weights
neighbors : list
nodes that are t... |
def update(self, new_details, old_details=None):
''' a method to upsert changes to a record in the table
:param new_details: dictionary with updated record fields
:param old_details: [optional] dictionary with original record fields
:return: list of dictionaries with u... | a method to upsert changes to a record in the table
:param new_details: dictionary with updated record fields
:param old_details: [optional] dictionary with original record fields
:return: list of dictionaries with updated field details
NOTE: if old_details is empty,... | Below is the the instruction that describes the task:
### Input:
a method to upsert changes to a record in the table
:param new_details: dictionary with updated record fields
:param old_details: [optional] dictionary with original record fields
:return: list of dictionaries with up... |
def get_device_info(self, bigip):
'''Get device information about a specific BigIP device.
:param bigip: bigip object --- device to inspect
:returns: bigip object
'''
coll = bigip.tm.cm.devices.get_collection()
device = [device for device in coll if device.selfDevice ==... | Get device information about a specific BigIP device.
:param bigip: bigip object --- device to inspect
:returns: bigip object | Below is the the instruction that describes the task:
### Input:
Get device information about a specific BigIP device.
:param bigip: bigip object --- device to inspect
:returns: bigip object
### Response:
def get_device_info(self, bigip):
'''Get device information about a specific BigIP de... |
def _fetch_result(self):
"""
Fetch the queried object.
"""
self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params) | Fetch the queried object. | Below is the the instruction that describes the task:
### Input:
Fetch the queried object.
### Response:
def _fetch_result(self):
"""
Fetch the queried object.
"""
self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params) |
def groupby_task_class(self):
"""
Returns a dictionary mapping the task class to the list of tasks in the flow
"""
# Find all Task classes
class2tasks = OrderedDict()
for task in self.iflat_tasks():
cls = task.__class__
if cls not in class2tasks: c... | Returns a dictionary mapping the task class to the list of tasks in the flow | Below is the the instruction that describes the task:
### Input:
Returns a dictionary mapping the task class to the list of tasks in the flow
### Response:
def groupby_task_class(self):
"""
Returns a dictionary mapping the task class to the list of tasks in the flow
"""
# Find all T... |
def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is... | Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted. | Below is the the instruction that describes the task:
### Input:
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
act... |
def get_current(self, layout=None, network=None, verbose=False):
"""
Returns the current view or null if there is none.
:param verbose: print more
:returns: current view or null if there is none
"""
PARAMS={}
response=api(url=self.__url+"/get_current", PARAMS=PA... | Returns the current view or null if there is none.
:param verbose: print more
:returns: current view or null if there is none | Below is the the instruction that describes the task:
### Input:
Returns the current view or null if there is none.
:param verbose: print more
:returns: current view or null if there is none
### Response:
def get_current(self, layout=None, network=None, verbose=False):
"""
Returns... |
def connect(self):
"""Connect to vCenter server"""
try:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
if self.config['no_ssl_verify']:
requests.packages.urllib3.disable_warnings()
context.verify_mode = ssl.CERT_NONE
self.si = Smart... | Connect to vCenter server | Below is the the instruction that describes the task:
### Input:
Connect to vCenter server
### Response:
def connect(self):
"""Connect to vCenter server"""
try:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
if self.config['no_ssl_verify']:
requests.packages.... |
def _get_extension_loader_mapping(self):
"""
:return: Mappings of format extension and loader class.
:rtype: dict
"""
loader_table = self._get_common_loader_mapping()
loader_table.update(
{
"htm": HtmlTableFileLoader,
"md": Mar... | :return: Mappings of format extension and loader class.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
:return: Mappings of format extension and loader class.
:rtype: dict
### Response:
def _get_extension_loader_mapping(self):
"""
:return: Mappings of format extension and loader class.
:rtype: dict
"""
... |
def upload(
cls, files, metadata=None, tags=None, project=None, coerce_ascii=False, progressbar=None
):
"""Uploads a series of files to the One Codex server.
Parameters
----------
files : `string` or `tuple`
A single path to a file on the system, or a tuple conta... | Uploads a series of files to the One Codex server.
Parameters
----------
files : `string` or `tuple`
A single path to a file on the system, or a tuple containing a pairs of paths. Tuple
values will be interleaved as paired-end reads and both files should contain the sam... | Below is the the instruction that describes the task:
### Input:
Uploads a series of files to the One Codex server.
Parameters
----------
files : `string` or `tuple`
A single path to a file on the system, or a tuple containing a pairs of paths. Tuple
values will be ... |
def _setUpElements(self):
"""TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
... | TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: should only supp... | Below is the the instruction that describes the task:
### Input:
TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model gr... |
def related(self, domain):
'''Get the related domains of the given domain.
For details, see https://investigate.umbrella.com/docs/api#relatedDomains
'''
uri = self._uris["related"].format(domain)
return self.get_parse(uri) | Get the related domains of the given domain.
For details, see https://investigate.umbrella.com/docs/api#relatedDomains | Below is the the instruction that describes the task:
### Input:
Get the related domains of the given domain.
For details, see https://investigate.umbrella.com/docs/api#relatedDomains
### Response:
def related(self, domain):
'''Get the related domains of the given domain.
For details, see... |
def get_absolute_path(cls, roots, path):
"""Returns the absolute location of ``path`` relative to one of
the ``roots``.
``roots`` is the path configured for this `StaticFileHandler`
(in most cases the ``static_path`` `Application` setting).
"""
for root in roots:
... | Returns the absolute location of ``path`` relative to one of
the ``roots``.
``roots`` is the path configured for this `StaticFileHandler`
(in most cases the ``static_path`` `Application` setting). | Below is the the instruction that describes the task:
### Input:
Returns the absolute location of ``path`` relative to one of
the ``roots``.
``roots`` is the path configured for this `StaticFileHandler`
(in most cases the ``static_path`` `Application` setting).
### Response:
def get_absolu... |
def _build_message(self):
"""
Build different type of Dingding message
As most commonly used type, text message just need post message content
rather than a dict like ``{'content': 'message'}``
"""
if self.message_type in ['text', 'markdown']:
data = {
... | Build different type of Dingding message
As most commonly used type, text message just need post message content
rather than a dict like ``{'content': 'message'}`` | Below is the the instruction that describes the task:
### Input:
Build different type of Dingding message
As most commonly used type, text message just need post message content
rather than a dict like ``{'content': 'message'}``
### Response:
def _build_message(self):
"""
Build diff... |
def cluster_node_add(node, extra_args=None):
'''
Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_node_add... | Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_node_add node=node2.example.org | Below is the the instruction that describes the task:
### Input:
Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.clus... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.