code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def writeByteArray(self, n):
"""
Writes a L{ByteArray} to the data stream.
@param n: The L{ByteArray} data to be encoded to the AMF3 data stream.
@type n: L{ByteArray}
"""
self.stream.write(TYPE_BYTEARRAY)
ref = self.context.getObjectReference(n)
if ref... | Writes a L{ByteArray} to the data stream.
@param n: The L{ByteArray} data to be encoded to the AMF3 data stream.
@type n: L{ByteArray} | Below is the the instruction that describes the task:
### Input:
Writes a L{ByteArray} to the data stream.
@param n: The L{ByteArray} data to be encoded to the AMF3 data stream.
@type n: L{ByteArray}
### Response:
def writeByteArray(self, n):
"""
Writes a L{ByteArray} to the data s... |
def get_stats(self):
"""
Get some stats on the packages in the registry
"""
try:
query = {
# We only care about the aggregations, so don't return the hits
'size': 0,
'aggs': {
'num_packages': {
... | Get some stats on the packages in the registry | Below is the the instruction that describes the task:
### Input:
Get some stats on the packages in the registry
### Response:
def get_stats(self):
"""
Get some stats on the packages in the registry
"""
try:
query = {
# We only care about the aggregations,... |
def ignore(self, matcher):
'''
Unblock and ignore the matched events, if any.
'''
events = self.eventtree.findAndRemove(matcher)
for e in events:
self.queue.unblock(e)
e.canignore = True | Unblock and ignore the matched events, if any. | Below is the the instruction that describes the task:
### Input:
Unblock and ignore the matched events, if any.
### Response:
def ignore(self, matcher):
'''
Unblock and ignore the matched events, if any.
'''
events = self.eventtree.findAndRemove(matcher)
for e in events:
... |
def get(section, key):
"""
returns the value of a given key of a given section of the main
config file.
:param section: the section.
:type section: str.
:param key: the key.
:type key: str.
:returns: the value which will be casted to float, int or boolean.
if no cast is successfull... | returns the value of a given key of a given section of the main
config file.
:param section: the section.
:type section: str.
:param key: the key.
:type key: str.
:returns: the value which will be casted to float, int or boolean.
if no cast is successfull, the raw string will be returned. | Below is the the instruction that describes the task:
### Input:
returns the value of a given key of a given section of the main
config file.
:param section: the section.
:type section: str.
:param key: the key.
:type key: str.
:returns: the value which will be casted to float, int or bool... |
def execute_tools(config, path, progress=None):
"""
Executes the suite of TidyPy tools upon the project and returns the
issues that are found.
:param config: the TidyPy configuration to use
:type config: dict
:param path: that path to the project to analyze
:type path: str
:param progre... | Executes the suite of TidyPy tools upon the project and returns the
issues that are found.
:param config: the TidyPy configuration to use
:type config: dict
:param path: that path to the project to analyze
:type path: str
:param progress:
the progress reporter object that will receive c... | Below is the the instruction that describes the task:
### Input:
Executes the suite of TidyPy tools upon the project and returns the
issues that are found.
:param config: the TidyPy configuration to use
:type config: dict
:param path: that path to the project to analyze
:type path: str
:par... |
def get_cdpp(self, flux=None):
'''
Returns the scalar CDPP for the light curve.
'''
if flux is None:
flux = self.flux
return self._mission.CDPP(self.apply_mask(flux), cadence=self.cadence) | Returns the scalar CDPP for the light curve. | Below is the the instruction that describes the task:
### Input:
Returns the scalar CDPP for the light curve.
### Response:
def get_cdpp(self, flux=None):
'''
Returns the scalar CDPP for the light curve.
'''
if flux is None:
flux = self.flux
return self._missio... |
def fast_home(self, axis, safety_margin):
''' home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home.
'''
# move some mm distance away from the target axes endstop switc... | home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home. | Below is the the instruction that describes the task:
### Input:
home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home.
### Response:
def fast_home(self, axis, safety_margin):
'''... |
def ensure_proper_casing(self):
"""Ensures proper casing of Pipfile packages"""
pfile = self.parsed_pipfile
casing_changed = self.proper_case_section(pfile.get("packages", {}))
casing_changed |= self.proper_case_section(pfile.get("dev-packages", {}))
return casing_changed | Ensures proper casing of Pipfile packages | Below is the the instruction that describes the task:
### Input:
Ensures proper casing of Pipfile packages
### Response:
def ensure_proper_casing(self):
"""Ensures proper casing of Pipfile packages"""
pfile = self.parsed_pipfile
casing_changed = self.proper_case_section(pfile.get("packages"... |
def collect(self):
"""
Collector GPU stats
"""
stats_config = self.config['stats']
if USE_PYTHON_BINDING:
collect_metrics = self.collect_via_pynvml
else:
collect_metrics = self.collect_via_nvidia_smi
collect_metrics(stats_config) | Collector GPU stats | Below is the the instruction that describes the task:
### Input:
Collector GPU stats
### Response:
def collect(self):
"""
Collector GPU stats
"""
stats_config = self.config['stats']
if USE_PYTHON_BINDING:
collect_metrics = self.collect_via_pynvml
else:
... |
def encode_gen(line, encoding="utf-8"):
"""Encodes all Unicode strings in line to encoding
Parameters
----------
line: Iterable of Unicode strings
\tDate to be encoded
encoding: String, defaults to "utf-8"
\tTarget encoding
"""
for ele in line:
if isinstance(ele, types.Uni... | Encodes all Unicode strings in line to encoding
Parameters
----------
line: Iterable of Unicode strings
\tDate to be encoded
encoding: String, defaults to "utf-8"
\tTarget encoding | Below is the the instruction that describes the task:
### Input:
Encodes all Unicode strings in line to encoding
Parameters
----------
line: Iterable of Unicode strings
\tDate to be encoded
encoding: String, defaults to "utf-8"
\tTarget encoding
### Response:
def encode_gen(line, encoding=... |
def normalize(url):
"""Normalize a URL.
>>> normalize('hTtp://ExAMPLe.COM:80')
'http://example.com/'
"""
url = url.strip()
if url == '':
return ''
parts = split(url)
if parts.scheme:
netloc = parts.netloc
if parts.scheme in SCHEMES:
path = normalize_p... | Normalize a URL.
>>> normalize('hTtp://ExAMPLe.COM:80')
'http://example.com/' | Below is the the instruction that describes the task:
### Input:
Normalize a URL.
>>> normalize('hTtp://ExAMPLe.COM:80')
'http://example.com/'
### Response:
def normalize(url):
"""Normalize a URL.
>>> normalize('hTtp://ExAMPLe.COM:80')
'http://example.com/'
"""
url = url.strip()
i... |
def set_window_rect(self, x=None, y=None, width=None, height=None):
"""
Sets the x, y coordinates of the window as well as height and width of
the current window. This method is only supported for W3C compatible
browsers; other browsers should use `set_window_position` and
`set_w... | Sets the x, y coordinates of the window as well as height and width of
the current window. This method is only supported for W3C compatible
browsers; other browsers should use `set_window_position` and
`set_window_size`.
:Usage:
::
driver.set_window_rect(x=1... | Below is the the instruction that describes the task:
### Input:
Sets the x, y coordinates of the window as well as height and width of
the current window. This method is only supported for W3C compatible
browsers; other browsers should use `set_window_position` and
`set_window_size`.
... |
def encrypted_json(self):
"""Returns an encrypted json serialized from self.
"""
json = serialize(objects=[self.instance])
encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)
return encrypted_json | Returns an encrypted json serialized from self. | Below is the the instruction that describes the task:
### Input:
Returns an encrypted json serialized from self.
### Response:
def encrypted_json(self):
"""Returns an encrypted json serialized from self.
"""
json = serialize(objects=[self.instance])
encrypted_json = Cryptor().aes_en... |
def chain(*tasks):
"""
Given a number of tasks, builds a dependency chain.
chain(task_1, task_2, task_3, task_4)
is equivalent to
task_1.set_downstream(task_2)
task_2.set_downstream(task_3)
task_3.set_downstream(task_4)
"""
for up_task, down_task in zip(tasks[:-1], tasks[1:]):
... | Given a number of tasks, builds a dependency chain.
chain(task_1, task_2, task_3, task_4)
is equivalent to
task_1.set_downstream(task_2)
task_2.set_downstream(task_3)
task_3.set_downstream(task_4) | Below is the the instruction that describes the task:
### Input:
Given a number of tasks, builds a dependency chain.
chain(task_1, task_2, task_3, task_4)
is equivalent to
task_1.set_downstream(task_2)
task_2.set_downstream(task_3)
task_3.set_downstream(task_4)
### Response:
def chain(*tasks... |
def normalize(self, text, normalizations=None):
"""Normalize a given text applying all normalizations.
Normalizations to apply can be specified through a list of
parameters and will be executed in that order.
Args:
text: The text to be processed.
normalizations:... | Normalize a given text applying all normalizations.
Normalizations to apply can be specified through a list of
parameters and will be executed in that order.
Args:
text: The text to be processed.
normalizations: List of normalizations to apply.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Normalize a given text applying all normalizations.
Normalizations to apply can be specified through a list of
parameters and will be executed in that order.
Args:
text: The text to be processed.
norma... |
def norm_int_dict(int_dict):
"""Normalizes values in the given dict with int values.
Parameters
----------
int_dict : list
A dict object mapping each key to an int value.
Returns
-------
dict
A dict where each key is mapped to its relative part in the sum of
all dic... | Normalizes values in the given dict with int values.
Parameters
----------
int_dict : list
A dict object mapping each key to an int value.
Returns
-------
dict
A dict where each key is mapped to its relative part in the sum of
all dict values.
Example
-------
... | Below is the the instruction that describes the task:
### Input:
Normalizes values in the given dict with int values.
Parameters
----------
int_dict : list
A dict object mapping each key to an int value.
Returns
-------
dict
A dict where each key is mapped to its relative p... |
def filter_user(user, using='records', interaction=None,
part_of_week='allweek', part_of_day='allday'):
"""
Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
... | Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
'records' or 'recharges'
part_of_week : {'allweek', 'weekday', 'weekend'}, default 'allweek'
* 'weekend': keep only ... | Below is the the instruction that describes the task:
### Input:
Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
'records' or 'recharges'
part_of_week : {'allweek', 'we... |
def receive(self):
"""
Generator yielding results from the web socket. Results
will come as they are received. Even though socket select
has a timeout, the SMC will not reply with a message more
than every two minutes.
"""
try:
itr = 0
whil... | Generator yielding results from the web socket. Results
will come as they are received. Even though socket select
has a timeout, the SMC will not reply with a message more
than every two minutes. | Below is the the instruction that describes the task:
### Input:
Generator yielding results from the web socket. Results
will come as they are received. Even though socket select
has a timeout, the SMC will not reply with a message more
than every two minutes.
### Response:
def receive(self... |
def setup_hfb_pars(self):
"""setup non-mult parameters for hfb (yuck!)
"""
if self.m.hfb6 is None:
self.logger.lraise("couldn't find hfb pak")
tpl_file,df = pyemu.gw_utils.write_hfb_template(self.m)
self.in_files.append(os.path.split(tpl_file.replace(".tpl",""))[-1]... | setup non-mult parameters for hfb (yuck!) | Below is the the instruction that describes the task:
### Input:
setup non-mult parameters for hfb (yuck!)
### Response:
def setup_hfb_pars(self):
"""setup non-mult parameters for hfb (yuck!)
"""
if self.m.hfb6 is None:
self.logger.lraise("couldn't find hfb pak")
tpl_fi... |
def _ss_tot(self):
"""Total sum of squares."""
return np.sum(
np.square(self.ywins - np.expand_dims(self._ybar, axis=-1)), axis=1
) | Total sum of squares. | Below is the the instruction that describes the task:
### Input:
Total sum of squares.
### Response:
def _ss_tot(self):
"""Total sum of squares."""
return np.sum(
np.square(self.ywins - np.expand_dims(self._ybar, axis=-1)), axis=1
) |
def properMotionError(G, vmini, beta, extension=0.0):
"""
Calculate the proper motion errors from G and (V-I) and the Ecliptic latitude beta of the source.
NOTE! THE ERRORS ARE FOR PROPER MOTIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE
YOUR SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
Param... | Calculate the proper motion errors from G and (V-I) and the Ecliptic latitude beta of the source.
NOTE! THE ERRORS ARE FOR PROPER MOTIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE
YOUR SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
Parameters
----------
G - Value(s) of G-band magnitude.
... | Below is the the instruction that describes the task:
### Input:
Calculate the proper motion errors from G and (V-I) and the Ecliptic latitude beta of the source.
NOTE! THE ERRORS ARE FOR PROPER MOTIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE
YOUR SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
... |
def create_or_replace_primary_key(self,
table: str,
fieldnames: Sequence[str]) -> int:
"""Make a primary key, or replace it if it exists."""
# *** create_or_replace_primary_key: Uses code specific to MySQL
sql = """
... | Make a primary key, or replace it if it exists. | Below is the the instruction that describes the task:
### Input:
Make a primary key, or replace it if it exists.
### Response:
def create_or_replace_primary_key(self,
table: str,
fieldnames: Sequence[str]) -> int:
"""Make a primary... |
def post(self):
"""Start a new profiler."""
if is_profiler_running():
self.set_status(201)
self.finish()
return
start_profiling()
self.set_status(201)
self.finish() | Start a new profiler. | Below is the the instruction that describes the task:
### Input:
Start a new profiler.
### Response:
def post(self):
"""Start a new profiler."""
if is_profiler_running():
self.set_status(201)
self.finish()
return
start_profiling()
self.set_status... |
def _download_one_night_of_atlas_data(
mjd,
log,
archivePath):
"""*summary of function*
**Key Arguments:**
- ``mjd`` -- the mjd of the night of data to download
- ``archivePath`` -- the path to the root of the local archive
"""
# SETUP A DATABASE CONNEC... | *summary of function*
**Key Arguments:**
- ``mjd`` -- the mjd of the night of data to download
- ``archivePath`` -- the path to the root of the local archive | Below is the the instruction that describes the task:
### Input:
*summary of function*
**Key Arguments:**
- ``mjd`` -- the mjd of the night of data to download
- ``archivePath`` -- the path to the root of the local archive
### Response:
def _download_one_night_of_atlas_data(
mjd,
... |
def find_pulls(self, testpulls=None):
"""Finds a list of new pull requests that need to be processed.
:arg testpulls: a list of tserver.FakePull instances so we can test the code
functionality without making live requests to github.
"""
#We check all the repositories installed... | Finds a list of new pull requests that need to be processed.
:arg testpulls: a list of tserver.FakePull instances so we can test the code
functionality without making live requests to github. | Below is the the instruction that describes the task:
### Input:
Finds a list of new pull requests that need to be processed.
:arg testpulls: a list of tserver.FakePull instances so we can test the code
functionality without making live requests to github.
### Response:
def find_pulls(self, test... |
def worker_allocator(self, async_loop, to_do, **kwargs):
""" Handler starting the asyncio part. """
d = kwargs
threading.Thread(
target=self._asyncio_thread, args=(async_loop, to_do, d)
).start() | Handler starting the asyncio part. | Below is the the instruction that describes the task:
### Input:
Handler starting the asyncio part.
### Response:
def worker_allocator(self, async_loop, to_do, **kwargs):
""" Handler starting the asyncio part. """
d = kwargs
threading.Thread(
target=self._asyncio_thread, args=(a... |
def basename_without_extension(self):
"""
Get the ``os.path.basename`` of the local file, if any, with extension removed.
"""
ret = self.basename.rsplit('.', 1)[0]
if ret.endswith('.tar'):
ret = ret[0:len(ret)-4]
return ret | Get the ``os.path.basename`` of the local file, if any, with extension removed. | Below is the the instruction that describes the task:
### Input:
Get the ``os.path.basename`` of the local file, if any, with extension removed.
### Response:
def basename_without_extension(self):
"""
Get the ``os.path.basename`` of the local file, if any, with extension removed.
"""
... |
def loadTargetPatterns(self, filename, cols = None, everyNrows = 1,
delim = ' ', checkEven = 1):
"""
Loads targets as patterns from file.
"""
self.loadTargetPatternssFromFile(filename, cols, everyNrows,
delim, checkEven... | Loads targets as patterns from file. | Below is the the instruction that describes the task:
### Input:
Loads targets as patterns from file.
### Response:
def loadTargetPatterns(self, filename, cols = None, everyNrows = 1,
delim = ' ', checkEven = 1):
"""
Loads targets as patterns from file.
"""
... |
def get_status(self):
"""Return the status embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed."""
result = ''
if self._data_struct is not None:
result = self._data_struct[KEY_STATUS]
return result | Return the status embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed. | Below is the the instruction that describes the task:
### Input:
Return the status embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed.
### Response:
def get_status(self):
"""Return the status embedded in the JSON error response body,
or an empty stri... |
def chdir(self, path):
"""
Changes the current directory to the given path
"""
self.cwd = self._join_chunks(self._normalize_path(path)) | Changes the current directory to the given path | Below is the the instruction that describes the task:
### Input:
Changes the current directory to the given path
### Response:
def chdir(self, path):
"""
Changes the current directory to the given path
"""
self.cwd = self._join_chunks(self._normalize_path(path)) |
def cert_base_path(cacert_path=None):
'''
Return the base path for certs from CLI or from options
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.cert_base_path
'''
if not cacert_path:
cacert_path = __cont... | Return the base path for certs from CLI or from options
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.cert_base_path | Below is the the instruction that describes the task:
### Input:
Return the base path for certs from CLI or from options
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.cert_base_path
### Response:
def cert_base_path(cacert_... |
def urisplit(uristring):
"""Split a well-formed URI reference string into a tuple with five
components corresponding to a URI's general structure::
<scheme>://<authority>/<path>?<query>#<fragment>
"""
if isinstance(uristring, bytes):
result = SplitResultBytes
else:
result = S... | Split a well-formed URI reference string into a tuple with five
components corresponding to a URI's general structure::
<scheme>://<authority>/<path>?<query>#<fragment> | Below is the the instruction that describes the task:
### Input:
Split a well-formed URI reference string into a tuple with five
components corresponding to a URI's general structure::
<scheme>://<authority>/<path>?<query>#<fragment>
### Response:
def urisplit(uristring):
"""Split a well-formed URI ... |
def _check_input_directory_listing(base_directory, listing):
"""
Raises an DirectoryError if files or directories, given in the listing, could not be found in the local filesystem.
:param base_directory: The path to the directory to check
:param listing: A listing given as dictionary
:raise Directo... | Raises an DirectoryError if files or directories, given in the listing, could not be found in the local filesystem.
:param base_directory: The path to the directory to check
:param listing: A listing given as dictionary
:raise DirectoryError: If the given base directory does not contain all of the subdirec... | Below is the the instruction that describes the task:
### Input:
Raises an DirectoryError if files or directories, given in the listing, could not be found in the local filesystem.
:param base_directory: The path to the directory to check
:param listing: A listing given as dictionary
:raise DirectoryEr... |
def new_mountpoint(self, name):
"""Create a new mountpoint"""
url = posixpath.join(self.path, name)
r = self._jfs.post(url, extra_headers={'content-type': 'application/x-www-form-urlencoded'})
return r | Create a new mountpoint | Below is the the instruction that describes the task:
### Input:
Create a new mountpoint
### Response:
def new_mountpoint(self, name):
"""Create a new mountpoint"""
url = posixpath.join(self.path, name)
r = self._jfs.post(url, extra_headers={'content-type': 'application/x-www-form-urlencode... |
def remove(self, repo):
"""Remove custom repository
"""
rem_repo = False
with open(self.custom_repo_file, "w") as repos:
for line in self.custom_repositories_list.splitlines():
repo_name = line.split()[0]
if repo_name != repo:
... | Remove custom repository | Below is the the instruction that describes the task:
### Input:
Remove custom repository
### Response:
def remove(self, repo):
"""Remove custom repository
"""
rem_repo = False
with open(self.custom_repo_file, "w") as repos:
for line in self.custom_repositories_list.spli... |
def from_default(cls):
"""The default security configuration.
Usually this loads the credentials stored in the configuration
directory (``~/.skein`` by default). If these credentials don't already
exist, new ones will be created.
When run in a YARN container started by Skein, t... | The default security configuration.
Usually this loads the credentials stored in the configuration
directory (``~/.skein`` by default). If these credentials don't already
exist, new ones will be created.
When run in a YARN container started by Skein, this loads the same
securit... | Below is the the instruction that describes the task:
### Input:
The default security configuration.
Usually this loads the credentials stored in the configuration
directory (``~/.skein`` by default). If these credentials don't already
exist, new ones will be created.
When run in a... |
def iter_python_modules(tile):
"""Iterate over all python products in the given tile.
This will yield tuples where the first entry is the path to the module
containing the product the second entry is the appropriate
import string to include in an entry point, and the third entry is
the entry point ... | Iterate over all python products in the given tile.
This will yield tuples where the first entry is the path to the module
containing the product the second entry is the appropriate
import string to include in an entry point, and the third entry is
the entry point name. | Below is the the instruction that describes the task:
### Input:
Iterate over all python products in the given tile.
This will yield tuples where the first entry is the path to the module
containing the product the second entry is the appropriate
import string to include in an entry point, and the thir... |
def dctmat(N,K,freqstep,orthogonalize=True):
"""Return the orthogonal DCT-II/DCT-III matrix of size NxK.
For computing or inverting MFCCs, N is the number of
log-power-spectrum bins while K is the number of cepstra."""
cosmat = numpy.zeros((N, K), 'double')
for n in range(0,N):
for k in rang... | Return the orthogonal DCT-II/DCT-III matrix of size NxK.
For computing or inverting MFCCs, N is the number of
log-power-spectrum bins while K is the number of cepstra. | Below is the the instruction that describes the task:
### Input:
Return the orthogonal DCT-II/DCT-III matrix of size NxK.
For computing or inverting MFCCs, N is the number of
log-power-spectrum bins while K is the number of cepstra.
### Response:
def dctmat(N,K,freqstep,orthogonalize=True):
"""Return t... |
async def process_lander_page(session, github_api_token, ltd_product_data,
mongo_collection=None):
"""Extract, transform, and load metadata from Lander-based projects.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session... | Extract, transform, and load metadata from Lander-based projects.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
github_api_token : `str`
A GitHub personal API token. See... | Below is the the instruction that describes the task:
### Input:
Extract, transform, and load metadata from Lander-based projects.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
... |
def resample(df, rule, time_index, groupby=None, aggregation='mean'):
"""pd.DataFrame.resample adapter.
Call the `df.resample` method on the given time_index
and afterwards call the indicated aggregation.
Optionally group the dataframe by the indicated columns before
performing the resampling.
... | pd.DataFrame.resample adapter.
Call the `df.resample` method on the given time_index
and afterwards call the indicated aggregation.
Optionally group the dataframe by the indicated columns before
performing the resampling.
If groupby option is used, the result is a multi-index datagrame.
Args... | Below is the the instruction that describes the task:
### Input:
pd.DataFrame.resample adapter.
Call the `df.resample` method on the given time_index
and afterwards call the indicated aggregation.
Optionally group the dataframe by the indicated columns before
performing the resampling.
If gro... |
def add_fields(self, *args):
"""
This method only works for extensible fields. It allows to add values without precising their fields' names
or indexes.
Parameters
----------
args: field values
"""
if not self.is_extensible():
raise TypeError(... | This method only works for extensible fields. It allows to add values without precising their fields' names
or indexes.
Parameters
----------
args: field values | Below is the the instruction that describes the task:
### Input:
This method only works for extensible fields. It allows to add values without precising their fields' names
or indexes.
Parameters
----------
args: field values
### Response:
def add_fields(self, *args):
"""
... |
def visit_RepOptional(self, node: parsing.RepOptional) -> ([ast.stmt] or
ast.expr):
"""Generates python code for an optional clause.
<code for the clause>
"""
cl_ast = self.visit(node.pt)
if isinstance(cl_ast, ast.ex... | Generates python code for an optional clause.
<code for the clause> | Below is the the instruction that describes the task:
### Input:
Generates python code for an optional clause.
<code for the clause>
### Response:
def visit_RepOptional(self, node: parsing.RepOptional) -> ([ast.stmt] or
ast.expr):
"""G... |
def skipped(x, y, method='spearman'):
"""
Skipped correlation (Rousselet and Pernet 2012).
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
method : str
Method used to compute the correlation after outlier removal. Can be... | Skipped correlation (Rousselet and Pernet 2012).
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
method : str
Method used to compute the correlation after outlier removal. Can be
either 'spearman' (default) or 'pearson'.... | Below is the the instruction that describes the task:
### Input:
Skipped correlation (Rousselet and Pernet 2012).
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
method : str
Method used to compute the correlation after outl... |
def resolve(self, definitions):
"""
Resolve named references to other WSDL objects. This includes
cross-linking information (from) the portType (to) the I{soap}
protocol information on the binding for each operation.
@param definitions: A definitions object.
@type defini... | Resolve named references to other WSDL objects. This includes
cross-linking information (from) the portType (to) the I{soap}
protocol information on the binding for each operation.
@param definitions: A definitions object.
@type definitions: L{Definitions} | Below is the the instruction that describes the task:
### Input:
Resolve named references to other WSDL objects. This includes
cross-linking information (from) the portType (to) the I{soap}
protocol information on the binding for each operation.
@param definitions: A definitions object.
... |
def from_file(cls, filename):
"""
Creates an VSGSuite instance from a filename.
:param str filename: The fully qualified path to the VSG configuration file.
"""
# Read the configuration file
config = VSGConfigParser()
if filename not in config.read([filename]):
... | Creates an VSGSuite instance from a filename.
:param str filename: The fully qualified path to the VSG configuration file. | Below is the the instruction that describes the task:
### Input:
Creates an VSGSuite instance from a filename.
:param str filename: The fully qualified path to the VSG configuration file.
### Response:
def from_file(cls, filename):
"""
Creates an VSGSuite instance from a filename.
... |
def telnet_login(
self,
pri_prompt_terminator="#",
alt_prompt_terminator=">",
username_pattern=r"Login Name:",
pwd_pattern=r"assword",
delay_factor=1,
max_loops=60,
):
"""Telnet login: can be username/password or just password."""
super(HPProcu... | Telnet login: can be username/password or just password. | Below is the the instruction that describes the task:
### Input:
Telnet login: can be username/password or just password.
### Response:
def telnet_login(
self,
pri_prompt_terminator="#",
alt_prompt_terminator=">",
username_pattern=r"Login Name:",
pwd_pattern=r"assword",
... |
def build(client, destination_args):
""" Build a SetupHandler object for client from destination parameters.
"""
# Have defined a remote job directory, lets do the setup locally.
if client.job_directory:
handler = LocalSetupHandler(client, destination_args)
else:
handler = RemoteSetu... | Build a SetupHandler object for client from destination parameters. | Below is the the instruction that describes the task:
### Input:
Build a SetupHandler object for client from destination parameters.
### Response:
def build(client, destination_args):
""" Build a SetupHandler object for client from destination parameters.
"""
# Have defined a remote job directory, lets... |
def largest_factor_relatively_prime( a, b ):
"""Return the largest factor of a relatively prime to b.
"""
while 1:
d = gcd( a, b )
if d <= 1: break
b = d
while 1:
q, r = divmod( a, d )
if r > 0:
break
a = q
return a | Return the largest factor of a relatively prime to b. | Below is the the instruction that describes the task:
### Input:
Return the largest factor of a relatively prime to b.
### Response:
def largest_factor_relatively_prime( a, b ):
"""Return the largest factor of a relatively prime to b.
"""
while 1:
d = gcd( a, b )
if d <= 1: break
b = d
while... |
def ip_link_delete(session, name):
"""
Deletes an interface record from Zebra protocol service database.
The arguments are similar to "ip link delete" command of iproute2.
:param session: Session instance connecting to database.
:param name: Name of interface.
:return: Name of interface which ... | Deletes an interface record from Zebra protocol service database.
The arguments are similar to "ip link delete" command of iproute2.
:param session: Session instance connecting to database.
:param name: Name of interface.
:return: Name of interface which was deleted. None if failed. | Below is the the instruction that describes the task:
### Input:
Deletes an interface record from Zebra protocol service database.
The arguments are similar to "ip link delete" command of iproute2.
:param session: Session instance connecting to database.
:param name: Name of interface.
:return: Na... |
def session(self):
""" Creates a context with an open SQLAlchemy session.
"""
engine = self.engine
connection = engine.connect()
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=True, bind=engine))
yield db_session
db_session.close... | Creates a context with an open SQLAlchemy session. | Below is the the instruction that describes the task:
### Input:
Creates a context with an open SQLAlchemy session.
### Response:
def session(self):
""" Creates a context with an open SQLAlchemy session.
"""
engine = self.engine
connection = engine.connect()
db_session = sco... |
def fetch_cdn_data(self, container):
"""
Returns a dict containing the CDN information for the specified
container. If the container is not CDN-enabled, returns an empty dict.
"""
name = utils.get_name(container)
uri = "/%s" % name
try:
resp, resp_body... | Returns a dict containing the CDN information for the specified
container. If the container is not CDN-enabled, returns an empty dict. | Below is the the instruction that describes the task:
### Input:
Returns a dict containing the CDN information for the specified
container. If the container is not CDN-enabled, returns an empty dict.
### Response:
def fetch_cdn_data(self, container):
"""
Returns a dict containing the CDN in... |
def get_spherical_bounding_box(lons, lats):
"""
Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:return:
A t... | Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:return:
A tuple of four items. These items represent western, easte... | Below is the the instruction that describes the task:
### Input:
Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:return... |
def remove_elaborated(type_):
"""removes type-declaration class-binder :class:`elaborated_t` from
the `type_`
If `type_` is not :class:`elaborated_t`, it will be returned as is
"""
nake_type = remove_alias(type_)
if not is_elaborated(nake_type):
return type_
else:
if isinsta... | removes type-declaration class-binder :class:`elaborated_t` from
the `type_`
If `type_` is not :class:`elaborated_t`, it will be returned as is | Below is the the instruction that describes the task:
### Input:
removes type-declaration class-binder :class:`elaborated_t` from
the `type_`
If `type_` is not :class:`elaborated_t`, it will be returned as is
### Response:
def remove_elaborated(type_):
"""removes type-declaration class-binder :class:`... |
def reset_parameter(self, params):
"""Reset parameters of Booster.
Parameters
----------
params : dict
New parameters for Booster.
Returns
-------
self : Booster
Booster with new parameters.
"""
if any(metric_alias in para... | Reset parameters of Booster.
Parameters
----------
params : dict
New parameters for Booster.
Returns
-------
self : Booster
Booster with new parameters. | Below is the the instruction that describes the task:
### Input:
Reset parameters of Booster.
Parameters
----------
params : dict
New parameters for Booster.
Returns
-------
self : Booster
Booster with new parameters.
### Response:
def reset... |
def delete(self, location_name):
"""
Remove a given location by location name. This operation is
performed only if the given location is valid, and if so,
`update` is called automatically.
:param str location: location name or location ref
:raises UpdateElementFa... | Remove a given location by location name. This operation is
performed only if the given location is valid, and if so,
`update` is called automatically.
:param str location: location name or location ref
:raises UpdateElementFailed: failed to update element with reason
:r... | Below is the the instruction that describes the task:
### Input:
Remove a given location by location name. This operation is
performed only if the given location is valid, and if so,
`update` is called automatically.
:param str location: location name or location ref
:raises... |
def get_all_remote_methods(resolver=None, ns_prefix=''):
"""
Returns a dictionary to be used for calling ``djangoCall.configure()``, which itself extends the
Angular API to the client, offering him to call remote methods.
"""
if not resolver:
resolver = get_resolver(get_urlconf())
result... | Returns a dictionary to be used for calling ``djangoCall.configure()``, which itself extends the
Angular API to the client, offering him to call remote methods. | Below is the the instruction that describes the task:
### Input:
Returns a dictionary to be used for calling ``djangoCall.configure()``, which itself extends the
Angular API to the client, offering him to call remote methods.
### Response:
def get_all_remote_methods(resolver=None, ns_prefix=''):
"""
Re... |
def get_image_for_repo(self, repo: str, branch: str, git_repo: Repo, repo_path: Path):
"""
Returns an image for the specific repo (based on settings and requirements).
1. Checks if the image already exists locally
2. Tries to pull it from registry (if ``use_registry_name`` is set)
... | Returns an image for the specific repo (based on settings and requirements).
1. Checks if the image already exists locally
2. Tries to pull it from registry (if ``use_registry_name`` is set)
3. Builds the image
4. Pushes the image to registry so the image is available next time (if ``re... | Below is the the instruction that describes the task:
### Input:
Returns an image for the specific repo (based on settings and requirements).
1. Checks if the image already exists locally
2. Tries to pull it from registry (if ``use_registry_name`` is set)
3. Builds the image
4. Push... |
def vcf_annotator(self):
"""Vcf annotator"""
tstart = datetime.now()
# python ../scripts/annotate_vcfs.py -i mm13173_14.ug.target1.vcf -r 1000genomes dbsnp138 clinvar esp6500 -a ../data/1000genomes/ALL.wgs.integrated_phase1_v3.20101123.snps_indels_sv.sites.vcf.gz ../data/dbsnp138/00-All.vcf.gz... | Vcf annotator | Below is the the instruction that describes the task:
### Input:
Vcf annotator
### Response:
def vcf_annotator(self):
"""Vcf annotator"""
tstart = datetime.now()
# python ../scripts/annotate_vcfs.py -i mm13173_14.ug.target1.vcf -r 1000genomes dbsnp138 clinvar esp6500 -a ../data/1000genome... |
def sync_entities(*model_objs):
"""
Syncs entities
Args:
model_objs (List[Model]): The model objects to sync. If empty, all entities will be synced
"""
# Check if we are deferring processing
if sync_entities.defer:
# If we dont have any model objects passed add a none to let us... | Syncs entities
Args:
model_objs (List[Model]): The model objects to sync. If empty, all entities will be synced | Below is the the instruction that describes the task:
### Input:
Syncs entities
Args:
model_objs (List[Model]): The model objects to sync. If empty, all entities will be synced
### Response:
def sync_entities(*model_objs):
"""
Syncs entities
Args:
model_objs (List[Model]): The mod... |
def copy(app, need, needs, option, need_id=None):
"""
Copies the value of one need option to another
.. code-block:: jinja
.. req:: copy-example
:id: copy_1
:tags: tag_1, tag_2, tag_3
:status: open
.. spec:: copy-example implementation
:id: copy... | Copies the value of one need option to another
.. code-block:: jinja
.. req:: copy-example
:id: copy_1
:tags: tag_1, tag_2, tag_3
:status: open
.. spec:: copy-example implementation
:id: copy_2
:status: [[copy("status", "copy_1")]]
... | Below is the the instruction that describes the task:
### Input:
Copies the value of one need option to another
.. code-block:: jinja
.. req:: copy-example
:id: copy_1
:tags: tag_1, tag_2, tag_3
:status: open
.. spec:: copy-example implementation
:i... |
def _search(self, searchterm, pred, **args):
"""
Search for things using labels
"""
# TODO: DRY with sparql_ontol_utils
searchterm = searchterm.replace('%','.*')
namedGraph = get_named_graph(self.handle)
query = """
prefix oboInOwl: <http://www.geneontolog... | Search for things using labels | Below is the the instruction that describes the task:
### Input:
Search for things using labels
### Response:
def _search(self, searchterm, pred, **args):
"""
Search for things using labels
"""
# TODO: DRY with sparql_ontol_utils
searchterm = searchterm.replace('%','.*')
... |
def query(self, variables, evidence=None, joint=True):
"""
Query method using belief propagation.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var:... | Query method using belief propagation.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
joint: boo... | Below is the the instruction that describes the task:
### Input:
Query method using belief propagation.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state... |
def _find_batch_containing_event(self, uuid):
"""Find the batch number that contains a certain event.
Parameters:
uuid -- the event uuid to search for.
returns -- a batch number, or None if not found.
"""
if self.estore.key_exists(uuid):
# Reusing alread... | Find the batch number that contains a certain event.
Parameters:
uuid -- the event uuid to search for.
returns -- a batch number, or None if not found. | Below is the the instruction that describes the task:
### Input:
Find the batch number that contains a certain event.
Parameters:
uuid -- the event uuid to search for.
returns -- a batch number, or None if not found.
### Response:
def _find_batch_containing_event(self, uuid):
"... |
def inHouseJoy(self):
""" Returns if the object is in its house of joy. """
house = self.house()
return props.object.houseJoy[self.obj.id] == house.id | Returns if the object is in its house of joy. | Below is the the instruction that describes the task:
### Input:
Returns if the object is in its house of joy.
### Response:
def inHouseJoy(self):
""" Returns if the object is in its house of joy. """
house = self.house()
return props.object.houseJoy[self.obj.id] == house.id |
def parse_zone(zonefile=None, zone=None):
'''
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
'''
if zonefile:
try:
with salt.utils.files.fopen(zonefile,... | Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone | Below is the the instruction that describes the task:
### Input:
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
### Response:
def parse_zone(zonefile=None, zone=None):
'''
Par... |
def hostedzone_from_element(zone):
"""
Construct a L{HostedZone} instance from a I{HostedZone} XML element.
"""
return HostedZone(
name=maybe_bytes_to_unicode(zone.find("Name").text).encode("ascii").decode("idna"),
identifier=maybe_bytes_to_unicode(zone.find("Id").text).replace(u"/hosted... | Construct a L{HostedZone} instance from a I{HostedZone} XML element. | Below is the the instruction that describes the task:
### Input:
Construct a L{HostedZone} instance from a I{HostedZone} XML element.
### Response:
def hostedzone_from_element(zone):
"""
Construct a L{HostedZone} instance from a I{HostedZone} XML element.
"""
return HostedZone(
name=maybe_b... |
def sub_for(expr, substitutions):
"""Substitute subexpressions in `expr` with expression to expression
mapping `substitutions`.
Parameters
----------
expr : ibis.expr.types.Expr
An Ibis expression
substitutions : List[Tuple[ibis.expr.types.Expr, ibis.expr.types.Expr]]
A mapping ... | Substitute subexpressions in `expr` with expression to expression
mapping `substitutions`.
Parameters
----------
expr : ibis.expr.types.Expr
An Ibis expression
substitutions : List[Tuple[ibis.expr.types.Expr, ibis.expr.types.Expr]]
A mapping from expression to expression. If any sub... | Below is the the instruction that describes the task:
### Input:
Substitute subexpressions in `expr` with expression to expression
mapping `substitutions`.
Parameters
----------
expr : ibis.expr.types.Expr
An Ibis expression
substitutions : List[Tuple[ibis.expr.types.Expr, ibis.expr.typ... |
def _infer_cell_type(self):
"""
Examines module_parameters and maps the Technology key for the CEC
database and the Material key for the Sandia database to a common
list of strings for cell type.
Returns
-------
cell_type: str
"""
_cell_type_di... | Examines module_parameters and maps the Technology key for the CEC
database and the Material key for the Sandia database to a common
list of strings for cell type.
Returns
-------
cell_type: str | Below is the the instruction that describes the task:
### Input:
Examines module_parameters and maps the Technology key for the CEC
database and the Material key for the Sandia database to a common
list of strings for cell type.
Returns
-------
cell_type: str
### Response:
... |
def _revert_caffe2_pad(attr):
"""Removing extra padding from Caffe2."""
if len(attr) == 4:
attr = attr[:2]
elif len(attr) == 2:
pass
else:
raise ValueError("Invalid caffe2 type padding: {}".format(attr))
return attr | Removing extra padding from Caffe2. | Below is the the instruction that describes the task:
### Input:
Removing extra padding from Caffe2.
### Response:
def _revert_caffe2_pad(attr):
"""Removing extra padding from Caffe2."""
if len(attr) == 4:
attr = attr[:2]
elif len(attr) == 2:
pass
else:
raise ValueError("Inv... |
def update_payload(self, fields=None):
"""Wrap submitted data within an extra dict."""
payload = super(Media, self).update_payload(fields)
if 'path_' in payload:
payload['path'] = payload.pop('path_')
return {u'medium': payload} | Wrap submitted data within an extra dict. | Below is the the instruction that describes the task:
### Input:
Wrap submitted data within an extra dict.
### Response:
def update_payload(self, fields=None):
"""Wrap submitted data within an extra dict."""
payload = super(Media, self).update_payload(fields)
if 'path_' in payload:
... |
def polyFitIgnoringOutliers(
x, y, deg=2, niter=3, nstd=2, return_outliers=False):
"""Returns:
(np.poly1d): callable function of polynomial fit excluding all outliers
Args:
deg (int): degree of polynomial fit
n_iter (int): do linear regression n times
succes... | Returns:
(np.poly1d): callable function of polynomial fit excluding all outliers
Args:
deg (int): degree of polynomial fit
n_iter (int): do linear regression n times
successive removing
nstd (float): exclude outliers, if their deviation
is > [nstd] *... | Below is the the instruction that describes the task:
### Input:
Returns:
(np.poly1d): callable function of polynomial fit excluding all outliers
Args:
deg (int): degree of polynomial fit
n_iter (int): do linear regression n times
successive removing
nstd (f... |
def port_channels(self):
"""list[dict]: A list of dictionary items of port channels.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.202']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... | list[dict]: A list of dictionary items of port channels.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.202']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device... | Below is the the instruction that describes the task:
### Input:
list[dict]: A list of dictionary items of port channels.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.202']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... |
def delete_comment(self, comment_id):
"""Delete a comment"""
comment_obj = self.query(Comment).get(comment_id)
if comment_obj:
logger.debug("Deleting comment {0}".format(comment_obj.id))
self.session.delete(comment_obj)
self.save()
return comment_obj | Delete a comment | Below is the the instruction that describes the task:
### Input:
Delete a comment
### Response:
def delete_comment(self, comment_id):
"""Delete a comment"""
comment_obj = self.query(Comment).get(comment_id)
if comment_obj:
logger.debug("Deleting comment {0}".format(comment_obj.... |
def is_following(self, user, obj):
""" Returns `True` or `False` """
if isinstance(user, AnonymousUser):
return False
return 0 < self.get_follows(obj).filter(user=user).count() | Returns `True` or `False` | Below is the the instruction that describes the task:
### Input:
Returns `True` or `False`
### Response:
def is_following(self, user, obj):
""" Returns `True` or `False` """
if isinstance(user, AnonymousUser):
return False
return 0 < self.get_follows(obj).filter(user=use... |
def _update_activities(self):
"""Update stored activities and update caches as required."""
self._activities = self._activities_request()
_LOGGER.debug("Device Activities Response: %s", self._activities)
if not self._activities:
self._activities = []
elif not isinsta... | Update stored activities and update caches as required. | Below is the the instruction that describes the task:
### Input:
Update stored activities and update caches as required.
### Response:
def _update_activities(self):
"""Update stored activities and update caches as required."""
self._activities = self._activities_request()
_LOGGER.debug("Dev... |
def check(self, line_info):
"""If the ifun is magic, and automagic is on, run it. Note: normal,
non-auto magic would already have been triggered via '%' in
check_esc_chars. This just checks for automagic. Also, before
triggering the magic handler, make sure that there is nothing in the... | If the ifun is magic, and automagic is on, run it. Note: normal,
non-auto magic would already have been triggered via '%' in
check_esc_chars. This just checks for automagic. Also, before
triggering the magic handler, make sure that there is nothing in the
user namespace which could sha... | Below is the the instruction that describes the task:
### Input:
If the ifun is magic, and automagic is on, run it. Note: normal,
non-auto magic would already have been triggered via '%' in
check_esc_chars. This just checks for automagic. Also, before
triggering the magic handler, make sur... |
def play(self, start_pos=0, end_pos=0, count=0):
"""Play internal color pattern
:param start_pos: pattern line to start from
:param end_pos: pattern line to end at
:param count: number of times to play, 0=play forever
"""
if ( self.dev == None ): return ''
buf = ... | Play internal color pattern
:param start_pos: pattern line to start from
:param end_pos: pattern line to end at
:param count: number of times to play, 0=play forever | Below is the the instruction that describes the task:
### Input:
Play internal color pattern
:param start_pos: pattern line to start from
:param end_pos: pattern line to end at
:param count: number of times to play, 0=play forever
### Response:
def play(self, start_pos=0, end_pos=0, count=... |
def process(self, username, password, remember=True):
"""
Process a login request
@type username: str
@type password: str
@param remember: Save the login session to disk
@type remember: bool
@raise BadLoginException: Login request failed
@... | Process a login request
@type username: str
@type password: str
@param remember: Save the login session to disk
@type remember: bool
@raise BadLoginException: Login request failed
@return: Session cookies
@rtype: cookielib.LWPCookieJar | Below is the the instruction that describes the task:
### Input:
Process a login request
@type username: str
@type password: str
@param remember: Save the login session to disk
@type remember: bool
@raise BadLoginException: Login request failed
@retur... |
def watch_log_for_alive(self, nodes, from_mark=None, timeout=720, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when thi... | Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE. | Below is the the instruction that describes the task:
### Input:
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE.
### Response:
def wa... |
def walk_transitive_dependee_graph(self,
addresses,
work,
predicate=None,
postorder=False,
prelude=None,
... | Identical to `walk_transitive_dependency_graph`, but walks dependees preorder (or postorder
if the postorder parameter is True).
This is identical to reversing the direction of every arrow in the DAG, then calling
`walk_transitive_dependency_graph`.
:API: public | Below is the the instruction that describes the task:
### Input:
Identical to `walk_transitive_dependency_graph`, but walks dependees preorder (or postorder
if the postorder parameter is True).
This is identical to reversing the direction of every arrow in the DAG, then calling
`walk_transitive_depende... |
def _create_threads(self):
"""
This method creates job instances.
"""
creator = JobCreator(
self.config,
self.observers.jobs,
self.logger
)
self.jobs = creator.job_factory() | This method creates job instances. | Below is the the instruction that describes the task:
### Input:
This method creates job instances.
### Response:
def _create_threads(self):
"""
This method creates job instances.
"""
creator = JobCreator(
self.config,
self.observers.jobs,
self.l... |
def weighted_mode(values, weights):
"""Return the value with the greatest total weight.
>>> weighted_mode('abbaa', [1,2,3,1,2])
'b'"""
totals = defaultdict(int)
for v, w in zip(values, weights):
totals[v] += w
return max(totals.keys(), key=totals.get) | Return the value with the greatest total weight.
>>> weighted_mode('abbaa', [1,2,3,1,2])
'b | Below is the the instruction that describes the task:
### Input:
Return the value with the greatest total weight.
>>> weighted_mode('abbaa', [1,2,3,1,2])
'b
### Response:
def weighted_mode(values, weights):
"""Return the value with the greatest total weight.
>>> weighted_mode('abbaa', [1,2,3,1,2])
... |
def spanishNIFNIECIFhelper(cid):
'''
Given a spanish NIF, CIF or NIE, it returns:
1 for a valid NIF
2 for a valid CIF
3 for a valid NIE
-1 for an invalid NIF (it looks like NIF but it doesn't validate the CRC)
-2 for an invalid CIF (it looks like CIF but it doesn't validate the CRC)
-3 ... | Given a spanish NIF, CIF or NIE, it returns:
1 for a valid NIF
2 for a valid CIF
3 for a valid NIE
-1 for an invalid NIF (it looks like NIF but it doesn't validate the CRC)
-2 for an invalid CIF (it looks like CIF but it doesn't validate the CRC)
-3 for an invalid NIE (it looks like NIE but id ... | Below is the the instruction that describes the task:
### Input:
Given a spanish NIF, CIF or NIE, it returns:
1 for a valid NIF
2 for a valid CIF
3 for a valid NIE
-1 for an invalid NIF (it looks like NIF but it doesn't validate the CRC)
-2 for an invalid CIF (it looks like CIF but it doesn't v... |
def remove(name: str) -> bool:
"""
Remove corpus
:param string name: corpus name
:return: True or False
"""
db = TinyDB(corpus_db_path())
temp = Query()
data = db.search(temp.name == name)
if len(data) > 0:
path = get_corpus_path(name)
os.remove(path)
db.rem... | Remove corpus
:param string name: corpus name
:return: True or False | Below is the the instruction that describes the task:
### Input:
Remove corpus
:param string name: corpus name
:return: True or False
### Response:
def remove(name: str) -> bool:
"""
Remove corpus
:param string name: corpus name
:return: True or False
"""
db = TinyDB(corpus_db_pat... |
def _parse_from_ref(cls, pairs=None, flat=None,
reference=None, serialized=None, urlsafe=None,
app=None, namespace=None, parent=None):
"""Construct a Reference; the signature is the same as for Key."""
if cls is not Key:
raise TypeError('Cannot construct Key ref... | Construct a Reference; the signature is the same as for Key. | Below is the the instruction that describes the task:
### Input:
Construct a Reference; the signature is the same as for Key.
### Response:
def _parse_from_ref(cls, pairs=None, flat=None,
reference=None, serialized=None, urlsafe=None,
app=None, namespace=None, parent=Non... |
def p_JP_hl(p):
""" asm : JP reg8_hl
| JP LP reg16i RP
"""
s = 'JP '
if p[2] == '(HL)':
s += p[2]
else:
s += '(%s)' % p[3]
p[0] = Asm(p.lineno(1), s) | asm : JP reg8_hl
| JP LP reg16i RP | Below is the the instruction that describes the task:
### Input:
asm : JP reg8_hl
| JP LP reg16i RP
### Response:
def p_JP_hl(p):
""" asm : JP reg8_hl
| JP LP reg16i RP
"""
s = 'JP '
if p[2] == '(HL)':
s += p[2]
else:
s += '(%s)' % p[3]
p[0] = Asm(p.... |
def unload_fixture(apps, schema_editor):
"Brutally deleting all entries for this model..."
MyModel = apps.get_model("blog", "Post")
MyModel.objects.all().delete() | Brutally deleting all entries for this model... | Below is the the instruction that describes the task:
### Input:
Brutally deleting all entries for this model...
### Response:
def unload_fixture(apps, schema_editor):
"Brutally deleting all entries for this model..."
MyModel = apps.get_model("blog", "Post")
MyModel.objects.all().delete() |
def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000):
"""
Return a 2D histogram the isochrone in mag-mag space.
Parameters:
-----------
distance_modulus : distance modulus to calculate histogram at
delta_mag : magnitude bin size
mass_steps : num... | Return a 2D histogram the isochrone in mag-mag space.
Parameters:
-----------
distance_modulus : distance modulus to calculate histogram at
delta_mag : magnitude bin size
mass_steps : number of steps to sample isochrone at
Returns:
--------
bins_mag_1 : ... | Below is the the instruction that describes the task:
### Input:
Return a 2D histogram the isochrone in mag-mag space.
Parameters:
-----------
distance_modulus : distance modulus to calculate histogram at
delta_mag : magnitude bin size
mass_steps : number of steps to sample ... |
def start(self, trunk_type):
"""Type of internal network trunk.
in trunk_type of type str
Type of internal network trunk.
"""
if not isinstance(trunk_type, basestring):
raise TypeError("trunk_type can only be an instance of type basestring")
self._call("... | Type of internal network trunk.
in trunk_type of type str
Type of internal network trunk. | Below is the the instruction that describes the task:
### Input:
Type of internal network trunk.
in trunk_type of type str
Type of internal network trunk.
### Response:
def start(self, trunk_type):
"""Type of internal network trunk.
in trunk_type of type str
Type o... |
def get_reaction_values(self, reaction_id):
"""Return stoichiometric values of reaction as a dictionary"""
if reaction_id not in self._reaction_set:
raise ValueError('Unknown reaction: {}'.format(repr(reaction_id)))
return self._database.get_reaction_values(reaction_id) | Return stoichiometric values of reaction as a dictionary | Below is the the instruction that describes the task:
### Input:
Return stoichiometric values of reaction as a dictionary
### Response:
def get_reaction_values(self, reaction_id):
"""Return stoichiometric values of reaction as a dictionary"""
if reaction_id not in self._reaction_set:
ra... |
def as_dict(self):
"""Return all properties and values in a dictionary (includes private properties)"""
return {config_name: getattr(self, config_name)
for config_name, _ in self._iter_config_props()} | Return all properties and values in a dictionary (includes private properties) | Below is the the instruction that describes the task:
### Input:
Return all properties and values in a dictionary (includes private properties)
### Response:
def as_dict(self):
"""Return all properties and values in a dictionary (includes private properties)"""
return {config_name: getattr(self, co... |
def flatten(input, file=None, encoding=None, errors='strict'):
"""Return a flattened representation of a cinje chunk stream.
This has several modes of operation. If no `file` argument is given, output will be returned as a string.
The type of string will be determined by the presence of an `encoding`; if one is g... | Return a flattened representation of a cinje chunk stream.
This has several modes of operation. If no `file` argument is given, output will be returned as a string.
The type of string will be determined by the presence of an `encoding`; if one is given the returned value is a
binary string, otherwise the native u... | Below is the the instruction that describes the task:
### Input:
Return a flattened representation of a cinje chunk stream.
This has several modes of operation. If no `file` argument is given, output will be returned as a string.
The type of string will be determined by the presence of an `encoding`; if one is... |
def encode_sid(cls, secret, sid):
"""Computes the HMAC for the given session id."""
secret_bytes = secret.encode("utf-8")
sid_bytes = sid.encode("utf-8")
sig = hmac.new(secret_bytes, sid_bytes, hashlib.sha512).hexdigest()
return "%s%s" % (sig, sid) | Computes the HMAC for the given session id. | Below is the the instruction that describes the task:
### Input:
Computes the HMAC for the given session id.
### Response:
def encode_sid(cls, secret, sid):
"""Computes the HMAC for the given session id."""
secret_bytes = secret.encode("utf-8")
sid_bytes = sid.encode("utf-8")
sig ... |
def download_feed_posts(self, max_count: int = None, fast_update: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None) -> None:
"""
Download pictures from the user's feed.
Example to download up to the 20 pics the user last liked::
loader ... | Download pictures from the user's feed.
Example to download up to the 20 pics the user last liked::
loader = Instaloader()
loader.load_session_from_file('USER')
loader.download_feed_posts(max_count=20, fast_update=True,
post_filter=lam... | Below is the the instruction that describes the task:
### Input:
Download pictures from the user's feed.
Example to download up to the 20 pics the user last liked::
loader = Instaloader()
loader.load_session_from_file('USER')
loader.download_feed_posts(max_count=20, fas... |
def resolve(self, token):
"""Attempts to resolve the :class:`SymbolToken` against the current table.
If the ``text`` is not None, the token is returned, otherwise, a token
in the table is attempted to be retrieved. If not token is found, then
this method will raise.
"""
... | Attempts to resolve the :class:`SymbolToken` against the current table.
If the ``text`` is not None, the token is returned, otherwise, a token
in the table is attempted to be retrieved. If not token is found, then
this method will raise. | Below is the the instruction that describes the task:
### Input:
Attempts to resolve the :class:`SymbolToken` against the current table.
If the ``text`` is not None, the token is returned, otherwise, a token
in the table is attempted to be retrieved. If not token is found, then
this method... |
def iter_comments(self, number=-1, etag=None):
"""Iterate over the comments on this pull request.
:param int number: (optional), number of comments to return. Default:
-1 returns all available comments.
:param str etag: (optional), ETag from a previous request to the same
... | Iterate over the comments on this pull request.
:param int number: (optional), number of comments to return. Default:
-1 returns all available comments.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`ReviewCo... | Below is the the instruction that describes the task:
### Input:
Iterate over the comments on this pull request.
:param int number: (optional), number of comments to return. Default:
-1 returns all available comments.
:param str etag: (optional), ETag from a previous request to the same... |
def area_lfom_orifices_top(FLOW,HL_LFOM):
"""Estimate the orifice area corresponding to the top row of orifices.
Another solution method is to use integration to solve this problem.
Here we use the width of the stout weir in the center of the top row
to estimate the area of the top orifice
"""
r... | Estimate the orifice area corresponding to the top row of orifices.
Another solution method is to use integration to solve this problem.
Here we use the width of the stout weir in the center of the top row
to estimate the area of the top orifice | Below is the the instruction that describes the task:
### Input:
Estimate the orifice area corresponding to the top row of orifices.
Another solution method is to use integration to solve this problem.
Here we use the width of the stout weir in the center of the top row
to estimate the area of the top o... |
def credential_share_simulate(self, cred_id, *user_ids):
"""Shares a given credential to the specified Users.
:param cred_id: Credential ID
:param user_ids: List of User IDs
"""
return self.raw_query("credential", "shareSimulate", data={
'id': cred_id,
'u... | Shares a given credential to the specified Users.
:param cred_id: Credential ID
:param user_ids: List of User IDs | Below is the the instruction that describes the task:
### Input:
Shares a given credential to the specified Users.
:param cred_id: Credential ID
:param user_ids: List of User IDs
### Response:
def credential_share_simulate(self, cred_id, *user_ids):
"""Shares a given credential to the spec... |
def multi_map(key, iterable, *, default_dict=False):
"""Collect data into a multi-map.
Arguments
----------
key : function
A function that accepts an element retrieved from the
iterable and returns the key to be used in the multi-map
iterable : ite... | Collect data into a multi-map.
Arguments
----------
key : function
A function that accepts an element retrieved from the
iterable and returns the key to be used in the multi-map
iterable : iterable
default_dict : boolean
Indicate... | Below is the the instruction that describes the task:
### Input:
Collect data into a multi-map.
Arguments
----------
key : function
A function that accepts an element retrieved from the
iterable and returns the key to be used in the multi-map
iterable ... |
def create_order(self, debtor, is_vat_included=True, due_date=None,
heading='', text_line1='', text_line2='',
debtor_data=None, delivery_data=None, products=None,
project=None, other_reference='', model=models.Order, **extra
):
... | Create a new Order.
Args:
debtor (Debtor): the debtor of the order
debtor_data (mapping): map of debtor data {'postal_code: .., 'city': .., 'ean': ..}
defaults to values on debitor instance for missing values
delivery_data (mapping): map of... | Below is the the instruction that describes the task:
### Input:
Create a new Order.
Args:
debtor (Debtor): the debtor of the order
debtor_data (mapping): map of debtor data {'postal_code: .., 'city': .., 'ean': ..}
defaults to values on debitor in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.