code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def time_in_range(self):
"""Return true if current time is in the active range"""
curr = datetime.datetime.now().time()
if self.start_time <= self.end_time:
return self.start_time <= curr <= self.end_time
else:
return self.start_time <= curr or curr <= self.end_ti... | Return true if current time is in the active range | Below is the the instruction that describes the task:
### Input:
Return true if current time is in the active range
### Response:
def time_in_range(self):
"""Return true if current time is in the active range"""
curr = datetime.datetime.now().time()
if self.start_time <= self.end_time:
... |
def load_config():
"""Load a keyring using the config file in the config root."""
filename = 'keyringrc.cfg'
keyring_cfg = os.path.join(platform.config_root(), filename)
if not os.path.exists(keyring_cfg):
return
config = configparser.RawConfigParser()
config.read(keyring_cfg)
_l... | Load a keyring using the config file in the config root. | Below is the the instruction that describes the task:
### Input:
Load a keyring using the config file in the config root.
### Response:
def load_config():
"""Load a keyring using the config file in the config root."""
filename = 'keyringrc.cfg'
keyring_cfg = os.path.join(platform.config_root(), filen... |
def sayHello(self, name="Not given", message="nothing"):
"""
Synchronous implementation of IHello.sayHello synchronous method.
The remote calling thread will be blocked until this is executed and
responds.
"""
print(
"Python.sayHello called by: {0} "
... | Synchronous implementation of IHello.sayHello synchronous method.
The remote calling thread will be blocked until this is executed and
responds. | Below is the the instruction that describes the task:
### Input:
Synchronous implementation of IHello.sayHello synchronous method.
The remote calling thread will be blocked until this is executed and
responds.
### Response:
def sayHello(self, name="Not given", message="nothing"):
"""
... |
def set_connection(host=None, database=None, user=None, password=None):
"""Set connection parameters. Call set_connection with no arguments to clear."""
c.CONNECTION['HOST'] = host
c.CONNECTION['DATABASE'] = database
c.CONNECTION['USER'] = user
c.CONNECTION['PASSWORD'] = password | Set connection parameters. Call set_connection with no arguments to clear. | Below is the the instruction that describes the task:
### Input:
Set connection parameters. Call set_connection with no arguments to clear.
### Response:
def set_connection(host=None, database=None, user=None, password=None):
"""Set connection parameters. Call set_connection with no arguments to clear."""
... |
def __build_author_name_expr(author_name, author_email_address):
"""
Build the name of the author of a message as described in the Internet
Message Format specification: https://tools.ietf.org/html/rfc5322#section-3.6.2
@param author_name: complete name of the originator of the message.
@param au... | Build the name of the author of a message as described in the Internet
Message Format specification: https://tools.ietf.org/html/rfc5322#section-3.6.2
@param author_name: complete name of the originator of the message.
@param author_email_address: address of the mailbox to which the author
of the... | Below is the the instruction that describes the task:
### Input:
Build the name of the author of a message as described in the Internet
Message Format specification: https://tools.ietf.org/html/rfc5322#section-3.6.2
@param author_name: complete name of the originator of the message.
@param author_ema... |
def zip_entry_rollup(zipfile):
"""
returns a tuple of (files, dirs, size_uncompressed,
size_compressed). files+dirs will equal len(zipfile.infolist)
"""
files = dirs = 0
total_c = total_u = 0
for i in zipfile.infolist():
if i.filename[-1] == '/':
# I wonder if there's a... | returns a tuple of (files, dirs, size_uncompressed,
size_compressed). files+dirs will equal len(zipfile.infolist) | Below is the the instruction that describes the task:
### Input:
returns a tuple of (files, dirs, size_uncompressed,
size_compressed). files+dirs will equal len(zipfile.infolist)
### Response:
def zip_entry_rollup(zipfile):
"""
returns a tuple of (files, dirs, size_uncompressed,
size_compressed). f... |
def _get_reference(self):
"""
Sets up references to important components. A reference is typically an
index or a list of indices that point to the corresponding elements
in a flatten array, which is how MuJoCo stores physical simulation data.
"""
super()._get_reference()
... | Sets up references to important components. A reference is typically an
index or a list of indices that point to the corresponding elements
in a flatten array, which is how MuJoCo stores physical simulation data. | Below is the the instruction that describes the task:
### Input:
Sets up references to important components. A reference is typically an
index or a list of indices that point to the corresponding elements
in a flatten array, which is how MuJoCo stores physical simulation data.
### Response:
def _ge... |
def create_app(config='udata.settings.Defaults', override=None,
init_logging=init_logging):
'''Factory for a minimal application'''
app = UDataApp(APP_NAME)
app.config.from_object(config)
settings = os.environ.get('UDATA_SETTINGS', join(os.getcwd(), 'udata.cfg'))
if exists(settings):... | Factory for a minimal application | Below is the the instruction that describes the task:
### Input:
Factory for a minimal application
### Response:
def create_app(config='udata.settings.Defaults', override=None,
init_logging=init_logging):
'''Factory for a minimal application'''
app = UDataApp(APP_NAME)
app.config.from_ob... |
def validate_data(self):
"""
Validate specimen, sample, site, and location data.
"""
warnings = {}
spec_warnings, samp_warnings, site_warnings, loc_warnings = {}, {}, {}, {}
if self.specimens:
spec_warnings = self.validate_items(self.specimens, 'specimen')
... | Validate specimen, sample, site, and location data. | Below is the the instruction that describes the task:
### Input:
Validate specimen, sample, site, and location data.
### Response:
def validate_data(self):
"""
Validate specimen, sample, site, and location data.
"""
warnings = {}
spec_warnings, samp_warnings, site_warnings, ... |
def get_locations():
"""
Pull the accounts locations.
"""
arequest = requests.get(LOCATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.... | Pull the accounts locations. | Below is the the instruction that describes the task:
### Input:
Pull the accounts locations.
### Response:
def get_locations():
"""
Pull the accounts locations.
"""
arequest = requests.get(LOCATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if st... |
def guess_labels(self, doc):
"""
return a prediction of label names
"""
if doc.nb_pages <= 0:
return set()
self.label_guesser.total_nb_documents = len(self._docs_by_id.keys())
label_names = self.label_guesser.guess(doc)
labels = set()
for label... | return a prediction of label names | Below is the the instruction that describes the task:
### Input:
return a prediction of label names
### Response:
def guess_labels(self, doc):
"""
return a prediction of label names
"""
if doc.nb_pages <= 0:
return set()
self.label_guesser.total_nb_documents = le... |
def _at_extend(self, calculator, rule, scope, block):
"""
Implements @extend
"""
from scss.selector import Selector
selectors = calculator.apply_vars(block.argument)
rule.extends_selectors.extend(Selector.parse_many(selectors)) | Implements @extend | Below is the the instruction that describes the task:
### Input:
Implements @extend
### Response:
def _at_extend(self, calculator, rule, scope, block):
"""
Implements @extend
"""
from scss.selector import Selector
selectors = calculator.apply_vars(block.argument)
rul... |
def wrap(x):
"""
Wraps an element or integer type by serializing it and base64 encoding
the resulting bytes.
"""
# Detect the type so we can call the proper serialization routine
if isinstance(x, G1Element):
return _wrap(x, serializeG1)
elif isinstance(x, G2Element):
return... | Wraps an element or integer type by serializing it and base64 encoding
the resulting bytes. | Below is the the instruction that describes the task:
### Input:
Wraps an element or integer type by serializing it and base64 encoding
the resulting bytes.
### Response:
def wrap(x):
"""
Wraps an element or integer type by serializing it and base64 encoding
the resulting bytes.
"""
# Det... |
def set_event_data(self, data, read_attrs):
""" Set event data with the specied attributes.
:param data: Event data table.
:param read_attrs: Attributes to put on the read group. This must include
the read_number, which must refer to a read present in the object. The
... | Set event data with the specied attributes.
:param data: Event data table.
:param read_attrs: Attributes to put on the read group. This must include
the read_number, which must refer to a read present in the object. The
attributes should not include the standard read att... | Below is the the instruction that describes the task:
### Input:
Set event data with the specied attributes.
:param data: Event data table.
:param read_attrs: Attributes to put on the read group. This must include
the read_number, which must refer to a read present in the object... |
def _construct_w(self, inputs):
"""Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A 4D Tensor of shape:
[batch_size, input_height, input_width, input_channels]
and of type `tf.float16`, `tf.bfloat16` or `tf.float32`.
Returns:
A tuple of two 4D... | Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A 4D Tensor of shape:
[batch_size, input_height, input_width, input_channels]
and of type `tf.float16`, `tf.bfloat16` or `tf.float32`.
Returns:
A tuple of two 4D Tensors, each with the same dtype as `... | Below is the the instruction that describes the task:
### Input:
Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A 4D Tensor of shape:
[batch_size, input_height, input_width, input_channels]
and of type `tf.float16`, `tf.bfloat16` or `tf.float32`.
Re... |
def _parse_geometry(geometry):
""" Parses given geometry into shapely object
:param geometry:
:return: Shapely polygon or multipolygon
:rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon
:raises TypeError
"""
if isinstance(geometry, str):
... | Parses given geometry into shapely object
:param geometry:
:return: Shapely polygon or multipolygon
:rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon
:raises TypeError | Below is the the instruction that describes the task:
### Input:
Parses given geometry into shapely object
:param geometry:
:return: Shapely polygon or multipolygon
:rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon
:raises TypeError
### Response:
def _parse_geometry... |
def _add_arg_python(self, key, value=None, mask=False):
"""Add CLI Arg formatted specifically for Python.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask val... | Add CLI Arg formatted specifically for Python.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value. | Below is the the instruction that describes the task:
### Input:
Add CLI Arg formatted specifically for Python.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask v... |
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
c... | Creates and connects the underlying paging widget. | Below is the the instruction that describes the task:
### Input:
Creates and connects the underlying paging widget.
### Response:
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_co... |
def limit(self, limit_value, key_func=None, per_method=False,
methods=None, error_message=None, exempt_when=None):
"""
decorator to be used for rate limiting individual routes.
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-stri... | decorator to be used for rate limiting individual routes.
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-string` for more details.
:param function key_func: function/lambda to extract the unique identifier for
the rate limit. defaults to rem... | Below is the the instruction that describes the task:
### Input:
decorator to be used for rate limiting individual routes.
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-string` for more details.
:param function key_func: function/lambda to extra... |
def ruamel_structure(data, validator=None):
"""
Take dicts and lists and return a ruamel.yaml style
structure of CommentedMaps, CommentedSeqs and
data.
If a validator is presented and the type is unknown,
it is checked against the validator to see if it will
turn it back in to YAML.
"""... | Take dicts and lists and return a ruamel.yaml style
structure of CommentedMaps, CommentedSeqs and
data.
If a validator is presented and the type is unknown,
it is checked against the validator to see if it will
turn it back in to YAML. | Below is the the instruction that describes the task:
### Input:
Take dicts and lists and return a ruamel.yaml style
structure of CommentedMaps, CommentedSeqs and
data.
If a validator is presented and the type is unknown,
it is checked against the validator to see if it will
turn it back in to ... |
def _copy_selection(self, *event):
"""Copies the current selection to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("copy selection")
global_clipboard.copy(self.model.selection)
return True | Copies the current selection to the clipboard. | Below is the the instruction that describes the task:
### Input:
Copies the current selection to the clipboard.
### Response:
def _copy_selection(self, *event):
"""Copies the current selection to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.de... |
def getquals(args):
"""
%prog getquals [--options] gbkfile > qualsfile
Read GenBank file and extract all qualifiers per feature type
into a tab-delimited file
"""
p = OptionParser(getquals.__doc__)
p.add_option("--types", default="gene,mRNA,CDS",
type="str", dest="quals_ftyp... | %prog getquals [--options] gbkfile > qualsfile
Read GenBank file and extract all qualifiers per feature type
into a tab-delimited file | Below is the the instruction that describes the task:
### Input:
%prog getquals [--options] gbkfile > qualsfile
Read GenBank file and extract all qualifiers per feature type
into a tab-delimited file
### Response:
def getquals(args):
"""
%prog getquals [--options] gbkfile > qualsfile
Read Gen... |
def SetPlatformArchContext():
"""Add the running contexts to the config system."""
# Initialize the running platform context:
_CONFIG.AddContext("Platform:%s" % platform.system().title())
machine = platform.uname()[4]
if machine in ["x86_64", "AMD64", "i686"]:
# 32 bit binaries running on AMD64 will sti... | Add the running contexts to the config system. | Below is the the instruction that describes the task:
### Input:
Add the running contexts to the config system.
### Response:
def SetPlatformArchContext():
"""Add the running contexts to the config system."""
# Initialize the running platform context:
_CONFIG.AddContext("Platform:%s" % platform.system().tit... |
def logBranch(self, indent=0, level=logging.DEBUG):
""" Logs the item and all descendants, one line per child
"""
if 0:
print(indent * " " + str(self))
else:
logger.log(level, indent * " " + str(self))
for childItems in self.childItems:
c... | Logs the item and all descendants, one line per child | Below is the the instruction that describes the task:
### Input:
Logs the item and all descendants, one line per child
### Response:
def logBranch(self, indent=0, level=logging.DEBUG):
""" Logs the item and all descendants, one line per child
"""
if 0:
print(indent * " " + st... |
def rev_comp(seq):
"""Get reverse complement of sequence.
rev_comp will maintain the case of the sequence.
Parameters
----------
seq : str
nucleotide sequence. valid {a, c, t, g, n}
Returns
-------
rev_comp_seq : str
reverse complement of sequence
"""
rev_seq =... | Get reverse complement of sequence.
rev_comp will maintain the case of the sequence.
Parameters
----------
seq : str
nucleotide sequence. valid {a, c, t, g, n}
Returns
-------
rev_comp_seq : str
reverse complement of sequence | Below is the the instruction that describes the task:
### Input:
Get reverse complement of sequence.
rev_comp will maintain the case of the sequence.
Parameters
----------
seq : str
nucleotide sequence. valid {a, c, t, g, n}
Returns
-------
rev_comp_seq : str
reverse c... |
def local_open(url):
"""Read a local path, with special support for directories"""
scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
filename = urllib.request.url2pathname(path)
if os.path.isfile(filename):
return urllib.request.urlopen(url)
elif path.endswith('/') and os... | Read a local path, with special support for directories | Below is the the instruction that describes the task:
### Input:
Read a local path, with special support for directories
### Response:
def local_open(url):
"""Read a local path, with special support for directories"""
scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
filename = urll... |
def cmd_tcpscan(ip, port, iface, flags, sleeptime, timeout, show_all, verbose):
"""TCP Port Scanner.
Print the ports that generated a response with the SYN flag or (if show use -a) all the
ports that generated a response.
It's really basic compared with nmap, but who is comparing?
Example:
\... | TCP Port Scanner.
Print the ports that generated a response with the SYN flag or (if show use -a) all the
ports that generated a response.
It's really basic compared with nmap, but who is comparing?
Example:
\b
# habu.tcpscan -p 22,23,80,443 -s 1 45.77.113.133
22 S -> SA
80 S -> SA
... | Below is the the instruction that describes the task:
### Input:
TCP Port Scanner.
Print the ports that generated a response with the SYN flag or (if show use -a) all the
ports that generated a response.
It's really basic compared with nmap, but who is comparing?
Example:
\b
# habu.tcpsc... |
def options(argv=[]):
"""
A helper function that returns a dictionary of the default key-values pairs
"""
parser = HendrixOptionParser
parsed_args = parser.parse_args(argv)
return vars(parsed_args[0]) | A helper function that returns a dictionary of the default key-values pairs | Below is the the instruction that describes the task:
### Input:
A helper function that returns a dictionary of the default key-values pairs
### Response:
def options(argv=[]):
"""
A helper function that returns a dictionary of the default key-values pairs
"""
parser = HendrixOptionParser
parse... |
def ber_code(self):
"""
This method gets ber code listed in Daft.
:return:
"""
try:
alt_text = self._ad_page_content.find(
'span', {'class': 'ber-hover'}
).find('img')['alt']
if ('exempt' in alt_text):
return 'e... | This method gets ber code listed in Daft.
:return: | Below is the the instruction that describes the task:
### Input:
This method gets ber code listed in Daft.
:return:
### Response:
def ber_code(self):
"""
This method gets ber code listed in Daft.
:return:
"""
try:
alt_text = self._ad_page_content.find(
... |
def is_img_id_valid(img_id):
"""
Checks if img_id is valid.
"""
t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE)
t = re.sub(r'\.+', '.', t)
if img_id != t or img_id.count(':') != 1:
return False
profile, base_name = img_id.split(':', 1)
if not profile or not base_name:
... | Checks if img_id is valid. | Below is the the instruction that describes the task:
### Input:
Checks if img_id is valid.
### Response:
def is_img_id_valid(img_id):
"""
Checks if img_id is valid.
"""
t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE)
t = re.sub(r'\.+', '.', t)
if img_id != t or img_id.count(':') ... |
def mean_by_panel(self, length):
"""
Compute the mean across fixed sized panels of each record.
Splits each record into panels of size `length`,
and then computes the mean across panels.
Panel length must subdivide record exactly.
Parameters
----------
l... | Compute the mean across fixed sized panels of each record.
Splits each record into panels of size `length`,
and then computes the mean across panels.
Panel length must subdivide record exactly.
Parameters
----------
length : int
Fixed length with which to su... | Below is the the instruction that describes the task:
### Input:
Compute the mean across fixed sized panels of each record.
Splits each record into panels of size `length`,
and then computes the mean across panels.
Panel length must subdivide record exactly.
Parameters
----... |
def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | Returns a string for various input types | Below is the the instruction that describes the task:
### Input:
Returns a string for various input types
### Response:
def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(... |
def _parse_wsgi_headers(wsgi_environ):
"""
HTTP headers are presented in WSGI environment with 'HTTP_' prefix.
This method finds those headers, removes the prefix, converts
underscores to dashes, and converts to lower case.
:param wsgi_environ:
:return: returns a diction... | HTTP headers are presented in WSGI environment with 'HTTP_' prefix.
This method finds those headers, removes the prefix, converts
underscores to dashes, and converts to lower case.
:param wsgi_environ:
:return: returns a dictionary of headers | Below is the the instruction that describes the task:
### Input:
HTTP headers are presented in WSGI environment with 'HTTP_' prefix.
This method finds those headers, removes the prefix, converts
underscores to dashes, and converts to lower case.
:param wsgi_environ:
:return: returns... |
def consume_changes(self, start, end):
"""Clear the changed status of lines from start till end"""
left, right = self._get_changed(start, end)
if left < right:
del self.lines[left:right]
return left < right | Clear the changed status of lines from start till end | Below is the the instruction that describes the task:
### Input:
Clear the changed status of lines from start till end
### Response:
def consume_changes(self, start, end):
"""Clear the changed status of lines from start till end"""
left, right = self._get_changed(start, end)
if left < right... |
async def deregister(self, check):
"""Deregisters a local check
Parameters:
check (ObjectID): Check ID
Returns:
bool: ``True`` on success
The agent will take care of deregistering the check from the Catalog.
"""
check_id = extract_attr(check, key... | Deregisters a local check
Parameters:
check (ObjectID): Check ID
Returns:
bool: ``True`` on success
The agent will take care of deregistering the check from the Catalog. | Below is the the instruction that describes the task:
### Input:
Deregisters a local check
Parameters:
check (ObjectID): Check ID
Returns:
bool: ``True`` on success
The agent will take care of deregistering the check from the Catalog.
### Response:
async def deregi... |
def set(ctx, key, value):
""" Set configuration parameters
"""
if key == "default_account" and value[0] == "@":
value = value[1:]
ctx.bitshares.config[key] = value | Set configuration parameters | Below is the the instruction that describes the task:
### Input:
Set configuration parameters
### Response:
def set(ctx, key, value):
""" Set configuration parameters
"""
if key == "default_account" and value[0] == "@":
value = value[1:]
ctx.bitshares.config[key] = value |
def price_change(self):
"""
This method returns any price change.
:return:
"""
try:
if self._data_from_search:
return self._data_from_search.find('div', {'class': 'price-changes-sr'}).text
else:
return self._ad_page_content.... | This method returns any price change.
:return: | Below is the the instruction that describes the task:
### Input:
This method returns any price change.
:return:
### Response:
def price_change(self):
"""
This method returns any price change.
:return:
"""
try:
if self._data_from_search:
re... |
def fromJSON(value):
"""loads the GP object from a JSON string """
j = json.loads(value)
v = GPString()
if "defaultValue" in j:
v.value = j['defaultValue']
else:
v.value = j['value']
if 'paramName' in j:
v.paramName = j['paramName']
... | loads the GP object from a JSON string | Below is the the instruction that describes the task:
### Input:
loads the GP object from a JSON string
### Response:
def fromJSON(value):
"""loads the GP object from a JSON string """
j = json.loads(value)
v = GPString()
if "defaultValue" in j:
v.value = j['defaultValue... |
def delete_image(self, identifier):
"""
::
DELETE /:login/images/:id
:param identifier: match on the listed image identifier
:type identifier: :py:class:`basestring` or :py:class:`dict`
A string or a dictionary containing an ``id`` key may b... | ::
DELETE /:login/images/:id
:param identifier: match on the listed image identifier
:type identifier: :py:class:`basestring` or :py:class:`dict`
A string or a dictionary containing an ``id`` key may be
passed in. Will raise an error if the response... | Below is the the instruction that describes the task:
### Input:
::
DELETE /:login/images/:id
:param identifier: match on the listed image identifier
:type identifier: :py:class:`basestring` or :py:class:`dict`
A string or a dictionary containing an ``i... |
def remove_entry(self, entry):
"""
Remove specified entry.
:param entry: The Entry object to remove.
:type entry: :class:`keepassdb.model.Entry`
"""
if not isinstance(entry, Entry):
raise TypeError("entry param must be of type Entry.")
if not ... | Remove specified entry.
:param entry: The Entry object to remove.
:type entry: :class:`keepassdb.model.Entry` | Below is the the instruction that describes the task:
### Input:
Remove specified entry.
:param entry: The Entry object to remove.
:type entry: :class:`keepassdb.model.Entry`
### Response:
def remove_entry(self, entry):
"""
Remove specified entry.
:param en... |
def addText(self, text):
"""append text in the chosen color"""
# move to the end of the doc
self.moveCursor(QtGui.QTextCursor.End)
# insert the text
self.setTextColor(self._currentColor)
self.textCursor().insertText(text) | append text in the chosen color | Below is the the instruction that describes the task:
### Input:
append text in the chosen color
### Response:
def addText(self, text):
"""append text in the chosen color"""
# move to the end of the doc
self.moveCursor(QtGui.QTextCursor.End)
# insert the text
self.setTextCol... |
def robot_files(self):
'''Return a list of all folders, and test suite files (.txt, .robot)
'''
result = []
for name in os.listdir(self.path):
fullpath = os.path.join(self.path, name)
if os.path.isdir(fullpath):
result.append(RobotFactory(fullpath,... | Return a list of all folders, and test suite files (.txt, .robot) | Below is the the instruction that describes the task:
### Input:
Return a list of all folders, and test suite files (.txt, .robot)
### Response:
def robot_files(self):
'''Return a list of all folders, and test suite files (.txt, .robot)
'''
result = []
for name in os.listdir(self.pa... |
def load_preferences(session, config, valid_paths,
cull_disabled=False, openid=None,
cull_backends=None):
""" Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted h... | Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted here.
If the `openid` argument is None, then this is an expensive query that
loads, practically, the whole database. However, if an openid string i... | Below is the the instruction that describes the task:
### Input:
Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted here.
If the `openid` argument is None, then this is an expensive query that
lo... |
def GetRowHeaders(self) -> list:
"""
Call IUIAutomationTablePattern::GetCurrentRowHeaders.
Return list, a list of `Control` subclasses, representing all the row headers in a table.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiauto... | Call IUIAutomationTablePattern::GetCurrentRowHeaders.
Return list, a list of `Control` subclasses, representing all the row headers in a table.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtablepattern-getcurrentrowheaders | Below is the the instruction that describes the task:
### Input:
Call IUIAutomationTablePattern::GetCurrentRowHeaders.
Return list, a list of `Control` subclasses, representing all the row headers in a table.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomati... |
def get_instance(self, payload):
"""
Build an instance of MonthlyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance
:rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance
... | Build an instance of MonthlyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance
:rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of MonthlyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance
:rtype: twilio.rest.api.v2010.account.usage.record.monthly.M... |
def delete_collection_pod_security_policy(self, **kwargs):
"""
delete collection of PodSecurityPolicy
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_pod_security_policy(a... | delete collection of PodSecurityPolicy
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_pod_security_policy(async_req=True)
>>> result = thread.get()
:param async_req bool... | Below is the the instruction that describes the task:
### Input:
delete collection of PodSecurityPolicy
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_pod_security_policy(async_req=T... |
def contains_entry(self, key, value):
"""
Returns whether the multimap contains an entry with the value.
:param key: (object), the specified key.
:param value: (object), the specified value.
:return: (bool), ``true`` if this multimap contains the key-value tuple.
"""
... | Returns whether the multimap contains an entry with the value.
:param key: (object), the specified key.
:param value: (object), the specified value.
:return: (bool), ``true`` if this multimap contains the key-value tuple. | Below is the the instruction that describes the task:
### Input:
Returns whether the multimap contains an entry with the value.
:param key: (object), the specified key.
:param value: (object), the specified value.
:return: (bool), ``true`` if this multimap contains the key-value tuple.
### ... |
def parse_and_normalize_url_date(date_str):
"""Parse a ISO 8601 date-time with optional timezone.
- Return as datetime with timezone adjusted to UTC.
- Return naive date-time set to UTC.
"""
if date_str is None:
return None
try:
return d1_common.date_time.dt_from_iso8601_str(da... | Parse a ISO 8601 date-time with optional timezone.
- Return as datetime with timezone adjusted to UTC.
- Return naive date-time set to UTC. | Below is the the instruction that describes the task:
### Input:
Parse a ISO 8601 date-time with optional timezone.
- Return as datetime with timezone adjusted to UTC.
- Return naive date-time set to UTC.
### Response:
def parse_and_normalize_url_date(date_str):
"""Parse a ISO 8601 date-time with opti... |
def create_layout(self, size = None):
"""utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout"""
if not self.context:
# TODO - this is rather sloppy as far as exception goes
... | utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout | Below is the the instruction that describes the task:
### Input:
utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout
### Response:
def create_layout(self, size = None):
"""utility function to create ... |
def merge_code(left_code, right_code):
"""
{ relative_line:
((left_abs_line, ((offset, op, args), ...)),
(right_abs_line, ((offset, op, args), ...))),
... }
"""
data = dict()
code_lines = (left_code and left_code.iter_code_by_lines()) or tuple()
for abs_line, rel_line, dis i... | { relative_line:
((left_abs_line, ((offset, op, args), ...)),
(right_abs_line, ((offset, op, args), ...))),
... } | Below is the the instruction that describes the task:
### Input:
{ relative_line:
((left_abs_line, ((offset, op, args), ...)),
(right_abs_line, ((offset, op, args), ...))),
... }
### Response:
def merge_code(left_code, right_code):
"""
{ relative_line:
((left_abs_line, ((offset, op... |
def light_to_gl(light, transform, lightN):
"""
Convert trimesh.scene.lighting.Light objects into
args for gl.glLightFv calls
Parameters
--------------
light : trimesh.scene.lighting.Light
Light object to be converted to GL
transform : (4, 4) float
Transformation matrix of light
... | Convert trimesh.scene.lighting.Light objects into
args for gl.glLightFv calls
Parameters
--------------
light : trimesh.scene.lighting.Light
Light object to be converted to GL
transform : (4, 4) float
Transformation matrix of light
lightN : int
Result of gl.GL_LIGHT0, gl.GL_LI... | Below is the the instruction that describes the task:
### Input:
Convert trimesh.scene.lighting.Light objects into
args for gl.glLightFv calls
Parameters
--------------
light : trimesh.scene.lighting.Light
Light object to be converted to GL
transform : (4, 4) float
Transformation ma... |
async def pause(self, pause: bool = True):
"""
Pauses the current song.
Parameters
----------
pause : bool
Set to ``False`` to resume.
"""
self._paused = pause
await self.node.pause(self.channel.guild.id, pause) | Pauses the current song.
Parameters
----------
pause : bool
Set to ``False`` to resume. | Below is the the instruction that describes the task:
### Input:
Pauses the current song.
Parameters
----------
pause : bool
Set to ``False`` to resume.
### Response:
async def pause(self, pause: bool = True):
"""
Pauses the current song.
Parameters
... |
def _rotate_tr(self):
"""Rotate the transformation matrix based on camera parameters"""
rot, x, y, z = self._quaternion.get_axis_angle()
up, forward, right = self._get_dim_vectors()
self.transform.rotate(180 * rot / np.pi, (x, z, y)) | Rotate the transformation matrix based on camera parameters | Below is the the instruction that describes the task:
### Input:
Rotate the transformation matrix based on camera parameters
### Response:
def _rotate_tr(self):
"""Rotate the transformation matrix based on camera parameters"""
rot, x, y, z = self._quaternion.get_axis_angle()
up, forward, ri... |
def _cbc_decrypt(self, final_key, crypted_content):
"""This method decrypts the database"""
# Just decrypt the content with the created key
aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv)
decrypted_content = aes.decrypt(crypted_content)
padding = decrypted_content[-1]
... | This method decrypts the database | Below is the the instruction that describes the task:
### Input:
This method decrypts the database
### Response:
def _cbc_decrypt(self, final_key, crypted_content):
"""This method decrypts the database"""
# Just decrypt the content with the created key
aes = AES.new(final_key, AES.MODE_CBC... |
def add_sent(self, sent_obj):
''' Add a ttl.Sentence object to this document '''
if sent_obj is None:
raise Exception("Sentence object cannot be None")
elif sent_obj.ID is None:
# if sentID is None, create a new ID
sent_obj.ID = next(self.__idgen)
elif... | Add a ttl.Sentence object to this document | Below is the the instruction that describes the task:
### Input:
Add a ttl.Sentence object to this document
### Response:
def add_sent(self, sent_obj):
''' Add a ttl.Sentence object to this document '''
if sent_obj is None:
raise Exception("Sentence object cannot be None")
elif ... |
def save(self, set_cookie, **params):
"""Update cookies if the session has been changed."""
if set(self.store.items()) ^ set(self.items()):
value = dict(self.items())
value = json.dumps(value)
value = self.encrypt(value)
if not isinstance(value, str):
... | Update cookies if the session has been changed. | Below is the the instruction that describes the task:
### Input:
Update cookies if the session has been changed.
### Response:
def save(self, set_cookie, **params):
"""Update cookies if the session has been changed."""
if set(self.store.items()) ^ set(self.items()):
value = dict(self.it... |
async def teardown_client(self, client_id):
"""Release all resources held by a client.
This method must be called and awaited whenever a client is
disconnected. It ensures that all of the client's resources are
properly released and any devices they have connected to are
discon... | Release all resources held by a client.
This method must be called and awaited whenever a client is
disconnected. It ensures that all of the client's resources are
properly released and any devices they have connected to are
disconnected cleanly.
Args:
client_id (s... | Below is the the instruction that describes the task:
### Input:
Release all resources held by a client.
This method must be called and awaited whenever a client is
disconnected. It ensures that all of the client's resources are
properly released and any devices they have connected to are
... |
def set_data_length(self, length):
# type: (int) -> None
'''
A method to set the length of the data that this UDF File Entry
points to.
Parameters:
length - The new length for the data.
Returns:
Nothing.
'''
if not self._initialized:
... | A method to set the length of the data that this UDF File Entry
points to.
Parameters:
length - The new length for the data.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
A method to set the length of the data that this UDF File Entry
points to.
Parameters:
length - The new length for the data.
Returns:
Nothing.
### Response:
def set_data_length(self, length):
# type:... |
def rsi(self, n, array=False):
"""RSI指标"""
result = talib.RSI(self.close, n)
if array:
return result
return result[-1] | RSI指标 | Below is the the instruction that describes the task:
### Input:
RSI指标
### Response:
def rsi(self, n, array=False):
"""RSI指标"""
result = talib.RSI(self.close, n)
if array:
return result
return result[-1] |
def cidr_notation(ip_address, netmask):
"""
Retrieve the cidr notation given an ip address and netmask.
For example:
cidr_notation('12.34.56.78', '255.255.255.248')
Would return: 12.34.56.72/29
@see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for... | Retrieve the cidr notation given an ip address and netmask.
For example:
cidr_notation('12.34.56.78', '255.255.255.248')
Would return: 12.34.56.72/29
@see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for-a-subne-given-an-ip-and-netmask/
@see http://ww... | Below is the the instruction that describes the task:
### Input:
Retrieve the cidr notation given an ip address and netmask.
For example:
cidr_notation('12.34.56.78', '255.255.255.248')
Would return: 12.34.56.72/29
@see http://terminalmage.net/2012/06/10/how-to-find-out-the-... |
def subscribe_topics(self):
"""subscribe to all registered device and node topics"""
base = self.topic
subscribe = self.mqtt.subscribe
# device topics
subscribe(b"/".join((base, b"$stats/interval/set")))
subscribe(b"/".join((self.settings.MQTT_BASE_TOPIC, b"$broadcast/#"... | subscribe to all registered device and node topics | Below is the the instruction that describes the task:
### Input:
subscribe to all registered device and node topics
### Response:
def subscribe_topics(self):
"""subscribe to all registered device and node topics"""
base = self.topic
subscribe = self.mqtt.subscribe
# device topics
... |
def stop(cls, app_id):
"""
Stops an app by issuing a PUT request to the /apps/ID/stop endpoint.
"""
conn = Qubole.agent()
return conn.put(cls.element_path(app_id) + "/stop") | Stops an app by issuing a PUT request to the /apps/ID/stop endpoint. | Below is the the instruction that describes the task:
### Input:
Stops an app by issuing a PUT request to the /apps/ID/stop endpoint.
### Response:
def stop(cls, app_id):
"""
Stops an app by issuing a PUT request to the /apps/ID/stop endpoint.
"""
conn = Qubole.agent()
retur... |
def playlist_create(
self,
name,
description='',
*,
make_public=False,
songs=None
):
"""Create a playlist.
Parameters:
name (str): Name to give the playlist.
description (str): Description to give the playlist.
make_public (bool, Optional): If ``True`` and account has a subscription,
make... | Create a playlist.
Parameters:
name (str): Name to give the playlist.
description (str): Description to give the playlist.
make_public (bool, Optional): If ``True`` and account has a subscription,
make playlist public.
Default: ``False``
songs (list, Optional): A list of song dicts to add to the ... | Below is the the instruction that describes the task:
### Input:
Create a playlist.
Parameters:
name (str): Name to give the playlist.
description (str): Description to give the playlist.
make_public (bool, Optional): If ``True`` and account has a subscription,
make playlist public.
Default: ``F... |
def loadfn(fn, *args, **kwargs):
"""
Loads json/yaml/msgpack directly from a filename instead of a
File-like object. For YAML, ruamel.yaml must be installed. The file type is
automatically detected. YAML is assumed if the filename contains "yaml"
(lower or upper case). Otherwise, json is always assu... | Loads json/yaml/msgpack directly from a filename instead of a
File-like object. For YAML, ruamel.yaml must be installed. The file type is
automatically detected. YAML is assumed if the filename contains "yaml"
(lower or upper case). Otherwise, json is always assumed.
Args:
fn (str/Path): filena... | Below is the the instruction that describes the task:
### Input:
Loads json/yaml/msgpack directly from a filename instead of a
File-like object. For YAML, ruamel.yaml must be installed. The file type is
automatically detected. YAML is assumed if the filename contains "yaml"
(lower or upper case). Otherw... |
def Update(self, env, args=None):
"""
Update an environment with the option variables.
env - the environment to update.
"""
values = {}
# first set the defaults:
for option in self.options:
if not option.default is None:
values[optio... | Update an environment with the option variables.
env - the environment to update. | Below is the the instruction that describes the task:
### Input:
Update an environment with the option variables.
env - the environment to update.
### Response:
def Update(self, env, args=None):
"""
Update an environment with the option variables.
env - the environment to update.
... |
def Sonnad_Goudar_2006(Re, eD):
r'''Calculates Darcy friction factor using the method in Sonnad and Goudar
(2006) [2]_ as shown in [1]_.
.. math::
\frac{1}{\sqrt{f_d}} = 0.8686\ln\left(\frac{0.4587Re}{S^{S/(S+1)}}\right)
.. math::
S = 0.1240\times\frac{\epsilon}{D}\times Re + \ln(0.458... | r'''Calculates Darcy friction factor using the method in Sonnad and Goudar
(2006) [2]_ as shown in [1]_.
.. math::
\frac{1}{\sqrt{f_d}} = 0.8686\ln\left(\frac{0.4587Re}{S^{S/(S+1)}}\right)
.. math::
S = 0.1240\times\frac{\epsilon}{D}\times Re + \ln(0.4587Re)
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
r'''Calculates Darcy friction factor using the method in Sonnad and Goudar
(2006) [2]_ as shown in [1]_.
.. math::
\frac{1}{\sqrt{f_d}} = 0.8686\ln\left(\frac{0.4587Re}{S^{S/(S+1)}}\right)
.. math::
S = 0.1240\times\frac{... |
def build_image_from_inherited_image(self, image_name: str, image_tag: str,
repo_path: Path,
requirements_option: RequirementsOptions):
"""
Builds a image with installed requirements from the inherited image. (Or just tags... | Builds a image with installed requirements from the inherited image. (Or just tags the image
if there are no requirements.)
See :meth:`build_image` for parameters descriptions.
:rtype: docker.models.images.Image | Below is the the instruction that describes the task:
### Input:
Builds a image with installed requirements from the inherited image. (Or just tags the image
if there are no requirements.)
See :meth:`build_image` for parameters descriptions.
:rtype: docker.models.images.Image
### Response:... |
def save_aggregate_report_to_elasticsearch(aggregate_report,
index_suffix=None,
monthly_indexes=False):
"""
Saves a parsed DMARC aggregate report to ElasticSearch
Args:
aggregate_report (OrderedDict): A parsed for... | Saves a parsed DMARC aggregate report to ElasticSearch
Args:
aggregate_report (OrderedDict): A parsed forensic report
index_suffix (str): The suffix of the name of the index to save to
monthly_indexes (bool): Use monthly indexes instead of daily indexes
Raises:
AlreadySaved | Below is the the instruction that describes the task:
### Input:
Saves a parsed DMARC aggregate report to ElasticSearch
Args:
aggregate_report (OrderedDict): A parsed forensic report
index_suffix (str): The suffix of the name of the index to save to
monthly_indexes (bool): Use monthly i... |
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a bool. If that fails, convert it to ``None``.
"""
for d in dict_list:
# d[key] = True if d[key] == "Y" else False
... | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a bool. If that fails, convert it to ``None``. | Below is the the instruction that describes the task:
### Input:
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a bool. If that fails, convert it to ``None``.
### Response:
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None:
"""
P... |
def _get_new_connection(self, conn_params):
"""Opens a connection to the database."""
self.__connection_string = conn_params.get('connection_string', '')
conn = self.Database.connect(**conn_params)
return conn | Opens a connection to the database. | Below is the the instruction that describes the task:
### Input:
Opens a connection to the database.
### Response:
def _get_new_connection(self, conn_params):
"""Opens a connection to the database."""
self.__connection_string = conn_params.get('connection_string', '')
conn = self.Database.connect(**con... |
def load(self):
""" Loads the user's account details and
Raises
parseException
"""
pg = self.usr.getPage("http://www.neopets.com/bank.phtml")
# Verifies account exists
if not "great to see you again" in pg.content:
logging.getL... | Loads the user's account details and
Raises
parseException | Below is the the instruction that describes the task:
### Input:
Loads the user's account details and
Raises
parseException
### Response:
def load(self):
""" Loads the user's account details and
Raises
parseException
"""
pg = s... |
def get_arctic_version(self, symbol, as_of=None):
"""
Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str`... | Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was a... | Below is the the instruction that describes the task:
### Input:
Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` ... |
def space_cluster(catalog, d_thresh, show=True):
"""
Cluster a catalog by distance only.
Will compute the matrix of physical distances between events and utilize
the :mod:`scipy.clustering.hierarchy` module to perform the clustering.
:type catalog: obspy.core.event.Catalog
:param catalog: Cata... | Cluster a catalog by distance only.
Will compute the matrix of physical distances between events and utilize
the :mod:`scipy.clustering.hierarchy` module to perform the clustering.
:type catalog: obspy.core.event.Catalog
:param catalog: Catalog of events to clustered
:type d_thresh: float
:par... | Below is the the instruction that describes the task:
### Input:
Cluster a catalog by distance only.
Will compute the matrix of physical distances between events and utilize
the :mod:`scipy.clustering.hierarchy` module to perform the clustering.
:type catalog: obspy.core.event.Catalog
:param catal... |
def is_valid_number_for_region(numobj, region_code):
"""Tests whether a phone number is valid for a certain region.
Note this doesn't verify the number is actually in use, which is
impossible to tell by just looking at a number itself. If the country
calling code is not the same as the country calling ... | Tests whether a phone number is valid for a certain region.
Note this doesn't verify the number is actually in use, which is
impossible to tell by just looking at a number itself. If the country
calling code is not the same as the country calling code for the region,
this immediately exits with false. ... | Below is the the instruction that describes the task:
### Input:
Tests whether a phone number is valid for a certain region.
Note this doesn't verify the number is actually in use, which is
impossible to tell by just looking at a number itself. If the country
calling code is not the same as the country... |
def result(self):
"""
Returns a ``string`` constant to indicate whether the team lost in
regulation, lost in overtime, or won.
"""
if self._result.lower() == 'w':
return WIN
if self._result.lower() == 'l' and \
self.overtime != 0:
return... | Returns a ``string`` constant to indicate whether the team lost in
regulation, lost in overtime, or won. | Below is the the instruction that describes the task:
### Input:
Returns a ``string`` constant to indicate whether the team lost in
regulation, lost in overtime, or won.
### Response:
def result(self):
"""
Returns a ``string`` constant to indicate whether the team lost in
regulation... |
def _trunc(x, minval=None, maxval=None):
"""Truncate vector values to have values on range [minval, maxval]
"""
x = np.copy(x)
if minval is not None:
x[x < minval] = minval
if maxval is not None:
x[x > maxval] = maxval
return x | Truncate vector values to have values on range [minval, maxval] | Below is the the instruction that describes the task:
### Input:
Truncate vector values to have values on range [minval, maxval]
### Response:
def _trunc(x, minval=None, maxval=None):
"""Truncate vector values to have values on range [minval, maxval]
"""
x = np.copy(x)
if minval is not None:
... |
def _get_task_with_policy(queue_name, task_id, owner):
"""Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
... | Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
The valid WorkQueue task that is currently owned.
Rai... | Below is the the instruction that describes the task:
### Input:
Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Return... |
def register_entity_to_group(self, entity, group):
'''
Add entity to a group.
If group does not exist, entity will be added as first member
entity is of type Entity
group is a string that is the name of the group
'''
if entity in self._entities:
if gro... | Add entity to a group.
If group does not exist, entity will be added as first member
entity is of type Entity
group is a string that is the name of the group | Below is the the instruction that describes the task:
### Input:
Add entity to a group.
If group does not exist, entity will be added as first member
entity is of type Entity
group is a string that is the name of the group
### Response:
def register_entity_to_group(self, entity, group):
... |
def get_gaf_format(self):
"""Return a GAF 2.0-compatible string representation of the annotation.
Parameters
----------
Returns
-------
str
The formatted string.
"""
sep = '\t'
return sep.join(
[self.gene, self.db_ref, sel... | Return a GAF 2.0-compatible string representation of the annotation.
Parameters
----------
Returns
-------
str
The formatted string. | Below is the the instruction that describes the task:
### Input:
Return a GAF 2.0-compatible string representation of the annotation.
Parameters
----------
Returns
-------
str
The formatted string.
### Response:
def get_gaf_format(self):
"""Return a GAF... |
def _translate_segment_glob(pattern):
"""
Translates the glob pattern to a regular expression. This is used in
the constructor to translate a path segment glob pattern to its
corresponding regular expression.
*pattern* (:class:`str`) is the glob pattern.
Returns the regular expression (:class:`str`).
""... | Translates the glob pattern to a regular expression. This is used in
the constructor to translate a path segment glob pattern to its
corresponding regular expression.
*pattern* (:class:`str`) is the glob pattern.
Returns the regular expression (:class:`str`). | Below is the the instruction that describes the task:
### Input:
Translates the glob pattern to a regular expression. This is used in
the constructor to translate a path segment glob pattern to its
corresponding regular expression.
*pattern* (:class:`str`) is the glob pattern.
Returns the regular expressi... |
def GET_names( self, path_info ):
"""
Get all names in existence
If `all=true` is set, then include expired names.
Returns the list on success
Returns 400 on invalid arguments
Returns 502 on failure to get names
"""
include_expired = False
qs_val... | Get all names in existence
If `all=true` is set, then include expired names.
Returns the list on success
Returns 400 on invalid arguments
Returns 502 on failure to get names | Below is the the instruction that describes the task:
### Input:
Get all names in existence
If `all=true` is set, then include expired names.
Returns the list on success
Returns 400 on invalid arguments
Returns 502 on failure to get names
### Response:
def GET_names( self, path_info... |
def _has_population_germline(rec):
"""Check if header defines population annotated germline samples for tumor only.
"""
for k in population_keys:
if k in rec.header.info:
return True
return False | Check if header defines population annotated germline samples for tumor only. | Below is the the instruction that describes the task:
### Input:
Check if header defines population annotated germline samples for tumor only.
### Response:
def _has_population_germline(rec):
"""Check if header defines population annotated germline samples for tumor only.
"""
for k in population_keys:
... |
def printSegmentForCell(tm, cell):
"""Print segment information for this cell"""
print "Segments for cell", cell, ":"
for seg in tm.basalConnections._cells[cell]._segments:
print " ",
synapses = seg._synapses
for s in synapses:
print "%d:%g" %(s.presynapticCell,s.permanence),
print | Print segment information for this cell | Below is the the instruction that describes the task:
### Input:
Print segment information for this cell
### Response:
def printSegmentForCell(tm, cell):
"""Print segment information for this cell"""
print "Segments for cell", cell, ":"
for seg in tm.basalConnections._cells[cell]._segments:
print " ",... |
def read(self, want=0):
'''
Read method, gets data from internal buffer while releasing
:meth:`write` locks when needed.
The lock usage means it must ran on a different thread than
:meth:`fill`, ie. the main thread, otherwise will deadlock.
The combination of both write... | Read method, gets data from internal buffer while releasing
:meth:`write` locks when needed.
The lock usage means it must ran on a different thread than
:meth:`fill`, ie. the main thread, otherwise will deadlock.
The combination of both write and this method running on different
... | Below is the the instruction that describes the task:
### Input:
Read method, gets data from internal buffer while releasing
:meth:`write` locks when needed.
The lock usage means it must ran on a different thread than
:meth:`fill`, ie. the main thread, otherwise will deadlock.
The ... |
def get_serializer(name):
'''
Return the serialize function.
'''
try:
log.debug('Using %s as serializer', name)
return SERIALIZER_LOOKUP[name]
except KeyError:
msg = 'Serializer {} is not available'.format(name)
log.error(msg, exc_info=True)
raise InvalidSeria... | Return the serialize function. | Below is the the instruction that describes the task:
### Input:
Return the serialize function.
### Response:
def get_serializer(name):
'''
Return the serialize function.
'''
try:
log.debug('Using %s as serializer', name)
return SERIALIZER_LOOKUP[name]
except KeyError:
m... |
def _shrink_file(dicom_file_in, subsample_factor):
"""
Anonimize a single dicomfile
:param dicom_file_in: filepath for input file
:param dicom_file_out: filepath for output file
:param fields_to_keep: dicom tags to keep
"""
# Default meta_fields
# Required fields according to reference
... | Anonimize a single dicomfile
:param dicom_file_in: filepath for input file
:param dicom_file_out: filepath for output file
:param fields_to_keep: dicom tags to keep | Below is the the instruction that describes the task:
### Input:
Anonimize a single dicomfile
:param dicom_file_in: filepath for input file
:param dicom_file_out: filepath for output file
:param fields_to_keep: dicom tags to keep
### Response:
def _shrink_file(dicom_file_in, subsample_factor):
"""
... |
def _build_urlmapping(urls, strict_slashes=False, **kwargs):
"""Convers the anillo urlmappings list into
werkzeug Map instance.
:return: a werkzeug Map instance
:rtype: Map
"""
rules = _build_rules(urls)
return Map(rules=list(rules), strict_slashes=strict_slashes, **kwargs) | Convers the anillo urlmappings list into
werkzeug Map instance.
:return: a werkzeug Map instance
:rtype: Map | Below is the the instruction that describes the task:
### Input:
Convers the anillo urlmappings list into
werkzeug Map instance.
:return: a werkzeug Map instance
:rtype: Map
### Response:
def _build_urlmapping(urls, strict_slashes=False, **kwargs):
"""Convers the anillo urlmappings list into
w... |
def _deserialize_datetime(self, data):
"""Take any values coming in as a datetime and deserialize them
"""
for key in data:
if isinstance(data[key], dict):
if data[key].get('type') == 'datetime':
data[key] = \
datetime.date... | Take any values coming in as a datetime and deserialize them | Below is the the instruction that describes the task:
### Input:
Take any values coming in as a datetime and deserialize them
### Response:
def _deserialize_datetime(self, data):
"""Take any values coming in as a datetime and deserialize them
"""
for key in data:
if isinstance(... |
def login(self, token, use_token=True, mount_point=DEFAULT_MOUNT_POINT):
"""Login using GitHub access token.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param token: GitHub personal API token.
:type token: str | unicode
:para... | Login using GitHub access token.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param token: GitHub personal API token.
:type token: str | unicode
:param use_token: if True, uses the token in the response received from the auth request ... | Below is the the instruction that describes the task:
### Input:
Login using GitHub access token.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param token: GitHub personal API token.
:type token: str | unicode
:param use_token: if... |
def _on_changed(self):
"""Slot for changed events"""
page = self._get_page()
if not page.flag_autosave:
page.flag_changed = True
self._update_gui_text_tabs() | Slot for changed events | Below is the the instruction that describes the task:
### Input:
Slot for changed events
### Response:
def _on_changed(self):
"""Slot for changed events"""
page = self._get_page()
if not page.flag_autosave:
page.flag_changed = True
self._update_gui_text_tabs() |
def date_parser(items):
""" datetime parser to help load smp files
Parameters
----------
items : iterable
something or somethings to try to parse into datetimes
Returns
-------
dt : iterable
the cast datetime things
"""
try:
dt = datetime.strptime(items,"%d/... | datetime parser to help load smp files
Parameters
----------
items : iterable
something or somethings to try to parse into datetimes
Returns
-------
dt : iterable
the cast datetime things | Below is the the instruction that describes the task:
### Input:
datetime parser to help load smp files
Parameters
----------
items : iterable
something or somethings to try to parse into datetimes
Returns
-------
dt : iterable
the cast datetime things
### Response:
def da... |
def _send_content(self, content, connection):
""" Send a content array from the connection """
if connection:
if connection.async:
callback = connection.callbacks['remote']
if callback:
callback(self, self.parent_object, content)
... | Send a content array from the connection | Below is the the instruction that describes the task:
### Input:
Send a content array from the connection
### Response:
def _send_content(self, content, connection):
""" Send a content array from the connection """
if connection:
if connection.async:
callback = connect... |
def p_new_expr(self, p):
"""new_expr : member_expr
| NEW new_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.NewExpr(p[2])
p[0].setpos(p) | new_expr : member_expr
| NEW new_expr | Below is the the instruction that describes the task:
### Input:
new_expr : member_expr
| NEW new_expr
### Response:
def p_new_expr(self, p):
"""new_expr : member_expr
| NEW new_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
... |
def map_nested(function, data_struct, dict_only=False, map_tuple=False):
"""Apply a function recursively to each element of a nested data struct."""
# Could add support for more exotic data_struct, like OrderedDict
if isinstance(data_struct, dict):
return {
k: map_nested(function, v, dict_only, map_t... | Apply a function recursively to each element of a nested data struct. | Below is the the instruction that describes the task:
### Input:
Apply a function recursively to each element of a nested data struct.
### Response:
def map_nested(function, data_struct, dict_only=False, map_tuple=False):
"""Apply a function recursively to each element of a nested data struct."""
# Could add ... |
def setup(self):
"""
Set up the power system object by executing the following workflow:
* Sort the loaded models to meet the initialization sequence
* Create call strings for routines
* Call the ``setup`` function of the loaded models
* Assign addresses for the load... | Set up the power system object by executing the following workflow:
* Sort the loaded models to meet the initialization sequence
* Create call strings for routines
* Call the ``setup`` function of the loaded models
* Assign addresses for the loaded models
* Call ``dae.setup... | Below is the the instruction that describes the task:
### Input:
Set up the power system object by executing the following workflow:
* Sort the loaded models to meet the initialization sequence
* Create call strings for routines
* Call the ``setup`` function of the loaded models
... |
def parse_reports(self):
""" Find RSeQC infer_experiment reports and parse their data """
# Set up vars
self.infer_exp = dict()
regexes = {
'pe_sense': r"\"1\+\+,1--,2\+-,2-\+\": (\d\.\d+)",
'pe_antisense': r"\"1\+-,1-\+,2\+\+,2--\": (\d\.\d+)",
'se_sense': r"\"\+\+,--\": (\d\.\... | Find RSeQC infer_experiment reports and parse their data | Below is the the instruction that describes the task:
### Input:
Find RSeQC infer_experiment reports and parse their data
### Response:
def parse_reports(self):
""" Find RSeQC infer_experiment reports and parse their data """
# Set up vars
self.infer_exp = dict()
regexes = {
'pe_sense': r"... |
def cert_from_instance(instance):
""" Find certificates that are part of an instance
:param instance: An instance
:return: possible empty list of certificates
"""
if instance.signature:
if instance.signature.key_info:
return cert_from_key_info(instance.signature.key_info,
... | Find certificates that are part of an instance
:param instance: An instance
:return: possible empty list of certificates | Below is the the instruction that describes the task:
### Input:
Find certificates that are part of an instance
:param instance: An instance
:return: possible empty list of certificates
### Response:
def cert_from_instance(instance):
""" Find certificates that are part of an instance
:param insta... |
def _decode_image(fobj, session, filename):
"""Reads and decodes an image from a file object as a Numpy array.
The SUN dataset contains images in several formats (despite the fact that
all of them have .jpg extension). Some of them are:
- BMP (RGB)
- PNG (grayscale, RGBA, RGB interlaced)
- JPEG (RGB)... | Reads and decodes an image from a file object as a Numpy array.
The SUN dataset contains images in several formats (despite the fact that
all of them have .jpg extension). Some of them are:
- BMP (RGB)
- PNG (grayscale, RGBA, RGB interlaced)
- JPEG (RGB)
- GIF (1-frame RGB)
Since TFDS assumes tha... | Below is the the instruction that describes the task:
### Input:
Reads and decodes an image from a file object as a Numpy array.
The SUN dataset contains images in several formats (despite the fact that
all of them have .jpg extension). Some of them are:
- BMP (RGB)
- PNG (grayscale, RGBA, RGB interlac... |
def scopes(self):
"""
Gets the Scopes API client.
Returns:
Scopes:
"""
if not self.__scopes:
self.__scopes = Scopes(self.__connection)
return self.__scopes | Gets the Scopes API client.
Returns:
Scopes: | Below is the the instruction that describes the task:
### Input:
Gets the Scopes API client.
Returns:
Scopes:
### Response:
def scopes(self):
"""
Gets the Scopes API client.
Returns:
Scopes:
"""
if not self.__scopes:
self.__scope... |
def add_default_parameter_values(self, sam_template):
"""
Method to read default values for template parameters and merge with user supplied values.
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
... | Method to read default values for template parameters and merge with user supplied values.
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: default_value
Param2:
... | Below is the the instruction that describes the task:
### Input:
Method to read default values for template parameters and merge with user supplied values.
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.