code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
slug_separator='-'):
"""
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check aga... | Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check against for uniqueness).
``queryset`` usually doesn't need to be explicitly provided - it'll default
to using the ``.all(... | Below is the the instruction that describes the task:
### Input:
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check against for uniqueness).
``queryset`` usually doesn't ne... |
def run(self):
"""Runs the command.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None``
"""
for build_dir in self.build_dirs:
if os.path.isdir(build_dir):
sys.stdout.write('Removing %s%s' % (build_dir, os.li... | Runs the command.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None`` | Below is the the instruction that describes the task:
### Input:
Runs the command.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None``
### Response:
def run(self):
"""Runs the command.
Args:
self (CleanCommand): the ``CleanComm... |
def complete(text, state):
""" Auto complete scss constructions in interactive mode. """
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1 | Auto complete scss constructions in interactive mode. | Below is the the instruction that describes the task:
### Input:
Auto complete scss constructions in interactive mode.
### Response:
def complete(text, state):
""" Auto complete scss constructions in interactive mode. """
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
... |
def clearConnections( self, cls ):
"""
Clears all the connections for this node.
:param cls | <subclass of XNodeConnection> || None
:return <int> | number of connections removed
"""
count = 0
for connection in self.connections(cls):
... | Clears all the connections for this node.
:param cls | <subclass of XNodeConnection> || None
:return <int> | number of connections removed | Below is the the instruction that describes the task:
### Input:
Clears all the connections for this node.
:param cls | <subclass of XNodeConnection> || None
:return <int> | number of connections removed
### Response:
def clearConnections( self, cls ):
"""
... |
def get_objective_bank_ids_by_activity(self, activity_id):
"""Gets the list of ``ObjectiveBank Ids`` mapped to a ``Activity``.
arg: activity_id (osid.id.Id): ``Id`` of a ``Activity``
return: (osid.id.IdList) - list of objective bank ``Ids``
raise: NotFound - ``activity_id`` is not f... | Gets the list of ``ObjectiveBank Ids`` mapped to a ``Activity``.
arg: activity_id (osid.id.Id): ``Id`` of a ``Activity``
return: (osid.id.IdList) - list of objective bank ``Ids``
raise: NotFound - ``activity_id`` is not found
raise: NullArgument - ``activity_id`` is ``null``
... | Below is the the instruction that describes the task:
### Input:
Gets the list of ``ObjectiveBank Ids`` mapped to a ``Activity``.
arg: activity_id (osid.id.Id): ``Id`` of a ``Activity``
return: (osid.id.IdList) - list of objective bank ``Ids``
raise: NotFound - ``activity_id`` is not fo... |
def segment_shakespeare_works(input_file=PATH_SHAKESPEARE, verbose=False):
"""Find start and end of each volume within _Complete Works of William Shakespeare_
"""
works = [{}]
meta = {}
j = 0
for i, line in enumerate(generate_lines(input_file=input_file)):
if 'title' not in meta:
... | Find start and end of each volume within _Complete Works of William Shakespeare_ | Below is the the instruction that describes the task:
### Input:
Find start and end of each volume within _Complete Works of William Shakespeare_
### Response:
def segment_shakespeare_works(input_file=PATH_SHAKESPEARE, verbose=False):
"""Find start and end of each volume within _Complete Works of William Shake... |
def compute_partition_size(result, processes):
"""
Attempts to compute the partition size to evenly distribute work across processes. Defaults to
1 if the length of result cannot be determined.
:param result: Result to compute on
:param processes: Number of processes to use
:return: Best partit... | Attempts to compute the partition size to evenly distribute work across processes. Defaults to
1 if the length of result cannot be determined.
:param result: Result to compute on
:param processes: Number of processes to use
:return: Best partition size | Below is the the instruction that describes the task:
### Input:
Attempts to compute the partition size to evenly distribute work across processes. Defaults to
1 if the length of result cannot be determined.
:param result: Result to compute on
:param processes: Number of processes to use
:return: B... |
def match_msequence(self, tokens, item):
"""Matches a middle sequence."""
series_type, head_matches, middle, _, last_matches = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")
self.add_check("_coconut.len(" + item + ") >= " + str(len(head_matches) + len(l... | Matches a middle sequence. | Below is the the instruction that describes the task:
### Input:
Matches a middle sequence.
### Response:
def match_msequence(self, tokens, item):
"""Matches a middle sequence."""
series_type, head_matches, middle, _, last_matches = tokens
self.add_check("_coconut.isinstance(" + item + ", _... |
def close(self):
"""
Close all endpoint file descriptors.
"""
ep_list = self._ep_list
while ep_list:
ep_list.pop().close()
self._closed = True | Close all endpoint file descriptors. | Below is the the instruction that describes the task:
### Input:
Close all endpoint file descriptors.
### Response:
def close(self):
"""
Close all endpoint file descriptors.
"""
ep_list = self._ep_list
while ep_list:
ep_list.pop().close()
self._closed = T... |
def amount_converter(obj):
"""Converts amount value from several types into Decimal."""
if isinstance(obj, Decimal):
return obj
elif isinstance(obj, (str, int, float)):
return Decimal(str(obj))
else:
raise ValueError('do not know how to convert: {}'.format(type(obj))) | Converts amount value from several types into Decimal. | Below is the the instruction that describes the task:
### Input:
Converts amount value from several types into Decimal.
### Response:
def amount_converter(obj):
"""Converts amount value from several types into Decimal."""
if isinstance(obj, Decimal):
return obj
elif isinstance(obj, (str, int, f... |
def install_host(trg_queue, *hosts, **kwargs):
''' Atomically install host queues '''
user = kwargs.pop('user', None)
group = kwargs.pop('group', None)
mode = kwargs.pop('mode', None)
item_user = kwargs.pop('item_user', None)
item_group = kwargs.pop('item_group', None)
item_mode = kwargs.pop... | Atomically install host queues | Below is the the instruction that describes the task:
### Input:
Atomically install host queues
### Response:
def install_host(trg_queue, *hosts, **kwargs):
''' Atomically install host queues '''
user = kwargs.pop('user', None)
group = kwargs.pop('group', None)
mode = kwargs.pop('mode', None)
i... |
def get_week_start_end_day():
"""
Get the week start date and end date
"""
t = date.today()
wd = t.weekday()
return (t - timedelta(wd), t + timedelta(6 - wd)) | Get the week start date and end date | Below is the the instruction that describes the task:
### Input:
Get the week start date and end date
### Response:
def get_week_start_end_day():
"""
Get the week start date and end date
"""
t = date.today()
wd = t.weekday()
return (t - timedelta(wd), t + timedelta(6 - wd)) |
def sp_search_query(query):
"""Translate a Mopidy search query to a Spotify search query"""
result = []
for (field, values) in query.items():
field = SEARCH_FIELD_MAP.get(field, field)
if field is None:
continue
for value in values:
if field == 'year':
... | Translate a Mopidy search query to a Spotify search query | Below is the the instruction that describes the task:
### Input:
Translate a Mopidy search query to a Spotify search query
### Response:
def sp_search_query(query):
"""Translate a Mopidy search query to a Spotify search query"""
result = []
for (field, values) in query.items():
field = SEARCH... |
def parseGopkgImportPath(self, path):
"""
Definition: gopkg.in/<v>/<repo> || gopkg.in/<repo>.<v> || gopkg.in/<project>/<repo>
"""
parts = path.split('/')
if re.match('v[0-9]+', parts[1]):
if len(parts) < 3:
raise ValueError("Import path %s is not in gopkg.in/<v>/<repo> form" % path)
project = ""
... | Definition: gopkg.in/<v>/<repo> || gopkg.in/<repo>.<v> || gopkg.in/<project>/<repo> | Below is the the instruction that describes the task:
### Input:
Definition: gopkg.in/<v>/<repo> || gopkg.in/<repo>.<v> || gopkg.in/<project>/<repo>
### Response:
def parseGopkgImportPath(self, path):
"""
Definition: gopkg.in/<v>/<repo> || gopkg.in/<repo>.<v> || gopkg.in/<project>/<repo>
"""
parts = path.s... |
def request(self, method, url, erc, **kwargs):
"""Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support for Webex Te... | Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support for Webex Teams rate-limiting
* Inspects response codes an... | Below is the the instruction that describes the task:
### Input:
Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support f... |
def notify(self, correlation_id, event, value):
"""
Fires event specified by its name and notifies all registered
IEventListener listeners
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param event: the name of the event that is to be f... | Fires event specified by its name and notifies all registered
IEventListener listeners
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param event: the name of the event that is to be fired.
:param value: the event arguments (parameters). | Below is the the instruction that describes the task:
### Input:
Fires event specified by its name and notifies all registered
IEventListener listeners
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param event: the name of the event that is to be ... |
def runGetRequest(self, obj):
"""
Runs a get request by converting the specified datamodel
object into its protocol representation.
"""
protocolElement = obj.toProtocolElement()
jsonString = protocol.toJson(protocolElement)
return jsonString | Runs a get request by converting the specified datamodel
object into its protocol representation. | Below is the the instruction that describes the task:
### Input:
Runs a get request by converting the specified datamodel
object into its protocol representation.
### Response:
def runGetRequest(self, obj):
"""
Runs a get request by converting the specified datamodel
object into its... |
def main(host='localhost', port=8086):
"""Instantiate the connection to the InfluxDB client."""
user = 'root'
password = 'root'
dbname = 'demo'
protocol = 'json'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(ra... | Instantiate the connection to the InfluxDB client. | Below is the the instruction that describes the task:
### Input:
Instantiate the connection to the InfluxDB client.
### Response:
def main(host='localhost', port=8086):
"""Instantiate the connection to the InfluxDB client."""
user = 'root'
password = 'root'
dbname = 'demo'
protocol = 'json'
... |
def parse_classi_or_classii_allele_name(name, infer_pair=True):
"""
Handle different forms of both single and alpha-beta allele names.
Alpha-beta alleles may look like:
DPA10105-DPB110001
HLA-DPA1*01:05-DPB1*100:01
hla-dpa1*0105-dpb1*10001
dpa1*0105-dpb1*10001
HLA-DPA1*01:05/DPB1*100:01... | Handle different forms of both single and alpha-beta allele names.
Alpha-beta alleles may look like:
DPA10105-DPB110001
HLA-DPA1*01:05-DPB1*100:01
hla-dpa1*0105-dpb1*10001
dpa1*0105-dpb1*10001
HLA-DPA1*01:05/DPB1*100:01
Other class II alleles may look like:
DRB1_0102
DRB101:02
... | Below is the the instruction that describes the task:
### Input:
Handle different forms of both single and alpha-beta allele names.
Alpha-beta alleles may look like:
DPA10105-DPB110001
HLA-DPA1*01:05-DPB1*100:01
hla-dpa1*0105-dpb1*10001
dpa1*0105-dpb1*10001
HLA-DPA1*01:05/DPB1*100:01
O... |
def calculate_feature_vectorizer_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C_1], ..., [N, C_n] ---> [N, C_1 + ... + C_n]
Feature vectorizer concatenates all input tensors along the C-axis, so the output dimension along C-axis is simply
a sum of all input features.
... | Allowed input/output patterns are
1. [N, C_1], ..., [N, C_n] ---> [N, C_1 + ... + C_n]
Feature vectorizer concatenates all input tensors along the C-axis, so the output dimension along C-axis is simply
a sum of all input features. | Below is the the instruction that describes the task:
### Input:
Allowed input/output patterns are
1. [N, C_1], ..., [N, C_n] ---> [N, C_1 + ... + C_n]
Feature vectorizer concatenates all input tensors along the C-axis, so the output dimension along C-axis is simply
a sum of all input features.
###... |
def make_connection(self):
"Create a new connection"
if self._created_connections >= self.max_connections:
raise ConnectionError("Too many connections")
self._created_connections += 1
return self.connection_class(**self.connection_kwargs) | Create a new connection | Below is the the instruction that describes the task:
### Input:
Create a new connection
### Response:
def make_connection(self):
"Create a new connection"
if self._created_connections >= self.max_connections:
raise ConnectionError("Too many connections")
self._created_connectio... |
def genre(self):
""" Cette routine convertit les indications morphologiques, données dans le fichier lemmes.la, pour exprimer le genre du mot dans la langue courante.
:return: Genre
:rtype: str
"""
_genre = ""
if " m." in self._indMorph:
_genre += "m"
... | Cette routine convertit les indications morphologiques, données dans le fichier lemmes.la, pour exprimer le genre du mot dans la langue courante.
:return: Genre
:rtype: str | Below is the the instruction that describes the task:
### Input:
Cette routine convertit les indications morphologiques, données dans le fichier lemmes.la, pour exprimer le genre du mot dans la langue courante.
:return: Genre
:rtype: str
### Response:
def genre(self):
""" Cette routine con... |
def write_vasp_input(self, vasp_input_set=MPRelaxSet, output_dir=".",
create_directory=True, **kwargs):
"""
Writes VASP input to an output_dir.
Args:
vasp_input_set:
pymatgen.io.vaspio_set.VaspInputSet like object that creates
... | Writes VASP input to an output_dir.
Args:
vasp_input_set:
pymatgen.io.vaspio_set.VaspInputSet like object that creates
vasp input files from structures
output_dir: Directory to output files
create_directory: Create the directory if not present... | Below is the the instruction that describes the task:
### Input:
Writes VASP input to an output_dir.
Args:
vasp_input_set:
pymatgen.io.vaspio_set.VaspInputSet like object that creates
vasp input files from structures
output_dir: Directory to output fi... |
def set_led(self, red=0, green=0, blue=0):
"""Sets the LED color. Values are RGB between 0-255."""
self._led = (red, green, blue)
self._control() | Sets the LED color. Values are RGB between 0-255. | Below is the the instruction that describes the task:
### Input:
Sets the LED color. Values are RGB between 0-255.
### Response:
def set_led(self, red=0, green=0, blue=0):
"""Sets the LED color. Values are RGB between 0-255."""
self._led = (red, green, blue)
self._control() |
def variables(self, value):
"""
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("variables", value)
... | Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict | Below is the the instruction that describes the task:
### Input:
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
### Response:
def variables(self, value):
"""
Setter for **self.__variables** attribute.
:param value: Attribute val... |
def probe_wdl(self, board: chess.Board) -> int:
"""
Probes for win/draw/loss-information.
Returns ``1`` if the side to move is winning, ``0`` if it is a draw,
and ``-1`` if the side to move is losing.
>>> import chess
>>> import chess.gaviota
>>>
>>> wit... | Probes for win/draw/loss-information.
Returns ``1`` if the side to move is winning, ``0`` if it is a draw,
and ``-1`` if the side to move is losing.
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... | Below is the the instruction that describes the task:
### Input:
Probes for win/draw/loss-information.
Returns ``1`` if the side to move is winning, ``0`` if it is a draw,
and ``-1`` if the side to move is losing.
>>> import chess
>>> import chess.gaviota
>>>
>>> wi... |
def get_data(self, as_text=False):
"""The string representation of the request body. Whenever you call
this property the request iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
:attr:`implic... | The string representation of the request body. Whenever you call
this property the request iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
:attr:`implicit_sequence_conversion` to `False`.
I... | Below is the the instruction that describes the task:
### Input:
The string representation of the request body. Whenever you call
this property the request iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by settin... |
async def eval(self, text, opts=None, user=None):
'''
Evaluate a storm query and yield Nodes only.
'''
if user is None:
user = self.auth.getUserByName('root')
await self.boss.promote('storm', user=user, info={'query': text})
async with await self.snap(user=us... | Evaluate a storm query and yield Nodes only. | Below is the the instruction that describes the task:
### Input:
Evaluate a storm query and yield Nodes only.
### Response:
async def eval(self, text, opts=None, user=None):
'''
Evaluate a storm query and yield Nodes only.
'''
if user is None:
user = self.auth.getUserByN... |
def load(self):
"""
Extract tabular data as |TableData| instances from an Excel file.
|spreadsheet_load_desc|
:return:
Loaded |TableData| iterator.
|TableData| created for each sheet in the workbook.
|load_table_name_desc|
===============... | Extract tabular data as |TableData| instances from an Excel file.
|spreadsheet_load_desc|
:return:
Loaded |TableData| iterator.
|TableData| created for each sheet in the workbook.
|load_table_name_desc|
=================== ==============================... | Below is the the instruction that describes the task:
### Input:
Extract tabular data as |TableData| instances from an Excel file.
|spreadsheet_load_desc|
:return:
Loaded |TableData| iterator.
|TableData| created for each sheet in the workbook.
|load_table_name_d... |
def add_function(self, func):
""" Record line profiling information for the given Python function.
"""
try:
# func_code does not exist in Python3
code = func.__code__
except AttributeError:
import warnings
warnings.warn("Could not extract a... | Record line profiling information for the given Python function. | Below is the the instruction that describes the task:
### Input:
Record line profiling information for the given Python function.
### Response:
def add_function(self, func):
""" Record line profiling information for the given Python function.
"""
try:
# func_code does not exist ... |
def _flatten_file_with_secondary(input, out_dir):
"""Flatten file representation with secondary indices (CWL-like)
"""
out = []
orig_dir = os.path.dirname(input["base"])
for finfo in [input["base"]] + input.get("secondary", []):
cur_dir = os.path.dirname(finfo)
if cur_dir != orig_dir... | Flatten file representation with secondary indices (CWL-like) | Below is the the instruction that describes the task:
### Input:
Flatten file representation with secondary indices (CWL-like)
### Response:
def _flatten_file_with_secondary(input, out_dir):
"""Flatten file representation with secondary indices (CWL-like)
"""
out = []
orig_dir = os.path.dirname(inp... |
def get_machines(self, origin, hostnames):
"""Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error.
"""
hostnames = {
hostname: True
for hostname in hostnames
}
machines = origin.Machines.read(hostn... | Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error. | Below is the the instruction that describes the task:
### Input:
Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error.
### Response:
def get_machines(self, origin, hostnames):
"""Return a set of machines based on `hostnames`.
Any hostname t... |
def __dtw_calc_accu_cost(C, D, D_steps, step_sizes_sigma,
weights_mul, weights_add, max_0, max_1): # pragma: no cover
'''Calculate the accumulated cost matrix D.
Use dynamic programming to calculate the accumulated costs.
Parameters
----------
C : np.ndarray [shape=(N, M)... | Calculate the accumulated cost matrix D.
Use dynamic programming to calculate the accumulated costs.
Parameters
----------
C : np.ndarray [shape=(N, M)]
pre-computed cost matrix
D : np.ndarray [shape=(N, M)]
accumulated cost matrix
D_steps : np.ndarray [shape=(N, M)]
... | Below is the the instruction that describes the task:
### Input:
Calculate the accumulated cost matrix D.
Use dynamic programming to calculate the accumulated costs.
Parameters
----------
C : np.ndarray [shape=(N, M)]
pre-computed cost matrix
D : np.ndarray [shape=(N, M)]
accu... |
def ConfigureRequest(self, upload_config, http_request, url_builder):
"""Configure the request and url for this upload."""
# Validate total_size vs. max_size
if (self.total_size and upload_config.max_size and
self.total_size > upload_config.max_size):
raise exceptions... | Configure the request and url for this upload. | Below is the the instruction that describes the task:
### Input:
Configure the request and url for this upload.
### Response:
def ConfigureRequest(self, upload_config, http_request, url_builder):
"""Configure the request and url for this upload."""
# Validate total_size vs. max_size
if (sel... |
def _blocks(self, name):
"""Inner wrapper to search for blocks by name.
"""
i = len(self)
while i >= 0:
i -= 1
if name in self[i]['__names__']:
for b in self[i]['__blocks__']:
r = b.raw()
if r and r == name:
... | Inner wrapper to search for blocks by name. | Below is the the instruction that describes the task:
### Input:
Inner wrapper to search for blocks by name.
### Response:
def _blocks(self, name):
"""Inner wrapper to search for blocks by name.
"""
i = len(self)
while i >= 0:
i -= 1
if name in self[i]['__nam... |
def _validate_samples_factors(mwtabfile, validate_samples=True, validate_factors=True):
"""Validate ``Samples`` and ``Factors`` identifiers across the file.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile`
:return: None
:rtype: :py:obj:... | Validate ``Samples`` and ``Factors`` identifiers across the file.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile`
:return: None
:rtype: :py:obj:`None` | Below is the the instruction that describes the task:
### Input:
Validate ``Samples`` and ``Factors`` identifiers across the file.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile`
:return: None
:rtype: :py:obj:`None`
### Response:
def ... |
def registration_request_verify(registration_request):
"""
Verifies that all required parameters and correct values are included in the client registration request.
:param registration_request: the authentication request to verify
:raise InvalidClientRegistrationRequest: if the registration is incorrect... | Verifies that all required parameters and correct values are included in the client registration request.
:param registration_request: the authentication request to verify
:raise InvalidClientRegistrationRequest: if the registration is incorrect | Below is the the instruction that describes the task:
### Input:
Verifies that all required parameters and correct values are included in the client registration request.
:param registration_request: the authentication request to verify
:raise InvalidClientRegistrationRequest: if the registration is incorre... |
def _build_int_array_el(el_name, parent, list_):
"""build a soapenc:Array made of ints called `el_name` as a child
of `parent`"""
el = parent.add_child(el_name)
el.add_attribute('xmlns:soapenc',
'http://schemas.xmlsoap.org/soap/encoding/')
el.add_attribute('xsi:type', 'soapenc:A... | build a soapenc:Array made of ints called `el_name` as a child
of `parent` | Below is the the instruction that describes the task:
### Input:
build a soapenc:Array made of ints called `el_name` as a child
of `parent`
### Response:
def _build_int_array_el(el_name, parent, list_):
"""build a soapenc:Array made of ints called `el_name` as a child
of `parent`"""
el = parent.add... |
def make_absolute_paths(content):
"""Convert all MEDIA files into a file://URL paths in order to
correctly get it displayed in PDFs."""
overrides = [
{
'root': settings.MEDIA_ROOT,
'url': settings.MEDIA_URL,
},
{
'root': settings.STATIC_ROOT,
... | Convert all MEDIA files into a file://URL paths in order to
correctly get it displayed in PDFs. | Below is the the instruction that describes the task:
### Input:
Convert all MEDIA files into a file://URL paths in order to
correctly get it displayed in PDFs.
### Response:
def make_absolute_paths(content):
"""Convert all MEDIA files into a file://URL paths in order to
correctly get it displayed in P... |
def stop(self, **kwargs):
"""Stop the environment.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabStopError: If the operation failed
"""
path = '%s/%s/... | Stop the environment.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabStopError: If the operation failed | Below is the the instruction that describes the task:
### Input:
Stop the environment.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabStopError: If the operation failed
##... |
def ca_bundle(self, ca_bundle):
"""
Sets the ca_bundle of this V1alpha1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used.
:param ca_bundle: The ca_bundl... | Sets the ca_bundle of this V1alpha1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used.
:param ca_bundle: The ca_bundle of this V1alpha1WebhookClientConfig.
:type... | Below is the the instruction that describes the task:
### Input:
Sets the ca_bundle of this V1alpha1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used.
:param ca_bun... |
def _parse_references(xml):
"""Parse the references to ``Reference`` instances."""
references = []
ref_finder = HTMLReferenceFinder(xml)
for elm, uri_attr in ref_finder:
type_ = _discover_uri_type(elm.get(uri_attr))
references.append(Reference(elm, type_, uri_attr))
return references | Parse the references to ``Reference`` instances. | Below is the the instruction that describes the task:
### Input:
Parse the references to ``Reference`` instances.
### Response:
def _parse_references(xml):
"""Parse the references to ``Reference`` instances."""
references = []
ref_finder = HTMLReferenceFinder(xml)
for elm, uri_attr in ref_finder:
... |
def get_nts_sections(self, sections, sortby=None):
"""Given a list of sections containing GO IDs, get a list of sections w/GO nts."""
goids = self.get_goids_sections(sections)
gosubdag = GoSubDag(goids, self.go2obj)
return [(sec, gosubdag.get_nts(gos, sortby)) for sec, gos in sections] | Given a list of sections containing GO IDs, get a list of sections w/GO nts. | Below is the the instruction that describes the task:
### Input:
Given a list of sections containing GO IDs, get a list of sections w/GO nts.
### Response:
def get_nts_sections(self, sections, sortby=None):
"""Given a list of sections containing GO IDs, get a list of sections w/GO nts."""
goids = s... |
def _import_epublication(self, epub):
"""
Fill internal property ._POST dictionary with data from EPublication.
"""
# mrs. Svobodová requires that annotation exported by us have this
# prefix
prefixed_annotation = ANNOTATION_PREFIX + epub.anotace
self._POST["P050... | Fill internal property ._POST dictionary with data from EPublication. | Below is the the instruction that describes the task:
### Input:
Fill internal property ._POST dictionary with data from EPublication.
### Response:
def _import_epublication(self, epub):
"""
Fill internal property ._POST dictionary with data from EPublication.
"""
# mrs. Svobodová r... |
def dir_name_changed(self, widget, data=None):
"""
Function is used for controlling
label Full Directory project name
and storing current project directory
in configuration manager
"""
config_manager.set_config_value("da.project_dir", self.dir_name.get_text())
... | Function is used for controlling
label Full Directory project name
and storing current project directory
in configuration manager | Below is the the instruction that describes the task:
### Input:
Function is used for controlling
label Full Directory project name
and storing current project directory
in configuration manager
### Response:
def dir_name_changed(self, widget, data=None):
"""
Function is use... |
def send_request(self, worker_class_or_function, args, on_receive=None):
"""
Requests some work to be done by the backend. You can get notified of
the work results by passing a callback (on_receive).
:param worker_class_or_function: Worker class or function
:param args: worker a... | Requests some work to be done by the backend. You can get notified of
the work results by passing a callback (on_receive).
:param worker_class_or_function: Worker class or function
:param args: worker args, any Json serializable objects
:param on_receive: an optional callback executed w... | Below is the the instruction that describes the task:
### Input:
Requests some work to be done by the backend. You can get notified of
the work results by passing a callback (on_receive).
:param worker_class_or_function: Worker class or function
:param args: worker args, any Json serializab... |
def attach(cls, ip, vm, background=False, force=False):
""" Attach """
vm_ = Iaas.info(vm)
ip_ = cls.info(ip)
if not cls._check_and_detach(ip_, vm_):
return
# then we should attach the ip to the vm
attach = Iface._attach(ip_['iface_id'], vm_['id'])
if... | Attach | Below is the the instruction that describes the task:
### Input:
Attach
### Response:
def attach(cls, ip, vm, background=False, force=False):
""" Attach """
vm_ = Iaas.info(vm)
ip_ = cls.info(ip)
if not cls._check_and_detach(ip_, vm_):
return
# then we should at... |
def GetEntries(
self, parser_mediator, cookie_data=None, url=None, **kwargs):
"""Extracts event objects from the cookie.
Args:
parser_mediator (ParserMediator): parser mediator.
cookie_data (bytes): cookie data.
url (str): URL or path where the cookie got set.
"""
fields = cooki... | Extracts event objects from the cookie.
Args:
parser_mediator (ParserMediator): parser mediator.
cookie_data (bytes): cookie data.
url (str): URL or path where the cookie got set. | Below is the the instruction that describes the task:
### Input:
Extracts event objects from the cookie.
Args:
parser_mediator (ParserMediator): parser mediator.
cookie_data (bytes): cookie data.
url (str): URL or path where the cookie got set.
### Response:
def GetEntries(
self, parse... |
def build_etag(self, response, include_etag=True, **kwargs):
"""
Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html
"""
if not include... | Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html | Below is the the instruction that describes the task:
### Input:
Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html
### Response:
def build_etag(self, response, i... |
def restore_yaml_comments(data, default_data):
"""Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping.
"""
comment_map = dict... | Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping. | Below is the the instruction that describes the task:
### Input:
Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping.
### Response:
... |
def with_units(self, val, ua, ub):
"""Return value with unit.
args:
val (mixed): result
ua (str): 1st unit
ub (str): 2nd unit
raises:
SyntaxError
returns:
str
"""
if not val:
return str(val)
i... | Return value with unit.
args:
val (mixed): result
ua (str): 1st unit
ub (str): 2nd unit
raises:
SyntaxError
returns:
str | Below is the the instruction that describes the task:
### Input:
Return value with unit.
args:
val (mixed): result
ua (str): 1st unit
ub (str): 2nd unit
raises:
SyntaxError
returns:
str
### Response:
def with_units(self, val, ua, u... |
def _footer_start_thread(self, text, time):
"""Display given text in the footer. Clears after <time> seconds
"""
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.top.footer = footerwid
load_thread = Thread(target=self._loading_thread, args=(time,))
load_thread.... | Display given text in the footer. Clears after <time> seconds | Below is the the instruction that describes the task:
### Input:
Display given text in the footer. Clears after <time> seconds
### Response:
def _footer_start_thread(self, text, time):
"""Display given text in the footer. Clears after <time> seconds
"""
footerwid = urwid.AttrMap(urwid.Text... |
def _prepare_request(reddit_session, url, params, data, auth, files,
method=None):
"""Return a requests Request object that can be "prepared"."""
# Requests using OAuth for authorization must switch to using the oauth
# domain.
if getattr(reddit_session, '_use_oauth', False):
... | Return a requests Request object that can be "prepared". | Below is the the instruction that describes the task:
### Input:
Return a requests Request object that can be "prepared".
### Response:
def _prepare_request(reddit_session, url, params, data, auth, files,
method=None):
"""Return a requests Request object that can be "prepared"."""
# Re... |
def djfrontend_fontawesome(version=None):
"""
Returns Font Awesome CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_FONTAWESOME', DJFRONTEND_FONTAWESOME_DEFAULT)
return format_html(
'<lin... | Returns Font Awesome CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file. | Below is the the instruction that describes the task:
### Input:
Returns Font Awesome CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
### Response:
def djfrontend_fontawesome(version=None):
"""
Returns Font Awesome CSS file.
TEMPLATE_DEBUG returns full file, otherwise r... |
def filter(self, value=None, model=None, context=None):
"""
Sequentially applies all the filters to provided value
:param value: a value to filter
:param model: parent entity
:param context: filtering context, usually parent entity
:return: filtered value
"""
... | Sequentially applies all the filters to provided value
:param value: a value to filter
:param model: parent entity
:param context: filtering context, usually parent entity
:return: filtered value | Below is the the instruction that describes the task:
### Input:
Sequentially applies all the filters to provided value
:param value: a value to filter
:param model: parent entity
:param context: filtering context, usually parent entity
:return: filtered value
### Response:
def fil... |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
self.HashStart = reader.ReadSerializableArray('neocore.UInt256.UInt256')
self.HashStop = reader.ReadUInt256() | Deserialize full object.
Args:
reader (neo.IO.BinaryReader): | Below is the the instruction that describes the task:
### Input:
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
### Response:
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
s... |
def rm(package, force=False):
"""
Remove a package (all instances) from the local store.
"""
team, owner, pkg = parse_package(package)
if not force:
confirmed = input("Remove {0}? (y/n) ".format(package))
if confirmed.lower() != 'y':
return
store = PackageStore()
... | Remove a package (all instances) from the local store. | Below is the the instruction that describes the task:
### Input:
Remove a package (all instances) from the local store.
### Response:
def rm(package, force=False):
"""
Remove a package (all instances) from the local store.
"""
team, owner, pkg = parse_package(package)
if not force:
con... |
def get_all_params(self, session=None):
"""Return the parameters in a list of array."""
_params = []
for p in self.all_params:
if session is None:
_params.append(p.eval())
else:
_params.append(session.run(p))
return _params | Return the parameters in a list of array. | Below is the the instruction that describes the task:
### Input:
Return the parameters in a list of array.
### Response:
def get_all_params(self, session=None):
"""Return the parameters in a list of array."""
_params = []
for p in self.all_params:
if session is None:
... |
def next(self):
"""
Implementation of next method from Iterator.
:return: Result
:raises: StopIteration if IndexError occurs.
"""
try:
result = self.data[self.index]
except IndexError:
self.index = 0
raise StopIteration
... | Implementation of next method from Iterator.
:return: Result
:raises: StopIteration if IndexError occurs. | Below is the the instruction that describes the task:
### Input:
Implementation of next method from Iterator.
:return: Result
:raises: StopIteration if IndexError occurs.
### Response:
def next(self):
"""
Implementation of next method from Iterator.
:return: Result
... |
def add_chart(self, chart_type, x, y, cx, cy, chart_data):
"""Add a new chart of *chart_type* to the slide.
The chart is positioned at (*x*, *y*), has size (*cx*, *cy*), and
depicts *chart_data*. *chart_type* is one of the :ref:`XlChartType`
enumeration values. *chart_data* is a |ChartD... | Add a new chart of *chart_type* to the slide.
The chart is positioned at (*x*, *y*), has size (*cx*, *cy*), and
depicts *chart_data*. *chart_type* is one of the :ref:`XlChartType`
enumeration values. *chart_data* is a |ChartData| object populated
with the categories and series values fo... | Below is the the instruction that describes the task:
### Input:
Add a new chart of *chart_type* to the slide.
The chart is positioned at (*x*, *y*), has size (*cx*, *cy*), and
depicts *chart_data*. *chart_type* is one of the :ref:`XlChartType`
enumeration values. *chart_data* is a |ChartDa... |
def check_validity(self, checks=None, report=True):
""" Runs a Symbol's validity checks.
Parameters
----------
checks : str, [str,], optional
Only run certain checks.
report : bool, optional
If set to False, the method will return only t... | Runs a Symbol's validity checks.
Parameters
----------
checks : str, [str,], optional
Only run certain checks.
report : bool, optional
If set to False, the method will return only the result of the
check checks (True/False). Set to ... | Below is the the instruction that describes the task:
### Input:
Runs a Symbol's validity checks.
Parameters
----------
checks : str, [str,], optional
Only run certain checks.
report : bool, optional
If set to False, the method will return on... |
def get_context_arguments(self):
"""Return a dictionary containing the current context arguments."""
cargs = {}
for context in self.__context_stack:
cargs.update(context.context_arguments)
return cargs | Return a dictionary containing the current context arguments. | Below is the the instruction that describes the task:
### Input:
Return a dictionary containing the current context arguments.
### Response:
def get_context_arguments(self):
"""Return a dictionary containing the current context arguments."""
cargs = {}
for context in self.__context_stack:
... |
def _paint_icon(self, iconic, painter, rect, mode, state, options):
"""Paint a single icon."""
painter.save()
color = options['color']
char = options['char']
color_options = {
QIcon.On: {
QIcon.Normal: (options['color_on'], options['on']),
... | Paint a single icon. | Below is the the instruction that describes the task:
### Input:
Paint a single icon.
### Response:
def _paint_icon(self, iconic, painter, rect, mode, state, options):
"""Paint a single icon."""
painter.save()
color = options['color']
char = options['char']
color_options = ... |
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
... | Strips accents from a piece of text. | Below is the the instruction that describes the task:
### Input:
Strips accents from a piece of text.
### Response:
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat ... |
def date_totals(entries, by):
"""Yield a user's name and a dictionary of their hours"""
date_dict = {}
for date, date_entries in groupby(entries, lambda x: x['date']):
if isinstance(date, datetime.datetime):
date = date.date()
d_entries = list(date_entries)
if by == 'use... | Yield a user's name and a dictionary of their hours | Below is the the instruction that describes the task:
### Input:
Yield a user's name and a dictionary of their hours
### Response:
def date_totals(entries, by):
"""Yield a user's name and a dictionary of their hours"""
date_dict = {}
for date, date_entries in groupby(entries, lambda x: x['date']):
... |
def log_future_exceptions(logger, f, ignore=()):
"""Log any exceptions set to a future
Parameters
----------
logger : logging.Logger instance
logger.exception(...) is called if the future resolves with an exception
f : Future object
Future to be monitored for exceptions
ignore :... | Log any exceptions set to a future
Parameters
----------
logger : logging.Logger instance
logger.exception(...) is called if the future resolves with an exception
f : Future object
Future to be monitored for exceptions
ignore : Exception or tuple of Exception
Exptected excep... | Below is the the instruction that describes the task:
### Input:
Log any exceptions set to a future
Parameters
----------
logger : logging.Logger instance
logger.exception(...) is called if the future resolves with an exception
f : Future object
Future to be monitored for exceptions... |
def space_row(left, right, filler=' ', total_width=-1):
"""space the data in a row with optional filling
Arguments
---------
left : str, to be aligned left
right : str, to be aligned right
filler : str, default ' '.
must be of length 1
total_width : int, width of line.
if ne... | space the data in a row with optional filling
Arguments
---------
left : str, to be aligned left
right : str, to be aligned right
filler : str, default ' '.
must be of length 1
total_width : int, width of line.
if negative number is specified,
then that number of spaces ... | Below is the the instruction that describes the task:
### Input:
space the data in a row with optional filling
Arguments
---------
left : str, to be aligned left
right : str, to be aligned right
filler : str, default ' '.
must be of length 1
total_width : int, width of line.
... |
def coerce(self, value):
"""
Coerces value to location hash.
"""
return {
'lat': float(value.get('lat', value.get('latitude'))),
'lon': float(value.get('lon', value.get('longitude')))
} | Coerces value to location hash. | Below is the the instruction that describes the task:
### Input:
Coerces value to location hash.
### Response:
def coerce(self, value):
"""
Coerces value to location hash.
"""
return {
'lat': float(value.get('lat', value.get('latitude'))),
'lon': float(value... |
def run_through(script, ensemble, roles=1, strict=False):
"""
:py:class:`turberfield.dialogue.model.SceneScript`.
"""
with script as dialogue:
selection = dialogue.select(ensemble, roles=roles)
if not any(selection.values()) or strict and not all(selection.values()):
return
... | :py:class:`turberfield.dialogue.model.SceneScript`. | Below is the the instruction that describes the task:
### Input:
:py:class:`turberfield.dialogue.model.SceneScript`.
### Response:
def run_through(script, ensemble, roles=1, strict=False):
"""
:py:class:`turberfield.dialogue.model.SceneScript`.
"""
with script as dialogue:
selection = dialo... |
def _GetModuleCodeObjects(module):
"""Gets all code objects defined in the specified module.
There are two BFS traversals involved. One in this function and the other in
_FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has
a depth limit. This function does not. The motivation is that this f... | Gets all code objects defined in the specified module.
There are two BFS traversals involved. One in this function and the other in
_FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has
a depth limit. This function does not. The motivation is that this function
explores code object of the mo... | Below is the the instruction that describes the task:
### Input:
Gets all code objects defined in the specified module.
There are two BFS traversals involved. One in this function and the other in
_FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has
a depth limit. This function does not. ... |
def get_recently_played_games(self, steamID, count=0, format=None):
"""Request a list of recently played games by a given steam id.
steamID: The users ID
count: Number of games to return. (0 is all recent games.)
format: Return format. None defaults to json. (json, xml, vdf)
""... | Request a list of recently played games by a given steam id.
steamID: The users ID
count: Number of games to return. (0 is all recent games.)
format: Return format. None defaults to json. (json, xml, vdf) | Below is the the instruction that describes the task:
### Input:
Request a list of recently played games by a given steam id.
steamID: The users ID
count: Number of games to return. (0 is all recent games.)
format: Return format. None defaults to json. (json, xml, vdf)
### Response:
def ge... |
def getreferingobjs(self, iddgroups=None, fields=None):
"""Get a list of objects that refer to this object"""
return getreferingobjs(self, iddgroups=iddgroups, fields=fields) | Get a list of objects that refer to this object | Below is the the instruction that describes the task:
### Input:
Get a list of objects that refer to this object
### Response:
def getreferingobjs(self, iddgroups=None, fields=None):
"""Get a list of objects that refer to this object"""
return getreferingobjs(self, iddgroups=iddgroups, fields=field... |
def daily_at(cls, at, target):
"""
Schedule a command to run at a specific time each day.
"""
daily = datetime.timedelta(days=1)
# convert when to the next datetime matching this time
when = datetime.datetime.combine(datetime.date.today(), at)
if when < now():
... | Schedule a command to run at a specific time each day. | Below is the the instruction that describes the task:
### Input:
Schedule a command to run at a specific time each day.
### Response:
def daily_at(cls, at, target):
"""
Schedule a command to run at a specific time each day.
"""
daily = datetime.timedelta(days=1)
# convert wh... |
def _create_clock(self):
"""
If the clock property is not set, then create one based on frequency.
"""
trading_o_and_c = self.trading_calendar.schedule.ix[
self.sim_params.sessions]
market_closes = trading_o_and_c['market_close']
minutely_emission = False
... | If the clock property is not set, then create one based on frequency. | Below is the the instruction that describes the task:
### Input:
If the clock property is not set, then create one based on frequency.
### Response:
def _create_clock(self):
"""
If the clock property is not set, then create one based on frequency.
"""
trading_o_and_c = self.trading_... |
def write_module_file(name, path, package):
'''Creates an RST file for the module name passed in. It places it in the
path defined
'''
file_path = join(path, '%s.rst' % name)
mod_file = open(file_path, 'w')
mod_file.write('%s\n' % AUTOGEN)
mod_file.write('%s\n' % name.title())
mod_file.... | Creates an RST file for the module name passed in. It places it in the
path defined | Below is the the instruction that describes the task:
### Input:
Creates an RST file for the module name passed in. It places it in the
path defined
### Response:
def write_module_file(name, path, package):
'''Creates an RST file for the module name passed in. It places it in the
path defined
'''
... |
def _draw_chars(self, data, to_draw):
"""
Draw the specified charachters using the specified format.
"""
i = 0
while not self._cursor.atBlockEnd() and i < len(to_draw) and len(to_draw) > 1:
self._cursor.deleteChar()
i += 1
self._cursor.insertText(t... | Draw the specified charachters using the specified format. | Below is the the instruction that describes the task:
### Input:
Draw the specified charachters using the specified format.
### Response:
def _draw_chars(self, data, to_draw):
"""
Draw the specified charachters using the specified format.
"""
i = 0
while not self._cursor.atB... |
def streams(self):
"""Property providing access to the :class:`.StreamsAPI`"""
if self._streams_api is None:
self._streams_api = self.get_streams_api()
return self._streams_api | Property providing access to the :class:`.StreamsAPI` | Below is the the instruction that describes the task:
### Input:
Property providing access to the :class:`.StreamsAPI`
### Response:
def streams(self):
"""Property providing access to the :class:`.StreamsAPI`"""
if self._streams_api is None:
self._streams_api = self.get_streams_api()
... |
def getFasta(opened_file, sequence_name):
"""
Retrieves a sequence from an opened multifasta file
:param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+')
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:1... | Retrieves a sequence from an opened multifasta file
:param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+')
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:182113224:1 REF' use: sequence_name=str(2)
returns... | Below is the the instruction that describes the task:
### Input:
Retrieves a sequence from an opened multifasta file
:param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+')
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromoso... |
def get_writer_factory_for(self, name, *, format=None):
"""
Returns a callable to build a writer for the provided filename, eventually forcing a format.
:param name: filename
:param format: format
:return: type
"""
return self.get_factory_for(WRITER, name, format... | Returns a callable to build a writer for the provided filename, eventually forcing a format.
:param name: filename
:param format: format
:return: type | Below is the the instruction that describes the task:
### Input:
Returns a callable to build a writer for the provided filename, eventually forcing a format.
:param name: filename
:param format: format
:return: type
### Response:
def get_writer_factory_for(self, name, *, format=None):
... |
def load(handle):
"""Loads a module from a handle.
Currently this method only works with Tensorflow 2.x and can only load modules
created by calling tensorflow.saved_model.save(). The method works in both
eager and graph modes.
Depending on the type of handle used, the call may involve downloading a
Tenso... | Loads a module from a handle.
Currently this method only works with Tensorflow 2.x and can only load modules
created by calling tensorflow.saved_model.save(). The method works in both
eager and graph modes.
Depending on the type of handle used, the call may involve downloading a
Tensorflow Hub module to a l... | Below is the the instruction that describes the task:
### Input:
Loads a module from a handle.
Currently this method only works with Tensorflow 2.x and can only load modules
created by calling tensorflow.saved_model.save(). The method works in both
eager and graph modes.
Depending on the type of handle us... |
def remove_message(self, message):
"""
Removes a message.
:param message: Message to remove
"""
import time
_logger(self.__class__).log(5, 'removing message %s' % message)
t = time.time()
usd = message.block.userData()
if usd:
try:
... | Removes a message.
:param message: Message to remove | Below is the the instruction that describes the task:
### Input:
Removes a message.
:param message: Message to remove
### Response:
def remove_message(self, message):
"""
Removes a message.
:param message: Message to remove
"""
import time
_logger(self.__cl... |
def freeze(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph',
conversion_out_dir_path=None, checkpoint_out_path=None, use_padding_same=False):
"""Freeze and shrink the graph based on a Caffe model, the input tensors and the output node names."""
with caf... | Freeze and shrink the graph based on a Caffe model, the input tensors and the output node names. | Below is the the instruction that describes the task:
### Input:
Freeze and shrink the graph based on a Caffe model, the input tensors and the output node names.
### Response:
def freeze(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph',
conversion_out_dir_... |
def keylist(self):
"""Return a list of names in order by value."""
items = self.enumerations.items()
items.sort(lambda a, b: self.cmp(a[1], b[1]))
# last item has highest value
rslt = [None] * (items[-1][1] + 1)
# map the values
for key, value in items:
... | Return a list of names in order by value. | Below is the the instruction that describes the task:
### Input:
Return a list of names in order by value.
### Response:
def keylist(self):
"""Return a list of names in order by value."""
items = self.enumerations.items()
items.sort(lambda a, b: self.cmp(a[1], b[1]))
# last item ha... |
def pre_build_check():
"""
Try to verify build tools
"""
if os.environ.get('CASS_DRIVER_NO_PRE_BUILD_CHECK'):
return True
try:
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
from distutils.dist import Distribution
... | Try to verify build tools | Below is the the instruction that describes the task:
### Input:
Try to verify build tools
### Response:
def pre_build_check():
"""
Try to verify build tools
"""
if os.environ.get('CASS_DRIVER_NO_PRE_BUILD_CHECK'):
return True
try:
from distutils.ccompiler import new_compiler
... |
def basis_function_all(degree, knot_vector, span, knot):
""" Computes all non-zero basis functions of all degrees from 0 up to the input degree for a single parameter.
A slightly modified version of Algorithm A2.2 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: in... | Computes all non-zero basis functions of all degrees from 0 up to the input degree for a single parameter.
A slightly modified version of Algorithm A2.2 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_... | Below is the the instruction that describes the task:
### Input:
Computes all non-zero basis functions of all degrees from 0 up to the input degree for a single parameter.
A slightly modified version of Algorithm A2.2 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree... |
async def BlockUntilLeadershipReleased(self, name):
'''
name : str
Returns -> Error
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='LeadershipService',
request='BlockUntilLeadershipReleased',
version=2,
... | name : str
Returns -> Error | Below is the the instruction that describes the task:
### Input:
name : str
Returns -> Error
### Response:
async def BlockUntilLeadershipReleased(self, name):
'''
name : str
Returns -> Error
'''
# map input types to rpc msg
_params = dict()
msg = dict... |
def _download_to_local(boto_conn, s3_path, fp, num_result_dir, delim=None):
'''
Downloads the contents of all objects in s3_path into fp
Args:
`boto_conn`: S3 connection object
`s3_path`: S3 path to be downloaded
`fp`: The file object where data is to be downloaded
'''
#Pr... | Downloads the contents of all objects in s3_path into fp
Args:
`boto_conn`: S3 connection object
`s3_path`: S3 path to be downloaded
`fp`: The file object where data is to be downloaded | Below is the the instruction that describes the task:
### Input:
Downloads the contents of all objects in s3_path into fp
Args:
`boto_conn`: S3 connection object
`s3_path`: S3 path to be downloaded
`fp`: The file object where data is to be downloaded
### Response:
def _download_to_lo... |
def Email(
self,
From,
To,
Cc=None,
Bcc=None,
Subject=None,
Tag=None,
HtmlBody=None,
TextBody=None,
Metadata=None,
ReplyTo=None,
Headers=None,
TrackOpens=None,
TrackLinks="None",
Attachments=None,
... | Constructs :py:class:`Email` instance.
:return: :py:class:`Email` | Below is the the instruction that describes the task:
### Input:
Constructs :py:class:`Email` instance.
:return: :py:class:`Email`
### Response:
def Email(
self,
From,
To,
Cc=None,
Bcc=None,
Subject=None,
Tag=None,
HtmlBody=None,
Text... |
def sqs_delete_item(queue_url,
receipt_handle,
client=None,
raiseonfail=False):
"""This deletes a message from the queue, effectively acknowledging its
receipt.
Call this only when all messages retrieved from the queue have been
processed, sin... | This deletes a message from the queue, effectively acknowledging its
receipt.
Call this only when all messages retrieved from the queue have been
processed, since this will prevent redelivery of these messages to other
queue workers pulling fromn the same queue channel.
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
This deletes a message from the queue, effectively acknowledging its
receipt.
Call this only when all messages retrieved from the queue have been
processed, since this will prevent redelivery of these messages to other
queue workers p... |
def __is_json_error(self, status, headers):
"""Determine if response is an error.
Args:
status: HTTP status code.
headers: Dictionary of (lowercase) header name to value.
Returns:
True if the response was an error, else False.
"""
content_header = headers.get('content-type', '')
... | Determine if response is an error.
Args:
status: HTTP status code.
headers: Dictionary of (lowercase) header name to value.
Returns:
True if the response was an error, else False. | Below is the the instruction that describes the task:
### Input:
Determine if response is an error.
Args:
status: HTTP status code.
headers: Dictionary of (lowercase) header name to value.
Returns:
True if the response was an error, else False.
### Response:
def __is_json_error(self, st... |
def _dcm_to_q(self, dcm):
"""
Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array
"""
assert(dcm.shape == (3, 3))
q = np.zeros(4)... | Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array | Below is the the instruction that describes the task:
### Input:
Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array
### Response:
def _dcm_to_q(self, dcm):
... |
def _count_fields_recursive(dataset, fields):
"""Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario con los campos a v... | Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario con los campos a verificar en dataset
como claves, y 'optat... | Below is the the instruction that describes the task:
### Input:
Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario co... |
def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs):
"""
Associated a list of assets by site to the site collection used
to instantiate GeographicObjects.
:param assets_by_sites: a list of lists of assets
:param assoc_dist: the maximum distance for association
... | Associated a list of assets by site to the site collection used
to instantiate GeographicObjects.
:param assets_by_sites: a list of lists of assets
:param assoc_dist: the maximum distance for association
:param mode: 'strict', 'warn' or 'filter'
:param asset_ref: ID of the asset... | Below is the the instruction that describes the task:
### Input:
Associated a list of assets by site to the site collection used
to instantiate GeographicObjects.
:param assets_by_sites: a list of lists of assets
:param assoc_dist: the maximum distance for association
:param mode: '... |
def putcol(self, value, startrow=0, nrow=-1, rowincr=1):
"""Put an entire column or part of it.
(see :func:`table.putcol`)"""
return self._table.putcol(self._column, value, startrow, nrow, rowincr) | Put an entire column or part of it.
(see :func:`table.putcol`) | Below is the the instruction that describes the task:
### Input:
Put an entire column or part of it.
(see :func:`table.putcol`)
### Response:
def putcol(self, value, startrow=0, nrow=-1, rowincr=1):
"""Put an entire column or part of it.
(see :func:`table.putcol`)"""
return self._ta... |
def get(self, app_id, view_specifier):
"""
Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
3. "las... | Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
3. "last" to look up the last view used | Below is the the instruction that describes the task:
### Input:
Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
... |
def get_skydir_distance_mask(src_skydir, skydir, dist, min_dist=None,
square=False, coordsys='CEL'):
"""Retrieve sources within a certain angular distance of an
(ra,dec) coordinate. This function supports two types of
geometric selections: circular (square=False) and square
... | Retrieve sources within a certain angular distance of an
(ra,dec) coordinate. This function supports two types of
geometric selections: circular (square=False) and square
(square=True). The circular selection finds all sources with a given
angular distance of the target position. The square selection... | Below is the the instruction that describes the task:
### Input:
Retrieve sources within a certain angular distance of an
(ra,dec) coordinate. This function supports two types of
geometric selections: circular (square=False) and square
(square=True). The circular selection finds all sources with a giv... |
def get_instance(self, cls):
"""Return an instance for a class."""
binding = self._bindings.get(cls)
if binding:
return binding()
# Try to create a runtime binding.
with _BINDING_LOCK:
binding = self._bindings.get(cls)
if binding:
... | Return an instance for a class. | Below is the the instruction that describes the task:
### Input:
Return an instance for a class.
### Response:
def get_instance(self, cls):
"""Return an instance for a class."""
binding = self._bindings.get(cls)
if binding:
return binding()
# Try to create a runtime bin... |
def no_more_a_problem(self, hosts, services, timeperiods, bi_modulations):
"""Remove this objects as an impact for other schedulingitem.
:param hosts: hosts objects, used to get impacts
:type hosts: alignak.objects.host.Hosts
:param services: services objects, used to get impacts
... | Remove this objects as an impact for other schedulingitem.
:param hosts: hosts objects, used to get impacts
:type hosts: alignak.objects.host.Hosts
:param services: services objects, used to get impacts
:type services: alignak.objects.service.Services
:param timeperiods: Timeper... | Below is the the instruction that describes the task:
### Input:
Remove this objects as an impact for other schedulingitem.
:param hosts: hosts objects, used to get impacts
:type hosts: alignak.objects.host.Hosts
:param services: services objects, used to get impacts
:type services:... |
def put(self, path, data, **options):
"""
Parses PUT request options and dispatches a request
"""
data, options = self._update_request(data, options)
return self.request('put', path, data=data, **options) | Parses PUT request options and dispatches a request | Below is the the instruction that describes the task:
### Input:
Parses PUT request options and dispatches a request
### Response:
def put(self, path, data, **options):
"""
Parses PUT request options and dispatches a request
"""
data, options = self._update_request(data, options)
... |
def _iter_all_paths(start, end, rand=False, path=tuple()):
"""Iterate through all paths from start to end."""
path = path + (start, )
if start is end:
yield path
else:
nodes = [start.lo, start.hi]
if rand: # pragma: no cover
random.shuffle(nodes)
for node in n... | Iterate through all paths from start to end. | Below is the the instruction that describes the task:
### Input:
Iterate through all paths from start to end.
### Response:
def _iter_all_paths(start, end, rand=False, path=tuple()):
"""Iterate through all paths from start to end."""
path = path + (start, )
if start is end:
yield path
else:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.