text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _get_metadata_for_region(region_code):
"""The metadata needed by this class is the same for all regions
sharing the same country calling code. Therefore, we return the
metadata for "main" region for this country calling code."""
country_calling_code = country_code_for_region(region_code)
main_co... | 0.001575 |
def write(self, data):
"""Write data into the device input buffer.
:param data: single element byte
:type data: bytes
"""
logger.debug('Writing into device input buffer: %r' % data)
if not isinstance(data, bytes):
raise TypeError('data must be an instance of ... | 0.002425 |
def _get_3d_plot(self, label_stable=True):
"""
Shows the plot using pylab. Usually I won"t do imports in methods,
but since plotting is a fairly expensive library to load and not all
machines have matplotlib installed, I have done it this way.
"""
import matplotlib.pyplo... | 0.001427 |
def fetchall(self):
"""
As in DBAPI2.0 (except the fact rows are not tuples but
lists so if you try to modify them, you will succeed instead of
the correct behavior that would be that an exception would have
been raised)
Additionally every row returned by this class is ad... | 0.003529 |
def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
assert q_values.ndim == 1
nb_actions = q_values.shape[0]
if n... | 0.004158 |
def get_details(self):
""" The function called to get the details appended to the help message when self.append_details is True """
strval = str(self.wrong_value)
if len(strval) > self.__max_str_length_displayed__:
return '(Actual value is too big to be printed in this message)'
... | 0.007634 |
def get_user_by_id(bridge_id, include_course_summary=True):
"""
:param bridge_id: integer
Return a list of BridgeUsers objects with custom fields
"""
url = author_id_url(bridge_id) + "?%s" % CUSTOM_FIELD
if include_course_summary:
url = "%s&%s" % (url, COURSE_SUMMARY)
resp = get_reso... | 0.002703 |
def make_default(self, user, group_membership):
"""
Set the passed GroupMembership as default for the specified user.
:param user: User object or id
:param group_membership: GroupMembership object or id
"""
return self._put(self._build_url(self.endpoint.make_default(user... | 0.008499 |
def lookupEnvVar(name, envName, defaultValue):
"""
Use this for looking up environment variables that control Toil and are important enough to
log the result of that lookup.
:param str name: the human readable name of the variable
:param str envName: the name of the environment variable to lookup
... | 0.006289 |
def from_points(cls, lons, lats, depths=None, sitemodel=None,
req_site_params=()):
"""
Build the site collection from
:param lons:
a sequence of longitudes
:param lats:
a sequence of latitudes
:param depths:
a sequence of d... | 0.001396 |
def multi_process(func, data, num_process=None, verbose=True, **args):
'''Function to use multiprocessing to process pandas Dataframe.
This function applies a function on each row of the input DataFrame by
multiprocessing.
Args:
func (function): The function to apply on each row of the input
... | 0.000408 |
def remove_task_db(self, fs_id):
'''将任务从数据库中删除'''
sql = 'DELETE FROM tasks WHERE fsid=?'
self.cursor.execute(sql, [fs_id, ])
self.check_commit() | 0.011364 |
def harea_stack(self, stackers, **kw):
''' Generate multiple ``HArea`` renderers for levels stacked left
to right.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``x1`` and ``x2`` harea coordinates.
Additional... | 0.003133 |
def cli_form(self, *args):
"""Display a schemata's form definition"""
if args[0] == '*':
for schema in schemastore:
self.log(schema, ':', schemastore[schema]['form'], pretty=True)
else:
self.log(schemastore[args[0]]['form'], pretty=True) | 0.006623 |
def get_variable_initializer(hparams):
"""Get variable initializer from hparams."""
if not hparams.initializer:
return None
mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN,
value=hparams.initializer_gain,
hparams=hparams)
... | 0.009244 |
def inferObjectsWithRandomMovements(self, objectPlacements, maxTouches=20,
settlingTime=2):
"""
Infer each object without any location input.
"""
for monitor in self.monitors.values():
monitor.afterPlaceObjects(objectPlacements)
for objectName, objectDic... | 0.007847 |
def connected(self, node_id):
"""Return True iff the node_id is connected."""
conn = self._conns.get(node_id)
if conn is None:
return False
return conn.connected() | 0.009662 |
def is_series(obj):
"""
Returns True if the given object is a Pandas Series.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas Series.
"""
try:
# This is the best method of type checking
from pandas import Series
return isinsta... | 0.002151 |
def cli(self):
""" Makes the interface or refreshes it """
if self._cli is None:
self._cli = self.create_interface()
return self._cli | 0.011834 |
def find_amplitude(chunk):
"""
Calculate the 0-1 amplitude of an ndarray chunk of audio samples.
Samples in the ndarray chunk are signed int16 values oscillating
anywhere between -32768 and 32767. Find the amplitude between 0 and 1
by summing the absolute values of the minimum and maximum, and divi... | 0.001529 |
def get_thumbprint(self):
"""
Calculates the current thumbprint of the item being tracked.
"""
d = {}
if self.names:
names = self.names
else:
names = list(self.satchel.lenv)
for name in self.names:
d[name] = deepcopy(self.satche... | 0.005731 |
def read(self, count=None, block=None, last_id=None):
"""
Monitor the stream for new messages within the context of the parent
:py:class:`ConsumerGroup`.
:param int count: limit number of messages returned
:param int block: milliseconds to block, 0 for indefinitely.
:par... | 0.002692 |
def summary(self, title, sentences=0, chars=0, auto_suggest=True, redirect=True):
""" Get the summary for the title in question
Args:
title (str): Page title to summarize
sentences (int): Number of sentences to return in summary
chars (int): Number of... | 0.00432 |
def getDescriptor(self, dir):
"""
Detects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory
"""
try:
return self.getProjectDescriptor(dir)
except:
try:
return self.getPluginDescriptor(dir)
except:
raise UnrealManagerException('could not detect an ... | 0.042105 |
def move(self, source_path, destination_path):
"""
Rename/move an object from one GCS location to another.
"""
self.copy(source_path, destination_path)
self.remove(source_path) | 0.009259 |
def verify_service(self, service_id, specification=None, description=None, agent_mapping=None):
'''
verify_service(self, service_id, specification=None, description=None, agent_mapping=None)
| Verifies validity of service yaml
:Parameters:
* *service_id* (`string`) -- Identifie... | 0.008166 |
def add_comment(self, table, column, comment):
"""Add a comment to an existing column in a table."""
col_def = self.get_column_definition(table, column)
query = "ALTER TABLE {0} MODIFY COLUMN {1} {2} COMMENT '{3}'".format(table, column, col_def, comment)
self.execute(query)
self.... | 0.007576 |
def quantile_normalize(matrix, inplace=False, target=None):
"""Quantile normalization, allowing for missing values (NaN).
In case of nan values, this implementation will calculate evenly
distributed quantiles and fill in the missing data with those values.
Quantile normalization is then performed on th... | 0.001193 |
def get_dedicated_package(self, ha_enabled=False):
"""Retrieves the dedicated firewall package.
:param bool ha_enabled: True if HA is to be enabled on the firewall
False for No HA
:returns: A dictionary containing the dedicated virtual server firewall
... | 0.002604 |
def load_base_files(self):
"""
At startup we copy base file to the user location to allow
them to customize it
"""
dst_path = self.configs_path()
src_path = get_resource('configs')
try:
for file in os.listdir(src_path):
if not os.path.e... | 0.006135 |
def request(self, message, timeout=False, *args, **kwargs):
"""Populate connection pool, send message, return BytesIO, and cleanup"""
if not self.connection_pool.full():
self.connection_pool.put(self._register_socket())
_socket = self.connection_pool.get()
# setting timeout... | 0.004601 |
def _Close(self):
"""Closes the file system object.
Raises:
IOError: if the close failed.
"""
self._vslvm_volume_group = None
self._vslvm_handle.close()
self._vslvm_handle = None
self._file_object.close()
self._file_object = None | 0.003717 |
def tilt_model(params, shape):
"""lmfit tilt model"""
mx = params["mx"].value
my = params["my"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0]) - bg.shape[0] // 2
y = np.arange(bg.shape[1]) - bg.shape[1] // 2
x = x.reshape(-1, 1)
y =... | 0.002653 |
def stdev(requestContext, seriesList, points, windowTolerance=0.1):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draw the Standard Deviation of all metrics passed for the past N
datapoints. If the ratio of null points in the window is greater than
windowTolerance, skip the... | 0.000359 |
def emit(self, record):
"""
Handle the given record, this is the entry point from the python
logging facility
Params:
record (logging.LogRecord): log record to handle
Returns:
None
"""
record.task = self.cur_task
if record.leveln... | 0.001485 |
def increment(cls, v):
"""Increment the version number of an object number of object number string"""
if not isinstance(v, ObjectNumber):
v = ObjectNumber.parse(v)
return v.rev(v.revision+1) | 0.013216 |
def __GetChunk(self, start, end, additional_headers=None):
"""Retrieve a chunk, and return the full response."""
self.EnsureInitialized()
request = http_wrapper.Request(url=self.url)
self.__SetRangeHeader(request, start, end=end)
if additional_headers is not None:
req... | 0.003968 |
def get_comment_init(request, obj):
"""
Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return:
"""
if request.user.is_authenticated():
init = {'obj': obj, 'username': request.use... | 0.004831 |
def dbmin50years(self, value=None):
""" Corresponds to IDD Field `dbmin50years`
50-year return period values for minimum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmin50years`
Unit: C
if `value` is None it will not be ch... | 0.002548 |
def pat(p):
"""Given a string `p` with feature matrices (features grouped with square
brackets into segments, return a list of sets of (value, feature) tuples.
Args:
p (str): list of feature matrices as strings
Return:
list: list of sets of (value, feature) tuples
"""
pattern =... | 0.001972 |
async def send_message(self, message, **kwargs):
"""Coroutine to send message to the client.
If server sends UNARY response, then you should call this coroutine only
once. If server sends STREAM response, then you can call this coroutine
as many times as you need.
:param messag... | 0.002519 |
def exec_cmd(self, command, **kwargs):
"""Wrapper method that can be changed in the inheriting classes."""
self._is_allowed_command(command)
self._check_command_parameters(**kwargs)
return self._exec_cmd(command, **kwargs) | 0.007874 |
def read_length_adjust(self, analysistype):
"""
Trim the reads to the correct length using reformat.sh
:param analysistype: current analysis type. Will be either 'simulated' or 'sampled'
"""
logging.info('Trimming {at} reads'.format(at=analysistype))
for sample in self.me... | 0.004979 |
def tritonast2arybo(e, use_exprs=True, use_esf=False, context=None):
''' Convert a subset of Triton's AST into Arybo's representation
Args:
e: Triton AST
use_esf: use ESFs when creating the final expression
context: dictionnary that associates Triton expression ID to arybo expressions
... | 0.016208 |
def apply(
self,
docs=None,
split=0,
train=False,
clear=True,
parallelism=None,
progress_bar=True,
):
"""Apply features to the specified candidates.
:param docs: If provided, apply features to all the candidates in these
documents.... | 0.00142 |
def scope_lookup(self, node, name, offset=0):
"""Lookup where the given names is assigned.
:param node: The node to look for assignments up to.
Any assignments after the given node are ignored.
:type node: NodeNG
:param name: The name to find assignments for.
:type ... | 0.00153 |
def get_context_data(self, **kwargs):
"""Tests cookies.
"""
self.request.session.set_test_cookie()
if not self.request.session.test_cookie_worked():
messages.add_message(
self.request, messages.ERROR, "Please enable cookies.")
self.request.session.dele... | 0.005181 |
def set_canvas_properties(self, canvas, x_title=None, y_title=None, x_lim=None, y_lim=None, x_labels=True, y_labels=True):
"""!
@brief Set properties for specified canvas.
@param[in] canvas (uint): Index of canvas whose properties should changed.
@param[in] x_title (string): Title ... | 0.011236 |
def flow_rate(vol_per_rev, rpm):
"""Return the flow rate from a pump given the volume of fluid pumped per
revolution and the desired pump speed.
:param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:param rpm: Desired pump speed in revolu... | 0.002841 |
def reverse_sequences(records):
"""
Reverse the order of sites in sequences.
"""
logging.info('Applying _reverse_sequences generator: '
'reversing the order of sites in sequences.')
for record in records:
rev_record = SeqRecord(record.seq[::-1], id=record.id,
... | 0.001898 |
def format_size(size, threshold=1536):
"""Return file size as string from byte size.
>>> format_size(1234)
'1234 B'
>>> format_size(12345678901)
'11.50 GiB'
"""
if size < threshold:
return "%i B" % size
for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
size /= 1024.0
... | 0.002427 |
def multi_curve_fit(xs, ys, verbose):
"""
fit multiple functions to the x, y data, return the best fit
"""
#functions = {exponential: p0_exponential, reciprocal: p0_reciprocal, single_reciprocal: p0_single_reciprocal}
functions = {
exponential: p0_exponential,
reciprocal: p0_reciproc... | 0.004304 |
def update_settings(self, settings):
"""Update the settings
If a derived class has an ALLOWED_SETTINGS dict, we check here that
incoming settings from the web app are allowed, and set the child
properties as appropriate.
"""
def error_string(setting, setting_val):
... | 0.003265 |
def total_reads_from_grabix(in_file):
"""Retrieve total reads in a fastq file from grabix index.
"""
gbi_file = _get_grabix_index(in_file)
if gbi_file:
with open(gbi_file) as in_handle:
next(in_handle) # throw away
num_lines = int(next(in_handle).strip())
assert ... | 0.002309 |
def get_options_dict(self):
"""Return options from synchronizer (possibly overridden by own extra_opts)."""
d = self.synchronizer.options if self.synchronizer else {}
d.update(self.extra_opts)
return d | 0.012876 |
def get_port_channel_detail_output_lacp_partner_oper_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel... | 0.003205 |
def _logpdf(self, **kwargs):
"""Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored.
"""
if kwargs not in self:
return -numpy.inf
return self._lognorm + \
... | 0.004739 |
def copy(self):
"""
Returns a copy of the model.
Returns
-------
BayesianModel: Copy of the model on which the method was called.
Examples
--------
>>> from pgmpy.models import BayesianModel
>>> from pgmpy.factors.discrete import TabularCPD
... | 0.001381 |
def notifications_get(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /notifications/get API method.
"""
return DXHTTPRequest('/notifications/get', input_params, always_retry=always_retry, **kwargs) | 0.008734 |
def run_evaluate(self) -> None:
"""
Overrides the base evaluation to set the value to the evaluation result of the value
expression in the schema
"""
result = None
self.eval_error = False
if self._needs_evaluation:
result = self._schema.value.evaluate(... | 0.004501 |
def matchremove_verb_endings(word):
"""Remove the verb endings"""
"""verb endings sorted by charlen then alph"""
verb_endings =['issiiens', 'isseient', 'issiiez', 'issons', 'issent', 'issant', 'isseie', 'isseit', 'issons',
'isseiz', 'assent', 'issons', 'isseiz', 'issent', 'iiens', 'eient'... | 0.007429 |
def add_route(self, method, path, handler,
*, name=None, expect_handler=None,
swagger_data=None,
validate=None):
""" Returns route
:param method: as well as in aiohttp
:param path: as well as in aiohttp
:param handler: as well as in ... | 0.004382 |
def prompt(self):
"""Returns the UTF-8 encoded prompt string."""
if self.prompt_string is not None:
return self.prompt_string
if not self.color_enabled:
return (' '.join(self.command) + '>> ').encode('utf8')
color = '34'
sub_color = '37'
prompt_... | 0.003509 |
def rm_fstab(name, device, config='/etc/fstab'):
'''
.. versionchanged:: 2016.3.2
Remove the mount point from the fstab
CLI Example:
.. code-block:: bash
salt '*' mount.rm_fstab /mnt/foo /dev/sdg
'''
modified = False
if __grains__['kernel'] == 'SunOS':
criteria = _vf... | 0.000652 |
def get(self):
"""
Get a JSON-ready representation of this Personalization.
:returns: This Personalization, ready for use in a request body.
:rtype: dict
"""
personalization = {}
for key in ['tos', 'ccs', 'bccs']:
value = getattr(self, key)
... | 0.002294 |
def find(self, item, description='', event_type=''):
"""
Find regexp in activitylog
find record as if type are in description.
"""
# TODO: should be refactored, dumb logic
if ': ' in item:
splited = item.split(': ', 1)
if splited[0] in self.TYPES:
... | 0.004677 |
def from_api_repr(cls, resource):
"""Factory: construct instance from resource.
:type resource: dict
:param resource: mapping as returned from API call.
:rtype: :class:`LifecycleRuleDelete`
:returns: Instance created from resource.
"""
action = resource["action... | 0.004525 |
def get_node_selectable(node, context):
"""Return the Selectable Union[Table, CTE] associated with the node."""
query_path = node.query_path
if query_path not in context.query_path_to_selectable:
raise AssertionError(
u'Unable to find selectable for query path {} with context {}.'.format... | 0.004515 |
def whitelisted(argument=None):
"""Decorates a method requiring that the requesting IP address is
whitelisted. Requires a whitelist value as a list in the
Application.settings dictionary. IP addresses can be an individual IP
address or a subnet.
Examples:
['10.0.0.0/8','192.168.1.0/24', '1.... | 0.000603 |
def collapse_focussed(self):
"""
Collapse currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.collapse(focuspos)
self._walker.clear_cache(... | 0.005747 |
def get_edge_schema_element_or_raise(self, edge_classname):
"""Return the schema element with the given name, asserting that it's of edge type."""
schema_element = self.get_element_by_class_name_or_raise(edge_classname)
if not schema_element.is_edge:
raise InvalidClassError(u'Non-ed... | 0.012594 |
def restore(self, name, filename):
"""
Loads state of a backup file to a database.
Note
----
If database name does not exist, it will be created.
Parameters
----------
name: str
the database to which backup will be restored.
filename:... | 0.00438 |
def update_chars(self):
"""Update the current charters in the tokenizer."""
# NOTE: We spoof non-Unix files by returning '\n' on StopIteration
self.prior_char, self.char = self.char, next(self.characters, '\n')
self.idx += 1 | 0.007813 |
def _get_phi(self, C, mag):
"""
Returns the magnitude dependent intra-event standard deviation (phi)
(equation 15)
"""
if mag < 5.5:
return C["phi1"]
elif mag < 5.75:
return C["phi1"] + (C["phi2"] - C["phi1"]) * ((mag - 5.5) / 0.25)
else:
... | 0.005764 |
def _prime_install_map(self):
"""Fetch all installations and look up the ID for each."""
url = "{}/app/installations".format(self.api_url)
headers = self._get_app_auth_headers()
LOGGER.debug("Fetching installations for GitHub app")
response = requests.get(url, headers=headers)
... | 0.00241 |
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the dmidecode output. All data is parsed into a dictionary."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(cmd, return_val)
output = iter(stdout.decode("utf-8").splitline... | 0.005932 |
def update(self, duration):
"""Add a recorded duration."""
if duration >= 0:
self.histogram.update(duration)
self.meter.mark() | 0.012048 |
def get_albums(self):
"""
Retrieves all the albums by the artist
:return: List. Albums published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['album'])[1:] | 0.012766 |
def main_decrypt(A):
"Get all local keys OR prompt user for key, then attempt to decrypt with each."
profile = get_profile(A)
localKeys = profile.get('local keys', [])
if not localKeys:
localKeys = [make_lock_securely(warn_only = A.ignore_entropy)]
else:
localKeys = [crypto.UserLock.... | 0.008197 |
def confusion_performance(mat, fn):
"""Apply a performance function to a confusion matrix
:param mat: confusion matrix
:type mat: square matrix
:param function fn: performance function
"""
if mat.shape[0] != mat.shape[1] or mat.shape < (2, 2):
raise TypeError('{} is not a confusion ... | 0.002548 |
def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None):
"""Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weig... | 0.004155 |
def rollbackBlockUser(self, userId, chatroomId):
"""
移除封禁聊天室成员方法 方法
@param userId:用户 Id。(必传)
@param chatroomId:聊天室 Id。(必传)
@return code:返回码,200 为正常。
@return errorMessage:错误信息。
"""
desc = {
"name": "CodeSuccessReslut",
"desc": " h... | 0.009029 |
def randomfill(a):
"""Fill masked areas with random noise
This is needed for any fft-based operations
"""
a = checkma(a)
#For data that have already been normalized,
#This provides a proper normal distribution with mean=0 and std=1
#a = (a - a.mean()) / a.std()
#noise = a.mask * (np... | 0.014894 |
def select_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Select function takes a row as a list and a column name and returns the date in that column.
"""
dates: List[Date] = []
for row in rows:
cell_value = row.values[column.name]
if isinsta... | 0.006834 |
def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
context['top_level_forum'] = self.top_level_forum
context['top_level_forum_url'] = self.get_top_level_forum_url()
return context | 0.00641 |
def valid_header_waiting(self):
"""
Check if a valid header is waiting in buffer
"""
if len(self.buffer) < 4:
self.logger.debug("Buffer does not yet contain full header")
result = False
else:
result = True
result = result and self.b... | 0.003488 |
def get_geocode(city, state, street_address="", zipcode=""):
"""
For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)... | 0.005714 |
def make_quaternion(theta, *axis):
'''Given an angle and an axis, create a quaternion.'''
x, y, z = axis
r = np.sqrt(x * x + y * y + z * z)
st = np.sin(theta / 2.)
ct = np.cos(theta / 2.)
return [x * st / r, y * st / r, z * st / r, ct] | 0.003861 |
def update_volume(self, volumeID, metadata):
'''update existing volume metadata
the given metadata will substitute the old one
'''
log.debug('updating volume metadata: {}'.format(volumeID))
rawVolume = self._req_raw_volume(volumeID)
normalized = self.normalize_volume(r... | 0.004115 |
def applet_list_projects(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
"""
return DXHTTPRequest('/%s/listProjec... | 0.010336 |
def parse_jellyfish_data(self, f):
""" Go through the hist file and memorise it """
histogram = {}
occurence = 0
for line in f['f']:
line = line.rstrip('\n')
occurence = int(line.split(" ")[0])
count = int(line.split(" ")[1])
histogram[occu... | 0.007901 |
def read_backup_keys(self, recovery_key=False):
"""Retrieve the backup copy of PGP-encrypted unseal keys.
The returned value is the nonce of the rekey operation and a map of PGP key fingerprint to hex-encoded
PGP-encrypted key.
Supported methods:
PUT: /sys/rekey/backup. Pro... | 0.00454 |
def is_invalid_params(func, *args, **kwargs):
"""
Method:
Validate pre-defined criteria, if any is True - function is invalid
0. func should be callable
1. kwargs should not have unexpected keywords
2. remove kwargs.keys from func.parameters
3. number of args should be <=... | 0.000905 |
def _execute_single_level_task(self):
""" Execute a single-level task """
self.log(u"Executing single level task...")
try:
# load audio file, extract MFCCs from real wave, clear audio file
self._step_begin(u"extract MFCC real wave")
real_wave_mfcc = self._extr... | 0.002513 |
def initWithEventUriWgtList(uriWgtList):
"""
Set a custom list of event uris. The results will be then computed on this list - no query will be done (all conditions will be ignored).
"""
q = QueryEvents()
assert isinstance(uriWgtList, list), "uriWgtList has to be a list of string... | 0.014737 |
def get(self, sid):
"""
Constructs a BuildContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.build.BuildContext
:rtype: twilio.rest.serverless.v1.service.build.BuildContext
"""
return BuildContext(self._version, service_sid=self._solution['s... | 0.008721 |
def _commonParent(zi1, zi2):
"""
Locate the common parent of two Interface objects.
@param zi1: a zope Interface object.
@param zi2: another Interface object.
@return: the rightmost common parent of the two provided Interface objects,
or None, if they have no common parent other than Interfac... | 0.00161 |
def get_fernet():
"""
Deferred load of Fernet key.
This function could fail either because Cryptography is not installed
or because the Fernet key is invalid.
:return: Fernet object
:raises: airflow.exceptions.AirflowException if there's a problem trying to load Fernet
"""
global _fern... | 0.001475 |
def create_signature(self, base_url, payload=None):
"""
Creates unique signature for request.
Make sure ALL 'GET' and 'POST' data is already included before
creating the signature or receiver won't be able to re-create it.
:param base_url:
The url you'll using for yo... | 0.004762 |
def extract_users(self):
""" extract user info """
email_set = set()
users_dict = {}
self.verbose('going to extract user information from retrieved nodes...')
for node in self.old_nodes:
email_set.add(node.email)
if node.email not in users_dict:
... | 0.005484 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.