code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _stringify_column(self, column_index):
'''
Same as _stringify_row but for columns.
'''
table_column = TableTranspose(self.table)[column_index]
prior_cell = None
for row_index in range(self.start[0], self.end[0]):
cell, changed = self._check_interpret_cell(... | Same as _stringify_row but for columns. |
def _swap_slice_indices(self, slc, make_slice=False):
'''Swap slice indices
Change slice indices from Verilog slicing (e.g. IEEE 1800-2012) to Python slicing.
'''
try:
start = slc.start
stop = slc.stop
slc_step = slc.step
except AttributeError... | Swap slice indices
Change slice indices from Verilog slicing (e.g. IEEE 1800-2012) to Python slicing. |
def node_to_evenly_discretized(node):
"""
Parses the evenly discretized mfd node to an instance of the
:class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD,
or to None if not all parameters are available
"""
if not all([node.attrib["minMag"], node.attrib["binWidth"],
... | Parses the evenly discretized mfd node to an instance of the
:class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD,
or to None if not all parameters are available |
def repr_size(n_bytes):
"""
>>> repr_size(1000)
'1000 Bytes'
>>> repr_size(8257332324597)
'7.5 TiB'
"""
if n_bytes < 1024:
return '{0} Bytes'.format(n_bytes)
i = -1
while n_bytes > 1023:
n_bytes /= 1024.0
i += 1
return '{0} {1}iB'.format(round(n_bytes, 1),... | >>> repr_size(1000)
'1000 Bytes'
>>> repr_size(8257332324597)
'7.5 TiB' |
def rbac_policy_update(request, policy_id, **kwargs):
"""Update a RBAC Policy.
:param request: request context
:param policy_id: target policy id
:param target_tenant: target tenant of the policy
:return: RBACPolicy object
"""
body = {'rbac_policy': kwargs}
rbac_policy = neutronclient(r... | Update a RBAC Policy.
:param request: request context
:param policy_id: target policy id
:param target_tenant: target tenant of the policy
:return: RBACPolicy object |
def dockprep(self, force_rerun=False):
"""Prepare a PDB file for docking by first converting it to mol2 format.
Args:
force_rerun (bool): If method should be rerun even if output file exists
"""
log.debug('{}: running dock preparation...'.format(self.id))
prep_mol2... | Prepare a PDB file for docking by first converting it to mol2 format.
Args:
force_rerun (bool): If method should be rerun even if output file exists |
def sync_memoize(f):
"""
Like memoize, but guarantees that decorated function is only called once, even when multiple
threads are calling the decorating function with multiple parameters.
"""
# TODO: Think about an f that is recursive
memory = {}
lock = Lock()
@wraps(f)
def new_f(*a... | Like memoize, but guarantees that decorated function is only called once, even when multiple
threads are calling the decorating function with multiple parameters. |
def cmd_up(self, args):
'''adjust TRIM_PITCH_CD up by 5 degrees'''
if len(args) == 0:
adjust = 5.0
else:
adjust = float(args[0])
old_trim = self.get_mav_param('TRIM_PITCH_CD', None)
if old_trim is None:
print("Existing trim value unknown!")
... | adjust TRIM_PITCH_CD up by 5 degrees |
def MoveToAttribute(self, name):
"""Moves the position of the current instance to the attribute
with the specified qualified name. """
ret = libxml2mod.xmlTextReaderMoveToAttribute(self._o, name)
return ret | Moves the position of the current instance to the attribute
with the specified qualified name. |
def in6_chksum(nh, u, p):
"""
As Specified in RFC 2460 - 8.1 Upper-Layer Checksums
Performs IPv6 Upper Layer checksum computation. Provided parameters are:
- 'nh' : value of upper layer protocol
- 'u' : upper layer instance (TCP, UDP, ICMPv6*, ). Instance must be
provided with all und... | As Specified in RFC 2460 - 8.1 Upper-Layer Checksums
Performs IPv6 Upper Layer checksum computation. Provided parameters are:
- 'nh' : value of upper layer protocol
- 'u' : upper layer instance (TCP, UDP, ICMPv6*, ). Instance must be
provided with all under layers (IPv6 and all extension head... |
def _print_divide(self):
"""Prints all those table line dividers."""
for space in self.AttributesLength:
self.StrTable += "+ " + "- " * space
self.StrTable += "+" + "\n" | Prints all those table line dividers. |
def data_to_imagesurface (data, **kwargs):
"""Turn arbitrary data values into a Cairo ImageSurface.
The method and arguments are the same as data_to_argb32, except that the
data array will be treated as 2D, and higher dimensionalities are not
allowed. The return value is a Cairo ImageSurface object.
... | Turn arbitrary data values into a Cairo ImageSurface.
The method and arguments are the same as data_to_argb32, except that the
data array will be treated as 2D, and higher dimensionalities are not
allowed. The return value is a Cairo ImageSurface object.
Combined with the write_to_png() method on Imag... |
def rvs(self, size=1, param=None):
"""Gives a set of random values drawn from the kde.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given paramete... | Gives a set of random values drawn from the kde.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns random value... |
def push(self, next_dfa, next_state, node_type, lineno, column):
"""Push a terminal and adjust the current state."""
dfa, state, node = self.stack[-1]
new_node = Node(node_type, None, [], lineno, column)
self.stack[-1] = (dfa, next_state, node)
self.stack.append((next_dfa, 0, new... | Push a terminal and adjust the current state. |
def to_match(self):
"""Return a unicode object with the MATCH representation of this BetweenClause."""
template = u'({field_name} BETWEEN {lower_bound} AND {upper_bound})'
return template.format(
field_name=self.field.to_match(),
lower_bound=self.lower_bound.to_match(),
... | Return a unicode object with the MATCH representation of this BetweenClause. |
def check_auth(name, sock_dir=None, queue=None, timeout=300):
'''
This function is called from a multiprocess instance, to wait for a minion
to become available to receive salt commands
'''
event = salt.utils.event.SaltEvent('master', sock_dir, listen=True)
starttime = time.mktime(time.localtime... | This function is called from a multiprocess instance, to wait for a minion
to become available to receive salt commands |
def change_email(self, email):
"""
Change user's login email
:param user: AuthUser
:param email:
:return:
"""
def cb():
if not utils.is_email_valid(email):
raise exceptions.AuthError("Email address invalid")
self.user.chang... | Change user's login email
:param user: AuthUser
:param email:
:return: |
def create_venv(local='y', test='y', general='y'):
"""Create virtualenv w/requirements. Specify y/n for local/test/general to control installation."""
if not path.isdir(project_paths.venv):
execute('virtualenv', '--distribute', '--no-site-packages', project_paths.venv)
project.execute_python('-m... | Create virtualenv w/requirements. Specify y/n for local/test/general to control installation. |
def _dump_query_timestamps(self, current_time: float):
"""Output the number of GraphQL queries grouped by their query_hash within the last time."""
windows = [10, 11, 15, 20, 30, 60]
print("GraphQL requests:", file=sys.stderr)
for query_hash, times in self._graphql_query_timestamps.items... | Output the number of GraphQL queries grouped by their query_hash within the last time. |
def notify(self, message, priority='normal', timeout=0, block=False):
"""
opens notification popup.
:param message: message to print
:type message: str
:param priority: priority string, used to format the popup: currently,
'normal' and 'error' are define... | opens notification popup.
:param message: message to print
:type message: str
:param priority: priority string, used to format the popup: currently,
'normal' and 'error' are defined. If you use 'X' here,
the attribute 'global_notify_X' is used t... |
def verify_ticket(self, ticket, **kwargs):
"""Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.
@date: 2011-11-30
@author: Carlos Gonzalez Vila <carlewis@gmail.com>
Returns username and attributes on success and None,None on failure.
"""
... | Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.
@date: 2011-11-30
@author: Carlos Gonzalez Vila <carlewis@gmail.com>
Returns username and attributes on success and None,None on failure. |
def contains_point(self, x, y, d=2):
""" Returns true when x, y is on the path stroke outline.
"""
if self.path != None and len(self.path) > 1 \
and self.path.contains(x, y):
# If all points around the mouse are also part of the path,
# this mean... | Returns true when x, y is on the path stroke outline. |
def make_ar_transition_matrix(coefficients):
"""Build transition matrix for an autoregressive StateSpaceModel.
When applied to a vector of previous values, this matrix computes
the expected new value (summing the previous states according to the
autoregressive coefficients) in the top dimension of the state sp... | Build transition matrix for an autoregressive StateSpaceModel.
When applied to a vector of previous values, this matrix computes
the expected new value (summing the previous states according to the
autoregressive coefficients) in the top dimension of the state space,
and moves all previous values down by one d... |
def get_service(self, name):
"""
Locates a remote service by name. The name can be a glob-like pattern
(``"project.worker.*"``). If multiple services match the given name, a
random instance will be chosen. There might be multiple services that
match a given name if there are mult... | Locates a remote service by name. The name can be a glob-like pattern
(``"project.worker.*"``). If multiple services match the given name, a
random instance will be chosen. There might be multiple services that
match a given name if there are multiple services with the same name
running,... |
def min(a, axis=None):
"""
Request the minimum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose minimum is to be found.
axis : None, or int, or iterable of ints
Axis or ax... | Request the minimum of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
Parameters
----------
a : Array object
The object whose minimum is to be found.
axis : None, or int, or iterable of ints
Axis or axes along which the operation is per... |
def _find_by_name(tree_data, name, is_dir, start_at):
"""return data entry matching the given name and tree mode
or None.
Before the item is returned, the respective data item is set
None in the tree_data list to mark it done"""
try:
item = tree_data[start_at]
if item and item[2] == ... | return data entry matching the given name and tree mode
or None.
Before the item is returned, the respective data item is set
None in the tree_data list to mark it done |
def relativefrom(base, path):
# type: (Text, Text) -> Text
"""Return a path relative from a given base path.
Insert backrefs as appropriate to reach the path from the base.
Arguments:
base (str): Path to a directory.
path (str): Path to make relative.
Returns:
str: the pat... | Return a path relative from a given base path.
Insert backrefs as appropriate to reach the path from the base.
Arguments:
base (str): Path to a directory.
path (str): Path to make relative.
Returns:
str: the path to ``base`` from ``path``.
>>> relativefrom("foo/bar", "baz/ind... |
def convert_to_argument(self):
'''
Convert the Argument object to a tuple use in :meth:`~argparse.ArgumentParser.add_argument` calls on the parser
'''
field_list = [
"action", "nargs", "const", "default", "type",
"choices", "required", "help", "metavar", "des... | Convert the Argument object to a tuple use in :meth:`~argparse.ArgumentParser.add_argument` calls on the parser |
def _removePunctuation(text_string):
"""
Removes punctuation symbols from a string.
:param text_string: A string.
:type text_string: str.
:returns: The input ``text_string`` with punctuation symbols removed.
:rtype: str.
>>> from rnlp.textprocessing import __removePunctuation
>>> exam... | Removes punctuation symbols from a string.
:param text_string: A string.
:type text_string: str.
:returns: The input ``text_string`` with punctuation symbols removed.
:rtype: str.
>>> from rnlp.textprocessing import __removePunctuation
>>> example = 'Hello, World!'
>>> __removePunctuation... |
def compare(self,
reference_ids: Iterable,
query_profiles: Iterable[Iterable],
method: Optional) -> SimResult:
"""
Given two lists of entities (classes, individuals),
resolves them to some type (phenotypes, go terms, etc) and
returns their ... | Given two lists of entities (classes, individuals),
resolves them to some type (phenotypes, go terms, etc) and
returns their similarity |
def email_link_expired(self, now=None):
""" Check if email link expired """
if not now: now = datetime.datetime.utcnow()
return self.email_link_expires < now | Check if email link expired |
def is_armed(self):
"""Return True or False if the system is armed in any way"""
alarm_code = self.get_armed_status()
if alarm_code == YALE_STATE_ARM_FULL:
return True
if alarm_code == YALE_STATE_ARM_PARTIAL:
return True
return False | Return True or False if the system is armed in any way |
def isosceles(cls, origin=None, base=1, alpha=90):
'''
:origin: optional Point
:base: optional float describing triangle base length
:return: Triangle initialized with points comprising a
isosceles triangle.
XXX isoceles triangle definition
'''
... | :origin: optional Point
:base: optional float describing triangle base length
:return: Triangle initialized with points comprising a
isosceles triangle.
XXX isoceles triangle definition |
def add_quality_score_vs_no_of_observations_section(self):
""" Add a section for the quality score vs number of observations line plot """
sample_data = []
data_labels = []
for rt_type_name, rt_type in recal_table_type._asdict().items():
sample_tables = self.gatk_base_recali... | Add a section for the quality score vs number of observations line plot |
def add_column(self, column):
"""Add a new column along with a formatting function."""
self.columns.append(column.name)
self.column_funcs.append(column.path)
if column.mask is not None:
self.mask_parts.add(column.mask) | Add a new column along with a formatting function. |
def auth(view, **kwargs):
"""
This plugin allow user to login to application
kwargs:
- signin_view
- signout_view
- template_dir
- menu:
- name
- group_name
- ...
@plugin(user.login, model=model.User)
class MyAccount(Juice... | This plugin allow user to login to application
kwargs:
- signin_view
- signout_view
- template_dir
- menu:
- name
- group_name
- ...
@plugin(user.login, model=model.User)
class MyAccount(Juice):
pass |
def K_run_converging_Crane(D_run, D_branch, Q_run, Q_branch, angle=90):
r'''Returns the loss coefficient for the run of a converging tee or wye
according to the Crane method [1]_.
.. math::
K_{branch} = C\left[1 + D\left(\frac{Q_{branch}}{Q_{comb}\cdot
\beta_{branch}^2}\right)^2 - E\le... | r'''Returns the loss coefficient for the run of a converging tee or wye
according to the Crane method [1]_.
.. math::
K_{branch} = C\left[1 + D\left(\frac{Q_{branch}}{Q_{comb}\cdot
\beta_{branch}^2}\right)^2 - E\left(1 - \frac{Q_{branch}}{Q_{comb}}
\right)^2 - \frac{F}{\beta_{branc... |
def _get_compose_volumes(app_name, assembled_specs):
""" This returns formatted volume specifications for a docker-compose app. We mount the app
as well as any libs it needs so that local code is used in our container, instead of whatever
code was in the docker image.
Additionally, we create a volume f... | This returns formatted volume specifications for a docker-compose app. We mount the app
as well as any libs it needs so that local code is used in our container, instead of whatever
code was in the docker image.
Additionally, we create a volume for the /cp directory used by Dusty to facilitate
easy fil... |
def validate_boundary(reference_intervals, estimated_intervals, trim):
"""Checks that the input annotations to a segment boundary estimation
metric (i.e. one that only takes in segment intervals) look like valid
segment times, and throws helpful errors if not.
Parameters
----------
reference_in... | Checks that the input annotations to a segment boundary estimation
metric (i.e. one that only takes in segment intervals) look like valid
segment times, and throws helpful errors if not.
Parameters
----------
reference_intervals : np.ndarray, shape=(n, 2)
reference segment intervals, in the... |
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
'''draw a line on the image'''
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
clipped = cv.ClipLine((img.width, img.height), pix1, pix2)
if clipped is None:
return
(pix1, pix2) = clipped
cv... | draw a line on the image |
def servo_output_raw_send(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, force_mavlink1=False):
'''
The RAW values of the servo outputs (for RC input from the remote, use
the RC_CHANNELS messages). Th... | The RAW values of the servo outputs (for RC input from the remote, use
the RC_CHANNELS messages). The standard PPM modulation
is as follows: 1000 microseconds: 0%, 2000
microseconds: 100%.
time_usec : Timestamp (microseconds since system b... |
def update(self, alert_condition_infra_id, policy_id,
name, condition_type, alert_condition_configuration, enabled=True):
"""
This API endpoint allows you to update an alert condition for infrastucture
:type alert_condition_infra_id: int
:param alert_condition_infra_id: A... | This API endpoint allows you to update an alert condition for infrastucture
:type alert_condition_infra_id: int
:param alert_condition_infra_id: Alert Condition Infra ID
:type policy_id: int
:param policy_id: Alert policy id
:type name: str
:param name: The name of the... |
def set_chuid(ctx, management_key, pin):
"""
Generate and set a CHUID on the YubiKey.
"""
controller = ctx.obj['controller']
_ensure_authenticated(ctx, controller, pin, management_key)
controller.update_chuid() | Generate and set a CHUID on the YubiKey. |
def draw_char_screen(self):
"""
Draws the output buffered in the char_buffer.
"""
self.screen = Image.new("RGB", (self.height, self.width))
self.drawer = ImageDraw.Draw(self.screen)
for sy, line in enumerate(self.char_buffer):
for sx, tinfo in enumerate(line):
self.drawer.text((sx * 6, sy * 9), tinf... | Draws the output buffered in the char_buffer. |
def _cleanup_channel(self, channel_id):
"""Remove the the channel from the list of available channels.
:param int channel_id: Channel id
:return:
"""
with self.lock:
if channel_id not in self._channels:
return
del self._channels[channel_i... | Remove the the channel from the list of available channels.
:param int channel_id: Channel id
:return: |
def words(ctx, input, output):
"""Read input document, and output words."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences... | Read input document, and output words. |
def before_create(self, context, resource):
"""
When triggered the resource which can either be uploaded or linked
to will be parsed and analysed to see if it possibly is a budget
data package resource (checking if all required headers and any of
the recommended headers exist in ... | When triggered the resource which can either be uploaded or linked
to will be parsed and analysed to see if it possibly is a budget
data package resource (checking if all required headers and any of
the recommended headers exist in the csv).
The budget data package specific fields are t... |
def remap( x, oMin, oMax, nMin, nMax ):
"""Map to a 0 to 1 scale
http://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio
"""
#range check
if oMin == oMax:
log.warning("Zero input range, unable to rescale")
return x
if nMin == nMa... | Map to a 0 to 1 scale
http://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio |
def greenlet_logs(self):
""" This greenlet always runs in background to update current
logs in MongoDB every 10 seconds.
Caution: it might get delayed when doing long blocking operations.
Should we do this in a thread instead?
"""
while True:
tr... | This greenlet always runs in background to update current
logs in MongoDB every 10 seconds.
Caution: it might get delayed when doing long blocking operations.
Should we do this in a thread instead? |
def lu_companion(top_row, value):
r"""Compute an LU-factored :math:`C - t I` and its 1-norm.
.. _dgecon:
http://www.netlib.org/lapack/explore-html/dd/d9a/group__double_g_ecomputational_ga188b8d30443d14b1a3f7f8331d87ae60.html#ga188b8d30443d14b1a3f7f8331d87ae60
.. _dgetrf:
http://www.netlib.o... | r"""Compute an LU-factored :math:`C - t I` and its 1-norm.
.. _dgecon:
http://www.netlib.org/lapack/explore-html/dd/d9a/group__double_g_ecomputational_ga188b8d30443d14b1a3f7f8331d87ae60.html#ga188b8d30443d14b1a3f7f8331d87ae60
.. _dgetrf:
http://www.netlib.org/lapack/explore-html/dd/d9a/group__d... |
def _get_environ_vars(self):
# type: () -> Iterable[Tuple[str, str]]
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
should_be_yielded = (
key.startswith("PIP_") and
key[4:].lower() not in self... | Returns a generator with all environmental vars with prefix PIP_ |
def subscriber_choice_control(self):
"""
It controls subscribers choice and generates
error message if there is a non-choice.
"""
self.current.task_data['option'] = None
self.current.task_data['chosen_subscribers'], names = self.return_selected_form_items(
sel... | It controls subscribers choice and generates
error message if there is a non-choice. |
def compare_ecp_pots(potential1, potential2, compare_meta=False, rel_tol=0.0):
'''
Compare two ecp potentials for approximate equality
(exponents/coefficients are within a tolerance)
If compare_meta is True, the metadata is also compared for exact equality.
'''
if potential1['angular_momentum... | Compare two ecp potentials for approximate equality
(exponents/coefficients are within a tolerance)
If compare_meta is True, the metadata is also compared for exact equality. |
def mtFeatureExtractionToFile(fileName, midTermSize, midTermStep, shortTermSize, shortTermStep, outPutFile,
storeStFeatures=False, storeToCSV=False, PLOT=False):
"""
This function is used as a wrapper to:
a) read the content of a WAV file
b) perform mid-term feature extract... | This function is used as a wrapper to:
a) read the content of a WAV file
b) perform mid-term feature extraction on that signal
c) write the mid-term feature sequences to a numpy file |
def query_organism_host():
"""
Returns list of host organism by query parameters
---
tags:
- Query functions
parameters:
- name: taxid
in: query
type: integer
required: false
description: NCBI taxonomy identifier
default: 9606
- name: en... | Returns list of host organism by query parameters
---
tags:
- Query functions
parameters:
- name: taxid
in: query
type: integer
required: false
description: NCBI taxonomy identifier
default: 9606
- name: entry_name
in: query
type... |
def use_plenary_agent_view(self):
"""Pass through to provider ResourceAgentSession.use_plenary_agent_view"""
self._object_views['agent'] = PLENARY
# self._get_provider_session('resource_agent_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
... | Pass through to provider ResourceAgentSession.use_plenary_agent_view |
def start_watching(self, cluster, callback):
"""
Initiates the "watching" of a cluster's associated znode.
This is done via kazoo's ChildrenWatch object. When a cluster's
znode's child nodes are updated, a callback is fired and we update
the cluster's `nodes` attribute based on... | Initiates the "watching" of a cluster's associated znode.
This is done via kazoo's ChildrenWatch object. When a cluster's
znode's child nodes are updated, a callback is fired and we update
the cluster's `nodes` attribute based on the existing child znodes
and fire a passed-in callback ... |
def copy_config_file(self, config_file, path=None, overwrite=False):
"""Copy a default config file into the active profile directory.
Default configuration files are kept in :mod:`IPython.config.default`.
This function moves these from that location to the working profile
directory.
... | Copy a default config file into the active profile directory.
Default configuration files are kept in :mod:`IPython.config.default`.
This function moves these from that location to the working profile
directory. |
def deactivate_workflow_transitions(cr, model, transitions=None):
"""
Disable workflow transitions for workflows on a given model.
This can be necessary for automatic workflow transitions when writing
to an object via the ORM in the post migration step.
Returns a dictionary to be used on reactivate_... | Disable workflow transitions for workflows on a given model.
This can be necessary for automatic workflow transitions when writing
to an object via the ORM in the post migration step.
Returns a dictionary to be used on reactivate_workflow_transitions
:param model: the model for which workflow transitio... |
def subject_sequence_retriever(fasta_handle, b6_handle, e_value,
*args, **kwargs):
"""Returns FASTA entries for subject sequences from BLAST hits
Stores B6/M8 entries with E-Values below the e_value cutoff. Then iterates
through the FASTA file and if an entry matches the subj... | Returns FASTA entries for subject sequences from BLAST hits
Stores B6/M8 entries with E-Values below the e_value cutoff. Then iterates
through the FASTA file and if an entry matches the subject of an B6/M8
entry, it's sequence is extracted and returned as a FASTA entry
plus the E-Value.
Args:
... |
def _check_iou_licence(self):
"""
Checks for a valid IOU key in the iourc file (paranoid mode).
"""
try:
license_check = self._config().getboolean("license_check", True)
except ValueError:
raise IOUError("Invalid licence check setting")
if license_... | Checks for a valid IOU key in the iourc file (paranoid mode). |
def determine_node(self):
"""
Determines the type of node based on a combination of forwarding
reachability and NAT type.
"""
# Manually set node_type as simultaneous.
if self.node_type == "simultaneous":
if self.nat_type != "unknown":
... | Determines the type of node based on a combination of forwarding
reachability and NAT type. |
def parse_node_response(self, response):
"""
Update the object with the remote node object
"""
for key, value in response.items():
if key == "console":
self._console = value
elif key == "node_directory":
self._node_directory = value... | Update the object with the remote node object |
def delete_collection_namespaced_replication_controller(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_replication_controller # noqa: E501
delete collection of ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | delete_collection_namespaced_replication_controller # noqa: E501
delete collection of ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespa... |
def _apply_dvportgroup_out_shaping(pg_name, out_shaping, out_shaping_conf):
'''
Applies the values in out_shaping_conf to an out_shaping object
pg_name
The name of the portgroup
out_shaping
The vim.DVSTrafficShapingPolicy to apply the config to
out_shaping_conf
The out sha... | Applies the values in out_shaping_conf to an out_shaping object
pg_name
The name of the portgroup
out_shaping
The vim.DVSTrafficShapingPolicy to apply the config to
out_shaping_conf
The out shaping config |
def mean(self):
"""Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible.
"""
return np.dot(np.array(self.norm_scores), self.weights) | Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible. |
def perform_permissions_check(self, user, obj, perms):
""" Performs the permissions check. """
return self.request.forum_permission_handler.can_access_moderation_queue(user) | Performs the permissions check. |
def dorun(method, platonics=None, nsnrs=20, noise_samples=30, sweeps=30, burn=15):
"""
platonics = create_many_platonics(N=50)
dorun(platonics)
"""
sigmas = np.logspace(np.log10(1.0/2048), 0, nsnrs)
crbs, vals, errs, poss = [], [], [], []
for sigma in sigmas:
print "#### sigma:", si... | platonics = create_many_platonics(N=50)
dorun(platonics) |
def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) | Saves dictionary as CSV file. |
def create_border(video, color="blue", border_percent=2):
"""Creates a border around each frame to differentiate input and target.
Args:
video: 5-D NumPy array.
color: string, "blue", "red" or "green".
border_percent: Percentarge of the frame covered by the border.
Returns:
video: 5-D NumPy array... | Creates a border around each frame to differentiate input and target.
Args:
video: 5-D NumPy array.
color: string, "blue", "red" or "green".
border_percent: Percentarge of the frame covered by the border.
Returns:
video: 5-D NumPy array. |
def strip_water(self, os=None, o=None, on=None, compact=False,
resn="SOL", groupname="notwater", **kwargs):
"""Write xtc and tpr with water (by resname) removed.
:Keywords:
*os*
Name of the output tpr file; by default use the original but
inser... | Write xtc and tpr with water (by resname) removed.
:Keywords:
*os*
Name of the output tpr file; by default use the original but
insert "nowater" before suffix.
*o*
Name of the output trajectory; by default use the original name but
i... |
def transform_case(self, description, case_type):
"""Transforms the case of the expression description, based on options
Args:
description: The description to transform
case_type: The casing type that controls the output casing
second_expression: Seconds part
... | Transforms the case of the expression description, based on options
Args:
description: The description to transform
case_type: The casing type that controls the output casing
second_expression: Seconds part
Returns:
The transformed description with proper ... |
def saved_xids(self):
"""Return previously saved xids."""
if self._saved_xids is None:
self._saved_xids = []
if self.debug:
fpfn = os.path.join(self.tcex.args.tc_temp_path, 'xids-saved')
if os.path.isfile(fpfn) and os.access(fpfn, os.R_OK):
... | Return previously saved xids. |
def cloudInCells(x, y, bins, weights=None):
"""
Use cloud-in-cells binning algorithm. Only valid for equal-spaced linear bins.
http://ta.twi.tudelft.nl/dv/users/Lemmens/MThesis.TTH/chapter4.html#tth_sEc2
http://www.gnu.org/software/archimedes/manual/html/node29.html
INPUTS:
x: array of x-va... | Use cloud-in-cells binning algorithm. Only valid for equal-spaced linear bins.
http://ta.twi.tudelft.nl/dv/users/Lemmens/MThesis.TTH/chapter4.html#tth_sEc2
http://www.gnu.org/software/archimedes/manual/html/node29.html
INPUTS:
x: array of x-values
y: array or y-values
bins: [bins_x,... |
def rewind_body(prepared_request):
"""Move file pointer back to its recorded starting position
so it can be read again on redirect.
"""
body_seek = getattr(prepared_request.body, 'seek', None)
if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
try:
... | Move file pointer back to its recorded starting position
so it can be read again on redirect. |
def _request_reports(self, resource_param_name, resources, endpoint_name):
"""Sends multiples requests for the resources to a particular endpoint.
Args:
resource_param_name: a string name of the resource parameter.
resources: list of of the resources.
endpoint_name: ... | Sends multiples requests for the resources to a particular endpoint.
Args:
resource_param_name: a string name of the resource parameter.
resources: list of of the resources.
endpoint_name: VirusTotal endpoint URL suffix.
Returns:
A list of the responses. |
def contact_addresses(self):
"""
Provides a reference to contact addresses used by this server.
Obtain a reference to manipulate or iterate existing contact
addresses::
>>> from smc.elements.servers import ManagementServer
>>> mgt_server = Manage... | Provides a reference to contact addresses used by this server.
Obtain a reference to manipulate or iterate existing contact
addresses::
>>> from smc.elements.servers import ManagementServer
>>> mgt_server = ManagementServer.objects.first()
>>> for co... |
def reindex(self):
'''reset counters and indexes'''
for i in range(self.rally_count()):
self.rally_points[i].count = self.rally_count()
self.rally_points[i].idx = i
self.last_change = time.time() | reset counters and indexes |
def sanitize(self):
'''
Check if the current settings conform to the LISP specifications and
fix them where possible.
'''
super(EncapsulatedControlMessage, self).sanitize()
# S: This is the Security bit. When set to 1 the following
# authentication information w... | Check if the current settings conform to the LISP specifications and
fix them where possible. |
def _validate_list(self, input_list, schema_list, path_to_root, object_title=''):
'''
a helper method for recursively validating items in a list
:return: input_list
'''
# construct rules for list and items
rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root)
... | a helper method for recursively validating items in a list
:return: input_list |
def stop(self):
"""Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical.
"""
if not self.is_running():
raise RuntimeError('Not started')
running, self._running = self._running, None
try:
... | Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical. |
def double_hash_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
... | Computes the double hash encoding of the ngrams with the given keys.
Using the method from:
Schnell, R., Bachteler, T., & Reiher, J. (2011).
A Novel Error-Tolerant Anonymous Linking Code.
http://grlc.german-microsimulation.de/wp-content/uploads/2017/05/downloadwp-grlc-20... |
def difference(self, other, joinBy=None, exact=False):
"""
*Wrapper of* ``DIFFERENCE``
DIFFERENCE is a binary, non-symmetric operator that produces one sample
in the result for each sample of the first operand, by keeping the same
metadata of the first operand sample and only th... | *Wrapper of* ``DIFFERENCE``
DIFFERENCE is a binary, non-symmetric operator that produces one sample
in the result for each sample of the first operand, by keeping the same
metadata of the first operand sample and only those regions (with their
schema and values) of the first operand sam... |
def _pack(formatstring, value):
"""Pack a value into a bytestring.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* value (depends on formatstring): The value to be packed
Returns:
A ... | Pack a value into a bytestring.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* value (depends on formatstring): The value to be packed
Returns:
A bytestring (str).
Raises:
... |
def batch_run_many(player, positions, batch_size=100):
"""Used to avoid a memory oveflow issue when running the network
on too many positions. TODO: This should be a member function of
player.network?"""
prob_list = []
value_list = []
for idx in range(0, len(positions), batch_size):
prob... | Used to avoid a memory oveflow issue when running the network
on too many positions. TODO: This should be a member function of
player.network? |
def on_channel_flow(self, method):
"""When RabbitMQ indicates the connection is unblocked, set the state
appropriately.
:param pika.spec.Channel.Flow method: The Channel flow frame
"""
if method.active:
LOGGER.info('Channel flow is active (READY)')
self.... | When RabbitMQ indicates the connection is unblocked, set the state
appropriately.
:param pika.spec.Channel.Flow method: The Channel flow frame |
def check_and_make_label(lbl, lineno):
""" Checks if the given label (or line number) is valid and, if so,
returns a label object.
:param lbl: Line number of label (string)
:param lineno: Line number in the basic source code for error reporting
:return: Label object or None if error.
"""
if ... | Checks if the given label (or line number) is valid and, if so,
returns a label object.
:param lbl: Line number of label (string)
:param lineno: Line number in the basic source code for error reporting
:return: Label object or None if error. |
def sum(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None):
"""Combine arrays by addition, with masks and offsets.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an ar... | Combine arrays by addition, with masks and offsets.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains th... |
def get_event_logs(self, request_filter=None, log_limit=20, iterator=True):
"""Returns a list of event logs
Example::
event_mgr = SoftLayer.EventLogManager(env.client)
request_filter = event_mgr.build_filter(date_min="01/01/2019", date_max="02/01/2019")
logs = event... | Returns a list of event logs
Example::
event_mgr = SoftLayer.EventLogManager(env.client)
request_filter = event_mgr.build_filter(date_min="01/01/2019", date_max="02/01/2019")
logs = event_mgr.get_event_logs(request_filter)
for log in logs:
print(... |
def _l2rgb(self, mode):
"""Convert from L (black and white) to RGB.
"""
self._check_modes(("L", "LA"))
bands = ["L"] * 3
if mode[-1] == "A":
bands.append("A")
data = self.data.sel(bands=bands)
data["bands"] = list(mode)
return data | Convert from L (black and white) to RGB. |
def filter_off(self, filt=None, analyte=None, samples=None, subset=None, show_status=False):
"""
Turns data filters off for particular analytes and samples.
Parameters
----------
filt : optional, str or array_like
Name, partial name or list of names of filters. Suppo... | Turns data filters off for particular analytes and samples.
Parameters
----------
filt : optional, str or array_like
Name, partial name or list of names of filters. Supports
partial matching. i.e. if 'cluster' is specified, all
filters with 'cluster' in the n... |
def apply(self, func, ids=None, applyto='measurement', noneval=nan,
setdata=False, output_format='dict', ID=None,
**kwargs):
'''
Apply func to each of the specified measurements.
Parameters
----------
func : callable
Accepts a Measurement ... | Apply func to each of the specified measurements.
Parameters
----------
func : callable
Accepts a Measurement object or a DataFrame.
ids : hashable| iterable of hashables | None
Keys of measurements to which func will be applied.
If None is given appl... |
def execute_task(f, args, kwargs, user_ns):
"""
Deserialize the buffer and execute the task.
# Returns the result or exception.
"""
fname = getattr(f, '__name__', 'f')
prefix = "parsl_"
fname = prefix + "f"
argname = prefix + "args"
kwargname = prefix + "kwargs"
resultname = pre... | Deserialize the buffer and execute the task.
# Returns the result or exception. |
def _get_graph_title(self):
"""获取图像的title."""
start_time = datetime.fromtimestamp(int(self.timestamp_list[0]))
end_time = datetime.fromtimestamp(int(self.timestamp_list[-1]))
end_time = end_time.strftime('%H:%M:%S')
title = "Timespan: %s —— %s" % (start_time, end_time)
r... | 获取图像的title. |
def has_callback(obj, handle):
"""Return whether a callback is currently registered for an object."""
callbacks = obj._callbacks
if not callbacks:
return False
if isinstance(callbacks, Node):
return handle is callbacks
else:
return handle in callbacks | Return whether a callback is currently registered for an object. |
def save_keywords(filename, xml):
"""Save keyword XML to filename."""
tmp_dir = os.path.dirname(filename)
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
file_desc = open(filename, "w")
file_desc.write(xml)
file_desc.close() | Save keyword XML to filename. |
def set_Name(self, Name, SaveName=None,
include=None,
ForceUpdate=False):
""" Set the Name of the instance, automatically updating the SaveName
The name should be a str without spaces or underscores (removed)
When the name is changed, if SaveName (i.e. the name... | Set the Name of the instance, automatically updating the SaveName
The name should be a str without spaces or underscores (removed)
When the name is changed, if SaveName (i.e. the name used for saving)
was not user-defined, it is automatically updated
Parameters
----------
... |
def complete_hit(self, text, line, begidx, endidx):
''' Tab-complete hit command. '''
return [i for i in PsiturkNetworkShell.hit_commands if \
i.startswith(text)] | Tab-complete hit command. |
def fill_extents(self):
"""Computes a bounding box in user-space coordinates
covering the area that would be affected, (the "inked" area),
by a :meth:`fill` operation given the current path and fill parameters.
If the current path is empty,
returns an empty rectangle ``(0, 0, 0, ... | Computes a bounding box in user-space coordinates
covering the area that would be affected, (the "inked" area),
by a :meth:`fill` operation given the current path and fill parameters.
If the current path is empty,
returns an empty rectangle ``(0, 0, 0, 0)``.
Surface dimensions an... |
def setCentralWidget(self, widget):
"""
Sets the central widget for this button.
:param widget | <QWidget>
"""
self.setEnabled(widget is not None)
self._popupWidget.setCentralWidget(widget) | Sets the central widget for this button.
:param widget | <QWidget> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.