code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def create(att_name: str, parsed_att: S, attribute_type: Type[T], caught_exec: Dict[Converter[S, T], Exception]):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param att_name... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param att_name:
:param parsed_att:
:param attribute_type:
:param caught_exec:
:return: | Below is the the instruction that describes the task:
### Input:
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param att_name:
:param parsed_att:
:param attribute_type:
... |
def get_my_hostname(self, split_hostname_on_first_period=False):
"""
Returns a best guess for the hostname registered with OpenStack for this host
"""
hostname = self.init_config.get("os_host") or self.hostname
if split_hostname_on_first_period:
hostname = hostname.s... | Returns a best guess for the hostname registered with OpenStack for this host | Below is the the instruction that describes the task:
### Input:
Returns a best guess for the hostname registered with OpenStack for this host
### Response:
def get_my_hostname(self, split_hostname_on_first_period=False):
"""
Returns a best guess for the hostname registered with OpenStack for this ... |
def get(self, event):
"""Get a stored configuration"""
try:
comp = event.data['uuid']
except KeyError:
comp = None
if not comp:
self.log('Invalid get request without schema or component',
lvl=error)
return
se... | Get a stored configuration | Below is the the instruction that describes the task:
### Input:
Get a stored configuration
### Response:
def get(self, event):
"""Get a stored configuration"""
try:
comp = event.data['uuid']
except KeyError:
comp = None
if not comp:
self.log('I... |
def plotFCM(data, channel_names, kind='histogram', ax=None,
autolabel=True, xlabel_kwargs={}, ylabel_kwargs={},
colorbar=False, grid=False,
**kwargs):
"""
Plots the sample on the current axis.
Follow with a call to matplotlibs show() in order to see the plot.
Parame... | Plots the sample on the current axis.
Follow with a call to matplotlibs show() in order to see the plot.
Parameters
----------
data : DataFrame
{graph_plotFCM_pars}
{common_plot_ax}
Returns
-------
The output of the plot command used | Below is the the instruction that describes the task:
### Input:
Plots the sample on the current axis.
Follow with a call to matplotlibs show() in order to see the plot.
Parameters
----------
data : DataFrame
{graph_plotFCM_pars}
{common_plot_ax}
Returns
-------
The output of ... |
def print_png(o):
"""
A function to display sympy expression using inline style LaTeX in PNG.
"""
s = latex(o, mode='inline')
# mathtext does not understand certain latex flags, so we try to replace
# them with suitable subs.
s = s.replace('\\operatorname','')
s = s.replace('\\overline',... | A function to display sympy expression using inline style LaTeX in PNG. | Below is the the instruction that describes the task:
### Input:
A function to display sympy expression using inline style LaTeX in PNG.
### Response:
def print_png(o):
"""
A function to display sympy expression using inline style LaTeX in PNG.
"""
s = latex(o, mode='inline')
# mathtext does no... |
def from_sky(cls, distancelimit=15, magnitudelimit=18):
'''
Create a Constellation from a criteria search of the whole sky.
Parameters
----------
distancelimit : float
Maximum distance (parsecs).
magnitudelimit : float
Maximum magnitude (for Gaia ... | Create a Constellation from a criteria search of the whole sky.
Parameters
----------
distancelimit : float
Maximum distance (parsecs).
magnitudelimit : float
Maximum magnitude (for Gaia G). | Below is the the instruction that describes the task:
### Input:
Create a Constellation from a criteria search of the whole sky.
Parameters
----------
distancelimit : float
Maximum distance (parsecs).
magnitudelimit : float
Maximum magnitude (for Gaia G).
###... |
def analyzeParameters(expName, suite):
"""
Analyze the impact of each list parameter in this experiment
"""
print("\n================",expName,"=====================")
try:
expParams = suite.get_params(expName)
pprint.pprint(expParams)
for p in ["boost_strength", "k", "learning_rate", "weight_spa... | Analyze the impact of each list parameter in this experiment | Below is the the instruction that describes the task:
### Input:
Analyze the impact of each list parameter in this experiment
### Response:
def analyzeParameters(expName, suite):
"""
Analyze the impact of each list parameter in this experiment
"""
print("\n================",expName,"=====================")... |
def uuid_from_kronos_time(time, _type=UUIDType.RANDOM):
"""
Generate a UUID with the specified time.
If `lowest` is true, return the lexicographically first UUID for the specified
time.
"""
return timeuuid_from_time(int(time) + UUID_TIME_OFFSET, type=_type) | Generate a UUID with the specified time.
If `lowest` is true, return the lexicographically first UUID for the specified
time. | Below is the the instruction that describes the task:
### Input:
Generate a UUID with the specified time.
If `lowest` is true, return the lexicographically first UUID for the specified
time.
### Response:
def uuid_from_kronos_time(time, _type=UUIDType.RANDOM):
"""
Generate a UUID with the specified time.
... |
def show_firmware_version_output_show_firmware_version_node_info_firmware_version_info_application_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
out... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_firmware_version_output_show_firmware_version_node_info_firmware_version_info_application_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_f... |
def send(self, test=None):
'''
Send the email through the Postmark system.
Pass test=True to just print out the resulting
JSON message being sent to Postmark
'''
self._check_values()
# Set up message dictionary
json_message = self.to_json_message()
... | Send the email through the Postmark system.
Pass test=True to just print out the resulting
JSON message being sent to Postmark | Below is the the instruction that describes the task:
### Input:
Send the email through the Postmark system.
Pass test=True to just print out the resulting
JSON message being sent to Postmark
### Response:
def send(self, test=None):
'''
Send the email through the Postmark system.
... |
def _list_files(self, args):
'''
List files for an installed package
'''
if len(args) < 2:
raise SPMInvocationError('A package name must be specified')
package = args[-1]
files = self._pkgdb_fun('list_files', package, self.db_conn)
if files is None:
... | List files for an installed package | Below is the the instruction that describes the task:
### Input:
List files for an installed package
### Response:
def _list_files(self, args):
'''
List files for an installed package
'''
if len(args) < 2:
raise SPMInvocationError('A package name must be specified')
... |
def to_json(df, x, y, timeseries=False):
"""Format output for json response."""
values = {k: [] for k in y}
for i, row in df.iterrows():
for yy in y:
values[yy].append({
"x": row[x],
"y": row[yy]
})
r... | Format output for json response. | Below is the the instruction that describes the task:
### Input:
Format output for json response.
### Response:
def to_json(df, x, y, timeseries=False):
"""Format output for json response."""
values = {k: [] for k in y}
for i, row in df.iterrows():
for yy in y:
v... |
def heightmap_get_normal(
hm: np.ndarray, x: float, y: float, waterLevel: float
) -> Tuple[float, float, float]:
"""Return the map normal at given coordinates.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
x (float): The x coordinate.
y (float): The y ... | Return the map normal at given coordinates.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
x (float): The x coordinate.
y (float): The y coordinate.
waterLevel (float): The heightmap is considered flat below this value.
Returns:
Tuple[float... | Below is the the instruction that describes the task:
### Input:
Return the map normal at given coordinates.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
x (float): The x coordinate.
y (float): The y coordinate.
waterLevel (float): The heightmap i... |
def cipher(self):
""" Generate AES-cipher
:return: Crypto.Cipher.AES.AESCipher
"""
#cipher = pyAES.new(*self.mode().aes_args(), **self.mode().aes_kwargs())
cipher = Cipher(*self.mode().aes_args(), **self.mode().aes_kwargs())
return WAES.WAESCipher(cipher) | Generate AES-cipher
:return: Crypto.Cipher.AES.AESCipher | Below is the the instruction that describes the task:
### Input:
Generate AES-cipher
:return: Crypto.Cipher.AES.AESCipher
### Response:
def cipher(self):
""" Generate AES-cipher
:return: Crypto.Cipher.AES.AESCipher
"""
#cipher = pyAES.new(*self.mode().aes_args(), **self.mode().aes_kwargs())
cipher = ... |
async def vcx_agent_provision(config: str) -> None:
"""
Provision an agent in the agency, populate configuration and wallet for this agent.
Example:
import json
enterprise_config = {
'agency_url': 'http://localhost:8080',
'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
'agency_verkey... | Provision an agent in the agency, populate configuration and wallet for this agent.
Example:
import json
enterprise_config = {
'agency_url': 'http://localhost:8080',
'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
'agency_verkey': "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR",
'wall... | Below is the the instruction that describes the task:
### Input:
Provision an agent in the agency, populate configuration and wallet for this agent.
Example:
import json
enterprise_config = {
'agency_url': 'http://localhost:8080',
'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
'agency_v... |
def exists(hdfs_path, user=None):
"""
Return :obj:`True` if ``hdfs_path`` exists in the default HDFS.
"""
hostname, port, path = split(hdfs_path, user=user)
fs = hdfs_fs.hdfs(hostname, port)
retval = fs.exists(path)
fs.close()
return retval | Return :obj:`True` if ``hdfs_path`` exists in the default HDFS. | Below is the the instruction that describes the task:
### Input:
Return :obj:`True` if ``hdfs_path`` exists in the default HDFS.
### Response:
def exists(hdfs_path, user=None):
"""
Return :obj:`True` if ``hdfs_path`` exists in the default HDFS.
"""
hostname, port, path = split(hdfs_path, user=user)... |
def parser_functions(self) -> List['ParserFunction']:
"""Return a list of parser function objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
ParserFunction(_lststr, _type_to_spans, span, 'ParserFunction')
for span in self._subspans('P... | Return a list of parser function objects. | Below is the the instruction that describes the task:
### Input:
Return a list of parser function objects.
### Response:
def parser_functions(self) -> List['ParserFunction']:
"""Return a list of parser function objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
... |
def loudest_time(self, start=0, duration=0):
"""Find the loudest time in the window given by start and duration
Returns frame number in context of entire track, not just the window.
:param integer start: Start frame
:param integer duration: Number of frames to consider from start
... | Find the loudest time in the window given by start and duration
Returns frame number in context of entire track, not just the window.
:param integer start: Start frame
:param integer duration: Number of frames to consider from start
:returns: Frame number of loudest frame
:rtype... | Below is the the instruction that describes the task:
### Input:
Find the loudest time in the window given by start and duration
Returns frame number in context of entire track, not just the window.
:param integer start: Start frame
:param integer duration: Number of frames to consider from... |
def parse(self, rrstr):
# type: (bytes) -> int
'''
Parse a Rock Ridge POSIX File Attributes record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
A string representing the RR version, either 1.09 or 1.12.
'''
... | Parse a Rock Ridge POSIX File Attributes record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
A string representing the RR version, either 1.09 or 1.12. | Below is the the instruction that describes the task:
### Input:
Parse a Rock Ridge POSIX File Attributes record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
A string representing the RR version, either 1.09 or 1.12.
### Response:
def parse... |
def observe(self, event_name, func):
"""
event_name := {'created', 'modified', 'deleted'}, list, tuple
Attaches a function to run to a particular event. The function must be
unique to be removed cleanly. Alternatively, event_name can be an list/
tuple if any of the string possib... | event_name := {'created', 'modified', 'deleted'}, list, tuple
Attaches a function to run to a particular event. The function must be
unique to be removed cleanly. Alternatively, event_name can be an list/
tuple if any of the string possibilities to be added on multiple events | Below is the the instruction that describes the task:
### Input:
event_name := {'created', 'modified', 'deleted'}, list, tuple
Attaches a function to run to a particular event. The function must be
unique to be removed cleanly. Alternatively, event_name can be an list/
tuple if any of the s... |
def is_longitudinal(self):
"""
Returns
-------
boolean :
longitudinal status of this project
"""
return len(self.events) > 0 and \
len(self.arm_nums) > 0 and \
len(self.arm_names) > 0 | Returns
-------
boolean :
longitudinal status of this project | Below is the the instruction that describes the task:
### Input:
Returns
-------
boolean :
longitudinal status of this project
### Response:
def is_longitudinal(self):
"""
Returns
-------
boolean :
longitudinal status of this project
"... |
def get_features(model_description_features):
"""Get features from a list of dictionaries
Parameters
----------
model_description_features : list of dictionaries
Examples
--------
>>> l = [{'StrokeCount': None}, \
{'ConstantPointCoordinates': \
[{'strokes': 4}, \... | Get features from a list of dictionaries
Parameters
----------
model_description_features : list of dictionaries
Examples
--------
>>> l = [{'StrokeCount': None}, \
{'ConstantPointCoordinates': \
[{'strokes': 4}, \
{'points_per_stroke': 81}, \
... | Below is the the instruction that describes the task:
### Input:
Get features from a list of dictionaries
Parameters
----------
model_description_features : list of dictionaries
Examples
--------
>>> l = [{'StrokeCount': None}, \
{'ConstantPointCoordinates': \
[{... |
def _make_sampling_sequence(n):
# type: (int) -> List[int]
"""
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
"""
s... | Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n. | Below is the the instruction that describes the task:
### Input:
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
### Response:
def ... |
def minute(self):
'''set unit to minute'''
self.magnification = 60
self._update(self.baseNumber, self.magnification)
return self | set unit to minute | Below is the the instruction that describes the task:
### Input:
set unit to minute
### Response:
def minute(self):
'''set unit to minute'''
self.magnification = 60
self._update(self.baseNumber, self.magnification)
return self |
def run(self):
"""
updates the modules output.
Currently only time and tztime need to do this
"""
if self.update_time_value():
self.i3status.py3_wrapper.notify_update(self.module_name)
due_time = self.py3.time_in(sync_to=self.time_delta)
self.i3status... | updates the modules output.
Currently only time and tztime need to do this | Below is the the instruction that describes the task:
### Input:
updates the modules output.
Currently only time and tztime need to do this
### Response:
def run(self):
"""
updates the modules output.
Currently only time and tztime need to do this
"""
if self.update_... |
def getObjectsInHouse(self, house):
""" Returns a list with all objects in a house. """
res = [obj for obj in self if house.hasObject(obj)]
return ObjectList(res) | Returns a list with all objects in a house. | Below is the the instruction that describes the task:
### Input:
Returns a list with all objects in a house.
### Response:
def getObjectsInHouse(self, house):
""" Returns a list with all objects in a house. """
res = [obj for obj in self if house.hasObject(obj)]
return ObjectList(res) |
def result(self, s, a):
'''Result of applying an action to a state.'''
# result: boat on opposite side, and numbers of missioners and
# cannibals updated according to the move
if s[2] == 0:
return (s[0] - a[1][0], s[1] - a[1][1], 1)
else:
return (s[0] + a[... | Result of applying an action to a state. | Below is the the instruction that describes the task:
### Input:
Result of applying an action to a state.
### Response:
def result(self, s, a):
'''Result of applying an action to a state.'''
# result: boat on opposite side, and numbers of missioners and
# cannibals updated according to the ... |
def _check_inputs(self, operators, weights):
""" Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class instances
weights :... | Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class instances
weights : list, tuple or np.ndarray
List of weights fo... | Below is the the instruction that describes the task:
### Input:
Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class instances
... |
def create_dataset(self,
name,
x_img_size,
y_img_size,
z_img_size,
x_vox_res,
y_vox_res,
z_vox_res,
x_offset=0,
y... | Creates a dataset.
Arguments:
name (str): Name of dataset
x_img_size (int): max x coordinate of image size
y_img_size (int): max y coordinate of image size
z_img_size (int): max z coordinate of image size
x_vox_res (float): x voxel resolution
... | Below is the the instruction that describes the task:
### Input:
Creates a dataset.
Arguments:
name (str): Name of dataset
x_img_size (int): max x coordinate of image size
y_img_size (int): max y coordinate of image size
z_img_size (int): max z coordinate of ... |
def create_tags_with_concatenated_css_classes(tags):
"""Function that creates <mark> tags such that they are not overlapping.
In order to do this, it concatenates the css classes and stores the concatenated
result in new tags.
"""
current_classes = set()
result = []
for pos, group in group_t... | Function that creates <mark> tags such that they are not overlapping.
In order to do this, it concatenates the css classes and stores the concatenated
result in new tags. | Below is the the instruction that describes the task:
### Input:
Function that creates <mark> tags such that they are not overlapping.
In order to do this, it concatenates the css classes and stores the concatenated
result in new tags.
### Response:
def create_tags_with_concatenated_css_classes(tags):
... |
async def fetch_block(self, request):
"""Fetches a specific block from the validator, specified by id.
Request:
path:
- block_id: The 128-character id of the block to be fetched
Response:
data: A JSON object with the data from the fully expanded Block
... | Fetches a specific block from the validator, specified by id.
Request:
path:
- block_id: The 128-character id of the block to be fetched
Response:
data: A JSON object with the data from the fully expanded Block
link: The link to this exact query | Below is the the instruction that describes the task:
### Input:
Fetches a specific block from the validator, specified by id.
Request:
path:
- block_id: The 128-character id of the block to be fetched
Response:
data: A JSON object with the data from the full... |
def send(self, line):
'''send some bytes'''
line = line.strip()
if line == ".":
self.stop()
return
mav = self.master.mav
if line != '+++':
line += "\r\n"
buf = [ord(x) for x in line]
buf.extend([0]*(70-len(buf)))
flags ... | send some bytes | Below is the the instruction that describes the task:
### Input:
send some bytes
### Response:
def send(self, line):
'''send some bytes'''
line = line.strip()
if line == ".":
self.stop()
return
mav = self.master.mav
if line != '+++':
line ... |
def filename(value):
'''
Remove everything that would affect paths in the filename
:param value:
:return:
'''
return re.sub('[^a-zA-Z0-9.-_ ]', '', os.path.basename(InputSanitizer.trim(value))) | Remove everything that would affect paths in the filename
:param value:
:return: | Below is the the instruction that describes the task:
### Input:
Remove everything that would affect paths in the filename
:param value:
:return:
### Response:
def filename(value):
'''
Remove everything that would affect paths in the filename
:param value:
:return:... |
def delete_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs):
"""Delete TableRateShipping
Delete an instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> t... | Delete TableRateShipping
Delete an instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_table_rate_shipping_by_id(table_rate_shipping_id, async=True)
... | Below is the the instruction that describes the task:
### Input:
Delete TableRateShipping
Delete an instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_... |
def to_header(self):
"""Converts the object back into an HTTP header."""
ranges = []
for begin, end in self.ranges:
if end is None:
ranges.append("%s-" % begin if begin >= 0 else str(begin))
else:
ranges.append("%s-%s" % (begin, end - 1))
... | Converts the object back into an HTTP header. | Below is the the instruction that describes the task:
### Input:
Converts the object back into an HTTP header.
### Response:
def to_header(self):
"""Converts the object back into an HTTP header."""
ranges = []
for begin, end in self.ranges:
if end is None:
ranges... |
def yum_install_from_url(pkg_name, url):
""" installs a pkg from a url
p pkg_name: the name of the package to install
p url: the full URL for the rpm package
"""
if is_package_installed(distribution='el', pkg=pkg_name) is False:
log_green(
"installing %s from %s" % (pkg_n... | installs a pkg from a url
p pkg_name: the name of the package to install
p url: the full URL for the rpm package | Below is the the instruction that describes the task:
### Input:
installs a pkg from a url
p pkg_name: the name of the package to install
p url: the full URL for the rpm package
### Response:
def yum_install_from_url(pkg_name, url):
""" installs a pkg from a url
p pkg_name: the name of ... |
def islitlet_progress(islitlet, islitlet_max):
"""Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number.
"""
if islitlet % 10 == 0:
cout = str(islitlet // ... | Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number. | Below is the the instruction that describes the task:
### Input:
Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number.
### Response:
def islitlet_progress(islitlet, islit... |
def age(self, id):
""" Returns the age of the cache entry, in days.
"""
path = self.hash(id)
if os.path.exists(path):
modified = datetime.datetime.fromtimestamp(os.stat(path)[8])
age = datetime.datetime.today() - modified
return age.days
else... | Returns the age of the cache entry, in days. | Below is the the instruction that describes the task:
### Input:
Returns the age of the cache entry, in days.
### Response:
def age(self, id):
""" Returns the age of the cache entry, in days.
"""
path = self.hash(id)
if os.path.exists(path):
modified = datetime.datetim... |
def gen_table(self, inner_widths, inner_heights, outer_widths):
"""Combine everything and yield every line of the entire table with borders.
:param iter inner_widths: List of widths (no padding) for each column.
:param iter inner_heights: List of heights (no padding) for each row.
:para... | Combine everything and yield every line of the entire table with borders.
:param iter inner_widths: List of widths (no padding) for each column.
:param iter inner_heights: List of heights (no padding) for each row.
:param iter outer_widths: List of widths (with padding) for each column.
... | Below is the the instruction that describes the task:
### Input:
Combine everything and yield every line of the entire table with borders.
:param iter inner_widths: List of widths (no padding) for each column.
:param iter inner_heights: List of heights (no padding) for each row.
:param iter... |
def _subset(subset, superset):
"""True if subset is a subset of superset.
:param dict subset: subset to compare.
:param dict superset: superset to compare.
:return: True iif all pairs (key, value) of subset are in superset.
:rtype: bool
"""
result = True
for k in subset:
result... | True if subset is a subset of superset.
:param dict subset: subset to compare.
:param dict superset: superset to compare.
:return: True iif all pairs (key, value) of subset are in superset.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
True if subset is a subset of superset.
:param dict subset: subset to compare.
:param dict superset: superset to compare.
:return: True iif all pairs (key, value) of subset are in superset.
:rtype: bool
### Response:
def _subset(subs... |
def forget_fact(term):
"""
Forgets a fact by removing it from the database
"""
logger.info('Removing fact %s', term)
db.facts.remove({'term': term_regex(term)})
return random.choice(ACKS) | Forgets a fact by removing it from the database | Below is the the instruction that describes the task:
### Input:
Forgets a fact by removing it from the database
### Response:
def forget_fact(term):
"""
Forgets a fact by removing it from the database
"""
logger.info('Removing fact %s', term)
db.facts.remove({'term': term_regex(term)})
ret... |
def _render_content(self, content, **settings):
"""
Perform widget rendering, but do not print anything.
"""
result = []
columns = settings[self.SETTING_COLUMNS]
# Format each table cell into string.
(columns, content) = self.table_format(columns, content)
... | Perform widget rendering, but do not print anything. | Below is the the instruction that describes the task:
### Input:
Perform widget rendering, but do not print anything.
### Response:
def _render_content(self, content, **settings):
"""
Perform widget rendering, but do not print anything.
"""
result = []
columns = settings[sel... |
def get_arg_type_descriptors(self):
"""
The parameter type descriptor list for a method, or None for a
field. Type descriptors are shorthand identifiers for the
builtin java types.
"""
if not self.is_method:
return tuple()
tp = _typeseq(self.get_des... | The parameter type descriptor list for a method, or None for a
field. Type descriptors are shorthand identifiers for the
builtin java types. | Below is the the instruction that describes the task:
### Input:
The parameter type descriptor list for a method, or None for a
field. Type descriptors are shorthand identifiers for the
builtin java types.
### Response:
def get_arg_type_descriptors(self):
"""
The parameter type des... |
def add_update_resources(self, resources, ignore_datasetid=False):
# type: (List[Union[hdx.data.resource.Resource,Dict,str]], bool) -> None
"""Add new or update existing resources with new metadata to the dataset
Args:
resources (List[Union[hdx.data.resource.Resource,Dict,str]]): A ... | Add new or update existing resources with new metadata to the dataset
Args:
resources (List[Union[hdx.data.resource.Resource,Dict,str]]): A list of either resource ids or resources metadata from either Resource objects or dictionaries
ignore_datasetid (bool): Whether to ignore dataset i... | Below is the the instruction that describes the task:
### Input:
Add new or update existing resources with new metadata to the dataset
Args:
resources (List[Union[hdx.data.resource.Resource,Dict,str]]): A list of either resource ids or resources metadata from either Resource objects or dictiona... |
def bump_version(project, source, force_init): # type: (str, str, bool, bool) ->int
"""
Entry point
:return:
"""
file_opener = FileOpener()
# logger.debug("Starting version jiggler...")
jiggler = JiggleVersion(project, source, file_opener, force_init)
logger.debug(
"Current, ne... | Entry point
:return: | Below is the the instruction that describes the task:
### Input:
Entry point
:return:
### Response:
def bump_version(project, source, force_init): # type: (str, str, bool, bool) ->int
"""
Entry point
:return:
"""
file_opener = FileOpener()
# logger.debug("Starting version jiggler...")
... |
def loadTargetsFromFile(self, filename, cols = None, everyNrows = 1,
delim = ' ', checkEven = 1):
"""
Loads targets from file.
"""
self.targets = self.loadVectors(filename, cols, everyNrows,
delim, checkEven) | Loads targets from file. | Below is the the instruction that describes the task:
### Input:
Loads targets from file.
### Response:
def loadTargetsFromFile(self, filename, cols = None, everyNrows = 1,
delim = ' ', checkEven = 1):
"""
Loads targets from file.
"""
self.targets = self.... |
def get_time_delta(time_string: str) -> timedelta:
"""
Takes a time string (1 hours, 10 days, etc.) and returns
a python timedelta object
:param time_string: the time value to convert to a timedelta
:type time_string: str
:returns: datetime.timedelta for relative time
:type datetime.timedel... | Takes a time string (1 hours, 10 days, etc.) and returns
a python timedelta object
:param time_string: the time value to convert to a timedelta
:type time_string: str
:returns: datetime.timedelta for relative time
:type datetime.timedelta | Below is the the instruction that describes the task:
### Input:
Takes a time string (1 hours, 10 days, etc.) and returns
a python timedelta object
:param time_string: the time value to convert to a timedelta
:type time_string: str
:returns: datetime.timedelta for relative time
:type datetime.t... |
def seriesshape(self):
"""Shape of the whole time series (time being the first dimension)."""
seriesshape = [len(hydpy.pub.timegrids.init)]
seriesshape.extend(self.shape)
return tuple(seriesshape) | Shape of the whole time series (time being the first dimension). | Below is the the instruction that describes the task:
### Input:
Shape of the whole time series (time being the first dimension).
### Response:
def seriesshape(self):
"""Shape of the whole time series (time being the first dimension)."""
seriesshape = [len(hydpy.pub.timegrids.init)]
seriess... |
def _convert_to_dict(data):
"""
Convert `data` to dictionary.
Tries to get sense in multidimensional arrays.
Args:
data: List/dict/tuple of variable dimension.
Returns:
dict: If the data can be converted to dictionary.
Raises:
MetaParsingException: When the data are u... | Convert `data` to dictionary.
Tries to get sense in multidimensional arrays.
Args:
data: List/dict/tuple of variable dimension.
Returns:
dict: If the data can be converted to dictionary.
Raises:
MetaParsingException: When the data are unconvertible to dict. | Below is the the instruction that describes the task:
### Input:
Convert `data` to dictionary.
Tries to get sense in multidimensional arrays.
Args:
data: List/dict/tuple of variable dimension.
Returns:
dict: If the data can be converted to dictionary.
Raises:
MetaParsingE... |
def match(self, fsys_view):
'''
Compare potentially partial criteria against built filesystems entry dictionary
'''
evalue_dict = fsys_view[1]
for key, value in six.viewitems(self.criteria):
if key in evalue_dict:
if evalue_dict[key] != value:
... | Compare potentially partial criteria against built filesystems entry dictionary | Below is the the instruction that describes the task:
### Input:
Compare potentially partial criteria against built filesystems entry dictionary
### Response:
def match(self, fsys_view):
'''
Compare potentially partial criteria against built filesystems entry dictionary
'''
evalue_d... |
def doprinc(data):
"""
Gets principal components from data in form of a list of [dec,inc] data.
Parameters
----------
data : nested list of dec, inc directions
Returns
-------
ppars : dictionary with the principal components
dec : principal directiion declination
inc : ... | Gets principal components from data in form of a list of [dec,inc] data.
Parameters
----------
data : nested list of dec, inc directions
Returns
-------
ppars : dictionary with the principal components
dec : principal directiion declination
inc : principal direction inclination... | Below is the the instruction that describes the task:
### Input:
Gets principal components from data in form of a list of [dec,inc] data.
Parameters
----------
data : nested list of dec, inc directions
Returns
-------
ppars : dictionary with the principal components
dec : principal... |
def start(self) -> None:
"""
Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer.
"""
self._setup()
if self._run_control_loop:
asyncio.set_event_loop(asyncio.new_event_loop())
... | Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer. | Below is the the instruction that describes the task:
### Input:
Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer.
### Response:
def start(self) -> None:
"""
Start the internal control loop. Potentially blocking, dep... |
def change_option_default(self, opt_name, default_val):
""" Change the default value of an option
:param opt_name: option name
:type opt_name: str
:param value: new default option value
"""
if not self.has_option(opt_name):
raise ValueError("... | Change the default value of an option
:param opt_name: option name
:type opt_name: str
:param value: new default option value | Below is the the instruction that describes the task:
### Input:
Change the default value of an option
:param opt_name: option name
:type opt_name: str
:param value: new default option value
### Response:
def change_option_default(self, opt_name, default_val):
""" ... |
def parse_sv_frequencies(variant):
"""Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
sv_frequencies(dict)
... | Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
sv_frequencies(dict) | Below is the the instruction that describes the task:
### Input:
Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
... |
def read(self, size=None):
"""Read a length of bytes. Return empty on EOF. If 'size' is omitted,
return whole file.
"""
if size is not None:
return self.__sf.read(size)
block_size = self.__class__.__block_size
b = bytearray()
received_bytes = 0
... | Read a length of bytes. Return empty on EOF. If 'size' is omitted,
return whole file. | Below is the the instruction that describes the task:
### Input:
Read a length of bytes. Return empty on EOF. If 'size' is omitted,
return whole file.
### Response:
def read(self, size=None):
"""Read a length of bytes. Return empty on EOF. If 'size' is omitted,
return whole file.
... |
def profile(self):
"""Measure of bandedness, also known as 'envelope size'."""
leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0)
return (np.arange(self.num_vertices()) - leftmost_idx).sum() | Measure of bandedness, also known as 'envelope size'. | Below is the the instruction that describes the task:
### Input:
Measure of bandedness, also known as 'envelope size'.
### Response:
def profile(self):
"""Measure of bandedness, also known as 'envelope size'."""
leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0)
return (np.arange(self.... |
def transmit(self, bytes, protocol=None):
"""Transmit an apdu. Internally calls doTransmit() class method
and notify observers upon command/response APDU events.
Subclasses must override the doTransmit() class method.
@param bytes: list of bytes to transmit
@param protocol... | Transmit an apdu. Internally calls doTransmit() class method
and notify observers upon command/response APDU events.
Subclasses must override the doTransmit() class method.
@param bytes: list of bytes to transmit
@param protocol: the transmission protocol, from
... | Below is the the instruction that describes the task:
### Input:
Transmit an apdu. Internally calls doTransmit() class method
and notify observers upon command/response APDU events.
Subclasses must override the doTransmit() class method.
@param bytes: list of bytes to transmit
... |
def _dict_increment(self, dictionary, key):
"""Increments the value of the dictionary at the specified key."""
if key in dictionary:
dictionary[key] += 1
else:
dictionary[key] = 1 | Increments the value of the dictionary at the specified key. | Below is the the instruction that describes the task:
### Input:
Increments the value of the dictionary at the specified key.
### Response:
def _dict_increment(self, dictionary, key):
"""Increments the value of the dictionary at the specified key."""
if key in dictionary:
dictionary[key... |
def setup_image_plane_pixelization_grid_from_galaxies_and_grid_stack(galaxies, grid_stack):
"""An image-plane pixelization is one where its pixel centres are computed by tracing a sparse grid of pixels from \
the image's regular grid to other planes (e.g. the source-plane).
Provided a galaxy has an image-p... | An image-plane pixelization is one where its pixel centres are computed by tracing a sparse grid of pixels from \
the image's regular grid to other planes (e.g. the source-plane).
Provided a galaxy has an image-plane pixelization, this function returns a new *GridStack* instance where the \
image-plane pix... | Below is the the instruction that describes the task:
### Input:
An image-plane pixelization is one where its pixel centres are computed by tracing a sparse grid of pixels from \
the image's regular grid to other planes (e.g. the source-plane).
Provided a galaxy has an image-plane pixelization, this functi... |
def sbar(Ss):
"""
calculate average s,sigma from list of "s"s.
"""
if type(Ss) == list:
Ss = np.array(Ss)
npts = Ss.shape[0]
Ss = Ss.transpose()
avd, avs = [], []
# D=np.array([Ss[0],Ss[1],Ss[2],Ss[3]+0.5*(Ss[0]+Ss[1]),Ss[4]+0.5*(Ss[1]+Ss[2]),Ss[5]+0.5*(Ss[0]+Ss[2])]).transpose(... | calculate average s,sigma from list of "s"s. | Below is the the instruction that describes the task:
### Input:
calculate average s,sigma from list of "s"s.
### Response:
def sbar(Ss):
"""
calculate average s,sigma from list of "s"s.
"""
if type(Ss) == list:
Ss = np.array(Ss)
npts = Ss.shape[0]
Ss = Ss.transpose()
avd, avs ... |
def next_string(min_size, max_size):
"""
Generates a random string, consisting of upper and lower case letters (of the English alphabet),
digits (0-9), and symbols ("_,.:-/.[].{},#-!,$=%.+^.&*-() ").
:param min_size: (optional) minimum string length.
:param max_size: maximum st... | Generates a random string, consisting of upper and lower case letters (of the English alphabet),
digits (0-9), and symbols ("_,.:-/.[].{},#-!,$=%.+^.&*-() ").
:param min_size: (optional) minimum string length.
:param max_size: maximum string length.
:return: a random string. | Below is the the instruction that describes the task:
### Input:
Generates a random string, consisting of upper and lower case letters (of the English alphabet),
digits (0-9), and symbols ("_,.:-/.[].{},#-!,$=%.+^.&*-() ").
:param min_size: (optional) minimum string length.
:param max_size... |
def headloss_fric(FlowRate, Diam, Length, Nu, PipeRough):
"""Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows.
"""
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range(... | Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows. | Below is the the instruction that describes the task:
### Input:
Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows.
### Response:
def headloss_fric(FlowRate, Diam, Length, Nu, PipeRough):
"""Return the major head loss (due to wall shear) in... |
def ticket_satisfaction_rating_create(self, ticket_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating"
api_path = "/api/v2/tickets/{ticket_id}/satisfaction_rating.json"
api_path = api_path.format(ticket_id=ticket_id)
r... | https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating
### Response:
def ticket_satisfaction_rating_create(self, ticket_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/satisfa... |
def get_manifest_digests(image, registry, insecure=False, dockercfg_path=None,
versions=('v1', 'v2', 'v2_list', 'oci', 'oci_index'), require_digest=True):
"""Return manifest digest for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registr... | Return manifest digest for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True registry's cert is not verified
:param dockercfg_path: str, dirn... | Below is the the instruction that describes the task:
### Input:
Return manifest digest for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param insecure: bool, when True... |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Update <resource> Properties."""
assert wait_for_completion is True # async not supported yet
try:
resource = hmc.lookup_by_uri(uri)
except KeyError:
rais... | Operation: Update <resource> Properties. | Below is the the instruction that describes the task:
### Input:
Operation: Update <resource> Properties.
### Response:
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Update <resource> Properties."""
assert wait_for_completion is True #... |
def conv2d_fixed_padding(inputs,
filters,
kernel_size,
strides,
data_format="channels_first",
use_td=False,
targeting_rate=None,
keep_prob=None,
... | Strided 2-D convolution with explicit padding.
The padding is consistent and is based only on `kernel_size`, not on the
dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).
Args:
inputs: `Tensor` of size `[batch, channels, height_in, width_in]`.
filters: `int` number of filters in the ... | Below is the the instruction that describes the task:
### Input:
Strided 2-D convolution with explicit padding.
The padding is consistent and is based only on `kernel_size`, not on the
dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).
Args:
inputs: `Tensor` of size `[batch, channels... |
def _parse_part(client, command, actor, args):
"""Parse a PART and update channel states, then dispatch events.
Note that two events are dispatched here:
- PART, because a user parted the channel
- MEMBERS, because the channel's members changed
"""
actor = User(actor)
channel, _, me... | Parse a PART and update channel states, then dispatch events.
Note that two events are dispatched here:
- PART, because a user parted the channel
- MEMBERS, because the channel's members changed | Below is the the instruction that describes the task:
### Input:
Parse a PART and update channel states, then dispatch events.
Note that two events are dispatched here:
- PART, because a user parted the channel
- MEMBERS, because the channel's members changed
### Response:
def _parse_part(clie... |
def next(self):
"""Returns the next batch of data."""
if self.curr_idx == len(self.idx):
raise StopIteration
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
audio_paths = []
texts = []
for duration, audio_path, text in self.data[i][j:j+self.batch_si... | Returns the next batch of data. | Below is the the instruction that describes the task:
### Input:
Returns the next batch of data.
### Response:
def next(self):
"""Returns the next batch of data."""
if self.curr_idx == len(self.idx):
raise StopIteration
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
... |
def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
"""
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
... | Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location. | Below is the the instruction that describes the task:
### Input:
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
### Response:
def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the co... |
def get_movielens_iter(filename, batch_size):
"""Not particularly fast code to parse the text file and load into NDArrays.
return two data iters, one for train, the other for validation.
"""
logging.info("Preparing data iterators for " + filename + " ... ")
user = []
item = []
score = []
... | Not particularly fast code to parse the text file and load into NDArrays.
return two data iters, one for train, the other for validation. | Below is the the instruction that describes the task:
### Input:
Not particularly fast code to parse the text file and load into NDArrays.
return two data iters, one for train, the other for validation.
### Response:
def get_movielens_iter(filename, batch_size):
"""Not particularly fast code to parse the t... |
def _speak_normal_inherit(self, element):
"""
Speak the content of element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
self._visit(element, self._speak_normal)
element.normalize() | Speak the content of element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement | Below is the the instruction that describes the task:
### Input:
Speak the content of element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
### Response:
def _speak_normal_inherit(self, element):
"""
Speak the content ... |
def init(self, formula, incr=False):
"""
Initialize the internal SAT oracle. The oracle is used
incrementally and so it is initialized only once when
constructing an object of class :class:`RC2`. Given an
input :class:`.WCNF` formula, the method bootstraps the
... | Initialize the internal SAT oracle. The oracle is used
incrementally and so it is initialized only once when
constructing an object of class :class:`RC2`. Given an
input :class:`.WCNF` formula, the method bootstraps the
oracle with its hard clauses. It also augments the s... | Below is the the instruction that describes the task:
### Input:
Initialize the internal SAT oracle. The oracle is used
incrementally and so it is initialized only once when
constructing an object of class :class:`RC2`. Given an
input :class:`.WCNF` formula, the method bootstraps... |
def get_list(file,fmt):
'''makes a list out of the fmt from the LspOutput f using the format
i for int
f for float
d for double
s for string'''
out=[]
for i in fmt:
if i == 'i':
out.append(get_int(file));
elif i == 'f' or i == 'd':
out.appe... | makes a list out of the fmt from the LspOutput f using the format
i for int
f for float
d for double
s for string | Below is the the instruction that describes the task:
### Input:
makes a list out of the fmt from the LspOutput f using the format
i for int
f for float
d for double
s for string
### Response:
def get_list(file,fmt):
'''makes a list out of the fmt from the LspOutput f using the form... |
def import_class(classpath):
"""Import the class referred to by the fully qualified class path.
Args:
classpath: A full "foo.bar.MyClass" path to a class definition.
Returns:
The class referred to by the classpath.
Raises:
ImportError: If an error occurs while importing the mo... | Import the class referred to by the fully qualified class path.
Args:
classpath: A full "foo.bar.MyClass" path to a class definition.
Returns:
The class referred to by the classpath.
Raises:
ImportError: If an error occurs while importing the module.
AttributeError: IF the... | Below is the the instruction that describes the task:
### Input:
Import the class referred to by the fully qualified class path.
Args:
classpath: A full "foo.bar.MyClass" path to a class definition.
Returns:
The class referred to by the classpath.
Raises:
ImportError: If an er... |
def snr_ratio(in1, in2):
"""
The following function simply calculates the signal to noise ratio between two signals.
INPUTS:
in1 (no default): Array containing values for signal 1.
in2 (no default): Array containing values for signal 2.
OUTPUTS:
out1 ... | The following function simply calculates the signal to noise ratio between two signals.
INPUTS:
in1 (no default): Array containing values for signal 1.
in2 (no default): Array containing values for signal 2.
OUTPUTS:
out1 The ratio of the signal to noise ... | Below is the the instruction that describes the task:
### Input:
The following function simply calculates the signal to noise ratio between two signals.
INPUTS:
in1 (no default): Array containing values for signal 1.
in2 (no default): Array containing values for signal 2.
OUTPU... |
def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Returns a tuple of (user, host, port) with config, pillar, or default
values assigned to missing values.
'''
if six.text_type(port).isdigit():
return memcache.Client(['{0}:{1}'.format(host, port)], debug=0)
raise SaltInvocationError... | Returns a tuple of (user, host, port) with config, pillar, or default
values assigned to missing values. | Below is the the instruction that describes the task:
### Input:
Returns a tuple of (user, host, port) with config, pillar, or default
values assigned to missing values.
### Response:
def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Returns a tuple of (user, host, port) with config, pillar, or d... |
def schema_columns(self):
"""Return column informatino only from this schema"""
t = self.schema_term
columns = []
if t:
for i, c in enumerate(t.children):
if c.term_is("Table.Column"):
p = c.all_props
p['pos'] = i
... | Return column informatino only from this schema | Below is the the instruction that describes the task:
### Input:
Return column informatino only from this schema
### Response:
def schema_columns(self):
"""Return column informatino only from this schema"""
t = self.schema_term
columns = []
if t:
for i, c in enumerate... |
def _prepare(constituents, t0, t = None, radians = True):
"""
Return constituent speed and equilibrium argument at a given time, and constituent node factors at given times.
Arguments:
constituents -- list of constituents to prepare
t0 -- time at which to evaluate speed and equilibrium argument for each const... | Return constituent speed and equilibrium argument at a given time, and constituent node factors at given times.
Arguments:
constituents -- list of constituents to prepare
t0 -- time at which to evaluate speed and equilibrium argument for each constituent
t -- list of times at which to evaluate node factors for ... | Below is the the instruction that describes the task:
### Input:
Return constituent speed and equilibrium argument at a given time, and constituent node factors at given times.
Arguments:
constituents -- list of constituents to prepare
t0 -- time at which to evaluate speed and equilibrium argument for each co... |
def prepare(self, hash, start, end, name, sources, sample=None):
""" Prepare a historics query which can later be started.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsprepare
:param hash: The hash of a CSDL create the query for
:type ... | Prepare a historics query which can later be started.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsprepare
:param hash: The hash of a CSDL create the query for
:type hash: str
:param start: when to start querying data from - unix t... | Below is the the instruction that describes the task:
### Input:
Prepare a historics query which can later be started.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsprepare
:param hash: The hash of a CSDL create the query for
:type hash: st... |
def clear(self):
"Remove all rows and reset internal structures"
## list has no clear ... remove items in reverse order
for i in range(len(self)-1, -1, -1):
del self[i]
self._key = 0
if hasattr(self._grid_view, "wx_obj"):
self._grid_view.wx_obj.Clea... | Remove all rows and reset internal structures | Below is the the instruction that describes the task:
### Input:
Remove all rows and reset internal structures
### Response:
def clear(self):
"Remove all rows and reset internal structures"
## list has no clear ... remove items in reverse order
for i in range(len(self)-1, -1, -1):
... |
def mock_cmd(self, release, *cmd, **kwargs):
"""Run a mock command in the chroot for a given release"""
fmt = '{mock_cmd}'
if kwargs.get('new_chroot') is True:
fmt +=' --new-chroot'
fmt += ' --configdir={mock_dir}'
return self.call(fmt.format(**release).split()
... | Run a mock command in the chroot for a given release | Below is the the instruction that describes the task:
### Input:
Run a mock command in the chroot for a given release
### Response:
def mock_cmd(self, release, *cmd, **kwargs):
"""Run a mock command in the chroot for a given release"""
fmt = '{mock_cmd}'
if kwargs.get('new_chroot') is True:... |
def from_stmt(stmt, engine, **kwargs):
"""
Execute a query in form of texture clause, return the result in form of
:class:`PrettyTable`.
:type stmt: TextClause
:param stmt:
:type engine: Engine
:param engine:
:rtype: PrettyTable
"""
result_proxy = engine.execute(stmt, **kwarg... | Execute a query in form of texture clause, return the result in form of
:class:`PrettyTable`.
:type stmt: TextClause
:param stmt:
:type engine: Engine
:param engine:
:rtype: PrettyTable | Below is the the instruction that describes the task:
### Input:
Execute a query in form of texture clause, return the result in form of
:class:`PrettyTable`.
:type stmt: TextClause
:param stmt:
:type engine: Engine
:param engine:
:rtype: PrettyTable
### Response:
def from_stmt(stmt, en... |
def get_user_lists(self, course, aggregationid=''):
""" Get the available student and tutor lists for aggregation edition"""
tutor_list = course.get_staff()
# Determine student list and if they are grouped
student_list = list(self.database.aggregations.aggregate([
{"$match":... | Get the available student and tutor lists for aggregation edition | Below is the the instruction that describes the task:
### Input:
Get the available student and tutor lists for aggregation edition
### Response:
def get_user_lists(self, course, aggregationid=''):
""" Get the available student and tutor lists for aggregation edition"""
tutor_list = course.get_staff... |
def getPageSizeByName(self, pageSizeName):
""" Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize.
"""
pageSize = None
lowerCaseNames = {pageSize.lower(): pageSize for pageSize in
self.availablePageSizes()}
if pageSize... | Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize. | Below is the the instruction that describes the task:
### Input:
Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize.
### Response:
def getPageSizeByName(self, pageSizeName):
""" Returns a validated PageSize instance corresponding to the given... |
def create_ip_arp_request(srchw, srcip, targetip):
'''
Create and return a packet containing an Ethernet header
and ARP header.
'''
ether = Ethernet()
ether.src = srchw
ether.dst = SpecialEthAddr.ETHER_BROADCAST.value
ether.ethertype = EtherType.ARP
arp = Arp()
arp.operation = Ar... | Create and return a packet containing an Ethernet header
and ARP header. | Below is the the instruction that describes the task:
### Input:
Create and return a packet containing an Ethernet header
and ARP header.
### Response:
def create_ip_arp_request(srchw, srcip, targetip):
'''
Create and return a packet containing an Ethernet header
and ARP header.
'''
ether =... |
def download_data(identifier, outdir):
"""Download data from a separate data repository for testing.
Parameters
----------
identifier: string
The identifier used to find the data set
outdir: string
unzip the data in this directory
"""
# determine target
if use_local_data... | Download data from a separate data repository for testing.
Parameters
----------
identifier: string
The identifier used to find the data set
outdir: string
unzip the data in this directory | Below is the the instruction that describes the task:
### Input:
Download data from a separate data repository for testing.
Parameters
----------
identifier: string
The identifier used to find the data set
outdir: string
unzip the data in this directory
### Response:
def download_d... |
def paint(self):
"""
Renders a javascript snippet suitable for use as a mapbox-gl fill-extrusion paint entry
Returns:
A dict that can be converted to a mapbox-gl javascript paint snippet
"""
snippet = {
'fill-extrusion-opacity': VectorStyle.get_style_valu... | Renders a javascript snippet suitable for use as a mapbox-gl fill-extrusion paint entry
Returns:
A dict that can be converted to a mapbox-gl javascript paint snippet | Below is the the instruction that describes the task:
### Input:
Renders a javascript snippet suitable for use as a mapbox-gl fill-extrusion paint entry
Returns:
A dict that can be converted to a mapbox-gl javascript paint snippet
### Response:
def paint(self):
"""
Renders a ja... |
def set_attributes(obj, additional_data):
"""
Given an object and a dictionary, give the object new attributes from that dictionary.
Uses _strip_column_name to git rid of whitespace/uppercase/special characters.
"""
for key, value in additional_data.items():
if hasattr(obj, key):
... | Given an object and a dictionary, give the object new attributes from that dictionary.
Uses _strip_column_name to git rid of whitespace/uppercase/special characters. | Below is the the instruction that describes the task:
### Input:
Given an object and a dictionary, give the object new attributes from that dictionary.
Uses _strip_column_name to git rid of whitespace/uppercase/special characters.
### Response:
def set_attributes(obj, additional_data):
"""
Given an ob... |
def xlim(min, max):
"""
This function will set the x axis range for all time series plots
Parameters:
min : flt
The time to start all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
max : flt
... | This function will set the x axis range for all time series plots
Parameters:
min : flt
The time to start all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
max : flt
The time to end all time series... | Below is the the instruction that describes the task:
### Input:
This function will set the x axis range for all time series plots
Parameters:
min : flt
The time to start all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH... |
def _get_log_lines(self, n=300):
"""Returns a list with the last ``n`` lines of the nextflow log file
Parameters
----------
n : int
Number of last lines from the log file
Returns
-------
list
List of strings with the nextflow log
... | Returns a list with the last ``n`` lines of the nextflow log file
Parameters
----------
n : int
Number of last lines from the log file
Returns
-------
list
List of strings with the nextflow log | Below is the the instruction that describes the task:
### Input:
Returns a list with the last ``n`` lines of the nextflow log file
Parameters
----------
n : int
Number of last lines from the log file
Returns
-------
list
List of strings with ... |
def _check_choices_attribute(self): # pragma: no cover
"""Checks to make sure that choices contains valid timezone choices."""
if self.choices:
warning_params = {
'msg': (
"'choices' contains an invalid time zone value '{value}' "
"w... | Checks to make sure that choices contains valid timezone choices. | Below is the the instruction that describes the task:
### Input:
Checks to make sure that choices contains valid timezone choices.
### Response:
def _check_choices_attribute(self): # pragma: no cover
"""Checks to make sure that choices contains valid timezone choices."""
if self.choices:
... |
def items_sharing_ngrams(self, query):
"""Retrieve the subset of items that share n-grams the query string.
:param query: look up items that share N-grams with this string.
:return: mapping from matched string to the number of shared N-grams.
>>> from ngram import NGram
>>> n =... | Retrieve the subset of items that share n-grams the query string.
:param query: look up items that share N-grams with this string.
:return: mapping from matched string to the number of shared N-grams.
>>> from ngram import NGram
>>> n = NGram(["ham","spam","eggs"])
>>> sorted(n... | Below is the the instruction that describes the task:
### Input:
Retrieve the subset of items that share n-grams the query string.
:param query: look up items that share N-grams with this string.
:return: mapping from matched string to the number of shared N-grams.
>>> from ngram import NG... |
def create_dialog(self):
"""Create the dialog."""
bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.idx_ok = bbox.button(QDialogButtonBox.Ok)
self.idx_cancel = bbox.button(QDialogButtonBox.Cancel)
filebutton = QPushButton()
filebutton.setText('C... | Create the dialog. | Below is the the instruction that describes the task:
### Input:
Create the dialog.
### Response:
def create_dialog(self):
"""Create the dialog."""
bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.idx_ok = bbox.button(QDialogButtonBox.Ok)
self.idx_cancel =... |
def centroid_2dg(data, error=None, mask=None):
"""
Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus
a constant) to the array.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
represents the combinati... | Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus
a constant) to the array.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
represents the combination of the invalid-value masks for the
``data`` and ``er... | Below is the the instruction that describes the task:
### Input:
Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus
a constant) to the array.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
represents the... |
def project_closing(self, project):
"""
Called when a project is about to be closed.
:param project: Project instance
"""
yield from super().project_closing(project)
# delete the Dynamips devices corresponding to the project
tasks = []
for device in self... | Called when a project is about to be closed.
:param project: Project instance | Below is the the instruction that describes the task:
### Input:
Called when a project is about to be closed.
:param project: Project instance
### Response:
def project_closing(self, project):
"""
Called when a project is about to be closed.
:param project: Project instance
... |
def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
... | Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it wi... | Below is the the instruction that describes the task:
### Input:
Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as we... |
def get_vprof_version(filename):
"""Returns actual version specified in filename."""
with open(filename) as src_file:
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
src_file.read(), re.M)
if version_match:
return version_match.group... | Returns actual version specified in filename. | Below is the the instruction that describes the task:
### Input:
Returns actual version specified in filename.
### Response:
def get_vprof_version(filename):
"""Returns actual version specified in filename."""
with open(filename) as src_file:
version_match = re.search(r"^__version__ = ['\"]([^'\"]*... |
def handle_starting_instance(self):
"""Starting up PostgreSQL may take a long time. In case we are the leader we may want to
fail over to."""
# Check if we are in startup, when paused defer to main loop for manual failovers.
if not self.state_handler.check_for_startup() or self.is_pause... | Starting up PostgreSQL may take a long time. In case we are the leader we may want to
fail over to. | Below is the the instruction that describes the task:
### Input:
Starting up PostgreSQL may take a long time. In case we are the leader we may want to
fail over to.
### Response:
def handle_starting_instance(self):
"""Starting up PostgreSQL may take a long time. In case we are the leader we may wan... |
def get_next_iteration(self, iteration, iteration_kwargs={}):
"""
BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters
----------
iteration: int
the index of the iteration to be instantiated
Returns
-------
SuccessiveHalving: t... | BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters
----------
iteration: int
the index of the iteration to be instantiated
Returns
-------
SuccessiveHalving: the SuccessiveHalving iteration with the
corresponding number of co... | Below is the the instruction that describes the task:
### Input:
BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters
----------
iteration: int
the index of the iteration to be instantiated
Returns
-------
SuccessiveHalving: th... |
def __related_categories(self, category_id):
""" Get all related categories to a given one """
related = []
for cat in self.categories_tree:
if category_id in self.categories_tree[cat]:
related.append(self.categories[cat])
return related | Get all related categories to a given one | Below is the the instruction that describes the task:
### Input:
Get all related categories to a given one
### Response:
def __related_categories(self, category_id):
""" Get all related categories to a given one """
related = []
for cat in self.categories_tree:
if category_id in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.