code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def validate_slice_increment(dicoms):
"""
Validate that the distance between all slices is equal (or very close to)
:param dicoms: list of dicoms
"""
first_image_position = numpy.array(dicoms[0].ImagePositionPatient)
previous_image_position = numpy.array(dicoms[1].ImagePositionPatient)
inc... | Validate that the distance between all slices is equal (or very close to)
:param dicoms: list of dicoms | Below is the the instruction that describes the task:
### Input:
Validate that the distance between all slices is equal (or very close to)
:param dicoms: list of dicoms
### Response:
def validate_slice_increment(dicoms):
"""
Validate that the distance between all slices is equal (or very close to)
... |
def bind(cls, target):
"""Bind a copy of the collection to the class, modified per our class' settings.
The given target (and eventual collection returned) must be safe within the context the document sublcass
being bound is constructed within. E.g. at the module scope this binding must be thread-safe.
"""
... | Bind a copy of the collection to the class, modified per our class' settings.
The given target (and eventual collection returned) must be safe within the context the document sublcass
being bound is constructed within. E.g. at the module scope this binding must be thread-safe. | Below is the the instruction that describes the task:
### Input:
Bind a copy of the collection to the class, modified per our class' settings.
The given target (and eventual collection returned) must be safe within the context the document sublcass
being bound is constructed within. E.g. at the module scope ... |
def unpack(self, column_name_prefix = "X", column_types=None, na_value=None, limit=None):
"""
Convert an SArray of list, array, or dict type to an SFrame with
multiple columns.
`unpack` expands an SArray using the values of each list/array/dict as
elements in a new SFrame of mul... | Convert an SArray of list, array, or dict type to an SFrame with
multiple columns.
`unpack` expands an SArray using the values of each list/array/dict as
elements in a new SFrame of multiple columns. For example, an SArray of
lists each of length 4 will be expanded into an SFrame of 4 c... | Below is the the instruction that describes the task:
### Input:
Convert an SArray of list, array, or dict type to an SFrame with
multiple columns.
`unpack` expands an SArray using the values of each list/array/dict as
elements in a new SFrame of multiple columns. For example, an SArray of
... |
def do_read(self, args):
"""read <addr> ( <objid> ( <prop> [ <indx> ] )... )..."""
args = args.split()
if _debug: ReadPropertyMultipleConsoleCmd._debug("do_read %r", args)
try:
i = 0
addr = args[i]
i += 1
read_access_spec_list = []
... | read <addr> ( <objid> ( <prop> [ <indx> ] )... )... | Below is the the instruction that describes the task:
### Input:
read <addr> ( <objid> ( <prop> [ <indx> ] )... )...
### Response:
def do_read(self, args):
"""read <addr> ( <objid> ( <prop> [ <indx> ] )... )..."""
args = args.split()
if _debug: ReadPropertyMultipleConsoleCmd._debug("do_read... |
def _clean():
"""
Cleans up build dir
"""
LOGGER.info('Cleaning project directory...')
folders_to_cleanup = [
'.eggs',
'build',
f'{config.PACKAGE_NAME()}.egg-info',
]
for folder in folders_to_cleanup:
if os.path.exists(folder):
LOGGER.info('\tremov... | Cleans up build dir | Below is the the instruction that describes the task:
### Input:
Cleans up build dir
### Response:
def _clean():
"""
Cleans up build dir
"""
LOGGER.info('Cleaning project directory...')
folders_to_cleanup = [
'.eggs',
'build',
f'{config.PACKAGE_NAME()}.egg-info',
]
... |
def find_bookmark_file ():
"""Return the bookmark file of the Default profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found.
"""
if sys.platform != 'darwin':
return u""
try:
dirname = get_profile_dir()
if os.path.isdir(dirname):
... | Return the bookmark file of the Default profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found. | Below is the the instruction that describes the task:
### Input:
Return the bookmark file of the Default profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found.
### Response:
def find_bookmark_file ():
"""Return the bookmark file of the Default profile.
Retu... |
def has_argument(arg, arguments):
"""
Verifica se ci sono argument con la classe.
"""
try:
if not isinstance(arguments, list):
arguments = arguments.__arguments__
for idx, (args, kwargs) in enumerate(arguments):
arg_name = kwargs.get(
'dest', args[... | Verifica se ci sono argument con la classe. | Below is the the instruction that describes the task:
### Input:
Verifica se ci sono argument con la classe.
### Response:
def has_argument(arg, arguments):
"""
Verifica se ci sono argument con la classe.
"""
try:
if not isinstance(arguments, list):
arguments = arguments.__argum... |
def get_jwt(self, request):
"""Extract the JWT token from the authorisation header of the request.
Returns the JWT token or None, if the token cannot be extracted.
:param request: request object.
:type request: :class:`morepath.Request`
"""
try:
authorizatio... | Extract the JWT token from the authorisation header of the request.
Returns the JWT token or None, if the token cannot be extracted.
:param request: request object.
:type request: :class:`morepath.Request` | Below is the the instruction that describes the task:
### Input:
Extract the JWT token from the authorisation header of the request.
Returns the JWT token or None, if the token cannot be extracted.
:param request: request object.
:type request: :class:`morepath.Request`
### Response:
def ... |
def acquire_connection(settings, tag=None, logger_name=None, auto_commit=False):
"""
Return a connection to a Relational DataBase Management System (RDBMS)
the most appropriate for the service requesting this connection.
@param settings: a dictionary of connection properties::
... | Return a connection to a Relational DataBase Management System (RDBMS)
the most appropriate for the service requesting this connection.
@param settings: a dictionary of connection properties::
{
None: {
'rdbms_hostname': "...",
... | Below is the the instruction that describes the task:
### Input:
Return a connection to a Relational DataBase Management System (RDBMS)
the most appropriate for the service requesting this connection.
@param settings: a dictionary of connection properties::
{
... |
def exit(self, pub_id, *node_ids):
'''Agents will notify the pub they want to leave'''
try:
pub = self['pubs'][pub_id]
except KeyError:
raise ValueError('Pub {} is not available'.format(pub_id))
for node_id in node_ids:
node = self.get_agent(node_id)
... | Agents will notify the pub they want to leave | Below is the the instruction that describes the task:
### Input:
Agents will notify the pub they want to leave
### Response:
def exit(self, pub_id, *node_ids):
'''Agents will notify the pub they want to leave'''
try:
pub = self['pubs'][pub_id]
except KeyError:
raise ... |
def rle_encode(img:NPArrayMask)->str:
"Return run-length encoding string from `img`."
pixels = np.concatenate([[0], img.flatten() , [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x) for x in runs) | Return run-length encoding string from `img`. | Below is the the instruction that describes the task:
### Input:
Return run-length encoding string from `img`.
### Response:
def rle_encode(img:NPArrayMask)->str:
"Return run-length encoding string from `img`."
pixels = np.concatenate([[0], img.flatten() , [0]])
runs = np.where(pixels[1:] != pixels[:-1... |
def _security_auth_headers(self, username, password, headers):
"""
Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:... | Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:type dict | Below is the the instruction that describes the task:
### Input:
Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:type dict
### ... |
def count_passed_node_filter(graph: BELGraph, node_predicates: NodePredicates) -> int:
"""Count how many nodes pass a given set of node predicates."""
return sum(1 for _ in filter_nodes(graph, node_predicates=node_predicates)) | Count how many nodes pass a given set of node predicates. | Below is the the instruction that describes the task:
### Input:
Count how many nodes pass a given set of node predicates.
### Response:
def count_passed_node_filter(graph: BELGraph, node_predicates: NodePredicates) -> int:
"""Count how many nodes pass a given set of node predicates."""
return sum(1 for _ ... |
def update(self, table_name, set_query, where=None):
"""Execute an UPDATE query.
Args:
table_name (|str|):
Table name of executing the query.
set_query (|str|):
``SET`` clause for the update query.
where (|arg_where_type| , optional):
... | Execute an UPDATE query.
Args:
table_name (|str|):
Table name of executing the query.
set_query (|str|):
``SET`` clause for the update query.
where (|arg_where_type| , optional):
``WHERE`` clause for the update query.
... | Below is the the instruction that describes the task:
### Input:
Execute an UPDATE query.
Args:
table_name (|str|):
Table name of executing the query.
set_query (|str|):
``SET`` clause for the update query.
where (|arg_where_type| , option... |
def webserver_list():
"""
list of webserver packages
"""
p = set(get_packages())
w = set(['apache2','gunicorn','uwsgi','nginx'])
installed = p & w
return list(installed) | list of webserver packages | Below is the the instruction that describes the task:
### Input:
list of webserver packages
### Response:
def webserver_list():
"""
list of webserver packages
"""
p = set(get_packages())
w = set(['apache2','gunicorn','uwsgi','nginx'])
installed = p & w
return list(installed) |
def UUIDField(default=NOTHING, required=False, repr=True, cmp=True, key=None):
"""
Create new UUID field on a model.
:param default: any value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param ... | Create new UUID field on a model.
:param default: any value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name ... | Below is the the instruction that describes the task:
### Input:
Create new UUID field on a model.
:param default: any value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this... |
def server_add_and_update_opts(*args, **kwargs):
"""
shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to know if it's being used as `add` or `update`.
usage:
>>> @server_add_and_update_opts
>>> def command... | shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to know if it's being used as `add` or `update`.
usage:
>>> @server_add_and_update_opts
>>> def command_func(subject, port, scheme, hostname):
>>> ...
... | Below is the the instruction that describes the task:
### Input:
shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to know if it's being used as `add` or `update`.
usage:
>>> @server_add_and_update_opts
>>> def... |
def _save_queue(self):
"""Save the current state of the queue."""
if self.queue is not None:
# Maximum batch is 486, anything larger will still only
# return 486
batch_size = 400
total = 0
num_return = batch_size
# Need to get all ... | Save the current state of the queue. | Below is the the instruction that describes the task:
### Input:
Save the current state of the queue.
### Response:
def _save_queue(self):
"""Save the current state of the queue."""
if self.queue is not None:
# Maximum batch is 486, anything larger will still only
# return 4... |
def _anomalyScoreMovingAverage(anomalyScores,
windowSize=10,
verbosity=0,
):
"""
Given a list of anomaly scores return a list of averaged records.
anomalyScores is assumed to be a list of records of the form:
... | Given a list of anomaly scores return a list of averaged records.
anomalyScores is assumed to be a list of records of the form:
[datetime.datetime(2013, 8, 10, 23, 0), 6.0, 1.0]
Each record in the returned list list contains:
[datetime, value, averagedScore]
*Note:* we only average the ano... | Below is the the instruction that describes the task:
### Input:
Given a list of anomaly scores return a list of averaged records.
anomalyScores is assumed to be a list of records of the form:
[datetime.datetime(2013, 8, 10, 23, 0), 6.0, 1.0]
Each record in the returned list list contains:
... |
def month(self):
"""
Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat.
"""
url = "/stats/month"
result = self._get(url)
return StatModel.parse(result) | Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat. | Below is the the instruction that describes the task:
### Input:
Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat.
### Response:
def month(self):
"""
Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat.
... |
def semester_feature(catalog, soup):
"""The year and semester information that this xml file hold courses for.
"""
raw = _text(soup.findAll('h3')).split('\n')[1]
match = RE_SEMESTER_RANGE.match(raw)
catalog.year = int(match.group('year'))
#month_mapping = {'Spring': 1, 'Summer': 5, 'Fall': 9}
... | The year and semester information that this xml file hold courses for. | Below is the the instruction that describes the task:
### Input:
The year and semester information that this xml file hold courses for.
### Response:
def semester_feature(catalog, soup):
"""The year and semester information that this xml file hold courses for.
"""
raw = _text(soup.findAll('h3')).split(... |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
if name in CELESTIAL_TIME_TYPES:
namespace = 'time'
domain = 'Celestial Time Systems'
time_name = CELESTIAL_TIME_TYPES[nam... | Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type | Below is the the instruction that describes the task:
### Input:
Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
### Response:
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives... |
def fetchThreadInfo(self, *thread_ids):
"""
Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread` objects... | Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread` objects, labeled by their ID
:rtype: dict
:raises: ... | Below is the the instruction that describes the task:
### Input:
Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread... |
def process_login(context, request):
"""Authenticate username and password and log in user"""
username = request.json['username']
password = request.json['password']
# Do the password validation.
user = context.authenticate(username, password)
if not user:
@request.after
def adj... | Authenticate username and password and log in user | Below is the the instruction that describes the task:
### Input:
Authenticate username and password and log in user
### Response:
def process_login(context, request):
"""Authenticate username and password and log in user"""
username = request.json['username']
password = request.json['password']
# ... |
def body_as_str(self, encoding='UTF-8'):
"""
The body of the event data as a string if the data is of a
compatible type.
:param encoding: The encoding to use for decoding message data.
Default is 'UTF-8'
:rtype: str or unicode
"""
data = self.body
... | The body of the event data as a string if the data is of a
compatible type.
:param encoding: The encoding to use for decoding message data.
Default is 'UTF-8'
:rtype: str or unicode | Below is the the instruction that describes the task:
### Input:
The body of the event data as a string if the data is of a
compatible type.
:param encoding: The encoding to use for decoding message data.
Default is 'UTF-8'
:rtype: str or unicode
### Response:
def body_as_str(self... |
def _set_active_tools(self, plot):
"Activates the list of active tools"
for tool in self.active_tools:
if isinstance(tool, util.basestring):
tool_type = TOOL_TYPES[tool]
matching = [t for t in plot.toolbar.tools
if isinstance(t, too... | Activates the list of active tools | Below is the the instruction that describes the task:
### Input:
Activates the list of active tools
### Response:
def _set_active_tools(self, plot):
"Activates the list of active tools"
for tool in self.active_tools:
if isinstance(tool, util.basestring):
tool_type = TOOL... |
def update_template(self, template_id, template_dict):
"""
Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict
"""
return self._create_put_request(
resource=TEMPLATES,
billomat_id=template_id,
... | Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict | Below is the the instruction that describes the task:
### Input:
Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict
### Response:
def update_template(self, template_id, template_dict):
"""
Updates a template
:param templ... |
def server_delete(endpoint_id, server):
"""
Executor for `globus endpoint server show`
"""
client = get_client()
mode = _detect_mode(server)
# list (even if not necessary) in order to make errors more consistent when
# mode='id'
endpoint, server_list = get_endpoint_w_server_list(endpoi... | Executor for `globus endpoint server show` | Below is the the instruction that describes the task:
### Input:
Executor for `globus endpoint server show`
### Response:
def server_delete(endpoint_id, server):
"""
Executor for `globus endpoint server show`
"""
client = get_client()
mode = _detect_mode(server)
# list (even if not necess... |
def _createDefaultPolicy(cls):
""" [private] Create the default database connection policy instance
Parameters:
----------------------------------------------------------------
retval: The default database connection policy instance
"""
logger = _getLogger(cls)
logger.debug(
... | [private] Create the default database connection policy instance
Parameters:
----------------------------------------------------------------
retval: The default database connection policy instance | Below is the the instruction that describes the task:
### Input:
[private] Create the default database connection policy instance
Parameters:
----------------------------------------------------------------
retval: The default database connection policy instance
### Response:
def _createDef... |
def SNR_hinken(imgs, bg=0, roi=None):
'''
signal-to-noise ratio (SNR) as mean(images) / std(images)
as defined in Hinken et.al. 2011 (DOI: 10.1063/1.3541766)
works on unloaded images
no memory overload if too many images are given
'''
mean = None
M = len(imgs)
if bg is... | signal-to-noise ratio (SNR) as mean(images) / std(images)
as defined in Hinken et.al. 2011 (DOI: 10.1063/1.3541766)
works on unloaded images
no memory overload if too many images are given | Below is the the instruction that describes the task:
### Input:
signal-to-noise ratio (SNR) as mean(images) / std(images)
as defined in Hinken et.al. 2011 (DOI: 10.1063/1.3541766)
works on unloaded images
no memory overload if too many images are given
### Response:
def SNR_hinken(imgs, bg=0,... |
def renames(old, new):
# type: (str, str) -> None
"""Like os.renames(), but handles renaming across devices."""
# Implementation borrowed from os.renames().
head, tail = os.path.split(new)
if head and tail and not os.path.exists(head):
os.makedirs(head)
shutil.move(old, new)
head, ... | Like os.renames(), but handles renaming across devices. | Below is the the instruction that describes the task:
### Input:
Like os.renames(), but handles renaming across devices.
### Response:
def renames(old, new):
# type: (str, str) -> None
"""Like os.renames(), but handles renaming across devices."""
# Implementation borrowed from os.renames().
head, t... |
def remove(self, *args):
"""Remove the instance tied to the field for the given "value" (via `args`) from the index
For the parameters, see ``BaseIndex.remove``
Notes
-----
This method calls the ``unstore`` method that should be overridden in subclasses
to remove data f... | Remove the instance tied to the field for the given "value" (via `args`) from the index
For the parameters, see ``BaseIndex.remove``
Notes
-----
This method calls the ``unstore`` method that should be overridden in subclasses
to remove data from the index sorted-set key | Below is the the instruction that describes the task:
### Input:
Remove the instance tied to the field for the given "value" (via `args`) from the index
For the parameters, see ``BaseIndex.remove``
Notes
-----
This method calls the ``unstore`` method that should be overridden in su... |
def lapmod(n, cc, ii, kk, fast=True, return_cost=True,
fp_version=FP_DYNAMIC):
"""Solve sparse linear assignment problem using Jonker-Volgenant algorithm.
n: number of rows of the assignment cost matrix
cc: 1D array of all finite elements of the assignement cost matrix
ii: 1D array of indice... | Solve sparse linear assignment problem using Jonker-Volgenant algorithm.
n: number of rows of the assignment cost matrix
cc: 1D array of all finite elements of the assignement cost matrix
ii: 1D array of indices of the row starts in cc. The following must hold:
ii[0] = 0 and ii[n+1] = len(cc).
... | Below is the the instruction that describes the task:
### Input:
Solve sparse linear assignment problem using Jonker-Volgenant algorithm.
n: number of rows of the assignment cost matrix
cc: 1D array of all finite elements of the assignement cost matrix
ii: 1D array of indices of the row starts in cc. T... |
def log_request(self, code='-', size='-'):
"""Logs the current request."""
print_size = getattr(thread_local, 'size', -1)
if size != '-':
size_str = ' (%s)' % size
elif print_size >= 0:
size_str = self.log_size_string(print_size) + ' '
else:
si... | Logs the current request. | Below is the the instruction that describes the task:
### Input:
Logs the current request.
### Response:
def log_request(self, code='-', size='-'):
"""Logs the current request."""
print_size = getattr(thread_local, 'size', -1)
if size != '-':
size_str = ' (%s)' % size
el... |
def make_logs_df(fns, define_sample_name=None):
"""Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample nam... | Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name i... | Below is the the instruction that describes the task:
### Input:
Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename... |
def remove_data_point(self, x, y):
"""Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last data point from\
... | Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last data point from\
a series. | Below is the the instruction that describes the task:
### Input:
Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last ... |
def _generatePayload(self, query):
"""Adds the following defaults to the payload:
__rev, __user, __a, ttstamp, fb_dtsg, __req
"""
payload = self._payload_default.copy()
if query:
payload.update(query)
payload["__req"] = str_base(self._req_counter, 36)
... | Adds the following defaults to the payload:
__rev, __user, __a, ttstamp, fb_dtsg, __req | Below is the the instruction that describes the task:
### Input:
Adds the following defaults to the payload:
__rev, __user, __a, ttstamp, fb_dtsg, __req
### Response:
def _generatePayload(self, query):
"""Adds the following defaults to the payload:
__rev, __user, __a, ttstamp, fb_dtsg, ... |
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str... | Determine if the given node is a docstring, as long as it is at the
correct place in the node tree. | Below is the the instruction that describes the task:
### Input:
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
### Response:
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
cor... |
def radians(degrees=0, arcminutes=0, arcseconds=0):
"""
TODO docs.
"""
if arcminutes:
degrees += arcminutes / arcmin(degrees=1.)
if arcseconds:
degrees += arcseconds / arcsec(degrees=1.)
return math.radians(degrees) | TODO docs. | Below is the the instruction that describes the task:
### Input:
TODO docs.
### Response:
def radians(degrees=0, arcminutes=0, arcseconds=0):
"""
TODO docs.
"""
if arcminutes:
degrees += arcminutes / arcmin(degrees=1.)
if arcseconds:
degrees += arcseconds / arcsec(degrees=1.)
... |
def _aggregate(df, by):
"""Aggregate `df` by specified column(s), return indexed `pd.Series`"""
by = [by] if isstr(by) else by
cols = [c for c in list(df.columns) if c not in ['value'] + by]
return df.groupby(cols).sum()['value'] | Aggregate `df` by specified column(s), return indexed `pd.Series` | Below is the the instruction that describes the task:
### Input:
Aggregate `df` by specified column(s), return indexed `pd.Series`
### Response:
def _aggregate(df, by):
"""Aggregate `df` by specified column(s), return indexed `pd.Series`"""
by = [by] if isstr(by) else by
cols = [c for c in list(df.colu... |
def read_shapefile(fname, region_col=None, **kwargs):
"""Read a shapefile for use in regional plots. Shapefiles must have a
column denoted as "region".
Parameters
----------
fname : string
path to shapefile to be read by geopandas
region_col : string, default None
if provided, r... | Read a shapefile for use in regional plots. Shapefiles must have a
column denoted as "region".
Parameters
----------
fname : string
path to shapefile to be read by geopandas
region_col : string, default None
if provided, rename a column in the shapefile to "region" | Below is the the instruction that describes the task:
### Input:
Read a shapefile for use in regional plots. Shapefiles must have a
column denoted as "region".
Parameters
----------
fname : string
path to shapefile to be read by geopandas
region_col : string, default None
if pro... |
def apply_M(self, ax, ay):
"""Linear operator that converts ax, ay to abcd.
"""
jac = numpy.array(
[[self.dx.dot(ax), self.dy.dot(ax)], [self.dx.dot(ay), self.dy.dot(ay)]]
)
# jacs and J are of shape (2, 2, k). M must be of the same shape and
# contain the re... | Linear operator that converts ax, ay to abcd. | Below is the the instruction that describes the task:
### Input:
Linear operator that converts ax, ay to abcd.
### Response:
def apply_M(self, ax, ay):
"""Linear operator that converts ax, ay to abcd.
"""
jac = numpy.array(
[[self.dx.dot(ax), self.dy.dot(ax)], [self.dx.dot(ay), ... |
def tolist(obj, flat=True, split=True):
'''
Returns `obj` as a list: if it is falsy, returns an empty list; if
it is a string and `split` is truthy, then it is split into
substrings using Unix shell semantics; if it is sequence-like, a
list is returned optionally flattened if `flat` is truthy (see
:func:`fl... | Returns `obj` as a list: if it is falsy, returns an empty list; if
it is a string and `split` is truthy, then it is split into
substrings using Unix shell semantics; if it is sequence-like, a
list is returned optionally flattened if `flat` is truthy (see
:func:`flatten`). | Below is the the instruction that describes the task:
### Input:
Returns `obj` as a list: if it is falsy, returns an empty list; if
it is a string and `split` is truthy, then it is split into
substrings using Unix shell semantics; if it is sequence-like, a
list is returned optionally flattened if `flat` is tr... |
def subsampleCorrelatedData(A_t, g=None, fast=False, conservative=False, verbose=False):
"""Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional... | Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional
if provided, the statistical inefficiency g is used to subsample the timeseries -- othe... | Below is the the instruction that describes the task:
### Input:
Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional
if provided, the s... |
def update_metadata(self, params):
""" Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2... | Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata>... | Below is the the instruction that describes the task:
### Input:
Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/... |
def run(self, definition):
"""Processing the pipeline."""
self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
self.logger.info("Running on platform %s", platform.platform())
self.logger.info("Current cpu count is %d", multiprocessing.cpu_count())
self.logger... | Processing the pipeline. | Below is the the instruction that describes the task:
### Input:
Processing the pipeline.
### Response:
def run(self, definition):
"""Processing the pipeline."""
self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
self.logger.info("Running on platform %s", platform.pla... |
def _remove_broken_links():
'''
Remove broken links in `<conda prefix>/etc/microdrop/plugins/enabled/`.
Returns
-------
list
List of links removed (if any).
'''
enabled_dir = MICRODROP_CONDA_PLUGINS.joinpath('enabled')
if not enabled_dir.isdir():
return []
broken_li... | Remove broken links in `<conda prefix>/etc/microdrop/plugins/enabled/`.
Returns
-------
list
List of links removed (if any). | Below is the the instruction that describes the task:
### Input:
Remove broken links in `<conda prefix>/etc/microdrop/plugins/enabled/`.
Returns
-------
list
List of links removed (if any).
### Response:
def _remove_broken_links():
'''
Remove broken links in `<conda prefix>/etc/microdr... |
def add_multiifo_output_list_opt(self, opt, outputs):
""" Add an option that determines a list of outputs from multiple
detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2
.....
"""
# NOTE: Here we have to use the raw arguments functionality as the
... | Add an option that determines a list of outputs from multiple
detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2
..... | Below is the the instruction that describes the task:
### Input:
Add an option that determines a list of outputs from multiple
detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2
.....
### Response:
def add_multiifo_output_list_opt(self, opt, outputs):
""" Add an opti... |
def assert_eq(expected, actual, message=None, tolerance=None, extra=None):
"""Raises an AssertionError if expected != actual.
If tolerance is specified, raises an AssertionError if either
- expected or actual isn't a number, or
- the difference between expected and actual is larger than the tolerance.
... | Raises an AssertionError if expected != actual.
If tolerance is specified, raises an AssertionError if either
- expected or actual isn't a number, or
- the difference between expected and actual is larger than the tolerance. | Below is the the instruction that describes the task:
### Input:
Raises an AssertionError if expected != actual.
If tolerance is specified, raises an AssertionError if either
- expected or actual isn't a number, or
- the difference between expected and actual is larger than the tolerance.
### Response:... |
def _update_setup_py(self):
"""
Update :code:`setup.py` so that it always have the right name.
"""
# We initiate the path to the file we have to filter.
setup_py_path = PyFunceble.CURRENT_DIRECTORY + "setup.py"
if self.is_dev_version():
# The current version... | Update :code:`setup.py` so that it always have the right name. | Below is the the instruction that describes the task:
### Input:
Update :code:`setup.py` so that it always have the right name.
### Response:
def _update_setup_py(self):
"""
Update :code:`setup.py` so that it always have the right name.
"""
# We initiate the path to the file we hav... |
def get_flops():
""" # DOESNT WORK """
from sys import stdout
from re import compile
filename = "linpack.out"
fpnum = r'\d+\.\d+E[+-]\d\d'
fpnum_1 = fpnum + r' +'
pattern = compile(r'^ *' + fpnum_1 + fpnum_1 + fpnum_1 + r'(' + fpnum + r') +' + fpnum_1 + fpnum + r' *\n$')
speeds = [0.0, ... | # DOESNT WORK | Below is the the instruction that describes the task:
### Input:
# DOESNT WORK
### Response:
def get_flops():
""" # DOESNT WORK """
from sys import stdout
from re import compile
filename = "linpack.out"
fpnum = r'\d+\.\d+E[+-]\d\d'
fpnum_1 = fpnum + r' +'
pattern = compile(r'^ *' + fpn... |
def get_books(self):
"""Pass through to provider BookLookupSession.get_books"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('book_lookup_session').get_books()
cat_list = []
for cat in c... | Pass through to provider BookLookupSession.get_books | Below is the the instruction that describes the task:
### Input:
Pass through to provider BookLookupSession.get_books
### Response:
def get_books(self):
"""Pass through to provider BookLookupSession.get_books"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_... |
def summary(self, file_name=None):
"""
A summary method to call the Markov homogeneity test to test for
temporally lagged spatial dependence.
To learn more about the properties of the tests, refer to
:cite:`Rey2016a` and :cite:`Kang2018`.
"""
class_names = ["C%d... | A summary method to call the Markov homogeneity test to test for
temporally lagged spatial dependence.
To learn more about the properties of the tests, refer to
:cite:`Rey2016a` and :cite:`Kang2018`. | Below is the the instruction that describes the task:
### Input:
A summary method to call the Markov homogeneity test to test for
temporally lagged spatial dependence.
To learn more about the properties of the tests, refer to
:cite:`Rey2016a` and :cite:`Kang2018`.
### Response:
def summary... |
async def status_by_state(self, state: str) -> dict:
"""Return the CDC status for the specified state."""
data = await self.raw_cdc_data()
try:
info = next((v for k, v in data.items() if state in k))
except StopIteration:
return {}
return adjust_status(i... | Return the CDC status for the specified state. | Below is the the instruction that describes the task:
### Input:
Return the CDC status for the specified state.
### Response:
async def status_by_state(self, state: str) -> dict:
"""Return the CDC status for the specified state."""
data = await self.raw_cdc_data()
try:
info = n... |
def read_mrz(file, save_roi=False, extra_cmdline_params=''):
"""The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param... | The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param save_roi: when this is True, the .aux['roi'] field will contain the... | Below is the the instruction that describes the task:
### Input:
The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:para... |
def _set_session_style(self, v, load=False):
"""
Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as a private
... | Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as a private
method. Backends looking to populate this variable sho... | Below is the the instruction that describes the task:
### Input:
Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as... |
def reflash_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True):
"""Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will ... | Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have its firmware
reflashed.
:para... | Below is the the instruction that describes the task:
### Input:
Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have ... |
def unpatch_locals(depth=3):
"""Restores the original values of module variables
considered preferences if they are still PatchedLocal
and not PrefProxy.
"""
for name, locals_dict in traverse_local_prefs(depth):
if isinstance(locals_dict[name], PatchedLocal):
locals_dict[name] =... | Restores the original values of module variables
considered preferences if they are still PatchedLocal
and not PrefProxy. | Below is the the instruction that describes the task:
### Input:
Restores the original values of module variables
considered preferences if they are still PatchedLocal
and not PrefProxy.
### Response:
def unpatch_locals(depth=3):
"""Restores the original values of module variables
considered prefer... |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usuall... | Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumer... | Below is the the instruction that describes the task:
### Input:
Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
... |
def input_size(self):
'''Size of layer input (for layers with one input).'''
shape = self.input_shape
if shape is None:
raise util.ConfigurationError(
'undefined input size for layer "{}"'.format(self.name))
return shape[-1] | Size of layer input (for layers with one input). | Below is the the instruction that describes the task:
### Input:
Size of layer input (for layers with one input).
### Response:
def input_size(self):
'''Size of layer input (for layers with one input).'''
shape = self.input_shape
if shape is None:
raise util.ConfigurationError(
... |
def MakeDeployableBinary(self, template_path, output_path):
"""This will add the config to the client template and create a .rpm."""
rpmbuild_binary = "/usr/bin/rpmbuild"
if not os.path.exists(rpmbuild_binary):
logging.error("rpmbuild not found, unable to repack client.")
return
with utils... | This will add the config to the client template and create a .rpm. | Below is the the instruction that describes the task:
### Input:
This will add the config to the client template and create a .rpm.
### Response:
def MakeDeployableBinary(self, template_path, output_path):
"""This will add the config to the client template and create a .rpm."""
rpmbuild_binary = "/usr/bin... |
def sbar_(self, stack_index=None, label=None, style=None, opts=None,
options={}):
"""
Get a stacked bar chart
"""
self.opts(dict(stack_index=stack_index, color_index=stack_index))
try:
if stack_index is None:
self.err(self.sbar_, "Please provide a stack index parameter")
options["stack_index"] ... | Get a stacked bar chart | Below is the the instruction that describes the task:
### Input:
Get a stacked bar chart
### Response:
def sbar_(self, stack_index=None, label=None, style=None, opts=None,
options={}):
"""
Get a stacked bar chart
"""
self.opts(dict(stack_index=stack_index, color_index=stack_index))
try:
if stack_... |
def _write(self, body, id):
"""
Respond to a WRITE command, sending some data over a virtual channel
created by VIRTUAL. The answer is simply an acknowledgement, as it is
simply meant to note that the write went through without errors.
An occurrence of I{Write} on the wire, tog... | Respond to a WRITE command, sending some data over a virtual channel
created by VIRTUAL. The answer is simply an acknowledgement, as it is
simply meant to note that the write went through without errors.
An occurrence of I{Write} on the wire, together with the response
generated by thi... | Below is the the instruction that describes the task:
### Input:
Respond to a WRITE command, sending some data over a virtual channel
created by VIRTUAL. The answer is simply an acknowledgement, as it is
simply meant to note that the write went through without errors.
An occurrence of I{Wr... |
def isTransiting(self):
""" Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue
version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented
"""
try:
isTransiting = self.par... | Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue
version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented | Below is the the instruction that describes the task:
### Input:
Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue
version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented
### Response:
def isTransi... |
def disconnect(self, callback=None):
"""Disconnect a callback from this emitter.
If no callback is specified, then *all* callbacks are removed.
If the callback was not already connected, then the call does nothing.
"""
if callback is None:
self._callbacks = []
... | Disconnect a callback from this emitter.
If no callback is specified, then *all* callbacks are removed.
If the callback was not already connected, then the call does nothing. | Below is the the instruction that describes the task:
### Input:
Disconnect a callback from this emitter.
If no callback is specified, then *all* callbacks are removed.
If the callback was not already connected, then the call does nothing.
### Response:
def disconnect(self, callback=None):
... |
def randombytes(n):
"""Return n random bytes."""
# Use /dev/urandom if it is available. Fall back to random module
# if not. It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists("/dev/urandom"):
f = open("/de... | Return n random bytes. | Below is the the instruction that describes the task:
### Input:
Return n random bytes.
### Response:
def randombytes(n):
"""Return n random bytes."""
# Use /dev/urandom if it is available. Fall back to random module
# if not. It might be worthwhile to extend this function to use
# other platform... |
def get_safe_redirect_target(arg='next'):
"""Get URL to redirect to and ensure that it is local."""
for target in request.args.get(arg), request.referrer:
if not target:
continue
if is_local_url(target):
return target
return None | Get URL to redirect to and ensure that it is local. | Below is the the instruction that describes the task:
### Input:
Get URL to redirect to and ensure that it is local.
### Response:
def get_safe_redirect_target(arg='next'):
"""Get URL to redirect to and ensure that it is local."""
for target in request.args.get(arg), request.referrer:
if not target... |
def to_project(project):
"""Serializes project to id string
:param project: object to serialize
:return: string id
"""
from sevenbridges.models.project import Project
if not project:
raise SbgError('Project is required!')
elif isinstance(project, Proje... | Serializes project to id string
:param project: object to serialize
:return: string id | Below is the the instruction that describes the task:
### Input:
Serializes project to id string
:param project: object to serialize
:return: string id
### Response:
def to_project(project):
"""Serializes project to id string
:param project: object to serialize
:return: stri... |
def create(self):
"""
Creates the Indicator/Group/Victim or Security Label given Owner
Args:
"""
if not self.can_create():
self._tcex.handle_error(905, [self.type])
response = self.tc_requests.create(self.api_type, self.api_sub_type, self._data, self.owner)
... | Creates the Indicator/Group/Victim or Security Label given Owner
Args: | Below is the the instruction that describes the task:
### Input:
Creates the Indicator/Group/Victim or Security Label given Owner
Args:
### Response:
def create(self):
"""
Creates the Indicator/Group/Victim or Security Label given Owner
Args:
"""
if not self.can_cr... |
def _create(cls, model_class, *args, **kwargs):
"""Create an instance of the model, and save it to the database."""
if cls._meta.django_get_or_create:
return cls._get_or_create(model_class, *args, **kwargs)
manager = cls._get_manager(model_class)
return manager.create(*args,... | Create an instance of the model, and save it to the database. | Below is the the instruction that describes the task:
### Input:
Create an instance of the model, and save it to the database.
### Response:
def _create(cls, model_class, *args, **kwargs):
"""Create an instance of the model, and save it to the database."""
if cls._meta.django_get_or_create:
... |
def plot_eigh(self, colorbar=True, cb_orientation='vertical',
tick_interval=[60, 60], minor_tick_interval=[20, 20],
xlabel='Longitude', ylabel='Latitude',
axes_labelsize=9, tick_labelsize=8, show=True, fname=None,
**kwargs):
"""
Plo... | Plot the two eigenvalues and maximum absolute value eigenvalue of the
horizontal tensor.
Usage
-----
x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel,
colorbar, cb_orientation, cb_label, axes_labelsize,
tick_labelsize, show, fname... | Below is the the instruction that describes the task:
### Input:
Plot the two eigenvalues and maximum absolute value eigenvalue of the
horizontal tensor.
Usage
-----
x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel,
colorbar, cb_orientation, cb_la... |
def process_child(node):
"""This function changes class references to not have the
intermediate module name by hacking at the doctree"""
# Edit descriptions to be nicer
if isinstance(node, sphinx.addnodes.desc_addname):
if len(node.children) == 1:
child = node.children[0]
... | This function changes class references to not have the
intermediate module name by hacking at the doctree | Below is the the instruction that describes the task:
### Input:
This function changes class references to not have the
intermediate module name by hacking at the doctree
### Response:
def process_child(node):
"""This function changes class references to not have the
intermediate module name by h... |
def environment(self, atom):
"""
pairs of (bond, atom) connected to atom
:param atom: number
:return: list
"""
return tuple((bond, self._node[n]) for n, bond in self._adj[atom].items()) | pairs of (bond, atom) connected to atom
:param atom: number
:return: list | Below is the the instruction that describes the task:
### Input:
pairs of (bond, atom) connected to atom
:param atom: number
:return: list
### Response:
def environment(self, atom):
"""
pairs of (bond, atom) connected to atom
:param atom: number
:return: list
... |
def camel_to_snake_case(camel_input):
'''
Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str
... | Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str | Below is the the instruction that describes the task:
### Input:
Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_cas... |
def need_maintenance_response(request):
"""
Tells if the given request needs a maintenance response or not.
"""
try:
view_match = resolve(request.path)
view_func = view_match[0]
view_dict = view_func.__dict__
view_force_maintenance_mode_off = view_dict.get(
... | Tells if the given request needs a maintenance response or not. | Below is the the instruction that describes the task:
### Input:
Tells if the given request needs a maintenance response or not.
### Response:
def need_maintenance_response(request):
"""
Tells if the given request needs a maintenance response or not.
"""
try:
view_match = resolve(request.p... |
def timeshift_isc(data, pairwise=False, summary_statistic='median',
n_shifts=1000, tolerate_nans=True, random_state=None):
"""Circular time-shift randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where respon... | Circular time-shift randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time series
are first circularly shifted by random intervals. If pairwise,
apply time-shift randomization to each subjects and compute pai... | Below is the the instruction that describes the task:
### Input:
Circular time-shift randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time series
are first circularly shifted by random intervals. If pairwise... |
def verifyscrollbarvertical(self, window_name, object_name):
"""
Verify scrollbar is vertical
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, eithe... | Verify scrollbar is vertical
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object... | Below is the the instruction that describes the task:
### Input:
Verify scrollbar is vertical
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,... |
def set_inteface_up(ifindex, auth, url, devid=None, devip=None):
"""
function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to "undo shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 addr... | function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to "undo shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 address of the target devices
:param ifindex: int or str value of the target... | Below is the the instruction that describes the task:
### Input:
function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to "undo shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 address of t... |
def main():
'''Main routine.'''
# check for single command argument
if len(sys.argv) != 2:
sys.exit('Usage: python ' + sys.argv[0] + ' rg_name')
rgname = sys.argv[1]
# if in Azure cloud shell, authenticate using the MSI endpoint
if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.env... | Main routine. | Below is the the instruction that describes the task:
### Input:
Main routine.
### Response:
def main():
'''Main routine.'''
# check for single command argument
if len(sys.argv) != 2:
sys.exit('Usage: python ' + sys.argv[0] + ' rg_name')
rgname = sys.argv[1]
# if in Azure cloud shell,... |
def _get_all_secret_version_ids(self, secure_data_path, limit=None):
"""
Convenience function that returns a generator that will paginate over the secret version ids
secure_data_path -- full path to the key in the safety deposit box
limit -- Default(100), limits how many records to be re... | Convenience function that returns a generator that will paginate over the secret version ids
secure_data_path -- full path to the key in the safety deposit box
limit -- Default(100), limits how many records to be returned from the api at once. | Below is the the instruction that describes the task:
### Input:
Convenience function that returns a generator that will paginate over the secret version ids
secure_data_path -- full path to the key in the safety deposit box
limit -- Default(100), limits how many records to be returned from the api ... |
def pcre(tgt, minion_id=None):
'''
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*'
'''
if minio... | Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*' | Below is the the instruction that describes the task:
### Input:
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre... |
def msg_err(message):
"""
Log an error message
:param message: the message to be logged
"""
to_stdout(" !!! {message}".format(message=message), colorf=red, bold=True)
if _logger:
_logger.error(message) | Log an error message
:param message: the message to be logged | Below is the the instruction that describes the task:
### Input:
Log an error message
:param message: the message to be logged
### Response:
def msg_err(message):
"""
Log an error message
:param message: the message to be logged
"""
to_stdout(" !!! {message}".format(message=message), colo... |
def calc_grad(self):
"""The gradient of the cost w.r.t. the parameters."""
residuals = self.calc_residuals()
return 2*np.dot(self.J, residuals) | The gradient of the cost w.r.t. the parameters. | Below is the the instruction that describes the task:
### Input:
The gradient of the cost w.r.t. the parameters.
### Response:
def calc_grad(self):
"""The gradient of the cost w.r.t. the parameters."""
residuals = self.calc_residuals()
return 2*np.dot(self.J, residuals) |
def min_version(self):
"""Version with the fewest downloads."""
data = self.version_downloads
if not data:
return (None, 0)
return min(data.items(), key=lambda item: item[1]) | Version with the fewest downloads. | Below is the the instruction that describes the task:
### Input:
Version with the fewest downloads.
### Response:
def min_version(self):
"""Version with the fewest downloads."""
data = self.version_downloads
if not data:
return (None, 0)
return min(data.items(), key=lamb... |
def add_insertions(self, skip=10, window=1, test=False):
'''Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ... '''
assert 2 * window < skip
new_seq = list(self.seq)
for i in range(l... | Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ... | Below is the the instruction that describes the task:
### Input:
Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ...
### Response:
def add_insertions(self, skip=10, window=1, test=False):
'''Adds a ran... |
def error(self, nCells=15):
'''
calculate the standard deviation of all fitted images,
averaged to a grid
'''
s0, s1 = self.fits[0].shape
aR = s0 / s1
if aR > 1:
ss0 = int(nCells)
ss1 = int(ss0 / aR)
else:
ss... | calculate the standard deviation of all fitted images,
averaged to a grid | Below is the the instruction that describes the task:
### Input:
calculate the standard deviation of all fitted images,
averaged to a grid
### Response:
def error(self, nCells=15):
'''
calculate the standard deviation of all fitted images,
averaged to a grid
'''
... |
def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | Convert an IBPy Order object to a dict containing any non-default values. | Below is the the instruction that describes the task:
### Input:
Convert an IBPy Order object to a dict containing any non-default values.
### Response:
def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for fie... |
def _GetGsScopes(self):
"""Return all Google Storage scopes available on this VM."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
scopes = service_accounts[self.service_account]['scopes']
return list(GS_SCOPES.intersection(set(scopes))) if scopes else None
... | Return all Google Storage scopes available on this VM. | Below is the the instruction that describes the task:
### Input:
Return all Google Storage scopes available on this VM.
### Response:
def _GetGsScopes(self):
"""Return all Google Storage scopes available on this VM."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
... |
def wikidata(self, title, wikibase=None):
"""
Returns Wikidata query string
"""
self.domain = 'www.wikidata.org'
self.uri = self.wiki_uri(self.domain)
query = self.WIKIDATA.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LANG=self.v... | Returns Wikidata query string | Below is the the instruction that describes the task:
### Input:
Returns Wikidata query string
### Response:
def wikidata(self, title, wikibase=None):
"""
Returns Wikidata query string
"""
self.domain = 'www.wikidata.org'
self.uri = self.wiki_uri(self.domain)
query ... |
def prepare(self):
'''
Run the preparation sequence required to start a salt master server.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(Master, self).prepare()
try:
if self.config['verify_env']:
... | Run the preparation sequence required to start a salt master server.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare() | Below is the the instruction that describes the task:
### Input:
Run the preparation sequence required to start a salt master server.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
### Response:
def prepare(self):
'''
Run the preparation sequ... |
def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_cod... | Get user's locale
:return: :class:`babel.core.Locale` | Below is the the instruction that describes the task:
### Input:
Get user's locale
:return: :class:`babel.core.Locale`
### Response:
def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_co... |
def load_address_books(names, config, search_queries):
"""Load all address books with the given names from the config.
:param names: the address books to load
:type names: list(str)
:param config: the config instance to use when looking up address books
:type config: config.Config
:param search... | Load all address books with the given names from the config.
:param names: the address books to load
:type names: list(str)
:param config: the config instance to use when looking up address books
:type config: config.Config
:param search_queries: a mapping of address book names to search queries
... | Below is the the instruction that describes the task:
### Input:
Load all address books with the given names from the config.
:param names: the address books to load
:type names: list(str)
:param config: the config instance to use when looking up address books
:type config: config.Config
:param... |
def calculate_cache_access(self):
"""Apply cache prediction to generate cache access behaviour."""
self.results = {'misses': self.predictor.get_misses(),
'hits': self.predictor.get_hits(),
'evicts': self.predictor.get_evicts(),
'ver... | Apply cache prediction to generate cache access behaviour. | Below is the the instruction that describes the task:
### Input:
Apply cache prediction to generate cache access behaviour.
### Response:
def calculate_cache_access(self):
"""Apply cache prediction to generate cache access behaviour."""
self.results = {'misses': self.predictor.get_misses(),
... |
def log_to_collapsed_structure(execution_history_items, throw_on_pickle_error=True,
include_erroneous_data_ports=False, full_next=False):
"""
Collapsed structure means that all history items belonging to the same state execution are
merged together into one object (e.g. CallIt... | Collapsed structure means that all history items belonging to the same state execution are
merged together into one object (e.g. CallItem and ReturnItem of an ExecutionState). This
is based on the log structure in which all Items which belong together have the same run_id.
The collapsed items hold input as ... | Below is the the instruction that describes the task:
### Input:
Collapsed structure means that all history items belonging to the same state execution are
merged together into one object (e.g. CallItem and ReturnItem of an ExecutionState). This
is based on the log structure in which all Items which belong ... |
def brew_innuendo(args):
"""Brews a given list of processes according to the recipe
Parameters
----------
args : argparse.Namespace
The arguments passed through argparser that will be used to check the
the recipe, tasks and brew the process
Returns
-------
str
The f... | Brews a given list of processes according to the recipe
Parameters
----------
args : argparse.Namespace
The arguments passed through argparser that will be used to check the
the recipe, tasks and brew the process
Returns
-------
str
The final pipeline string, ready for ... | Below is the the instruction that describes the task:
### Input:
Brews a given list of processes according to the recipe
Parameters
----------
args : argparse.Namespace
The arguments passed through argparser that will be used to check the
the recipe, tasks and brew the process
Retu... |
def _get_variable_for_input(scope, input_name, global_inputs, output_dict):
'''
Find the corresponding Variable for a given raw operator (model) name
The variable is either supplied as graph/global inputs or has been generated as output by previous ops
:param input_name:
:param global_inputs:
:p... | Find the corresponding Variable for a given raw operator (model) name
The variable is either supplied as graph/global inputs or has been generated as output by previous ops
:param input_name:
:param global_inputs:
:param output_dict:
:return: | Below is the the instruction that describes the task:
### Input:
Find the corresponding Variable for a given raw operator (model) name
The variable is either supplied as graph/global inputs or has been generated as output by previous ops
:param input_name:
:param global_inputs:
:param output_dict:
... |
def purge(context, resource, force):
"""purge(context, resource, force)
Purge soft-deleted resources.
>>> dcictl purge --resource remotecis
"""
resources = ['components', 'topics', 'tests', 'teams', 'feeders',
'remotecis', 'jobs', 'files', 'users', 'products']
l_resources = ... | purge(context, resource, force)
Purge soft-deleted resources.
>>> dcictl purge --resource remotecis | Below is the the instruction that describes the task:
### Input:
purge(context, resource, force)
Purge soft-deleted resources.
>>> dcictl purge --resource remotecis
### Response:
def purge(context, resource, force):
"""purge(context, resource, force)
Purge soft-deleted resources.
>>> dcictl... |
def decr(self, stat, count=1, rate=1):
"""Decrement a stat by `count`."""
self.incr(stat, -count, rate) | Decrement a stat by `count`. | Below is the the instruction that describes the task:
### Input:
Decrement a stat by `count`.
### Response:
def decr(self, stat, count=1, rate=1):
"""Decrement a stat by `count`."""
self.incr(stat, -count, rate) |
def doc_includes_process(xmldoc, program):
"""
Return True if the process table in xmldoc includes entries for a
program named program.
"""
return program in lsctables.ProcessTable.get_table(xmldoc).getColumnByName(u"program") | Return True if the process table in xmldoc includes entries for a
program named program. | Below is the the instruction that describes the task:
### Input:
Return True if the process table in xmldoc includes entries for a
program named program.
### Response:
def doc_includes_process(xmldoc, program):
"""
Return True if the process table in xmldoc includes entries for a
program named program.
"""
r... |
def write_table(self):
"""
|write_table| with
`Line-delimited JSON(LDJSON) <https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON>`__
/NDJSON/JSON Lines format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`exam... | |write_table| with
`Line-delimited JSON(LDJSON) <https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON>`__
/NDJSON/JSON Lines format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`example-jsonl-writer` | Below is the the instruction that describes the task:
### Input:
|write_table| with
`Line-delimited JSON(LDJSON) <https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON>`__
/NDJSON/JSON Lines format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Examp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.