code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def unregister_counter_nonzero(network):
"""
Unregister nonzero counter hooks
:param network: The network previously registered via `register_nonzero_counter`
"""
if not hasattr(network, "__counter_nonzero_handles__"):
raise ValueError("register_counter_nonzero was not called for this network")
for h i... | Unregister nonzero counter hooks
:param network: The network previously registered via `register_nonzero_counter` | Below is the the instruction that describes the task:
### Input:
Unregister nonzero counter hooks
:param network: The network previously registered via `register_nonzero_counter`
### Response:
def unregister_counter_nonzero(network):
"""
Unregister nonzero counter hooks
:param network: The network previous... |
def repr_string(outer_string, inner_strings, allow_mixed_seps=True):
r"""Return a pretty string for ``repr``.
The returned string is formatted such that it does not extend
beyond the line boundary if avoidable. The line width is taken from
NumPy's printing options that can be retrieved with
`numpy.... | r"""Return a pretty string for ``repr``.
The returned string is formatted such that it does not extend
beyond the line boundary if avoidable. The line width is taken from
NumPy's printing options that can be retrieved with
`numpy.get_printoptions`. They can be temporarily overridden
using the `npy_... | Below is the the instruction that describes the task:
### Input:
r"""Return a pretty string for ``repr``.
The returned string is formatted such that it does not extend
beyond the line boundary if avoidable. The line width is taken from
NumPy's printing options that can be retrieved with
`numpy.get_... |
def fit_angular_distribution(angles, rates, rate_errors, shape='pexp'):
"""Fits angular distribution of rates.
Parameters
----------
rates: numpy array
with rates for all PMT combinations
angles: numpy array
with angles for all PMT combinations
shape:
which function to fit; ex... | Fits angular distribution of rates.
Parameters
----------
rates: numpy array
with rates for all PMT combinations
angles: numpy array
with angles for all PMT combinations
shape:
which function to fit; exp for exponential or pexp for
exponential_polinomial
Returns
---... | Below is the the instruction that describes the task:
### Input:
Fits angular distribution of rates.
Parameters
----------
rates: numpy array
with rates for all PMT combinations
angles: numpy array
with angles for all PMT combinations
shape:
which function to fit; exp for expo... |
def parse_link_header(header_value, strict=True):
"""
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive a... | Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all parameters.
:return: a sequence of :class:`~ietfparse.d... | Below is the the instruction that describes the task:
### Input:
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to re... |
def parameterize(self, call, host):
"""
Parameterize a Call with its Context set to a per-host Config.
"""
debug("Parameterizing {!r} for host {!r}".format(call, host))
# Generate a custom ConnectionCall that knows how to yield a Connection
# in its make_context(), specif... | Parameterize a Call with its Context set to a per-host Config. | Below is the the instruction that describes the task:
### Input:
Parameterize a Call with its Context set to a per-host Config.
### Response:
def parameterize(self, call, host):
"""
Parameterize a Call with its Context set to a per-host Config.
"""
debug("Parameterizing {!r} for hos... |
def finalize_backward_execution(self):
""" Utility function to finalize the backward execution of the concurrency state.
:return:
"""
# backward_execution needs to be True to signal the parent container state the backward execution
self.backward_execution = True
# pop th... | Utility function to finalize the backward execution of the concurrency state.
:return: | Below is the the instruction that describes the task:
### Input:
Utility function to finalize the backward execution of the concurrency state.
:return:
### Response:
def finalize_backward_execution(self):
""" Utility function to finalize the backward execution of the concurrency state.
:r... |
def memoize(func):
"""Memoize a method that should return the same result every time on a
given instance.
"""
@wraps(func)
def memoizer(self):
if not hasattr(self, '_cache'):
self._cache = {}
if func.__name__ not in self._cache:
self._cache[func.__name__] = f... | Memoize a method that should return the same result every time on a
given instance. | Below is the the instruction that describes the task:
### Input:
Memoize a method that should return the same result every time on a
given instance.
### Response:
def memoize(func):
"""Memoize a method that should return the same result every time on a
given instance.
"""
@wraps(func)
def ... |
def parse_signature(signature):
"""Parse a signature into its input and return parameter types.
This will also collect the types that are required by any of the input
and return types.
:sig: (str) -> Tuple[List[str], str, Set[str]]
:param signature: Signature to parse.
:return: Input parameter... | Parse a signature into its input and return parameter types.
This will also collect the types that are required by any of the input
and return types.
:sig: (str) -> Tuple[List[str], str, Set[str]]
:param signature: Signature to parse.
:return: Input parameter types, return type, and all required t... | Below is the the instruction that describes the task:
### Input:
Parse a signature into its input and return parameter types.
This will also collect the types that are required by any of the input
and return types.
:sig: (str) -> Tuple[List[str], str, Set[str]]
:param signature: Signature to parse... |
def connect(self):
"""Connect the |LinkSequence| instances handled by the actual model
to the |NodeSequence| instances handled by one inlet node and
multiple oulet nodes.
The HydPy-H-Branch model passes multiple output values to different
outlet nodes. This requires additional ... | Connect the |LinkSequence| instances handled by the actual model
to the |NodeSequence| instances handled by one inlet node and
multiple oulet nodes.
The HydPy-H-Branch model passes multiple output values to different
outlet nodes. This requires additional information regarding the
... | Below is the the instruction that describes the task:
### Input:
Connect the |LinkSequence| instances handled by the actual model
to the |NodeSequence| instances handled by one inlet node and
multiple oulet nodes.
The HydPy-H-Branch model passes multiple output values to different
o... |
def upload_file(self, owner, id, name, **kwargs):
"""
Upload file
Upload one file at a time to a dataset. This endpoint expects requests of type `application/octet-stream`. For example, assuming that you want to upload a local file named `file1.csv` to a hypothetical dataset `https://data.worl... | Upload file
Upload one file at a time to a dataset. This endpoint expects requests of type `application/octet-stream`. For example, assuming that you want to upload a local file named `file1.csv` to a hypothetical dataset `https://data.world/awesome-user/awesome-dataset` and choose its name on data.world to b... | Below is the the instruction that describes the task:
### Input:
Upload file
Upload one file at a time to a dataset. This endpoint expects requests of type `application/octet-stream`. For example, assuming that you want to upload a local file named `file1.csv` to a hypothetical dataset `https://data.world... |
def image_url(self) -> Optional[str]:
r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It may be :const:`None` if it's not an image.
"""
images = self.attributes.get('imageinfo', [])
if images and isinstance(images, collections.abc.Sequence):
return ima... | r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It may be :const:`None` if it's not an image. | Below is the the instruction that describes the task:
### Input:
r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It may be :const:`None` if it's not an image.
### Response:
def image_url(self) -> Optional[str]:
r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It... |
def copy(source, destination):
"""Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(source):
... | Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise. | Below is the the instruction that describes the task:
### Input:
Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise.
### Response:... |
def reset_course_favorites(self):
"""
Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses
"""
path = {}
data = {}
params = {}
self.logger.debug("DELETE /api/... | Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses | Below is the the instruction that describes the task:
### Input:
Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses
### Response:
def reset_course_favorites(self):
"""
Reset course favorites.
... |
def get_check(self, check):
"""
Returns an instance of the specified check.
"""
chk = self._check_manager.get(check)
chk.set_entity(self)
return chk | Returns an instance of the specified check. | Below is the the instruction that describes the task:
### Input:
Returns an instance of the specified check.
### Response:
def get_check(self, check):
"""
Returns an instance of the specified check.
"""
chk = self._check_manager.get(check)
chk.set_entity(self)
return... |
def draw_residual(x, y, yerr, xerr,
show_errbars=True, ax=None,
zero_line=True, grid=True,
**kwargs):
"""Draw a residual plot on the axis.
By default, if show_errbars if True, residuals are drawn as blue points
with errorbars with no endcaps. If show_er... | Draw a residual plot on the axis.
By default, if show_errbars if True, residuals are drawn as blue points
with errorbars with no endcaps. If show_errbars is False, residuals are
drawn as a bar graph with black bars.
**Arguments**
- **x** array of numbers, x-coordinates
- **y** array ... | Below is the the instruction that describes the task:
### Input:
Draw a residual plot on the axis.
By default, if show_errbars if True, residuals are drawn as blue points
with errorbars with no endcaps. If show_errbars is False, residuals are
drawn as a bar graph with black bars.
**Arguments**
... |
def get_pixel(self, x: int, y: int) -> Tuple[int, int, int]:
"""Get the color of a pixel in this Image.
Args:
x (int): X pixel of the Image. Starting from the left at 0.
y (int): Y pixel of the Image. Starting from the top at 0.
Returns:
Tuple[int, int, in... | Get the color of a pixel in this Image.
Args:
x (int): X pixel of the Image. Starting from the left at 0.
y (int): Y pixel of the Image. Starting from the top at 0.
Returns:
Tuple[int, int, int]:
An (r, g, b) tuple containing the pixels color value... | Below is the the instruction that describes the task:
### Input:
Get the color of a pixel in this Image.
Args:
x (int): X pixel of the Image. Starting from the left at 0.
y (int): Y pixel of the Image. Starting from the top at 0.
Returns:
Tuple[int, int, int]:... |
def asDictionary(self):
""" returns the data source as a dictionary """
self._dict = {
"type": "queryTable",
"workspaceId": self._workspaceId,
"query": self._query,
"oidFields": self._oidFields,
"spatialReference": {"wkid" : self._wkid}
... | returns the data source as a dictionary | Below is the the instruction that describes the task:
### Input:
returns the data source as a dictionary
### Response:
def asDictionary(self):
""" returns the data source as a dictionary """
self._dict = {
"type": "queryTable",
"workspaceId": self._workspaceId,
"... |
def convert_pronouns( mrf_lines ):
''' Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to
syntactic analyzer's mrf format;
Uses the set of predefined pronoun conversion rules from _pronConversions;
_pronConversions should be a list of lists, where each outer list ... | Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to
syntactic analyzer's mrf format;
Uses the set of predefined pronoun conversion rules from _pronConversions;
_pronConversions should be a list of lists, where each outer list stands
for a single conversion rul... | Below is the the instruction that describes the task:
### Input:
Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to
syntactic analyzer's mrf format;
Uses the set of predefined pronoun conversion rules from _pronConversions;
_pronConversions should be a list of lis... |
def is_generic_list(type_: Type) -> bool:
"""Determines whether a type is a List[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
Returns:
... | Determines whether a type is a List[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
Returns:
True iff it's a List[...something...]. | Below is the the instruction that describes the task:
### Input:
Determines whether a type is a List[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
... |
def complete_server(self, text, line, begidx, endidx):
''' Tab-complete server command '''
return [i for i in PsiturkShell.server_commands if i.startswith(text)] | Tab-complete server command | Below is the the instruction that describes the task:
### Input:
Tab-complete server command
### Response:
def complete_server(self, text, line, begidx, endidx):
''' Tab-complete server command '''
return [i for i in PsiturkShell.server_commands if i.startswith(text)] |
def get_pages(self):
"""Get all registered pages.
Returns
-------
pages : dict
A ``dict`` of ``route`` to ``ProxiedPage`` for all pages.
"""
resp = self._client._call('GetProxies', proto.GetProxiesRequest())
return {i.route: ProxiedPage(i.route, i.tar... | Get all registered pages.
Returns
-------
pages : dict
A ``dict`` of ``route`` to ``ProxiedPage`` for all pages. | Below is the the instruction that describes the task:
### Input:
Get all registered pages.
Returns
-------
pages : dict
A ``dict`` of ``route`` to ``ProxiedPage`` for all pages.
### Response:
def get_pages(self):
"""Get all registered pages.
Returns
---... |
async def clear(self, using_db=None) -> None:
"""
Clears ALL relations.
"""
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, sel... | Clears ALL relations. | Below is the the instruction that describes the task:
### Input:
Clears ALL relations.
### Response:
async def clear(self, using_db=None) -> None:
"""
Clears ALL relations.
"""
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
... |
def num_neighbors(self, pores, mode='or', flatten=False):
r"""
Returns the number of neigbhoring pores for each given input pore
Parameters
----------
pores : array_like
Pores whose neighbors are to be counted
flatten : boolean (optional)
If ``Fa... | r"""
Returns the number of neigbhoring pores for each given input pore
Parameters
----------
pores : array_like
Pores whose neighbors are to be counted
flatten : boolean (optional)
If ``False`` (default) the number of pores neighboring each input
... | Below is the the instruction that describes the task:
### Input:
r"""
Returns the number of neigbhoring pores for each given input pore
Parameters
----------
pores : array_like
Pores whose neighbors are to be counted
flatten : boolean (optional)
If `... |
def walk_directory_directories_relative_path(self, relativePath=""):
"""
Walk a certain directory in repository and yield all found directories relative path.
:parameters:
#. relativePath (str): The relative path of the directory.
"""
# get directory info dict
... | Walk a certain directory in repository and yield all found directories relative path.
:parameters:
#. relativePath (str): The relative path of the directory. | Below is the the instruction that describes the task:
### Input:
Walk a certain directory in repository and yield all found directories relative path.
:parameters:
#. relativePath (str): The relative path of the directory.
### Response:
def walk_directory_directories_relative_path(self, relati... |
def _positive_int(integer_string, strict=False, cutoff=None):
"""
Cast a string to a strictly positive integer.
"""
ret = int(integer_string)
if ret < 0 or (ret == 0 and strict):
raise ValueError()
if cutoff:
ret = min(ret, cutoff)
return ret | Cast a string to a strictly positive integer. | Below is the the instruction that describes the task:
### Input:
Cast a string to a strictly positive integer.
### Response:
def _positive_int(integer_string, strict=False, cutoff=None):
"""
Cast a string to a strictly positive integer.
"""
ret = int(integer_string)
if ret < 0 or (ret == 0 and... |
def update_labels(self, func):
"""
Map a function over baseline and adjustment values in place.
Note that the baseline data values must be a LabelArray.
"""
if not isinstance(self.data, LabelArray):
raise TypeError(
'update_labels only supported if da... | Map a function over baseline and adjustment values in place.
Note that the baseline data values must be a LabelArray. | Below is the the instruction that describes the task:
### Input:
Map a function over baseline and adjustment values in place.
Note that the baseline data values must be a LabelArray.
### Response:
def update_labels(self, func):
"""
Map a function over baseline and adjustment values in plac... |
def __build_helper_map(cls):
"""Build a mapping from command names to helper names.
One command name maps to at most one helper method.
Multiple command names can map to the same helper method.
Only used by __init__() to initialize self._cmd_map. MUST NOT be used
elsewhere.
... | Build a mapping from command names to helper names.
One command name maps to at most one helper method.
Multiple command names can map to the same helper method.
Only used by __init__() to initialize self._cmd_map. MUST NOT be used
elsewhere.
Raises:
PyShellError: ... | Below is the the instruction that describes the task:
### Input:
Build a mapping from command names to helper names.
One command name maps to at most one helper method.
Multiple command names can map to the same helper method.
Only used by __init__() to initialize self._cmd_map. MUST NOT b... |
def get_stack_trace(self, depth = 16):
"""
Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@rtype: tuple of tuple( int, int, str )
@... | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
... | Below is the the instruction that describes the task:
### Input:
Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@rtype: tuple of tuple( int, int, str )... |
def _get_encoding(dom, default="utf-8"):
"""
Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given en... | Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given encoding or `default` parameter if not found. | Below is the the instruction that describes the task:
### Input:
Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/d... |
def _append_request_ids(self, resp):
"""Add request_ids as an attribute to the object
:param resp: Response object or list of Response objects
"""
if isinstance(resp, list):
# Add list of request_ids if response is of type list.
for resp_obj in resp:
... | Add request_ids as an attribute to the object
:param resp: Response object or list of Response objects | Below is the the instruction that describes the task:
### Input:
Add request_ids as an attribute to the object
:param resp: Response object or list of Response objects
### Response:
def _append_request_ids(self, resp):
"""Add request_ids as an attribute to the object
:param resp: Response... |
def receive_request(self, transaction):
"""
Handle request and execute the requested method
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request
... | Handle request and execute the requested method
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request | Below is the the instruction that describes the task:
### Input:
Handle request and execute the requested method
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the req... |
def delete(uid):
'''
Delete by uid
'''
del_count = TabPostHist.delete().where(TabPostHist.uid == uid)
try:
del_count.execute()
return False
except:
return True | Delete by uid | Below is the the instruction that describes the task:
### Input:
Delete by uid
### Response:
def delete(uid):
'''
Delete by uid
'''
del_count = TabPostHist.delete().where(TabPostHist.uid == uid)
try:
del_count.execute()
return False
except:
... |
def _purge_datasets_unique_to_resource(ref_key, ref_id):
"""
Find the number of times a a resource and dataset combination
occurs. If this equals the number of times the dataset appears, then
we can say this dataset is unique to this resource, therefore it can be deleted
"""
count_qr... | Find the number of times a a resource and dataset combination
occurs. If this equals the number of times the dataset appears, then
we can say this dataset is unique to this resource, therefore it can be deleted | Below is the the instruction that describes the task:
### Input:
Find the number of times a a resource and dataset combination
occurs. If this equals the number of times the dataset appears, then
we can say this dataset is unique to this resource, therefore it can be deleted
### Response:
def _purg... |
def get_stat_json(self, pathobj):
"""
Request remote file/directory status info
Returns a json object as specified by Artifactory REST API
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).str... | Request remote file/directory status info
Returns a json object as specified by Artifactory REST API | Below is the the instruction that describes the task:
### Input:
Request remote file/directory status info
Returns a json object as specified by Artifactory REST API
### Response:
def get_stat_json(self, pathobj):
"""
Request remote file/directory status info
Returns a json object a... |
def _tokens_to_subtoken(self, tokens):
""" Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
"""
ret = []
for token in tokens:
ret.extend(
... | Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size) | Below is the the instruction that describes the task:
### Input:
Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
### Response:
def _tokens_to_subtoken(self, tokens):
""" Converts ... |
def _iterContours(self, **kwargs):
"""
This must return an iterator that returns wrapped contours.
Subclasses may override this method.
"""
count = len(self)
index = 0
while count:
yield self[index]
count -= 1
index += 1 | This must return an iterator that returns wrapped contours.
Subclasses may override this method. | Below is the the instruction that describes the task:
### Input:
This must return an iterator that returns wrapped contours.
Subclasses may override this method.
### Response:
def _iterContours(self, **kwargs):
"""
This must return an iterator that returns wrapped contours.
Subcla... |
def send(self, request, expect_json=True, ignore_content=False):
"""
Send a formatted API request
:param request: a formatted request object
:type request: :class:`.Request`
:param bool expect_json: if True, raise :class:`.InvalidAPIAccess` if
response is not in JSON... | Send a formatted API request
:param request: a formatted request object
:type request: :class:`.Request`
:param bool expect_json: if True, raise :class:`.InvalidAPIAccess` if
response is not in JSON format
:param bool ignore_content: whether to ignore setting content of the
... | Below is the the instruction that describes the task:
### Input:
Send a formatted API request
:param request: a formatted request object
:type request: :class:`.Request`
:param bool expect_json: if True, raise :class:`.InvalidAPIAccess` if
response is not in JSON format
... |
def class_name_teleflask_message(self) -> str:
"""
If it starts with `Send` remove that.
"""
# strip leading "Send"
name = self.class_name # "sendPhoto" -> "SendPhoto"
name = name[4:] if name.startswith('Send') else name # "SendPhoto" -> "Photo"
name = name + "M... | If it starts with `Send` remove that. | Below is the the instruction that describes the task:
### Input:
If it starts with `Send` remove that.
### Response:
def class_name_teleflask_message(self) -> str:
"""
If it starts with `Send` remove that.
"""
# strip leading "Send"
name = self.class_name # "sendPhoto" -> "... |
def add_replica(self, partition_name, count=1):
"""Adding a replica is done by trying to add the replica to every
broker in the cluster and choosing the resulting state with the
highest fitness score.
:param partition_name: (topic_id, partition_id) of the partition to add replicas of.
... | Adding a replica is done by trying to add the replica to every
broker in the cluster and choosing the resulting state with the
highest fitness score.
:param partition_name: (topic_id, partition_id) of the partition to add replicas of.
:param count: The number of replicas to add. | Below is the the instruction that describes the task:
### Input:
Adding a replica is done by trying to add the replica to every
broker in the cluster and choosing the resulting state with the
highest fitness score.
:param partition_name: (topic_id, partition_id) of the partition to add repl... |
def make_image(imagesize, voxval=0, spacing=None, origin=None, direction=None, has_components=False, pixeltype='float'):
"""
Make an image with given size and voxel value or given a mask and vector
ANTsR function: `makeImage`
Arguments
---------
shape : tuple/ANTsImage
input image size... | Make an image with given size and voxel value or given a mask and vector
ANTsR function: `makeImage`
Arguments
---------
shape : tuple/ANTsImage
input image size or mask
voxval : scalar
input image value or vector, size of mask
spacing : tuple/list
image spatial resol... | Below is the the instruction that describes the task:
### Input:
Make an image with given size and voxel value or given a mask and vector
ANTsR function: `makeImage`
Arguments
---------
shape : tuple/ANTsImage
input image size or mask
voxval : scalar
input image value or vecto... |
def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: ... | Validates that the response from Google was successful. | Below is the the instruction that describes the task:
### Input:
Validates that the response from Google was successful.
### Response:
def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
... |
def DeregisterPlugin(cls, plugin_class):
"""Deregisters an preprocess plugin class.
Args:
plugin_class (type): preprocess plugin class.
Raises:
KeyError: if plugin class is not set for the corresponding name.
TypeError: if the source type of the plugin class is not supported.
"""
... | Deregisters an preprocess plugin class.
Args:
plugin_class (type): preprocess plugin class.
Raises:
KeyError: if plugin class is not set for the corresponding name.
TypeError: if the source type of the plugin class is not supported. | Below is the the instruction that describes the task:
### Input:
Deregisters an preprocess plugin class.
Args:
plugin_class (type): preprocess plugin class.
Raises:
KeyError: if plugin class is not set for the corresponding name.
TypeError: if the source type of the plugin class is not s... |
def dispatch(self, request, *args, **kwargs):
""" Fetches queried data from graphql and returns cached & hashed key. """
if not graphql_api_settings.CACHE_ACTIVE:
return self.super_call(request, *args, **kwargs)
cache = caches["default"]
operation_ast = self.get_operation_as... | Fetches queried data from graphql and returns cached & hashed key. | Below is the the instruction that describes the task:
### Input:
Fetches queried data from graphql and returns cached & hashed key.
### Response:
def dispatch(self, request, *args, **kwargs):
""" Fetches queried data from graphql and returns cached & hashed key. """
if not graphql_api_settings.CACH... |
def sign_up(self, username=None, password=None):
"""
创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。
用户对象上必须包含 username 和 password 两个字段
"""
if username:
self.set('username', username)
if password:
self.set('password', password)
usern... | 创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。
用户对象上必须包含 username 和 password 两个字段 | Below is the the instruction that describes the task:
### Input:
创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。
用户对象上必须包含 username 和 password 两个字段
### Response:
def sign_up(self, username=None, password=None):
"""
创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。
用户对象上必须包... |
def save_metadata(self, phase, data_name):
"""
Save metadata associated with the phase, such as the name of the pipeline, the name of the phase and the name
of the data being fit
"""
with open("{}/.metadata".format(make_path(phase)), "w+") as f:
f.write("pipeline={}\n... | Save metadata associated with the phase, such as the name of the pipeline, the name of the phase and the name
of the data being fit | Below is the the instruction that describes the task:
### Input:
Save metadata associated with the phase, such as the name of the pipeline, the name of the phase and the name
of the data being fit
### Response:
def save_metadata(self, phase, data_name):
"""
Save metadata associated with the... |
def name(self):
"""str: name of the file entry, which does not include the full path."""
if self._name is None:
location = getattr(self.path_spec, 'location', None)
if location is not None:
self._name = self._file_system.BasenamePath(location)
else:
volume_index = apfs_helper.A... | str: name of the file entry, which does not include the full path. | Below is the the instruction that describes the task:
### Input:
str: name of the file entry, which does not include the full path.
### Response:
def name(self):
"""str: name of the file entry, which does not include the full path."""
if self._name is None:
location = getattr(self.path_spec, 'locatio... |
def _create_dock(self):
"""Create dockwidget and tabify it with the legend."""
# Import dock here as it needs to be imported AFTER i18n is set up
from safe.gui.widgets.dock import Dock
self.dock_widget = Dock(self.iface)
self.dock_widget.setObjectName('InaSAFE-Dock')
self... | Create dockwidget and tabify it with the legend. | Below is the the instruction that describes the task:
### Input:
Create dockwidget and tabify it with the legend.
### Response:
def _create_dock(self):
"""Create dockwidget and tabify it with the legend."""
# Import dock here as it needs to be imported AFTER i18n is set up
from safe.gui.wid... |
def get_transaction_by_tx_hash(self, tx_hash: str, is_full: bool = False) -> dict:
"""
This interface is used to get the corresponding transaction information based on the specified hash value.
:param tx_hash: str, a hexadecimal hash value.
:param is_full:
:return: dict
... | This interface is used to get the corresponding transaction information based on the specified hash value.
:param tx_hash: str, a hexadecimal hash value.
:param is_full:
:return: dict | Below is the the instruction that describes the task:
### Input:
This interface is used to get the corresponding transaction information based on the specified hash value.
:param tx_hash: str, a hexadecimal hash value.
:param is_full:
:return: dict
### Response:
def get_transaction_by_tx_h... |
def lande_g_factors(element, isotope, L=None, J=None, F=None):
r"""Return the Lande g-factors for a given atom or level.
>>> element = "Rb"
>>> isotope = 87
>>> print(lande_g_factors(element, isotope))
[ 9.9999e-01 2.0023e+00 -9.9514e-04]
The spin-orbit g-factor for a certain J
>... | r"""Return the Lande g-factors for a given atom or level.
>>> element = "Rb"
>>> isotope = 87
>>> print(lande_g_factors(element, isotope))
[ 9.9999e-01 2.0023e+00 -9.9514e-04]
The spin-orbit g-factor for a certain J
>>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2)))
... | Below is the the instruction that describes the task:
### Input:
r"""Return the Lande g-factors for a given atom or level.
>>> element = "Rb"
>>> isotope = 87
>>> print(lande_g_factors(element, isotope))
[ 9.9999e-01 2.0023e+00 -9.9514e-04]
The spin-orbit g-factor for a certain J
... |
def apply_patches(self):
"""
Applies the patches.
:return: Method success.
:rtype: bool
"""
success = True
for name, patch in sorted(self):
success = self.apply_patch(patch)
return success | Applies the patches.
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Applies the patches.
:return: Method success.
:rtype: bool
### Response:
def apply_patches(self):
"""
Applies the patches.
:return: Method success.
:rtype: bool
"""
success = True
... |
def cleanup_dataset(dataset, data_home=None, ext=".zip"):
"""
Removes the dataset directory and archive file from the data home directory.
Parameters
----------
dataset : str
The name of the dataset; should either be a folder in data home or
specified in the yellowbrick.datasets.DAT... | Removes the dataset directory and archive file from the data home directory.
Parameters
----------
dataset : str
The name of the dataset; should either be a folder in data home or
specified in the yellowbrick.datasets.DATASETS variable.
data_home : str, optional
The path on dis... | Below is the the instruction that describes the task:
### Input:
Removes the dataset directory and archive file from the data home directory.
Parameters
----------
dataset : str
The name of the dataset; should either be a folder in data home or
specified in the yellowbrick.datasets.DATA... |
def create(self, context, request):
"""/@@API/create: Create new object.
Required parameters:
- obj_type = portal_type of new object.
- obj_path = path of new object, from plone site root. - Not required for
obj_type=AnalysisRequest
Optionally:
... | /@@API/create: Create new object.
Required parameters:
- obj_type = portal_type of new object.
- obj_path = path of new object, from plone site root. - Not required for
obj_type=AnalysisRequest
Optionally:
- obj_id = ID of new object.
All oth... | Below is the the instruction that describes the task:
### Input:
/@@API/create: Create new object.
Required parameters:
- obj_type = portal_type of new object.
- obj_path = path of new object, from plone site root. - Not required for
obj_type=AnalysisRequest
O... |
def _make_query_from_terms(self, terms):
""" Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (str, dict): First element is str with FTS query, second is parameters of the query.
"""
... | Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (str, dict): First element is str with FTS query, second is parameters of the query. | Below is the the instruction that describes the task:
### Input:
Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (str, dict): First element is str with FTS query, second is parameters of the query.
### R... |
def data(self, run_config):
"""Return the map data."""
try:
return run_config.map_data(self.path)
except (IOError, OSError) as e: # Catch both for python 2/3 compatibility.
if self.download and hasattr(e, "filename"):
logging.error("Error reading map '%s' from: %s", self.name, e.filenam... | Return the map data. | Below is the the instruction that describes the task:
### Input:
Return the map data.
### Response:
def data(self, run_config):
"""Return the map data."""
try:
return run_config.map_data(self.path)
except (IOError, OSError) as e: # Catch both for python 2/3 compatibility.
if self.download ... |
def fetch(self, seq_id, start=None, end=None):
"""fetch sequence by seq_id, optionally with start, end bounds
"""
rec = self._db.execute("""select * from seqinfo where seq_id = ? order by added desc""", [seq_id]).fetchone()
if rec is None:
raise KeyError(seq_id)
if... | fetch sequence by seq_id, optionally with start, end bounds | Below is the the instruction that describes the task:
### Input:
fetch sequence by seq_id, optionally with start, end bounds
### Response:
def fetch(self, seq_id, start=None, end=None):
"""fetch sequence by seq_id, optionally with start, end bounds
"""
rec = self._db.execute("""select * fr... |
def get_language(language_name):
"""
Returns a callable that instantiates meta-model for the given language.
"""
langs = list(pkg_resources.iter_entry_points(group=LANG_EP,
name=language_name))
if not langs:
raise TextXError('Language "{}" i... | Returns a callable that instantiates meta-model for the given language. | Below is the the instruction that describes the task:
### Input:
Returns a callable that instantiates meta-model for the given language.
### Response:
def get_language(language_name):
"""
Returns a callable that instantiates meta-model for the given language.
"""
langs = list(pkg_resources.iter_en... |
def from_request(cls, request, webhook_id=PAYPAL_WEBHOOK_ID):
"""
Create, validate and process a WebhookEventTrigger given a Django
request object.
The webhook_id parameter expects the ID of the Webhook that was
triggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required
for Webhook verification.
... | Create, validate and process a WebhookEventTrigger given a Django
request object.
The webhook_id parameter expects the ID of the Webhook that was
triggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required
for Webhook verification.
The process is three-fold:
1. Create a WebhookEventTrigger object... | Below is the the instruction that describes the task:
### Input:
Create, validate and process a WebhookEventTrigger given a Django
request object.
The webhook_id parameter expects the ID of the Webhook that was
triggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required
for Webhook verification.
... |
def get_item(self):
"""Gets the ``Item``.
return: (osid.assessment.Item) - the assessment item
*compliance: mandatory -- This method must be implemented.*
"""
# So, for now we're assuming that what should be returned here is the question.
# We could change this class im... | Gets the ``Item``.
return: (osid.assessment.Item) - the assessment item
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the ``Item``.
return: (osid.assessment.Item) - the assessment item
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_item(self):
"""Gets the ``Item``.
return: (osid.assessment.Ite... |
def smart_open(filename: str, mode: str = "rt", ftype: str = "auto", errors: str = 'replace'):
"""
Returns a file descriptor for filename with UTF-8 encoding.
If mode is "rt", file is opened read-only.
If ftype is "auto", uses gzip iff filename endswith .gz.
If ftype is {"gzip","gz"}, uses gzip.
... | Returns a file descriptor for filename with UTF-8 encoding.
If mode is "rt", file is opened read-only.
If ftype is "auto", uses gzip iff filename endswith .gz.
If ftype is {"gzip","gz"}, uses gzip.
If ftype is "auto" and read mode requested, uses gzip iff is_gzip_file(filename).
Note: encoding erro... | Below is the the instruction that describes the task:
### Input:
Returns a file descriptor for filename with UTF-8 encoding.
If mode is "rt", file is opened read-only.
If ftype is "auto", uses gzip iff filename endswith .gz.
If ftype is {"gzip","gz"}, uses gzip.
If ftype is "auto" and read mode requ... |
def _typed_value(self, value):
""" Transform string value to an actual data type of the same value. """
if value not in self._value_cache:
new_value = value
if is_int(value):
new_value = int(value)
elif is_float(value):
new_value = flo... | Transform string value to an actual data type of the same value. | Below is the the instruction that describes the task:
### Input:
Transform string value to an actual data type of the same value.
### Response:
def _typed_value(self, value):
""" Transform string value to an actual data type of the same value. """
if value not in self._value_cache:
new... |
def consume_message(self, header, message):
"""Consume a message"""
logmessage = {
"time": (time.time() % 1000) * 1000,
"header": "",
"message": message,
}
if header:
logmessage["header"] = (
json.dumps(header, indent=2) + "... | Consume a message | Below is the the instruction that describes the task:
### Input:
Consume a message
### Response:
def consume_message(self, header, message):
"""Consume a message"""
logmessage = {
"time": (time.time() % 1000) * 1000,
"header": "",
"message": message,
}
... |
def _iter_sims(self):
"""iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
for sim in self._find_common(lineset, lineset2):
... | iterate on similarities among all files, by making a cartesian
product | Below is the the instruction that describes the task:
### Input:
iterate on similarities among all files, by making a cartesian
product
### Response:
def _iter_sims(self):
"""iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enume... |
def _array_star(args):
"""
Unpacks the tuple `args` and calls _array. Needed to pass multiple args to
a pool.map-ed function
"""
fn, cls, genelist, kwargs = args
return _array(fn, cls, genelist, **kwargs) | Unpacks the tuple `args` and calls _array. Needed to pass multiple args to
a pool.map-ed function | Below is the the instruction that describes the task:
### Input:
Unpacks the tuple `args` and calls _array. Needed to pass multiple args to
a pool.map-ed function
### Response:
def _array_star(args):
"""
Unpacks the tuple `args` and calls _array. Needed to pass multiple args to
a pool.map-ed func... |
def detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu,
omega_levelu, iu0, ju0):
r"""Rewrite a symbolic expression in terms of allowed transition detunings.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, N... | r"""Rewrite a symbolic expression in terms of allowed transition detunings.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
>>> for l in range(Nl):
... for pair in co... | Below is the the instruction that describes the task:
### Input:
r"""Rewrite a symbolic expression in terms of allowed transition detunings.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4... |
def phase_transformation(Ne, Nl, rm, xi, return_equations=False):
"""Returns a phase transformation theta_i.
The phase transformation is defined in a way such that
theta1 + omega_level1 = 0.
>>> xi = np.zeros((1, 2, 2))
>>> xi[0, 1, 0] = 1.0
>>> xi[0, 0, 1] = 1.0
>>> rm = np.zeros((3, ... | Returns a phase transformation theta_i.
The phase transformation is defined in a way such that
theta1 + omega_level1 = 0.
>>> xi = np.zeros((1, 2, 2))
>>> xi[0, 1, 0] = 1.0
>>> xi[0, 0, 1] = 1.0
>>> rm = np.zeros((3, 2, 2))
>>> rm[0, 1, 0] = 1.0
>>> rm[1, 1, 0] = 1.0
>>> rm[2, ... | Below is the the instruction that describes the task:
### Input:
Returns a phase transformation theta_i.
The phase transformation is defined in a way such that
theta1 + omega_level1 = 0.
>>> xi = np.zeros((1, 2, 2))
>>> xi[0, 1, 0] = 1.0
>>> xi[0, 0, 1] = 1.0
>>> rm = np.zeros((3, 2, 2... |
def background_knowledge(self):
'''
Emits the background knowledge in prolog form for RSD.
'''
modeslist, getters = [self.mode(self.db.target_table, [('+', self.db.target_table)], head=True)], []
for (table, ref_table) in self.db.connected.keys():
if ref_table == self... | Emits the background knowledge in prolog form for RSD. | Below is the the instruction that describes the task:
### Input:
Emits the background knowledge in prolog form for RSD.
### Response:
def background_knowledge(self):
'''
Emits the background knowledge in prolog form for RSD.
'''
modeslist, getters = [self.mode(self.db.target_table, ... |
def union_conforms(element: Union, etype, namespace: Dict[str, Any], conforms: Callable) -> bool:
""" Determine whether element conforms to at least one of the types in etype
:param element: element to test
:param etype: type to test against
:param namespace: Namespace to use for resolving forward refe... | Determine whether element conforms to at least one of the types in etype
:param element: element to test
:param etype: type to test against
:param namespace: Namespace to use for resolving forward references
:param conforms: conformance test function
:return: True if element conforms to at least on... | Below is the the instruction that describes the task:
### Input:
Determine whether element conforms to at least one of the types in etype
:param element: element to test
:param etype: type to test against
:param namespace: Namespace to use for resolving forward references
:param conforms: conforman... |
def export(self, top=True):
"""Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist ... | Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist objects
should be expor... | Below is the the instruction that describes the task:
### Input:
Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are... |
def placeholders(cls,dic):
"""Placeholders for fields names and value binds"""
keys = [str(x) for x in dic]
entete = ",".join(keys)
placeholders = ",".join(cls.named_style.format(x) for x in keys)
entete = f"({entete})"
placeholders = f"({placeholders})"
return en... | Placeholders for fields names and value binds | Below is the the instruction that describes the task:
### Input:
Placeholders for fields names and value binds
### Response:
def placeholders(cls,dic):
"""Placeholders for fields names and value binds"""
keys = [str(x) for x in dic]
entete = ",".join(keys)
placeholders = ",".join(cl... |
def create(self, customer_name, street, city, region, postal_code, iso_country,
friendly_name=values.unset, emergency_enabled=values.unset,
auto_correct_address=values.unset):
"""
Create a new AddressInstance
:param unicode customer_name: The name to associate with... | Create a new AddressInstance
:param unicode customer_name: The name to associate with the new address
:param unicode street: The number and street address of the new address
:param unicode city: The city of the new address
:param unicode region: The state or region of the new address
... | Below is the the instruction that describes the task:
### Input:
Create a new AddressInstance
:param unicode customer_name: The name to associate with the new address
:param unicode street: The number and street address of the new address
:param unicode city: The city of the new address
... |
def get_nehrp_classes(self, sites):
"""
Site classification threshholds from Section 4 "Site correction
coefficients" p. 205. Note that site classes E and F are not
supported.
"""
classes = sorted(self.NEHRP_VS30_UPPER_BOUNDS.keys())
bounds = [self.NEHRP_VS30_UPP... | Site classification threshholds from Section 4 "Site correction
coefficients" p. 205. Note that site classes E and F are not
supported. | Below is the the instruction that describes the task:
### Input:
Site classification threshholds from Section 4 "Site correction
coefficients" p. 205. Note that site classes E and F are not
supported.
### Response:
def get_nehrp_classes(self, sites):
"""
Site classification threshho... |
def submit(self):
"""Submits a chagelist to the depot"""
if self._dirty:
self.save()
self._connection.run(['submit', '-c', str(self._change)], marshal_output=False) | Submits a chagelist to the depot | Below is the the instruction that describes the task:
### Input:
Submits a chagelist to the depot
### Response:
def submit(self):
"""Submits a chagelist to the depot"""
if self._dirty:
self.save()
self._connection.run(['submit', '-c', str(self._change)], marshal_output=False) |
def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pycodestyle.stdin_get_value()
else:
with pep257.tokenize_open(self.filename) as fd:
self.source = fd.read() | Load the source for the specified file. | Below is the the instruction that describes the task:
### Input:
Load the source for the specified file.
### Response:
def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pycodestyle.stdin_get_value()
... |
def remove(self, doc_type, doc_ids, **kwargs):
""" Implements call to remove the documents from the index """
try:
# ignore is flagged as an unexpected-keyword-arg; ES python client documents that it can be used
# pylint: disable=unexpected-keyword-arg
actions = []
... | Implements call to remove the documents from the index | Below is the the instruction that describes the task:
### Input:
Implements call to remove the documents from the index
### Response:
def remove(self, doc_type, doc_ids, **kwargs):
""" Implements call to remove the documents from the index """
try:
# ignore is flagged as an unexpected-... |
def nub(it):
'''Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``.
'''
seen = set()
for v in it:
h = hash(v)
if h in seen:
continue
seen.add(h)
yield v | Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``. | Below is the the instruction that describes the task:
### Input:
Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``.
### Response:
def nub(it):
'''Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it... |
def __display_left(self, stat_display):
"""Display the left sidebar in the Curses interface."""
self.init_column()
if self.args.disable_left_sidebar:
return
for s in self._left_sidebar:
if ((hasattr(self.args, 'enable_' + s) or
hasattr(self.args... | Display the left sidebar in the Curses interface. | Below is the the instruction that describes the task:
### Input:
Display the left sidebar in the Curses interface.
### Response:
def __display_left(self, stat_display):
"""Display the left sidebar in the Curses interface."""
self.init_column()
if self.args.disable_left_sidebar:
... |
def create_dataset(parent, path, overwrite=False, **kwargs):
"""Create a new dataset inside the parent HDF5 object
Parameters
----------
parent : `h5py.Group`, `h5py.File`
the object in which to create a new dataset
path : `str`
the path at which to create the new dataset
over... | Create a new dataset inside the parent HDF5 object
Parameters
----------
parent : `h5py.Group`, `h5py.File`
the object in which to create a new dataset
path : `str`
the path at which to create the new dataset
overwrite : `bool`
if `True`, delete any existing dataset at the... | Below is the the instruction that describes the task:
### Input:
Create a new dataset inside the parent HDF5 object
Parameters
----------
parent : `h5py.Group`, `h5py.File`
the object in which to create a new dataset
path : `str`
the path at which to create the new dataset
ove... |
def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
'''This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set ... | This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set to parsed arguments. | Below is the the instruction that describes the task:
### Input:
This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set to parsed ar... |
def send_mfg_inspector_data(inspector_proto, credentials, destination_url):
"""Upload MfgEvent to steam_engine."""
envelope = guzzle_pb2.TestRunEnvelope()
envelope.payload = zlib.compress(inspector_proto.SerializeToString())
envelope.payload_type = guzzle_pb2.COMPRESSED_MFG_EVENT
envelope_data = envelope.Seri... | Upload MfgEvent to steam_engine. | Below is the the instruction that describes the task:
### Input:
Upload MfgEvent to steam_engine.
### Response:
def send_mfg_inspector_data(inspector_proto, credentials, destination_url):
"""Upload MfgEvent to steam_engine."""
envelope = guzzle_pb2.TestRunEnvelope()
envelope.payload = zlib.compress(inspector... |
def fix_field_params_repr(params):
"""
Fixes repr() of "field_params" for Python 2 with future text_type_literals.
"""
class ReprUnicode(text_type):
def __new__(cls, text):
return text_type.__new__(cls, text)
def __repr__(self):
out = repr(text_type(self))
... | Fixes repr() of "field_params" for Python 2 with future text_type_literals. | Below is the the instruction that describes the task:
### Input:
Fixes repr() of "field_params" for Python 2 with future text_type_literals.
### Response:
def fix_field_params_repr(params):
"""
Fixes repr() of "field_params" for Python 2 with future text_type_literals.
"""
class ReprUnicode(text_ty... |
def close_holes(script, hole_max_edge=30, selected=False,
sel_new_face=True, self_intersection=True):
""" Close holes smaller than a given threshold
Args:
script: the FilterScript object or script filename to write
the filter to.
hole_max_edge (int): The size is expr... | Close holes smaller than a given threshold
Args:
script: the FilterScript object or script filename to write
the filter to.
hole_max_edge (int): The size is expressed as number of edges composing
the hole boundary.
selected (bool): Only the holes with at least one of... | Below is the the instruction that describes the task:
### Input:
Close holes smaller than a given threshold
Args:
script: the FilterScript object or script filename to write
the filter to.
hole_max_edge (int): The size is expressed as number of edges composing
the hole b... |
def pretty_descriptor(self):
"""
get the class or interface name, its accessor flags, its parent
class, and any interfaces it implements
"""
f = " ".join(self.pretty_access_flags())
if not self.is_interface():
f += " class"
n = self.pretty_this()
... | get the class or interface name, its accessor flags, its parent
class, and any interfaces it implements | Below is the the instruction that describes the task:
### Input:
get the class or interface name, its accessor flags, its parent
class, and any interfaces it implements
### Response:
def pretty_descriptor(self):
"""
get the class or interface name, its accessor flags, its parent
cla... |
def find_mismatch(self, other, indent=''):
"""
Highlights where two nodes differ in a human-readable form
Parameters
----------
other : TreeNode
The node to compare
indent : str
The white-space with which to indent output string
Returns
... | Highlights where two nodes differ in a human-readable form
Parameters
----------
other : TreeNode
The node to compare
indent : str
The white-space with which to indent output string
Returns
-------
mismatch : str
The human-rea... | Below is the the instruction that describes the task:
### Input:
Highlights where two nodes differ in a human-readable form
Parameters
----------
other : TreeNode
The node to compare
indent : str
The white-space with which to indent output string
Ret... |
def calc_snu(eta, kappa, width, elongation, dist):
"""Calculate the flux density S_ν given a simple physical configuration.
This is basic radiative transfer as per Dulk (1985) equations 5, 6, and 11.
eta
The emissivity, in units of ``erg s^-1 Hz^-1 cm^-3 sr^-1``.
kappa
The absorption coeff... | Calculate the flux density S_ν given a simple physical configuration.
This is basic radiative transfer as per Dulk (1985) equations 5, 6, and 11.
eta
The emissivity, in units of ``erg s^-1 Hz^-1 cm^-3 sr^-1``.
kappa
The absorption coefficient, in units of ``cm^-1``.
width
The charact... | Below is the the instruction that describes the task:
### Input:
Calculate the flux density S_ν given a simple physical configuration.
This is basic radiative transfer as per Dulk (1985) equations 5, 6, and 11.
eta
The emissivity, in units of ``erg s^-1 Hz^-1 cm^-3 sr^-1``.
kappa
The absor... |
def dice_coeff(im1, im2, val=1):
''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representin... | Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representing one ROI out of many in the parcellation... | Below is the the instruction that describes the task:
### Input:
Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. ... |
def update(self, **kwargs):
"""Call this to change the configuration of the service on the device.
This method uses HTTP PUT to alter the service state on the device.
The attributes of the instance will be packaged as a dictionary. That
dictionary will be updated with kwargs. It is t... | Call this to change the configuration of the service on the device.
This method uses HTTP PUT to alter the service state on the device.
The attributes of the instance will be packaged as a dictionary. That
dictionary will be updated with kwargs. It is then submitted as JSON
to the de... | Below is the the instruction that describes the task:
### Input:
Call this to change the configuration of the service on the device.
This method uses HTTP PUT to alter the service state on the device.
The attributes of the instance will be packaged as a dictionary. That
dictionary will be... |
def ServiceWorker_dispatchSyncEvent(self, origin, registrationId, tag,
lastChance):
"""
Function path: ServiceWorker.dispatchSyncEvent
Domain: ServiceWorker
Method name: dispatchSyncEvent
Parameters:
Required arguments:
'origin' (type: string) -> No description
'registrationId' (type:... | Function path: ServiceWorker.dispatchSyncEvent
Domain: ServiceWorker
Method name: dispatchSyncEvent
Parameters:
Required arguments:
'origin' (type: string) -> No description
'registrationId' (type: string) -> No description
'tag' (type: string) -> No description
'lastChance' (type: b... | Below is the the instruction that describes the task:
### Input:
Function path: ServiceWorker.dispatchSyncEvent
Domain: ServiceWorker
Method name: dispatchSyncEvent
Parameters:
Required arguments:
'origin' (type: string) -> No description
'registrationId' (type: string) -> No description
... |
def led_control_encode(self, target_system, target_component, instance, pattern, custom_len, custom_bytes):
'''
Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instanc... | Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instance : Instance (LED instance to control or 255 for all LEDs) (uint8_t)
pattern : Pattern (see L... | Below is the the instruction that describes the task:
### Input:
Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instance : Instance (LED instance to control or 255 for all LEDs)... |
def __extract_lemmas(self, doc, m, phrase):
"""
:param sent: sentence from which the match was found
:param m: the found match
:phrase: name of the phrase
:return: tuple of the lemmas in the match
"""
ph_start = m['start']
ph_end = m['end']
start_... | :param sent: sentence from which the match was found
:param m: the found match
:phrase: name of the phrase
:return: tuple of the lemmas in the match | Below is the the instruction that describes the task:
### Input:
:param sent: sentence from which the match was found
:param m: the found match
:phrase: name of the phrase
:return: tuple of the lemmas in the match
### Response:
def __extract_lemmas(self, doc, m, phrase):
"""
... |
def _add_remove_user_template(self, url, template_id, account_id=None, email_address=None):
''' Add or Remove user from a Template
We use this function for two tasks because they have the same API call
Args:
template_id (str): The id of the template
account_id (s... | Add or Remove user from a Template
We use this function for two tasks because they have the same API call
Args:
template_id (str): The id of the template
account_id (str): ID of the account to add/remove access to/from
email_address (str): The email... | Below is the the instruction that describes the task:
### Input:
Add or Remove user from a Template
We use this function for two tasks because they have the same API call
Args:
template_id (str): The id of the template
account_id (str): ID of the account to add... |
def _plan_on_valid_line(self, at_line, final_line_count):
"""Check if a plan is on a valid line."""
# Put the common cases first.
if at_line == 1 or at_line == final_line_count:
return True
# The plan may only appear on line 2 if the version is at line 1.
after_versi... | Check if a plan is on a valid line. | Below is the the instruction that describes the task:
### Input:
Check if a plan is on a valid line.
### Response:
def _plan_on_valid_line(self, at_line, final_line_count):
"""Check if a plan is on a valid line."""
# Put the common cases first.
if at_line == 1 or at_line == final_line_count... |
def pack_word(self, offset, word):
"""
Applies the little-endian WORD (2 bytes) to the relative offset.
Arguments:
- `offset`: The relative offset from the start of the block.
- `word`: The data to apply.
"""
o = self._offset + offset
return struct.pack_in... | Applies the little-endian WORD (2 bytes) to the relative offset.
Arguments:
- `offset`: The relative offset from the start of the block.
- `word`: The data to apply. | Below is the the instruction that describes the task:
### Input:
Applies the little-endian WORD (2 bytes) to the relative offset.
Arguments:
- `offset`: The relative offset from the start of the block.
- `word`: The data to apply.
### Response:
def pack_word(self, offset, word):
"""... |
def items_differ(jsonitems, dbitems, subfield_dict):
""" check whether or not jsonitems and dbitems differ """
# short circuit common cases
if len(jsonitems) == len(dbitems) == 0:
# both are empty
return False
elif len(jsonitems) != len(dbitems):
# if lengths differ, they're def... | check whether or not jsonitems and dbitems differ | Below is the the instruction that describes the task:
### Input:
check whether or not jsonitems and dbitems differ
### Response:
def items_differ(jsonitems, dbitems, subfield_dict):
""" check whether or not jsonitems and dbitems differ """
# short circuit common cases
if len(jsonitems) == len(dbitems)... |
def is_corrupted(l, sym, input_v):
"""
This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
... | This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
The VersionStore instance against which ... | Below is the the instruction that describes the task:
### Input:
This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_sto... |
def command(self):
"""Returns a string representing the command you have to type to obtain the same packet"""
f = []
for fn,fv in self.fields.items():
fld = self.get_field(fn)
if isinstance(fv, Packet):
fv = fv.command()
elif fld.islist and fld... | Returns a string representing the command you have to type to obtain the same packet | Below is the the instruction that describes the task:
### Input:
Returns a string representing the command you have to type to obtain the same packet
### Response:
def command(self):
"""Returns a string representing the command you have to type to obtain the same packet"""
f = []
for fn,fv ... |
def main(argv):
"""Run Minigo in GTP mode."""
del argv
engine = make_gtp_instance(FLAGS.load_file,
cgos_mode=FLAGS.cgos_mode,
kgs_mode=FLAGS.kgs_mode,
minigui_mode=FLAGS.minigui_mode)
dbg("GTP engine ready\n")
... | Run Minigo in GTP mode. | Below is the the instruction that describes the task:
### Input:
Run Minigo in GTP mode.
### Response:
def main(argv):
"""Run Minigo in GTP mode."""
del argv
engine = make_gtp_instance(FLAGS.load_file,
cgos_mode=FLAGS.cgos_mode,
kgs_mode=FLA... |
def _mixed_precision_is_enabled(hparams):
"""Should be the same as in common_attention, avoiding import."""
activation_dtype = hparams.activation_dtype
weight_dtype = hparams.weight_dtype
return activation_dtype == tf.float16 and weight_dtype == tf.float32 | Should be the same as in common_attention, avoiding import. | Below is the the instruction that describes the task:
### Input:
Should be the same as in common_attention, avoiding import.
### Response:
def _mixed_precision_is_enabled(hparams):
"""Should be the same as in common_attention, avoiding import."""
activation_dtype = hparams.activation_dtype
weight_dtype = hpa... |
def ipvoid_check(ip):
"""Checks IPVoid.com for info on an IP address"""
if not is_IPv4Address(ip):
return None
return_dict = {}
headers = {'User-Agent': useragent}
url = 'http://ipvoid.com/scan/%s/' % ip
response = requests.get(url, headers=headers)
data = BeautifulSoup(response.tex... | Checks IPVoid.com for info on an IP address | Below is the the instruction that describes the task:
### Input:
Checks IPVoid.com for info on an IP address
### Response:
def ipvoid_check(ip):
"""Checks IPVoid.com for info on an IP address"""
if not is_IPv4Address(ip):
return None
return_dict = {}
headers = {'User-Agent': useragent}
... |
def close(self):
"""Close the connection"""
if self.pinger:
self.pinger.cancel()
self.pinger = None
if getattr(self, 'protocol', None):
self.protocol.close() | Close the connection | Below is the the instruction that describes the task:
### Input:
Close the connection
### Response:
def close(self):
"""Close the connection"""
if self.pinger:
self.pinger.cancel()
self.pinger = None
if getattr(self, 'protocol', None):
self.protocol.close... |
def _mask_invalid(self, data, header):
"""Mask invalid data"""
invalid = da.logical_or(data == header['block5']["count_value_outside_scan_pixels"][0],
data == header['block5']["count_value_error_pixels"][0])
return da.where(invalid, np.float32(np.nan), data) | Mask invalid data | Below is the the instruction that describes the task:
### Input:
Mask invalid data
### Response:
def _mask_invalid(self, data, header):
"""Mask invalid data"""
invalid = da.logical_or(data == header['block5']["count_value_outside_scan_pixels"][0],
data == header['blo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.