code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resnet"
hparams.student_hparams = "resnet_cifar_15"
hparams.optimizer_momentum_nesterov = True
# (base_lr... | Set of hyperparameters. | Below is the the instruction that describes the task:
### Input:
Set of hyperparameters.
### Response:
def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resn... |
def diff_matrix(array_1, array_2, cell_size):
"""
:param array_1: supercell scaled positions respect unit cell
:param array_2: supercell scaled positions respect unit cell
:param cell_size: diference between arrays accounting for periodicity
:return:
"""
array_1_norm = np.array(array_1) / np... | :param array_1: supercell scaled positions respect unit cell
:param array_2: supercell scaled positions respect unit cell
:param cell_size: diference between arrays accounting for periodicity
:return: | Below is the the instruction that describes the task:
### Input:
:param array_1: supercell scaled positions respect unit cell
:param array_2: supercell scaled positions respect unit cell
:param cell_size: diference between arrays accounting for periodicity
:return:
### Response:
def diff_matrix(array_1... |
def layer_description_extractor(layer, node_to_id):
'''get layer description.
'''
layer_input = layer.input
layer_output = layer.output
if layer_input is not None:
if isinstance(layer_input, Iterable):
layer_input = list(map(lambda x: node_to_id[x], layer_input))
else:
... | get layer description. | Below is the the instruction that describes the task:
### Input:
get layer description.
### Response:
def layer_description_extractor(layer, node_to_id):
'''get layer description.
'''
layer_input = layer.input
layer_output = layer.output
if layer_input is not None:
if isinstance(layer_... |
def intervals(self, range_start=datetime.datetime.min, range_end=datetime.datetime.max):
"""Returns a list of tuples of start/end datetimes for when the schedule
is active during the provided range."""
raise NotImplementedError | Returns a list of tuples of start/end datetimes for when the schedule
is active during the provided range. | Below is the the instruction that describes the task:
### Input:
Returns a list of tuples of start/end datetimes for when the schedule
is active during the provided range.
### Response:
def intervals(self, range_start=datetime.datetime.min, range_end=datetime.datetime.max):
"""Returns a list of tup... |
def status(self, job_ids):
"""Get the status of a list of jobs identified by their ids.
Parameters
----------
job_ids : list of str
Identifiers for the jobs.
Returns
-------
list of int
The status codes of the requsted jobs.
"""
... | Get the status of a list of jobs identified by their ids.
Parameters
----------
job_ids : list of str
Identifiers for the jobs.
Returns
-------
list of int
The status codes of the requsted jobs. | Below is the the instruction that describes the task:
### Input:
Get the status of a list of jobs identified by their ids.
Parameters
----------
job_ids : list of str
Identifiers for the jobs.
Returns
-------
list of int
The status codes of t... |
def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente):
"Realiza la consulta remota a ARBA, estableciendo los resultados"
self.limpiar()
try:
self.xml = SimpleXMLElement(XML_ENTRADA_BASE)
self.xml.fechaDesde = fecha_desde
self.xml.fec... | Realiza la consulta remota a ARBA, estableciendo los resultados | Below is the the instruction that describes the task:
### Input:
Realiza la consulta remota a ARBA, estableciendo los resultados
### Response:
def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente):
"Realiza la consulta remota a ARBA, estableciendo los resultados"
self.limp... |
def reset(self):
'''Reset stream.'''
self._text = None
self._markdown = False
self._channel = Incoming.DEFAULT_CHANNEL
self._attachments = []
return self | Reset stream. | Below is the the instruction that describes the task:
### Input:
Reset stream.
### Response:
def reset(self):
'''Reset stream.'''
self._text = None
self._markdown = False
self._channel = Incoming.DEFAULT_CHANNEL
self._attachments = []
return self |
def _read_bits(cls, raw_value):
"""Generator that takes a memory view and provides bitfields from it.
After creating the generator, call `send(None)` to initialise it, and
thereafter call `send(need_bits)` to obtain that many bits.
"""
have_bits = 0
bits = 0
byte_... | Generator that takes a memory view and provides bitfields from it.
After creating the generator, call `send(None)` to initialise it, and
thereafter call `send(need_bits)` to obtain that many bits. | Below is the the instruction that describes the task:
### Input:
Generator that takes a memory view and provides bitfields from it.
After creating the generator, call `send(None)` to initialise it, and
thereafter call `send(need_bits)` to obtain that many bits.
### Response:
def _read_bits(cls, raw... |
def writeRecord(self, f):
"""This is nearly identical to the original the FAU tag is the only tag not writen in the same place, doing so would require changing the parser and lots of extra logic.
"""
if self.bad:
raise BadPubmedRecord("This record cannot be converted to a file as the... | This is nearly identical to the original the FAU tag is the only tag not writen in the same place, doing so would require changing the parser and lots of extra logic. | Below is the the instruction that describes the task:
### Input:
This is nearly identical to the original the FAU tag is the only tag not writen in the same place, doing so would require changing the parser and lots of extra logic.
### Response:
def writeRecord(self, f):
"""This is nearly identical to the ... |
def _py_outvar(parameter, lparams, tab):
"""Returns the code to produce a ctypes output variable for interacting with fortran.
"""
if ("out" in parameter.direction and parameter.D > 0 and ":" in parameter.dimension and
("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)):
... | Returns the code to produce a ctypes output variable for interacting with fortran. | Below is the the instruction that describes the task:
### Input:
Returns the code to produce a ctypes output variable for interacting with fortran.
### Response:
def _py_outvar(parameter, lparams, tab):
"""Returns the code to produce a ctypes output variable for interacting with fortran.
"""
if ("out" ... |
def show_environment(self, name=None):
"""Show environment ``$ tmux show-environment -t [session] <name>``.
Return dict of environment variables for the session or the value of a
specific variable if the name is specified.
Parameters
----------
name : str
th... | Show environment ``$ tmux show-environment -t [session] <name>``.
Return dict of environment variables for the session or the value of a
specific variable if the name is specified.
Parameters
----------
name : str
the environment variable name. such as 'PATH'.
... | Below is the the instruction that describes the task:
### Input:
Show environment ``$ tmux show-environment -t [session] <name>``.
Return dict of environment variables for the session or the value of a
specific variable if the name is specified.
Parameters
----------
name :... |
def sniff_link(url):
"""performs basic heuristics to detect what the URL is"""
protocol = None
link = url.strip()
# heuristics begin
if inurl(['service=CSW', 'request=GetRecords'], link):
protocol = 'OGC:CSW'
elif inurl(['service=SOS', 'request=GetObservation'], link):
protocol... | performs basic heuristics to detect what the URL is | Below is the the instruction that describes the task:
### Input:
performs basic heuristics to detect what the URL is
### Response:
def sniff_link(url):
"""performs basic heuristics to detect what the URL is"""
protocol = None
link = url.strip()
# heuristics begin
if inurl(['service=CSW', 'req... |
def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
"""
url = "/2/shifts/?%s" % urlencode(
{'ids': ",".join(str(s) for s in shifts)})
data = self._delete_resource(url)
return data | Delete existing shifts.
http://dev.wheniwork.com/#delete-shift | Below is the the instruction that describes the task:
### Input:
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
### Response:
def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
"""
url = "/2/shifts/?%... |
def bidcollateral(
ctx, collateral_symbol, collateral_amount, debt_symbol, debt_amount, account
):
""" Bid for collateral in the settlement fund
"""
print_tx(
ctx.bitshares.bid_collateral(
Amount(collateral_amount, collateral_symbol),
Amount(debt_amount, debt_symbol),
... | Bid for collateral in the settlement fund | Below is the the instruction that describes the task:
### Input:
Bid for collateral in the settlement fund
### Response:
def bidcollateral(
ctx, collateral_symbol, collateral_amount, debt_symbol, debt_amount, account
):
""" Bid for collateral in the settlement fund
"""
print_tx(
ctx.bitshar... |
def backup_key(self, name, mount_point=DEFAULT_MOUNT_POINT):
"""Return a plaintext backup of a named key.
The backup contains all the configuration data and keys of all the versions along with the HMAC key. The
response from this endpoint can be used with the /restore endpoint to restore the ke... | Return a plaintext backup of a named key.
The backup contains all the configuration data and keys of all the versions along with the HMAC key. The
response from this endpoint can be used with the /restore endpoint to restore the key.
Supported methods:
GET: /{mount_point}/backup/{n... | Below is the the instruction that describes the task:
### Input:
Return a plaintext backup of a named key.
The backup contains all the configuration data and keys of all the versions along with the HMAC key. The
response from this endpoint can be used with the /restore endpoint to restore the key.
... |
def _to_ned(self):
"""
Switches the reference frame to NED
"""
if self.ref_frame is 'USE':
# Rotate
return utils.use_to_ned(self.tensor), \
utils.use_to_ned(self.tensor_sigma)
elif self.ref_frame is 'NED':
# Alreadt NED
... | Switches the reference frame to NED | Below is the the instruction that describes the task:
### Input:
Switches the reference frame to NED
### Response:
def _to_ned(self):
"""
Switches the reference frame to NED
"""
if self.ref_frame is 'USE':
# Rotate
return utils.use_to_ned(self.tensor), \
... |
def main():
"""Test code called from commandline"""
model = load_model('../data/hmmdefs')
hmm = model.hmms['r-We']
for state_name in hmm.state_names:
print(state_name)
state = model.states[state_name]
print(state.means_)
print(model)
model2 = load_model('../data/prior.hmm... | Test code called from commandline | Below is the the instruction that describes the task:
### Input:
Test code called from commandline
### Response:
def main():
"""Test code called from commandline"""
model = load_model('../data/hmmdefs')
hmm = model.hmms['r-We']
for state_name in hmm.state_names:
print(state_name)
st... |
async def get_stats(self, battletag: str, regions=(EUROPE, KOREA, AMERICAS, CHINA, JAPAN, ANY),
platform=None, _session=None, handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Returns the stats for the profiles on the specified regions and platform. The format for regions ... | Returns the stats for the profiles on the specified regions and platform. The format for regions without a matching user, the format is the same as get_profile.
The stats are returned in a dictionary with a similar format to what https://github.com/SunDwarf/OWAPI/blob/master/api.md#get-apiv3ubattletagstats spec... | Below is the the instruction that describes the task:
### Input:
Returns the stats for the profiles on the specified regions and platform. The format for regions without a matching user, the format is the same as get_profile.
The stats are returned in a dictionary with a similar format to what https://githu... |
def write_block(self, block, data, erase=True):
"""Write an 8-byte data block at address (block * 8). The target
bytes are zero'd first if *erase* is True.
"""
if block < 0 or block > 255:
raise ValueError("invalid block number")
log.debug("write block {0}".format(bl... | Write an 8-byte data block at address (block * 8). The target
bytes are zero'd first if *erase* is True. | Below is the the instruction that describes the task:
### Input:
Write an 8-byte data block at address (block * 8). The target
bytes are zero'd first if *erase* is True.
### Response:
def write_block(self, block, data, erase=True):
"""Write an 8-byte data block at address (block * 8). The target
... |
def init(port=6600, server="localhost"):
"""Initialize mpd."""
client = mpd.MPDClient()
try:
client.connect(server, port)
return client
except ConnectionRefusedError:
print("error: Connection refused to mpd/mopidy.")
os._exit(1) | Initialize mpd. | Below is the the instruction that describes the task:
### Input:
Initialize mpd.
### Response:
def init(port=6600, server="localhost"):
"""Initialize mpd."""
client = mpd.MPDClient()
try:
client.connect(server, port)
return client
except ConnectionRefusedError:
print("erro... |
def scan_chain_len(self, scan_chain):
"""Retrieves and returns the number of bits in the scan chain.
Args:
self (JLink): the ``JLink`` instance
scan_chain (int): scan chain to be measured
Returns:
Number of bits in the specified scan chain.
Raises:
... | Retrieves and returns the number of bits in the scan chain.
Args:
self (JLink): the ``JLink`` instance
scan_chain (int): scan chain to be measured
Returns:
Number of bits in the specified scan chain.
Raises:
JLinkException: on error. | Below is the the instruction that describes the task:
### Input:
Retrieves and returns the number of bits in the scan chain.
Args:
self (JLink): the ``JLink`` instance
scan_chain (int): scan chain to be measured
Returns:
Number of bits in the specified scan chain.
... |
def consume_token(self, tokens, index, tokens_len):
"""Consume a token.
Returns a tuple of (tokens, tokens_len, index) when consumption is
completed and tokens have been merged together.
"""
del tokens_len
if tokens[index].type == TokenType.EndInlineRST:
ret... | Consume a token.
Returns a tuple of (tokens, tokens_len, index) when consumption is
completed and tokens have been merged together. | Below is the the instruction that describes the task:
### Input:
Consume a token.
Returns a tuple of (tokens, tokens_len, index) when consumption is
completed and tokens have been merged together.
### Response:
def consume_token(self, tokens, index, tokens_len):
"""Consume a token.
... |
def add_borders(Figs, titles, border_color='#000000', text_color='#800080', con_id=""):
"""
Formatting for generating plots on the server
Default border color: black
Default text color: purple
"""
def split_title(s):
"""
Add '\n's to split of overly long titles
"""
... | Formatting for generating plots on the server
Default border color: black
Default text color: purple | Below is the the instruction that describes the task:
### Input:
Formatting for generating plots on the server
Default border color: black
Default text color: purple
### Response:
def add_borders(Figs, titles, border_color='#000000', text_color='#800080', con_id=""):
"""
Formatting for generating ... |
def set_power(self, state):
"""Sets the power state of the smart plug."""
packet = bytearray(16)
packet[0] = 2
if self.check_nightlight():
packet[4] = 3 if state else 2
else:
packet[4] = 1 if state else 0
self.send_packet(0x6a, packet) | Sets the power state of the smart plug. | Below is the the instruction that describes the task:
### Input:
Sets the power state of the smart plug.
### Response:
def set_power(self, state):
"""Sets the power state of the smart plug."""
packet = bytearray(16)
packet[0] = 2
if self.check_nightlight():
packet[4] = 3 if state else 2
e... |
def order_shares(id_or_ins, amount, price=None, style=None):
"""
落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str`
:param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
... | 落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str`
:param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
:param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `st... | Below is the the instruction that describes the task:
### Input:
落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str`
:param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
:pa... |
def lookup_family(family):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L94.
Positional arguments:
family -- integer.
Returns:
genl_ops class instance or None.
"""
for ops in nl_list_for_each_entry(genl_ops(), genl_ops_list, 'o_list'):
if ops.o_id == family:... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L94.
Positional arguments:
family -- integer.
Returns:
genl_ops class instance or None. | Below is the the instruction that describes the task:
### Input:
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L94.
Positional arguments:
family -- integer.
Returns:
genl_ops class instance or None.
### Response:
def lookup_family(family):
"""https://github.com/thom311/lib... |
def catch(cls, catch_exception, config='default'):
"""Decorator class method catching exceptions raised by the wrapped
member function. When exception is caught, the decorator waits
for an amount of time specified in the `ha_config`.
:param catch_exception: Exception class or tuple of e... | Decorator class method catching exceptions raised by the wrapped
member function. When exception is caught, the decorator waits
for an amount of time specified in the `ha_config`.
:param catch_exception: Exception class or tuple of exception classes. | Below is the the instruction that describes the task:
### Input:
Decorator class method catching exceptions raised by the wrapped
member function. When exception is caught, the decorator waits
for an amount of time specified in the `ha_config`.
:param catch_exception: Exception class or tup... |
def _guess_type_from_validator(validator):
"""
Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator
in order to unpack the validators.
:param validator:
:return: the type of attribute declared in an inner 'instance_of' validator (if any... | Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator
in order to unpack the validators.
:param validator:
:return: the type of attribute declared in an inner 'instance_of' validator (if any is found, the first one is used)
or None if no inn... | Below is the the instruction that describes the task:
### Input:
Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator
in order to unpack the validators.
:param validator:
:return: the type of attribute declared in an inner 'instance_of' val... |
def get_search_results(self, request, queryset, search_term):
"""
Returns a tuple containing a queryset to implement the search,
and a boolean indicating if the results may contain duplicates.
"""
# Apply keyword searches.
def construct_search(field_name):
if ... | Returns a tuple containing a queryset to implement the search,
and a boolean indicating if the results may contain duplicates. | Below is the the instruction that describes the task:
### Input:
Returns a tuple containing a queryset to implement the search,
and a boolean indicating if the results may contain duplicates.
### Response:
def get_search_results(self, request, queryset, search_term):
"""
Returns a tuple con... |
def footprint(self):
"""Find and return footprint as Shapely Polygon."""
# Check whether product or granule footprint needs to be calculated.
tile_geocoding = self._metadata.iter("Tile_Geocoding").next()
resolution = 10
searchstring = ".//*[@resolution='%s']" % resolution
... | Find and return footprint as Shapely Polygon. | Below is the the instruction that describes the task:
### Input:
Find and return footprint as Shapely Polygon.
### Response:
def footprint(self):
"""Find and return footprint as Shapely Polygon."""
# Check whether product or granule footprint needs to be calculated.
tile_geocoding = self._m... |
def _read_header(self):
"""Read the header info"""
data = np.fromfile(self.filename,
dtype=native_header, count=1)
self.header.update(recarray2dict(data))
data15hd = self.header['15_DATA_HEADER']
sec15hd = self.header['15_SECONDARY_PRODUCT_HEADER']
... | Read the header info | Below is the the instruction that describes the task:
### Input:
Read the header info
### Response:
def _read_header(self):
"""Read the header info"""
data = np.fromfile(self.filename,
dtype=native_header, count=1)
self.header.update(recarray2dict(data))
... |
def _MigrationFilenameToInt(fname):
"""Converts migration filename to a migration number."""
base, _ = os.path.splitext(fname)
return int(base) | Converts migration filename to a migration number. | Below is the the instruction that describes the task:
### Input:
Converts migration filename to a migration number.
### Response:
def _MigrationFilenameToInt(fname):
"""Converts migration filename to a migration number."""
base, _ = os.path.splitext(fname)
return int(base) |
def delete_cas(self, key, *, index):
"""Deletes the Key with check-and-set semantics.
Parameters:
key (str): Key to delete
index (ObjectIndex): Index ID
The Key will only be deleted if its current modify index matches
the supplied Index
"""
self.... | Deletes the Key with check-and-set semantics.
Parameters:
key (str): Key to delete
index (ObjectIndex): Index ID
The Key will only be deleted if its current modify index matches
the supplied Index | Below is the the instruction that describes the task:
### Input:
Deletes the Key with check-and-set semantics.
Parameters:
key (str): Key to delete
index (ObjectIndex): Index ID
The Key will only be deleted if its current modify index matches
the supplied Index
### ... |
def normalize(self, text):
""" Normalizes text.
Converts to lowercase,
Unicode NFC normalization
and removes mentions and links
:param text: Text to be normalized.
"""
#print 'Normalize...\n'
text = text.lower()
text = unicodedata.... | Normalizes text.
Converts to lowercase,
Unicode NFC normalization
and removes mentions and links
:param text: Text to be normalized. | Below is the the instruction that describes the task:
### Input:
Normalizes text.
Converts to lowercase,
Unicode NFC normalization
and removes mentions and links
:param text: Text to be normalized.
### Response:
def normalize(self, text):
""" Normalizes text... |
def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` clas... | Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class, a message is printed to t... | Below is the the instruction that describes the task:
### Input:
Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised us... |
def _print_download_progress_msg(self, msg, flush=False):
"""Prints a message about download progress either to the console or TF log.
Args:
msg: Message to print.
flush: Indicates whether to flush the output (only used in interactive
mode).
"""
if self._interactive_mode():
... | Prints a message about download progress either to the console or TF log.
Args:
msg: Message to print.
flush: Indicates whether to flush the output (only used in interactive
mode). | Below is the the instruction that describes the task:
### Input:
Prints a message about download progress either to the console or TF log.
Args:
msg: Message to print.
flush: Indicates whether to flush the output (only used in interactive
mode).
### Response:
def _print_download_progr... |
def _get_admin_change_url(self, model, context):
"""
Returns the admin change url.
"""
app_label = model._meta.app_label
return reverse('%s:%s_%s_changelist' % (get_admin_site_name(context),
app_label,
... | Returns the admin change url. | Below is the the instruction that describes the task:
### Input:
Returns the admin change url.
### Response:
def _get_admin_change_url(self, model, context):
"""
Returns the admin change url.
"""
app_label = model._meta.app_label
return reverse('%s:%s_%s_changelist' % (get_a... |
def _bb_intensity(self, Teff, photon_weighted=False):
"""
Computes mean passband intensity using blackbody atmosphere:
I_pb^E = \int_\lambda I(\lambda) P(\lambda) d\lambda / \int_\lambda P(\lambda) d\lambda
I_pb^P = \int_\lambda \lambda I(\lambda) P(\lambda) d\lambda / \int_\lambda \lam... | Computes mean passband intensity using blackbody atmosphere:
I_pb^E = \int_\lambda I(\lambda) P(\lambda) d\lambda / \int_\lambda P(\lambda) d\lambda
I_pb^P = \int_\lambda \lambda I(\lambda) P(\lambda) d\lambda / \int_\lambda \lambda P(\lambda) d\lambda
Superscripts E and P stand for energy and... | Below is the the instruction that describes the task:
### Input:
Computes mean passband intensity using blackbody atmosphere:
I_pb^E = \int_\lambda I(\lambda) P(\lambda) d\lambda / \int_\lambda P(\lambda) d\lambda
I_pb^P = \int_\lambda \lambda I(\lambda) P(\lambda) d\lambda / \int_\lambda \lambda P... |
def cpu():
'''
Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.cpu
'''
# Test data
max_primes = [500, 1000, 2500, 5000]
# Initializing the test variables
test_command = 'sysbench --test=cpu --cpu-max-prime={0} run'
resul... | Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.cpu | Below is the the instruction that describes the task:
### Input:
Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.cpu
### Response:
def cpu():
'''
Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
... |
def get_logging_level(debug):
"""Returns logging level based on boolean"""
level = logging.INFO
if debug:
level = logging.DEBUG
return level | Returns logging level based on boolean | Below is the the instruction that describes the task:
### Input:
Returns logging level based on boolean
### Response:
def get_logging_level(debug):
"""Returns logging level based on boolean"""
level = logging.INFO
if debug:
level = logging.DEBUG
return level |
def quantiles(self, quantiles,
axis=0, strict=False,
recompute_integral=False):
"""
Calculate the quantiles of this histogram.
Parameters
----------
quantiles : list or int
A list of cumulative probabilities or an integer used to ... | Calculate the quantiles of this histogram.
Parameters
----------
quantiles : list or int
A list of cumulative probabilities or an integer used to determine
equally spaced values between 0 and 1 (inclusive).
axis : int, optional (default=0)
The axis ... | Below is the the instruction that describes the task:
### Input:
Calculate the quantiles of this histogram.
Parameters
----------
quantiles : list or int
A list of cumulative probabilities or an integer used to determine
equally spaced values between 0 and 1 (inclus... |
def get_clearsky(self, times, model='ineichen', solar_position=None,
dni_extra=None, **kwargs):
"""
Calculate the clear sky estimates of GHI, DNI, and/or DHI
at this location.
Parameters
----------
times: DatetimeIndex
model: str, default 'in... | Calculate the clear sky estimates of GHI, DNI, and/or DHI
at this location.
Parameters
----------
times: DatetimeIndex
model: str, default 'ineichen'
The clear sky model to use. Must be one of
'ineichen', 'haurwitz', 'simplified_solis'.
solar_posi... | Below is the the instruction that describes the task:
### Input:
Calculate the clear sky estimates of GHI, DNI, and/or DHI
at this location.
Parameters
----------
times: DatetimeIndex
model: str, default 'ineichen'
The clear sky model to use. Must be one of
... |
def getKnownPlayers(reset=False):
"""identify all of the currently defined players"""
global playerCache
if not playerCache or reset:
jsonFiles = os.path.join(c.PLAYERS_FOLDER, "*.json")
for playerFilepath in glob.glob(jsonFiles):
filename = os.path.basename(playerFilepath)
... | identify all of the currently defined players | Below is the the instruction that describes the task:
### Input:
identify all of the currently defined players
### Response:
def getKnownPlayers(reset=False):
"""identify all of the currently defined players"""
global playerCache
if not playerCache or reset:
jsonFiles = os.path.join(c.PLAYERS_F... |
def _process_gradient(self, backward, dmdp):
"""
backward: `callable`
callable that backpropagates the gradient of the model w.r.t to
preprocessed input through the preprocessing to get the gradient
of the model's output w.r.t. the input before preprocessing
d... | backward: `callable`
callable that backpropagates the gradient of the model w.r.t to
preprocessed input through the preprocessing to get the gradient
of the model's output w.r.t. the input before preprocessing
dmdp: gradient of model w.r.t. preprocessed input | Below is the the instruction that describes the task:
### Input:
backward: `callable`
callable that backpropagates the gradient of the model w.r.t to
preprocessed input through the preprocessing to get the gradient
of the model's output w.r.t. the input before preprocessing
... |
def neighborhood(self, elements: List[ELEMENT_NAME]) \
-> References:
""" Return a list of all slots, classes and types that touch any element in elements, including the element
itself
@param elements: Elements to do proximity with
@return: All slots and classes that touch e... | Return a list of all slots, classes and types that touch any element in elements, including the element
itself
@param elements: Elements to do proximity with
@return: All slots and classes that touch element | Below is the the instruction that describes the task:
### Input:
Return a list of all slots, classes and types that touch any element in elements, including the element
itself
@param elements: Elements to do proximity with
@return: All slots and classes that touch element
### Response:
def... |
def filter_log_events(awsclient, log_group_name, start_ts, end_ts=None):
"""
Note: this is used to retrieve logs in ramuda.
:param log_group_name: log group name
:param start_ts: timestamp
:param end_ts: timestamp
:return: list of log entries
"""
client_logs = awsclient.get_client('logs... | Note: this is used to retrieve logs in ramuda.
:param log_group_name: log group name
:param start_ts: timestamp
:param end_ts: timestamp
:return: list of log entries | Below is the the instruction that describes the task:
### Input:
Note: this is used to retrieve logs in ramuda.
:param log_group_name: log group name
:param start_ts: timestamp
:param end_ts: timestamp
:return: list of log entries
### Response:
def filter_log_events(awsclient, log_group_name, star... |
def close(self):
"""Ends the background threads, and prevent this instance from
servicing further queries."""
if globals()['_GLOBAL_DONE'] == 0:
globals()['_GLOBAL_DONE'] = 1
self.notify_all()
self.engine.notify()
self.unregister_all_services()
... | Ends the background threads, and prevent this instance from
servicing further queries. | Below is the the instruction that describes the task:
### Input:
Ends the background threads, and prevent this instance from
servicing further queries.
### Response:
def close(self):
"""Ends the background threads, and prevent this instance from
servicing further queries."""
if glob... |
def _parse_type_value(types, value, supported_types):
"""Parse type value of phone numbers, email and post addresses.
:param types: list of type values
:type types: list(str)
:param value: the corresponding label, required for more verbose
exceptions
:type value: str... | Parse type value of phone numbers, email and post addresses.
:param types: list of type values
:type types: list(str)
:param value: the corresponding label, required for more verbose
exceptions
:type value: str
:param supported_types: all allowed standard types
... | Below is the the instruction that describes the task:
### Input:
Parse type value of phone numbers, email and post addresses.
:param types: list of type values
:type types: list(str)
:param value: the corresponding label, required for more verbose
exceptions
:type value:... |
def _thread_multi_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
fn_ = os.path.join(minion_instance.proc_dir, data['jid'])
if opts['multiprocessing'] and not salt.utils.platform.... | This method should be used as a threading target, start the actual
minion side execution. | Below is the the instruction that describes the task:
### Input:
This method should be used as a threading target, start the actual
minion side execution.
### Response:
def _thread_multi_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start th... |
def request(
self,
url: str,
method: str,
raise_for_status: bool = True,
path_to_errors: tuple = None,
*args,
**kwargs
) -> tuple:
"""
A wrapper method for :meth:`~requests.Session.request``, which adds some defaults and logging
:param... | A wrapper method for :meth:`~requests.Session.request``, which adds some defaults and logging
:param url: The URL to send the reply to
:param method: The method to use
:param raise_for_status: Should an exception be raised for a failed response. Default is **True**
:param args: Addition... | Below is the the instruction that describes the task:
### Input:
A wrapper method for :meth:`~requests.Session.request``, which adds some defaults and logging
:param url: The URL to send the reply to
:param method: The method to use
:param raise_for_status: Should an exception be raised for... |
def _syllabify(word, T4=True):
'''Syllabify the given word.'''
word = replace_umlauts(word)
word, rules = apply_T1(word)
if re.search(r'[^ieAyOauo]*([ieAyOauo]{2})[^ieAyOauo]*', word):
word, T2 = apply_T2(word)
word, T8 = apply_T8(word)
word, T9 = apply_T9(word)
word, T4... | Syllabify the given word. | Below is the the instruction that describes the task:
### Input:
Syllabify the given word.
### Response:
def _syllabify(word, T4=True):
'''Syllabify the given word.'''
word = replace_umlauts(word)
word, rules = apply_T1(word)
if re.search(r'[^ieAyOauo]*([ieAyOauo]{2})[^ieAyOauo]*', word):
... |
def change_screens(self):
""" Change to the next tool to edit or back to MAIN form """
if self.settings['next_tool']:
self.parentApp.change_form(self.settings['next_tool'])
else:
self.parentApp.change_form('MAIN') | Change to the next tool to edit or back to MAIN form | Below is the the instruction that describes the task:
### Input:
Change to the next tool to edit or back to MAIN form
### Response:
def change_screens(self):
""" Change to the next tool to edit or back to MAIN form """
if self.settings['next_tool']:
self.parentApp.change_form(self.setti... |
def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
... |
def enable(self, **kwdargs):
"""
General enable function encompassing all user interface features.
Usage (e.g.):
viewer.enable(rotate=False, flip=True)
"""
for feat, value in kwdargs:
feat = feat.lower()
if feat not in self.features:
... | General enable function encompassing all user interface features.
Usage (e.g.):
viewer.enable(rotate=False, flip=True) | Below is the the instruction that describes the task:
### Input:
General enable function encompassing all user interface features.
Usage (e.g.):
viewer.enable(rotate=False, flip=True)
### Response:
def enable(self, **kwdargs):
"""
General enable function encompassing all user in... |
def close(self):
"""Shuts down the thread."""
if not self.closed:
log.debug("Closing worker thread")
self.closed = True
if self._wait:
self._wait.set() | Shuts down the thread. | Below is the the instruction that describes the task:
### Input:
Shuts down the thread.
### Response:
def close(self):
"""Shuts down the thread."""
if not self.closed:
log.debug("Closing worker thread")
self.closed = True
if self._wait:
self._wait.set() |
def build_api_object(uo=None, api_key=None, uo_id=None, uo_type=None):
"""
Builds API object identifier
:return:
"""
if uo is not None:
api_key = uo.resolve_api_key() if uo.resolve_api_key() is not None else api_key
uo_id = uo.uo_id if uo.uo_id is not None... | Builds API object identifier
:return: | Below is the the instruction that describes the task:
### Input:
Builds API object identifier
:return:
### Response:
def build_api_object(uo=None, api_key=None, uo_id=None, uo_type=None):
"""
Builds API object identifier
:return:
"""
if uo is not None:
ap... |
def upload_segmentation_image_file(self, mapobject_type_name,
plate_name, well_name, well_pos_y, well_pos_x, tpoint, zplane,
filename):
'''Uploads segmentations from a *PNG* image file.
Parameters
----------
mapobject_type_name: str
name of the segmen... | Uploads segmentations from a *PNG* image file.
Parameters
----------
mapobject_type_name: str
name of the segmented objects
plate_name: str
name of the plate
well_name: str
name of the well in which the image is located
well_pos_y: int... | Below is the the instruction that describes the task:
### Input:
Uploads segmentations from a *PNG* image file.
Parameters
----------
mapobject_type_name: str
name of the segmented objects
plate_name: str
name of the plate
well_name: str
n... |
def save_copy_as(self, index=None):
"""Save copy of file as...
Args:
index: self.data index for the file to save.
Returns:
False if no file name was selected or if save() was unsuccessful.
True is save() was successful.
Gets the new file n... | Save copy of file as...
Args:
index: self.data index for the file to save.
Returns:
False if no file name was selected or if save() was unsuccessful.
True is save() was successful.
Gets the new file name from select_savename(). If no name is chose... | Below is the the instruction that describes the task:
### Input:
Save copy of file as...
Args:
index: self.data index for the file to save.
Returns:
False if no file name was selected or if save() was unsuccessful.
True is save() was successful.
... |
def is_nsfw():
"""A :func:`.check` that checks if the channel is a NSFW channel.
This check raises a special exception, :exc:`.NSFWChannelRequired`
that is derived from :exc:`.CheckFailure`.
.. versionchanged:: 1.1.0
Raise :exc:`.NSFWChannelRequired instead of generic :exc:`.CheckFailure`.
... | A :func:`.check` that checks if the channel is a NSFW channel.
This check raises a special exception, :exc:`.NSFWChannelRequired`
that is derived from :exc:`.CheckFailure`.
.. versionchanged:: 1.1.0
Raise :exc:`.NSFWChannelRequired instead of generic :exc:`.CheckFailure`.
DM channels will... | Below is the the instruction that describes the task:
### Input:
A :func:`.check` that checks if the channel is a NSFW channel.
This check raises a special exception, :exc:`.NSFWChannelRequired`
that is derived from :exc:`.CheckFailure`.
.. versionchanged:: 1.1.0
Raise :exc:`.NSFWChannelRequi... |
def get_cache_data(request):
if 'init' in request.POST:
init = bool(float(request.POST['init']))
else:
init = False
active_variables = []
if 'variables[]' in request.POST:
active_variables = request.POST.getlist('variables[]')
"""
else:
active_variables = list(
... | else:
active_variables = list(
GroupDisplayPermission.objects.filter(hmi_group__in=request.user.groups.iterator()).values_list(
'charts__variables', flat=True))
active_variables += list(
GroupDisplayPermission.objects.filter(hmi_group__in=request.user.groups.itera... | Below is the the instruction that describes the task:
### Input:
else:
active_variables = list(
GroupDisplayPermission.objects.filter(hmi_group__in=request.user.groups.iterator()).values_list(
'charts__variables', flat=True))
active_variables += list(
GroupDis... |
def get_result(self, cursor):
'''Get the current result's data from the cursor.'''
title = headers = None
# cursor.description is not None for queries that return result sets,
# e.g. SELECT or SHOW.
if cursor.description is not None:
headers = [x[0] for x in cursor.d... | Get the current result's data from the cursor. | Below is the the instruction that describes the task:
### Input:
Get the current result's data from the cursor.
### Response:
def get_result(self, cursor):
'''Get the current result's data from the cursor.'''
title = headers = None
# cursor.description is not None for queries that return r... |
def main(global_config, **settings):
"""Main WSGI application factory."""
initialize_sentry_integration()
config = Configurator(settings=settings)
declare_api_routes(config)
declare_type_info(config)
# allowing the pyramid templates to render rss and xml
config.include('pyramid_jinja2')
... | Main WSGI application factory. | Below is the the instruction that describes the task:
### Input:
Main WSGI application factory.
### Response:
def main(global_config, **settings):
"""Main WSGI application factory."""
initialize_sentry_integration()
config = Configurator(settings=settings)
declare_api_routes(config)
declare_typ... |
def on_gcloud_vm():
""" Determines if we're running on a GCE instance."""
r = None
try:
r = requests.get('http://metadata.google.internal')
except requests.ConnectionError:
return False
try:
if r.headers['Metadata-Flavor'] == 'Google' and \
r.headers['Server'] == ... | Determines if we're running on a GCE instance. | Below is the the instruction that describes the task:
### Input:
Determines if we're running on a GCE instance.
### Response:
def on_gcloud_vm():
""" Determines if we're running on a GCE instance."""
r = None
try:
r = requests.get('http://metadata.google.internal')
except requests.Connectio... |
def getWorkersName(data):
"""Returns the list of the names of the workers sorted alphabetically"""
names = [fichier for fichier in data.keys()]
names.sort()
try:
names.remove("broker")
except ValueError:
pass
return names | Returns the list of the names of the workers sorted alphabetically | Below is the the instruction that describes the task:
### Input:
Returns the list of the names of the workers sorted alphabetically
### Response:
def getWorkersName(data):
"""Returns the list of the names of the workers sorted alphabetically"""
names = [fichier for fichier in data.keys()]
names.sort()
... |
def sign(self, data: bytes, v: int = 27) -> Signature:
""" Sign data hash with local private key """
assert v in (0, 27), 'Raiden is only signing messages with v in (0, 27)'
_hash = eth_sign_sha3(data)
signature = self.private_key.sign_msg_hash(message_hash=_hash)
sig_bytes = sig... | Sign data hash with local private key | Below is the the instruction that describes the task:
### Input:
Sign data hash with local private key
### Response:
def sign(self, data: bytes, v: int = 27) -> Signature:
""" Sign data hash with local private key """
assert v in (0, 27), 'Raiden is only signing messages with v in (0, 27)'
... |
def newton(f,c,tol=0.0001,restrict=None):
"""
newton(f,c) --> float
Returns the x closest to c such that f(x) = 0
"""
#print(c)
if restrict:
lo,hi = restrict
if c < lo or c > hi:
print(c)
c = random*(hi-lo)+lo
if fuzzyequals(f(c),0,tol):
... | newton(f,c) --> float
Returns the x closest to c such that f(x) = 0 | Below is the the instruction that describes the task:
### Input:
newton(f,c) --> float
Returns the x closest to c such that f(x) = 0
### Response:
def newton(f,c,tol=0.0001,restrict=None):
"""
newton(f,c) --> float
Returns the x closest to c such that f(x) = 0
"""
#print(c)
if... |
def phone_subcommand(search_terms, vcard_list, parsable):
"""Print a phone application friendly contact table.
:param search_terms: used as search term to filter the contacts before
printing
:type search_terms: str
:param vcard_list: the vcards to search for matching entries which should
... | Print a phone application friendly contact table.
:param search_terms: used as search term to filter the contacts before
printing
:type search_terms: str
:param vcard_list: the vcards to search for matching entries which should
be printed
:type vcard_list: list of carddav_object.Carddav... | Below is the the instruction that describes the task:
### Input:
Print a phone application friendly contact table.
:param search_terms: used as search term to filter the contacts before
printing
:type search_terms: str
:param vcard_list: the vcards to search for matching entries which should
... |
def dispatch_patterns(self):
"""\
Low-level dispatching of socket data based on regex matching, in general
handles
* In event a nickname is taken, registers under a different one
* Responds to periodic PING messages from server
* Dispatches to registered callbacks when
... | \
Low-level dispatching of socket data based on regex matching, in general
handles
* In event a nickname is taken, registers under a different one
* Responds to periodic PING messages from server
* Dispatches to registered callbacks when
- any user leaves or enters a... | Below is the the instruction that describes the task:
### Input:
\
Low-level dispatching of socket data based on regex matching, in general
handles
* In event a nickname is taken, registers under a different one
* Responds to periodic PING messages from server
* Dispatches t... |
def from_triple(cls, triple):
"""
Create a Target instance for the given triple (a string).
"""
with ffi.OutputString() as outerr:
target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode('utf8'),
outerr)
if... | Create a Target instance for the given triple (a string). | Below is the the instruction that describes the task:
### Input:
Create a Target instance for the given triple (a string).
### Response:
def from_triple(cls, triple):
"""
Create a Target instance for the given triple (a string).
"""
with ffi.OutputString() as outerr:
tar... |
def start_polling(self, reset_webhook=None, timeout=20, fast=True):
"""
Start bot in long-polling mode
:param reset_webhook:
:param timeout:
"""
self._prepare_polling()
loop: asyncio.AbstractEventLoop = self.loop
try:
loop.run_until_complete(... | Start bot in long-polling mode
:param reset_webhook:
:param timeout: | Below is the the instruction that describes the task:
### Input:
Start bot in long-polling mode
:param reset_webhook:
:param timeout:
### Response:
def start_polling(self, reset_webhook=None, timeout=20, fast=True):
"""
Start bot in long-polling mode
:param reset_webhook:
... |
def begin_send(self, p):
"""Begin the transmission of message p. This method returns after
sending the first frame. If multiple frames are necessary to send the
message, this socket will unable to send other messages until either
the transmission of this frame succeeds or it fails."""
... | Begin the transmission of message p. This method returns after
sending the first frame. If multiple frames are necessary to send the
message, this socket will unable to send other messages until either
the transmission of this frame succeeds or it fails. | Below is the the instruction that describes the task:
### Input:
Begin the transmission of message p. This method returns after
sending the first frame. If multiple frames are necessary to send the
message, this socket will unable to send other messages until either
the transmission of this ... |
def add_member(self, username, permissions, api=None):
"""Add member to a dataset
:param username: Member username
:param permissions: Permissions dict
:param api: Api instance
:return: New member instance
"""
api = api or self._API
data = {
'u... | Add member to a dataset
:param username: Member username
:param permissions: Permissions dict
:param api: Api instance
:return: New member instance | Below is the the instruction that describes the task:
### Input:
Add member to a dataset
:param username: Member username
:param permissions: Permissions dict
:param api: Api instance
:return: New member instance
### Response:
def add_member(self, username, permissions, api=None):
... |
def _exec_cmd(command):
"""Call a CMD command and return the output and returncode"""
proc = sp.Popen(command,
stdout=sp.PIPE,
shell=True)
if six.PY2:
res = proc.communicate()[0]
else:
res = proc.communicate(timeout=5)[0]
return res, proc.retur... | Call a CMD command and return the output and returncode | Below is the the instruction that describes the task:
### Input:
Call a CMD command and return the output and returncode
### Response:
def _exec_cmd(command):
"""Call a CMD command and return the output and returncode"""
proc = sp.Popen(command,
stdout=sp.PIPE,
shell... |
def l_sa_check(template, literal, is_standalone):
"""Do a preliminary check to see if a tag could be a standalone"""
# If there is a newline, or the previous tag was a standalone
if literal.find('\n') != -1 or is_standalone:
padding = literal.split('\n')[-1]
# If all the characters since t... | Do a preliminary check to see if a tag could be a standalone | Below is the the instruction that describes the task:
### Input:
Do a preliminary check to see if a tag could be a standalone
### Response:
def l_sa_check(template, literal, is_standalone):
"""Do a preliminary check to see if a tag could be a standalone"""
# If there is a newline, or the previous tag was ... |
def poll_crontab(self):
"""Check crontab and run target jobs
"""
polled_time = self._get_current_time()
if polled_time.second >= 30:
self.log.debug('Skip cronjobs in {}'.format(polled_time))
return
for job in self._crontab:
if not job.is_runnab... | Check crontab and run target jobs | Below is the the instruction that describes the task:
### Input:
Check crontab and run target jobs
### Response:
def poll_crontab(self):
"""Check crontab and run target jobs
"""
polled_time = self._get_current_time()
if polled_time.second >= 30:
self.log.debug('Skip cron... |
def get_tags_of_delivery_note_per_page(self, delivery_note_id, per_page=1000, page=1):
"""
Get tags of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:retu... | Get tags of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | Below is the the instruction that describes the task:
### Input:
Get tags of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
### Response:
def get_tags_o... |
def custom_environment(self, **kwargs):
"""
A context manager around the above ``update_environment`` method to restore the
environment back to its previous state after operation.
``Examples``::
with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'):
repo.... | A context manager around the above ``update_environment`` method to restore the
environment back to its previous state after operation.
``Examples``::
with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'):
repo.remotes.origin.fetch()
:param kwargs: see update_en... | Below is the the instruction that describes the task:
### Input:
A context manager around the above ``update_environment`` method to restore the
environment back to its previous state after operation.
``Examples``::
with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'):
... |
def _select_meshes(self, data):
"""
Define the x and y indices with respect to the low-resolution
mesh image of the meshes to use for the background
interpolation.
The ``exclude_percentile`` keyword determines which meshes are
not used for the background interpolation.
... | Define the x and y indices with respect to the low-resolution
mesh image of the meshes to use for the background
interpolation.
The ``exclude_percentile`` keyword determines which meshes are
not used for the background interpolation.
Parameters
----------
data :... | Below is the the instruction that describes the task:
### Input:
Define the x and y indices with respect to the low-resolution
mesh image of the meshes to use for the background
interpolation.
The ``exclude_percentile`` keyword determines which meshes are
not used for the background... |
def setMagnitude(self, band, value):
"""Makes the magnitude of the source in the band equal to value.
band is a SpectralElement.
This method is marked for deletion once the .renorm method is
well tested.
Object returned is a CompositeSourceSpectrum.
.. warning:: DO NOT ... | Makes the magnitude of the source in the band equal to value.
band is a SpectralElement.
This method is marked for deletion once the .renorm method is
well tested.
Object returned is a CompositeSourceSpectrum.
.. warning:: DO NOT USED | Below is the the instruction that describes the task:
### Input:
Makes the magnitude of the source in the band equal to value.
band is a SpectralElement.
This method is marked for deletion once the .renorm method is
well tested.
Object returned is a CompositeSourceSpectrum.
... |
def walk_dir_progress(path, maxdircnt=5000, file=sys.stdout):
""" Walk a directory, printing status updates along the way. """
p = ProgressBar(
'Walking {}'.format(C(path, 'cyan')),
bars=Bars.numbers_blue.with_wrapper(('(', ')')),
show_time=True,
file=file,
)
rootcnt = 0
... | Walk a directory, printing status updates along the way. | Below is the the instruction that describes the task:
### Input:
Walk a directory, printing status updates along the way.
### Response:
def walk_dir_progress(path, maxdircnt=5000, file=sys.stdout):
""" Walk a directory, printing status updates along the way. """
p = ProgressBar(
'Walking {}'.format... |
def lti(self):
"""
Dictionary extended_loss_type -> extended_loss_type index
"""
return {lt: i for i, (lt, dt) in enumerate(self.loss_dt_list())} | Dictionary extended_loss_type -> extended_loss_type index | Below is the the instruction that describes the task:
### Input:
Dictionary extended_loss_type -> extended_loss_type index
### Response:
def lti(self):
"""
Dictionary extended_loss_type -> extended_loss_type index
"""
return {lt: i for i, (lt, dt) in enumerate(self.loss_dt_list())} |
def _create_type(self, env, item):
"""Create a forward reference for a union or struct."""
if item.name in env:
existing_dt = env[item.name]
raise InvalidSpec(
'Symbol %s already defined (%s:%d).' %
(quote(item.name), existing_dt._ast_node.path,
... | Create a forward reference for a union or struct. | Below is the the instruction that describes the task:
### Input:
Create a forward reference for a union or struct.
### Response:
def _create_type(self, env, item):
"""Create a forward reference for a union or struct."""
if item.name in env:
existing_dt = env[item.name]
raise... |
def id(self):
"""获取用户id,就是网址最后那一部分.
:return: 用户id
:rtype: str
"""
return re.match(r'^.*/([^/]+)/$', self.url).group(1) \
if self.url is not None else '' | 获取用户id,就是网址最后那一部分.
:return: 用户id
:rtype: str | Below is the the instruction that describes the task:
### Input:
获取用户id,就是网址最后那一部分.
:return: 用户id
:rtype: str
### Response:
def id(self):
"""获取用户id,就是网址最后那一部分.
:return: 用户id
:rtype: str
"""
return re.match(r'^.*/([^/]+)/$', self.url).group(1) \
... |
def remove_all_labels(stdout=None):
"""
Calls functions for dropping constraints and indexes.
:param stdout: output stream
:return: None
"""
if not stdout:
stdout = sys.stdout
stdout.write("Droping constraints...\n")
drop_constraints(quiet=False, stdout=stdout)
stdout.wri... | Calls functions for dropping constraints and indexes.
:param stdout: output stream
:return: None | Below is the the instruction that describes the task:
### Input:
Calls functions for dropping constraints and indexes.
:param stdout: output stream
:return: None
### Response:
def remove_all_labels(stdout=None):
"""
Calls functions for dropping constraints and indexes.
:param stdout: output s... |
def takeScreenshotAndShowItOnWindow(self):
'''
Takes the current screenshot and shows it on the main window.
It also:
- sizes the window
- create the canvas
- set the focus
- enable the events
- create widgets
- finds the targets (as explaine... | Takes the current screenshot and shows it on the main window.
It also:
- sizes the window
- create the canvas
- set the focus
- enable the events
- create widgets
- finds the targets (as explained in L{findTargets})
- hides the vignette (that could ... | Below is the the instruction that describes the task:
### Input:
Takes the current screenshot and shows it on the main window.
It also:
- sizes the window
- create the canvas
- set the focus
- enable the events
- create widgets
- finds the targets (as ex... |
def exists(self):
""" Checks if the item exists. """
try:
return self.metadata is not None
except datalab.utils.RequestException:
return False
except Exception as e:
raise e | Checks if the item exists. | Below is the the instruction that describes the task:
### Input:
Checks if the item exists.
### Response:
def exists(self):
""" Checks if the item exists. """
try:
return self.metadata is not None
except datalab.utils.RequestException:
return False
except Exception as e:
raise e |
def multiply(self, data, fill_value=0.):
"""
Multiply the aperture mask with the input data, taking any edge
effects into account.
The result is a mask-weighted cutout from the data.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
... | Multiply the aperture mask with the input data, taking any edge
effects into account.
The result is a mask-weighted cutout from the data.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array to multiply with the aperture mask.
f... | Below is the the instruction that describes the task:
### Input:
Multiply the aperture mask with the input data, taking any edge
effects into account.
The result is a mask-weighted cutout from the data.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
... |
def move_inside(self, parent_id):
""" Moving one node of tree inside another
For example see:
* :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_function`
* :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_to_the_same_parent_function`
""" # noqa
... | Moving one node of tree inside another
For example see:
* :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_function`
* :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_to_the_same_parent_function` | Below is the the instruction that describes the task:
### Input:
Moving one node of tree inside another
For example see:
* :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_function`
* :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_to_the_same_parent_function`
### ... |
def send(channel, message, **kwargs):
"""
Site: http://www.pubnub.com/
API: https://www.mashape.com/pubnub/pubnub-network
Desc: real-time browser notifications
Installation and usage:
pip install -U pubnub
Tests for browser notification http://127.0.0.1:8000/browser_notification/
"""
... | Site: http://www.pubnub.com/
API: https://www.mashape.com/pubnub/pubnub-network
Desc: real-time browser notifications
Installation and usage:
pip install -U pubnub
Tests for browser notification http://127.0.0.1:8000/browser_notification/ | Below is the the instruction that describes the task:
### Input:
Site: http://www.pubnub.com/
API: https://www.mashape.com/pubnub/pubnub-network
Desc: real-time browser notifications
Installation and usage:
pip install -U pubnub
Tests for browser notification http://127.0.0.1:8000/browser_notif... |
def date_from_adverb(base_date, name):
"""
Convert Day adverbs to dates
Tomorrow => Date
Today => Date
"""
# Reset date to start of the day
adverb_date = datetime(base_date.year, base_date.month, base_date.day)
if name == 'today' or name == 'tonite' or name == 'tonight':
return a... | Convert Day adverbs to dates
Tomorrow => Date
Today => Date | Below is the the instruction that describes the task:
### Input:
Convert Day adverbs to dates
Tomorrow => Date
Today => Date
### Response:
def date_from_adverb(base_date, name):
"""
Convert Day adverbs to dates
Tomorrow => Date
Today => Date
"""
# Reset date to start of the day
... |
def current_resp_rate(self):
"""Return current respiratory rate for in-progress session."""
try:
rates = self.intervals[0]['timeseries']['respiratoryRate']
num_rates = len(rates)
if num_rates == 0:
return None
rate = rates[num_rates-1][1]... | Return current respiratory rate for in-progress session. | Below is the the instruction that describes the task:
### Input:
Return current respiratory rate for in-progress session.
### Response:
def current_resp_rate(self):
"""Return current respiratory rate for in-progress session."""
try:
rates = self.intervals[0]['timeseries']['respiratoryRa... |
def get_reffs(self, objectId, subreference=None, collection=None, export_collection=False):
""" Retrieve and transform a list of references.
Returns the inventory collection object with its metadata and a callback function taking a level parameter \
and returning a list of strings.
:pa... | Retrieve and transform a list of references.
Returns the inventory collection object with its metadata and a callback function taking a level parameter \
and returning a list of strings.
:param objectId: Collection Identifier
:type objectId: str
:param subreference: Subreferenc... | Below is the the instruction that describes the task:
### Input:
Retrieve and transform a list of references.
Returns the inventory collection object with its metadata and a callback function taking a level parameter \
and returning a list of strings.
:param objectId: Collection Identifier... |
def create_from_template(self, client_id, subject, name, from_name,
from_email, reply_to, list_ids, segment_ids, template_id, template_content):
"""Creates a new campaign for a client, from a template.
:param client_id: String representing the ID of the client for whom the
... | Creates a new campaign for a client, from a template.
:param client_id: String representing the ID of the client for whom the
campaign will be created.
:param subject: String representing the subject of the campaign.
:param name: String representing the name of the campaign.
:... | Below is the the instruction that describes the task:
### Input:
Creates a new campaign for a client, from a template.
:param client_id: String representing the ID of the client for whom the
campaign will be created.
:param subject: String representing the subject of the campaign.
... |
def read(self):
"""Parse and validate the config file. The read data is accessible as a dictionary in this instance
:return: None
"""
try:
data = load(open(self.file), Loader)
except (UnicodeDecodeError, YAMLError) as e:
raise InvalidConfig(self.file, '{}... | Parse and validate the config file. The read data is accessible as a dictionary in this instance
:return: None | Below is the the instruction that describes the task:
### Input:
Parse and validate the config file. The read data is accessible as a dictionary in this instance
:return: None
### Response:
def read(self):
"""Parse and validate the config file. The read data is accessible as a dictionary in this i... |
def plotSolidAngleCMD(self):
"""
Solid angle within the mask as a function of color and magnitude.
"""
msg = "'%s.plotSolidAngleCMD': ADW 2018-05-05"%self.__class__.__name__
DeprecationWarning(msg)
import ugali.utils.plotting
ugali.utils.plotting.twoDimen... | Solid angle within the mask as a function of color and magnitude. | Below is the the instruction that describes the task:
### Input:
Solid angle within the mask as a function of color and magnitude.
### Response:
def plotSolidAngleCMD(self):
"""
Solid angle within the mask as a function of color and magnitude.
"""
msg = "'%s.plotSolidAngleCMD': ADW ... |
def save(self, filename, format_='fasta'):
"""
Write the reads to C{filename} in the requested format.
@param filename: Either a C{str} file name to save into (the file will
be overwritten) or an open file descriptor (e.g., sys.stdout).
@param format_: A C{str} format to sav... | Write the reads to C{filename} in the requested format.
@param filename: Either a C{str} file name to save into (the file will
be overwritten) or an open file descriptor (e.g., sys.stdout).
@param format_: A C{str} format to save as, either 'fasta', 'fastq' or
'fasta-ss'.
... | Below is the the instruction that describes the task:
### Input:
Write the reads to C{filename} in the requested format.
@param filename: Either a C{str} file name to save into (the file will
be overwritten) or an open file descriptor (e.g., sys.stdout).
@param format_: A C{str} format ... |
async def jsk_cancel(self, ctx: commands.Context, *, index: int):
"""
Cancels a task with the given index.
If the index passed is -1, will cancel the last task instead.
"""
if not self.tasks:
return await ctx.send("No tasks to cancel.")
if index == -1:
... | Cancels a task with the given index.
If the index passed is -1, will cancel the last task instead. | Below is the the instruction that describes the task:
### Input:
Cancels a task with the given index.
If the index passed is -1, will cancel the last task instead.
### Response:
async def jsk_cancel(self, ctx: commands.Context, *, index: int):
"""
Cancels a task with the given index.
... |
def is_modified(self) -> bool:
"""
Find whether the files on the left and right are different. Note,
modified implies the contents of the file have changed, which is
predicated on the file existing on both the left and right. Therefore
this will be false if the file on the left h... | Find whether the files on the left and right are different. Note,
modified implies the contents of the file have changed, which is
predicated on the file existing on both the left and right. Therefore
this will be false if the file on the left has been deleted, or the
file on the right i... | Below is the the instruction that describes the task:
### Input:
Find whether the files on the left and right are different. Note,
modified implies the contents of the file have changed, which is
predicated on the file existing on both the left and right. Therefore
this will be false if the ... |
def cells(a, b):
'''
# Sum
'''
a, b = int(a), int(b)
'''
'''
a + b | # Sum | Below is the the instruction that describes the task:
### Input:
# Sum
### Response:
def cells(a, b):
'''
# Sum
'''
a, b = int(a), int(b)
'''
'''
a + b |
def output_data(self):
"""Get a buffer of data that needs to be written to the network.
"""
c = self.has_output
if c <= 0:
return None
try:
buf = self._pn_transport.peek(c)
except Exception as e:
self._connection_failed(str(e))
... | Get a buffer of data that needs to be written to the network. | Below is the the instruction that describes the task:
### Input:
Get a buffer of data that needs to be written to the network.
### Response:
def output_data(self):
"""Get a buffer of data that needs to be written to the network.
"""
c = self.has_output
if c <= 0:
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.