code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def comment_sync(self, comment):
"""Update comments to host and notify subscribers"""
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment) | Update comments to host and notify subscribers | Below is the the instruction that describes the task:
### Input:
Update comments to host and notify subscribers
### Response:
def comment_sync(self, comment):
"""Update comments to host and notify subscribers"""
self.host.update(key="comment", value=comment)
self.host.emit("commented", comm... |
def calcTm(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50,
max_nn_length=60, tm_method='santalucia',
salt_corrections_method='santalucia'):
''' Calculate the melting temperature (Tm) of a DNA sequence.
Note that NN thermodynamics will be used to calculate the Tm of sequences
u... | Calculate the melting temperature (Tm) of a DNA sequence.
Note that NN thermodynamics will be used to calculate the Tm of sequences
up to 60 bp in length, after which point the following formula will be
used::
Tm = 81.5 + 16.6(log10([mv_conc])) + 0.41(%GC) - 600/length
Args:
seq (str)... | Below is the the instruction that describes the task:
### Input:
Calculate the melting temperature (Tm) of a DNA sequence.
Note that NN thermodynamics will be used to calculate the Tm of sequences
up to 60 bp in length, after which point the following formula will be
used::
Tm = 81.5 + 16.6(lo... |
def attach_log_stream(self):
"""A log stream can only be attached if the container uses a json-file
log driver.
"""
if self.has_api_logs:
self.log_stream = self.attach(stdout=True, stderr=True, stream=True) | A log stream can only be attached if the container uses a json-file
log driver. | Below is the the instruction that describes the task:
### Input:
A log stream can only be attached if the container uses a json-file
log driver.
### Response:
def attach_log_stream(self):
"""A log stream can only be attached if the container uses a json-file
log driver.
"""
... |
def havespace(self, scriptname, scriptsize):
"""Ask for available space.
See MANAGESIEVE specifications, section 2.5
:param scriptname: script's name
:param scriptsize: script's size
:rtype: boolean
"""
code, data = self.__send_command(
"HAVESPACE", ... | Ask for available space.
See MANAGESIEVE specifications, section 2.5
:param scriptname: script's name
:param scriptsize: script's size
:rtype: boolean | Below is the the instruction that describes the task:
### Input:
Ask for available space.
See MANAGESIEVE specifications, section 2.5
:param scriptname: script's name
:param scriptsize: script's size
:rtype: boolean
### Response:
def havespace(self, scriptname, scriptsize):
... |
def get_export(
self,
export_type,
generate=False,
wait=False,
wait_timeout=None,
):
"""
Downloads a data export over HTTP. Returns a `Requests Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`_
object containing the ... | Downloads a data export over HTTP. Returns a `Requests Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`_
object containing the content of the export.
- **export_type** is a string specifying which type of export should be
downloaded.
- **generate** ... | Below is the the instruction that describes the task:
### Input:
Downloads a data export over HTTP. Returns a `Requests Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`_
object containing the content of the export.
- **export_type** is a string specifying which t... |
def hasUserAddEditPermission(self):
"""
Checks if the current user has privileges to access to the editing view.
From Jira LIMS-1549:
- Creation/Edit: Lab manager, Client Contact, Lab Clerk, Client Contact (for Client-specific SRTs)
:returns: True/False
"""
mto... | Checks if the current user has privileges to access to the editing view.
From Jira LIMS-1549:
- Creation/Edit: Lab manager, Client Contact, Lab Clerk, Client Contact (for Client-specific SRTs)
:returns: True/False | Below is the the instruction that describes the task:
### Input:
Checks if the current user has privileges to access to the editing view.
From Jira LIMS-1549:
- Creation/Edit: Lab manager, Client Contact, Lab Clerk, Client Contact (for Client-specific SRTs)
:returns: True/False
### Respon... |
def from_clause(cls, clause):
""" Factory method """
fn_name = clause[0]
if fn_name == "size":
return SizeConstraint.from_clause(clause)
elif fn_name == "attribute_type":
return TypeConstraint.from_clause(clause)
else:
fn_name = clause[0]
... | Factory method | Below is the the instruction that describes the task:
### Input:
Factory method
### Response:
def from_clause(cls, clause):
""" Factory method """
fn_name = clause[0]
if fn_name == "size":
return SizeConstraint.from_clause(clause)
elif fn_name == "attribute_type":
... |
def track_request(self, name, url, success, start_time=None, duration=None, response_code=None, http_method=None, properties=None, measurements=None, request_id=None):
"""Sends a single request that was captured for the application.
Args:
name (str). the name for this request. All requests ... | Sends a single request that was captured for the application.
Args:
name (str). the name for this request. All requests with the same name will be grouped together.\n
url (str). the actual URL for this request (to show in individual request instances).\n
success (bool). true... | Below is the the instruction that describes the task:
### Input:
Sends a single request that was captured for the application.
Args:
name (str). the name for this request. All requests with the same name will be grouped together.\n
url (str). the actual URL for this request (to show... |
def _srn_store_single_run(self, traj,
recursive=True,
store_data=pypetconstants.STORE_DATA,
max_depth=None):
""" Stores a single run instance to disk (only meta data)"""
if store_data != pypetconstants.STORE_NOTHI... | Stores a single run instance to disk (only meta data) | Below is the the instruction that describes the task:
### Input:
Stores a single run instance to disk (only meta data)
### Response:
def _srn_store_single_run(self, traj,
recursive=True,
store_data=pypetconstants.STORE_DATA,
... |
def date_director(**kwargs):
"""Direct which class should be used based on the date qualifier
or if the date should be converted at all.
"""
# If the date is a creation date, return the element object.
if kwargs.get('qualifier') == 'creation':
return ETD_MSDate(content=kwargs.get('content').... | Direct which class should be used based on the date qualifier
or if the date should be converted at all. | Below is the the instruction that describes the task:
### Input:
Direct which class should be used based on the date qualifier
or if the date should be converted at all.
### Response:
def date_director(**kwargs):
"""Direct which class should be used based on the date qualifier
or if the date should be ... |
def load(self, stream):
""" Load properties from an open file stream """
# For the time being only accept file input streams
if not _is_file(stream):
raise TypeError('Argument should be a file object!')
# Check for the opened mode
if stream.mode != 'r':
r... | Load properties from an open file stream | Below is the the instruction that describes the task:
### Input:
Load properties from an open file stream
### Response:
def load(self, stream):
""" Load properties from an open file stream """
# For the time being only accept file input streams
if not _is_file(stream):
raise Ty... |
def get(self):
"""
Parse a response into string format and clear out its temporary containers
:return: The parsed response message
:rtype : str
"""
self._log.debug('Converting Response object to string format')
response = ''.join(map(str, self._response)).strip()
... | Parse a response into string format and clear out its temporary containers
:return: The parsed response message
:rtype : str | Below is the the instruction that describes the task:
### Input:
Parse a response into string format and clear out its temporary containers
:return: The parsed response message
:rtype : str
### Response:
def get(self):
"""
Parse a response into string format and clear out its tempor... |
def set_goterm(self, go2obj):
"""Set goterm and copy GOTerm's name and namespace."""
if self.GO in go2obj:
goterm = go2obj[self.GO]
self.goterm = goterm
self.name = goterm.name
self.depth = goterm.depth
self.NS = self.namespace2NS[self.goterm.n... | Set goterm and copy GOTerm's name and namespace. | Below is the the instruction that describes the task:
### Input:
Set goterm and copy GOTerm's name and namespace.
### Response:
def set_goterm(self, go2obj):
"""Set goterm and copy GOTerm's name and namespace."""
if self.GO in go2obj:
goterm = go2obj[self.GO]
self.goterm = g... |
def dependencies(self, name=None, prefix=None, pkgs=None, channels=None,
dep=True):
"""Get dependenciy list for packages to be installed in an env."""
if not pkgs or not isinstance(pkgs, (list, tuple)):
raise TypeError('must specify a list of one or more packages to '
... | Get dependenciy list for packages to be installed in an env. | Below is the the instruction that describes the task:
### Input:
Get dependenciy list for packages to be installed in an env.
### Response:
def dependencies(self, name=None, prefix=None, pkgs=None, channels=None,
dep=True):
"""Get dependenciy list for packages to be installed in an env... |
def migrate_tables(tables, engine_name=None):
"""
Used to migrate dynamic table to database
:param tables: tables name list, such as ['user']
"""
from alembic.migration import MigrationContext
engine = engine_manager[engine_name]
mc = MigrationContext.configure(engine.session().connection)
... | Used to migrate dynamic table to database
:param tables: tables name list, such as ['user'] | Below is the the instruction that describes the task:
### Input:
Used to migrate dynamic table to database
:param tables: tables name list, such as ['user']
### Response:
def migrate_tables(tables, engine_name=None):
"""
Used to migrate dynamic table to database
:param tables: tables name list, suc... |
def get_content(self, r):
"""Abstraction for grabbing content from a returned response"""
if self.type == 'exp_file':
# don't use the decoded r.text
return r.content
elif self.type == 'version':
return r.content
else:
if self.fmt == 'json':... | Abstraction for grabbing content from a returned response | Below is the the instruction that describes the task:
### Input:
Abstraction for grabbing content from a returned response
### Response:
def get_content(self, r):
"""Abstraction for grabbing content from a returned response"""
if self.type == 'exp_file':
# don't use the decoded r.text
... |
def encode_nibbles(nibbles):
"""
The Hex Prefix function
"""
if is_nibbles_terminated(nibbles):
flag = HP_FLAG_2
else:
flag = HP_FLAG_0
raw_nibbles = remove_nibbles_terminator(nibbles)
is_odd = len(raw_nibbles) % 2
if is_odd:
flagged_nibbles = tuple(itertools.c... | The Hex Prefix function | Below is the the instruction that describes the task:
### Input:
The Hex Prefix function
### Response:
def encode_nibbles(nibbles):
"""
The Hex Prefix function
"""
if is_nibbles_terminated(nibbles):
flag = HP_FLAG_2
else:
flag = HP_FLAG_0
raw_nibbles = remove_nibbles_termin... |
def conditional_probability_alive(self, frequency, recency, T):
"""
Compute conditional probability alive.
Compute the probability that a customer with history
(frequency, recency, T) is currently alive.
From http://www.brucehardie.com/notes/021/palive_for_BGNBD.pdf
Pa... | Compute conditional probability alive.
Compute the probability that a customer with history
(frequency, recency, T) is currently alive.
From http://www.brucehardie.com/notes/021/palive_for_BGNBD.pdf
Parameters
----------
frequency: array or scalar
historica... | Below is the the instruction that describes the task:
### Input:
Compute conditional probability alive.
Compute the probability that a customer with history
(frequency, recency, T) is currently alive.
From http://www.brucehardie.com/notes/021/palive_for_BGNBD.pdf
Parameters
... |
def replace_gist_tags(generator):
"""Replace gist tags in the article content."""
from jinja2 import Template
template = Template(gist_template)
should_cache = generator.context.get('GIST_CACHE_ENABLED')
cache_location = generator.context.get('GIST_CACHE_LOCATION')
pygments_style = generator.co... | Replace gist tags in the article content. | Below is the the instruction that describes the task:
### Input:
Replace gist tags in the article content.
### Response:
def replace_gist_tags(generator):
"""Replace gist tags in the article content."""
from jinja2 import Template
template = Template(gist_template)
should_cache = generator.context... |
def _sample_item(self, **kwargs):
"""Sample an item from the pool according to the instrumental
distribution
"""
loc = np.random.choice(self._n_items, p = self._inst_pmf)
weight = (1/self._n_items)/self._inst_pmf[loc]
return loc, weight, {} | Sample an item from the pool according to the instrumental
distribution | Below is the the instruction that describes the task:
### Input:
Sample an item from the pool according to the instrumental
distribution
### Response:
def _sample_item(self, **kwargs):
"""Sample an item from the pool according to the instrumental
distribution
"""
loc = np.ra... |
def _get_stddevs(self, C, stddev_types, nsites):
"""
Compute total standard deviation, see table 4.2, page 50.
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.... | Compute total standard deviation, see table 4.2, page 50. | Below is the the instruction that describes the task:
### Input:
Compute total standard deviation, see table 4.2, page 50.
### Response:
def _get_stddevs(self, C, stddev_types, nsites):
"""
Compute total standard deviation, see table 4.2, page 50.
"""
stddevs = []
for stddev... |
def rename_get_variable(mapping):
"""
Args:
mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'}
Returns:
A context where the variables are renamed.
"""
def custom_getter(getter, name, *args, **kwargs):
splits = name.split('/')
basename = ... | Args:
mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'}
Returns:
A context where the variables are renamed. | Below is the the instruction that describes the task:
### Input:
Args:
mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'}
Returns:
A context where the variables are renamed.
### Response:
def rename_get_variable(mapping):
"""
Args:
mapping(dict): a... |
def dev():
"""Define dev stage"""
env.roledefs = {
'web': ['192.168.1.2'],
'lb': ['192.168.1.2'],
}
env.user = 'vagrant'
env.backends = env.roledefs['web']
env.server_name = 'django_search_model-dev.net'
env.short_server_name = 'django_search_model-dev'
env.stat... | Define dev stage | Below is the the instruction that describes the task:
### Input:
Define dev stage
### Response:
def dev():
"""Define dev stage"""
env.roledefs = {
'web': ['192.168.1.2'],
'lb': ['192.168.1.2'],
}
env.user = 'vagrant'
env.backends = env.roledefs['web']
env.server_name... |
def _dms_formatter(latitude, longitude, mode, unistr=False):
"""Generate a human readable DM/DMS location string.
Args:
latitude (float): Location's latitude
longitude (float): Location's longitude
mode (str): Coordinate formatting system to use
unistr (bool): Whether to use ext... | Generate a human readable DM/DMS location string.
Args:
latitude (float): Location's latitude
longitude (float): Location's longitude
mode (str): Coordinate formatting system to use
unistr (bool): Whether to use extended character set | Below is the the instruction that describes the task:
### Input:
Generate a human readable DM/DMS location string.
Args:
latitude (float): Location's latitude
longitude (float): Location's longitude
mode (str): Coordinate formatting system to use
unistr (bool): Whether to use ex... |
def extractFile(self, filename):
"""
This function will extract a single file from the remote zip without downloading
the entire zip file. The filename argument should match whatever is in the 'filename'
key of the tableOfContents.
"""
files = [x for x in self.tableOfCont... | This function will extract a single file from the remote zip without downloading
the entire zip file. The filename argument should match whatever is in the 'filename'
key of the tableOfContents. | Below is the the instruction that describes the task:
### Input:
This function will extract a single file from the remote zip without downloading
the entire zip file. The filename argument should match whatever is in the 'filename'
key of the tableOfContents.
### Response:
def extractFile(self, fil... |
def logical_raid_levels(self):
"""Gets the raid level for each logical volume
:returns the set of list of raid levels configured.
"""
lg_raid_lvls = set()
for member in self.get_members():
lg_raid_lvls.add(mappings.RAID_LEVEL_MAP_REV.get(member.raid))
return ... | Gets the raid level for each logical volume
:returns the set of list of raid levels configured. | Below is the the instruction that describes the task:
### Input:
Gets the raid level for each logical volume
:returns the set of list of raid levels configured.
### Response:
def logical_raid_levels(self):
"""Gets the raid level for each logical volume
:returns the set of list of raid lev... |
def delete_process_by_id(self, process_type_id):
"""DeleteProcessById.
[Preview API] Removes a process of a specific ID.
:param str process_type_id:
"""
route_values = {}
if process_type_id is not None:
route_values['processTypeId'] = self._serialize.url('proc... | DeleteProcessById.
[Preview API] Removes a process of a specific ID.
:param str process_type_id: | Below is the the instruction that describes the task:
### Input:
DeleteProcessById.
[Preview API] Removes a process of a specific ID.
:param str process_type_id:
### Response:
def delete_process_by_id(self, process_type_id):
"""DeleteProcessById.
[Preview API] Removes a process of a... |
def getChild(self, path, request):
"""
This is necessary because the parent class would call
proxy.ReverseProxyResource instead of CacheProxyResource
"""
return CacheProxyResource(
self.host, self.port, self.path + '/' + urlquote(path, safe=""),
self.react... | This is necessary because the parent class would call
proxy.ReverseProxyResource instead of CacheProxyResource | Below is the the instruction that describes the task:
### Input:
This is necessary because the parent class would call
proxy.ReverseProxyResource instead of CacheProxyResource
### Response:
def getChild(self, path, request):
"""
This is necessary because the parent class would call
... |
def symmetrize_JMS_dict(C):
"""For a dictionary with JMS Wilson coefficients but keys that might not be
in the non-redundant basis, return a dictionary with keys from the basis
and values conjugated if necessary."""
wc_keys = set(wcxf.Basis['WET', 'JMS'].all_wcs)
Cs = {}
for op, v in C.items():
... | For a dictionary with JMS Wilson coefficients but keys that might not be
in the non-redundant basis, return a dictionary with keys from the basis
and values conjugated if necessary. | Below is the the instruction that describes the task:
### Input:
For a dictionary with JMS Wilson coefficients but keys that might not be
in the non-redundant basis, return a dictionary with keys from the basis
and values conjugated if necessary.
### Response:
def symmetrize_JMS_dict(C):
"""For a dicti... |
def check_status(self):
""" tests both the ext_url and local_url to see if the database is
running
returns:
True if a connection can be made
False if the connection cannot me made
"""
log = logging.getLogger("%s.%s" % (self.log_name,
... | tests both the ext_url and local_url to see if the database is
running
returns:
True if a connection can be made
False if the connection cannot me made | Below is the the instruction that describes the task:
### Input:
tests both the ext_url and local_url to see if the database is
running
returns:
True if a connection can be made
False if the connection cannot me made
### Response:
def check_status(self):
... |
def _unichr(i):
"""
Helper function for taking a Unicode scalar value and returning a Unicode character.
:param s: Unicode scalar value to convert.
:return: Unicode character
"""
if not isinstance(i, int):
raise TypeError
try:
return six.unichr(i)
except ValueError:
... | Helper function for taking a Unicode scalar value and returning a Unicode character.
:param s: Unicode scalar value to convert.
:return: Unicode character | Below is the the instruction that describes the task:
### Input:
Helper function for taking a Unicode scalar value and returning a Unicode character.
:param s: Unicode scalar value to convert.
:return: Unicode character
### Response:
def _unichr(i):
"""
Helper function for taking a Unicode scalar ... |
def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Preparation work for SomaticIndelDetector.
"""
base_config = items[0]["config"]
for x in align_bams:
bam.index(x, base_config)
params = ["-R", ref_file, "-T", "SomaticIndelDetector", "-U", "ALLOW_N_... | Preparation work for SomaticIndelDetector. | Below is the the instruction that describes the task:
### Input:
Preparation work for SomaticIndelDetector.
### Response:
def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Preparation work for SomaticIndelDetector.
"""
base_config = items[0]["config"]
for ... |
def body_json(soup, base_url=None):
""" Get body json and then alter it with section wrapping and removing boxed-text """
body_content = body(soup, remove_key_info_box=True, base_url=base_url)
# Wrap in a section if the first block is not a section
if (body_content and len(body_content) > 0 and "type" i... | Get body json and then alter it with section wrapping and removing boxed-text | Below is the the instruction that describes the task:
### Input:
Get body json and then alter it with section wrapping and removing boxed-text
### Response:
def body_json(soup, base_url=None):
""" Get body json and then alter it with section wrapping and removing boxed-text """
body_content = body(soup, re... |
def execute_procedure(self, name, args=None, kwargs=None):
"""
Call the concrete python function corresponding to given RPC Method `name` and return the result.
Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class.
"""
_method = registry.get... | Call the concrete python function corresponding to given RPC Method `name` and return the result.
Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class. | Below is the the instruction that describes the task:
### Input:
Call the concrete python function corresponding to given RPC Method `name` and return the result.
Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class.
### Response:
def execute_procedure(self, name, args... |
def _load_tasks(self, project):
'''load tasks from database'''
task_queue = project.task_queue
for task in self.taskdb.load_tasks(
self.taskdb.ACTIVE, project.name, self.scheduler_task_fields
):
taskid = task['taskid']
_schedule = task.get('schedu... | load tasks from database | Below is the the instruction that describes the task:
### Input:
load tasks from database
### Response:
def _load_tasks(self, project):
'''load tasks from database'''
task_queue = project.task_queue
for task in self.taskdb.load_tasks(
self.taskdb.ACTIVE, project.name, self.... |
def publish_attrs(self, upcount=1):
"""
Magic function which inject all attrs into the callers namespace
:param upcount int, how many stack levels we go up
:return:
"""
frame = inspect.currentframe()
i = upcount
while True:
if frame.f_back... | Magic function which inject all attrs into the callers namespace
:param upcount int, how many stack levels we go up
:return: | Below is the the instruction that describes the task:
### Input:
Magic function which inject all attrs into the callers namespace
:param upcount int, how many stack levels we go up
:return:
### Response:
def publish_attrs(self, upcount=1):
"""
Magic function which inject all att... |
def confirm_deliveries(self):
"""Set the channel to confirm that each message has been
successfully delivered.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an ... | Set the channel to confirm that each message has been
successfully delivered.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | Below is the the instruction that describes the task:
### Input:
Set the channel to confirm that each message has been
successfully delivered.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
... |
def send_keys(self, keysToSend):
"""
Send Keys to the Alert.
:Args:
- keysToSend: The text to be sent to Alert.
"""
if self.driver.w3c:
self.driver.execute(Command.W3C_SET_ALERT_VALUE, {'value': keys_to_typing(keysToSend),
... | Send Keys to the Alert.
:Args:
- keysToSend: The text to be sent to Alert. | Below is the the instruction that describes the task:
### Input:
Send Keys to the Alert.
:Args:
- keysToSend: The text to be sent to Alert.
### Response:
def send_keys(self, keysToSend):
"""
Send Keys to the Alert.
:Args:
- keysToSend: The text to be sent to Aler... |
def is_bin(ip):
"""Return true if the IP address is in binary notation."""
try:
ip = str(ip)
if len(ip) != 32:
return False
dec = int(ip, 2)
except (TypeError, ValueError):
return False
if dec > 4294967295 or dec < 0:
return False
return True | Return true if the IP address is in binary notation. | Below is the the instruction that describes the task:
### Input:
Return true if the IP address is in binary notation.
### Response:
def is_bin(ip):
"""Return true if the IP address is in binary notation."""
try:
ip = str(ip)
if len(ip) != 32:
return False
dec = int(ip, 2... |
def to_frame(self, frame, current_frame=None, **kwargs):
"""
TODO:
Parameters
----------
frame : `gala.potential.CFrameBase`
The frame to transform to.
current_frame : `gala.potential.CFrameBase` (optional)
If the Orbit has no associated Hamiltoni... | TODO:
Parameters
----------
frame : `gala.potential.CFrameBase`
The frame to transform to.
current_frame : `gala.potential.CFrameBase` (optional)
If the Orbit has no associated Hamiltonian, this specifies the
current frame of the orbit.
Retur... | Below is the the instruction that describes the task:
### Input:
TODO:
Parameters
----------
frame : `gala.potential.CFrameBase`
The frame to transform to.
current_frame : `gala.potential.CFrameBase` (optional)
If the Orbit has no associated Hamiltonian, this... |
def _addDatasetAction(self, dataset):
"""
Adds an action for the inputed dataset to the toolbar
:param dataset | <XChartDataset>
"""
# create the toolbar action
action = QAction(dataset.name(), self)
action.setIcon(XColorIcon(dataset.color())... | Adds an action for the inputed dataset to the toolbar
:param dataset | <XChartDataset> | Below is the the instruction that describes the task:
### Input:
Adds an action for the inputed dataset to the toolbar
:param dataset | <XChartDataset>
### Response:
def _addDatasetAction(self, dataset):
"""
Adds an action for the inputed dataset to the toolbar
... |
def path(cls, ref):
"""
:return: string to absolute path at which the reflog of the given ref
instance would be found. The path is not guaranteed to point to a valid
file though.
:param ref: SymbolicReference instance"""
return osp.join(ref.repo.git_dir, "logs", t... | :return: string to absolute path at which the reflog of the given ref
instance would be found. The path is not guaranteed to point to a valid
file though.
:param ref: SymbolicReference instance | Below is the the instruction that describes the task:
### Input:
:return: string to absolute path at which the reflog of the given ref
instance would be found. The path is not guaranteed to point to a valid
file though.
:param ref: SymbolicReference instance
### Response:
def path(c... |
def _get_dependencies_of(name, location=None):
'''
Returns list of first level dependencies of the given installed dap
or dap from Dapi if not installed
If a location is specified, this only checks for dap installed in that path
and return [] if the dap is not located there
'''
if not locat... | Returns list of first level dependencies of the given installed dap
or dap from Dapi if not installed
If a location is specified, this only checks for dap installed in that path
and return [] if the dap is not located there | Below is the the instruction that describes the task:
### Input:
Returns list of first level dependencies of the given installed dap
or dap from Dapi if not installed
If a location is specified, this only checks for dap installed in that path
and return [] if the dap is not located there
### Response: ... |
def parse_gene_list(path: str, graph: Graph, anno_type: str = "name") -> list:
"""Parse a list of genes and return them if they are in the network.
:param str path: The path of input file.
:param Graph graph: The graph with genes as nodes.
:param str anno_type: The type of annotation with two options:n... | Parse a list of genes and return them if they are in the network.
:param str path: The path of input file.
:param Graph graph: The graph with genes as nodes.
:param str anno_type: The type of annotation with two options:name-Entrez ID, symbol-HGNC symbol.
:return list: A list of genes, all of which are... | Below is the the instruction that describes the task:
### Input:
Parse a list of genes and return them if they are in the network.
:param str path: The path of input file.
:param Graph graph: The graph with genes as nodes.
:param str anno_type: The type of annotation with two options:name-Entrez ID, sy... |
def text(self, encoding=None, errors='strict'):
r""" Open this file, read it in, return the content as a string.
This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
are automatically translated to '\n'.
Optional arguments:
encoding - The Unicode encoding (or charact... | r""" Open this file, read it in, return the content as a string.
This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
are automatically translated to '\n'.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. If present, the conten... | Below is the the instruction that describes the task:
### Input:
r""" Open this file, read it in, return the content as a string.
This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
are automatically translated to '\n'.
Optional arguments:
encoding - The Unicode encodin... |
def determine_final_config(config_module):
"""Determines the final additions and replacements.
Combines the config module with the defaults.
Args:
config_module: The loaded local configuration module.
Returns:
Config: the final configuration.
"""
config = Config(
DEFAU... | Determines the final additions and replacements.
Combines the config module with the defaults.
Args:
config_module: The loaded local configuration module.
Returns:
Config: the final configuration. | Below is the the instruction that describes the task:
### Input:
Determines the final additions and replacements.
Combines the config module with the defaults.
Args:
config_module: The loaded local configuration module.
Returns:
Config: the final configuration.
### Response:
def dete... |
def log_request_success(self, method, full_url, path, body, status_code, response, duration):
""" Log a successful API call. """
if body and not isinstance(body, dict):
body = body.decode('utf-8')
logger.info(
'%s %s [status:%s request:%.3fs]', method, full_url,
... | Log a successful API call. | Below is the the instruction that describes the task:
### Input:
Log a successful API call.
### Response:
def log_request_success(self, method, full_url, path, body, status_code, response, duration):
""" Log a successful API call. """
if body and not isinstance(body, dict):
body = bod... |
def delete_query(self, query_id):
"""Delete query in device query service.
:param int query_id: ID of the query to delete (Required)
:return: void
"""
api = self._get_api(device_directory.DefaultApi)
api.device_query_destroy(query_id)
return | Delete query in device query service.
:param int query_id: ID of the query to delete (Required)
:return: void | Below is the the instruction that describes the task:
### Input:
Delete query in device query service.
:param int query_id: ID of the query to delete (Required)
:return: void
### Response:
def delete_query(self, query_id):
"""Delete query in device query service.
:param int query_... |
def rdcandump(filename, count=None,
is_not_log_file_format=False,
interface=None):
"""Read a candump log file and return a packet list
count: read only <count> packets
is_not_log_file_format: read input with candumps stdout format
interfaces: return only packets from a specified interfa... | Read a candump log file and return a packet list
count: read only <count> packets
is_not_log_file_format: read input with candumps stdout format
interfaces: return only packets from a specified interface | Below is the the instruction that describes the task:
### Input:
Read a candump log file and return a packet list
count: read only <count> packets
is_not_log_file_format: read input with candumps stdout format
interfaces: return only packets from a specified interface
### Response:
def rdcandump(filename, count=N... |
def expression(self, text):
"""expression = number , op_mult , expression
| expression_terminal , op_mult , number , [operator , expression]
| expression_terminal , op_add , [operator , expression]
| expression_terminal , [operator , expression] ;
"""
se... | expression = number , op_mult , expression
| expression_terminal , op_mult , number , [operator , expression]
| expression_terminal , op_add , [operator , expression]
| expression_terminal , [operator , expression] ; | Below is the the instruction that describes the task:
### Input:
expression = number , op_mult , expression
| expression_terminal , op_mult , number , [operator , expression]
| expression_terminal , op_add , [operator , expression]
| expression_terminal , [opera... |
def _flat_values(self):
"""Return tuple of mean values as found in cube response.
Mean data may include missing items represented by a dict like
{'?': -1} in the cube response. These are replaced by np.nan in the
returned value.
"""
return tuple(
np.nan if ty... | Return tuple of mean values as found in cube response.
Mean data may include missing items represented by a dict like
{'?': -1} in the cube response. These are replaced by np.nan in the
returned value. | Below is the the instruction that describes the task:
### Input:
Return tuple of mean values as found in cube response.
Mean data may include missing items represented by a dict like
{'?': -1} in the cube response. These are replaced by np.nan in the
returned value.
### Response:
def _flat... |
def load(cls, filename, name=None):
""" Load yaml configuration from filename. """
if not os.path.exists(filename):
return {}
name = name or filename
if name not in cls._conffiles:
with open(filename) as fdesc:
content = yaml.load(fdesc, YAMLLoade... | Load yaml configuration from filename. | Below is the the instruction that describes the task:
### Input:
Load yaml configuration from filename.
### Response:
def load(cls, filename, name=None):
""" Load yaml configuration from filename. """
if not os.path.exists(filename):
return {}
name = name or filename
if... |
def AsRegEx(self):
"""Return the current glob as a simple regex.
Note: No interpolation is performed.
Returns:
A RegularExpression() object.
"""
parts = self.__class__.REGEX_SPLIT_PATTERN.split(self._value)
result = u"".join(self._ReplaceRegExPart(p) for p in parts)
return rdf_stand... | Return the current glob as a simple regex.
Note: No interpolation is performed.
Returns:
A RegularExpression() object. | Below is the the instruction that describes the task:
### Input:
Return the current glob as a simple regex.
Note: No interpolation is performed.
Returns:
A RegularExpression() object.
### Response:
def AsRegEx(self):
"""Return the current glob as a simple regex.
Note: No interpolation is p... |
def add_canstrat_striplogs(self,
path, uwi_transform=None, name='canstrat'):
"""
This may be too specific a method... just move it to the workflow.
Requires striplog.
"""
from striplog import Striplog
uwi_transform = uwi_transform or utils... | This may be too specific a method... just move it to the workflow.
Requires striplog. | Below is the the instruction that describes the task:
### Input:
This may be too specific a method... just move it to the workflow.
Requires striplog.
### Response:
def add_canstrat_striplogs(self,
path, uwi_transform=None, name='canstrat'):
"""
This may be t... |
def old_properties_names_to_new(self): # pragma: no cover, never called
"""Convert old Nagios2 names to Nagios3 new names
TODO: still useful?
:return: None
"""
for i in itertools.chain(iter(list(self.items.values())),
iter(list(self.templates.v... | Convert old Nagios2 names to Nagios3 new names
TODO: still useful?
:return: None | Below is the the instruction that describes the task:
### Input:
Convert old Nagios2 names to Nagios3 new names
TODO: still useful?
:return: None
### Response:
def old_properties_names_to_new(self): # pragma: no cover, never called
"""Convert old Nagios2 names to Nagios3 new names
... |
def _parse_proto(prototxt_fname):
"""Parse Caffe prototxt into symbol string
"""
proto = caffe_parser.read_prototxt(prototxt_fname)
# process data layer
input_name, input_dim, layers = _get_input(proto)
# only support single input, so always use `data` as the input data
mapping = {input_nam... | Parse Caffe prototxt into symbol string | Below is the the instruction that describes the task:
### Input:
Parse Caffe prototxt into symbol string
### Response:
def _parse_proto(prototxt_fname):
"""Parse Caffe prototxt into symbol string
"""
proto = caffe_parser.read_prototxt(prototxt_fname)
# process data layer
input_name, input_dim,... |
def train(self):
"""
Train model with transformed data
"""
for i, model in enumerate(self.models):
N = [int(i * len(self.y)) for i in self.lc_range]
for n in N:
X = self.X[:n]
y = self.y[:n]
e = Experiment(X, y, mode... | Train model with transformed data | Below is the the instruction that describes the task:
### Input:
Train model with transformed data
### Response:
def train(self):
"""
Train model with transformed data
"""
for i, model in enumerate(self.models):
N = [int(i * len(self.y)) for i in self.lc_range]
... |
def first_from_generator(generator):
"""Pull the first value from a generator and return it, closing the generator
:param generator:
A generator, this will be mapped onto a list and the first item extracted.
:return:
None if there are no items, or the first item otherwise.
:internal:
... | Pull the first value from a generator and return it, closing the generator
:param generator:
A generator, this will be mapped onto a list and the first item extracted.
:return:
None if there are no items, or the first item otherwise.
:internal: | Below is the the instruction that describes the task:
### Input:
Pull the first value from a generator and return it, closing the generator
:param generator:
A generator, this will be mapped onto a list and the first item extracted.
:return:
None if there are no items, or the first item oth... |
def deduplicate(list_object):
"""Rebuild `list_object` removing duplicated and keeping order"""
new = []
for item in list_object:
if item not in new:
new.append(item)
return new | Rebuild `list_object` removing duplicated and keeping order | Below is the the instruction that describes the task:
### Input:
Rebuild `list_object` removing duplicated and keeping order
### Response:
def deduplicate(list_object):
"""Rebuild `list_object` removing duplicated and keeping order"""
new = []
for item in list_object:
if item not in new:
... |
def get_pause_time(self, speed=ETHER_SPEED_MBIT_1000):
"""
get pause time for given link speed in seconds
:param speed: select link speed to get the pause time for, must be ETHER_SPEED_MBIT_[10,100,1000] # noqa: E501
:return: pause time in seconds
:raises MACControlInvalidSpeed... | get pause time for given link speed in seconds
:param speed: select link speed to get the pause time for, must be ETHER_SPEED_MBIT_[10,100,1000] # noqa: E501
:return: pause time in seconds
:raises MACControlInvalidSpeedException: on invalid speed selector | Below is the the instruction that describes the task:
### Input:
get pause time for given link speed in seconds
:param speed: select link speed to get the pause time for, must be ETHER_SPEED_MBIT_[10,100,1000] # noqa: E501
:return: pause time in seconds
:raises MACControlInvalidSpeedExcept... |
def sample_bitstrings(self, n_samples):
"""
Sample bitstrings from the distribution defined by the wavefunction.
Qubit 0 is at ``out[:, 0]``.
:param n_samples: The number of bitstrings to sample
:return: An array of shape (n_samples, n_qubits)
"""
if self.rs is ... | Sample bitstrings from the distribution defined by the wavefunction.
Qubit 0 is at ``out[:, 0]``.
:param n_samples: The number of bitstrings to sample
:return: An array of shape (n_samples, n_qubits) | Below is the the instruction that describes the task:
### Input:
Sample bitstrings from the distribution defined by the wavefunction.
Qubit 0 is at ``out[:, 0]``.
:param n_samples: The number of bitstrings to sample
:return: An array of shape (n_samples, n_qubits)
### Response:
def sample... |
def delete(self, key, *keys):
"""Delete a key."""
fut = self.execute(b'DEL', key, *keys)
return wait_convert(fut, int) | Delete a key. | Below is the the instruction that describes the task:
### Input:
Delete a key.
### Response:
def delete(self, key, *keys):
"""Delete a key."""
fut = self.execute(b'DEL', key, *keys)
return wait_convert(fut, int) |
def tgread_bool(self):
"""Reads a Telegram boolean value."""
value = self.read_int(signed=False)
if value == 0x997275b5: # boolTrue
return True
elif value == 0xbc799737: # boolFalse
return False
else:
raise RuntimeError('Invalid boolean code ... | Reads a Telegram boolean value. | Below is the the instruction that describes the task:
### Input:
Reads a Telegram boolean value.
### Response:
def tgread_bool(self):
"""Reads a Telegram boolean value."""
value = self.read_int(signed=False)
if value == 0x997275b5: # boolTrue
return True
elif value == 0... |
def main(arguments=None):
"""
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
"""
# setup the command-line util settings
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="DEBUG",
option... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* | Below is the the instruction that describes the task:
### Input:
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
### Response:
def main(arguments=None):
"""
*The main function used when ``cl_utils.py`` is run as a single script from the... |
def selected(self):
""" returns the list of selected component names.
if no component selected return the one marked as default.
If the block is required and no component where indicated as default,
then the first component is selected.
"""
selected = self._selected
... | returns the list of selected component names.
if no component selected return the one marked as default.
If the block is required and no component where indicated as default,
then the first component is selected. | Below is the the instruction that describes the task:
### Input:
returns the list of selected component names.
if no component selected return the one marked as default.
If the block is required and no component where indicated as default,
then the first component is selected.
### Response:... |
def _check_completion_errors(self):
"""
Parses four potential errors that can cause jobs to crash: inability to transform
coordinates due to a bad symmetric specification, an input file that fails to pass
inspection, and errors reading and writing files.
"""
if read_patte... | Parses four potential errors that can cause jobs to crash: inability to transform
coordinates due to a bad symmetric specification, an input file that fails to pass
inspection, and errors reading and writing files. | Below is the the instruction that describes the task:
### Input:
Parses four potential errors that can cause jobs to crash: inability to transform
coordinates due to a bad symmetric specification, an input file that fails to pass
inspection, and errors reading and writing files.
### Response:
def _... |
def get_url_for_get(url, parameters=None):
# type: (str, Optional[Dict]) -> str
"""Get full url for GET request including parameters
Args:
url (str): URL to download
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
Returns:
str: Ful... | Get full url for GET request including parameters
Args:
url (str): URL to download
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
Returns:
str: Full url | Below is the the instruction that describes the task:
### Input:
Get full url for GET request including parameters
Args:
url (str): URL to download
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
Returns:
str: Full url
### Response:
def get_u... |
async def set_access_string(self, **params):
"""Writes content access string to database
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
cid = int(params.get("cid", "0"))
seller_access_string = params.get("seller_access_string")
seller_pubkey = params.get("seller_pubkey")... | Writes content access string to database | Below is the the instruction that describes the task:
### Input:
Writes content access string to database
### Response:
async def set_access_string(self, **params):
"""Writes content access string to database
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
cid = int(para... |
def set_tensor_final(self, tensor_name):
"""Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
"""
tensor = self._name_to_tensor(tensor_name)
self._final_tensors.add(tensor) | Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph. | Below is the the instruction that describes the task:
### Input:
Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
### Response:
def set_tensor_final(self, tensor_name):
"""Denotes a tensor as a final output of the computation.
Ar... |
def _make_random_string(length):
"""Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate.
"""
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
return ''.join(random.choice(chars) for x in range(length)) | Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate. | Below is the the instruction that describes the task:
### Input:
Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate.
### Response:
def _make_random_string(length):
"""Returns a random lowercase, uppercase, alphanumerical string.
... |
def send_apply_request(self, socket, f, args=None, kwargs=None, subheader=None, track=False,
ident=None):
"""construct and send an apply message via a socket.
This is the principal method with which all engine execution is performed by views.
"""
if self._cl... | construct and send an apply message via a socket.
This is the principal method with which all engine execution is performed by views. | Below is the the instruction that describes the task:
### Input:
construct and send an apply message via a socket.
This is the principal method with which all engine execution is performed by views.
### Response:
def send_apply_request(self, socket, f, args=None, kwargs=None, subheader=None, track=False,
... |
def create_history_model(self, model, inherited):
"""
Creates a historical model to associate with the model provided.
"""
attrs = {
"__module__": self.module,
"_history_excluded_fields": self.excluded_fields,
}
app_module = "%s.models" % model._m... | Creates a historical model to associate with the model provided. | Below is the the instruction that describes the task:
### Input:
Creates a historical model to associate with the model provided.
### Response:
def create_history_model(self, model, inherited):
"""
Creates a historical model to associate with the model provided.
"""
attrs = {
... |
def _timestamp_regulator(self):
"""
Makes a dictionary whose keys are audio file basenames and whose
values are a list of word blocks from unregulated timestamps and
updates the main timestamp attribute. After all done, purges
unregulated ones.
In case the audio file was ... | Makes a dictionary whose keys are audio file basenames and whose
values are a list of word blocks from unregulated timestamps and
updates the main timestamp attribute. After all done, purges
unregulated ones.
In case the audio file was large enough to be splitted, it adds seconds
... | Below is the the instruction that describes the task:
### Input:
Makes a dictionary whose keys are audio file basenames and whose
values are a list of word blocks from unregulated timestamps and
updates the main timestamp attribute. After all done, purges
unregulated ones.
In case th... |
def catch_errors(f):
"""
Catches specific errors in admin actions and shows a friendly error.
"""
@functools.wraps(f)
def wrapper(self, request, *args, **kwargs):
try:
return f(self, request, *args, **kwargs)
except exceptions.CertificateExpired:
self.message... | Catches specific errors in admin actions and shows a friendly error. | Below is the the instruction that describes the task:
### Input:
Catches specific errors in admin actions and shows a friendly error.
### Response:
def catch_errors(f):
"""
Catches specific errors in admin actions and shows a friendly error.
"""
@functools.wraps(f)
def wrapper(self, request, *... |
def _ExtractJQuery(self, jquery_raw):
"""Extracts values from a JQuery string.
Args:
jquery_raw (str): JQuery string.
Returns:
dict[str, str]: extracted values.
"""
data_part = ''
if not jquery_raw:
return {}
if '[' in jquery_raw:
_, _, first_part = jquery_raw.part... | Extracts values from a JQuery string.
Args:
jquery_raw (str): JQuery string.
Returns:
dict[str, str]: extracted values. | Below is the the instruction that describes the task:
### Input:
Extracts values from a JQuery string.
Args:
jquery_raw (str): JQuery string.
Returns:
dict[str, str]: extracted values.
### Response:
def _ExtractJQuery(self, jquery_raw):
"""Extracts values from a JQuery string.
Args:
... |
def wrap(self, value, session=None):
''' Validates that ``value`` is an ObjectId (or hex representation
of one), then returns it '''
self.validate_wrap(value)
if isinstance(value, bytes) or isinstance(value, basestring):
return ObjectId(value)
return value | Validates that ``value`` is an ObjectId (or hex representation
of one), then returns it | Below is the the instruction that describes the task:
### Input:
Validates that ``value`` is an ObjectId (or hex representation
of one), then returns it
### Response:
def wrap(self, value, session=None):
''' Validates that ``value`` is an ObjectId (or hex representation
of one), the... |
def _send_ffe(self, pid, app_id, app_flags, fr):
"""Send a flood-fill end packet.
The cores and regions that the application should be loaded to will
have been specified by a stream of flood-fill core select packets
(FFCS).
"""
arg1 = (NNCommands.flood_fill_end << 24) | ... | Send a flood-fill end packet.
The cores and regions that the application should be loaded to will
have been specified by a stream of flood-fill core select packets
(FFCS). | Below is the the instruction that describes the task:
### Input:
Send a flood-fill end packet.
The cores and regions that the application should be loaded to will
have been specified by a stream of flood-fill core select packets
(FFCS).
### Response:
def _send_ffe(self, pid, app_id, app_fl... |
def get_parser():
"""
This is a helper method to return an argparse parser, to
be used with the Sphinx argparse plugin for documentation.
"""
manager = cfg.build_manager()
source = cfg.build_command_line_source(prog='prospector', description=None)
return source.build_parser(manager.settings,... | This is a helper method to return an argparse parser, to
be used with the Sphinx argparse plugin for documentation. | Below is the the instruction that describes the task:
### Input:
This is a helper method to return an argparse parser, to
be used with the Sphinx argparse plugin for documentation.
### Response:
def get_parser():
"""
This is a helper method to return an argparse parser, to
be used with the Sphinx a... |
def resolver(self, vocab_data, attribute):
"""Pull the requested attribute based on the given vocabulary
and content.
"""
term_list = vocab_data.get(self.content_vocab, [])
# Loop through the terms from the vocabulary.
for term_dict in term_list:
# Match the n... | Pull the requested attribute based on the given vocabulary
and content. | Below is the the instruction that describes the task:
### Input:
Pull the requested attribute based on the given vocabulary
and content.
### Response:
def resolver(self, vocab_data, attribute):
"""Pull the requested attribute based on the given vocabulary
and content.
"""
te... |
def cs_bahdanau_attention(key, context, hidden_size, depth, projected_align=False):
""" It is a implementation of the Bahdanau et al. attention mechanism. Based on the papers:
https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate"
https://andre-martin... | It is a implementation of the Bahdanau et al. attention mechanism. Based on the papers:
https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy... | Below is the the instruction that describes the task:
### Input:
It is a implementation of the Bahdanau et al. attention mechanism. Based on the papers:
https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate"
https://andre-martins.github.io/docs/emnlp2... |
def get_version_from_list(v, vlist):
"""See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way."""
if is_windows:
# Simple case, just find it in the list
if v in vlist: return v
else: return None
else:
# Fuzzy match: normalize version ... | See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way. | Below is the the instruction that describes the task:
### Input:
See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way.
### Response:
def get_version_from_list(v, vlist):
"""See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way... |
def to_vec3(self):
"""Convert this vector4 instance into a vector3 instance."""
vec3 = Vector3()
vec3.x = self.x
vec3.y = self.y
vec3.z = self.z
if self.w != 0:
vec3 /= self.w
return vec3 | Convert this vector4 instance into a vector3 instance. | Below is the the instruction that describes the task:
### Input:
Convert this vector4 instance into a vector3 instance.
### Response:
def to_vec3(self):
"""Convert this vector4 instance into a vector3 instance."""
vec3 = Vector3()
vec3.x = self.x
vec3.y = self.y
vec3.z = sel... |
def updateMappingsOnDeviceType(self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy = "never"):
"""
Add mappings for a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id of the application interfac... | Add mappings for a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id of the application interface these mappings are for
- notificationStrategy (string) - the notification strategy to use for these mappings
- ma... | Below is the the instruction that describes the task:
### Input:
Add mappings for a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id of the application interface these mappings are for
- notificationStrategy (string) -... |
def read_frames(self):
'''
Read frames from the transport and process them. Some transports may
choose to do this in the background, in several threads, and so on.
'''
# It's possible in a concurrent environment that our transport handle
# has gone away, so handle that cl... | Read frames from the transport and process them. Some transports may
choose to do this in the background, in several threads, and so on. | Below is the the instruction that describes the task:
### Input:
Read frames from the transport and process them. Some transports may
choose to do this in the background, in several threads, and so on.
### Response:
def read_frames(self):
'''
Read frames from the transport and process them.... |
def generate(categorize=unicodedata.category, group_class=RangeGroup):
'''
Generate a dict of RangeGroups for each unicode character category,
including general ones.
:param categorize: category function, defaults to unicodedata.category.
:type categorize: callable
:param group_class: class for... | Generate a dict of RangeGroups for each unicode character category,
including general ones.
:param categorize: category function, defaults to unicodedata.category.
:type categorize: callable
:param group_class: class for range groups, defaults to RangeGroup
:type group_class: type
:returns: dic... | Below is the the instruction that describes the task:
### Input:
Generate a dict of RangeGroups for each unicode character category,
including general ones.
:param categorize: category function, defaults to unicodedata.category.
:type categorize: callable
:param group_class: class for range groups,... |
def intersects_id(self,
ray_origins,
ray_directions,
return_locations=False,
multiple_hits=True,
**kwargs):
"""
Find the intersections between the current mesh and a list of rays.
Param... | Find the intersections between the current mesh and a list of rays.
Parameters
------------
ray_origins: (m,3) float, ray origin points
ray_directions: (m,3) float, ray direction vectors
multiple_hits: bool, consider multiple hits of each ray or not
return_loca... | Below is the the instruction that describes the task:
### Input:
Find the intersections between the current mesh and a list of rays.
Parameters
------------
ray_origins: (m,3) float, ray origin points
ray_directions: (m,3) float, ray direction vectors
multiple_hits: ... |
def create_dbsnapshot(self, snapshot_id, dbinstance_id):
"""
Create a new DB snapshot.
:type snapshot_id: string
:param snapshot_id: The identifier for the DBSnapshot
:type dbinstance_id: string
:param dbinstance_id: The source identifier for the RDS instance from
... | Create a new DB snapshot.
:type snapshot_id: string
:param snapshot_id: The identifier for the DBSnapshot
:type dbinstance_id: string
:param dbinstance_id: The source identifier for the RDS instance from
which the snapshot is created.
:rtype: :cla... | Below is the the instruction that describes the task:
### Input:
Create a new DB snapshot.
:type snapshot_id: string
:param snapshot_id: The identifier for the DBSnapshot
:type dbinstance_id: string
:param dbinstance_id: The source identifier for the RDS instance from
... |
def subset(self, service=None):
"""Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'NetcdfSubset'
or 'N... | Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'NetcdfSubset'
or 'NetcdfServer', in that order, depending on t... | Below is the the instruction that describes the task:
### Input:
Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'Netcd... |
def sentences(self):
"""
Returns the instances by sentences, and yields a list of tokens,
similar to the pywsd.semcor.sentences.
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> for sent in coarse_wsd.sentences():
>>> for token in sent:
>>> print token
... | Returns the instances by sentences, and yields a list of tokens,
similar to the pywsd.semcor.sentences.
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> for sent in coarse_wsd.sentences():
>>> for token in sent:
>>> print token
>>> break
>>> ... | Below is the the instruction that describes the task:
### Input:
Returns the instances by sentences, and yields a list of tokens,
similar to the pywsd.semcor.sentences.
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> for sent in coarse_wsd.sentences():
>>> for token in sent:
... |
def build(self, builder):
"""Build XML by appending to builder"""
builder.start("Symbol", {})
for child in self.translations:
child.build(builder)
builder.end("Symbol") | Build XML by appending to builder | Below is the the instruction that describes the task:
### Input:
Build XML by appending to builder
### Response:
def build(self, builder):
"""Build XML by appending to builder"""
builder.start("Symbol", {})
for child in self.translations:
child.build(builder)
builder.end... |
def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
nginxInfo = NginxInfo(self._host, self._port,
self._user, self._password,
... | Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise. | Below is the the instruction that describes the task:
### Input:
Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
### Response:
def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@re... |
def paginate_queryset(self, queryset, request, view=None):
"""
adds `max_count` as a running tally of the largest table size. Used for calculating
next/previous links later
"""
result = super(MultipleModelLimitOffsetPagination, self).paginate_queryset(queryset, request, view)
... | adds `max_count` as a running tally of the largest table size. Used for calculating
next/previous links later | Below is the the instruction that describes the task:
### Input:
adds `max_count` as a running tally of the largest table size. Used for calculating
next/previous links later
### Response:
def paginate_queryset(self, queryset, request, view=None):
"""
adds `max_count` as a running tally of... |
def stream(self, to=values.unset, from_=values.unset,
date_sent_before=values.unset, date_sent=values.unset,
date_sent_after=values.unset, limit=None, page_size=None):
"""
Streams MessageInstance records from the API as a generator stream.
This operation lazily load... | Streams MessageInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode to: Filter by messages sent to th... | Below is the the instruction that describes the task:
### Input:
Streams MessageInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory... |
def auth(view, **kwargs):
"""
This plugin allow user to login to application
kwargs:
- signin_view
- signout_view
- template_dir
- menu:
- name
- group_name
- ...
@plugin(user.login, model=model.User)
class MyAccount(Juice... | This plugin allow user to login to application
kwargs:
- signin_view
- signout_view
- template_dir
- menu:
- name
- group_name
- ...
@plugin(user.login, model=model.User)
class MyAccount(Juice):
pass | Below is the the instruction that describes the task:
### Input:
This plugin allow user to login to application
kwargs:
- signin_view
- signout_view
- template_dir
- menu:
- name
- group_name
- ...
@plugin(user.login, model=model.User... |
def ajax_required(func):
# taken from djangosnippets.org
"""
AJAX request required decorator
use it in your views:
@ajax_required
def my_view(request):
....
"""
def wrap(request, *args, **kwargs):
if not request.is_ajax():
return HttpResponseBadRequest
... | AJAX request required decorator
use it in your views:
@ajax_required
def my_view(request):
.... | Below is the the instruction that describes the task:
### Input:
AJAX request required decorator
use it in your views:
@ajax_required
def my_view(request):
....
### Response:
def ajax_required(func):
# taken from djangosnippets.org
"""
AJAX request required decorator
use it in ... |
def _choose_pool(self, protocol=None):
"""
Selects a connection pool according to the default protocol
and the passed one.
:param protocol: the protocol to use
:type protocol: string
:rtype: Pool
"""
if not protocol:
protocol = self.protocol
... | Selects a connection pool according to the default protocol
and the passed one.
:param protocol: the protocol to use
:type protocol: string
:rtype: Pool | Below is the the instruction that describes the task:
### Input:
Selects a connection pool according to the default protocol
and the passed one.
:param protocol: the protocol to use
:type protocol: string
:rtype: Pool
### Response:
def _choose_pool(self, protocol=None):
"""... |
def stdlib_list(version=None):
"""
Given a ``version``, return a ``list`` of names of the Python Standard
Libraries for that version. These names are obtained from the Sphinx inventory
file (used in :py:mod:`sphinx.ext.intersphinx`).
:param str|None version: The version (as a string) whose list of ... | Given a ``version``, return a ``list`` of names of the Python Standard
Libraries for that version. These names are obtained from the Sphinx inventory
file (used in :py:mod:`sphinx.ext.intersphinx`).
:param str|None version: The version (as a string) whose list of libraries you want
(one of ``"2.6"``, `... | Below is the the instruction that describes the task:
### Input:
Given a ``version``, return a ``list`` of names of the Python Standard
Libraries for that version. These names are obtained from the Sphinx inventory
file (used in :py:mod:`sphinx.ext.intersphinx`).
:param str|None version: The version (a... |
def factorial(n):
""" Returns the factorial of n.
"""
f = 1
while (n > 0):
f = f * n
n = n - 1
return f | Returns the factorial of n. | Below is the the instruction that describes the task:
### Input:
Returns the factorial of n.
### Response:
def factorial(n):
""" Returns the factorial of n.
"""
f = 1
while (n > 0):
f = f * n
n = n - 1
return f |
def memoize(func):
"""
simple memoization decorator
References:
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Args:
func (function): live python function
Returns:
func:
CommandLine:
python -m utool.util_decor memoize
Example:
>>> # ... | simple memoization decorator
References:
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Args:
func (function): live python function
Returns:
func:
CommandLine:
python -m utool.util_decor memoize
Example:
>>> # ENABLE_DOCTEST
>>> from... | Below is the the instruction that describes the task:
### Input:
simple memoization decorator
References:
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Args:
func (function): live python function
Returns:
func:
CommandLine:
python -m utool.util_deco... |
def iteritems(self):
r"""
Iterator over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterat... | r"""
Iterator over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterated over.
content : Se... | Below is the the instruction that describes the task:
### Input:
r"""
Iterator over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The col... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.