code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_dtext(value):
""" dtext = <printable ascii except \ [ ]> / obs-dtext
obs-dtext = obs-NO-WS-CTL / quoted-pair
We allow anything except the excluded characters, but if we find any
ASCII other than the RFC defined printable ASCII an NonPrintableDefect is
added to the token's defects list. ... | dtext = <printable ascii except \ [ ]> / obs-dtext
obs-dtext = obs-NO-WS-CTL / quoted-pair
We allow anything except the excluded characters, but if we find any
ASCII other than the RFC defined printable ASCII an NonPrintableDefect is
added to the token's defects list. Quoted pairs are converted to... | Below is the the instruction that describes the task:
### Input:
dtext = <printable ascii except \ [ ]> / obs-dtext
obs-dtext = obs-NO-WS-CTL / quoted-pair
We allow anything except the excluded characters, but if we find any
ASCII other than the RFC defined printable ASCII an NonPrintableDefect is
... |
def _get_rsi(cls, df, n_days):
""" Calculate the RSI (Relative Strength Index) within N days
calculated based on the formula at:
https://en.wikipedia.org/wiki/Relative_strength_index
:param df: data
:param n_days: N days
:return: None
"""
n_day... | Calculate the RSI (Relative Strength Index) within N days
calculated based on the formula at:
https://en.wikipedia.org/wiki/Relative_strength_index
:param df: data
:param n_days: N days
:return: None | Below is the the instruction that describes the task:
### Input:
Calculate the RSI (Relative Strength Index) within N days
calculated based on the formula at:
https://en.wikipedia.org/wiki/Relative_strength_index
:param df: data
:param n_days: N days
:return: None
##... |
def street_address(self, address):
"""
Geocode one and only address, get a single Address object back
>>> client.street_address("100 Main St, Anywhere, USA")
>>> client.street_address({"street": "100 Main St, anywhere USA"})
:param address: string or dictionary with street addr... | Geocode one and only address, get a single Address object back
>>> client.street_address("100 Main St, Anywhere, USA")
>>> client.street_address({"street": "100 Main St, anywhere USA"})
:param address: string or dictionary with street address information
:return: an Address object or N... | Below is the the instruction that describes the task:
### Input:
Geocode one and only address, get a single Address object back
>>> client.street_address("100 Main St, Anywhere, USA")
>>> client.street_address({"street": "100 Main St, anywhere USA"})
:param address: string or dictionary wi... |
def write_bus_data(self, file):
""" Writes bus data to an Excel spreadsheet.
"""
bus_sheet = self.book.add_sheet("Buses")
for i, bus in enumerate(self.case.buses):
for j, attr in enumerate(BUS_ATTRS):
bus_sheet.write(i, j, getattr(bus, attr)) | Writes bus data to an Excel spreadsheet. | Below is the the instruction that describes the task:
### Input:
Writes bus data to an Excel spreadsheet.
### Response:
def write_bus_data(self, file):
""" Writes bus data to an Excel spreadsheet.
"""
bus_sheet = self.book.add_sheet("Buses")
for i, bus in enumerate(self.case.buses)... |
def _get_rule_definition(self, rule):
"""Generates the source code for a rule."""
fmt = """def {rule_fxn_name}(self, text):
{indent}\"\"\"{rule_source}\"\"\"
{indent}self._attempting(text)
{indent}return {rule_definition}(text){transform}
"""
fmt = self._clea... | Generates the source code for a rule. | Below is the the instruction that describes the task:
### Input:
Generates the source code for a rule.
### Response:
def _get_rule_definition(self, rule):
"""Generates the source code for a rule."""
fmt = """def {rule_fxn_name}(self, text):
{indent}\"\"\"{rule_source}\"\"\"
{inden... |
def _load_vertex_buffers(self):
"""Load each vertex buffer into each material"""
fd = gzip.open(cache_name(self.file_name), 'rb')
for buff in self.meta.vertex_buffers:
mat = self.wavefront.materials.get(buff['material'])
if not mat:
mat = Material(name=b... | Load each vertex buffer into each material | Below is the the instruction that describes the task:
### Input:
Load each vertex buffer into each material
### Response:
def _load_vertex_buffers(self):
"""Load each vertex buffer into each material"""
fd = gzip.open(cache_name(self.file_name), 'rb')
for buff in self.meta.vertex_buffers:
... |
def execute(self, duration):
"""
Executes the measurement, recording the event status.
:param duration: the time to run for.
:return: nothing.
"""
self.statuses.append({'name': ScheduledMeasurementStatus.RUNNING.name, 'time': datetime.utcnow()})
try:
s... | Executes the measurement, recording the event status.
:param duration: the time to run for.
:return: nothing. | Below is the the instruction that describes the task:
### Input:
Executes the measurement, recording the event status.
:param duration: the time to run for.
:return: nothing.
### Response:
def execute(self, duration):
"""
Executes the measurement, recording the event status.
... |
def get_exported(self):
"""Get a new dict with the exported variables."""
return dict((k, self.vars[k]) for k in self.exported_vars) | Get a new dict with the exported variables. | Below is the the instruction that describes the task:
### Input:
Get a new dict with the exported variables.
### Response:
def get_exported(self):
"""Get a new dict with the exported variables."""
return dict((k, self.vars[k]) for k in self.exported_vars) |
def get_context(self):
"""
Return the context used to render the templates for the email
subject and body.
By default, this context includes:
* All of the validated values in the form, as variables of the
same names as their fields.
* The current ``Site`` obj... | Return the context used to render the templates for the email
subject and body.
By default, this context includes:
* All of the validated values in the form, as variables of the
same names as their fields.
* The current ``Site`` object, as the variable ``site``.
* A... | Below is the the instruction that describes the task:
### Input:
Return the context used to render the templates for the email
subject and body.
By default, this context includes:
* All of the validated values in the form, as variables of the
same names as their fields.
... |
def _set_adj_type(self, v, load=False):
"""
Setter method for adj_type, mapped from YANG variable /adj_neighbor_entries_state/adj_neighbor/adj_type (isis-adj-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_adj_type is considered as a private
method. Backends lo... | Setter method for adj_type, mapped from YANG variable /adj_neighbor_entries_state/adj_neighbor/adj_type (isis-adj-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_adj_type is considered as a private
method. Backends looking to populate this variable should
do so via... | Below is the the instruction that describes the task:
### Input:
Setter method for adj_type, mapped from YANG variable /adj_neighbor_entries_state/adj_neighbor/adj_type (isis-adj-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_adj_type is considered as a private
me... |
def run_with_gunicorn(self, **options):
"""Run with gunicorn."""
import gunicorn.app.base
from gunicorn.six import iteritems
import multiprocessing
class GourdeApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
sel... | Run with gunicorn. | Below is the the instruction that describes the task:
### Input:
Run with gunicorn.
### Response:
def run_with_gunicorn(self, **options):
"""Run with gunicorn."""
import gunicorn.app.base
from gunicorn.six import iteritems
import multiprocessing
class GourdeApplication(guni... |
def create_entry_line_from_text(self, text):
"""
Try to parse the given text line and extract and entry. Return an :class:`~taxi.timesheet.lines.Entry`
object if parsing is successful, otherwise raise :exc:`~taxi.exceptions.ParseError`.
"""
split_line = re.match(self.entry_line_r... | Try to parse the given text line and extract and entry. Return an :class:`~taxi.timesheet.lines.Entry`
object if parsing is successful, otherwise raise :exc:`~taxi.exceptions.ParseError`. | Below is the the instruction that describes the task:
### Input:
Try to parse the given text line and extract and entry. Return an :class:`~taxi.timesheet.lines.Entry`
object if parsing is successful, otherwise raise :exc:`~taxi.exceptions.ParseError`.
### Response:
def create_entry_line_from_text(self, te... |
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
... | List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket | Below is the the instruction that describes the task:
### Input:
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
### Response:
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefi... |
def create_single_weather(df, rename_dc):
"""Create an oemof weather object for the given geometry"""
my_weather = weather.FeedinWeather()
data_height = {}
name = None
# Create a pandas.DataFrame with the time series of the weather data set
weather_df = pd.DataFrame(index=df.time_series.iloc[0].... | Create an oemof weather object for the given geometry | Below is the the instruction that describes the task:
### Input:
Create an oemof weather object for the given geometry
### Response:
def create_single_weather(df, rename_dc):
"""Create an oemof weather object for the given geometry"""
my_weather = weather.FeedinWeather()
data_height = {}
name = Non... |
def allreduce(self, f, value, flat=True):
"""parallel reduce followed by broadcast of the result"""
return self.reduce(f, value, flat=flat, all=True) | parallel reduce followed by broadcast of the result | Below is the the instruction that describes the task:
### Input:
parallel reduce followed by broadcast of the result
### Response:
def allreduce(self, f, value, flat=True):
"""parallel reduce followed by broadcast of the result"""
return self.reduce(f, value, flat=flat, all=True) |
def _read_stimtime_AFNI(stimtime_files, n_C, n_S, scan_onoff):
""" Utility called by gen_design. It reads in one or more stimulus timing
file comforming to AFNI style, and return a list
(size of ``[number of runs \\* number of conditions]``)
of dictionary including onsets, durations and weig... | Utility called by gen_design. It reads in one or more stimulus timing
file comforming to AFNI style, and return a list
(size of ``[number of runs \\* number of conditions]``)
of dictionary including onsets, durations and weights of each event.
Parameters
----------
stimtime_files: ... | Below is the the instruction that describes the task:
### Input:
Utility called by gen_design. It reads in one or more stimulus timing
file comforming to AFNI style, and return a list
(size of ``[number of runs \\* number of conditions]``)
of dictionary including onsets, durations and weight... |
def count_protein_group_hits(lineproteins, groups):
"""Takes a list of protein accessions and a list of protein groups
content from DB. Counts for each group in list how many proteins
are found in lineproteins. Returns list of str amounts.
"""
hits = []
for group in groups:
hits.append(0... | Takes a list of protein accessions and a list of protein groups
content from DB. Counts for each group in list how many proteins
are found in lineproteins. Returns list of str amounts. | Below is the the instruction that describes the task:
### Input:
Takes a list of protein accessions and a list of protein groups
content from DB. Counts for each group in list how many proteins
are found in lineproteins. Returns list of str amounts.
### Response:
def count_protein_group_hits(lineproteins, ... |
def _update_limits_from_api(self):
"""
Query RDS's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
We ignore the usage information from the API,
"""
self.connect()
logger.info("Querying RDS DescribeAccoun... | Query RDS's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
We ignore the usage information from the API, | Below is the the instruction that describes the task:
### Input:
Query RDS's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
We ignore the usage information from the API,
### Response:
def _update_limits_from_api(self):
"""
... |
def create_module_rst_file(module_name):
"""Function for creating content in each .rst file for a module.
:param module_name: name of the module.
:type module_name: str
:returns: A content for auto module.
:rtype: str
"""
return_text = 'Module: ' + module_name
dash = '=' * len(return... | Function for creating content in each .rst file for a module.
:param module_name: name of the module.
:type module_name: str
:returns: A content for auto module.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Function for creating content in each .rst file for a module.
:param module_name: name of the module.
:type module_name: str
:returns: A content for auto module.
:rtype: str
### Response:
def create_module_rst_file(module_name):
... |
def map_v2_event_into_v1(event):
'''
Helper method to convert Sensu 2.x event into Sensu 1.x event.
'''
# return the event if it has already been mapped
if "v2_event_mapped_into_v1" in event:
return event
# Trigger mapping code if enity exists and client does not
if not bool(event.... | Helper method to convert Sensu 2.x event into Sensu 1.x event. | Below is the the instruction that describes the task:
### Input:
Helper method to convert Sensu 2.x event into Sensu 1.x event.
### Response:
def map_v2_event_into_v1(event):
'''
Helper method to convert Sensu 2.x event into Sensu 1.x event.
'''
# return the event if it has already been mapped
... |
def __handle_rate_limit_exception(self, rate_limit_exception):
"""
Sleep for the time specified in the exception. If not specified, wait
for 60 seconds.
"""
retry_after = int(
rate_limit_exception.response.headers.get('Retry-After', 60))
self.log.info(
... | Sleep for the time specified in the exception. If not specified, wait
for 60 seconds. | Below is the the instruction that describes the task:
### Input:
Sleep for the time specified in the exception. If not specified, wait
for 60 seconds.
### Response:
def __handle_rate_limit_exception(self, rate_limit_exception):
"""
Sleep for the time specified in the exception. If not speci... |
def nworker(data, smpchunk, tests):
""" The workhorse function. Not numba. """
## tell engines to limit threads
#numba.config.NUMBA_DEFAULT_NUM_THREADS = 1
## open the seqarray view, the modified array is in bootsarr
with h5py.File(data.database.input, 'r') as io5:
seqview = io5["b... | The workhorse function. Not numba. | Below is the the instruction that describes the task:
### Input:
The workhorse function. Not numba.
### Response:
def nworker(data, smpchunk, tests):
""" The workhorse function. Not numba. """
## tell engines to limit threads
#numba.config.NUMBA_DEFAULT_NUM_THREADS = 1
## open the seqarra... |
def connect(self):
# type: () -> None
"""
Connect to server
Returns:
None
"""
if self.connection_type.lower() == 'ssl':
self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, local_hostname=self.local_hostname,
... | Connect to server
Returns:
None | Below is the the instruction that describes the task:
### Input:
Connect to server
Returns:
None
### Response:
def connect(self):
# type: () -> None
"""
Connect to server
Returns:
None
"""
if self.connection_type.lower() == 'ssl':
... |
def gprmc_to_degdec(lat, latDirn, lng, lngDirn):
"""Converts GPRMC formats (Decimal Minutes) to Degrees Decimal."""
x = float(lat[0:2]) + float(lat[2:]) / 60
y = float(lng[0:3]) + float(lng[3:]) / 60
if latDirn == 'S':
x = -x
if lngDirn == 'W':
y = -y
return x, y | Converts GPRMC formats (Decimal Minutes) to Degrees Decimal. | Below is the the instruction that describes the task:
### Input:
Converts GPRMC formats (Decimal Minutes) to Degrees Decimal.
### Response:
def gprmc_to_degdec(lat, latDirn, lng, lngDirn):
"""Converts GPRMC formats (Decimal Minutes) to Degrees Decimal."""
x = float(lat[0:2]) + float(lat[2:]) / 60
y = f... |
def creep_kill(self, target, timestamp):
"""
A creep was tragically killed. Need to split this into radiant/dire
and neutrals
"""
self.creep_kill_types[target] += 1
matched = False
for k, v in self.creep_types.iteritems():
if target.startswith(k):
... | A creep was tragically killed. Need to split this into radiant/dire
and neutrals | Below is the the instruction that describes the task:
### Input:
A creep was tragically killed. Need to split this into radiant/dire
and neutrals
### Response:
def creep_kill(self, target, timestamp):
"""
A creep was tragically killed. Need to split this into radiant/dire
and neutra... |
def templatesCollector(text, open, close):
"""leaves related articles and wikitables in place"""
others = []
spans = [i for i in findBalanced(text, open, close)]
spanscopy = copy(spans)
for i in range(len(spans)):
start, end = spans[i]
o = text[start:end]
ol = o.lower()
... | leaves related articles and wikitables in place | Below is the the instruction that describes the task:
### Input:
leaves related articles and wikitables in place
### Response:
def templatesCollector(text, open, close):
"""leaves related articles and wikitables in place"""
others = []
spans = [i for i in findBalanced(text, open, close)]
spanscopy ... |
def copy(self):
'''Create a copy of the current instance.
:returns: A safely editable copy of the current sequence.
'''
# Significant performance improvements by skipping alphabet check
return type(self)(self.seq, self.material, run_checks=False) | Create a copy of the current instance.
:returns: A safely editable copy of the current sequence. | Below is the the instruction that describes the task:
### Input:
Create a copy of the current instance.
:returns: A safely editable copy of the current sequence.
### Response:
def copy(self):
'''Create a copy of the current instance.
:returns: A safely editable copy of the current sequenc... |
def dimension_name(dimension):
"""Return the Dimension.name for a dimension-like object.
Args:
dimension: Dimension or dimension string, tuple or dict
Returns:
The name of the Dimension or what would be the name if the
input as converted to a Dimension.
"""
if isinstance(di... | Return the Dimension.name for a dimension-like object.
Args:
dimension: Dimension or dimension string, tuple or dict
Returns:
The name of the Dimension or what would be the name if the
input as converted to a Dimension. | Below is the the instruction that describes the task:
### Input:
Return the Dimension.name for a dimension-like object.
Args:
dimension: Dimension or dimension string, tuple or dict
Returns:
The name of the Dimension or what would be the name if the
input as converted to a Dimensio... |
def _get_parameter(self, name, tp, timeout=1.0, max_retries=2):
""" Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to chec... | Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to check. It is always the command to
set it but without the value.
... | Below is the the instruction that describes the task:
### Input:
Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to check. It i... |
def get_int(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `int`/`li... | Get a the value corresponding to the key and converts it to `int`/`list(int)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_l... | Below is the the instruction that describes the task:
### Input:
Get a the value corresponding to the key and converts it to `int`/`list(int)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not f... |
def ptz_status_send(self, zoom, pan, tilt, force_mavlink1=False):
'''
Transmits the actual Pan, Tilt and Zoom values of the camera unit
zoom : The actual Zoom Value (uint8_t)
pan : The Pan value in 10ths of degre... | Transmits the actual Pan, Tilt and Zoom values of the camera unit
zoom : The actual Zoom Value (uint8_t)
pan : The Pan value in 10ths of degree (int16_t)
tilt : The Tilt value in 10ths of degree (int16_t) | Below is the the instruction that describes the task:
### Input:
Transmits the actual Pan, Tilt and Zoom values of the camera unit
zoom : The actual Zoom Value (uint8_t)
pan : The Pan value in 10ths of degree (int16_t)
tilt ... |
def reset(self):
"""
Resets the initial radii used for updating the particles. Call
if any of the particle radii or positions have been changed
external to the augmented state.
"""
inds = list(range(self.state.obj_get_positions().shape[0]))
self._rad_nms = self.st... | Resets the initial radii used for updating the particles. Call
if any of the particle radii or positions have been changed
external to the augmented state. | Below is the the instruction that describes the task:
### Input:
Resets the initial radii used for updating the particles. Call
if any of the particle radii or positions have been changed
external to the augmented state.
### Response:
def reset(self):
"""
Resets the initial radii us... |
def getRecord(self, n=None):
"""Returns the nth record"""
if n is None:
assert len(self.fields)>0
n = self.fields[0].numRecords-1
assert (all(field.numRecords>n for field in self.fields))
record = [field.values[n] for field in self.fields]
return record | Returns the nth record | Below is the the instruction that describes the task:
### Input:
Returns the nth record
### Response:
def getRecord(self, n=None):
"""Returns the nth record"""
if n is None:
assert len(self.fields)>0
n = self.fields[0].numRecords-1
assert (all(field.numRecords>n for field in self.fields))... |
def upload_directory(self, directory, bucket, key, transfer_config=None, subscribers=None):
''' upload a directory using Aspera '''
check_io_access(directory, os.R_OK)
return self._queue_task(bucket, [FilePair(key, directory)], transfer_config,
subscribers, enumAs... | upload a directory using Aspera | Below is the the instruction that describes the task:
### Input:
upload a directory using Aspera
### Response:
def upload_directory(self, directory, bucket, key, transfer_config=None, subscribers=None):
''' upload a directory using Aspera '''
check_io_access(directory, os.R_OK)
return self.... |
def size(self,value):
'''
The number of hits to return. Defaults to 10
'''
if not self.params:
self.params = dict(size=value)
return self
self.params['size'] = value
return self | The number of hits to return. Defaults to 10 | Below is the the instruction that describes the task:
### Input:
The number of hits to return. Defaults to 10
### Response:
def size(self,value):
'''
The number of hits to return. Defaults to 10
'''
if not self.params:
self.params = dict(size=value)
return se... |
def _process_batch_write_response(request, response, table_crypto_config):
# type: (Dict, Dict, Dict[Text, CryptoConfig]) -> Dict
"""Handle unprocessed items in the response from a transparently encrypted write.
:param dict request: The DynamoDB plaintext request dictionary
:param dict response: The Dy... | Handle unprocessed items in the response from a transparently encrypted write.
:param dict request: The DynamoDB plaintext request dictionary
:param dict response: The DynamoDB response from the batch operation
:param Dict[Text, CryptoConfig] table_crypto_config: table level CryptoConfig used in encrypting... | Below is the the instruction that describes the task:
### Input:
Handle unprocessed items in the response from a transparently encrypted write.
:param dict request: The DynamoDB plaintext request dictionary
:param dict response: The DynamoDB response from the batch operation
:param Dict[Text, CryptoCon... |
def _relative_paths(xs, base_path):
"""Adjust paths to be relative to the provided base path.
"""
if isinstance(xs, six.string_types):
if xs.startswith(base_path):
return xs.replace(base_path + "/", "", 1)
else:
return xs
elif isinstance(xs, (list, tuple)):
... | Adjust paths to be relative to the provided base path. | Below is the the instruction that describes the task:
### Input:
Adjust paths to be relative to the provided base path.
### Response:
def _relative_paths(xs, base_path):
"""Adjust paths to be relative to the provided base path.
"""
if isinstance(xs, six.string_types):
if xs.startswith(base_path... |
def r_annotation_body(self, sha):
""" Route to retrieve contents of an annotation resource
:param uri: The uri of the annotation resource
:type uri: str
:return: annotation contents
:rtype: {str: Any}
"""
annotation = self.__queryinterface__.getResource(sha)
... | Route to retrieve contents of an annotation resource
:param uri: The uri of the annotation resource
:type uri: str
:return: annotation contents
:rtype: {str: Any} | Below is the the instruction that describes the task:
### Input:
Route to retrieve contents of an annotation resource
:param uri: The uri of the annotation resource
:type uri: str
:return: annotation contents
:rtype: {str: Any}
### Response:
def r_annotation_body(self, sha):
... |
def reversed(self):
"""returns a copy of the Arc object with its orientation reversed."""
return Arc(self.end, self.radius, self.rotation, self.large_arc,
not self.sweep, self.start) | returns a copy of the Arc object with its orientation reversed. | Below is the the instruction that describes the task:
### Input:
returns a copy of the Arc object with its orientation reversed.
### Response:
def reversed(self):
"""returns a copy of the Arc object with its orientation reversed."""
return Arc(self.end, self.radius, self.rotation, self.large_arc,
... |
def create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
"""Creates `TrainingInstance`s for a single document."""
document = all_documents[document_index]
# Account for [CLS], [SEP], [SEP]
... | Creates `TrainingInstance`s for a single document. | Below is the the instruction that describes the task:
### Input:
Creates `TrainingInstance`s for a single document.
### Response:
def create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
"""Cre... |
def pkg_tracking(self):
"""Tracking package dependencies
"""
flag = []
options = [
"-t",
"--tracking"
]
additional_options = [
"--check-deps",
"--graph=",
"--case-ins"
]
for arg in self.args[2:]:
... | Tracking package dependencies | Below is the the instruction that describes the task:
### Input:
Tracking package dependencies
### Response:
def pkg_tracking(self):
"""Tracking package dependencies
"""
flag = []
options = [
"-t",
"--tracking"
]
additional_options = [
... |
def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=None):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `gen`.
"""
if seed:
gen.reset(seed)
elems = [format(next(gen), fmt) for _ in range(num)]
sep_initial = "\n\n" if '\n' in... | Helper function which prints a sequence of `num` items
produced by the random generator `gen`. | Below is the the instruction that describes the task:
### Input:
Helper function which prints a sequence of `num` items
produced by the random generator `gen`.
### Response:
def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=None):
"""
Helper function which prints a sequence of `num` item... |
def json_hash(obj, digest=None, encoder=None):
"""Hashes `obj` by dumping to JSON.
:param obj: An object that can be rendered to json using the given `encoder`.
:param digest: An optional `hashlib` compatible message digest. Defaults to `hashlib.sha1`.
:param encoder: An optional custom json encoder.
:type e... | Hashes `obj` by dumping to JSON.
:param obj: An object that can be rendered to json using the given `encoder`.
:param digest: An optional `hashlib` compatible message digest. Defaults to `hashlib.sha1`.
:param encoder: An optional custom json encoder.
:type encoder: :class:`json.JSONEncoder`
:returns: A hash... | Below is the the instruction that describes the task:
### Input:
Hashes `obj` by dumping to JSON.
:param obj: An object that can be rendered to json using the given `encoder`.
:param digest: An optional `hashlib` compatible message digest. Defaults to `hashlib.sha1`.
:param encoder: An optional custom json e... |
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
... | Initialize centroids according to method by Huang [1997]. | Below is the the instruction that describes the task:
### Input:
Initialize centroids according to method by Huang [1997].
### Response:
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clus... |
def rot(self, x, fun, rot=1, args=()):
"""returns ``fun(rotation(x), *args)``, ie. `fun` applied to a rotated argument"""
if len(np.shape(array(x))) > 1: # parallelized
res = []
for x in x:
res.append(self.rot(x, fun, rot, args))
return res
i... | returns ``fun(rotation(x), *args)``, ie. `fun` applied to a rotated argument | Below is the the instruction that describes the task:
### Input:
returns ``fun(rotation(x), *args)``, ie. `fun` applied to a rotated argument
### Response:
def rot(self, x, fun, rot=1, args=()):
"""returns ``fun(rotation(x), *args)``, ie. `fun` applied to a rotated argument"""
if len(np.shape(array... |
def assertHeader(self, name, value=None, *args, **kwargs):
"""
Returns `True` if ``name`` was in the headers and, if ``value`` is
True, whether or not the values match, or `False` otherwise.
"""
return name in self.raw_headers and (
True if value is None else self.raw... | Returns `True` if ``name`` was in the headers and, if ``value`` is
True, whether or not the values match, or `False` otherwise. | Below is the the instruction that describes the task:
### Input:
Returns `True` if ``name`` was in the headers and, if ``value`` is
True, whether or not the values match, or `False` otherwise.
### Response:
def assertHeader(self, name, value=None, *args, **kwargs):
"""
Returns `True` if ``n... |
def _parse_summary(tag, parser, parent):
"""Parses a <summary> tag and adds it the Executable parent instance.
:arg parser: an instance of DocParser to create the DocElement with.
"""
summary = DocElement(tag, parser, parent)
parent.docstring.append(summary) | Parses a <summary> tag and adds it the Executable parent instance.
:arg parser: an instance of DocParser to create the DocElement with. | Below is the the instruction that describes the task:
### Input:
Parses a <summary> tag and adds it the Executable parent instance.
:arg parser: an instance of DocParser to create the DocElement with.
### Response:
def _parse_summary(tag, parser, parent):
"""Parses a <summary> tag and adds it the Exec... |
def check_req(req):
"""Checks if a given req is the latest version available."""
if not isinstance(req, Requirement):
return None
info = get_package_info(req.name)
newest_version = _get_newest_version(info)
if _is_pinned(req) and _is_version_range(req):
return None
current_spe... | Checks if a given req is the latest version available. | Below is the the instruction that describes the task:
### Input:
Checks if a given req is the latest version available.
### Response:
def check_req(req):
"""Checks if a given req is the latest version available."""
if not isinstance(req, Requirement):
return None
info = get_package_info(req.na... |
def get_utt_regions(self):
"""
Return the regions of all utterances, assuming all utterances are concatenated.
It is assumed that the utterances are sorted in ascending order for concatenation.
A region is defined by offset (in chunks), length (num-chunks) and
a list of referenc... | Return the regions of all utterances, assuming all utterances are concatenated.
It is assumed that the utterances are sorted in ascending order for concatenation.
A region is defined by offset (in chunks), length (num-chunks) and
a list of references to the utterance datasets in the containers.... | Below is the the instruction that describes the task:
### Input:
Return the regions of all utterances, assuming all utterances are concatenated.
It is assumed that the utterances are sorted in ascending order for concatenation.
A region is defined by offset (in chunks), length (num-chunks) and
... |
def _raw_read(self):
"""
Reads data from the socket and writes it to the memory bio
used by libssl to decrypt the data. Returns the unencrypted
data for the purpose of debugging handshakes.
:return:
A byte string of ciphertext from the socket. Used for
de... | Reads data from the socket and writes it to the memory bio
used by libssl to decrypt the data. Returns the unencrypted
data for the purpose of debugging handshakes.
:return:
A byte string of ciphertext from the socket. Used for
debugging the handshake only. | Below is the the instruction that describes the task:
### Input:
Reads data from the socket and writes it to the memory bio
used by libssl to decrypt the data. Returns the unencrypted
data for the purpose of debugging handshakes.
:return:
A byte string of ciphertext from the soc... |
def stop(self):
"""To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server."""
stopped = []
for interface_id, proxy in self.proxies.items():
if interface_id in self.failed_inits:
LOG.warning("ServerThread.stop: Not performing de-init f... | To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server. | Below is the the instruction that describes the task:
### Input:
To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server.
### Response:
def stop(self):
"""To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server."""
stopped = []
... |
def get_zonefile_data( self, zonefile_hash, zonefile_dir ):
"""
Get a zonefile by hash
Return the serialized zonefile on success
Return None on error
"""
# check cache
atlas_zonefile_data = get_atlas_zonefile_data( zonefile_hash, zonefile_dir, check=False )
... | Get a zonefile by hash
Return the serialized zonefile on success
Return None on error | Below is the the instruction that describes the task:
### Input:
Get a zonefile by hash
Return the serialized zonefile on success
Return None on error
### Response:
def get_zonefile_data( self, zonefile_hash, zonefile_dir ):
"""
Get a zonefile by hash
Return the serialized z... |
def vectorize(fn):
"""
Allows a method to accept a list argument, but internally deal only
with a single item of that list.
"""
@functools.wraps(fn)
def vectorized_function(values, *vargs, **kwargs):
return [fn(value, *vargs, **kwargs) for value in values]
return vectorized_functio... | Allows a method to accept a list argument, but internally deal only
with a single item of that list. | Below is the the instruction that describes the task:
### Input:
Allows a method to accept a list argument, but internally deal only
with a single item of that list.
### Response:
def vectorize(fn):
"""
Allows a method to accept a list argument, but internally deal only
with a single item of that l... |
def index(self, shape):
"""Return the index of *shape* in this sequence.
Raises |ValueError| if *shape* is not in the collection.
"""
shape_elms = list(self._element.iter_shape_elms())
return shape_elms.index(shape.element) | Return the index of *shape* in this sequence.
Raises |ValueError| if *shape* is not in the collection. | Below is the the instruction that describes the task:
### Input:
Return the index of *shape* in this sequence.
Raises |ValueError| if *shape* is not in the collection.
### Response:
def index(self, shape):
"""Return the index of *shape* in this sequence.
Raises |ValueError| if *shape* is ... |
def get_atom(value):
"""atom = [CFWS] 1*atext [CFWS]
"""
atom = Atom()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
atom.append(token)
if value and value[0] in ATOM_ENDS:
raise errors.HeaderParseError(
"expected atom but found '{}'".format... | atom = [CFWS] 1*atext [CFWS] | Below is the the instruction that describes the task:
### Input:
atom = [CFWS] 1*atext [CFWS]
### Response:
def get_atom(value):
"""atom = [CFWS] 1*atext [CFWS]
"""
atom = Atom()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
atom.append(token)
if value an... |
def arrange_all(self):
""" Arrange the components of the node using Graphviz.
"""
# FIXME: Circular reference avoidance.
import godot.dot_data_parser
import godot.graph
graph = godot.graph.Graph(ID="g")
graph.add_node(self)
print "GRAPH DOT:\n", str(grap... | Arrange the components of the node using Graphviz. | Below is the the instruction that describes the task:
### Input:
Arrange the components of the node using Graphviz.
### Response:
def arrange_all(self):
""" Arrange the components of the node using Graphviz.
"""
# FIXME: Circular reference avoidance.
import godot.dot_data_parser
... |
def _extract_recipients(
message: Message, resent_dates: List[Union[str, Header]] = None
) -> List[str]:
"""
Extract the recipients from the message object given.
"""
recipients = [] # type: List[str]
if resent_dates:
recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
els... | Extract the recipients from the message object given. | Below is the the instruction that describes the task:
### Input:
Extract the recipients from the message object given.
### Response:
def _extract_recipients(
message: Message, resent_dates: List[Union[str, Header]] = None
) -> List[str]:
"""
Extract the recipients from the message object given.
"""... |
def finish_scan(self, scan_id):
""" Sets a scan as finished. """
self.set_scan_progress(scan_id, 100)
self.set_scan_status(scan_id, ScanStatus.FINISHED)
logger.info("%s: Scan finished.", scan_id) | Sets a scan as finished. | Below is the the instruction that describes the task:
### Input:
Sets a scan as finished.
### Response:
def finish_scan(self, scan_id):
""" Sets a scan as finished. """
self.set_scan_progress(scan_id, 100)
self.set_scan_status(scan_id, ScanStatus.FINISHED)
logger.info("%s: Scan fini... |
def get_gid(path, follow_symlinks=True):
'''
Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_gid /etc/passwd... | Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_gid /etc/passwd
.. versionchanged:: 0.16.4
``follow_sym... | Below is the the instruction that describes the task:
### Input:
Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get... |
def get(self, identity):
"""
Constructs a SyncListPermissionContext
:param identity: Identity of the user to whom the Sync List Permission applies.
:returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext
:rtype: twilio.rest.sync.v1.service... | Constructs a SyncListPermissionContext
:param identity: Identity of the user to whom the Sync List Permission applies.
:returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext
:rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermi... | Below is the the instruction that describes the task:
### Input:
Constructs a SyncListPermissionContext
:param identity: Identity of the user to whom the Sync List Permission applies.
:returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext
:rtype: twi... |
def remove_account_user_from_groups(self, account_id, user_id, body, **kwargs): # noqa: E501
"""Remove user from groups. # noqa: E501
An endpoint for removing user from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{user-id}/groups -d '... | Remove user from groups. # noqa: E501
An endpoint for removing user from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{user-id}/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30242590700000000]' -H 'content-type: application/json' ... | Below is the the instruction that describes the task:
### Input:
Remove user from groups. # noqa: E501
An endpoint for removing user from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{user-id}/groups -d '[0162056a9a1586f30242590700000000,01... |
def is_equal(self, string1, string2):
''' Simple string comparator '''
return string1.lower().strip() == string2.lower().strip() | Simple string comparator | Below is the the instruction that describes the task:
### Input:
Simple string comparator
### Response:
def is_equal(self, string1, string2):
''' Simple string comparator '''
return string1.lower().strip() == string2.lower().strip() |
def _dequeue(self, local_prof):
"""
**Purpose**: This is the function that is run in the dequeue thread. This function extracts Tasks from the
completed queus and updates the copy of workflow that exists in the WFprocessor object.
Since this thread works on the copy of the workflow, ever... | **Purpose**: This is the function that is run in the dequeue thread. This function extracts Tasks from the
completed queus and updates the copy of workflow that exists in the WFprocessor object.
Since this thread works on the copy of the workflow, every state update to the Task, Stage and Pipeline is
... | Below is the the instruction that describes the task:
### Input:
**Purpose**: This is the function that is run in the dequeue thread. This function extracts Tasks from the
completed queus and updates the copy of workflow that exists in the WFprocessor object.
Since this thread works on the copy of t... |
def get_ZXY_data_IFFT(Data, zf, xf, yf,
zwidth=10000, xwidth=5000, ywidth=5000,
timeStart=None, timeEnd=None,
show_fig=True):
"""
Given a Data object and the frequencies of the z, x and y peaks (and some
optional parameters for the created fi... | Given a Data object and the frequencies of the z, x and y peaks (and some
optional parameters for the created filters) this function extracts the
individual z, x and y signals (in volts) by creating IIR filters and filtering
the Data.
Parameters
----------
Data : DataObject
DataObject c... | Below is the the instruction that describes the task:
### Input:
Given a Data object and the frequencies of the z, x and y peaks (and some
optional parameters for the created filters) this function extracts the
individual z, x and y signals (in volts) by creating IIR filters and filtering
the Data.
... |
def generator(self, random, args):
"""Return a candidate solution for an evolutionary computation."""
locations = [i for i in range(len(self.weights))]
random.shuffle(locations)
return locations | Return a candidate solution for an evolutionary computation. | Below is the the instruction that describes the task:
### Input:
Return a candidate solution for an evolutionary computation.
### Response:
def generator(self, random, args):
"""Return a candidate solution for an evolutionary computation."""
locations = [i for i in range(len(self.weights))]
... |
def forwards(self, orm):
"Write your forwards methods here."
Project = orm['samples.Project']
Cohort = orm['samples.Cohort']
now = datetime.datetime.now()
# Create default project
try:
project = Project.objects.get(name=DEFAULT_PROJECT_NAME)
except ... | Write your forwards methods here. | Below is the the instruction that describes the task:
### Input:
Write your forwards methods here.
### Response:
def forwards(self, orm):
"Write your forwards methods here."
Project = orm['samples.Project']
Cohort = orm['samples.Cohort']
now = datetime.datetime.now()
# Cr... |
def get_sequence(self, chrom, start, end, strand='+', indexing=(-1, 0)):
"""
chromosome is entered relative to the file it was built with, so it can be 'chr11' or '11',
start/end are coordinates, which default to python style [0,1) internally. So positions should be
entered with (1,1) in... | chromosome is entered relative to the file it was built with, so it can be 'chr11' or '11',
start/end are coordinates, which default to python style [0,1) internally. So positions should be
entered with (1,1) indexing. This can be changed with the indexing keyword.
The default is for everything ... | Below is the the instruction that describes the task:
### Input:
chromosome is entered relative to the file it was built with, so it can be 'chr11' or '11',
start/end are coordinates, which default to python style [0,1) internally. So positions should be
entered with (1,1) indexing. This can be chan... |
def collect_snmp(self, device, host, port, community):
"""
Collect SNMP interface data from device
"""
# Log
self.log.info("Collecting SNMP interface statistics from: %s", device)
# Define a list of interface indexes
ifIndexes = []
# Get Interface Indexe... | Collect SNMP interface data from device | Below is the the instruction that describes the task:
### Input:
Collect SNMP interface data from device
### Response:
def collect_snmp(self, device, host, port, community):
"""
Collect SNMP interface data from device
"""
# Log
self.log.info("Collecting SNMP interface statis... |
def _find_address_range(addresses):
"""Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence.
"""
it = iter(addresses)
first = last = next(it)
for ip in... | Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence. | Below is the the instruction that describes the task:
### Input:
Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence.
### Response:
def _find_address_range(addresses)... |
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(s... | Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compose in rev... | Below is the the instruction that describes the task:
### Input:
Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order ... |
def get_nearest(self, path, return_type='file', strict=True, all_=False,
ignore_strict_entities=None, full_search=False, **kwargs):
''' Walk up the file tree from the specified path and return the
nearest matching file(s).
Args:
path (str): The file to search fro... | Walk up the file tree from the specified path and return the
nearest matching file(s).
Args:
path (str): The file to search from.
return_type (str): What to return; must be one of 'file' (default)
or 'tuple'.
strict (bool): When True, all entities pre... | Below is the the instruction that describes the task:
### Input:
Walk up the file tree from the specified path and return the
nearest matching file(s).
Args:
path (str): The file to search from.
return_type (str): What to return; must be one of 'file' (default)
... |
def response(self, status, content_type, content, headers=None):
"""
Send an HTTP response
"""
assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes'
response_headers = [('Content-Type', content_type)]
if headers:
resp... | Send an HTTP response | Below is the the instruction that describes the task:
### Input:
Send an HTTP response
### Response:
def response(self, status, content_type, content, headers=None):
"""
Send an HTTP response
"""
assert not isinstance(content, (str, bytes)), 'response content cannot be of type str ... |
def set_defaults(self, config_file):
"""Set defaults.
"""
self.defaults = Defaults(config_file)
self.locations = Locations(self.defaults)
self.python = Python()
self.setuptools = Setuptools()
self.scp = SCP()
self.scms = SCMFactory()
self.urlparser... | Set defaults. | Below is the the instruction that describes the task:
### Input:
Set defaults.
### Response:
def set_defaults(self, config_file):
"""Set defaults.
"""
self.defaults = Defaults(config_file)
self.locations = Locations(self.defaults)
self.python = Python()
self.setuptoo... |
def mirror(self, handler, path_from, path_to, log_files=False):
"""Recursively mirror the contents of "path_from" into "path_to".
"handler" should be self.mirror_to_local_no_recursion or
self.mirror_to_remote_no_recursion to represent which way the files are
moving.
"""
... | Recursively mirror the contents of "path_from" into "path_to".
"handler" should be self.mirror_to_local_no_recursion or
self.mirror_to_remote_no_recursion to represent which way the files are
moving. | Below is the the instruction that describes the task:
### Input:
Recursively mirror the contents of "path_from" into "path_to".
"handler" should be self.mirror_to_local_no_recursion or
self.mirror_to_remote_no_recursion to represent which way the files are
moving.
### Response:
def mirror... |
def buffer_focus(self, buf, redraw=True):
"""focus given :class:`~alot.buffers.Buffer`."""
# call pre_buffer_focus hook
prehook = settings.get_hook('pre_buffer_focus')
if prehook is not None:
prehook(ui=self, dbm=self.dbman, buf=buf)
success = False
if buf n... | focus given :class:`~alot.buffers.Buffer`. | Below is the the instruction that describes the task:
### Input:
focus given :class:`~alot.buffers.Buffer`.
### Response:
def buffer_focus(self, buf, redraw=True):
"""focus given :class:`~alot.buffers.Buffer`."""
# call pre_buffer_focus hook
prehook = settings.get_hook('pre_buffer_focus')
... |
def prj_view_atype(self, *args, **kwargs):
"""View the, in the atype table view selected, assettype.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_prj:
return
i = self.prj_atype_tablev.currentIndex()
item = i.internalPointer()
... | View the, in the atype table view selected, assettype.
:returns: None
:rtype: None
:raises: None | Below is the the instruction that describes the task:
### Input:
View the, in the atype table view selected, assettype.
:returns: None
:rtype: None
:raises: None
### Response:
def prj_view_atype(self, *args, **kwargs):
"""View the, in the atype table view selected, assettype.
... |
def _validate_raw_nc(self):
"""Checks that raw netCDF file has the right dimensions and variables.
Returns
-------
int:
Length of rivid dimension.
int:
Length of time dimension.
Remarks: Raises exception if file doesn't validate.
... | Checks that raw netCDF file has the right dimensions and variables.
Returns
-------
int:
Length of rivid dimension.
int:
Length of time dimension.
Remarks: Raises exception if file doesn't validate. | Below is the the instruction that describes the task:
### Input:
Checks that raw netCDF file has the right dimensions and variables.
Returns
-------
int:
Length of rivid dimension.
int:
Length of time dimension.
Remarks: Raises exception if ... |
def get_tunings(instrument=None, nr_of_strings=None, nr_of_courses=None):
"""Search tunings on instrument, strings, courses or a combination.
The instrument is actually treated like a case-insensitive prefix. So
asking for 'bass' yields the same tunings as 'Bass Guitar'; the string
'ba' yields all the ... | Search tunings on instrument, strings, courses or a combination.
The instrument is actually treated like a case-insensitive prefix. So
asking for 'bass' yields the same tunings as 'Bass Guitar'; the string
'ba' yields all the instruments starting with 'ba'.
Example:
>>> tunings.get_tunings(nr_of_s... | Below is the the instruction that describes the task:
### Input:
Search tunings on instrument, strings, courses or a combination.
The instrument is actually treated like a case-insensitive prefix. So
asking for 'bass' yields the same tunings as 'Bass Guitar'; the string
'ba' yields all the instruments ... |
def lchisqprob(chisq,df):
"""
Returns the (1-tailed) probability value associated with the provided
chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat.
Usage: lchisqprob(chisq,df)
"""
BIG = 20.0
def ex(x):
BIG = 20.0
if x < -BIG:
return 0.0
else:
... | Returns the (1-tailed) probability value associated with the provided
chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat.
Usage: lchisqprob(chisq,df) | Below is the the instruction that describes the task:
### Input:
Returns the (1-tailed) probability value associated with the provided
chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat.
Usage: lchisqprob(chisq,df)
### Response:
def lchisqprob(chisq,df):
"""
Returns the (1-tailed) probab... |
def where_is(strings, pattern, n=1, lookup_func=re.match):
"""Return index of the nth match found of pattern in strings
Parameters
----------
strings: list of str
List of strings
pattern: str
Pattern to be matched
nth: int
Number of times the match must happen to retur... | Return index of the nth match found of pattern in strings
Parameters
----------
strings: list of str
List of strings
pattern: str
Pattern to be matched
nth: int
Number of times the match must happen to return the item index.
lookup_func: callable
Function to m... | Below is the the instruction that describes the task:
### Input:
Return index of the nth match found of pattern in strings
Parameters
----------
strings: list of str
List of strings
pattern: str
Pattern to be matched
nth: int
Number of times the match must happen to re... |
def _parse_sv8_int(fileobj, limit=9):
"""Reads (max limit) bytes from fileobj until the MSB is zero.
All 7 LSB will be merged to a big endian uint.
Raises ValueError in case not MSB is zero, or EOFError in
case the file ended before limit is reached.
Returns (parsed number, number of bytes read)
... | Reads (max limit) bytes from fileobj until the MSB is zero.
All 7 LSB will be merged to a big endian uint.
Raises ValueError in case not MSB is zero, or EOFError in
case the file ended before limit is reached.
Returns (parsed number, number of bytes read) | Below is the the instruction that describes the task:
### Input:
Reads (max limit) bytes from fileobj until the MSB is zero.
All 7 LSB will be merged to a big endian uint.
Raises ValueError in case not MSB is zero, or EOFError in
case the file ended before limit is reached.
Returns (parsed number,... |
def strategyKLogN(kls, n, k=4):
"""Return the directory names to preserve under the KLogN purge strategy."""
assert(k>1)
s = set([n])
i = 0
while k**i <= n:
s.update(range(n, n-k*k**i, -k**i))
i += 1
n -= n % k**i
return set(map(str, filter(lambda x:x>=0, s))) | Return the directory names to preserve under the KLogN purge strategy. | Below is the the instruction that describes the task:
### Input:
Return the directory names to preserve under the KLogN purge strategy.
### Response:
def strategyKLogN(kls, n, k=4):
"""Return the directory names to preserve under the KLogN purge strategy."""
assert(k>1)
s = set([n])
i = 0
while k**i <... |
def process_shells_ordered(self, shells):
"""Processing a list of shells one after the other."""
output = []
for shell in shells:
entry = shell['entry']
config = ShellConfig(script=entry['script'], title=entry['title'] if 'title' in entry else '',
... | Processing a list of shells one after the other. | Below is the the instruction that describes the task:
### Input:
Processing a list of shells one after the other.
### Response:
def process_shells_ordered(self, shells):
"""Processing a list of shells one after the other."""
output = []
for shell in shells:
entry = shell['entry'... |
def adjust_for_scratch(self):
"""
Remove certain plugins in order to handle the "scratch build"
scenario. Scratch builds must not affect subsequent builds,
and should not be imported into Koji.
"""
if self.user_params.scratch.value:
remove_plugins = [
... | Remove certain plugins in order to handle the "scratch build"
scenario. Scratch builds must not affect subsequent builds,
and should not be imported into Koji. | Below is the the instruction that describes the task:
### Input:
Remove certain plugins in order to handle the "scratch build"
scenario. Scratch builds must not affect subsequent builds,
and should not be imported into Koji.
### Response:
def adjust_for_scratch(self):
"""
Remove cer... |
def dispatch_map(self, rep, as_map_key, cache):
"""Used to determine and dipatch the writing of a map - a simple
map with strings as keys, or a complex map, whose keys are also
compound types.
"""
if self.are_stringable_keys(rep):
return self.emit_map(rep, as_map_key,... | Used to determine and dipatch the writing of a map - a simple
map with strings as keys, or a complex map, whose keys are also
compound types. | Below is the the instruction that describes the task:
### Input:
Used to determine and dipatch the writing of a map - a simple
map with strings as keys, or a complex map, whose keys are also
compound types.
### Response:
def dispatch_map(self, rep, as_map_key, cache):
"""Used to determine a... |
def filename(self, type_, id_):
"""
cache filename to read for this type/id.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: str
"""
profile = self.connection.profile
return os.path.join(self.directory, profile, type_, str(id_)) | cache filename to read for this type/id.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: str | Below is the the instruction that describes the task:
### Input:
cache filename to read for this type/id.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: str
### Response:
def filename(self, type_, id_):
"""
cache filename to read for this type/id.
... |
def send_message(self, msg):
"""
Send a message to the MUC.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
:return: The stanza token of the message.
:rtype: :class:`~aioxmpp.stream.StanzaToken`
There is no need to set the address attributes... | Send a message to the MUC.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
:return: The stanza token of the message.
:rtype: :class:`~aioxmpp.stream.StanzaToken`
There is no need to set the address attributes or the type of the
message correctly; th... | Below is the the instruction that describes the task:
### Input:
Send a message to the MUC.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
:return: The stanza token of the message.
:rtype: :class:`~aioxmpp.stream.StanzaToken`
There is no need to set th... |
def create_derivative(self, word):
''' Creates derivative of (base) word by adding any affixes that apply '''
result = None
if self.char_to_strip != '':
if self.opt == "PFX":
result = word[len(self.char_to_strip):len(word)]
result = self.affix + result... | Creates derivative of (base) word by adding any affixes that apply | Below is the the instruction that describes the task:
### Input:
Creates derivative of (base) word by adding any affixes that apply
### Response:
def create_derivative(self, word):
''' Creates derivative of (base) word by adding any affixes that apply '''
result = None
if self.char_to_strip... |
def container_elem_type(container_type, params):
"""
Returns container element type
:param container_type:
:param params:
:return:
"""
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
return elem_type | Returns container element type
:param container_type:
:param params:
:return: | Below is the the instruction that describes the task:
### Input:
Returns container element type
:param container_type:
:param params:
:return:
### Response:
def container_elem_type(container_type, params):
"""
Returns container element type
:param container_type:
:param params:
:r... |
def add_child(self, n, parent, **attrs):
'''
API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
parent: Parent nod... | API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
parent: Parent node name.
attrs: Attributes of node being added.
... | Below is the the instruction that describes the task:
### Input:
API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
parent: Pa... |
def get_axis_num(self, dim: Union[Hashable, Iterable[Hashable]]
) -> Union[int, Tuple[int, ...]]:
"""Return axis number(s) corresponding to dimension(s) in this array.
Parameters
----------
dim : str or iterable of str
Dimension name(s) for which to look... | Return axis number(s) corresponding to dimension(s) in this array.
Parameters
----------
dim : str or iterable of str
Dimension name(s) for which to lookup axes.
Returns
-------
int or tuple of int
Axis number or numbers corresponding to the give... | Below is the the instruction that describes the task:
### Input:
Return axis number(s) corresponding to dimension(s) in this array.
Parameters
----------
dim : str or iterable of str
Dimension name(s) for which to lookup axes.
Returns
-------
int or tupl... |
def check_geom(c1, a1, c2, a2, tol=_DEF.XYZ_COORD_MATCH_TOL):
""" Check for consistency of two geometries and atom symbol lists
Cartesian coordinates are considered consistent with the input
coords if each component matches to within `tol`. If coords or
atoms vectors are passed that are of mismatched ... | Check for consistency of two geometries and atom symbol lists
Cartesian coordinates are considered consistent with the input
coords if each component matches to within `tol`. If coords or
atoms vectors are passed that are of mismatched lengths, a
|False| value is returned.
Both coords vectors mus... | Below is the the instruction that describes the task:
### Input:
Check for consistency of two geometries and atom symbol lists
Cartesian coordinates are considered consistent with the input
coords if each component matches to within `tol`. If coords or
atoms vectors are passed that are of mismatched l... |
def find(self, item_id=None):
"Recursively find a menu item by its id (useful for event handlers)"
for it in self:
found = it.find(item_id)
if found:
return found | Recursively find a menu item by its id (useful for event handlers) | Below is the the instruction that describes the task:
### Input:
Recursively find a menu item by its id (useful for event handlers)
### Response:
def find(self, item_id=None):
"Recursively find a menu item by its id (useful for event handlers)"
for it in self:
found = it.find(item_id... |
def new(ruletype, **kwargs):
"""Instantiate a new build rule based on kwargs.
Appropriate args list varies with rule type.
Minimum args required:
[... fill this in ...]
"""
try:
ruleclass = TYPE_MAP[ruletype]
except KeyError:
raise error.InvalidRule('Unrecognized rule type... | Instantiate a new build rule based on kwargs.
Appropriate args list varies with rule type.
Minimum args required:
[... fill this in ...] | Below is the the instruction that describes the task:
### Input:
Instantiate a new build rule based on kwargs.
Appropriate args list varies with rule type.
Minimum args required:
[... fill this in ...]
### Response:
def new(ruletype, **kwargs):
"""Instantiate a new build rule based on kwargs.
... |
def reserve_ports(self, locations, force=False, reset=True):
""" Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reserve Port.
:param locations: list of ports locations in the form <ip/slot/port> to reserve
:param force: Tr... | Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reserve Port.
:param locations: list of ports locations in the form <ip/slot/port> to reserve
:param force: True - take forcefully. False - fail if port is reserved by other user
... | Below is the the instruction that describes the task:
### Input:
Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reserve Port.
:param locations: list of ports locations in the form <ip/slot/port> to reserve
:param force: True -... |
def calculate_extra_keys(self, buffer):
"""
Determine extra keys pressed since the given buffer was built
"""
extraBs = len(self.inputStack) - len(buffer)
if extraBs > 0:
extraKeys = ''.join(self.inputStack[len(buffer)])
else:
extraBs = 0
... | Determine extra keys pressed since the given buffer was built | Below is the the instruction that describes the task:
### Input:
Determine extra keys pressed since the given buffer was built
### Response:
def calculate_extra_keys(self, buffer):
"""
Determine extra keys pressed since the given buffer was built
"""
extraBs = len(self.inputStack) -... |
def create_from_file_extension(cls, file_extension):
"""
Create a table writer class instance from a file extension.
Supported file extensions are as follows:
================== ===================================
Extension Writer Class
===========... | Create a table writer class instance from a file extension.
Supported file extensions are as follows:
================== ===================================
Extension Writer Class
================== ===================================
``".csv"`` ... | Below is the the instruction that describes the task:
### Input:
Create a table writer class instance from a file extension.
Supported file extensions are as follows:
================== ===================================
Extension Writer Class
===============... |
def parse(cls, prefix):
"""
Extracts informations from `prefix`.
:param prefix: prefix with format ``<servername>|<nick>['!'<user>]['@'<host>]``.
:type prefix: unicode
:return: extracted informations (nickname or host, mode, username, host).
:rtype: tuple(str, str, str, ... | Extracts informations from `prefix`.
:param prefix: prefix with format ``<servername>|<nick>['!'<user>]['@'<host>]``.
:type prefix: unicode
:return: extracted informations (nickname or host, mode, username, host).
:rtype: tuple(str, str, str, str) | Below is the the instruction that describes the task:
### Input:
Extracts informations from `prefix`.
:param prefix: prefix with format ``<servername>|<nick>['!'<user>]['@'<host>]``.
:type prefix: unicode
:return: extracted informations (nickname or host, mode, username, host).
:rty... |
def _clean_prior(self):
""" Cleans up from a previous task that didn't exit cleanly.
Returns ``True`` if previous task was cleaned.
"""
if self._loaded:
try:
pid_file = daemon.get_daemon_pidfile(self)
# check if it exists so we don't... | Cleans up from a previous task that didn't exit cleanly.
Returns ``True`` if previous task was cleaned. | Below is the the instruction that describes the task:
### Input:
Cleans up from a previous task that didn't exit cleanly.
Returns ``True`` if previous task was cleaned.
### Response:
def _clean_prior(self):
""" Cleans up from a previous task that didn't exit cleanly.
Returns ``Tru... |
def create_or_update_user(self, username, policies=None, groups=None, mount_point=DEFAULT_MOUNT_POINT):
"""
Create or update LDAP users policies and group associations.
Supported methods:
POST: /auth/{mount_point}/users/{username}. Produces: 204 (empty body)
:param usernam... | Create or update LDAP users policies and group associations.
Supported methods:
POST: /auth/{mount_point}/users/{username}. Produces: 204 (empty body)
:param username: The username of the LDAP user
:type username: str | unicode
:param policies: List of policies associated ... | Below is the the instruction that describes the task:
### Input:
Create or update LDAP users policies and group associations.
Supported methods:
POST: /auth/{mount_point}/users/{username}. Produces: 204 (empty body)
:param username: The username of the LDAP user
:type username... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.