code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def load_table(self, table):
"""
Load resources as specified by given table into our db.
"""
region = table.database if table.database else self.default_region
resource_name, collection_name = table.table.split('_', 1)
# we use underscore "_" instead of dash "-" for regio... | Load resources as specified by given table into our db. | Below is the the instruction that describes the task:
### Input:
Load resources as specified by given table into our db.
### Response:
def load_table(self, table):
"""
Load resources as specified by given table into our db.
"""
region = table.database if table.database else self.def... |
def _get_invalid_info(granule_data):
"""Get a detailed report of the missing data.
N/A: not applicable
MISS: required value missing at time of processing
OBPT: onboard pixel trim (overlapping/bow-tie pixel removed during
SDR processing)
OGPT: on-ground pixel trim (overlap... | Get a detailed report of the missing data.
N/A: not applicable
MISS: required value missing at time of processing
OBPT: onboard pixel trim (overlapping/bow-tie pixel removed during
SDR processing)
OGPT: on-ground pixel trim (overlapping/bow-tie pixel removed
durin... | Below is the the instruction that describes the task:
### Input:
Get a detailed report of the missing data.
N/A: not applicable
MISS: required value missing at time of processing
OBPT: onboard pixel trim (overlapping/bow-tie pixel removed during
SDR processing)
OGPT: on-g... |
def encode (self):
"""Encodes this SeqCmd to binary and returns a bytearray."""
return self.attrs.encode() + self.delay.encode() + self.cmd.encode() | Encodes this SeqCmd to binary and returns a bytearray. | Below is the the instruction that describes the task:
### Input:
Encodes this SeqCmd to binary and returns a bytearray.
### Response:
def encode (self):
"""Encodes this SeqCmd to binary and returns a bytearray."""
return self.attrs.encode() + self.delay.encode() + self.cmd.encode() |
def utctimetuple(self):
"Return UTC time tuple compatible with time.gmtime()."
y, m, d = self.year, self.month, self.day
hh, mm, ss = self.hour, self.minute, self.second
offset = self._utcoffset()
if offset: # neither None nor 0
mm -= offset
y, m, d, hh, ... | Return UTC time tuple compatible with time.gmtime(). | Below is the the instruction that describes the task:
### Input:
Return UTC time tuple compatible with time.gmtime().
### Response:
def utctimetuple(self):
"Return UTC time tuple compatible with time.gmtime()."
y, m, d = self.year, self.month, self.day
hh, mm, ss = self.hour, self.minute, s... |
def as_search_document_update(self, *, index, update_fields):
"""
Return a partial update document based on which fields have been updated.
If an object is saved with the `update_fields` argument passed
through, then it is assumed that this is a 'partial update'. In
this scenari... | Return a partial update document based on which fields have been updated.
If an object is saved with the `update_fields` argument passed
through, then it is assumed that this is a 'partial update'. In
this scenario we need a {property: value} dictionary containing
just the fields we wan... | Below is the the instruction that describes the task:
### Input:
Return a partial update document based on which fields have been updated.
If an object is saved with the `update_fields` argument passed
through, then it is assumed that this is a 'partial update'. In
this scenario we need a {... |
async def request(self, request):
"""
Execute a STUN transaction and return the response.
"""
assert request.transaction_id not in self.transactions
if self.integrity_key:
self.__add_authentication(request)
transaction = stun.Transaction(request, self.server... | Execute a STUN transaction and return the response. | Below is the the instruction that describes the task:
### Input:
Execute a STUN transaction and return the response.
### Response:
async def request(self, request):
"""
Execute a STUN transaction and return the response.
"""
assert request.transaction_id not in self.transactions
... |
def list_projects_search(self, searchstring):
"""List projects with searchstring."""
log.debug('List all projects with: %s' % searchstring)
return self.collection('projects/search/%s.json' %
quote_plus(searchstring)) | List projects with searchstring. | Below is the the instruction that describes the task:
### Input:
List projects with searchstring.
### Response:
def list_projects_search(self, searchstring):
"""List projects with searchstring."""
log.debug('List all projects with: %s' % searchstring)
return self.collection('projects/search... |
def gravitational_force(position_a, mass_a, position_b, mass_b):
"""Returns the gravitational force between the two bodies a and b."""
distance = distance_between(position_a, position_b)
# Calculate the direction and magnitude of the force.
angle = math.atan2(position_a[1] - position_b[1], position_a[0... | Returns the gravitational force between the two bodies a and b. | Below is the the instruction that describes the task:
### Input:
Returns the gravitational force between the two bodies a and b.
### Response:
def gravitational_force(position_a, mass_a, position_b, mass_b):
"""Returns the gravitational force between the two bodies a and b."""
distance = distance_between(p... |
def is_frameshift_len(mut_df):
"""Simply returns a series indicating whether each corresponding mutation
is a frameshift.
This is based on the length of the indel. Thus may be fooled by frameshifts
at exon-intron boundaries or other odd cases.
Parameters
----------
mut_df : pd.DataFrame
... | Simply returns a series indicating whether each corresponding mutation
is a frameshift.
This is based on the length of the indel. Thus may be fooled by frameshifts
at exon-intron boundaries or other odd cases.
Parameters
----------
mut_df : pd.DataFrame
mutation input file as a datafra... | Below is the the instruction that describes the task:
### Input:
Simply returns a series indicating whether each corresponding mutation
is a frameshift.
This is based on the length of the indel. Thus may be fooled by frameshifts
at exon-intron boundaries or other odd cases.
Parameters
--------... |
def is_published(self):
"""Return True if a record is published.
We say that a record is published if it is citeable, which means that
it has enough information in a ``publication_info``, or if we know its
DOI and a ``journal_title``, which means it is in press.
Returns:
... | Return True if a record is published.
We say that a record is published if it is citeable, which means that
it has enough information in a ``publication_info``, or if we know its
DOI and a ``journal_title``, which means it is in press.
Returns:
bool: whether the record is p... | Below is the the instruction that describes the task:
### Input:
Return True if a record is published.
We say that a record is published if it is citeable, which means that
it has enough information in a ``publication_info``, or if we know its
DOI and a ``journal_title``, which means it is ... |
def _pyuncompress_sqlitecurve(sqlitecurve, force=False):
'''This just uncompresses the sqlitecurve. Should be independent of OS.
'''
outfile = sqlitecurve.replace('.gz','')
try:
if os.path.exists(outfile) and not force:
return outfile
else:
with gzip.open(sq... | This just uncompresses the sqlitecurve. Should be independent of OS. | Below is the the instruction that describes the task:
### Input:
This just uncompresses the sqlitecurve. Should be independent of OS.
### Response:
def _pyuncompress_sqlitecurve(sqlitecurve, force=False):
'''This just uncompresses the sqlitecurve. Should be independent of OS.
'''
outfile = sqlitecurv... |
def handle_splits(self, splits):
"""Processes a list of splits by modifying any positions as needed.
Parameters
----------
splits: list
A list of splits. Each split is a tuple of (asset, ratio).
Returns
-------
int: The leftover cash from fractional... | Processes a list of splits by modifying any positions as needed.
Parameters
----------
splits: list
A list of splits. Each split is a tuple of (asset, ratio).
Returns
-------
int: The leftover cash from fractional shares after modifying each
pos... | Below is the the instruction that describes the task:
### Input:
Processes a list of splits by modifying any positions as needed.
Parameters
----------
splits: list
A list of splits. Each split is a tuple of (asset, ratio).
Returns
-------
int: The left... |
def get_certificate_issuer(self, certificate_issuer_id, **kwargs): # noqa: E501
"""Get certificate issuer by ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_certificate_i... | Get certificate issuer by ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_certificate_issuer(certificate_issuer_id, asynchronous=True)
>>> result = thread.get()
:... | Below is the the instruction that describes the task:
### Input:
Get certificate issuer by ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_certificate_issuer(certificate_issue... |
def delete_stack(self, stack_name):
"""Teardown a stack."""
get_stack(stack_name)
CLIENT.delete_stack(
StackName=stack_name
)
DELETE_WAITER.wait(StackName=stack_name) | Teardown a stack. | Below is the the instruction that describes the task:
### Input:
Teardown a stack.
### Response:
def delete_stack(self, stack_name):
"""Teardown a stack."""
get_stack(stack_name)
CLIENT.delete_stack(
StackName=stack_name
)
DELETE_WAITER.wait(StackName=stack_name) |
def collect(self):
"""
Collect xfs stats.
For an explanation of the following metrics visit
http://xfs.org/index.php/Runtime_Stats
https://github.com/torvalds/linux/blob/master/fs/xfs/xfs_stats.h
"""
data_structure = {
'extent_alloc': (
... | Collect xfs stats.
For an explanation of the following metrics visit
http://xfs.org/index.php/Runtime_Stats
https://github.com/torvalds/linux/blob/master/fs/xfs/xfs_stats.h | Below is the the instruction that describes the task:
### Input:
Collect xfs stats.
For an explanation of the following metrics visit
http://xfs.org/index.php/Runtime_Stats
https://github.com/torvalds/linux/blob/master/fs/xfs/xfs_stats.h
### Response:
def collect(self):
"""
... |
def print_user(self, user):
'''print a relational database user
'''
status = "active"
token = user.token
if token in ['finished', 'revoked']:
status = token
if token is None:
token = ''
subid = "%s\t%s[%s]" %(user.id, token, status)
print(subid)
return subid | print a relational database user | Below is the the instruction that describes the task:
### Input:
print a relational database user
### Response:
def print_user(self, user):
'''print a relational database user
'''
status = "active"
token = user.token
if token in ['finished', 'revoked']:
status = token
if token is... |
def list_nodes(full=False, call=None):
'''
list of nodes, keeping only a brief listing
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
... | list of nodes, keeping only a brief listing
CLI Example:
.. code-block:: bash
salt-cloud -Q | Below is the the instruction that describes the task:
### Input:
list of nodes, keeping only a brief listing
CLI Example:
.. code-block:: bash
salt-cloud -Q
### Response:
def list_nodes(full=False, call=None):
'''
list of nodes, keeping only a brief listing
CLI Example:
.. code... |
def send_audio(chat_id, audio,
caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None,
disable_notification=False, parse_mode=None, **kwargs):
"""
Use this method to send audio files, if you want Telegram clients to display them in the ... | Use this method to send audio files, if you want Telegram clients to display them in the music player.
Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio
files of up to 50 MB in size, this limit may be changed in the future.
For backward compatib... | Below is the the instruction that describes the task:
### Input:
Use this method to send audio files, if you want Telegram clients to display them in the music player.
Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio
files of up to 50 MB in size... |
def add_reader(self, fd, callback):
" Add read file descriptor to the event loop. "
fd = fd_to_int(fd)
self._read_fds[fd] = callback
self.selector.register(fd) | Add read file descriptor to the event loop. | Below is the the instruction that describes the task:
### Input:
Add read file descriptor to the event loop.
### Response:
def add_reader(self, fd, callback):
" Add read file descriptor to the event loop. "
fd = fd_to_int(fd)
self._read_fds[fd] = callback
self.selector.register(fd) |
def _join_disease(query, disease_definition, disease_id, disease_name):
"""helper function to add a query join to Disease model
:param sqlalchemy.orm.query.Query query: SQL Alchemy query
:param disease_definition:
:param str disease_id: see :attr:`models.Disease.disease_id`
... | helper function to add a query join to Disease model
:param sqlalchemy.orm.query.Query query: SQL Alchemy query
:param disease_definition:
:param str disease_id: see :attr:`models.Disease.disease_id`
:param disease_name:
:rtype: sqlalchemy.orm.query.Query | Below is the the instruction that describes the task:
### Input:
helper function to add a query join to Disease model
:param sqlalchemy.orm.query.Query query: SQL Alchemy query
:param disease_definition:
:param str disease_id: see :attr:`models.Disease.disease_id`
:param di... |
def receive_data(socket):
"""Receive an answer from the daemon and return the response.
Args:
socket (socket.socket): A socket that is connected to the daemon.
Returns:
dir or string: The unpickled answer.
"""
answer = b""
while True:
packet = socket.recv(4096)
if n... | Receive an answer from the daemon and return the response.
Args:
socket (socket.socket): A socket that is connected to the daemon.
Returns:
dir or string: The unpickled answer. | Below is the the instruction that describes the task:
### Input:
Receive an answer from the daemon and return the response.
Args:
socket (socket.socket): A socket that is connected to the daemon.
Returns:
dir or string: The unpickled answer.
### Response:
def receive_data(socket):
"""Rece... |
def cumulative_value(self, slip, mmax, mag_value, bbar, dbar, beta):
'''
Returns the rate of events with M > mag_value
:param float slip:
Slip rate in mm/yr
:param float mmax:
Maximum magnitude
:param float mag_value:
Magnitude value
:... | Returns the rate of events with M > mag_value
:param float slip:
Slip rate in mm/yr
:param float mmax:
Maximum magnitude
:param float mag_value:
Magnitude value
:param float bbar:
\bar{b} parameter (effectively = b * log(10.))
:par... | Below is the the instruction that describes the task:
### Input:
Returns the rate of events with M > mag_value
:param float slip:
Slip rate in mm/yr
:param float mmax:
Maximum magnitude
:param float mag_value:
Magnitude value
:param float bbar:
... |
def edit(self):
"""
Edit the SSH Key
"""
input_params = {
"name": self.name,
"public_key": self.public_key,
}
data = self.get_data(
"account/keys/%s" % self.id,
type=PUT,
params=input_params
)
... | Edit the SSH Key | Below is the the instruction that describes the task:
### Input:
Edit the SSH Key
### Response:
def edit(self):
"""
Edit the SSH Key
"""
input_params = {
"name": self.name,
"public_key": self.public_key,
}
data = self.get_data(
... |
def open(self, *args, **kwargs):
"""
Works exactly like the Telnet.open() call from the telnetlib
module, except SSL/TLS may be transparently negotiated.
"""
Telnet.open(self, *args, **kwargs)
if self.force_ssl:
self._start_tls() | Works exactly like the Telnet.open() call from the telnetlib
module, except SSL/TLS may be transparently negotiated. | Below is the the instruction that describes the task:
### Input:
Works exactly like the Telnet.open() call from the telnetlib
module, except SSL/TLS may be transparently negotiated.
### Response:
def open(self, *args, **kwargs):
"""
Works exactly like the Telnet.open() call from the telnetl... |
def geometric_progression_for_stepsize(x, update, dist, decision_function,
current_iteration):
""" Geometric progression to search for stepsize.
Keep decreasing stepsize by half until reaching
the desired side of the boundary.
"""
epsilon = dist / np.sqrt(current... | Geometric progression to search for stepsize.
Keep decreasing stepsize by half until reaching
the desired side of the boundary. | Below is the the instruction that describes the task:
### Input:
Geometric progression to search for stepsize.
Keep decreasing stepsize by half until reaching
the desired side of the boundary.
### Response:
def geometric_progression_for_stepsize(x, update, dist, decision_function,
... |
def cublasDsbmv(handle, uplo, n, k, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real symmetric-banded matrix.
"""
status = _libcublas.cublasDsbmv_v2(handle,
_CUBLAS_FILL_MODE[uplo], n, k,
ctypes.byr... | Matrix-vector product for real symmetric-banded matrix. | Below is the the instruction that describes the task:
### Input:
Matrix-vector product for real symmetric-banded matrix.
### Response:
def cublasDsbmv(handle, uplo, n, k, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real symmetric-banded matrix.
"""
status = _libcublas.cu... |
def create():
"""Create a new database with information about the films in the specified
directory or directories."""
if not all(map(os.path.isdir, ARGS.directory)):
exit('Error: One or more of the specified directories does not exist.')
with sqlite3.connect(ARGS.database) as connection:
... | Create a new database with information about the films in the specified
directory or directories. | Below is the the instruction that describes the task:
### Input:
Create a new database with information about the films in the specified
directory or directories.
### Response:
def create():
"""Create a new database with information about the films in the specified
directory or directories."""
... |
def send(self, msg):
"""Queue `msg` for sending to Nvim."""
debug('sent %s', msg)
self.loop.send(self._packer.pack(msg)) | Queue `msg` for sending to Nvim. | Below is the the instruction that describes the task:
### Input:
Queue `msg` for sending to Nvim.
### Response:
def send(self, msg):
"""Queue `msg` for sending to Nvim."""
debug('sent %s', msg)
self.loop.send(self._packer.pack(msg)) |
def protect(self, password=None, read_protect=False, protect_from=0):
"""The implementation of :meth:`nfc.tag.Tag.protect` for a generic
type 1 tag is limited to setting the NDEF data read-only for
tags that are already NDEF formatted.
"""
return super(Type1Tag, self).protect(
... | The implementation of :meth:`nfc.tag.Tag.protect` for a generic
type 1 tag is limited to setting the NDEF data read-only for
tags that are already NDEF formatted. | Below is the the instruction that describes the task:
### Input:
The implementation of :meth:`nfc.tag.Tag.protect` for a generic
type 1 tag is limited to setting the NDEF data read-only for
tags that are already NDEF formatted.
### Response:
def protect(self, password=None, read_protect=False, prot... |
def getElementsByName(self, name):
""" get element with given name,
return list of element objects regarding to 'name'
:param name: element name, case sensitive, if elements are
auto-generated from LteParser, the name should be lower cased.
"""
try:
... | get element with given name,
return list of element objects regarding to 'name'
:param name: element name, case sensitive, if elements are
auto-generated from LteParser, the name should be lower cased. | Below is the the instruction that describes the task:
### Input:
get element with given name,
return list of element objects regarding to 'name'
:param name: element name, case sensitive, if elements are
auto-generated from LteParser, the name should be lower cased.
### Resp... |
def isPe64(self):
"""
Determines if the current L{PE} instance is a PE64 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE64 file. Otherwise, returns C{False}.
"""
if self.ntHeaders.optionalHeader.magic.value == consts.PE64:
re... | Determines if the current L{PE} instance is a PE64 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE64 file. Otherwise, returns C{False}. | Below is the the instruction that describes the task:
### Input:
Determines if the current L{PE} instance is a PE64 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE64 file. Otherwise, returns C{False}.
### Response:
def isPe64(self):
"""
Determines ... |
def permission_required(perm, login_url=None, raise_exception=False):
"""
Re-implementation of the permission_required decorator, honors settings.
If ``DASHBOARD_REQUIRE_LOGIN`` is False, this decorator will always return
``True``, otherwise it will check for the permission as usual.
"""
def c... | Re-implementation of the permission_required decorator, honors settings.
If ``DASHBOARD_REQUIRE_LOGIN`` is False, this decorator will always return
``True``, otherwise it will check for the permission as usual. | Below is the the instruction that describes the task:
### Input:
Re-implementation of the permission_required decorator, honors settings.
If ``DASHBOARD_REQUIRE_LOGIN`` is False, this decorator will always return
``True``, otherwise it will check for the permission as usual.
### Response:
def permission_r... |
def call_modules(auto_discover=()):
"""
this is called in project urls.py
for registering desired modules (eg.: admin.py)
"""
for app in settings.INSTALLED_APPS:
modules = set(auto_discover)
if app in INSTALLED_APPS_REGISTER:
modules.update(INSTALLED_APPS_REGISTER[app])
... | this is called in project urls.py
for registering desired modules (eg.: admin.py) | Below is the the instruction that describes the task:
### Input:
this is called in project urls.py
for registering desired modules (eg.: admin.py)
### Response:
def call_modules(auto_discover=()):
"""
this is called in project urls.py
for registering desired modules (eg.: admin.py)
"""
for ... |
def prepare_synteny(tourfile, lastfile, odir, p, opts):
"""
Prepare synteny plots for movie().
"""
qbedfile, sbedfile = get_bed_filenames(lastfile, p, opts)
qbedfile = op.abspath(qbedfile)
sbedfile = op.abspath(sbedfile)
qbed = Bed(qbedfile, sorted=False)
contig_to_beds = dict(qbed.sub_... | Prepare synteny plots for movie(). | Below is the the instruction that describes the task:
### Input:
Prepare synteny plots for movie().
### Response:
def prepare_synteny(tourfile, lastfile, odir, p, opts):
"""
Prepare synteny plots for movie().
"""
qbedfile, sbedfile = get_bed_filenames(lastfile, p, opts)
qbedfile = op.abspath(qb... |
def hpx_to_coords(h, shape):
""" Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map."""
x, z = hpx_to_axes(h, shape)
x = np.sqrt(x[0:-1] * x[1:])
z = z[:-1] + 0.5
x = np.ravel(np.ones(shape) * x[:, np.newaxis])
z = np.... | Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map. | Below is the the instruction that describes the task:
### Input:
Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map.
### Response:
def hpx_to_coords(h, shape):
""" Generate an N x D list of pixel center coordinates where N is
the nu... |
def getloansurl(idcred, *args, **kwargs):
"""Request Loans URL.
If idcred is set, you'll get a response adequate for a MambuLoan object.
If not set, you'll get a response adequate for a MambuLoans object.
See mambuloan module and pydoc for further information.
Currently implemented filter paramete... | Request Loans URL.
If idcred is set, you'll get a response adequate for a MambuLoan object.
If not set, you'll get a response adequate for a MambuLoans object.
See mambuloan module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* accountState
* br... | Below is the the instruction that describes the task:
### Input:
Request Loans URL.
If idcred is set, you'll get a response adequate for a MambuLoan object.
If not set, you'll get a response adequate for a MambuLoans object.
See mambuloan module and pydoc for further information.
Currently impleme... |
def requires_permission(permission):
"""
View decorator that requires a certain permission to be present in
``current_auth.permissions`` before the view is allowed to proceed.
Aborts with ``403 Forbidden`` if the permission is not present.
The decorated view will have an ``is_available`` method tha... | View decorator that requires a certain permission to be present in
``current_auth.permissions`` before the view is allowed to proceed.
Aborts with ``403 Forbidden`` if the permission is not present.
The decorated view will have an ``is_available`` method that can be called
to perform the same test.
... | Below is the the instruction that describes the task:
### Input:
View decorator that requires a certain permission to be present in
``current_auth.permissions`` before the view is allowed to proceed.
Aborts with ``403 Forbidden`` if the permission is not present.
The decorated view will have an ``is_av... |
def emit(self, span_datas):
"""
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
envelopes = [self.span_data_to_envelope(sd) for sd in span_d... | :type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit | Below is the the instruction that describes the task:
### Input:
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
### Response:
def emit(self, span_datas):
"""
... |
def __substitute_objects(self, value, context_dict):
"""
recursively substitute value with the context_dict
"""
if type(value) == dict:
return dict([(k, self.__substitute_objects(v, context_dict)) for k, v in value.items()])
elif type(value) == str:
try:
... | recursively substitute value with the context_dict | Below is the the instruction that describes the task:
### Input:
recursively substitute value with the context_dict
### Response:
def __substitute_objects(self, value, context_dict):
"""
recursively substitute value with the context_dict
"""
if type(value) == dict:
retur... |
def visitAnnotation(self, ctx: ShExDocParser.AnnotationContext):
""" annotation: '//' predicate (iri | literal) """
# Annotations apply to the expression, NOT the shape (!)
annot = Annotation(self.context.predicate_to_IRI(ctx.predicate()))
if ctx.iri():
annot.object = self.co... | annotation: '//' predicate (iri | literal) | Below is the the instruction that describes the task:
### Input:
annotation: '//' predicate (iri | literal)
### Response:
def visitAnnotation(self, ctx: ShExDocParser.AnnotationContext):
""" annotation: '//' predicate (iri | literal) """
# Annotations apply to the expression, NOT the shape (!)
... |
def filter_url(pkg_type, url):
"""
Returns URL of specified file type
'source', 'egg', or 'all'
"""
bad_stuff = ["?modtime", "#md5="]
for junk in bad_stuff:
if junk in url:
url = url.split(junk)[0]
break
#pkg_spec==dev (svn)
if url.endswith("-dev"):
... | Returns URL of specified file type
'source', 'egg', or 'all' | Below is the the instruction that describes the task:
### Input:
Returns URL of specified file type
'source', 'egg', or 'all'
### Response:
def filter_url(pkg_type, url):
"""
Returns URL of specified file type
'source', 'egg', or 'all'
"""
bad_stuff = ["?modtime", "#md5="]
for junk in b... |
def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None):
"""
:param frame: current frame
:param birthframe: frame where this animation starts returning something other than None
:param startframe: frame where animation starts to evolve
:param ... | :param frame: current frame
:param birthframe: frame where this animation starts returning something other than None
:param startframe: frame where animation starts to evolve
:param stopframe: frame where animation is completed
:param deathframe: frame where animation starts to return N... | Below is the the instruction that describes the task:
### Input:
:param frame: current frame
:param birthframe: frame where this animation starts returning something other than None
:param startframe: frame where animation starts to evolve
:param stopframe: frame where animation is complete... |
def update(self, identifier, new_instance):
"""
Update an encryptable field, make sure that:
* We won't change the encryption context key
* The new value is going to be encrypted
* The return instance.plaintext is the updated one
Note: Will expunge the returned instance
... | Update an encryptable field, make sure that:
* We won't change the encryption context key
* The new value is going to be encrypted
* The return instance.plaintext is the updated one
Note: Will expunge the returned instance | Below is the the instruction that describes the task:
### Input:
Update an encryptable field, make sure that:
* We won't change the encryption context key
* The new value is going to be encrypted
* The return instance.plaintext is the updated one
Note: Will expunge the returned inst... |
def merge(self):
"""Merges the rendered blueprint into the application."""
temp_dir = self.temp_dir
app_dir = self.application.directory
for root, dirs, files in os.walk(temp_dir):
for directory in dirs:
directory = os.path.join(root, directory)
... | Merges the rendered blueprint into the application. | Below is the the instruction that describes the task:
### Input:
Merges the rendered blueprint into the application.
### Response:
def merge(self):
"""Merges the rendered blueprint into the application."""
temp_dir = self.temp_dir
app_dir = self.application.directory
for root, dirs,... |
def sum(self, property):
"""Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float
"""
self.__prepare()
total = 0
for i in self._json_data:
total += i.get(property)
return total | Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float | Below is the the instruction that describes the task:
### Input:
Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float
### Response:
def sum(self, property):
"""Getting the sum according to the given property
:@param p... |
def get_url_name(self, action_url_name="list"):
"""
Get full namespaced url name to use for reverse()
"""
url_name = "{}-{}".format(self.basename, action_url_name)
namespace = self.request.resolver_match.namespace
if namespace:
url_name = "{}:{}".format(names... | Get full namespaced url name to use for reverse() | Below is the the instruction that describes the task:
### Input:
Get full namespaced url name to use for reverse()
### Response:
def get_url_name(self, action_url_name="list"):
"""
Get full namespaced url name to use for reverse()
"""
url_name = "{}-{}".format(self.basename, action_... |
def add_logger(self, name, address, conn_type, log_dir_path=None, **kwargs):
''' Add a new stream capturer to the manager.
Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be add... | Add a new stream capturer to the manager.
Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be added to it.
Args:
name:
A string defining the new capt... | Below is the the instruction that describes the task:
### Input:
Add a new stream capturer to the manager.
Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be added to it.
A... |
def enter(self, container_alias):
'''
a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None
'''
title = '%s.enter' % self.__class__.__name__
# validate inputs
... | a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None | Below is the the instruction that describes the task:
### Input:
a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None
### Response:
def enter(self, container_alias):
'''
a method to open up a... |
def format_pixels( top, bottom, reset=True, repeat=1 ):
"""Return the ANSI escape sequence to render two vertically-stacked pixels as a
single monospace character.
top
Top colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
bottom
Bottom colou... | Return the ANSI escape sequence to render two vertically-stacked pixels as a
single monospace character.
top
Top colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
bottom
Bottom colour to use. Accepted types: None, int (xterm
palette ID),... | Below is the the instruction that describes the task:
### Input:
Return the ANSI escape sequence to render two vertically-stacked pixels as a
single monospace character.
top
Top colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
bottom
Bottom... |
def callback(self):
'''Run the callback'''
self._callback(*self._args, **self._kwargs)
self._last_checked = time.time() | Run the callback | Below is the the instruction that describes the task:
### Input:
Run the callback
### Response:
def callback(self):
'''Run the callback'''
self._callback(*self._args, **self._kwargs)
self._last_checked = time.time() |
def propose_unif(self):
"""Propose a new live point by sampling *uniformly* within
the union of ellipsoids."""
while True:
# Sample a point from the union of ellipsoids.
# Returns the point `u`, ellipsoid index `idx`, and number of
# overlapping ellipsoids `q... | Propose a new live point by sampling *uniformly* within
the union of ellipsoids. | Below is the the instruction that describes the task:
### Input:
Propose a new live point by sampling *uniformly* within
the union of ellipsoids.
### Response:
def propose_unif(self):
"""Propose a new live point by sampling *uniformly* within
the union of ellipsoids."""
while True:... |
def set_windows_permissions(filename):
'''
At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on windows
Change ... | At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on windows
Change the permissions for Allusers of the application
... | Below is the the instruction that describes the task:
### Input:
At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on wi... |
def get_longitude_variables(nc):
'''
Returns a list of all variables matching definitions for longitude
:param netcdf4.dataset nc: an open netcdf dataset object
'''
longitude_variables = []
# standard_name takes precedence
for variable in nc.get_variables_by_attributes(standard_name="longit... | Returns a list of all variables matching definitions for longitude
:param netcdf4.dataset nc: an open netcdf dataset object | Below is the the instruction that describes the task:
### Input:
Returns a list of all variables matching definitions for longitude
:param netcdf4.dataset nc: an open netcdf dataset object
### Response:
def get_longitude_variables(nc):
'''
Returns a list of all variables matching definitions for longi... |
def ping(self):
"""
Ping the LDBD Server and return any message received back as a string.
@return: message received (may be empty) from LDBD Server as a string
"""
msg = "PING\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "... | Ping the LDBD Server and return any message received back as a string.
@return: message received (may be empty) from LDBD Server as a string | Below is the the instruction that describes the task:
### Input:
Ping the LDBD Server and return any message received back as a string.
@return: message received (may be empty) from LDBD Server as a string
### Response:
def ping(self):
"""
Ping the LDBD Server and return any message received back as a... |
def default_reset_type(self):
"""! @brief One of the Target.ResetType enums.
@todo Support multiple cores.
"""
try:
resetSequence = self._info.debugs[0].attrib['defaultResetSequence']
if resetSequence == 'ResetHardware':
return Target.ResetType.HW
... | ! @brief One of the Target.ResetType enums.
@todo Support multiple cores. | Below is the the instruction that describes the task:
### Input:
! @brief One of the Target.ResetType enums.
@todo Support multiple cores.
### Response:
def default_reset_type(self):
"""! @brief One of the Target.ResetType enums.
@todo Support multiple cores.
"""
try:
... |
def close(self):
"""Cleanly shut down the SSL protocol and close the transport."""
if self._closing or self._handle.closed:
return
self._closing = True
self._write_backlog.append([b'', False])
self._process_write_backlog() | Cleanly shut down the SSL protocol and close the transport. | Below is the the instruction that describes the task:
### Input:
Cleanly shut down the SSL protocol and close the transport.
### Response:
def close(self):
"""Cleanly shut down the SSL protocol and close the transport."""
if self._closing or self._handle.closed:
return
self._clo... |
def write_all(self):
"""
Write out all registered config files.
"""
[self.write(k) for k in six.iterkeys(self.templates)] | Write out all registered config files. | Below is the the instruction that describes the task:
### Input:
Write out all registered config files.
### Response:
def write_all(self):
"""
Write out all registered config files.
"""
[self.write(k) for k in six.iterkeys(self.templates)] |
def set_lan_port(self, port_id, mac=None):
"""Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary.
"""
port_handler = _parse_physical_port_id(port_id)
port = self._find_port(port_hand... | Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary. | Below is the the instruction that describes the task:
### Input:
Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary.
### Response:
def set_lan_port(self, port_id, mac=None):
"""Set LAN port information... |
def keys(name, basepath='/etc/pki', **kwargs):
'''
Manage libvirt keys.
name
The name variable used to track the execution
basepath
Defaults to ``/etc/pki``, this is the root location used for libvirt
keys on the hypervisor
The following parameters are optional:
c... | Manage libvirt keys.
name
The name variable used to track the execution
basepath
Defaults to ``/etc/pki``, this is the root location used for libvirt
keys on the hypervisor
The following parameters are optional:
country
The country that the certificate should ... | Below is the the instruction that describes the task:
### Input:
Manage libvirt keys.
name
The name variable used to track the execution
basepath
Defaults to ``/etc/pki``, this is the root location used for libvirt
keys on the hypervisor
The following parameters are optional:
... |
def get_episode_title(episode: Episode) -> int:
"""Get the episode title.
Japanese title is prioritized.
"""
for title in episode.titles:
if title.lang == 'ja':
return title.title
else:
return episode.titles[0].title | Get the episode title.
Japanese title is prioritized. | Below is the the instruction that describes the task:
### Input:
Get the episode title.
Japanese title is prioritized.
### Response:
def get_episode_title(episode: Episode) -> int:
"""Get the episode title.
Japanese title is prioritized.
"""
for title in episode.titles:
if title.lang ... |
def schema(self, sources=None, tables=None, clean=False, force=False, use_pipeline=False):
"""
Generate destination schemas.
:param sources: If specified, build only destination tables for these sources
:param tables: If specified, build only these tables
:param clean: Delete ta... | Generate destination schemas.
:param sources: If specified, build only destination tables for these sources
:param tables: If specified, build only these tables
:param clean: Delete tables and partitions first
:param force: Population tables even if the table isn't empty
:param ... | Below is the the instruction that describes the task:
### Input:
Generate destination schemas.
:param sources: If specified, build only destination tables for these sources
:param tables: If specified, build only these tables
:param clean: Delete tables and partitions first
:param f... |
def update(self, attributes=None):
"""
Updates the entry with attributes.
"""
if attributes is None:
attributes = {}
attributes['content_type_id'] = self.sys['content_type'].id
return super(Entry, self).update(attributes) | Updates the entry with attributes. | Below is the the instruction that describes the task:
### Input:
Updates the entry with attributes.
### Response:
def update(self, attributes=None):
"""
Updates the entry with attributes.
"""
if attributes is None:
attributes = {}
attributes['content_type_id'] ... |
def time(value):
"""
Returns a time literal if value is likely coercible to a time
Parameters
----------
value : time value as string
Returns
--------
result : TimeScalar
"""
if isinstance(value, str):
value = to_time(value)
return literal(value, type=dt.time) | Returns a time literal if value is likely coercible to a time
Parameters
----------
value : time value as string
Returns
--------
result : TimeScalar | Below is the the instruction that describes the task:
### Input:
Returns a time literal if value is likely coercible to a time
Parameters
----------
value : time value as string
Returns
--------
result : TimeScalar
### Response:
def time(value):
"""
Returns a time literal if value... |
def _fmt_structured(d):
"""Formats '{k1:v1, k2:v2}' => 'time=... pid=... k1=v1 k2=v2'
Output is lexically sorted, *except* the time and pid always
come first, to assist with human scanning of the data.
"""
timeEntry = datetime.datetime.utcnow().strftime(
"time=%Y-%m-... | Formats '{k1:v1, k2:v2}' => 'time=... pid=... k1=v1 k2=v2'
Output is lexically sorted, *except* the time and pid always
come first, to assist with human scanning of the data. | Below is the the instruction that describes the task:
### Input:
Formats '{k1:v1, k2:v2}' => 'time=... pid=... k1=v1 k2=v2'
Output is lexically sorted, *except* the time and pid always
come first, to assist with human scanning of the data.
### Response:
def _fmt_structured(d):
"""Formats '... |
def execute(self, conn, primary_ds_name="", primary_ds_type="", transaction=False):
"""
Lists all primary datasets if pattern is not provided.
"""
sql = self.sql
binds = {}
#import pdb
#pdb.set_trace()
if primary_ds_name and primary_ds_type in ('', None, ... | Lists all primary datasets if pattern is not provided. | Below is the the instruction that describes the task:
### Input:
Lists all primary datasets if pattern is not provided.
### Response:
def execute(self, conn, primary_ds_name="", primary_ds_type="", transaction=False):
"""
Lists all primary datasets if pattern is not provided.
"""
s... |
def batch_parameters(self, saa, sza, p, x, y, g, s, z):
"""Takes lists for parameters and saves them as class properties
:param saa: <list> Sun Azimuth Angle (deg)
:param sza: <list> Sun Zenith Angle (deg)
:param p: <list> Phytoplankton linear scalling factor
:param x: <list> Sc... | Takes lists for parameters and saves them as class properties
:param saa: <list> Sun Azimuth Angle (deg)
:param sza: <list> Sun Zenith Angle (deg)
:param p: <list> Phytoplankton linear scalling factor
:param x: <list> Scattering scaling factor
:param y: <list> Scattering slope f... | Below is the the instruction that describes the task:
### Input:
Takes lists for parameters and saves them as class properties
:param saa: <list> Sun Azimuth Angle (deg)
:param sza: <list> Sun Zenith Angle (deg)
:param p: <list> Phytoplankton linear scalling factor
:param x: <list> ... |
def set_random_starting_grid(lfe):
"""
generate a random grid for game of life using a
set of patterns (just to make it interesting)
"""
cls_patterns = mod_grid.GameOfLifePatterns(25)
print(cls_patterns)
exit(0)
patterns = cls_patterns.get_patterns()
for pattern in patterns:
... | generate a random grid for game of life using a
set of patterns (just to make it interesting) | Below is the the instruction that describes the task:
### Input:
generate a random grid for game of life using a
set of patterns (just to make it interesting)
### Response:
def set_random_starting_grid(lfe):
"""
generate a random grid for game of life using a
set of patterns (just to make it inte... |
def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimens... | Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimension(s) to compute histogram on
num_bins (int, optional): Number of bins
bin_range (t... | Below is the the instruction that describes the task:
### Input:
Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimension(s) to compute histogram on
... |
def CollectData(self):
"""Return some current samples. Call StartDataCollection() first.
"""
while 1: # loop until we get data or a timeout
_bytes = self._ReadPacket()
if not _bytes:
return None
if len(_bytes) < 4 + 8 + 1 or _bytes[0] < 0x20 o... | Return some current samples. Call StartDataCollection() first. | Below is the the instruction that describes the task:
### Input:
Return some current samples. Call StartDataCollection() first.
### Response:
def CollectData(self):
"""Return some current samples. Call StartDataCollection() first.
"""
while 1: # loop until we get data or a timeout
... |
def __retrieve(self, key):
''' Retrieve file location from cache DB
'''
with self.get_conn() as conn:
try:
c = conn.cursor()
if key is None:
c.execute("SELECT value FROM cache_entries WHERE key IS NULL")
else:
... | Retrieve file location from cache DB | Below is the the instruction that describes the task:
### Input:
Retrieve file location from cache DB
### Response:
def __retrieve(self, key):
''' Retrieve file location from cache DB
'''
with self.get_conn() as conn:
try:
c = conn.cursor()
if key... |
def setup_logging():
"""Called when __name__ == '__main__' below. Sets up logging library.
All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages.
"""
fmt = 'DBG<0>%(pathname)s:%(lineno)d %(funcName)s: %(message)s'
handler_stderr = logging.StreamH... | Called when __name__ == '__main__' below. Sets up logging library.
All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages. | Below is the the instruction that describes the task:
### Input:
Called when __name__ == '__main__' below. Sets up logging library.
All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages.
### Response:
def setup_logging():
"""Called when __name__ == '__mai... |
def run(self, world: int) -> IO:
"""Run IO Action"""
filename, func = self._get_value()
f = self.open_func(filename)
action = func(f.read())
return action(world=world + 1) | Run IO Action | Below is the the instruction that describes the task:
### Input:
Run IO Action
### Response:
def run(self, world: int) -> IO:
"""Run IO Action"""
filename, func = self._get_value()
f = self.open_func(filename)
action = func(f.read())
return action(world=world + 1) |
def generic_visit(self, node: ast.AST) -> None:
"""Raise an exception that this node has not been handled."""
raise NotImplementedError("Unhandled recomputation of the node: {} {}".format(type(node), node)) | Raise an exception that this node has not been handled. | Below is the the instruction that describes the task:
### Input:
Raise an exception that this node has not been handled.
### Response:
def generic_visit(self, node: ast.AST) -> None:
"""Raise an exception that this node has not been handled."""
raise NotImplementedError("Unhandled recomputation of ... |
def profile_create(name, config=None, devices=None, description=None,
remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Creates a profile.
name :
The name of the profile to get.
config :
A config dict or None (None = unset).... | Creates a profile.
name :
The name of the profile to get.
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
... | Below is the the instruction that describes the task:
### Input:
Creates a profile.
name :
The name of the profile to get.
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
... |
def centroids(self, window_size=5):
"""
Detects peaks in raw data.
:param mzs: sorted array of m/z values
:param intensities: array of corresponding intensities
:param window_size: size of m/z averaging window
:returns: isotope pattern containing the centroids
:... | Detects peaks in raw data.
:param mzs: sorted array of m/z values
:param intensities: array of corresponding intensities
:param window_size: size of m/z averaging window
:returns: isotope pattern containing the centroids
:rtype: CentroidedSpectrum | Below is the the instruction that describes the task:
### Input:
Detects peaks in raw data.
:param mzs: sorted array of m/z values
:param intensities: array of corresponding intensities
:param window_size: size of m/z averaging window
:returns: isotope pattern containing the centro... |
def write(self, data):
"""Write data into the device input buffer.
:param data: single element byte
:type data: bytes
"""
logger.debug('Writing into device input buffer: %r' % data)
if not isinstance(data, bytes):
raise TypeError('data must be an instance of ... | Write data into the device input buffer.
:param data: single element byte
:type data: bytes | Below is the the instruction that describes the task:
### Input:
Write data into the device input buffer.
:param data: single element byte
:type data: bytes
### Response:
def write(self, data):
"""Write data into the device input buffer.
:param data: single element byte
:t... |
def is_time_included(self, time):
"""Check if time is included in analysis period.
Return True if time is inside this analysis period,
otherwise return False
Args:
time: A DateTime to be tested
Returns:
A boolean. True if time is included in analysis pe... | Check if time is included in analysis period.
Return True if time is inside this analysis period,
otherwise return False
Args:
time: A DateTime to be tested
Returns:
A boolean. True if time is included in analysis period | Below is the the instruction that describes the task:
### Input:
Check if time is included in analysis period.
Return True if time is inside this analysis period,
otherwise return False
Args:
time: A DateTime to be tested
Returns:
A boolean. True if time is... |
def get_all_locations(self, timeout: int=None):
"""Get a list of all locations
Parameters
----------
timeout: Optional[int] = None
Custom timeout that overwrites Client.timeout
"""
url = self.api.LOCATIONS
return self._get_model(url, timeout=timeout) | Get a list of all locations
Parameters
----------
timeout: Optional[int] = None
Custom timeout that overwrites Client.timeout | Below is the the instruction that describes the task:
### Input:
Get a list of all locations
Parameters
----------
timeout: Optional[int] = None
Custom timeout that overwrites Client.timeout
### Response:
def get_all_locations(self, timeout: int=None):
"""Get a list of ... |
def read_csv(text, sep="\t"):
"""Create a DataFrame from CSV text"""
import pandas as pd # no top level load to make a faster import of db
return pd.read_csv(StringIO(text), sep="\t") | Create a DataFrame from CSV text | Below is the the instruction that describes the task:
### Input:
Create a DataFrame from CSV text
### Response:
def read_csv(text, sep="\t"):
"""Create a DataFrame from CSV text"""
import pandas as pd # no top level load to make a faster import of db
return pd.read_csv(StringIO(text), sep="\t") |
def run(self, files, working_area):
"""
Run checks concurrently.
Returns a list of CheckResults ordered by declaration order of the checks in the imported module
"""
# Ensure that dictionary is ordered by check declaration order (via self.check_names)
# NOTE: Requires CP... | Run checks concurrently.
Returns a list of CheckResults ordered by declaration order of the checks in the imported module | Below is the the instruction that describes the task:
### Input:
Run checks concurrently.
Returns a list of CheckResults ordered by declaration order of the checks in the imported module
### Response:
def run(self, files, working_area):
"""
Run checks concurrently.
Returns a list of... |
def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, lineterminator='\n',
encoding='utf-8', skiprows=0):
"""fileobj can be a StringIO in Py3, but should be a BytesIO in Py2."""
# Python 3 version
if sys.versi... | fileobj can be a StringIO in Py3, but should be a BytesIO in Py2. | Below is the the instruction that describes the task:
### Input:
fileobj can be a StringIO in Py3, but should be a BytesIO in Py2.
### Response:
def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, lineterminator='\n',
... |
def _pnorm_diagweight(x, p, w):
"""Diagonally weighted p-norm implementation."""
# Ravel both in the same order (w is a numpy array)
order = 'F' if all(a.flags.f_contiguous for a in (x.data, w)) else 'C'
# This is faster than first applying the weights and then summing with
# BLAS dot or nrm2
x... | Diagonally weighted p-norm implementation. | Below is the the instruction that describes the task:
### Input:
Diagonally weighted p-norm implementation.
### Response:
def _pnorm_diagweight(x, p, w):
"""Diagonally weighted p-norm implementation."""
# Ravel both in the same order (w is a numpy array)
order = 'F' if all(a.flags.f_contiguous for a in... |
def upload_image(self, subreddit, image_path, name=None,
header=False, upload_as=None):
"""Upload an image to the subreddit.
:param image_path: A path to the jpg or png image you want to upload.
:param name: The name to provide the image. When None the name will be
... | Upload an image to the subreddit.
:param image_path: A path to the jpg or png image you want to upload.
:param name: The name to provide the image. When None the name will be
filename less any extension.
:param header: When True, upload the image as the subreddit header.
:pa... | Below is the the instruction that describes the task:
### Input:
Upload an image to the subreddit.
:param image_path: A path to the jpg or png image you want to upload.
:param name: The name to provide the image. When None the name will be
filename less any extension.
:param hea... |
def get_departures(self, stop_id, route, destination, api_key):
"""Get the latest data from Transport NSW."""
self.stop_id = stop_id
self.route = route
self.destination = destination
self.api_key = api_key
# Build the URL including the STOP_ID and the API key
url... | Get the latest data from Transport NSW. | Below is the the instruction that describes the task:
### Input:
Get the latest data from Transport NSW.
### Response:
def get_departures(self, stop_id, route, destination, api_key):
"""Get the latest data from Transport NSW."""
self.stop_id = stop_id
self.route = route
self.destina... |
def linkify(self, modules):
"""Link modules and Satellite links
:param modules: Module object list
:type modules: alignak.objects.module.Modules
:return: None
"""
logger.debug("Linkify %s with %s", self, modules)
self.linkify_s_by_module(modules) | Link modules and Satellite links
:param modules: Module object list
:type modules: alignak.objects.module.Modules
:return: None | Below is the the instruction that describes the task:
### Input:
Link modules and Satellite links
:param modules: Module object list
:type modules: alignak.objects.module.Modules
:return: None
### Response:
def linkify(self, modules):
"""Link modules and Satellite links
:p... |
def get_recent_state(self, current_observation):
"""Return list of last observations
# Argument
current_observation (object): Last observation
# Returns
A list of the last observations
"""
# This code is slightly complicated by the fact that subsequent o... | Return list of last observations
# Argument
current_observation (object): Last observation
# Returns
A list of the last observations | Below is the the instruction that describes the task:
### Input:
Return list of last observations
# Argument
current_observation (object): Last observation
# Returns
A list of the last observations
### Response:
def get_recent_state(self, current_observation):
"""R... |
def _count(dicts):
"""
Merge a list of dicts, summing their values.
"""
counts = defaultdict(int)
for d in dicts:
for k, v in d.items():
counts[k] += v
return counts | Merge a list of dicts, summing their values. | Below is the the instruction that describes the task:
### Input:
Merge a list of dicts, summing their values.
### Response:
def _count(dicts):
"""
Merge a list of dicts, summing their values.
"""
counts = defaultdict(int)
for d in dicts:
for k, v in d.items():
counts[k] += v... |
def iplot_hys(fignum, B, M, s):
"""
function to plot hysteresis data
This function has been adapted from pmagplotlib.iplot_hys for specific use
within a Jupyter notebook.
Parameters
-----------
fignum : reference number for matplotlib figure being created
B : list of B (flux density) v... | function to plot hysteresis data
This function has been adapted from pmagplotlib.iplot_hys for specific use
within a Jupyter notebook.
Parameters
-----------
fignum : reference number for matplotlib figure being created
B : list of B (flux density) values of hysteresis experiment
M : list ... | Below is the the instruction that describes the task:
### Input:
function to plot hysteresis data
This function has been adapted from pmagplotlib.iplot_hys for specific use
within a Jupyter notebook.
Parameters
-----------
fignum : reference number for matplotlib figure being created
B : l... |
def setText(self, label, default='', description='Set Text', format='text'):
""" Set text in a notebook pipeline (via interaction or with nbconvert) """
obj = self.load(label)
if obj == None:
obj=default
self.save(obj, label) # initialize with default
textw = T... | Set text in a notebook pipeline (via interaction or with nbconvert) | Below is the the instruction that describes the task:
### Input:
Set text in a notebook pipeline (via interaction or with nbconvert)
### Response:
def setText(self, label, default='', description='Set Text', format='text'):
""" Set text in a notebook pipeline (via interaction or with nbconvert) """
... |
def historical_identifier(self):
"""Scopus IDs of previous profiles now compromising this profile."""
hist = chained_get(self._json, ["coredata", 'historical-identifier'], [])
return [d['$'].split(":")[-1] for d in hist] or None | Scopus IDs of previous profiles now compromising this profile. | Below is the the instruction that describes the task:
### Input:
Scopus IDs of previous profiles now compromising this profile.
### Response:
def historical_identifier(self):
"""Scopus IDs of previous profiles now compromising this profile."""
hist = chained_get(self._json, ["coredata", 'historical... |
def port_knock_tcp(self, host="localhost", port=22, timeout=15):
"""Open a TCP socket to check for a listening sevice on a host.
:param host: host name or IP address, default to localhost
:param port: TCP port number, default to 22
:param timeout: Connect timeout, default to 15 seconds
... | Open a TCP socket to check for a listening sevice on a host.
:param host: host name or IP address, default to localhost
:param port: TCP port number, default to 22
:param timeout: Connect timeout, default to 15 seconds
:returns: True if successful, False if connect failed | Below is the the instruction that describes the task:
### Input:
Open a TCP socket to check for a listening sevice on a host.
:param host: host name or IP address, default to localhost
:param port: TCP port number, default to 22
:param timeout: Connect timeout, default to 15 seconds
... |
def make_raw_content_url(repo_slug, git_ref, file_path):
"""Make a raw content (raw.githubusercontent.com) URL to a file.
Parameters
----------
repo_slug : `str` or `RepoSlug`
The repository slug, formatted as either a `str` (``'owner/name'``)
or a `RepoSlug` object (created by `parse_r... | Make a raw content (raw.githubusercontent.com) URL to a file.
Parameters
----------
repo_slug : `str` or `RepoSlug`
The repository slug, formatted as either a `str` (``'owner/name'``)
or a `RepoSlug` object (created by `parse_repo_slug_from_url`).
git_ref : `str`
The git ref: a ... | Below is the the instruction that describes the task:
### Input:
Make a raw content (raw.githubusercontent.com) URL to a file.
Parameters
----------
repo_slug : `str` or `RepoSlug`
The repository slug, formatted as either a `str` (``'owner/name'``)
or a `RepoSlug` object (created by `pa... |
async def create_server(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
protocol: Type[Protocol] = None,
backlog: int = 100,
stop_event: A... | Asynchronous version of :func:`run`.
This method will take care of the operations necessary to invoke
the *before_start* events via :func:`trigger_events` method invocation
before starting the *sanic* app in Async mode.
.. note::
This does not support multiprocessing and is... | Below is the the instruction that describes the task:
### Input:
Asynchronous version of :func:`run`.
This method will take care of the operations necessary to invoke
the *before_start* events via :func:`trigger_events` method invocation
before starting the *sanic* app in Async mode.
... |
def del_hparam(self, name):
"""Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter.
"""
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name] | Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter. | Below is the the instruction that describes the task:
### Input:
Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter.
### Response:
def del_hparam(self, name):
"""Removes the hyperparameter with key 'name'.
Does nothing if it... |
def _get_encodings():
"""
Just a simple function to return the system encoding (defaults to utf-8)
"""
stdout_encoding = sys.stdout.encoding if sys.stdout.encoding else 'utf-8'
stderr_encoding = sys.stderr.encoding if sys.stderr.encoding else 'utf-8'
return stdout_encoding, stderr_encoding | Just a simple function to return the system encoding (defaults to utf-8) | Below is the the instruction that describes the task:
### Input:
Just a simple function to return the system encoding (defaults to utf-8)
### Response:
def _get_encodings():
"""
Just a simple function to return the system encoding (defaults to utf-8)
"""
stdout_encoding = sys.stdout.encoding if sys... |
def init_from_files(
vocab_file, files, target_vocab_size, threshold, min_count=None,
file_byte_limit=1e6, reserved_tokens=None):
"""Create subtoken vocabulary based on files, and save vocab to file.
Args:
vocab_file: String name of vocab file to store subtoken vocabulary.
files: List o... | Create subtoken vocabulary based on files, and save vocab to file.
Args:
vocab_file: String name of vocab file to store subtoken vocabulary.
files: List of file paths that will be used to generate vocabulary.
target_vocab_size: target vocabulary size to generate.
threshold: int threshold of... | Below is the the instruction that describes the task:
### Input:
Create subtoken vocabulary based on files, and save vocab to file.
Args:
vocab_file: String name of vocab file to store subtoken vocabulary.
files: List of file paths that will be used to generate vocabulary.
target_vocab_size: ... |
def _merge_lib_dict(d1, d2):
""" Merges lib_dict `d2` into lib_dict `d1`
"""
for required, requirings in d2.items():
if required in d1:
d1[required].update(requirings)
else:
d1[required] = requirings
return None | Merges lib_dict `d2` into lib_dict `d1` | Below is the the instruction that describes the task:
### Input:
Merges lib_dict `d2` into lib_dict `d1`
### Response:
def _merge_lib_dict(d1, d2):
""" Merges lib_dict `d2` into lib_dict `d1`
"""
for required, requirings in d2.items():
if required in d1:
d1[required].update(requirin... |
def _get_param_iterator(self):
"""Return ParameterSampler instance for the given distributions"""
return model_selection.ParameterSampler(
self.param_distributions, self.n_iter, random_state=self.random_state
) | Return ParameterSampler instance for the given distributions | Below is the the instruction that describes the task:
### Input:
Return ParameterSampler instance for the given distributions
### Response:
def _get_param_iterator(self):
"""Return ParameterSampler instance for the given distributions"""
return model_selection.ParameterSampler(
self.par... |
def reset_terminal():
''' Reset the terminal/console screen. (Also aliased to cls.)
Greater than a fullscreen terminal clear, also clears the scrollback
buffer. May expose bugs in dumb terminals.
'''
if os.name == 'nt':
from .windows import cls
cls()
else:
text ... | Reset the terminal/console screen. (Also aliased to cls.)
Greater than a fullscreen terminal clear, also clears the scrollback
buffer. May expose bugs in dumb terminals. | Below is the the instruction that describes the task:
### Input:
Reset the terminal/console screen. (Also aliased to cls.)
Greater than a fullscreen terminal clear, also clears the scrollback
buffer. May expose bugs in dumb terminals.
### Response:
def reset_terminal():
''' Reset the terminal... |
def create_shortcuts(self):
"""Create local shortcuts"""
# --- Configurable shortcuts
inspect = config_shortcut(self.inspect_current_object, context='Editor',
name='Inspect current object', parent=self)
set_breakpoint = config_shortcut(self.set_or_c... | Create local shortcuts | Below is the the instruction that describes the task:
### Input:
Create local shortcuts
### Response:
def create_shortcuts(self):
"""Create local shortcuts"""
# --- Configurable shortcuts
inspect = config_shortcut(self.inspect_current_object, context='Editor',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.