content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def multiplicities(pattern):
""" Return a dictionary keyed by the geodesics in the given pattern, with values equal to the number of times the geodesic occurs."""
g = geodesics(pattern)
ans = {}
x = 0
for i in g:
if i == x:
ans[i] += 1
else:
x = i
... | 24eee8bcb3ce39927d1f60e89216b583e9eb12db | 3,637,400 |
def show_menu():
""" Shows a menu """
print '================== ' + util.HEADER + 'WORKFLOW MENU' + util.ENDC + ' =================='
print '1) Development - Create a git branch off of staging'
print '2) Merge - Merge your development branch to staging (GitHub)'
print '3) Build - Builds project, and... | 27d9733342a4fbbf64bf6635a06329043c843c9d | 3,637,401 |
def imap4_utf7_decode(data):
"""Decode a folder name from IMAP modified UTF-7 encoding to unicode.
Input is bytes (Python 3) or str (Python 2); output is always
unicode. If non-bytes/str input is provided, the input is returned
unchanged.
"""
if not isinstance(data, bytes):
return byte... | 9d0acbc22ce3079cff7849f992e924d9610f1154 | 3,637,402 |
def get_characters(character_path, character_dim):
"""Reads list of characters .txt file and returns embedding matrix and mappings from characters to character ids.
Input:
character_path: path to characters.txt
character_dim: integer
Returns:
emb_matrix: Numpy array shape (len(characters... | 5f523aa15ea03f79cf2fa1a313e6196dbcb1f650 | 3,637,403 |
def create_data_storage(dxres):
"""
Creates a DataStorage record for the given DNAnexus sequencing results.
Args:
dxres: `scgpm_seqresults_dnanexus.dnanexus_utils.du.DxSeqResults()` instance that contains
sequencing results metadata in DNAnexus for the given srun.
Returns:
... | 732ac620f98fa72577c37dfcba7c8f1099399604 | 3,637,404 |
def french_to_english(french_text: str) -> str:
"""This function translates from french to english
Parameters
----------
french_text : str
french text to translate
Returns
-------
str
translated text
"""
language_translator = translator_instance()
response = lan... | 1c2b4d3526394e22251bf68b2d2f035db9b3e5f6 | 3,637,405 |
from pathlib import Path
from typing import Iterable
def prefit_histograms(
rex_dir: str | Path,
samples: Iterable[str],
region: str,
fit_name: str = "tW",
) -> dict[str, TH1]:
"""Retrieve sample prefit histograms for a region.
Parameters
----------
rex_dir : str or pathlib.Path
... | 372a9d223b58473e3a90633b88a8800f7eadeabb | 3,637,406 |
def ymstring2mjd( ymstr ):
"""
The `ymstring2mjd` function enables array input.
Documentation see the `_ymstring2mjd` function.
"""
ymstr = np.array(ymstr,ndmin=1)
ymstr_count = np.size(ymstr)
mjd = np.zeros(ymstr_count,dtype=np.float_)
for ix in range(ymstr_count):
try:
... | 6f20be92833729ac712fe1a89c545d01015d5af2 | 3,637,407 |
def average(l):
""" Computes average of 2-D list """
llen = len(l)
def divide(x):
return x / float(llen)
return list(map(divide, map(sum, zip(*l)))) | 67395ce4417022a673565a8227c684b7649a5e6a | 3,637,408 |
def slugify3(text, delim=u'-'):
"""Generates an ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
result.extend(unidecode(word).split())
return unicode(delim.join(result)) | dbabf44a4681d613d7f7a1a096a32c66640e5185 | 3,637,409 |
from datetime import datetime
def teacher_registeration(request):
"""
Info: Registeration for the teacher.
Request-Body: email_id -> str
password -> str
image -> file
name -> str
date_of_birth -> str
education_qualification ->... | 96152e3c628360d498d497c23c6cd4c6a39a743b | 3,637,410 |
def check_response(response):
""" Checks that a response is successful, raising the appropriate Exceptions otherwise. """
status_code = response.status_code
if 100 < status_code < 299:
return True
elif status_code == 401 or status_code == 403:
message = get_response_data(response)
... | 4afd0003619cc90759778f513e2a692a7b81309d | 3,637,411 |
from typing import Iterator
from typing import Tuple
def walk_storage_from_command(command: instances.FilesRelatedCommand,
filesystem: Filesystem
) -> Iterator[Tuple[str, str, str]]:
"""Typical iteration by command settings."""
return walk(command.st... | 675e476fb2dcd2253181b7b4eeedbf43b58db54f | 3,637,412 |
import logging
def parse_csv_data(csv_filename: FileIO) -> list[str]:
"""Returns contents of 'csv_filename' as list of strings by row"""
try:
return open(csv_filename).readlines()
except FileNotFoundError:
logging.warning("File with path '%s' not found", csv_filename)
return [] | daf826d97a983b8ab3b1ebeb1b063b890c256236 | 3,637,413 |
from typing import Mapping
from typing import Any
import os
def generate_parquet_file(
name: str, columns: Mapping[str, str], num_rows: int, custom_rows: Mapping[int, Mapping[str, Any]] = None
) -> str:
"""Generates a random data and save it to a tmp file"""
filename = os.path.join(tmp_folder(), name + "... | 78f45758a515d36c58999e3988ed9979b6fc493e | 3,637,414 |
import math
def _interpolate_sym(y0, Tkk, f_Tkk, y_half, f_yj, hs, H, k, atol, rtol,
seq=(lambda t: 4*t-2)):
"""
Symmetric dense output formula; used for example with the midpoint method.
It calculates a polynomial to interpolate any value from t0 (time at y0) to
t0+H (time at Tkk... | a8ab6765a2eff3c3a847c79f3524059cca831796 | 3,637,415 |
def _gtin_fails_checksum(gtin: str) -> bool:
"""Determines if the provided gtin violates the check digit calculation.
Args:
gtin: a string representing the product's GTIN
Returns:
True if the gtin fails check digit validation, otherwise False.
"""
padded_gtin = gtin.zfill(14)
existing_check_digit ... | 04d3857fd66e592938fa352be7a59f1784e3e00f | 3,637,416 |
import operator
def mergeGuideInfo(seq, startDict, pamPat, otMatches, inputPos, effScores, sortBy=None):
"""
merges guide information from the sequence, the efficiency scores and the off-targets.
creates rows with too many fields. Probably needs refactoring.
for each pam in startDict, retrieve the g... | 39ea084851f6ba6c1726ed181ac4f3ab10b71472 | 3,637,417 |
def search_orf(seq:str, min_orf:int) -> list:
"""Search full orf over ceration length in 6 frames"""
scod = "M"
send = "*"
orf_regions = {}
# Load 6 reading frames
seq1 = seq
seq2 = seq1[1: ]
seq3 = seq1[2: ]
seq4 = rc_seq(seq1)
seq5 = seq4[1: ]
seq6 = seq4[2: ]
# Shrink ... | 8d4e4c5d18e12aec5511bc06e5f0f532aec6e532 | 3,637,418 |
import json
def getPath():
"""
Gets path of the from ./metadata.json/
"""
with open('metadata.json', 'r') as openfile:
global path
json_object = json.load(openfile)
pairs = json_object.items()
path = json_object["renamer"]["path"]
return path | 03047172e653b4b4aee7f096a67291ad460969c9 | 3,637,419 |
from typing import Optional
def read_ann_h5ad(file_path, spatial_key: Optional[str] = None):
"""
read the h5ad file in Anndata format, and generate the object of StereoExpData.
:param file_path: h5ad file path.
:param spatial_key: use .obsm[`'spatial_key'`] as position. If spatial data, must set.
... | fbe003cd011833b5dad215fd2ae7eea59a58aa8d | 3,637,420 |
def get_token(token_method, acc=None, vo=None, idt=None, pwd=None):
"""
Gets a token with the token_method provided.
:param token_method: the method to get the token
:param acc: Rucio account string
:param idt: Rucio identity string
:param pwd: Rucio password string (in case of userpass auth_typ... | b04a60546e1aefdc2b8a2d2b0b7019f61c11ecc3 | 3,637,421 |
def valid_float_0_to_1(val):
"""
:param val: Object to check, then throw an error if it is invalid
:return: val if it is a float between 0 and 1 (otherwise invalid)
"""
return validate(val, lambda x: 0 <= float(x) <= 1, float,
'Value must be a number between 0 and 1') | 81b92a1f8d3212905c2080d995da65d84916fae9 | 3,637,422 |
def get_usps_data():
"""
"""
trainset = dsets.USPS(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
testset = dsets.USPS(root='./data',
... | 2bb47e25b6d15e4b8a2e597320d9adfee6ff3008 | 3,637,423 |
def logout():
"""
Logs out a user
Returns:
(str): A JWT access token
"""
res = {}
try:
response = jsonify({"msg": "logout successful"})
unset_jwt_cookies(response)
return make_response(response), 200
except Exception as e:
res["data"] = None
r... | 478da4504b2804990f7e2f2c8de7a5578e23b64e | 3,637,424 |
def bm_reduction(mat):
""" Performs the Bloch-Messiah decomposition of single mode thermal state.
Said decomposition writes a gaussian state as a a thermal squeezed-rotated-displaced state
The function returns the thermal population, rotation angle and squeezing parameters
"""
if mat.shape != (2, ... | 1e69f610e885140442cc81d62969e96c69b294b8 | 3,637,425 |
def pinlattice_2ring_full():
"""Full, non-test instance of PinLattice object for testing
Subchannel object"""
n_ring = 2
pitch = 1.0
d_pin = 0.5
return dassh.PinLattice(n_ring, pitch, d_pin) | 8b78274bf7ebe33808885fab24d73aaff6ed17b2 | 3,637,426 |
def dmenu_view_previous_entry(entry, folders):
"""View previous entry
Args: entry (Item)
Returns: entry (Item)
"""
if entry is not None:
text = view_entry(entry, folders)
type_text(text)
return entry | d39cbe86be00563bfd77c2d9254e51df726185db | 3,637,427 |
def unary_to_gast(node):
"""
Takes unary operation such as ! and converts it to generic AST.
javascript makes negative numbers unary expressions. This is our
current workaround.
"""
if node.operator == "-":
return {"type": "num", "value": node.argument.value * -1}
return {
"... | 5cf86896008e38510a8d6133e9f795c76b75a608 | 3,637,428 |
def _norm_intensity(spectrum_intensity: np.ndarray) -> np.ndarray:
"""
Normalize spectrum peak intensities.
Parameters
----------
spectrum_intensity : np.ndarray
The spectrum peak intensities to be normalized.
Returns
-------
np.ndarray
The normalized peak intensities.
... | daba7d3a33ea4baf630332e9528ede82dabe6691 | 3,637,429 |
def axes_to_list(axes_data: dict) -> list:
"""helper method to convert a dict of sensor axis graphs to a 2d array for graphing
"""
axes_tuples = axes_data.items()
axes_list = [axes[1].tolist() for axes in axes_tuples]
return axes_list | fb2e5ef1f2283e2f31e5c8828a3ec7ef94869c5c | 3,637,430 |
from typing import List
def list(
repo_info: str,
git_host: str = DEFAULT_GIT_HOST,
use_cache: bool = True,
commit: str = None,
protocol: str = DEFAULT_PROTOCOL,
) -> List[str]:
"""Lists all entrypoints available in repo hubconf.
:param repo_info:
a string with format ``"repo_owne... | 2b9a635a8ee97ecd46fa47b06b6d872b562d7ceb | 3,637,431 |
from typing import Callable
def repeatfunc(func: Callable, times: Int = None, *args):
"""Repeat calls to func with specified arguments.
Example: repeatfunc(random.random)
:param func: function to be called
:param times: amount of call times
"""
if times is None:
return starmap(func,... | cae37683fd45a66b0ebec6ee0ab5a07d0cb128d7 | 3,637,432 |
from typing import Iterable
import functools
import operator
def prod(values: Iterable[int]) -> int:
"""Compute the product of the integers."""
return functools.reduce(operator.mul, values) | 3f03200078daf1b0b27f777e7744144ab72ec7af | 3,637,433 |
def get_stars_dict(stars):
"""
Transform list of stars into dictionary where keys are their names
Parameters
----------
stars : list, iterable
Star objects
Return
------
dict
Stars dictionary
"""
x = {}
for st in stars:
try:
x[st.name] = ... | 6d627be48a96d8ba93bd13511a05c251f3a3f169 | 3,637,434 |
from typing import Tuple
def initialize_molecular_pos(
key: PRNGKey,
nchains: int,
ion_pos: Array,
ion_charges: Array,
nelec_total: int,
init_width: float = 1.0,
dtype=jnp.float32,
) -> Tuple[PRNGKey, Array]:
"""Initialize a set of plausible initial electron positions.
For each ch... | f9d787bcf24010a81789b3f6f2d65f7ea2582a95 | 3,637,435 |
def urlencode(query, *args, **kwargs):
"""Handle nested form-data queries and serialize them appropriately.
There are times when a website expects a nested form data query to be sent
but, the standard library's urlencode function does not appropriately
handle the nested structures. In that case, you ne... | e73d532d7d4bc6b2534ec2e9224e2ef91074b94e | 3,637,436 |
import scipy
def zca_whiten_np(images, epsilon=1e-6):
"""Whitening the images using numpy/scipy.
Stolen from https://github.com/keras-team/keras-preprocessing/blob/master/keras_preprocessing/image/image_data_generator.py
A good answer on ZCA vs. PCA: https://stats.stackexchange.com/questions/117427/what... | 7937cfc928e5eb04166d789bbdb58f82bd4ecc35 | 3,637,437 |
def set_kernel(kernel, **kwargs):
"""kernelsを指定する
Parameters
----------
kernel : str or :obj:`gpytorch.kernels`
使用するカーネル関数を指定する
基本はstrで指定されることを想定しているものの、自作のカーネル関数を入力することも可能
**kwargs : dict
カーネル関数に渡す設定
Returns
-------
out : :obj:`gpytorch.kernels`
カーネル... | 6ac8e4655ea775233e4470200893039c53e2d3d6 | 3,637,438 |
def holding_period_return(multivariate_df: pd.DataFrame, lag: int, ending_lag: int = 0, skip_nan: bool = False):
"""
Calculate the rolling holding period return for each column
Holding period return for stock = Price(t - ending_lag) / Price(t - lag) - 1
:param multivariate_df: DataFrame
:param lag: ... | d0470a36704d11865323f1b07717f6d433ea59f5 | 3,637,439 |
def _unpack_var(var):
"""
Parses key : value pair from `var`
Parameters
----------
var : str
Entry from HEAD file
Returns
-------
name : str
Name of attribute
value : object
Value of attribute
Examples
--------
>>> var = "type = integer-attribut... | ea23bee3bdddda47c3ab608e41b086e5e8796bc8 | 3,637,440 |
import io
def cmd_ok(packet: Packet, cmd: int,
writer: io.BufferedWriter = None) -> bool:
"""
Returns true if command is okay, and logs if not.
If the command is INCORRECT, a packet is sent to the
client with BAD_CMD command.
"""
ok = True
if packet is None:
... | 296a179b07fb483bb78a15013f0443d2972b19fa | 3,637,441 |
import torch
def get_representation(keypoint_coordinates: torch.Tensor,
image: torch.Tensor,
feature_map: torch.Tensor) -> (torch.Tensor, torch.Tensor):
"""
:param keypoint_coordinates: Tensor of key-point coordinates in (N, 2/3)
:param image: Tensor of curre... | 0373f45121020b868dda2bd84dd650f2a398f635 | 3,637,442 |
async def async_setup(opp: OpenPeerPowerType, config: ConfigType):
"""Set up the System Health component."""
opp.components.websocket_api.async_register_command(handle_info)
return True | 993af39e4f1b59b535f800578df743d1dd27b925 | 3,637,443 |
import requests
def getSoup(url: str, ftrs: str = "html5lib") -> bsp:
"""
Function to extract soup from the url passed in, returns a bsp object.
"""
rspns = requests.get(url)
return bsp(rspns.content, ftrs) | ebd1d0914591b71b38e0977a4cdf86c964afb3c5 | 3,637,444 |
def _fit_HoRT(T_ref, HoRT_ref, a_low, a_high, T_mid):
"""Fit a[5] coefficient in a_low and a_high attributes given the
dimensionless enthalpy
Parameters
----------
T_ref : float
Reference temperature in K
HoRT_ref : float
Reference dimensionless enthalpy
... | a849ef860dd68f32fef012149eb1fc2a594b2691 | 3,637,445 |
import glob
def get_q_k_size(database,elph_save):
"""
Get number of k and q points in the (IBZ) grids
"""
# kpoints
db = Dataset(database+"/SAVE/ns.db1")
Nk = len(db.variables['K-POINTS'][:].T)
db.close()
# qpoints
Nq = len(glob('./elph_dir/s.dbph_0*'))
return Nq,Nk | 7ed941d40e90ba81e505e8f93e135b7cce256167 | 3,637,446 |
def false(feedback, msg, comment, alias_used="false"):
"""
Marks a post as a false positive
:param feedback:
:param msg:
:return: String
"""
post_data = get_report_data(msg)
if not post_data:
raise CmdException("That message is not a report.")
post_url, owner_url = post_data... | 6b894eaa3debbdb8029cd6cd9ab5074f63622b5f | 3,637,447 |
def so3_to_SO3_(so3mat):
"""
Convert so(3) to SO(3)
Parameters
----------
so3mat (tf.Tensor):
so(3)
N x 3 x 3
Returns
------
ret (tf.Tensor):
SO(3)
N x 3 x 3
"""
omgtheta = so3_to_vec(so3mat)
c_1 = near_zero(tf.norm(omgtheta,axis=1))
c_2 ... | 2c8b6e857acb9943e519b0604d9ef47ef80329ab | 3,637,448 |
from typing import Dict
def find_worst_offenders(
all_resource_type_stats: Dict[str, ResourceTypeStats],
version: str,
) -> Dict[str, ResourceTypeStats]:
"""
Finds the resource types with the worst polymorphing and nesting
"""
# find the resource type with the most number of shapes
most_po... | 73a4a8ce2b303f75be544753fde2f74fce8a39b1 | 3,637,449 |
def optimize(nn_last_layer, correct_label, learning_rate, num_classes):
"""
Build the TensorFLow loss and optimizer operations.
:param nn_last_layer: TF Tensor of the last layer in the neural network
:param correct_label: TF Placeholder for the correct label image
:param learning_rate: TF Placeholde... | 587ed3efcc1eb3e8c910a66590e8afd79f80627e | 3,637,450 |
async def all_pairs(factory, weth, dai, wbtc, paused_token):
"""all_pairs set up a very specific arbitrage opportunity.
We want a opportunity that requires less then 2 WETH and provides significant profit as
to be able to separate profit from gas costs. If the numbers do not make sense it is because
th... | be03091afbcc95b6f4a46436881525f6cd4fdb63 | 3,637,451 |
def meeting_point(a, b, window=100, start=0):
"""
Determines the point where the moving average of a meets that of b
"""
cva = np.convolve(a, np.ones((window,))/window, mode='valid')
cvb = np.convolve(b, np.ones((window,))/window, mode='valid')
for x, (val_a, val_b) in enumerate(zip(cva, cvb))... | aa97ab0baed01f36e44dda4f21f6a1b2de3b86d9 | 3,637,452 |
from typing import Dict
from re import T
from typing import Optional
def fixed_dictionaries(
mapping: Dict[T, SearchStrategy[Ex]],
*,
optional: Optional[Dict[T, SearchStrategy[Ex]]] = None,
) -> SearchStrategy[Dict[T, Ex]]:
"""Generates a dictionary of the same type as mapping with a fixed set of
... | b37429efc30989eb180dc39849cfcc2d719af6b1 | 3,637,453 |
def estimate_R0(model, curves: pd.DataFrame, method="OLS", **kwargs) -> ValueStd:
"""
Estimate R0 from epidemic curves and model.
{args}
Returns:
A ValueStd with R0 and its associated standard deviation.
See Also:
naive_R0
OLS_R0
"""
return METHODS_R0[method](model... | 0b2443a2af250871afba542c77d73632dc005dc1 | 3,637,454 |
def get_bone_list(armature, layer_list):
"""Get Bone name List of selected layers"""
ret = []
for bone in armature.data.bones:
if is_valid_layer(bone.layers, layer_list):
ret.append(bone.name)
return ret | 1ed2c4030e962c0bc88119c5e5a18e7e12b49f04 | 3,637,455 |
def clean_packages_list(packages):
"""
Remove comments from the package list
"""
lines = []
for line in packages:
if not line.startswith("#"):
lines.append(line)
return lines | a6c942f9b90c8f6c610ba0b57728f3da48f35ded | 3,637,456 |
import random
def IndividualBuilder(size, possList, probList):
"""
Args:
size (int) - the list size to be created
PossArr - a list of the possible mutations
types (mutation, deletion,...)
ProbArr - a list of the probibilities of the possible
mutations occuring.
... | 055d582fffbc2e13a25a17012831c098fc89330d | 3,637,457 |
def getConfigId(dsn_string, test_data):
"""Returns the integer ID of the configuration name used in this run."""
# If we have not already done so, we query the local DB for the ID
# matching this sqlbench config name. If none is there, we insert
# a new record in the bench_config table and return the newly ge... | 2f0f4581f36e1e50bf5f006ea950b2611c194aeb | 3,637,458 |
import os
def get_file_open_command(script_path, turls, nthreads):
"""
:param script_path: path to script (string).
:param turls: comma-separated turls (string).
:param nthreads: number of concurrent file open threads (int).
:return: comma-separated list of turls (string).
"""
return "%s... | 9d85df723cf6512e876c2c953ab2229f947ef40e | 3,637,459 |
def invert_contactmap(cmap):
"""Method to invert a contact map
:param :py:obj:`~conkit.core.ContactMap` cmap: the contact map of interest
:returns: and inverted_cmap: the contact map corresponding with the inverted sequence (1-res_seq) \
(:py:obj:`~conkit.core.ContactMap`)
"""
inverted_cmap = ... | 6b13bbe75b1184854a2686c12c6ae5f824383cdd | 3,637,460 |
def indexes_with_respect_to_y(Y):
"""
Checks Y and returns indexes with respect to the groups.
Parameters
----------
Y : numpy array like of one single output.
Corresponding to a categorical variable.
Returns
-------
List of indexes corresponding to each group.
"""
catego... | b0ad9062916c3c7d76acf7e699b6a7e7798ac054 | 3,637,461 |
def rrotate(x, disp):
"""Rotate x's bits to the right by disp."""
if disp == 0:
return x
elif disp < 0:
return lrotate(x, -disp)
disp &= 31
x = trim(x)
return trim((x >> disp) | (x << (32 - disp))) | 9ac6a4504de42a7f9f280ae169d523af6a228ce1 | 3,637,462 |
import os
import subprocess
import time
def main(cases_fname):
"""
This method use existing cluster, and then
for a given cluster launches pods (one pod per case),
which are read from input file
"""
if cases_fname is None:
return -1
cfg = read_config("config_cluster.json")
C... | 38f47c1a8ffbfd771e6d03eb95bfe3121a6c9de3 | 3,637,463 |
import os
import sys
def setup_parameters():
"""
This function sets up the hyperparameters needed to train the model.
Returns:
hyperparameters : Dictionary containing the hyperparameters for the model.
options : Dictionary containing the options for the dataset location, augmentation, etc.
... | 0e3c0e30618062b6c3b7b252a714a5dab2b09cba | 3,637,464 |
import logging
import copy
def search_for_start ( r, X, w0, applythreshold, hf0, pm=(.85,.93,1.,1.07,1.15), storeopt=False, modulation=False, doublemodulation=False):
"""Search for starting values
:Parameters:
*d*
data set
*w0*
coarse starting values
*pm*
... | d9a28ff06992624a3d60fcbe6e7f483281c7a12d | 3,637,465 |
def point_sample(input, points, align_corners=False, **kwargs):
"""
A wrapper around :func:`grid_sample` to support 3D point_coords tensors
Unlike :func:`torch.nn.functional.grid_sample` it assumes point_coords to
lie inside ``[0, 1] x [0, 1]`` square.
Args:
input (Tensor): Feature map, sha... | 31e5d19c1eff260d337b4eee65b4eed08a1e070b | 3,637,466 |
import sys
def compareStringsWithFloats(a,b,numTol = 1e-10, zeroThreshold = sys.float_info.min*4.0, removeWhitespace = False, removeUnicodeIdentifier = False):
"""
Compares two strings that have floats inside them. This searches for floating point numbers, and compares them with a numeric tolerance.
@ In, ... | edeb450dcc33802b0bfdb56a1870faa49c834ce5 | 3,637,467 |
from typing import Any
import time
def login_render(auth_url: str) -> Any:
"""Return login page.
Arguments:
auth_url {str} -- Link to last.fm authorization page.
"""
return render_template("login.html", auth_url=auth_url, timestamp=time()) | a1569ac51d6ce38feba6d263e03404a4af9ee566 | 3,637,468 |
import os
def save_image(file_path, mat, overwrite=True):
"""
Save 2D data to an image.
Parameters
----------
file_path : str
Path to the file.
mat : int or float
2D array.
overwrite : bool
Overwrite the existing file if True.
Returns
-------
str
... | af003972c874aafa2cfd776c3950a6b2c082e378 | 3,637,469 |
def receive_consensus_genome(*, session):
"""
Receive references to consensus genomes.
POST receiving/consensus-genome with a JSON body
"""
document = request.get_data(as_text = True)
LOG.debug(f"Received consensus genome")
datastore.store_consensus_genome(session, document)
return "... | 5e76dd7639298cd63a2b185530b53bff5e42ca7f | 3,637,470 |
def get_genres_from_games(games, their_games):
"""
From the games we will get the same genres
"""
genres = set()
for d in games:
n = d['id']
if n in their_games:
genres.add(d['Genre'])
return genres | 27bbf3c5ba40c6443e12b4119943c40879ceb622 | 3,637,471 |
def webfinger(request):
"""
A thin wrapper around Bridgy Fed's implementation of WebFinger.
In most cases, this view simply redirects to the same endpoint at Bridgy.
However, Bridgy does not support the ``mailto:`` and ``xmpp:`` resource
schemes - quite reasonably, since there's no possible way to ... | 86b9f28cc49fd3a253ad916a426385394ae8fed3 | 3,637,472 |
import requests
def send_to_teams(url, message_json, debug):
""" posts the json message to the ms teams webhook url """
headers = {'Content-Type': 'application/json'}
r = requests.post(url, data=message_json, headers=headers)
if r.status_code == requests.codes.ok:
if debug:
print('... | 5acfadd74b4f3df6bd3ec034a9153674c174c71b | 3,637,473 |
import pathlib
import platform
import os
def get_candidate_dir():
"""
Returns a valid directory name to store the pictures.
If it can not be determined, "" is returned.
requires:
import os
import pathlib
import platform
https://docs.python.org/3/library/pathlib.html#pathl... | 48353d226da4a6fdc4ca3208118b01c406e00dfb | 3,637,474 |
def inflection_points(points, rise_axis, run_axis):
"""
Find the list of vertices that preceed inflection points in a curve. The
curve is differentiated with respect to the coordinate system defined by
`rise_axis` and `run_axis`.
Interestingly, `lambda x: 2*x + 1` should have no inflection points, ... | c0044d0a46bc286c0b827fd557bdba74a07812a0 | 3,637,475 |
def compile(raw_model):
"""Compile a raw model.
Parameters
----------
raw_model : list of dict
A raw GPTC model.
Returns
-------
dict
A compiled GPTC model.
"""
categories = {}
for portion in raw_model:
text = gptc.tokenizer.tokenize(portion['text'])
... | 87607fdccac51acf367f0d7722b20ee8795f866b | 3,637,476 |
def get_elements_html_by_attribute(*args, **kwargs):
"""Return the html of the tag with the specified attribute in the passed HTML document"""
return [whole for _, whole in get_elements_text_and_html_by_attribute(*args, **kwargs)] | 726a3a6b8753fd6513f4860393076c9e3298a390 | 3,637,477 |
def patched_requests_mocker(requests_mock):
"""
This function mocks various PANOS API responses so we can accurately test the instance
"""
base_url = "{}:{}/api/".format(integration_params['server'], integration_params['port'])
# Version information
mock_version_xml = """
<response status = ... | 828425e11e38468ab2aacef397b6375c0ec65d6a | 3,637,478 |
def validate(model, model_name: str, dataloader_valid, class_weights, epoch: int,
validations_dir: str, save_oof=True):
"""
Validate model at the epoch end
Input:
model: current model
dataloader_valid: dataloader for the validation fold
device: CUDA or CPU
... | d9e1b172b9c28f30b80e43969cb39b4b1054a4b6 | 3,637,479 |
def shared_empty(dim=2, dtype=None):
"""
Shortcut to create an empty Theano shared variable with
the specified number of dimensions.
"""
if dtype is None:
dtype = theano.config.floatX
shp = tuple([1] * dim)
return theano.shared(np.zeros(shp, dtype=dtype)) | d199a069b4a47eeb97f2a87b6c35ed797764eb9f | 3,637,480 |
def add_kwds(dictionary, key, value):
"""
A simple helper function to initialize our dictionary if it is None and then add in a single keyword if
the value is not None.
It doesn't add any keywords at all if passed value==None.
Parameters
----------
dictionary: dict (or None)
A dictio... | 96aa104f86e521e419d51096b6c1f86e4b506c57 | 3,637,481 |
def parse_private_key(data, password):
"""
Identifies, decrypts and returns a cryptography private key object.
"""
# PEM
if is_pem(data):
if b"ENCRYPTED" in data:
if password is None:
raise TypeError("No password provided for encrypted key.")
try:
... | dd664a390ba2db49039067de98ee95a87eaf4736 | 3,637,482 |
def _get_cindex(circ, name, index):
"""
Find the classical bit index.
Args:
circ: The Qiskit QuantumCircuit in question
name: The name of the classical register
index: The qubit's relative index inside the register
Returns:
The classical bit's absolute index if all regi... | 340105a2ddfe5fb2527171a7592390c9dd2937e5 | 3,637,483 |
def get_bin(pdf: str) -> str:
"""
Get the bins of the pdf, e.g. './00/02/Br_J_Cancer_1977_Jan_35(1)_78-86.tar.gz'
returns '00/02'.
"""
parts = pdf.split('/')
return parts[-3] + '/' + parts[-2] + '/' | a1e25162b8a353f508667ccb4fc750e51fcf611d | 3,637,484 |
def to_symbol(text):
"""Return the corresponding string representing the websites.
:param str text: TODO
:returns: TODO
"""
text = text.upper()
if text in ("BGM", "BANGUMI"):
return "bgm"
elif text in ("MAL", "MYANIMELIST"):
return "mal"
else:
return None | c602c7d88574f95cb9c31946963748aca0eb9add | 3,637,485 |
def burkert_density(r, r_s, rho_o):
"""
Burkert dark matter density profile
"""
x = r / r_s
density = rho_o / ( (x) * (1.0 + x)**2)
return density.to('g/cm**3') | 8293a62b6c52c65e7c5fe7c676fd3807f301e40b | 3,637,486 |
def send_file(path):
"""
Route for file downloads
"""
# If the document path has a tilde, expand it
path_prefix = expanduser(DOCUMENT_DIRECTORY_PATH)
return send_from_directory(path_prefix, path) | 9c11acd930c7bc3851421e70b4822ac8efbc7c05 | 3,637,487 |
def locations__single(request, location_id: int):
"""
Renders the locations page, when a single location has been selected.
"""
context = {'geolocation': request.session.get('geolocation'),
'location_error': request.session.get('location_error')}
try:
location_id = validat... | 0b7ab51fe021a677ca87aecde1a9981095ef56ff | 3,637,488 |
def page_not_found(e):
"""
Application wide 404 error handler
"""
return render_template('404.html',
base_template=appbuilder.base_template,
appbuilder=appbuilder), 404 | a1c146b4d782a35d45ec0f351d12e09cdff9be1a | 3,637,489 |
def licols(A, tol=1e-10):
"""
Extracts a linearly independent set of columns from a given matrix A.
Solution found at https://nl.mathworks.com/matlabcentral/answers/108835-how-to-get-only-linearly-independent-rows-in-a-matrix-or-to-remove-linear-dependency-b-w-rows-in-a-m
:param A: matrix
:param to... | 96c15e65c7e12dc86342642c2b6cc1e147430cb4 | 3,637,490 |
import os
def GetArchivePath ():
"""Return the archive path as defined by the L{PathEnvironmentVariable},
or C{None} if that variable is not defined."""
return os.environ.get(PathEnvironmentVariable) | a79babf2991d081d6ce209272b84c70208c6049e | 3,637,491 |
def area_description(area,theory_expt):
""" Generate plain-language name of research area from database codes.
"""
area_name_by_area = {
"As" : "Astrophysics",
"BP" : "Biophysics",
"CM" : "Condensed matter",
"HE" : "High energy",
"NS" : "Network science",
... | d7743c2d80d9a74dd6a24f735b7c0a389eb36468 | 3,637,492 |
def parse_username_password_hostname(remote_url):
"""
Parse a command line string and return username, password, remote hostname and remote path.
:param remote_url: A command line string.
:return: A tuple, containing username, password, remote hostname and remote path.
"""
assert remote_url
... | 50410ad87865559af84b83ab6bdfae19e536791d | 3,637,493 |
def _random_inverse_gaussian_no_gradient(shape, loc, concentration, seed):
"""Sample from Inverse Gaussian distribution."""
# See https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution or
# https://www.jstor.org/stable/2683801
dtype = dtype_util.common_dtype([loc, concentration], tf.float32)
concentratio... | 6ce80d87c4350e7816fcd50956639906bdf7244e | 3,637,494 |
import sys
def optParse():
"""Parses commandline options."""
parser = OptionParser(prog=__applicationName__, version="%prog " + __version__)
parser.set_usage("%prog [options] filename")
parser.add_option("--autobrief",
action="store_true", dest="autobrief",
help="use the docstring summary line as \\brief des... | cea9007efa60d75deea21d5458dee4da2139c15f | 3,637,495 |
from pathlib import Path
def resolve(path):
"""
fully resolve a path:
resolve env vars ($HOME etc.) -> expand user (~) -> make absolute
Returns:
pathlib.Path: resolved absolute path
"""
return Path(expandvars(str(path))).expanduser().resolve() | cc75751421206450f551617d558ec000d54ba54f | 3,637,496 |
def sas_2J1x_x(x):
"""return 2*J1(x)/x"""
if np.isscalar(x):
retvalue = 2*sas_J1(x)/x if x != 0 else 1.
else:
with np.errstate(all='ignore'):
retvalue = 2*sas_J1(x)/x
retvalue[x == 0] = 1.
return retvalue | 286dfb2c4df4120ff232e347f2381023a0bdaf40 | 3,637,497 |
def get_cross_matrix(vec: ndarray) -> ndarray:
"""Get the matrix equivalent of cross product. S() in (10.68)
cross_product_matrix(vec1)@vec2 == np.cross(vec1, vec2)
Hint: see (10.5)
Args:
vec (ndarray[3]): vector
Returns:
S (ndarray[3,3]): cross product matrix equivalent
"""
... | 2e95611fbe2bbd5ae6a94e490345e0d19c3a5e61 | 3,637,498 |
from typing import Tuple
from typing import Set
def apply_proteomics_elastic_relaxation(
original_model: Model,
objective_rule: Objective_rule = Objective_rule.MIN_ELASTIC_SUM_OBJECTIVE,
) -> Tuple[Model, Set]:
"""Relax the problem by relaxing the protein concentration constraints.
The relaxed proble... | d2dd9fa8f179535cf1a8e4dcb9abb8fbf1ce5633 | 3,637,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.