code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def join_and(value):
"""Given a list of strings, format them with commas and spaces, but
with 'and' at the end.
>>> join_and(['apples', 'oranges', 'pears'])
"apples, oranges, and pears"
There is surely a better home for this
"""
# convert numbers to strings
value = [str(item) for item... | Given a list of strings, format them with commas and spaces, but
with 'and' at the end.
>>> join_and(['apples', 'oranges', 'pears'])
"apples, oranges, and pears"
There is surely a better home for this | Below is the the instruction that describes the task:
### Input:
Given a list of strings, format them with commas and spaces, but
with 'and' at the end.
>>> join_and(['apples', 'oranges', 'pears'])
"apples, oranges, and pears"
There is surely a better home for this
### Response:
def join_and(valu... |
def D_d(self, H_0, Om0, Ode0=None):
"""
angular diameter to deflector
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
"""
lensCosmo = self._get_cosom(H_0, Om0, Ode0)
return lensCosmo.D_d | angular diameter to deflector
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc] | Below is the the instruction that describes the task:
### Input:
angular diameter to deflector
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
### Response:
def D_d(self, H_0, Om0, Ode0=None):
"""
angular dia... |
def Rock(*args, **kwargs):
"""
Graceful deprecation for old class name.
"""
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "The 'Rock' class was renamed 'Component'. "
w += "Please update your code."
warnings.warn(w, DeprecationWarning, stacklevel=2)... | Graceful deprecation for old class name. | Below is the the instruction that describes the task:
### Input:
Graceful deprecation for old class name.
### Response:
def Rock(*args, **kwargs):
"""
Graceful deprecation for old class name.
"""
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "The 'Rock' class ... |
def denormalize_bbox(bbox, rows, cols):
"""Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
"""
if rows == 0:
raise ValueError('Argument ... | Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`. | Below is the the instruction that describes the task:
### Input:
Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
### Response:
def denormalize_bbox(bbo... |
def parse_argspec(callable_):
"""
Takes a callable and returns a tuple with the list of Argument objects,
the name of *args, and the name of **kwargs.
If *args or **kwargs is not present, it will be None.
This returns a namedtuple called Argspec that has three fields named:
... | Takes a callable and returns a tuple with the list of Argument objects,
the name of *args, and the name of **kwargs.
If *args or **kwargs is not present, it will be None.
This returns a namedtuple called Argspec that has three fields named:
args, starargs, and kwargs. | Below is the the instruction that describes the task:
### Input:
Takes a callable and returns a tuple with the list of Argument objects,
the name of *args, and the name of **kwargs.
If *args or **kwargs is not present, it will be None.
This returns a namedtuple called Argspec that has three ... |
def new(arg_name, annotated_with=None):
"""Creates a BindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated binding key
Returns:
a new BindingKey
"""
if annotated_with is not None:
annotation = annotations.Annotati... | Creates a BindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated binding key
Returns:
a new BindingKey | Below is the the instruction that describes the task:
### Input:
Creates a BindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated binding key
Returns:
a new BindingKey
### Response:
def new(arg_name, annotated_with=None):
"""... |
def get_kabsch_rotation(Q, P):
"""Calculate the optimal rotation from ``P`` unto ``Q``.
Using the Kabsch algorithm the optimal rotation matrix
for the rotation of ``other`` unto ``self`` is calculated.
The algorithm is described very well in
`wikipedia <http://en.wikipedia.org/wiki/Kabsch_algorithm... | Calculate the optimal rotation from ``P`` unto ``Q``.
Using the Kabsch algorithm the optimal rotation matrix
for the rotation of ``other`` unto ``self`` is calculated.
The algorithm is described very well in
`wikipedia <http://en.wikipedia.org/wiki/Kabsch_algorithm>`_.
Args:
other (Cartesi... | Below is the the instruction that describes the task:
### Input:
Calculate the optimal rotation from ``P`` unto ``Q``.
Using the Kabsch algorithm the optimal rotation matrix
for the rotation of ``other`` unto ``self`` is calculated.
The algorithm is described very well in
`wikipedia <http://en.wiki... |
def kitchen_config(backend, kitchen, add, get, unset, listall):
"""
Get and Set Kitchen variable overrides
"""
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
check_and_print(DKCloudCommandRunner.config_kitchen(bac... | Get and Set Kitchen variable overrides | Below is the the instruction that describes the task:
### Input:
Get and Set Kitchen variable overrides
### Response:
def kitchen_config(backend, kitchen, add, get, unset, listall):
"""
Get and Set Kitchen variable overrides
"""
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if u... |
def _send(self):
"""
Take metrics from queue and send it to Datadog API
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.g... | Take metrics from queue and send it to Datadog API | Below is the the instruction that describes the task:
### Input:
Take metrics from queue and send it to Datadog API
### Response:
def _send(self):
"""
Take metrics from queue and send it to Datadog API
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
... |
def edterm(trmtyp, source, target, et, fixref, abcorr, obsrvr, npts):
"""
Compute a set of points on the umbral or penumbral terminator of
a specified target body, where the target shape is modeled as an
ellipsoid.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edterm_c.html
:param tr... | Compute a set of points on the umbral or penumbral terminator of
a specified target body, where the target shape is modeled as an
ellipsoid.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edterm_c.html
:param trmtyp: Terminator type.
:type trmtyp: str
:param source: Light source.
... | Below is the the instruction that describes the task:
### Input:
Compute a set of points on the umbral or penumbral terminator of
a specified target body, where the target shape is modeled as an
ellipsoid.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edterm_c.html
:param trmtyp: Termina... |
def erase_line(method=EraseMethod.ALL, file=sys.stdout):
""" Erase a line, or part of a line. See `method` argument below.
Cursor position does not change.
Esc[<method>K
Arguments:
method : One of these possible values:
EraseMethod.END or 0:
... | Erase a line, or part of a line. See `method` argument below.
Cursor position does not change.
Esc[<method>K
Arguments:
method : One of these possible values:
EraseMethod.END or 0:
Clear from cursor to the end of the line.
... | Below is the the instruction that describes the task:
### Input:
Erase a line, or part of a line. See `method` argument below.
Cursor position does not change.
Esc[<method>K
Arguments:
method : One of these possible values:
EraseMethod.END or 0:
... |
def parallel_timebin(lclist,
binsizesec,
maxobjects=None,
outdir=None,
lcformat='hat-sql',
lcformatdir=None,
timecols=None,
magcols=None,
errcols=None,
... | This time-bins all the LCs in the list using the specified bin size.
Parameters
----------
lclist : list of str
The input LCs to process.
binsizesec : float
The time bin size to use in seconds.
maxobjects : int or None
If provided, LC processing will stop at `lclist[maxob... | Below is the the instruction that describes the task:
### Input:
This time-bins all the LCs in the list using the specified bin size.
Parameters
----------
lclist : list of str
The input LCs to process.
binsizesec : float
The time bin size to use in seconds.
maxobjects : int ... |
def forwards(apps, schema_editor):
"""
Set the venue_name field of all Events that have a Venue.
"""
Event = apps.get_model('spectator_events', 'Event')
for event in Event.objects.all():
if event.venue is not None:
event.venue_name = event.venue.name
event.save() | Set the venue_name field of all Events that have a Venue. | Below is the the instruction that describes the task:
### Input:
Set the venue_name field of all Events that have a Venue.
### Response:
def forwards(apps, schema_editor):
"""
Set the venue_name field of all Events that have a Venue.
"""
Event = apps.get_model('spectator_events', 'Event')
for ... |
def decode_file_args(self, argv: List[str]) -> List[str]:
"""
Preprocess any arguments that begin with the fromfile prefix char(s).
This replaces the one in Argparse because it
a) doesn't process "-x y" correctly and
b) ignores bad files
:param argv: raw options l... | Preprocess any arguments that begin with the fromfile prefix char(s).
This replaces the one in Argparse because it
a) doesn't process "-x y" correctly and
b) ignores bad files
:param argv: raw options list
:return: options list with file references replaced | Below is the the instruction that describes the task:
### Input:
Preprocess any arguments that begin with the fromfile prefix char(s).
This replaces the one in Argparse because it
a) doesn't process "-x y" correctly and
b) ignores bad files
:param argv: raw options list
... |
def shift_or_mirror_into_invertible_domain(self, solution_genotype,
copy=False):
"""Details: input ``solution_genotype`` is changed. The domain is
[lb - al, ub + au] and in [lb - 2*al - (ub - lb) / 2, lb - al]
mirroring is applied.
"""
... | Details: input ``solution_genotype`` is changed. The domain is
[lb - al, ub + au] and in [lb - 2*al - (ub - lb) / 2, lb - al]
mirroring is applied. | Below is the the instruction that describes the task:
### Input:
Details: input ``solution_genotype`` is changed. The domain is
[lb - al, ub + au] and in [lb - 2*al - (ub - lb) / 2, lb - al]
mirroring is applied.
### Response:
def shift_or_mirror_into_invertible_domain(self, solution_genotype,
... |
def repr_imgs(imgs):
"""Printing of img or imgs"""
if isinstance(imgs, string_types):
return imgs
if isinstance(imgs, collections.Iterable):
return '[{}]'.format(', '.join(repr_imgs(img) for img in imgs))
# try get_filename
try:
filename = imgs.get_filename()
if fil... | Printing of img or imgs | Below is the the instruction that describes the task:
### Input:
Printing of img or imgs
### Response:
def repr_imgs(imgs):
"""Printing of img or imgs"""
if isinstance(imgs, string_types):
return imgs
if isinstance(imgs, collections.Iterable):
return '[{}]'.format(', '.join(repr_imgs(i... |
def _minimize_neldermead(
func,
x0,
args=(),
callback=None,
xtol=1e-4,
ftol=1e-4,
maxiter=None,
maxfev=None,
disp=False,
return_all=False,
): # pragma: no cover
"""
Minimization of scalar function of one or more variables using the
Nelder-Mead algorithm.
Options... | Minimization of scalar function of one or more variables using the
Nelder-Mead algorithm.
Options for the Nelder-Mead algorithm are:
disp : bool
Set to True to print convergence messages.
xtol : float
Relative error in solution `xopt` acceptable for convergence.
... | Below is the the instruction that describes the task:
### Input:
Minimization of scalar function of one or more variables using the
Nelder-Mead algorithm.
Options for the Nelder-Mead algorithm are:
disp : bool
Set to True to print convergence messages.
xtol : float
R... |
def reset(self, total_size=None):
"""Remove all file system contents and reset the root."""
self.root = FakeDirectory(self.path_separator, filesystem=self)
self.cwd = self.root.name
self.open_files = []
self._free_fd_heap = []
self._last_ino = 0
self._last_dev = ... | Remove all file system contents and reset the root. | Below is the the instruction that describes the task:
### Input:
Remove all file system contents and reset the root.
### Response:
def reset(self, total_size=None):
"""Remove all file system contents and reset the root."""
self.root = FakeDirectory(self.path_separator, filesystem=self)
self... |
def viterbi_alignment(es, fs, t, a):
'''
return
dictionary
e in es -> f in fs
'''
max_a = collections.defaultdict(float)
l_e = len(es)
l_f = len(fs)
for (j, e) in enumerate(es, 1):
current_max = (0, -1)
for (i, f) in enumerate(fs, 1):
... | return
dictionary
e in es -> f in fs | Below is the the instruction that describes the task:
### Input:
return
dictionary
e in es -> f in fs
### Response:
def viterbi_alignment(es, fs, t, a):
'''
return
dictionary
e in es -> f in fs
'''
max_a = collections.defaultdict(float)
l_e = len... |
def rates(ctx, opts):
"""Check current API rate limits."""
click.echo("Retrieving rate limits ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
resources_limits = get_rate_limits... | Check current API rate limits. | Below is the the instruction that describes the task:
### Input:
Check current API rate limits.
### Response:
def rates(ctx, opts):
"""Check current API rate limits."""
click.echo("Retrieving rate limits ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, op... |
def load_save_state(self) -> SaveState:
"""
Load the savestate of the plugin.
:return: savestate
:rtype: ~unidown.plugin.save_state.SaveState
:raises ~unidown.plugin.exceptions.PluginException: broken savestate json
:raises ~unidown.plugin.exceptions.PluginException: dif... | Load the savestate of the plugin.
:return: savestate
:rtype: ~unidown.plugin.save_state.SaveState
:raises ~unidown.plugin.exceptions.PluginException: broken savestate json
:raises ~unidown.plugin.exceptions.PluginException: different savestate versions
:raises ~unidown.plugin.ex... | Below is the the instruction that describes the task:
### Input:
Load the savestate of the plugin.
:return: savestate
:rtype: ~unidown.plugin.save_state.SaveState
:raises ~unidown.plugin.exceptions.PluginException: broken savestate json
:raises ~unidown.plugin.exceptions.PluginExcep... |
def f_get_derived_parameters(self, fast_access=False, copy=True):
""" Returns a dictionary containing the full parameter names as keys and the parameters
or the parameter data items as values.
:param fast_access:
Determines whether the parameter objects or their values are return... | Returns a dictionary containing the full parameter names as keys and the parameters
or the parameter data items as values.
:param fast_access:
Determines whether the parameter objects or their values are returned
in the dictionary.
:param copy:
Whether t... | Below is the the instruction that describes the task:
### Input:
Returns a dictionary containing the full parameter names as keys and the parameters
or the parameter data items as values.
:param fast_access:
Determines whether the parameter objects or their values are returned
... |
def get_translations(self, status=None):
'''
Returns the translations requested by the user
'''
if status is not None:
result = self.api_call('translation/?status=%s' % status)
else:
result = self.api_call('translation/')
if result.status_code ... | Returns the translations requested by the user | Below is the the instruction that describes the task:
### Input:
Returns the translations requested by the user
### Response:
def get_translations(self, status=None):
'''
Returns the translations requested by the user
'''
if status is not None:
result = self.api_call... |
def decode_offset_fetch_response(cls, data):
"""
Decode bytes to an OffsetFetchResponse
Arguments:
data: bytes to decode
"""
((correlation_id,), cur) = relative_unpack('>i', data, 0)
((num_topics,), cur) = relative_unpack('>i', data, cur)
for _ in r... | Decode bytes to an OffsetFetchResponse
Arguments:
data: bytes to decode | Below is the the instruction that describes the task:
### Input:
Decode bytes to an OffsetFetchResponse
Arguments:
data: bytes to decode
### Response:
def decode_offset_fetch_response(cls, data):
"""
Decode bytes to an OffsetFetchResponse
Arguments:
data: b... |
def _formatVals(self, val_list):
"""Formats value list from Munin Graph and returns multi-line value
entries for the plugin fetch cycle.
@param val_list: List of name-value pairs.
@return: Multi-line text.
"""
vals = []
for (name, val) i... | Formats value list from Munin Graph and returns multi-line value
entries for the plugin fetch cycle.
@param val_list: List of name-value pairs.
@return: Multi-line text. | Below is the the instruction that describes the task:
### Input:
Formats value list from Munin Graph and returns multi-line value
entries for the plugin fetch cycle.
@param val_list: List of name-value pairs.
@return: Multi-line text.
### Response:
def _formatVals(self, va... |
def get_param(self):
"""A simple representation of the credentials object for passing into the API.authenticate() server call.
:return: The simple credentials object for use by API.authenticate().
:rtype: dict
"""
return dict(userName=self.username, sessionId=self.session_id, da... | A simple representation of the credentials object for passing into the API.authenticate() server call.
:return: The simple credentials object for use by API.authenticate().
:rtype: dict | Below is the the instruction that describes the task:
### Input:
A simple representation of the credentials object for passing into the API.authenticate() server call.
:return: The simple credentials object for use by API.authenticate().
:rtype: dict
### Response:
def get_param(self):
"""A... |
def file_to_delete(cls):
"""
Return the list of file to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.OUTPUT_DIRECTORY + PyFunceble.OUTPUTS["parent_directory"]
if not directory.endswith(PyFunceble.directory_separator): # pragma: no... | Return the list of file to delete. | Below is the the instruction that describes the task:
### Input:
Return the list of file to delete.
### Response:
def file_to_delete(cls):
"""
Return the list of file to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.OUTPUT_DIRECTORY + P... |
def positive_value(target_type):
"""
Wraps target_type in a function that requires the parsed argument
be >= 0
"""
def inner(string):
value = target_type(string)
if not value >= 0:
raise argparse.ArgumentTypeError("Invalid positive number: " +
string)
... | Wraps target_type in a function that requires the parsed argument
be >= 0 | Below is the the instruction that describes the task:
### Input:
Wraps target_type in a function that requires the parsed argument
be >= 0
### Response:
def positive_value(target_type):
"""
Wraps target_type in a function that requires the parsed argument
be >= 0
"""
def inner(string):
... |
def __ordinal(self, num):
"""Returns the ordinal number of a given integer, as a string.
eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc.
"""
if 10 <= num % 100 < 20:
return str(num) + 'th'
else:
ord_info = {1: 'st', 2: 'nd', 3: 'rd'}.get(num % 10, 'th')
... | Returns the ordinal number of a given integer, as a string.
eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc. | Below is the the instruction that describes the task:
### Input:
Returns the ordinal number of a given integer, as a string.
eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc.
### Response:
def __ordinal(self, num):
"""Returns the ordinal number of a given integer, as a string.
eg. 1 -> 1st, 2 -> 2nd, ... |
def GetDefaultServicePeriod(self):
"""Return the default ServicePeriod. If no default ServicePeriod has been
set select the default depending on how many ServicePeriod objects are in
the Schedule. If there are 0 make a new ServicePeriod the default, if there
is 1 it becomes the default, if there is more... | Return the default ServicePeriod. If no default ServicePeriod has been
set select the default depending on how many ServicePeriod objects are in
the Schedule. If there are 0 make a new ServicePeriod the default, if there
is 1 it becomes the default, if there is more than 1 then return None. | Below is the the instruction that describes the task:
### Input:
Return the default ServicePeriod. If no default ServicePeriod has been
set select the default depending on how many ServicePeriod objects are in
the Schedule. If there are 0 make a new ServicePeriod the default, if there
is 1 it becomes th... |
def top(self, limit=None):
"""GETs top links from this subreddit. Calls :meth:`narwal.Reddit.top`.
:param limit: max number of links to return
"""
return self._reddit.top(self.display_name, limit=limit) | GETs top links from this subreddit. Calls :meth:`narwal.Reddit.top`.
:param limit: max number of links to return | Below is the the instruction that describes the task:
### Input:
GETs top links from this subreddit. Calls :meth:`narwal.Reddit.top`.
:param limit: max number of links to return
### Response:
def top(self, limit=None):
"""GETs top links from this subreddit. Calls :meth:`narwal.Reddit.top... |
def extract_module_locals(depth=0):
"""Returns (module, locals) of the funciton `depth` frames away from the caller"""
f = sys._getframe(depth + 1)
global_ns = f.f_globals
module = sys.modules[global_ns['__name__']]
return (module, f.f_locals) | Returns (module, locals) of the funciton `depth` frames away from the caller | Below is the the instruction that describes the task:
### Input:
Returns (module, locals) of the funciton `depth` frames away from the caller
### Response:
def extract_module_locals(depth=0):
"""Returns (module, locals) of the funciton `depth` frames away from the caller"""
f = sys._getframe(depth + 1)
... |
def delete(self):
"""Deletes the record.
"""
res = requests.delete(url=self.record_url, headers=HEADERS, verify=False)
#self.write_response_html_to_file(res,"bob_delete.html")
if res.status_code == 204:
#No content. Can't render json:
return {}
ret... | Deletes the record. | Below is the the instruction that describes the task:
### Input:
Deletes the record.
### Response:
def delete(self):
"""Deletes the record.
"""
res = requests.delete(url=self.record_url, headers=HEADERS, verify=False)
#self.write_response_html_to_file(res,"bob_delete.html")
... |
def _clear_cache(tgt=None,
tgt_type='glob',
clear_pillar_flag=False,
clear_grains_flag=False,
clear_mine_flag=False,
clear_mine_func_flag=None):
'''
Clear the cached data/files for the targeted minions.
'''
if tgt is No... | Clear the cached data/files for the targeted minions. | Below is the the instruction that describes the task:
### Input:
Clear the cached data/files for the targeted minions.
### Response:
def _clear_cache(tgt=None,
tgt_type='glob',
clear_pillar_flag=False,
clear_grains_flag=False,
clear_mine_flag=Fals... |
def _parse_vagrant_sandbox_status(self, vagrant_output):
'''
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
'''
# typical output
# [default] - snapshot mode is off
# or
# [default] - machine not created
# if the ... | Returns the status of the sandbox mode given output from
'vagrant sandbox status'. | Below is the the instruction that describes the task:
### Input:
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
### Response:
def _parse_vagrant_sandbox_status(self, vagrant_output):
'''
Returns the status of the sandbox mode given output from
'va... |
def get_machine_group_applied_configs(self, project_name, group_name):
""" get the logtail config names applied in a machine group
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_name: strin... | get the logtail config names applied in a machine group
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_name: string
:param group_name: the group name list
:return: GetMachineGrou... | Below is the the instruction that describes the task:
### Input:
get the logtail config names applied in a machine group
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_name: string
:par... |
def api(namespace=None, command="", PARAMS={}, body=None, host=HOST, port=str(PORT), version=VERSION, method="POST", verbose=VERBOSE, url=None, parse_params=True):
"""
General function for interacting with Cytoscape API.
:param namespace: namespace where the request should be executed. eg. "string"
:pa... | General function for interacting with Cytoscape API.
:param namespace: namespace where the request should be executed. eg. "string"
:param commnand: command to execute. eg. "protein query"
:param PARAMs: a dictionary with the parameters. Check your swagger normaly running on
http://localhost:1234/v1/sw... | Below is the the instruction that describes the task:
### Input:
General function for interacting with Cytoscape API.
:param namespace: namespace where the request should be executed. eg. "string"
:param commnand: command to execute. eg. "protein query"
:param PARAMs: a dictionary with the parameters. ... |
def clean_text(self, text):
'''Clean text using bleach.'''
if text is None:
return ''
text = re.sub(ILLEGAL_CHARACTERS_RE, '', text)
if '<' in text or '<' in text:
text = clean(text, tags=self.tags, strip=self.strip)
return unescape(text) | Clean text using bleach. | Below is the the instruction that describes the task:
### Input:
Clean text using bleach.
### Response:
def clean_text(self, text):
'''Clean text using bleach.'''
if text is None:
return ''
text = re.sub(ILLEGAL_CHARACTERS_RE, '', text)
if '<' in text or '<' in text:
... |
def addWriter(self, writer):
"""Add a FileDescriptor for notification of data available to write.
"""
self._sendToThread(self.writes.__setitem__, writer, 1)
self.wakeUp() | Add a FileDescriptor for notification of data available to write. | Below is the the instruction that describes the task:
### Input:
Add a FileDescriptor for notification of data available to write.
### Response:
def addWriter(self, writer):
"""Add a FileDescriptor for notification of data available to write.
"""
self._sendToThread(self.writes.__setitem__, ... |
def write_unregistered_file(date=None):
"""
Write .unregistered out to disk
"""
delete_registered_file()
if date is None:
date = get_time()
for f in constants.unregistered_files:
if os.path.lexists(f):
if os.path.islink(f):
# kill symlinks and regenera... | Write .unregistered out to disk | Below is the the instruction that describes the task:
### Input:
Write .unregistered out to disk
### Response:
def write_unregistered_file(date=None):
"""
Write .unregistered out to disk
"""
delete_registered_file()
if date is None:
date = get_time()
for f in constants.unregistered_... |
def from_counts_to_ratios(layer):
"""Transform counts to ratios.
Formula: ratio = subset count / total count
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The layer with new ratios.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = recomp... | Transform counts to ratios.
Formula: ratio = subset count / total count
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The layer with new ratios.
:rtype: QgsVectorLayer
.. versionadded:: 4.0 | Below is the the instruction that describes the task:
### Input:
Transform counts to ratios.
Formula: ratio = subset count / total count
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The layer with new ratios.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
### Respon... |
def uri2module(self, uri):
"""Convert an unencoded source uri to an encoded module name"""
# uri is the source code of the module
compressed = zlib.compress(uri)
encoded = base64.b64encode(compressed, b'+&')
encoded_str = encoded.decode('ASCII')
return super(EncodedModule... | Convert an unencoded source uri to an encoded module name | Below is the the instruction that describes the task:
### Input:
Convert an unencoded source uri to an encoded module name
### Response:
def uri2module(self, uri):
"""Convert an unencoded source uri to an encoded module name"""
# uri is the source code of the module
compressed = zlib.compre... |
def plot_soma(ax, soma, plane='xy',
soma_outline=True,
linewidth=_LINEWIDTH,
color=None, alpha=_ALPHA):
'''Generates a 2d figure of the soma.
Args:
ax(matplotlib axes): on what to plot
soma(neurom.core.Soma): plotted soma
plane(str): Any pair of... | Generates a 2d figure of the soma.
Args:
ax(matplotlib axes): on what to plot
soma(neurom.core.Soma): plotted soma
plane(str): Any pair of 'xyz'
diameter_scale(float): Scale factor multiplied with segment diameters before plotting
linewidth(float): all segments are plotted w... | Below is the the instruction that describes the task:
### Input:
Generates a 2d figure of the soma.
Args:
ax(matplotlib axes): on what to plot
soma(neurom.core.Soma): plotted soma
plane(str): Any pair of 'xyz'
diameter_scale(float): Scale factor multiplied with segment diameters... |
def create_cfm(in_file, lesion_mask=None, global_mask=True, out_path=None):
"""
Create a mask to constrain registration.
Parameters
----------
in_file : str
Path to an existing image (usually a mask).
If global_mask = True, this is used as a size/dimension reference.
out_path : ... | Create a mask to constrain registration.
Parameters
----------
in_file : str
Path to an existing image (usually a mask).
If global_mask = True, this is used as a size/dimension reference.
out_path : str
Path/filename for the new cost function mask.
lesion_mask : str, optiona... | Below is the the instruction that describes the task:
### Input:
Create a mask to constrain registration.
Parameters
----------
in_file : str
Path to an existing image (usually a mask).
If global_mask = True, this is used as a size/dimension reference.
out_path : str
Path/fi... |
def parse_duration(duration):
'''
Parse duration string, such as '3h2m3s' into milliseconds
>>> parse_duration('3h2m3s')
10923000
>>> parse_duration('0.3s')
300
>>> parse_duration('5')
5000
'''
_re_token = re.compile("([0-9.]+)([dhms]?)")
def parse_token(time, multiplier)... | Parse duration string, such as '3h2m3s' into milliseconds
>>> parse_duration('3h2m3s')
10923000
>>> parse_duration('0.3s')
300
>>> parse_duration('5')
5000 | Below is the the instruction that describes the task:
### Input:
Parse duration string, such as '3h2m3s' into milliseconds
>>> parse_duration('3h2m3s')
10923000
>>> parse_duration('0.3s')
300
>>> parse_duration('5')
5000
### Response:
def parse_duration(duration):
'''
Parse durat... |
def _copy_calibration(self, calibration):
"""Copy another ``StereoCalibration`` object's values."""
for key, item in calibration.__dict__.items():
self.__dict__[key] = item | Copy another ``StereoCalibration`` object's values. | Below is the the instruction that describes the task:
### Input:
Copy another ``StereoCalibration`` object's values.
### Response:
def _copy_calibration(self, calibration):
"""Copy another ``StereoCalibration`` object's values."""
for key, item in calibration.__dict__.items():
self.__di... |
def coordination_geometry_symmetry_measures_separation_plane_optim(self,
coordination_geometry,
separation_plane_algo,
... | Returns the symmetry measures of the given coordination geometry "coordination_geometry" using separation
facets to reduce the complexity of the system. Caller to the refined 2POINTS, 3POINTS and other ...
:param coordination_geometry: The coordination geometry to be investigated
:return: The sy... | Below is the the instruction that describes the task:
### Input:
Returns the symmetry measures of the given coordination geometry "coordination_geometry" using separation
facets to reduce the complexity of the system. Caller to the refined 2POINTS, 3POINTS and other ...
:param coordination_geometry:... |
def _clean_doc(self, doc, namespace, timestamp):
"""Reformats the given document before insertion into Solr.
This method reformats the document in the following ways:
- removes extraneous fields that aren't defined in schema.xml
- unwinds arrays in order to find and later flatten su... | Reformats the given document before insertion into Solr.
This method reformats the document in the following ways:
- removes extraneous fields that aren't defined in schema.xml
- unwinds arrays in order to find and later flatten sub-documents
- flattens the document so that there ... | Below is the the instruction that describes the task:
### Input:
Reformats the given document before insertion into Solr.
This method reformats the document in the following ways:
- removes extraneous fields that aren't defined in schema.xml
- unwinds arrays in order to find and later f... |
def generate_sphere(radius):
"""Generates a centered boolean mask of a 3D sphere"""
rint = np.ceil(radius).astype('int')
t = np.arange(-rint, rint+1, 1)
x,y,z = np.meshgrid(t, t, t, indexing='ij')
r = np.sqrt(x*x + y*y + z*z)
sphere = r < radius
return sphere | Generates a centered boolean mask of a 3D sphere | Below is the the instruction that describes the task:
### Input:
Generates a centered boolean mask of a 3D sphere
### Response:
def generate_sphere(radius):
"""Generates a centered boolean mask of a 3D sphere"""
rint = np.ceil(radius).astype('int')
t = np.arange(-rint, rint+1, 1)
x,y,z = np.meshgri... |
def gen_parameter_description(sections, descriptions, params_rst):
"""Write descriptions of parameters to the documentation file.
Parameters
----------
sections : list
Names of parameters sections.
descriptions : list
Structured descriptions of parameters.
params_rst : string
... | Write descriptions of parameters to the documentation file.
Parameters
----------
sections : list
Names of parameters sections.
descriptions : list
Structured descriptions of parameters.
params_rst : string
Path to the file with parameters documentation. | Below is the the instruction that describes the task:
### Input:
Write descriptions of parameters to the documentation file.
Parameters
----------
sections : list
Names of parameters sections.
descriptions : list
Structured descriptions of parameters.
params_rst : string
... |
def dict_array_bytes(ary, template):
"""
Return the number of bytes required by an array
Arguments
---------------
ary : dict
Dictionary representation of an array
template : dict
A dictionary of key-values, used to replace any
string values in the array with concrete in... | Return the number of bytes required by an array
Arguments
---------------
ary : dict
Dictionary representation of an array
template : dict
A dictionary of key-values, used to replace any
string values in the array with concrete integral
values
Returns
----------... | Below is the the instruction that describes the task:
### Input:
Return the number of bytes required by an array
Arguments
---------------
ary : dict
Dictionary representation of an array
template : dict
A dictionary of key-values, used to replace any
string values in the ar... |
def conv(name, x, output_channels, filter_size=None, stride=None,
logscale_factor=3.0, apply_actnorm=True, conv_init="default",
dilations=None):
"""Convolutional layer with edge bias padding and optional actnorm.
If x is 5-dimensional, actnorm is applied independently across every
time-step.
... | Convolutional layer with edge bias padding and optional actnorm.
If x is 5-dimensional, actnorm is applied independently across every
time-step.
Args:
name: variable scope.
x: 4-D Tensor or 5-D Tensor of shape NHWC or NTHWC
output_channels: Number of output channels.
filter_size: list of ints, i... | Below is the the instruction that describes the task:
### Input:
Convolutional layer with edge bias padding and optional actnorm.
If x is 5-dimensional, actnorm is applied independently across every
time-step.
Args:
name: variable scope.
x: 4-D Tensor or 5-D Tensor of shape NHWC or NTHWC
output_... |
def load_buildfile(self, target):
"""Pull a build file from git."""
log.info('Loading: %s', target)
filepath = os.path.join(target.path, app.get_options().buildfile_name)
try:
repo = self.repo_state.GetRepo(target.repo)
return repo.get_file(filepath)
excep... | Pull a build file from git. | Below is the the instruction that describes the task:
### Input:
Pull a build file from git.
### Response:
def load_buildfile(self, target):
"""Pull a build file from git."""
log.info('Loading: %s', target)
filepath = os.path.join(target.path, app.get_options().buildfile_name)
try:
... |
def get_external_model(class_object):
"""
Given a class (class_object), it locates the related model (throught the codenerix abstract class)
"""
class_abstract = class_object.CodenerixMeta.abstract
if class_abstract is not None:
for class_related in class_object._meta.related_objects:
... | Given a class (class_object), it locates the related model (throught the codenerix abstract class) | Below is the the instruction that describes the task:
### Input:
Given a class (class_object), it locates the related model (throught the codenerix abstract class)
### Response:
def get_external_model(class_object):
"""
Given a class (class_object), it locates the related model (throught the codenerix abst... |
def _call(self, method, auth, arg, defer, notimeout=False):
"""Calls the Exosite One Platform RPC API.
If `defer` is False, result is a tuple with this structure:
(success (boolean), response)
Otherwise, the result is just True.
notimeout, if True, ignores th... | Calls the Exosite One Platform RPC API.
If `defer` is False, result is a tuple with this structure:
(success (boolean), response)
Otherwise, the result is just True.
notimeout, if True, ignores the reuseconnection setting, creating
a new connection with no... | Below is the the instruction that describes the task:
### Input:
Calls the Exosite One Platform RPC API.
If `defer` is False, result is a tuple with this structure:
(success (boolean), response)
Otherwise, the result is just True.
notimeout, if True, ignores the ... |
def configure(self, config):
"""
Initialize the plugin. This creates a data object which holds a
BudgetDataPackage parser which operates based on a specification
which is either provided in the config via:
``ckan.budgets.specification`` or the included version.
"""
... | Initialize the plugin. This creates a data object which holds a
BudgetDataPackage parser which operates based on a specification
which is either provided in the config via:
``ckan.budgets.specification`` or the included version. | Below is the the instruction that describes the task:
### Input:
Initialize the plugin. This creates a data object which holds a
BudgetDataPackage parser which operates based on a specification
which is either provided in the config via:
``ckan.budgets.specification`` or the included version... |
def sample(self, params, argmax_sampling=False):
""" Sample from a probability space of all actions """
means = params[:, :, 0]
log_std = params[:, :, 1]
if argmax_sampling:
return means
else:
return torch.randn_like(means) * torch.exp(log_std) + means | Sample from a probability space of all actions | Below is the the instruction that describes the task:
### Input:
Sample from a probability space of all actions
### Response:
def sample(self, params, argmax_sampling=False):
""" Sample from a probability space of all actions """
means = params[:, :, 0]
log_std = params[:, :, 1]
if... |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Del... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
### Response:
def fi... |
def dump_set(self, obj, class_name=set_class_name):
"""
``set`` dumper.
"""
return {"$" + class_name: [self._json_convert(item) for item in obj]} | ``set`` dumper. | Below is the the instruction that describes the task:
### Input:
``set`` dumper.
### Response:
def dump_set(self, obj, class_name=set_class_name):
"""
``set`` dumper.
"""
return {"$" + class_name: [self._json_convert(item) for item in obj]} |
def syntax_check():
"""Runs flake8 against the codebase."""
with fab_settings(warn_only=True):
for file_type in settings.SYNTAX_CHECK:
needs_to_abort = False
# because egrep fails with exit code 1, we need to allow this as
# a successful exit code in our env
... | Runs flake8 against the codebase. | Below is the the instruction that describes the task:
### Input:
Runs flake8 against the codebase.
### Response:
def syntax_check():
"""Runs flake8 against the codebase."""
with fab_settings(warn_only=True):
for file_type in settings.SYNTAX_CHECK:
needs_to_abort = False
# be... |
def watch(limit):
"""watch scan rates across the cluster"""
period = 5.0
prev = db.db()
prev_totals = None
while True:
click.clear()
time.sleep(period)
cur = db.db()
cur.data['gkrate'] = {}
progress = []
prev_buckets = {b.bucket_id: b for b in prev.bu... | watch scan rates across the cluster | Below is the the instruction that describes the task:
### Input:
watch scan rates across the cluster
### Response:
def watch(limit):
"""watch scan rates across the cluster"""
period = 5.0
prev = db.db()
prev_totals = None
while True:
click.clear()
time.sleep(period)
cur... |
async def asynchronously_get_data(self, url):
""" Asynchronously get data from Chunked transfer encoding of https://smartcity.rbccps.org/api/0.1.0/subscribe.
(Only this function requires Python 3. Rest of the functions can be run in python2.
Args:
url (string): url to subscribe
... | Asynchronously get data from Chunked transfer encoding of https://smartcity.rbccps.org/api/0.1.0/subscribe.
(Only this function requires Python 3. Rest of the functions can be run in python2.
Args:
url (string): url to subscribe | Below is the the instruction that describes the task:
### Input:
Asynchronously get data from Chunked transfer encoding of https://smartcity.rbccps.org/api/0.1.0/subscribe.
(Only this function requires Python 3. Rest of the functions can be run in python2.
Args:
url (string): url to su... |
def _inv_sqrtm(x):
'''Computes x^(-1/2)'''
vals, vecs = np.linalg.eigh(x)
return (vecs / np.sqrt(vals)).dot(vecs.T) | Computes x^(-1/2) | Below is the the instruction that describes the task:
### Input:
Computes x^(-1/2)
### Response:
def _inv_sqrtm(x):
'''Computes x^(-1/2)'''
vals, vecs = np.linalg.eigh(x)
return (vecs / np.sqrt(vals)).dot(vecs.T) |
def p_Body(p):
'''
Body : Line
| Body Line
'''
if not isinstance(p[1], Body):
p[0] = Body(None, p[1])
else:
p[0] = Body(p[1], p[2]) | Body : Line
| Body Line | Below is the the instruction that describes the task:
### Input:
Body : Line
| Body Line
### Response:
def p_Body(p):
'''
Body : Line
| Body Line
'''
if not isinstance(p[1], Body):
p[0] = Body(None, p[1])
else:
p[0] = Body(p[1], p[2]) |
def pangocairo_create_context(cr):
"""
If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful.
"""
# TODO move this to core.backend
try:
return PangoCairo.create_context(cr)
except KeyError a... | If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful. | Below is the the instruction that describes the task:
### Input:
If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful.
### Response:
def pangocairo_create_context(cr):
"""
If python-gi-cairo is not installed,... |
def artist_related_artists(self, spotify_id):
"""Get related artists for an artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by.
"""
route = Route('GET', '/artists/{spotify_id}/related-artists', spotify_id=spotify_id)
... | Get related artists for an artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by. | Below is the the instruction that describes the task:
### Input:
Get related artists for an artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by.
### Response:
def artist_related_artists(self, spotify_id):
"""Get related artists for an ... |
def update_font(self):
"""Update font from Preferences"""
font = self.get_plugin_font()
for client in self.clients:
client.set_font(font) | Update font from Preferences | Below is the the instruction that describes the task:
### Input:
Update font from Preferences
### Response:
def update_font(self):
"""Update font from Preferences"""
font = self.get_plugin_font()
for client in self.clients:
client.set_font(font) |
def _channel(self, width, height, state_sizes,
start_level, start_image, dataset):
"""Generate a channel.
Parameters
----------
width : `int`
Image width.
height : `int`
Image height.
state_sizes : `list` of (`int` or `None`)
... | Generate a channel.
Parameters
----------
width : `int`
Image width.
height : `int`
Image height.
state_sizes : `list` of (`int` or `None`)
Level state sizes.
start_level : `int`
Initial level.
start_image : `PIL.Im... | Below is the the instruction that describes the task:
### Input:
Generate a channel.
Parameters
----------
width : `int`
Image width.
height : `int`
Image height.
state_sizes : `list` of (`int` or `None`)
Level state sizes.
start_l... |
def write_state_file(self):
"""Save information that must persist to a file.
We do not want to create a new VPC and new identical security groups, so we save
information about them in a file between runs.
"""
fh = open('awsproviderstate.json', 'w')
state = {}
sta... | Save information that must persist to a file.
We do not want to create a new VPC and new identical security groups, so we save
information about them in a file between runs. | Below is the the instruction that describes the task:
### Input:
Save information that must persist to a file.
We do not want to create a new VPC and new identical security groups, so we save
information about them in a file between runs.
### Response:
def write_state_file(self):
"""Save i... |
def getTypeInfo(self, sql_type): # nopep8
"""Executes SQLGetTypeInfo a creates a result set with information
about the specified data type or all data types supported by the
ODBC driver if not specified.
"""
fut = self._run_operation(self._impl.getTypeInfo, sql_type)
ret... | Executes SQLGetTypeInfo a creates a result set with information
about the specified data type or all data types supported by the
ODBC driver if not specified. | Below is the the instruction that describes the task:
### Input:
Executes SQLGetTypeInfo a creates a result set with information
about the specified data type or all data types supported by the
ODBC driver if not specified.
### Response:
def getTypeInfo(self, sql_type): # nopep8
"""Execute... |
def __get_matching_indices(self, args, kwargs, args_list, kwargs_list):
"""
Args:
args: tuple, the arguments inputed by the user
kwargs: dictionary, the keyword arguments inputed by the user
args_list: list, a list of argument tuples
kwargs_list: list, a l... | Args:
args: tuple, the arguments inputed by the user
kwargs: dictionary, the keyword arguments inputed by the user
args_list: list, a list of argument tuples
kwargs_list: list, a list of keyword argument dictionaries
Returns:
list, the list of indices ... | Below is the the instruction that describes the task:
### Input:
Args:
args: tuple, the arguments inputed by the user
kwargs: dictionary, the keyword arguments inputed by the user
args_list: list, a list of argument tuples
kwargs_list: list, a list of keyword argument... |
def gep(self, i):
"""
Resolve the type of the i-th element (for getelementptr lookups).
*i* needs to be a LLVM constant, so that the type can be determined
at compile-time.
"""
if not isinstance(i.type, IntType):
raise TypeError(i.type)
return self.el... | Resolve the type of the i-th element (for getelementptr lookups).
*i* needs to be a LLVM constant, so that the type can be determined
at compile-time. | Below is the the instruction that describes the task:
### Input:
Resolve the type of the i-th element (for getelementptr lookups).
*i* needs to be a LLVM constant, so that the type can be determined
at compile-time.
### Response:
def gep(self, i):
"""
Resolve the type of the i-th e... |
def evalOptions(self, root, parsed, unparsed):
""" Evaluate only the options and return flags as suggestions """
logger.debug("parsing options at tree: %s with p:%s, u:%s", root.node, parsed, unparsed)
suggestions = dict()
token = unparsed.pop().strip()
parts = token.partition('... | Evaluate only the options and return flags as suggestions | Below is the the instruction that describes the task:
### Input:
Evaluate only the options and return flags as suggestions
### Response:
def evalOptions(self, root, parsed, unparsed):
""" Evaluate only the options and return flags as suggestions """
logger.debug("parsing options at tree: %s with p:... |
def _basic_cancel(self, frame_in):
"""Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_in: Amqp frame.
:return:
"""
LOGGER.warning(
'Received Basic.Cancel on consumer_tag: %s',
try_utf8_decode(frame_in.consumer_tag)
)
... | Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_in: Amqp frame.
:return: | Below is the the instruction that describes the task:
### Input:
Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_in: Amqp frame.
:return:
### Response:
def _basic_cancel(self, frame_in):
"""Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_... |
def get_profile(A):
"Fail-soft profile getter; if no profile is present assume none and quietly ignore."
try:
with open(os.path.expanduser(A.profile)) as I:
profile = json.load(I)
return profile
except:
return {} | Fail-soft profile getter; if no profile is present assume none and quietly ignore. | Below is the the instruction that describes the task:
### Input:
Fail-soft profile getter; if no profile is present assume none and quietly ignore.
### Response:
def get_profile(A):
"Fail-soft profile getter; if no profile is present assume none and quietly ignore."
try:
with open(os.path.expanduse... |
def init(self):
"""
Cortex M initialization. The bus must be accessible when this method is called.
"""
if not self.call_delegate('will_start_debug_core', core=self):
if self.halt_on_connect:
self.halt()
self._read_core_type()
self._che... | Cortex M initialization. The bus must be accessible when this method is called. | Below is the the instruction that describes the task:
### Input:
Cortex M initialization. The bus must be accessible when this method is called.
### Response:
def init(self):
"""
Cortex M initialization. The bus must be accessible when this method is called.
"""
if not self.call_del... |
def update(self):
"""Update the AMP list."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
for k, v in iteritems(self.glances_amps.update()):
stats.append({'key': k,
'name': v.NAME,
... | Update the AMP list. | Below is the the instruction that describes the task:
### Input:
Update the AMP list.
### Response:
def update(self):
"""Update the AMP list."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
for k, v in iteritems(self.glances_amps.updat... |
def kml_lod(min_lod_pixels=DEFAULT_MIN_LOD_PIXELS, max_lod_pixels=DEFAULT_MAX_LOD_PIXELS):
"""
Create the KML LevelOfDetail (LOD) Tag.
In a Region, the <minLodPixels> and <maxLodPixels> elements allow you to specify
an area of the screen (in square pixels). When your data is projected onto the screen,
... | Create the KML LevelOfDetail (LOD) Tag.
In a Region, the <minLodPixels> and <maxLodPixels> elements allow you to specify
an area of the screen (in square pixels). When your data is projected onto the screen,
it must occupy an area of the screen that is greater than <minLodPixels> and less
than <maxLodP... | Below is the the instruction that describes the task:
### Input:
Create the KML LevelOfDetail (LOD) Tag.
In a Region, the <minLodPixels> and <maxLodPixels> elements allow you to specify
an area of the screen (in square pixels). When your data is projected onto the screen,
it must occupy an area of the ... |
def do_ultracache(parser, token):
"""Based on Django's default cache template tag"""
nodelist = parser.parse(("endultracache",))
parser.delete_first_token()
tokens = token.split_contents()
if len(tokens) < 3:
raise TemplateSyntaxError(""%r" tag requires at least 2 arguments." % tokens[0])
... | Based on Django's default cache template tag | Below is the the instruction that describes the task:
### Input:
Based on Django's default cache template tag
### Response:
def do_ultracache(parser, token):
"""Based on Django's default cache template tag"""
nodelist = parser.parse(("endultracache",))
parser.delete_first_token()
tokens = token.spl... |
def group_re(self):
''' Return a regexp pattern with named groups '''
out = ''
for token, data in self.tokens():
if token == 'TXT': out += re.escape(data)
elif token == 'VAR': out += '(?P<%s>%s)' % (data[1], data[0])
elif token == 'ANON': out += '(?:%s)' %... | Return a regexp pattern with named groups | Below is the the instruction that describes the task:
### Input:
Return a regexp pattern with named groups
### Response:
def group_re(self):
''' Return a regexp pattern with named groups '''
out = ''
for token, data in self.tokens():
if token == 'TXT': out += re.escape(data)
... |
def zoom(ax, xy='x', factor=1):
"""Zoom into axis.
Parameters
----------
"""
limits = ax.get_xlim() if xy == 'x' else ax.get_ylim()
new_limits = (0.5*(limits[0] + limits[1])
+ 1./factor * np.array((-0.5, 0.5)) * (limits[1] - limits[0]))
if xy == 'x':
ax.set_xlim(ne... | Zoom into axis.
Parameters
---------- | Below is the the instruction that describes the task:
### Input:
Zoom into axis.
Parameters
----------
### Response:
def zoom(ax, xy='x', factor=1):
"""Zoom into axis.
Parameters
----------
"""
limits = ax.get_xlim() if xy == 'x' else ax.get_ylim()
new_limits = (0.5*(limits[0] + l... |
def _vectorize_and_bind(self, local_path, dest):
# type: (Uploader, blobxfer.models.upload.LocalPath,
# List[blobxfer.models.azure.StorageEntity]) ->
# Tuple[blobxfer.operations.upload.UploadAction,
# blobxfer.models.upload.LocalPath,
# blobxfer.models... | Vectorize local path to destinations, if necessary, and bind
:param Uploader self: this
:param blobxfer.models.LocalPath local_path: local path
:param list dest: list of destination tuples (sa, ase)
:rtype: tuple
:return: action, LocalPath, ase | Below is the the instruction that describes the task:
### Input:
Vectorize local path to destinations, if necessary, and bind
:param Uploader self: this
:param blobxfer.models.LocalPath local_path: local path
:param list dest: list of destination tuples (sa, ase)
:rtype: tuple
... |
def scalc_vgp_df(vgp_df, anti=0, rev=0, cutoff=180., kappa=0, n=0, spin=0, v=0, boot=0, mm97=0, nb=1000):
"""
Calculates Sf for a dataframe with VGP Lat., and optional Fisher's k, site latitude and N information can be used to correct for within site scatter (McElhinny & McFadden, 1997)
Parameters
____... | Calculates Sf for a dataframe with VGP Lat., and optional Fisher's k, site latitude and N information can be used to correct for within site scatter (McElhinny & McFadden, 1997)
Parameters
_________
df : Pandas Dataframe with columns
REQUIRED:
vgp_lat : VGP latitude
ONLY REQUIRED f... | Below is the the instruction that describes the task:
### Input:
Calculates Sf for a dataframe with VGP Lat., and optional Fisher's k, site latitude and N information can be used to correct for within site scatter (McElhinny & McFadden, 1997)
Parameters
_________
df : Pandas Dataframe with columns
... |
def _request(self, data):
# type: (str) -> None
"""Override parent by buffering the metric instead of sending now"""
data = bytearray("{}\n".format(data).encode())
self._prepare_batches_for_storage(len(data))
self._batches[-1].extend(data) | Override parent by buffering the metric instead of sending now | Below is the the instruction that describes the task:
### Input:
Override parent by buffering the metric instead of sending now
### Response:
def _request(self, data):
# type: (str) -> None
"""Override parent by buffering the metric instead of sending now"""
data = bytearray("{}\n".format(... |
def identical(self, a, b):
"""
This should return whether `a` is identical to `b`. Of course, this isn't always clear. True should mean that it
is definitely identical. False eans that, conservatively, it might not be.
:param a: an AST
:param b: another AST
"""
r... | This should return whether `a` is identical to `b`. Of course, this isn't always clear. True should mean that it
is definitely identical. False eans that, conservatively, it might not be.
:param a: an AST
:param b: another AST | Below is the the instruction that describes the task:
### Input:
This should return whether `a` is identical to `b`. Of course, this isn't always clear. True should mean that it
is definitely identical. False eans that, conservatively, it might not be.
:param a: an AST
:param b: another AST... |
def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None):
"""
Usage:
deprecate_module_with_proxy(__name__, locals()) # at bottom of module
"""
def _ModuleProxy(module, depr):
"""Return a wrapped object that warns about deprecated accesses"""
# http:/... | Usage:
deprecate_module_with_proxy(__name__, locals()) # at bottom of module | Below is the the instruction that describes the task:
### Input:
Usage:
deprecate_module_with_proxy(__name__, locals()) # at bottom of module
### Response:
def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None):
"""
Usage:
deprecate_module_with_proxy(__name__... |
def outdict(self, ndigits=3):
"""Return dictionary structure rounded to a given precision."""
output = self.__dict__.copy()
for item in output:
output[item] = round(output[item], ndigits)
return output | Return dictionary structure rounded to a given precision. | Below is the the instruction that describes the task:
### Input:
Return dictionary structure rounded to a given precision.
### Response:
def outdict(self, ndigits=3):
"""Return dictionary structure rounded to a given precision."""
output = self.__dict__.copy()
for item in output:
... |
def _render_config(cls, dest, template_name, template_args):
"""
Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations
"""
template_args = template_args.copy()
# Substitute values here
pyversion = tem... | Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations | Below is the the instruction that describes the task:
### Input:
Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations
### Response:
def _render_config(cls, dest, template_name, template_args):
"""
Renders and writes a template_... |
def render_template(cmd_derived_from_alias, pos_args_table):
"""
Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments.
Args:
cmd_derived_from_alias: The string to be injected with positional arguemnts.
pos_args_table: The dictionary used to rendered.
R... | Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments.
Args:
cmd_derived_from_alias: The string to be injected with positional arguemnts.
pos_args_table: The dictionary used to rendered.
Returns:
A processed string with positional arguments injected. | Below is the the instruction that describes the task:
### Input:
Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments.
Args:
cmd_derived_from_alias: The string to be injected with positional arguemnts.
pos_args_table: The dictionary used to rendered.
Retur... |
def recursive_replace(list_, target, repl=-1):
r"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable
"""
repl_list = [
recursive_replace(item, target, repl) if isinstance(item, (list, np.ndarray)) else
(repl if item == target else item)
... | r"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable | Below is the the instruction that describes the task:
### Input:
r"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable
### Response:
def recursive_replace(list_, target, repl=-1):
r"""
Recursively removes target in all lists and sublists and replaces the... |
def upsert(db, table, key_cols, update_dict):
"""Fabled upsert for SQLiteDB.
Perform an upsert based on primary key.
:param SQLiteDB db: database
:param str table: table to upsert into
:param str key_cols: name of key columns
:param dict update_dict: key-value pairs to upsert
"""
with... | Fabled upsert for SQLiteDB.
Perform an upsert based on primary key.
:param SQLiteDB db: database
:param str table: table to upsert into
:param str key_cols: name of key columns
:param dict update_dict: key-value pairs to upsert | Below is the the instruction that describes the task:
### Input:
Fabled upsert for SQLiteDB.
Perform an upsert based on primary key.
:param SQLiteDB db: database
:param str table: table to upsert into
:param str key_cols: name of key columns
:param dict update_dict: key-value pairs to upsert
#... |
def run(ctx,
algofile,
algotext,
define,
data_frequency,
capital_base,
bundle,
bundle_timestamp,
start,
end,
output,
trading_calendar,
print_algo,
metrics_set,
local_namespace,
blotter):
"""Run a ... | Run a backtest for the given algorithm. | Below is the the instruction that describes the task:
### Input:
Run a backtest for the given algorithm.
### Response:
def run(ctx,
algofile,
algotext,
define,
data_frequency,
capital_base,
bundle,
bundle_timestamp,
start,
end,
output,... |
def _compute_distance_scaling(self, C, mag, rrup):
"""
Compute distance scaling term (eq.3, page 319).
The distance scaling assumes the near-source effect of local site
conditions due to 50% very firm soil and soft rock and 50% firm rock.
"""
g = C['c5'] + C['c6'] * 0.5 ... | Compute distance scaling term (eq.3, page 319).
The distance scaling assumes the near-source effect of local site
conditions due to 50% very firm soil and soft rock and 50% firm rock. | Below is the the instruction that describes the task:
### Input:
Compute distance scaling term (eq.3, page 319).
The distance scaling assumes the near-source effect of local site
conditions due to 50% very firm soil and soft rock and 50% firm rock.
### Response:
def _compute_distance_scaling(self,... |
def get_chain(self, group_name):
""" Provides the component and group names for an analysis chain.
:param group_name: The group name of the last step in the analysis
chain e.g. 'Basecall_1D_000'
:returns: A list of component-name/group-name pairs (tuples). This
w... | Provides the component and group names for an analysis chain.
:param group_name: The group name of the last step in the analysis
chain e.g. 'Basecall_1D_000'
:returns: A list of component-name/group-name pairs (tuples). This
will include each component of the chain, in o... | Below is the the instruction that describes the task:
### Input:
Provides the component and group names for an analysis chain.
:param group_name: The group name of the last step in the analysis
chain e.g. 'Basecall_1D_000'
:returns: A list of component-name/group-name pairs (tup... |
def run_rsem(job, rna_bam, univ_options, rsem_options):
"""
Run rsem on the input RNA bam.
ARGUMENTS
:param toil.fileStore.FileID rna_bam: fsID of a transcriptome bam generated by STAR
:param dict univ_options: Dict of universal options used by almost all tools
:param dict rsem_options: Options... | Run rsem on the input RNA bam.
ARGUMENTS
:param toil.fileStore.FileID rna_bam: fsID of a transcriptome bam generated by STAR
:param dict univ_options: Dict of universal options used by almost all tools
:param dict rsem_options: Options specific to rsem
:return: Dict of gene- and isoform-level expre... | Below is the the instruction that describes the task:
### Input:
Run rsem on the input RNA bam.
ARGUMENTS
:param toil.fileStore.FileID rna_bam: fsID of a transcriptome bam generated by STAR
:param dict univ_options: Dict of universal options used by almost all tools
:param dict rsem_options: Option... |
def to_posix_path(code_path):
"""
Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
Returns
-------
... | Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
Returns
-------
str
Posix equivalent of absolute ... | Below is the the instruction that describes the task:
### Input:
Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
... |
def include(module_name, *module_names):
"""Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info.
"""
def decorated(fn):
_add_decorator(fn, "include", nargs=[module_name] + list(module_names))
return fn
... | Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info. | Below is the the instruction that describes the task:
### Input:
Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info.
### Response:
def include(module_name, *module_names):
"""Used by functions in package.py to have access ... |
def _create_body(self, name, emailAddress, ttl=3600, comment=None,
subdomains=None, records=None):
"""
Creates the appropriate dict for creating a new domain.
"""
if subdomains is None:
subdomains = []
if records is None:
records = []
b... | Creates the appropriate dict for creating a new domain. | Below is the the instruction that describes the task:
### Input:
Creates the appropriate dict for creating a new domain.
### Response:
def _create_body(self, name, emailAddress, ttl=3600, comment=None,
subdomains=None, records=None):
"""
Creates the appropriate dict for creating a new d... |
def dist_factory(path_item, entry, only):
"""
Return a dist_factory for a path_item and entry
"""
lower = entry.lower()
is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info')))
return (
distributions_from_metadata
if is_meta else
find_distributions
if not o... | Return a dist_factory for a path_item and entry | Below is the the instruction that describes the task:
### Input:
Return a dist_factory for a path_item and entry
### Response:
def dist_factory(path_item, entry, only):
"""
Return a dist_factory for a path_item and entry
"""
lower = entry.lower()
is_meta = any(map(lower.endswith, ('.egg-info', ... |
def _get_lr_tensor(self):
"""Get lr minimizing the surrogate.
Returns:
The lr_t.
"""
lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min
return lr | Get lr minimizing the surrogate.
Returns:
The lr_t. | Below is the the instruction that describes the task:
### Input:
Get lr minimizing the surrogate.
Returns:
The lr_t.
### Response:
def _get_lr_tensor(self):
"""Get lr minimizing the surrogate.
Returns:
The lr_t.
"""
lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.