content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gains2utvec(g):
"""Converts a vector into an outer product matrix and vectorizes its upper
triangle to obtain a vector in same format as the CHIME visibility matrix.
Parameters
----------
g : 1d array
gain vector
Returns
-------
1d array with vectorized form of upper triang... | 200 |
def get_user_surveys(user: User) -> List[Dict]:
"""
Returns a list of all surveys created by
specific user with survey secret.
"""
return list(map(Survey.get_api_brief_result_with_secrets, db.get_all_surveys(user))) | 201 |
def velocity_clb(data):
"""
Get current velocity from FCU
:param data: velocity from NED
"""
global norm_velocity
norm_velocity = np.linalg.norm(np.array([data.twist.linear.x,
data.twist.linear.y])) | 202 |
def combine_mpgs(objs, cls=None):
"""
Combine multiple multipart geometries into a single multipart geometry of
geometry collection.
"""
# Generate new list of individual geometries
new = []
for obj in objs:
if isinstance(obj, shapely.geometry.base.BaseMultipartGeometry):
... | 203 |
def get_polygon_point_dist(poly, pt):
"""Returns the distance between a polygon and point.
Parameters
----------
poly : libpysal.cg.Polygon
A polygon to compute distance from.
pt : libpysal.cg.Point
a point to compute distance from
Returns
-------
dist : float
... | 204 |
def score_bearing(
wanted: LocationReferencePoint,
actual: PointOnLine,
is_last_lrp: bool,
bear_dist: float
) -> float:
"""Scores the difference between expected and actual bearing angle.
A difference of 0° will result in a 1.0 score, while 180° will cause a score of 0.0."""
... | 205 |
def test_state_break_larger():
"""Stop the simulation once the value of a state is
larger than a preset value
"""
sim = Sim()
sys = VanDerPol()
sys.add_break_greater("y",1.0)
sim.add_system(sys)
sim.simulate(20,0.01)
#If correct the simulation should break at time 0.79
assert s... | 206 |
def load_graph (graph_path):
"""
load a graph from JSON
"""
with open(graph_path) as f:
data = json.load(f)
graph = json_graph.node_link_graph(data, directed=True)
return graph | 207 |
def assign_bond_states_to_dataframe(df: pd.DataFrame) -> pd.DataFrame:
"""
Takes a ``PandasPDB`` atom dataframe and assigns bond states to each atom based on:
Atomic Structures of all the Twenty Essential Amino Acids and a Tripeptide, with Bond Lengths as Sums of Atomic Covalent Radii
Heyrovska... | 208 |
def strong_components(vs, g):
"""
Output all vertices of g reachable from any of vs enumerated by strong components.
The components are outputted in reversed topological order.
"""
c = collections.deque(topo_sort(vs, g))
nest = 0
current_comp = 0
for label, v in dfs_iterative(GraphFilte... | 209 |
def extract_features():
""" extract features for cifar10 """
model = tiny_imagenet_100_a_model()
training_features = model.predict(X_train, verbose=1)
validation_features = model.predict(X_val, verbose=1)
testing_features = model.predict(X_test, verbose=1)
with h5py.File('cifar10_features.h5',... | 210 |
def extend_cfg(cfg):
"""
Add new config variables.
E.g.
from yacs.config import CfgNode as CN
cfg.TRAINER.MY_MODEL = CN()
cfg.TRAINER.MY_MODEL.PARAM_A = 1.
cfg.TRAINER.MY_MODEL.PARAM_B = 0.5
cfg.TRAINER.MY_MODEL.PARAM_C = False
"""
from yacs.config import Cfg... | 211 |
def lastero(f, B=None):
"""
Last erosion.
y = lastero(f, B=None)
`lastero` creates the image y by computing the last erosion by
the structuring element B of the image f . The objects found in
y are the objects of the erosion by nB that can not be
reconstructed from the erosion by (n+1)B , ... | 212 |
def Sparse2Raster(arr, x0, y0, epsg, px, py, filename="", save_nodata_as=-9999):
"""
Sparse2Rastersave_nodata_as
"""
BS = 256
geotransform = (x0, px, 0.0, y0, 0.0, -(abs(py)))
srs = osr.SpatialReference()
srs.ImportFromEPSG(int("%s" % (epsg)))
projection = srs.ExportToWkt()
if isspar... | 213 |
def modularity(modules, G, L):
""" calculate modularity
modularity = [list of nx.Graph objects]
G = graph
L = num of links
"""
N_m = len(modules)
M = 0.0
for s in range(N_m):
l_s = 0.0
d_s = 0
for i in modules[s]:
l_s += float(modules[s].degree(i))
... | 214 |
def nonan_compstat_tstat_scan(dist, aInd, bInd, returnMaxInds = False):
"""
For local sieve analysis, compare A and B group for each site using a max t-statistic over a parameter space
filteredDist: [ptid x sites x params] ndarray
Returns tstat array [sites]
aInd, bInd: Boolean row index for the tw... | 215 |
def path_to_key(path, base):
"""Return the relative path that represents the absolute path PATH under
the absolute path BASE. PATH must be a path under BASE. The returned
path has '/' separators."""
if path == base:
return ''
if base.endswith(os.sep) or base.endswith('/') or base.endswith(':'):
# S... | 216 |
def extract_digits_from_end_of_string(input_string):
"""
Gets digits at the end of a string
:param input_string: str
:return: int
"""
result = re.search(r'(\d+)$', input_string)
if result is not None:
return int(result.group(0)) | 217 |
def move_bdim_to_front(x, result_ndim=None):
"""
Returns a tensor with a batch dimension at the front. If a batch
dimension already exists, move it. Otherwise, create a new batch
dimension at the front. If `result_ndim` is not None, ensure that the
resulting tensor has rank equal to `result_ndim`.
... | 218 |
def print_positions(jdate):
"""Function to format and print positions of the bodies for a date"""
print('\n')
print('------------- Bodies Positions -------------')
for index, pos in ndenumerate(positions(jdate)):
sign, degs, mins, secs = body_sign(pos)
retro = ', R' if is_retrograde(jdat... | 219 |
def paginate(**options):
"""
Automatically force request pagination for endpoints
that shouldn't return all items in the database directly.
If this decorator is used, ``limit`` and ``offset`` request
arguments are automatically included in the request. The
burden is then on developers to do some... | 220 |
def fetch_basc_vascular_atlas(n_scales='scale007',
target_affine=np.diag((5, 5, 5))):
""" Fetch the BASC brain atlas given its resolution.
Parameters
----------
hrf_atlas: str, BASC dataset name possible values are: 'scale007',
'scale012', 'scale036', 'scale064', '... | 221 |
def _get_time_slices(
window_start,
window,
projection, # Defer calling until called by test code
resampling_scale,
lag = 1,
):
"""Extracts the time slice features.
Args:
window_start: Start of the time window over which to extract data.
window: Length of the window (in days).
proj... | 222 |
def hash_parameters(keys, minimize=True, to_int=None):
"""
Calculates the parameters for a perfect hash. The result is returned
as a HashInfo tuple which has the following fields:
t
The "table parameter". This is the minimum side length of the
table used to create the hash. In practice, t... | 223 |
def Base64EncodeHash(digest_value):
"""Returns the base64-encoded version of the input hex digest value."""
return base64.encodestring(binascii.unhexlify(digest_value)).rstrip('\n') | 224 |
def to_cropped_imgs(ids, dir, suffix, scale):
"""从元组列表中返回经过剪裁的正确img"""
for id, pos in ids:
im = resize_and_crop(Image.open(dir + id + suffix), scale=scale) # 重新设置图片大小为原来的scale倍
yield get_square(im, pos) | 225 |
def init_node(node_name, publish_topic):
"""
Init the node.
Parameters
----------
node_name
Name assigned to the node
publish_topic
Name of the publisher topic
"""
rospy.init_node(node_name, anonymous=True)
publisher = rospy.Publisher(publish_topic, Int16MultiArray,... | 226 |
def AdvectionRK4(particle, fieldset, time):
"""Advection of particles using fourth-order Runge-Kutta integration.
Function needs to be converted to Kernel object before execution"""
(u1, v1) = fieldset.UV[time, particle.depth, particle.lat, particle.lon]
lon1, lat1 = (particle.lon + u1*.5*particle.dt, ... | 227 |
def fits_checkkeyword(fitsfile, keyword, ext=0, silent=False):
"""
Check the keyword value of a FITS extension.
Parameters
----------
fitsfile : str
Path to the FITS file.
keyword : str
The keyword to check.
ext : int or str
Extension index (int) or key (str).
R... | 228 |
def check_nodes(redis_server, host_list, hpgdomain):
"""Count number of nodes which are accesible via the Hashpipe-Redis
gateway. Use this to show which nodes are inaccessible.
"""
print("Counting accessible hosts:")
n_accessible = 0
for host in host_list:
host_key = "{}://{}/0/status".... | 229 |
def print_size_np_array(array, array_name):
"""Print shape and total Mb consumed by the elements of the array."""
logger.debug("Shape of {0} array: {1}".format(array_name, array.shape))
logger.debug("Size of {0}: {1:.3f} MB".format(array_name, array.nbytes / float(2 ** 20))) | 230 |
def arr_ds(time=True, var='tmp'):
"""
Read in a saved dataset containing lat, lon, and values
:param time: (boolean) - whether to return dataset with time
:param var: (str) - variable type (only tmp/rh currently)
:return ds: (xr.dataset) - dataset
"""
if time:
if var is 'tm... | 231 |
def reset_all():
""" Reset the stored values """
print('Resetting stored values')
st.session_state.results = []
st.session_state.carrier_accumulation = None
st.session_state.period = ''
st.session_state.ran = False | 232 |
def test_invalid_file_type():
"""
To test the script behaviour if we provide an invalid file type
"""
expected_error_msg = 'Invalid File Type. Allowed File Type is .apk'
script_error = None
# Input Values
app_path = get_file_location(product_test_config.INVALID_FILE)
build_info = 'Imag... | 233 |
def clone():
"""clone(n, args, inpanel) -> Node
Create a clone node that behaves identical to the original. The node argument is the node to be cloned, args and inpanel are optional arguments similar to createNode.
A cloned node shares the exact same properties with its original. Clones share the s... | 234 |
def quarter(d):
"""
Return start/stop datetime for the quarter as defined by dt.
"""
from django_toolkit.datetime_util import quarter as datetime_quarter
first_date, last_date = datetime_quarter(datetime(d.year, d.month, d.day))
return first_date.date(), last_date.date() | 235 |
def _fp(yhat, ytrue):
"""
Class wise false positive count.
:param yhat:
:param ytrue:
:return:
"""
yhat_true = np.asarray(yhat == np.max(yhat, axis=1, keepdims=True), dtype="float32")
return np.sum(yhat_true * (1. - ytrue), axis=0) | 236 |
def rawmap(k2i, file):
"""
Map index to raw data from file
Arguments
k2i: key-to-index map
file: file containing raw data map
Returns
raw: index-to-raw map if file exists else identity map
"""
raw = {0: ''}
if os.path.isfile(file):
with open(file, "r") as f... | 237 |
def explainPlan(cursor, query, iid):
"""
Determine the execution plan Oracle follows to execute a specified SQL statement.
"""
cursor.execute("EXPLAIN PLAN SET STATEMENT_ID = '{0}' FOR ".format(iid) + query) | 238 |
def out_flag():
"""Either -o or --outfile"""
return '-o' if random.randint(0, 1) else '--outfile' | 239 |
def guess_from_peak(y, x, negative=False):
"""Estimate starting values from 1D peak data and return (height,center,sigma).
Parameters
----------
y : array-like
y data
x : array-like
x data
negative : bool, optional
determines if peak height is positive or negative, by de... | 240 |
def setup():
"""
Configure SSL with letsencrypt's certbot for the domain
"""
server_name = ctx("nginx.server_name")
path_letsencrypt = '/etc/letsencrypt/live'
path_dhparams = '/etc/letsencrypt/ssl-dhparams.pem'
path_key = '{}/{}/privkey.pem'.format(path_letsencrypt, server_name)
path_cer... | 241 |
def get_default_extension():
"""
return the default view extension
"""
return rawData.Visualization | 242 |
def reset():
"""Resets the logging system, removing all log handlers."""
global _log_handlers, _log_handlers_limited, _initialized
_log_handlers = []
_log_handlers_limited = []
_initialized = False | 243 |
def trace(service_addr,
logdir,
duration_ms,
worker_list='',
num_tracing_attempts=3):
"""Sends grpc requests to profiler server to perform on-demand profiling.
This method will block caller thread until receives tracing result.
Args:
service_addr: Address of profiler ... | 244 |
def getNewPluginManager() -> pluginManager.ArmiPluginManager:
"""
Return a new plugin manager with all of the hookspecs pre-registered.
"""
pm = pluginManager.ArmiPluginManager("armi")
pm.add_hookspecs(ArmiPlugin)
return pm | 245 |
def get_utterances_from_stm(stm_file):
"""
Return list of entries containing phrase and its start/end timings
:param stm_file:
:return:
"""
res = []
with io.open(stm_file, "r", encoding='utf-8') as f:
for stm_line in f:
if re.match ("^;;",stm_line) is None :
... | 246 |
def _iter_model_rows(model,
column,
include_root=False):
"""Iterate over all row indices in a model"""
indices = [QtCore.QModelIndex()] # start iteration at root
for index in indices:
# Add children to the iterations
child_rows = model.rowCount(in... | 247 |
def lookup_quo_marks(lang='en-US', map_files=MAP_FILES, encoding='utf-8'):
"""Looks up quotation marks for a language.
Arguments:
``lang`` (``str``):
An RFC 5646-ish language code (e.g., "en-US", "pt-BR",
"de", "es"). Defines the language the quotation marks
of which... | 248 |
def extractVars(*names,**kw):
"""Extract a set of variables by name from another frame.
:Parameters:
- `*names`: strings
One or more variable names which will be extracted from the caller's
frame.
:Keywords:
- `depth`: integer (0)
How many frames in the stack to walk when l... | 249 |
def chmod_rights(file, access_rights):
"""Changes access permission of a file:
Read additional information in:
https://docs.python.org/3/library/os.html#os.chmod
https://www.geeksforgeeks.org/python-os-chmod-method/
"""
access = os.chmod(file, access_rights, follow_symlinks=True) | 250 |
def assert_array_almost_equal(
x: Tuple[int, int, int, int, int, int], y: Tuple[int, int, int, int, int, int]
):
"""
usage.skimage: 1
"""
... | 251 |
def replace_unwanted_xml_attrs(body):
"""
Method to return transformed string after removing all the unwanted characters from given xml body
:param body:
:return:
"""
return body.replace('&', '&').replace('<', '<').replace('>', '>') | 252 |
def protocol_version_to_kmip_version(value):
"""
Convert a ProtocolVersion struct to its KMIPVersion enumeration equivalent.
Args:
value (ProtocolVersion): A ProtocolVersion struct to be converted into
a KMIPVersion enumeration.
Returns:
KMIPVersion: The enumeration equival... | 253 |
def compressStack( imageStack, blosc_threads = 1, pool_threads=maxThreads ):
"""
Does frame compression using a ThreadPool to distribute the load.
"""
blosc.set_nthreads( blosc_threads )
tPool = ThreadPool( pool_threads )
num_slices = imageStack.shape[0]
# Build parameters list for the thre... | 254 |
def packing_with_uncommitted_data_non_undoing():
"""
This covers regression for bug #130459.
When uncommitted data exists it formerly was written to the root of the
blob_directory and confused our packing strategy. We now use a separate
temporary directory that is ignored while packing.
>>> im... | 255 |
def UniversalInput(i, o, *args, **kwargs):
"""
Returns the most appropriate input UI element, based on available keys
of input devices present. For now, always returns UI elements configured
for character input.
TODO: document arguments (most of them are passed through, like "name" or "message")
... | 256 |
def valid_template(template):
"""Is this a template that returns a valid URL?"""
if template.name.lower() == "google books" and (
template.has("plainurl") or template.has("plain-url")
):
return True
if template.name.lower() == "billboardurlbyname":
return True
return False | 257 |
def wait_process(pid, *, exitcode, timeout=None):
"""
Wait until process pid completes and check that the process exit code is
exitcode.
Raise an AssertionError if the process exit code is not equal to exitcode.
If the process runs longer than timeout seconds (SHORT_TIMEOUT by default),
kill t... | 258 |
def test_calculate_distance_factor():
"""
Tests calculate_distance_factor function
"""
assert utils.calculate_distance_factor(441.367, 100) == 0.11 | 259 |
def build_get_complex_item_null_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get array of complex type with null item [{'integer': 1 'string': '2'}, null, {'integer': 5,
'string': '6'}].
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request bui... | 260 |
def maybe_load_pyjulia():
"""
Execute ``julia.Julia(init_julia=False)`` if appropriate.
It is useful since it skips initialization when creating the
global "cached" API. This makes PyJuli initialization slightly
faster and also makes sure to not load incompatible `libjulia`
when the name of th... | 261 |
def get_choice():
""" Gets and returns choice for mode to use when running minimax """
choice = input(
"Please enter a number (1 - 4)\n 1. Both players use minimax correctly at every turn\n 2. The starting player (X) is an expert and the opponent (0) only has a 50% chance to use minimax\n\t at each turn... | 262 |
def _arange_ndarray(arr, shape, axis, reverse=False):
"""
Create an ndarray of `shape` with increments along specified `axis`
Parameters
----------
arr : ndarray
Input array of arbitrary shape.
shape : tuple of ints
Shape of desired array. Should be equivalent to `arr.shape` exc... | 263 |
def rotate_pt(x_arr, y_arr, theta_deg, xoff=0, yoff=0):
"""
Rotate an array of points (x_arr, y_arr) by theta_deg offsetted
from a center point by (xoff, yoff).
"""
# TODO: use opencv acceleration if available
a_arr = x_arr - xoff
b_arr = y_arr - yoff
cos_t = np.cos(np.radians(theta_deg)... | 264 |
def get_frames(data: Union[sc.DataArray, sc.Dataset], **kwargs) -> sc.Dataset:
"""
For a supplied instrument chopper cascade and detector positions, find
the locations in microseconds of the WFM frames.
TODO: Currently, only the analytical (time-distance) method has been tested
and is enabled.
... | 265 |
def _map_nonlinearities(
element: Any, nonlinearity_mapping: Type[NonlinearityMapping] = NonlinearityMapping
) -> Any:
"""Checks whether a string input specifies a PyTorch layer.
The method checks if the input is a string.
If the input is a string, it is preprocessed and then mapped to
a correspond... | 266 |
def confirm(text, app, version, services=None, default_yes=False):
"""Asks a user to confirm the action related to GAE app.
Args:
text: actual text of the prompt.
app: instance of Application.
version: version or a list of versions to operate upon.
services: list of services to operate upon (or Non... | 267 |
def _get_streamflow(product, feature_id, s_date, s_time, e_date, lag):
"""Downloads streamflow time series for a given river.
Downloads streamflow time series for a given river feature using
the HydroShare archive and Web service. Units are in cubic feet per
second as returned by HydroShare. For the AP... | 268 |
def main():
"""Make a jazz noise here"""
args = get_args()
input_sudoku = [[0, 0, 0, 0, 5, 2, 0, 4, 0],
[0, 0, 3, 6, 7, 0, 0, 0, 9],
[0, 6, 0, 0, 0, 3, 5, 0, 0],
[0, 9, 0, 0, 2, 6, 8, 0, 0],
[0, 0, 0, 0, 0, 7, 1, 0, 0],
... | 269 |
def debug(func):
"""Debug the decorated function"""
@functools.wraps(func)
def wrapper_debug(*args, **kwargs):
args_repr = [repr(a) for a in args]
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
signature = ", ".join(args_repr + kwargs_repr)
print(f"Calling {func.__n... | 270 |
def get_profanity(text: str, duplicates=False) -> list:
"""Gets all profane words and returns them in a list"""
text: str = text.lower()
additional: list = []
profane: list = [word for word in PROFANE_WORD_LIST if word in text]
if duplicates:
for word in profane:
c: int = text.c... | 271 |
def build_stats(train_result, eval_result, time_callback):
"""Normalizes and returns dictionary of stats.
Args:
train_result: The final loss at training time.
eval_result: Output of the eval step. Assumes first value is eval_loss and
second value is accuracy_top_1.
time_callback: Time tracking ca... | 272 |
def multiplicative(v1, v2, alpha=1, beta=1):
"""
Weighted elementwise multiplication.
"""
compword = str(v1.row2word[0]) + " " + str(v2.row2word[0])
comp = (alpha * v1) * (beta * v2)
comp.row2word = [compword]
return comp | 273 |
def supported_formats():
"""Generates dictionary entries for supported formats. Each entry will
always have description, extension, mimetype, and category. Reader
will provide the reader, if one exists, writer will provide the writer,
if one exists.
Metadata gives a list of metadata read and/or wri... | 274 |
async def test_setup_without_ipv6(hass, mock_zeroconf):
"""Test without ipv6."""
with patch.object(hass.config_entries.flow, "async_init"), patch.object(
zeroconf, "HaServiceBrowser", side_effect=service_update_mock
):
mock_zeroconf.get_service_info.side_effect = get_service_info_mock
... | 275 |
def is_information(status_code, **options):
"""
gets a value indicating that given status code is a information code.
if returns True if the provided status code is
from `InformationResponseCodeEnum` values.
:param int status_code: status code to be checked.
:keyword bool strict_status: speci... | 276 |
def create_application_registration(
onefuzz_instance_name: str, name: str, approle: OnefuzzAppRole, subscription_id: str
) -> Any:
"""Create an application registration"""
app = get_application(
display_name=onefuzz_instance_name, subscription_id=subscription_id
)
if not app:
rais... | 277 |
def test_fnirs_channel_naming_and_order_custom_raw():
"""Ensure fNIRS channel checking on manually created data."""
data = np.random.normal(size=(6, 10))
# Start with a correctly named raw intensity dataset
# These are the steps required to build an fNIRS Raw object from scratch
ch_names = ['S1_D1 ... | 278 |
def get_all_stocks():
"""获取本地文件已有数据的股票列表"""
stock_files = os.listdir(PATH_STOCK)
stocks = [ file.split('_')[0] for file in stock_files if file.endswith('csv')]
return stocks | 279 |
def from_mel(
mel_,
sr=16000,
n_fft=2048,
n_iter=32,
win_length=1000,
hop_length=100,
):
"""
Change melspectrogram into waveform using Librosa.
Parameters
----------
spectrogram: np.array
Returns
--------
result: np.array
"""
return librosa.feature.inver... | 280 |
def read(filename, conn):
""" Read data from a file and send it to a pipe """
with open(filename, encoding='utf-8') as f:
conn.send(f.read()) | 281 |
def validate_unique_contests():
"""Should have a unique set of contests for all elections"""
# Get all election ids
election_ids = list(Contest.objects.distinct('election_id'))
for elec_id in election_ids:
contests = Contest.objects.filter(election_id=elec_id)
# compare the number of con... | 282 |
def expand(arg):
"""
sp.expand currently has no matrix support
"""
if isinstance(arg, sp.Matrix):
return arg.applyfunc(sp.expand)
else:
return sp.expand(arg) | 283 |
def validate(obj, schema):
"""
validates the object against the schema, inserting default values when required
"""
validator(schema).validate(obj) | 284 |
def test_table_no_headers(mocker):
"""This situation could never happen as parsed from Markdown. See
https://stackoverflow.com/a/17543474.
However this situation could happen manually when using the Table() class
directly.
"""
fake_config = mocker.patch.object(lookatme.widgets.table, "confi... | 285 |
def generate_genome_index(annotation, unstranded_genome_index, stranded_genome_index, chrom_sizes):
""" Create an index of the genome annotations and save it in a file. """
# Initializations
intervals_dict = {}
max_value = -1
prev_chrom = ""
i = 0 # Line counter
# Write the chromosome lengt... | 286 |
def ElementTreeToDataset(element_tree, namespaces, csv_path, load_all_data):
"""Convert an ElementTree tree model into a DataSet object.
Args:
element_tree: ElementTree.ElementTree object containing complete data from
DSPL XML file
namespaces: A list of (namespace_id, namespace_url) tuple... | 287 |
def load_config(path):
"""
load the config of LSTMLM
"""
if path.rfind('.ckpt') != -1:
path_name = path[0: path.rfind('.ckpt')]
else:
path_name = path
with open(path_name + '.config', 'rt') as f:
name = f.readline().split()[0]
config = wb.Config.load(f... | 288 |
def box_plot_stats(
## arguments / inputs
x, ## input array of values
coef = 1.5 ## positive real number
## (determines how far the whiskers extend from the iqr)
):
"""
calculates box plot five-number summary: the lower whisker extreme, the
lo... | 289 |
def handle_echo(reader, writer):
"""Nehme Kommandos von PureData entgegen und sende sie an die Bulb
netcat -l 8081
nc localhost 8081
nc dahomey.local 8081
"""
# Verhindere minutenlange Warteschlangen
global tiefe
if tiefe >= MAX_PUFFER:
if args.verbose:
print("{}... | 290 |
def test_ms_infer_for_func():
""" test_ms_infer_for_func """
ms_infer_for_func(1.0) | 291 |
def expand_multinomial(expr, deep=True):
"""
Wrapper around expand that only uses the multinomial hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import symbols, expand_multinomial, exp
>>> x, y = symbols('x y', positive=True)
>>> expand_multinomi... | 292 |
def unpickle_tokens(filepath):
"""Unpickle the tokens into memory."""
try:
with open(filepath+'_tokens.pickle', 'rb') as f:
tokens = pickle.load(f)
except FileNotFoundError:
tokens = tokenize_and_tag(filepath)
pickle_tokens(tokens, filepath)
return tokens | 293 |
def make_cov(df, columns=["parallax", "pmra", "pmdec"]):
"""Generate covariance matrix from Gaia data
columns : list
list of columns to calculate covariance.
Must be a subset of 'ra', 'dec' 'parallax', 'pmra', 'pmdec'.
Returns
-------
numpy.array
(N, number of columns) arra... | 294 |
def kinetics(request, section='', subsection=''):
"""
The RMG database homepage.
"""
# Make sure section has an allowed value
if section not in ['libraries', 'families', '']:
raise Http404
# Load the kinetics database, if necessary
database.load('kinetics', section)
# Determine... | 295 |
def test_safe_std():
"""Checks that the calculated standard deviation is correct."""
array = np.array((1, 2, 3))
calc_std = _weighting._safe_std(array)
assert_allclose(calc_std, np.std(array)) | 296 |
def cot_to_cot(craft: dict, known_craft: dict = {}) -> str:
"""
Given an input CoT XML Event with an ICAO Hex as the UID, will transform the Event's name, callsign & CoT Event
Type based on known craft input database (CSV file).
"""
return xml.etree.ElementTree.tostring(cot_to_cot_xml(craft, known_c... | 297 |
def update_export(module, export, filesystem, system):
""" Create new filesystem or update existing one"""
assert export
changed = False
name = module.params['name']
client_list = module.params['client_list']
if client_list:
if set(map(transform, unmunchify(export.get_permissions()))) ... | 298 |
def create_kdf(kdf_type: str) -> typing.Type[KDF]:
"""Returns the class corresponding to the given key derivation function
type name.
Args:
kdf_type
The name of the OpenSSH private key key derivation function type.
Returns:
The subclass of :py:class:`KDF` corresponding to t... | 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.