code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def make_parser(stream_or_string):
"""Create a xml.dom.pulldom parser."""
if isinstance(stream_or_string, six.string_types):
# XXX: the pulldom.parseString() function doesn't seem to
# like operating on unicode strings!
return pulldom.parseString(str(stream_or_string))
else:
... | Create a xml.dom.pulldom parser. | Below is the the instruction that describes the task:
### Input:
Create a xml.dom.pulldom parser.
### Response:
def make_parser(stream_or_string):
"""Create a xml.dom.pulldom parser."""
if isinstance(stream_or_string, six.string_types):
# XXX: the pulldom.parseString() function doesn't seem to
... |
def compute_freq(self, csd=False):
"""Compute frequency domain analysis.
Returns
-------
list of dict
each item is a dict where 'data' is an instance of ChanFreq for a
single segment of signal, 'name' is the event type, if applicable,
'times' is a tup... | Compute frequency domain analysis.
Returns
-------
list of dict
each item is a dict where 'data' is an instance of ChanFreq for a
single segment of signal, 'name' is the event type, if applicable,
'times' is a tuple of the start and end times in sec, 'duratio... | Below is the the instruction that describes the task:
### Input:
Compute frequency domain analysis.
Returns
-------
list of dict
each item is a dict where 'data' is an instance of ChanFreq for a
single segment of signal, 'name' is the event type, if applicable,
... |
def query(self, s):
"""Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets.
"""
... | Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets. | Below is the the instruction that describes the task:
### Input:
Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the orig... |
def parse_timezone(matches, default_timezone=UTC):
"""Parses ISO 8601 time zone specs into tzinfo offsets
"""
if matches["timezone"] == "Z":
return UTC
# This isn't strictly correct, but it's common to encounter dates without
# timezones so I'll assume the default (which defaults to UTC).
... | Parses ISO 8601 time zone specs into tzinfo offsets | Below is the the instruction that describes the task:
### Input:
Parses ISO 8601 time zone specs into tzinfo offsets
### Response:
def parse_timezone(matches, default_timezone=UTC):
"""Parses ISO 8601 time zone specs into tzinfo offsets
"""
if matches["timezone"] == "Z":
return UTC
# This... |
def PyParseRangeCheck(lower_bound, upper_bound):
"""Verify that a number is within a defined range.
This is a callback method for pyparsing setParseAction
that verifies that a read number is within a certain range.
To use this method it needs to be defined as a callback method
in setParseAction with the upp... | Verify that a number is within a defined range.
This is a callback method for pyparsing setParseAction
that verifies that a read number is within a certain range.
To use this method it needs to be defined as a callback method
in setParseAction with the upper and lower bound set as parameters.
Args:
low... | Below is the the instruction that describes the task:
### Input:
Verify that a number is within a defined range.
This is a callback method for pyparsing setParseAction
that verifies that a read number is within a certain range.
To use this method it needs to be defined as a callback method
in setParseActi... |
def expand(args):
"""
%prog expand bes.fasta reads.fastq
Expand sequences using short reads. Useful, for example for getting BAC-end
sequences. The template to use, in `bes.fasta` may just contain the junction
sequences, then align the reads to get the 'flanks' for such sequences.
"""
impor... | %prog expand bes.fasta reads.fastq
Expand sequences using short reads. Useful, for example for getting BAC-end
sequences. The template to use, in `bes.fasta` may just contain the junction
sequences, then align the reads to get the 'flanks' for such sequences. | Below is the the instruction that describes the task:
### Input:
%prog expand bes.fasta reads.fastq
Expand sequences using short reads. Useful, for example for getting BAC-end
sequences. The template to use, in `bes.fasta` may just contain the junction
sequences, then align the reads to get the 'flanks... |
def sha1(self):
"""SHA1 hash of the config file itself."""
with open(self.path, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest() | SHA1 hash of the config file itself. | Below is the the instruction that describes the task:
### Input:
SHA1 hash of the config file itself.
### Response:
def sha1(self):
"""SHA1 hash of the config file itself."""
with open(self.path, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest() |
def set_management_icmp(enabled=True, deploy=False):
'''
Enables or disables the ICMP management service on the device.
CLI Example:
Args:
enabled (bool): If true the service will be enabled. If false the service will be disabled.
deploy (bool): If true then commit the full candidate ... | Enables or disables the ICMP management service on the device.
CLI Example:
Args:
enabled (bool): If true the service will be enabled. If false the service will be disabled.
deploy (bool): If true then commit the full candidate configuration, if false only set pending change.
.. code-blo... | Below is the the instruction that describes the task:
### Input:
Enables or disables the ICMP management service on the device.
CLI Example:
Args:
enabled (bool): If true the service will be enabled. If false the service will be disabled.
deploy (bool): If true then commit the full candid... |
def tacacs_server_host_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
tacacs_server = ET.SubElement(config, "tacacs-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(tacacs_server, "host")
hostname_key = ET.SubElement(h... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def tacacs_server_host_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
tacacs_server = ET.SubElement(config, "tacacs-server", xmlns="urn:brocade.com:mgmt:... |
def supprime(cls,table, **kwargs):
""" Remove entries matchin given condition
kwargs is a dict of column name : value , with length ONE.
"""
assert len(kwargs) == 1
field, value = kwargs.popitem()
req = f"""DELETE FROM {table} WHERE {field} = """ + cls.mark_style
... | Remove entries matchin given condition
kwargs is a dict of column name : value , with length ONE. | Below is the the instruction that describes the task:
### Input:
Remove entries matchin given condition
kwargs is a dict of column name : value , with length ONE.
### Response:
def supprime(cls,table, **kwargs):
""" Remove entries matchin given condition
kwargs is a dict of column name : ... |
def _set_limit(self, v, load=False):
"""
Setter method for limit, mapped from YANG variable /hardware/profile/tcam/limit (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_limit is considered as a private
method. Backends looking to populate this variable sh... | Setter method for limit, mapped from YANG variable /hardware/profile/tcam/limit (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_limit is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_limit() d... | Below is the the instruction that describes the task:
### Input:
Setter method for limit, mapped from YANG variable /hardware/profile/tcam/limit (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_limit is considered as a private
method. Backends looking to popul... |
def skip(self, other):
'''(<<) Ends with a specified parser, and at the end parser consumed the
end flag.'''
@Parser
def ends_with_parser(text, index):
res = self(text, index)
if not res.status:
return res
end = other(text, res.index)
... | (<<) Ends with a specified parser, and at the end parser consumed the
end flag. | Below is the the instruction that describes the task:
### Input:
(<<) Ends with a specified parser, and at the end parser consumed the
end flag.
### Response:
def skip(self, other):
'''(<<) Ends with a specified parser, and at the end parser consumed the
end flag.'''
@Parser
... |
def chunk_by(n, iterable, fillvalue=None):
"""
Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n: (int) a chun... | Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n: (int) a chunk size number
:param iterable: (iterator) an input ... | Below is the the instruction that describes the task:
### Input:
Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n... |
def gettrans(t):
"""
Return a trans object
Parameters
----------
t : str | callable | type | trans
name of transformation function
Returns
-------
out : trans
"""
obj = t
# Make sure trans object is instantiated
if isinstance(obj, str):
name = '{}_trans'... | Return a trans object
Parameters
----------
t : str | callable | type | trans
name of transformation function
Returns
-------
out : trans | Below is the the instruction that describes the task:
### Input:
Return a trans object
Parameters
----------
t : str | callable | type | trans
name of transformation function
Returns
-------
out : trans
### Response:
def gettrans(t):
"""
Return a trans object
Paramete... |
def auto(name):
'''
.. versionadded:: 0.17.0
Instruct alternatives to use the highest priority
path for <name>
name
is the master name for this link group
(e.g. pager)
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
... | .. versionadded:: 0.17.0
Instruct alternatives to use the highest priority
path for <name>
name
is the master name for this link group
(e.g. pager) | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 0.17.0
Instruct alternatives to use the highest priority
path for <name>
name
is the master name for this link group
(e.g. pager)
### Response:
def auto(name):
'''
.. versionadded:: 0.17.0
... |
def download_file(self, fname, output_dir):
"""Downloads competition file to output_dir."""
if fname not in self.competition_files: # pylint: disable=unsupported-membership-test
raise ValueError("%s is not one of the competition's "
"files: %s" % (fname, self.competition_files))
... | Downloads competition file to output_dir. | Below is the the instruction that describes the task:
### Input:
Downloads competition file to output_dir.
### Response:
def download_file(self, fname, output_dir):
"""Downloads competition file to output_dir."""
if fname not in self.competition_files: # pylint: disable=unsupported-membership-test
r... |
async def get_entity_by_id(self, get_entity_by_id_request):
"""Return one or more user entities.
Searching by phone number only finds entities when their phone number
is in your contacts (and not always even then), and can't be used to
find Google Voice contacts.
"""
res... | Return one or more user entities.
Searching by phone number only finds entities when their phone number
is in your contacts (and not always even then), and can't be used to
find Google Voice contacts. | Below is the the instruction that describes the task:
### Input:
Return one or more user entities.
Searching by phone number only finds entities when their phone number
is in your contacts (and not always even then), and can't be used to
find Google Voice contacts.
### Response:
async def ... |
def run_play(play_source, inventory_path=None, roles=None,
extra_vars=None, on_error_continue=False):
"""Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict... | Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict): ansible task
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_err... | Below is the the instruction that describes the task:
### Input:
Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict): ansible task
inventory_path (str): invento... |
def d_cal(calibcurve, rcmean, w2, cutoff=0.0001, normal_distr=False, t_a=3, t_b=4):
"""Get calendar date probabilities
Parameters
----------
calibcurve : CalibCurve
Calibration curve.
rcmean : scalar
Reservoir-adjusted age.
w2 : scalar
r'$w^2_j(\theta)$' from pg 461 & 46... | Get calendar date probabilities
Parameters
----------
calibcurve : CalibCurve
Calibration curve.
rcmean : scalar
Reservoir-adjusted age.
w2 : scalar
r'$w^2_j(\theta)$' from pg 461 & 463 of Blaauw and Christen 2011.
cutoff : scalar, optional
Unknown.
normal_di... | Below is the the instruction that describes the task:
### Input:
Get calendar date probabilities
Parameters
----------
calibcurve : CalibCurve
Calibration curve.
rcmean : scalar
Reservoir-adjusted age.
w2 : scalar
r'$w^2_j(\theta)$' from pg 461 & 463 of Blaauw and Christ... |
def check_basic_battery_status(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0
MIB Excerpt
The status of the UPS batteries. A batteryLow(3)
value indicates the UPS will be unable to sustain the
current load, and its services will be lost if power is
not ... | OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0
MIB Excerpt
The status of the UPS batteries. A batteryLow(3)
value indicates the UPS will be unable to sustain the
current load, and its services will be lost if power is
not restored. The amount of run time in reserve at the
time of low battery can be c... | Below is the the instruction that describes the task:
### Input:
OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0
MIB Excerpt
The status of the UPS batteries. A batteryLow(3)
value indicates the UPS will be unable to sustain the
current load, and its services will be lost if power is
not restored. The a... |
def parse(cls, content, is_pyproject=False):
"""
A convenience method for parsing a TOML-serialized configuration.
:param content: a TOML string containing a TidyPy configuration
:type content: str
:param is_pyproject:
whether or not the content is (or resembles) a `... | A convenience method for parsing a TOML-serialized configuration.
:param content: a TOML string containing a TidyPy configuration
:type content: str
:param is_pyproject:
whether or not the content is (or resembles) a ``pyproject.toml``
file, where the TidyPy configuratio... | Below is the the instruction that describes the task:
### Input:
A convenience method for parsing a TOML-serialized configuration.
:param content: a TOML string containing a TidyPy configuration
:type content: str
:param is_pyproject:
whether or not the content is (or resembles)... |
def get_all_matches(self, partial_selector):
"""Returns all values matching `partial_selector` as a list."""
matching_selectors = self.matching_selectors(partial_selector)
return [self._selector_map[selector] for selector in matching_selectors] | Returns all values matching `partial_selector` as a list. | Below is the the instruction that describes the task:
### Input:
Returns all values matching `partial_selector` as a list.
### Response:
def get_all_matches(self, partial_selector):
"""Returns all values matching `partial_selector` as a list."""
matching_selectors = self.matching_selectors(partial_selector... |
def train(dataset, nef, ndf, ngf, nc, batch_size, Z, lr, beta1, epsilon, ctx, check_point, g_dl_weight, output_path, checkpoint_path, data_path, activation,num_epoch, save_after_every, visualize_after_every, show_after_every):
'''adversarial training of the VAE
'''
#encoder
z_mu, z_lv, z = encoder(nef,... | adversarial training of the VAE | Below is the the instruction that describes the task:
### Input:
adversarial training of the VAE
### Response:
def train(dataset, nef, ndf, ngf, nc, batch_size, Z, lr, beta1, epsilon, ctx, check_point, g_dl_weight, output_path, checkpoint_path, data_path, activation,num_epoch, save_after_every, visualize_after_eve... |
def _create_consumer(self):
"""Tries to establing the Kafka consumer connection"""
if not self.closed:
try:
self.logger.debug("Creating new kafka consumer using brokers: " +
str(self.settings['KAFKA_HOSTS']) + ' and topic ' +
... | Tries to establing the Kafka consumer connection | Below is the the instruction that describes the task:
### Input:
Tries to establing the Kafka consumer connection
### Response:
def _create_consumer(self):
"""Tries to establing the Kafka consumer connection"""
if not self.closed:
try:
self.logger.debug("Creating new kaf... |
def create_symmetric_key(self, algorithm, length):
"""
Create a symmetric key.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created key will be compliant.
length(int): The length of the key to be created. ... | Create a symmetric key.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created key will be compliant.
length(int): The length of the key to be created. This value must
be compliant with the constraints of th... | Below is the the instruction that describes the task:
### Input:
Create a symmetric key.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created key will be compliant.
length(int): The length of the key to be created. Th... |
def _create_deserializer(self) -> JsonObjectDeserializer:
"""
Creates a deserializer that is to be used by this decoder.
:return: the deserializer
"""
if self._deserializer_cache is None:
deserializer_cls = type(
"%sInternalDeserializer" % type(self),
... | Creates a deserializer that is to be used by this decoder.
:return: the deserializer | Below is the the instruction that describes the task:
### Input:
Creates a deserializer that is to be used by this decoder.
:return: the deserializer
### Response:
def _create_deserializer(self) -> JsonObjectDeserializer:
"""
Creates a deserializer that is to be used by this decoder.
... |
def as_coeff_unit(self):
"""Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import u... | Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import unyt as u
>>> unit = (u.m**2/... | Below is the the instruction that describes the task:
### Input:
Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
... |
def calculate_pertubations(self):
""" experimental method to calculate finite difference parameter
pertubations. The pertubation values are added to the
Pst.parameter_data attribute
Note
----
user beware!
"""
self.build_increments()
self.paramet... | experimental method to calculate finite difference parameter
pertubations. The pertubation values are added to the
Pst.parameter_data attribute
Note
----
user beware! | Below is the the instruction that describes the task:
### Input:
experimental method to calculate finite difference parameter
pertubations. The pertubation values are added to the
Pst.parameter_data attribute
Note
----
user beware!
### Response:
def calculate_pertubations(... |
def isample(self, *args, **kwds):
"""
Samples in interactive mode. Main thread of control stays in this function.
"""
self._exc_info = None
out = kwds.pop('out', sys.stdout)
kwds['progress_bar'] = False
def samp_targ(*args, **kwds):
try:
... | Samples in interactive mode. Main thread of control stays in this function. | Below is the the instruction that describes the task:
### Input:
Samples in interactive mode. Main thread of control stays in this function.
### Response:
def isample(self, *args, **kwds):
"""
Samples in interactive mode. Main thread of control stays in this function.
"""
self._exc_... |
def derivativeX(self,x,y):
'''
Evaluate the first derivative with respect to x of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; should be of same shape ... | Evaluate the first derivative with respect to x of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; should be of same shape as x.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Evaluate the first derivative with respect to x of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; sh... |
def load(self, playerName=None):
"""retrieve the PlayerRecord settings from saved disk file"""
if playerName: # switch the PlayerRecord this object describes
self.name = playerName # preset value to load self.filename
try:
with open(self.filename, "rb") as f:
... | retrieve the PlayerRecord settings from saved disk file | Below is the the instruction that describes the task:
### Input:
retrieve the PlayerRecord settings from saved disk file
### Response:
def load(self, playerName=None):
"""retrieve the PlayerRecord settings from saved disk file"""
if playerName: # switch the PlayerRecord this object describes
... |
def main(args=None):
"""
Program entry point.
"""
if args is None:
args = process_args()
print('Parsing and resolving model: '+args.lems_file)
model = Model()
if args.I is not None:
for dir in args.I:
model.add_include_directory(dir)
model.import_fro... | Program entry point. | Below is the the instruction that describes the task:
### Input:
Program entry point.
### Response:
def main(args=None):
"""
Program entry point.
"""
if args is None:
args = process_args()
print('Parsing and resolving model: '+args.lems_file)
model = Model()
if args.I ... |
def __set_labels(self, labels):
"""
Add a label on the document.
"""
with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'w') \
as file_desc:
for label in labels:
file_desc.write("%s,%s\n" % (label.name,
... | Add a label on the document. | Below is the the instruction that describes the task:
### Input:
Add a label on the document.
### Response:
def __set_labels(self, labels):
"""
Add a label on the document.
"""
with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'w') \
as file_desc:
... |
def reload(self):
"""Reload the metadata for this instance.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_instance]
:end-before: [END bigtable_reload_instance]
"""
instance_pb = self._client.instance_admin_client.get_i... | Reload the metadata for this instance.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_instance]
:end-before: [END bigtable_reload_instance] | Below is the the instruction that describes the task:
### Input:
Reload the metadata for this instance.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_instance]
:end-before: [END bigtable_reload_instance]
### Response:
def reload(self):
... |
def execute_sql(self, *args, **kwargs):
"""Sync execute SQL query, `allow_sync` must be set to True.
"""
assert self._allow_sync, (
"Error, sync query is not allowed! Call the `.set_allow_sync()` "
"or use the `.allow_sync()` context manager.")
if self._allow_sync... | Sync execute SQL query, `allow_sync` must be set to True. | Below is the the instruction that describes the task:
### Input:
Sync execute SQL query, `allow_sync` must be set to True.
### Response:
def execute_sql(self, *args, **kwargs):
"""Sync execute SQL query, `allow_sync` must be set to True.
"""
assert self._allow_sync, (
"Error, sy... |
def get_driver_whitelist(driver): # noqa: E501
"""Retrieve the whitelist in the driver
Retrieve the whitelist in the driver # noqa: E501
:param driver: The driver to use for the request. ie. github
:type driver: str
:rtype: Response
"""
response = errorIfUnauthorized(role='admin')
i... | Retrieve the whitelist in the driver
Retrieve the whitelist in the driver # noqa: E501
:param driver: The driver to use for the request. ie. github
:type driver: str
:rtype: Response | Below is the the instruction that describes the task:
### Input:
Retrieve the whitelist in the driver
Retrieve the whitelist in the driver # noqa: E501
:param driver: The driver to use for the request. ie. github
:type driver: str
:rtype: Response
### Response:
def get_driver_whitelist(driver): ... |
def _sql(self, sql: str, params=()):
"""
:deprecated: use self.sql instead
"""
statement = SingleSqlStatement(sql)
return self.statement(statement).execute_for_params(params).cursor | :deprecated: use self.sql instead | Below is the the instruction that describes the task:
### Input:
:deprecated: use self.sql instead
### Response:
def _sql(self, sql: str, params=()):
"""
:deprecated: use self.sql instead
"""
statement = SingleSqlStatement(sql)
return self.statement(statement).execute_for_pa... |
def _prompt_username(prompt="Username: ", prefill=None):
"""Prompt the user for username."""
if prefill:
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt).strip()
except EOFError:
print()
finally:
readline.set_startup_hook() | Prompt the user for username. | Below is the the instruction that describes the task:
### Input:
Prompt the user for username.
### Response:
def _prompt_username(prompt="Username: ", prefill=None):
"""Prompt the user for username."""
if prefill:
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
re... |
def to_database(self, manager=None):
"""Send the model to the PyBEL database
This function wraps :py:func:`pybel.to_database`.
Parameters
----------
manager : Optional[pybel.manager.Manager]
A PyBEL database manager. If none, first checks the PyBEL
confi... | Send the model to the PyBEL database
This function wraps :py:func:`pybel.to_database`.
Parameters
----------
manager : Optional[pybel.manager.Manager]
A PyBEL database manager. If none, first checks the PyBEL
configuration for ``PYBEL_CONNECTION`` then checks th... | Below is the the instruction that describes the task:
### Input:
Send the model to the PyBEL database
This function wraps :py:func:`pybel.to_database`.
Parameters
----------
manager : Optional[pybel.manager.Manager]
A PyBEL database manager. If none, first checks the Py... |
def on_page_layout_choice(self, event):
"""Page layout choice event handler"""
width, height = self.paper_sizes_points[event.GetString()]
self.page_width_text_ctrl.SetValue(str(width / 72.0))
self.page_height_text_ctrl.SetValue(str(height / 72.0))
event.Skip() | Page layout choice event handler | Below is the the instruction that describes the task:
### Input:
Page layout choice event handler
### Response:
def on_page_layout_choice(self, event):
"""Page layout choice event handler"""
width, height = self.paper_sizes_points[event.GetString()]
self.page_width_text_ctrl.SetValue(str(w... |
def access_array(self, id_, lineno, scope=None, default_type=None):
"""
Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array.
"""
if not self.check_i... | Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array. | Below is the the instruction that describes the task:
### Input:
Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array.
### Response:
def access_array(self, id_, lineno, scope=N... |
def fields_to_dict(fields, type_=OrderedDict):
"""Convert a flat list of key/values into an OrderedDict"""
fields_iterator = iter(fields)
return type_(zip(fields_iterator, fields_iterator)) | Convert a flat list of key/values into an OrderedDict | Below is the the instruction that describes the task:
### Input:
Convert a flat list of key/values into an OrderedDict
### Response:
def fields_to_dict(fields, type_=OrderedDict):
"""Convert a flat list of key/values into an OrderedDict"""
fields_iterator = iter(fields)
return type_(zip(fields_iterator... |
def _pool_event_refresh_cb(conn, pool, opaque):
'''
Storage pool refresh events handler
'''
_salt_send_event(opaque, conn, {
'pool': {
'name': pool.name(),
'uuid': pool.UUIDString()
},
'event': opaque['event']
}) | Storage pool refresh events handler | Below is the the instruction that describes the task:
### Input:
Storage pool refresh events handler
### Response:
def _pool_event_refresh_cb(conn, pool, opaque):
'''
Storage pool refresh events handler
'''
_salt_send_event(opaque, conn, {
'pool': {
'name': pool.name(),
... |
def check_argument_types(cllable = None, call_args = None, clss = None, caller_level = 0):
"""Can be called from within a function or method to apply typechecking to
the arguments that were passed in by the caller. Checking is applied w.r.t.
type hints of the function or method hosting the call to check_arg... | Can be called from within a function or method to apply typechecking to
the arguments that were passed in by the caller. Checking is applied w.r.t.
type hints of the function or method hosting the call to check_argument_types. | Below is the the instruction that describes the task:
### Input:
Can be called from within a function or method to apply typechecking to
the arguments that were passed in by the caller. Checking is applied w.r.t.
type hints of the function or method hosting the call to check_argument_types.
### Response:
d... |
def user_loc_value_to_class(axis_tag, user_loc):
"""Return the OS/2 weight or width class that is closest to the provided
user location. For weight the user location is between 0 and 1000 and for
width it is a percentage.
>>> user_loc_value_to_class('wght', 310)
310
>>> user_loc_value_to_class(... | Return the OS/2 weight or width class that is closest to the provided
user location. For weight the user location is between 0 and 1000 and for
width it is a percentage.
>>> user_loc_value_to_class('wght', 310)
310
>>> user_loc_value_to_class('wdth', 62)
2 | Below is the the instruction that describes the task:
### Input:
Return the OS/2 weight or width class that is closest to the provided
user location. For weight the user location is between 0 and 1000 and for
width it is a percentage.
>>> user_loc_value_to_class('wght', 310)
310
>>> user_loc_va... |
def objects(self):
"""
The objects in this listing.
:type: List[:class:`.ObjectInfo`]
"""
return [ObjectInfo(o, self._instance, self._bucket, self._client)
for o in self._proto.object] | The objects in this listing.
:type: List[:class:`.ObjectInfo`] | Below is the the instruction that describes the task:
### Input:
The objects in this listing.
:type: List[:class:`.ObjectInfo`]
### Response:
def objects(self):
"""
The objects in this listing.
:type: List[:class:`.ObjectInfo`]
"""
return [ObjectInfo(o, self._insta... |
def team_2_json(self):
"""
transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("Team.team_2_json")
json_obj = {
'teamID': self.id,
'teamName': self.name,
'teamDescription': self.descrip... | transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj | Below is the the instruction that describes the task:
### Input:
transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj
### Response:
def team_2_json(self):
"""
transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj
... |
def show_mode_indicator(viewer, tf, corner='ur'):
"""Show a keyboard mode indicator in one of the corners.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the mark; else remove it if prese... | Show a keyboard mode indicator in one of the corners.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the mark; else remove it if present.
corner : str
One of 'll', 'lr', 'ul' or ... | Below is the the instruction that describes the task:
### Input:
Show a keyboard mode indicator in one of the corners.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the mark; else remove... |
def _configure_logging(kwargs, extract=True):
"""Requests the logging manager to configure logging.
:param extract:
If naming data should be extracted from the trajectory
"""
try:
logging_manager = kwargs['logging_manager']
if extract:
logging_manager.extract_repla... | Requests the logging manager to configure logging.
:param extract:
If naming data should be extracted from the trajectory | Below is the the instruction that describes the task:
### Input:
Requests the logging manager to configure logging.
:param extract:
If naming data should be extracted from the trajectory
### Response:
def _configure_logging(kwargs, extract=True):
"""Requests the logging manager to configure loggi... |
def quickstart():
"""Quickstart wizard for setting up twtxt."""
width = click.get_terminal_size()[0]
width = width if width <= 79 else 79
click.secho("twtxt - quickstart", fg="cyan")
click.secho("==================", fg="cyan")
click.echo()
help_text = "This wizard will generate a basic co... | Quickstart wizard for setting up twtxt. | Below is the the instruction that describes the task:
### Input:
Quickstart wizard for setting up twtxt.
### Response:
def quickstart():
"""Quickstart wizard for setting up twtxt."""
width = click.get_terminal_size()[0]
width = width if width <= 79 else 79
click.secho("twtxt - quickstart", fg="cya... |
def df64bitto32bit(tbl):
"""
Convert a Pandas dataframe from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
tbl : The dataframe to convert
Returns
-------
The converted dataframe
"""
newtbl = pd.DataFrame(index=tbl.index)
for colname in... | Convert a Pandas dataframe from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
tbl : The dataframe to convert
Returns
-------
The converted dataframe | Below is the the instruction that describes the task:
### Input:
Convert a Pandas dataframe from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
tbl : The dataframe to convert
Returns
-------
The converted dataframe
### Response:
def df64bitto32bit(tbl... |
def hsla_to_rgba(h, s, l, a):
""" 0 <= H < 360, 0 <= s,l,a < 1
"""
h = h % 360
s = max(0, min(1, s))
l = max(0, min(1, l))
a = max(0, min(1, a))
c = (1 - abs(2*l - 1)) * s
x = c * (1 - abs(h/60%2 - 1))
m = l - c/2
if h<60:
r, g, b = c, x, 0
elif h<120:
r, g,... | 0 <= H < 360, 0 <= s,l,a < 1 | Below is the the instruction that describes the task:
### Input:
0 <= H < 360, 0 <= s,l,a < 1
### Response:
def hsla_to_rgba(h, s, l, a):
""" 0 <= H < 360, 0 <= s,l,a < 1
"""
h = h % 360
s = max(0, min(1, s))
l = max(0, min(1, l))
a = max(0, min(1, a))
c = (1 - abs(2*l - 1)) * s
x ... |
def text_channels(self):
"""List[:class:`TextChannel`]: A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)]
r.sort(key=lambda c: (... | List[:class:`TextChannel`]: A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom. | Below is the the instruction that describes the task:
### Input:
List[:class:`TextChannel`]: A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
### Response:
def text_channels(self):
"""List[:class:`TextChannel`]: A list of te... |
def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs):
"""
Array or Matrix of random date generator.
:returns: 1d or 2d array of datetime.date
"""
if end is None:
end = date.today()
start = parser.parse_date(start)
end = parser.parse_date(end)
_assert_correct_star... | Array or Matrix of random date generator.
:returns: 1d or 2d array of datetime.date | Below is the the instruction that describes the task:
### Input:
Array or Matrix of random date generator.
:returns: 1d or 2d array of datetime.date
### Response:
def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs):
"""
Array or Matrix of random date generator.
:returns: 1d or 2d... |
def extract_path_ext(path, default_ext=None):
"""
Extract file extension (without dot) from `path` or return `default_ext` if
path does not contain a valid extension.
"""
ext = None
_, dotext = os.path.splitext(path)
if dotext:
ext = dotext[1:]
if not ext and default_ext:
... | Extract file extension (without dot) from `path` or return `default_ext` if
path does not contain a valid extension. | Below is the the instruction that describes the task:
### Input:
Extract file extension (without dot) from `path` or return `default_ext` if
path does not contain a valid extension.
### Response:
def extract_path_ext(path, default_ext=None):
"""
Extract file extension (without dot) from `path` or retur... |
def lookup(sock, domain, cache = None):
"""lookup an I2P domain name, returning a Destination instance"""
domain = normalize_domain(domain)
# cache miss, perform lookup
reply = sam_cmd(sock, "NAMING LOOKUP NAME=%s" % domain)
b64_dest = reply.get('VALUE')
if b64_dest:
dest = Dest(b64_de... | lookup an I2P domain name, returning a Destination instance | Below is the the instruction that describes the task:
### Input:
lookup an I2P domain name, returning a Destination instance
### Response:
def lookup(sock, domain, cache = None):
"""lookup an I2P domain name, returning a Destination instance"""
domain = normalize_domain(domain)
# cache miss, perform l... |
def confd_state_webui_listen_tcp_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
webui = ET.SubElement(confd_state, "webui")
listen = ET.SubE... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def confd_state_webui_listen_tcp_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.... |
def annotation(args):
"""
%prog annotation blastfile > annotations
Create simple two column files from the first two coluns in blastfile. Use
--queryids and --subjectids to switch IDs or descriptions.
"""
from jcvi.formats.base import DictFile
p = OptionParser(annotation.__doc__)
p.add... | %prog annotation blastfile > annotations
Create simple two column files from the first two coluns in blastfile. Use
--queryids and --subjectids to switch IDs or descriptions. | Below is the the instruction that describes the task:
### Input:
%prog annotation blastfile > annotations
Create simple two column files from the first two coluns in blastfile. Use
--queryids and --subjectids to switch IDs or descriptions.
### Response:
def annotation(args):
"""
%prog annotation b... |
def stats_per100(self, kind='R', summary=False):
"""Returns a DataFrame of per-100-possession stats."""
return self._get_stats_table('per_poss', kind=kind, summary=summary) | Returns a DataFrame of per-100-possession stats. | Below is the the instruction that describes the task:
### Input:
Returns a DataFrame of per-100-possession stats.
### Response:
def stats_per100(self, kind='R', summary=False):
"""Returns a DataFrame of per-100-possession stats."""
return self._get_stats_table('per_poss', kind=kind, summary=summary... |
def hincrby(self, key, field, increment=1):
"""Increment the integer value of a hash field by the given number."""
return self.execute(b'HINCRBY', key, field, increment) | Increment the integer value of a hash field by the given number. | Below is the the instruction that describes the task:
### Input:
Increment the integer value of a hash field by the given number.
### Response:
def hincrby(self, key, field, increment=1):
"""Increment the integer value of a hash field by the given number."""
return self.execute(b'HINCRBY', key, fie... |
def createGWB(psr, Amp, gam, noCorr=False, seed=None, turnover=False,
clm=[N.sqrt(4.0*N.pi)], lmax=0, f0=1e-9, beta=1,
power=1, userSpec=None, npts=600, howml=10):
"""
Function to create GW-induced residuals from a stochastic GWB as defined
in Chamberlin, Creighton, Demorest, et ... | Function to create GW-induced residuals from a stochastic GWB as defined
in Chamberlin, Creighton, Demorest, et al. (2014).
:param psr: pulsar object for single pulsar
:param Amp: Amplitude of red noise in GW units
:param gam: Red noise power law spectral index
:param noCorr: Add red noise wit... | Below is the the instruction that describes the task:
### Input:
Function to create GW-induced residuals from a stochastic GWB as defined
in Chamberlin, Creighton, Demorest, et al. (2014).
:param psr: pulsar object for single pulsar
:param Amp: Amplitude of red noise in GW units
:param gam: Re... |
def memory():
"""Determine the machine's memory specifications.
Returns
-------
mem_info : dictonary
Holds the current values for the total, free and used memory of the system.
"""
mem_info = {}
if platform.linux_distribution()[0]:
with open('/proc/meminfo') as file:
... | Determine the machine's memory specifications.
Returns
-------
mem_info : dictonary
Holds the current values for the total, free and used memory of the system. | Below is the the instruction that describes the task:
### Input:
Determine the machine's memory specifications.
Returns
-------
mem_info : dictonary
Holds the current values for the total, free and used memory of the system.
### Response:
def memory():
"""Determine the machine's memory spe... |
def get_cluster_assignment(self):
"""Fetch the cluster layout in form of assignment from zookeeper"""
plan = self.get_cluster_plan()
assignment = {}
for elem in plan['partitions']:
assignment[
(elem['topic'], elem['partition'])
] = elem['replicas']... | Fetch the cluster layout in form of assignment from zookeeper | Below is the the instruction that describes the task:
### Input:
Fetch the cluster layout in form of assignment from zookeeper
### Response:
def get_cluster_assignment(self):
"""Fetch the cluster layout in form of assignment from zookeeper"""
plan = self.get_cluster_plan()
assignment = {}
... |
def orthologs_iterator(fo, version):
"""Ortholog node and edge iterator"""
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0)
with gzip.open(fo, "rt") as f:
for line in f:
edge = json.loads(line)
if "metadata" in edge:
source = edg... | Ortholog node and edge iterator | Below is the the instruction that describes the task:
### Input:
Ortholog node and edge iterator
### Response:
def orthologs_iterator(fo, version):
"""Ortholog node and edge iterator"""
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0)
with gzip.open(fo, "rt") as f:
... |
def extract_pairs(fastqfile, p1fw, p2fw, fragsfw, p, suffix=False):
"""
Take fastqfile and array of pair ID, extract adjacent pairs to outfile.
Perform check on numbers when done. p1fw, p2fw is a list of file handles,
each for one end. p is a Pairs instance.
"""
fp = open(fastqfile)
currentI... | Take fastqfile and array of pair ID, extract adjacent pairs to outfile.
Perform check on numbers when done. p1fw, p2fw is a list of file handles,
each for one end. p is a Pairs instance. | Below is the the instruction that describes the task:
### Input:
Take fastqfile and array of pair ID, extract adjacent pairs to outfile.
Perform check on numbers when done. p1fw, p2fw is a list of file handles,
each for one end. p is a Pairs instance.
### Response:
def extract_pairs(fastqfile, p1fw, p2fw, ... |
def join_images(img_files, out_file):
"""Join the list of images into the out file"""
images = [PIL.Image.open(f) for f in img_files]
joined = PIL.Image.new(
'RGB',
(sum(i.size[0] for i in images), max(i.size[1] for i in images))
)
left = 0
for img in images:
joined.paste... | Join the list of images into the out file | Below is the the instruction that describes the task:
### Input:
Join the list of images into the out file
### Response:
def join_images(img_files, out_file):
"""Join the list of images into the out file"""
images = [PIL.Image.open(f) for f in img_files]
joined = PIL.Image.new(
'RGB',
(... |
def pass_allowedremoterelieve_v1(self):
"""Update the outlet link sequence |dam_outlets.R|."""
flu = self.sequences.fluxes.fastaccess
sen = self.sequences.senders.fastaccess
sen.r[0] += flu.allowedremoterelieve | Update the outlet link sequence |dam_outlets.R|. | Below is the the instruction that describes the task:
### Input:
Update the outlet link sequence |dam_outlets.R|.
### Response:
def pass_allowedremoterelieve_v1(self):
"""Update the outlet link sequence |dam_outlets.R|."""
flu = self.sequences.fluxes.fastaccess
sen = self.sequences.senders.fastaccess
... |
def __add_handler_factory(self, svc_ref):
# type: (ServiceReference) -> None
"""
Stores a new handler factory
:param svc_ref: ServiceReference of the new handler factory
"""
with self.__handlers_lock:
# Get the handler ID
handler_id = svc_ref.get_... | Stores a new handler factory
:param svc_ref: ServiceReference of the new handler factory | Below is the the instruction that describes the task:
### Input:
Stores a new handler factory
:param svc_ref: ServiceReference of the new handler factory
### Response:
def __add_handler_factory(self, svc_ref):
# type: (ServiceReference) -> None
"""
Stores a new handler factory
... |
def compile_with_instrumentation(self,
container: Container,
verbose: bool = False
) -> CompilationOutcome:
"""
Attempts to compile the program inside a given container with
instrumenta... | Attempts to compile the program inside a given container with
instrumentation enabled.
See: `Container.compile` | Below is the the instruction that describes the task:
### Input:
Attempts to compile the program inside a given container with
instrumentation enabled.
See: `Container.compile`
### Response:
def compile_with_instrumentation(self,
container: Container,
... |
def transform(self, transform, node):
"""
Transforms a node following the transform especification
:param transform: Transform node
:type transform: lxml.etree.Element
:param node: Element to transform
:type node: str
:return: Transformed node in a String
... | Transforms a node following the transform especification
:param transform: Transform node
:type transform: lxml.etree.Element
:param node: Element to transform
:type node: str
:return: Transformed node in a String | Below is the the instruction that describes the task:
### Input:
Transforms a node following the transform especification
:param transform: Transform node
:type transform: lxml.etree.Element
:param node: Element to transform
:type node: str
:return: Transformed node in a Stri... |
def adjust(
self,
aba_parameters,
boundary_indices,
real_wave_mfcc,
text_file,
allow_arbitrary_shift=False
):
"""
Adjust the boundaries of the text map
using the algorithm and parameters
specified in the constructor,
storing the... | Adjust the boundaries of the text map
using the algorithm and parameters
specified in the constructor,
storing the sync map fragment list internally.
:param dict aba_parameters: a dictionary containing the algorithm and its parameters,
as produced by ... | Below is the the instruction that describes the task:
### Input:
Adjust the boundaries of the text map
using the algorithm and parameters
specified in the constructor,
storing the sync map fragment list internally.
:param dict aba_parameters: a dictionary containing the algorithm an... |
def copy(self, strip=None, deep='ref'):
""" Return another instance of the object, with the same attributes
If deep=True, all attributes themselves are also copies
"""
dd = self.to_dict(strip=strip, deep=deep)
return self.__class__(fromdict=dd) | Return another instance of the object, with the same attributes
If deep=True, all attributes themselves are also copies | Below is the the instruction that describes the task:
### Input:
Return another instance of the object, with the same attributes
If deep=True, all attributes themselves are also copies
### Response:
def copy(self, strip=None, deep='ref'):
""" Return another instance of the object, with the same at... |
def generate_packer_filename(provider, region, builder):
"""Generate a filename to be used by packer.
Args:
provider (str): Name of Spinnaker provider.
region (str): Name of provider region to use.
builder (str): Name of builder process type.
Returns:
str: Generated filenam... | Generate a filename to be used by packer.
Args:
provider (str): Name of Spinnaker provider.
region (str): Name of provider region to use.
builder (str): Name of builder process type.
Returns:
str: Generated filename based on parameters. | Below is the the instruction that describes the task:
### Input:
Generate a filename to be used by packer.
Args:
provider (str): Name of Spinnaker provider.
region (str): Name of provider region to use.
builder (str): Name of builder process type.
Returns:
str: Generated fi... |
def format(self, soup):
"""format a BeautifulSoup document
This will transform the block elements content from
multi-lines text into single line.
This allow us to avoid having to deal with further text
rendering once this step has been done.
"""
# Remove all the... | format a BeautifulSoup document
This will transform the block elements content from
multi-lines text into single line.
This allow us to avoid having to deal with further text
rendering once this step has been done. | Below is the the instruction that describes the task:
### Input:
format a BeautifulSoup document
This will transform the block elements content from
multi-lines text into single line.
This allow us to avoid having to deal with further text
rendering once this step has been done.
##... |
def _init_draw(self):
"""Initializes the drawing of the frames by setting the images to
random colors.
This function is called by TimedAnimation.
"""
if self.original is not None:
self.original.set_data(np.random.random((10, 10, 3)))
self.processed.set_data(n... | Initializes the drawing of the frames by setting the images to
random colors.
This function is called by TimedAnimation. | Below is the the instruction that describes the task:
### Input:
Initializes the drawing of the frames by setting the images to
random colors.
This function is called by TimedAnimation.
### Response:
def _init_draw(self):
"""Initializes the drawing of the frames by setting the images to
... |
def upload(self, thread_uuid, file_path, description=None):
""" Upload a file to LinShare using its rest api.
The uploaded document uuid will be returned"""
url = "threads/%s/entries" % thread_uuid
return self.core.upload(file_path, url, description) | Upload a file to LinShare using its rest api.
The uploaded document uuid will be returned | Below is the the instruction that describes the task:
### Input:
Upload a file to LinShare using its rest api.
The uploaded document uuid will be returned
### Response:
def upload(self, thread_uuid, file_path, description=None):
""" Upload a file to LinShare using its rest api.
The uploaded... |
def adapter_add_nio_binding(self, adapter_number, port_number, nio):
"""
Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port
"""
try:
adapter = self._ad... | Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port | Below is the the instruction that describes the task:
### Input:
Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port
### Response:
def adapter_add_nio_binding(self, adapter_number, port_number... |
def find_connectable_ip(host, port=None):
"""Resolve a hostname to an IP, preferring IPv4 addresses.
We prefer IPv4 so that we don't change behavior from previous IPv4-only
implementations, and because some drivers (e.g., FirefoxDriver) do not
support IPv6 connections.
If the optional port number ... | Resolve a hostname to an IP, preferring IPv4 addresses.
We prefer IPv4 so that we don't change behavior from previous IPv4-only
implementations, and because some drivers (e.g., FirefoxDriver) do not
support IPv6 connections.
If the optional port number is provided, only IPs that listen on the given
... | Below is the the instruction that describes the task:
### Input:
Resolve a hostname to an IP, preferring IPv4 addresses.
We prefer IPv4 so that we don't change behavior from previous IPv4-only
implementations, and because some drivers (e.g., FirefoxDriver) do not
support IPv6 connections.
If the o... |
def safe_logit(p: Union[float, int]) -> Optional[float]:
r"""
Returns the logit (log odds) of its input probability
.. math::
\alpha = logit(p) = log(x / (1 - x))
Args:
p: :math:`p`
Returns:
:math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1].
"""
if ... | r"""
Returns the logit (log odds) of its input probability
.. math::
\alpha = logit(p) = log(x / (1 - x))
Args:
p: :math:`p`
Returns:
:math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1]. | Below is the the instruction that describes the task:
### Input:
r"""
Returns the logit (log odds) of its input probability
.. math::
\alpha = logit(p) = log(x / (1 - x))
Args:
p: :math:`p`
Returns:
:math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1].
### Resp... |
def runPowerNotificationsThread(self):
"""Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop."""
pool = NSAutoreleasePool.alloc().init()
@objc.callbackFor(IOPSNotificationCreateRunLoopSource)
def on_power_source_notification(context):
w... | Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop. | Below is the the instruction that describes the task:
### Input:
Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.
### Response:
def runPowerNotificationsThread(self):
"""Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop."""
... |
async def addFeedData(self, name, items, seqn=None):
'''
Add feed data to the cortex.
'''
return await self.core.addFeedData(name, items, seqn) | Add feed data to the cortex. | Below is the the instruction that describes the task:
### Input:
Add feed data to the cortex.
### Response:
async def addFeedData(self, name, items, seqn=None):
'''
Add feed data to the cortex.
'''
return await self.core.addFeedData(name, items, seqn) |
def parse_job_id(self, output):
"""Take the output of the submit command and return the job id."""
m = self.job_id_regexp.search(output)
if m is not None:
job_id = m.group()
else:
raise LauncherError("Job id couldn't be determined: %s" % output)
self.job_i... | Take the output of the submit command and return the job id. | Below is the the instruction that describes the task:
### Input:
Take the output of the submit command and return the job id.
### Response:
def parse_job_id(self, output):
"""Take the output of the submit command and return the job id."""
m = self.job_id_regexp.search(output)
if m is not No... |
def tags(self, val: str) -> None:
"""
Accessor for record tags (metadata).
:param val: record tags
"""
if not StorageRecord.ok_tags(val):
LOGGER.debug('StorageRecord.__init__ <!< Tags %s must map strings to strings', val)
raise BadRecord('Tags {} must ma... | Accessor for record tags (metadata).
:param val: record tags | Below is the the instruction that describes the task:
### Input:
Accessor for record tags (metadata).
:param val: record tags
### Response:
def tags(self, val: str) -> None:
"""
Accessor for record tags (metadata).
:param val: record tags
"""
if not StorageRecord.... |
def check_ups_input_frequency(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency.
"""
a_frequency = calc_frequency_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_f... | OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency. | Below is the the instruction that describes the task:
### Input:
OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency.
### Response:
def check_ups_input_frequency(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input f... |
def encode_endpoint_props(ed):
"""
Encodes the properties of the given EndpointDescription
"""
props = encode_osgi_props(ed)
props[ECF_RSVC_ID] = "{0}".format(ed.get_remoteservice_id()[1])
props[ECF_ENDPOINT_ID] = "{0}".format(ed.get_container_id()[1])
props[ECF_ENDPOINT_CONTAINERID_NAMESPAC... | Encodes the properties of the given EndpointDescription | Below is the the instruction that describes the task:
### Input:
Encodes the properties of the given EndpointDescription
### Response:
def encode_endpoint_props(ed):
"""
Encodes the properties of the given EndpointDescription
"""
props = encode_osgi_props(ed)
props[ECF_RSVC_ID] = "{0}".format(e... |
def _handler(self, conn):
"""
Connection handler thread. Takes care of communication with the client
and running the proper task or applying a signal.
"""
incoming = self.recv(conn)
self.log(DEBUG, incoming)
try:
# E.g. ['twister', [7, 'invert'], {'gu... | Connection handler thread. Takes care of communication with the client
and running the proper task or applying a signal. | Below is the the instruction that describes the task:
### Input:
Connection handler thread. Takes care of communication with the client
and running the proper task or applying a signal.
### Response:
def _handler(self, conn):
"""
Connection handler thread. Takes care of communication with ... |
def Regions(self,
skip_executable_regions=False,
skip_shared_regions=False,
skip_readonly_regions=False):
"""Iterates over the readable regions for this process.
We use mach_vm_region_recurse here to get a fine grained view of
the process' memory space. The algorit... | Iterates over the readable regions for this process.
We use mach_vm_region_recurse here to get a fine grained view of
the process' memory space. The algorithm is that for some regions,
the function returns is_submap=True which means that there are
actually subregions that we need to examine by increasi... | Below is the the instruction that describes the task:
### Input:
Iterates over the readable regions for this process.
We use mach_vm_region_recurse here to get a fine grained view of
the process' memory space. The algorithm is that for some regions,
the function returns is_submap=True which means that ... |
def get_current_clementine():
"""
Get the current song from clementine.
"""
# mpris_version 2
try:
return get_info_mpris2('clementine')
except DBusErrorResponse:
bus_name = 'org.mpris.clementine'
path = '/Player'
interface = 'org.freedesktop.MediaPlayer'
r... | Get the current song from clementine. | Below is the the instruction that describes the task:
### Input:
Get the current song from clementine.
### Response:
def get_current_clementine():
"""
Get the current song from clementine.
"""
# mpris_version 2
try:
return get_info_mpris2('clementine')
except DBusErrorResponse:
... |
def get_group_participants(self, appointment_group, **kwargs):
"""
List student group participants in this appointment group.
:calls: `GET /api/v1/appointment_groups/:id/groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.groups>`_
... | List student group participants in this appointment group.
:calls: `GET /api/v1/appointment_groups/:id/groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.groups>`_
:param appointment_group: The object or ID of the appointment group.
:type... | Below is the the instruction that describes the task:
### Input:
List student group participants in this appointment group.
:calls: `GET /api/v1/appointment_groups/:id/groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.groups>`_
:param appoin... |
def parse_content(self, content):
"""
Called automatically to process the directory listing(s) contained in
the content.
"""
self.listings = ls_parser.parse(content, self.first_path)
# No longer need the first path found, if any.
delattr(self, 'first_path') | Called automatically to process the directory listing(s) contained in
the content. | Below is the the instruction that describes the task:
### Input:
Called automatically to process the directory listing(s) contained in
the content.
### Response:
def parse_content(self, content):
"""
Called automatically to process the directory listing(s) contained in
the content.
... |
def write(self, process_tile, data):
"""
Write data from process tiles into PNG file(s).
Parameters
----------
process_tile : ``BufferedTile``
must be member of process ``TilePyramid``
"""
data = self._prepare_array(data)
if data.mask.all():
... | Write data from process tiles into PNG file(s).
Parameters
----------
process_tile : ``BufferedTile``
must be member of process ``TilePyramid`` | Below is the the instruction that describes the task:
### Input:
Write data from process tiles into PNG file(s).
Parameters
----------
process_tile : ``BufferedTile``
must be member of process ``TilePyramid``
### Response:
def write(self, process_tile, data):
"""
... |
def schema_org(builder):
# pylint: disable=line-too-long
"""Builds schema.org microdata for DatasetSearch from DatasetBuilder.
Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset
Testing tool: https://search.google.com/structured-data/testing-tool
For Google Dataset Search: http... | Builds schema.org microdata for DatasetSearch from DatasetBuilder.
Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset
Testing tool: https://search.google.com/structured-data/testing-tool
For Google Dataset Search: https://toolbox.google.com/datasetsearch
Microdata format was cho... | Below is the the instruction that describes the task:
### Input:
Builds schema.org microdata for DatasetSearch from DatasetBuilder.
Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset
Testing tool: https://search.google.com/structured-data/testing-tool
For Google Dataset Search:... |
def from_stashy(klass, repository, labor_hours=True):
"""
Handles crafting Code.gov Project for Bitbucket Server repositories
"""
# if not isinstance(repository, stashy.repos.Repository):
# raise TypeError('Repository must be a stashy Repository object')
if not isinst... | Handles crafting Code.gov Project for Bitbucket Server repositories | Below is the the instruction that describes the task:
### Input:
Handles crafting Code.gov Project for Bitbucket Server repositories
### Response:
def from_stashy(klass, repository, labor_hours=True):
"""
Handles crafting Code.gov Project for Bitbucket Server repositories
"""
# if n... |
def find_element(self, by=By.ID, value=None, el_class=None):
"""
usages with ``'one string'`` selector:
- find_element(by: str) -> PageElement
- find_element(by: str, value: T <= PageElement) -> T
usages with ``'webdriver'`` By selector
- find_element(by: str, value: ... | usages with ``'one string'`` selector:
- find_element(by: str) -> PageElement
- find_element(by: str, value: T <= PageElement) -> T
usages with ``'webdriver'`` By selector
- find_element(by: str, value: str) -> PageElement
- find_element(by: str, value: str, el_class: T <= P... | Below is the the instruction that describes the task:
### Input:
usages with ``'one string'`` selector:
- find_element(by: str) -> PageElement
- find_element(by: str, value: T <= PageElement) -> T
usages with ``'webdriver'`` By selector
- find_element(by: str, value: str) -> Page... |
def login(self, login_type, **kwargs):
"""Perform /login.
Args:
login_type (str): The value for the 'type' key.
**kwargs: Additional key/values to add to the JSON submitted.
"""
content = {
"type": login_type
}
for key in kwargs:
... | Perform /login.
Args:
login_type (str): The value for the 'type' key.
**kwargs: Additional key/values to add to the JSON submitted. | Below is the the instruction that describes the task:
### Input:
Perform /login.
Args:
login_type (str): The value for the 'type' key.
**kwargs: Additional key/values to add to the JSON submitted.
### Response:
def login(self, login_type, **kwargs):
"""Perform /login.
... |
def multi_feat_match(template, image, options=None):
"""
Match template and image by extracting multiple features (specified) from it.
:param template: Template image
:param image: Search image
:param options: Options include
- features: List of options for each feature
:return:
""... | Match template and image by extracting multiple features (specified) from it.
:param template: Template image
:param image: Search image
:param options: Options include
- features: List of options for each feature
:return: | Below is the the instruction that describes the task:
### Input:
Match template and image by extracting multiple features (specified) from it.
:param template: Template image
:param image: Search image
:param options: Options include
- features: List of options for each feature
:return:
##... |
def instances_changed(self):
"""True if any instance has changed."""
value = bool(lib.EnvGetInstancesChanged(self._env))
lib.EnvSetInstancesChanged(self._env, int(False))
return value | True if any instance has changed. | Below is the the instruction that describes the task:
### Input:
True if any instance has changed.
### Response:
def instances_changed(self):
"""True if any instance has changed."""
value = bool(lib.EnvGetInstancesChanged(self._env))
lib.EnvSetInstancesChanged(self._env, int(False))
... |
def set_active_vectors(self, name, preference='cell'):
"""Finds the vectors by name and appropriately sets it as active"""
_, field = get_scalar(self, name, preference=preference, info=True)
if field == POINT_DATA_FIELD:
self.GetPointData().SetActiveVectors(name)
elif field =... | Finds the vectors by name and appropriately sets it as active | Below is the the instruction that describes the task:
### Input:
Finds the vectors by name and appropriately sets it as active
### Response:
def set_active_vectors(self, name, preference='cell'):
"""Finds the vectors by name and appropriately sets it as active"""
_, field = get_scalar(self, name, p... |
def pusher_connected(self, data):
"""Called when the pusherclient is connected
"""
# Inform user that pusher is done connecting
self.logger.info("Pusherclient connected")
# Bind the events we want to listen to
self.callback_client.bind("payment_authorized",
... | Called when the pusherclient is connected | Below is the the instruction that describes the task:
### Input:
Called when the pusherclient is connected
### Response:
def pusher_connected(self, data):
"""Called when the pusherclient is connected
"""
# Inform user that pusher is done connecting
self.logger.info("Pusherclient con... |
def construct_mapping(self, node, deep=False):
'''
Build the mapping for YAML
'''
if not isinstance(node, MappingNode):
raise ConstructorError(
None,
None,
'expected a mapping node, but found {0}'.format(node.id),
... | Build the mapping for YAML | Below is the the instruction that describes the task:
### Input:
Build the mapping for YAML
### Response:
def construct_mapping(self, node, deep=False):
'''
Build the mapping for YAML
'''
if not isinstance(node, MappingNode):
raise ConstructorError(
None,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.