content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_func_decl(a):
"""Return `True` if `a` is an SMT function declaration.
>>> f = Function('f', IntSort(), IntSort())
>>> is_func_decl(f)
True
>>> x = Real('x')
>>> is_func_decl(x)
False
"""
return isinstance(a, FuncDeclRef) | 11c886078509bdf3c841c82909cc69f4fd063b73 | 57,400 |
def get_instance(ec2_conn, ids=None, tags=None, hostnames=None, state=None):
"""Get single instance matching criteria.
If more than one image match, raise exception NonUniqueError.
"""
instances = list_instances(
ec2_conn, ids=ids, tags=tags, hostnames=hostnames, state=state
)
if not i... | 0cd7f43c75b622bc6eaa53819b6388a93ec5985b | 57,401 |
def MakeKiteFromOverride(override, aero_devices=None):
"""Makes a kite config from override dict.
Args:
override: Dict of overrides to define a kite config.
Returns:
Dict of kite config.
"""
kite = {}
# Setup aero device
# Pick from the dict of provided aero devices - if not provided, make a d... | 60845894c49e159df3b1eaf6502b7818c772f5d4 | 57,402 |
def _createLeafletNodes(mapObject=None, nodes=None, iconPrefix=None, iconType=None, iconColor=None, iconText=None):
"""
A sub-function to create leaflet nodes
Parameters
----------
mapObject: Folium object, Required
Add content to a folium map.
nodes: :ref:`Nodes`, Required
The Nodes dataframe to be generate... | c50f81da11ef998e5502b9edf0355eacc78268d1 | 57,403 |
def doc_param_dict_format(member_list) :
"""
member_list : list of the node of the members of a struct
returns the rst table
"""
member_list2 = treat_member_list(member_list)
h= ['Parameter Name', 'Type', 'Default', 'Documentation']
n_lmax = max(len(h[0]), max(len(m.spelling) for m in... | 68f489a57635b465238a981f3f01c532128b0ea1 | 57,404 |
def get_star_mag(df):
"""Solely for use with star truth catalogs. Computes and creates a list of magnitudes of form '(mag_g, mag_r, mag_i, mag_z)'.
Args:
df (pandas DataFram)
Returns:
m_griz (list of str) -- Stores magnitudes of each filter in form '(mag_g, mag_r, mag_i, mag_z)'.
"""
m_g = df['g_Corr_1']
m... | b78e873a8a0b9d83a06a124895f6c66899ffe938 | 57,405 |
def servers_delete(request, pk):
"""Delete an server"""
object = get_object_or_404(Server, pk=pk)
object.delete()
messages.success(request, 'Server has been deleted.')
return redirect(reverse('servers.views.servers_list', args=())) | aede4939b7d91261f225997502f2a75b206d9147 | 57,406 |
from typing import Callable
def __manage_undefined_ratios(func: Callable):
""" Wraps ratio functions to return NaN values instead of 0.0 in cases
where the ratio is undefined
"""
def wrapper(*args, **kwargs):
funcname = getattr(func, "__name__", "an unknown function")
msg = (
... | ae9f4a014acac2920bc18e852ea8dd28e988cd0d | 57,407 |
def to_one(dest_class, type=RelationType.DIRECT, resource_classes=None,
reverse=None, reverse_type=RelationType.DIRECT,
writable=False):
"""Create a one to one relation to a given target :class:`Resource`.
Args:
dest_class(Resource): The *target* class for the relationship
K... | d38fb795692d3b971853b0fb1c077b6a77f58f08 | 57,408 |
def get_unit_status(code):
"""Get on/off status for given unit."""
unit = int(code[1])
return get_status()[16 - int(unit)] == '1' | aa853535a384ac6d369da4f0a4fa792ebd569c42 | 57,409 |
def is_on(S, j):
"""
Returns 1 if and only if the `j`-th item of the set `S` is on.
Examples
========
Check if the 3-th and then 2-nd item of the set is on:
>>> S = 0b101010
>>> is_on(S, 3), is_on(S, 2)
(1, 0)
"""
return (S & (1 << j)) >> j | 76034f083372ee2cbe0c711e3a09daf26634550a | 57,410 |
def init_infected_symptomatic_70():
"""
Real Name: b'init Infected symptomatic 70'
Original Eqn: b'0'
Units: b'person'
Limits: (None, None)
Type: constant
b''
"""
return 0 | 40ff15eba496f9448055f7aa73468d3c5063b264 | 57,411 |
import argparse
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""Remove duplicate loci from a fasta given self-to-self lastz"""
)
parser.add_argument(
"--fasta",
required=True,
action=FullPaths,
help="""The fasta file... | f43d652d8e9dc365db38fbeb7f9437f807887be9 | 57,412 |
import os
def convert_ideal(ideal_path, output_filename, format='HDF'):
"""
Parameters
----------
ideal_path : str
The root path of the ideal low_freq dataset.
output_filename : str
The destination filename (including path and suffix).
format : str
format of output. Eit... | 9670430e2289c7e001a2f781826c1cf38a5ace16 | 57,413 |
import argparse
def prune_defaults(params, keep_params={}):
"""Removes parameters that are not in keep_params or in get_defaults
Args:
params (argparse.Namespace): Raw parsed arguments.
keep_params (list): List of parameters to keep
Returns:
new_dict (dict): Pruned argument dict... | 46ad5d666f4cb54d6d69ce507dd5a75e97f915e4 | 57,414 |
def fetch_val_for_key(key, delete_key=False):
"""Return the overriding config value for a key.
A successful search returns a string value.
An unsuccessful search raises a KeyError
The (decreasing) priority order is:
- THEANO_FLAGS
- ~./theanorc
"""
# first try to find it in the FLAGS
... | 3b0a10bbab0c1fef2d824267bf6b88beb22d6c58 | 57,415 |
def NEXUSEnvironmentProperties(
allCleanData, propertiesData, env, masking=(True, True, True), VERBOSE=True
):
"""Creates a properties file on the initial data grid for the given environment."""
funcName = "NEXUSEnvironmentProperties"
envList = ["fila", "wall", 3, 2]
if env not in envList:
t... | 8731b31da27bb40764ceb6d89b7ca04439022a7f | 57,416 |
def _get_pil_image_dimensions(pil_image):
"""Gets the dimensions of the Pillow Image.
Args:
pil_image: Image. A file in the Pillow Image format.
Returns:
tuple(int, int). Returns height and width of the image.
"""
width, height = pil_image.size
return height, width | d191ae705df97b1729be2dd03e9a5ff4ddcb4518 | 57,417 |
def loadNeutral(filename):
"""Reads a `Neutral` tetrahedral file format. Return an ``Mesh`` object."""
f = open(filename, "r")
lines = f.readlines()
f.close()
ncoords = int(lines[0])
coords = []
for i in range(1, ncoords + 1):
x, y, z = lines[i].split()
coords.append([float(... | 05be95d839d643c3570161a5b7839a92be9ef8c8 | 57,418 |
import heapq
def solve(n, times):
"""
小根堆/优先队列
"""
if n == 0:
return 0
heap = []
heapq.heappush(heap, times[0][1])
for time in times[1:]:
if time[0] >= heap[0]:
# 不需要新的客服
heapq.heappop(heap)
heapq.heappush(heap, time[1])
print(heap)
r... | 064d582ef76dcae4e69b2c037d3fae07fde3b143 | 57,419 |
from typing import List
def find_subgraphs_matching_pattern(graph: nx.DiGraph, pattern_graph: GraphPattern) -> List[List[str]]:
"""
Find a list of subgraphs for the particular graph that match the pattern expression.
:param graph: The model graph.
:param pattern_graph: A graph consists of patterns for... | 144672921ef37065ba46ed4438cd977b295544d6 | 57,420 |
def trace_stats_by_qu_sess(sessions, analyspar, stimpar, n_quints=4,
qu_idx="all", byroi=True, bysurp=False, integ=False,
ret_arr=False, nan_empty=False, lock="no",
baseline=None, sample_reg=False, datatype="roi"):
"""
trace_sta... | 40962074899a8dfd27181cff1bd278b8f6156741 | 57,421 |
def wrap_list(item):
"""
Returns an object as a list.
If the object is a list, it is returned directly. If it is a tuple or set, it
is returned as a list. If it is another object, it is wrapped in a list and
returned.
"""
if item is None:
return []
elif isinstance(item, list):
... | 6b2af543af39058f7df28e7d89dbb9231cf2b247 | 57,422 |
from typing import Union
import zlib
def zlib_compress(data: Union[bytes, str]) -> bytes:
"""
Compress things in a py2/3 safe fashion
>>> json_str = '{"test": 1}'
>>> blob = zlib_compress(json_str)
"""
if isinstance(data, str):
return zlib.compress(bytes(data, "utf-8"))
return zlib... | 0e7eaf018873ce335b06c4ca4857f9bf8b58864b | 57,423 |
import functools
import logging
def logdec(func):
"""A logging decorator wrapping a function with a standard logging mechanism.
This decorator wraps a function with a standard logging mechanism, providing the following functionalities:
* Logs the calling of the function and the parameters passed to it wh... | fd1ddf475f17758c09d3f44492a8b2ff66cf38de | 57,424 |
from typing import Any
from typing import Dict
from contextlib import suppress
def dictify(value: Any) -> Dict:
"""Ensure value is a dictionary."""
with suppress(AttributeError):
return {k: dictify(v) for k, v in value.items()}
if isinstance(value, str):
return value # type: ignore
... | 30a265fa37a634a8923a554cd89e219b8838a503 | 57,425 |
def crgrow(crarr, grad=3):
"""If a cosmic ray has been identified in the source, delete the pixels around
it according to gradius.
"""
darr=np.where(crarr>0)
xlen=len(crarr[0])
ylen=len(crarr)
#set it up as a box
if grad < 3: grad=3
mbox=int(grad/2)
for i in range(len(darr[0])):
... | 52d7b27bdefec3e06e12fe4c553793d6dd0f1d5e | 57,426 |
def sdbm_hash(name):
"""Calculate SDBM hash over a string."""
ret = 0
for ii in name:
ret = ret * 65599 + ord(ii)
return hex(int(ret & 0xFFFFFFFF)) | 07eb20e27fda5d7a228bc196a55f4ebbefe7c1c1 | 57,427 |
def _get_test_protocol_factory() -> IProtocolFactory:
"""Get a protocol Factory which will build an HTTPChannel
Returns:
interfaces.IProtocolFactory
"""
server_factory = Factory.forProtocol(HTTPChannel)
# Request.finish expects the factory to have a 'log' method.
server_factory.log = _... | e1b69a4eb4cd5becea640fcdff13a3b6eaba9e0a | 57,428 |
def compose_report():
"""
Compose rota report.
:return: A composed submission.
:rtype: html
"""
form = ReportForm()
if form.validate_on_submit():
flash('Report created')
return redirect(url_for('report.view_report'))
return render_template('compose_report.html', title='C... | 99e4e8a8606b1fce232da82e3aea845907a736c4 | 57,429 |
import typing
def score_by_sbs(
sentence_words: StringList,
top_kws: typing.Sequence[ScoredKeyword],
top_kw_words: StringList) -> float:
"""Score sentence (`words`) by summation
Arguments:
sentence_words {StringList} --
sequential list of words in sentence
... | 399d8503eb64bc18e038a88ae718b3879e315894 | 57,430 |
def worker_3d(vals):
"""
same as 2d version of this worker
:param vals: tuple wrapper for (propability, samples, lattice_size,)
:return: number of times percolation did occur in lattice
"""
v = vals[0]
su_rate = 0
for i in range(v[1]):
lat = lattice_gen_3D(v[2], v[2], v[2], v[0]... | d09ed4343c116e236ae86bd24c32a5fb7a6da7a5 | 57,431 |
def get_E(G, mi, xi, vi, mj, xj, vj, xp, vp, mp):
""" Returns the energy of mp and (mi,mj) combined """
m_in = mi + mj
cms_in = (mi * xi + mj * xj) / m_in
v_in = (mi * vi + mj * vj) / m_in
E = 0.5 * (m_in * norm(v_in)**2 + mp * norm(vp)**2) - G * m_in * mp / norm(xp - cms_in)
return E | 6a8d6c71e8d30c4bc874ca8cb41da641ea635ffc | 57,432 |
def mean_average_precision(ranking):
"""
Score is mean average precision. Relevance is binary (nonzero is relevant).
:param ranking: Relevance scores (list or numpy) in rank order (first element is the first item)
:type ranking: list, np.array
:return: Mean average precision
:rtype: float
... | 4c91c09108f4988ebbb6a4c6c4c2070f08e061a9 | 57,433 |
def convert_to_example(image_data, labels, labels_text, bboxes, shape,
difficult, truncated):
"""Build an Example proto for an image example.
Args:
image_data: string, JPEG encoding of RGB image;
labels: list of integers, identifier for the ground truth;
labels_text: li... | 1efb4c04cf552cc46ee29a744b780674d95de589 | 57,434 |
def predict(sample, relations):
"""
Predict entities and interactions of given sample
w.r.t set of known relations.
:param sample: Dict with `id` and `text` as strings
:param relations: Set of relation tuples
:return: Sample augmented with extracted entities and interactions.
"""
text = ... | 44046de044685609cf6252f2f106a60c2ecf5f7a | 57,435 |
def _clone_vdi(session, vdi_to_clone_ref):
"""Clones a VDI and return the new VDIs reference."""
vdi_ref = session.call_xenapi('VDI.clone', vdi_to_clone_ref)
LOG.debug('Cloned VDI %(vdi_ref)s from VDI '
'%(vdi_to_clone_ref)s',
{'vdi_ref': vdi_ref, 'vdi_to_clone_ref': vdi_to_clone... | 307cbc3679c98744c269c8b5c540af6febeefcaa | 57,436 |
def _get_storage_area(storage_area):
"""
:param storage_area: storage area entry in nodes collection.
Either a numpy string or a bytes type
:returns default '--' if the input is an empty string or 0., or the
given input will be converted to a float representation
"""
default_null =... | bd497219d1a0ea6ee5048fabc65431ee14e8dd9c | 57,437 |
import os
def create_app(test_config=None):
"""
:create_app Application factory function which creates another object
i.e. blog, username, and comment.
:param test_config: can be passed to the factory, will use this in testing.
this will seperate itself from any deployment values you have in 'conf... | de7ba4da3d98ac81322c69af2c45a839d2e06088 | 57,438 |
def GetEntityViaMemcache(entity_key):
"""Get entity from memcache if available, from datastore if not."""
entity = memcache.get(entity_key)
if entity is not None:
return entity
key = ndb.Key(urlsafe=entity_key)
entity = key.get()
if entity is not None:
memcache.set(entity_key, entity)
return entit... | 1b760a738fd207ba67039fb499e423b1e84f9ea3 | 57,439 |
def ehvicalc_vec(x, y_par, moboInfo, kriglist, pool=None):
"""Vectorised EHVI Function
Vectorises above EHVI function as much as possible. Currently,
still depends on the vectorisation of prediction.py prediction() and
kadal.optim_tools.ehvi.exi2d.exi2d() for best performance boost.
Args:
... | 429de869279320668db5998530caa71a3831b211 | 57,440 |
def resolve_params(obj, params, default=missing):
"""Given a dictionary of keyword arguments, return the same dictionary except with
values enclosed in `< >` resolved to attributes on `obj`.
"""
param_values = {}
for name, attr_tpl in iteritems(params):
attr_name = tpl(str(attr_tpl))
... | 85b32b7212b3c9451f1c2fcf88e443c6cd9015e1 | 57,441 |
def get_manual_iface(manual_iface, node_class):
""" Returns standardized interface dict based on manual_iface """
iface_dict = {
"node_id": "manual",
"node_uri": None,
"node_name": None,
"node_addr": None,
"node_fqdn": None,
"node_class": node_class,
"ifac... | 070207a1ba399b660147f0d3cb95419347e0344e | 57,442 |
from typing import Tuple
from datetime import datetime
def _zipinfo_date_time_to_timestamp(date_time: Tuple) -> float:
"""Converts a date_time of a ZipInfo object to a unix timestamp.
The timestamp is rounded to seconds because that is the resolution of
date_time.
"""
timestamp = datetime.datetime... | c3b03d7c3324a2ad66957fbf4881bd6863bd912f | 57,443 |
def find_tables(clause, check_columns=False,
include_aliases=False, include_joins=False,
include_selects=False, include_crud=False):
"""locate Table objects within the given expression."""
tables = []
_visitors = {}
if include_selects:
_visitors['select'] = _vis... | 4ba03b28ac66b4717b55c0adcf9a3cc5d4cf8282 | 57,444 |
import pprint
def elastic_search(request):
"""Use Elasticsearch for global search."""
user_input = UserInput(
query=request.GET.get('q'),
type=request.GET.get('type', 'project'),
project=request.GET.get('project'),
version=request.GET.get('version', LATEST),
taxonomy=re... | 1cbe94eb39f8ece14a1a55c524d61dd5de0887b8 | 57,445 |
def pluralize(singular: str) -> str:
"""Return plural form of given lowercase singular word.
Refer to: http://code.activestate.com/recipes/577781-pluralize-word-convert-singular-word-to-its-plural/
>>> pluralize('user')
'users'
"""
if not singular:
return ''
plural = ABERRANT_PLURA... | 97e4e02fb0cd77f0b2812e56262d92296df1729a | 57,446 |
def travel_cost():
"""
Returns the yearly costs of travel, 22£ per week.
:return: The cost of travel.
"""
# There are 52 weeks in a year minus two for Christmas and Summer holidays.
return 22 * 50 | fa51fba03ab3db9deea7f3e075c392d4c8db6cef | 57,447 |
import string
import re
def tokenize_count(s: str) -> int:
"""
Tokenizes the given strings to count the number of words.
:param s:
:return: number of words
"""
s = s.translate(str.maketrans('', '', string.punctuation + "„“–"))
return len(re.split(r'\W+', s)) | c68822f313a2ffcab11edf0c0ce146d758cb8e3f | 57,448 |
def set_idle_override(isUserActive: bool, isScreenUnlocked: bool) -> dict:
"""Overrides the Idle state.
Parameters
----------
isUserActive: bool
Mock isUserActive
isScreenUnlocked: bool
Mock isScreenUnlocked
**Experimental**
"""
return {
"method": "Emula... | 21b51d27edef13f66818d8d72583745e6c3449e9 | 57,449 |
def cr_encode(index):
"""cr: Get a custom value."""
return MessageEncode(f"08cr{index + 1:02}00", "CR") | e24c245ab7bb51cb6b570274657d2726d3faeda4 | 57,450 |
def format_strings(*strings):
"""Take an arbitrary number of strings and format them nicely.
Returns the nicely formatted string.
"""
accum_string = ""
for str in strings:
accum_string = "{0} {1}\n".format(accum_string, str)
return accum_string | 7785cf052ed04ce3185035b0921e98bd0d952449 | 57,451 |
def get_lang_obj(name: str) -> AbstractLanguage:
""" Returns a new language object """
if name.lower() == "abap":
return Abap()
raise Exception("Unknown language: " + name) | 974f6da222a20056d7d71c36af6137c7b9f5ebde | 57,452 |
def plot_spectrum(wavelength, flux, fig=None, scale='log', legend=None, ylabel='Flux Density', xlabel='Wavelength [um]', width=1024, height=500, **kwargs):
"""
Plot a generic spectrum
Parameters
----------
wavelength: array-like
The 1D wavelength array
flux: array-like
The 1D co... | e9ebd77f64b1b18578e619f06ae24ffbc4f1257c | 57,453 |
import sys
import os
def parse_args():
"""Parse the command-line arguments and check if input args are valid.
Returns
-------
args : argparse.Namespace
The namespace containing the arguments
"""
parser = ArgumentParser(
description='''Run SSTMap site-based calculations (Hydrat... | 0241a61664706207d43d7c28ba8307610ab314ea | 57,454 |
def batch_intersection_union(output, target, nclass):
"""mIoU"""
# inputs are numpy array, output 4D, target 3D
mini = 1
maxi = nclass
nbins = nclass
predict = paddle.argmax(output, 1) + 1 # [N,H,W]
target = target.astype('float32') + 1 # [N,H,W]
predict = predict.astype('fl... | 347577626149ef17652080c00c4b44dfaa7023ee | 57,455 |
def calc_mean_std_population(df_merged, discard_file=None):
"""Calculate mean and STD of the traning datasets
"""
A_freq_cols = [col for col in df_merged.columns if 'A' in col]
C_freq_cols = [col for col in df_merged.columns if 'C' in col]
G_freq_cols = [col for col in df_merged.columns if 'G' in co... | 57a94d893234d011f05f08f42f7caef52a018cc0 | 57,456 |
def __preprocessor(text):
"""
Happens before tokenizer.
:param text: text
:return: text
"""
s = text.lower()
s = s.replace('\r', ' ').replace('\n', ' ').strip()
s = strip_punctuation(s)
return s | 1c62f9a9f4db478aa694dc6b90c697fe21b699c1 | 57,457 |
def renameApkPackage(smaliFolder = 'file/decompile/smali', manifest = 'file/decompile/AndroidManifest.xml', newPackageName="com.zzw.noName"):
"""
rename apk package name.
"""
manifest = file_operate.getFullPath(manifest)
ET.register_namespace('android', androidNS)
targetTree = ET.parse(manif... | 15791aeebf6c9c27626f8d0806d8397cb4e8776f | 57,458 |
def estimated_autocorrelation(x):
"""
http://stackoverflow.com/questions/14297012/estimate-autocorrelation-using-python
http://stackoverflow.com/q/14297012/190597
http://en.wikipedia.org/wiki/Autocorrelation#Estimation
"""
result = estimate_unnormalised_autocorrelation(x, x.mean())
variance... | 06744514ccdbcef2fe5ebc962773a0e4da9a345d | 57,459 |
def SceneLightShadowsStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 81899f6c6b7decef9c02aa49c7112ad213537417 | 57,460 |
def get_location_recordings():
"""Retrieve show recordings for all locations"""
return locations.get_location_recordings(database_connection) | 940c88a448e6fa825594c46432cc553edfaf57f9 | 57,461 |
def _get_value(string, context):
"""
determines the true value of an input to a template tag. If the string is
quoted it's interpreted as a string. If not quoted then it's treated as a
variable and looked up against the context.
"""
if _is_quoted_string(string):
return string[1:-1]
r... | 0e0bf209ef24a5304e800db541d1943106636419 | 57,462 |
def modify_packet(packet):
"""
Modifies the DNS Resource Record `packet` ( the answer part)
to map our globally defined `dns_hosts` dictionary.
For instance, whenever we see a google.com answer, this function replaces
the real IP address (172.217.19.142) with fake IP address (192.168.0.6)
"""
... | 9401aeb5fe36b8782797616f7b863cdfe29e2ac0 | 57,463 |
from typing import Union
from typing import Iterable
def pop_path(
doc: Doc,
path: Union[str, Iterable[str]],
default=UNSET,
root: Doc = UNSET,
descend_objects=True,
):
"""
Delete and return the item referenced by json-pointer `path` from the nested `doc` .
:param doc:
the cur... | a9cc9e97f18518ae2f388222d4e739150ba06000 | 57,464 |
def database_get_most_cited( publication_period: int=None, # Limit the considered pubs to only those published in these years
cited_in_period: str='5', #
cite_count: int=0, # Has to be cited more than this number of times, a large nbr speeds the... | e94f7ba7b4dd0d177008998b63fedc6a200394db | 57,465 |
def fitLinReg(x, y):
"""
Fit multiple linear regression model.
x: indep variable / predictors
y: dep variable to predict
"""
rkf = RepeatedKFold(n_splits=10, n_repeats=100, random_state=0)
regressor = LinearRegression()
regressor.fit(x, y)
pred = regressor.predict(x)
cv_results... | d6eadfee1899f8619279ed60dbcde4b80cdab983 | 57,466 |
def process_data(packet, start, msg):
"""
This funcion aims to dissect PacketIn and PacketOut data
It assumes it is
Ethernet [vlan] (BDDP|LLDP|ARP|IP) [TCP|UDP]
Args:
packet: class OFMessage
start: offset
msg:
Returns:
payload: array with all class... | 22dc9b2114cbb37f7b95908e1f566a127135e676 | 57,467 |
def block(inputs,
activation: str = "swish",
drop_rate: float = 0.,
name: str = "",
input_channel: int = 32,
output_channel: int = 16,
kernel_size: int = 3,
strides: int = 1,
expand_ratio: int = 1,
use_se: bool = True,
s... | 02c31a0f3b204b4f9c2a6f5bfdae31fd0f80b72a | 57,468 |
import time
def set_seed(seed=None):
"""Making the seed (for random values) variable if None"""
# Set the seed
if seed is None:
seed = int((time.time() * 10**6) % 4294967295)
try:
np.random.seed(seed)
except Exception as e:
print("!!! WARNING !!!: Seed was not set correct... | ea751bdf0548887dbbeb03f47b48f33a9ba22a41 | 57,469 |
def _get_http_client():
"""Uses project credentials in CLIENT_SECRET_FILE along with requested OAuth2
scopes for authorization, and caches API tokens in TOKEN_STORE_FILE.
"""
store = file.Storage(TOKEN_STORE_FILE)
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_... | 846dc2dfbe31c4a7d84ca267818be655376056db | 57,470 |
def order_target_percent(id_or_ins, percent, style=None):
"""
Place an order to adjust position to a target percent of the portfolio
value, so that your final position value takes the percentage you
defined of your whole portfolio.
position_to_adjust = target_position - current_position
... | 9794c6c6ca6aa5c4f16cd3da89228537b3e518aa | 57,471 |
def rename_candidate_hugo(candidate, renamings):
"""Renames a candidate name according to a renaming map."""
candidate_split = candidate.split("_")
name_expr = candidate_split[0].split(".")
base_name = name_expr[0]
if base_name in renamings:
base_name = renamings[base_name]
name_expr[0] ... | dd0744bb725ddcb3cd6e9e520e32448ad7657495 | 57,472 |
import argparse
def argument_parser():
"""Generates the parser used by the aionasa.epic.__main__ script."""
parser = argparse.ArgumentParser(description=__doc__, usage=usage)
parser.add_argument(
'--date', '-d', type=date_strptime, default=None,
help="Format: YYYY-MM-DD"
)
parser.... | 2bd52ea415ee4c4521e6359939422f65de5e7826 | 57,473 |
def is_explicitly_rooted(path):
"""Return whether a relative path is explicitly rooted relative to the
cwd, rather than starting off immediately with a file or folder name.
It's nice to have paths start with "./" (or "../", "../../", etc.) so, if a
user is that explicit, we still find the path in the s... | bde26849889ac5c951160e441cdd0c3c60871ab1 | 57,474 |
def _description(title=None, exits=(), description=None, components=None):
"""
"""
return language.Description(
title=title, exits=exits, description=description,
components=components) | 27a5d6dc6a6947c156745fee2f93050c90ca140c | 57,475 |
from typing import List
def snip_out(file_str:str, start_key:str)->str:
"""From an anvil.yaml file, snips out only the string you want: the database description."""
good_string:List[str]=[]
save_this_one = False
for line in file_str.split('\n'):
if line.startswith(start_key):
good_... | 8e9ebde180fb5ff6faefcbd92629c75f260ce518 | 57,476 |
def eth_sign_sha3(data: bytes) -> bytes:
"""
eth_sign/recover compatible hasher
Prefixes data with "\x19Ethereum Signed Message:\n<len(data)>"
"""
prefix = b'\x19Ethereum Signed Message:\n'
if not data.startswith(prefix):
data = prefix + b'%d%s' % (len(data), data)
return sha3(data) | d69481f46e0e2ca8ba69eb512f2dfd6ca62b8d7c | 57,477 |
from typing import Any
import requests
def setup_api(
requests_mock: Any,
url_path: str = url_path(),
json_extras: dict = None,
headers_extras: dict = None,
matcher: Any = None,
) -> requests.Response:
"""Utility function for mocking API calls.
Args:
requests_mock: mock object for... | 4f07fd4bc727a754229917768eea09f221bc0a12 | 57,478 |
import platform
def get_terminal_size():
""" getTerminalSize()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
originally retrieved from:
http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
"""
current_os = platform.system... | f6e7d5b9bdbb88b84da615a74a967e96546064c8 | 57,479 |
from typing import Any
from typing import Dict
def validate_long_url(_netid: str, client: ShrunkClient, long_url: str) -> Any:
"""``GET /api/validate_long_url/<b32:long_url>``
Validate a long URL. This endpoint is used for form validation in the frontend. Response format:
.. code-block:: json
{ ... | ae49f477f1e1dcd19ab108b23a5be7b06b818fbe | 57,480 |
def bls_series(series_id, **kwargs):
"""
Authenticated request to the BLS API to fetch timeseries data in JSON
form. You can pass a list of up to 25 series_ids to fetch multiple
series, or you can pass in a single series_id string to do a simple
request. You can also pass in parameters via the kwarg... | f7d5b254d3b296ebc339a4e0c96c54760df9a936 | 57,481 |
def crawl(ob,keys=None,parents=None,capture=None,bubble=None,param=None):
"""
Returns what was passed in as param, after crawling through the target
object's nested structure and firing callbacks at every node in both capture
and bubble directions.
Parameters:
ob
- target dict being crawled through
parents
... | 7b84a94df5907f2f941ea216340fd5e3ef0ef8b3 | 57,482 |
def colour_code_segmentation(image, label_values, array_type):
"""
Given a 1-channel array of class keys, colour code the segmentation results.
# Arguments
image: single channel array where each value represents the class key.
label_values
# Returns
Colour coded image for segmen... | e9a6e9d0bb705cc17e30899126ca3081369f3a99 | 57,483 |
def init_step(idx, cols):
"""Helper function to find init suffix
in a column
Parameters
----------
idx: int
Index of 'init' column in cols.
cols: list[str]
List of column names.
"""
for i in range(idx, len(cols)):
if cols[i] != 'init':
return 'init-' ... | ec056ef39c56ec9dbc534e70105d55aa9bbf7be5 | 57,484 |
def training_base_config(estimator, inputs=None, job_name=None, mini_batch_size=None):
"""Export Airflow base training config from an estimator
Args:
estimator (sagemaker.estimator.EstimatorBase):
The estimator to export training config from. Can be a BYO estimator,
Framework es... | b36b68efeafbf869d8f5de517bc0575492752b94 | 57,485 |
def se_bhmass_mgii_vo09_fwhm(mgii_fwhm, cont_lwav, cont_wav):
"""Calculate the single-epoch virial BH mass based on the MgII FWHM
and monochromatic continuum luminosity at 1350A, 2100A, 3000A, or 5100A.
This relationship is taken from Vestergaard & Osmer 2009, ApJ 641, 689
To determine the FWHM of the... | 9cd1d8a90e30fcbc9fa2b045242a573020aeff70 | 57,486 |
import os
import gzip
def _open_file(in_file):
"""From bcbio code"""
_, ext = os.path.splitext(in_file)
if ext == ".gz":
return gzip.open(in_file, 'rb')
if ext in [".fastq", ".fq"]:
return open(in_file, 'r')
# default to just opening it
return open(in_file, "r") | 0c2ec3c2e6a59c189f86a4f5c1b0adb142b60f15 | 57,487 |
def get_plotly_fig():
"""Dummy Plotly Plot"""
return px.line(data_frame=get_dataframe(), x="quantity", y="price") | befcb64177b799977845bb98343cee0052ec18eb | 57,488 |
def next_nuc(seq, pos, n):
""" Returns the nucleotide that is n places from pos in seq. Skips gap symbols.
"""
i = pos + 1
while i < len(seq):
if seq[i] != '-':
n -= 1
if n == 0: break
i += 1
if i < len(seq) :
return seq[i]
else :
return 'N... | dbe3d204d3399167630cf83c74b0f1742d1c8367 | 57,489 |
def toolchains(request):
""" Return a Toolchains Instance """
res = Toolchains()
request.addfinalizer(res.clean)
return res | b973c31ab74deb5248ad6efe20992166049c96e3 | 57,490 |
def format_node(id, label):
"""
Return the formatted string to represent a node
"""
return NODE_PREFIX + id + label + NODE_SUFFIX | 02d70e31430ad79aff2d900a930e0f9ea0978977 | 57,491 |
def init_app():
"""Initialize the core application."""
app = Flask(__name__, template_folder='.')
app.config['FLASK_ENV'] = 'development'
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = config.SECRET_KEY
app.config['RECAPTCHA_PUBLIC_KEY'] = config.RECAPTCHA_PUBLIC_KEY
app.config['RECAP... | 0fc2244ead0e07c8305df101f5770e1aba074798 | 57,492 |
def Axes_Replace_Split_Axes(fig, axes_remove, split_fraction, direction='vertical'):
"""
Add sevearl new axes in the place of the axes_remove
(the axes which will be replaced by new ones). This could be
used to set break axes.
Parameters
----------
axes_remove: the axes ... | cb6ac4ac6fde65c39989db3c719d6ad366e46227 | 57,493 |
import logging
def _tile_scalar_to_batch_size(tensor_dict, batch_size):
"""Tile scalar tensors in the dictionary to have batch dimension."""
# bool(tf.constant(1).shape) = True.
# this is inconsistent with python default length test. Disable pylint.
scalar_keys = [k for k, v in tensor_dict.items() if len(v.sh... | 3d0281a89358b7c20070498016f928800980c8cf | 57,494 |
def yices_bvconst_minus_one(n):
"""Set all bits to 1.
Error report:
if n = 0
code = POS_INT_REQUIRED
badval = n
if n > YICES_MAX_BVSIZE
code = MAX_BVSIZE_EXCEEDED
badval = n.
"""
# let yices deal with int32_t excesses
if n > MAX_INT32_SIZE:
n = MA... | 6fcd12b438399f3c27b6d02a1717a3ccc0c0ca49 | 57,495 |
def high_pass_filter(x_vals, y_vals, cutoff, inspectPlots=True):
"""
Replicate origin directy
http://www.originlab.com/doc/Origin-Help/Smooth-Algorithm
"rotate" the data set so it ends at 0,
enforcing a periodicity in the data. Otherwise
oscillatory artifacts result at the ends
This uses a ... | b531921a91ff2cc6553979e7c6a87da313e2b761 | 57,496 |
def get_lemma(word: str) -> str:
""" returns the lemma of a word (simplifies word as possible)"""
return wn.morphy(word) or word | faea8c50b0abb2e541a8f84dfdfc7af5dd62e6fb | 57,497 |
import numpy
def avg_3_op(array_1, array_2, array_3, nodata):
"""Average 3 arrays. Skip nodata."""
result = numpy.empty_like(array_1)
result[:] = nodata
valid_mask = (
~numpy.isclose(array_1, nodata) &
~numpy.isclose(array_2, nodata) &
~numpy.isclose(array_3, nodata))
resul... | 6e6a47b8e5e7cae065fa933275122d1f9cee7f88 | 57,498 |
import sh
import re
def vm_stat(field):
"""Wrapper around 'vm_stat' cmdline utility."""
out = sh('vm_stat')
for line in out.split('\n'):
if field in line:
break
else:
raise ValueError("line not found")
return int(re.search(r'\d+', line).group(0)) * PAGESIZE | 15c35d607cbd7a54fa721a58d02f4bf4e0b4d81a | 57,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.