code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def parse_entry(self, row):
"""Parse an individual VCF entry and return a VCFEntry which contains information about
the call (such as alternative allele, zygosity, etc.)
"""
var_call = VCFEntry(self.individuals)
var_call.parse_entry(row)
return var_call | Parse an individual VCF entry and return a VCFEntry which contains information about
the call (such as alternative allele, zygosity, etc.) | Below is the the instruction that describes the task:
### Input:
Parse an individual VCF entry and return a VCFEntry which contains information about
the call (such as alternative allele, zygosity, etc.)
### Response:
def parse_entry(self, row):
"""Parse an individual VCF entry and return a VCFEntr... |
def get_all_handleable_roots(self):
"""
Get list of all handleable devices, return only those that represent
root nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._... | Get list of all handleable devices, return only those that represent
root nodes within the filtered device tree. | Below is the the instruction that describes the task:
### Input:
Get list of all handleable devices, return only those that represent
root nodes within the filtered device tree.
### Response:
def get_all_handleable_roots(self):
"""
Get list of all handleable devices, return only those that ... |
def Transactional(fn, self, *argv, **argd):
"""
Decorator that wraps DAO methods to handle transactions automatically.
It may only work with subclasses of L{BaseDAO}.
"""
return self._transactional(fn, *argv, **argd) | Decorator that wraps DAO methods to handle transactions automatically.
It may only work with subclasses of L{BaseDAO}. | Below is the the instruction that describes the task:
### Input:
Decorator that wraps DAO methods to handle transactions automatically.
It may only work with subclasses of L{BaseDAO}.
### Response:
def Transactional(fn, self, *argv, **argd):
"""
Decorator that wraps DAO methods to handle transactions ... |
def get_env_pass(self,user=None,msg=None,note=None):
"""Gets a password from the user if one is not already recorded for this environment.
@param user: username we are getting password for
@param msg: message to put out there
"""
shutit = self.shutit
shutit.handle_note(note)
user = user or self.wh... | Gets a password from the user if one is not already recorded for this environment.
@param user: username we are getting password for
@param msg: message to put out there | Below is the the instruction that describes the task:
### Input:
Gets a password from the user if one is not already recorded for this environment.
@param user: username we are getting password for
@param msg: message to put out there
### Response:
def get_env_pass(self,user=None,msg=None,note=None):
... |
def from_uncharted_json_file(cls, file):
""" Construct an AnalysisGraph object from a file containing INDRA
statements serialized exported by Uncharted's CauseMos webapp.
"""
with open(file, "r") as f:
_dict = json.load(f)
return cls.from_uncharted_json_serialized_dic... | Construct an AnalysisGraph object from a file containing INDRA
statements serialized exported by Uncharted's CauseMos webapp. | Below is the the instruction that describes the task:
### Input:
Construct an AnalysisGraph object from a file containing INDRA
statements serialized exported by Uncharted's CauseMos webapp.
### Response:
def from_uncharted_json_file(cls, file):
""" Construct an AnalysisGraph object from a file con... |
def resize(self, sizes, interpolation="cubic"):
"""
Resize the segmentation map array to the provided size given the provided interpolation.
Parameters
----------
sizes : float or iterable of int or iterable of float
New size of the array in ``(height, width)``.
... | Resize the segmentation map array to the provided size given the provided interpolation.
Parameters
----------
sizes : float or iterable of int or iterable of float
New size of the array in ``(height, width)``.
See :func:`imgaug.imgaug.imresize_single_image` for details.... | Below is the the instruction that describes the task:
### Input:
Resize the segmentation map array to the provided size given the provided interpolation.
Parameters
----------
sizes : float or iterable of int or iterable of float
New size of the array in ``(height, width)``.
... |
def dump_config(self, file_path):
"""
Dump system and routine configurations to an rc-formatted file.
Parameters
----------
file_path : str
path to the configuration file. The user will be prompted if the
file already exists.
Returns
----... | Dump system and routine configurations to an rc-formatted file.
Parameters
----------
file_path : str
path to the configuration file. The user will be prompted if the
file already exists.
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Dump system and routine configurations to an rc-formatted file.
Parameters
----------
file_path : str
path to the configuration file. The user will be prompted if the
file already exists.
Retur... |
def get_relationship_form(self, *args, **kwargs):
"""Pass through to provider RelationshipAdminSession.get_relationship_form_for_update"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.get_resource_form_for_update
# This method might be a bit sketchy. Tim... | Pass through to provider RelationshipAdminSession.get_relationship_form_for_update | Below is the the instruction that describes the task:
### Input:
Pass through to provider RelationshipAdminSession.get_relationship_form_for_update
### Response:
def get_relationship_form(self, *args, **kwargs):
"""Pass through to provider RelationshipAdminSession.get_relationship_form_for_update"""
... |
def anonymous_required(view, redirect_to=None):
"""
Only allow if user is NOT authenticated.
"""
if redirect_to is None:
redirect_to = settings.LOGIN_REDIRECT_URL
@wraps(view)
def wrapper(request, *a, **k):
if request.user and request.user.is_authenticated():
return ... | Only allow if user is NOT authenticated. | Below is the the instruction that describes the task:
### Input:
Only allow if user is NOT authenticated.
### Response:
def anonymous_required(view, redirect_to=None):
"""
Only allow if user is NOT authenticated.
"""
if redirect_to is None:
redirect_to = settings.LOGIN_REDIRECT_URL
@wr... |
def dict_to_ddb(item):
# type: (Dict[str, Any]) -> Dict[str, Any]
# TODO: narrow these types down
"""Converts a native Python dictionary to a raw DynamoDB item.
:param dict item: Native item
:returns: DynamoDB item
:rtype: dict
"""
serializer = TypeSerializer()
return {key: serializ... | Converts a native Python dictionary to a raw DynamoDB item.
:param dict item: Native item
:returns: DynamoDB item
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Converts a native Python dictionary to a raw DynamoDB item.
:param dict item: Native item
:returns: DynamoDB item
:rtype: dict
### Response:
def dict_to_ddb(item):
# type: (Dict[str, Any]) -> Dict[str, Any]
# TODO: narrow these t... |
def make_root(self, name): # noqa: D302
r"""
Make a sub-node the root node of the tree.
All nodes not belonging to the sub-tree are deleted
:param name: New root node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
... | r"""
Make a sub-node the root node of the tree.
All nodes not belonging to the sub-tree are deleted
:param name: New root node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tre... | Below is the the instruction that describes the task:
### Input:
r"""
Make a sub-node the root node of the tree.
All nodes not belonging to the sub-tree are deleted
:param name: New root node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`na... |
def create_object(self, api, metadata=None):
"""
Create an object using the CDSTAR API, with the file content as bitstream.
:param api:
:return:
"""
metadata = {k: v for k, v in (metadata or {}).items()}
metadata.setdefault('creator', '{0.__name__} {0.__version__... | Create an object using the CDSTAR API, with the file content as bitstream.
:param api:
:return: | Below is the the instruction that describes the task:
### Input:
Create an object using the CDSTAR API, with the file content as bitstream.
:param api:
:return:
### Response:
def create_object(self, api, metadata=None):
"""
Create an object using the CDSTAR API, with the file conte... |
def text_to_bool(value: str) -> bool:
"""
Tries to convert a text value to a bool. If unsuccessful returns if value is None or not
:param value: Value to check
"""
try:
return bool(strtobool(value))
except (ValueError, AttributeError):
return value is not None | Tries to convert a text value to a bool. If unsuccessful returns if value is None or not
:param value: Value to check | Below is the the instruction that describes the task:
### Input:
Tries to convert a text value to a bool. If unsuccessful returns if value is None or not
:param value: Value to check
### Response:
def text_to_bool(value: str) -> bool:
"""
Tries to convert a text value to a bool. If unsuccessful return... |
def S_isothermal_pipe_to_two_planes(D, Z, L=1.):
r'''Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D` which is `Z` distance from two infinite
isothermal planes of equal temperatures, parallel to each other and
enclosing the pipe. Length `L` must be provided,... | r'''Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D` which is `Z` distance from two infinite
isothermal planes of equal temperatures, parallel to each other and
enclosing the pipe. Length `L` must be provided, but can be set to
1 to obtain a dimensionless sh... | Below is the the instruction that describes the task:
### Input:
r'''Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D` which is `Z` distance from two infinite
isothermal planes of equal temperatures, parallel to each other and
enclosing the pipe. Length `L` m... |
def get_window():
"""Get IDA's top level window."""
tform = idaapi.get_current_tform()
# Required sometimes when closing IDBs and not IDA.
if not tform:
tform = idaapi.find_tform("Output window")
widget = form_to_widget(tform)
window = widget.window()
return window | Get IDA's top level window. | Below is the the instruction that describes the task:
### Input:
Get IDA's top level window.
### Response:
def get_window():
"""Get IDA's top level window."""
tform = idaapi.get_current_tform()
# Required sometimes when closing IDBs and not IDA.
if not tform:
tform = idaapi.find_tform("Out... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'key') and self.key is not None:
_dict['key'] = self.key._to_dict()
if hasattr(self, 'value') and self.value is not None:
_dict['value'] = self.value._to_dict()... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'key') and self.key is not None:
_dict['key'] ... |
def union(self, *queries):
'''Return a new :class:`Query` obtained form the union of this
:class:`Query` with one or more *queries*.
For example, lets say we want to have the union
of two queries obtained from the :meth:`filter` method::
query = session.query(MyModel)
qs = query.filter(field1 = ... | Return a new :class:`Query` obtained form the union of this
:class:`Query` with one or more *queries*.
For example, lets say we want to have the union
of two queries obtained from the :meth:`filter` method::
query = session.query(MyModel)
qs = query.filter(field1 = 'bla').union(query.filter(field2 = 'foo... | Below is the the instruction that describes the task:
### Input:
Return a new :class:`Query` obtained form the union of this
:class:`Query` with one or more *queries*.
For example, lets say we want to have the union
of two queries obtained from the :meth:`filter` method::
query = session.query(MyModel)
... |
def __get_chunk_dimensions(self):
""" Sets the chunking dimmentions depending on the file type.
"""
#Usually '.0000.' is in self.filename
if np.abs(self.header[b'foff']) < 1e-5:
logger.info('Detecting high frequency resolution data.')
chunk_dim = (1,1,1048576) #1... | Sets the chunking dimmentions depending on the file type. | Below is the the instruction that describes the task:
### Input:
Sets the chunking dimmentions depending on the file type.
### Response:
def __get_chunk_dimensions(self):
""" Sets the chunking dimmentions depending on the file type.
"""
#Usually '.0000.' is in self.filename
if np.a... |
def sign(self, message):
"""
Generates a signature for the supplied message using NTLM2 Session Security
Note: [MS-NLMP] Section 3.4.4
The message signature for NTLM with extended session security is a 16-byte value that contains the following
components, as described by the NTLM... | Generates a signature for the supplied message using NTLM2 Session Security
Note: [MS-NLMP] Section 3.4.4
The message signature for NTLM with extended session security is a 16-byte value that contains the following
components, as described by the NTLMSSP_MESSAGE_SIGNATURE structure:
- A... | Below is the the instruction that describes the task:
### Input:
Generates a signature for the supplied message using NTLM2 Session Security
Note: [MS-NLMP] Section 3.4.4
The message signature for NTLM with extended session security is a 16-byte value that contains the following
components, ... |
def download(url, file_name):
r = requests.get(url, stream=True)
file_size = int(r.headers['Content-length'])
'''
if py3:
file_size = int(u.getheader("Content-Length")[0])
else:
file_size = int(u.info().getheaders("Content-Length")[0])
'''
file_exists = False
if... | if py3:
file_size = int(u.getheader("Content-Length")[0])
else:
file_size = int(u.info().getheaders("Content-Length")[0]) | Below is the the instruction that describes the task:
### Input:
if py3:
file_size = int(u.getheader("Content-Length")[0])
else:
file_size = int(u.info().getheaders("Content-Length")[0])
### Response:
def download(url, file_name):
r = requests.get(url, stream=True)
file_size = int(... |
def clear(self, color: Tuple[int, int, int]) -> None:
"""Fill this entire Image with color.
Args:
color (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
"""
lib.TCOD_image_clear(self.image_c, color) | Fill this entire Image with color.
Args:
color (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance. | Below is the the instruction that describes the task:
### Input:
Fill this entire Image with color.
Args:
color (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
### Response:
def clear(self, color: Tuple[int, int, int]) -> None:
"""... |
def add_segmented_colorbar(da, colors, direction):
"""
Add 'non-rastered' colorbar to DrawingArea
"""
nbreak = len(colors)
if direction == 'vertical':
linewidth = da.height/nbreak
verts = [None] * nbreak
x1, x2 = 0, da.width
for i, color in enumerate(colors):
... | Add 'non-rastered' colorbar to DrawingArea | Below is the the instruction that describes the task:
### Input:
Add 'non-rastered' colorbar to DrawingArea
### Response:
def add_segmented_colorbar(da, colors, direction):
"""
Add 'non-rastered' colorbar to DrawingArea
"""
nbreak = len(colors)
if direction == 'vertical':
linewidth = da... |
def move_to_collection(self, source_collection, destination_collection):
"""Move entities from source to destination collection."""
for entity in self:
entity.move_to_collection(source_collection, destination_collection) | Move entities from source to destination collection. | Below is the the instruction that describes the task:
### Input:
Move entities from source to destination collection.
### Response:
def move_to_collection(self, source_collection, destination_collection):
"""Move entities from source to destination collection."""
for entity in self:
ent... |
def subject_area(soup):
"""
Find the subject areas from article-categories subject tags
"""
subject_area = []
tags = raw_parser.subject_area(soup)
for tag in tags:
subject_area.append(node_text(tag))
return subject_area | Find the subject areas from article-categories subject tags | Below is the the instruction that describes the task:
### Input:
Find the subject areas from article-categories subject tags
### Response:
def subject_area(soup):
"""
Find the subject areas from article-categories subject tags
"""
subject_area = []
tags = raw_parser.subject_area(soup)
for ... |
def roster(opts, runner=None, utils=None, whitelist=None):
'''
Returns the roster modules
'''
return LazyLoader(
_module_dirs(opts, 'roster'),
opts,
tag='roster',
whitelist=whitelist,
pack={
'__runner__': runner,
'__utils__': utils,
... | Returns the roster modules | Below is the the instruction that describes the task:
### Input:
Returns the roster modules
### Response:
def roster(opts, runner=None, utils=None, whitelist=None):
'''
Returns the roster modules
'''
return LazyLoader(
_module_dirs(opts, 'roster'),
opts,
tag='roster',
... |
def from_json(data):
"""Decode event encoded as JSON by processor"""
parsed_data = json.loads(data)
trigger = TriggerInfo(
parsed_data['trigger']['class'],
parsed_data['trigger']['kind'],
)
# extract content type, needed to decode body
content_ty... | Decode event encoded as JSON by processor | Below is the the instruction that describes the task:
### Input:
Decode event encoded as JSON by processor
### Response:
def from_json(data):
"""Decode event encoded as JSON by processor"""
parsed_data = json.loads(data)
trigger = TriggerInfo(
parsed_data['trigger']['class'],
... |
def build_from_token_counts(self,
token_counts,
min_count,
num_iterations=4,
reserved_tokens=None,
max_subtoken_length=None):
"""Train a SubwordTextEncoder based on a... | Train a SubwordTextEncoder based on a dictionary of word counts.
Args:
token_counts: a dictionary of Unicode strings to int.
min_count: an integer - discard subtokens with lower counts.
num_iterations: an integer. how many iterations of refinement.
reserved_tokens: List of reserved tokens.... | Below is the the instruction that describes the task:
### Input:
Train a SubwordTextEncoder based on a dictionary of word counts.
Args:
token_counts: a dictionary of Unicode strings to int.
min_count: an integer - discard subtokens with lower counts.
num_iterations: an integer. how many iter... |
def add_svc_comment(self, service, author, comment):
"""Add a service comment
Format of the line that triggers function call::
ADD_SVC_COMMENT;<host_name>;<service_description>;<persistent:obsolete>;<author>;<comment>
:param service: service to add the comment
:type service: al... | Add a service comment
Format of the line that triggers function call::
ADD_SVC_COMMENT;<host_name>;<service_description>;<persistent:obsolete>;<author>;<comment>
:param service: service to add the comment
:type service: alignak.objects.service.Service
:param author: author name... | Below is the the instruction that describes the task:
### Input:
Add a service comment
Format of the line that triggers function call::
ADD_SVC_COMMENT;<host_name>;<service_description>;<persistent:obsolete>;<author>;<comment>
:param service: service to add the comment
:type servic... |
def load_posts(self, post_type=None, max_pages=200, status=None):
"""
Load all WordPress posts of a given post_type from a site.
:param post_type: post, page, attachment, or any custom post type set up in the WP API
:param max_pages: kill counter to avoid infinite looping
:param... | Load all WordPress posts of a given post_type from a site.
:param post_type: post, page, attachment, or any custom post type set up in the WP API
:param max_pages: kill counter to avoid infinite looping
:param status: load posts with the given status,
including any of: "publish", "p... | Below is the the instruction that describes the task:
### Input:
Load all WordPress posts of a given post_type from a site.
:param post_type: post, page, attachment, or any custom post type set up in the WP API
:param max_pages: kill counter to avoid infinite looping
:param status: load pos... |
def apply_transforms_to_points( dim, points, transformlist,
whichtoinvert=None, verbose=False ):
"""
Apply a transform list to map a pointset from one domain to
another. In registration, one computes mappings between pairs of
domains. These transforms are often a sequence of incr... | Apply a transform list to map a pointset from one domain to
another. In registration, one computes mappings between pairs of
domains. These transforms are often a sequence of increasingly
complex maps, e.g. from translation, to rigid, to affine to
deformation. The list of such transforms is passed ... | Below is the the instruction that describes the task:
### Input:
Apply a transform list to map a pointset from one domain to
another. In registration, one computes mappings between pairs of
domains. These transforms are often a sequence of increasingly
complex maps, e.g. from translation, to rigid, t... |
def replace_capacities(self, capacities, team_context, iteration_id):
"""ReplaceCapacities.
Replace a team's capacity
:param [TeamMemberCapacity] capacities: Team capacity to replace
:param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team context ... | ReplaceCapacities.
Replace a team's capacity
:param [TeamMemberCapacity] capacities: Team capacity to replace
:param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team context for the operation
:param str iteration_id: ID of the iteration
:r... | Below is the the instruction that describes the task:
### Input:
ReplaceCapacities.
Replace a team's capacity
:param [TeamMemberCapacity] capacities: Team capacity to replace
:param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team context for the oper... |
def remove(self, index=None, hash=None, keepSorted=True):
"""
Removes a particle from the simulation.
Parameters
----------
index : int, optional
Specify particle to remove by index.
hash : c_uint32 or string, optional
Specifiy particle to remove... | Removes a particle from the simulation.
Parameters
----------
index : int, optional
Specify particle to remove by index.
hash : c_uint32 or string, optional
Specifiy particle to remove by hash (if a string is passed, the corresponding hash is calculated).
... | Below is the the instruction that describes the task:
### Input:
Removes a particle from the simulation.
Parameters
----------
index : int, optional
Specify particle to remove by index.
hash : c_uint32 or string, optional
Specifiy particle to remove by hash (... |
def list_files(directory):
'''
Return a list of all files found under directory (and its subdirectories)
'''
ret = set()
ret.add(directory)
for root, dirs, files in safe_walk(directory):
for name in files:
ret.add(os.path.join(root, name))
for name in dirs:
... | Return a list of all files found under directory (and its subdirectories) | Below is the the instruction that describes the task:
### Input:
Return a list of all files found under directory (and its subdirectories)
### Response:
def list_files(directory):
'''
Return a list of all files found under directory (and its subdirectories)
'''
ret = set()
ret.add(directory)
... |
def exception_handler(self, ex): # pylint: disable=no-self-use
""" The default exception handler """
if isinstance(ex, CLIError):
logger.error(ex)
else:
logger.exception(ex)
return 1 | The default exception handler | Below is the the instruction that describes the task:
### Input:
The default exception handler
### Response:
def exception_handler(self, ex): # pylint: disable=no-self-use
""" The default exception handler """
if isinstance(ex, CLIError):
logger.error(ex)
else:
logg... |
def loads(self, schema_txt: str) -> ShExJ.Schema:
""" Parse and return schema as a ShExJ Schema
:param schema_txt: ShExC or ShExJ representation of a ShEx Schema
:return: ShEx Schema representation of schema
"""
self.schema_text = schema_txt
if schema_txt.strip()[0] == '... | Parse and return schema as a ShExJ Schema
:param schema_txt: ShExC or ShExJ representation of a ShEx Schema
:return: ShEx Schema representation of schema | Below is the the instruction that describes the task:
### Input:
Parse and return schema as a ShExJ Schema
:param schema_txt: ShExC or ShExJ representation of a ShEx Schema
:return: ShEx Schema representation of schema
### Response:
def loads(self, schema_txt: str) -> ShExJ.Schema:
""" Par... |
def apply_custom_filter(self, filter_func, to_ngrams=False):
"""
Apply a custom filter function `filter_func` to all tokens or ngrams (if `to_ngrams` is True).
`filter_func` must accept a single parameter: a dictionary of structure `{<doc_label>: <tokens list>}`. It
must return a diction... | Apply a custom filter function `filter_func` to all tokens or ngrams (if `to_ngrams` is True).
`filter_func` must accept a single parameter: a dictionary of structure `{<doc_label>: <tokens list>}`. It
must return a dictionary with the same structure.
This function can only be run on a single p... | Below is the the instruction that describes the task:
### Input:
Apply a custom filter function `filter_func` to all tokens or ngrams (if `to_ngrams` is True).
`filter_func` must accept a single parameter: a dictionary of structure `{<doc_label>: <tokens list>}`. It
must return a dictionary with the... |
def get_property_example(cls, property_, nested=None, **kw):
""" Get example for property
:param dict property_:
:param set nested:
:return: example value
"""
paths = kw.get('paths', [])
name = kw.get('name', '')
result = None
if name and paths:
... | Get example for property
:param dict property_:
:param set nested:
:return: example value | Below is the the instruction that describes the task:
### Input:
Get example for property
:param dict property_:
:param set nested:
:return: example value
### Response:
def get_property_example(cls, property_, nested=None, **kw):
""" Get example for property
:param dict pr... |
def reverse_cipher(message):
"""
反转加密法
:param message: 待加密字符串
:return: 被加密字符串
"""
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
return translated | 反转加密法
:param message: 待加密字符串
:return: 被加密字符串 | Below is the the instruction that describes the task:
### Input:
反转加密法
:param message: 待加密字符串
:return: 被加密字符串
### Response:
def reverse_cipher(message):
"""
反转加密法
:param message: 待加密字符串
:return: 被加密字符串
"""
translated = ''
i = len(message) - 1
while i >= 0:
translate... |
def __put_year_col_first(d):
"""
Always write year column first. Reorder dictionary so that year is first
:param dict d: data
:return dict: Reordered data
"""
if "year" in d:
D = OrderedDict()
# store the year column first
D["year"] = d... | Always write year column first. Reorder dictionary so that year is first
:param dict d: data
:return dict: Reordered data | Below is the the instruction that describes the task:
### Input:
Always write year column first. Reorder dictionary so that year is first
:param dict d: data
:return dict: Reordered data
### Response:
def __put_year_col_first(d):
"""
Always write year column first. Reorder dictionar... |
def _name_messages_complete(self):
"""
Check if all name messages have been received
"""
for channel in range(1, self.number_of_channels() + 1):
try:
for name_index in range(1, 4):
if not isinstance(self._name_data[channel][name_index], str... | Check if all name messages have been received | Below is the the instruction that describes the task:
### Input:
Check if all name messages have been received
### Response:
def _name_messages_complete(self):
"""
Check if all name messages have been received
"""
for channel in range(1, self.number_of_channels() + 1):
t... |
def set_note_footer(data, trigger):
"""
handle the footer of the note
"""
footer = ''
if data.get('link'):
provided_by = _('Provided by')
provided_from = _('from')
footer_from = "<br/><br/>{} <em>{}</em> {} <a href='{}'>{}</a>"
... | handle the footer of the note | Below is the the instruction that describes the task:
### Input:
handle the footer of the note
### Response:
def set_note_footer(data, trigger):
"""
handle the footer of the note
"""
footer = ''
if data.get('link'):
provided_by = _('Provided by')
... |
def poll(self):
"""Start the poll process by invoking the get_stats method of the
consumers. If we hit this after another interval without fully
processing, note it with a warning.
"""
self.set_state(self.STATE_ACTIVE)
# If we don't have any active consumers, spawn new ... | Start the poll process by invoking the get_stats method of the
consumers. If we hit this after another interval without fully
processing, note it with a warning. | Below is the the instruction that describes the task:
### Input:
Start the poll process by invoking the get_stats method of the
consumers. If we hit this after another interval without fully
processing, note it with a warning.
### Response:
def poll(self):
"""Start the poll process by invok... |
def permutations(iterable, r=None):
"""permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)"""
pool = tuple(iterable)
n = len(pool)
if r is None:
r = n
indices = list(range(n))
cycles = list(range(n - r + 1, n + 1))[::-1]
yield tuple(pool[i] for i in indices[:r])
whi... | permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1) | Below is the the instruction that describes the task:
### Input:
permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)
### Response:
def permutations(iterable, r=None):
"""permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)"""
pool = tuple(iterable)
n = len(pool)
if r is N... |
def operator(self):
"""Get a ``LinearOperator`` corresponding to apply().
:return: a LinearOperator that calls apply().
"""
# is projection the zero operator?
if self.V.shape[1] == 0:
N = self.V.shape[0]
return ZeroLinearOperator((N, N))
return se... | Get a ``LinearOperator`` corresponding to apply().
:return: a LinearOperator that calls apply(). | Below is the the instruction that describes the task:
### Input:
Get a ``LinearOperator`` corresponding to apply().
:return: a LinearOperator that calls apply().
### Response:
def operator(self):
"""Get a ``LinearOperator`` corresponding to apply().
:return: a LinearOperator that calls ap... |
def bmpm(
word,
language_arg=0,
name_mode='gen',
match_mode='approx',
concat=False,
filter_langs=False,
):
"""Return the Beider-Morse Phonetic Matching encoding(s) of a term.
This is a wrapper for :py:meth:`BeiderMorse.encode`.
Parameters
----------
word : str
The w... | Return the Beider-Morse Phonetic Matching encoding(s) of a term.
This is a wrapper for :py:meth:`BeiderMorse.encode`.
Parameters
----------
word : str
The word to transform
language_arg : str
The language of the term; supported values include:
- ``any``
- `... | Below is the the instruction that describes the task:
### Input:
Return the Beider-Morse Phonetic Matching encoding(s) of a term.
This is a wrapper for :py:meth:`BeiderMorse.encode`.
Parameters
----------
word : str
The word to transform
language_arg : str
The language of the t... |
def receive_accepted(self, msg):
'''
Called when an Accepted message is received from an acceptor. Once the final value
is determined, the return value of this method will be a Resolution message containing
the consentual value. Subsequent calls after the resolution is chosen will contin... | Called when an Accepted message is received from an acceptor. Once the final value
is determined, the return value of this method will be a Resolution message containing
the consentual value. Subsequent calls after the resolution is chosen will continue to add
new Acceptors to the final_acceptor... | Below is the the instruction that describes the task:
### Input:
Called when an Accepted message is received from an acceptor. Once the final value
is determined, the return value of this method will be a Resolution message containing
the consentual value. Subsequent calls after the resolution is ch... |
def _flush_notifications(self):
"""Flush notifications of engine registrations waiting
in ZMQ queue."""
idents,msg = self.session.recv(self._notification_socket, mode=zmq.NOBLOCK)
while msg is not None:
if self.debug:
pprint(msg)
msg_type = msg['he... | Flush notifications of engine registrations waiting
in ZMQ queue. | Below is the the instruction that describes the task:
### Input:
Flush notifications of engine registrations waiting
in ZMQ queue.
### Response:
def _flush_notifications(self):
"""Flush notifications of engine registrations waiting
in ZMQ queue."""
idents,msg = self.session.recv(sel... |
def failed_hosts(self):
"""Hosts that failed during the execution of the task."""
return {h: r for h, r in self.items() if r.failed} | Hosts that failed during the execution of the task. | Below is the the instruction that describes the task:
### Input:
Hosts that failed during the execution of the task.
### Response:
def failed_hosts(self):
"""Hosts that failed during the execution of the task."""
return {h: r for h, r in self.items() if r.failed} |
def _jdn(self):
"""Return the Julian date number for the given date."""
if self._last_updated == "gdate":
return conv.gdate_to_jdn(self.gdate)
return conv.hdate_to_jdn(self.hdate) | Return the Julian date number for the given date. | Below is the the instruction that describes the task:
### Input:
Return the Julian date number for the given date.
### Response:
def _jdn(self):
"""Return the Julian date number for the given date."""
if self._last_updated == "gdate":
return conv.gdate_to_jdn(self.gdate)
return ... |
def _check_environ(variable, value):
"""check if a variable is present in the environmental variables"""
if is_not_none(value):
return value
else:
value = os.environ.get(variable)
if is_none(value):
stop(''.join([variable,
""" not supplied and no... | check if a variable is present in the environmental variables | Below is the the instruction that describes the task:
### Input:
check if a variable is present in the environmental variables
### Response:
def _check_environ(variable, value):
"""check if a variable is present in the environmental variables"""
if is_not_none(value):
return value
else:
... |
def _ensure_ifaces_tuple(ifaces):
"""Convert to a tuple of interfaces and raise if not interfaces."""
try:
ifaces = tuple(ifaces)
except TypeError:
ifaces = (ifaces,)
for iface in ifaces:
if not _issubclass(iface, ibc.Iface):
raise TypeError('Can only compare ag... | Convert to a tuple of interfaces and raise if not interfaces. | Below is the the instruction that describes the task:
### Input:
Convert to a tuple of interfaces and raise if not interfaces.
### Response:
def _ensure_ifaces_tuple(ifaces):
"""Convert to a tuple of interfaces and raise if not interfaces."""
try:
ifaces = tuple(ifaces)
except TypeError:
... |
def logout(self):
"""
Log currently authenticated user out, invalidating any existing tokens.
"""
# Remove token from local cache
# MAINT: need to expire token on server
data = self._read_uaa_cache()
if self.uri in data:
for client in data[self.uri]:
... | Log currently authenticated user out, invalidating any existing tokens. | Below is the the instruction that describes the task:
### Input:
Log currently authenticated user out, invalidating any existing tokens.
### Response:
def logout(self):
"""
Log currently authenticated user out, invalidating any existing tokens.
"""
# Remove token from local cache
... |
def is_bbox_not_intersecting(self, other):
"""Returns False iif bounding boxed of self and other intersect"""
self_x_min, self_x_max, self_y_min, self_y_max = self.get_bbox()
other_x_min, other_x_max, other_y_min, other_y_max = other.get_bbox()
return \
self_x_min > other_x... | Returns False iif bounding boxed of self and other intersect | Below is the the instruction that describes the task:
### Input:
Returns False iif bounding boxed of self and other intersect
### Response:
def is_bbox_not_intersecting(self, other):
"""Returns False iif bounding boxed of self and other intersect"""
self_x_min, self_x_max, self_y_min, self_y_max =... |
def parse_request(cls, request_string):
"""JSONRPC allows for **batch** requests to be communicated
as array of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns: ... | JSONRPC allows for **batch** requests to be communicated
as array of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns: | tuple of (results, is_batch_mode_flag)
... | Below is the the instruction that describes the task:
### Input:
JSONRPC allows for **batch** requests to be communicated
as array of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
... |
def make_simple():
"""
Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error.
"""
authfile = config.get('coilmq', 'auth.simple.... | Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error. | Below is the the instruction that describes the task:
### Input:
Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error.
### Response:
def ... |
def render(self, request, template, context):
"""
Returns a response. By default, this will contain the rendered PDF, but
if both ``allow_force_html`` is ``True`` and the querystring
``html=true`` was set it will return a plain HTML.
"""
if self.allow_force_html and self.... | Returns a response. By default, this will contain the rendered PDF, but
if both ``allow_force_html`` is ``True`` and the querystring
``html=true`` was set it will return a plain HTML. | Below is the the instruction that describes the task:
### Input:
Returns a response. By default, this will contain the rendered PDF, but
if both ``allow_force_html`` is ``True`` and the querystring
``html=true`` was set it will return a plain HTML.
### Response:
def render(self, request, template, ... |
def open_file(self, fname, external=False):
"""
Open filename with the appropriate application
Redirect to the right widget (txt -> editor, spydata -> workspace, ...)
or open file outside Spyder (if extension is not supported)
"""
fname = to_text_string(fname)
... | Open filename with the appropriate application
Redirect to the right widget (txt -> editor, spydata -> workspace, ...)
or open file outside Spyder (if extension is not supported) | Below is the the instruction that describes the task:
### Input:
Open filename with the appropriate application
Redirect to the right widget (txt -> editor, spydata -> workspace, ...)
or open file outside Spyder (if extension is not supported)
### Response:
def open_file(self, fname, external=Fal... |
def to_json(self):
"""Convert the Design Day to a dictionary."""
return {
'location': self.location.to_json(),
'design_days': [des_d.to_json() for des_d in self.design_days]
} | Convert the Design Day to a dictionary. | Below is the the instruction that describes the task:
### Input:
Convert the Design Day to a dictionary.
### Response:
def to_json(self):
"""Convert the Design Day to a dictionary."""
return {
'location': self.location.to_json(),
'design_days': [des_d.to_json() for des_d in ... |
def board_links_to_ids(self):
""" Convert board links to ids """
resp = self.stats.session.open(
"{0}/members/{1}/boards?{2}".format(
self.stats.url, self.username, urllib.urlencode({
"key": self.key,
"token": self.token,
... | Convert board links to ids | Below is the the instruction that describes the task:
### Input:
Convert board links to ids
### Response:
def board_links_to_ids(self):
""" Convert board links to ids """
resp = self.stats.session.open(
"{0}/members/{1}/boards?{2}".format(
self.stats.url, self.username, ... |
def police_priority_map_exceed_map_pri1_exceed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map, ... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def police_priority_map_exceed_map_pri1_exceed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-ma... |
def add_mag_drift_unit_vectors(inst, max_steps=40000, step_size=10.):
"""Add unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in S/C coordinates.
Interally, routine calls add_mag_drift_unit_vectors_ecef.
See function for inp... | Add unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in S/C coordinates.
Interally, routine calls add_mag_drift_unit_vectors_ecef.
See function for input parameter description.
Requires the orientation of the S/C basis vecto... | Below is the the instruction that describes the task:
### Input:
Add unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in S/C coordinates.
Interally, routine calls add_mag_drift_unit_vectors_ecef.
See function for input param... |
def get_view(self, request, view_class, opts=None):
"""
Instantiates and returns the view class that will generate the
actual context for this plugin.
"""
kwargs = {}
if opts:
if not isinstance(opts, dict):
opts = opts.__dict__
else:
... | Instantiates and returns the view class that will generate the
actual context for this plugin. | Below is the the instruction that describes the task:
### Input:
Instantiates and returns the view class that will generate the
actual context for this plugin.
### Response:
def get_view(self, request, view_class, opts=None):
"""
Instantiates and returns the view class that will generate th... |
def setpassword(self, password):
"""Sets the password to use when extracting.
"""
self._password = password
if self._file_parser:
if self._file_parser.has_header_encryption():
self._file_parser = None
if not self._file_parser:
self._parse()... | Sets the password to use when extracting. | Below is the the instruction that describes the task:
### Input:
Sets the password to use when extracting.
### Response:
def setpassword(self, password):
"""Sets the password to use when extracting.
"""
self._password = password
if self._file_parser:
if self._file_parser... |
def _set_get_nameserver_detail(self, v, load=False):
"""
Setter method for get_nameserver_detail, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_nameserver_detail is considered as a privat... | Setter method for get_nameserver_detail, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_nameserver_detail is considered as a private
method. Backends looking to populate this variable should
... | Below is the the instruction that describes the task:
### Input:
Setter method for get_nameserver_detail, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_nameserver_detail is considered as a pr... |
def integration(temporalcommunities, staticcommunities):
"""
Calculates the integration coefficient for each node. Measures the average probability
that a node is in the same community as nodes from other systems.
Parameters:
------------
temporalcommunities : array
temporal co... | Calculates the integration coefficient for each node. Measures the average probability
that a node is in the same community as nodes from other systems.
Parameters:
------------
temporalcommunities : array
temporal communities vector (node,time)
staticcommunities : array
... | Below is the the instruction that describes the task:
### Input:
Calculates the integration coefficient for each node. Measures the average probability
that a node is in the same community as nodes from other systems.
Parameters:
------------
temporalcommunities : array
temporal co... |
def _set_wait_for_bgp(self, v, load=False):
"""
Setter method for wait_for_bgp, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/router_isis_attributes/set_overload_bit/on_startup/wait_for_bgp (container)
If this variable is read-only (config: false) in the
source YANG file,... | Setter method for wait_for_bgp, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/router_isis_attributes/set_overload_bit/on_startup/wait_for_bgp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_wait_for_bgp is considered as a private
m... | Below is the the instruction that describes the task:
### Input:
Setter method for wait_for_bgp, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/router_isis_attributes/set_overload_bit/on_startup/wait_for_bgp (container)
If this variable is read-only (config: false) in the
sour... |
def verify_false(self, expr, msg=None):
"""
Soft assert for whether the condition is false
:params expr: the statement to evaluate
:params msg: (Optional) msg explaining the difference
"""
try:
self.assert_false(expr, msg)
except AssertionError, e:
... | Soft assert for whether the condition is false
:params expr: the statement to evaluate
:params msg: (Optional) msg explaining the difference | Below is the the instruction that describes the task:
### Input:
Soft assert for whether the condition is false
:params expr: the statement to evaluate
:params msg: (Optional) msg explaining the difference
### Response:
def verify_false(self, expr, msg=None):
"""
Soft assert for wh... |
def serialise(self):
"""Creates standard market book json response,
will error if EX_MARKET_DEF not incl.
"""
return {
'marketId': self.market_id,
'totalAvailable': None,
'isMarketDataDelayed': None,
'lastMatchTime': None,
'betD... | Creates standard market book json response,
will error if EX_MARKET_DEF not incl. | Below is the the instruction that describes the task:
### Input:
Creates standard market book json response,
will error if EX_MARKET_DEF not incl.
### Response:
def serialise(self):
"""Creates standard market book json response,
will error if EX_MARKET_DEF not incl.
"""
retu... |
def k8s_ports_to_metadata_ports(k8s_ports):
"""
:param k8s_ports: list of V1ServicePort
:return: list of str, list of exposed ports, example:
- ['1234/tcp', '8080/udp']
"""
ports = []
for k8s_port in k8s_ports:
if k8s_port.protocol is not None:
ports.append("%s/... | :param k8s_ports: list of V1ServicePort
:return: list of str, list of exposed ports, example:
- ['1234/tcp', '8080/udp'] | Below is the the instruction that describes the task:
### Input:
:param k8s_ports: list of V1ServicePort
:return: list of str, list of exposed ports, example:
- ['1234/tcp', '8080/udp']
### Response:
def k8s_ports_to_metadata_ports(k8s_ports):
"""
:param k8s_ports: list of V1ServicePort
... |
def compare(self,
query_classes: Set,
reference_classes: Set,
method: Optional) -> SimResult:
"""
Given two lists of entites (classes, individual)
return their similarity
"""
raise NotImplementedError | Given two lists of entites (classes, individual)
return their similarity | Below is the the instruction that describes the task:
### Input:
Given two lists of entites (classes, individual)
return their similarity
### Response:
def compare(self,
query_classes: Set,
reference_classes: Set,
method: Optional) -> SimResult:
"""
... |
def _nice_fieldnames(all_columns, index_columns):
"Indexes on the left, other fields in alphabetical order on the right."
non_index_columns = set(all_columns).difference(index_columns)
return index_columns + sorted(non_index_columns) | Indexes on the left, other fields in alphabetical order on the right. | Below is the the instruction that describes the task:
### Input:
Indexes on the left, other fields in alphabetical order on the right.
### Response:
def _nice_fieldnames(all_columns, index_columns):
"Indexes on the left, other fields in alphabetical order on the right."
non_index_columns = set(all_columns)... |
def execstr_funckw(func):
"""
for doctests kwargs
SeeAlso:
ut.exec_func_src
ut.argparse_funckw
"""
import utool as ut
funckw = ut.get_func_kwargs(func)
return ut.execstr_dict(funckw, explicit=True) | for doctests kwargs
SeeAlso:
ut.exec_func_src
ut.argparse_funckw | Below is the the instruction that describes the task:
### Input:
for doctests kwargs
SeeAlso:
ut.exec_func_src
ut.argparse_funckw
### Response:
def execstr_funckw(func):
"""
for doctests kwargs
SeeAlso:
ut.exec_func_src
ut.argparse_funckw
"""
import utool a... |
def parse_dbus_header(header):
"""Parse a D-BUS header. Return the message size."""
if six.indexbytes(header, 0) == ord('l'):
endian = '<'
elif six.indexbytes(header, 0) == ord('B'):
endian = '>'
else:
raise ValueError('illegal endianness')
if not 1 <= six.indexbytes(header, ... | Parse a D-BUS header. Return the message size. | Below is the the instruction that describes the task:
### Input:
Parse a D-BUS header. Return the message size.
### Response:
def parse_dbus_header(header):
"""Parse a D-BUS header. Return the message size."""
if six.indexbytes(header, 0) == ord('l'):
endian = '<'
elif six.indexbytes(header, 0)... |
def from_raw(self, rule_ids, outputs, raw_rules):
"""
A helper function that converts the results returned from C function
:param rule_ids:
:param outputs:
:param raw_rules:
:return:
"""
self._rule_pool = [([], [])] + raw_rules
self._rule_list = []... | A helper function that converts the results returned from C function
:param rule_ids:
:param outputs:
:param raw_rules:
:return: | Below is the the instruction that describes the task:
### Input:
A helper function that converts the results returned from C function
:param rule_ids:
:param outputs:
:param raw_rules:
:return:
### Response:
def from_raw(self, rule_ids, outputs, raw_rules):
"""
A hel... |
def is_ioinfo(obj, keys=None):
"""
:return: True if given 'obj' is a 'IOInfo' namedtuple object.
>>> assert not is_ioinfo(1)
>>> assert not is_ioinfo("aaa")
>>> assert not is_ioinfo({})
>>> assert not is_ioinfo(('a', 1, {}))
>>> inp = anyconfig.globals.IOInfo("/etc/hosts", "path", "/etc/ho... | :return: True if given 'obj' is a 'IOInfo' namedtuple object.
>>> assert not is_ioinfo(1)
>>> assert not is_ioinfo("aaa")
>>> assert not is_ioinfo({})
>>> assert not is_ioinfo(('a', 1, {}))
>>> inp = anyconfig.globals.IOInfo("/etc/hosts", "path", "/etc/hosts",
... ... | Below is the the instruction that describes the task:
### Input:
:return: True if given 'obj' is a 'IOInfo' namedtuple object.
>>> assert not is_ioinfo(1)
>>> assert not is_ioinfo("aaa")
>>> assert not is_ioinfo({})
>>> assert not is_ioinfo(('a', 1, {}))
>>> inp = anyconfig.globals.IOInfo("/et... |
def download(user, dl_type, name):
"""
Download user items of dl_type (ie. all, playlists, liked, commented, etc.)
"""
username = user['username']
user_id = user['id']
logger.info(
'Retrieving all {0} of user {1}...'.format(name, username)
)
dl_url = url[dl_type].format(user_id)
... | Download user items of dl_type (ie. all, playlists, liked, commented, etc.) | Below is the the instruction that describes the task:
### Input:
Download user items of dl_type (ie. all, playlists, liked, commented, etc.)
### Response:
def download(user, dl_type, name):
"""
Download user items of dl_type (ie. all, playlists, liked, commented, etc.)
"""
username = user['username... |
def epub_zip(outdirect):
"""
Zips up the input file directory into an EPUB file.
"""
def recursive_zip(zipf, directory, folder=None):
if folder is None:
folder = ''
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
... | Zips up the input file directory into an EPUB file. | Below is the the instruction that describes the task:
### Input:
Zips up the input file directory into an EPUB file.
### Response:
def epub_zip(outdirect):
"""
Zips up the input file directory into an EPUB file.
"""
def recursive_zip(zipf, directory, folder=None):
if folder is None:
... |
async def start(self, *args, **kwargs):
"""|coro|
A shorthand coroutine for :meth:`login` + :meth:`connect`.
"""
bot = kwargs.pop('bot', True)
reconnect = kwargs.pop('reconnect', True)
await self.login(*args, bot=bot)
await self.connect(reconnect=reconnect) | |coro|
A shorthand coroutine for :meth:`login` + :meth:`connect`. | Below is the the instruction that describes the task:
### Input:
|coro|
A shorthand coroutine for :meth:`login` + :meth:`connect`.
### Response:
async def start(self, *args, **kwargs):
"""|coro|
A shorthand coroutine for :meth:`login` + :meth:`connect`.
"""
bot = kwargs.p... |
def _apply_Create(self, change):
'''A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void
'''
ar = _AzureRecord(self._resource_group, change.new)
create = self._dns_client.record_... | A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void | Below is the the instruction that describes the task:
### Input:
A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void
### Response:
def _apply_Create(self, change):
'''A record from change must be ... |
def modifyBits(inputVal, maxChanges):
""" Modifies up to maxChanges number of bits in the inputVal
"""
changes = np.random.random_integers(0, maxChanges, 1)[0]
if changes == 0:
return inputVal
inputWidth = len(inputVal)
whatToChange = np.random.random_integers(0, 41, changes)
runningIndex = -1
n... | Modifies up to maxChanges number of bits in the inputVal | Below is the the instruction that describes the task:
### Input:
Modifies up to maxChanges number of bits in the inputVal
### Response:
def modifyBits(inputVal, maxChanges):
""" Modifies up to maxChanges number of bits in the inputVal
"""
changes = np.random.random_integers(0, maxChanges, 1)[0]
if changes... |
def include(d, e):
"""Generate a pair of (directory, file-list) for installation.
'd' -- A directory
'e' -- A glob pattern"""
return (d, [f for f in glob.glob('%s/%s' % (d, e)) if os.path.isfile(f)]) | Generate a pair of (directory, file-list) for installation.
'd' -- A directory
'e' -- A glob pattern | Below is the the instruction that describes the task:
### Input:
Generate a pair of (directory, file-list) for installation.
'd' -- A directory
'e' -- A glob pattern
### Response:
def include(d, e):
"""Generate a pair of (directory, file-list) for installation.
'd' -- A directory
'e' -- A glo... |
def mark_for_update(self):
'''
Note that a change has been made so all Statuses need update
'''
self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE)
push_key.delay(self) | Note that a change has been made so all Statuses need update | Below is the the instruction that describes the task:
### Input:
Note that a change has been made so all Statuses need update
### Response:
def mark_for_update(self):
'''
Note that a change has been made so all Statuses need update
'''
self.pub_statuses.exclude(status=UNPUBLISHE... |
def result(self) -> workflow.IntervalGeneratorType:
"""
Generate intervals indicating the valid sentences.
"""
config = cast(SentenceSegementationConfig, self.config)
index = -1
labels = None
while True:
# 1. Find the start of the sentence.
... | Generate intervals indicating the valid sentences. | Below is the the instruction that describes the task:
### Input:
Generate intervals indicating the valid sentences.
### Response:
def result(self) -> workflow.IntervalGeneratorType:
"""
Generate intervals indicating the valid sentences.
"""
config = cast(SentenceSegementationConfig,... |
def find_models(self, constructor, constraints=None, *, columns=None, order_by=None,
limiting=None, table_name=None):
"""Specialization of DataAccess.find_all that returns models instead of cursor objects."""
return self._find_models(
constructor, table_name or constructor.table_name, co... | Specialization of DataAccess.find_all that returns models instead of cursor objects. | Below is the the instruction that describes the task:
### Input:
Specialization of DataAccess.find_all that returns models instead of cursor objects.
### Response:
def find_models(self, constructor, constraints=None, *, columns=None, order_by=None,
limiting=None, table_name=None):
"""Speciali... |
def format_currency(value, decimals=2):
"""
Return a number suitably formatted for display as currency, with
thousands separated by commas and up to two decimal points.
>>> format_currency(1000)
'1,000'
>>> format_currency(100)
'100'
>>> format_currency(999.95)
'999.95'
>>> form... | Return a number suitably formatted for display as currency, with
thousands separated by commas and up to two decimal points.
>>> format_currency(1000)
'1,000'
>>> format_currency(100)
'100'
>>> format_currency(999.95)
'999.95'
>>> format_currency(99.95)
'99.95'
>>> format_curren... | Below is the the instruction that describes the task:
### Input:
Return a number suitably formatted for display as currency, with
thousands separated by commas and up to two decimal points.
>>> format_currency(1000)
'1,000'
>>> format_currency(100)
'100'
>>> format_currency(999.95)
'999... |
def get_distributions(catalog, filter_in=None, filter_out=None,
meta_field=None, exclude_meta_fields=None,
only_time_series=False):
"""Devuelve lista de distribuciones del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representaci... | Devuelve lista de distribuciones del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representación externa/interna de un
catálogo. Una representación _externa_ es un path local o una
URL remota a un archivo con la metadata de un catálogo, en
f... | Below is the the instruction that describes the task:
### Input:
Devuelve lista de distribuciones del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representación externa/interna de un
catálogo. Una representación _externa_ es un path local o una
URL... |
def scaled_fft(fft, scale=1.0):
"""
Produces a nicer graph, I'm not sure if this is correct
"""
data = np.zeros(len(fft))
for i, v in enumerate(fft):
data[i] = scale * (i * v) / NUM_SAMPLES
return data | Produces a nicer graph, I'm not sure if this is correct | Below is the the instruction that describes the task:
### Input:
Produces a nicer graph, I'm not sure if this is correct
### Response:
def scaled_fft(fft, scale=1.0):
"""
Produces a nicer graph, I'm not sure if this is correct
"""
data = np.zeros(len(fft))
for i, v in enumerate(fft):
da... |
def CaffeLMDB(lmdb_path, shuffle=True, keys=None):
"""
Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf.
Produces datapoints of the format: [HWC image, label].
Note that Caffe LMDB format is not efficient: it stores serialized raw
arrays rather than JPEG images.
Args... | Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf.
Produces datapoints of the format: [HWC image, label].
Note that Caffe LMDB format is not efficient: it stores serialized raw
arrays rather than JPEG images.
Args:
lmdb_path, shuffle, keys: same as :class:`LMDBData`.
... | Below is the the instruction that describes the task:
### Input:
Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf.
Produces datapoints of the format: [HWC image, label].
Note that Caffe LMDB format is not efficient: it stores serialized raw
arrays rather than JPEG images.
... |
def write(self, s, size=None):
"""
Writes the content of the specified C{s} into this buffer.
@param s: Raw bytes
"""
self._buffer.write(s)
self._len_changed = True | Writes the content of the specified C{s} into this buffer.
@param s: Raw bytes | Below is the the instruction that describes the task:
### Input:
Writes the content of the specified C{s} into this buffer.
@param s: Raw bytes
### Response:
def write(self, s, size=None):
"""
Writes the content of the specified C{s} into this buffer.
@param s: Raw bytes
"... |
def get_sha(path=None, log=None, short=False, timeout=None):
"""Use `git rev-parse HEAD <REPO>` to get current SHA.
"""
# git_command = "git rev-parse HEAD {}".format(repo_name).split()
# git_command = "git rev-parse HEAD".split()
git_command = ["git", "rev-parse"]
if short:
git_command.... | Use `git rev-parse HEAD <REPO>` to get current SHA. | Below is the the instruction that describes the task:
### Input:
Use `git rev-parse HEAD <REPO>` to get current SHA.
### Response:
def get_sha(path=None, log=None, short=False, timeout=None):
"""Use `git rev-parse HEAD <REPO>` to get current SHA.
"""
# git_command = "git rev-parse HEAD {}".format(repo_... |
def from_config(cls, cp, section, outputs, skip_opts=None,
additional_opts=None):
"""Initializes a transform from the given section.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration file that contains the transform opt... | Initializes a transform from the given section.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration file that contains the transform options.
section : str
Name of the section in the configuration file.
outputs : str
... | Below is the the instruction that describes the task:
### Input:
Initializes a transform from the given section.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration file that contains the transform options.
section : str
Name... |
def visit_field(self, _, children):
"""A simple field.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: for ``FILTERS``: list of instances of ``.resources.Field``.
Returns
-------
.resources.Field
An in... | A simple field.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: for ``FILTERS``: list of instances of ``.resources.Field``.
Returns
-------
.resources.Field
An instance of ``.resources.Field`` with the correct... | Below is the the instruction that describes the task:
### Input:
A simple field.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: for ``FILTERS``: list of instances of ``.resources.Field``.
Returns
-------
.resources.F... |
def average_over_area(q, x, y):
"""Averages a quantity `q` over a rectangular area given a 2D array and
the x and y vectors for sample locations, using the trapezoidal rule"""
area = (np.max(x) - np.min(x))*(np.max(y) - np.min(y))
integral = np.trapz(np.trapz(q, y, axis=0), x)
return integral/a... | Averages a quantity `q` over a rectangular area given a 2D array and
the x and y vectors for sample locations, using the trapezoidal rule | Below is the the instruction that describes the task:
### Input:
Averages a quantity `q` over a rectangular area given a 2D array and
the x and y vectors for sample locations, using the trapezoidal rule
### Response:
def average_over_area(q, x, y):
"""Averages a quantity `q` over a rectangular area given... |
def queryString_required(strList):
""" An decorator checking whether queryString key is valid or not
Args:
str: allowed queryString key
Returns:
if contains invalid queryString key, it will raise exception.
"""
def _dec(function):
@wraps(function)
def _wrap(request, *args, **kwargs):
for i in strList:
... | An decorator checking whether queryString key is valid or not
Args:
str: allowed queryString key
Returns:
if contains invalid queryString key, it will raise exception. | Below is the the instruction that describes the task:
### Input:
An decorator checking whether queryString key is valid or not
Args:
str: allowed queryString key
Returns:
if contains invalid queryString key, it will raise exception.
### Response:
def queryString_required(strList):
""" An decorator checking... |
def _normalize(obj):
"""
Normalize dicts and lists
:param obj:
:return: normalized object
"""
if isinstance(obj, list):
return [_normalize(item) for item in obj]
elif isinstance(obj, dict):
return {k: _normalize(v) for k, v in obj.items() if v is not None}
elif hasattr(o... | Normalize dicts and lists
:param obj:
:return: normalized object | Below is the the instruction that describes the task:
### Input:
Normalize dicts and lists
:param obj:
:return: normalized object
### Response:
def _normalize(obj):
"""
Normalize dicts and lists
:param obj:
:return: normalized object
"""
if isinstance(obj, list):
return [_... |
def generate(cls, partial_props=None):
"""
Generate new connection file props from
defaults
"""
partial_props = partial_props or {}
props = partial_props.copy()
props.update(cls.DEFAULT_PROPERTIES)
return cls(props) | Generate new connection file props from
defaults | Below is the the instruction that describes the task:
### Input:
Generate new connection file props from
defaults
### Response:
def generate(cls, partial_props=None):
"""
Generate new connection file props from
defaults
"""
partial_props = partial_props or {}
... |
def compute_key_composite(password=None, keyfile=None):
"""Compute composite key.
Used in header verification and payload decryption."""
# hash the password
if password:
password_composite = hashlib.sha256(password.encode('utf-8')).digest()
else:
password_composite = b''
# hash ... | Compute composite key.
Used in header verification and payload decryption. | Below is the the instruction that describes the task:
### Input:
Compute composite key.
Used in header verification and payload decryption.
### Response:
def compute_key_composite(password=None, keyfile=None):
"""Compute composite key.
Used in header verification and payload decryption."""
# hash ... |
def attach_attrs_table(key, value, fmt, meta):
"""Extracts attributes and attaches them to element."""
# We can't use attach_attrs_factory() because Table is a block-level element
if key in ['Table']:
assert len(value) == 5
caption = value[0] # caption, align, x, head, body
# Set ... | Extracts attributes and attaches them to element. | Below is the the instruction that describes the task:
### Input:
Extracts attributes and attaches them to element.
### Response:
def attach_attrs_table(key, value, fmt, meta):
"""Extracts attributes and attaches them to element."""
# We can't use attach_attrs_factory() because Table is a block-level eleme... |
def fetch():
"""
Fetches the latest exchange rate info from the European Central Bank. These
rates need to be used for displaying invoices since some countries require
local currency be quoted. Also useful to store the GBP rate of the VAT
collected at time of purchase to prevent fluctuations in exch... | Fetches the latest exchange rate info from the European Central Bank. These
rates need to be used for displaying invoices since some countries require
local currency be quoted. Also useful to store the GBP rate of the VAT
collected at time of purchase to prevent fluctuations in exchange rates from
signi... | Below is the the instruction that describes the task:
### Input:
Fetches the latest exchange rate info from the European Central Bank. These
rates need to be used for displaying invoices since some countries require
local currency be quoted. Also useful to store the GBP rate of the VAT
collected at time... |
def delete_pb_devices():
"""Delete PBs devices from the Tango database."""
parser = argparse.ArgumentParser(description='Register PB devices.')
parser.add_argument('num_pb', type=int,
help='Number of PBs devices to register.')
args = parser.parse_args()
log = logging.getLogg... | Delete PBs devices from the Tango database. | Below is the the instruction that describes the task:
### Input:
Delete PBs devices from the Tango database.
### Response:
def delete_pb_devices():
"""Delete PBs devices from the Tango database."""
parser = argparse.ArgumentParser(description='Register PB devices.')
parser.add_argument('num_pb', type=i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.