content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def check_single_replicate_and_resolve_paths(project_directory):
"""
Check read files and resolve paths
"""
sample_data = []
for r1 in project_directory.rglob("*_L001_R1_001.fastq.gz"):
r1 = r1.resolve()
r2 = Path(str(r1).replace("_L001_R1_001.fastq.gz", "_L001_R2_001.fastq.gz"))
i... | fce92ce07ff98515ddaa1af91406953eba5848ff | 584,889 |
def crop_gt(im, w, h, stride):
"""
Crop a 2D image into patches of size [w, h] using a fixed stride.
:param im: Image to crop ground truth labels from
:param w: Width of the crops
:param h: Height of the crops
:param stride: Stride of the crops
:return: List of patches in row-major ordering ... | 3737f37d04e61a45e9fbee85e878305b2d69ff1c | 584,890 |
import torch
def accuracy(y_hat:torch.Tensor, y:torch.Tensor):
""" Standard percentage accuracy computation """
preds = torch.max(y_hat, 1)[1]
return torch.mean((y == preds).float()) | b93262693b5c0c3b5f1cb7e11723991d19660573 | 584,893 |
import itertools
def get_copasi_model_obj_sbml_ids(model):
""" Get the SBML id of each object of a COPASI model
Args:
model (:obj:`COPASI.CModel`): model
Returns:
:obj:`list` of :obj:`str: SBML id of each object of the model
"""
ids = []
for object in itertools.chain(
... | 7d26f956e65e28943e17c461de27b860b787f788 | 584,894 |
def int_max_value(bits, signed=True):
"""Returns the maximum int value of a signed or unsigned integer
based on used bits.
Arguments:
bits -- How many bits, e.g., 16
signed -- True if a signed int
Returns:
max_value -- The maximum int value based on given parameters
"""
if signed:
... | 4d753bfb4ba4e047f3a939aadb1078aab914e2cc | 584,895 |
def freq_obs(request):
"""Return the array of observed proportions."""
return request.param | 91822c4eb09c57eaac22a4764d0fea835e5dd595 | 584,900 |
def getCenter(coords):
"""Returns the center of the given set of 2d coords as a 2-ple."""
xs = [c for i, c in enumerate(coords) if i % 2 == 0]
ys = [c for i, c in enumerate(coords) if i % 2 == 1]
cx = sum(xs)/float(len(xs))
cy = sum(ys)/float(len(ys))
return (cx, cy) | 06b0e08440de25ef0994ef2a9c856b3b46c12b64 | 584,908 |
import numbers
def is_float(x):
"""Test if `x` is a float number."""
return isinstance(x, numbers.Real) | 44e258bcb8e8a82838cc93e2d4c305f44f52c693 | 584,911 |
def to_msg_definition(identifier):
"""
Create message definition.
"""
return "SBP_" + identifier | e080ce0459ffcbbbc54efc84f6ef17ef779cdae0 | 584,922 |
import math
def get_candles_number_from_minutes(unit, candle_size, minutes):
"""
Get the number of bars needed for the given time interval
in minutes.
Notes
-----
Supports only "T", "D" and "H" units
Parameters
----------
unit: str
candle_size : int
minutes: int
Retu... | 5cb7d25483406ea1e23ba9ba6fd05f923e065cb0 | 584,924 |
import re
def image_from(from_value):
"""
:param from_value: string like "image:tag" or "image:tag AS name"
:return: tuple of the image and stage name, e.g. ("image:tag", None)
"""
regex = re.compile(r"""(?xi) # readable, case-insensitive regex
\s* # ignore lea... | a2fd0dc01444fe4f68e13337d81c2e23a418ceaf | 584,930 |
def _GaeBuilderPackagePath(runtime):
"""GCR package path for a builder that works on the given appengine runtime.
Args:
runtime: Name of a runtime from app.yaml, e.g. 'python38'.
Returns:
gcr.io image path.
"""
return 'gcr.io/gae-runtimes/buildpacks/%s/builder:latest' % runtime | 7e08bc01701874c4ebb064126d6d8eeeb0207f14 | 584,933 |
def index(seq, i):
""" Returns the ith element in the sequence `seq`. """
return seq[i] | 3ff17125a70154daece8df742109ae1c7e78878c | 584,934 |
def modular_inverse(n, p):
"""
invert n mod p using extended euclid algorithm
the algorithm breaks down into:
gcd(n,p) = s*p + t*n
since s*p % p is 0, we have that t%p = n^-1
:param n: number to invert, b
:param p: prime modulus, a
:returns: n^-1 mod p
"""
p0 = p # lo... | 357a9df3904ac05c37d1c69443033f57b30f73e1 | 584,937 |
def get_result_trans_imgs(file_result):
""" Read datafile holidays_images.dat and output a dictionary
mapping queries to the set of positive results (plus a list of all
images)"""
gt = {}
allnames = set()
for line in open(file_result, "r"):
fields = line.split()
imname = fields[0... | c49b8cd932beabddb99748cda94bfd874d82249e | 584,938 |
def integer_sqrt(n: int) -> int:
"""
Returns the integer square root of n >= 0 - the integer m satisfying
m**2 <= n < (m + 1)**2.
Parameters:
n: int (n >= 0)
Examples:
>>> integer_sqrt(10)
3
>>> integer_sqrt(121)
11
"""
if n < 0:
rais... | 03db9c9f3f132bcf43f39ffbbc8917a71d11f47a | 584,941 |
def get_interpob(model):
"""Retrieves the interpolation dictionary from model.
Different nufft objects use different interpolation objects. This function
only extracts the minimum amount necessary for sparse matrix
precomputation.
Args:
model (TorchKbNufft object): A TorchKbNufft object wi... | 270d38358b69fc898655353e9c4b1ffc7d03fdd4 | 584,942 |
def eo(self) -> tuple:
"""
Solve last layer cross.
Returns
-------
tuple of (list of str, dict of {'LAST LAYER CROSS': int})
Moves to solve last layer cross, statistics (move count in ETM).
Notes
-----
If an odd number of edges are oriented (1 or 3), do the OLL parity
algor... | 2e352130197f0e2efed1b04a2aa81b60ae3efb32 | 584,943 |
def H(path):
"""Head of path (the first name) or Empty."""
vec = [e for e in path.split('/') if e]
return vec[0] if vec else '' | da618dfe64ed6b30b23ddb9d528458e80e7a8708 | 584,944 |
import tempfile
def get_temp_dir(prefix):
"""
Creates and returns temporary directory.
The property `.name` holds the path. It can be deleted using the `.cleanup()` method.
"""
return tempfile.TemporaryDirectory(prefix=prefix) | a5ba3f29fd8fb7aacb83030e0505a1bff03ddc45 | 584,945 |
import math
def center_crop(size, im):
"""Performs center cropping (HWC format)."""
h, w = im.shape[:2]
y = int(math.ceil((h - size) / 2))
x = int(math.ceil((w - size) / 2))
im_crop = im[y : (y + size), x : (x + size), :]
assert im_crop.shape[:2] == (size, size)
return im_crop | 49d593e85f0dd3c6025ee0b50bb809507627d5d1 | 584,948 |
def translate_topo_name(topo):
"""Translate the name of a topology as given by
the benchmarks into a meaningful printable variant.
"""
if 'adaptivetree-shuffle-sort' in topo:
return 'adaptivetree-optimized'
else:
return topo | ee1ec9123b8875ca0deb9ab159009b1bb4ba9590 | 584,951 |
def filterBySequence(wordlist, sequence):
"""
Takes an array of words {word, sequence} and filters it down to words that match
the sequence as typed thus far. Returns a list of words {word, sequence}.
"""
filtered_list = [entry["word"] for entry in wordlist if entry["sequence"].startswith(sequence)]
return ... | a6d8ee84b5bd5ec6053bb2d3c7afe240e2a2222e | 584,952 |
def get_schedule_value(type):
"""Get the enum for schedule.
:param type: The type of rule
:return: The enum value for rule
"""
rule_type = {
"every_n_hours": 0,
"every_day": 1,
"every_n_days": 2,
"every_week": 3,
"every_month": 4
}
re... | 9d4a87c899510e31df7bebefc2299a41255fe7af | 584,954 |
from typing import Iterator
def concrete(seq):
""" Make nested iterators concrete lists
>>> data = [[1, 2], [3, 4]]
>>> seq = iter(map(iter, data))
>>> concrete(seq)
[[1, 2], [3, 4]]
"""
if isinstance(seq, Iterator):
seq = list(seq)
if isinstance(seq, (tuple, list)):
s... | 6e537a80ba405fa6b984d3f5bc5042d372488a8d | 584,958 |
from typing import List
from typing import Set
def get_missing_internal_subtypes(st_vals: List[str],
pos_subtypes_set: Set[str]) -> Set[str]:
"""Compare nested subtypes from the final subtype call to positive subtypes found
Args:
st_vals: Hierarchical subtype values
... | 426179f6e2268b1c90ccb0b6163795f54e6ee13e | 584,959 |
def _apply_attention_constraint(e, last_attended_idx, backward_window=1, forward_window=3):
"""Apply monotonic attention constraint.
This function apply the monotonic attention constraint
introduced in `Deep Voice 3: Scaling Text-to-Speech with Convolutional Sequence Learning`_.
Args:
e (Tensor)... | a4c7c02bbd1d391383cec31ef8fc450e5efb7863 | 584,962 |
def is_normalizeable(normalize_function, value) -> bool:
"""
Wraps a normalize_*() function, and returns True if value can be
normalized by normalize_function, otherwise returns False.
"""
try:
normalize_function(value)
return True
except Exception:
return False | 4491aa9d35d6565a89ffb461bd3d38efba90c8d2 | 584,964 |
def mean_rmse_to_score(mean_rmse):
"""Returns frii contest score associated with a mean RMSE value
"""
return 100 / (0.1 * mean_rmse + 1) | 6e1ec8dbb194fe90aafd54f0ddb5f6b1d4abdaa7 | 584,965 |
import unittest
def unittest_has(method):
"""Does `unittest.TestCase` have `method` defined?"""
return hasattr(unittest.TestCase, method) | c9a164310bed82ae3074fbbeceebcd89f464ea2d | 584,967 |
def get_statistical_uncertainty_hist(hists):
"""
Sum all histograms in hists and rename as stat.unc for statistical uncertainty overlay
"""
if len(hists) == 0:
return None
statistical_uncertainty_hist = hists[0].Clone("stat.unc")
for hist in hists[1:]:
statistical_uncertainty_hi... | fcf06ce75c46f5037dffe77b02237850169b000a | 584,968 |
def _capitalize(word: str) -> str:
"""Capitalizes the given word.
:param word: the word to capitalize
:return: the word with the first letter capitalized (any other uppercase characters are preserved)
"""
if word == "":
return word
return word[0].upper() + word[1:] | 8f16e0c1508525be3d5ce360e96b1b042ef12b29 | 584,972 |
def greatest_profit(array: list):
"""given array return the maximum profit from one buy and sell
the following algorithm does so in O(N) time
"""
minimum_price = array[0]
maximum_price = array[0]
greatest_profit = 0
for price in array:
if price < minimum_price:
minimum_price = price
maximum_price = pr... | 923adff21f4ae6faef97d9a26bb235d37d5cdc0c | 584,975 |
def get_efs_ids_from_terraform_output(config_data):
"""Grab the EFS Ids from the previous terraform output"""
for efs in config_data['pcluster']['efs_resources']:
name = efs['name']
id = config_data['terraform_output']['pcluster_resources'][name]['value']
efs['fs_id'] = id
return con... | 42796b5c490b5f01b59b81c87c354d3d5e486193 | 584,977 |
def custom_config_invalid_params(changes, vers1):
"""Generates data frame of invalid parameters in custom configuration.
Parameters
---------------
changes : pandas.DataFrame
vers1 : str
Returns
---------------
pandas.DataFrame
"""
invalid_param_custom = changes[changes[vers1]... | 97942f7aa9ae88115d9950481331e7c771298258 | 584,982 |
def uid2str(uid):
""" Convert PyDicom uid to a string """
return repr(uid).strip("'") | 88620f5d1b358400a7b85495ea67fa2cb1d6bfac | 584,986 |
def ranks_from_ordering(ordering):
"""Convert an ordering vector into a vector of ranks."""
ranks = [0] * len(ordering)
for r, x in enumerate(ordering):
ranks[x] = r
return ranks | a37f3592f02ecce65bff4a714703f77be1ab2609 | 584,987 |
def resolve_order(reg, deps):
"""
Resolve the order of all dependencies starting at a given register.
Example:
>>> want = {'a': 1, 'b': 'c', 'c': 'd', 'd': 7, 'x': 'd'}
>>> deps = {'a': [], 'b': [], 'c': ['b'], 'd': ['c', 'x'], 'x': []}
>>> resolve_order('a', deps)
['a']
... | 02ee9a516a81a9cc00c18eae8ce52c36728c27b0 | 584,988 |
def get_sets(infile):
"""
Function that maps a dataset name to a sliced version of a dataframe
Parameters
----------
infile : pandas DF
dataframe containing the features and objective values
Returns
-------
dict
dictionary that maps between datasets and a sliced... | 366a41f0a2851de22bca5eb0222afe29bd3705a0 | 584,992 |
import torch
def _mean_top_sim(sim: torch.Tensor, k: int, dim: int) -> torch.Tensor:
"""Compute the mean similarity of the top-k matches along an axis."""
return sim.topk(k=k, dim=dim, largest=True, sorted=False)[0].mean(dim=dim).unsqueeze(dim=dim) | 5103cbe5e2372bab4d5f378c61ca1d9e6905cbce | 584,997 |
from typing import OrderedDict
def dedupedlist(mylist):
"""Dedupe a list"""
return list(OrderedDict.fromkeys(mylist)) | f51ddf538a226ab22c9dfcda1335a7c025b8a4df | 584,999 |
def get_model_metadata(dashboard):
"""Retrieves the model metadata from the dashboard
Parameters
----------
dashboard : plsexplain.dashboard.Dashboard
The dashboard instance to read from
Returns
-------
Callable
The API handler for rendering the model metadata
"""
... | 6e3e7bbbbe76bde23cff7fc1b9a1f73690e8c510 | 585,000 |
import torch
def purge_unfeasible(x, res):
"""
Purge unfeasible event locations by setting their interpolation weights to zero.
:param x: location of motion compensated events
:param res: resolution of the image space
:return masked indices
:return mask for interpolation weights
"""
m... | 8e7cd559ced55c9cb20b80184c503cc615176673 | 585,001 |
def get_integral_error(pl, interval):
"""
Compute the integrale of the production profile and compute
the error with respect to the total energy production
obtained by the raster file
:parameter pl: plant
:parameter interval: step over computing the integral
:returns: the relative error
... | 407a741e8e12ce314ed98d29238c76b702fd60ad | 585,002 |
def user_name_attributes(user, service):
"""Return all available user name related fields and methods."""
attributes = {}
attributes['username'] = user.get_username()
attributes['full_name'] = user.get_full_name()
attributes['short_name'] = user.get_short_name()
return attributes | af5d841eff8e856c3ce02fdde927ff5a375c7c62 | 585,003 |
from typing import Counter
def compareLists(a, b):
"""
Compare two lists, return true if they are just the same under a permutation.
Parameters
----------
a, b : list of any
The two lists to compare.
Returns
bool
whether a and b are the same under a permutation.
"... | f23e2d1cf6e9c434c93f95ead4e548e05c4a912d | 585,004 |
def _GetWinLinkRuleNameSuffix(embed_manifest):
"""Returns the suffix used to select an appropriate linking rule depending on
whether the manifest embedding is enabled."""
return "_embed" if embed_manifest else "" | 2cf42d4a22007baa648842975f61d36406bd84cb | 585,008 |
from typing import MutableMapping
def flatten_dict(d, reducer=None, parent_key=()):
"""Flattens dict into single-level-tuple-keyed dict with
{(tuple of keys of parents and self): value}
Args:
reducer:
Character to join keys in a tuple.
If None, returns with key as a tu... | e6fccba6a99d929cf40f99da2a16bbd85839842d | 585,017 |
def get_num_iter(args):
""" Determines if iterations per phenotype must be performed (only enabled for testing).
If so, formats iterations properly for use.
"""
if args.n_iter is None:
return [None]
else:
return range(0, args.n_iter) | fe9db48a470386cdda4b8e6550435f2f3145723f | 585,019 |
import six
def _from_bytes(value):
"""Converts bytes to a string value, if necessary.
Args:
value: The string/bytes value to be converted.
Returns:
The original value converted to unicode (if bytes) or as passed in
if it started out as unicode.
Raises:
ValueError if ... | a4eff7a4d89204b9a8933b58b1e6ca30e23bb48c | 585,020 |
import re
def expand_sgml(text: str) -> str:
"""Replaces &#...; SGML entities to their Unicode character equivalents.
:param text: HTML to transform
:return: transformed text
"""
return re.sub(r"&#(\d+);", lambda m: chr(int(m.group(1))), text) | da118d2a46d7a1137306d6ff8e79d66237824884 | 585,021 |
def compareTriplets(a, b):
"""Return a list with the scores
Generated by comparing the first and the second triple
If the comparision between correspondent numbers result
in a greater one this one score's is incremented by 1,
if the correspondent numbers are equal nothing is added
... | af15df3155a9e668db9ffaa70e385baa65431b2e | 585,023 |
def is_uniform(x, epsilon=0.000000001):
"""Determine if the vector is uniform within epsilon tolerance. Useful to stop a simulation if the fitness landscape has become essentially uniform."""
x_0 = x[0]
for i in range(1, len(x)):
if abs(x[i] - x_0) > epsilon:
return False
return True | 95441cbc7ad1c06461d1e029d2490250e491e020 | 585,030 |
import random
import math
def evaluate_move(prev_td, prev_area, new_td, new_area, T):
"""Evaluates the move
Parameters
----------
prev_td : float
Previous timing cost.
prev_area : float
Previous area cost.
new_td : float
New timing cost.
new_area : float
Ne... | 47c86b4dab77a7a0e4523ba7e85cfd4267ff876f | 585,032 |
def parse_cores(cores, pm, default):
"""
Framework to finalize number of cores for an operation.
Some calls to a function may directly provide a desired number of cores,
others may not. Similarly, some pipeline managers may define a cores count
while others will not. This utility provides a single ... | 1292d11a68d5114fe784d5965b1ee40691e58b61 | 585,033 |
def bit_first(x):
"""Get the first digit where 1 stands(0-indexed)
Args:
x (int): bit
Returns:
int: first digit
>>> bit_first(1)
0
>>> bit_first(4)
2
>>> bit_first(6)
2
>>> bit_first(0b1011000)
6
"""
return x.bit_length() - 1 | d2bfb3c5934cd85f6c0ef934f874ac7667892d67 | 585,043 |
from typing import Iterable
def csv_mkln(
*args,
delim=',',
quote='\"',
esc='\\'):
"""
Formats a CSV row that can be written to a CSV file to be
reloaded later. The result of this function can be passed
to `csv_parseln` to parse it back into a list of strings.
:param args
The list of cells to format i... | a1482d2a9b8d90ac1441ff99d8037c42d067afd0 | 585,046 |
def _filter_status(tests_df):
"""Filters out any tests with statuses that aren't equal to "Passed" or "Failed"
Args:
tests (pandas.DataFrame): the test data; note that there should be a column called "status"
Returns:
two list or pd.DataFrame: the valid and invalid automated rest_a... | 52cab99cea1700f1108f7f7cdd4c52e969bebc63 | 585,052 |
def basic_rest_stream(rest_tap):
"""Get a RESTful tap stream."""
return rest_tap.streams["some_stream"] | ac10115c714487f749dc69efd44cb3176d52d197 | 585,054 |
def check_datagaps(tr, nsec=100):
"""Verify there is sufficient data"""
datalength = len(tr.data) * tr.stats.delta
assert datalength > nsec, \
f'(ValueError) Insufficient data length ({datalength} seconds)'
return None | 563fc6045144b7631eacda4da6a30cae4a14ae25 | 585,057 |
def myfunc(Xs):
""" returns a list of doubled values"""
Ys=[]
for x in Xs:
Ys.append(2*x)
return Ys | 397fc39c6fe661c2e950659e1d8b70952e3b5080 | 585,058 |
def extract_street(address: str):
"""
Извлекаем улицу из переданной строки с адресом.
В данном случае адреса уже достаточно чистые. В исходных строках компоненты адреса отделяются запятыми,
улица всегда стоит на втором месте. Так что не мудрим, берем просто второй сплит.
:param address: Строка с ад... | 053f270ec85f1c60a9115148f797ae1e94f72198 | 585,059 |
import json
def humanify(line):
"""
Decode json dump of execution engine's structured log and render a human friendly line,
containing, together with prefix rendered by the Python test framework, all useful
information. The original dictionary in the EE structured log looks like follows:
{'ti... | 93badbaa1407a3c2e1210edb47e2ea068c731a0c | 585,061 |
def get_primary_key(model):
"""
Return primary key name from a model
:param model:
Model class
"""
props = model._sa_class_manager.mapper.iterate_properties
for p in props:
if hasattr(p, 'columns'):
for c in p.columns:
if c.primary_key:
... | 22a3970244e94af9dc0662947ac23bb47b6f2c34 | 585,068 |
def update_dict(left, right):
"""Updates left dict with content from right dict
:param left: Left dict.
:param right: Right dict.
:return: the updated left dictionary.
"""
if left is None:
return right
if right is None:
return left
left.update(right)
return left | 918f7dd0a6dc30ce02df7f4a7f84c33a9e2f42a8 | 585,070 |
def read_freqs_file(filepath, separator=' '):
""" Reads word frequencies file and returns dictionary
where words are keys and frequencies are values.
"""
f = open(filepath, 'r')
ret = {}
for line in f.read().split('\n'):
tokens = line.split(separator)
if len(tokens) == 2:
... | 718c7d922098fdd21a2746ee8702fa5caee4d88b | 585,071 |
import click
def output_error(text):
"""Click echo error."""
return click.style("ERROR: {}".format(text), fg="bright_red", bold=True) | 4a3a7f2d94c18e4aa38d330690aadace2bffe216 | 585,074 |
def _generate_output_dataframe(data_subset, defaults):
"""
Generates an output dataframe from the given subset of user-provided
data, the given column names, and the given default values.
Parameters
----------
data_subset : DataFrame
A DataFrame, usually from an AssetData object,
... | c5caa9ac6eb19eb6e6e9467ab59684aa8210fb60 | 585,075 |
def cross_product_copy(template_copiable, **values):
"""Copy the object by substituting values, doing a cross-product when the value is a list
By cross-product, we mean that if one of the values is a list, this method is called
recursively with the key being mapped to each item in the list, resulting in re... | 9aff8429739aeed1f9816c411622255fbe1ec19c | 585,080 |
def _get_units(intuple):
"""
Extract Units from metadata.
>>> _get_units([("fmap.nii.gz", {"Units": "rad/s"})])
'rad/s'
>>> _get_units(("fmap.nii.gz", {"Units": "rad/s"}))
'rad/s'
"""
if isinstance(intuple, list):
intuple = intuple[0]
return intuple[1]["Units"] | 54a44bed769ac0967ec85ef74ac1073e77e1eb80 | 585,083 |
from typing import Any
def zarr_array_from_dask(arr: Any) -> Any:
"""
Return the zarr array that was used to create a dask array using `da.from_array(zarr_array)`
"""
keys = tuple(arr.dask.keys())
return arr.dask[keys[-1]] | 806a3854fcc2c9a262acc0623c6096783e90cc33 | 585,085 |
def format_timedelta(timedelta_obj):
"""Helper function to format timedelta to a human-readable time string"""
if timedelta_obj:
timedelta_string = '%02d:%02d:%02d' % (
int(timedelta_obj.total_seconds() // 3600),
(timedelta_obj.seconds // 60) % 60,
timedelta_obj.secon... | f10ddb22d682fcb6c1f406246f0819451b87a136 | 585,086 |
def episode_status_icon_info(ep):
"""
Given an Episode object, returns the icon details for the episode's status.
:params ep: Episode object
:returns: (status, title)
status is one of 'forced', 'have', 'ignore', 'need', or 'future' and title
is a printable string for the state.
"""
if ... | 21831631238284b3e06635be328a3048d723ce52 | 585,087 |
def expandMinAndMax(val0, val1, minimumDiff, growRatio, minLimit, maxLimit):
"""Expand the image dimension range
Inceases the min/max of the range by growRatio while maintaining
the same center. Also, ensures the range is at least minimumDiff.
Finally, limits the increases to ensure values are still wi... | 99efa887b8efef8ef35ac5979b869fd59b45f3e7 | 585,089 |
def wizard_input_verification(form):
""" Verification, if the entered lines are unique. Used during time measure wizard.
"""
# Note,that key must start with line_..., other options are ignored, to allow DNF option to work
lines = [value for key, value in form.items() if key.startswith("line")]
# if ... | 6e8108ea00359a638535f94f165f3a3d138a11ec | 585,090 |
from bs4 import BeautifulSoup
def extract_text_from_html(column_to_clean: str) -> str:
"""
This function is used to extract the text from the html.
:param column_to_clean: column to clean
:return: column with the text
"""
if type(column_to_clean) is str:
text = BeautifulSoup(column_to... | e39f2f4d3dfc1c9368f149a661173b1c9fac54ff | 585,091 |
def handle_index_syntax(key):
"""
Turn a key tuple into Julia slicing and indexing syntax
Parameters
----------
key: String, integer, slice or a tuple of these
"""
if isinstance(key, tuple):
indexes = []
for index in key:
if index == slice(None):
... | 0abb556a4fb3441156b5d8a5ba3f3e74e5fb492e | 585,095 |
def chars_different(box1, box2):
"""Count the number of characters that differ between box1 and box2"""
diff = sum(
1 if i != j else 0 for i, j in zip(box1, box2)
)
return diff | b9cfa5ba9a97bb48e60c46918953b1daba6d2f61 | 585,099 |
def check_headers(headers):
"""Return True if the headers have the required keys.
Parameters
----------
headers : dict
should contains 'content-type' and 'x-mailerlite-apikey'
Returns
-------
valid_headers : bool
True if it is valid
error_msg : str
the error mes... | bcfaff257386f97ece033ced31402f305ebf2229 | 585,100 |
def _init_features(num: int):
"""Initialize array of settings for tests
"""
features = []
for _ in range(num):
features.append(0)
return features | 5f8b0de568318cd298258b0c2084a09ee75e93e9 | 585,101 |
def PSD_sym_KL(u, v):
""" Calculate the symmetric KL divergence between two spectral densities
j = sum( u / v + v / u - 2)
Args:
u 1d array PSD array
v 1d array PSD array
"""
n = len(v)
j = (1 / n) * (u / v + v / u - 2).sum()
return... | bf76b728dab8f994e3bbe374aab61498d9c72371 | 585,102 |
def coral_parse_version_extra(extra):
"""
Parse the extra tag with the format of ${PREFIX}${INDEX}, e.g. tag10
${INDEX} is a decimal number.
010 is identical to 10
"""
string_index = 0
for string_index in range(len(extra)):
if not extra[-string_index - 1].isdigit():
break... | e7b7ffdcd3eef12271a18cb818f491e6ca3b07fb | 585,103 |
def get_proxy_column_names(protected_columns, noise_param, noise_index=''):
"""Gets proxy column names."""
return [
'PROXY' + noise_index + '_' + '%0.2f_' % noise_param + column_name
for column_name in protected_columns
] | 32d1c215394177ce130c8e1ae2751d3bbe2fdfaa | 585,109 |
def AB2_step(f, tcur, ucur, h, fold):
"""
Usage: unew, fcur = AB2_step(f, tcur, ucur, h, fold)
Adams-Bashforth method of order 2 for one step of the ODE
problem,
u' = f(t,u), t in tspan,
u(t0) = u0.
Inputs: f = function for ODE right-hand side, f(t,u)
tcur = current tim... | 63c72ab8178a6b94a8eee5e416fdedb83991b15b | 585,114 |
def invert_dict(d):
"""inverts a dictionary (keys become values, values become keys)"""
res = {}
for key in d:
res[d[key]] = key
return res | 9770812803bec69fcf3931d1acbb80437c963145 | 585,116 |
import torch
def subsample(data, mask_func, seed=None, mode='3D'):
"""
Subsample given k-space by multiplying with a mask.
Args:
data (torch.Tensor): The input k-space data. This should have at least 3 dimensions, where
dimensions -3 and -2 are the spatial dimensions, and the final di... | 889d39a59c7021398692a2e2b856bbdd2b21d27e | 585,118 |
def add_one(number):
"""Adds one to number"""
return number + 1 | 775605f6d32f10559612057c20ad46b65ea0423c | 585,121 |
def bst_search(root, value):
"""
Search a binary search tree for a value.
"""
if root.value == value:
return True
if root.value > value:
return False if root.left is None \
else bst_search(root.left, value)
return False if root.right is None \
else bst_search(root.right, value) | 874d55c6e7ebe730a909382b890fc8e437ff6a92 | 585,125 |
def key_to_cmdline_flag(key: str) -> str:
"""Convert key into a command line flag, e.g. 'foo-bars' -> '--foo-bar' """
if key.endswith("s"):
key = key[:-1]
return "--" + key.replace("_", "-") | 9dd601d8d2eb47d27e8f0865ef040c0d4610575d | 585,132 |
def direction(col_spec):
"""
Gets direction for column expression (1 for ascending - 1 for descending).
"""
if isinstance(col_spec, int):
return 1 if col_spec >= 0 else -1
else:
assert col_spec
return 1 if col_spec[0] != "-" else -1 | 86230f2c83fe0fe5210e082699eff9dd7c8fe839 | 585,139 |
import string
def strip_punctuation(text):
""" Takes punctiation out of text """
exclude = string.punctuation
return ''.join(s for s in text if s not in exclude) | eec5c2763e4b710659113a640f6eea11dd1342ef | 585,140 |
from typing import Callable
from typing import Any
from typing import List
from typing import Dict
from typing import Tuple
import time
def keep_trying(
fn: Callable[..., Any],
args: List[Any],
kwargs: Dict[Any, Any],
errors: Tuple[Any],
timeout: float,
sleep_time: float = 0.1,
) -> Any:
"... | 02a65f0f30160206fb651a8aadf5c2749a749b2d | 585,142 |
import requests
def get_feed_by_url(url):
"""
This fetches the feed from a given URL
:param url: A (valid) URL
:return: DiscoFeed as python object
"""
try:
r = requests.get(
url,
timeout=5
)
return r.json()
except:
raise Exception("Co... | 6505c6e1339fac1f58e774664159d3d96ca5bafd | 585,144 |
def merge_predictions_and_ground_truth(predictions_df, ground_truth_df):
"""Perform an outer join of predictions and ground truth, then set all empty values to False."""
combined = predictions_df.merge(ground_truth_df,
how="outer",
suffixes... | f8c5641b4c876059e1a446b7a1f1b3c1f24c3a3c | 585,148 |
def _calculate_number_message_batches(s3_event_message_mocks):
"""Calculates the number of message batches, i.e. the number of times
get_messages will return some messages.
"""
number_message_batches = (len(s3_event_message_mocks) + 1) / 2
return number_message_batches | 909fa77568098f895a5bb8eb9c17dd84492858dc | 585,149 |
import re
def get_timestamp(name):
"""从给定的文件名获取时间戳
Gets the timestamp from a given file name
:param name: (string) Name of a file generated by AlchemyDumps
:return: (string) The backup numeric id (in case of success) or False
"""
pattern = r'(.*)(-)(?P<timestamp>[\d]{14})(-)(.*)(.gz)'
ma... | 425d6c700d281b796e8fa2ddf80682f1911b883a | 585,150 |
def test_create_dataframe(data, columns, types, rows_allowed):
"""
Tests whether the data in a dataframe match the column name, data type,
and row count constraints.
Extended description of function.
Parameters:
data (pandas.dataframe): Data loaded from a publicdata source (911 CSV
from da... | 1e27efc5e31fb933763e1ee3d64d35537e34c283 | 585,152 |
def FindFieldDef(field_name, config):
"""Find the specified field, or return None."""
if not field_name:
return None
field_name_lower = field_name.lower()
for fd in config.field_defs:
if fd.field_name.lower() == field_name_lower:
return fd
return None | 16f5fbd5ffb64a79723716652f3571c0245d1568 | 585,153 |
def rdkit_molecule_atomic_numbers(rdkit_molecule):
"""Return atomic number list for RDKit molecule."""
return list(map(lambda x: x.GetAtomicNum(), list(rdkit_molecule.GetAtoms()))) | e7098a82bc699dcedbdbf6c96d63204e641a73ff | 585,155 |
def score_available(reqs, fd):
"""Checks if all fields in model_reqs are given (ie, not empty), returns True if complete"""
is_model_complete = True
for i in reqs:
if fd[i] == 'empty' or fd[i] == '': #added '' for clin_pred_f
is_model_complete = False
return is_model_complete | a8c91d436e855d0cdffae46ea09e8fc149f7aa63 | 585,156 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.