content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def populate_institute_form(form, institute_obj):
"""Populate institute settings form
Args:
form(scout.server.blueprints.institutes.models.InstituteForm)
institute_obj(dict) An institute object
"""
# get all other institutes to populate the select of the possible collaborators
insti... | 836850a55a02b199b2c7607a236f77e6b95051e0 | 3,650,808 |
def closestMedioidI(active_site, medioids, distD):
"""
returns the index of the closest medioid in medioids to active_site
input: active_site, an ActiveSite instance
medioids, a list of ActiveSite instances
distD, a dictionary of distances
output: the index of the ActiveSite close... | 379f98a84751c0a392f8f9b1703b89b299979676 | 3,650,809 |
def no_op_job():
"""
A no-op parsl.python_app to return a future for a job that already
has its outputs.
"""
return 0 | ad8d6379ba35dae14ce056d9900fb6e62c769d85 | 3,650,811 |
def identity(dim, shape=None):
"""Return identity operator with appropriate shape.
Parameters
----------
dim : int
Dimension of real space.
shape : int (optional)
Size of the unitary part of the operator.
If not provided, U is set to None.
Returns
-------
id : P... | 0cd40246f4ccf2805a852dcea09d451e7f8c63a5 | 3,650,812 |
from typing import Optional
from typing import Union
import torch
from pathlib import Path
import json
def load_separator(
model_str_or_path: str = "umxhq",
targets: Optional[list] = None,
niter: int = 1,
residual: bool = False,
wiener_win_len: Optional[int] = 300,
device: Union[str, torch.dev... | bb9d0ecf47174ebac9181710a1bc4689ca122ecf | 3,650,815 |
from datetime import datetime
def transform_datetime(date_str, site):
"""
ๆ นๆฎsite่ฝฌๆขๅๅง็dateไธบๆญฃ่ง็date็ฑปๅๅญๆพ
:param date_str: ๅๅง็date
:param site: ็ฝ็ซๆ ่ฏ
:return: ่ฝฌๆขๅ็date
"""
result = None
if site in SITE_MAP:
if SITE_MAP[site] in (SiteType.SINA, SiteType.HACKERNEWS):
try:
... | 647ab633b0d5ce0887042ef42a762f1bc3196242 | 3,650,816 |
import re
import numpy
def ParseEventsForTTLs(eventsFileName, TR = 2.0, onset = False, threshold = 5.0):
"""
Parses the events file from Avotec for TTLs. Use if history file is not available.
The events files does not contain save movie start/stops, so use the history file if possible
@param eventsFileName: name... | 59fa31df066424df3625e55496f0ccefa39f2d64 | 3,650,817 |
def _to_native_string(string, encoding='ascii'):
"""Given a string object, regardless of type, returns a representation of
that string in the native string type, encoding and decoding where
necessary. This assumes ASCII unless told otherwise.
"""
if isinstance(string, str):
out = string
... | b50fd0fc62b2cfc024c847b98e1f85b4b67d07e3 | 3,650,818 |
def load(path: str) -> model_lib.Model:
"""Deserializes a TensorFlow SavedModel at `path` to a `tff.learning.Model`.
Args:
path: The `str` path pointing to a SavedModel.
Returns:
A `tff.learning.Model`.
"""
py_typecheck.check_type(path, str)
if not path:
raise ValueError('`path` must be a non-... | 1bd16ed7b4a7955f2a78fc638e896bbd6d1ee5ac | 3,650,819 |
def parameters_from_object_schema(schema, in_='formData'):
"""Convert object schema to parameters."""
# We can only extract parameters from schema
if schema['type'] != 'object':
return []
properties = schema.get('properties', {})
required = schema.get('required', [])
parameters = []
... | 7508fb066d6924fc0af4a10338636b70ef64b9b2 | 3,650,821 |
def any_toggle_enabled(*toggles):
"""
Return a view decorator for allowing access if any of the given toggles are
enabled. Example usage:
@toggles.any_toggle_enabled(REPORT_BUILDER, USER_CONFIGURABLE_REPORTS)
def delete_custom_report():
pass
"""
def decorator(view_func):
@w... | 25f48e9227f5c6ff74ae9874ac0b3b7ad010861b | 3,650,823 |
def moguls(material, height, randomize, coverage, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=True, bf=True, optimize=True, xtraParams=defaultXtraParams):
"""moguls(material, radius, randomize, det, [e0=20.0], [withPoisson=True], [nTraj=defaultNumTraj], [dose = 120.0], [sf=True], [bf=... | 182aa248962877636e18860b46d20335eb535074 | 3,650,824 |
def link_datasets(yelp_results, dj_df, df_type="wages"):
"""
(Assisted by Record Linkage Toolkit library and documentation)
This functions compares the Yelp query results to database results and
produces the best matches based on computing the qgram score. Depending
on the specific database table c... | 326857d5060ac5cedcac3de90ce284048b2d2fa7 | 3,650,825 |
def hello():
"""Say Hello, so that we can check shared code."""
return b"hello" | 7197ed31c5fde419d4607ca1b5dbec7f8cb20608 | 3,650,826 |
def loglog_mean_lines(x, ys, axis=0, label=None, alpha=0.1):
""" Log-log plot of lines and their mean. """
return _plot_mean_lines(partial(plt.loglog, x), ys, axis, label, alpha) | 2f4461ca21c2f8db9ddfd763f474ebc73f3bf636 | 3,650,827 |
def generate_identifier(endpoint_description: str) -> str:
"""Generate ID for model."""
return (
Config.fdk_publishers_base_uri()
+ "/fdk-model-publisher/catalog/"
+ sha1(bytes(endpoint_description, encoding="utf-8")).hexdigest() # noqa
) | 30bfc15c12b47f637627391a45bb9b5f9355c4f7 | 3,650,829 |
def depthFirstSearch(problem):
"""Search the deepest nodes in the search tree first."""
stack = util.Stack() # Stack used as fringe list
stack.push((problem.getStartState(),[],0))
return genericSearch(problem,stack) | 67452934a29e9857f90b88f3fead67d101468471 | 3,650,830 |
def create_app():
"""
Method to init and set up the Flask application
"""
flask_app = MyFlask(import_name="dipp_app")
_init_config(flask_app)
_setup_context(flask_app)
_register_blueprint(flask_app)
_register_api_error(flask_app)
return flask_app | bfb64ac71fcd076fe26c3b342c33af30370be8db | 3,650,832 |
def find_consumes(method_type):
"""
Determine mediaType for input parameters in request body.
"""
if method_type in ('get', 'delete'):
return None
return ['application/json'] | 785e70e41629b0386d8b86f247afaf5bff3b7ba9 | 3,650,833 |
def preprocess(text):
""" Simple Arabic tokenizer and sentencizer. It is a space-based tokenizer. I use some rules to handle
tokenition exception like words containing the preposition 'ู'. For example 'ููุงูุฏุชู' is tokenized to 'ู ูุงูุฏุชู'
:param text: Arabic text to handle
:return: list of tokenized sen... | 48a44391413045a49d6d9f2dff20dcd89734b4f2 | 3,650,834 |
def login(client, password="pass", ):
"""Helper function to log into our app.
Parameters
----------
client : test client object
Passed here is the flask test client used to send the request.
password : str
Dummy password for logging into the app.
Return
-------
post re... | 5adca2e7d54dabe47ae92f0bcebb93e0984617b1 | 3,650,835 |
def define_dagstermill_solid(
name,
notebook_path,
input_defs=None,
output_defs=None,
config_schema=None,
required_resource_keys=None,
output_notebook=None,
output_notebook_name=None,
asset_key_prefix=None,
description=None,
tags=None,
):
"""Wrap a Jupyter notebook in a s... | 48097a7bed7ef84ad8d9df4eeef835f3723cb391 | 3,650,836 |
import torch
def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
"""De-normalizes LAFs from scale to image scale.
B,N,H,W = images.size()
MIN_SIZE = min(H,W)
[a11 a21 x]
[a21 a22 y]
becomes
[a11*MIN_SIZE a21*MIN_SIZE x*W]
[a21*MIN_... | 51b8c81359237a9e102c1cd33bb7d1ab16c39893 | 3,650,837 |
import re
def parse_regex_flags(raw_flags: str = 'gim'):
"""
parse flags user input and convert them to re flags.
Args:
raw_flags: string chars representing er flags
Returns:
(re flags, whether to return multiple matches)
"""
raw_flags = raw_flags.lstrip('-') # compatibilit... | 71816c57f4e4f6dac82b4746b534a680745bc730 | 3,650,839 |
def has_answer(answers, retrieved_text, match='string', tokenized: bool = False):
"""Check if retrieved_text contains an answer string.
If `match` is string, token matching is done between the text and answer.
If `match` is regex, we search the whole text with the regex.
"""
if not isinstance(answe... | f0107006d2796e620cd1a47ef9e79c1c5cc1fd7a | 3,650,841 |
def get_utm_zone(srs):
"""
extracts the utm_zone from an osr.SpatialReference object (srs)
returns the utm_zone as an int, returns None if utm_zone not found
"""
if not isinstance(srs, osr.SpatialReference):
raise TypeError('srs is not a osr.SpatialReference instance')
if srs.IsProjec... | 3ee1f9780ce0fbfd843ea6b72627e90e16fd1549 | 3,650,842 |
def get_documents_meta_url(project_id: int, limit: int = 10, host: str = KONFUZIO_HOST) -> str:
"""
Generate URL to load meta information about the Documents in the Project.
:param project_id: ID of the Project
:param host: Konfuzio host
:return: URL to get all the Documents details.
"""
re... | b538d028844a2f769e8700995d1052b440592046 | 3,650,843 |
def parse_params_from_string(paramStr: str) -> dict:
""" Create a dictionary representation of parameters in PBC format
"""
params = dict()
lines = paramStr.split('\n')
for line in lines:
if line:
name, value = parse_param_line(line)
add_param(params, name, value)
... | fbf8c8cfffd0c411cc4a83760f373dd4e02eec1e | 3,650,844 |
def number_fixed_unused_variables(block):
"""
Method to return the number of fixed Var components which do not appear
within any activated Constraint in a model.
Args:
block : model to be studied
Returns:
Number of fixed Var components which do not appear within any activated
... | a6432160bc52ac3e5682b255c951388242bbc2b0 | 3,650,846 |
def tunnelX11( node, display=None):
"""Create an X11 tunnel from node:6000 to the root host
display: display on root host (optional)
returns: node $DISPLAY, Popen object for tunnel"""
if display is None and 'DISPLAY' in environ:
display = environ[ 'DISPLAY' ]
if display is None:
... | a0e824bef4d23dd3a8a5c25653bf778731de180e | 3,650,847 |
import collections
def get_aws_account_id_file_section_dict() -> collections.OrderedDict:
"""~/.aws_accounts_for_set_aws_mfa ใใ Section ๆ
ๅ ฑใๅๅพใใ"""
# ~/.aws_accounts_for_set_aws_mfa ใฎๆ็กใ็ขบ่ชใใใชใใใฐ็ๆใใ
prepare_aws_account_id_file()
# ่ฉฒๅฝ ini ใใกใคใซใฎใปใฏใทใงใณ dictionary ใๅๅพ
return Config._sections | 51eb94857d62b91c5fcfe978b3cd2a32cbefb6ae | 3,650,849 |
from datetime import datetime
def profile(request, session_key):
"""download_audio.html renderer.
:param request: rest API request object.
:type request: Request
:param session_key: string representing the session key for the user
:type session_key: str
:return: Just another django mambo... | ba39b5a69c062ab62f83f46f7044f403120016ca | 3,650,850 |
import requests
def pipFetchLatestVersion(pkg_name: str) -> str:
"""
Fetches the latest version of a python package from pypi.org
:param pkg_name: package to search for
:return: latest version of the package or 'not found' if error was returned
"""
base_url = "https://pypi.org/pypi"
reques... | f1a49d31f4765a1a2ddc5942792a74be211fef49 | 3,650,851 |
def mock_datasource_http_oauth2(mock_datasource):
"""Mock DataSource object with http oauth2 credentials"""
mock_datasource.credentials = b"client_id: FOO\nclient_secret: oldisfjowe84uwosdijf"
mock_datasource.location = "http://foo.com"
return mock_datasource | 8496f6b9ac60af193571f762eb2ea925915a1223 | 3,650,853 |
def find_certificate_name(file_name):
"""Search the CRT for the actual aggregator name."""
# This loop looks for the collaborator name in the key
with open(file_name, 'r') as f:
for line in f:
if 'Subject: CN=' in line:
col_name = line.split('=')[-1].strip()
... | 853ec62b69feebd86c7a56e1d47b2c12e7f56d63 | 3,650,854 |
from typing import List
def float2bin(p: float, min_bits: int = 10, max_bits: int = 20, relative_error_tol=1e-02) -> List[bool]:
""" Converts probability `p` into binary list `b`.
Args:
p: probability such that 0 < p < 1
min_bits: minimum number of bits before testing relative error.
... | 1b25f84255ace0503f06ae2ab9f8dc650206176c | 3,650,856 |
def bin_thresh(img: np.ndarray, thresh: Number) -> np.ndarray:
"""
Performs binary thresholding of an image
Parameters
----------
img : np.ndarray
Image to filter.
thresh : int
Pixel values >= thresh are set to 1, else 0.
Returns
-------
np.ndarray :
Binariz... | 9064fb5f50c22aabc73bf63d3a818b6898a19a58 | 3,650,857 |
from mathutils import Matrix, Vector, Euler
def add_object_align_init(context, operator):
"""
Return a matrix using the operator settings and view context.
:arg context: The context to use.
:type context: :class:`bpy.types.Context`
:arg operator: The operator, checked for location and rotation pr... | 6bd32226c7024245b1252c3a51f5ae713f43a1b2 | 3,650,858 |
import pickle
def load_dataset():
"""
load dataset
:return: dataset in numpy style
"""
data_location = 'data.pk'
data = pickle.load(open(data_location, 'rb'))
return data | 9467826bebfc9ca3ad1594904e9f3195e345c065 | 3,650,859 |
def video_feed():
"""Return camera live feed."""
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame') | 87c9ae8aa84fe17a16b040d56fbdaac6351e0706 | 3,650,860 |
def area_in_squaremeters(geodataframe):
"""Calculates the area sizes of a geo dataframe in square meters.
Following https://gis.stackexchange.com/a/20056/77760 I am choosing equal-area projections
to receive a most accurate determination of the size of polygons in the geo dataframe.
Instead of Gall-Pet... | 47a2ae042c8cda7fa6b66ccd011d0293afb36504 | 3,650,861 |
import scipy
def add_eges_grayscale(image):
""" Edge detect.
Keep original image grayscale value where no edge.
"""
greyscale = rgb2gray(image)
laplacian = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
edges = scipy.ndimage.filters.correlate(greyscale, laplacian)
for index,value in np.nd... | 0cba5152578722693d0d796252a99973e980b365 | 3,650,862 |
def generateFromSitePaymentObject(signature: str, account_data: dict, data: dict)->dict:
"""[summary]
Creates object for from site chargment request
Args:
signature (str): signature hash string
account_data (dict): merchant_account: str
merchant_domain: str
... | 149434694e985956dede9bf8b6b0da1215ac9963 | 3,650,863 |
def deal_weights(node, data=None):
""" deal the weights of the custom layer
"""
layer_type = node.layer_type
weights_func = custom_layers[layer_type]['weights']
name = node.layer_name
return weights_func(name, data) | a2a271ea0aeb94a1267dbc06da8997985b81633e | 3,650,864 |
def label_brand_generic(df):
""" Correct the formatting of the brand and generic drug names """
df = df.reset_index(drop=True)
df = df.drop(['drug_brand_name', 'drug_generic_name'], axis=1)
df['generic_compare'] = df['generic_name'].str.replace('-', ' ')
df['generic_compare'] = df['generic_compare']... | a421eece6e595159847821abcaf2cf7dd8dc88c5 | 3,650,865 |
def RMSRE(
image_true: np.ndarray,
image_test: np.ndarray,
mask: np.ndarray = None,
epsilon: float = 1e-9,
) -> float:
"""Root mean squared relative error (RMSRE) between two images within the
specified mask. If not mask is specified the entire image is used.
Parameters
----------
i... | 6b377b2588ef0c02f059248d3214e0d7960ca25b | 3,650,866 |
import PIL
import logging
def getImage(imageData, flag):
"""
Returns the PIL image object from imageData based on the flag.
"""
image = None
try:
if flag == ENHANCED:
image = PIL.Image.open(imageData.enhancedImage.file)
elif flag == UNENHANCED:
image = PIL.... | a3aaa80bc396fcdf099d5963706d21d63a6dcf0d | 3,650,867 |
def save_record(record_type,
record_source,
info,
indicator,
date=None):
"""
A convenience function that calls 'create_record' and also saves the resulting record.
:param record_type: The record type, which should be a value from the RecordTyp... | 903eb7333cfd2cc534812c5417e5e32a7769ffe4 | 3,650,868 |
def update_product_price(pid: str, new_price: int):
""" Update product's price
Args:
pid (str): product id
new_price (int): new price
Returns:
dict: status(success, error)
"""
playload = {'status': ''}
try:
connection = create_connection()
with connectio... | fff3723a9138724f1957cd9a669cdcf79e4ed4e5 | 3,650,869 |
def select_n_products(lst, n):
"""Select the top N products (by number of reviews)
args:
lst: a list of lists that are (key,value) pairs for (ASIN, N-reviews)
sorted on the number of reviews in reverse order
n: a list of three numbers,
returns:
a list of... | ed052708010512758845186ae9e4fb33b41bc511 | 3,650,870 |
def load_vanHateren(params):
"""
Load van Hateren data and format as a Dataset object
Inputs:
params [obj] containing attributes:
data_dir [str] directory to van Hateren data
rand_state (optional) [obj] numpy random state object
num_images (optional) [int] how many images to extract. Default... | ca32f182f5534da89df0bd5454e74a586c6ca4d6 | 3,650,871 |
import torch
def wrap_to_pi(inp, mask=None):
"""Wraps to [-pi, pi)"""
if mask is None:
mask = torch.ones(1, inp.size(1))
if mask.dim() == 1:
mask = mask.unsqueeze(0)
mask = mask.to(dtype=inp.dtype)
val = torch.fmod((inp + pi) * mask, 2 * pi)
neg_mask = (val * mask) < 0
va... | 7aca43bb2146c1cad07f9a070a7099e6fb8ad857 | 3,650,874 |
import pandas
def if_pandas(func):
"""Test decorator that skips test if pandas not installed."""
@wraps(func)
def run_test(*args, **kwargs):
try:
except ImportError:
pytest.skip('Pandas not available.')
else:
return func(*args, **kwargs)
return run_test | b39f88543559c4f4f1b9bb5bb30768916d3708d6 | 3,650,875 |
def handle_front_pots(pots, next_pots):
"""Handle front, additional pots in pots."""
if next_pots[2] == PLANT:
first_pot = pots[0][1]
pots = [
[next_pots[2], first_pot - 1]] + pots
return pots, next_pots[2:]
return pots, next_pots[3:] | 53ec905a449c0402946cb8c28852e81da80a92ef | 3,650,876 |
import types
def environment(envdata):
"""
Class decorator that allows to run tests in sandbox against different Qubell environments.
Each test method in suite is converted to <test_name>_on_environemnt_<environment_name>
:param params: dict
"""
#assert isinstance(params, dict), "@environment ... | 9ce82ff8ee3627f8795b7bc9634c298e8ff195bc | 3,650,877 |
def get_domain_name(url):
""" Returns the domain name from a URL """
parsed_uri = urlparse(url)
return parsed_uri.netloc | 00160285a29a4b2d1fe42fb8ec1648ca4c31fa8b | 3,650,878 |
def get_answer_str(answers: list, scale: str):
"""
:param ans_type: span, multi-span, arithmetic, count
:param ans_list:
:param scale: "", thousand, million, billion, percent
:param mode:
:return:
"""
sorted_ans = sorted(answers)
ans_temp = []
for ans in sorted_ans:
ans... | 734015503ccec63265a0531aa05e8bd8514c7c15 | 3,650,879 |
def user_0post(users):
"""
Fixture that returns a test user with 0 posts.
"""
return users['user2'] | 5401e7f356e769b5ae68873f2374ef74a2d439c6 | 3,650,880 |
import json
def transportinfo_decoder(obj):
"""Decode programme object from json."""
transportinfo = json.loads(obj)
if "__type__" in transportinfo and transportinfo["__type__"] == "__transportinfo__":
return TransportInfo(**transportinfo["attributes"])
return transportinfo | 8a311cb419e9985ef0a184b82888220c0f3258b2 | 3,650,883 |
def group_events_data(events):
"""
Group events according to the date.
"""
# e.timestamp is a datetime.datetime in UTC
# change from UTC timezone to current seahub timezone
def utc_to_local(dt):
tz = timezone.get_default_timezone()
utc = dt.replace(tzinfo=timezone.utc)
lo... | de2f2031bdcaaf2faffdb99c67bbbb1e15828ef8 | 3,650,884 |
def create_matrix(PBC=None):
"""
Used for calculating distances in lattices with periodic boundary conditions. When multiplied with a set of points, generates additional points in cells adjacent to and diagonal to the original cell
Args:
PBC: an axis which does not have periodic boundary condition.... | 7470803fe8297ef2db1ce4bd159e9d9c93d34787 | 3,650,885 |
def get_additive_seasonality_linear_trend() -> pd.Series:
"""Get example data for additive seasonality tutorial"""
dates = pd.date_range(start="2017-06-01", end="2021-06-01", freq="MS")
T = len(dates)
base_trend = 2
state = np.random.get_state()
np.random.seed(13)
observations = base_trend *... | 034b4ca9e086e95fa1663704fda91ae3986694b4 | 3,650,886 |
def is_client_trafic_trace(conf_list, text):
"""Determine if text is client trafic that should be included."""
for index in range(len(conf_list)):
if text.find(conf_list[index].ident_text) != -1:
return True
return False | 0b7fdf58e199444ea52476d5621ea9353475b0a0 | 3,650,887 |
def isinf(x):
"""
For an ``mpf`` *x*, determines whether *x* is infinite::
>>> from sympy.mpmath import *
>>> isinf(inf), isinf(-inf), isinf(3)
(True, True, False)
"""
if not isinstance(x, mpf):
return False
return x._mpf_ in (finf, fninf) | 4d5ca6ac2f8ed233a70c706b7fff97bf171c4f21 | 3,650,888 |
def formalize_switches(switches):
"""
Create all entries for the switches in the topology.json
"""
switches_formal=dict()
for s, switch in enumerate(switches):
switches_formal["s_"+switch]=formalize_switch(switch, s)
return switches_formal | 8dbb9987e5bc9c9f81afc0432428a746e2f05fc4 | 3,650,889 |
def arp_scores(run):
"""
This function computes the Average Retrieval Performance (ARP) scores according to the following paper:
Timo Breuer, Nicola Ferro, Norbert Fuhr, Maria Maistro, Tetsuya Sakai, Philipp Schaer, Ian Soboroff.
How to Measure the Reproducibility of System-oriented IR Experiments.
... | 0e23eb1d6ee3c2502408585b1d0dbb0993ca7628 | 3,650,890 |
from typing import Tuple
from typing import Optional
import scipy
def bayesian_proportion_test(
x:Tuple[int,int],
n:Tuple[int,int],
prior:Tuple[float,float]=(0.5,0.5),
prior2:Optional[Tuple[float,float]]=None,
num_samples:int=1000,
seed:int=8675309) -> Tuple[float,floa... | 5f63424b9dcb6e235b13a9e63f0b9a2dc1e95b31 | 3,650,891 |
import torch
def _create_triangular_filterbank(
all_freqs: Tensor,
f_pts: Tensor,
) -> Tensor:
"""Create a triangular filter bank.
Args:
all_freqs (Tensor): STFT freq points of size (`n_freqs`).
f_pts (Tensor): Filter mid points of size (`n_filter`).
Returns:
fb (... | 1ad5bd58d673626a15e27b6d9d68829299fe7636 | 3,650,892 |
def convert_millis(track_dur_lst):
""" Convert milliseconds to 00:00:00 format """
converted_track_times = []
for track_dur in track_dur_lst:
seconds = (int(track_dur)/1000)%60
minutes = int(int(track_dur)/60000)
hours = int(int(track_dur)/(60000*60))
converted_time = '%... | 3d5199da01529f72b7eb6095a26e337277f3c2c9 | 3,650,893 |
def sync_xlims(*axes):
"""Synchronize the x-axis data limits for multiple axes. Uses the maximum
upper limit and minimum lower limit across all given axes.
Parameters
----------
*axes : axis objects
List of matplotlib axis objects to format
Returns
-------
out : yxin, xmax
... | a377877a9647dfc241db482f8a2c630fe3eed146 | 3,650,894 |
def algo_config_to_class(algo_config):
"""
Maps algo config to the IRIS algo class to instantiate, along with additional algo kwargs.
Args:
algo_config (Config instance): algo config
Returns:
algo_class: subclass of Algo
algo_kwargs (dict): dictionary of additional kwargs to pa... | 884ab7a91d9d8c901d078f9b477d5d21cba3e5ff | 3,650,895 |
def group_by_key(dirnames, key):
"""Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
... | b291cd889c72fb198400b513e52ff9417c8d93b7 | 3,650,896 |
def redistrict_grouped(df, kind, group_cols, district_col=None,
value_cols=None, **kwargs):
"""Redistrict dataframe by groups
Args:
df (pandas.DataFrame): input dataframe
kind (string): identifier of redistrict info (e.g. de/kreise)
group_cols (list): List of colu... | 21f6514ca15d5fff57d03dab9d0bb7693c132e95 | 3,650,897 |
from typing import Tuple
from typing import List
import torch
def count_wraps_rand(
nr_parties: int, shape: Tuple[int]
) -> Tuple[List[ShareTensor], List[ShareTensor]]:
"""Count wraps random.
The Trusted Third Party (TTP) or Crypto provider should generate:
- a set of shares for a random number
... | b16e21be2d421e134866df8929a319a19bdd304a | 3,650,898 |
from typing import Sequence
def text_sim(
sc1: Sequence,
sc2: Sequence,
) -> float:
"""Returns the Text_Sim similarity measure between two pitch class sets.
"""
sc1 = prime_form(sc1)
sc2 = prime_form(sc2)
corpus = [text_set_class(x) for x in sorted(allClasses)]
vectorizer = Tfidf... | 6479ad4916fb78d69935fb9b618c5eb02951f05a | 3,650,899 |
def _feature_properties(feature, layer_definition, whitelist=None, skip_empty_fields=False):
""" Returns a dictionary of feature properties for a feature in a layer.
Third argument is an optional list or dictionary of properties to
whitelist by case-sensitive name - leave it None to include eve... | 482e42a9f4761cd0273dfb4e5f70bdb55ce168d9 | 3,650,900 |
def reverse_search(view, what, start=0, end=-1, flags=0):
"""Do binary search to find `what` walking backwards in the buffer.
"""
if end == -1:
end = view.size()
end = find_eol(view, view.line(end).a)
last_match = None
lo, hi = start, end
while True:
middle = (lo + hi) / 2
... | 7b8d95a987b9b986fb0e334cf3a9bc74014be67d | 3,650,901 |
def formatLookupLigatureSubstitution(lookup, lookupList, makeName=makeName):
""" GSUB LookupType 4 """
# substitute <glyph sequence> by <glyph>;
# <glyph sequence> must contain two or more of <glyph|glyphclass>. For example:
# substitute [one one.oldstyle] [slash fraction] [two two.oldstyle] by onehalf;... | 3804d7c38564459b6f0cf19cbbac5e96642e61a2 | 3,650,902 |
import pathlib
def convert_raw2nc(path2rawfolder = '/nfs/grad/gradobs/raw/mlo/2020/', path2netcdf = '/mnt/telg/data/baseline/mlo/2020/',
# database = None,
start_date = '2020-02-06',
pattern = '*sp02.*',
sernos = [1032, 1046],
... | 16313b1a7abc05fac469d9a0c5003eebb7ef2a8c | 3,650,903 |
import requests
def get_curricula(course_url, year):
"""Encodes the available curricula for a given course in a given year in a vaguely sane format
Dictionary fields:
- constant.CODEFLD: curriculum code as used in JSON requests
- constant.NAMEFLD: human-readable curriculum name"""
curricula =... | 878f2a54e41624887aed720de52dea15bdbf6528 | 3,650,904 |
def conv3x3(in_planes, out_planes, stride=1, groups=1):
"""3x3 conv with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, groups=groups, bias=False) | 4e53568bb4bf88998020b0804770895b67e9e018 | 3,650,905 |
import numpy
def zeros(shape, dtype=None):
"""
Create a Tensor filled with zeros, closer to Numpy's syntax than ``alloc``.
"""
if dtype is None:
dtype = config.floatX
return alloc(numpy.array(0, dtype=dtype), *shape) | 9d1d70f59b585d06623d41c18acc67ec16572307 | 3,650,907 |
from typing import Optional
import types
import numpy
from typing import cast
def station_location_from_rinex(rinex_path: str) -> Optional[types.ECEF_XYZ]:
"""
Opens a RINEX file and looks in the headers for the station's position
Args:
rinex_path: the path to the rinex file
Returns:
... | e7fc390a36f34aed04d30becd544d58ea3f6aa41 | 3,650,908 |
def get_profiles():
"""Return the paths to all profiles in the local library"""
paths = APP_DIR.glob("profile_*")
return sorted(paths) | 729b78daa1d259a227147698a2d4d4c9c5126f29 | 3,650,909 |
def split(array, nelx, nely, nelz, dof):
"""
Splits an array of boundary conditions into an array of collections of
elements. Boundary conditions that are more than one node in size are
grouped together. From the nodes, the function returns the neighboring
elements inside the array.
"""
if l... | 1dbc48402e7124e3384bc56538b05f073fe64370 | 3,650,910 |
def sanitize_app_name(app):
"""Sanitize the app name and build matching path"""
app = "".join(c for c in app if c.isalnum() or c in ('.', '_')).rstrip().lstrip('/')
return app | fca922d8b622baa1d5935cd8eca2ffca050a4c86 | 3,650,911 |
import pathlib
def get_rinex_file_version(file_path: pathlib.PosixPath) -> str:
""" Get RINEX file version for a given file path
Args:
file_path: File path.
Returns:
RINEX file version
"""
with files.open(file_path, mode="rt") as infile:
try:
version ... | c7060e8eb32a0e5539323c7334221d4b1967bb1f | 3,650,912 |
import socket
def get_hm_port(identity_service, local_unit_name, local_unit_address,
host_id=None):
"""Get or create a per unit Neutron port for Octavia Health Manager.
A side effect of calling this function is that a port is created if one
does not already exist.
:param identity_ser... | 6cde426643219f4fc3385a36e3c20503b8c41a9e | 3,650,913 |
def total_length(neurite):
"""Neurite length. For a morphology it will be a sum of all neurite lengths."""
return sum(s.length for s in neurite.iter_sections()) | 854429e073eaea49c168fb0f9e381c71d7a7038a | 3,650,914 |
def _solarize(img, magnitude):
"""solarize"""
return ImageOps.solarize(img, magnitude) | d588068f42930872775e62a619333439d8aa47d8 | 3,650,915 |
def calculateCurvature(yRange, left_fit_cr):
"""
Returns the curvature of the polynomial `fit` on the y range `yRange`.
"""
return ((1 + (2 * left_fit_cr[0] * yRange * ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(
2 * left_fit_cr[0]) | af1cd81c3eeb85297bcfcb44779bf86b4c6b8dc9 | 3,650,916 |
def testing_server_error_view(request):
"""Displays a custom internal server error (500) page"""
return render(request, '500.html', {}) | 84055f37d1ba215ae0e439c1f9d96260208133ff | 3,650,918 |
def main_epilog() -> str:
"""
This method builds the footer for the main help screen.
"""
msg = "To get help on a specific command, see `conjur <command> -h | --help`\n\n"
msg += "To start using Conjur with your environment, you must first initialize " \
"the configuration. See `conjur in... | ecf4167535b5f1e787d286a3b2194816790a7e6a | 3,650,919 |
def sigma_M(n):
"""boson lowering operator, AKA sigma minus"""
return np.diag([np.sqrt(i) for i in range(1, n)], k=1) | 532a082ed5fd3094044162c85042bf963dad4461 | 3,650,920 |
def windowing_is(root, *window_sys):
"""
Check for the current operating system.
:param root: A tk widget to be used as reference
:param window_sys: if any windowing system provided here is the current
windowing system `True` is returned else `False`
:return: boolean
"""
windowing = r... | fd021039686b1971f8c5740beb804826a7afdf80 | 3,650,921 |
def init_columns_entries(variables):
"""
Making sure we have `columns` & `entries` to return, without effecting the original objects.
"""
columns = variables.get('columns')
if columns is None:
columns = [] # Relevant columns in proper order
if isinstance(columns, str):
columns ... | 49a12b0561d0581785c52d9474bc492f2c64626c | 3,650,922 |
from typing import Tuple
def _run_ic(dataset: str, name: str) -> Tuple[int, float, str]:
"""Run iterative compression on all datasets.
Parameters
----------
dataset : str
Dataset name.
name : str
FCL name.
Returns
-------
Tuple[int, float, str]
Solution size, ... | e041cb9c0ca5af98d1f8d23a0e6f3cbe7f5a34a4 | 3,650,923 |
def notch(Wn, Q=10, analog=False, output="ba"):
"""
Design an analog or digital biquad notch filter with variable Q.
The notch differs from a peaking cut filter in that the gain at the
notch center frequency is 0, or -Inf dB.
Transfer function: H(s) = (s**2 + 1) / (s**2 + s/Q + 1)
Parameter
... | a9b4e488bb5a849459bf843abe2bd9d6d18f662d | 3,650,924 |
def Torus(radius=(1, 0.5), tile=(20, 20), device='cuda:0'):
"""
Creates a torus quad mesh
Parameters
----------
radius : (float,float) (optional)
radii of the torus (default is (1,0.5))
tile : (int,int) (optional)
the number of divisions of the cylinder (default is (20,20))
... | 79c7934cabecdf3a4c9c28de7193ccae1ce037de | 3,650,925 |
def check_new_value(new_value: str, definition) -> bool:
"""
checks with definition if new value is a valid input
:param new_value: input to set as new value
:param definition: valid options for new value
:return: true if valid, false if not
"""
if type(definition) is list:
if new_va... | d7204c7501e713c4ce8ecaeb30239763c13c1f18 | 3,650,926 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.