code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def from_epsg_code(code):
"""
Load crs object from epsg code, via spatialreference.org.
Parses based on the proj4 representation.
Arguments:
- *code*: The EPSG code as an integer.
Returns:
- A CS instance of the indicated type.
"""
# must go online (or look up local table) to ge... | Load crs object from epsg code, via spatialreference.org.
Parses based on the proj4 representation.
Arguments:
- *code*: The EPSG code as an integer.
Returns:
- A CS instance of the indicated type. | Below is the the instruction that describes the task:
### Input:
Load crs object from epsg code, via spatialreference.org.
Parses based on the proj4 representation.
Arguments:
- *code*: The EPSG code as an integer.
Returns:
- A CS instance of the indicated type.
### Response:
def from_epsg_... |
def get_name(self):
"""
Tries to get WF name from 'process' or 'collobration' or 'pariticipant'
Returns:
str. WF name.
"""
paths = ['bpmn:process',
'bpmn:collaboration/bpmn:participant/',
'bpmn:collaboration',
]
... | Tries to get WF name from 'process' or 'collobration' or 'pariticipant'
Returns:
str. WF name. | Below is the the instruction that describes the task:
### Input:
Tries to get WF name from 'process' or 'collobration' or 'pariticipant'
Returns:
str. WF name.
### Response:
def get_name(self):
"""
Tries to get WF name from 'process' or 'collobration' or 'pariticipant'
... |
def send(mail, server='localhost'):
"""
Sends the given mail.
:type mail: Mail
:param mail: The mail object.
:type server: string
:param server: The address of the mailserver.
"""
sender = mail.get_sender()
rcpt = mail.get_receipients()
session = smtplib.SMTP(server)
messa... | Sends the given mail.
:type mail: Mail
:param mail: The mail object.
:type server: string
:param server: The address of the mailserver. | Below is the the instruction that describes the task:
### Input:
Sends the given mail.
:type mail: Mail
:param mail: The mail object.
:type server: string
:param server: The address of the mailserver.
### Response:
def send(mail, server='localhost'):
"""
Sends the given mail.
:type ... |
def _play(self):
"""Send play command to receiver command via HTTP post."""
# Use pause command only for sources which support NETAUDIO
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurEnter",
"cmd1": "aspMainZone_WebUpdateSt... | Send play command to receiver command via HTTP post. | Below is the the instruction that describes the task:
### Input:
Send play command to receiver command via HTTP post.
### Response:
def _play(self):
"""Send play command to receiver command via HTTP post."""
# Use pause command only for sources which support NETAUDIO
if self._input_func in ... |
def get_block_containing_tx(self, txid):
"""Retrieve the list of blocks (block ids) containing a
transaction with transaction id `txid`
Args:
txid (str): transaction id of the transaction to query
Returns:
Block id list (list(int))
"""
blocks ... | Retrieve the list of blocks (block ids) containing a
transaction with transaction id `txid`
Args:
txid (str): transaction id of the transaction to query
Returns:
Block id list (list(int)) | Below is the the instruction that describes the task:
### Input:
Retrieve the list of blocks (block ids) containing a
transaction with transaction id `txid`
Args:
txid (str): transaction id of the transaction to query
Returns:
Block id list (list(int))
### Respon... |
def append(self, position, array):
"""Append an array to the end of the map. The position
must be greater than any positions in the map"""
if not Gauged.map_append(self.ptr, position, array.ptr):
raise MemoryError | Append an array to the end of the map. The position
must be greater than any positions in the map | Below is the the instruction that describes the task:
### Input:
Append an array to the end of the map. The position
must be greater than any positions in the map
### Response:
def append(self, position, array):
"""Append an array to the end of the map. The position
must be greater than any... |
def setWorkingPlayAreaSize(self, sizeX, sizeZ):
"""Sets the Play Area in the working copy."""
fn = self.function_table.setWorkingPlayAreaSize
fn(sizeX, sizeZ) | Sets the Play Area in the working copy. | Below is the the instruction that describes the task:
### Input:
Sets the Play Area in the working copy.
### Response:
def setWorkingPlayAreaSize(self, sizeX, sizeZ):
"""Sets the Play Area in the working copy."""
fn = self.function_table.setWorkingPlayAreaSize
fn(sizeX, sizeZ) |
def DICOMfile_read(self, *args, **kwargs):
"""
Read a DICOM file and perform some initial
parsing of tags.
NB!
For thread safety, class member variables
should not be assigned since other threads
might override/change these variables in mid-
flight!
... | Read a DICOM file and perform some initial
parsing of tags.
NB!
For thread safety, class member variables
should not be assigned since other threads
might override/change these variables in mid-
flight! | Below is the the instruction that describes the task:
### Input:
Read a DICOM file and perform some initial
parsing of tags.
NB!
For thread safety, class member variables
should not be assigned since other threads
might override/change these variables in mid-
flight!... |
def tabify(text, options):
""" tabify(text : str, options : argparse.Namespace|str) -> str
>>> tabify(' (println "hello world")', '--tab=3')
'\t\t (println "hello world")'
Replace spaces with tabs
"""
opts = parse_options(options)
if opts.tab_size < 1:
return text
else... | tabify(text : str, options : argparse.Namespace|str) -> str
>>> tabify(' (println "hello world")', '--tab=3')
'\t\t (println "hello world")'
Replace spaces with tabs | Below is the the instruction that describes the task:
### Input:
tabify(text : str, options : argparse.Namespace|str) -> str
>>> tabify(' (println "hello world")', '--tab=3')
'\t\t (println "hello world")'
Replace spaces with tabs
### Response:
def tabify(text, options):
""" tabify(text ... |
def _glfw_get_version(filename):
'''
Queries and returns the library version tuple or None by using a
subprocess.
'''
version_checker_source = """
import sys
import ctypes
def get_version(library_handle):
'''
Queries and returns the library version tu... | Queries and returns the library version tuple or None by using a
subprocess. | Below is the the instruction that describes the task:
### Input:
Queries and returns the library version tuple or None by using a
subprocess.
### Response:
def _glfw_get_version(filename):
'''
Queries and returns the library version tuple or None by using a
subprocess.
'''
version_checker_s... |
def _get_regex_pattern(label):
"""Return a regular expression of the label.
This takes care of plural and different kinds of separators.
"""
parts = _split_by_punctuation.split(label)
for index, part in enumerate(parts):
if index % 2 == 0:
# Word
if not parts[index]... | Return a regular expression of the label.
This takes care of plural and different kinds of separators. | Below is the the instruction that describes the task:
### Input:
Return a regular expression of the label.
This takes care of plural and different kinds of separators.
### Response:
def _get_regex_pattern(label):
"""Return a regular expression of the label.
This takes care of plural and different kin... |
def _list_templates(settings):
"""
List templates from settings.
"""
for idx, option in enumerate(settings.config.get("project_templates"), start=1):
puts(" {0!s:5} {1!s:36}".format(
colored.yellow("[{0}]".format(idx)),
colored.cyan(option.get("name"))
))
... | List templates from settings. | Below is the the instruction that describes the task:
### Input:
List templates from settings.
### Response:
def _list_templates(settings):
"""
List templates from settings.
"""
for idx, option in enumerate(settings.config.get("project_templates"), start=1):
puts(" {0!s:5} {1!s:36}".format... |
def delete_comment(repo: GithubRepository, comment_id: int) -> None:
"""
References:
https://developer.github.com/v3/issues/comments/#delete-a-comment
"""
url = ("https://api.github.com/repos/{}/{}/issues/comments/{}"
"?access_token={}".format(repo.organization,
... | References:
https://developer.github.com/v3/issues/comments/#delete-a-comment | Below is the the instruction that describes the task:
### Input:
References:
https://developer.github.com/v3/issues/comments/#delete-a-comment
### Response:
def delete_comment(repo: GithubRepository, comment_id: int) -> None:
"""
References:
https://developer.github.com/v3/issues/comments/#... |
def shutdown(self):
"""
Shutdown the application and exit
:returns: No return value
"""
task = asyncio.ensure_future(self.core.shutdown())
self.loop.run_until_complete(task) | Shutdown the application and exit
:returns: No return value | Below is the the instruction that describes the task:
### Input:
Shutdown the application and exit
:returns: No return value
### Response:
def shutdown(self):
"""
Shutdown the application and exit
:returns: No return value
"""
task = asyncio.ensure_future(self.core... |
def min(self, constraints, X: BitVec, M=10000):
"""
Iteratively finds the minimum value for a symbol within given constraints.
:param constraints: constraints that the expression must fulfil
:param X: a symbol or expression
:param M: maximum number of iterations allowed
... | Iteratively finds the minimum value for a symbol within given constraints.
:param constraints: constraints that the expression must fulfil
:param X: a symbol or expression
:param M: maximum number of iterations allowed | Below is the the instruction that describes the task:
### Input:
Iteratively finds the minimum value for a symbol within given constraints.
:param constraints: constraints that the expression must fulfil
:param X: a symbol or expression
:param M: maximum number of iterations allowed
### Res... |
def select_ipam_strategy(self, network_id, network_strategy, **kwargs):
"""Return relevant IPAM strategy name.
:param network_id: neutron network id.
:param network_strategy: default strategy for the network.
NOTE(morgabra) This feels like a hack but I can't think of a better
i... | Return relevant IPAM strategy name.
:param network_id: neutron network id.
:param network_strategy: default strategy for the network.
NOTE(morgabra) This feels like a hack but I can't think of a better
idea. The root problem is we can now attach ports to networks with
a differe... | Below is the the instruction that describes the task:
### Input:
Return relevant IPAM strategy name.
:param network_id: neutron network id.
:param network_strategy: default strategy for the network.
NOTE(morgabra) This feels like a hack but I can't think of a better
idea. The root ... |
def generate_events_list(generator):
"""Populate the event_list variable to be used in jinja templates"""
if not localized_events:
generator.context['events_list'] = sorted(events, reverse = True,
key=lambda ev: (ev.dtstart, ev.dtend))
else:
... | Populate the event_list variable to be used in jinja templates | Below is the the instruction that describes the task:
### Input:
Populate the event_list variable to be used in jinja templates
### Response:
def generate_events_list(generator):
"""Populate the event_list variable to be used in jinja templates"""
if not localized_events:
generator.context['events... |
def __setup(local_download_dir_warc, log_level):
"""
Setup
:return:
"""
if not os.path.exists(local_download_dir_warc):
os.makedirs(local_download_dir_warc)
# make loggers quite
configure_logging({"LOG_LEVEL": "ERROR"})
logging.getLogger('requests').setLevel(logging.CRITICAL)
... | Setup
:return: | Below is the the instruction that describes the task:
### Input:
Setup
:return:
### Response:
def __setup(local_download_dir_warc, log_level):
"""
Setup
:return:
"""
if not os.path.exists(local_download_dir_warc):
os.makedirs(local_download_dir_warc)
# make loggers quite
co... |
def asset(self, id):
"""Returns a single Asset.
:param int id: (required), id of the asset
:returns: :class:`Asset <github3.repos.release.Asset>`
"""
data = None
if int(id) > 0:
url = self._build_url('releases', 'assets', str(id),
... | Returns a single Asset.
:param int id: (required), id of the asset
:returns: :class:`Asset <github3.repos.release.Asset>` | Below is the the instruction that describes the task:
### Input:
Returns a single Asset.
:param int id: (required), id of the asset
:returns: :class:`Asset <github3.repos.release.Asset>`
### Response:
def asset(self, id):
"""Returns a single Asset.
:param int id: (required), id of... |
def deepcp(data):
"""Use ujson to do deep_copy"""
import ujson
try:
return ujson.loads(ujson.dumps(data))
except Exception:
return copy.deepcopy(data) | Use ujson to do deep_copy | Below is the the instruction that describes the task:
### Input:
Use ujson to do deep_copy
### Response:
def deepcp(data):
"""Use ujson to do deep_copy"""
import ujson
try:
return ujson.loads(ujson.dumps(data))
except Exception:
return copy.deepcopy(data) |
def bookmark(ctx):
"""Bookmark build job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon build bookmark
```
\b
```bash
$ polyaxon build -b 2 bookmark
```
"""
user, project_name, _build = get_build_or_local(ctx.obj.get('project'),... | Bookmark build job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon build bookmark
```
\b
```bash
$ polyaxon build -b 2 bookmark
``` | Below is the the instruction that describes the task:
### Input:
Bookmark build job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon build bookmark
```
\b
```bash
$ polyaxon build -b 2 bookmark
```
### Response:
def bookmark(ctx):
""... |
def tuples(stream, *keys):
"""Reformat data as tuples.
Parameters
----------
stream : iterable
Stream of data objects.
*keys : strings
Keys to use for ordering data.
Yields
------
items : tuple of np.ndarrays
Data object reformated as a tuple.
Raises
-... | Reformat data as tuples.
Parameters
----------
stream : iterable
Stream of data objects.
*keys : strings
Keys to use for ordering data.
Yields
------
items : tuple of np.ndarrays
Data object reformated as a tuple.
Raises
------
DataError
If the... | Below is the the instruction that describes the task:
### Input:
Reformat data as tuples.
Parameters
----------
stream : iterable
Stream of data objects.
*keys : strings
Keys to use for ordering data.
Yields
------
items : tuple of np.ndarrays
Data object refor... |
def find_malformed_single_file_project(self): # type: () -> List[str]
"""
Take first non-setup.py python file. What a mess.
:return:
"""
files = [f for f in os.listdir(".") if os.path.isfile(f)]
candidates = []
# project misnamed & not in setup.py
for f... | Take first non-setup.py python file. What a mess.
:return: | Below is the the instruction that describes the task:
### Input:
Take first non-setup.py python file. What a mess.
:return:
### Response:
def find_malformed_single_file_project(self): # type: () -> List[str]
"""
Take first non-setup.py python file. What a mess.
:return:
"""... |
def add_section(self, section_name):
"""Create a section of the report, to be headed by section_name
Text and images can be added by using the `section` argument of the
`add_text` and `add_image` methods. Sections can also be ordered by
using the `set_section_order` method.
By ... | Create a section of the report, to be headed by section_name
Text and images can be added by using the `section` argument of the
`add_text` and `add_image` methods. Sections can also be ordered by
using the `set_section_order` method.
By default, text and images that have no section wi... | Below is the the instruction that describes the task:
### Input:
Create a section of the report, to be headed by section_name
Text and images can be added by using the `section` argument of the
`add_text` and `add_image` methods. Sections can also be ordered by
using the `set_section_order`... |
def pop_message(self, till=None):
"""
RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE
DUMMY IMPLEMENTATION FOR DEBUGGING
"""
if till is not None and not isinstance(till, Signal):
Log.error("Expecting a signal")
ret... | RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE
DUMMY IMPLEMENTATION FOR DEBUGGING | Below is the the instruction that describes the task:
### Input:
RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE
DUMMY IMPLEMENTATION FOR DEBUGGING
### Response:
def pop_message(self, till=None):
"""
RETURN TUPLE (message, payload) CALLER IS RESP... |
def aggregationDivide(dividend, divisor):
"""
Return the result from dividing two dicts that represent date and time.
Both dividend and divisor are dicts that contain one or more of the following
keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',
'milliseconds', 'microseconds'.
For ex... | Return the result from dividing two dicts that represent date and time.
Both dividend and divisor are dicts that contain one or more of the following
keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',
'milliseconds', 'microseconds'.
For example:
::
aggregationDivide({'hours': 4}, ... | Below is the the instruction that describes the task:
### Input:
Return the result from dividing two dicts that represent date and time.
Both dividend and divisor are dicts that contain one or more of the following
keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',
'milliseconds', 'micro... |
def parse_config(self):
"""
Parse the xml file with remote servers and discover resources on each found server.
"""
tree = ElementTree.parse(self.file_xml)
root = tree.getroot()
for server in root.findall('server'):
destination = server.text
name =... | Parse the xml file with remote servers and discover resources on each found server. | Below is the the instruction that describes the task:
### Input:
Parse the xml file with remote servers and discover resources on each found server.
### Response:
def parse_config(self):
"""
Parse the xml file with remote servers and discover resources on each found server.
"""
tree... |
def create_key_file(path):
"""
Creates a new encryption key in the path provided and sets the file
permissions. Setting the file permissions currently does not work
on Windows platforms because of the differences in how file
permissions are read and modified.
"""
iv = "{}{}".format(os.urand... | Creates a new encryption key in the path provided and sets the file
permissions. Setting the file permissions currently does not work
on Windows platforms because of the differences in how file
permissions are read and modified. | Below is the the instruction that describes the task:
### Input:
Creates a new encryption key in the path provided and sets the file
permissions. Setting the file permissions currently does not work
on Windows platforms because of the differences in how file
permissions are read and modified.
### Respo... |
def outlineColor(self, value):
"""gets/sets the outlineColor"""
if isinstance(value, Color) and \
not self._outline is None:
self._outline['color'] = value | gets/sets the outlineColor | Below is the the instruction that describes the task:
### Input:
gets/sets the outlineColor
### Response:
def outlineColor(self, value):
"""gets/sets the outlineColor"""
if isinstance(value, Color) and \
not self._outline is None:
self._outline['color'] = value |
def extend_with(func):
"""Extends with class or function"""
if not func.__name__ in ArgParseInator._plugins:
ArgParseInator._plugins[func.__name__] = func | Extends with class or function | Below is the the instruction that describes the task:
### Input:
Extends with class or function
### Response:
def extend_with(func):
"""Extends with class or function"""
if not func.__name__ in ArgParseInator._plugins:
ArgParseInator._plugins[func.__name__] = func |
def stop(self):
"""
Stops the connection
"""
self.__stop = True
self._queue.stop()
self._zk.stop() | Stops the connection | Below is the the instruction that describes the task:
### Input:
Stops the connection
### Response:
def stop(self):
"""
Stops the connection
"""
self.__stop = True
self._queue.stop()
self._zk.stop() |
def create_annotation(timestamp, value, host):
"""
Create a zipkin annotation object
:param timestamp: timestamp of when the annotation occured in microseconds
:param value: name of the annotation, such as 'sr'
:param host: zipkin endpoint object
:returns: zipkin annotation object
"""
... | Create a zipkin annotation object
:param timestamp: timestamp of when the annotation occured in microseconds
:param value: name of the annotation, such as 'sr'
:param host: zipkin endpoint object
:returns: zipkin annotation object | Below is the the instruction that describes the task:
### Input:
Create a zipkin annotation object
:param timestamp: timestamp of when the annotation occured in microseconds
:param value: name of the annotation, such as 'sr'
:param host: zipkin endpoint object
:returns: zipkin annotation object
##... |
def get_formset(self):
"""Provide the formset corresponding to this DataTable.
Use this to validate the formset and to get the submitted data back.
"""
if self._formset is None:
self._formset = self.formset_class(
self.request.POST or None,
in... | Provide the formset corresponding to this DataTable.
Use this to validate the formset and to get the submitted data back. | Below is the the instruction that describes the task:
### Input:
Provide the formset corresponding to this DataTable.
Use this to validate the formset and to get the submitted data back.
### Response:
def get_formset(self):
"""Provide the formset corresponding to this DataTable.
Use this ... |
def summarizePosition(self, index):
"""
Compute residue counts at a specific sequence index.
@param index: an C{int} index into the sequence.
@return: A C{dict} with the count of too-short (excluded) sequences,
and a Counter instance giving the residue counts.
"""
... | Compute residue counts at a specific sequence index.
@param index: an C{int} index into the sequence.
@return: A C{dict} with the count of too-short (excluded) sequences,
and a Counter instance giving the residue counts. | Below is the the instruction that describes the task:
### Input:
Compute residue counts at a specific sequence index.
@param index: an C{int} index into the sequence.
@return: A C{dict} with the count of too-short (excluded) sequences,
and a Counter instance giving the residue counts.
#... |
def _snakify_name(self, name):
"""Snakify a name string.
In this context, "to snakify" means to strip a name of all
diacritics, convert it to lower case, and replace any spaces
inside the name with hyphens.
This way the name is made "machine-friendly", and ready to be
c... | Snakify a name string.
In this context, "to snakify" means to strip a name of all
diacritics, convert it to lower case, and replace any spaces
inside the name with hyphens.
This way the name is made "machine-friendly", and ready to be
combined with a second name component into ... | Below is the the instruction that describes the task:
### Input:
Snakify a name string.
In this context, "to snakify" means to strip a name of all
diacritics, convert it to lower case, and replace any spaces
inside the name with hyphens.
This way the name is made "machine-friendly"... |
def make(parser):
"""
Install Ceph packages on remote hosts.
"""
version = parser.add_mutually_exclusive_group()
# XXX deprecated in favor of release
version.add_argument(
'--stable',
nargs='?',
action=StoreVersion,
metavar='CODENAME',
help='[DEPRECATED]... | Install Ceph packages on remote hosts. | Below is the the instruction that describes the task:
### Input:
Install Ceph packages on remote hosts.
### Response:
def make(parser):
"""
Install Ceph packages on remote hosts.
"""
version = parser.add_mutually_exclusive_group()
# XXX deprecated in favor of release
version.add_argument(... |
def _get_envs_from_ref_paths(self, refs):
'''
Return the names of remote refs (stripped of the remote name) and tags
which are map to the branches and tags.
'''
def _check_ref(env_set, rname):
'''
Add the appropriate saltenv(s) to the set
'''
... | Return the names of remote refs (stripped of the remote name) and tags
which are map to the branches and tags. | Below is the the instruction that describes the task:
### Input:
Return the names of remote refs (stripped of the remote name) and tags
which are map to the branches and tags.
### Response:
def _get_envs_from_ref_paths(self, refs):
'''
Return the names of remote refs (stripped of the remote... |
def get_account_invitation(self, account_id, invitation_id, **kwargs): # noqa: E501
"""Details of a user invitation. # noqa: E501
An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-... | Details of a user invitation. # noqa: E501
An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{account-id}/user-invitations/{invitation-id} -H 'Authorization: Bea... | Below is the the instruction that describes the task:
### Input:
Details of a user invitation. # noqa: E501
An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts... |
def get_path_contents(self, project, provider_name, service_endpoint_id=None, repository=None, commit_or_branch=None, path=None):
"""GetPathContents.
[Preview API] Gets the contents of a directory in the given source code repository.
:param str project: Project ID or project name
:param ... | GetPathContents.
[Preview API] Gets the contents of a directory in the given source code repository.
:param str project: Project ID or project name
:param str provider_name: The name of the source provider.
:param str service_endpoint_id: If specified, the ID of the service endpoint to q... | Below is the the instruction that describes the task:
### Input:
GetPathContents.
[Preview API] Gets the contents of a directory in the given source code repository.
:param str project: Project ID or project name
:param str provider_name: The name of the source provider.
:param str s... |
def get_pager_spec(self):
""" Find the best pager settings for this command. If the user has
specified overrides in the INI config file we prefer those. """
self_config = self.get_config()
pagercmd = self_config.get('pager')
istty = self_config.getboolean('pager_istty')
... | Find the best pager settings for this command. If the user has
specified overrides in the INI config file we prefer those. | Below is the the instruction that describes the task:
### Input:
Find the best pager settings for this command. If the user has
specified overrides in the INI config file we prefer those.
### Response:
def get_pager_spec(self):
""" Find the best pager settings for this command. If the user has
... |
def resolve(self, symbol):
"""
Resolve a symbol using the entrypoint group.
:param symbol: The symbol being resolved.
:returns: The value of that symbol. If the symbol cannot be
found, or if no entrypoint group was passed to the
constructor, will re... | Resolve a symbol using the entrypoint group.
:param symbol: The symbol being resolved.
:returns: The value of that symbol. If the symbol cannot be
found, or if no entrypoint group was passed to the
constructor, will return ``None``. | Below is the the instruction that describes the task:
### Input:
Resolve a symbol using the entrypoint group.
:param symbol: The symbol being resolved.
:returns: The value of that symbol. If the symbol cannot be
found, or if no entrypoint group was passed to the
... |
def unmount_loopbacks(self):
"""Unmounts all loopback devices as identified by :func:`find_loopbacks`"""
# re-index loopback devices
self._index_loopbacks()
for dev in self.find_loopbacks():
_util.check_output_(['losetup', '-d', dev]) | Unmounts all loopback devices as identified by :func:`find_loopbacks` | Below is the the instruction that describes the task:
### Input:
Unmounts all loopback devices as identified by :func:`find_loopbacks`
### Response:
def unmount_loopbacks(self):
"""Unmounts all loopback devices as identified by :func:`find_loopbacks`"""
# re-index loopback devices
self._in... |
def get_exit_code(self):
"""
@rtype: int
@return: Process exit code, or C{STILL_ACTIVE} if it's still alive.
@warning: If a process returns C{STILL_ACTIVE} as it's exit code,
you may not be able to determine if it's active or not with this
method. Use L{is_alive... | @rtype: int
@return: Process exit code, or C{STILL_ACTIVE} if it's still alive.
@warning: If a process returns C{STILL_ACTIVE} as it's exit code,
you may not be able to determine if it's active or not with this
method. Use L{is_alive} to check if the process is still active.
... | Below is the the instruction that describes the task:
### Input:
@rtype: int
@return: Process exit code, or C{STILL_ACTIVE} if it's still alive.
@warning: If a process returns C{STILL_ACTIVE} as it's exit code,
you may not be able to determine if it's active or not with this
... |
def create_port_postcommit(self, context):
"""Create port non-database commit event."""
# No new events are handled until replay
# thread has put the switch in active state.
# If a switch is in active state, verify
# the switch is still in active state
# before accepting... | Create port non-database commit event. | Below is the the instruction that describes the task:
### Input:
Create port non-database commit event.
### Response:
def create_port_postcommit(self, context):
"""Create port non-database commit event."""
# No new events are handled until replay
# thread has put the switch in active state... |
def proc_collector(process_map, args, pipeline_string):
"""
Function that collects all processes available and stores a dictionary of
the required arguments of each process class to be passed to
procs_dict_parser
Parameters
----------
process_map: dict
The dictionary with the Proces... | Function that collects all processes available and stores a dictionary of
the required arguments of each process class to be passed to
procs_dict_parser
Parameters
----------
process_map: dict
The dictionary with the Processes currently available in flowcraft
and their corresponding... | Below is the the instruction that describes the task:
### Input:
Function that collects all processes available and stores a dictionary of
the required arguments of each process class to be passed to
procs_dict_parser
Parameters
----------
process_map: dict
The dictionary with the Proce... |
def write(obj, data=None, **kwargs):
"""Write a value in to loader source
:param obj: settings object
:param data: vars to be stored
:param kwargs: vars to be stored
:return:
"""
if obj.REDIS_ENABLED_FOR_DYNACONF is False:
raise RuntimeError(
"Redis is not configured \n"... | Write a value in to loader source
:param obj: settings object
:param data: vars to be stored
:param kwargs: vars to be stored
:return: | Below is the the instruction that describes the task:
### Input:
Write a value in to loader source
:param obj: settings object
:param data: vars to be stored
:param kwargs: vars to be stored
:return:
### Response:
def write(obj, data=None, **kwargs):
"""Write a value in to loader source
:... |
def _UploadChunk(self, chunk):
"""Uploads a single chunk to the transfer store flow.
Args:
chunk: A chunk to upload.
Returns:
A `BlobImageChunkDescriptor` object.
"""
blob = _CompressedDataBlob(chunk)
self._action.ChargeBytesToSession(len(chunk.data))
self._action.SendReply(bl... | Uploads a single chunk to the transfer store flow.
Args:
chunk: A chunk to upload.
Returns:
A `BlobImageChunkDescriptor` object. | Below is the the instruction that describes the task:
### Input:
Uploads a single chunk to the transfer store flow.
Args:
chunk: A chunk to upload.
Returns:
A `BlobImageChunkDescriptor` object.
### Response:
def _UploadChunk(self, chunk):
"""Uploads a single chunk to the transfer store fl... |
def delete_field(field_uri):
"""
Helper function to request deletion of a field. This is necessary when you want to overwrite values instead of
appending.
<t:DeleteItemField>
<t:FieldURI FieldURI="calendar:Resources"/>
</t:DeleteItemField>
"""
root = T.DeleteItemField(
T.Fiel... | Helper function to request deletion of a field. This is necessary when you want to overwrite values instead of
appending.
<t:DeleteItemField>
<t:FieldURI FieldURI="calendar:Resources"/>
</t:DeleteItemField> | Below is the the instruction that describes the task:
### Input:
Helper function to request deletion of a field. This is necessary when you want to overwrite values instead of
appending.
<t:DeleteItemField>
<t:FieldURI FieldURI="calendar:Resources"/>
</t:DeleteItemField>
### Response:
de... |
def check_config(config, data):
'''Check config file inputs
:param dict config:
Configuration settings for the function
'''
essential_keys = ['input_mmin', 'b-value', 'sigma-b']
for key in essential_keys:
if not key in config.keys():
raise ValueError('For KijkoSellevol... | Check config file inputs
:param dict config:
Configuration settings for the function | Below is the the instruction that describes the task:
### Input:
Check config file inputs
:param dict config:
Configuration settings for the function
### Response:
def check_config(config, data):
'''Check config file inputs
:param dict config:
Configuration settings for the function... |
def _generate_phrases(self, sentences):
"""Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tu... | Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tuple is a collection
of words formi... | Below is the the instruction that describes the task:
### Input:
Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tu... |
def _lexists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._lstat(path))
except os.error:
return False | IMPORTANT: expects `path` to already be deref()'erenced. | Below is the the instruction that describes the task:
### Input:
IMPORTANT: expects `path` to already be deref()'erenced.
### Response:
def _lexists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._lstat(path))
except os.error:
return False |
def normalize_hex(hex_color):
"""Transform a xxx hex color to xxxxxx.
"""
hex_color = hex_color.replace('#', '').lower()
length = len(hex_color)
if length in (6, 8):
return '#' + hex_color
if length not in (3, 4):
return None
strhex = u'#%s%s%s' % (
hex_color[0] * 2,
... | Transform a xxx hex color to xxxxxx. | Below is the the instruction that describes the task:
### Input:
Transform a xxx hex color to xxxxxx.
### Response:
def normalize_hex(hex_color):
"""Transform a xxx hex color to xxxxxx.
"""
hex_color = hex_color.replace('#', '').lower()
length = len(hex_color)
if length in (6, 8):
retur... |
def _filter_dependencies_graph(self, internal):
"""build the internal or the external depedency graph"""
graph = collections.defaultdict(set)
for importee, importers in self.stats["dependencies"].items():
for importer in importers:
package = self._module_pkg.get(impor... | build the internal or the external depedency graph | Below is the the instruction that describes the task:
### Input:
build the internal or the external depedency graph
### Response:
def _filter_dependencies_graph(self, internal):
"""build the internal or the external depedency graph"""
graph = collections.defaultdict(set)
for importee, impor... |
def get_table_meta(self, db_patterns, tbl_patterns, tbl_types):
"""
Parameters:
- db_patterns
- tbl_patterns
- tbl_types
"""
self.send_get_table_meta(db_patterns, tbl_patterns, tbl_types)
return self.recv_get_table_meta() | Parameters:
- db_patterns
- tbl_patterns
- tbl_types | Below is the the instruction that describes the task:
### Input:
Parameters:
- db_patterns
- tbl_patterns
- tbl_types
### Response:
def get_table_meta(self, db_patterns, tbl_patterns, tbl_types):
"""
Parameters:
- db_patterns
- tbl_patterns
- tbl_types
"""
self.send_ge... |
def get(self, *args, **kwargs):
""" wraps the default get() and deals with encoding """
value, stat = super(XClient, self).get(*args, **kwargs)
try:
if value is not None:
value = value.decode(encoding="utf-8")
except UnicodeDecodeError:
pass
... | wraps the default get() and deals with encoding | Below is the the instruction that describes the task:
### Input:
wraps the default get() and deals with encoding
### Response:
def get(self, *args, **kwargs):
""" wraps the default get() and deals with encoding """
value, stat = super(XClient, self).get(*args, **kwargs)
try:
if... |
def _get_response_body_mime_type(self):
"""
Returns the response body MIME type. This might differ from the
overall response mime type e.g. in ATOM responses where the body
MIME type is XML.
"""
mime_type = self._get_response_mime_type()
if mime_type is AtomMime:
... | Returns the response body MIME type. This might differ from the
overall response mime type e.g. in ATOM responses where the body
MIME type is XML. | Below is the the instruction that describes the task:
### Input:
Returns the response body MIME type. This might differ from the
overall response mime type e.g. in ATOM responses where the body
MIME type is XML.
### Response:
def _get_response_body_mime_type(self):
"""
Returns the r... |
def link(origin=None, rel=None, value=None, attributes=None, source=None):
'''
Action function generator to create a link based on the context's current link, or on provided parameters
:param origin: IRI/string, or list of same; origins for the created relationships.
If None, the action context provide... | Action function generator to create a link based on the context's current link, or on provided parameters
:param origin: IRI/string, or list of same; origins for the created relationships.
If None, the action context provides the parameter.
:param rel: IRI/string, or list of same; IDs for the created rela... | Below is the the instruction that describes the task:
### Input:
Action function generator to create a link based on the context's current link, or on provided parameters
:param origin: IRI/string, or list of same; origins for the created relationships.
If None, the action context provides the parameter.
... |
def show(block=False):
"""Show current figures using vispy
Parameters
----------
block : bool
If True, blocking mode will be used. If False, then non-blocking
/ interactive mode will be used.
Returns
-------
canvases : list
List of the vispy canvases that were creat... | Show current figures using vispy
Parameters
----------
block : bool
If True, blocking mode will be used. If False, then non-blocking
/ interactive mode will be used.
Returns
-------
canvases : list
List of the vispy canvases that were created. | Below is the the instruction that describes the task:
### Input:
Show current figures using vispy
Parameters
----------
block : bool
If True, blocking mode will be used. If False, then non-blocking
/ interactive mode will be used.
Returns
-------
canvases : list
Lis... |
def cumprod(self, axis=0, *args, **kwargs):
"""
Cumulative product for each group.
"""
nv.validate_groupby_func('cumprod', args, kwargs,
['numeric_only', 'skipna'])
if axis != 0:
return self.apply(lambda x: x.cumprod(axis=axis, **kwarg... | Cumulative product for each group. | Below is the the instruction that describes the task:
### Input:
Cumulative product for each group.
### Response:
def cumprod(self, axis=0, *args, **kwargs):
"""
Cumulative product for each group.
"""
nv.validate_groupby_func('cumprod', args, kwargs,
... |
def _remove_init_all(r):
"""Remove any __all__ in __init__.py file."""
new_r = redbaron.NodeList()
for n in r.node_list:
if n.type == 'assignment' and n.target.value == '__all__':
pass
else:
new_r.append(n)
return new_r | Remove any __all__ in __init__.py file. | Below is the the instruction that describes the task:
### Input:
Remove any __all__ in __init__.py file.
### Response:
def _remove_init_all(r):
"""Remove any __all__ in __init__.py file."""
new_r = redbaron.NodeList()
for n in r.node_list:
if n.type == 'assignment' and n.target.value == '__all_... |
def shaddalike(partial, fully):
"""
If the two words has the same letters and the same harakats, this fuction return True.
The first word is partially vocalized, the second is fully
if the partially contians a shadda, it must be at the same place in the fully
@param partial: the partially vocaliz... | If the two words has the same letters and the same harakats, this fuction return True.
The first word is partially vocalized, the second is fully
if the partially contians a shadda, it must be at the same place in the fully
@param partial: the partially vocalized word
@type partial: unicode
@para... | Below is the the instruction that describes the task:
### Input:
If the two words has the same letters and the same harakats, this fuction return True.
The first word is partially vocalized, the second is fully
if the partially contians a shadda, it must be at the same place in the fully
@param parti... |
def get_latex_expression(s, pos, **parse_flags):
"""
Reads a latex expression, e.g. macro argument. This may be a single char, an escape
sequence, or a expression placed in braces.
Returns a tuple `(<LatexNode instance>, pos, len)`. `pos` is the first char of the
expression, and `len` is its length... | Reads a latex expression, e.g. macro argument. This may be a single char, an escape
sequence, or a expression placed in braces.
Returns a tuple `(<LatexNode instance>, pos, len)`. `pos` is the first char of the
expression, and `len` is its length.
.. deprecated:: 1.0
Please use :py:meth:`LatexW... | Below is the the instruction that describes the task:
### Input:
Reads a latex expression, e.g. macro argument. This may be a single char, an escape
sequence, or a expression placed in braces.
Returns a tuple `(<LatexNode instance>, pos, len)`. `pos` is the first char of the
expression, and `len` is it... |
def send_error(self, status_code: int = 500, **kwargs: Any) -> None:
"""Sends the given HTTP error code to the browser.
If `flush()` has already been called, it is not possible to send
an error, so this method will simply terminate the response.
If output has been written but not yet fl... | Sends the given HTTP error code to the browser.
If `flush()` has already been called, it is not possible to send
an error, so this method will simply terminate the response.
If output has been written but not yet flushed, it will be discarded
and replaced with the error page.
O... | Below is the the instruction that describes the task:
### Input:
Sends the given HTTP error code to the browser.
If `flush()` has already been called, it is not possible to send
an error, so this method will simply terminate the response.
If output has been written but not yet flushed, it w... |
def add(self, original_index, operation):
"""Add an operation to this Run instance.
:Parameters:
- `original_index`: The original index of this operation
within a larger bulk operation.
- `operation`: The operation document.
"""
self.index_map.append(orig... | Add an operation to this Run instance.
:Parameters:
- `original_index`: The original index of this operation
within a larger bulk operation.
- `operation`: The operation document. | Below is the the instruction that describes the task:
### Input:
Add an operation to this Run instance.
:Parameters:
- `original_index`: The original index of this operation
within a larger bulk operation.
- `operation`: The operation document.
### Response:
def add(self, o... |
def parse_voc_rec(filename):
"""
parse pascal voc record into a dictionary
:param filename: xml file path
:return: list of dict
"""
import xml.etree.ElementTree as ET
tree = ET.parse(filename)
objects = []
for obj in tree.findall('object'):
obj_dict = dict()
obj_dict[... | parse pascal voc record into a dictionary
:param filename: xml file path
:return: list of dict | Below is the the instruction that describes the task:
### Input:
parse pascal voc record into a dictionary
:param filename: xml file path
:return: list of dict
### Response:
def parse_voc_rec(filename):
"""
parse pascal voc record into a dictionary
:param filename: xml file path
:return: li... |
def update_project(self, project_id, name=None, description=None,
reference_language=None):
"""
Updates project settings (name, description, reference language)
If optional parameters are not sent, their respective fields are not updated.
"""
kwargs = {}
... | Updates project settings (name, description, reference language)
If optional parameters are not sent, their respective fields are not updated. | Below is the the instruction that describes the task:
### Input:
Updates project settings (name, description, reference language)
If optional parameters are not sent, their respective fields are not updated.
### Response:
def update_project(self, project_id, name=None, description=None,
... |
def bits_to_dict(bits):
"""Convert a Django template tag's kwargs into a dictionary of Python types.
The only necessary types are number, boolean, list, and string.
http://pygments.org/docs/formatters/#HtmlFormatter
from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='... | Convert a Django template tag's kwargs into a dictionary of Python types.
The only necessary types are number, boolean, list, and string.
http://pygments.org/docs/formatters/#HtmlFormatter
from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='[]'"]
to: {'style': 'mono... | Below is the the instruction that describes the task:
### Input:
Convert a Django template tag's kwargs into a dictionary of Python types.
The only necessary types are number, boolean, list, and string.
http://pygments.org/docs/formatters/#HtmlFormatter
from: ["style='monokai'", "cssclass='cssclass',"... |
def loadCommandMap(Class, subparsers=None, instantiate=True, **cmd_kwargs):
"""Instantiate each registered command to a dict mapping name/alias to
instance.
Due to aliases, the returned length may be greater there the number of
commands, but the unique instance count will match.
... | Instantiate each registered command to a dict mapping name/alias to
instance.
Due to aliases, the returned length may be greater there the number of
commands, but the unique instance count will match. | Below is the the instruction that describes the task:
### Input:
Instantiate each registered command to a dict mapping name/alias to
instance.
Due to aliases, the returned length may be greater there the number of
commands, but the unique instance count will match.
### Response:
def loadCo... |
def wrann(record_name, extension, sample, symbol=None, subtype=None, chan=None,
num=None, aux_note=None, label_store=None, fs=None,
custom_labels=None, write_dir=''):
"""
Write a WFDB annotation file.
Specify at least the following:
- The record name of the WFDB record (record_name... | Write a WFDB annotation file.
Specify at least the following:
- The record name of the WFDB record (record_name)
- The annotation file extension (extension)
- The annotation locations in samples relative to the beginning of
the record (sample)
- Either the numerical values used to store the ... | Below is the the instruction that describes the task:
### Input:
Write a WFDB annotation file.
Specify at least the following:
- The record name of the WFDB record (record_name)
- The annotation file extension (extension)
- The annotation locations in samples relative to the beginning of
the... |
def make_empty(self, axes=None):
""" return an empty BlockManager with the items axis of len 0 """
if axes is None:
axes = [ensure_index([])] + [ensure_index(a)
for a in self.axes[1:]]
# preserve dtype if possible
if self.ndim == 1:
... | return an empty BlockManager with the items axis of len 0 | Below is the the instruction that describes the task:
### Input:
return an empty BlockManager with the items axis of len 0
### Response:
def make_empty(self, axes=None):
""" return an empty BlockManager with the items axis of len 0 """
if axes is None:
axes = [ensure_index([])] + [ensur... |
def natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT):
"""
Sorts an iterable naturally.
Parameters
----------
seq : iterable
The input to sort.
key : callable, optional
A key used to determine how to sort each element of the iterable.
It is **not** applied recursi... | Sorts an iterable naturally.
Parameters
----------
seq : iterable
The input to sort.
key : callable, optional
A key used to determine how to sort each element of the iterable.
It is **not** applied recursively.
It should accept a single argument and return a single valu... | Below is the the instruction that describes the task:
### Input:
Sorts an iterable naturally.
Parameters
----------
seq : iterable
The input to sort.
key : callable, optional
A key used to determine how to sort each element of the iterable.
It is **not** applied recursively... |
def write_results(self, data, name=None):
"""
Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:para... | Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:param output: JSON object. | Below is the the instruction that describes the task:
### Input:
Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
... |
async def is_object_synced_to_cn(self, client, pid):
"""Check if object with {pid} has successfully synced to the CN.
CNRead.describe() is used as it's a light-weight HTTP HEAD request.
This assumes that the call is being made over a connection that has been
authenticated and has read ... | Check if object with {pid} has successfully synced to the CN.
CNRead.describe() is used as it's a light-weight HTTP HEAD request.
This assumes that the call is being made over a connection that has been
authenticated and has read or better access on the given object if it exists. | Below is the the instruction that describes the task:
### Input:
Check if object with {pid} has successfully synced to the CN.
CNRead.describe() is used as it's a light-weight HTTP HEAD request.
This assumes that the call is being made over a connection that has been
authenticated and has ... |
def main():
"""
Main function, called when run as an application.
"""
global args, server_address
# parse the command line arguments
parser = ArgumentParser(description=__doc__)
parser.add_argument(
"host", nargs='?',
help="address of host (default %r)" % (SERVER_HOST,),
... | Main function, called when run as an application. | Below is the the instruction that describes the task:
### Input:
Main function, called when run as an application.
### Response:
def main():
"""
Main function, called when run as an application.
"""
global args, server_address
# parse the command line arguments
parser = ArgumentParser(desc... |
def get_root_objective_bank_ids(self, alias):
"""Gets the root objective bank Ids in this hierarchy.
return: (osid.id.IdList) - the root objective bank Ids
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
compliance: mandatory... | Gets the root objective bank Ids in this hierarchy.
return: (osid.id.IdList) - the root objective bank Ids
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
compliance: mandatory - This method must be implemented. | Below is the the instruction that describes the task:
### Input:
Gets the root objective bank Ids in this hierarchy.
return: (osid.id.IdList) - the root objective bank Ids
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
complianc... |
def load_class(location):
""" Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer'
and return the IRCBotConsumer class.
"""
mod_name, cls_name = location = location.strip().split(':')
tokens = mod_name.split('.')
fromlist = '[]'
if len(tokens) > 1:
fromlist = '.'.join(... | Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer'
and return the IRCBotConsumer class. | Below is the the instruction that describes the task:
### Input:
Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer'
and return the IRCBotConsumer class.
### Response:
def load_class(location):
""" Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer'
and return the IRCBotCo... |
def _process_sample (self, ap1, ap2, ap3, triple, tflags):
"""We have computed one independent phase closure triple in one timeslot.
"""
# Frequency-resolved:
np.divide (triple, np.abs (triple), triple)
phase = np.angle (triple)
self.ap_spec_stats_by_ddid[self.cur_ddid]... | We have computed one independent phase closure triple in one timeslot. | Below is the the instruction that describes the task:
### Input:
We have computed one independent phase closure triple in one timeslot.
### Response:
def _process_sample (self, ap1, ap2, ap3, triple, tflags):
"""We have computed one independent phase closure triple in one timeslot.
"""
# F... |
def get(self, key, default=None, *, section=DataStoreDocumentSection.Data):
""" Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The ... | Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The key pointing to the value that should be retrieved. It supports
MongoDB'... | Below is the the instruction that describes the task:
### Input:
Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The key pointing to the... |
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
cj2 = cookiejar_from_dict(cookie_dict)
cj.update(cj2)
return cj | Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar. | Below is the the instruction that describes the task:
### Input:
Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
### Response:
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJ... |
def render(self, context=None):
"""Renders the error message, optionally using the given context (which, if specified,
will override the internal context)."""
ctx = context.render() if context else self.get_error_context().render()
return "%s: %s%s%s" % (
self.get_error_kind(... | Renders the error message, optionally using the given context (which, if specified,
will override the internal context). | Below is the the instruction that describes the task:
### Input:
Renders the error message, optionally using the given context (which, if specified,
will override the internal context).
### Response:
def render(self, context=None):
"""Renders the error message, optionally using the given context (w... |
def _get_size(fileno):
# Thanks to fabric (fabfile.org), and
# http://sqizit.bartletts.id.au/2011/02/14/pseudo-terminals-in-python/
"""
Get the size of this pseudo terminal.
:param fileno: stdout.fileno()
:returns: A (rows, cols) tuple.
"""
# Inline imports, because these modules are no... | Get the size of this pseudo terminal.
:param fileno: stdout.fileno()
:returns: A (rows, cols) tuple. | Below is the the instruction that describes the task:
### Input:
Get the size of this pseudo terminal.
:param fileno: stdout.fileno()
:returns: A (rows, cols) tuple.
### Response:
def _get_size(fileno):
# Thanks to fabric (fabfile.org), and
# http://sqizit.bartletts.id.au/2011/02/14/pseudo-termina... |
def to_json(df, values):
"""Format output for the json response."""
records = []
if df.empty:
return {"data": []}
sum_ = float(np.sum([df[c].iloc[0] for c in values]))
for c in values:
records.append({
"label": values[c],
"... | Format output for the json response. | Below is the the instruction that describes the task:
### Input:
Format output for the json response.
### Response:
def to_json(df, values):
"""Format output for the json response."""
records = []
if df.empty:
return {"data": []}
sum_ = float(np.sum([df[c].iloc[0] for c... |
def set_chebyshev_approximators(self, deg_forward=50, deg_backwards=200):
r'''Method to derive and set coefficients for chebyshev polynomial
function approximation of the height-volume and volume-height
relationship.
A single set of chebyshev coefficients is used for t... | r'''Method to derive and set coefficients for chebyshev polynomial
function approximation of the height-volume and volume-height
relationship.
A single set of chebyshev coefficients is used for the entire height-
volume and volume-height relationships respectively.
... | Below is the the instruction that describes the task:
### Input:
r'''Method to derive and set coefficients for chebyshev polynomial
function approximation of the height-volume and volume-height
relationship.
A single set of chebyshev coefficients is used for the entire height-
... |
def keep_session_alive(self):
"""If the session expired, logs back in."""
try:
self.resources()
except xmlrpclib.Fault as fault:
if fault.faultCode == 5:
self.login()
else:
raise | If the session expired, logs back in. | Below is the the instruction that describes the task:
### Input:
If the session expired, logs back in.
### Response:
def keep_session_alive(self):
"""If the session expired, logs back in."""
try:
self.resources()
except xmlrpclib.Fault as fault:
if fault.faultCode =... |
def createElementsFromHTML(cls, html, encoding='utf-8'):
'''
createElementsFromHTML - Creates elements from provided html, and returns a list of the root-level elements
children of these root-level nodes are accessable via the usual means.
@param html <str> - Some html d... | createElementsFromHTML - Creates elements from provided html, and returns a list of the root-level elements
children of these root-level nodes are accessable via the usual means.
@param html <str> - Some html data
@param encoding <str> - Encoding to use for document
... | Below is the the instruction that describes the task:
### Input:
createElementsFromHTML - Creates elements from provided html, and returns a list of the root-level elements
children of these root-level nodes are accessable via the usual means.
@param html <str> - Some html data
... |
def l_endian(v):
""" 小端序 """
w = struct.pack('<H', v)
return str(binascii.hexlify(w), encoding='gbk') | 小端序 | Below is the the instruction that describes the task:
### Input:
小端序
### Response:
def l_endian(v):
""" 小端序 """
w = struct.pack('<H', v)
return str(binascii.hexlify(w), encoding='gbk') |
def set_exception(self, exception):
"""Signal unsuccessful completion."""
was_handled = self._finish(self.errbacks, exception)
if not was_handled:
traceback.print_exception(
type(exception), exception, exception.__traceback__) | Signal unsuccessful completion. | Below is the the instruction that describes the task:
### Input:
Signal unsuccessful completion.
### Response:
def set_exception(self, exception):
"""Signal unsuccessful completion."""
was_handled = self._finish(self.errbacks, exception)
if not was_handled:
traceback.print_excep... |
def set_position_target_global_int_send(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False):
'''
Sets a desired vehicle position, velocity, and/or acceleration in a
... | Sets a desired vehicle position, velocity, and/or acceleration in a
global coordinate system (WGS84). Used by an external
controller to command the vehicle (manual controller
or other system).
time_boot_ms : Timestamp in milliseconds since sy... | Below is the the instruction that describes the task:
### Input:
Sets a desired vehicle position, velocity, and/or acceleration in a
global coordinate system (WGS84). Used by an external
controller to command the vehicle (manual controller
or other system).
... |
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_interface_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.SubEleme... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_interface_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.El... |
def init_variables(self, verbose=False):
"""Redefine the causes of the graph."""
for j in range(1, self.nodes):
nb_parents = np.random.randint(0, min([self.parents_max, j])+1)
for i in np.random.choice(range(0, j), nb_parents, replace=False):
self.adjacency_matrix... | Redefine the causes of the graph. | Below is the the instruction that describes the task:
### Input:
Redefine the causes of the graph.
### Response:
def init_variables(self, verbose=False):
"""Redefine the causes of the graph."""
for j in range(1, self.nodes):
nb_parents = np.random.randint(0, min([self.parents_max, j])+1... |
def path_complete(self, text: str, line: str, begidx: int, endidx: int,
path_filter: Optional[Callable[[str], bool]] = None) -> List[str]:
"""Performs completion of local file system paths
:param text: the string prefix we are attempting to match (all returned matches must begin w... | Performs completion of local file system paths
:param text: the string prefix we are attempting to match (all returned matches must begin with it)
:param line: the current input line with leading whitespace removed
:param begidx: the beginning index of the prefix text
:param endidx: the... | Below is the the instruction that describes the task:
### Input:
Performs completion of local file system paths
:param text: the string prefix we are attempting to match (all returned matches must begin with it)
:param line: the current input line with leading whitespace removed
:param begi... |
def _create_session(self, scope):
"""
Instantiate a new session object for use in connecting with Degreed
"""
now = datetime.datetime.utcnow()
if self.session is None or self.expires_at is None or now >= self.expires_at:
# Create a new session with a valid token
... | Instantiate a new session object for use in connecting with Degreed | Below is the the instruction that describes the task:
### Input:
Instantiate a new session object for use in connecting with Degreed
### Response:
def _create_session(self, scope):
"""
Instantiate a new session object for use in connecting with Degreed
"""
now = datetime.datetime.ut... |
def get_by_natural_key(self, *args):
"""
Return the object corresponding to the provided natural key.
(This is a generic implementation of the standard Django function)
"""
kwargs = self.natural_key_kwargs(*args)
# Since kwargs already has __ lookups in it, we could ju... | Return the object corresponding to the provided natural key.
(This is a generic implementation of the standard Django function) | Below is the the instruction that describes the task:
### Input:
Return the object corresponding to the provided natural key.
(This is a generic implementation of the standard Django function)
### Response:
def get_by_natural_key(self, *args):
"""
Return the object corresponding to the pro... |
def process_apk(self, data, name):
"""
Processes Android application
:param data:
:param name:
:return:
"""
try:
from apk_parse.apk import APK
except Exception as e:
logger.warning('Could not import apk_parse, try running: pip insta... | Processes Android application
:param data:
:param name:
:return: | Below is the the instruction that describes the task:
### Input:
Processes Android application
:param data:
:param name:
:return:
### Response:
def process_apk(self, data, name):
"""
Processes Android application
:param data:
:param name:
:return:
... |
def sg_summary_audio(tensor, sample_rate=16000, prefix=None, name=None):
r"""Register `tensor` to summary report as audio
Args:
tensor: A `Tensor` to log as audio
sample_rate : An int. Sample rate to report. Default is 16000.
prefix: A `string`. A prefix to display in the tensor board web UI.... | r"""Register `tensor` to summary report as audio
Args:
tensor: A `Tensor` to log as audio
sample_rate : An int. Sample rate to report. Default is 16000.
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
R... | Below is the the instruction that describes the task:
### Input:
r"""Register `tensor` to summary report as audio
Args:
tensor: A `Tensor` to log as audio
sample_rate : An int. Sample rate to report. Default is 16000.
prefix: A `string`. A prefix to display in the tensor board web UI.
n... |
def is_mode_supported(mode, ver):
"""\
Returns if `mode` is supported by `version`.
Note: This function does not check if `version` is actually a valid
(Micro) QR Code version. Invalid versions like ``41`` may return an illegal
value.
:param int mode: Canonicalized mode.
:param int or None... | \
Returns if `mode` is supported by `version`.
Note: This function does not check if `version` is actually a valid
(Micro) QR Code version. Invalid versions like ``41`` may return an illegal
value.
:param int mode: Canonicalized mode.
:param int or None ver: (Micro) QR Code version constant.
... | Below is the the instruction that describes the task:
### Input:
\
Returns if `mode` is supported by `version`.
Note: This function does not check if `version` is actually a valid
(Micro) QR Code version. Invalid versions like ``41`` may return an illegal
value.
:param int mode: Canonicalized ... |
def replace(pretty, old_str, new_str):
""" Replace strings giving some info on where
the replacement was done
"""
out_str = ''
line_number = 1
changes = 0
for line in pretty.splitlines(keepends=True):
new_line = line.replace(old_str, new_str)
if line.find(old_str) != -1:
... | Replace strings giving some info on where
the replacement was done | Below is the the instruction that describes the task:
### Input:
Replace strings giving some info on where
the replacement was done
### Response:
def replace(pretty, old_str, new_str):
""" Replace strings giving some info on where
the replacement was done
"""
out_str = ''
line_number = 1
... |
def socket_parse(self, astr_destination):
'''
Examines <astr_destination> and if of form <str1>:<str2> assumes
that <str1> is a host to send datagram comms to over port <str2>.
Returns True or False.
'''
t_socketInfo = astr_destination.partition(':')
if ... | Examines <astr_destination> and if of form <str1>:<str2> assumes
that <str1> is a host to send datagram comms to over port <str2>.
Returns True or False. | Below is the the instruction that describes the task:
### Input:
Examines <astr_destination> and if of form <str1>:<str2> assumes
that <str1> is a host to send datagram comms to over port <str2>.
Returns True or False.
### Response:
def socket_parse(self, astr_destination):
'''
Exa... |
def save_hdf(self, filename, path='', overwrite=False, append=False):
"""Saves object data to HDF file (only works if MCMC is run)
Samples are saved to /samples location under given path,
and object properties are also attached, so suitable for
re-loading via :func:`StarModel.load_hdf`.... | Saves object data to HDF file (only works if MCMC is run)
Samples are saved to /samples location under given path,
and object properties are also attached, so suitable for
re-loading via :func:`StarModel.load_hdf`.
:param filename:
Name of file to save to. Should b... | Below is the the instruction that describes the task:
### Input:
Saves object data to HDF file (only works if MCMC is run)
Samples are saved to /samples location under given path,
and object properties are also attached, so suitable for
re-loading via :func:`StarModel.load_hdf`.
... |
def setproctitle(text):
"""
This is a wrapper for setproctitle.setproctitle(). The call sets
'text' as the new process title and returns the previous value.
The module is commonly not installed. If missing, nothing is changed,
and the call returns None.
The module is described here: https://... | This is a wrapper for setproctitle.setproctitle(). The call sets
'text' as the new process title and returns the previous value.
The module is commonly not installed. If missing, nothing is changed,
and the call returns None.
The module is described here: https://pypi.python.org/pypi/setproctitle | Below is the the instruction that describes the task:
### Input:
This is a wrapper for setproctitle.setproctitle(). The call sets
'text' as the new process title and returns the previous value.
The module is commonly not installed. If missing, nothing is changed,
and the call returns None.
The m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.