code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def close(self) -> Awaitable[None]:
"""Close all ongoing DNS calls."""
for ev in self._throttle_dns_events.values():
ev.cancel()
return super().close() | Close all ongoing DNS calls. | Below is the the instruction that describes the task:
### Input:
Close all ongoing DNS calls.
### Response:
def close(self) -> Awaitable[None]:
"""Close all ongoing DNS calls."""
for ev in self._throttle_dns_events.values():
ev.cancel()
return super().close() |
def pairplot(dataset, vars, filename, bins=60):
""" Plot a matrix of the specified variables with all the 2D pdfs and 1D pdfs.
"""
n = len(vars)
fig, axes = plt.subplots(nrows=n, ncols=n)
plt.subplots_adjust(wspace=0.1, hspace=0.1)
for i, x in enumerate(vars):
for j, y in enumerate(var... | Plot a matrix of the specified variables with all the 2D pdfs and 1D pdfs. | Below is the the instruction that describes the task:
### Input:
Plot a matrix of the specified variables with all the 2D pdfs and 1D pdfs.
### Response:
def pairplot(dataset, vars, filename, bins=60):
""" Plot a matrix of the specified variables with all the 2D pdfs and 1D pdfs.
"""
n = len(vars)
... |
def convert(gr, raw_node):
"""
Convert raw node information to a Node or Leaf instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the tree is build
strictly bottom-up.
"""
type, value, context, children = ... | Convert raw node information to a Node or Leaf instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the tree is build
strictly bottom-up. | Below is the the instruction that describes the task:
### Input:
Convert raw node information to a Node or Leaf instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the tree is build
strictly bottom-up.
### Response:
... |
def bytes(num, check_result=False):
"""
Returns num bytes of cryptographically strong pseudo-random
bytes. If checkc_result is True, raises error if PRNG is not
seeded enough
"""
if num <= 0:
raise ValueError("'num' should be > 0")
buf = create_string_buffer(num)
result = libcry... | Returns num bytes of cryptographically strong pseudo-random
bytes. If checkc_result is True, raises error if PRNG is not
seeded enough | Below is the the instruction that describes the task:
### Input:
Returns num bytes of cryptographically strong pseudo-random
bytes. If checkc_result is True, raises error if PRNG is not
seeded enough
### Response:
def bytes(num, check_result=False):
"""
Returns num bytes of cryptographically strong... |
def cluster(self, window):
""" Cluster the dict array, assuming it has the relevant Coinc colums,
time1, time2, stat, and timeslide_id
"""
# If no events, do nothing
if len(self.time1) == 0 or len(self.time2) == 0:
return self
from pycbc.events import cluster_... | Cluster the dict array, assuming it has the relevant Coinc colums,
time1, time2, stat, and timeslide_id | Below is the the instruction that describes the task:
### Input:
Cluster the dict array, assuming it has the relevant Coinc colums,
time1, time2, stat, and timeslide_id
### Response:
def cluster(self, window):
""" Cluster the dict array, assuming it has the relevant Coinc colums,
time1, tim... |
def get_cash_asset_class(self) -> AssetClass:
""" Find the cash asset class by name. """
for ac in self.asset_classes:
if ac.name.lower() == "cash":
return ac
return None | Find the cash asset class by name. | Below is the the instruction that describes the task:
### Input:
Find the cash asset class by name.
### Response:
def get_cash_asset_class(self) -> AssetClass:
""" Find the cash asset class by name. """
for ac in self.asset_classes:
if ac.name.lower() == "cash":
return a... |
def set_fun_prop(f, k, v):
"""Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property named `k` to be
value `v`.
... | Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property named `k` to be
value `v`.
Users should never access this fun... | Below is the the instruction that describes the task:
### Input:
Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property n... |
def subscribe_condition_fulfilled(self, agreement_id, timeout, callback, args,
timeout_callback=None, wait=False):
"""
Subscribe to the condition fullfilled event.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param call... | Subscribe to the condition fullfilled event.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param callback:
:param args:
:param timeout_callback:
:param wait: if true block the listener until get the event, bool
:return: | Below is the the instruction that describes the task:
### Input:
Subscribe to the condition fullfilled event.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param callback:
:param args:
:param timeout_callback:
:param wait: if true block the liste... |
def joinArgs(args):
""" Returns a query string (uses for HTTP URLs) where only the value is URL encoded.
Example return value: '?genre=action&type=1337'.
Parameters:
args (dict): Arguments to include in query string.
"""
if not args:
return ''
arglist = []
for ke... | Returns a query string (uses for HTTP URLs) where only the value is URL encoded.
Example return value: '?genre=action&type=1337'.
Parameters:
args (dict): Arguments to include in query string. | Below is the the instruction that describes the task:
### Input:
Returns a query string (uses for HTTP URLs) where only the value is URL encoded.
Example return value: '?genre=action&type=1337'.
Parameters:
args (dict): Arguments to include in query string.
### Response:
def joinArgs(a... |
def calc_riseset(t, target_name, location, prev_next, rise_set, horizon):
"""
Time at next rise/set of ``target``.
Parameters
----------
t : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initia... | Time at next rise/set of ``target``.
Parameters
----------
t : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including ... | Below is the the instruction that describes the task:
### Input:
Time at next rise/set of ``target``.
Parameters
----------
t : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can ... |
def _start_of_decade(self):
"""
Reset the date to the first day of the decade.
:rtype: Date
"""
year = self.year - self.year % YEARS_PER_DECADE
return self.set(year, 1, 1) | Reset the date to the first day of the decade.
:rtype: Date | Below is the the instruction that describes the task:
### Input:
Reset the date to the first day of the decade.
:rtype: Date
### Response:
def _start_of_decade(self):
"""
Reset the date to the first day of the decade.
:rtype: Date
"""
year = self.year - self.year %... |
def create_image_summary(name, val):
"""
Args:
name(str):
val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3.
Can be either float or uint8. Range has to be [0,255].
Returns:
tf.Summary:
"""
assert isinstance(name, six.string_types), type(name)
n, h, w, c ... | Args:
name(str):
val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3.
Can be either float or uint8. Range has to be [0,255].
Returns:
tf.Summary: | Below is the the instruction that describes the task:
### Input:
Args:
name(str):
val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3.
Can be either float or uint8. Range has to be [0,255].
Returns:
tf.Summary:
### Response:
def create_image_summary(name, val):
"""
... |
def read_serialized_rsa_pub_key(serialized):
"""
Reads serialized RSA pub key
TAG|len-2B|value. 81 = exponent, 82 = modulus
:param serialized:
:return: n, e
"""
n = None
e = None
rsa = from_hex(serialized)
pos = 0
ln = len(rsa)
... | Reads serialized RSA pub key
TAG|len-2B|value. 81 = exponent, 82 = modulus
:param serialized:
:return: n, e | Below is the the instruction that describes the task:
### Input:
Reads serialized RSA pub key
TAG|len-2B|value. 81 = exponent, 82 = modulus
:param serialized:
:return: n, e
### Response:
def read_serialized_rsa_pub_key(serialized):
"""
Reads serialized RSA pub key
T... |
def clean_dateobject_to_string(x):
"""Convert a Pandas Timestamp object or datetime object
to 'YYYY-MM-DD' string
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A Pandas Timestamp object or datetime object,
or an array of these objects
Returns
-... | Convert a Pandas Timestamp object or datetime object
to 'YYYY-MM-DD' string
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A Pandas Timestamp object or datetime object,
or an array of these objects
Returns
-------
y : str, list, tuple, numpy.nda... | Below is the the instruction that describes the task:
### Input:
Convert a Pandas Timestamp object or datetime object
to 'YYYY-MM-DD' string
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A Pandas Timestamp object or datetime object,
or an array of these... |
def main(): # mini/unit test
"""
PURPOSE: command-line interface for map information
"""
options = optionsParser().parse_args()
params = getSelectionParams(options)
if options.list or options.details:
specifiedMaps = filterMapNames(
options.mapname,
records = filt... | PURPOSE: command-line interface for map information | Below is the the instruction that describes the task:
### Input:
PURPOSE: command-line interface for map information
### Response:
def main(): # mini/unit test
"""
PURPOSE: command-line interface for map information
"""
options = optionsParser().parse_args()
params = getSelectionParams(options)... |
def _query_entities(self, table_name, filter=None, select=None, max_results=None,
marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
property_resolver=None, timeout=None):
'''
Returns a list of entities under the specified table. Makes a single li... | Returns a list of entities under the specified table. Makes a single list
request to the service. Used internally by the query_entities method.
:param str table_name:
The name of the table to query.
:param str filter:
Returns only entities that satisfy the specified fil... | Below is the the instruction that describes the task:
### Input:
Returns a list of entities under the specified table. Makes a single list
request to the service. Used internally by the query_entities method.
:param str table_name:
The name of the table to query.
:param str fil... |
def on_nick(self, connection, event):
"""
Someone changed their nickname - send the nicknames list to the
WebSocket.
"""
old_nickname = self.get_nickname(event)
old_color = self.nicknames.pop(old_nickname)
new_nickname = event.target()
message = "is now kn... | Someone changed their nickname - send the nicknames list to the
WebSocket. | Below is the the instruction that describes the task:
### Input:
Someone changed their nickname - send the nicknames list to the
WebSocket.
### Response:
def on_nick(self, connection, event):
"""
Someone changed their nickname - send the nicknames list to the
WebSocket.
"""
... |
def update_stack(self, fqn, template, old_parameters, parameters, tags,
force_interactive=False, force_change_set=False,
stack_policy=None, **kwargs):
"""Update a Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation ... | Update a Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stack.
old_parameters (list): A list of dictionaries that def... | Below is the the instruction that describes the task:
### Input:
Update a Cloudformation stack.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.providers.base.Template`): A Template
object to use when updating the stac... |
def unravel_sections(section_data):
"""Unravels section type dictionary into flat list of sections with
section type set as an attribute.
Args:
section_data(dict): Data return from py:method::get_sections
Returns:
list: Flat list of sections with ``sectionType``... | Unravels section type dictionary into flat list of sections with
section type set as an attribute.
Args:
section_data(dict): Data return from py:method::get_sections
Returns:
list: Flat list of sections with ``sectionType`` set to
type (i.e. recitation, ... | Below is the the instruction that describes the task:
### Input:
Unravels section type dictionary into flat list of sections with
section type set as an attribute.
Args:
section_data(dict): Data return from py:method::get_sections
Returns:
list: Flat list of section... |
def alter_function(self, dbName, funcName, newFunc):
"""
Parameters:
- dbName
- funcName
- newFunc
"""
self.send_alter_function(dbName, funcName, newFunc)
self.recv_alter_function() | Parameters:
- dbName
- funcName
- newFunc | Below is the the instruction that describes the task:
### Input:
Parameters:
- dbName
- funcName
- newFunc
### Response:
def alter_function(self, dbName, funcName, newFunc):
"""
Parameters:
- dbName
- funcName
- newFunc
"""
self.send_alter_function(dbName, funcName, ne... |
def mavlink_packet(self, m):
'''handle a mavlink packet'''
mtype = m.get_type()
if mtype == "SYS_STATUS":
self.battery_update(m)
if mtype == "BATTERY2":
self.battery2_voltage = m.voltage * 0.001
if mtype == "POWER_STATUS":
self.power_status_upd... | handle a mavlink packet | Below is the the instruction that describes the task:
### Input:
handle a mavlink packet
### Response:
def mavlink_packet(self, m):
'''handle a mavlink packet'''
mtype = m.get_type()
if mtype == "SYS_STATUS":
self.battery_update(m)
if mtype == "BATTERY2":
sel... |
def put(f, s3_path, multipart_chunk_size_mb=500, logger=None):
'''
Uploads a single file to S3, using s3cmd.
Args:
f (str): Path to a single file.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``f``. For example::
... | Uploads a single file to S3, using s3cmd.
Args:
f (str): Path to a single file.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``f``. For example::
put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/path/to/')
... | Below is the the instruction that describes the task:
### Input:
Uploads a single file to S3, using s3cmd.
Args:
f (str): Path to a single file.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``f``. For example::
... |
def close(self) -> None:
"""Closes connection to the LifeSOS ethernet interface."""
self.cancel_pending_tasks()
_LOGGER.debug("Disconnected")
if self._transport:
self._transport.close()
self._is_connected = False | Closes connection to the LifeSOS ethernet interface. | Below is the the instruction that describes the task:
### Input:
Closes connection to the LifeSOS ethernet interface.
### Response:
def close(self) -> None:
"""Closes connection to the LifeSOS ethernet interface."""
self.cancel_pending_tasks()
_LOGGER.debug("Disconnected")
if self... |
def set_misc(self):
'''Set more parameters, after the tank is better defined than in the
__init__ function.
Notes
-----
Two of D, L, and L_over_D must be known when this function runs.
The other one is set from the other two first thing in this function.
a_ratio ... | Set more parameters, after the tank is better defined than in the
__init__ function.
Notes
-----
Two of D, L, and L_over_D must be known when this function runs.
The other one is set from the other two first thing in this function.
a_ratio parameters are used to calculat... | Below is the the instruction that describes the task:
### Input:
Set more parameters, after the tank is better defined than in the
__init__ function.
Notes
-----
Two of D, L, and L_over_D must be known when this function runs.
The other one is set from the other two first th... |
def encode(self):
"""Encode a GNTP Registration Message
:return string: Encoded GNTP Registration message. Returned as a byte string
"""
buff = _GNTPBuffer()
buff.writeln(self._format_info())
#Headers
for k, v in self.headers.items():
buff.writeheader(k, v)
buff.writeln()
#Notifications
if l... | Encode a GNTP Registration Message
:return string: Encoded GNTP Registration message. Returned as a byte string | Below is the the instruction that describes the task:
### Input:
Encode a GNTP Registration Message
:return string: Encoded GNTP Registration message. Returned as a byte string
### Response:
def encode(self):
"""Encode a GNTP Registration Message
:return string: Encoded GNTP Registration message. Returned ... |
def connectionLost(self, reason):
"""
If a login has happened, perform a logout.
"""
AMP.connectionLost(self, reason)
if self.logout is not None:
self.logout()
self.boxReceiver = self.logout = None | If a login has happened, perform a logout. | Below is the the instruction that describes the task:
### Input:
If a login has happened, perform a logout.
### Response:
def connectionLost(self, reason):
"""
If a login has happened, perform a logout.
"""
AMP.connectionLost(self, reason)
if self.logout is not None:
... |
def display_value(self, ctx, value):
""" Display value to be used for this parameter. """
gandi = ctx.obj
gandi.log('%s: %s' % (self.name, (value if value is not None
else 'Not found'))) | Display value to be used for this parameter. | Below is the the instruction that describes the task:
### Input:
Display value to be used for this parameter.
### Response:
def display_value(self, ctx, value):
""" Display value to be used for this parameter. """
gandi = ctx.obj
gandi.log('%s: %s' % (self.name, (value if value is not None
... |
def main():
"""
Loop over a list of input text strings. Parse each string using a list of
parsers, one included in megaparsex and one defined in this script. If a
confirmation is requested, seek confirmation, otherwise display any response
text and engage any triggered functions.
"""
for tex... | Loop over a list of input text strings. Parse each string using a list of
parsers, one included in megaparsex and one defined in this script. If a
confirmation is requested, seek confirmation, otherwise display any response
text and engage any triggered functions. | Below is the the instruction that describes the task:
### Input:
Loop over a list of input text strings. Parse each string using a list of
parsers, one included in megaparsex and one defined in this script. If a
confirmation is requested, seek confirmation, otherwise display any response
text and engage... |
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value | Returns today (date only) as datetime | Below is the the instruction that describes the task:
### Input:
Returns today (date only) as datetime
### Response:
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value |
def _parse_value(self, raw):
"""Parses value
:param raw: raw value
:return: Parsed value
"""
try:
if not raw.startswith("0"):
val = float(raw)
if (val % 1) == 0: # integer
val = int(raw)
return ... | Parses value
:param raw: raw value
:return: Parsed value | Below is the the instruction that describes the task:
### Input:
Parses value
:param raw: raw value
:return: Parsed value
### Response:
def _parse_value(self, raw):
"""Parses value
:param raw: raw value
:return: Parsed value
"""
try:
if not raw.... |
def stop(self):
"""
Restore the TTY to its original state.
"""
_curses.nocbreak()
self.window.keypad(0)
_curses.echo()
_curses.resetty()
_curses.endwin()
self.running = False | Restore the TTY to its original state. | Below is the the instruction that describes the task:
### Input:
Restore the TTY to its original state.
### Response:
def stop(self):
"""
Restore the TTY to its original state.
"""
_curses.nocbreak()
self.window.keypad(0)
_curses.echo()
_curses.resetty()
... |
def _combine_contract(self, years, wages):
"""
Combine the contract wages and year.
Match the wages with the year and add to a dictionary representing the
player's contract.
Parameters
----------
years : list
A list where each element is a string den... | Combine the contract wages and year.
Match the wages with the year and add to a dictionary representing the
player's contract.
Parameters
----------
years : list
A list where each element is a string denoting the season, such as
'2017-18'.
wages ... | Below is the the instruction that describes the task:
### Input:
Combine the contract wages and year.
Match the wages with the year and add to a dictionary representing the
player's contract.
Parameters
----------
years : list
A list where each element is a stri... |
def two_numbers(
cls, request,
operation: (Ptypes.path,
String('One of the 4 arithmetic operations.',
enum=['add', 'sub', 'mul', 'div'])),
first: (Ptypes.path,
Float('The first operand.')),
second... | Any of the four arithmetic operation on two numbers. | Below is the the instruction that describes the task:
### Input:
Any of the four arithmetic operation on two numbers.
### Response:
def two_numbers(
cls, request,
operation: (Ptypes.path,
String('One of the 4 arithmetic operations.',
e... |
def run_on_executor(*args: Any, **kwargs: Any) -> Callable:
"""Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
The executor to be used is determined by the ``executor``
attributes of ... | Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
The executor to be used is determined by the ``executor``
attributes of ``self``. To use a different attribute name, pass a
keyword arg... | Below is the the instruction that describes the task:
### Input:
Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
The executor to be used is determined by the ``executor``
attributes o... |
def p_expr_div_expr(p):
""" expr : expr BAND expr
| expr BOR expr
| expr BXOR expr
| expr PLUS expr
| expr MINUS expr
| expr MUL expr
| expr DIV expr
| expr MOD expr
| expr POW expr
| expr LSHIFT exp... | expr : expr BAND expr
| expr BOR expr
| expr BXOR expr
| expr PLUS expr
| expr MINUS expr
| expr MUL expr
| expr DIV expr
| expr MOD expr
| expr POW expr
| expr LSHIFT expr
| expr RSHIFT exp... | Below is the the instruction that describes the task:
### Input:
expr : expr BAND expr
| expr BOR expr
| expr BXOR expr
| expr PLUS expr
| expr MINUS expr
| expr MUL expr
| expr DIV expr
| expr MOD expr
| expr PO... |
def _get_run_by_other_worker(worker):
"""
This returns a set of the tasks that are being run by other worker
"""
task_sets = _get_external_workers(worker).values()
return functools.reduce(lambda a, b: a | b, task_sets, set()) | This returns a set of the tasks that are being run by other worker | Below is the the instruction that describes the task:
### Input:
This returns a set of the tasks that are being run by other worker
### Response:
def _get_run_by_other_worker(worker):
"""
This returns a set of the tasks that are being run by other worker
"""
task_sets = _get_external_workers(worker... |
def _delete(self, namespace, stream, start_id, end_time, configuration):
"""
Delete events with id > `start_id` and end_time <= `end_time`.
"""
start_id_event = Event(start_id)
end_id_event = Event(uuid_from_kronos_time(end_time,
_type=UUIDType.HIGHEST)... | Delete events with id > `start_id` and end_time <= `end_time`. | Below is the the instruction that describes the task:
### Input:
Delete events with id > `start_id` and end_time <= `end_time`.
### Response:
def _delete(self, namespace, stream, start_id, end_time, configuration):
"""
Delete events with id > `start_id` and end_time <= `end_time`.
"""
start_id_even... |
def getProjectDescriptor(self, dir):
"""
Detects the .uproject descriptor file for the Unreal project in the specified directory
"""
for project in glob.glob(os.path.join(dir, '*.uproject')):
return os.path.realpath(project)
# No project detected
raise UnrealManagerException('could not detect an Unrea... | Detects the .uproject descriptor file for the Unreal project in the specified directory | Below is the the instruction that describes the task:
### Input:
Detects the .uproject descriptor file for the Unreal project in the specified directory
### Response:
def getProjectDescriptor(self, dir):
"""
Detects the .uproject descriptor file for the Unreal project in the specified directory
"""
for pro... |
def add_item(self,item):
"""Add an item to `self`.
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `MucItemBase`
"""
if not isinstance(item,MucItemBase):
raise TypeError("Bad item type for muc#user")
item.as_xml(self.xmlnode) | Add an item to `self`.
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `MucItemBase` | Below is the the instruction that describes the task:
### Input:
Add an item to `self`.
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `MucItemBase`
### Response:
def add_item(self,item):
"""Add an item to `self`.
:Parameters:
- `item... |
def create_calc_dh_d_shape(estimator):
"""
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the shape parameters.
Parameters
----------
estimator : an instance of the estimation.LogitTypeE... | Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the shape parameters.
Parameters
----------
estimator : an instance of the estimation.LogitTypeEstimator class.
Should contain a `rows_to_a... | Below is the the instruction that describes the task:
### Input:
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the shape parameters.
Parameters
----------
estimator : an instance of the est... |
def _randomize_subject_list(data_list, random):
"""Randomly permute the voxels of a subject list.
The method shuffles the subject one by one in place according to
the random type. If RandomType.NORANDOM, return the original list.
Parameters
----------
data_list: list of 2D array in shape [nV... | Randomly permute the voxels of a subject list.
The method shuffles the subject one by one in place according to
the random type. If RandomType.NORANDOM, return the original list.
Parameters
----------
data_list: list of 2D array in shape [nVxels, nTRs]
Activity image data list to be shuf... | Below is the the instruction that describes the task:
### Input:
Randomly permute the voxels of a subject list.
The method shuffles the subject one by one in place according to
the random type. If RandomType.NORANDOM, return the original list.
Parameters
----------
data_list: list of 2D arra... |
def target_info_from_filename(filename):
"""Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png')."""
basename = osp.basename(filename)
storedir = osp.dirname(osp.abspath(filename))
target = filename.split(".")[-1]
return storedir, basename, target | Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png'). | Below is the the instruction that describes the task:
### Input:
Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png').
### Response:
def target_info_from_filename(filename):
"""Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png')."""
basename = osp.basename(filename)
store... |
def calculate(self, T, method):
r'''Method to calculate low-pressure liquid viscosity at tempearture
`T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperature at w... | r'''Method to calculate low-pressure liquid viscosity at tempearture
`T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperature at which to calculate viscosity, [K]
... | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate low-pressure liquid viscosity at tempearture
`T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float... |
def lazygo(watchFolder='../abfs/',reAnalyze=False,rebuildSite=False,
keepGoing=True,matching=False):
"""
continuously monitor a folder for new abfs and try to analyze them.
This is intended to watch only one folder, but can run multiple copies.
"""
abfsKnown=[]
while True:
pr... | continuously monitor a folder for new abfs and try to analyze them.
This is intended to watch only one folder, but can run multiple copies. | Below is the the instruction that describes the task:
### Input:
continuously monitor a folder for new abfs and try to analyze them.
This is intended to watch only one folder, but can run multiple copies.
### Response:
def lazygo(watchFolder='../abfs/',reAnalyze=False,rebuildSite=False,
keepGoing=Tr... |
def _get_view_media(self):
"""
Gather view-level media assets
"""
try:
css = self.Media.css
except AttributeError:
css = {}
try:
js = self.Media.js
except AttributeError:
js = []
return Media(css=css, js=js) | Gather view-level media assets | Below is the the instruction that describes the task:
### Input:
Gather view-level media assets
### Response:
def _get_view_media(self):
"""
Gather view-level media assets
"""
try:
css = self.Media.css
except AttributeError:
css = {}
try:
... |
def add_callback(self, fn, *args, **kwargs):
"""
Attaches a callback function to be called when the final results arrive.
By default, `fn` will be called with the results as the first and only
argument. If `*args` or `**kwargs` are supplied, they will be passed
through as addit... | Attaches a callback function to be called when the final results arrive.
By default, `fn` will be called with the results as the first and only
argument. If `*args` or `**kwargs` are supplied, they will be passed
through as additional positional or keyword arguments to `fn`.
If an err... | Below is the the instruction that describes the task:
### Input:
Attaches a callback function to be called when the final results arrive.
By default, `fn` will be called with the results as the first and only
argument. If `*args` or `**kwargs` are supplied, they will be passed
through as a... |
def offset_to_skydir(skydir, offset_lon, offset_lat,
coordsys='CEL', projection='AIT'):
"""Convert a cartesian offset (X,Y) in the given projection into
a SkyCoord."""
offset_lon = np.array(offset_lon, ndmin=1)
offset_lat = np.array(offset_lat, ndmin=1)
w = create_wcs(skydir, ... | Convert a cartesian offset (X,Y) in the given projection into
a SkyCoord. | Below is the the instruction that describes the task:
### Input:
Convert a cartesian offset (X,Y) in the given projection into
a SkyCoord.
### Response:
def offset_to_skydir(skydir, offset_lon, offset_lat,
coordsys='CEL', projection='AIT'):
"""Convert a cartesian offset (X,Y) in the gi... |
def get_content(self):
"""
Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
self.content = self.book.get_template('cover')
tree = parse_string(super(... | Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3).
:Returns:
Returns content of this document. | Below is the the instruction that describes the task:
### Input:
Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3).
:Returns:
Returns content of this document.
### Response:
def get_content(self):
"""
Returns content for... |
def replace(self, key, value):
"""
Convenience method provided as a way to replace a value mapped by a
key.This is required since a MergingDict always merges via assignment
of item/attribute.
:param key: Attribute name or item key to replace rvalue for.
:type key: object... | Convenience method provided as a way to replace a value mapped by a
key.This is required since a MergingDict always merges via assignment
of item/attribute.
:param key: Attribute name or item key to replace rvalue for.
:type key: object
:param value: The new value to assign.
... | Below is the the instruction that describes the task:
### Input:
Convenience method provided as a way to replace a value mapped by a
key.This is required since a MergingDict always merges via assignment
of item/attribute.
:param key: Attribute name or item key to replace rvalue for.
... |
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set_base_prompt()
cmd = self.RETURN + "rows 0" + self.RETURN
self.disable_paging(command=cmd) | Prepare the session after the connection has been established. | Below is the the instruction that describes the task:
### Input:
Prepare the session after the connection has been established.
### Response:
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set_base_prompt()
cmd = self.RETURN + "rows ... |
def generate_data_type(self, data_type):
"""Output a data type definition (a struct or union)."""
if isinstance(data_type, Struct):
# Output a struct definition.
self.emit('')
self.emit('struct %s' % data_type.name)
with self.indent():
if d... | Output a data type definition (a struct or union). | Below is the the instruction that describes the task:
### Input:
Output a data type definition (a struct or union).
### Response:
def generate_data_type(self, data_type):
"""Output a data type definition (a struct or union)."""
if isinstance(data_type, Struct):
# Output a struct definit... |
def merge_files(sources, destination):
"""Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return:
"""
with open(destination, 'w') as hout:
for f in sources:
if os.pa... | Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return: | Below is the the instruction that describes the task:
### Input:
Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return:
### Response:
def merge_files(sources, destination):
"""Copy content... |
async def execute(self, fn, *args, **kwargs) -> None:
'''Execute an arbitrary function outside the event loop using
a shared Executor.'''
fn = functools.partial(fn, *args, **kwargs)
return await self.loop.run_in_executor(self.executor, fn) | Execute an arbitrary function outside the event loop using
a shared Executor. | Below is the the instruction that describes the task:
### Input:
Execute an arbitrary function outside the event loop using
a shared Executor.
### Response:
async def execute(self, fn, *args, **kwargs) -> None:
'''Execute an arbitrary function outside the event loop using
a shared Executor.... |
def jarSources(target, source, env, for_signature):
"""Only include sources that are not a manifest file."""
try:
env['JARCHDIR']
except KeyError:
jarchdir_set = False
else:
jarchdir_set = True
jarchdir = env.subst('$JARCHDIR', target=target, source=source)
if jar... | Only include sources that are not a manifest file. | Below is the the instruction that describes the task:
### Input:
Only include sources that are not a manifest file.
### Response:
def jarSources(target, source, env, for_signature):
"""Only include sources that are not a manifest file."""
try:
env['JARCHDIR']
except KeyError:
jarchdir_s... |
def insert(self, nodes, pos):
# TODO: check docstring
"""Inserts all nodes from `nodes` list into this route at position `pos`
Parameters
----------
nodes : type
Desc
pos : type
Desc
"""
node_list = []
... | Inserts all nodes from `nodes` list into this route at position `pos`
Parameters
----------
nodes : type
Desc
pos : type
Desc | Below is the the instruction that describes the task:
### Input:
Inserts all nodes from `nodes` list into this route at position `pos`
Parameters
----------
nodes : type
Desc
pos : type
Desc
### Response:
def insert(self, nodes, pos):
# TODO:... |
def stream(self, report, callback=None):
"""Queue data for streaming
Args:
report (IOTileReport): A report object to stream to a client
callback (callable): An optional callback that will be called with
a bool value of True when this report actually gets streamed... | Queue data for streaming
Args:
report (IOTileReport): A report object to stream to a client
callback (callable): An optional callback that will be called with
a bool value of True when this report actually gets streamed.
If the client disconnects and the ... | Below is the the instruction that describes the task:
### Input:
Queue data for streaming
Args:
report (IOTileReport): A report object to stream to a client
callback (callable): An optional callback that will be called with
a bool value of True when this report actua... |
def create_port(self, port):
"""Enqueue port create"""
instance_type = self.get_instance_type(port)
if not instance_type:
return
port_type = instance_type + a_const.PORT_SUFFIX
p_res = MechResource(port['id'], port_type, a_const.CREATE)
self.provision_queue.pu... | Enqueue port create | Below is the the instruction that describes the task:
### Input:
Enqueue port create
### Response:
def create_port(self, port):
"""Enqueue port create"""
instance_type = self.get_instance_type(port)
if not instance_type:
return
port_type = instance_type + a_const.PORT_SU... |
def _buffer_ini(data, sample_rate):
"""
Initializes the buffer with eight 1s intervals
----------
Parameters
----------
data : ndarray
Pre-processed ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
rr_buffe... | Initializes the buffer with eight 1s intervals
----------
Parameters
----------
data : ndarray
Pre-processed ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
rr_buffer : list
Data structure that stores eigh... | Below is the the instruction that describes the task:
### Input:
Initializes the buffer with eight 1s intervals
----------
Parameters
----------
data : ndarray
Pre-processed ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
... |
def concretize(self, memory, addr):
"""
Concretizes the address into a list of values.
If this strategy cannot handle this address, returns None.
"""
if self._filter is None or self._filter(memory, addr):
return self._concretize(memory, addr) | Concretizes the address into a list of values.
If this strategy cannot handle this address, returns None. | Below is the the instruction that describes the task:
### Input:
Concretizes the address into a list of values.
If this strategy cannot handle this address, returns None.
### Response:
def concretize(self, memory, addr):
"""
Concretizes the address into a list of values.
If this str... |
def prepare(self):
"""Prepare the incoming request, checking to see the request is sending
JSON content in the request body. If so, the content is decoded and
assigned to the json_arguments attribute.
"""
super(RequestHandler, self).prepare()
if self.request.headers.get(... | Prepare the incoming request, checking to see the request is sending
JSON content in the request body. If so, the content is decoded and
assigned to the json_arguments attribute. | Below is the the instruction that describes the task:
### Input:
Prepare the incoming request, checking to see the request is sending
JSON content in the request body. If so, the content is decoded and
assigned to the json_arguments attribute.
### Response:
def prepare(self):
"""Prepare the... |
def compare_container_networks(first, second):
'''
.. versionadded:: 2018.3.0
Returns the differences between two containers' networks. When a network is
only present one of the two containers, that network's diff will simply be
represented with ``True`` for the side of the diff in which the networ... | .. versionadded:: 2018.3.0
Returns the differences between two containers' networks. When a network is
only present one of the two containers, that network's diff will simply be
represented with ``True`` for the side of the diff in which the network is
present) and ``False`` for the side of the diff in... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2018.3.0
Returns the differences between two containers' networks. When a network is
only present one of the two containers, that network's diff will simply be
represented with ``True`` for the side of the diff in which ... |
def _make_passage_kwargs(urn, reference):
""" Little helper used by CapitainsCtsPassage here to comply with parents args
:param urn: URN String
:param reference: Reference String
:return: Dictionary of arguments with URN based on identifier and reference
"""
kwargs = {}
if urn is not None:
... | Little helper used by CapitainsCtsPassage here to comply with parents args
:param urn: URN String
:param reference: Reference String
:return: Dictionary of arguments with URN based on identifier and reference | Below is the the instruction that describes the task:
### Input:
Little helper used by CapitainsCtsPassage here to comply with parents args
:param urn: URN String
:param reference: Reference String
:return: Dictionary of arguments with URN based on identifier and reference
### Response:
def _make_pass... |
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
... | Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return: | Below is the the instruction that describes the task:
### Input:
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
### Response:
def __dump_compose_file(path, compose_result, success_msg, already... |
def returns(*checkers_args):
""" Create a decorator for validating function return values.
Parameters
----------
checkers_args: positional arguments
A single functions to apply to the output of the decorated function. If a tuple is returned
by the decorated function, multiple function ... | Create a decorator for validating function return values.
Parameters
----------
checkers_args: positional arguments
A single functions to apply to the output of the decorated function. If a tuple is returned
by the decorated function, multiple function can be listed and are assumed to matc... | Below is the the instruction that describes the task:
### Input:
Create a decorator for validating function return values.
Parameters
----------
checkers_args: positional arguments
A single functions to apply to the output of the decorated function. If a tuple is returned
by the decora... |
def timeCall(*funcAndArgs, **kwargs):
r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)``
"""
func, args = func... | r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)`` | Below is the the instruction that describes the task:
### Input:
r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)``
###... |
def subst_src_suffixes(self, env):
"""
The suffix list may contain construction variable expansions,
so we have to evaluate the individual strings. To avoid doing
this over and over, we memoize the results for each construction
environment.
"""
memo_key = id(env)... | The suffix list may contain construction variable expansions,
so we have to evaluate the individual strings. To avoid doing
this over and over, we memoize the results for each construction
environment. | Below is the the instruction that describes the task:
### Input:
The suffix list may contain construction variable expansions,
so we have to evaluate the individual strings. To avoid doing
this over and over, we memoize the results for each construction
environment.
### Response:
def subst... |
def mouse_button_callback(self, window, button, action, mods):
"""
Handle mouse button events and forward them to the example
"""
# Offset button index by 1 to make it match the other libraries
button += 1
# Support left and right mouse button for now
if bu... | Handle mouse button events and forward them to the example | Below is the the instruction that describes the task:
### Input:
Handle mouse button events and forward them to the example
### Response:
def mouse_button_callback(self, window, button, action, mods):
"""
Handle mouse button events and forward them to the example
"""
# Offset bu... |
def wait_for_array(self, wait_for, timeout_ms):
"""Waits for one or more events to happen.
Scriptable version of :py:func:`wait_for` .
in wait_for of type :class:`GuestSessionWaitForFlag`
Specifies what to wait for;
see :py:class:`GuestSessionWaitForFlag` for more infor... | Waits for one or more events to happen.
Scriptable version of :py:func:`wait_for` .
in wait_for of type :class:`GuestSessionWaitForFlag`
Specifies what to wait for;
see :py:class:`GuestSessionWaitForFlag` for more information.
in timeout_ms of type int
Time... | Below is the the instruction that describes the task:
### Input:
Waits for one or more events to happen.
Scriptable version of :py:func:`wait_for` .
in wait_for of type :class:`GuestSessionWaitForFlag`
Specifies what to wait for;
see :py:class:`GuestSessionWaitForFlag` for ... |
def SetupAuth(self,
project_id=None,
project_number=None,
service_account_json_file=None):
"""Sets up authentication with Google APIs.
This will use the credentials from service_account_json_file if provided,
falling back to application default credentials.
... | Sets up authentication with Google APIs.
This will use the credentials from service_account_json_file if provided,
falling back to application default credentials.
See https://cloud.google.com/docs/authentication/production.
Args:
project_id: GCP project ID (e.g. myproject). If not provided, wil... | Below is the the instruction that describes the task:
### Input:
Sets up authentication with Google APIs.
This will use the credentials from service_account_json_file if provided,
falling back to application default credentials.
See https://cloud.google.com/docs/authentication/production.
Args:
... |
def _create_feed_dict(self, data):
"""Create the dictionary of data to feed to tf session during training.
:param data: training/validation set batch
:return: dictionary(self.input_data: data, self.hrand: random_uniform,
self.vrand: random_uniform)
"""
... | Create the dictionary of data to feed to tf session during training.
:param data: training/validation set batch
:return: dictionary(self.input_data: data, self.hrand: random_uniform,
self.vrand: random_uniform) | Below is the the instruction that describes the task:
### Input:
Create the dictionary of data to feed to tf session during training.
:param data: training/validation set batch
:return: dictionary(self.input_data: data, self.hrand: random_uniform,
self.vrand: random_unif... |
def setup_to_argv(setup):
'''
:param dict setup:
A dict previously gotten from process_command_line.
:note: does not handle --file nor --DEBUG.
'''
ret = [get_pydevd_file()]
for handler in ACCEPTED_ARG_HANDLERS:
if handler.arg_name in setup:
handler.to_argv(ret, set... | :param dict setup:
A dict previously gotten from process_command_line.
:note: does not handle --file nor --DEBUG. | Below is the the instruction that describes the task:
### Input:
:param dict setup:
A dict previously gotten from process_command_line.
:note: does not handle --file nor --DEBUG.
### Response:
def setup_to_argv(setup):
'''
:param dict setup:
A dict previously gotten from process_comman... |
def should_see_link_text(self, link_text, link_url):
"""Assert a link with the provided text points to the provided URL."""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"][./text()="%s"]' % (link_url, link_text)),
filter_displayed=True,
)
if not elements:
... | Assert a link with the provided text points to the provided URL. | Below is the the instruction that describes the task:
### Input:
Assert a link with the provided text points to the provided URL.
### Response:
def should_see_link_text(self, link_text, link_url):
"""Assert a link with the provided text points to the provided URL."""
elements = ElementSelector(
wo... |
def set_redirect(self, url, status=HttpStatusCodes.HTTP_303):
"""Helper method to set a redirect response.
Args:
url (:obj:`str`): URL to redirect to
status (:obj:`str`, optional): Status code of the response
"""
self.set_status(status)
self.set_content('... | Helper method to set a redirect response.
Args:
url (:obj:`str`): URL to redirect to
status (:obj:`str`, optional): Status code of the response | Below is the the instruction that describes the task:
### Input:
Helper method to set a redirect response.
Args:
url (:obj:`str`): URL to redirect to
status (:obj:`str`, optional): Status code of the response
### Response:
def set_redirect(self, url, status=HttpStatusCodes.HTTP_303... |
def _read_value(path):
"""
Reads value of specified path.
:param path: A valid system path
"""
read_value = 0
if not os.path.exists(path):
# Path will generally only exist on a Raspberry Pi
pass
else:
with open(path) as f:
read_value = int(f.read())
re... | Reads value of specified path.
:param path: A valid system path | Below is the the instruction that describes the task:
### Input:
Reads value of specified path.
:param path: A valid system path
### Response:
def _read_value(path):
"""
Reads value of specified path.
:param path: A valid system path
"""
read_value = 0
if not os.path.exists(path):
... |
def levels_to_accepting_states(self) -> dict:
"""Return a dict from states to level, i.e. the number of steps to reach any accepting state.
level = -1 if the state cannot reach any accepting state"""
res = {accepting_state: 0 for accepting_state in self._accepting_states}
level = 0
... | Return a dict from states to level, i.e. the number of steps to reach any accepting state.
level = -1 if the state cannot reach any accepting state | Below is the the instruction that describes the task:
### Input:
Return a dict from states to level, i.e. the number of steps to reach any accepting state.
level = -1 if the state cannot reach any accepting state
### Response:
def levels_to_accepting_states(self) -> dict:
"""Return a dict from stat... |
def add_clause(self, clause, no_return=True):
"""
Add a new clause to solver's internal formula.
"""
if self.maplesat:
res = pysolvers.maplesat_add_cl(self.maplesat, clause)
if res == False:
self.status = False
if not no_return:
... | Add a new clause to solver's internal formula. | Below is the the instruction that describes the task:
### Input:
Add a new clause to solver's internal formula.
### Response:
def add_clause(self, clause, no_return=True):
"""
Add a new clause to solver's internal formula.
"""
if self.maplesat:
res = pysolvers.maple... |
def get_checkpoint_path(model_path):
"""
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
"""
if os.path.basename(model_path) == model_path:
model_path = os.path.... | Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader | Below is the the instruction that describes the task:
### Input:
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
### Response:
def get_checkpoint_path(model_path):
"""
Work... |
def _read_from_seg(self, n):
"""Read from current seg.
Args:
n: max number of bytes to read.
Returns:
valid bytes from the current seg. "" if no more is left.
"""
result = self._seg.read(size=n)
if result == "":
return result
offset = self._seg.tell()
if offset > self... | Read from current seg.
Args:
n: max number of bytes to read.
Returns:
valid bytes from the current seg. "" if no more is left. | Below is the the instruction that describes the task:
### Input:
Read from current seg.
Args:
n: max number of bytes to read.
Returns:
valid bytes from the current seg. "" if no more is left.
### Response:
def _read_from_seg(self, n):
"""Read from current seg.
Args:
n: max numb... |
def uvw(self, context):
""" Supply UVW antenna coordinates to montblanc """
# Shape (ntime, na, 3)
(lt, ut), (la, ua), (l, u) = context.array_extents(context.name)
# Create empty UVW coordinates
data = np.empty(context.shape, context.dtype)
data[:,:,0] = np.arange(la+1,... | Supply UVW antenna coordinates to montblanc | Below is the the instruction that describes the task:
### Input:
Supply UVW antenna coordinates to montblanc
### Response:
def uvw(self, context):
""" Supply UVW antenna coordinates to montblanc """
# Shape (ntime, na, 3)
(lt, ut), (la, ua), (l, u) = context.array_extents(context.name)
... |
def iso8601_date(s):
"""
Parses an ISO 8601 date string and returns a UTC date object or the string
if the parsing failed.
:param s: ISO 8601-formatted date string (2015-01-25)
:return:
"""
try:
return datetime.datetime.strptime(s, ISO8601_DATE_FORMAT).replace(tzinfo=pytz.utc).date()... | Parses an ISO 8601 date string and returns a UTC date object or the string
if the parsing failed.
:param s: ISO 8601-formatted date string (2015-01-25)
:return: | Below is the the instruction that describes the task:
### Input:
Parses an ISO 8601 date string and returns a UTC date object or the string
if the parsing failed.
:param s: ISO 8601-formatted date string (2015-01-25)
:return:
### Response:
def iso8601_date(s):
"""
Parses an ISO 8601 date string... |
def _load_script(self, filename: str) -> Script:
"""Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute.
"""
with open(path.join(here,... | Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute. | Below is the the instruction that describes the task:
### Input:
Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute.
### Response:
def _load_script(self... |
def remote_startCommand(self, stepref, stepId, command, args):
"""
This gets invoked by L{buildbot.process.step.RemoteCommand.start}, as
part of various master-side BuildSteps, to start various commands
that actually do the build. I return nothing. Eventually I will call
.command... | This gets invoked by L{buildbot.process.step.RemoteCommand.start}, as
part of various master-side BuildSteps, to start various commands
that actually do the build. I return nothing. Eventually I will call
.commandComplete() to notify the master-side RemoteCommand that I'm
done. | Below is the the instruction that describes the task:
### Input:
This gets invoked by L{buildbot.process.step.RemoteCommand.start}, as
part of various master-side BuildSteps, to start various commands
that actually do the build. I return nothing. Eventually I will call
.commandComplete() to ... |
def farps(self) -> typing.Iterator['Static']:
"""
Returns: generator over all FARPs in this coalition
"""
for static in self.statics:
if static.static_is_farp:
yield static | Returns: generator over all FARPs in this coalition | Below is the the instruction that describes the task:
### Input:
Returns: generator over all FARPs in this coalition
### Response:
def farps(self) -> typing.Iterator['Static']:
"""
Returns: generator over all FARPs in this coalition
"""
for static in self.statics:
if st... |
def maybe_show_tree(walker, ast):
"""
Show the ast based on the showast flag (or file object), writing to the
appropriate stream depending on the type of the flag.
:param show_tree: Flag which determines whether the parse tree is
written to sys.stdout or not. (It is also to pass a... | Show the ast based on the showast flag (or file object), writing to the
appropriate stream depending on the type of the flag.
:param show_tree: Flag which determines whether the parse tree is
written to sys.stdout or not. (It is also to pass a file
like object, into ... | Below is the the instruction that describes the task:
### Input:
Show the ast based on the showast flag (or file object), writing to the
appropriate stream depending on the type of the flag.
:param show_tree: Flag which determines whether the parse tree is
written to sys.stdout or not... |
def _os_name_factory(settings):
"""Factory for the :r:`software_os setting` default.
"""
# pylint: disable-msg=W0613,W0142
return u"{0} {1} {2}".format(platform.system(), platform.release(),
platform.machine()) | Factory for the :r:`software_os setting` default. | Below is the the instruction that describes the task:
### Input:
Factory for the :r:`software_os setting` default.
### Response:
def _os_name_factory(settings):
"""Factory for the :r:`software_os setting` default.
"""
# pylint: disable-msg=W0613,W0142
return u"{0} {1} {2}".format(platform.system(),... |
def api(feature='conditions', city='Portland', state='OR', key=None):
"""Use the wunderground API to get current conditions instead of scraping
Please be kind and use your own key (they're FREE!):
http://www.wunderground.com/weather/api/d/login.html
References:
http://www.wunderground.com/weat... | Use the wunderground API to get current conditions instead of scraping
Please be kind and use your own key (they're FREE!):
http://www.wunderground.com/weather/api/d/login.html
References:
http://www.wunderground.com/weather/api/d/terms.html
Examples:
>>> api('hurric', 'Boise', 'ID') ... | Below is the the instruction that describes the task:
### Input:
Use the wunderground API to get current conditions instead of scraping
Please be kind and use your own key (they're FREE!):
http://www.wunderground.com/weather/api/d/login.html
References:
http://www.wunderground.com/weather/api/... |
def plan_first_phase(N1, N2):
"""
Create a plan for the first stage of the pruned FFT operation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
plan : FFTWF plan
... | Create a plan for the first stage of the pruned FFT operation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
plan : FFTWF plan
The plan for performing the first phase ... | Below is the the instruction that describes the task:
### Input:
Create a plan for the first stage of the pruned FFT operation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
... |
def is_birthday(self, dt=None):
"""
Check if its the birthday.
Compares the date/month values of the two dates.
:rtype: bool
"""
if dt is None:
dt = self.now(self.tz)
instance = pendulum.instance(dt)
return (self.month, self.day) == (instanc... | Check if its the birthday.
Compares the date/month values of the two dates.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if its the birthday.
Compares the date/month values of the two dates.
:rtype: bool
### Response:
def is_birthday(self, dt=None):
"""
Check if its the birthday.
Compares the date/month values of the two d... |
def update_derived_metric(self, id, **kwargs): # noqa: E501
"""Update a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.upd... | Update a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_derived_metric(id, async_req=True)
>>> result = thread.get()... | Below is the the instruction that describes the task:
### Input:
Update a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update... |
def _fix_overlapping_graphics( spansStartingFrom ):
''' Provides a fix for overlapping annotations that are formatted graphically
(underlined or printed in non-default color).
If two graphically formatted annotations overlap, and if one annotation,
say A, ends within another an... | Provides a fix for overlapping annotations that are formatted graphically
(underlined or printed in non-default color).
If two graphically formatted annotations overlap, and if one annotation,
say A, ends within another annotation, say B, then ending of graphics of A
also c... | Below is the the instruction that describes the task:
### Input:
Provides a fix for overlapping annotations that are formatted graphically
(underlined or printed in non-default color).
If two graphically formatted annotations overlap, and if one annotation,
say A, ends within an... |
def get_counter(self, name=None):
'''Shortcut for getting a :class:`~statsd.counter.Counter` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
'''
return self.get_client(name=name, class_=statsd.Counter) | Shortcut for getting a :class:`~statsd.counter.Counter` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str | Below is the the instruction that describes the task:
### Input:
Shortcut for getting a :class:`~statsd.counter.Counter` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
### Response:
def get_counter(self, name=None):
'''Shortcut for getting a :class:`~s... |
def evalRanges(self, datetimeString, sourceTime=None):
"""
Evaluate the C{datetimeString} text and determine if
it represents a date or time range.
@type datetimeString: string
@param datetimeString: datetime text to evaluate
@type sourceTime: struct_time
@... | Evaluate the C{datetimeString} text and determine if
it represents a date or time range.
@type datetimeString: string
@param datetimeString: datetime text to evaluate
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
@rty... | Below is the the instruction that describes the task:
### Input:
Evaluate the C{datetimeString} text and determine if
it represents a date or time range.
@type datetimeString: string
@param datetimeString: datetime text to evaluate
@type sourceTime: struct_time
@param ... |
def resolve_cert_reqs(candidate):
"""
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbrevi... | Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbreviation.
(So you can specify `REQUIRED` inst... | Below is the the instruction that describes the task:
### Input:
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl... |
def disconnect_relationship(cls, id, related_collection_name, request_json):
"""
Disconnect one or more relationship in a collection with cardinality 'Many'.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \
be set in the mo... | Disconnect one or more relationship in a collection with cardinality 'Many'.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \
be set in the model -- it is not the same as the node id
:param related_collection_name: The name of the ... | Below is the the instruction that describes the task:
### Input:
Disconnect one or more relationship in a collection with cardinality 'Many'.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \
be set in the model -- it is not the same as... |
def from_arrays(**arrays):
"""Create an in memory DataFrame from numpy arrays.
Example
>>> import vaex, numpy as np
>>> x = np.arange(5)
>>> y = x ** 2
>>> vaex.from_arrays(x=x, y=y)
# x y
0 0 0
1 1 1
2 2 4
3 3 9
4 4 16
... | Create an in memory DataFrame from numpy arrays.
Example
>>> import vaex, numpy as np
>>> x = np.arange(5)
>>> y = x ** 2
>>> vaex.from_arrays(x=x, y=y)
# x y
0 0 0
1 1 1
2 2 4
3 3 9
4 4 16
>>> some_dict = {'x': x, 'y': y}
... | Below is the the instruction that describes the task:
### Input:
Create an in memory DataFrame from numpy arrays.
Example
>>> import vaex, numpy as np
>>> x = np.arange(5)
>>> y = x ** 2
>>> vaex.from_arrays(x=x, y=y)
# x y
0 0 0
1 1 1
2 2 4
... |
def resolve_colors(self, colorstack):
'Returns the curses attribute for the colorstack, a list of color option names sorted highest-precedence color first.'
attr = CursesAttr()
for coloropt in colorstack:
c = self.get_color(coloropt)
attr = attr.update_attr(c)
ret... | Returns the curses attribute for the colorstack, a list of color option names sorted highest-precedence color first. | Below is the the instruction that describes the task:
### Input:
Returns the curses attribute for the colorstack, a list of color option names sorted highest-precedence color first.
### Response:
def resolve_colors(self, colorstack):
'Returns the curses attribute for the colorstack, a list of color option ... |
def iter_org_events(self, org, number=-1, etag=None):
"""Iterate over events as they appear on the user's organization
dashboard. You must be authenticated to view this.
:param str org: (required), name of the organization
:param int number: (optional), number of events to return. Defau... | Iterate over events as they appear on the user's organization
dashboard. You must be authenticated to view this.
:param str org: (required), name of the organization
:param int number: (optional), number of events to return. Default: -1
returns all available events
:param st... | Below is the the instruction that describes the task:
### Input:
Iterate over events as they appear on the user's organization
dashboard. You must be authenticated to view this.
:param str org: (required), name of the organization
:param int number: (optional), number of events to return. D... |
def records(self):
"""
Parse the DIAMOND output and yield records. This will be used to read
original DIAMOND output (either from stdin or from a file) to turn the
DIAMOND results into Python dictionaries that will then be stored in
our JSON format.
@return: A generator ... | Parse the DIAMOND output and yield records. This will be used to read
original DIAMOND output (either from stdin or from a file) to turn the
DIAMOND results into Python dictionaries that will then be stored in
our JSON format.
@return: A generator that produces C{dict}s containing 'alig... | Below is the the instruction that describes the task:
### Input:
Parse the DIAMOND output and yield records. This will be used to read
original DIAMOND output (either from stdin or from a file) to turn the
DIAMOND results into Python dictionaries that will then be stored in
our JSON format.
... |
def plot_compare(self, other_plotter):
"""
plot two band structure for comparison. One is in red the other in blue.
The two band structures need to be defined on the same symmetry lines!
and the distance between symmetry lines is
the one of the band structure used to build the Ph... | plot two band structure for comparison. One is in red the other in blue.
The two band structures need to be defined on the same symmetry lines!
and the distance between symmetry lines is
the one of the band structure used to build the PhononBSPlotter
Args:
another PhononBSPl... | Below is the the instruction that describes the task:
### Input:
plot two band structure for comparison. One is in red the other in blue.
The two band structures need to be defined on the same symmetry lines!
and the distance between symmetry lines is
the one of the band structure used to bu... |
def unifrac(self, weighted=True, rank="auto"):
"""A beta diversity metric that takes into account the relative relatedness of community
members. Weighted UniFrac looks at abundances, unweighted UniFrac looks at presence.
Parameters
----------
weighted : `bool`
Calcul... | A beta diversity metric that takes into account the relative relatedness of community
members. Weighted UniFrac looks at abundances, unweighted UniFrac looks at presence.
Parameters
----------
weighted : `bool`
Calculate the weighted (True) or unweighted (False) distance met... | Below is the the instruction that describes the task:
### Input:
A beta diversity metric that takes into account the relative relatedness of community
members. Weighted UniFrac looks at abundances, unweighted UniFrac looks at presence.
Parameters
----------
weighted : `bool`
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.