code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def request_param_update(self, complete_name):
"""
Request an update of the value for the supplied parameter.
"""
self.param_updater.request_param_update(
self.toc.get_element_id(complete_name)) | Request an update of the value for the supplied parameter. | Below is the the instruction that describes the task:
### Input:
Request an update of the value for the supplied parameter.
### Response:
def request_param_update(self, complete_name):
"""
Request an update of the value for the supplied parameter.
"""
self.param_updater.request_para... |
def get_json(identifier, namespace='cid', domain='compound', operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses JSON response and supresses NotFoundError."""
try:
return json.loads(get(identifier, namespace, domain, operation, 'JSON', searchtype, **kwargs).decode())... | Request wrapper that automatically parses JSON response and supresses NotFoundError. | Below is the the instruction that describes the task:
### Input:
Request wrapper that automatically parses JSON response and supresses NotFoundError.
### Response:
def get_json(identifier, namespace='cid', domain='compound', operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically pars... |
def build_tqdm_outer(self, desc, total):
"""
Extension point. Override to provide custom options to outer progress bars (Epoch loop)
:param desc: Description
:param total: Number of epochs
:return: new progress bar
"""
return self.tqdm(desc=desc, total=total, leav... | Extension point. Override to provide custom options to outer progress bars (Epoch loop)
:param desc: Description
:param total: Number of epochs
:return: new progress bar | Below is the the instruction that describes the task:
### Input:
Extension point. Override to provide custom options to outer progress bars (Epoch loop)
:param desc: Description
:param total: Number of epochs
:return: new progress bar
### Response:
def build_tqdm_outer(self, desc, total):
... |
def decimal_to_alpha(dec):
"""
expects: decimal between 0 and 100
returns: alpha value for rgba
"""
dec /= 100.0
alpha = hex(int(dec*65535))[2:]
while len(alpha) < 4:
alpha = '0' + alpha
return alpha | expects: decimal between 0 and 100
returns: alpha value for rgba | Below is the the instruction that describes the task:
### Input:
expects: decimal between 0 and 100
returns: alpha value for rgba
### Response:
def decimal_to_alpha(dec):
"""
expects: decimal between 0 and 100
returns: alpha value for rgba
"""
dec /= 100.0
alpha = hex(int(dec*65535))[2... |
def load(self, *relations):
"""
Load a set of relationships onto the collection.
"""
if len(self._items) > 0:
query = self.first().new_query().with_(*relations)
self._items = query.eager_load_relations(self._items)
return self | Load a set of relationships onto the collection. | Below is the the instruction that describes the task:
### Input:
Load a set of relationships onto the collection.
### Response:
def load(self, *relations):
"""
Load a set of relationships onto the collection.
"""
if len(self._items) > 0:
query = self.first().new_query().... |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: h... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | Below is the the instruction that describes the task:
### Input:
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
### Response:
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to cr... |
def register_flag_by_module(self, module_name, flag):
"""Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: str, the name of a Python module.
flag: Flag, the Flag instance... | Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: str, the name of a Python module.
flag: Flag, the Flag instance that is key to the module. | Below is the the instruction that describes the task:
### Input:
Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: str, the name of a Python module.
flag: Flag, the Flag ... |
def get_tables_for_query(query):
"""
Takes a Django 'query' object and returns all tables that will be used in
that query as a list. Note that where clauses can have their own
querysets with their own dependent queries, etc.
"""
from django.db.models.sql.where import WhereNode, SubqueryConstrai... | Takes a Django 'query' object and returns all tables that will be used in
that query as a list. Note that where clauses can have their own
querysets with their own dependent queries, etc. | Below is the the instruction that describes the task:
### Input:
Takes a Django 'query' object and returns all tables that will be used in
that query as a list. Note that where clauses can have their own
querysets with their own dependent queries, etc.
### Response:
def get_tables_for_query(query):
""... |
def _general_init(self, opts, out=None):
"""
Initializes a variety of variables depending on user input.
@return: a tuple containing a boolean value indicating whether
progressbars should be hidden, functionality and enabled
functionality.
"""
se... | Initializes a variety of variables depending on user input.
@return: a tuple containing a boolean value indicating whether
progressbars should be hidden, functionality and enabled
functionality. | Below is the the instruction that describes the task:
### Input:
Initializes a variety of variables depending on user input.
@return: a tuple containing a boolean value indicating whether
progressbars should be hidden, functionality and enabled
functionality.
### Response:
def ... |
def get_datasets(self):
# type: () -> List[hdx.data.dataset.Dataset]
"""Get any datasets in the showcase
Returns:
List[Dataset]: List of datasets
"""
assoc_result, datasets_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='showcase_id',
... | Get any datasets in the showcase
Returns:
List[Dataset]: List of datasets | Below is the the instruction that describes the task:
### Input:
Get any datasets in the showcase
Returns:
List[Dataset]: List of datasets
### Response:
def get_datasets(self):
# type: () -> List[hdx.data.dataset.Dataset]
"""Get any datasets in the showcase
Returns:
... |
def articles(self):
''' Tries to scrape the correct articles for singular and plural from uitmuntend.nl. '''
result = [None, None]
element = self._first('NN')
if element:
element = element.split('\r\n')[0]
if ' | ' in element:
# This means there is a plural
singular, plural = element.split(' | ')... | Tries to scrape the correct articles for singular and plural from uitmuntend.nl. | Below is the the instruction that describes the task:
### Input:
Tries to scrape the correct articles for singular and plural from uitmuntend.nl.
### Response:
def articles(self):
''' Tries to scrape the correct articles for singular and plural from uitmuntend.nl. '''
result = [None, None]
element = self._f... |
def add_rel(self, rId, reltype, target, is_external=False):
"""
Add a child ``<Relationship>`` element with attributes set according
to parameter values.
"""
target_mode = RTM.EXTERNAL if is_external else RTM.INTERNAL
relationship = CT_Relationship.new(rId, reltype, targe... | Add a child ``<Relationship>`` element with attributes set according
to parameter values. | Below is the the instruction that describes the task:
### Input:
Add a child ``<Relationship>`` element with attributes set according
to parameter values.
### Response:
def add_rel(self, rId, reltype, target, is_external=False):
"""
Add a child ``<Relationship>`` element with attributes set... |
def get_public_agents_public_ip():
"""Provides a list public IPs for public agents in the cluster"""
public_ip_list = []
agents = get_public_agents()
for agent in agents:
status, public_ip = shakedown.run_command_on_agent(agent, "/opt/mesosphere/bin/detect_ip_public")
public_ip_list.appe... | Provides a list public IPs for public agents in the cluster | Below is the the instruction that describes the task:
### Input:
Provides a list public IPs for public agents in the cluster
### Response:
def get_public_agents_public_ip():
"""Provides a list public IPs for public agents in the cluster"""
public_ip_list = []
agents = get_public_agents()
for agent ... |
def start_watching(self):
""" Begins watching etcd for changes. """
# Don't create a new watcher thread if we already have one running
if self.watcher and self.watcher.is_alive():
return
# Create a new watcher thread and start it
self.watcher = Watcher()
self... | Begins watching etcd for changes. | Below is the the instruction that describes the task:
### Input:
Begins watching etcd for changes.
### Response:
def start_watching(self):
""" Begins watching etcd for changes. """
# Don't create a new watcher thread if we already have one running
if self.watcher and self.watcher.is_alive()... |
def _query_iterator(cursor, chunksize, columns, index_col=None,
coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
while True:
data = cursor.fetchmany(chunksize)
if type(data) == tuple:
data = list(data... | Return generator through chunked result set | Below is the the instruction that describes the task:
### Input:
Return generator through chunked result set
### Response:
def _query_iterator(cursor, chunksize, columns, index_col=None,
coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
... |
def create(self, bucket, descriptor, force=False):
"""https://github.com/frictionlessdata/tableschema-pandas-py#storage
"""
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
descriptors = descriptor
if isinstanc... | https://github.com/frictionlessdata/tableschema-pandas-py#storage | Below is the the instruction that describes the task:
### Input:
https://github.com/frictionlessdata/tableschema-pandas-py#storage
### Response:
def create(self, bucket, descriptor, force=False):
"""https://github.com/frictionlessdata/tableschema-pandas-py#storage
"""
# Make lists
... |
def find_objects(self, ObjectClass, **kwargs):
""" Retrieve all objects of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case sensitive.
"""
filter = None
for k, v in kwargs.items():
cond = ObjectClass.getattr(k) == v
filter = con... | Retrieve all objects of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case sensitive. | Below is the the instruction that describes the task:
### Input:
Retrieve all objects of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case sensitive.
### Response:
def find_objects(self, ObjectClass, **kwargs):
""" Retrieve all objects of type ``ObjectClass``,
mat... |
def field_stats(self, indices=''):
"""
Retrieve the field data stats for one or more indices
(See :ref:'es-guide-reference-api-admin-cluster-nodes-stats')
:keyword indices: an index or a list of indices
"""
path = self.conn._make_path(indices, (), '_stats','fielddata')
... | Retrieve the field data stats for one or more indices
(See :ref:'es-guide-reference-api-admin-cluster-nodes-stats')
:keyword indices: an index or a list of indices | Below is the the instruction that describes the task:
### Input:
Retrieve the field data stats for one or more indices
(See :ref:'es-guide-reference-api-admin-cluster-nodes-stats')
:keyword indices: an index or a list of indices
### Response:
def field_stats(self, indices=''):
"""
... |
def UpsertUserDefinedFunction(self, collection_link, udf, options=None):
"""Upserts a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
... | Upserts a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
The upserted UDF.
:rtype:
dict | Below is the the instruction that describes the task:
### Input:
Upserts a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
:return:
... |
def getShutdownArgs(self):
"""return command line arguments for shutting down the
server; this command line is built from the name server
startup arguments."""
shutdownArgs = []
if self.host:
shutdownArgs += ['-h', self.host]
if self.bcport:
shutdo... | return command line arguments for shutting down the
server; this command line is built from the name server
startup arguments. | Below is the the instruction that describes the task:
### Input:
return command line arguments for shutting down the
server; this command line is built from the name server
startup arguments.
### Response:
def getShutdownArgs(self):
"""return command line arguments for shutting down the
... |
def ckinv(self,oo):
""" check the value is date or not
檢查是否為日期格式
"""
pattern = re.compile(r"[0-9]{2}/[0-9]{2}/[0-9]{2}")
b = re.search(pattern, oo[0])
try:
b.group()
return True
except:
return False | check the value is date or not
檢查是否為日期格式 | Below is the the instruction that describes the task:
### Input:
check the value is date or not
檢查是否為日期格式
### Response:
def ckinv(self,oo):
""" check the value is date or not
檢查是否為日期格式
"""
pattern = re.compile(r"[0-9]{2}/[0-9]{2}/[0-9]{2}")
b = re.search(pattern, oo[0])
try:
... |
def rows_to_dicts(self, serialize_cell=None):
"""Generates a sequence of dictionaries of {header[i] => row[i]} for each row."""
if serialize_cell is None:
serialize_cell = self.get_cell_value
# keys = [serialize_cell(cell) for cell in self.rows[0]]
keys = self.headers(serialize_cell)
for row i... | Generates a sequence of dictionaries of {header[i] => row[i]} for each row. | Below is the the instruction that describes the task:
### Input:
Generates a sequence of dictionaries of {header[i] => row[i]} for each row.
### Response:
def rows_to_dicts(self, serialize_cell=None):
"""Generates a sequence of dictionaries of {header[i] => row[i]} for each row."""
if serialize_cell is Non... |
def get_datatype(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
return self.flavour.get_datatype(self, table, column).upper() | Returns database SQL datatype for a column: e.g. VARCHAR. | Below is the the instruction that describes the task:
### Input:
Returns database SQL datatype for a column: e.g. VARCHAR.
### Response:
def get_datatype(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
return self.flavour.get_datatype(self, tab... |
def vb_wait_for_session_state(xp_session, state='Unlocked', timeout=10, step=None):
'''
Waits until a session state has been reached, checking at regular intervals.
@param xp_session:
@type xp_session: ISession from the Virtualbox API
@param state: The constant descriptor according to the docs
... | Waits until a session state has been reached, checking at regular intervals.
@param xp_session:
@type xp_session: ISession from the Virtualbox API
@param state: The constant descriptor according to the docs
@type state: str
@param timeout: in seconds
@type timeout: int | float
@param step: ... | Below is the the instruction that describes the task:
### Input:
Waits until a session state has been reached, checking at regular intervals.
@param xp_session:
@type xp_session: ISession from the Virtualbox API
@param state: The constant descriptor according to the docs
@type state: str
@param... |
def API520_SH(T1, P1):
r'''Calculates correction due to steam superheat for steam flow for use in
API 520 relief valve sizing. 2D interpolation among a table with 28
pressures and 10 temperatures is performed.
Parameters
----------
T1 : float
Temperature of the fluid entering the valve... | r'''Calculates correction due to steam superheat for steam flow for use in
API 520 relief valve sizing. 2D interpolation among a table with 28
pressures and 10 temperatures is performed.
Parameters
----------
T1 : float
Temperature of the fluid entering the valve [K]
P1 : float
... | Below is the the instruction that describes the task:
### Input:
r'''Calculates correction due to steam superheat for steam flow for use in
API 520 relief valve sizing. 2D interpolation among a table with 28
pressures and 10 temperatures is performed.
Parameters
----------
T1 : float
T... |
def get_entity_meta(self, datastream):
"""
To add entity meta data to a datastream
:param datastream: string
:param options: dict
"""
url = '/datastream/' + str(datastream) + '/entityMeta'
response = self.http.get(url)
entityMetaList = []
for entit... | To add entity meta data to a datastream
:param datastream: string
:param options: dict | Below is the the instruction that describes the task:
### Input:
To add entity meta data to a datastream
:param datastream: string
:param options: dict
### Response:
def get_entity_meta(self, datastream):
"""
To add entity meta data to a datastream
:param datastream: string
... |
def __cutline(self, oiraw):
'''对单行进行分词,这段函数包含前处理preprogress.py以及一系列后处理,将分词结果返回为一个map'''
oiraw = decode(oiraw)
vec = []
if(len(oiraw) < self.__maxLength):
vec.append(oiraw)
else:
vec = self.__cutRaw(oiraw, self.__maxLength)
ans = []
for oira... | 对单行进行分词,这段函数包含前处理preprogress.py以及一系列后处理,将分词结果返回为一个map | Below is the the instruction that describes the task:
### Input:
对单行进行分词,这段函数包含前处理preprogress.py以及一系列后处理,将分词结果返回为一个map
### Response:
def __cutline(self, oiraw):
'''对单行进行分词,这段函数包含前处理preprogress.py以及一系列后处理,将分词结果返回为一个map'''
oiraw = decode(oiraw)
vec = []
if(len(oiraw) < self.__maxLengt... |
def addup_fluxes(self):
"""Add up the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 1.0
>>> fluxes.q(2.0)
>>> model.addup_fluxes()
>>> fluxes.fastaccess._q_sum
3.0
""... | Add up the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 1.0
>>> fluxes.q(2.0)
>>> model.addup_fluxes()
>>> fluxes.fastaccess._q_sum
3.0 | Below is the the instruction that describes the task:
### Input:
Add up the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 1.0
>>> fluxes.q(2.0)
>>> model.addup_fluxes()
>>> fluxes.fastac... |
def moveTo(self, newX=0, newY=0):
"""!
\~english
Move vertex of rectangles to new point (x,y)
@param newX: Coordinated X value
@param newY: Coordinated Y value
\~chinese
移动矩形到新坐标点 (x,y)
@param newX: 坐标 X
@param newY: 坐标 Y
"""
self.... | !
\~english
Move vertex of rectangles to new point (x,y)
@param newX: Coordinated X value
@param newY: Coordinated Y value
\~chinese
移动矩形到新坐标点 (x,y)
@param newX: 坐标 X
@param newY: 坐标 Y | Below is the the instruction that describes the task:
### Input:
!
\~english
Move vertex of rectangles to new point (x,y)
@param newX: Coordinated X value
@param newY: Coordinated Y value
\~chinese
移动矩形到新坐标点 (x,y)
@param newX: 坐标 X
@param newY: 坐标 Y
#... |
def scalarcoords(self):
"""A dictionary of values that don't label any axes (point-like)."""
return {k: v.values for k, v in self.coords.items() if v.dims==()} | A dictionary of values that don't label any axes (point-like). | Below is the the instruction that describes the task:
### Input:
A dictionary of values that don't label any axes (point-like).
### Response:
def scalarcoords(self):
"""A dictionary of values that don't label any axes (point-like)."""
return {k: v.values for k, v in self.coords.items() if v.dims==(... |
def _run_single(self, thread_id, agent, environment, deterministic=False,
max_episode_timesteps=-1, episode_finished=None, testing=False, sleep=None):
"""
The target function for a thread, runs an agent and environment until signaled to stop.
Adds rewards to shared episode re... | The target function for a thread, runs an agent and environment until signaled to stop.
Adds rewards to shared episode rewards list.
Args:
thread_id (int): The ID of the thread that's running this target function.
agent (Agent): The Agent object that this particular thread uses.... | Below is the the instruction that describes the task:
### Input:
The target function for a thread, runs an agent and environment until signaled to stop.
Adds rewards to shared episode rewards list.
Args:
thread_id (int): The ID of the thread that's running this target function.
... |
def bsp_traverse_in_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.in_order` instead.
"""
_bsp_traverse(node.in_order(), callback, userData) | Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.in_order` instead. | Below is the the instruction that describes the task:
### Input:
Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.in_order` instead.
### Response:
def bsp_traverse_in_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,... |
def get_intra_edges(self, time_slice=0):
"""
Returns the intra slice edges present in the 2-TBN.
Parameter
---------
time_slice: int (whole number)
The time slice for which to get intra edges. The timeslice
should be a positive value or zero.
... | Returns the intra slice edges present in the 2-TBN.
Parameter
---------
time_slice: int (whole number)
The time slice for which to get intra edges. The timeslice
should be a positive value or zero.
Examples
--------
>>> from pgmpy.models ... | Below is the the instruction that describes the task:
### Input:
Returns the intra slice edges present in the 2-TBN.
Parameter
---------
time_slice: int (whole number)
The time slice for which to get intra edges. The timeslice
should be a positive value or ze... |
def del_register_user(self, register_user):
"""
Deletes registration object from database
:param register_user: RegisterUser object to delete
"""
try:
self.get_session.delete(register_user)
self.get_session.commit()
return True
... | Deletes registration object from database
:param register_user: RegisterUser object to delete | Below is the the instruction that describes the task:
### Input:
Deletes registration object from database
:param register_user: RegisterUser object to delete
### Response:
def del_register_user(self, register_user):
"""
Deletes registration object from database
:param... |
def _write_flush(self, fd, payload=None):
"""Write a payload to a given fd (if provided) and flush the fd."""
try:
if payload:
fd.write(ensure_binary(payload))
fd.flush()
except (IOError, OSError) as e:
# If a `Broken Pipe` is encountered during a stdio fd write, we're headless - b... | Write a payload to a given fd (if provided) and flush the fd. | Below is the the instruction that describes the task:
### Input:
Write a payload to a given fd (if provided) and flush the fd.
### Response:
def _write_flush(self, fd, payload=None):
"""Write a payload to a given fd (if provided) and flush the fd."""
try:
if payload:
fd.write(ensure_binary(pa... |
def convert(self, args, handler=None):
"""Prepare filters."""
name = args
field = attr = None
opts = ()
if isinstance(args, (list, tuple)):
name, *opts = args
if opts:
attr = opts.pop()
if opts:
field = opts.pop(... | Prepare filters. | Below is the the instruction that describes the task:
### Input:
Prepare filters.
### Response:
def convert(self, args, handler=None):
"""Prepare filters."""
name = args
field = attr = None
opts = ()
if isinstance(args, (list, tuple)):
name, *opts = args
... |
def submit(self, map, method, postfix):
'''Realiza um requisição HTTP para a networkAPI.
:param map: Dicionário com os dados para gerar o XML enviado no corpo da requisição HTTP.
:param method: Método da requisição HTTP ('GET', 'POST', 'PUT' ou 'DELETE').
:param postfix: Posfixo a ser c... | Realiza um requisição HTTP para a networkAPI.
:param map: Dicionário com os dados para gerar o XML enviado no corpo da requisição HTTP.
:param method: Método da requisição HTTP ('GET', 'POST', 'PUT' ou 'DELETE').
:param postfix: Posfixo a ser colocado na URL básica de acesso à networkAPI. Ex: /... | Below is the the instruction that describes the task:
### Input:
Realiza um requisição HTTP para a networkAPI.
:param map: Dicionário com os dados para gerar o XML enviado no corpo da requisição HTTP.
:param method: Método da requisição HTTP ('GET', 'POST', 'PUT' ou 'DELETE').
:param postfi... |
def jieba_tokenize(text, external_wordlist=False):
"""
Tokenize the given text into tokens whose word frequencies can probably
be looked up. This uses Jieba, a word-frequency-based tokenizer.
If `external_wordlist` is False, we tell Jieba to default to using
wordfreq's own Chinese wordlist, and not... | Tokenize the given text into tokens whose word frequencies can probably
be looked up. This uses Jieba, a word-frequency-based tokenizer.
If `external_wordlist` is False, we tell Jieba to default to using
wordfreq's own Chinese wordlist, and not to infer unknown words using a
hidden Markov model. This e... | Below is the the instruction that describes the task:
### Input:
Tokenize the given text into tokens whose word frequencies can probably
be looked up. This uses Jieba, a word-frequency-based tokenizer.
If `external_wordlist` is False, we tell Jieba to default to using
wordfreq's own Chinese wordlist, a... |
def get_size(self, value=None):
"""Return struct size.
Returns:
int: Returns the struct size based on inner attributes.
"""
if isinstance(value, type(self)):
return value.get_size()
return 2 + self.length | Return struct size.
Returns:
int: Returns the struct size based on inner attributes. | Below is the the instruction that describes the task:
### Input:
Return struct size.
Returns:
int: Returns the struct size based on inner attributes.
### Response:
def get_size(self, value=None):
"""Return struct size.
Returns:
int: Returns the struct size based on... |
def new(self):
# type: () -> None
'''
A method to create a new UDF Logical Volume Implementation Use.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Imple... | A method to create a new UDF Logical Volume Implementation Use.
Parameters:
None.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
A method to create a new UDF Logical Volume Implementation Use.
Parameters:
None.
Returns:
Nothing.
### Response:
def new(self):
# type: () -> None
'''
A method to create a new UDF Logical Vo... |
def set_interface_altsetting(self, interface = None, alternate_setting = None):
r"""Set the alternate setting for an interface.
When you want to use an interface and it has more than one alternate
setting, you should call this method to select the appropriate
alternate setting. If you c... | r"""Set the alternate setting for an interface.
When you want to use an interface and it has more than one alternate
setting, you should call this method to select the appropriate
alternate setting. If you call the method without one or the two
parameters, it will be selected the first ... | Below is the the instruction that describes the task:
### Input:
r"""Set the alternate setting for an interface.
When you want to use an interface and it has more than one alternate
setting, you should call this method to select the appropriate
alternate setting. If you call the method with... |
async def forget_ticket(self, request):
"""Called to forget the ticket data a request
Args:
request: aiohttp Request object.
"""
session = await get_session(request)
session.pop(self.cookie_name, '') | Called to forget the ticket data a request
Args:
request: aiohttp Request object. | Below is the the instruction that describes the task:
### Input:
Called to forget the ticket data a request
Args:
request: aiohttp Request object.
### Response:
async def forget_ticket(self, request):
"""Called to forget the ticket data a request
Args:
request: aio... |
def check_attr(self, repo_abspath, attrs):
"""
Generator that returns attributes for given paths relative to repo_abspath.
>>> g = GitArchiver.check_attr('repo_path', ['export-ignore'])
>>> next(g)
>>> attrs = g.send('relative_path')
>>> print(attrs['export-ignore'])
... | Generator that returns attributes for given paths relative to repo_abspath.
>>> g = GitArchiver.check_attr('repo_path', ['export-ignore'])
>>> next(g)
>>> attrs = g.send('relative_path')
>>> print(attrs['export-ignore'])
@param repo_abspath: Absolute path to a git repository.
... | Below is the the instruction that describes the task:
### Input:
Generator that returns attributes for given paths relative to repo_abspath.
>>> g = GitArchiver.check_attr('repo_path', ['export-ignore'])
>>> next(g)
>>> attrs = g.send('relative_path')
>>> print(attrs['export-ignore'... |
def scale(self, percent, scaleFromCenter=True):
"""scales an Image object
Parameters:
| percent - a percent of the original size
| numbers bigger than 100 scale up
| numbers less than 100 scale down
| 100 scales to the... | scales an Image object
Parameters:
| percent - a percent of the original size
| numbers bigger than 100 scale up
| numbers less than 100 scale down
| 100 scales to the original size
Optional keyword parameters:
... | Below is the the instruction that describes the task:
### Input:
scales an Image object
Parameters:
| percent - a percent of the original size
| numbers bigger than 100 scale up
| numbers less than 100 scale down
| 100 scal... |
def create_child_folder(self, name, description=None):
""" Creates a Child Folder
:param str name: the name of the new child folder
:param str description: the description of the new child folder
:return: newly created folder
:rtype: drive.Folder
"""
if not self... | Creates a Child Folder
:param str name: the name of the new child folder
:param str description: the description of the new child folder
:return: newly created folder
:rtype: drive.Folder | Below is the the instruction that describes the task:
### Input:
Creates a Child Folder
:param str name: the name of the new child folder
:param str description: the description of the new child folder
:return: newly created folder
:rtype: drive.Folder
### Response:
def create_chil... |
def error(self, msg):
"""Override/enhance default error method to display tracebacks."""
print("***", msg, file=self.stdout)
if not self.config.show_traceback_on_error:
return
etype, evalue, tb = sys.exc_info()
if tb and tb.tb_frame.f_code.co_name == "default":
... | Override/enhance default error method to display tracebacks. | Below is the the instruction that describes the task:
### Input:
Override/enhance default error method to display tracebacks.
### Response:
def error(self, msg):
"""Override/enhance default error method to display tracebacks."""
print("***", msg, file=self.stdout)
if not self.config.show_t... |
def var_quadratic_sum(A, C, H, beta, x0):
r"""
Computes the expected discounted quadratic sum
.. math::
q(x_0) = \mathbb{E} \Big[ \sum_{t=0}^{\infty} \beta^t x_t' H x_t \Big]
Here :math:`{x_t}` is the VAR process :math:`x_{t+1} = A x_t + C w_t`
with :math:`{x_t}` standard normal and :math... | r"""
Computes the expected discounted quadratic sum
.. math::
q(x_0) = \mathbb{E} \Big[ \sum_{t=0}^{\infty} \beta^t x_t' H x_t \Big]
Here :math:`{x_t}` is the VAR process :math:`x_{t+1} = A x_t + C w_t`
with :math:`{x_t}` standard normal and :math:`x_0` the initial condition.
Parameters
... | Below is the the instruction that describes the task:
### Input:
r"""
Computes the expected discounted quadratic sum
.. math::
q(x_0) = \mathbb{E} \Big[ \sum_{t=0}^{\infty} \beta^t x_t' H x_t \Big]
Here :math:`{x_t}` is the VAR process :math:`x_{t+1} = A x_t + C w_t`
with :math:`{x_t}` st... |
def _parse_doms(self):
"""Extract dom information from detector file"""
self.print("Reading PMT information...")
self._det_file.seek(0, 0)
self._readline()
pmts = defaultdict(list)
pmt_index = 0
while True:
line = self._readline()
if line ... | Extract dom information from detector file | Below is the the instruction that describes the task:
### Input:
Extract dom information from detector file
### Response:
def _parse_doms(self):
"""Extract dom information from detector file"""
self.print("Reading PMT information...")
self._det_file.seek(0, 0)
self._readline()
... |
def update_ptr_record(self, device, record, domain_name, data=None,
ttl=None, comment=None):
"""
Updates a PTR record with the supplied values.
"""
return self._manager.update_ptr_record(device, record, domain_name,
data=data, ttl=ttl, comment=comment) | Updates a PTR record with the supplied values. | Below is the the instruction that describes the task:
### Input:
Updates a PTR record with the supplied values.
### Response:
def update_ptr_record(self, device, record, domain_name, data=None,
ttl=None, comment=None):
"""
Updates a PTR record with the supplied values.
"""
... |
def load_fetched_objects_into_contexts(events, model_data, context_hints_per_source):
"""
Given the fetched model data and the context hints for each source, go through each
event and populate the contexts with the loaded information.
"""
for event in events:
context_hints = context_hints_pe... | Given the fetched model data and the context hints for each source, go through each
event and populate the contexts with the loaded information. | Below is the the instruction that describes the task:
### Input:
Given the fetched model data and the context hints for each source, go through each
event and populate the contexts with the loaded information.
### Response:
def load_fetched_objects_into_contexts(events, model_data, context_hints_per_source):
... |
def _get_num_interval(config, num_pre, num_post):
'''
Returns numerical interval based on optionals num_pre, num_post values
'''
post = int(num_post) if num_post else 0
pre = int(num_pre) if num_pre is not None else _get_last_snapshot(config)['id']
return pre, post | Returns numerical interval based on optionals num_pre, num_post values | Below is the the instruction that describes the task:
### Input:
Returns numerical interval based on optionals num_pre, num_post values
### Response:
def _get_num_interval(config, num_pre, num_post):
'''
Returns numerical interval based on optionals num_pre, num_post values
'''
post = int(num_post)... |
def get_select_sql(self, columns, order=None, limit=0, skip=0):
"""
Build a SELECT query based on the current state of the builder.
:param columns:
SQL fragment describing which columns to select i.e. 'e.obstoryID, s.statusID'
:param order:
Optional ordering cons... | Build a SELECT query based on the current state of the builder.
:param columns:
SQL fragment describing which columns to select i.e. 'e.obstoryID, s.statusID'
:param order:
Optional ordering constraint, i.e. 'e.eventTime DESC'
:param limit:
Optional, used to ... | Below is the the instruction that describes the task:
### Input:
Build a SELECT query based on the current state of the builder.
:param columns:
SQL fragment describing which columns to select i.e. 'e.obstoryID, s.statusID'
:param order:
Optional ordering constraint, i.e. 'e... |
def start_head_processes(self):
"""Start head processes on the node."""
logger.info(
"Process STDOUT and STDERR is being redirected to {}.".format(
self._logs_dir))
assert self._redis_address is None
# If this is the head node, start the relevant head node pro... | Start head processes on the node. | Below is the the instruction that describes the task:
### Input:
Start head processes on the node.
### Response:
def start_head_processes(self):
"""Start head processes on the node."""
logger.info(
"Process STDOUT and STDERR is being redirected to {}.".format(
self._logs... |
def main(args=None):
"""
Main function.
This function is the command line entry point.
Args:
args (list of str): the arguments passed to the program.
Returns:
int: return code being 0 (OK), 1 (dsm empty) or 2 (error).
"""
parser = get_parser()
args = parser.parse_args(... | Main function.
This function is the command line entry point.
Args:
args (list of str): the arguments passed to the program.
Returns:
int: return code being 0 (OK), 1 (dsm empty) or 2 (error). | Below is the the instruction that describes the task:
### Input:
Main function.
This function is the command line entry point.
Args:
args (list of str): the arguments passed to the program.
Returns:
int: return code being 0 (OK), 1 (dsm empty) or 2 (error).
### Response:
def main(arg... |
def ssim_value(self, target):
"""Compute the SSIM value from the reference image to the target image.
Args:
target (str or PIL.Image): Input image to compare the reference image
to. This may be a PIL Image object or, to save time, an SSIMImage
object (e.g. the img member o... | Compute the SSIM value from the reference image to the target image.
Args:
target (str or PIL.Image): Input image to compare the reference image
to. This may be a PIL Image object or, to save time, an SSIMImage
object (e.g. the img member of another SSIM object).
Returns:... | Below is the the instruction that describes the task:
### Input:
Compute the SSIM value from the reference image to the target image.
Args:
target (str or PIL.Image): Input image to compare the reference image
to. This may be a PIL Image object or, to save time, an SSIMImage
o... |
def create_context(self, message_queue, task_id):
"""
Create data needed by upload_project_run(DukeDS connection info).
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly
... | Create data needed by upload_project_run(DukeDS connection info).
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly | Below is the the instruction that describes the task:
### Input:
Create data needed by upload_project_run(DukeDS connection info).
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly
### R... |
def ndd_prefix_for_region(region_code, strip_non_digits):
"""Returns the national dialling prefix for a specific region.
For example, this would be 1 for the United States, and 0 for New
Zealand. Set strip_non_digits to True to strip symbols like "~" (which
indicates a wait for a dialling tone) from th... | Returns the national dialling prefix for a specific region.
For example, this would be 1 for the United States, and 0 for New
Zealand. Set strip_non_digits to True to strip symbols like "~" (which
indicates a wait for a dialling tone) from the prefix returned. If no
national prefix is present, we retur... | Below is the the instruction that describes the task:
### Input:
Returns the national dialling prefix for a specific region.
For example, this would be 1 for the United States, and 0 for New
Zealand. Set strip_non_digits to True to strip symbols like "~" (which
indicates a wait for a dialling tone) fro... |
def fcsp_sa_fcsp_auth_policy_switch(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth")
fcsp = ET.SubElement(fcsp_sa, "fcsp")
auth = ET.SubElement(fcsp, "auth")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcsp_sa_fcsp_auth_policy_switch(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:bro... |
def create_subnet(context, subnet):
"""Create a subnet.
Create a subnet which represents a range of IP addresses
that can be allocated to devices
: param context: neutron api request context
: param subnet: dictionary describing the subnet, with keys
as listed in the RESOURCE_ATTRIBUTE_MAP... | Create a subnet.
Create a subnet which represents a range of IP addresses
that can be allocated to devices
: param context: neutron api request context
: param subnet: dictionary describing the subnet, with keys
as listed in the RESOURCE_ATTRIBUTE_MAP object in
neutron/api/v2/attribute... | Below is the the instruction that describes the task:
### Input:
Create a subnet.
Create a subnet which represents a range of IP addresses
that can be allocated to devices
: param context: neutron api request context
: param subnet: dictionary describing the subnet, with keys
as listed in ... |
def get_autoscaling_group_properties(asg_client, env, service):
"""
Gets the autoscaling group properties based on the service name that is provided. This function will attempt the find
the autoscaling group base on the following logic:
1. If the service name provided matches the autoscaling group name
2.... | Gets the autoscaling group properties based on the service name that is provided. This function will attempt the find
the autoscaling group base on the following logic:
1. If the service name provided matches the autoscaling group name
2. If the service name provided matches the Name tag of the autoscaling gr... | Below is the the instruction that describes the task:
### Input:
Gets the autoscaling group properties based on the service name that is provided. This function will attempt the find
the autoscaling group base on the following logic:
1. If the service name provided matches the autoscaling group name
2. If... |
def register_bjam_action (self, action_name, function=None):
"""Informs self that 'action_name' is declared in bjam.
From this point, 'action_name' is a valid argument to the
set_update_action method. The action_name should be callable
in the global module of bjam.
"""
... | Informs self that 'action_name' is declared in bjam.
From this point, 'action_name' is a valid argument to the
set_update_action method. The action_name should be callable
in the global module of bjam. | Below is the the instruction that describes the task:
### Input:
Informs self that 'action_name' is declared in bjam.
From this point, 'action_name' is a valid argument to the
set_update_action method. The action_name should be callable
in the global module of bjam.
### Response:
def regis... |
def info(self):
"""
tuple of the start_pc, end_pc, handler_pc and catch_type_ref
"""
return (self.start_pc, self.end_pc,
self.handler_pc, self.get_catch_type()) | tuple of the start_pc, end_pc, handler_pc and catch_type_ref | Below is the the instruction that describes the task:
### Input:
tuple of the start_pc, end_pc, handler_pc and catch_type_ref
### Response:
def info(self):
"""
tuple of the start_pc, end_pc, handler_pc and catch_type_ref
"""
return (self.start_pc, self.end_pc,
self.... |
def parse_csv_header(line):
"""Parse the CSV header returned by TDS."""
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
names.append(str(var))
continue
else:
names.append(str(var[:start]))
end = var... | Parse the CSV header returned by TDS. | Below is the the instruction that describes the task:
### Input:
Parse the CSV header returned by TDS.
### Response:
def parse_csv_header(line):
"""Parse the CSV header returned by TDS."""
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
... |
def timespan(self, from_date, to_date=None, span=None, current=False):
"""
Takes a beginning date a filters entries. An optional to_date can be
specified, or a span, which is one of ('month', 'week', 'day').
N.B. - If given a to_date, it does not include that date, only before.
"... | Takes a beginning date a filters entries. An optional to_date can be
specified, or a span, which is one of ('month', 'week', 'day').
N.B. - If given a to_date, it does not include that date, only before. | Below is the the instruction that describes the task:
### Input:
Takes a beginning date a filters entries. An optional to_date can be
specified, or a span, which is one of ('month', 'week', 'day').
N.B. - If given a to_date, it does not include that date, only before.
### Response:
def timespan(sel... |
def write_chunks(self, data, start, step, count) -> None:
'''
Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step ... | Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets. | Below is the the instruction that describes the task:
### Input:
Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset... |
def advance_robots(self):
'''Produces a new game state in which the robots have advanced
towards the player by one step. Handles the robots crashing into
one another too.'''
# move the robots towards the player
self = lens.robots.Each().call_step_towards(self.player)(self)
... | Produces a new game state in which the robots have advanced
towards the player by one step. Handles the robots crashing into
one another too. | Below is the the instruction that describes the task:
### Input:
Produces a new game state in which the robots have advanced
towards the player by one step. Handles the robots crashing into
one another too.
### Response:
def advance_robots(self):
'''Produces a new game state in which the ro... |
def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs
if p.key not in ('contents', 'dataset')}
d['modified_datetime'] = self.modified_datetime
... | A dict that holds key/values for all of the properties in the
object.
:return: | Below is the the instruction that describes the task:
### Input:
A dict that holds key/values for all of the properties in the
object.
:return:
### Response:
def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
... |
def extractLargestRegion(actor):
"""Keep only the largest connected part of a mesh and discard all the smaller pieces.
.. hint:: |largestregion.py|_
"""
conn = vtk.vtkConnectivityFilter()
conn.SetExtractionModeToLargestRegion()
conn.ScalarConnectivityOff()
poly = actor.GetMapper().GetInput(... | Keep only the largest connected part of a mesh and discard all the smaller pieces.
.. hint:: |largestregion.py|_ | Below is the the instruction that describes the task:
### Input:
Keep only the largest connected part of a mesh and discard all the smaller pieces.
.. hint:: |largestregion.py|_
### Response:
def extractLargestRegion(actor):
"""Keep only the largest connected part of a mesh and discard all the smaller pie... |
def _install(self, name, autoinstall):
'''Check existence of Python module and install it using command
pip install if necessary.'''
import importlib
import pkg_resources
spam_spec = importlib.util.find_spec(name)
reinstall = False
if spam_spec is not None:
... | Check existence of Python module and install it using command
pip install if necessary. | Below is the the instruction that describes the task:
### Input:
Check existence of Python module and install it using command
pip install if necessary.
### Response:
def _install(self, name, autoinstall):
'''Check existence of Python module and install it using command
pip install if neces... |
def _get_referenced_apps(specs):
"""
Returns a set of all apps that are required to run any bundle in specs[constants.CONFIG_BUNDLES_KEY]
"""
activated_bundles = specs[constants.CONFIG_BUNDLES_KEY].keys()
all_active_apps = set()
for active_bundle in activated_bundles:
bundle_spec = specs... | Returns a set of all apps that are required to run any bundle in specs[constants.CONFIG_BUNDLES_KEY] | Below is the the instruction that describes the task:
### Input:
Returns a set of all apps that are required to run any bundle in specs[constants.CONFIG_BUNDLES_KEY]
### Response:
def _get_referenced_apps(specs):
"""
Returns a set of all apps that are required to run any bundle in specs[constants.CONFIG_BU... |
def get_j_ty_callback(self):
""" Generates a callback for evaluating the jacobian. """
j_exprs = self.get_jac()
if j_exprs is False:
return None
cb = self._callback_factory(j_exprs)
if self.sparse:
from scipy.sparse import csc_matrix
def spars... | Generates a callback for evaluating the jacobian. | Below is the the instruction that describes the task:
### Input:
Generates a callback for evaluating the jacobian.
### Response:
def get_j_ty_callback(self):
""" Generates a callback for evaluating the jacobian. """
j_exprs = self.get_jac()
if j_exprs is False:
return None
... |
def device_id(self):
"""
Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`.
"""
if self.is_block:
for filename in self._P.Block.Symlinks:
parts = decode_ay... | Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`. | Below is the the instruction that describes the task:
### Input:
Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`.
### Response:
def device_id(self):
"""
Return a unique and persistent identifi... |
def unescape_quoted_string(string):
r'''
This function implementes the recommended functionality described in the
tor control-spec to be compatible with older tor versions:
* Read \\n \\t \\r and \\0 ... \\377 as C escapes.
* Treat a backslash followed by any other character as that character.
... | r'''
This function implementes the recommended functionality described in the
tor control-spec to be compatible with older tor versions:
* Read \\n \\t \\r and \\0 ... \\377 as C escapes.
* Treat a backslash followed by any other character as that character.
Except the legacy support for the e... | Below is the the instruction that describes the task:
### Input:
r'''
This function implementes the recommended functionality described in the
tor control-spec to be compatible with older tor versions:
* Read \\n \\t \\r and \\0 ... \\377 as C escapes.
* Treat a backslash followed by any other ... |
def _flatten_ex_dict(self):
"""Flatten structure of exceptions dictionary."""
odict = {}
for _, fdict in self._ex_dict.items():
for (extype, exmsg), value in fdict.items():
key = value["name"]
odict[key] = copy.deepcopy(value)
del odict... | Flatten structure of exceptions dictionary. | Below is the the instruction that describes the task:
### Input:
Flatten structure of exceptions dictionary.
### Response:
def _flatten_ex_dict(self):
"""Flatten structure of exceptions dictionary."""
odict = {}
for _, fdict in self._ex_dict.items():
for (extype, exmsg), value i... |
def _generate_examples(self, file_path):
"""Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target
"""
with tf.io.gfile.GFile(file_path) as f:
raw_data = csv.DictReader(f)
for row in raw... | Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target | Below is the the instruction that describes the task:
### Input:
Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target
### Response:
def _generate_examples(self, file_path):
"""Generate features and ta... |
def server_online(self):
"""
Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode.
"""
response = self._post(self.apiurl + '/v2/server/online', data={'apikey': self.apikey})
return self._raise_or_extract(response) | Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode. | Below is the the instruction that describes the task:
### Input:
Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode.
### Response:
def server_online(self):
"""
Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode.
... |
def set_editor(self, editor, refresh=True):
"""
Set associated editor/web page:
codeeditor.base.TextEditBaseWidget
browser.WebView
"""
self.editor = editor
# Note: This is necessary to test widgets/editor.py
# in Qt builds that don't have w... | Set associated editor/web page:
codeeditor.base.TextEditBaseWidget
browser.WebView | Below is the the instruction that describes the task:
### Input:
Set associated editor/web page:
codeeditor.base.TextEditBaseWidget
browser.WebView
### Response:
def set_editor(self, editor, refresh=True):
"""
Set associated editor/web page:
codeeditor.base.... |
def _data_build(self, data, modname, path):
"""Build tree node from data and add some informations"""
try:
node = _parse(data + "\n")
except (TypeError, ValueError, SyntaxError) as exc:
raise exceptions.AstroidSyntaxError(
"Parsing Python code failed:\n{er... | Build tree node from data and add some informations | Below is the the instruction that describes the task:
### Input:
Build tree node from data and add some informations
### Response:
def _data_build(self, data, modname, path):
"""Build tree node from data and add some informations"""
try:
node = _parse(data + "\n")
except (TypeEr... |
def rename_nodes(self, renaming_map):
'''Rename nodes in this ``Tree``
Args:
``renaming_map`` (``dict``): A dictionary mapping old labels (keys) to new labels (values)
'''
if not isinstance(renaming_map, dict):
raise TypeError("renaming_map must be a dict")
... | Rename nodes in this ``Tree``
Args:
``renaming_map`` (``dict``): A dictionary mapping old labels (keys) to new labels (values) | Below is the the instruction that describes the task:
### Input:
Rename nodes in this ``Tree``
Args:
``renaming_map`` (``dict``): A dictionary mapping old labels (keys) to new labels (values)
### Response:
def rename_nodes(self, renaming_map):
'''Rename nodes in this ``Tree``
... |
def verify_declared_bit(self, obj):
"""Verify a qubit id against the gate prototype."""
# We are verifying gate args against the formal parameters of a
# gate prototype.
if obj.name not in self.current_symtab:
raise QasmError("Cannot find symbol '" + obj.name
... | Verify a qubit id against the gate prototype. | Below is the the instruction that describes the task:
### Input:
Verify a qubit id against the gate prototype.
### Response:
def verify_declared_bit(self, obj):
"""Verify a qubit id against the gate prototype."""
# We are verifying gate args against the formal parameters of a
# gate prototy... |
def hydrophobic_interactions(atom_set_a, atom_set_b):
"""Detection of hydrophobic pliprofiler between atom_set_a (binding site) and atom_set_b (ligand).
Definition: All pairs of qualified carbon atoms within a distance of HYDROPH_DIST_MAX
"""
data = namedtuple('hydroph_interaction', 'bsatom bsatom_orig_... | Detection of hydrophobic pliprofiler between atom_set_a (binding site) and atom_set_b (ligand).
Definition: All pairs of qualified carbon atoms within a distance of HYDROPH_DIST_MAX | Below is the the instruction that describes the task:
### Input:
Detection of hydrophobic pliprofiler between atom_set_a (binding site) and atom_set_b (ligand).
Definition: All pairs of qualified carbon atoms within a distance of HYDROPH_DIST_MAX
### Response:
def hydrophobic_interactions(atom_set_a, atom_set_... |
def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probab... | Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probably be "rolling" at
any given ... | Below is the the instruction that describes the task:
### Input:
Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch ... |
def evolve(self, rho: Density) -> Density:
"""Apply the action of this channel upon a density"""
N = rho.qubit_nb
qubits = rho.qubits
indices = list([qubits.index(q) for q in self.qubits]) + \
list([qubits.index(q) + N for q in self.qubits])
tensor = bk.tensormul(se... | Apply the action of this channel upon a density | Below is the the instruction that describes the task:
### Input:
Apply the action of this channel upon a density
### Response:
def evolve(self, rho: Density) -> Density:
"""Apply the action of this channel upon a density"""
N = rho.qubit_nb
qubits = rho.qubits
indices = list([qubit... |
def write(self):
""" Writes generated presentation code into the destination file.
"""
html = self.render()
if self.file_type == 'pdf':
self.write_pdf(html)
else:
with codecs.open(self.destination_file, 'w',
encoding='utf_8') ... | Writes generated presentation code into the destination file. | Below is the the instruction that describes the task:
### Input:
Writes generated presentation code into the destination file.
### Response:
def write(self):
""" Writes generated presentation code into the destination file.
"""
html = self.render()
if self.file_type == 'pdf':
... |
def generate_adhoc_ssl_context():
"""Generates an adhoc SSL context for the development server."""
crypto = _get_openssl_crypto_module()
import tempfile
import atexit
cert, pkey = generate_adhoc_ssl_pair()
cert_handle, cert_file = tempfile.mkstemp()
pkey_handle, pkey_file = tempfile.mkstemp... | Generates an adhoc SSL context for the development server. | Below is the the instruction that describes the task:
### Input:
Generates an adhoc SSL context for the development server.
### Response:
def generate_adhoc_ssl_context():
"""Generates an adhoc SSL context for the development server."""
crypto = _get_openssl_crypto_module()
import tempfile
import a... |
def approxEqual(x, y, *args, **kwargs):
"""approxEqual(float1, float2[, tol=1e-18, rel=1e-7]) -> True|False
approxEqual(obj1, obj2[, *args, **kwargs]) -> True|False
Return True if x and y are approximately equal, otherwise False.
If x and y are floats, return True if y is within either absolute error
... | approxEqual(float1, float2[, tol=1e-18, rel=1e-7]) -> True|False
approxEqual(obj1, obj2[, *args, **kwargs]) -> True|False
Return True if x and y are approximately equal, otherwise False.
If x and y are floats, return True if y is within either absolute error
tol or relative error rel of x. You can dis... | Below is the the instruction that describes the task:
### Input:
approxEqual(float1, float2[, tol=1e-18, rel=1e-7]) -> True|False
approxEqual(obj1, obj2[, *args, **kwargs]) -> True|False
Return True if x and y are approximately equal, otherwise False.
If x and y are floats, return True if y is within ... |
def _run__cherrypy(app, config, mode):
"""Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed."""
assert mode == "cherrypy-wsgiserver"
try:
from cherrypy import wsgiserver
from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter
_logger.warning("WARNING: cherrypy.ws... | Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed. | Below is the the instruction that describes the task:
### Input:
Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed.
### Response:
def _run__cherrypy(app, config, mode):
"""Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed."""
assert mode == "cherrypy-wsgiserver"
try:
... |
def _wrap(self, value, priority=0):
"""
Given a function/method, this will automatically wrap a method using
weakref to avoid circular references.
"""
if not callable(value):
raise TypeError("Only callable values can be stored in CallbackContainer")
elif sel... | Given a function/method, this will automatically wrap a method using
weakref to avoid circular references. | Below is the the instruction that describes the task:
### Input:
Given a function/method, this will automatically wrap a method using
weakref to avoid circular references.
### Response:
def _wrap(self, value, priority=0):
"""
Given a function/method, this will automatically wrap a method us... |
def letterSequence(letters, w=40):
"""
Return a list of input vectors corresponding to sequence of letters.
The vector for each letter has w contiguous bits ON and represented as a
sequence of non-zero indices.
"""
sequence = []
for letter in letters:
i = ord(letter) - ord('A')
sequence.append(set... | Return a list of input vectors corresponding to sequence of letters.
The vector for each letter has w contiguous bits ON and represented as a
sequence of non-zero indices. | Below is the the instruction that describes the task:
### Input:
Return a list of input vectors corresponding to sequence of letters.
The vector for each letter has w contiguous bits ON and represented as a
sequence of non-zero indices.
### Response:
def letterSequence(letters, w=40):
"""
Return a list of ... |
def scan_directory(self, dirname, exclude_exts=(), exclude_fnames=()):
"""
Analyze the files contained in directory dirname.
Args:
dirname: directory path
exclude_exts: list of file extensions that should be skipped.
exclude_fnames: list of file names that sh... | Analyze the files contained in directory dirname.
Args:
dirname: directory path
exclude_exts: list of file extensions that should be skipped.
exclude_fnames: list of file names that should be skipped.
Returns:
List of pseudopotential objects. | Below is the the instruction that describes the task:
### Input:
Analyze the files contained in directory dirname.
Args:
dirname: directory path
exclude_exts: list of file extensions that should be skipped.
exclude_fnames: list of file names that should be skipped.
... |
def append(self, item):
"""Append `item` (:class:`StyledText` or :class:`str`) to the end of
this mixed-styled text.
The parent of `item` is set to this mixed-styled text."""
if isinstance(item, str):
item = SingleStyledText(item)
item.parent = self
list.appe... | Append `item` (:class:`StyledText` or :class:`str`) to the end of
this mixed-styled text.
The parent of `item` is set to this mixed-styled text. | Below is the the instruction that describes the task:
### Input:
Append `item` (:class:`StyledText` or :class:`str`) to the end of
this mixed-styled text.
The parent of `item` is set to this mixed-styled text.
### Response:
def append(self, item):
"""Append `item` (:class:`StyledText` or :... |
def upload_module(self, local_path=None, remote_path="/tmp/lime.ko"):
"""
Upload LiME kernel module to remote host
:type local_path: str
:param local_path: local path to lime kernel module
:type remote_path: str
:param remote_path: remote path to upload lime kernel modul... | Upload LiME kernel module to remote host
:type local_path: str
:param local_path: local path to lime kernel module
:type remote_path: str
:param remote_path: remote path to upload lime kernel module | Below is the the instruction that describes the task:
### Input:
Upload LiME kernel module to remote host
:type local_path: str
:param local_path: local path to lime kernel module
:type remote_path: str
:param remote_path: remote path to upload lime kernel module
### Response:
def ... |
def validate_supported_property_type_id(property_name, property_type_id):
"""Ensure that the given property type_id is supported by the graph."""
if property_type_id not in PROPERTY_TYPE_ID_TO_NAME:
raise AssertionError(u'Property "{}" has unsupported property type id: '
u'{... | Ensure that the given property type_id is supported by the graph. | Below is the the instruction that describes the task:
### Input:
Ensure that the given property type_id is supported by the graph.
### Response:
def validate_supported_property_type_id(property_name, property_type_id):
"""Ensure that the given property type_id is supported by the graph."""
if property_type... |
def cart_modify(self, items, CartId=None, HMAC=None, **kwargs):
"""CartAdd.
:param items:
A dictionary containing the items to be added to the cart.
Or a list containing these dictionaries.
example: [{'cart_item_id': 'rt2ofih3f389nwiuhf8934z87o3f4h',
'quan... | CartAdd.
:param items:
A dictionary containing the items to be added to the cart.
Or a list containing these dictionaries.
example: [{'cart_item_id': 'rt2ofih3f389nwiuhf8934z87o3f4h',
'quantity': 1}]
:param CartId: Id of Cart
:param HMAC: HMAC of C... | Below is the the instruction that describes the task:
### Input:
CartAdd.
:param items:
A dictionary containing the items to be added to the cart.
Or a list containing these dictionaries.
example: [{'cart_item_id': 'rt2ofih3f389nwiuhf8934z87o3f4h',
'quantity':... |
def send_message(self, author, content):
"""发送私信给一个用户
:param Author author: 接收私信用户对象
:param string content: 发送给用户的私信内容
:return: 成功返回 True,失败返回 False
:rtype: bool
"""
if isinstance(author, Author) is False:
raise ValueError('argument answer need to be ... | 发送私信给一个用户
:param Author author: 接收私信用户对象
:param string content: 发送给用户的私信内容
:return: 成功返回 True,失败返回 False
:rtype: bool | Below is the the instruction that describes the task:
### Input:
发送私信给一个用户
:param Author author: 接收私信用户对象
:param string content: 发送给用户的私信内容
:return: 成功返回 True,失败返回 False
:rtype: bool
### Response:
def send_message(self, author, content):
"""发送私信给一个用户
:param Author ... |
def lambdanu_to_Rz(l,n,ac=5.,Delta=1.):
"""
NAME:
lambdanu_to_Rz
PURPOSE:
calculate galactocentric cylindrical coordinates (R,z)
from prolate spheroidal coordinates (lambda,nu),
cf. eq. (2.2) in Dejonghe & de Zeeuw (1988a)
INPUT:
l - prolate spheroidal co... | NAME:
lambdanu_to_Rz
PURPOSE:
calculate galactocentric cylindrical coordinates (R,z)
from prolate spheroidal coordinates (lambda,nu),
cf. eq. (2.2) in Dejonghe & de Zeeuw (1988a)
INPUT:
l - prolate spheroidal coordinate lambda
n - prolate spheroidal c... | Below is the the instruction that describes the task:
### Input:
NAME:
lambdanu_to_Rz
PURPOSE:
calculate galactocentric cylindrical coordinates (R,z)
from prolate spheroidal coordinates (lambda,nu),
cf. eq. (2.2) in Dejonghe & de Zeeuw (1988a)
INPUT:
l - prol... |
def TENSES(self):
""" Yields a list of tenses for this language, excluding negations.
Each tense is a (tense, person, number, mood, aspect)-tuple.
"""
a = set(TENSES[id] for id in self._format)
a = a.union(set(TENSES[id] for id in self._default.keys()))
a = a.union(se... | Yields a list of tenses for this language, excluding negations.
Each tense is a (tense, person, number, mood, aspect)-tuple. | Below is the the instruction that describes the task:
### Input:
Yields a list of tenses for this language, excluding negations.
Each tense is a (tense, person, number, mood, aspect)-tuple.
### Response:
def TENSES(self):
""" Yields a list of tenses for this language, excluding negations.
... |
def save_asset(self, asset_form, *args, **kwargs):
"""Pass through to provider AssetAdminSession.update_asset"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if asset_form.is_for_update():
return self.update_asset(asset_form, ... | Pass through to provider AssetAdminSession.update_asset | Below is the the instruction that describes the task:
### Input:
Pass through to provider AssetAdminSession.update_asset
### Response:
def save_asset(self, asset_form, *args, **kwargs):
"""Pass through to provider AssetAdminSession.update_asset"""
# Implemented from kitosid template for -
#... |
def build_model(self, n_features, regtype='none'):
"""Build the Restricted Boltzmann Machine model in TensorFlow.
:param n_features: number of features
:param regtype: regularization type
:return: self
"""
self._create_placeholders(n_features)
self._create_variab... | Build the Restricted Boltzmann Machine model in TensorFlow.
:param n_features: number of features
:param regtype: regularization type
:return: self | Below is the the instruction that describes the task:
### Input:
Build the Restricted Boltzmann Machine model in TensorFlow.
:param n_features: number of features
:param regtype: regularization type
:return: self
### Response:
def build_model(self, n_features, regtype='none'):
"""B... |
def addCases(self, tupesValStmnts):
"""
Add multiple case statements from iterable of tuleles
(caseVal, statements)
"""
s = self
for val, statements in tupesValStmnts:
s = s.Case(val, statements)
return s | Add multiple case statements from iterable of tuleles
(caseVal, statements) | Below is the the instruction that describes the task:
### Input:
Add multiple case statements from iterable of tuleles
(caseVal, statements)
### Response:
def addCases(self, tupesValStmnts):
"""
Add multiple case statements from iterable of tuleles
(caseVal, statements)
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.