code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def add_agent(self, *args, **kwargs):
"""
Add an `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ to the list of agents in the metsHdr.
"""
el_metsHdr = self._tree.getroot().find('.//mets:metsHdr', NS)
if el_metsHdr is None:
el_metsHdr = ET.Element(TAG_ME... | Add an `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ to the list of agents in the metsHdr. |
def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]:
"""
Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postcondit... | Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postconditions: postconditions of the function (before the collapse)
:return: collapsed sequence of postconditions |
def fill_missing_attributes_from_default_parameter(self, param):
"""
Empty fields in Parameter definitions in scenarios are populated with default values.
E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar.
| name | scenario ... | Empty fields in Parameter definitions in scenarios are populated with default values.
E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar.
| name | scenario | val | tags | source |
|----------|----------|-----|--------|---------... |
def schedule_forced_host_svc_checks(self, host, check_time):
"""Schedule a forced check on all services of a host
Format of the line that triggers function call::
SCHEDULE_FORCED_HOST_SVC_CHECKS;<host_name>;<check_time>
:param host: host to check
:type host: alignak.object.host... | Schedule a forced check on all services of a host
Format of the line that triggers function call::
SCHEDULE_FORCED_HOST_SVC_CHECKS;<host_name>;<check_time>
:param host: host to check
:type host: alignak.object.host.Host
:param check_time: time to check
:type check_time:... |
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` that fits in a bounding box.
Bounding box dimensions are `width`x`height`.
"""
imagefile = BytesIO()
image.thumbnail(
(wid... | Return a BytesIO instance of `image` that fits in a bounding box.
Bounding box dimensions are `width`x`height`. |
def choose_tag(self: object, tokens: List[str], index: int, history: List[str]):
"""
Looks up token in ``lemmas`` dict and returns the corresponding
value as lemma.
:rtype: str
:type tokens: list
:param tokens: List of tokens to be lemmatized
:type index: int
... | Looks up token in ``lemmas`` dict and returns the corresponding
value as lemma.
:rtype: str
:type tokens: list
:param tokens: List of tokens to be lemmatized
:type index: int
:param index: Int with current token
:type history: list
:param history: List wit... |
def indices(self, fit):
"""return the set of indices to be reevaluated for noise
measurement.
Given the first values are the earliest, this is a useful policy also
with a time changing objective.
"""
## meta_parameters.noise_reeval_multiplier == 1.0
lam_reev = 1... | return the set of indices to be reevaluated for noise
measurement.
Given the first values are the earliest, this is a useful policy also
with a time changing objective. |
def set_defaults(self):
""" Add each model entry with it's default
"""
for key, value in self.spec.items():
setattr(self, key.upper(), value.get("default", None)) | Add each model entry with it's default |
def save_info_df(self):
"""Saves the DataFrame with info about the runs to a JSON file"""
logger.debug("running save_info_df")
info_df = self.info_df
top_level_dict = {'info_df': info_df, 'metadata': self._prm_packer()}
# packing prms
jason_string = json.dumps(top_leve... | Saves the DataFrame with info about the runs to a JSON file |
def raw(self):
"""
Build query and passes to Elasticsearch, then returns the raw
format returned.
"""
qs = self.build_search()
es = self.get_es()
index = self.get_indexes()
doc_type = self.get_doctypes()
if doc_type and not index:
rai... | Build query and passes to Elasticsearch, then returns the raw
format returned. |
def to_capabilities(self):
"""
Creates a capabilities with all the options that have been set
:Returns: A dictionary with everything
"""
caps = self._caps
chrome_options = self.experimental_options.copy()
chrome_options["extensions"] = self.extensions
if ... | Creates a capabilities with all the options that have been set
:Returns: A dictionary with everything |
def rho_rec(self, g2):
"""
Reciprocal space model charge value
for input squared reciprocal vector.
Args:
g2: Square of reciprocal vector
Returns:
Charge density at the reciprocal vector magnitude
"""
return (self.expnorm / np.sqrt(1 + sel... | Reciprocal space model charge value
for input squared reciprocal vector.
Args:
g2: Square of reciprocal vector
Returns:
Charge density at the reciprocal vector magnitude |
def plot_energy_signature(
meter_data,
temperature_data,
temp_col=None,
ax=None,
title=None,
figsize=None,
**kwargs
):
""" Plot meter and temperature data in energy signature.
Parameters
----------
meter_data : :any:`pandas.DataFrame`
A :any:`pandas.DatetimeIndex`-in... | Plot meter and temperature data in energy signature.
Parameters
----------
meter_data : :any:`pandas.DataFrame`
A :any:`pandas.DatetimeIndex`-indexed DataFrame of meter data with the column ``value``.
temperature_data : :any:`pandas.Series`
A :any:`pandas.DatetimeIndex`-indexed Series o... |
def set_marked(self, name: str, marked: bool = False,
unmarked: bool = False) -> None:
"""Add or remove the ``\\Marked`` and ``\\Unmarked`` mailbox
attributes.
Args:
name: The name of the mailbox.
marked: True if the ``\\Marked`` attribute should be ad... | Add or remove the ``\\Marked`` and ``\\Unmarked`` mailbox
attributes.
Args:
name: The name of the mailbox.
marked: True if the ``\\Marked`` attribute should be added.
unmarked: True if the ``\\Unmarked`` attribute should be added. |
def _get_all_merges(routing_table):
"""Get possible sets of entries to merge.
Yields
------
:py:class:`~.Merge`
"""
# Memorise entries that have been considered as part of a merge
considered_entries = set()
for i, entry in enumerate(routing_table):
# If we've already considered... | Get possible sets of entries to merge.
Yields
------
:py:class:`~.Merge` |
def _gen_figure(nxplot=1, nyplot=1, figargs=None, projection=None,
sharex='none', joinx=False, sharey='none', joiny=False,
x=None, nxlabel=None, xlabels=None, nxdecimal=None, xmin=None, xmax=None,
y=None, nylabel=None, ylabels=None, nydecimal=None, ymin=None, ymax=None,
... | Returns a figure object with as much customization as provided. |
def save(self, p_todolist):
"""
Saves a tuple with archive, todolist and command with its arguments
into the backup file with unix timestamp as the key. Tuple is then
indexed in backup file with combination of hash calculated from
p_todolist and unix timestamp. Backup file is clo... | Saves a tuple with archive, todolist and command with its arguments
into the backup file with unix timestamp as the key. Tuple is then
indexed in backup file with combination of hash calculated from
p_todolist and unix timestamp. Backup file is closed afterwards. |
def finish(self):
"""jump the the last frame of all tweens"""
for obj in self.current_tweens:
for tween in self.current_tweens[obj]:
tween.finish()
self.current_tweens = {} | jump the the last frame of all tweens |
def hoverLeaveEvent(self, event):
"""
Processes when this hotspot is entered.
:param event | <QHoverEvent>
:return <bool> | processed
"""
self._hovered = False
if self.toolTip():
QToolTip.hideText()
... | Processes when this hotspot is entered.
:param event | <QHoverEvent>
:return <bool> | processed |
def _set_sub_interface_statistics_state(self, v, load=False):
"""
Setter method for sub_interface_statistics_state, mapped from YANG variable /sub_interface_statistics_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sub_interface_statistics_state is con... | Setter method for sub_interface_statistics_state, mapped from YANG variable /sub_interface_statistics_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sub_interface_statistics_state is considered as a private
method. Backends looking to populate this variabl... |
def _extract_dependencies_by_root(cls, result):
"""
Only extracts the transitive dependencies for the given coursier resolve.
Note the "dependencies" field is already transitive.
Example:
{
"conflict_resolution": {},
"dependencies": [
{
"coord": "a",
"depende... | Only extracts the transitive dependencies for the given coursier resolve.
Note the "dependencies" field is already transitive.
Example:
{
"conflict_resolution": {},
"dependencies": [
{
"coord": "a",
"dependencies": ["b", "c"]
"file": ...
},
... |
def _plain_authentication(self, login, password, authz_id=b""):
"""SASL PLAIN authentication
:param login: username
:param password: clear password
:return: True on success, False otherwise.
"""
if isinstance(login, six.text_type):
login = login.encode("utf-8... | SASL PLAIN authentication
:param login: username
:param password: clear password
:return: True on success, False otherwise. |
def string_to_uuid(value, strict=True):
"""
Return a Universally Unique Identifier (UUID) object represented by
the specified string.
@param value: a string representation of a UUID.
@param strict: indicate whether the specified string MUST be of a
valid UUID representation.
@return: a... | Return a Universally Unique Identifier (UUID) object represented by
the specified string.
@param value: a string representation of a UUID.
@param strict: indicate whether the specified string MUST be of a
valid UUID representation.
@return: a UUID object. |
def generate_unique_name(self, basename):
"""Generates a unique name for a child given a base name."""
counts = self.__counts
try:
count = counts[basename]
counts[basename] += 1
except KeyError:
count = 0
counts[basename] = 1
... | Generates a unique name for a child given a base name. |
def load(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",
loader_class=None):
u"""load google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. this method never work twice if you want to reload, use... | u"""load google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. this method never work twice if you want to reload, use `e4u.reload()` insted. |
def getDependencySpecs(self, target=None):
''' Returns [DependencySpec]
These are returned in the order that they are listed in the
component description file: this is so that dependency resolution
proceeds in a predictable way.
'''
deps = []
def spe... | Returns [DependencySpec]
These are returned in the order that they are listed in the
component description file: this is so that dependency resolution
proceeds in a predictable way. |
def add(self, stream_id, task_ids, grouping, source_comp_name):
"""Adds the target component
:type stream_id: str
:param stream_id: stream id into which tuples are emitted
:type task_ids: list of str
:param task_ids: list of task ids to which tuples are emitted
:type grouping: ICustomStreamGrou... | Adds the target component
:type stream_id: str
:param stream_id: stream id into which tuples are emitted
:type task_ids: list of str
:param task_ids: list of task ids to which tuples are emitted
:type grouping: ICustomStreamGrouping object
:param grouping: custom grouping to use
:type sourc... |
def GetLastChildControl(self) -> 'Control':
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetLastChildElement(self.Element)
return Control.CreateControlFromElement(ele) | Return `Control` subclass or None. |
def _get_device_by_key(devices, key):
'''
Returns the device with the given key, raises error if the device is
not found.
devices
list of vim.vm.device.VirtualDevice objects
key
Unique key of device
'''
device_keys = [d for d in devices if d.key == key]
if device_keys:
... | Returns the device with the given key, raises error if the device is
not found.
devices
list of vim.vm.device.VirtualDevice objects
key
Unique key of device |
def predict_step(F, covX, filt):
"""Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
... | Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
Returns
-------
pred: MeanAn... |
def create_self_signed(cls, name, common_name, public_key_algorithm='rsa',
signature_algorithm='rsa_sha_512', key_length=4096):
"""
Create a self signed certificate. This is a convenience method that
first calls :meth:`~create_csr`, then calls :meth:`~self_sign` on the
return... | Create a self signed certificate. This is a convenience method that
first calls :meth:`~create_csr`, then calls :meth:`~self_sign` on the
returned TLSServerCredential object.
:param str name: name of TLS Server Credential
:param str rcommon_name: common name for certificate. An ... |
def _ip_setter(self, ipaddr_name, ipaddrs_name, ips):
"""Setter for ip fields
Accept as input string or list of IP instances.
String case:
only ipvXaddr is going to be filled, that is enough to perform
host record search using ip
List of IP instances case:
... | Setter for ip fields
Accept as input string or list of IP instances.
String case:
only ipvXaddr is going to be filled, that is enough to perform
host record search using ip
List of IP instances case:
ipvXaddrs is going to be filled with ips content,
... |
def readall_fast(stm, size):
"""
Slightly faster version of readall, it reads no more than two chunks.
Meaning that it can only be used to read small data that doesn't span
more that two packets.
:param stm: Stream to read from, should have read method.
:param size: Number of bytes to read.
... | Slightly faster version of readall, it reads no more than two chunks.
Meaning that it can only be used to read small data that doesn't span
more that two packets.
:param stm: Stream to read from, should have read method.
:param size: Number of bytes to read.
:return: |
def moments_match_ep(self, Y_i, tau_i, v_i, Y_metadata_i=None):
"""
Moments match of the marginal approximation in EP algorithm
:param i: number of observation (int)
:param tau_i: precision of the cavity distribution (float)
:param v_i: mean/variance of the cavity distribution (... | Moments match of the marginal approximation in EP algorithm
:param i: number of observation (int)
:param tau_i: precision of the cavity distribution (float)
:param v_i: mean/variance of the cavity distribution (float) |
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, unitsx='', unitsy='', scalex=1, scaley=1, **kwargs):
""" Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
and optionally hiding the x and y axes
- ax : the axis to attach ticks to
... | Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
and optionally hiding the x and y axes
- ax : the axis to attach ticks to
- matchx,matchy : if True, set size of scale bars to spacing between ticks
if False, size should be set using s... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'global_') and self.global_ is not None:
_dict['global'] = self.global_._to_dict()
if hasattr(self, 'skills') and self.skills is not None:
_dict['skills'] = sel... | Return a json dictionary representing this model. |
def update_links(self, request, admin_site=None):
"""
Called to update the widget's urls. Tries to find the
bundle for the model that this foreign key points to and then
asks it for the urls for adding and listing and sets them on
this widget instance. The urls are only set if re... | Called to update the widget's urls. Tries to find the
bundle for the model that this foreign key points to and then
asks it for the urls for adding and listing and sets them on
this widget instance. The urls are only set if request.user
has permissions on that url.
:param reques... |
def sample(records, k, random_seed=None):
"""Choose a length-``k`` subset of ``records``, retaining the input
order. If k > len(records), all are returned. If an integer
``random_seed`` is provided, sets ``random.seed()``
"""
if random_seed is not None:
random.seed(random_seed)
resul... | Choose a length-``k`` subset of ``records``, retaining the input
order. If k > len(records), all are returned. If an integer
``random_seed`` is provided, sets ``random.seed()`` |
def division_content(self, election_day, division, special=False):
"""
Return serialized content for a division page.
"""
from electionnight.models import PageType
division_type = ContentType.objects.get_for_model(division)
page_type = PageType.objects.get(
m... | Return serialized content for a division page. |
def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validator",
)
parser.add_argument(
"--log",
default="INFO",
help=("log level: DEBUG, INFO or INFO "
... | Parser the command line and run the validator. |
def lime_tabular_regression_1000(model, data):
""" LIME Tabular 1000
"""
return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000) | LIME Tabular 1000 |
def getSendPath(self, volume):
""" Get a path appropriate for sending the volume from this Store.
The path may be relative or absolute in this Store.
"""
try:
return self._fullPath(next(iter(self.getPaths(volume))))
except StopIteration:
return None | Get a path appropriate for sending the volume from this Store.
The path may be relative or absolute in this Store. |
def delete_older(self):
""" Delete all older duplicates.
Only keeps the subset sharing the most recent timestamp.
"""
logger.info(
"Deleting all mails strictly older than the {} timestamp..."
"".format(self.newest_timestamp))
# Select candidates for delet... | Delete all older duplicates.
Only keeps the subset sharing the most recent timestamp. |
def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs):
"""
Sends an APNS notification to a single registration_id.
This will send the notification as form data.
If sending multiple notifications, it is more efficient to use
apns_send_bulk_message()
Note that if set alert sho... | Sends an APNS notification to a single registration_id.
This will send the notification as form data.
If sending multiple notifications, it is more efficient to use
apns_send_bulk_message()
Note that if set alert should always be a string. If it is not set,
it won"t be included in the notification. You will need ... |
def createuser(email, password, role=None, name=None, first_name=None):
"""Create new user."""
if User.query.filter(User.email == email).count() > 0:
print(f"A user with email '{email}' already exists, aborting.")
return
# if password is None:
# password = prompt_pass("Password")
... | Create new user. |
def value_after(self, x):
"""Returns value of argument after given found argument (or list thereof)."""
try:
try:
i = self.all.index(x)
except ValueError:
return None
return self.all[i + 1]
except IndexError:
retu... | Returns value of argument after given found argument (or list thereof). |
def _ResponseToClientsFullInfo(self, response):
"""Creates a ClientFullInfo object from a database response."""
c_full_info = None
prev_cid = None
for row in response:
(cid, fs, crt, ping, clk, ip, foreman, first, last_client_ts,
last_crash_ts, last_startup_ts, client_obj, client_startup_ob... | Creates a ClientFullInfo object from a database response. |
def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is... | Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted. |
def generate_candidates(freq_set, k):
"""
Generate candidates for an iteration.
Use this only for k >= 2.
"""
single_set = {(i,) for i in set(flatten(freq_set))}
# TO DO generating all combinations gets very slow for large documents.
# Is there a way of doing this without exhaustively searc... | Generate candidates for an iteration.
Use this only for k >= 2. |
async def start_child():
"""
Start the child process that will look for changes in modules.
"""
logger.info('Started to watch for code changes')
loop = asyncio.get_event_loop()
watcher = aionotify.Watcher()
flags = (
aionotify.Flags.MODIFY |
aionotify.Flags.DELETE |
... | Start the child process that will look for changes in modules. |
def create_stack(name=None, template_file=None, environment=None,
parameters=None, poll=0, rollback=False, timeout=60,
profile=None, enviroment=None):
'''
Create a stack (heat stack-create)
name
Name of the new stack
template_file
File of template
... | Create a stack (heat stack-create)
name
Name of the new stack
template_file
File of template
environment
File of environment
parameters
Parameter dict used to create the stack
poll
Poll and report events until stack complete
rollback
Enable r... |
def to_dict(self):
"""Returns a simplified dictionary representing the Graph.
Returns:
A dictionary that can easily be serialized to JSON.
"""
return {
"node": [v.to_dict() for v in self.vertices],
"edge": [e.to_dict() for e in self.edges]
} | Returns a simplified dictionary representing the Graph.
Returns:
A dictionary that can easily be serialized to JSON. |
def _fuzzy_time_parse(self, value):
""" Parses a fuzzy time value into a meaningful interpretation.
`value`
String value to parse.
"""
value = value.lower().strip()
today = datetime.date.today()
if value in ('today', 't'):
return tod... | Parses a fuzzy time value into a meaningful interpretation.
`value`
String value to parse. |
def destroy_plugin(plugin_name, conn=None):
"""
Creates a new plugin
:param plugin_name: <str>
:param conn:
:return: <dict> rethinkdb response
"""
results = {}
if plugin_exists(plugin_name, conn=conn):
results = RPX.table_drop(plugin_name).run(conn)
return results | Creates a new plugin
:param plugin_name: <str>
:param conn:
:return: <dict> rethinkdb response |
def _alt_ac_for_tx_ac(self, tx_ac):
"""return chromosomal accession for given transcript accession (and
the_assembly and aln_method setting used to instantiate this
AssemblyMapper)
"""
alt_acs = [
e["alt_ac"] for e in self.hdp.get_tx_mapping_options(tx_ac) if
... | return chromosomal accession for given transcript accession (and
the_assembly and aln_method setting used to instantiate this
AssemblyMapper) |
def getPhysicalDisplayInfo(self):
''' Gets C{mPhysicalDisplayInfo} values from dumpsys. This is a method to obtain display dimensions and density'''
self.__checkTransport()
phyDispRE = re.compile('Physical size: (?P<width>\d+)x(?P<height>\d+).*Physical density: (?P<density>\d+)',
... | Gets C{mPhysicalDisplayInfo} values from dumpsys. This is a method to obtain display dimensions and density |
def detect_language_filename(cls, filename):
"""
Detect the language of a subtitle filename
:param filename: filename of a subtitle
:return: Language object, None if language could not be detected.
"""
log.debug('detect_language(filename="{}") ...'.format(filename))
... | Detect the language of a subtitle filename
:param filename: filename of a subtitle
:return: Language object, None if language could not be detected. |
def validate_obj(keys, obj):
"""Super simple "object" validation."""
msg = ''
for k in keys:
if isinstance(k, str):
if k not in obj or (not isinstance(obj[k], list) and not obj[k]):
if msg:
msg = "%s," % msg
msg = "%s%s" % (msg, k)
... | Super simple "object" validation. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'response_type') and self.response_type is not None:
_dict['response_type'] = self.response_type
if hasattr(self, 'values') and self.values is not None:
_dict['... | Return a json dictionary representing this model. |
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
... | Makes a checksum address given a supported format. |
def _serialiseExistingJob(self, jobGraph, jobStore, returnValues):
"""
Serialise an existing job.
"""
self._serialiseJobGraph(jobGraph, jobStore, returnValues, False)
#Drop the completed command, if not dropped already
jobGraph.command = None
#Merge any children (... | Serialise an existing job. |
def diff(a, b):
"""
Compares JSON objects
:param a:
:param b:
:return: difference object a vs b
"""
delta = diff(a, b)
if not a:
return delta
for item in delta:
if isinstance(a[item], list):
if delta[item] ==... | Compares JSON objects
:param a:
:param b:
:return: difference object a vs b |
def removeProfile(self, profile, silent=False):
"""
Removes the given profile from the toolbar.
:param profile | <projexui.widgets.xviewwidget.XViewProfile>
"""
if not profile:
return
if not silent:
title = 'Remove ... | Removes the given profile from the toolbar.
:param profile | <projexui.widgets.xviewwidget.XViewProfile> |
def readObject(self, innode):
'''reads in a node and returns as a tuple: (type, name, points[])'''
#get name
names=innode.getElementsByTagName('name')[0].childNodes[0].data.strip()
#get type
pointType = 'Unknown'
if len(innode.getElementsByTagName('LineString')) ... | reads in a node and returns as a tuple: (type, name, points[]) |
def stop(self):
"""
Stops the thread pool. Does nothing if the pool is already stopped.
"""
if self._done_event.is_set():
# Stop event set: we're stopped
return
# Set the stop event
self._done_event.set()
with self.__lock:
# A... | Stops the thread pool. Does nothing if the pool is already stopped. |
def directory_is_present(self, directory_path):
"""
check if directory 'directory_path' is present, raise IOError if it's not a directory
:param directory_path: str, directory to check
:return: True if directory exists, False if directory does not exist
"""
p = self.p(di... | check if directory 'directory_path' is present, raise IOError if it's not a directory
:param directory_path: str, directory to check
:return: True if directory exists, False if directory does not exist |
def pp(self):
"""
Pretty printing.
"""
# TODO: make it prettier
for src, dst, data in self.graph.edges(data=True):
print("%s <-- %s, %s" % (src, dst, data)) | Pretty printing. |
def _setDatasets(self, metadata):
"""Extract dataset definitions from CSV metadata"""
# Pull the lot into a list
cols = list(self.getCSVReader(metadata))
# sort the cols by view name and ordinal (they come sorted, but lets be sure)
cols.sort(key=lambda x: [x['viewname'], int(x['... | Extract dataset definitions from CSV metadata |
def validate_mixture(supports_mixture: SupportsMixture):
"""Validates that the mixture's tuple are valid probabilities."""
mixture_tuple = mixture(supports_mixture, None)
if mixture_tuple is None:
raise TypeError('{}_mixture did not have a _mixture_ method'.format(
supports_mixture))
... | Validates that the mixture's tuple are valid probabilities. |
def load_ext(self):
"""Read the internal data from an external data file."""
try:
sequencemanager = hydpy.pub.sequencemanager
except AttributeError:
raise RuntimeError(
'The time series of sequence %s cannot be loaded. Firstly, '
'you have... | Read the internal data from an external data file. |
def separateKeywords(kwArgsDict):
""" Look through the keywords passed and separate the special ones we
have added from the legal/standard ones. Return both sets as two
dicts (in a tuple), as (standardKws, ourKws) """
standardKws = {}
ourKws = {}
for k in kwArgsDict:
if k in STA... | Look through the keywords passed and separate the special ones we
have added from the legal/standard ones. Return both sets as two
dicts (in a tuple), as (standardKws, ourKws) |
def bind_unix_socket(file_, mode=0o600, backlog=_DEFAULT_BACKLOG):
"""Creates a listening unix socket.
If a socket with the given name already exists, it will be deleted.
If any other file with that name exists, an exception will be
raised.
Returns a socket object (not a list of socket objects lik... | Creates a listening unix socket.
If a socket with the given name already exists, it will be deleted.
If any other file with that name exists, an exception will be
raised.
Returns a socket object (not a list of socket objects like
`bind_sockets`) |
def _compute_integral_x(self):
"""Computes the integral of x,
\\int_V x,
over all atomic "triangles", i.e., areas cornered by a node, an edge
midpoint, and a circumcenter.
"""
# The integral of any linear function over a triangle is the average of
# the values... | Computes the integral of x,
\\int_V x,
over all atomic "triangles", i.e., areas cornered by a node, an edge
midpoint, and a circumcenter. |
def derivative(self, point):
r"""The derivative operator.
``DistOperator(y).derivative(z)(x) ==
((y - z) / y.dist(z)).inner(x)``
This is only applicable in inner product spaces.
Parameters
----------
x : `domain` `element-like`
Point in whic... | r"""The derivative operator.
``DistOperator(y).derivative(z)(x) ==
((y - z) / y.dist(z)).inner(x)``
This is only applicable in inner product spaces.
Parameters
----------
x : `domain` `element-like`
Point in which to take the derivative.
Re... |
def get_organisations(self, **query_params):
'''
Get all organisations this member is attached to. Return a list of
Organisation objects.
Returns:
list(Organisation): Return all organisations this member is
attached to
'''
organisations = self.get... | Get all organisations this member is attached to. Return a list of
Organisation objects.
Returns:
list(Organisation): Return all organisations this member is
attached to |
def hexists(self, key, field):
"""Determine if hash field exists."""
fut = self.execute(b'HEXISTS', key, field)
return wait_convert(fut, bool) | Determine if hash field exists. |
def raw_command(self, lun, netfn, raw_bytes):
"""Send the raw command data and return the raw response.
lun: the logical unit number
netfn: the network function
raw_bytes: the raw message as bytestring
Returns the response as bytestring.
"""
return self.interfac... | Send the raw command data and return the raw response.
lun: the logical unit number
netfn: the network function
raw_bytes: the raw message as bytestring
Returns the response as bytestring. |
def revnet_110_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = False
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams | Tiny hparams suitable for CIFAR/etc. |
def create_category(self, category):
"""CreateCategory.
[Preview API]
:param :class:`<ExtensionCategory> <azure.devops.v5_1.gallery.models.ExtensionCategory>` category:
:rtype: :class:`<ExtensionCategory> <azure.devops.v5_1.gallery.models.ExtensionCategory>`
"""
content =... | CreateCategory.
[Preview API]
:param :class:`<ExtensionCategory> <azure.devops.v5_1.gallery.models.ExtensionCategory>` category:
:rtype: :class:`<ExtensionCategory> <azure.devops.v5_1.gallery.models.ExtensionCategory>` |
def _truncateend(self, bits):
"""Truncate bits from the end of the bitstring."""
assert 0 <= bits <= self.len
if not bits:
return
if bits == self.len:
self._clear()
return
newlength_in_bytes = (self._offset + self.len - bits + 7) // 8
s... | Truncate bits from the end of the bitstring. |
def static_sum(values, limit_n=1000):
"""Example of static sum routine."""
if len(values) < limit_n:
return sum(values)
else:
half = len(values) // 2
return add(
static_sum(values[:half], limit_n),
static_sum(values[half:], limit_n)) | Example of static sum routine. |
def insert_fft_option_group(parser):
"""
Adds the options used to choose an FFT backend. This should be used
if your program supports the ability to select the FFT backend; otherwise
you may simply call the fft and ifft functions and rely on default
choices. This function will also attempt to add a... | Adds the options used to choose an FFT backend. This should be used
if your program supports the ability to select the FFT backend; otherwise
you may simply call the fft and ifft functions and rely on default
choices. This function will also attempt to add any options exported
by available backends thr... |
def echo(
message=None, file=None, nl=True, err=False, color=None, carriage_return=False
):
"""
Patched click echo function.
"""
message = message or ""
if carriage_return and nl:
click_echo(message + "\r\n", file, False, err, color)
elif carriage_return and not nl:
click_ech... | Patched click echo function. |
def destructive_inject(self, filename, content):
"""
Injects the injections desired immediately. This should
generally be run only during the commit phase, when no future
injections will be done.
"""
content = _unicode(content)
backup_file(filename)
full_p... | Injects the injections desired immediately. This should
generally be run only during the commit phase, when no future
injections will be done. |
def prepare(_next, self):
"""Hook after prepare and set 'principal_roles' as selection to
``self.form``.
"""
_next(self)
if not self.roles_support:
return
if not self.request.has_permission('manage', self.model.parent):
# XXX: yafowil selection dis... | Hook after prepare and set 'principal_roles' as selection to
``self.form``. |
def make_table(self):
"""Make numpy array from timeseries data."""
num_records = int(np.sum([1 for frame in self.timeseries]))
dtype = [
("frame",float),("time",float),("proteinring",list),
("ligand_ring_ids",list),("distance",float),("angle",float),
... | Make numpy array from timeseries data. |
def get_slider_items(context, amount=None):
"""Returns the published slider items."""
req = context.get('request')
qs = SliderItem.objects.published(req).order_by('position')
if amount:
qs = qs[:amount]
return qs | Returns the published slider items. |
def delete(self):
"""Remove the activation from the agenda."""
if lib.EnvDeleteActivation(self._env, self._act) != 1:
raise CLIPSError(self._env)
self._env = None | Remove the activation from the agenda. |
def show_category(self):
"""doc: http://open.youku.com/docs/doc?id=93
"""
url = 'https://openapi.youku.com/v2/schemas/show/category.json'
r = requests.get(url)
check_error(r)
return r.json() | doc: http://open.youku.com/docs/doc?id=93 |
def prettyln(text, fill='-', align='^', prefix='[ ', suffix=' ]', length=69):
"""Wrap `text` in a pretty line with maximum length."""
text = '{prefix}{0}{suffix}'.format(text, prefix=prefix, suffix=suffix)
print(
"{0:{fill}{align}{length}}".format(
text, fill=fill, align=align, length=le... | Wrap `text` in a pretty line with maximum length. |
def visitNodeConstraintNonLiteral(self, ctx: ShExDocParser.NodeConstraintNonLiteralContext):
""" nodeConstraint: nonLiteralKind stringFacet* # nodeConstraintNonLiteral """
self.nodeconstraint.nodeKind = 'iri' if ctx.nonLiteralKind().KW_IRI() \
else 'bnode' if ctx.nonLiteralKind().KW_BNODE()... | nodeConstraint: nonLiteralKind stringFacet* # nodeConstraintNonLiteral |
def lambda_vpc_execution_statements():
"""Allow Lambda to manipuate EC2 ENIs for VPC support."""
return [
Statement(
Effect=Allow,
Resource=['*'],
Action=[
ec2.CreateNetworkInterface,
ec2.DescribeNetworkInterfaces,
ec2.D... | Allow Lambda to manipuate EC2 ENIs for VPC support. |
def array(input, separator=',', strip=True, empty=False):
"""Convert the given input to a list.
Intelligently handles list and non-string values, returning
as-is and passing to the list builtin respectively.
The default optional keyword arguments allow for lists in the form::
"foo... | Convert the given input to a list.
Intelligently handles list and non-string values, returning
as-is and passing to the list builtin respectively.
The default optional keyword arguments allow for lists in the form::
"foo,bar, baz , diz" -> ['foo', 'bar', 'baz', 'diz']
For a... |
def stop_ppp_link(self):
'''stop the link'''
if self.ppp_fd == -1:
return
try:
self.mpself.select_extra.pop(self.ppp_fd)
os.close(self.ppp_fd)
os.waitpid(self.pid, 0)
except Exception:
pass
self.pid = -1
self.ppp... | stop the link |
def plot_all(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, kurtosis=True, **kwargs):
""" Plot waterfall of data as well as spectrum; also, placeholder to make even more complicated plots in the future.
Args:
f_start (float): start frequency, in MHz
f_stop (float):... | Plot waterfall of data as well as spectrum; also, placeholder to make even more complicated plots in the future.
Args:
f_start (float): start frequency, in MHz
f_stop (float): stop frequency, in MHz
logged (bool): Plot in linear (False) or dB units (True),
t (int... |
def max_display_width(myDict):
'''
currd = {0:'你们大家好', 125:'ABCDE', 6:'1234567'}
dict_get_max_word_displaywidth(currd)
'''
maxValueWidth = 0
for each in myDict:
eachValueWidth = str_display_width(myDict[each])
if(eachValueWidth > maxValueWidth):
maxValueWidth ... | currd = {0:'你们大家好', 125:'ABCDE', 6:'1234567'}
dict_get_max_word_displaywidth(currd) |
def download_file(self, url, download_dir, sceneName):
""" Downloads large files in pieces """
try:
# Log
logger.info('\nStarting download..')
print('\n Starting download..\n')
# Request
req = urllib.request.urlopen(url)
try:
... | Downloads large files in pieces |
def collections(cloud=None, api_key=None, version=None, **kwargs):
"""
This is a status report endpoint. It is used to get the status on all of the collections currently trained, as
well as some basic statistics on their accuracies.
Inputs
api_key (optional) - String: Your API key, required only if... | This is a status report endpoint. It is used to get the status on all of the collections currently trained, as
well as some basic statistics on their accuracies.
Inputs
api_key (optional) - String: Your API key, required only if the key has not been declared
elsewhere. This allows the API to recogniz... |
def brighten(self, amount=10):
"""
Brighten this color by `amount` luminance.
Converts this color to the LCH color space, and then
increases the `L` parameter by `amount`.
:param float amount: Amount to increase the luminance.
:rtype: Color
:returns: A new spec... | Brighten this color by `amount` luminance.
Converts this color to the LCH color space, and then
increases the `L` parameter by `amount`.
:param float amount: Amount to increase the luminance.
:rtype: Color
:returns: A new spectra.Color |
def expression_filter(self, name, **kwargs):
"""
Returns a decorator function for adding an expression filter.
Args:
name (str): The name of the filter.
**kwargs: Variable keyword arguments for the filter.
Returns:
Callable[[Callable[[AbstractExpress... | Returns a decorator function for adding an expression filter.
Args:
name (str): The name of the filter.
**kwargs: Variable keyword arguments for the filter.
Returns:
Callable[[Callable[[AbstractExpression, Any], AbstractExpression]]]: A decorator
fun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.