code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def users_setPresence(self, *, presence: str, **kwargs) -> SlackResponse:
"""Manually sets user presence.
Args:
presence (str): Either 'auto' or 'away'.
"""
kwargs.update({"presence": presence})
return self.api_call("users.setPresence", json=kwargs) | Manually sets user presence.
Args:
presence (str): Either 'auto' or 'away'. | Below is the the instruction that describes the task:
### Input:
Manually sets user presence.
Args:
presence (str): Either 'auto' or 'away'.
### Response:
def users_setPresence(self, *, presence: str, **kwargs) -> SlackResponse:
"""Manually sets user presence.
Args:
... |
def replace_vobject(self, uid, ical, filename=None):
"""Update the Remind command with the uid in the file with the new iCalendar"""
if not filename:
filename = self._filename
elif filename not in self._reminders:
return
uid = uid.split('@')[0]
with self... | Update the Remind command with the uid in the file with the new iCalendar | Below is the the instruction that describes the task:
### Input:
Update the Remind command with the uid in the file with the new iCalendar
### Response:
def replace_vobject(self, uid, ical, filename=None):
"""Update the Remind command with the uid in the file with the new iCalendar"""
if not filena... |
def port_channel_minimum_links(self, **kwargs):
"""Set minimum number of links in a port channel.
Args:
name (str): Port-channel number. (1, 5, etc)
minimum_links (str): Minimum number of links in channel group.
callback (function): A function executed upon completio... | Set minimum number of links in a port channel.
Args:
name (str): Port-channel number. (1, 5, etc)
minimum_links (str): Minimum number of links in channel group.
callback (function): A function executed upon completion of the
method. The only parameter passed... | Below is the the instruction that describes the task:
### Input:
Set minimum number of links in a port channel.
Args:
name (str): Port-channel number. (1, 5, etc)
minimum_links (str): Minimum number of links in channel group.
callback (function): A function executed upon... |
def getChildrenInfo(self):
"""get all children information
Returns:
children's extended address
"""
print '%s call getChildrenInfo' % self.port
try:
childrenInfoAll = []
childrenInfo = {'EUI': 0, 'Rloc16': 0, 'MLEID': ''}
childrenL... | get all children information
Returns:
children's extended address | Below is the the instruction that describes the task:
### Input:
get all children information
Returns:
children's extended address
### Response:
def getChildrenInfo(self):
"""get all children information
Returns:
children's extended address
"""
prin... |
def is_passive_request(self, request):
""" Should we skip activity update on this URL/View. """
if request.path in PASSIVE_URLS:
return True
try:
match = resolve(request.path)
# TODO: check namespaces too
if match.url_name in PASSIVE_URL_NAMES:
... | Should we skip activity update on this URL/View. | Below is the the instruction that describes the task:
### Input:
Should we skip activity update on this URL/View.
### Response:
def is_passive_request(self, request):
""" Should we skip activity update on this URL/View. """
if request.path in PASSIVE_URLS:
return True
try:
... |
def LegacyKextunload(self, cf_bundle_identifier):
"""Unload a kext by forking into kextunload."""
error_code = OS_SUCCESS
bundle_identifier = self.CFStringToPystring(cf_bundle_identifier)
try:
subprocess.check_call(['/sbin/kextunload', '-b', bundle_identifier])
except subprocess.CalledProcessE... | Unload a kext by forking into kextunload. | Below is the the instruction that describes the task:
### Input:
Unload a kext by forking into kextunload.
### Response:
def LegacyKextunload(self, cf_bundle_identifier):
"""Unload a kext by forking into kextunload."""
error_code = OS_SUCCESS
bundle_identifier = self.CFStringToPystring(cf_bundle_identi... |
def plot_sino(self, ax=None, Ang=_def.LOSImpAng,
AngUnit=_def.LOSImpAngUnit, Sketch=True, dP=None,
dLeg=_def.TorLegd, draw=True, fs=None, wintit=None,
Test=True):
""" Plot the sinogram of the vessel polygon, by computing its envelopp in a cross-section, can ... | Plot the sinogram of the vessel polygon, by computing its envelopp in a cross-section, can also plot a 3D version of it
The envelop of the polygon is computed using self.Sino_RefPt as a reference point in projection space,
and plotted using the provided dictionary of properties.
Optionaly a sma... | Below is the the instruction that describes the task:
### Input:
Plot the sinogram of the vessel polygon, by computing its envelopp in a cross-section, can also plot a 3D version of it
The envelop of the polygon is computed using self.Sino_RefPt as a reference point in projection space,
and plotted... |
def StartHuntFlowOnClient(client_id, hunt_id):
"""Starts a flow corresponding to a given hunt on a given client."""
hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
hunt_obj = CompleteHuntIfExpirationTimeReached(hunt_obj)
# There may be a little race between foreman rules being removed and
# foreman sche... | Starts a flow corresponding to a given hunt on a given client. | Below is the the instruction that describes the task:
### Input:
Starts a flow corresponding to a given hunt on a given client.
### Response:
def StartHuntFlowOnClient(client_id, hunt_id):
"""Starts a flow corresponding to a given hunt on a given client."""
hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)... |
def echo_headers(headers, file=None):
"""Echo headers, sorted."""
for k, v in sorted(headers.items()):
click.echo("{0}: {1}".format(k.title(), v), file=file)
click.echo(file=file) | Echo headers, sorted. | Below is the the instruction that describes the task:
### Input:
Echo headers, sorted.
### Response:
def echo_headers(headers, file=None):
"""Echo headers, sorted."""
for k, v in sorted(headers.items()):
click.echo("{0}: {1}".format(k.title(), v), file=file)
click.echo(file=file) |
def create_match(self, matcher_name, classification):
"""
Create a TextLogErrorMatch instance
Typically used for manual "matches" or tests.
"""
if classification is None:
classification = ClassifiedFailure.objects.create()
TextLogErrorMatch.objects.create(
... | Create a TextLogErrorMatch instance
Typically used for manual "matches" or tests. | Below is the the instruction that describes the task:
### Input:
Create a TextLogErrorMatch instance
Typically used for manual "matches" or tests.
### Response:
def create_match(self, matcher_name, classification):
"""
Create a TextLogErrorMatch instance
Typically used for manual ... |
def infer(self, limit=100, confidence=0.75):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
if self.__schema is None or self.__headers is None:
# Infer (tabulator)
if not self.__storage:
with self.__stream as stream:
... | https://github.com/frictionlessdata/tableschema-py#schema | Below is the the instruction that describes the task:
### Input:
https://github.com/frictionlessdata/tableschema-py#schema
### Response:
def infer(self, limit=100, confidence=0.75):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
if self.__schema is None or self.__headers i... |
def execute(handlers, local_commands):
'''
Run the command
:return:
'''
# verify if the environment variables are correctly set
check_environment()
# create the argument parser
parser = create_parser(handlers)
# if no argument is provided, print help and exit
if len(sys.argv[1:]) == 0:
parser.... | Run the command
:return: | Below is the the instruction that describes the task:
### Input:
Run the command
:return:
### Response:
def execute(handlers, local_commands):
'''
Run the command
:return:
'''
# verify if the environment variables are correctly set
check_environment()
# create the argument parser
parser = create... |
def updateSiteName(self, block_name, origin_site_name):
"""
Update the origin_site_name for a given block name
"""
if not origin_site_name:
dbsExceptionHandler('dbsException-invalid-input',
"DBSBlock/updateSiteName. origin_site_name is mandator... | Update the origin_site_name for a given block name | Below is the the instruction that describes the task:
### Input:
Update the origin_site_name for a given block name
### Response:
def updateSiteName(self, block_name, origin_site_name):
"""
Update the origin_site_name for a given block name
"""
if not origin_site_name:
d... |
def convert_index(self, index: int, from_view: int, to_view: int, decoded: bool, message_indx=-1) -> tuple:
"""
Konvertiert einen Index aus der einen Sicht (z.B. Bit) in eine andere (z.B. Hex)
:param message_indx: if -1, the message with max length is chosen
:return:
"""
... | Konvertiert einen Index aus der einen Sicht (z.B. Bit) in eine andere (z.B. Hex)
:param message_indx: if -1, the message with max length is chosen
:return: | Below is the the instruction that describes the task:
### Input:
Konvertiert einen Index aus der einen Sicht (z.B. Bit) in eine andere (z.B. Hex)
:param message_indx: if -1, the message with max length is chosen
:return:
### Response:
def convert_index(self, index: int, from_view: int, to_view: in... |
def main():
"""
If a project has a Curses driver, the section "main" in the section
"run" must be "bibliopixel.drivers.curses.Curses.main".
"""
if not _curses:
# https://stackoverflow.com/a/1325587/43839
if os.name == 'nt':
raise ValueErro... | If a project has a Curses driver, the section "main" in the section
"run" must be "bibliopixel.drivers.curses.Curses.main". | Below is the the instruction that describes the task:
### Input:
If a project has a Curses driver, the section "main" in the section
"run" must be "bibliopixel.drivers.curses.Curses.main".
### Response:
def main():
"""
If a project has a Curses driver, the section "main" in the section
... |
def workdir_loaded(func):
"""
Decorator to make sure that the workdir is loaded when calling the
decorated function
"""
@wraps(func)
def decorator(workdir, *args, **kwargs):
if not workdir.loaded:
workdir.load()
return func(workdir, *args, **kwargs)
return deco... | Decorator to make sure that the workdir is loaded when calling the
decorated function | Below is the the instruction that describes the task:
### Input:
Decorator to make sure that the workdir is loaded when calling the
decorated function
### Response:
def workdir_loaded(func):
"""
Decorator to make sure that the workdir is loaded when calling the
decorated function
"""
@wrap... |
def get_all_handleable_leaves(self):
"""
Get list of all handleable devices, return only those that represent
leaf nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode.... | Get list of all handleable devices, return only those that represent
leaf nodes within the filtered device tree. | Below is the the instruction that describes the task:
### Input:
Get list of all handleable devices, return only those that represent
leaf nodes within the filtered device tree.
### Response:
def get_all_handleable_leaves(self):
"""
Get list of all handleable devices, return only those that... |
def optionIsSet(self, name):
"""
Check whether an option with a given name exists and has been set.
:param name: the name of the option to check; can be short or long name.
:return: true if an option matching the given name exists and it has had
it's value set by the user
"""
name ... | Check whether an option with a given name exists and has been set.
:param name: the name of the option to check; can be short or long name.
:return: true if an option matching the given name exists and it has had
it's value set by the user | Below is the the instruction that describes the task:
### Input:
Check whether an option with a given name exists and has been set.
:param name: the name of the option to check; can be short or long name.
:return: true if an option matching the given name exists and it has had
it's value set b... |
def make_movie(q: np.ndarray, step: int, bodies: List[str], plot_colors: Dict[str, str], fname: str):
"""
Make a series of frames of the planetary orbits that can be assembled into a movie.
q is a Nx3B array. t indexes time points. 3B columns are (x, y, z) for the bodies in order.
"""
# Get N and ... | Make a series of frames of the planetary orbits that can be assembled into a movie.
q is a Nx3B array. t indexes time points. 3B columns are (x, y, z) for the bodies in order. | Below is the the instruction that describes the task:
### Input:
Make a series of frames of the planetary orbits that can be assembled into a movie.
q is a Nx3B array. t indexes time points. 3B columns are (x, y, z) for the bodies in order.
### Response:
def make_movie(q: np.ndarray, step: int, bodies: List[... |
def duration(self):
"""Returns the duration in seconds of this audio or video file"""
if self.filetype not in ("video", "audio"):
raise RuntimeError("Only videos and audio have durations")
return self.info.get("length") or self.info.get("duration") | Returns the duration in seconds of this audio or video file | Below is the the instruction that describes the task:
### Input:
Returns the duration in seconds of this audio or video file
### Response:
def duration(self):
"""Returns the duration in seconds of this audio or video file"""
if self.filetype not in ("video", "audio"):
raise RuntimeErro... |
def get_queryset_filters(self, query):
"""
Return the filtered queryset
"""
conditions = Q()
for field_name in self.fields:
conditions |= Q(**{
self._construct_qs_filter(field_name): query
})
return conditions | Return the filtered queryset | Below is the the instruction that describes the task:
### Input:
Return the filtered queryset
### Response:
def get_queryset_filters(self, query):
"""
Return the filtered queryset
"""
conditions = Q()
for field_name in self.fields:
conditions |= Q(**{
... |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Get 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
... | Write the data encoding the Get 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 enumeration defining the K... | Below is the the instruction that describes the task:
### Input:
Write the data encoding the Get 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.
... |
def _load_template_or_config(self, template_path, config_path):
"""Load the config file if it exists, else read the default config.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path: The user's config file pa... | Load the config file if it exists, else read the default config.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path: The user's config file path.
:rtype: :class:`configobj.ConfigObj`
:return: The conf... | Below is the the instruction that describes the task:
### Input:
Load the config file if it exists, else read the default config.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path: The user's config file path.
... |
def load_routing_tables(self, routing_tables, app_id):
"""Allocate space for an load multicast routing tables.
The routing table entries will be removed automatically when the
associated application is stopped.
Parameters
----------
routing_tables : {(x, y): \
... | Allocate space for an load multicast routing tables.
The routing table entries will be removed automatically when the
associated application is stopped.
Parameters
----------
routing_tables : {(x, y): \
[:py:class:`~rig.routing_table.RoutingTableEntry`... | Below is the the instruction that describes the task:
### Input:
Allocate space for an load multicast routing tables.
The routing table entries will be removed automatically when the
associated application is stopped.
Parameters
----------
routing_tables : {(x, y): \
... |
def export_complex_gateway_info(node_params, output_element):
"""
Adds ComplexGateway node attributes to exported XML element
:param node_params: dictionary with given complex gateway parameters,
:param output_element: object representing BPMN XML 'complexGateway' element.
"""
... | Adds ComplexGateway node attributes to exported XML element
:param node_params: dictionary with given complex gateway parameters,
:param output_element: object representing BPMN XML 'complexGateway' element. | Below is the the instruction that describes the task:
### Input:
Adds ComplexGateway node attributes to exported XML element
:param node_params: dictionary with given complex gateway parameters,
:param output_element: object representing BPMN XML 'complexGateway' element.
### Response:
def export_... |
def find_write_contribs() -> None:
"""Look for files, find authors, sort, write file."""
map_file_auth = {} # type: Dict[str, List[str]]
for filename in scantree('cltk'):
filepath = filename.path # type: str
authors_list = get_authors(filepath) # type: List[str]
if authors_list:
... | Look for files, find authors, sort, write file. | Below is the the instruction that describes the task:
### Input:
Look for files, find authors, sort, write file.
### Response:
def find_write_contribs() -> None:
"""Look for files, find authors, sort, write file."""
map_file_auth = {} # type: Dict[str, List[str]]
for filename in scantree('cltk'):
... |
def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
jsn = {
'name': self.name,
'symbol': self.symbol,
'decimals': self.decimals,
'script_hash': self.ScriptHash.To... | Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict: | Below is the the instruction that describes the task:
### Input:
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
### Response:
def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
... |
def insert_paragraph_before(self, text=None, style=None):
"""
Return a newly created paragraph, inserted directly before this
paragraph. If *text* is supplied, the new paragraph contains that
text in a single run. If *style* is provided, that style is assigned
to the new paragrap... | Return a newly created paragraph, inserted directly before this
paragraph. If *text* is supplied, the new paragraph contains that
text in a single run. If *style* is provided, that style is assigned
to the new paragraph. | Below is the the instruction that describes the task:
### Input:
Return a newly created paragraph, inserted directly before this
paragraph. If *text* is supplied, the new paragraph contains that
text in a single run. If *style* is provided, that style is assigned
to the new paragraph.
### Re... |
def _validate_obj_by_schema(self, obj, obj_nex_id, vc):
"""Creates:
errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET,
warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET,
or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET.
... | Creates:
errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET,
warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET,
or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET. | Below is the the instruction that describes the task:
### Input:
Creates:
errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET,
warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET,
or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET... |
def _get_keyid_by_gpg_key(key_material):
"""Get a GPG key fingerprint by GPG key material.
Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded
or binary GPG key material. Can be used, for example, to generate file
names for keys passed via charm options.
:param key_material: A... | Get a GPG key fingerprint by GPG key material.
Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded
or binary GPG key material. Can be used, for example, to generate file
names for keys passed via charm options.
:param key_material: ASCII armor-encoded or binary GPG key material
... | Below is the the instruction that describes the task:
### Input:
Get a GPG key fingerprint by GPG key material.
Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded
or binary GPG key material. Can be used, for example, to generate file
names for keys passed via charm options.
:... |
def add_readlen_dist_plot(self):
""" Generate plot HTML for read length distribution plot. """
pconfig = {
'id': 'skewer_read_length_histogram',
'title': 'Skewer: Read Length Distribution after trimming',
'xDecimals': False,
'ylab': '% of Reads',
... | Generate plot HTML for read length distribution plot. | Below is the the instruction that describes the task:
### Input:
Generate plot HTML for read length distribution plot.
### Response:
def add_readlen_dist_plot(self):
""" Generate plot HTML for read length distribution plot. """
pconfig = {
'id': 'skewer_read_length_histogram',
... |
def iaf_flow(one_hot_assignments,
scale_weights,
scale_bias,
num_codes,
summary=True,
name=None):
"""Performs a single IAF flow using scale and normalization transformations.
Args:
one_hot_assignments: Assignments Tensor with shape [num_samples, ... | Performs a single IAF flow using scale and normalization transformations.
Args:
one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size,
latent_size, num_codes].
scale_weights: Tensor corresponding to lower triangular matrix used to
autoregressively generate scale matrix from ... | Below is the the instruction that describes the task:
### Input:
Performs a single IAF flow using scale and normalization transformations.
Args:
one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size,
latent_size, num_codes].
scale_weights: Tensor corresponding to lower triangu... |
def get_floating_ip_action(self, ip_addr, action_id):
"""
Retrieve the status of a Floating IP action.
"""
if self.api_version == 2:
json = self.request('/floating_ips/' + ip_addr + '/actions/' + action_id)
return json['action']
else:
raise DoE... | Retrieve the status of a Floating IP action. | Below is the the instruction that describes the task:
### Input:
Retrieve the status of a Floating IP action.
### Response:
def get_floating_ip_action(self, ip_addr, action_id):
"""
Retrieve the status of a Floating IP action.
"""
if self.api_version == 2:
json = self.re... |
def process(self, request_adu):
""" Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request.
"""
validate_crc(request_adu)
return super(RTUServer, self).process(r... | Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request. | Below is the the instruction that describes the task:
### Input:
Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request.
### Response:
def process(self, request_adu):
""" Process r... |
def p_ex_expression(tok):
"""ex_expression : OP_EXISTS cmp_expression
| cmp_expression"""
if len(tok) == 3:
tok[0] = UnaryOperationRule(tok[1], tok[2])
else:
tok[0] = tok[1] | ex_expression : OP_EXISTS cmp_expression
| cmp_expression | Below is the the instruction that describes the task:
### Input:
ex_expression : OP_EXISTS cmp_expression
| cmp_expression
### Response:
def p_ex_expression(tok):
"""ex_expression : OP_EXISTS cmp_expression
| cmp_expression"""
if len(tok) == 3:
... |
def _reader(self, name, stream, outbuf):
"""
Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connected to th... | Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connected to the output stream of a subprocess.
:param outbuf: The l... | Below is the the instruction that describes the task:
### Input:
Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connect... |
def complete_help_subcommand(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Completes the subcommand argument of help"""
# Get all tokens through the one being completed
tokens, _ = self.tokens_for_completion(line, begidx, endidx)
if not tokens:
retu... | Completes the subcommand argument of help | Below is the the instruction that describes the task:
### Input:
Completes the subcommand argument of help
### Response:
def complete_help_subcommand(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Completes the subcommand argument of help"""
# Get all tokens through the one... |
def dump(self, filename=None, compressed=True, pretty=True):
'''dump device window and pull to local file.'''
content = self.server.jsonrpc.dumpWindowHierarchy(compressed, None)
if filename:
with open(filename, "wb") as f:
f.write(content.encode("utf-8"))
if p... | dump device window and pull to local file. | Below is the the instruction that describes the task:
### Input:
dump device window and pull to local file.
### Response:
def dump(self, filename=None, compressed=True, pretty=True):
'''dump device window and pull to local file.'''
content = self.server.jsonrpc.dumpWindowHierarchy(compressed, None)... |
def select_eep(self, rorg_func, rorg_type, direction=None, command=None):
''' Set EEP based on FUNC and TYPE '''
# set EEP profile
self.rorg_func = rorg_func
self.rorg_type = rorg_type
self._profile = self.eep.find_profile(self._bit_data, self.rorg, rorg_func, rorg_type, directio... | Set EEP based on FUNC and TYPE | Below is the the instruction that describes the task:
### Input:
Set EEP based on FUNC and TYPE
### Response:
def select_eep(self, rorg_func, rorg_type, direction=None, command=None):
''' Set EEP based on FUNC and TYPE '''
# set EEP profile
self.rorg_func = rorg_func
self.rorg_type ... |
def positions(weights, period, freq=None):
"""
Builds net position values time series, the portfolio percentage invested
in each position.
Parameters
----------
weights: pd.Series
pd.Series containing factor weights, the index contains timestamps at
which the trades are computed... | Builds net position values time series, the portfolio percentage invested
in each position.
Parameters
----------
weights: pd.Series
pd.Series containing factor weights, the index contains timestamps at
which the trades are computed and the values correspond to assets
weights
... | Below is the the instruction that describes the task:
### Input:
Builds net position values time series, the portfolio percentage invested
in each position.
Parameters
----------
weights: pd.Series
pd.Series containing factor weights, the index contains timestamps at
which the trade... |
def get_template(request, query, meta, proxyMode):
"""Return (if needed) the template to use"""
templateContent = None
if not proxyMode:
templateContent = plugIt.getTemplate(query, meta)
if not templateContent:
return (None, gen404(request, baseURI, 'template'))
return (... | Return (if needed) the template to use | Below is the the instruction that describes the task:
### Input:
Return (if needed) the template to use
### Response:
def get_template(request, query, meta, proxyMode):
"""Return (if needed) the template to use"""
templateContent = None
if not proxyMode:
templateContent = plugIt.getTemplate(... |
def read(self, size=None):
"""Reads a byte string from the gzip file at the current offset.
The function will read a byte string up to the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remain... | Reads a byte string from the gzip file at the current offset.
The function will read a byte string up to the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
byte... | Below is the the instruction that describes the task:
### Input:
Reads a byte string from the gzip file at the current offset.
The function will read a byte string up to the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read,... |
def adj_nodes_ali(ali_nodes):
"""Adjust details specific to AliCloud."""
for node in ali_nodes:
node.cloud = "alicloud"
node.cloud_disp = "AliCloud"
node.private_ips = ip_to_str(node.extra['vpc_attributes']['private_ip_address'])
node.public_ips = ip_to_str(node.public_ips)
... | Adjust details specific to AliCloud. | Below is the the instruction that describes the task:
### Input:
Adjust details specific to AliCloud.
### Response:
def adj_nodes_ali(ali_nodes):
"""Adjust details specific to AliCloud."""
for node in ali_nodes:
node.cloud = "alicloud"
node.cloud_disp = "AliCloud"
node.private_ips =... |
def filter_creation_date(groups, start, end):
"""Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start.
"""
results = []
for g in groups:
created = datetime.fromtimestamp(g['creationTime'] / 1000.0)
if created... | Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start. | Below is the the instruction that describes the task:
### Input:
Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start.
### Response:
def filter_creation_date(groups, start, end):
"""Filter log groups by their creation date.
Al... |
def parse(self, limit=None):
"""
Override Source.parse()
Args:
:param limit (int, optional) limit the number of rows processed
Returns:
:return None
"""
if limit is not None:
LOG.info("Only parsing first %d rows", limit)
ensemb... | Override Source.parse()
Args:
:param limit (int, optional) limit the number of rows processed
Returns:
:return None | Below is the the instruction that describes the task:
### Input:
Override Source.parse()
Args:
:param limit (int, optional) limit the number of rows processed
Returns:
:return None
### Response:
def parse(self, limit=None):
"""
Override Source.parse()
... |
def delete(build_folder):
"""Delete build directory and all its contents.
"""
if _meta_.del_build in ["on", "ON"] and os.path.exists(build_folder):
shutil.rmtree(build_folder) | Delete build directory and all its contents. | Below is the the instruction that describes the task:
### Input:
Delete build directory and all its contents.
### Response:
def delete(build_folder):
"""Delete build directory and all its contents.
"""
if _meta_.del_build in ["on", "ON"] and os.path.exists(build_folder):
shutil.rmtree(build_fol... |
def _mkstemp_inner(dir, pre, suf, flags):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, pre + name + suf)
try:
fd = _os.open(file, flags, 0o600)... | Code common to mkstemp, TemporaryFile, and NamedTemporaryFile. | Below is the the instruction that describes the task:
### Input:
Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.
### Response:
def _mkstemp_inner(dir, pre, suf, flags):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
names = _get_candidate_names()
for seq in range(... |
def add_edge(self,
source: Node,
target: Node,
weight: float = 1,
save_to_cache: bool = True) -> None:
"""
Adds an edge to the edge list that will connect the specified nodes.
Arguments:
source (Node): The ... | Adds an edge to the edge list that will connect the specified nodes.
Arguments:
source (Node): The source node of the edge.
target (Node): The target node of the edge.
weight (float): The weight of the created edge.
save_to_cache (bool): Whether the edge sh... | Below is the the instruction that describes the task:
### Input:
Adds an edge to the edge list that will connect the specified nodes.
Arguments:
source (Node): The source node of the edge.
target (Node): The target node of the edge.
weight (float): The weight of the... |
def color_cycle(colors=None):
"""An infinite iterator of the given (or default) colors
"""
if colors:
return itertools.cycle(colors)
try:
return itertools.cycle(p["color"] for p in rcParams["axes.prop_cycle"])
except KeyError: # matplotlib < 1.5
return itertools.cycle(rcPara... | An infinite iterator of the given (or default) colors | Below is the the instruction that describes the task:
### Input:
An infinite iterator of the given (or default) colors
### Response:
def color_cycle(colors=None):
"""An infinite iterator of the given (or default) colors
"""
if colors:
return itertools.cycle(colors)
try:
return itert... |
def send_file(self, key, fp, headers, cb=None, num_cb=10):
"""
Upload a file to a key into a bucket on GS, using GS resumable upload
protocol.
:type key: :class:`boto.s3.key.Key` or subclass
:param key: The Key object to which data is to be uploaded
:typ... | Upload a file to a key into a bucket on GS, using GS resumable upload
protocol.
:type key: :class:`boto.s3.key.Key` or subclass
:param key: The Key object to which data is to be uploaded
:type fp: file-like object
:param fp: The file pointer to upload
... | Below is the the instruction that describes the task:
### Input:
Upload a file to a key into a bucket on GS, using GS resumable upload
protocol.
:type key: :class:`boto.s3.key.Key` or subclass
:param key: The Key object to which data is to be uploaded
:type fp: file... |
def log_part(self):
""" Log what has been captured so far """
self.cap_stdout.seek(self._pos)
text = self.cap_stdout.read()
self._pos = self.cap_stdout.tell()
self.parts.append(text)
self.text = text | Log what has been captured so far | Below is the the instruction that describes the task:
### Input:
Log what has been captured so far
### Response:
def log_part(self):
""" Log what has been captured so far """
self.cap_stdout.seek(self._pos)
text = self.cap_stdout.read()
self._pos = self.cap_stdout.tell()
sel... |
def _costfcn(self, x):
""" Evaluates the objective function, gradient and Hessian for OPF.
"""
f = self._f(x)
df = self._df(x)
d2f = self._d2f(x)
return f, df, d2f | Evaluates the objective function, gradient and Hessian for OPF. | Below is the the instruction that describes the task:
### Input:
Evaluates the objective function, gradient and Hessian for OPF.
### Response:
def _costfcn(self, x):
""" Evaluates the objective function, gradient and Hessian for OPF.
"""
f = self._f(x)
df = self._df(x)
d2f =... |
def write_to_files_rec(instances, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
"""Create IndexedRecordIO files from `TrainingInstance`s."""
writers = []
for output_file in output_files:
writers.append(
mx.recordio.MXIndexedRecordIO(
... | Create IndexedRecordIO files from `TrainingInstance`s. | Below is the the instruction that describes the task:
### Input:
Create IndexedRecordIO files from `TrainingInstance`s.
### Response:
def write_to_files_rec(instances, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
"""Create IndexedRecordIO files from `TrainingInstanc... |
def HasNext(self, page):
"""Checks if there is still a page left to query.
This method is meant to be used with NextPage(). When using DataService,
the paging mechanism is different from other services. For details, see
https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through... | Checks if there is still a page left to query.
This method is meant to be used with NextPage(). When using DataService,
the paging mechanism is different from other services. For details, see
https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results.
Args:
page:... | Below is the the instruction that describes the task:
### Input:
Checks if there is still a page left to query.
This method is meant to be used with NextPage(). When using DataService,
the paging mechanism is different from other services. For details, see
https://developers.google.com/adwords/api/docs... |
def list_device_events(self, **kwargs):
"""List all device logs.
:param int limit: The number of logs to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc)
:param str after: Get logs after/starting at given `device_event_id`
:par... | List all device logs.
:param int limit: The number of logs to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc)
:param str after: Get logs after/starting at given `device_event_id`
:param dict filters: Dictionary of filters to apply.
... | Below is the the instruction that describes the task:
### Input:
List all device logs.
:param int limit: The number of logs to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc)
:param str after: Get logs after/starting at given `device_even... |
def __new_request_id(self):
"""requestId follows form "pre num" where pre is some random ascii prefix EG 6 chars long
and num is an ever increasing number (self.__reqnum). MUST be called within self.__requests lock
"""
while True:
# Since seqnum wraps on 2^64 at most, this sh... | requestId follows form "pre num" where pre is some random ascii prefix EG 6 chars long
and num is an ever increasing number (self.__reqnum). MUST be called within self.__requests lock | Below is the the instruction that describes the task:
### Input:
requestId follows form "pre num" where pre is some random ascii prefix EG 6 chars long
and num is an ever increasing number (self.__reqnum). MUST be called within self.__requests lock
### Response:
def __new_request_id(self):
"""reque... |
def Scale(self, factor):
"""Multiplies the xs by a factor.
factor: what to multiply by
"""
new = self.Copy()
new.xs = [x * factor for x in self.xs]
return new | Multiplies the xs by a factor.
factor: what to multiply by | Below is the the instruction that describes the task:
### Input:
Multiplies the xs by a factor.
factor: what to multiply by
### Response:
def Scale(self, factor):
"""Multiplies the xs by a factor.
factor: what to multiply by
"""
new = self.Copy()
new.xs = [x * fact... |
def str2type(value):
"""
Take a string and convert it to a value of proper type.
.. testsetup::
from proso.coversion import str2type
.. doctest::
>>> print(str2type("[1, 2, 3]")
[1, 2, 3]
"""
if not isinstance(value, str):
return value
... | Take a string and convert it to a value of proper type.
.. testsetup::
from proso.coversion import str2type
.. doctest::
>>> print(str2type("[1, 2, 3]")
[1, 2, 3] | Below is the the instruction that describes the task:
### Input:
Take a string and convert it to a value of proper type.
.. testsetup::
from proso.coversion import str2type
.. doctest::
>>> print(str2type("[1, 2, 3]")
[1, 2, 3]
### Response:
def str2type(val... |
def from_dict(cls, obj_dict):
"""
Load the object from a dictionary (produced with :py:func:`Concise.to_dict`)
Returns:
Concise: Loaded Concise object.
"""
# convert the output into a proper form
obj_dict['output'] = helper.rec_dict_to_numpy_dict(obj_dict["o... | Load the object from a dictionary (produced with :py:func:`Concise.to_dict`)
Returns:
Concise: Loaded Concise object. | Below is the the instruction that describes the task:
### Input:
Load the object from a dictionary (produced with :py:func:`Concise.to_dict`)
Returns:
Concise: Loaded Concise object.
### Response:
def from_dict(cls, obj_dict):
"""
Load the object from a dictionary (produced wit... |
def bounding_box(dset):
'''return the coordinates (in RAI) of the corners of a box enclosing the data in ``dset``'''
o = nl.run(["3dAutobox","-input",dset])
ijk_coords = re.findall(r'[xyz]=(\d+)\.\.(\d+)',o.output)
from_rai = ijk_to_xyz(dset,[float(x[0]) for x in ijk_coords])
to_rai = ijk_to_xyz(dse... | return the coordinates (in RAI) of the corners of a box enclosing the data in ``dset`` | Below is the the instruction that describes the task:
### Input:
return the coordinates (in RAI) of the corners of a box enclosing the data in ``dset``
### Response:
def bounding_box(dset):
'''return the coordinates (in RAI) of the corners of a box enclosing the data in ``dset``'''
o = nl.run(["3dAutobox",... |
def handle_connection_repl(client):
"""
Handles connection.
"""
client.settimeout(None)
# # disable this till we have evidence that it's needed
# client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 0)
# # Note: setting SO_RCVBUF on UDS has no effect, see: http://man7.org/linux/man-pages/m... | Handles connection. | Below is the the instruction that describes the task:
### Input:
Handles connection.
### Response:
def handle_connection_repl(client):
"""
Handles connection.
"""
client.settimeout(None)
# # disable this till we have evidence that it's needed
# client.setsockopt(socket.SOL_SOCKET, socket.SO... |
def remove_read_more_sep(self, raw_content):
"""
Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content.
"""
if self._read_more_exp is None:
return raw_content
sp = self._read_more_exp.split(ra... | Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content. | Below is the the instruction that describes the task:
### Input:
Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content.
### Response:
def remove_read_more_sep(self, raw_content):
"""
Removes the first read_more_sep that occu... |
def where_method(self, cond, other=dtypes.NA):
"""Return elements from `self` or `other` depending on `cond`.
Parameters
----------
cond : DataArray or Dataset with boolean dtype
Locations at which to preserve this objects values.
other : scalar, DataArray or Dataset, optional
Value... | Return elements from `self` or `other` depending on `cond`.
Parameters
----------
cond : DataArray or Dataset with boolean dtype
Locations at which to preserve this objects values.
other : scalar, DataArray or Dataset, optional
Value to use for locations in this object where ``cond`` is... | Below is the the instruction that describes the task:
### Input:
Return elements from `self` or `other` depending on `cond`.
Parameters
----------
cond : DataArray or Dataset with boolean dtype
Locations at which to preserve this objects values.
other : scalar, DataArray or Dataset, optiona... |
def _make_key(relation):
"""Make _ReferenceKeys with lowercase values for the cache so we don't have
to keep track of quoting
"""
return _ReferenceKey(_lower(relation.database),
_lower(relation.schema),
_lower(relation.identifier)) | Make _ReferenceKeys with lowercase values for the cache so we don't have
to keep track of quoting | Below is the the instruction that describes the task:
### Input:
Make _ReferenceKeys with lowercase values for the cache so we don't have
to keep track of quoting
### Response:
def _make_key(relation):
"""Make _ReferenceKeys with lowercase values for the cache so we don't have
to keep track of quoting
... |
def create_default_layout(app, message='',
lexer=None, is_password=False,
reserve_space_for_menu=False,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
display_completions_in_columns... | Generate default layout.
Returns a ``Layout`` instance.
:param message: Text to be used as prompt.
:param lexer: Lexer to be used for the highlighting.
:param is_password: `bool` or `CLIFilter`. When True, display input as '*'.
:param reserve_space_for_menu: When True, make sure that a minimal hei... | Below is the the instruction that describes the task:
### Input:
Generate default layout.
Returns a ``Layout`` instance.
:param message: Text to be used as prompt.
:param lexer: Lexer to be used for the highlighting.
:param is_password: `bool` or `CLIFilter`. When True, display input as '*'.
:... |
def cluster(data, sample, nthreads, force):
"""
Calls vsearch for clustering. cov varies by data type, values were chosen
based on experience, but could be edited by users
"""
## get the dereplicated reads
if "reference" in data.paramsdict["assembly_method"]:
derephandle = os.path.join(... | Calls vsearch for clustering. cov varies by data type, values were chosen
based on experience, but could be edited by users | Below is the the instruction that describes the task:
### Input:
Calls vsearch for clustering. cov varies by data type, values were chosen
based on experience, but could be edited by users
### Response:
def cluster(data, sample, nthreads, force):
"""
Calls vsearch for clustering. cov varies by data typ... |
def _load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
"""
... | Instantiates an already-trained model, based on the experiment
configuration and some optional overrides. | Below is the the instruction that describes the task:
### Input:
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
### Response:
def _load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,... |
def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num):
"""
This is called when the coordinator node determines that a read or
write operation cannot be successful because the number of live
replicas are too low to meet the requested :class:`.Consisten... | This is called when the coordinator node determines that a read or
write operation cannot be successful because the number of live
replicas are too low to meet the requested :class:`.ConsistencyLevel`.
This means that the read or write operation was never forwarded to
any replicas.
... | Below is the the instruction that describes the task:
### Input:
This is called when the coordinator node determines that a read or
write operation cannot be successful because the number of live
replicas are too low to meet the requested :class:`.ConsistencyLevel`.
This means that the read ... |
def value(self, view, template=None):
"""Get a dict with the same keys as the template and values
validated according to the value types.
"""
out = AttrDict()
for key, typ in self.subtemplates.items():
out[key] = typ.value(view[key], self)
return out | Get a dict with the same keys as the template and values
validated according to the value types. | Below is the the instruction that describes the task:
### Input:
Get a dict with the same keys as the template and values
validated according to the value types.
### Response:
def value(self, view, template=None):
"""Get a dict with the same keys as the template and values
validated accordi... |
def add_maxjobs_category(self,categoryName,maxJobsNum):
"""
Add a category to this DAG called categoryName with a maxjobs of maxJobsNum.
@param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories.
"""
self.__maxjobs_categories.append((str(categoryName),str(maxJobsNum))) | Add a category to this DAG called categoryName with a maxjobs of maxJobsNum.
@param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories. | Below is the the instruction that describes the task:
### Input:
Add a category to this DAG called categoryName with a maxjobs of maxJobsNum.
@param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories.
### Response:
def add_maxjobs_category(self,categoryName,maxJobsNum):
"""
Add... |
def dbStore(self, typ, py_value):
"""
Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant>
"""
# convert base types to work in the ... | Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant> | Below is the the instruction that describes the task:
### Input:
Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant>
### Response:
def dbStore(self, typ, py_... |
def happens(intervals: Iterable[float], name: Optional[str] = None) -> Callable:
"""
Decorator used to set up a process that adds a new instance of another process at intervals dictated by the given
sequence (which may be infinite).
Example: the following program runs process named `my_process` 5 times... | Decorator used to set up a process that adds a new instance of another process at intervals dictated by the given
sequence (which may be infinite).
Example: the following program runs process named `my_process` 5 times, each time spaced by 2.0 time units.
```
from itertools import repeat
sim = Si... | Below is the the instruction that describes the task:
### Input:
Decorator used to set up a process that adds a new instance of another process at intervals dictated by the given
sequence (which may be infinite).
Example: the following program runs process named `my_process` 5 times, each time spaced by 2.... |
def cast_to_str(obj):
"""Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence
"""
if isinstance(obj, str):
return obj
if isinstance(obj, Seq):
retu... | Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence | Below is the the instruction that describes the task:
### Input:
Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence
### Response:
def cast_to_str(obj):
"""Return a string... |
def match(prev, pattern, *args, **kw):
"""The pipe greps the data passed from previous generator according to
given regular expression. The data passed to next pipe is MatchObject
, dict or tuple which determined by 'to' in keyword argument.
By default, match pipe yields MatchObject. Use 'to' in keywor... | The pipe greps the data passed from previous generator according to
given regular expression. The data passed to next pipe is MatchObject
, dict or tuple which determined by 'to' in keyword argument.
By default, match pipe yields MatchObject. Use 'to' in keyword argument
to change the type of match res... | Below is the the instruction that describes the task:
### Input:
The pipe greps the data passed from previous generator according to
given regular expression. The data passed to next pipe is MatchObject
, dict or tuple which determined by 'to' in keyword argument.
By default, match pipe yields MatchObj... |
def download(self, path='', name=None, overwrite=False, size=None):
"""
Download the image.
:param path: The image will be downloaded to the folder specified at
path, if path is None (default) then the current working directory
will be used.
:param name: The name... | Download the image.
:param path: The image will be downloaded to the folder specified at
path, if path is None (default) then the current working directory
will be used.
:param name: The name the image will be stored as (not including file
extension). If name is None... | Below is the the instruction that describes the task:
### Input:
Download the image.
:param path: The image will be downloaded to the folder specified at
path, if path is None (default) then the current working directory
will be used.
:param name: The name the image will be ... |
def merge(cls, first, second):
"""
Return an AttributeList that is the result of merging first with second.
"""
merged = AttributeList([], None)
assert (isinstance(first, AttributeList))
assert (isinstance(second, AttributeList))
merged._contents = first._content... | Return an AttributeList that is the result of merging first with second. | Below is the the instruction that describes the task:
### Input:
Return an AttributeList that is the result of merging first with second.
### Response:
def merge(cls, first, second):
"""
Return an AttributeList that is the result of merging first with second.
"""
merged = AttributeL... |
def connect_to_networks(self, si, logger, vm_uuid, vm_network_mappings, default_network_name,
reserved_networks, dv_switch_name, promiscuous_mode):
"""
Connect VM to Network
:param si: VmWare Service Instance - defined connection to vCenter
:param logger:
... | Connect VM to Network
:param si: VmWare Service Instance - defined connection to vCenter
:param logger:
:param vm_uuid: <str> UUID for VM
:param vm_network_mappings: <collection of 'VmNetworkMapping'>
:param default_network_name: <str> Full Network name - likes 'DataCenterName/Ne... | Below is the the instruction that describes the task:
### Input:
Connect VM to Network
:param si: VmWare Service Instance - defined connection to vCenter
:param logger:
:param vm_uuid: <str> UUID for VM
:param vm_network_mappings: <collection of 'VmNetworkMapping'>
:param def... |
def min_temperature(self, unit='kelvin'):
"""Returns a tuple containing the min value in the temperature
series preceeded by its timestamp
:param unit: the unit of measure for the temperature values. May be
among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*'
:... | Returns a tuple containing the min value in the temperature
series preceeded by its timestamp
:param unit: the unit of measure for the temperature values. May be
among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*'
:type unit: str
:returns: a tuple
:rai... | Below is the the instruction that describes the task:
### Input:
Returns a tuple containing the min value in the temperature
series preceeded by its timestamp
:param unit: the unit of measure for the temperature values. May be
among: '*kelvin*' (default), '*celsius*' or '*fahren... |
def standardize(self, mol):
"""Return a standardized version the given molecule.
The standardization process consists of the following stages: RDKit
:py:func:`~rdkit.Chem.rdmolops.RemoveHs`, RDKit :py:func:`~rdkit.Chem.rdmolops.SanitizeMol`,
:class:`~molvs.metal.MetalDisconnector`, :cla... | Return a standardized version the given molecule.
The standardization process consists of the following stages: RDKit
:py:func:`~rdkit.Chem.rdmolops.RemoveHs`, RDKit :py:func:`~rdkit.Chem.rdmolops.SanitizeMol`,
:class:`~molvs.metal.MetalDisconnector`, :class:`~molvs.normalize.Normalizer`,
... | Below is the the instruction that describes the task:
### Input:
Return a standardized version the given molecule.
The standardization process consists of the following stages: RDKit
:py:func:`~rdkit.Chem.rdmolops.RemoveHs`, RDKit :py:func:`~rdkit.Chem.rdmolops.SanitizeMol`,
:class:`~molvs.... |
def warp_vrt(directory, delete_extra=False, use_band_map=False,
overwrite=False, remove_bqa=True, return_profile=False):
""" Read in image geometry, resample subsequent images to same grid.
The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578
to download ... | Read in image geometry, resample subsequent images to same grid.
The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578
to download and unzip them, then run them through this to get identical geometries for analysis.
Files
:param use_band_map:
:param delete_extr... | Below is the the instruction that describes the task:
### Input:
Read in image geometry, resample subsequent images to same grid.
The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578
to download and unzip them, then run them through this to get identical geometries fo... |
def ADD(self, params):
"""
ADD [Rx,] Ry, [Rz, PC]
ADD [Rx,] [SP, PC], #imm10_4
ADD [SP,] SP, #imm9_4
Add Ry and Rz and store the result in Rx
Rx, Ry, and Rz can be any register
If Rx is omitted, then it is assumed to be Ry
"""
# This instruction a... | ADD [Rx,] Ry, [Rz, PC]
ADD [Rx,] [SP, PC], #imm10_4
ADD [SP,] SP, #imm9_4
Add Ry and Rz and store the result in Rx
Rx, Ry, and Rz can be any register
If Rx is omitted, then it is assumed to be Ry | Below is the the instruction that describes the task:
### Input:
ADD [Rx,] Ry, [Rz, PC]
ADD [Rx,] [SP, PC], #imm10_4
ADD [SP,] SP, #imm9_4
Add Ry and Rz and store the result in Rx
Rx, Ry, and Rz can be any register
If Rx is omitted, then it is assumed to be Ry
### Response: ... |
def loadnetcdf(filename, copy=True):
"""Load a dataarray from a NetCDF file.
Args:
filename (str): Filename (*.nc).
copy (bool): If True, dataarray is copied in memory. Default is True.
Returns:
dataarray (xarray.DataArray): Loaded dataarray.
"""
filename = str(Path(filenam... | Load a dataarray from a NetCDF file.
Args:
filename (str): Filename (*.nc).
copy (bool): If True, dataarray is copied in memory. Default is True.
Returns:
dataarray (xarray.DataArray): Loaded dataarray. | Below is the the instruction that describes the task:
### Input:
Load a dataarray from a NetCDF file.
Args:
filename (str): Filename (*.nc).
copy (bool): If True, dataarray is copied in memory. Default is True.
Returns:
dataarray (xarray.DataArray): Loaded dataarray.
### Response: ... |
def get_program_files_dir():
"""
Get the location of the program files directory
Returns
-------
"""
# Now see if we can look in the registry...
val = ''
if SCons.Util.can_read_reg:
try:
# Look for Windows Program Files directory
k=SCons.Util.RegOpenKeyEx... | Get the location of the program files directory
Returns
------- | Below is the the instruction that describes the task:
### Input:
Get the location of the program files directory
Returns
-------
### Response:
def get_program_files_dir():
"""
Get the location of the program files directory
Returns
-------
"""
# Now see if we can look in the regist... |
def enable_host_event_handler(self, host):
"""Enable event handlers for a host
Format of the line that triggers function call::
ENABLE_HOST_EVENT_HANDLER;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None
"""
if not... | Enable event handlers for a host
Format of the line that triggers function call::
ENABLE_HOST_EVENT_HANDLER;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None | Below is the the instruction that describes the task:
### Input:
Enable event handlers for a host
Format of the line that triggers function call::
ENABLE_HOST_EVENT_HANDLER;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None
### Respons... |
def list_active_times_gen(self):
"""Generator for the LIST ACTIVE.TIMES command.
Generates a list of newsgroups including the creation time and who
created them.
See <http://tools.ietf.org/html/rfc3977#section-7.6.4>
Yields:
A tuple containing the name, creation da... | Generator for the LIST ACTIVE.TIMES command.
Generates a list of newsgroups including the creation time and who
created them.
See <http://tools.ietf.org/html/rfc3977#section-7.6.4>
Yields:
A tuple containing the name, creation date as a datetime object and
crea... | Below is the the instruction that describes the task:
### Input:
Generator for the LIST ACTIVE.TIMES command.
Generates a list of newsgroups including the creation time and who
created them.
See <http://tools.ietf.org/html/rfc3977#section-7.6.4>
Yields:
A tuple contain... |
def _subscribe(self, sub_id, channel, callback, **kwargs):
"""Listen to a queue, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received
... | Listen to a queue, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received
:param **kwargs: Further parameters for the transport layer. For ex... | Below is the the instruction that describes the task:
### Input:
Listen to a queue, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received
... |
def edit(self, *args, **kwargs):
"""Edit this multireddit.
Convenience function that utilizes
:meth:`.MultiredditMixin.edit_multireddit` populating the `name`
parameter.
"""
return self.reddit_session.edit_multireddit(name=self.name, *args,
... | Edit this multireddit.
Convenience function that utilizes
:meth:`.MultiredditMixin.edit_multireddit` populating the `name`
parameter. | Below is the the instruction that describes the task:
### Input:
Edit this multireddit.
Convenience function that utilizes
:meth:`.MultiredditMixin.edit_multireddit` populating the `name`
parameter.
### Response:
def edit(self, *args, **kwargs):
"""Edit this multireddit.
C... |
def _build_interpolation(self):
"""Rebuild the _data_lookup_fn using different interpolations within
the shader
"""
interpolation = self._interpolation
self._data_lookup_fn = self._interpolation_fun[interpolation]
self.shared_program.frag['get_data'] = self._data_lookup_f... | Rebuild the _data_lookup_fn using different interpolations within
the shader | Below is the the instruction that describes the task:
### Input:
Rebuild the _data_lookup_fn using different interpolations within
the shader
### Response:
def _build_interpolation(self):
"""Rebuild the _data_lookup_fn using different interpolations within
the shader
"""
int... |
def render_asset(self, name):
"""
Render all includes in asset by names
:type name: str|unicode
:rtype: str|unicode
"""
result = ""
if self.has_asset(name):
asset = self.get_asset(name)
if asset.files:
for f in asset.files:... | Render all includes in asset by names
:type name: str|unicode
:rtype: str|unicode | Below is the the instruction that describes the task:
### Input:
Render all includes in asset by names
:type name: str|unicode
:rtype: str|unicode
### Response:
def render_asset(self, name):
"""
Render all includes in asset by names
:type name: str|unicode
:rtype: ... |
def transform_array(array, force_list=False, buffers=None):
''' Transform a NumPy arrays into serialized format
Converts un-serializable dtypes and returns JSON serializable
format
Args:
array (np.ndarray) : a NumPy array to be transformed
force_list (bool, optional) : whether to only ... | Transform a NumPy arrays into serialized format
Converts un-serializable dtypes and returns JSON serializable
format
Args:
array (np.ndarray) : a NumPy array to be transformed
force_list (bool, optional) : whether to only output to standard lists
This function can encode some d... | Below is the the instruction that describes the task:
### Input:
Transform a NumPy arrays into serialized format
Converts un-serializable dtypes and returns JSON serializable
format
Args:
array (np.ndarray) : a NumPy array to be transformed
force_list (bool, optional) : whether to only... |
def _getAllJobStates(workflowDir):
"""
Generator function that deserializes and yields the job state for every job on the node,
one at a time.
:param str workflowDir: The location of the workflow directory on the node.
:return: dict with keys (jobName, jobPID, jobDir, deferredF... | Generator function that deserializes and yields the job state for every job on the node,
one at a time.
:param str workflowDir: The location of the workflow directory on the node.
:return: dict with keys (jobName, jobPID, jobDir, deferredFunctions)
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Generator function that deserializes and yields the job state for every job on the node,
one at a time.
:param str workflowDir: The location of the workflow directory on the node.
:return: dict with keys (jobName, jobPID, job... |
def get_task_tree(white_list=None):
"""Returns a tree of Task instances
The tree is comprised of dictionaries containing strings for
keys and either dictionaries or Task instances for values.
When WHITE_LIST is given, only the tasks and plugins in this
list will become part of the task tree. The ... | Returns a tree of Task instances
The tree is comprised of dictionaries containing strings for
keys and either dictionaries or Task instances for values.
When WHITE_LIST is given, only the tasks and plugins in this
list will become part of the task tree. The WHITE_LIST may
contain either strings, ... | Below is the the instruction that describes the task:
### Input:
Returns a tree of Task instances
The tree is comprised of dictionaries containing strings for
keys and either dictionaries or Task instances for values.
When WHITE_LIST is given, only the tasks and plugins in this
list will become pa... |
def need_processing(self):
"""A utility to help determine which connections need
processing. Returns a triple of lists containing those connections that
0) need to read from the network, 1) need to write to the network, 2)
waiting for pending timers to expire. The timer list is sorted w... | A utility to help determine which connections need
processing. Returns a triple of lists containing those connections that
0) need to read from the network, 1) need to write to the network, 2)
waiting for pending timers to expire. The timer list is sorted with
the connection next expiri... | Below is the the instruction that describes the task:
### Input:
A utility to help determine which connections need
processing. Returns a triple of lists containing those connections that
0) need to read from the network, 1) need to write to the network, 2)
waiting for pending timers to expi... |
def create_conf_file (self, data, directory=None):
"""Create local config file from given data (list of lines) in
the directory (or current directory if not given)."""
data.insert(0, "# this file is automatically created by setup.py")
data.insert(0, "# -*- coding: iso-8859-1 -*-")
... | Create local config file from given data (list of lines) in
the directory (or current directory if not given). | Below is the the instruction that describes the task:
### Input:
Create local config file from given data (list of lines) in
the directory (or current directory if not given).
### Response:
def create_conf_file (self, data, directory=None):
"""Create local config file from given data (list of lines... |
def get_similar_entries(context, number=5,
template='zinnia/tags/entries_similar.html'):
"""
Return similar entries.
"""
entry = context.get('entry')
if not entry:
return {'template': template, 'entries': []}
vectors = EntryPublishedVectorBuilder()
entries = ... | Return similar entries. | Below is the the instruction that describes the task:
### Input:
Return similar entries.
### Response:
def get_similar_entries(context, number=5,
template='zinnia/tags/entries_similar.html'):
"""
Return similar entries.
"""
entry = context.get('entry')
if not entry:
... |
def python_file_with_version(self):
"""Return Python filename with ``__version__`` marker, if configured.
Enable this by adding a ``python-file-with-version`` option::
[zest.releaser]
python-file-with-version = reinout/maurits.py
Return None when nothing has been confi... | Return Python filename with ``__version__`` marker, if configured.
Enable this by adding a ``python-file-with-version`` option::
[zest.releaser]
python-file-with-version = reinout/maurits.py
Return None when nothing has been configured. | Below is the the instruction that describes the task:
### Input:
Return Python filename with ``__version__`` marker, if configured.
Enable this by adding a ``python-file-with-version`` option::
[zest.releaser]
python-file-with-version = reinout/maurits.py
Return None when ... |
def clear(self):
"""Clear current state."""
self.exposures = []
self.exposure_labels = []
self.exposure_combo_boxes = []
self.exposure_edit_buttons = []
self.mode = CHOOSE_MODE
self.layer_purpose = None
self.layer_mode = None
self.special_case_ind... | Clear current state. | Below is the the instruction that describes the task:
### Input:
Clear current state.
### Response:
def clear(self):
"""Clear current state."""
self.exposures = []
self.exposure_labels = []
self.exposure_combo_boxes = []
self.exposure_edit_buttons = []
self.mode = CH... |
def update(self, value):
"""Update the mean and variance estimates.
Args:
value: Batch or single value tensor.
Returns:
Summary tensor.
"""
with tf.name_scope(self._name + '/update'):
if value.shape.ndims == self._mean.shape.ndims:
# Add a batch dimension if necessary.
... | Update the mean and variance estimates.
Args:
value: Batch or single value tensor.
Returns:
Summary tensor. | Below is the the instruction that describes the task:
### Input:
Update the mean and variance estimates.
Args:
value: Batch or single value tensor.
Returns:
Summary tensor.
### Response:
def update(self, value):
"""Update the mean and variance estimates.
Args:
value: Batch or s... |
def _get_colors(segmentation):
"""Get a list of colors which is as long as the segmentation.
Parameters
----------
segmentation : list of lists
Returns
-------
list
A list of colors.
"""
symbol_count = len(segmentation)
num_colors = symbol_count
# See http://stacko... | Get a list of colors which is as long as the segmentation.
Parameters
----------
segmentation : list of lists
Returns
-------
list
A list of colors. | Below is the the instruction that describes the task:
### Input:
Get a list of colors which is as long as the segmentation.
Parameters
----------
segmentation : list of lists
Returns
-------
list
A list of colors.
### Response:
def _get_colors(segmentation):
"""Get a list of c... |
def _create_states(self, states_num):
"""
Args:
states_num (int): Number of States
Returns:
list: An initialized list
"""
states = []
for i in range(0, states_num):
states.append(i)
return states | Args:
states_num (int): Number of States
Returns:
list: An initialized list | Below is the the instruction that describes the task:
### Input:
Args:
states_num (int): Number of States
Returns:
list: An initialized list
### Response:
def _create_states(self, states_num):
"""
Args:
states_num (int): Number of States
Returns:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.