code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def accumulate(self, buf):
'''add in some more bytes'''
accum = self.crc
for b in buf:
tmp = b ^ (accum & 0xff)
tmp = (tmp ^ (tmp<<4)) & 0xFF
accum = (accum>>8) ^ (tmp<<8) ^ (tmp<<3) ^ (tmp>>4)
self.crc = accum | add in some more bytes | Below is the the instruction that describes the task:
### Input:
add in some more bytes
### Response:
def accumulate(self, buf):
'''add in some more bytes'''
accum = self.crc
for b in buf:
tmp = b ^ (accum & 0xff)
tmp = (tmp ^ (tmp<<4)) & 0xFF
accum = (ac... |
def get_instance(self, payload):
"""
Build an instance of SyncMapItemInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance
:rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item... | Build an instance of SyncMapItemInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance
:rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of SyncMapItemInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance
:rtype: twilio.rest.preview.sync.service.sync_m... |
def _finalize_arguments(self, args):
"""Derive standard args from our weird ones
:type args: Namespace with command line arguments
"""
gps = args.gps
search = args.search
# ensure we have enough data for filter settling
max_plot = max(args.plot)
search = m... | Derive standard args from our weird ones
:type args: Namespace with command line arguments | Below is the the instruction that describes the task:
### Input:
Derive standard args from our weird ones
:type args: Namespace with command line arguments
### Response:
def _finalize_arguments(self, args):
"""Derive standard args from our weird ones
:type args: Namespace with command line ... |
def find_prime_polynomials(generator=2, c_exp=8, fast_primes=False, single=False):
'''Compute the list of prime polynomials for the given generator and galois field characteristic exponent.'''
# fast_primes will output less results but will be significantly faster.
# single will output the first prime polyn... | Compute the list of prime polynomials for the given generator and galois field characteristic exponent. | Below is the the instruction that describes the task:
### Input:
Compute the list of prime polynomials for the given generator and galois field characteristic exponent.
### Response:
def find_prime_polynomials(generator=2, c_exp=8, fast_primes=False, single=False):
'''Compute the list of prime polynomials for ... |
def get_outputs(self, input_value):
"""
Generate a set of output values for a given input.
"""
output_value = self.convert_to_xmlrpc(input_value)
output = {}
for name in self.output_names:
output[name] = output_value
return output | Generate a set of output values for a given input. | Below is the the instruction that describes the task:
### Input:
Generate a set of output values for a given input.
### Response:
def get_outputs(self, input_value):
"""
Generate a set of output values for a given input.
"""
output_value = self.convert_to_xmlrpc(input_value)
... |
def _run_vagrant_command(self, args):
'''
Run a vagrant command and return its stdout.
args: A sequence of arguments to a vagrant command line.
e.g. ['up', 'my_vm_name', '--no-provision'] or
['up', None, '--no-provision'] for a non-Multi-VM environment.
'''
# Make... | Run a vagrant command and return its stdout.
args: A sequence of arguments to a vagrant command line.
e.g. ['up', 'my_vm_name', '--no-provision'] or
['up', None, '--no-provision'] for a non-Multi-VM environment. | Below is the the instruction that describes the task:
### Input:
Run a vagrant command and return its stdout.
args: A sequence of arguments to a vagrant command line.
e.g. ['up', 'my_vm_name', '--no-provision'] or
['up', None, '--no-provision'] for a non-Multi-VM environment.
### Response:
... |
def to_coverage(ctx):
"""
Produce a .coverage file from a smother file
"""
sm = Smother.load(ctx.obj['report'])
sm.coverage = coverage.coverage()
sm.write_coverage() | Produce a .coverage file from a smother file | Below is the the instruction that describes the task:
### Input:
Produce a .coverage file from a smother file
### Response:
def to_coverage(ctx):
"""
Produce a .coverage file from a smother file
"""
sm = Smother.load(ctx.obj['report'])
sm.coverage = coverage.coverage()
sm.write_coverage() |
def not_right(self, num):
"""
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:]
"""
if num == None:
return FlatList([_get_list(self)[:-1:]])
if num <= 0:
return FlatList.EMPTY
return FlatList(_get_list(self)[:-num:]) | WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] | Below is the the instruction that describes the task:
### Input:
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:]
### Response:
def not_right(self, num):
"""
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:]
"""
if num == None:
... |
def _call(self, name, soapheaders):
"""return the Call to the named remote web service method.
closure used to prevent multiple values for name and soapheaders
parameters
"""
def call_closure(*args, **kwargs):
"""Call the named remote web service method."""... | return the Call to the named remote web service method.
closure used to prevent multiple values for name and soapheaders
parameters | Below is the the instruction that describes the task:
### Input:
return the Call to the named remote web service method.
closure used to prevent multiple values for name and soapheaders
parameters
### Response:
def _call(self, name, soapheaders):
"""return the Call to the named remote web ... |
def Arrow(startPoint, endPoint, s=None, c="r", alpha=1, res=12):
"""
Build a 3D arrow from `startPoint` to `endPoint` of section size `s`,
expressed as the fraction of the window size.
.. note:: If ``s=None`` the arrow is scaled proportionally to its length,
otherwise it represents th... | Build a 3D arrow from `startPoint` to `endPoint` of section size `s`,
expressed as the fraction of the window size.
.. note:: If ``s=None`` the arrow is scaled proportionally to its length,
otherwise it represents the fraction of the window size.
|OrientedArrow| | Below is the the instruction that describes the task:
### Input:
Build a 3D arrow from `startPoint` to `endPoint` of section size `s`,
expressed as the fraction of the window size.
.. note:: If ``s=None`` the arrow is scaled proportionally to its length,
otherwise it represents the fracti... |
def send_content(
self,
http_code,
content,
mime_type="text/html",
http_message=None,
content_length=-1,
):
# type: (int, str, str, str, int) -> None
"""
Utility method to send the given content as an answer.
You can still use get_wfile... | Utility method to send the given content as an answer.
You can still use get_wfile or write afterwards, if you forced the
content length.
If content_length is negative (default), it will be computed as the
length of the content;
if it is positive, the given value will be used;
... | Below is the the instruction that describes the task:
### Input:
Utility method to send the given content as an answer.
You can still use get_wfile or write afterwards, if you forced the
content length.
If content_length is negative (default), it will be computed as the
length of th... |
def QA_util_get_real_date(date, trade_list=trade_date_sse, towards=-1):
"""
获取真实的交易日期,其中,第三个参数towards是表示向前/向后推
towards=1 日期向后迭代
towards=-1 日期向前迭代
@ yutiansut
"""
date = str(date)[0:10]
if towards == 1:
while date not in trade_list:
date = str(
datetim... | 获取真实的交易日期,其中,第三个参数towards是表示向前/向后推
towards=1 日期向后迭代
towards=-1 日期向前迭代
@ yutiansut | Below is the the instruction that describes the task:
### Input:
获取真实的交易日期,其中,第三个参数towards是表示向前/向后推
towards=1 日期向后迭代
towards=-1 日期向前迭代
@ yutiansut
### Response:
def QA_util_get_real_date(date, trade_list=trade_date_sse, towards=-1):
"""
获取真实的交易日期,其中,第三个参数towards是表示向前/向后推
towards=1 日期向后迭代
... |
def geom_check_axis(g, atwts, ax,
nmax=_DEF.SYMM_MATCH_NMAX,
tol=_DEF.SYMM_MATCH_TOL):
""" [Get max proper order and reflection for an axis]
.. todo:: Complete geom_parse_axis docstring
"""
# Imports
import numpy as np
# Store the max found rotation order of the geometry.
... | [Get max proper order and reflection for an axis]
.. todo:: Complete geom_parse_axis docstring | Below is the the instruction that describes the task:
### Input:
[Get max proper order and reflection for an axis]
.. todo:: Complete geom_parse_axis docstring
### Response:
def geom_check_axis(g, atwts, ax,
nmax=_DEF.SYMM_MATCH_NMAX,
tol=_DEF.SYMM_MATCH_TOL):
""" [Get max proper order and... |
def _get_fwl_port_speed(self, server_id, is_virt=True):
"""Determines the appropriate speed for a firewall.
:param int server_id: The ID of server the firewall is for
:param bool is_virt: True if the server_id is for a virtual server
:returns: a integer representing the Mbps speed of a ... | Determines the appropriate speed for a firewall.
:param int server_id: The ID of server the firewall is for
:param bool is_virt: True if the server_id is for a virtual server
:returns: a integer representing the Mbps speed of a firewall | Below is the the instruction that describes the task:
### Input:
Determines the appropriate speed for a firewall.
:param int server_id: The ID of server the firewall is for
:param bool is_virt: True if the server_id is for a virtual server
:returns: a integer representing the Mbps speed of ... |
def parse_domains(self, domain, params):
"""
Parse a single Route53Domains domain
"""
domain_id = self.get_non_aws_id(domain['DomainName'])
domain['name'] = domain.pop('DomainName')
#TODO: Get Dnssec info when available
#api_client = params['api_client']
#... | Parse a single Route53Domains domain | Below is the the instruction that describes the task:
### Input:
Parse a single Route53Domains domain
### Response:
def parse_domains(self, domain, params):
"""
Parse a single Route53Domains domain
"""
domain_id = self.get_non_aws_id(domain['DomainName'])
domain['name'] = do... |
def _get_field_type(self, key, value):
"""
Helper to create field object based on value type
"""
if isinstance(value, bool):
return BooleanField(name=key)
elif isinstance(value, int):
return IntegerField(name=key)
elif isinstance(value, float):
... | Helper to create field object based on value type | Below is the the instruction that describes the task:
### Input:
Helper to create field object based on value type
### Response:
def _get_field_type(self, key, value):
"""
Helper to create field object based on value type
"""
if isinstance(value, bool):
return BooleanFie... |
def get_members(self, **query_params):
'''
Get all members attached to this organisation. Returns a list of
Member objects
Returns:
list(Member): The members attached to this organisation
'''
members = self.get_members_json(self.base_uri,
... | Get all members attached to this organisation. Returns a list of
Member objects
Returns:
list(Member): The members attached to this organisation | Below is the the instruction that describes the task:
### Input:
Get all members attached to this organisation. Returns a list of
Member objects
Returns:
list(Member): The members attached to this organisation
### Response:
def get_members(self, **query_params):
'''
Get... |
def nlp(self, inputString, sourceTime=None, version=None):
"""Utilizes parse() after making judgements about what datetime
information belongs together.
It makes logical groupings based on proximity and returns a parsed
datetime for each matched grouping of datetime text, along with
... | Utilizes parse() after making judgements about what datetime
information belongs together.
It makes logical groupings based on proximity and returns a parsed
datetime for each matched grouping of datetime text, along with
location info within the given inputString.
@type input... | Below is the the instruction that describes the task:
### Input:
Utilizes parse() after making judgements about what datetime
information belongs together.
It makes logical groupings based on proximity and returns a parsed
datetime for each matched grouping of datetime text, along with
... |
def example_delta_alter_configs(a, args):
"""
The AlterConfigs Kafka API requires all configuration to be passed,
any left out configuration properties will revert to their default settings.
This example shows how to just modify the supplied configuration entries
by first reading the configuration ... | The AlterConfigs Kafka API requires all configuration to be passed,
any left out configuration properties will revert to their default settings.
This example shows how to just modify the supplied configuration entries
by first reading the configuration from the broker, updating the supplied
configurati... | Below is the the instruction that describes the task:
### Input:
The AlterConfigs Kafka API requires all configuration to be passed,
any left out configuration properties will revert to their default settings.
This example shows how to just modify the supplied configuration entries
by first reading the... |
def _set_edgeport(self, v, load=False):
"""
Setter method for edgeport, mapped from YANG variable /interface/port_channel/spanning_tree/edgeport (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edgeport is considered as a private
method. Backends looking t... | Setter method for edgeport, mapped from YANG variable /interface/port_channel/spanning_tree/edgeport (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edgeport is considered as a private
method. Backends looking to populate this variable should
do so via callin... | Below is the the instruction that describes the task:
### Input:
Setter method for edgeport, mapped from YANG variable /interface/port_channel/spanning_tree/edgeport (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edgeport is considered as a private
method. B... |
def get_time(self) -> float:
"""
Get the current position in the music in seconds
"""
if self.paused:
return self.pause_time
return mixer.music.get_pos() / 1000.0 | Get the current position in the music in seconds | Below is the the instruction that describes the task:
### Input:
Get the current position in the music in seconds
### Response:
def get_time(self) -> float:
"""
Get the current position in the music in seconds
"""
if self.paused:
return self.pause_time
return mi... |
def update(self, *, name=None, show_headers=None, show_totals=None, style=None):
"""
Updates this table
:param str name: the name of the table
:param bool show_headers: whether or not to show the headers
:param bool show_totals: whether or not to show the totals
:param st... | Updates this table
:param str name: the name of the table
:param bool show_headers: whether or not to show the headers
:param bool show_totals: whether or not to show the totals
:param str style: the style of the table
:return: Success or Failure | Below is the the instruction that describes the task:
### Input:
Updates this table
:param str name: the name of the table
:param bool show_headers: whether or not to show the headers
:param bool show_totals: whether or not to show the totals
:param str style: the style of the table
... |
def neighbor_add(self, address, remote_as,
remote_port=DEFAULT_BGP_PORT,
enable_ipv4=DEFAULT_CAP_MBGP_IPV4,
enable_ipv6=DEFAULT_CAP_MBGP_IPV6,
enable_vpnv4=DEFAULT_CAP_MBGP_VPNV4,
enable_vpnv6=DEFAULT_CAP_MBGP_VPNV6... | This method registers a new neighbor. The BGP speaker tries to
establish a bgp session with the peer (accepts a connection
from the peer and also tries to connect to it).
``address`` specifies the IP address of the peer. It must be
the string representation of an IP address. Only IPv4 i... | Below is the the instruction that describes the task:
### Input:
This method registers a new neighbor. The BGP speaker tries to
establish a bgp session with the peer (accepts a connection
from the peer and also tries to connect to it).
``address`` specifies the IP address of the peer. It mu... |
def get_ids(a):
"""
make copy of sequences with short identifier
"""
a_id = '%s.id.fa' % (a.rsplit('.', 1)[0])
a_id_lookup = '%s.id.lookup' % (a.rsplit('.', 1)[0])
if check(a_id) is True:
return a_id, a_id_lookup
a_id_f = open(a_id, 'w')
a_id_lookup_f = open(a_id_lookup, 'w')
... | make copy of sequences with short identifier | Below is the the instruction that describes the task:
### Input:
make copy of sequences with short identifier
### Response:
def get_ids(a):
"""
make copy of sequences with short identifier
"""
a_id = '%s.id.fa' % (a.rsplit('.', 1)[0])
a_id_lookup = '%s.id.lookup' % (a.rsplit('.', 1)[0])
if ... |
def SetRange(self, range_offset, range_size):
"""Sets the data range (offset and size).
The data range is used to map a range of data within one file
(e.g. a single partition within a full disk image) as a file-like object.
Args:
range_offset (int): start offset of the data range.
range_si... | Sets the data range (offset and size).
The data range is used to map a range of data within one file
(e.g. a single partition within a full disk image) as a file-like object.
Args:
range_offset (int): start offset of the data range.
range_size (int): size of the data range.
Raises:
... | Below is the the instruction that describes the task:
### Input:
Sets the data range (offset and size).
The data range is used to map a range of data within one file
(e.g. a single partition within a full disk image) as a file-like object.
Args:
range_offset (int): start offset of the data range... |
def checkbox_check(self, force_check=False):
"""
Wrapper to check a checkbox
"""
if not self.get_attribute('checked'):
self.click(force_click=force_check) | Wrapper to check a checkbox | Below is the the instruction that describes the task:
### Input:
Wrapper to check a checkbox
### Response:
def checkbox_check(self, force_check=False):
"""
Wrapper to check a checkbox
"""
if not self.get_attribute('checked'):
self.click(force_click=force_check) |
def release_port(self, port):
"""release port"""
if port in self.__closed:
self.__closed.remove(port)
self.__ports.add(port) | release port | Below is the the instruction that describes the task:
### Input:
release port
### Response:
def release_port(self, port):
"""release port"""
if port in self.__closed:
self.__closed.remove(port)
self.__ports.add(port) |
def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED):
"""Returns the scope at which a message was enabled/disabled."""
if self.config.confidence and confidence.name not in self.config.confidence:
return MSG_STATE_CONFIDENCE
try:
if line in self.file_s... | Returns the scope at which a message was enabled/disabled. | Below is the the instruction that describes the task:
### Input:
Returns the scope at which a message was enabled/disabled.
### Response:
def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED):
"""Returns the scope at which a message was enabled/disabled."""
if self.config.confid... |
def load_retaildata():
"""Monthly retail trade data from census.gov."""
# full = 'https://www.census.gov/retail/mrts/www/mrtssales92-present.xls'
# indiv = 'https://www.census.gov/retail/marts/www/timeseries.html'
db = {
"Auto, other Motor Vehicle": "https://www.census.gov/retail/marts/ww... | Monthly retail trade data from census.gov. | Below is the the instruction that describes the task:
### Input:
Monthly retail trade data from census.gov.
### Response:
def load_retaildata():
"""Monthly retail trade data from census.gov."""
# full = 'https://www.census.gov/retail/mrts/www/mrtssales92-present.xls'
# indiv = 'https://www.census.go... |
def _report_container_spec_metrics(self, pod_list, instance_tags):
"""Reports pod requests & limits by looking at pod specs."""
for pod in pod_list['items']:
pod_name = pod.get('metadata', {}).get('name')
pod_phase = pod.get('status', {}).get('phase')
if self._should_... | Reports pod requests & limits by looking at pod specs. | Below is the the instruction that describes the task:
### Input:
Reports pod requests & limits by looking at pod specs.
### Response:
def _report_container_spec_metrics(self, pod_list, instance_tags):
"""Reports pod requests & limits by looking at pod specs."""
for pod in pod_list['items']:
... |
def fix2real(uval, conv):
"""
Convert a 32 bit unsigned int register into the value it represents in its Fixed arithmetic form.
@param uval: the numeric unsigned value in simulink representation
@param conv: conv structure with conversion specs as generated by I{get_conv}
@return: the real number re... | Convert a 32 bit unsigned int register into the value it represents in its Fixed arithmetic form.
@param uval: the numeric unsigned value in simulink representation
@param conv: conv structure with conversion specs as generated by I{get_conv}
@return: the real number represented by the Fixed arithmetic defi... | Below is the the instruction that describes the task:
### Input:
Convert a 32 bit unsigned int register into the value it represents in its Fixed arithmetic form.
@param uval: the numeric unsigned value in simulink representation
@param conv: conv structure with conversion specs as generated by I{get_conv}
... |
def drawDisplay( self, painter, option, rect, text ):
"""
Handles the display drawing for this delegate.
:param painter | <QPainter>
option | <QStyleOption>
rect | <QRect>
text | <str>
"""
painter.se... | Handles the display drawing for this delegate.
:param painter | <QPainter>
option | <QStyleOption>
rect | <QRect>
text | <str> | Below is the the instruction that describes the task:
### Input:
Handles the display drawing for this delegate.
:param painter | <QPainter>
option | <QStyleOption>
rect | <QRect>
text | <str>
### Response:
def drawDisplay( sel... |
def composition_prediction(self, composition, to_this_composition=True):
"""
Returns charged balanced substitutions from a starting or ending
composition.
Args:
composition:
starting or ending composition
to_this_composition:
If tr... | Returns charged balanced substitutions from a starting or ending
composition.
Args:
composition:
starting or ending composition
to_this_composition:
If true, substitutions with this as a final composition
will be found. If false, s... | Below is the the instruction that describes the task:
### Input:
Returns charged balanced substitutions from a starting or ending
composition.
Args:
composition:
starting or ending composition
to_this_composition:
If true, substitutions with t... |
def add_patch(self, *args, **kwargs):
"""
Shortcut for add_route with method PATCH
"""
return self.add_route(hdrs.METH_PATCH, *args, **kwargs) | Shortcut for add_route with method PATCH | Below is the the instruction that describes the task:
### Input:
Shortcut for add_route with method PATCH
### Response:
def add_patch(self, *args, **kwargs):
"""
Shortcut for add_route with method PATCH
"""
return self.add_route(hdrs.METH_PATCH, *args, **kwargs) |
def streaming_to_client():
"""Puts the client logger into streaming mode, which sends
unbuffered input through to the socket one character at a time.
We also disable propagation so the root logger does not
receive many one-byte emissions. This context handler
was originally created for streaming Com... | Puts the client logger into streaming mode, which sends
unbuffered input through to the socket one character at a time.
We also disable propagation so the root logger does not
receive many one-byte emissions. This context handler
was originally created for streaming Compose up's
terminal output thro... | Below is the the instruction that describes the task:
### Input:
Puts the client logger into streaming mode, which sends
unbuffered input through to the socket one character at a time.
We also disable propagation so the root logger does not
receive many one-byte emissions. This context handler
was o... |
def set_default_prediction_value(self, values):
"""
Set the default prediction value(s).
The values given here form the base prediction value that the values
at activated leaves are added to. If values is a scalar, then
the output of the tree must also be 1 dimensional; otherwi... | Set the default prediction value(s).
The values given here form the base prediction value that the values
at activated leaves are added to. If values is a scalar, then
the output of the tree must also be 1 dimensional; otherwise, values
must be a list with length matching the dimension... | Below is the the instruction that describes the task:
### Input:
Set the default prediction value(s).
The values given here form the base prediction value that the values
at activated leaves are added to. If values is a scalar, then
the output of the tree must also be 1 dimensional; otherw... |
def format(self):
"""Return the format attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FORMAT) | Return the format attribute of the BFD file being processed. | Below is the the instruction that describes the task:
### Input:
Return the format attribute of the BFD file being processed.
### Response:
def format(self):
"""Return the format attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
... |
def process_get(self):
"""
Analyse the GET request
:return:
* :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting
for authentication renewal
* :attr:`USER_AUTHENTICATED` if the user is authenticated and is no... | Analyse the GET request
:return:
* :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting
for authentication renewal
* :attr:`USER_AUTHENTICATED` if the user is authenticated and is not requesting
for authenticati... | Below is the the instruction that describes the task:
### Input:
Analyse the GET request
:return:
* :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting
for authentication renewal
* :attr:`USER_AUTHENTICATED` if the user is a... |
def add_status_message(self, message, severity="info"):
"""Set a portal message
"""
self.context.plone_utils.addPortalMessage(message, severity) | Set a portal message | Below is the the instruction that describes the task:
### Input:
Set a portal message
### Response:
def add_status_message(self, message, severity="info"):
"""Set a portal message
"""
self.context.plone_utils.addPortalMessage(message, severity) |
def get_stp_mst_detail_output_cist_cist_reg_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cis... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_stp_mst_detail_output_cist_cist_reg_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
... |
def ip_unnumbered(self, **kwargs):
"""Configure an unnumbered interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 etc).
delete... | Configure an unnumbered interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 etc).
delete (bool): True is the IP address is added and F... | Below is the the instruction that describes the task:
### Input:
Configure an unnumbered interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 e... |
def plot_site(fignum, SiteRec, data, key):
"""
deprecated (used in ipmag)
"""
print('Site mean data: ')
print(' dec inc n_lines n_planes kappa R alpha_95 comp coord')
print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'],
... | deprecated (used in ipmag) | Below is the the instruction that describes the task:
### Input:
deprecated (used in ipmag)
### Response:
def plot_site(fignum, SiteRec, data, key):
"""
deprecated (used in ipmag)
"""
print('Site mean data: ')
print(' dec inc n_lines n_planes kappa R alpha_95 comp coord')
print(SiteRec... |
def start(io_loop=None, check_time=2):
"""Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated.
"""
io_loop = io_loop or asyncio.get_event_loop()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) >... | Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated. | Below is the the instruction that describes the task:
### Input:
Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated.
### Response:
def start(io_loop=None, check_time=2):
"""Begins watching source files for changes.
.. versionchanged:: 4.1
... |
def get_spec(self):
"""
Return the Core ML spec
"""
if _mac_ver() >= (10, 14):
return self.vggish_model.get_spec()
else:
vggish_model_file = VGGish()
coreml_model_path = vggish_model_file.get_model_path(format='coreml')
return MLMod... | Return the Core ML spec | Below is the the instruction that describes the task:
### Input:
Return the Core ML spec
### Response:
def get_spec(self):
"""
Return the Core ML spec
"""
if _mac_ver() >= (10, 14):
return self.vggish_model.get_spec()
else:
vggish_model_file = VGGish(... |
def _split_string_to_tokens(text):
"""Splits text to a list of string tokens."""
if not text:
return []
ret = []
token_start = 0
# Classify each character in the input string
is_alnum = [c in _ALPHANUMERIC_CHAR_SET for c in text]
for pos in xrange(1, len(text)):
if is_alnum[pos] != is_alnum[pos - ... | Splits text to a list of string tokens. | Below is the the instruction that describes the task:
### Input:
Splits text to a list of string tokens.
### Response:
def _split_string_to_tokens(text):
"""Splits text to a list of string tokens."""
if not text:
return []
ret = []
token_start = 0
# Classify each character in the input string
is_al... |
def get_creation_date(
self,
bucket: str,
key: str,
) -> datetime.datetime:
"""
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation... | Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is being retrieved.
:return: the creation date | Below is the the instruction that describes the task:
### Input:
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is being retrieved.
:return: the creation date
### Re... |
def get_rendered_objects(self):
"""Render objects"""
objects = self.objects
if isinstance(objects, str):
objects = getattr(self.object, objects).all()
return [
self.get_rendered_object(obj)
for obj in objects
] | Render objects | Below is the the instruction that describes the task:
### Input:
Render objects
### Response:
def get_rendered_objects(self):
"""Render objects"""
objects = self.objects
if isinstance(objects, str):
objects = getattr(self.object, objects).all()
return [
sel... |
def mutex(self, mutex, **kwargs):
"""Add Mutex data to Batch object.
Args:
mutex (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
... | Add Mutex data to Batch object.
Args:
mutex (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date time... | Below is the the instruction that describes the task:
### Input:
Add Mutex data to Batch object.
Args:
mutex (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicato... |
def dlogpdf_dlink_dvar(self, inv_link_f, y, Y_metadata=None):
"""
Derivative of the dlogpdf_dlink w.r.t variance parameter (t_noise)
.. math::
\\frac{d}{d\\sigma^{2}}(\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{df}) = \\frac{-2\\sigma v(v + 1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i})... | Derivative of the dlogpdf_dlink w.r.t variance parameter (t_noise)
.. math::
\\frac{d}{d\\sigma^{2}}(\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{df}) = \\frac{-2\\sigma v(v + 1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i}))^2 + \\sigma^2 v)^2}
:param inv_link_f: latent variables inv_link_f
... | Below is the the instruction that describes the task:
### Input:
Derivative of the dlogpdf_dlink w.r.t variance parameter (t_noise)
.. math::
\\frac{d}{d\\sigma^{2}}(\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{df}) = \\frac{-2\\sigma v(v + 1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i}))^2 + \\sigma... |
def get_port_profile_for_intf_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
output = ET.SubElement(get_port_profile_for_intf,... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_port_profile_for_intf_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_int... |
def get_cs_archs(self):
''' capstone disassembler '''
cs_archs = {
'x16': (CS_ARCH_X86, CS_MODE_16),
'x86': (CS_ARCH_X86, CS_MODE_32),
'x64': (CS_ARCH_X86, CS_MODE_64),
'arm': (CS_ARCH_ARM, CS_MODE_ARM),
'arm_t':... | capstone disassembler | Below is the the instruction that describes the task:
### Input:
capstone disassembler
### Response:
def get_cs_archs(self):
''' capstone disassembler '''
cs_archs = {
'x16': (CS_ARCH_X86, CS_MODE_16),
'x86': (CS_ARCH_X86, CS_MODE_32),
'x64': ... |
def _all_tables_present(self, txn):
"""
Checks if any tables are present in the current assets database.
Parameters
----------
txn : Transaction
The open transaction to check in.
Returns
-------
has_tables : bool
True if any table... | Checks if any tables are present in the current assets database.
Parameters
----------
txn : Transaction
The open transaction to check in.
Returns
-------
has_tables : bool
True if any tables are present, otherwise False. | Below is the the instruction that describes the task:
### Input:
Checks if any tables are present in the current assets database.
Parameters
----------
txn : Transaction
The open transaction to check in.
Returns
-------
has_tables : bool
True... |
def get_string(self):
"""A string representation of the junction
:return: string represnetation
:rtype: string
"""
return self.left.chr+':'+str(self.left.end)+'-'+self.right.chr+':'+str(self.right.start) | A string representation of the junction
:return: string represnetation
:rtype: string | Below is the the instruction that describes the task:
### Input:
A string representation of the junction
:return: string represnetation
:rtype: string
### Response:
def get_string(self):
"""A string representation of the junction
:return: string represnetation
:rtype: string
"""
retur... |
def display(surface):
"""Displays a pygame.Surface in the window.
in pygame the window is represented through a surface, on which you can draw
as on any other pygame.Surface. A refernce to to the screen can be optained
via the :py:func:`pygame.display.get_surface` function. To display the
conte... | Displays a pygame.Surface in the window.
in pygame the window is represented through a surface, on which you can draw
as on any other pygame.Surface. A refernce to to the screen can be optained
via the :py:func:`pygame.display.get_surface` function. To display the
contents of the screen surface in ... | Below is the the instruction that describes the task:
### Input:
Displays a pygame.Surface in the window.
in pygame the window is represented through a surface, on which you can draw
as on any other pygame.Surface. A refernce to to the screen can be optained
via the :py:func:`pygame.display.get_sur... |
def get_seqstr(config, metadata):
"""
Extract and reformat imaging sequence(s) and variant(s) into pretty
strings.
Parameters
----------
config : :obj:`dict`
A dictionary with relevant information regarding sequences, sequence
variants, phase encoding directions, and task names.... | Extract and reformat imaging sequence(s) and variant(s) into pretty
strings.
Parameters
----------
config : :obj:`dict`
A dictionary with relevant information regarding sequences, sequence
variants, phase encoding directions, and task names.
metadata : :obj:`dict`
The metada... | Below is the the instruction that describes the task:
### Input:
Extract and reformat imaging sequence(s) and variant(s) into pretty
strings.
Parameters
----------
config : :obj:`dict`
A dictionary with relevant information regarding sequences, sequence
variants, phase encoding dire... |
def _default_read_frame(self, *, frame=None, mpkit=None):
"""Read frames with default engine.
- Extract frames and each layer of packets.
- Make Info object out of frame properties.
- Append Info.
- Write plist & append Info.
"""
from pcapkit.toolkit.default imp... | Read frames with default engine.
- Extract frames and each layer of packets.
- Make Info object out of frame properties.
- Append Info.
- Write plist & append Info. | Below is the the instruction that describes the task:
### Input:
Read frames with default engine.
- Extract frames and each layer of packets.
- Make Info object out of frame properties.
- Append Info.
- Write plist & append Info.
### Response:
def _default_read_frame(self, *, frame... |
async def profile(self, ctx, tag):
'''Example command for use inside a discord bot cog.'''
if not self.check_valid_tag(tag):
return await ctx.send('Invalid tag!')
profile = await self.cr.get_profile(tag)
em = discord.Embed(color=0x00FFFFF)
em.set_author(name=str(pro... | Example command for use inside a discord bot cog. | Below is the the instruction that describes the task:
### Input:
Example command for use inside a discord bot cog.
### Response:
async def profile(self, ctx, tag):
'''Example command for use inside a discord bot cog.'''
if not self.check_valid_tag(tag):
return await ctx.send('Invalid ta... |
def get_group_details(group):
""" Get group details. """
result = []
for datastore in _get_datastores():
value = datastore.get_group_details(group)
value['datastore'] = datastore.config['DESCRIPTION']
result.append(value)
return result | Get group details. | Below is the the instruction that describes the task:
### Input:
Get group details.
### Response:
def get_group_details(group):
""" Get group details. """
result = []
for datastore in _get_datastores():
value = datastore.get_group_details(group)
value['datastore'] = datastore.config['DE... |
def remove(self, resource):
"""Removes a resource from the context"""
if isinstance(resource, Resource):
self._resources.remove(resource) | Removes a resource from the context | Below is the the instruction that describes the task:
### Input:
Removes a resource from the context
### Response:
def remove(self, resource):
"""Removes a resource from the context"""
if isinstance(resource, Resource):
self._resources.remove(resource) |
def _factln(num):
# type: (int) -> float
"""
Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise.
"""
if num < 20:
log_factorial = log(factorial(num))
else:
log_factorial = num * log(num) - num + log(num * (1 + 4 * num * (
1... | Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise. | Below is the the instruction that describes the task:
### Input:
Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise.
### Response:
def _factln(num):
# type: (int) -> float
"""
Computes logfactorial regularly for tractable numbers, uses Ramanujans approximatio... |
def keyword(
name: str,
ns: Optional[str] = None,
kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN,
) -> Keyword:
"""Create a new keyword."""
h = hash((name, ns))
return kw_cache.swap(__get_or_create, h, name, ns)[h] | Create a new keyword. | Below is the the instruction that describes the task:
### Input:
Create a new keyword.
### Response:
def keyword(
name: str,
ns: Optional[str] = None,
kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN,
) -> Keyword:
"""Create a new keyword."""
h = hash((name, ns))
return kw_cache.swap(__... |
def insert_all(db, schema_name, table_name, columns, items):
"""
Insert all item in given items list into the specified table, schema_name.table_name.
"""
table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name
columns_list = ', '.join(columns)
values_list = ', '.join(['... | Insert all item in given items list into the specified table, schema_name.table_name. | Below is the the instruction that describes the task:
### Input:
Insert all item in given items list into the specified table, schema_name.table_name.
### Response:
def insert_all(db, schema_name, table_name, columns, items):
"""
Insert all item in given items list into the specified table, schema_name.tab... |
def train(cls, new_data, old=None):
"""
Train a continuous scale
Parameters
----------
new_data : array_like
New values
old : array_like
Old range. Most likely a tuple of length 2.
Returns
-------
out : tuple
L... | Train a continuous scale
Parameters
----------
new_data : array_like
New values
old : array_like
Old range. Most likely a tuple of length 2.
Returns
-------
out : tuple
Limits(range) of the scale | Below is the the instruction that describes the task:
### Input:
Train a continuous scale
Parameters
----------
new_data : array_like
New values
old : array_like
Old range. Most likely a tuple of length 2.
Returns
-------
out : tuple
... |
def resample(self, seed=None):
"""Resample the dataset.
Args:
seed (int, optional): Seed for resampling. By default no seed is
used.
"""
if seed is not None:
gen = torch.manual_seed(seed)
else:
gen = torch.default_generator
... | Resample the dataset.
Args:
seed (int, optional): Seed for resampling. By default no seed is
used. | Below is the the instruction that describes the task:
### Input:
Resample the dataset.
Args:
seed (int, optional): Seed for resampling. By default no seed is
used.
### Response:
def resample(self, seed=None):
"""Resample the dataset.
Args:
seed (int, op... |
def get_activities_by_query(self, activity_query=None):
"""Gets a list of Activities matching the given activity query.
arg: activityQuery (osid.learning.ActivityQuery): the
activity query
return: (osid.learning.ActivityList) - the returned ActivityList
raise: NullAr... | Gets a list of Activities matching the given activity query.
arg: activityQuery (osid.learning.ActivityQuery): the
activity query
return: (osid.learning.ActivityList) - the returned ActivityList
raise: NullArgument - activityQuery is null
raise: OperationFailed - un... | Below is the the instruction that describes the task:
### Input:
Gets a list of Activities matching the given activity query.
arg: activityQuery (osid.learning.ActivityQuery): the
activity query
return: (osid.learning.ActivityList) - the returned ActivityList
raise: Null... |
def read_config(config):
"""Read config file and return uncomment line
"""
for line in config.splitlines():
line = line.lstrip()
if line and not line.startswith("#"):
return line
return "" | Read config file and return uncomment line | Below is the the instruction that describes the task:
### Input:
Read config file and return uncomment line
### Response:
def read_config(config):
"""Read config file and return uncomment line
"""
for line in config.splitlines():
line = line.lstrip()
if line and not line.startswith("#")... |
def get_item_lookup_session(self):
"""Gets the ``OsidSession`` associated with the item lookup service.
return: (osid.assessment.ItemLookupSession) - an
``ItemLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_item_loo... | Gets the ``OsidSession`` associated with the item lookup service.
return: (osid.assessment.ItemLookupSession) - an
``ItemLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_item_lookup()`` is ``false``
*compliance: opti... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the item lookup service.
return: (osid.assessment.ItemLookupSession) - an
``ItemLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemente... |
def Region2_cp0(Tr, Pr):
"""Ideal properties for Region 2
Parameters
----------
Tr : float
Reduced temperature, [-]
Pr : float
Reduced pressure, [-]
Returns
-------
prop : array
Array with ideal Gibbs energy partial derivatives:
* g: Ideal Specific ... | Ideal properties for Region 2
Parameters
----------
Tr : float
Reduced temperature, [-]
Pr : float
Reduced pressure, [-]
Returns
-------
prop : array
Array with ideal Gibbs energy partial derivatives:
* g: Ideal Specific Gibbs energy [kJ/kg]
... | Below is the the instruction that describes the task:
### Input:
Ideal properties for Region 2
Parameters
----------
Tr : float
Reduced temperature, [-]
Pr : float
Reduced pressure, [-]
Returns
-------
prop : array
Array with ideal Gibbs energy partial derivativ... |
def scheduleServices(self, jobGraph):
"""
Schedule the services of a job asynchronously.
When the job's services are running the jobGraph for the job will
be returned by toil.leader.ServiceManager.getJobGraphsWhoseServicesAreRunning.
:param toil.jobGraph.JobGraph jobGraph: wrapp... | Schedule the services of a job asynchronously.
When the job's services are running the jobGraph for the job will
be returned by toil.leader.ServiceManager.getJobGraphsWhoseServicesAreRunning.
:param toil.jobGraph.JobGraph jobGraph: wrapper of job with services to schedule. | Below is the the instruction that describes the task:
### Input:
Schedule the services of a job asynchronously.
When the job's services are running the jobGraph for the job will
be returned by toil.leader.ServiceManager.getJobGraphsWhoseServicesAreRunning.
:param toil.jobGraph.JobGraph jobG... |
def get_search_score(query, choice, ignore_case=True, apply_regex=True,
template='{}'):
"""Returns a tuple with the enriched text (if a template is provided) and
a score for the match.
Parameters
----------
query : str
String with letters to search in choice (in order o... | Returns a tuple with the enriched text (if a template is provided) and
a score for the match.
Parameters
----------
query : str
String with letters to search in choice (in order of appearance).
choice : str
Sentence/words in which to search for the 'query' letters.
ignore_case :... | Below is the the instruction that describes the task:
### Input:
Returns a tuple with the enriched text (if a template is provided) and
a score for the match.
Parameters
----------
query : str
String with letters to search in choice (in order of appearance).
choice : str
Sentenc... |
def scale_edges(self, multiplier):
'''Multiply all edges in this ``Tree`` by ``multiplier``'''
if not isinstance(multiplier,int) and not isinstance(multiplier,float):
raise TypeError("multiplier must be an int or float")
for node in self.traverse_preorder():
if node.edge_... | Multiply all edges in this ``Tree`` by ``multiplier`` | Below is the the instruction that describes the task:
### Input:
Multiply all edges in this ``Tree`` by ``multiplier``
### Response:
def scale_edges(self, multiplier):
'''Multiply all edges in this ``Tree`` by ``multiplier``'''
if not isinstance(multiplier,int) and not isinstance(multiplier,float):... |
def purity(rho: Density) -> bk.BKTensor:
"""
Calculate the purity of a mixed quantum state.
Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state,
and a lower bound of 1/D (where D is the Hilbert space dimension) for a
competently mixed state.
Two closely related measures are ... | Calculate the purity of a mixed quantum state.
Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state,
and a lower bound of 1/D (where D is the Hilbert space dimension) for a
competently mixed state.
Two closely related measures are the linear entropy, 1- purity, and the
participat... | Below is the the instruction that describes the task:
### Input:
Calculate the purity of a mixed quantum state.
Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state,
and a lower bound of 1/D (where D is the Hilbert space dimension) for a
competently mixed state.
Two closely relat... |
def set_attributes(self, obj, **attributes):
""" Set attributes.
:param obj: requested object.
:param attributes: dictionary of {attribute: value} to set
"""
attributes_url = '{}/{}/attributes'.format(self.session_url, obj.ref)
attributes_list = [{u'name': str(name), u'... | Set attributes.
:param obj: requested object.
:param attributes: dictionary of {attribute: value} to set | Below is the the instruction that describes the task:
### Input:
Set attributes.
:param obj: requested object.
:param attributes: dictionary of {attribute: value} to set
### Response:
def set_attributes(self, obj, **attributes):
""" Set attributes.
:param obj: requested object.
... |
def from_dict(cls, data):
"""
:type data: dict[str, str]
:rtype: satosa.internal.AuthenticationInformation
:param data: A dict representation of an AuthenticationInformation object
:return: An AuthenticationInformation object
"""
return cls(
auth_class... | :type data: dict[str, str]
:rtype: satosa.internal.AuthenticationInformation
:param data: A dict representation of an AuthenticationInformation object
:return: An AuthenticationInformation object | Below is the the instruction that describes the task:
### Input:
:type data: dict[str, str]
:rtype: satosa.internal.AuthenticationInformation
:param data: A dict representation of an AuthenticationInformation object
:return: An AuthenticationInformation object
### Response:
def from_dict(cl... |
def save(self):
""" Saves current patches list in the series file """
with open(self.series_file, "wb") as f:
for patchline in self.patchlines:
f.write(_encode_str(str(patchline)))
f.write(b"\n") | Saves current patches list in the series file | Below is the the instruction that describes the task:
### Input:
Saves current patches list in the series file
### Response:
def save(self):
""" Saves current patches list in the series file """
with open(self.series_file, "wb") as f:
for patchline in self.patchlines:
f.... |
def delete_entitlement(owner, repo, identifier):
"""Delete an entitlement from a repository."""
client = get_entitlements_api()
with catch_raise_api_exception():
_, _, headers = client.entitlements_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratel... | Delete an entitlement from a repository. | Below is the the instruction that describes the task:
### Input:
Delete an entitlement from a repository.
### Response:
def delete_entitlement(owner, repo, identifier):
"""Delete an entitlement from a repository."""
client = get_entitlements_api()
with catch_raise_api_exception():
_, _, header... |
def _conv_general_permutations(self, dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C')
charpairs = (lhs_char, rhs_char, out_char)
for i, (a,... | Utility for convolution dimension permutations relative to Conv HLO. | Below is the the instruction that describes the task:
### Input:
Utility for convolution dimension permutations relative to Conv HLO.
### Response:
def _conv_general_permutations(self, dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spe... |
def get_namespaced_custom_object_status(self, group, version, namespace, plural, name, **kwargs): # noqa: E501
"""get_namespaced_custom_object_status # noqa: E501
read status of the specified namespace scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default.... | get_namespaced_custom_object_status # noqa: E501
read status of the specified namespace scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_namespaced_custom_ob... | Below is the the instruction that describes the task:
### Input:
get_namespaced_custom_object_status # noqa: E501
read status of the specified namespace scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please ... |
def load(self, file, **options):
""" Loads the field *value* for each :class:`Field` *nested* in the
`Container` from an ``.ini`` *file*.
:param str file: name and location of the ``.ini`` *file*.
:keyword str section: section in the ``.ini`` *file* to lookup the
value for e... | Loads the field *value* for each :class:`Field` *nested* in the
`Container` from an ``.ini`` *file*.
:param str file: name and location of the ``.ini`` *file*.
:keyword str section: section in the ``.ini`` *file* to lookup the
value for each :class:`Field` in the `Container`.
... | Below is the the instruction that describes the task:
### Input:
Loads the field *value* for each :class:`Field` *nested* in the
`Container` from an ``.ini`` *file*.
:param str file: name and location of the ``.ini`` *file*.
:keyword str section: section in the ``.ini`` *file* to lookup the... |
def parse(self, configManager, config):
"""
Parse configuration options out of an .ini configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options popul... | Parse configuration options out of an .ini configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options populated thus far.
Outputs: A dictionary of new configu... | Below is the the instruction that describes the task:
### Input:
Parse configuration options out of an .ini configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration opti... |
def _get_loftee(data):
"""Retrieve loss of function plugin parameters for LOFTEE.
https://github.com/konradjk/loftee
"""
ancestral_file = tz.get_in(("genome_resources", "variation", "ancestral"), data)
if not ancestral_file or not os.path.exists(ancestral_file):
ancestral_file = "false"
... | Retrieve loss of function plugin parameters for LOFTEE.
https://github.com/konradjk/loftee | Below is the the instruction that describes the task:
### Input:
Retrieve loss of function plugin parameters for LOFTEE.
https://github.com/konradjk/loftee
### Response:
def _get_loftee(data):
"""Retrieve loss of function plugin parameters for LOFTEE.
https://github.com/konradjk/loftee
"""
ance... |
def _is_not_pickle_safe_gl_class(obj_class):
"""
Check if class is a Turi create model.
The function does it by checking the method resolution order (MRO) of the
class and verifies that _Model is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
---... | Check if class is a Turi create model.
The function does it by checking the method resolution order (MRO) of the
class and verifies that _Model is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the class is a GLC Model. | Below is the the instruction that describes the task:
### Input:
Check if class is a Turi create model.
The function does it by checking the method resolution order (MRO) of the
class and verifies that _Model is the base class.
Parameters
----------
obj_class : Class to be checked.
Ret... |
def joint_distances(self):
'''Get the current joint separations for the skeleton.
Returns
-------
distances : list of float
A list expressing the distance between the two joint anchor points,
for each joint in the skeleton. These quantities describe how
... | Get the current joint separations for the skeleton.
Returns
-------
distances : list of float
A list expressing the distance between the two joint anchor points,
for each joint in the skeleton. These quantities describe how
"exploded" the bodies in the skelet... | Below is the the instruction that describes the task:
### Input:
Get the current joint separations for the skeleton.
Returns
-------
distances : list of float
A list expressing the distance between the two joint anchor points,
for each joint in the skeleton. These qu... |
def find_uuid(es_url, index):
""" Find the unique identifier field for a given index """
uid_field = None
# Get the first item to detect the data source and raw/enriched type
res = requests.get('%s/%s/_search?size=1' % (es_url, index))
first_item = res.json()['hits']['hits'][0]['_source']
fiel... | Find the unique identifier field for a given index | Below is the the instruction that describes the task:
### Input:
Find the unique identifier field for a given index
### Response:
def find_uuid(es_url, index):
""" Find the unique identifier field for a given index """
uid_field = None
# Get the first item to detect the data source and raw/enriched t... |
def p_class_constant_declaration(p):
'''class_constant_declaration : class_constant_declaration COMMA STRING EQUALS static_scalar
| CONST STRING EQUALS static_scalar'''
if len(p) == 6:
p[0] = p[1] + [ast.ClassConstant(p[3], p[5], lineno=p.lineno(2))]
else:
p... | class_constant_declaration : class_constant_declaration COMMA STRING EQUALS static_scalar
| CONST STRING EQUALS static_scalar | Below is the the instruction that describes the task:
### Input:
class_constant_declaration : class_constant_declaration COMMA STRING EQUALS static_scalar
| CONST STRING EQUALS static_scalar
### Response:
def p_class_constant_declaration(p):
'''class_constant_declaration : cla... |
def _add_cat_dict(self,
cat_dict_class,
key_in_self,
check_for_dupes=True,
compare_to_existing=True,
**kwargs):
"""Add a `CatDict` to this `Entry`.
CatDict only added if initialization succeeds... | Add a `CatDict` to this `Entry`.
CatDict only added if initialization succeeds and it
doesn't already exist within the Entry. | Below is the the instruction that describes the task:
### Input:
Add a `CatDict` to this `Entry`.
CatDict only added if initialization succeeds and it
doesn't already exist within the Entry.
### Response:
def _add_cat_dict(self,
cat_dict_class,
key_in_se... |
def _is_empty_observation_data(
feature_ndims, observation_index_points, observations):
"""Returns `True` if given observation data is empty.
Emptiness means either
1. Both `observation_index_points` and `observations` are `None`, or
2. the "number of observations" shape is 0. The shape of
`observa... | Returns `True` if given observation data is empty.
Emptiness means either
1. Both `observation_index_points` and `observations` are `None`, or
2. the "number of observations" shape is 0. The shape of
`observation_index_points` is `[..., N, f1, ..., fF]`, where `N` is the
number of observations and th... | Below is the the instruction that describes the task:
### Input:
Returns `True` if given observation data is empty.
Emptiness means either
1. Both `observation_index_points` and `observations` are `None`, or
2. the "number of observations" shape is 0. The shape of
`observation_index_points` is `[...,... |
def parse_minionqc_report(self, s_name, f):
'''
Parses minionqc's 'summary.yaml' report file for results.
Uses only the "All reads" stats. Ignores "Q>=x" part.
'''
try:
# Parsing as OrderedDict is slightly messier with YAML
# http://stackoverflow.com/a/210... | Parses minionqc's 'summary.yaml' report file for results.
Uses only the "All reads" stats. Ignores "Q>=x" part. | Below is the the instruction that describes the task:
### Input:
Parses minionqc's 'summary.yaml' report file for results.
Uses only the "All reads" stats. Ignores "Q>=x" part.
### Response:
def parse_minionqc_report(self, s_name, f):
'''
Parses minionqc's 'summary.yaml' report file for res... |
def isSane(self):
"""
This method checks the to see if a trust root represents a
reasonable (sane) set of URLs. 'http://*.com/', for example
is not a reasonable pattern, as it cannot meaningfully specify
the site claiming it. This function attempts to find many
related ... | This method checks the to see if a trust root represents a
reasonable (sane) set of URLs. 'http://*.com/', for example
is not a reasonable pattern, as it cannot meaningfully specify
the site claiming it. This function attempts to find many
related examples, but it can only work via heu... | Below is the the instruction that describes the task:
### Input:
This method checks the to see if a trust root represents a
reasonable (sane) set of URLs. 'http://*.com/', for example
is not a reasonable pattern, as it cannot meaningfully specify
the site claiming it. This function attempt... |
def invoice(request, invoice_id, access_code=None):
''' Displays an invoice.
This view is not authenticated, but it will only allow access to either:
the user the invoice belongs to; staff; or a request made with the correct
access code.
Arguments:
invoice_id (castable to int): The invoic... | Displays an invoice.
This view is not authenticated, but it will only allow access to either:
the user the invoice belongs to; staff; or a request made with the correct
access code.
Arguments:
invoice_id (castable to int): The invoice_id for the invoice you want
to view.
... | Below is the the instruction that describes the task:
### Input:
Displays an invoice.
This view is not authenticated, but it will only allow access to either:
the user the invoice belongs to; staff; or a request made with the correct
access code.
Arguments:
invoice_id (castable to int): T... |
def get_cache_item(self):
'''Gets the cached item. Raises AttributeError if it hasn't been set.'''
if settings.DEBUG:
raise AttributeError('Caching disabled in DEBUG mode')
return getattr(self.template, self.options['template_cache_key']) | Gets the cached item. Raises AttributeError if it hasn't been set. | Below is the the instruction that describes the task:
### Input:
Gets the cached item. Raises AttributeError if it hasn't been set.
### Response:
def get_cache_item(self):
'''Gets the cached item. Raises AttributeError if it hasn't been set.'''
if settings.DEBUG:
raise AttributeError('C... |
def removeUnreferencedElements(doc, keepDefs):
"""
Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>.
Also vacuums the defs of any non-referenced renderable elements.
Returns the number of unreferenced elements removed from the document.
"""
global _num... | Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>.
Also vacuums the defs of any non-referenced renderable elements.
Returns the number of unreferenced elements removed from the document. | Below is the the instruction that describes the task:
### Input:
Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>.
Also vacuums the defs of any non-referenced renderable elements.
Returns the number of unreferenced elements removed from the document.
### Response:... |
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.
Raises:
QiskitError: if the input and output d... | The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.
Raises:
QiskitError: if the input and output dimensions of the
Qu... | Below is the the instruction that describes the task:
### Input:
The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.
Raises:
... |
def get_filterbanks(nfilt=20,nfft=512,samplerate=16000,lowfreq=0,highfreq=None):
"""Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond
to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1)
:param nfilt: the number of filters in the filterbank, defa... | Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond
to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1)
:param nfilt: the number of filters in the filterbank, default 20.
:param nfft: the FFT size. Default is 512.
:param samplerate: the sample... | Below is the the instruction that describes the task:
### Input:
Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond
to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1)
:param nfilt: the number of filters in the filterbank, default 20.
:param ... |
def _can_connect(host, port=22): # type: (str, int) -> bool
"""Checks if the connection to provided ``host`` and ``port`` is possible or not.
Args:
host (str): Hostname for the host to check connection.
port (int): Port name of the host to check connection on.
"""
try:
... | Checks if the connection to provided ``host`` and ``port`` is possible or not.
Args:
host (str): Hostname for the host to check connection.
port (int): Port name of the host to check connection on. | Below is the the instruction that describes the task:
### Input:
Checks if the connection to provided ``host`` and ``port`` is possible or not.
Args:
host (str): Hostname for the host to check connection.
port (int): Port name of the host to check connection on.
### Response:
def _can_... |
def auto_constraints(self, component=None):
"""
Use CLDF reference properties to implicitely create foreign key constraints.
:param component: A Table object or `None`.
"""
if not component:
for table in self.tables:
self.auto_constraints(table)
... | Use CLDF reference properties to implicitely create foreign key constraints.
:param component: A Table object or `None`. | Below is the the instruction that describes the task:
### Input:
Use CLDF reference properties to implicitely create foreign key constraints.
:param component: A Table object or `None`.
### Response:
def auto_constraints(self, component=None):
"""
Use CLDF reference properties to implicite... |
def value_compare(left, right, ordering=1):
"""
SORT VALUES, NULL IS THE LEAST VALUE
:param left: LHS
:param right: RHS
:param ordering: (-1, 0, 1) TO AFFECT SORT ORDER
:return: The return value is negative if x < y, zero if x == y and strictly positive if x > y.
"""
try:
ltype ... | SORT VALUES, NULL IS THE LEAST VALUE
:param left: LHS
:param right: RHS
:param ordering: (-1, 0, 1) TO AFFECT SORT ORDER
:return: The return value is negative if x < y, zero if x == y and strictly positive if x > y. | Below is the the instruction that describes the task:
### Input:
SORT VALUES, NULL IS THE LEAST VALUE
:param left: LHS
:param right: RHS
:param ordering: (-1, 0, 1) TO AFFECT SORT ORDER
:return: The return value is negative if x < y, zero if x == y and strictly positive if x > y.
### Response:
def ... |
def _get_audio_channels(self, audio_abs_path):
"""
Parameters
----------
audio_abs_path : str
Returns
-------
channel_num : int
"""
channel_num = int(
subprocess.check_output(
("""sox --i {} | grep "{}" | awk -F " : " '... | Parameters
----------
audio_abs_path : str
Returns
-------
channel_num : int | Below is the the instruction that describes the task:
### Input:
Parameters
----------
audio_abs_path : str
Returns
-------
channel_num : int
### Response:
def _get_audio_channels(self, audio_abs_path):
"""
Parameters
----------
audio_abs_pat... |
def ctx() -> moderngl.Context:
"""ModernGL context"""
win = window()
if not win.ctx:
raise RuntimeError("Attempting to get context before creation")
return win.ctx | ModernGL context | Below is the the instruction that describes the task:
### Input:
ModernGL context
### Response:
def ctx() -> moderngl.Context:
"""ModernGL context"""
win = window()
if not win.ctx:
raise RuntimeError("Attempting to get context before creation")
return win.ctx |
def get_qpimage(self, idx):
"""Return background-corrected QPImage of data at index `idx`"""
if self._bgdata:
# The user has explicitly chosen different background data
# using `get_qpimage_raw`.
qpi = super(SeriesHdf5Qpimage, self).get_qpimage(idx)
else:
... | Return background-corrected QPImage of data at index `idx` | Below is the the instruction that describes the task:
### Input:
Return background-corrected QPImage of data at index `idx`
### Response:
def get_qpimage(self, idx):
"""Return background-corrected QPImage of data at index `idx`"""
if self._bgdata:
# The user has explicitly chosen differ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.