content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_cnv_report(adapter: MongoAdapter, report_path: str, case_id: str, update: bool = False):
"""Load a CNV report into a case in the database
If the report already exists the function will exit.
If the user want to load a report that is already in the database
'update' has to be 'True'
Args:
... | 2c866cf9152d0f57be749b31e70d629d5f919875 | 75,976 |
import click
def name_argument(func):
"""Add a machine name argument."""
def _callback(ctx, unused_param, value):
if not value:
return ctx.obj['config'].get_selected()
return value
return click.argument('name', metavar='NAME', default='', callback=_callback)(func) | 39e82c4836c196d48a29b370a9bd5310927d5da1 | 75,977 |
def role_ls_cmd(api: ZoeAPI, args):
"""List available roles."""
def b2t(val):
"""Boolean to text."""
if val:
return "Yes"
else:
return "No"
filters = {}
if args.name is not None:
filters['name'] = args.name
roles = api.role.list(filters)
t... | 1058a55b5bb04c7eb007d1ed7d1b25b8471efd14 | 75,978 |
def lowPrimeFact_near(n, pmax=31, nmin=None, evens_only=True):
"""
Find the nearest integer to `n` with prime factors all less than
`pmax`.
This routine is used to change the length of arrays to speed-up
Fast Fourier Transforms.
Parameters
----------
n : int
The start... | 57bc73aab58d1cf4820b51f0528886b2bee61ec0 | 75,979 |
def get_all_mentioned_users(message: discord.Message):
"""
Returns a set of all user ids mentioned in a message
:param message: discord.Message - The message with mentions
:return: set
"""
mentioned_users = set()
everyone = contains_everyone(message.content)
here = contains_here(messag... | ea80dc55eb8664c90506382850e95d56f7df7528 | 75,980 |
import re
import itertools
def key_ranges(keys):
"""Take a list of keys and convert them to a compact
output string.
E.g. foo100, foo101, ..., foo200, foo300
becomes
foo[100..200], foo300
"""
keys.sort()
last_digits_re = re.compile("^(?P<pre>()|(.*[^\d]))(?P<digits>\d+)"
... | 58557b771d1062647290ebc964f4557cadaebf86 | 75,981 |
def get_disk_type(path):
"""Retrieve disk type (raw, qcow2, lvm) for given file."""
if path.startswith('/dev'):
return 'lvm'
elif path.startswith('rbd:'):
return 'rbd'
return images.qemu_img_info(path).file_format | 9e227cbbcbda899689cb3206a7ff751374408256 | 75,982 |
from typing import OrderedDict
from pathlib import Path
def bids(
root=None,
datatype=None,
prefix=None,
suffix=None,
subject=None,
session=None,
include_subject_dir=True,
include_session_dir=True,
**entities,
):
"""Helper function for generating bids paths for snakemake workfl... | 0b90a7b4c0ed4b1e6cd392823446f00f9b21b33d | 75,983 |
def tag_special_ingredients(dish):
"""
:param dish: tuple of (str of dish name, list of dish ingredients)
:return: tuple of (str of dish name, set of dish special ingredients)
Return the dish name followed by the `set` of ingredients that require a special note on the dish description.
For the pur... | 9caa38005aac0b49a938814a987f75975993dc90 | 75,984 |
def get_model(cfg):
"""
Get network model.
"""
model = PointNetClassification(
cfg.dataset.num_classes,
cfg.model.use_input_transform,
cfg.model.use_feature_transform
)
model.to(cfg.general.device)
return model | e4f82e791ec60b259db31439a054a99d641db151 | 75,986 |
def sympy_newer_than(version):
"""Returns true if the installed version of SymPy is newer than the
provided version string."""
return parse_version(SYMPY_VERSION) > parse_version(version) | b3b6c815c1e4fc356e66c54e66792238d000a726 | 75,987 |
def clean_image_data(imdata, metadata):
"""
clean up 4d-tensor of imdata consistently (fix contrast, move upside up, etc...)
:param imdata:
:return:
"""
# normalize contrast
flat_data = np.concatenate([i.flatten() for i in imdata]).flatten()
high = np.percentile(flat_data, 95.0)
low... | c44272efd59f102728875ab4042490d4b2a97894 | 75,988 |
import base64
def base64_url_decode(inp):
"""
Base64 decode.
"""
padding_factor = (4 - len(inp) % 4) % 4
inp += "="*padding_factor
return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/')))) | 3f97b495b4868d6cfc4a715ef02575648537283a | 75,989 |
def blur(img):
"""
:param img: (SimpleImage) The original image that has not been blurred
:return: (SimpleImage) The new image that has been blurred
"""
clear = img
blurred = SimpleImage.blank(clear.width, clear.height)
for y in range(clear.height):
for x in range(clear.width):
... | 6c522b31e65c1ad2dba10af45a95ea4e33591a49 | 75,990 |
import json
import requests
def main(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.... | a38d88c4688b14bf11be5fd4d770c6c910da722b | 75,991 |
from typing import Optional
from typing import Tuple
from typing import Union
import torch
def data_split(X_train: np.ndarray,
y_train: np.ndarray,
test_size: float = 0.15,
random_state: int = 1,
channel: Optional[str] = None,
format_out: str ... | 860e6f8653ca17a14ec3e57a895f4fdb21689b53 | 75,992 |
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrab... | 56fcaab107a2bc232e9357e4f2e8c1da0699d1a1 | 75,993 |
def maximum(lst):
"""(list) -> int
Computes the maximum element in a list of integers
"""
return 0 | 645ffb1dede15e1848eec67f581e23ef6a071233 | 75,994 |
def person_search():
"""
Person REST controller
- limited to just search_ac for use in Autocompletes
- allows differential access permissions
"""
# Filter to just Volunteers
s3.filter = s3base.S3FieldSelector("human_resource.type") == 2
# Only allow use in the search_ac met... | 06890cb77d405510af2c610fd9462cd8e5781a3f | 75,995 |
def get_scoped_session():
"""Return a scoped session
According to SQLAlchemy docs, this returns always the same object within a thread, and a different object in a
different thread. Moreover, since we update the session class upon forking, different session objects will be used.
"""
global SCOPED_S... | 940fe9671f50a366be17b3eeb5ff719d4ec4e462 | 75,997 |
def adjust_index_pair(index_pair, increment):
"""Returns pair of indices incremented by given number."""
return [i + increment for i in index_pair] | 43968980998f6d12457e922c3c70d2ceba6d6b2e | 75,998 |
def _var(x, keepdims=False, axis=None, ddof=0):
"""Defines variance without using abs. Permits use of
complex-step numerical derivative."""
x = np.asarray(x)
def mean(y, keepdims=False, axis=None, ddof=0):
if isinstance(axis, int):
axis = (axis,)
N = y.size if axis is None e... | ff08e94ebae322660eba5bf255a1c01e73e044b2 | 75,999 |
import json
def generate_verification_token(data):
""" It generates a email verification token """
token = serializer.dumps(json.dumps(data))
return token | 008316e39fecaeedd660dc22ae75637fff606d12 | 76,000 |
import base64
def main():
"""
Main function of the program
:return:
"""
model = load_model_pickle('knn')
transform = load_transformations_pickle('MinMax')
input_data, result = side_menu(model, transform)
if result is not None:
# Visualize the result
result_string = ... | b760e8858e514497260d1797cb3de9350b384298 | 76,001 |
def calculate_2d_projections(coordinates_3d, intrinsics):
"""
Input:
coordinates: [3, N]
intrinsics: [3, 3]
Return
projected_coordinates: [N, 2]
"""
projected_coordinates = intrinsics @ coordinates_3d
projected_coordinates = projected_coordinates[:2, :] / projected_coor... | 2999e547b26612ad0fcf261647e89a886ec05aac | 76,002 |
def nonzero_batch_rmse(y_true, y_pred):
"""RMSE that ignores zero values and averages over a batch, assuming
that there is at least one nonzero value per batch.
"""
return K.sqrt(nonzero_batch_mse(y_true, y_pred)) | d5631e2dcce397e2957c47908c2df67a340533fb | 76,003 |
def paragraph_detokenizer(sentences, breaks):
"""Restore original paragraph format from indexes of sentences and newlines
Args:
sentences (list): List of sentences
breaks (list): List of indexes of sentences and newlines
Returns:
text (str): Text with original format
"""
ou... | fbba0099326156bff3ba5d76dfb3b9bc197c3269 | 76,004 |
def sample_from_simplex(n, dim=3, vmin=0.):
"""Samples random points from a k-simplex.
See Donald B. Rubin (1981) "The Bayesian Bootstrap", page 131.
Args:
n: Number of points that are sampled.
dim: Dimension of the points to be sampled, e.g. dim=3 samples points from
the 2-simplex.
vmin: Mini... | 091b8bce459d38cdbfca90b2c71670f80ec13bba | 76,005 |
def is_start_with_vowel(string):
"""判断一个字符串是不是元音开头
:param string: Str
"""
if string[0] in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'):
return True
return False | 902a893eae5a554e530127ba43bc79ea977da6f7 | 76,006 |
from typing import Sequence
import site
def get_IM_params(
im: IM,
imdb_ffps: Sequence[str],
site_info: site.SiteInfo,
ensemble: gm_data.Ensemble = None,
):
"""Retrieves the IM parameters (i.e. mean and sigma) for the
specified IM and returns it as dataframe with columns mu & sigma"""
im_d... | 47de0d70c94c3ebd0939baecd4a9a16cc352f2b3 | 76,007 |
from datetime import datetime
def percentiles(raster_path:str, percentiles:list = [10,90], binwidth:int = 10, n_cores:int = 1, block_scale_factor:int = 8, default_block_size: int = 256, time:bool = False) -> list:
"""Function that approximates percentiles of a raster, leveraging multiple cores
***
Parameters
--... | 6dada621f6771b2cc556266d9ca0451c51898033 | 76,008 |
def ansi(code):
"""Conditionally return ANSI-escaped codes."""
return '\033[' + code if HAS_ANSI else code | 54a21ee862815178ad340d727216b3357eefb120 | 76,009 |
def custom_lineplot(ax, x, y, error, xlims, ylims, color='red'):
"""Customized line plot with error bars."""
ax.errorbar(x, y, yerr=error, color=color, ls='--', marker='o', capsize=5, capthick=1, ecolor='black')
ax.set_xlim(xlims)
ax.set_ylim(ylims)
return ax | f80b76b8f9f60a44bf62bc64829c40793747ada2 | 76,010 |
def load_kitti_raw_intrinsics(file_name, new_h, new_w):
"""Load kitti raw data intrinscis
Args:
file_name (str): txt file path
Returns:
params (dict): each element contains [cx, cy, fx, fy]
"""
raw_img_h = 370.0
raw_img_w = 1226.0
intrinsics = {}
with open(file_name... | 2d2fd5aaad0f331272c295dc790ec9099ba6b4a3 | 76,011 |
def generate_role_with_colon_format(content, defined_role, generated_role):
"""Generate role data with input as Compute:ComputeA
In Compute:ComputeA, the defined role 'Compute' can be added to
roles_data.yaml by changing the name to 'ComputeA'. This allows duplicating
the defined roles so that hardware... | a303bf17a8416b2b4df410095d76faaa7d2466ca | 76,012 |
def make_cigar(seq, mature):
"""
Function that will create CIGAR string from aligment
between read and reference sequence.
Args:
*seq(str)*: read sequence.
*mature(str)*: short sequence.
Return:
*short(str)*: CIGAR string.
"""
cigar = ""
for pos in range(0, len... | 55832e5dd7e3246a94e7cf8d9ad9b2511758be00 | 76,013 |
def user_settings(user_id: int) -> ResponseType:
"""
Show and process a form to edit a user's settings.
:param user_id: The ID of the user whose settings will be managed.
:return: The response for this view.
"""
user = User.load_from_id(user_id)
if user is None:
abort(4... | 6df3c5fa607fcba8cec61a3bf3c5eb31d4c581f7 | 76,014 |
def draw_waterfall(df, ax=None, stocks=[0], **kwargs):
"""Draw waterfall chart
`stocks` parameter is for specifying column indexes of `df` that are to
be interpreted as stock items as opposed to flow items,
i.e. bars for these columns are drawn from zero.
"""
if ax is None:
plt.figure(... | 15403253ed6632d62b621dfacfe3c8383d189484 | 76,015 |
def validate_subnet_list_or_none(data, key_specs=None):
"""Validate data is a list of subnet dicts or None.
:param data: The data to validate.
:param key_specs: Not used!
:returns: None if data is None or a valid list of subnet dicts, otherwise
a human readable message as to why the data is inv... | 2ee15812f306c42cb15b3c41d2a94393e9a8a682 | 76,016 |
def param(name, *args, **kwargs):
"""
A wrapper for `tf.Variable` which enables parameter sharing in models.
Creates and returns theano shared variables similarly to `tf.Variable`,
except if you try to create a param with the same name as a
previously-created one, `param(...)` will just return the ... | ccd70f8756e3a96809b0c5bc28a49d7d6cea1ae0 | 76,018 |
from inspectparser import parseInspect
def weightedMatrix(spectra_name, dbList, fdr=0.05, init_weight=0, Tide=False, decoy_tag="REVERSED|DECOY", verbose=True):
"""
Based on InsPecT output (or output parsed by inspectparser)
for dataset and all proteomes, construct a weighted similarity matrix
(return: proteome si... | 9b64f24b8d412483cb02ea9ccb5b5470c6772a27 | 76,019 |
import ctypes
def get_window_pos(window):
"""
Retrieves the position of the client area of the specified window.
Wrapper for:
void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);
"""
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_i... | d7b612b03d4aae11e172e9005a1d24f86ca7249a | 76,022 |
from torchvision.ops import roi_align as torch_roi_align
from typing import List
import torch
def RoiAlign_forward(op: Operation, values: List[torch.Tensor], ctx: TorchBackendContext = None, **kwargs) -> torch.Tensor:
"""Region of Interest (RoI) align operation described in the Mask R-CNN
paper. RoiAlign cons... | 01c66350e063aafe333f7ce5fd9b1dafdcabd5c2 | 76,023 |
import ctypes
def logi_led_get_config_option_bool(key, default=False):
""" get the default value for the key as a bool. if the call fails, the return value is None.
for example, check if the effect is enabled:
logi_led_get_config_option_bool('health/pulse_on_low', True) """
if led_dll:
... | 00d9ad156011fb125b4a6e7a69ae2f4cd7c7cc67 | 76,024 |
def nb_state_marginals_10_log(p0s, t_mat, terminal_state_mask, rs, max_path_length):
"""Compute state marginals using Ziebart's 2010 algorithm
This algorithm is designed to compute state marginals for an un-discounted MDP with
state-feature reward basis functions.
Args:
p0s (numpy arra... | 814d9c85e30b559ff7c2e81940a7a034e81f66b4 | 76,025 |
def upper(row, index):
"""Convert ``row[index]`` to upper case.
"""
return _read_value(row[index]).upper().strip() | e73717dd4fe5dee543416d354f7673d1735495be | 76,026 |
import re
def split_at_comma_semi(text, extra=()):
"""Splits the text at commas and semicolons, unless they are inside
parenthesis."""
assert isinstance(text, str)
assert isinstance(extra, (list, tuple))
lst = []
paren_cnt = 0
bracket_cnt = 0
ofs = 0
parts = []
split_re = r"[][... | 6ab486c19bf5a93b03d782ae8b576083bfa5b35c | 76,028 |
def tabela_user():
"""
Função que tem como objetivo a criação da tabela usuario
"""
tab_user = conexao_bd()
# ACESSA O BANCO BD_AGENDA
tab_user.execute('USE BD_AGENDA')
# Cria uma tabela chamada de USUARIO no Banco BD_Agenda
tab_user.execute("CREATE TABLE USUARIO("
... | cbdc7385f65440e59dc5b877d7d3fcdee06f5aa0 | 76,029 |
import locale
def decode_byte_str(byte_str):
"""
Decodes byte string into unicode string.
Args:
byte_str(byte): Byte string.
Returns:
Unicode string.
"""
# first try to decode with utf-8 and if that fails try with system default
for encoding in ("utf-8", locale.getprefer... | 1ae790ef9fee9ce5053f55e1d8757a4a385dc56d | 76,031 |
import torch
def execute_epoch(network, training_data_loader, validation_data_loader, optimiser, scheduler,
best_validation_loss, best_epoch, model_save_path):
"""
Wrapper to execute one epoch including a training step, a validation step and relevant logging.
"""
training_loss_dict =... | a8399e10ac0c3b48fd970fc3940b73919385778b | 76,033 |
def disp_to_pos(disp,cen_x,cen_y,psi):
"""
Calculates source position in camera coordinates(x,y) from "disp_"
distance.
For now, it only works for POINT GAMMAS, it doesn't take into
account the duplicity of the disp method.
Parameters:
-----------
disp: float - disp distance
ce... | 393ead72954a3b59052fc709078bd6ec577204e5 | 76,034 |
def count_af(substitution_matrix, variant_df, subject_lst, subject_headers):
"""
Calculate substitution matrix, not normalized.
:param substitution_matrix: empty DataFrame which will contain summed substitution frequencies
:param variant_df: DataFrame which contains aggregated variant information: for e... | 28265035708277d7c09fcf64d7ad7a0c31fdd28a | 76,035 |
def nplog(arr: np.array, eps: float = 1e-30, verbose: bool = False) -> np.array:
"""
:math:`C^2` extension of :math:`\\ln(a)` below `eps`
:param np.array arr: a Numpy array
:param float eps: lower bound
:return: :math:`\\ln(a)` :math:`C^2`-extended below `eps`
"""
if np.min(arr) > eps:
... | 3e64e8283bb8c153a261f1cd99e6f3ecffb464db | 76,036 |
from typing import Sequence
from typing import Tuple
from typing import Pattern
from typing import Callable
from typing import Any
def build_result_transformer(
column_transformations: Sequence[Tuple[Pattern[str], Callable[[Any], Any]]],
) -> Callable[[Result], None]:
"""
Builds and returns a function tha... | 51886cda14dec3a73de2a4f9d78c802d0c162fd0 | 76,037 |
def partition_on_key(pred, d):
"""Partition the dict according to a predicate on the keys.
Returns a tuple of two dicts:
The first dict contains all elements that satisfy the predicate,
the second all elements that fail the predicate."""
f = lambda k, v: bool(pred(k))
p = partition(f, d)
ret... | a3b561cb12656db2637085d8bdac6b96d9359040 | 76,038 |
import struct
def _eight_byte_real_to_float(value):
"""
Convert a number from GDSII 8 byte real format to float.
Parameters
----------
value : string
The GDSII binary string representation of the number.
Returns
-------
out : float
The number represented by ``value``.... | eaa823caa69e643fe8fc497adc31f9506a0c71c5 | 76,039 |
def parse_github_url(url):
""" Parse a github url and return hostname, Org, repo, PR or isue id"""
if url is None or len(url.strip()) == 0:
return None, None, None, None
url = url.strip()
parsed_url = urlparse(url)
path_list = parsed_url.path.split('/')
hostname = parsed_u... | 0489edeb556d37b92eafb7e415bd50b64b6ae5cc | 76,040 |
import signal
def harris_matrix(img, size):
"""Compute harris matrix from image with given window size.
Args:
img: np.ndarray, [H, W], gray scale image.
size: int, size of the window.
Returns:
np.ndarray, [H - size + 1, W - size + 1, 2, 2], harris matrix.
"""
# [H, W]
d... | 9882fa83a9e14ad52b02c31b53e343da5d42f414 | 76,041 |
def depth_first_search(graph, node):
"""
Starting with a given node, the graph is serached for all connected nodes.
It is depth first because the nodes that are most recently discovered are
then analyzed to find more connected nodes.
Parameters
----------
graph : 2d binary ndarray
... | 61aa4c05687ae322888c75b72e534beab9c453ed | 76,044 |
def algorithms() -> SearchStrategy: # DigestAlgorithm
"""
Strategy that generates digest algorithms.
"""
return sampled_from(DigestAlgorithm) | ac038da8f38cfed3489158455f37f6881e0e9a78 | 76,045 |
import re
def find_tilesets(page_text):
"""
This method uses a simple heuristic to extract tileset info from a page's text.
Specifically, it looks at the tileset template.
:param page_text: The Wiki markup of a page.
:return: A list of image names.
"""
global min_tile_size
# Reformat... | 5a080ca8fe5894e73aafe866d11b01f3a691f165 | 76,046 |
def cont_raw(npoints, elecs, start_timestamp=0):
"""
Retrieve raw data (sampled at 30 kHz).
Returns a tuple of (timestamp, data) where the timestamp is that of the
first data, and data is a list of data points. If start_timestamp is not
specified, the output timestamp is always 0.
Args:
... | 5426500eaa0db940ab87fd23d6cf71339278bdef | 76,048 |
def getPartCharFunc1_Python(partDHisto, key, paramProd, rArray, drPrime, delta):
"""Calculates intra-atom contributions.
"""
partCF = np.zeros((len(rArray), 2))
partCF[:, 0] = rArray[:]
param = paramProd[key]
elements = key.split(",")
NMean = partDHisto[key][0, 1]
# print "NMean("+key+")... | d18de181b5a04117c01e90b04db09fc97f2d5820 | 76,050 |
def _GetCalendarService(refresh_memcache=False):
"""Create gdata calendar service with a valid session id.
Creates a gdata calendar service. Uses session key from memcache when
available. On a memcache miss, loads the session key from datastore. Tries to
return a usable calendar service and None if it fails to... | cabc63fa8adf5b10ba5263c0055faec01fcce890 | 76,051 |
def _validate_host(func):
"""Content"""
@wraps(func)
def inner(self, *args, **kwargs):
if not self.host:
raise AttributeError("An 'host' attribute has not been defined.")
return func(self, *args, **kwargs)
return inner | 1514f24a8e5088bf06016ff5bb19a7f2af8ffd59 | 76,052 |
from typing import Tuple
from typing import List
def tokenize(sentence: Tuple[int, int, str],
entities: List[Entity],
events: List[Event],
language: str = 'english'
) -> List[Tuple[int, int, str]]:
"""Tokenizes a sentence and makes sure entity and event spans are compatible
with the tokenization re... | 9ae8e223dc549b6cb364e64c95cb72c5ceba87dd | 76,053 |
def _get_model(
shape,
kernel=(3, 3),
padding=(1, 1),
strides=(1, 1),
dilation=(1, 1),
groups=1,
dtype="float32",
channels=-1, # -1 means same as input channels
bias_type="none",
activation_type="none",
):
"""Return a model and any parameters it may have"""
if channels =... | 7ebbc0cd13e7afabbec448f99231ea21ed04aaa2 | 76,054 |
def simple_propensity(params, population):
"""
Returns an array of propensities given a set of parameters
and an array of populations.
"""
# Unpack parameters
beta, b, d, u, v = params
# Unpack population
S, I, R = population
N = S + I + R
return np.array([beta*I*S... | 0f8f8efec313f93459cb046ac0f4ce0d53ef428a | 76,055 |
def largest_element(a, loc=False):
""" Return the largest element of a sequence a.
"""
maxval= a[0]
maxloc= 0
for i in range(1, len(a)):
if a[i] > maxval:
maxval = a[i]
maxloc =i
if loc==True:
return maxval, maxloc
else:
return maxval | c4281ff3f60ecaecb36b4f3d8ae6ab41696c672f | 76,056 |
def first_matching_pattern_first_capture(patterns, string,
case=True):
""" first capture from the first matching pattern
"""
pattern = first_matching_pattern(patterns, string,
case=case)
return first_capture(pattern, string, c... | 690d7a3a712db661443782cb0979d44f4e11e321 | 76,057 |
def upload_module_constants(module):
"""Uploads all constants from given module into dictionary of Constant-objects"""
constants = {}
for func in dir(module):
if isinstance(getattr(module, func), float):
constants[func] = Constant((getattr(module, func)))
return constants | 3990068c9c749ef70ceda3f491fb0b9d168587ab | 76,058 |
from typing import Any
def get_file_handler() -> Any:
"""Return a file handler for logging."""
file_handler = TimedRotatingFileHandler(LOG_FILE, when="midnight")
file_handler.setFormatter(CustomFormatter())
return file_handler | 9e4b91b1d5900c9f86d38db112bd628da4e98231 | 76,059 |
def make_options(obs_settings, obs_names):
"""Constructs a dict of configuration options for a set of named observables.
Args:
obs_settings: An `ObservationSettings` instance.
obs_names: An `ObservableNames` instance.
Returns:
A nested dict containing `{observable_name: {option_name: value}}`.
"""... | a9c0d605835533b0e41cf8df4c934c42f5601a4a | 76,060 |
def days_in_month(year, month):
"""
returns number of days for the given year and month
:param int year: calendar year
:param int month: calendar month
:return int:
"""
eom = _days_per_month[month - 1]
if is_leap_year(year) and month == 2:
eom += 1
return eom | 7df83004c106cafb32ea1f10a45268821bf5f1bf | 76,061 |
def force_positive_definite(H):
"""
Force all eigenvalues to be positive.
"""
# Sorted eigenvalues and corresponding eigenvectors of the Hessian
Hvals, Hvecs = sorted_eigh(H, asc=True)
Hs = np.zeros_like(H)
for i in range(H.shape[0]):
if Hvals[i] > 0:
Hs += Hvals[i] * np.... | c4b296c297c6e18d98612843dd57e451e083a9c4 | 76,062 |
def welcome(request):
""" Main home screen """
return render(request, 'rssfeed/welcome.html') | ac92b1897ab8b57701f984582385c6463d4d0e6e | 76,063 |
def AND(domains):
"""AND([D1,D2,...]) returns a domain representing D1 and D2 and ... """
return combine(AND_OPERATOR, TRUE_DOMAIN, FALSE_DOMAIN, domains) | a2772bf434217370bb758de7817a9fa398b04f2b | 76,064 |
import time
def time2hide(starttime):
"""A helper function for blinking things.
The return value is a Boolean that changes twice per second.
"""
return (time.time() - starttime) % 1 < 0.5 | 2990bd0387b7c3e7b0f7d966b8210ef1ab6bca89 | 76,065 |
def home():
"""home page."""
return render_ex("index.jade", _title=setting.ncon + setting.header) | 5adbd37e8fab59af2d090a7548dda2d3cd977251 | 76,066 |
def compute_relative_trajectory_error_time(est, gt, delta, max_delta=-1):
"""
The Relative Trajectory Error (RTE) defined in:
A Benchmark for the evaluation of RGB-D SLAM Systems
http://ais.informatik.uni-freiburg.de/publications/papers/sturm12iros.pdf
Args:
est: the estimated trajectory
... | cbde8096e8629eaf5a799925f17529144009b3b0 | 76,067 |
def compareFaceSimilarity(hFDEngine, hFREngine, inputImgA, inputImgB):
"""
人脸相似度对比
"""
# Do Face Detect
faceInfosA = doFaceDetection(hFDEngine, inputImgA)
if len(faceInfosA) < 1:
print(u'no face in Image A ')
return 0.0
faceInfosB = doFaceDetection(hFDEngine, inputImgB)
i... | 90c1e8ce2e137af5b860846993bddd42f85723bd | 76,068 |
def decode_val(val_text, hexnum):
"""
Decode tile value text to its numerical equvalent.
@param val_text: Value text to decode.
@type val_text: C{str}
@param hexnum: Value is a hexadecimal number.
@type hexnum: C{bool}
@return: Its numeric value if it can be decoded, C{None} if it canno... | d68ad3c3dcac9d023a430c4a17aa045742f3ae87 | 76,069 |
def mobilenetv3_small_minimal_100(pretrained=False, **kwargs):
""" MobileNet V3 Small (Minimalistic) 1.0 """
model = _gen_mobilenet_v3('mobilenetv3_small_minimal_100', 1.0, pretrained=pretrained, **kwargs)
return model | ba691efe04bb94d3408707f48109c906aad21e17 | 76,070 |
def run_sox_silence(cmd_str, input_stream=None, output_stream=None, error_stream=None):
"""
to remove the warning in sox such as:
"sox WARN wav: Length in output .wav header will be wrong since can't seek to fix it"
"""
return run_cmd(cmd_str.replace('sox', 'sox -V0'),
input_s... | 3d5876bf47bc34034eab1c8b745545a7ea938f95 | 76,072 |
import random
def generate_bdays(num_bdays):
"""Generates n birthdays and returns them as a list"""
bdays = []
for bday in range(num_bdays):
bdays.append(random.randint(1, 365))
return bdays | ef2c5988db714bebea81301edc9f2aa3e979766d | 76,073 |
from datetime import datetime
def stats(update, context):
""" Show help info about all secret admins commands """
u = User.get_user(update, context)
if not u.is_admin:
return
text = f"""
*Users*: {User.objects.count()}
*24h active*: {User.objects.filter(updated_at__gte=now() - datetime.timede... | 36bcec36ec8fde1470f2a35f775f1d8308f473de | 76,076 |
import io
def fetch_data_with_singer_ids(data_annotations, key):
"""
A function to return data used for training
given a dictionary of the Wagner dataset.
Compared to the "fetch_data" function this returns
the labels for multi-class scenario.
Args:
data_annotati... | 127285054d6501f4e4250eb6428bf5447b753db7 | 76,077 |
from typing import Dict
def matthews_corrcoef(target: np.ndarray,
prediction: np.ndarray) -> Dict[str, float]:
"""Returns Matthews correlation coefficient (MCC)."""
return {
'matthews_corrcoef': sklearn.metrics.matthews_corrcoef(
target, prediction)
} | ec5d64cd1f183334b297d7e473aa084b87c132ac | 76,078 |
import types
def _check_required(
*, schema: oa_types.Schema, schemas: oa_types.Schemas
) -> types.OptResult:
"""Check required."""
# Retrieve property names
property_name_set = set(_get_property_names_model(schema=schema, schemas=schemas))
# Check that all required values are lists
required_... | 5de50186df23980f63df7d096143ffee2c1182c6 | 76,080 |
def account_for(**breadcrumbs):
"""Return the first account the breadcrumbs match."""
for cls in Account.__subclasses__():
if cls.match(**breadcrumbs):
return cls(**breadcrumbs) | e1fc6d92834ac8a2adb17e9a5779bc82f7123972 | 76,081 |
from typing import List
from typing import Dict
def column_reflection_fallback(selectable, dialect, sqlalchemy_engine):
"""If we can't reflect the table, use a query to at least get column names."""
col_info_dict_list: List[Dict]
if dialect.name.lower() == "mssql":
type_module = _get_dialect_type_... | 500770420c0f3d4e767d3edf7c57adf7a5871d5a | 76,082 |
from typing import List
from pathlib import Path
from typing import Union
import re
def val_from_ahs_files(ahs_folders: List[Path], type_: str) -> Union[str, None]:
"""Get unit number/date from list of ahs FR folders
Parameters
----------
ahs_folders : List[Path]
[data, dnevent, sfevent]
... | 9b30a9e2b4b37e54de03b42156db8ccefc76cf1f | 76,083 |
def calc_raytosphere(sp, li):
"""Calculate the intersection between a ray and a sphere, returning
the distance between the ray origin and the shere or
-1.0 if the two do not intersect"""
oc = li.p - sp.center
loc = geom.scalar(li.u, oc)
uu = geom.scalar(li.u, li.u)
delta = loc**2 - geom.s... | dd85f83bfb078ca95bb3f111299419a397c34558 | 76,084 |
def _choose(**kwargs):
"""Sub-submenu to choose an existing virtualenv.
Return the selected virtualenv as a tuple with format (env_name, env_route),
being env_name the custom virtualenv name, and env_route the absolute path of the env.
:param envs: List of virtual envs returned by get_envs() (optional, ... | a44133dee32f98d50a5f0f52cddcd93f7b548c10 | 76,085 |
from typing import Optional
from typing import Tuple
from typing import List
def uim_extract_text_and_semantics(uim_bytes: bytes, hwr_view: str = CommonViews.HWR_VIEW.value,
ner_view: Optional[str] = None) \
-> Tuple[List[dict], List[dict]]:
"""
Extracting the text f... | 2bd97279369b1bec141f40eb6e595e6cdee6f054 | 76,086 |
def get_colors(img):
"""pull the colors out of an image"""
return [ c[1] for c in img.getcolors(img.size[0]*img.size[1]) ] | a8bc950dd365742c38784ce4e75d37e27b63c0c3 | 76,087 |
def get_heat_flow_convect_vent_layer(matrix_temp: np.ndarray, param: Parameters, h_cv: float) -> float:
"""
通気層内表面から通気層空気への対流熱量
:param matrix_temp: 各部温度計算結果 (5,1), degC
:param param: 計算条件パラメータ群
:param h_cv: 通気層対流熱伝達率, W/m2K
:return: 通気層内表面から通気層空気への対流熱量、W/m2
"""
... | a32e002f51082550b9ad613d5e661e78a6e42bdf | 76,088 |
import numpy
def _spc_dates_to_years(spc_date_strings):
"""Finds first and last years in set of SPC dates.
:param spc_date_strings: 1-D list of SPC dates (format "yyyymmdd").
:return: first_year: First year.
:return: last_year: Last year.
"""
start_times_unix_sec = numpy.array(
[time... | ab7484492a89d1ace098b936686123d6e35aa90a | 76,090 |
import requests
def delete(endpoint, token, id):
"""
send a DELETE request for one object
:param endpoint: an endpoint from ENDPOINTS list
:param token: float token
:param id: id of the object
:return: a dictionary representing the json response
"""
if endpoint not in ENDPOINTS:
... | 23e17514a9454468f9b5669354562db09eebaf98 | 76,091 |
def emojis(post):
"""
Returns a list of all extracted emojis.
Parameters
----------
post : UniMessage
Returns
-------
list(str)
The extracted emojis
"""
return findall_list(post.text, desc=False) | 6c10ace1b96edc44ccbed4d9bc8d93b62268feb3 | 76,092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.