code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _augment_observation_files(self, e):
"""
Augment all the file records in an event
:internal:
"""
e.file_records = [self._augment_file(f) for f in e.file_records]
return e | Augment all the file records in an event
:internal: | Below is the the instruction that describes the task:
### Input:
Augment all the file records in an event
:internal:
### Response:
def _augment_observation_files(self, e):
"""
Augment all the file records in an event
:internal:
"""
e.file_records = [self._augment_fil... |
def Backup(self, duration=0):
'''
method to use when a backup tag is encountered in musicXML. Moves back in the bar by <duration>
:param duration:
:return:
'''
total = 0
duration_total = duration * 4
children = self.GetChildrenIndexes()
notes = 0
... | method to use when a backup tag is encountered in musicXML. Moves back in the bar by <duration>
:param duration:
:return: | Below is the the instruction that describes the task:
### Input:
method to use when a backup tag is encountered in musicXML. Moves back in the bar by <duration>
:param duration:
:return:
### Response:
def Backup(self, duration=0):
'''
method to use when a backup tag is encountered i... |
def pickle_encode(session_dict):
"Returns the given session dictionary pickled and encoded as a string."
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
return base64.encodestring(pickled + get_query_hash(pickled).encode()) | Returns the given session dictionary pickled and encoded as a string. | Below is the the instruction that describes the task:
### Input:
Returns the given session dictionary pickled and encoded as a string.
### Response:
def pickle_encode(session_dict):
"Returns the given session dictionary pickled and encoded as a string."
pickled = pickle.dumps(session_dict, pickle.HIGHEST_P... |
def transform(self, y):
"""
Transform features per specified math function.
:param y:
:return:
"""
if isinstance(y, pd.DataFrame):
x = y.ix[:,0]
y = y.ix[:,1]
else:
x = y[:,0]
y = y[:,1]
if self.transform_typ... | Transform features per specified math function.
:param y:
:return: | Below is the the instruction that describes the task:
### Input:
Transform features per specified math function.
:param y:
:return:
### Response:
def transform(self, y):
"""
Transform features per specified math function.
:param y:
:return:
"""
if isi... |
def find_harpoon_options(self, configuration, args_dict):
"""Return us all the harpoon options"""
d = lambda r: {} if r in (None, "", NotSpecified) else r
return MergedOptions.using(
dict(d(configuration.get('harpoon')).items())
, dict(d(args_dict.get("harpoon")).items(... | Return us all the harpoon options | Below is the the instruction that describes the task:
### Input:
Return us all the harpoon options
### Response:
def find_harpoon_options(self, configuration, args_dict):
"""Return us all the harpoon options"""
d = lambda r: {} if r in (None, "", NotSpecified) else r
return MergedOptions.us... |
def hash_file_contents(requirements_option: RequirementsOptions, path: Path) -> str:
""" Returns a SHA256 hash of the contents of ``path`` combined with the Arca version.
"""
return hashlib.sha256(path.read_bytes() + bytes(
requirements_option.name + arca.__version__, "utf-8"
... | Returns a SHA256 hash of the contents of ``path`` combined with the Arca version. | Below is the the instruction that describes the task:
### Input:
Returns a SHA256 hash of the contents of ``path`` combined with the Arca version.
### Response:
def hash_file_contents(requirements_option: RequirementsOptions, path: Path) -> str:
""" Returns a SHA256 hash of the contents of ``path`` combine... |
def is_valid_camel(cls, input_string, strcmp=None, ignore=''):
""" Checks to see if an input string is valid for use in camel casing
This assumes that all lowercase strings are not valid camel case situations and no camel string
can just be a capitalized word. Took ideas from here:
... | Checks to see if an input string is valid for use in camel casing
This assumes that all lowercase strings are not valid camel case situations and no camel string
can just be a capitalized word. Took ideas from here:
http://stackoverflow.com/questions/29916065/how-to-do-camelcase-spl... | Below is the the instruction that describes the task:
### Input:
Checks to see if an input string is valid for use in camel casing
This assumes that all lowercase strings are not valid camel case situations and no camel string
can just be a capitalized word. Took ideas from here:
... |
def ring_is_planar(ring, r_atoms):
"""Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic"""
normals = []
for a in r_atoms:
adj = pybel.ob.OBAtomAtomIter(a.OBAtom)
# Check for neighboring atoms in the ring
n_coords = [pybel.Atom(neigh).co... | Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic | Below is the the instruction that describes the task:
### Input:
Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic
### Response:
def ring_is_planar(ring, r_atoms):
"""Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromati... |
def coil_combine(data, w_idx=[1,2,3], coil_dim=2, sampling_rate=5000.):
"""
Combine data across coils based on the amplitude of the water peak,
according to:
.. math::
X = \sum_{i}{w_i S_i}
Where X is the resulting combined signal, $S_i$ are the individual coil
signals and $w_i$... | Combine data across coils based on the amplitude of the water peak,
according to:
.. math::
X = \sum_{i}{w_i S_i}
Where X is the resulting combined signal, $S_i$ are the individual coil
signals and $w_i$ are calculated as:
.. math::
w_i = mean(S_i) / var (S_i)
... | Below is the the instruction that describes the task:
### Input:
Combine data across coils based on the amplitude of the water peak,
according to:
.. math::
X = \sum_{i}{w_i S_i}
Where X is the resulting combined signal, $S_i$ are the individual coil
signals and $w_i$ are calculated... |
def GetSOAPHeaders(self, create_method):
"""Returns the SOAP headers required for request authorization.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers.
"""
header = create_method(self._SOAP_HE... | Returns the SOAP headers required for request authorization.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers. | Below is the the instruction that describes the task:
### Input:
Returns the SOAP headers required for request authorization.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers.
### Response:
def GetSOAPH... |
def immutable_worker(worker, state, pre_state, created):
"""Converts to an immutable slots class to handle internally."""
# noinspection PyUnresolvedReferences,PyProtectedMember
return WorkerData._make(chain(
(getattr(worker, f) for f in WORKER_OWN_FIELDS),
(state, pre_state, created),
... | Converts to an immutable slots class to handle internally. | Below is the the instruction that describes the task:
### Input:
Converts to an immutable slots class to handle internally.
### Response:
def immutable_worker(worker, state, pre_state, created):
"""Converts to an immutable slots class to handle internally."""
# noinspection PyUnresolvedReferences,PyProtect... |
def _get_asam_configuration(driver_url=''):
'''
Return the configuration read from the master configuration
file or directory
'''
asam_config = __opts__['asam'] if 'asam' in __opts__ else None
if asam_config:
try:
for asam_server, service_config in six.iteritems(asam_config)... | Return the configuration read from the master configuration
file or directory | Below is the the instruction that describes the task:
### Input:
Return the configuration read from the master configuration
file or directory
### Response:
def _get_asam_configuration(driver_url=''):
'''
Return the configuration read from the master configuration
file or directory
'''
asam... |
def _increment(self, n=1):
"""Move forward n tokens in the stream."""
if self._cur_position >= self.num_tokens-1:
self._cur_positon = self.num_tokens - 1
self._finished = True
else:
self._cur_position += n | Move forward n tokens in the stream. | Below is the the instruction that describes the task:
### Input:
Move forward n tokens in the stream.
### Response:
def _increment(self, n=1):
"""Move forward n tokens in the stream."""
if self._cur_position >= self.num_tokens-1:
self._cur_positon = self.num_tokens - 1
self.... |
def _get_result_constructor(self):
""" Returns a function that will be used to instantiate query results """
if not self._values_list: # we want models
return self.model._construct_instance
elif self._flat_values_list: # the user has requested flattened list (1 value per row)
... | Returns a function that will be used to instantiate query results | Below is the the instruction that describes the task:
### Input:
Returns a function that will be used to instantiate query results
### Response:
def _get_result_constructor(self):
""" Returns a function that will be used to instantiate query results """
if not self._values_list: # we want models
... |
def save_diskspace(fname, reason, config):
"""Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message.
"""
if config["algorithm"].get("save_diskspace", False):
for ext in ["",... | Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message. | Below is the the instruction that describes the task:
### Input:
Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message.
### Response:
def save_diskspace(fname, reason, config):
"""Over... |
def cast(self, method, args={}, declare=None, retry=None,
retry_policy=None, type=None, exchange=None, **props):
"""Send message to actor. Discarding replies."""
retry = self.retry if retry is None else retry
body = {'class': self.name, 'method': method, 'args': args}
_ret... | Send message to actor. Discarding replies. | Below is the the instruction that describes the task:
### Input:
Send message to actor. Discarding replies.
### Response:
def cast(self, method, args={}, declare=None, retry=None,
retry_policy=None, type=None, exchange=None, **props):
"""Send message to actor. Discarding replies."""
... |
def pass_to_pipeline_if_article(
self,
response,
source_domain,
original_url,
rss_title=None
):
"""
Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scr... | Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
:param str original_url: the url set in the json file
:param ... | Below is the the instruction that describes the task:
### Input:
Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
... |
def update_service(self, service_id, **kwargs):
"""Update a service."""
body = self._formdata(kwargs, FastlyService.FIELDS)
content = self._fetch("/service/%s" % service_id, method="PUT", body=body)
return FastlyService(self, content) | Update a service. | Below is the the instruction that describes the task:
### Input:
Update a service.
### Response:
def update_service(self, service_id, **kwargs):
"""Update a service."""
body = self._formdata(kwargs, FastlyService.FIELDS)
content = self._fetch("/service/%s" % service_id, method="PUT", body=body)
return Fast... |
def get_template_name(self):
"""
Get the template name of this page if defined or if a closer
parent has a defined template or
:data:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise.
"""
template = self.get_template()
page_templates = settings.get_page_templates()... | Get the template name of this page if defined or if a closer
parent has a defined template or
:data:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise. | Below is the the instruction that describes the task:
### Input:
Get the template name of this page if defined or if a closer
parent has a defined template or
:data:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise.
### Response:
def get_template_name(self):
"""
Get the template name... |
def score(package_path):
"""
Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score
"""
python_files = find_files(package_path, '*.py')
total_counter = Counter()
for python_file in python_files:... | Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score | Below is the the instruction that describes the task:
### Input:
Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score
### Response:
def score(package_path):
"""
Runs pylint on a package and returns a score... |
def replace_vcf_info(keyword, annotation, variant_line=None, variant_dict=None):
"""Replace the information of a info field of a vcf variant line or a
variant dict.
Arguments:
variant_line (str): A vcf formatted variant line
variant_dict (dict): A variant dictionary
keyword... | Replace the information of a info field of a vcf variant line or a
variant dict.
Arguments:
variant_line (str): A vcf formatted variant line
variant_dict (dict): A variant dictionary
keyword (str): The info field key
annotation (str): If the annotation is a key, value p... | Below is the the instruction that describes the task:
### Input:
Replace the information of a info field of a vcf variant line or a
variant dict.
Arguments:
variant_line (str): A vcf formatted variant line
variant_dict (dict): A variant dictionary
keyword (str): The info fi... |
def primitive(self, primitive):
"""Entry from Python primitive."""
self.entry_number = primitive['entry-number']
self.item_hash = primitive['item-hash']
self.timestamp = primitive['timestamp'] | Entry from Python primitive. | Below is the the instruction that describes the task:
### Input:
Entry from Python primitive.
### Response:
def primitive(self, primitive):
"""Entry from Python primitive."""
self.entry_number = primitive['entry-number']
self.item_hash = primitive['item-hash']
self.timestamp = primi... |
def interpolate_exe(self, testString):
"""
Replace testString with a path to an executable based on the format.
If this looks like
${which:lalapps_tmpltbank}
it will return the equivalent of which(lalapps_tmpltbank)
Otherwise it will return an unchanged string.
... | Replace testString with a path to an executable based on the format.
If this looks like
${which:lalapps_tmpltbank}
it will return the equivalent of which(lalapps_tmpltbank)
Otherwise it will return an unchanged string.
Parameters
-----------
testString : stri... | Below is the the instruction that describes the task:
### Input:
Replace testString with a path to an executable based on the format.
If this looks like
${which:lalapps_tmpltbank}
it will return the equivalent of which(lalapps_tmpltbank)
Otherwise it will return an unchanged stri... |
def client_get(self, url, **kwargs):
"""Send GET request with given url."""
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response... | Send GET request with given url. | Below is the the instruction that describes the task:
### Input:
Send GET request with given url.
### Response:
def client_get(self, url, **kwargs):
"""Send GET request with given url."""
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise... |
def fstab_present(name, fs_file, fs_vfstype, fs_mntops='defaults',
fs_freq=0, fs_passno=0, mount_by=None,
config='/etc/fstab', mount=True, match_on='auto'):
'''
Makes sure that a fstab mount point is pressent.
name
The name of block device. Can be any valid fs_sp... | Makes sure that a fstab mount point is pressent.
name
The name of block device. Can be any valid fs_spec value.
fs_file
Mount point (target) for the filesystem.
fs_vfstype
The type of the filesystem (e.g. ext4, xfs, btrfs, ...)
fs_mntops
The mount options associated w... | Below is the the instruction that describes the task:
### Input:
Makes sure that a fstab mount point is pressent.
name
The name of block device. Can be any valid fs_spec value.
fs_file
Mount point (target) for the filesystem.
fs_vfstype
The type of the filesystem (e.g. ext4, x... |
def do_PROPPATCH(self, environ, start_response):
"""Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
"""
path = environ["PATH_INFO"]
res = self._davProvider.get_resource_inst(path, environ)
# Only accep... | Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH | Below is the the instruction that describes the task:
### Input:
Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
### Response:
def do_PROPPATCH(self, environ, start_response):
"""Handle PROPPATCH request to set or remove a proper... |
def _add_image_part(self, image):
"""
Return an |ImagePart| instance newly created from image and appended
to the collection.
"""
partname = self._next_image_partname(image.ext)
image_part = ImagePart.from_image(image, partname)
self.append(image_part)
ret... | Return an |ImagePart| instance newly created from image and appended
to the collection. | Below is the the instruction that describes the task:
### Input:
Return an |ImagePart| instance newly created from image and appended
to the collection.
### Response:
def _add_image_part(self, image):
"""
Return an |ImagePart| instance newly created from image and appended
to the co... |
def generate_ucsm_handle(hostname, username, password):
""" Creates UCS Manager handle object and establishes a session with
UCS Manager.
:param hostname: UCS Manager hostname or IP-address
:param username: Username to login to UCS Manager
:param password: Login user password
:rais... | Creates UCS Manager handle object and establishes a session with
UCS Manager.
:param hostname: UCS Manager hostname or IP-address
:param username: Username to login to UCS Manager
:param password: Login user password
:raises UcsConnectionError: In case of error. | Below is the the instruction that describes the task:
### Input:
Creates UCS Manager handle object and establishes a session with
UCS Manager.
:param hostname: UCS Manager hostname or IP-address
:param username: Username to login to UCS Manager
:param password: Login user password
... |
def recursive_cov(self, cov, length, mean, chain, scaling=1, epsilon=0):
r"""Compute the covariance recursively.
Return the new covariance and the new mean.
.. math::
C_k & = \frac{1}{k-1} (\sum_{i=1}^k x_i x_i^T - k\bar{x_k}\bar{x_k}^T)
C_n & = \frac{1}{n-1} (\sum_{i=1... | r"""Compute the covariance recursively.
Return the new covariance and the new mean.
.. math::
C_k & = \frac{1}{k-1} (\sum_{i=1}^k x_i x_i^T - k\bar{x_k}\bar{x_k}^T)
C_n & = \frac{1}{n-1} (\sum_{i=1}^k x_i x_i^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
... | Below is the the instruction that describes the task:
### Input:
r"""Compute the covariance recursively.
Return the new covariance and the new mean.
.. math::
C_k & = \frac{1}{k-1} (\sum_{i=1}^k x_i x_i^T - k\bar{x_k}\bar{x_k}^T)
C_n & = \frac{1}{n-1} (\sum_{i=1}^k x_i x_i^... |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None
"""
if self.parent.is_selected_layer_keywordless:
# insert keyword creation thread here
self.parent... | Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None | Below is the the instruction that describes the task:
### Input:
Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None
### Response:
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
... |
def printer(self, message, color_level='info'):
"""Print Messages and Log it.
:param message: item to print to screen
"""
if self.job_args.get('colorized'):
print(cloud_utils.return_colorized(msg=message, color=color_level))
else:
print(message) | Print Messages and Log it.
:param message: item to print to screen | Below is the the instruction that describes the task:
### Input:
Print Messages and Log it.
:param message: item to print to screen
### Response:
def printer(self, message, color_level='info'):
"""Print Messages and Log it.
:param message: item to print to screen
"""
if s... |
def _get_col_dimstr(tdim, is_string=False):
"""
not for variable length
"""
dimstr = ''
if tdim is None:
dimstr = 'array[bad TDIM]'
else:
if is_string:
if len(tdim) > 1:
dimstr = [str(d) for d in tdim[1:]]
else:
if len(tdim) > 1 or ... | not for variable length | Below is the the instruction that describes the task:
### Input:
not for variable length
### Response:
def _get_col_dimstr(tdim, is_string=False):
"""
not for variable length
"""
dimstr = ''
if tdim is None:
dimstr = 'array[bad TDIM]'
else:
if is_string:
if len(t... |
def show_disk(name=None, kwargs=None, call=None): # pylint: disable=W0613
'''
Show the details of an existing disk.
CLI Example:
.. code-block:: bash
salt-cloud -a show_disk myinstance disk_name=mydisk
salt-cloud -f show_disk gce disk_name=mydisk
'''
if not kwargs or 'disk_na... | Show the details of an existing disk.
CLI Example:
.. code-block:: bash
salt-cloud -a show_disk myinstance disk_name=mydisk
salt-cloud -f show_disk gce disk_name=mydisk | Below is the the instruction that describes the task:
### Input:
Show the details of an existing disk.
CLI Example:
.. code-block:: bash
salt-cloud -a show_disk myinstance disk_name=mydisk
salt-cloud -f show_disk gce disk_name=mydisk
### Response:
def show_disk(name=None, kwargs=None, ca... |
def get_environment(self):
"""
Get environment facts.
power and fan are currently not implemented
cpu is using 1-minute average
cpu hard-coded to cpu0 (i.e. only a single CPU)
"""
environment = {}
cpu_cmd = 'show proc cpu'
mem_cmd = 'show memory s... | Get environment facts.
power and fan are currently not implemented
cpu is using 1-minute average
cpu hard-coded to cpu0 (i.e. only a single CPU) | Below is the the instruction that describes the task:
### Input:
Get environment facts.
power and fan are currently not implemented
cpu is using 1-minute average
cpu hard-coded to cpu0 (i.e. only a single CPU)
### Response:
def get_environment(self):
"""
Get environment fac... |
def loadScopeGroupbyID(self, id, callback=None, errback=None):
"""
Load an existing Scope Group by ID into a high level Scope Group object
:param int id: id of an existing ScopeGroup
"""
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, id=id)
return... | Load an existing Scope Group by ID into a high level Scope Group object
:param int id: id of an existing ScopeGroup | Below is the the instruction that describes the task:
### Input:
Load an existing Scope Group by ID into a high level Scope Group object
:param int id: id of an existing ScopeGroup
### Response:
def loadScopeGroupbyID(self, id, callback=None, errback=None):
"""
Load an existing Scope Group... |
def mean(self, values, axis=0, weights=None, dtype=None):
"""compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
wei... | compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for e... | Below is the the instruction that describes the task:
### Input:
compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
wei... |
def create(self, name, data):
"""Create a Job Binary Internal.
:param str data: raw data of script text
"""
return self._update('/job-binary-internals/%s' %
urlparse.quote(name.encode('utf-8')), data,
'job_binary_internal', dump_js... | Create a Job Binary Internal.
:param str data: raw data of script text | Below is the the instruction that describes the task:
### Input:
Create a Job Binary Internal.
:param str data: raw data of script text
### Response:
def create(self, name, data):
"""Create a Job Binary Internal.
:param str data: raw data of script text
"""
return self._up... |
def update(request, ident, stateless=False, **kwargs):
'Generate update json response'
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode('utf-8'))
if app.use_dash_dispatch():
# Force call through dash
view_func = app.locate_endpoint_fun... | Generate update json response | Below is the the instruction that describes the task:
### Input:
Generate update json response
### Response:
def update(request, ident, stateless=False, **kwargs):
'Generate update json response'
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode('utf-8... |
def processes(self, processes):
'''Set the number of concurrent processes the ABC will utilize for
fitness function evaluation; if <= 1, single process is used
Args:
processes (int): number of concurrent processes
'''
if self._processes > 1:
self._pool.c... | Set the number of concurrent processes the ABC will utilize for
fitness function evaluation; if <= 1, single process is used
Args:
processes (int): number of concurrent processes | Below is the the instruction that describes the task:
### Input:
Set the number of concurrent processes the ABC will utilize for
fitness function evaluation; if <= 1, single process is used
Args:
processes (int): number of concurrent processes
### Response:
def processes(self, processe... |
def load_path(path, overrides=None, **kwargs):
"""
Convenience function for loading a YAML configuration from a file.
Parameters
----------
path : str
The path to the file to load on disk.
overrides : dict, optional
A dictionary containing overrides to apply. The location of
... | Convenience function for loading a YAML configuration from a file.
Parameters
----------
path : str
The path to the file to load on disk.
overrides : dict, optional
A dictionary containing overrides to apply. The location of
the override is specified in the key as a dot-delimite... | Below is the the instruction that describes the task:
### Input:
Convenience function for loading a YAML configuration from a file.
Parameters
----------
path : str
The path to the file to load on disk.
overrides : dict, optional
A dictionary containing overrides to apply. The locat... |
def stop_app(self):
"""Overrides superclass."""
try:
if self._conn:
# Be polite; let the dest know we're shutting down.
try:
self.closeSl4aSession()
except:
self.log.exception('Failed to gracefully shut d... | Overrides superclass. | Below is the the instruction that describes the task:
### Input:
Overrides superclass.
### Response:
def stop_app(self):
"""Overrides superclass."""
try:
if self._conn:
# Be polite; let the dest know we're shutting down.
try:
self.clos... |
def get_evidence_by_hash(self, evidence_hash: str) -> Optional[Evidence]:
"""Look up an evidence by its hash."""
return self.session.query(Evidence).filter(Evidence.sha512 == evidence_hash).one_or_none() | Look up an evidence by its hash. | Below is the the instruction that describes the task:
### Input:
Look up an evidence by its hash.
### Response:
def get_evidence_by_hash(self, evidence_hash: str) -> Optional[Evidence]:
"""Look up an evidence by its hash."""
return self.session.query(Evidence).filter(Evidence.sha512 == evidence_has... |
def reduce_data_frame (df, chunk_slicers,
avg_cols=(),
uavg_cols=(),
minmax_cols=(),
nchunk_colname='nchunk',
uncert_prefix='u',
min_points_per_chunk=3):
""""Reduce" a DataFrame ... | Reduce" a DataFrame by collapsing rows in grouped chunks. Returns another
DataFrame with similar columns but fewer rows.
Arguments:
df
The input :class:`pandas.DataFrame`.
chunk_slicers
An iterable that returns values that are used to slice *df* with its
:meth:`pandas.DataFrame.iloc`... | Below is the the instruction that describes the task:
### Input:
Reduce" a DataFrame by collapsing rows in grouped chunks. Returns another
DataFrame with similar columns but fewer rows.
Arguments:
df
The input :class:`pandas.DataFrame`.
chunk_slicers
An iterable that returns values tha... |
def invoke_ssh_shell(cls, *args, **kwargs):
"""invoke_ssh(arguments..., pty=False, echo=False)
Star a new shell on a remote server. It first calls
:meth:`Flow.connect_ssh` using all positional and keyword
arguments, then calls :meth:`SSHClient.invoke_shell` with the
pty / echo o... | invoke_ssh(arguments..., pty=False, echo=False)
Star a new shell on a remote server. It first calls
:meth:`Flow.connect_ssh` using all positional and keyword
arguments, then calls :meth:`SSHClient.invoke_shell` with the
pty / echo options.
Args:
arguments...: The op... | Below is the the instruction that describes the task:
### Input:
invoke_ssh(arguments..., pty=False, echo=False)
Star a new shell on a remote server. It first calls
:meth:`Flow.connect_ssh` using all positional and keyword
arguments, then calls :meth:`SSHClient.invoke_shell` with the
... |
def post_fork_child(self):
"""Post-fork() child callback for ProcessManager.daemon_spawn()."""
entry_point = '{}:launch'.format(__name__)
exec_env = combined_dict(os.environ, dict(PANTS_ENTRYPOINT=entry_point))
# Pass all of sys.argv so that we can proxy arg flags e.g. `-ldebug`.
cmd = [sys.executab... | Post-fork() child callback for ProcessManager.daemon_spawn(). | Below is the the instruction that describes the task:
### Input:
Post-fork() child callback for ProcessManager.daemon_spawn().
### Response:
def post_fork_child(self):
"""Post-fork() child callback for ProcessManager.daemon_spawn()."""
entry_point = '{}:launch'.format(__name__)
exec_env = combined_dict... |
def indication(self, pdu):
"""Message going downstream."""
if _debug: StreamToPacket._debug("indication %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.downstreamBuffer):
self.request(packet) | Message going downstream. | Below is the the instruction that describes the task:
### Input:
Message going downstream.
### Response:
def indication(self, pdu):
"""Message going downstream."""
if _debug: StreamToPacket._debug("indication %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self... |
def assignMgtKey(self, CorpNum, MgtKeyType, ItemKey, MgtKey, UserID=None):
""" 관리번호할당
args
CorpNum : 팝빌회원 사업자번호
MgtKeyType : 세금계산서 유형, SELL-매출, BUY-매입, TRUSTEE-위수탁
ItemKey : 아이템키 (Search API로 조회 가능)
MgtKey : 세금계산서에 할당할 파트너 관리 번호
... | 관리번호할당
args
CorpNum : 팝빌회원 사업자번호
MgtKeyType : 세금계산서 유형, SELL-매출, BUY-매입, TRUSTEE-위수탁
ItemKey : 아이템키 (Search API로 조회 가능)
MgtKey : 세금계산서에 할당할 파트너 관리 번호
UserID : 팝빌회원 아이디
return
처리결과. consist of code and... | Below is the the instruction that describes the task:
### Input:
관리번호할당
args
CorpNum : 팝빌회원 사업자번호
MgtKeyType : 세금계산서 유형, SELL-매출, BUY-매입, TRUSTEE-위수탁
ItemKey : 아이템키 (Search API로 조회 가능)
MgtKey : 세금계산서에 할당할 파트너 관리 번호
UserID : ... |
def get_conditional_probs(self, source=None):
"""Returns the full conditional probabilities table as a numpy array,
where row i*(k+1) + ly is the conditional probabilities of source i
emmiting label ly (including abstains 0), conditioned on different
values of Y, i.e.:
c_pro... | Returns the full conditional probabilities table as a numpy array,
where row i*(k+1) + ly is the conditional probabilities of source i
emmiting label ly (including abstains 0), conditioned on different
values of Y, i.e.:
c_probs[i*(k+1) + ly, y] = P(\lambda_i = ly | Y = y)
... | Below is the the instruction that describes the task:
### Input:
Returns the full conditional probabilities table as a numpy array,
where row i*(k+1) + ly is the conditional probabilities of source i
emmiting label ly (including abstains 0), conditioned on different
values of Y, i.e.:
... |
def _build_register_function(universe: bool, in_place: bool): # noqa: D202
"""Build a decorator function to tag transformation functions.
:param universe: Does the first positional argument of this function correspond to a universe graph?
:param in_place: Does this function return a new graph, or just mod... | Build a decorator function to tag transformation functions.
:param universe: Does the first positional argument of this function correspond to a universe graph?
:param in_place: Does this function return a new graph, or just modify it in-place? | Below is the the instruction that describes the task:
### Input:
Build a decorator function to tag transformation functions.
:param universe: Does the first positional argument of this function correspond to a universe graph?
:param in_place: Does this function return a new graph, or just modify it in-plac... |
def p_expr_usr(p):
""" bexpr : USR bexpr %prec UMINUS
"""
if p[2].type_ == TYPE.string:
p[0] = make_builtin(p.lineno(1), 'USR_STR', p[2], type_=TYPE.uinteger)
else:
p[0] = make_builtin(p.lineno(1), 'USR',
make_typecast(TYPE.uinteger, p[2], p.lineno(1)),
... | bexpr : USR bexpr %prec UMINUS | Below is the the instruction that describes the task:
### Input:
bexpr : USR bexpr %prec UMINUS
### Response:
def p_expr_usr(p):
""" bexpr : USR bexpr %prec UMINUS
"""
if p[2].type_ == TYPE.string:
p[0] = make_builtin(p.lineno(1), 'USR_STR', p[2], type_=TYPE.uinteger)
else:
p[0] = m... |
def WaitHotKeyReleased(hotkey: tuple) -> None:
"""hotkey: tuple, two ints tuple(modifierKey, key)"""
mod = {ModifierKey.Alt: Keys.VK_MENU,
ModifierKey.Control: Keys.VK_CONTROL,
ModifierKey.Shift: Keys.VK_SHIFT,
ModifierKey.Win: Keys.VK_LWIN
}
while Tru... | hotkey: tuple, two ints tuple(modifierKey, key) | Below is the the instruction that describes the task:
### Input:
hotkey: tuple, two ints tuple(modifierKey, key)
### Response:
def WaitHotKeyReleased(hotkey: tuple) -> None:
"""hotkey: tuple, two ints tuple(modifierKey, key)"""
mod = {ModifierKey.Alt: Keys.VK_MENU,
ModifierKey.Control: Keys.VK_C... |
def _separate(self):
"""
get a width of separator for current column
:return: int
"""
if self.total_free_space is None:
return 0
else:
sepa = self.default_column_space
# we need to distribute remainders
if self.default_colu... | get a width of separator for current column
:return: int | Below is the the instruction that describes the task:
### Input:
get a width of separator for current column
:return: int
### Response:
def _separate(self):
"""
get a width of separator for current column
:return: int
"""
if self.total_free_space is None:
... |
def p_expression_sla(self, p):
'expression : expression LSHIFTA expression'
p[0] = Sll(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression LSHIFTA expression | Below is the the instruction that describes the task:
### Input:
expression : expression LSHIFTA expression
### Response:
def p_expression_sla(self, p):
'expression : expression LSHIFTA expression'
p[0] = Sll(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def _cb_inform_interface_change(self, msg):
"""Update the sensors and requests available."""
self._logger.debug('cb_inform_interface_change(%s)', msg)
self._interface_changed.set() | Update the sensors and requests available. | Below is the the instruction that describes the task:
### Input:
Update the sensors and requests available.
### Response:
def _cb_inform_interface_change(self, msg):
"""Update the sensors and requests available."""
self._logger.debug('cb_inform_interface_change(%s)', msg)
self._interface_ch... |
def to_dict(mapreduce_yaml):
"""Converts a MapReduceYaml file into a JSON-encodable dictionary.
For use in user-visible UI and internal methods for interfacing with
user code (like param validation). as a list
Args:
mapreduce_yaml: The Pyton representation of the mapreduce.yaml document.
Re... | Converts a MapReduceYaml file into a JSON-encodable dictionary.
For use in user-visible UI and internal methods for interfacing with
user code (like param validation). as a list
Args:
mapreduce_yaml: The Pyton representation of the mapreduce.yaml document.
Returns:
A list of configuration... | Below is the the instruction that describes the task:
### Input:
Converts a MapReduceYaml file into a JSON-encodable dictionary.
For use in user-visible UI and internal methods for interfacing with
user code (like param validation). as a list
Args:
mapreduce_yaml: The Pyton representation of the... |
def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Explained variance between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
var_pct = torch.var(targ - pred) / torch.var(targ)
return 1 - var_pct | Explained variance between `pred` and `targ`. | Below is the the instruction that describes the task:
### Input:
Explained variance between `pred` and `targ`.
### Response:
def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Explained variance between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
var_pct = torch.var(targ - pre... |
def tracefunc_xml(func):
"""
Causes output of function to be printed in an XML style block
"""
funcname = meta_util_six.get_funcname(func)
def wrp_tracefunc2(*args, **kwargs):
verbose = kwargs.get('verbose', True)
if verbose:
print('<%s>' % (funcname,))
with util_... | Causes output of function to be printed in an XML style block | Below is the the instruction that describes the task:
### Input:
Causes output of function to be printed in an XML style block
### Response:
def tracefunc_xml(func):
"""
Causes output of function to be printed in an XML style block
"""
funcname = meta_util_six.get_funcname(func)
def wrp_tracefu... |
def tokenize_sents(string):
"""
Tokenize input text to sentences.
:param string: Text to tokenize
:type string: str or unicode
:return: sentences
:rtype: list of strings
"""
string = six.text_type(string)
spans = []
for match in re.finditer('[^\s]+', string):
spans.appe... | Tokenize input text to sentences.
:param string: Text to tokenize
:type string: str or unicode
:return: sentences
:rtype: list of strings | Below is the the instruction that describes the task:
### Input:
Tokenize input text to sentences.
:param string: Text to tokenize
:type string: str or unicode
:return: sentences
:rtype: list of strings
### Response:
def tokenize_sents(string):
"""
Tokenize input text to sentences.
:p... |
def turb_ice(turbice: [str], unit: str = 'ft') -> str: # type: ignore
"""
Translate the list of turbulance or icing into a readable sentence
Ex: Occasional moderate turbulence in clouds from 3000ft to 14000ft
"""
if not turbice:
return ''
# Determine turbulance or icing
if turbice[... | Translate the list of turbulance or icing into a readable sentence
Ex: Occasional moderate turbulence in clouds from 3000ft to 14000ft | Below is the the instruction that describes the task:
### Input:
Translate the list of turbulance or icing into a readable sentence
Ex: Occasional moderate turbulence in clouds from 3000ft to 14000ft
### Response:
def turb_ice(turbice: [str], unit: str = 'ft') -> str: # type: ignore
"""
Translate the... |
def by_position(self, position):
"""Like `.get()`, but by position number."""
# don't use .first(), so that MultipleResultsFound can be raised
try:
return self.filter_by(position=position).one()
except sa.orm.exc.NoResultFound:
return None | Like `.get()`, but by position number. | Below is the the instruction that describes the task:
### Input:
Like `.get()`, but by position number.
### Response:
def by_position(self, position):
"""Like `.get()`, but by position number."""
# don't use .first(), so that MultipleResultsFound can be raised
try:
return self.f... |
def get_tables(self):
""" Returns a collection of this worksheet tables"""
url = self.build_url(self._endpoints.get('get_tables'))
response = self.session.get(url)
if not response:
return []
data = response.json()
return [self.table_constructor(parent=self... | Returns a collection of this worksheet tables | Below is the the instruction that describes the task:
### Input:
Returns a collection of this worksheet tables
### Response:
def get_tables(self):
""" Returns a collection of this worksheet tables"""
url = self.build_url(self._endpoints.get('get_tables'))
response = self.session.get(url)
... |
def to_vcf(self, path, rename=None, number=None, description=None,
fill=None, write_header=True):
r"""Write to a variant call format (VCF) file.
Parameters
----------
path : string
File path.
rename : dict, optional
Rename these columns in ... | r"""Write to a variant call format (VCF) file.
Parameters
----------
path : string
File path.
rename : dict, optional
Rename these columns in the VCF.
number : dict, optional
Override the number specified in INFO headers.
description :... | Below is the the instruction that describes the task:
### Input:
r"""Write to a variant call format (VCF) file.
Parameters
----------
path : string
File path.
rename : dict, optional
Rename these columns in the VCF.
number : dict, optional
... |
def scale_dtype(arr, dtype):
"""Convert an array from 0..1 to dtype, scaling up linearly
"""
max_int = np.iinfo(dtype).max
return (arr * max_int).astype(dtype) | Convert an array from 0..1 to dtype, scaling up linearly | Below is the the instruction that describes the task:
### Input:
Convert an array from 0..1 to dtype, scaling up linearly
### Response:
def scale_dtype(arr, dtype):
"""Convert an array from 0..1 to dtype, scaling up linearly
"""
max_int = np.iinfo(dtype).max
return (arr * max_int).astype(dtype) |
def index():
"""Display a list of all user institutes."""
institute_objs = user_institutes(store, current_user)
institutes_count = ((institute_obj, store.cases(collaborator=institute_obj['_id']).count())
for institute_obj in institute_objs if institute_obj)
return dict(institutes... | Display a list of all user institutes. | Below is the the instruction that describes the task:
### Input:
Display a list of all user institutes.
### Response:
def index():
"""Display a list of all user institutes."""
institute_objs = user_institutes(store, current_user)
institutes_count = ((institute_obj, store.cases(collaborator=institute_ob... |
def conv_elems_1d(x, factor, out_depth=None):
"""Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. The original lengt... | Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. The original length has to be divided by factor.
Args:
x (tf.T... | Below is the the instruction that describes the task:
### Input:
Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. ... |
def _make_request(session, url, argument=None, params=None, raw=False):
"""Make a request to API endpoint."""
if not params:
params = {}
params['key'] = session.auth.key
try:
if argument:
request_url = '{}{}{}{}'.format(session.auth.base_url, VOOBLY_API_URL, url, argument)
... | Make a request to API endpoint. | Below is the the instruction that describes the task:
### Input:
Make a request to API endpoint.
### Response:
def _make_request(session, url, argument=None, params=None, raw=False):
"""Make a request to API endpoint."""
if not params:
params = {}
params['key'] = session.auth.key
try:
... |
def tokenize(self, s, pattern=None, active=None):
"""
Rewrite and tokenize the input string *s*.
Args:
s (str): the input string to process
pattern (str, optional): the regular expression pattern on
which to split tokens; defaults to `[ \t]+`
... | Rewrite and tokenize the input string *s*.
Args:
s (str): the input string to process
pattern (str, optional): the regular expression pattern on
which to split tokens; defaults to `[ \t]+`
active (optional): a collection of external module names
... | Below is the the instruction that describes the task:
### Input:
Rewrite and tokenize the input string *s*.
Args:
s (str): the input string to process
pattern (str, optional): the regular expression pattern on
which to split tokens; defaults to `[ \t]+`
a... |
def conv_block(name, x, mid_channels, dilations=None, activation="relu",
dropout=0.0):
"""2 layer conv block used in the affine coupling layer.
Args:
name: variable scope.
x: 4-D or 5-D Tensor.
mid_channels: Output channels of the second layer.
dilations: Optional, list of integers.
... | 2 layer conv block used in the affine coupling layer.
Args:
name: variable scope.
x: 4-D or 5-D Tensor.
mid_channels: Output channels of the second layer.
dilations: Optional, list of integers.
activation: relu or gatu.
If relu, the second layer is relu(W*x)
If gatu, the second layer ... | Below is the the instruction that describes the task:
### Input:
2 layer conv block used in the affine coupling layer.
Args:
name: variable scope.
x: 4-D or 5-D Tensor.
mid_channels: Output channels of the second layer.
dilations: Optional, list of integers.
activation: relu or gatu.
If... |
def inverse_transform(self, maps):
""" This function transforms from component masses and cartesian spins to
mass-weighted spin parameters perpendicular with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
... | This function transforms from component masses and cartesian spins to
mass-weighted spin parameters perpendicular with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name an... | Below is the the instruction that describes the task:
### Input:
This function transforms from component masses and cartesian spins to
mass-weighted spin parameters perpendicular with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
------... |
def run(*args):
'''Run the normal shovel functionality'''
import os
import sys
import argparse
import pkg_resources
# First off, read the arguments
parser = argparse.ArgumentParser(prog='shovel', description='Rake, for Python')
parser.add_argument('method', help='The task to run')
p... | Run the normal shovel functionality | Below is the the instruction that describes the task:
### Input:
Run the normal shovel functionality
### Response:
def run(*args):
'''Run the normal shovel functionality'''
import os
import sys
import argparse
import pkg_resources
# First off, read the arguments
parser = argparse.Argume... |
def remove(self, first, count):
"""
Remove a range of count consecutive ids starting at id first
from all the ranges in the set.
"""
# Avoid trivialities
if first < 0 or count < 1:
return
new_range = []
last = first + count - 1
for r ... | Remove a range of count consecutive ids starting at id first
from all the ranges in the set. | Below is the the instruction that describes the task:
### Input:
Remove a range of count consecutive ids starting at id first
from all the ranges in the set.
### Response:
def remove(self, first, count):
"""
Remove a range of count consecutive ids starting at id first
from all the r... |
def _get_current_object(self):
"""Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
if not hasattr(self.__local, '__release_local__'):
... | Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context. | Below is the the instruction that describes the task:
### Input:
Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
### Response:
def _get_current_object(self):
... |
def days_in_month(year, month):
"""
returns number of days for the given year and month
:param int year: calendar year
:param int month: calendar month
:return int:
"""
eom = _days_per_month[month - 1]
if is_leap_year(year) and month == 2:
eom += 1
return eom | returns number of days for the given year and month
:param int year: calendar year
:param int month: calendar month
:return int: | Below is the the instruction that describes the task:
### Input:
returns number of days for the given year and month
:param int year: calendar year
:param int month: calendar month
:return int:
### Response:
def days_in_month(year, month):
"""
returns number of days for the given year and mont... |
def get_map_values(self, lons, lats, ibin=None):
"""Return the map values corresponding to a set of coordinates.
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-l... | Return the map values corresponding to a set of coordinates.
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-like
Extract data only for a given energy bin. No... | Below is the the instruction that describes the task:
### Input:
Return the map values corresponding to a set of coordinates.
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int o... |
def _add_url(self, chunk):
""" Add a 'url' property to a chunk and return it """
if 'url' in chunk:
return chunk
public_path = chunk.get('publicPath')
if public_path:
chunk['url'] = public_path
else:
fullpath = posixpath.join(self.state.static_... | Add a 'url' property to a chunk and return it | Below is the the instruction that describes the task:
### Input:
Add a 'url' property to a chunk and return it
### Response:
def _add_url(self, chunk):
""" Add a 'url' property to a chunk and return it """
if 'url' in chunk:
return chunk
public_path = chunk.get('publicPath')
... |
def chunks(iterable, n):
"""Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 """
for i in range(0, len(iterable), n):
yield iterable[i:i + n] | Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 | Below is the the instruction that describes the task:
### Input:
Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464
### Response:
def chunks(iterable, n):
"""Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 """
for i in range(0, ... |
def unmodified_isinstance(*bases):
"""When called in the form
MyOverrideClass(unmodified_isinstance(BuiltInClass))
it allows calls against passed in built in instances to pass even if there not a subclass
"""
class UnmodifiedIsInstance(type):
if sys.version_info[0] == 2 and sys.version_in... | When called in the form
MyOverrideClass(unmodified_isinstance(BuiltInClass))
it allows calls against passed in built in instances to pass even if there not a subclass | Below is the the instruction that describes the task:
### Input:
When called in the form
MyOverrideClass(unmodified_isinstance(BuiltInClass))
it allows calls against passed in built in instances to pass even if there not a subclass
### Response:
def unmodified_isinstance(*bases):
"""When called in th... |
def write(self, buffer):
"""Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
socket.error if the connection is closed.
"""
if type(buffer) == type(0):
buffer = chr(buffer)
elif not isinstance(buffe... | Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
socket.error if the connection is closed. | Below is the the instruction that describes the task:
### Input:
Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
socket.error if the connection is closed.
### Response:
def write(self, buffer):
"""Write a string to the socket, d... |
def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval]:
"""
Returns our first interval that starts with the ``start`` parameter, or
``None``.
"""
for i in self.intervals:
if i.start == start:
return i
re... | Returns our first interval that starts with the ``start`` parameter, or
``None``. | Below is the the instruction that describes the task:
### Input:
Returns our first interval that starts with the ``start`` parameter, or
``None``.
### Response:
def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval]:
"""
Returns our first interval th... |
def _convert(cls, record):
"""
Core method of the converter. Converts a single dictionary into another dictionary.
"""
if not record:
return {}
converted_dict = {}
for field in cls.conversion:
key = field[0]
if len(field) >= 2 and fiel... | Core method of the converter. Converts a single dictionary into another dictionary. | Below is the the instruction that describes the task:
### Input:
Core method of the converter. Converts a single dictionary into another dictionary.
### Response:
def _convert(cls, record):
"""
Core method of the converter. Converts a single dictionary into another dictionary.
"""
i... |
def _set_link_error_disable(self, v, load=False):
"""
Setter method for link_error_disable, mapped from YANG variable /interface/ethernet/link_error_disable (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_error_disable is considered as a private
meth... | Setter method for link_error_disable, mapped from YANG variable /interface/ethernet/link_error_disable (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_error_disable is considered as a private
method. Backends looking to populate this variable should
do s... | Below is the the instruction that describes the task:
### Input:
Setter method for link_error_disable, mapped from YANG variable /interface/ethernet/link_error_disable (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_error_disable is considered as a private
... |
def _locate_free_sectors(self, ignore_chunk=None):
"""Return a list of booleans, indicating the free sectors."""
sectors = self._sectors(ignore_chunk=ignore_chunk)
# Sectors are considered free, if the value is an empty list.
return [not i for i in sectors] | Return a list of booleans, indicating the free sectors. | Below is the the instruction that describes the task:
### Input:
Return a list of booleans, indicating the free sectors.
### Response:
def _locate_free_sectors(self, ignore_chunk=None):
"""Return a list of booleans, indicating the free sectors."""
sectors = self._sectors(ignore_chunk=ignore_chunk)
... |
def handleGetValue(self, topContainer):
""" This method overrides ValueGetterBase's "pure virtual" method. It
returns the referenced value. The derived class is NOT responsible for
fully resolving the reference'd value in the event the value resolves to
another ValueGetterBase-based instance -- this i... | This method overrides ValueGetterBase's "pure virtual" method. It
returns the referenced value. The derived class is NOT responsible for
fully resolving the reference'd value in the event the value resolves to
another ValueGetterBase-based instance -- this is handled automatically
within ValueGetterBa... | Below is the the instruction that describes the task:
### Input:
This method overrides ValueGetterBase's "pure virtual" method. It
returns the referenced value. The derived class is NOT responsible for
fully resolving the reference'd value in the event the value resolves to
another ValueGetterBase-bas... |
def installed(name,
cyg_arch='x86_64',
mirrors=None):
'''
Make sure that a package is installed.
name
The name of the package to install
cyg_arch : x86_64
The cygwin architecture to install the package into.
Current options are x86 and x86_64
mi... | Make sure that a package is installed.
name
The name of the package to install
cyg_arch : x86_64
The cygwin architecture to install the package into.
Current options are x86 and x86_64
mirrors : None
List of mirrors to check.
None will use a default mirror (kernel.... | Below is the the instruction that describes the task:
### Input:
Make sure that a package is installed.
name
The name of the package to install
cyg_arch : x86_64
The cygwin architecture to install the package into.
Current options are x86 and x86_64
mirrors : None
List... |
def loads(cls, s):
"""
Load an instance of this class from YAML.
"""
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) | Load an instance of this class from YAML. | Below is the the instruction that describes the task:
### Input:
Load an instance of this class from YAML.
### Response:
def loads(cls, s):
"""
Load an instance of this class from YAML.
"""
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) |
def cmd_func(self, command: str) -> Optional[Callable]:
"""
Get the function for a command
:param command: the name of the command
"""
func_name = self.cmd_func_name(command)
if func_name:
return getattr(self, func_name) | Get the function for a command
:param command: the name of the command | Below is the the instruction that describes the task:
### Input:
Get the function for a command
:param command: the name of the command
### Response:
def cmd_func(self, command: str) -> Optional[Callable]:
"""
Get the function for a command
:param command: the name of the command
... |
def get_vcs_root(path):
"""Return VCS root directory path
Return None if path is not within a supported VCS repository"""
previous_path = path
while get_vcs_info(path) is None:
path = abspardir(path)
if path == previous_path:
return
else:
previous... | Return VCS root directory path
Return None if path is not within a supported VCS repository | Below is the the instruction that describes the task:
### Input:
Return VCS root directory path
Return None if path is not within a supported VCS repository
### Response:
def get_vcs_root(path):
"""Return VCS root directory path
Return None if path is not within a supported VCS repository"""
pr... |
def _do_multipart_upload(self, stream, metadata, size, num_retries):
"""Perform a multipart upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type size: int... | Perform a multipart upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type size: int
:param size: The number of bytes to be uploaded (which will be read
... | Below is the the instruction that describes the task:
### Input:
Perform a multipart upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type size: int
:p... |
def to_dict(self):
"""Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
"""
rv = {'code': self.code}
if not self.is_native():
rv['issuer'] = self.issuer
rv['type'] = self.type
else:
rv['type']... | Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset` | Below is the the instruction that describes the task:
### Input:
Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
### Response:
def to_dict(self):
"""Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
... |
def cli(debug, cache, incremental):
"""Crawler framework for documents and structured scrapers."""
settings.HTTP_CACHE = cache
settings.INCREMENTAL = incremental
settings.DEBUG = debug
if settings.DEBUG:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=log... | Crawler framework for documents and structured scrapers. | Below is the the instruction that describes the task:
### Input:
Crawler framework for documents and structured scrapers.
### Response:
def cli(debug, cache, incremental):
"""Crawler framework for documents and structured scrapers."""
settings.HTTP_CACHE = cache
settings.INCREMENTAL = incremental
s... |
def ensure_dir(self, mode=0777):
"""
Make sure the directory exists, create if necessary.
"""
if not self.exists() or not self.isdir():
os.makedirs(self, mode) | Make sure the directory exists, create if necessary. | Below is the the instruction that describes the task:
### Input:
Make sure the directory exists, create if necessary.
### Response:
def ensure_dir(self, mode=0777):
"""
Make sure the directory exists, create if necessary.
"""
if not self.exists() or not self.isdir():
os.... |
def feed_interval_get(feed_id, parameters):
'Get adaptive interval between checks for a feed.'
val = cache.get(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) ))
return val if isinstance(val, tuple) else (val, None) | Get adaptive interval between checks for a feed. | Below is the the instruction that describes the task:
### Input:
Get adaptive interval between checks for a feed.
### Response:
def feed_interval_get(feed_id, parameters):
'Get adaptive interval between checks for a feed.'
val = cache.get(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) ))
retur... |
def impulse_noise(x, severity=1):
"""Impulse noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added impulse noise.
"""
c = [.03, .06, .... | Impulse noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added impulse noise. | Below is the the instruction that describes the task:
### Input:
Impulse noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added impulse n... |
def _open(self, name=None, fileobj=None, mymap=None, block=None):
"""
The _open function takes some form of file identifier and creates
an :py:class:`CpioFile` instance from it.
:param :py:class:`str` name: a file name
:param :py:class:`file` fileobj: if given, this overrides *n... | The _open function takes some form of file identifier and creates
an :py:class:`CpioFile` instance from it.
:param :py:class:`str` name: a file name
:param :py:class:`file` fileobj: if given, this overrides *name*
:param :py:class:`mmap.mmap` mymap: if given, this overrides *fileobj*
... | Below is the the instruction that describes the task:
### Input:
The _open function takes some form of file identifier and creates
an :py:class:`CpioFile` instance from it.
:param :py:class:`str` name: a file name
:param :py:class:`file` fileobj: if given, this overrides *name*
:par... |
def vectorize(self, sentence_list):
'''
Args:
sentence_list: The list of tokenized sentences.
[[`token`, `token`, `token`, ...],
[`token`, `token`, `token`, ...],
[`token`, `token`, `token`, ...]]
... | Args:
sentence_list: The list of tokenized sentences.
[[`token`, `token`, `token`, ...],
[`token`, `token`, `token`, ...],
[`token`, `token`, `token`, ...]]
Returns:
`np.ndarray` of tokens.
... | Below is the the instruction that describes the task:
### Input:
Args:
sentence_list: The list of tokenized sentences.
[[`token`, `token`, `token`, ...],
[`token`, `token`, `token`, ...],
[`token`, `token`, `token`,... |
def obj(self):
"""Returns the value of :meth:`ObjectMixin.get_object` and sets a private
property called _obj. This property ensures the logic around allow_none
is enforced across Endpoints using the Object interface.
:raises: :class:`werkzeug.exceptions.BadRequest`
:returns: T... | Returns the value of :meth:`ObjectMixin.get_object` and sets a private
property called _obj. This property ensures the logic around allow_none
is enforced across Endpoints using the Object interface.
:raises: :class:`werkzeug.exceptions.BadRequest`
:returns: The result of :meth:ObjectM... | Below is the the instruction that describes the task:
### Input:
Returns the value of :meth:`ObjectMixin.get_object` and sets a private
property called _obj. This property ensures the logic around allow_none
is enforced across Endpoints using the Object interface.
:raises: :class:`werkzeug... |
def relabel_non_zero(label_image, start = 1):
r"""
Relabel the regions of a label image.
Re-processes the labels to make them consecutively and starting from start.
Keeps all zero (0) labels, as they are considered background.
Parameters
----------
label_image : array_like
A nD... | r"""
Relabel the regions of a label image.
Re-processes the labels to make them consecutively and starting from start.
Keeps all zero (0) labels, as they are considered background.
Parameters
----------
label_image : array_like
A nD label map.
start : integer
The id of ... | Below is the the instruction that describes the task:
### Input:
r"""
Relabel the regions of a label image.
Re-processes the labels to make them consecutively and starting from start.
Keeps all zero (0) labels, as they are considered background.
Parameters
----------
label_image : arra... |
def register(self, request, **cleaned_data):
"""
Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to th... | Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to that ``User``, containing the activation key which
will be ... | Below is the the instruction that describes the task:
### Input:
Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied t... |
def _join_factory(cls, gap, pad):
"""Build a joiner for the given cls, and the given padding options
"""
if issubclass(cls, dict):
def _join(data):
out = cls()
data = list(data)
while data:
tsd = data.pop(0)
out.append(tsd, gap=gap,... | Build a joiner for the given cls, and the given padding options | Below is the the instruction that describes the task:
### Input:
Build a joiner for the given cls, and the given padding options
### Response:
def _join_factory(cls, gap, pad):
"""Build a joiner for the given cls, and the given padding options
"""
if issubclass(cls, dict):
def _join(data):
... |
def chi2(T1, T2):
"""
chi-squared test of difference between two transition matrices.
Parameters
----------
T1 : array
(k, k), matrix of transitions (counts).
T2 : array
(k, k), matrix of transitions (counts) to use to form the
probabilities under the n... | chi-squared test of difference between two transition matrices.
Parameters
----------
T1 : array
(k, k), matrix of transitions (counts).
T2 : array
(k, k), matrix of transitions (counts) to use to form the
probabilities under the null.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
chi-squared test of difference between two transition matrices.
Parameters
----------
T1 : array
(k, k), matrix of transitions (counts).
T2 : array
(k, k), matrix of transitions (counts) to use to form th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.