code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def message(self, message, item, extra):
"""Uses arguments to create the message."""
if item is not None:
message += ": " + ascii(item)
if extra is not None:
message += " (" + str(extra) + ")"
return message | Uses arguments to create the message. | Below is the the instruction that describes the task:
### Input:
Uses arguments to create the message.
### Response:
def message(self, message, item, extra):
"""Uses arguments to create the message."""
if item is not None:
message += ": " + ascii(item)
if extra is not None:
... |
def _construct_punctuation_token(self, d: Dict, nlp) -> List[Dict]:
"""
Construct a shape token
Args:
d: Dict
nlp
Returns: List[Dict]
"""
result = []
if not d["token"]:
this_token = {attrs.IS_PUNCT: True}
elif len(d["t... | Construct a shape token
Args:
d: Dict
nlp
Returns: List[Dict] | Below is the the instruction that describes the task:
### Input:
Construct a shape token
Args:
d: Dict
nlp
Returns: List[Dict]
### Response:
def _construct_punctuation_token(self, d: Dict, nlp) -> List[Dict]:
"""
Construct a shape token
Args:
... |
def genCompleteTypes( compoundSig ):
"""
Generator function used to iterate over each complete,
top-level type contained in in a signature. Ex::
"iii" => [ 'i', 'i', 'i' ]
"i(ii)i" => [ 'i', '(ii)', 'i' ]
"i(i(ii))i" => [ 'i', '(i(ii))', 'i' ]
"""
i = 0
s... | Generator function used to iterate over each complete,
top-level type contained in in a signature. Ex::
"iii" => [ 'i', 'i', 'i' ]
"i(ii)i" => [ 'i', '(ii)', 'i' ]
"i(i(ii))i" => [ 'i', '(i(ii))', 'i' ] | Below is the the instruction that describes the task:
### Input:
Generator function used to iterate over each complete,
top-level type contained in in a signature. Ex::
"iii" => [ 'i', 'i', 'i' ]
"i(ii)i" => [ 'i', '(ii)', 'i' ]
"i(i(ii))i" => [ 'i', '(i(ii))', 'i' ]
### Resp... |
def from_json(f: TextIO) -> 'PrecalculatedTextMeasurer':
"""Return a PrecalculatedTextMeasurer given a JSON stream.
See precalculate_text.py for details on the required format.
"""
o = json.load(f)
return PrecalculatedTextMeasurer(o['mean-character-length'],
... | Return a PrecalculatedTextMeasurer given a JSON stream.
See precalculate_text.py for details on the required format. | Below is the the instruction that describes the task:
### Input:
Return a PrecalculatedTextMeasurer given a JSON stream.
See precalculate_text.py for details on the required format.
### Response:
def from_json(f: TextIO) -> 'PrecalculatedTextMeasurer':
"""Return a PrecalculatedTextMeasurer given a... |
def edit_message_media(
self,
chat_id: Union[int, str],
message_id: int,
media: InputMedia,
reply_markup: "pyrogram.InlineKeyboardMarkup" = None
) -> "pyrogram.Message":
"""Use this method to edit audio, document, photo, or video messages.
If a message is a p... | Use this method to edit audio, document, photo, or video messages.
If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise,
message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded.
Use previously uploaded ... | Below is the the instruction that describes the task:
### Input:
Use this method to edit audio, document, photo, or video messages.
If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise,
message type can be changed arbitrarily. When inline message is... |
def on(self, state):
""" Turn on or off.
:param state: True (on) or False (off).
"""
self._on = state
cmd = self.command_set.off()
if state:
cmd = self.command_set.on()
self.send(cmd) | Turn on or off.
:param state: True (on) or False (off). | Below is the the instruction that describes the task:
### Input:
Turn on or off.
:param state: True (on) or False (off).
### Response:
def on(self, state):
""" Turn on or off.
:param state: True (on) or False (off).
"""
self._on = state
cmd = self.command_set.off()... |
def replace_pyof_version(module_fullname, version):
"""Replace the OF Version of a module fullname.
Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on
a new 'version' (eg. 'pyof.v0x02.common.header').
Args:
module_fullname (str): The fullname of the modu... | Replace the OF Version of a module fullname.
Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on
a new 'version' (eg. 'pyof.v0x02.common.header').
Args:
module_fullname (str): The fullname of the module
(e.g.: pyof.v0x01.common.... | Below is the the instruction that describes the task:
### Input:
Replace the OF Version of a module fullname.
Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on
a new 'version' (eg. 'pyof.v0x02.common.header').
Args:
module_fullname (str): The fullname of th... |
def list_features(self, **kwargs):
"""Obtain a list of parkings.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Parking]), or message
string in case of error.
"""
# Endpoint parameters
... | Obtain a list of parkings.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Parking]), or message
string in case of error. | Below is the the instruction that describes the task:
### Input:
Obtain a list of parkings.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Parking]), or message
string in case of error.
### Response:
def list_... |
def clean_data(self, data, rename_col=None, drop_col=None,
resample=True, freq='h', resampler='mean',
interpolate=True, limit=1, method='linear',
remove_na=True, remove_na_how='any',
remove_outliers=True, sd_val=3,
remov... | Cleans dataframe according to user specifications and stores result in self.cleaned_data.
Parameters
----------
data : pd.DataFrame()
Dataframe to be cleaned.
rename_col : list(str)
List of new column names.
drop_col ... | Below is the the instruction that describes the task:
### Input:
Cleans dataframe according to user specifications and stores result in self.cleaned_data.
Parameters
----------
data : pd.DataFrame()
Dataframe to be cleaned.
rename_col : li... |
def shutdown(self, exitcode=0, exitmsg=None):
'''
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
'''
self.action_log_info('Shutting down')
if hasattr(self, 'minion') and hasattr(self.minion, 'destroy'):
self... | If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg | Below is the the instruction that describes the task:
### Input:
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
### Response:
def shutdown(self, exitcode=0, exitmsg=None):
'''
If sub-classed, run any shutdown operations on this method.
... |
def run(self):
"""Discovers the mongo cluster and creates a thread for each primary.
"""
# Reset the global minimum MongoDB version
update_mininum_mongodb_version(None)
self.main_conn = self.create_authed_client()
LOG.always(
"Source MongoDB version: %s",
... | Discovers the mongo cluster and creates a thread for each primary. | Below is the the instruction that describes the task:
### Input:
Discovers the mongo cluster and creates a thread for each primary.
### Response:
def run(self):
"""Discovers the mongo cluster and creates a thread for each primary.
"""
# Reset the global minimum MongoDB version
updat... |
def list_semod():
'''
Return a structure listing all of the selinux modules on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_semod
.. versionadded:: 2016.3.0
'''
helptext = __salt__['cmd.run']('semodule -h').splitlines()
sem... | Return a structure listing all of the selinux modules on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_semod
.. versionadded:: 2016.3.0 | Below is the the instruction that describes the task:
### Input:
Return a structure listing all of the selinux modules on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_semod
.. versionadded:: 2016.3.0
### Response:
def list_semod():
''... |
def distance_to_point(self, p):
'''Returns the distance from the point to the interval. Zero if the point lies inside the interval.'''
if self.start <= p <= self.end:
return 0
else:
return min(abs(self.start - p), abs(self.end - p)) | Returns the distance from the point to the interval. Zero if the point lies inside the interval. | Below is the the instruction that describes the task:
### Input:
Returns the distance from the point to the interval. Zero if the point lies inside the interval.
### Response:
def distance_to_point(self, p):
'''Returns the distance from the point to the interval. Zero if the point lies inside the interval.... |
def y_ticks(self, *ticks):
"""The points on the y-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-tic... | The points on the y-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if given, these will be chart's x-ticks.
:rtype: ``tuple`` | Below is the the instruction that describes the task:
### Input:
The points on the y-axis for which there are markers and grid lines.
There are default ticks, but you can pass values to this method to
override the defaults. Otherwise the method will return the ticks.
:param \*ticks: if giv... |
def _create_kube_dns_instance(self, instance):
"""
Set up kube_dns instance so it can be used in OpenMetricsBaseCheck
"""
kube_dns_instance = deepcopy(instance)
# kube_dns uses 'prometheus_endpoint' and not 'prometheus_url', so we have to rename the key
kube_dns_instance... | Set up kube_dns instance so it can be used in OpenMetricsBaseCheck | Below is the the instruction that describes the task:
### Input:
Set up kube_dns instance so it can be used in OpenMetricsBaseCheck
### Response:
def _create_kube_dns_instance(self, instance):
"""
Set up kube_dns instance so it can be used in OpenMetricsBaseCheck
"""
kube_dns_instan... |
def import_class(klass):
'''Import the named class and return that class'''
mod = __import__(klass.rpartition('.')[0])
for segment in klass.split('.')[1:-1]:
mod = getattr(mod, segment)
return getattr(mod, klass.rpartition('.')[2]) | Import the named class and return that class | Below is the the instruction that describes the task:
### Input:
Import the named class and return that class
### Response:
def import_class(klass):
'''Import the named class and return that class'''
mod = __import__(klass.rpartition('.')[0])
for segment in klass.split('.')[1:-1]:
mod = getattr... |
def get_input_message(message):
"""Similar to :meth:`get_input_peer`, but for input messages."""
try:
if isinstance(message, int): # This case is really common too
return types.InputMessageID(message)
elif message.SUBCLASS_OF_ID == 0x54b6bcc5: # crc32(b'InputMessage'):
... | Similar to :meth:`get_input_peer`, but for input messages. | Below is the the instruction that describes the task:
### Input:
Similar to :meth:`get_input_peer`, but for input messages.
### Response:
def get_input_message(message):
"""Similar to :meth:`get_input_peer`, but for input messages."""
try:
if isinstance(message, int): # This case is really common ... |
def output_files(self):
"""Returns the list of output files from this rule.
Paths are generated from the outputs of this rule's dependencies, with
their paths translated based on prefix and strip_prefix.
Returned paths are relative to buildroot.
"""
for dep in self.subg... | Returns the list of output files from this rule.
Paths are generated from the outputs of this rule's dependencies, with
their paths translated based on prefix and strip_prefix.
Returned paths are relative to buildroot. | Below is the the instruction that describes the task:
### Input:
Returns the list of output files from this rule.
Paths are generated from the outputs of this rule's dependencies, with
their paths translated based on prefix and strip_prefix.
Returned paths are relative to buildroot.
### Re... |
def sg_mean(tensor, opt):
r"""Computes the mean of elements across axis of a tensor.
See `tf.reduce_mean()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, re... | r"""Computes the mean of elements across axis of a tensor.
See `tf.reduce_mean()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with ... | Below is the the instruction that describes the task:
### Input:
r"""Computes the mean of elements across axis of a tensor.
See `tf.reduce_mean()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to... |
def clear_history(pymux, variables):
" Clear scrollback buffer. "
pane = pymux.arrangement.get_active_pane()
if pane.display_scroll_buffer:
raise CommandException('Not available in copy mode')
else:
pane.process.screen.clear_history() | Clear scrollback buffer. | Below is the the instruction that describes the task:
### Input:
Clear scrollback buffer.
### Response:
def clear_history(pymux, variables):
" Clear scrollback buffer. "
pane = pymux.arrangement.get_active_pane()
if pane.display_scroll_buffer:
raise CommandException('Not available in copy mode... |
def prefetch_users(persistent_course_grades):
"""
Prefetch Users from the list of user_ids present in the persistent_course_grades.
Arguments:
persistent_course_grades (list): A list of PersistentCourseGrade.
Returns:
(dict): A dictionary containing user_id to u... | Prefetch Users from the list of user_ids present in the persistent_course_grades.
Arguments:
persistent_course_grades (list): A list of PersistentCourseGrade.
Returns:
(dict): A dictionary containing user_id to user mapping. | Below is the the instruction that describes the task:
### Input:
Prefetch Users from the list of user_ids present in the persistent_course_grades.
Arguments:
persistent_course_grades (list): A list of PersistentCourseGrade.
Returns:
(dict): A dictionary containing user_id t... |
def simxAuxiliaryConsoleOpen(clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
consoleHandle = ct.c_int()
if (sys.version_info[0] == 3) and (type(title) is str):
... | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxAuxiliaryConsoleOpen(clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode):
'''
Please have a lo... |
def from_networkx_graph(cls, G, vartype=None, node_attribute_name='bias',
edge_attribute_name='bias'):
"""Create a binary quadratic model from a NetworkX graph.
Args:
G (:obj:`networkx.Graph`):
A NetworkX graph with biases stored as node/edge attr... | Create a binary quadratic model from a NetworkX graph.
Args:
G (:obj:`networkx.Graph`):
A NetworkX graph with biases stored as node/edge attributes.
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the binary quadratic model. Accepted inp... | Below is the the instruction that describes the task:
### Input:
Create a binary quadratic model from a NetworkX graph.
Args:
G (:obj:`networkx.Graph`):
A NetworkX graph with biases stored as node/edge attributes.
vartype (:class:`.Vartype`/str/set, optional):
... |
def insert_id(self, sname, skind, skinds, stype):
"""Inserts a new identifier at the end of the symbol table, if possible.
Returns symbol index, or raises an exception if the symbol alredy exists
sname - symbol name
skind - symbol kind
skinds - symbol kinds ... | Inserts a new identifier at the end of the symbol table, if possible.
Returns symbol index, or raises an exception if the symbol alredy exists
sname - symbol name
skind - symbol kind
skinds - symbol kinds to check for
stype - symbol type | Below is the the instruction that describes the task:
### Input:
Inserts a new identifier at the end of the symbol table, if possible.
Returns symbol index, or raises an exception if the symbol alredy exists
sname - symbol name
skind - symbol kind
skinds - symbol... |
def trim(args):
"""
%prog trim fasta.screen newfasta
take the screen output from `cross_match` (against a vector db, for
example), then trim the sequences to remove X's. Will also perform quality
trim if fasta.screen.qual is found. The trimming algorithm is based on
finding the subarray that ma... | %prog trim fasta.screen newfasta
take the screen output from `cross_match` (against a vector db, for
example), then trim the sequences to remove X's. Will also perform quality
trim if fasta.screen.qual is found. The trimming algorithm is based on
finding the subarray that maximize the sum | Below is the the instruction that describes the task:
### Input:
%prog trim fasta.screen newfasta
take the screen output from `cross_match` (against a vector db, for
example), then trim the sequences to remove X's. Will also perform quality
trim if fasta.screen.qual is found. The trimming algorithm is ... |
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use Op... | Try passwordless login with paramiko. | Below is the the instruction that describes the task:
### Input:
Try passwordless login with paramiko.
### Response:
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
... |
def set_context(self, new_context):
"""Assigns the new context to the member variable ``_context``."""
self._context = new_context
if hasattr(self, '_set_logging_context'):
self._set_logging_context(self._context) | Assigns the new context to the member variable ``_context``. | Below is the the instruction that describes the task:
### Input:
Assigns the new context to the member variable ``_context``.
### Response:
def set_context(self, new_context):
"""Assigns the new context to the member variable ``_context``."""
self._context = new_context
if hasattr(self, '_... |
def get_stp_mst_detail_output_last_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_stp_mst_detail_output_last_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
... |
def EndEdit(self, row, col, grid, val=None):
"Complete the editing of the current cell. Returns True if changed"
changed = False
val = self._tc.GetStringSelection()
print "val", val, row, col, self.startValue
if val != self.startValue:
changed = True
... | Complete the editing of the current cell. Returns True if changed | Below is the the instruction that describes the task:
### Input:
Complete the editing of the current cell. Returns True if changed
### Response:
def EndEdit(self, row, col, grid, val=None):
"Complete the editing of the current cell. Returns True if changed"
changed = False
val = self._tc... |
def get_boards(self):
"""
Get the list of boards to pull cards from. If the user gave a value to
trello.include_boards use that, otherwise ask the Trello API for the
user's boards.
"""
if 'include_boards' in self.config:
for boardid in self.config.get('includ... | Get the list of boards to pull cards from. If the user gave a value to
trello.include_boards use that, otherwise ask the Trello API for the
user's boards. | Below is the the instruction that describes the task:
### Input:
Get the list of boards to pull cards from. If the user gave a value to
trello.include_boards use that, otherwise ask the Trello API for the
user's boards.
### Response:
def get_boards(self):
"""
Get the list of boards... |
def manage_host_check_result_brok(self, b): # pylint: disable=too-many-branches
"""An host check result brok has just arrived..."""
host_name = b.data.get('host_name', None)
if not host_name:
return
logger.debug("host check result: %s", host_name)
# If host initial ... | An host check result brok has just arrived... | Below is the the instruction that describes the task:
### Input:
An host check result brok has just arrived...
### Response:
def manage_host_check_result_brok(self, b): # pylint: disable=too-many-branches
"""An host check result brok has just arrived..."""
host_name = b.data.get('host_name', None)... |
def xml_to_json(root):
"""Convert an Open511 XML document or document fragment to JSON.
Takes an lxml Element object. Returns a dict ready to be JSON-serialized."""
j = {}
if len(root) == 0: # Tag with no children, return str/int
return _maybe_intify(root.text)
if len(root) == 1 and root... | Convert an Open511 XML document or document fragment to JSON.
Takes an lxml Element object. Returns a dict ready to be JSON-serialized. | Below is the the instruction that describes the task:
### Input:
Convert an Open511 XML document or document fragment to JSON.
Takes an lxml Element object. Returns a dict ready to be JSON-serialized.
### Response:
def xml_to_json(root):
"""Convert an Open511 XML document or document fragment to JSON.
... |
def setY(self,Y,standardize=False):
"""
Set phenotype matrix
Args:
Y: phenotype matrix [N, P]
standardize: if True, phenotype is standardized (zero mean, unit variance)
"""
assert Y.shape[0]==self.N, 'CVarianceDecomposition:: Incompat... | Set phenotype matrix
Args:
Y: phenotype matrix [N, P]
standardize: if True, phenotype is standardized (zero mean, unit variance) | Below is the the instruction that describes the task:
### Input:
Set phenotype matrix
Args:
Y: phenotype matrix [N, P]
standardize: if True, phenotype is standardized (zero mean, unit variance)
### Response:
def setY(self,Y,standardize=False):
"""
... |
def _parse_options(opts, delim):
"""Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion and the use of the tlsInsecure option."""
options = _CaseInsensitiveDictionary()
for uriopt in opts.split(delim):
... | Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion and the use of the tlsInsecure option. | Below is the the instruction that describes the task:
### Input:
Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion and the use of the tlsInsecure option.
### Response:
def _parse_options(opts, delim):
"""... |
def decodeLength(length):
"""
Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded length.
"""
bytes_length = len(length)
if bytes_length < 2:
offset = b'\x00\x00\x00'
XOR = 0
elif bytes_leng... | Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded length. | Below is the the instruction that describes the task:
### Input:
Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded length.
### Response:
def decodeLength(length):
"""
Decode length based on given bytes.
:param length: Bytes string ... |
def create_correlation_matrix_plot(correlation_matrix, title, feature_list):
"""Creates plot for correlation matrix
:param correlation_matrix: Correlation matrix of features
:param title: Title of plot
:param feature_list: List of names of features
:return: Shows the given correlation matrix as ima... | Creates plot for correlation matrix
:param correlation_matrix: Correlation matrix of features
:param title: Title of plot
:param feature_list: List of names of features
:return: Shows the given correlation matrix as image | Below is the the instruction that describes the task:
### Input:
Creates plot for correlation matrix
:param correlation_matrix: Correlation matrix of features
:param title: Title of plot
:param feature_list: List of names of features
:return: Shows the given correlation matrix as image
### Response... |
def loadOFF(filename, c="gold", alpha=1, wire=False, bc=None):
"""Read OFF file format."""
if not os.path.exists(filename):
colors.printc("~noentry Error in loadOFF: Cannot find", filename, c=1)
return None
f = open(filename, "r")
lines = f.readlines()
f.close()
vertices = []
... | Read OFF file format. | Below is the the instruction that describes the task:
### Input:
Read OFF file format.
### Response:
def loadOFF(filename, c="gold", alpha=1, wire=False, bc=None):
"""Read OFF file format."""
if not os.path.exists(filename):
colors.printc("~noentry Error in loadOFF: Cannot find", filename, c=1)
... |
def validate_offset(reference_event, estimated_event, t_collar=0.200, percentage_of_length=0.5):
"""Validate estimated event based on event offset
Parameters
----------
reference_event : dict
Reference event.
estimated_event : dict
Estimated event.
... | Validate estimated event based on event offset
Parameters
----------
reference_event : dict
Reference event.
estimated_event : dict
Estimated event.
t_collar : float > 0, seconds
First condition, Time collar with which the estimated offset h... | Below is the the instruction that describes the task:
### Input:
Validate estimated event based on event offset
Parameters
----------
reference_event : dict
Reference event.
estimated_event : dict
Estimated event.
t_collar : float > 0, seconds
... |
def extract_detections(detections, templates, archive, arc_type,
extract_len=90.0, outdir=None, extract_Z=True,
additional_stations=[]):
"""
Extract waveforms associated with detections
Takes a list of detections for the template, template. Waveforms will be
... | Extract waveforms associated with detections
Takes a list of detections for the template, template. Waveforms will be
returned as a list of :class:`obspy.core.stream.Stream` containing
segments of extract_len. They will also be saved if outdir is set.
The default is unset. The default extract_len i... | Below is the the instruction that describes the task:
### Input:
Extract waveforms associated with detections
Takes a list of detections for the template, template. Waveforms will be
returned as a list of :class:`obspy.core.stream.Stream` containing
segments of extract_len. They will also be saved if... |
def __sum(self, line):
"""Return the IRQ sum number.
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts
FIQ: usb_fiq
"""
splitted_line = line.sp... | Return the IRQ sum number.
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts
FIQ: usb_fiq | Below is the the instruction that describes the task:
### Input:
Return the IRQ sum number.
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts
FIQ: usb_fiq
### Resp... |
def watch_instances(self, flag):
"""Whether or not the Class Instances are being watched."""
lib.EnvSetDefclassWatchInstances(self._env, int(flag), self._cls) | Whether or not the Class Instances are being watched. | Below is the the instruction that describes the task:
### Input:
Whether or not the Class Instances are being watched.
### Response:
def watch_instances(self, flag):
"""Whether or not the Class Instances are being watched."""
lib.EnvSetDefclassWatchInstances(self._env, int(flag), self._cls) |
def Value(self, p):
"""Returns InverseCDF(p), the value that corresponds to probability p.
Args:
p: number in the range [0, 1]
Returns:
number value
"""
if p < 0 or p > 1:
raise ValueError('Probability p must be in range [0, 1]')
if ... | Returns InverseCDF(p), the value that corresponds to probability p.
Args:
p: number in the range [0, 1]
Returns:
number value | Below is the the instruction that describes the task:
### Input:
Returns InverseCDF(p), the value that corresponds to probability p.
Args:
p: number in the range [0, 1]
Returns:
number value
### Response:
def Value(self, p):
"""Returns InverseCDF(p), the value that... |
def upload_file(self, filename, file_type=FILE_TYPE_FREESURFER_DIRECTORY):
"""Create an anatomy object on local disk from the given file.
Currently, only Freesurfer anatomy directories are supported. Expects a
tar file.
Parameters
----------
filename : string
... | Create an anatomy object on local disk from the given file.
Currently, only Freesurfer anatomy directories are supported. Expects a
tar file.
Parameters
----------
filename : string
Name of the (uploaded) file
file_type : string
File type (current... | Below is the the instruction that describes the task:
### Input:
Create an anatomy object on local disk from the given file.
Currently, only Freesurfer anatomy directories are supported. Expects a
tar file.
Parameters
----------
filename : string
Name of the (upl... |
def download(self, filename, representation, overwrite=False):
"""Download the resolved structure as a file.
:param string filename: File path to save to
:param string representation: Desired output representation
:param bool overwrite: (Optional) Whether to allow overwriting of an exis... | Download the resolved structure as a file.
:param string filename: File path to save to
:param string representation: Desired output representation
:param bool overwrite: (Optional) Whether to allow overwriting of an existing file | Below is the the instruction that describes the task:
### Input:
Download the resolved structure as a file.
:param string filename: File path to save to
:param string representation: Desired output representation
:param bool overwrite: (Optional) Whether to allow overwriting of an existing ... |
def open(self):
"""
Opens the URL associated with the GPFile and returns a file-like object
with three extra methods:
* geturl() - return the ultimate URL (can be used to determine if a
redirect was followed)
* info() - return the meta-information of the... | Opens the URL associated with the GPFile and returns a file-like object
with three extra methods:
* geturl() - return the ultimate URL (can be used to determine if a
redirect was followed)
* info() - return the meta-information of the page, such as headers
... | Below is the the instruction that describes the task:
### Input:
Opens the URL associated with the GPFile and returns a file-like object
with three extra methods:
* geturl() - return the ultimate URL (can be used to determine if a
redirect was followed)
* info() - r... |
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _... | List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...} | Below is the the instruction that describes the task:
### Input:
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
### Response:
def list(region=None,... |
def _get_default_tempdir():
"""Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is delet... | Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is deleted. To prevent denial of
servi... | Below is the the instruction that describes the task:
### Input:
Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is ... |
def _get_line(self) -> str:
"""Returns the current line from the file while incrementing the index."""
line = self.in_lines[self.index]
self.index += 1
return line | Returns the current line from the file while incrementing the index. | Below is the the instruction that describes the task:
### Input:
Returns the current line from the file while incrementing the index.
### Response:
def _get_line(self) -> str:
"""Returns the current line from the file while incrementing the index."""
line = self.in_lines[self.index]
self.in... |
def to_dict(self):
'''A representation of that publication data that matches the schema we use in our databases.'''
if not self.record_type == 'journal':
# todo: it may be worthwhile creating subclasses for each entry type (journal, conference, etc.) with a common
# API e.g. to_j... | A representation of that publication data that matches the schema we use in our databases. | Below is the the instruction that describes the task:
### Input:
A representation of that publication data that matches the schema we use in our databases.
### Response:
def to_dict(self):
'''A representation of that publication data that matches the schema we use in our databases.'''
if not self.r... |
def diff(iterable):
"""Diff elements of a sequence:
s -> s0 - s1, s1 - s2, s2 - s3, ...
"""
a, b = tee(iterable)
next(b, None)
return (i - j for i, j in izip(a, b)) | Diff elements of a sequence:
s -> s0 - s1, s1 - s2, s2 - s3, ... | Below is the the instruction that describes the task:
### Input:
Diff elements of a sequence:
s -> s0 - s1, s1 - s2, s2 - s3, ...
### Response:
def diff(iterable):
"""Diff elements of a sequence:
s -> s0 - s1, s1 - s2, s2 - s3, ...
"""
a, b = tee(iterable)
next(b, None)
return (i - j fo... |
def oem_name(self, value):
"""The oem_name property.
Args:
value (string). the property value.
"""
if value == self._defaults['ai.device.oemName'] and 'ai.device.oemName' in self._values:
del self._values['ai.device.oemName']
else:
sel... | The oem_name property.
Args:
value (string). the property value. | Below is the the instruction that describes the task:
### Input:
The oem_name property.
Args:
value (string). the property value.
### Response:
def oem_name(self, value):
"""The oem_name property.
Args:
value (string). the property value.
""... |
def _run1(self):
"""workhorse for do_run_1"""
if self.check_update_J():
self.update_J()
else:
if self.check_Broyden_J():
self.update_Broyden_J()
if self.check_update_eig_J():
self.update_eig_J()
#1. Assuming that J star... | workhorse for do_run_1 | Below is the the instruction that describes the task:
### Input:
workhorse for do_run_1
### Response:
def _run1(self):
"""workhorse for do_run_1"""
if self.check_update_J():
self.update_J()
else:
if self.check_Broyden_J():
self.update_Broyden_J()
... |
def set_proxy(self, host, port, user, password):
'''
Sets the proxy server host and port for the HTTP CONNECT Tunnelling.
Note that we set the proxies directly on the request later on rather than
using the session object as requests has a bug where session proxy is ignored
in fa... | Sets the proxy server host and port for the HTTP CONNECT Tunnelling.
Note that we set the proxies directly on the request later on rather than
using the session object as requests has a bug where session proxy is ignored
in favor of environment proxy. So, auth will not work unless it is passed
... | Below is the the instruction that describes the task:
### Input:
Sets the proxy server host and port for the HTTP CONNECT Tunnelling.
Note that we set the proxies directly on the request later on rather than
using the session object as requests has a bug where session proxy is ignored
in fa... |
def adjust_for_isolated(self):
"""
Remove certain plugins in order to handle the "isolated build"
scenario.
"""
if self.user_params.isolated.value:
remove_plugins = [
("prebuild_plugins", "check_and_set_rebuild"),
("prebuild_plugins", "... | Remove certain plugins in order to handle the "isolated build"
scenario. | Below is the the instruction that describes the task:
### Input:
Remove certain plugins in order to handle the "isolated build"
scenario.
### Response:
def adjust_for_isolated(self):
"""
Remove certain plugins in order to handle the "isolated build"
scenario.
"""
if ... |
def moderate(self, comment, content_object, request):
"""
Determine whether a given comment on a given object should be allowed to show up immediately,
or should be marked non-public and await approval.
Returns ``True`` if the comment should be moderated (marked non-public), ``False`` o... | Determine whether a given comment on a given object should be allowed to show up immediately,
or should be marked non-public and await approval.
Returns ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise. | Below is the the instruction that describes the task:
### Input:
Determine whether a given comment on a given object should be allowed to show up immediately,
or should be marked non-public and await approval.
Returns ``True`` if the comment should be moderated (marked non-public), ``False`` otherw... |
def uninstall_signal_trap(signums = None):
"""
Undo the effects of install_signal_trap(). Restores the original
signal handlers. If signums is a sequence of signal numbers only
the signal handlers for those signals will be restored (KeyError
will be raised if one of them is not one that install_signal_trap()
in... | Undo the effects of install_signal_trap(). Restores the original
signal handlers. If signums is a sequence of signal numbers only
the signal handlers for those signals will be restored (KeyError
will be raised if one of them is not one that install_signal_trap()
installed a handler for, in which case some undefin... | Below is the the instruction that describes the task:
### Input:
Undo the effects of install_signal_trap(). Restores the original
signal handlers. If signums is a sequence of signal numbers only
the signal handlers for those signals will be restored (KeyError
will be raised if one of them is not one that insta... |
def show_updates(self):
"""
Check installed packages for available updates on PyPI
@param project_name: optional package name to check; checks every
installed pacakge if none specified
@type project_name: string
@returns: None
"""
di... | Check installed packages for available updates on PyPI
@param project_name: optional package name to check; checks every
installed pacakge if none specified
@type project_name: string
@returns: None | Below is the the instruction that describes the task:
### Input:
Check installed packages for available updates on PyPI
@param project_name: optional package name to check; checks every
installed pacakge if none specified
@type project_name: string
@returns: No... |
def update_frontend(self, info):
"""Updates frontend with info from the log
:param info: dict - Information from a line in the log. i.e regular line, new step.
"""
headers = {'Content-Type': 'text/event-stream'}
if info.get('when'):
info['when'] = info['when'].isofor... | Updates frontend with info from the log
:param info: dict - Information from a line in the log. i.e regular line, new step. | Below is the the instruction that describes the task:
### Input:
Updates frontend with info from the log
:param info: dict - Information from a line in the log. i.e regular line, new step.
### Response:
def update_frontend(self, info):
"""Updates frontend with info from the log
:param inf... |
def all_table_names_in_database(self, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments."""
if not self.allow_multi_schema_metadata_fetch:
return []
return self.db_engine_spec.fetch_result_sets(self... | Parameters need to be passed as keyword arguments. | Below is the the instruction that describes the task:
### Input:
Parameters need to be passed as keyword arguments.
### Response:
def all_table_names_in_database(self, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments."""... |
def export_configuration(self):
"""
:rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList
"""
if self._export_configuration is None:
self._export_configuration = ExportConfigurationList(self)
return self._export_configuration | :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList | Below is the the instruction that describes the task:
### Input:
:rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList
### Response:
def export_configuration(self):
"""
:rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList
"""
... |
def _check_relation(self, relation):
"""Raise a `ValueError` if `relation` is not allowed among
the possible values.
"""
selection = [val[0] for val in self.selection]
if relation not in selection:
raise ValueError(
("The value '{value}' supplied doesn... | Raise a `ValueError` if `relation` is not allowed among
the possible values. | Below is the the instruction that describes the task:
### Input:
Raise a `ValueError` if `relation` is not allowed among
the possible values.
### Response:
def _check_relation(self, relation):
"""Raise a `ValueError` if `relation` is not allowed among
the possible values.
"""
... |
def print_inplace(*args, **kwargs):
""" Save cursor position, write some text, and then restore the position.
Arguments:
Same as `print()`.
Keyword Arguments:
Same as `print()`, except `end` defaults to '' (empty str),
and these:
delay : Time in s... | Save cursor position, write some text, and then restore the position.
Arguments:
Same as `print()`.
Keyword Arguments:
Same as `print()`, except `end` defaults to '' (empty str),
and these:
delay : Time in seconds between character writes. | Below is the the instruction that describes the task:
### Input:
Save cursor position, write some text, and then restore the position.
Arguments:
Same as `print()`.
Keyword Arguments:
Same as `print()`, except `end` defaults to '' (empty str),
and these:
... |
def build_model(self):
"""Build the model's computational graph."""
with tf.variable_scope(
"model", reuse=None, initializer=self.initializer):
self._create_placeholders()
self._create_rnn_cells()
self._create_initstate_and_embeddings()
sel... | Build the model's computational graph. | Below is the the instruction that describes the task:
### Input:
Build the model's computational graph.
### Response:
def build_model(self):
"""Build the model's computational graph."""
with tf.variable_scope(
"model", reuse=None, initializer=self.initializer):
self._cre... |
def unbind(self, instance_id: str, binding_id: str, details: UnbindDetails):
"""Unbinding the instance
see openbrokerapi documentation
Raises:
ErrBindingDoesNotExist: Binding does not exist.
"""
# Find the instance
instance = self._b... | Unbinding the instance
see openbrokerapi documentation
Raises:
ErrBindingDoesNotExist: Binding does not exist. | Below is the the instruction that describes the task:
### Input:
Unbinding the instance
see openbrokerapi documentation
Raises:
ErrBindingDoesNotExist: Binding does not exist.
### Response:
def unbind(self, instance_id: str, binding_id: str, details: UnbindDetails):
... |
def to_csv(df, filepath, sep=',', header=True, index=True):
"""Save DataFrame as csv.
Note data is expected to be evaluated.
Currently delegates to Pandas.
Parameters
----------
df : DataFrame
filepath : str
sep : str, optional
Separator used between values.
header : bool,... | Save DataFrame as csv.
Note data is expected to be evaluated.
Currently delegates to Pandas.
Parameters
----------
df : DataFrame
filepath : str
sep : str, optional
Separator used between values.
header : bool, optional
Whether to save the header.
index : bool, opt... | Below is the the instruction that describes the task:
### Input:
Save DataFrame as csv.
Note data is expected to be evaluated.
Currently delegates to Pandas.
Parameters
----------
df : DataFrame
filepath : str
sep : str, optional
Separator used between values.
header : boo... |
def find_serial_devices(serial_matcher="ED"):
"""
Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str]
"""
objWMIService = win32com.client... | Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str] | Below is the the instruction that describes the task:
### Input:
Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str]
### Response:
def find_serial_d... |
def serialize(self):
"""Serialize this segment to a ``Segment`` message.
Returns:
``Segment`` message.
"""
segment = hangouts_pb2.Segment(
type=self.type_,
text=self.text,
formatting=hangouts_pb2.Formatting(
bold=self.is_bo... | Serialize this segment to a ``Segment`` message.
Returns:
``Segment`` message. | Below is the the instruction that describes the task:
### Input:
Serialize this segment to a ``Segment`` message.
Returns:
``Segment`` message.
### Response:
def serialize(self):
"""Serialize this segment to a ``Segment`` message.
Returns:
``Segment`` message.
... |
def closest_distance_to(self, position: Union[Unit, Point2, Point3]) -> Union[int, float]:
""" Returns the distance between the closest unit from this group to the target unit """
assert self.exists
if isinstance(position, Unit):
position = position.position
return position.d... | Returns the distance between the closest unit from this group to the target unit | Below is the the instruction that describes the task:
### Input:
Returns the distance between the closest unit from this group to the target unit
### Response:
def closest_distance_to(self, position: Union[Unit, Point2, Point3]) -> Union[int, float]:
""" Returns the distance between the closest unit from t... |
def first(self, skipna=None, keep_attrs=None):
"""Return the first element of each group along the group dimension
"""
return self._first_or_last(duck_array_ops.first, skipna, keep_attrs) | Return the first element of each group along the group dimension | Below is the the instruction that describes the task:
### Input:
Return the first element of each group along the group dimension
### Response:
def first(self, skipna=None, keep_attrs=None):
"""Return the first element of each group along the group dimension
"""
return self._first_or_last(d... |
def assignment_to_plan(assignment):
"""Convert an assignment to the format used by Kafka to
describe a reassignment plan.
"""
return {
'version': 1,
'partitions':
[{'topic': t_p[0],
'partition': t_p[1],
'replicas': replica
} for t_p, replica in six.i... | Convert an assignment to the format used by Kafka to
describe a reassignment plan. | Below is the the instruction that describes the task:
### Input:
Convert an assignment to the format used by Kafka to
describe a reassignment plan.
### Response:
def assignment_to_plan(assignment):
"""Convert an assignment to the format used by Kafka to
describe a reassignment plan.
"""
return ... |
def add_update_date(self, item):
""" All item['updated_on'] from perceval is epoch """
updated = unixtime_to_datetime(item['updated_on'])
timestamp = unixtime_to_datetime(item['timestamp'])
item['metadata__updated_on'] = updated.isoformat()
# Also add timestamp used in incrementa... | All item['updated_on'] from perceval is epoch | Below is the the instruction that describes the task:
### Input:
All item['updated_on'] from perceval is epoch
### Response:
def add_update_date(self, item):
""" All item['updated_on'] from perceval is epoch """
updated = unixtime_to_datetime(item['updated_on'])
timestamp = unixtime_to_date... |
def execute_command_with_path_in_process(command, path, shell=False, cwd=None, logger=None):
"""Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether t... | Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional l... | Below is the the instruction that describes the task:
### Input:
Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether to use a shell
:param str cw... |
def command_line(self, input_path=None):
'''Return a string to run OrfM with, assuming sequences are incoming on
stdin and printed to stdout
Parameters
----------
input_path: str
path to the input path, or None for STDIN being the input
'''
... | Return a string to run OrfM with, assuming sequences are incoming on
stdin and printed to stdout
Parameters
----------
input_path: str
path to the input path, or None for STDIN being the input | Below is the the instruction that describes the task:
### Input:
Return a string to run OrfM with, assuming sequences are incoming on
stdin and printed to stdout
Parameters
----------
input_path: str
path to the input path, or None for STDIN being the input
### R... |
def dbg_repr(self):
"""
The debugging representation of this CFBlanket.
:return: The debugging representation of this CFBlanket.
:rtype: str
"""
output = [ ]
for obj in self.project.loader.all_objects:
for section in obj.sections:
... | The debugging representation of this CFBlanket.
:return: The debugging representation of this CFBlanket.
:rtype: str | Below is the the instruction that describes the task:
### Input:
The debugging representation of this CFBlanket.
:return: The debugging representation of this CFBlanket.
:rtype: str
### Response:
def dbg_repr(self):
"""
The debugging representation of this CFBlanket.
... |
def manage_options(self):
"""
Create a parser given the command-line arguments, creates a parser
Return True if the programme must exit.
"""
self.parser = self.create_parser()
self.options, self.args = self.parser.parse_args(self.argv)
self.do_imports()
... | Create a parser given the command-line arguments, creates a parser
Return True if the programme must exit. | Below is the the instruction that describes the task:
### Input:
Create a parser given the command-line arguments, creates a parser
Return True if the programme must exit.
### Response:
def manage_options(self):
"""
Create a parser given the command-line arguments, creates a parser
... |
async def ltrim(self, name, start, end):
"""
Trim the list ``name``, removing all values not within the slice
between ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
"""
return await self.execute_command('LTRI... | Trim the list ``name``, removing all values not within the slice
between ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation | Below is the the instruction that describes the task:
### Input:
Trim the list ``name``, removing all values not within the slice
between ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
### Response:
async def ltrim(self, name, start, e... |
def find_stringy_lines(tree: ast.AST, first_line_no: int) -> Set[int]:
"""
Finds all lines that contain a string in a tree, usually a function. These
lines will be ignored when searching for blank lines.
"""
str_footprints = set()
for node in ast.walk(tree):
if isinstance(node, ast.Str):... | Finds all lines that contain a string in a tree, usually a function. These
lines will be ignored when searching for blank lines. | Below is the the instruction that describes the task:
### Input:
Finds all lines that contain a string in a tree, usually a function. These
lines will be ignored when searching for blank lines.
### Response:
def find_stringy_lines(tree: ast.AST, first_line_no: int) -> Set[int]:
"""
Finds all lines that... |
def stream(self):
"""
the stream to write the log content too.
@return:
"""
if self._stream is None:
self._stream = tempfile.NamedTemporaryFile(delete=False)
try:
self._stream.write(self.client.open(self.filename, view='data').read())
... | the stream to write the log content too.
@return: | Below is the the instruction that describes the task:
### Input:
the stream to write the log content too.
@return:
### Response:
def stream(self):
"""
the stream to write the log content too.
@return:
"""
if self._stream is None:
self._stream = tempfile.N... |
def index(self, weighted=True, prune=False):
"""Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice.
"""
warnings.warn(
"CrunchCube.index() is deprecated. Use CubeSlice.index_table().",
DeprecationWarning,
)
... | Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice. | Below is the the instruction that describes the task:
### Input:
Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice.
### Response:
def index(self, weighted=True, prune=False):
"""Return cube index measurement.
This function is deprecated. Use index_... |
def next_line(self):
"""Read the next line from the line generator and split it"""
self.line = next(self.lines) # Will raise StopIteration when there are no more lines
self.values = self.line.split() | Read the next line from the line generator and split it | Below is the the instruction that describes the task:
### Input:
Read the next line from the line generator and split it
### Response:
def next_line(self):
"""Read the next line from the line generator and split it"""
self.line = next(self.lines) # Will raise StopIteration when there are no more l... |
def get_responsibles_data(self, reports):
"""Responsibles data to be used in the template
"""
if not reports:
return []
recipients = []
recipient_names = []
for num, report in enumerate(reports):
# get the linked AR of this ARReport
a... | Responsibles data to be used in the template | Below is the the instruction that describes the task:
### Input:
Responsibles data to be used in the template
### Response:
def get_responsibles_data(self, reports):
"""Responsibles data to be used in the template
"""
if not reports:
return []
recipients = []
re... |
def get_field_from_args_or_session(config, args, field_name):
"""
We try to get field_name from diffent sources:
The order of priorioty is following:
- command line argument (--<field_name>)
- current session configuration (default_<filed_name>)
"""
rez = getattr(args, field_name, None)
... | We try to get field_name from diffent sources:
The order of priorioty is following:
- command line argument (--<field_name>)
- current session configuration (default_<filed_name>) | Below is the the instruction that describes the task:
### Input:
We try to get field_name from diffent sources:
The order of priorioty is following:
- command line argument (--<field_name>)
- current session configuration (default_<filed_name>)
### Response:
def get_field_from_args_or_session(config, a... |
def ipv6_generate_random(total=100):
"""
The generator to produce random, unique IPv6 addresses that are not
defined (can be looked up using ipwhois).
Args:
total (:obj:`int`): The total number of IPv6 addresses to generate.
Yields:
str: The next IPv6 address.
"""
count = ... | The generator to produce random, unique IPv6 addresses that are not
defined (can be looked up using ipwhois).
Args:
total (:obj:`int`): The total number of IPv6 addresses to generate.
Yields:
str: The next IPv6 address. | Below is the the instruction that describes the task:
### Input:
The generator to produce random, unique IPv6 addresses that are not
defined (can be looked up using ipwhois).
Args:
total (:obj:`int`): The total number of IPv6 addresses to generate.
Yields:
str: The next IPv6 address.
#... |
def get_comment_book_assignment_session(self):
"""Gets the session for assigning comment to book mappings.
return: (osid.commenting.CommentBookAssignmentSession) - a
``CommentBookAssignmentSession``
raise: OperationFailed - unable to complete request
raise: Unimplement... | Gets the session for assigning comment to book mappings.
return: (osid.commenting.CommentBookAssignmentSession) - a
``CommentBookAssignmentSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_comment_book_assignment()``
... | Below is the the instruction that describes the task:
### Input:
Gets the session for assigning comment to book mappings.
return: (osid.commenting.CommentBookAssignmentSession) - a
``CommentBookAssignmentSession``
raise: OperationFailed - unable to complete request
raise: ... |
def font(self, container):
"""The :class:`Font` described by this single-styled text's style.
If the exact font style as described by the `font_weight`,
`font_slant` and `font_width` style attributes is not present in the
`typeface`, the closest font available is returned instead, and a... | The :class:`Font` described by this single-styled text's style.
If the exact font style as described by the `font_weight`,
`font_slant` and `font_width` style attributes is not present in the
`typeface`, the closest font available is returned instead, and a
warning is printed. | Below is the the instruction that describes the task:
### Input:
The :class:`Font` described by this single-styled text's style.
If the exact font style as described by the `font_weight`,
`font_slant` and `font_width` style attributes is not present in the
`typeface`, the closest font avail... |
def clan_badge_url(self):
'''Returns clan badge url'''
if self.clan_tag is None:
return None
url = self.raw_data.get('clan').get('badge').get('url')
if not url:
return None
return "http://api.cr-api.com" + url | Returns clan badge url | Below is the the instruction that describes the task:
### Input:
Returns clan badge url
### Response:
def clan_badge_url(self):
'''Returns clan badge url'''
if self.clan_tag is None:
return None
url = self.raw_data.get('clan').get('badge').get('url')
if not url:
... |
def str_to_v1_str(xml_str):
"""Convert a API v2 XML doc to v1 XML doc.
Removes elements that are only valid for v2 and changes namespace to v1.
If doc is already v1, it is returned unchanged.
Args:
xml_str : str
API v2 XML doc. E.g.: ``SystemMetadata v2``.
Returns:
str : API ... | Convert a API v2 XML doc to v1 XML doc.
Removes elements that are only valid for v2 and changes namespace to v1.
If doc is already v1, it is returned unchanged.
Args:
xml_str : str
API v2 XML doc. E.g.: ``SystemMetadata v2``.
Returns:
str : API v1 XML doc. E.g.: ``SystemMetadata ... | Below is the the instruction that describes the task:
### Input:
Convert a API v2 XML doc to v1 XML doc.
Removes elements that are only valid for v2 and changes namespace to v1.
If doc is already v1, it is returned unchanged.
Args:
xml_str : str
API v2 XML doc. E.g.: ``SystemMetadata v2... |
def close(self, **kw):
"""
This asks Tor to close the underlying circuit object. See
:meth:`txtorcon.torstate.TorState.close_circuit`
for details.
You may pass keyword arguments to take care of any Flags Tor
accepts for the CLOSECIRCUIT command. Currently, this is only
... | This asks Tor to close the underlying circuit object. See
:meth:`txtorcon.torstate.TorState.close_circuit`
for details.
You may pass keyword arguments to take care of any Flags Tor
accepts for the CLOSECIRCUIT command. Currently, this is only
"IfUnused". So for example: circ.clo... | Below is the the instruction that describes the task:
### Input:
This asks Tor to close the underlying circuit object. See
:meth:`txtorcon.torstate.TorState.close_circuit`
for details.
You may pass keyword arguments to take care of any Flags Tor
accepts for the CLOSECIRCUIT command.... |
def are_expparam_dtypes_consistent(self, expparams):
"""
Returns ``True`` iff all of the given expparams
correspond to outcome domains with the same dtype.
For efficiency, concrete subclasses should override this method
if the result is always ``True``.
:param np.ndarr... | Returns ``True`` iff all of the given expparams
correspond to outcome domains with the same dtype.
For efficiency, concrete subclasses should override this method
if the result is always ``True``.
:param np.ndarray expparams: Array of expparamms
of type ``expparams_dtype... | Below is the the instruction that describes the task:
### Input:
Returns ``True`` iff all of the given expparams
correspond to outcome domains with the same dtype.
For efficiency, concrete subclasses should override this method
if the result is always ``True``.
:param np.ndarray e... |
def current(self):
"""A namedtuple contains `uuid`, `project`, `action`.
Example::
@app.route('/webhook/broadcast-news')
def broadcast_news():
if rio.current.action.startswith('news-'):
broadcast(request.get_json())
"""
event ... | A namedtuple contains `uuid`, `project`, `action`.
Example::
@app.route('/webhook/broadcast-news')
def broadcast_news():
if rio.current.action.startswith('news-'):
broadcast(request.get_json()) | Below is the the instruction that describes the task:
### Input:
A namedtuple contains `uuid`, `project`, `action`.
Example::
@app.route('/webhook/broadcast-news')
def broadcast_news():
if rio.current.action.startswith('news-'):
broadcast(request... |
def handle_error(program_name, cmd, log=None):
"""Subprocess program error handling
Args:
program_name (str): name of the subprocess program
Returns:
break_now (bool): indicate whether calling program should break out of loop
"""
print('\nHouston, we have a problem.',
'\... | Subprocess program error handling
Args:
program_name (str): name of the subprocess program
Returns:
break_now (bool): indicate whether calling program should break out of loop | Below is the the instruction that describes the task:
### Input:
Subprocess program error handling
Args:
program_name (str): name of the subprocess program
Returns:
break_now (bool): indicate whether calling program should break out of loop
### Response:
def handle_error(program_name, cmd... |
def send_sync(self, body, exchange, key):
"""
发送并同步接受回复消息
:return:
"""
callback_queue = self.declare_queue(exclusive=True,
auto_delete=True) # 得到随机回调队列名
self._channel.basic_consume(self.on_response, # 客户端消费回调队列
... | 发送并同步接受回复消息
:return: | Below is the the instruction that describes the task:
### Input:
发送并同步接受回复消息
:return:
### Response:
def send_sync(self, body, exchange, key):
"""
发送并同步接受回复消息
:return:
"""
callback_queue = self.declare_queue(exclusive=True,
... |
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateProperty(state_field.workflow, field_name) | Attach a workflow to the attribute list (create a StateProperty). | Below is the the instruction that describes the task:
### Input:
Attach a workflow to the attribute list (create a StateProperty).
### Response:
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateP... |
def find_transfer_consensus_hash( name_rec, block_id, vtxindex, nameop_consensus_hash ):
"""
Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation.
@name_rec is the current name record, before this NAME_TRANSFER.
@block_id is the current block height.
@vtxindex is t... | Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation.
@name_rec is the current name record, before this NAME_TRANSFER.
@block_id is the current block height.
@vtxindex is the relative index of this transaction in this block.
@nameop_consensus_hash is the consensus hash... | Below is the the instruction that describes the task:
### Input:
Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation.
@name_rec is the current name record, before this NAME_TRANSFER.
@block_id is the current block height.
@vtxindex is the relative index of this transa... |
def ask(self, question, default=False):
""" Ask a y/n question to the user.
"""
choices = '[%s/%s]' % ('Y' if default else 'y', 'n' if default else 'N')
while True:
response = raw_input('%s %s' % (question, choices)).strip()
if not response:
return... | Ask a y/n question to the user. | Below is the the instruction that describes the task:
### Input:
Ask a y/n question to the user.
### Response:
def ask(self, question, default=False):
""" Ask a y/n question to the user.
"""
choices = '[%s/%s]' % ('Y' if default else 'y', 'n' if default else 'N')
while True:
... |
def _new_population_genalg(population,
fitnesses,
mutation_chance=0.02,
crossover_chance=0.7,
selection_function=gaoperators.tournament_selection,
crossover_function=gaoperators.one_poi... | Perform all genetic algorithm operations on a population, and return a new population.
population must have an even number of chromosomes.
Args:
population: A list of binary lists, ex. [[0,1,1,0], [1,0,1,0]]
fitness: A list of fitnesses that correspond with chromosomes in the population,
... | Below is the the instruction that describes the task:
### Input:
Perform all genetic algorithm operations on a population, and return a new population.
population must have an even number of chromosomes.
Args:
population: A list of binary lists, ex. [[0,1,1,0], [1,0,1,0]]
fitness: A list o... |
def set_meta_rdf(self, rdf, fmt='n3'):
"""Set the metadata for this Thing in RDF fmt
Advanced users who want to manipulate the RDF for this Thing directly without the
[ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object
Raises [IOTException](./Exceptions.m.htm... | Set the metadata for this Thing in RDF fmt
Advanced users who want to manipulate the RDF for this Thing directly without the
[ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
... | Below is the the instruction that describes the task:
### Input:
Set the metadata for this Thing in RDF fmt
Advanced users who want to manipulate the RDF for this Thing directly without the
[ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object
Raises [IOTException]... |
def path(self, startLayer, endLayer):
"""
Used in error checking with verifyArchitecture() and in prop_from().
"""
next = {startLayer.name : startLayer}
visited = {}
while next != {}:
for item in list(next.items()):
# item[0] : name, item[1] : ... | Used in error checking with verifyArchitecture() and in prop_from(). | Below is the the instruction that describes the task:
### Input:
Used in error checking with verifyArchitecture() and in prop_from().
### Response:
def path(self, startLayer, endLayer):
"""
Used in error checking with verifyArchitecture() and in prop_from().
"""
next = {startLayer.n... |
def create_review(self, review, pub_name, ext_name):
"""CreateReview.
[Preview API] Creates a new review for an extension
:param :class:`<Review> <azure.devops.v5_0.gallery.models.Review>` review: Review to be created for the extension
:param str pub_name: Name of the publisher who publi... | CreateReview.
[Preview API] Creates a new review for an extension
:param :class:`<Review> <azure.devops.v5_0.gallery.models.Review>` review: Review to be created for the extension
:param str pub_name: Name of the publisher who published the extension
:param str ext_name: Name of the exte... | Below is the the instruction that describes the task:
### Input:
CreateReview.
[Preview API] Creates a new review for an extension
:param :class:`<Review> <azure.devops.v5_0.gallery.models.Review>` review: Review to be created for the extension
:param str pub_name: Name of the publisher who ... |
def parse_list(cls, data):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
data = data or []
for obj in data:
if obj:
results.append(cls.parse(obj))
return results | Parse a list of JSON objects into a result set of model instances. | Below is the the instruction that describes the task:
### Input:
Parse a list of JSON objects into a result set of model instances.
### Response:
def parse_list(cls, data):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
data = data or []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.