content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _convert_json_keywords(json_dict, conversion_dict):
"""
Makes a shallow copy of a dictionary with JSON-formatted, producing a dictionary with
Python-formatted keys
:param json_dict: the JSON dictionary
:param conversion_dict: a dictionary that maps JSON keywords to their Python equivalents. Any
... | bef2749d49411489b61a6692eea15c06004ab264 | 698,097 |
def DSER(results):
"""DA Segmentation Rate: number of segments of the
reference incorrectly segmented
over number of reference segments.
"""
assert len(results) == 2
CorrectSegs = results[0]
TotalSegs = results[1]
return ((TotalSegs-CorrectSegs)/TotalSegs) * 100 | 5d74c7bd3329448609fe36fa4d7778155c54d7c1 | 698,099 |
def normalize_dataframe(df):
""" Converts the total occurrences and total docs into percentages"""
df.total_occurrences = df.total_occurrences * 100 / df.total_occurrences.sum()
df.total_docs = df.total_docs * 100 / df.total_docs.sum()
return df | 081efaf887b4465bffca9ebe8d2c8cb11e32f720 | 698,104 |
def set_element(base, index, value):
"""Implementation of perl = on an array element"""
base[index] = value
return value | 11940389f4f24868c5afc1e4dbbcbf370a1af102 | 698,105 |
import click
def command_line_input_output_file_arguments(f):
"""
Decorator for specifying input and output file arguments in a command
"""
f = click.argument("outfile", type=click.File("w"), default="-")(f)
f = click.argument("infile", type=click.File("r"), default="-")(f)
return f | 832a527c900d6dc073f0e543d06c48696731c9d7 | 698,106 |
from typing import Sequence
from typing import Any
def _get_cont_out_labels(network_structure: Sequence[Sequence]) -> Any:
"""
Compute the contracted and free labels of `network_structure`.
Contracted labels are labels appearing more than once,
free labels are labels appearing exactly once.
Computed lists a... | f749b67789a00fe1cf0b2491a0a476d3882de9be | 698,114 |
def get_avg_repr(inp_reprs, indxs, indxs_mask):
"""
Returns the average representation based on passed indxs and mask.
:param inp_reprs: [batch_size1, dim]
:param indxs: [batch_size2, seq_len]
:param indxs_mask: [batch_size2, seq_len]
:return: [batch_size2, dim]
"""
sel_reprs = inp_repr... | 7cf4cc78c108cfe58691fe7b0cec3b2c3608230c | 698,115 |
import hashlib
def hashhex(s):
"""
Returns a heximal formated SHA1 hash of the input string.
"""
h = hashlib.sha1()
h.update(s)
return h.hexdigest() | a96fb004984a583c72fdbb7f90ce705858ab8f9d | 698,116 |
def convert_coord(x_center, y_center, radius):
"""
Convert coordinates from central point to top left point
:param x_center: x coordinate of the center
:param y_center: y coordinate of the center
:param radius: the radius of the ball
:return: coordinates of top left point of the surface
"""
... | 95a6cfd91fd7a59d7995820d3d5fceba6ff985a1 | 698,119 |
def chop(x,y,s0,s1):
"""Chop two 1-d numpy arrays from s0 to s1"""
return x[s0:s1], y[s0:s1] | e43b4cbad862558862bb3539a4eac0add1bd14a1 | 698,121 |
def psri(b3, b4, b6):
"""
Plant Senescence Reflectance Index (Merzlyak et al., 1999).
.. math:: PSRI = (b4 - b3)/b6
:param b3: Green.
:type b3: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b6: Red-edge 2.
:type b6: numpy.ndarray or float
:retu... | 3be121d6e0852a6a83d307773ffacf8fddec9f9d | 698,122 |
def no_nodes(G):
"""
returns the number of nodes in a undirected network
"""
return len(G) | 9504cc092ae63069399124e478b6c9b20d3879c9 | 698,123 |
def PNT2Tidal_Tv14(XA,chiA=0,chiB=0,AqmA=0,AqmB=0,alpha2PNT=0):
""" TaylorT2 2PN Quadrupolar Tidal Coefficient, v^14 Timing Term.
XA = mass fraction of object
chiA = aligned spin-orbit component of object
chiB = aligned spin-orbit component of companion object
AqmA = dimensionless spin-induced quadrupol... | 82eae87495785a5d0cce4d3f0ae5b6654395a42c | 698,124 |
import random
def noisify(val, eps):
"""
Add a Gaussian White noise to function value
"""
val_noisy = (1 + random.gauss(mu=0,sigma=eps)) * (1-val)
return val_noisy | 40059eb7f87aa1b7b7096a1c84c7edef09cef4e1 | 698,126 |
def get_box_size(box):
"""Get box size"""
x0, y0, x1, y1 = box
sx = abs(x1 - x0) + 1
sy = abs(y1 - y0) + 1
return (sx, sy) | cefa6c8950687f0b4d244ebf9080ab29e358a7b2 | 698,129 |
from datetime import datetime
def unix_epoch_to_datetime(ux_epoch):
"""Convert number of seconds since 1970-01-01 to `datetime.datetime`
object.
"""
return datetime.utcfromtimestamp(ux_epoch) | 13edceec1631a2a3db06dad215380f609693f441 | 698,133 |
import torch
def point_edt2(point: torch.Tensor, grid: torch.Tensor) -> torch.Tensor:
"""Batched version of a Squared Euclidean Distance Transform for a D-dimensional point.
Args:
point: torch.Tensor of size [batch, *, D]. Each element is interpreted as a D-dimensional point (e.g. [row, col]
or... | b186ccccd94d8b709974efd3b2ec5817c698f77b | 698,134 |
import queue
def bfs(G, start):
""" A simple breadth-first search algorithm implemented using native queues. """
seen = set()
q = queue.Queue()
# we don't care about threading so don't ask Queue to block execution
q.put_nowait(start)
while not q.empty():
# get the waiting node, again ... | a15f6ef42f8873b108c2bd48c462175c77fdeee8 | 698,136 |
import re
def content_type(response, **patterns):
"""Return name for response's content-type based on regular expression matches."""
ct = response.headers.get('content-type', '')
matches = (name for name, pattern in patterns.items() if re.match(pattern, ct))
return next(matches, '') | c1071b2feae41bd049a26542d89414de54c06d8e | 698,137 |
import re
def convert_ip_address(ip_address: str):
"""
This function converts a ipv4 address in standard string format to a HEX representation
:param ip_address: string with IPv4 address in format '192.168.0.1'
:return: HEX representation of IPv4 address (string)
"""
if re.search('^((25[0-5]|... | 1f50e6e2cb34325d07680a58090b58a1e00b745e | 698,138 |
import base64
def base32_decode(encoded_bytes: bytes) -> str:
"""
Decodes a given bytes-like object to a string, returning a string
>>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====')
'Hello World!'
>>> base32_decode(b'GEZDGNBVGY======')
'123456'
>>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4C... | 215a1aacd815fe11b93cf7dc6105abdff3492ab2 | 698,139 |
import re
def replaceThreeOrMore(word):
"""
look for 3 or more repetitions of letters and replace with this letter itself only once
"""
pattern = re.compile(r"(.)\1{3,}", re.DOTALL)
return pattern.sub(r"\1", word) | c052a082d74873da1a4c64dc035aeff429b29efd | 698,140 |
def luhn_validation(credit_card_number: str) -> bool:
"""
Function to luhn algorithm validation for a given credit card number.
>>> luhn_validation('4111111111111111')
True
>>> luhn_validation('36111111111111')
True
>>> luhn_validation('41111111111111')
False
"""
cc_number = cred... | 4ed1cd788b54819ae4caead22bf34975a774dace | 698,142 |
def _rescale_score_by_abs(score: float, max_score: float,
min_score: float) -> float:
"""
Normalizes an attribution score to the range [0., 1.], where a score
score of 0. is mapped to 0.5.
:param score: An attribution score
:param max_score: The maximum possible attributio... | a9ab337cc47f2d62de33c267bfe19c9522190db4 | 698,143 |
def __get_leading_zeros(fl):
"""Returns the number of leading zeros in a float decimal."""
if fl > 1.0:
return 0
else:
fl_splitted = str(fl).split(".")[-1]
N_unstripped = len(fl_splitted)
N_left_stripped = len(fl_splitted.lstrip("0"))
return N_unstripped - N_left_stri... | c009a9dcf7f2c57baee3043acf9ec416679fab67 | 698,145 |
def df_to_dictionaries(df, change_names={}, include_index=True):
"""Returns a list of dictionaries, one dictionary for each row in the
DataFrame 'df'. The keys of the dictionary match the DataFrame column names,
except for any substitututions provided in the 'change_names' dictionary;
{'old_name': 'ne... | f02c97318dda4da6bb082d3a78898584e27d353c | 698,147 |
def _s(word, seq, suffix='s'):
"""Adds a suffix to ``word`` if some sequence has anything other than
exactly one element.
word : str
The string to add the suffix to.
seq : sequence
The sequence to check the length of.
suffix : str, optional.
The suffix to add to ``word``
... | 7ae7a7ac50b6b6ee92718877d242569d7339fd0e | 698,150 |
def label2Addr(label, labels):
""" Return int address associated with label or None.
label is a string, either digits or symbolic.
Array labels has labels for all addresses in mem.
"""
if label.isdigit():
return int(label)
if label in labels:
return labels.index(label) | 27b1fe8edce3aa4ee33f2e7ff25843fa958da620 | 698,152 |
def evenify(n):
"""Ensure number is even by incrementing if odd
"""
return n if n % 2 == 0 else n + 1 | 8a0e3263c2a4853c25361fda434c88a5f6c45a91 | 698,158 |
import logging
def _LoadResource(path):
"""Load the resource at given path.
Args:
path: a string resource path.
Returns:
The contents of that resource.
Raises:
ValueError: If the path is not set up correctly.
IOError: If the path is not found, or the resource can't be opened.
"""
try:
... | 73b5e318214fe44e9de2af251a4e58e7e5ef0376 | 698,159 |
import random
def valid_add(gene_info, individual):
"""Based on gene info and current individual, return a valid index to add
to an individual.
"""
return random.choice(list(set(range(0, gene_info.gene_count))
- individual)) | bc02ea8d35175ebeb91caf47717bb4d6d8202119 | 698,161 |
from typing import Any
def serialise(obj: Any, no_head: bool = False) -> dict:
"""Takes any non-primitive object and serialises it into a dict.
Arguments:
obj(Any): Any non primitive object.
no_head(bool): Will not specify the module and class of the object when True.
Returns:
dict... | 80f306e4fea637bda548c6292d2d38ecba641af8 | 698,162 |
def bdev_pmem_create_pool(client, pmem_file, num_blocks, block_size):
"""Create pmem pool at specified path.
Args:
pmem_file: path at which to create pmem pool
num_blocks: number of blocks for created pmem pool file
block_size: block size for pmem pool file
"""
params = {'pmem_fi... | f8851fb3d6472751d213ca4b7c4c1d59915e929c | 698,165 |
from datetime import datetime
import pytz
def now_iso_time(zulu_frmt=True):
"""
Returns now time in ISO 8601 format in UTC
:param zulu_frmt: if True return zulu time format, e.g. '2020-11-26T13:51:29Z',
otherwise return string with UTC offset, e.g. '2020-11-26T13:51:29+00:00'
"""
time_now ... | 55abbdda86beeddf7d6ed5e8e95575b89d7f5071 | 698,167 |
import numbers
def _create_weights_tuple(weights):
"""
Returns a tuple with the weights provided. If a number is provided,
this is converted to a tuple with one single element.
If None is provided, this is converted to the tuple (1.,)
"""
if weights is None:
weights_tuple = (1.,)
... | 6d4006a4a88b47fb009e6f45cc654fd7642cbc6a | 698,169 |
def nasa_polynomial(output_str):
""" Parse the NASA polynomial from the PAC99 output file.
:param output_str: string for the output file
:type output_str: str
:rtype: str
"""
lines = output_str.splitlines()
return '\n'.join([lines[i] for i in range(11)]) | cf02c398ac54c40d814bf649fec2b7d3079a01c7 | 698,170 |
import torch
def get_metrics(pred_scores: torch.Tensor,
true_idx: torch.Tensor,
k_values: torch.Tensor):
"""Calculates mean number of hits@k. Higher values are ranked first.
Args:
pred_scores: (B, N) tensor of prediction values where B is batch size
and N n... | f0c21fbb993805222f2b84fcc6644868211a95b5 | 698,171 |
import re
def clean_text(s):
""" Remove non alphabetic characters. E.g. 'B:a,n+a1n$a' becomes 'Banana' """
s = re.sub("[^a-z A-Z _]", "", s)
s = s.replace(' n ', ' ')
return s.strip().lower() | ab18429927bbca362801ec815934aa8dc9a106e9 | 698,172 |
def IsArticleURL(para):
"""该函数接收一个参数,并判断其是否是简书的文章 URL。
Args:
para (str): 需要被判断的参数
Returns:
bool: 如为 True 代表是文章 URL,为 False 则不是
"""
if para.find("http") == -1:
return False
if para.find("www.jianshu.com") == -1:
return False
if para.find("/p/") == -1:
... | 91f9878938e1799373ef928aa8ed6ea0fea1a3ca | 698,174 |
def _validate_lod(lod, tensor_height=-1):
"""Check whether the input length-based lod info is valid.
There are several things to check:
1. lod should be a list of lists. Empty list is fine.
2. The length of each sublist (a lod level) should be at least one.
3. Each element in each lod level should ... | c9717eb8668b03e4da75abdf24003e9458eb9783 | 698,176 |
def escape_string(string):
""" Escape a string for use in Gerrit commands.
Adds necessary escapes and surrounding double quotes to a
string so that it can be passed to any of the Gerrit commands
that require double-quoted strings.
"""
result = string
result = result.replace('\\', '\\\\')
... | 2c3b16b67377de3cba821cc405c0c5e24943b995 | 698,180 |
import importlib
def import_consumer(value):
"""Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str value: The consumer class in module.Consumer format
:return: tuple(Class, str)
"""
parts = value.split('.')
import_... | c63d57614d7be9cfbda35d25b6634ffaec938288 | 698,181 |
def _MakeSplitDimension(value, enabled):
"""Return dict modelling a BundleConfig splitDimension entry."""
return {'value': value, 'negate': not enabled} | de4d44598e5c9c76e46b57b4b07f41698dbe983d | 698,182 |
import math
def calc_easing_degree_for_proportion(proportion):
"""
Calculates a reasonable easing degree for a given proportion.
"""
return -math.log10(proportion) + 1 | feeab6e87fba3060cbd37f89f3e0391df1bc1102 | 698,184 |
def spatial_mean(tensor, ndim=1):
"""
Average `tensor` over the last dimensions; keep only the first `ndim` ones.
"""
if tensor.ndim > ndim:
return tensor.mean(tuple(range(ndim, tensor.ndim)))
return tensor | 19bcf5df1d197069842792b9bd5d07a5e223d609 | 698,185 |
import binascii
def get_address_bytes_from_string(address_string):
"""
Given a Bluetooth address as a string, optionally delimited by colons (':'), return the
bytes representation of the address.
:param address_string: A Bluetooth address string, optionally delimited by commas. This value is case-in... | 88e83d5916c461e34300a330603e3975320d6568 | 698,186 |
def compute_mean_rt(df):
"""
Computes subject-wise mean RT
Input
---
df : dataframe
aggregate response data
Returns
---
array of subject-wise mean RTs
"""
return df.groupby('subject').rt.mean().values | 04b51953a8a5fa37fc746e32416bd0b598cfb138 | 698,188 |
import re
def add_iteration_suffix(name):
"""
adds iteration suffix. If name already ends with an integer it will continue iteration
examples:
'col' -> 'col_01'
'col' -> 'col_01'
'col1' -> 'col2'
'col_02' -> 'col_03'
"""
# pylint: disable=import-outside-toplevel
... | 8021f1bc131f0a303bfaa06caa39e77f1de0dff9 | 698,189 |
def min_max(tr):
"""Return the ratio of minimum to maximum of a trace.
Parameters
----------
tr : 1D array of float
The input profile.
Returns
-------
mm : float
The ratio of the minimum value in `tr` over the maximum.
Examples
--------
>>> tr = np.array([0.8, ... | 8fcb533f22addf95ccf6e75e3d116dfe928aa6ca | 698,190 |
def f(x): # 2
"""Simple recursive function.""" # 3
if x == 0: # 4
return 1 # 5
return 1 + f(x - 1) | ad71b050af9f3e634b8afab7565bc4df1c3f1222 | 698,191 |
def _assert_float_dtype(dtype):
"""Validate and return floating point type based on `dtype`.
`dtype` must be a floating point type.
Args:
dtype: The data type to validate.
Returns:
Validated type.
Raises:
ValueError: if `dtype` is not a floating point type.
"""
if not dtype.is_floating:
... | 7aee4b4bc4b389b718b3e7a8cb9a77c37fd4ff1e | 698,193 |
def get_value(str_val):
"""convert a string into float or int, if possible."""
if not str_val:
return ""
if str_val is None:
return ""
try:
val = float(str_val)
if "." not in str_val:
val = int(val)
except ValueError:
val = str_val
return val | a3c7deee4110ea25a88f8568139015be20fef1d0 | 698,194 |
def relation_bet_point_and_line( point, line ):
"""Judge the realtion between point and the line, there are three situation:
1) the foot point is on the line, the value is in [0,1];
2) the foot point is on the extension line of segment AB, near the starting point, the value < 0;
3) the foot point is o... | 92a1ed906ee4d7fbb97fa46668fedbbd5f704fba | 698,195 |
def escape_quotes(value):
"""
DTD files can use single or double quotes for identifying strings,
so " and ' are the safe bet that will work in both cases.
"""
value = value.replace('"', "\\"")
value = value.replace("'", "\\'")
return value | 1aa6e5f2325bfc293dff6e34b77117284d5bd018 | 698,196 |
import json
def init_population(ind_init, filename):
"""
create initial population from json file
ind_init: [class] class that and individual will be assigned to
filename: [string] string of filename from which pop will be read
returns: [list] list of Individual objects
"""
with ope... | 015b4d6b81dc44e325393535fc7abd65ca26db55 | 698,197 |
import random
def shuffle(l):
"""
Returns the shuffled list.
"""
l = list(l)
random.shuffle(l)
return l | 4945d5d57ecaf3c9b8340f3f20c5e960938f3914 | 698,198 |
def vec2num(vec):
"""Convert list to number"""
num = 0
for node in vec:
num = num * 10 + node
return num | ffce787a02bc9f2bc5669dd8fb622bdff1fc941b | 698,205 |
from datetime import datetime
def _iardict_to_fil_header(iardict: dict) -> dict:
"""Build dict header from dict iar."""
source_name = iardict["Source Name"]
source_ra = iardict["Source RA (hhmmss.s)"]
source_dec = iardict["Source DEC (ddmmss.s)"]
# ref_dm = iardict["Reference DM"]
# pul_period... | 920ce832d0ab9b7fa219b14572cbfa04c4c0dfc2 | 698,207 |
from typing import OrderedDict
def make_per_dataset_plot(delta_cchalf_i):
"""Make a line plot of delta cc half per group."""
d = OrderedDict()
d.update(
{
"per_dataset_plot": {
"data": [
{
"y": [i * 100 for i in list(delta_cc... | 219b7a981f896c7723e8f6ccde16819703503e54 | 698,210 |
def merge_sort(array):
"""
An implementation of the merge sort algorithm. Recursively sorts arrays
by calling merge sort on halves of the array, then merging by comparing
the first element of each array, then adding the smaller of the two to a
the sorted array.
"""
# Base Cases
if len(a... | 659260d8a9b9160d0576c62d17dadd91925fb05c | 698,211 |
def vectorize_cst(value, cst_precision):
""" if cst_precision is a vector format return a list uniformly initialized
with value whose size macthes the vector size of cst_precision, else
return the scalar value """
if cst_precision.is_vector_format():
return [value] * cst_precision.get_ve... | 9a5ba282309f8134007084e32a4a58876ec05d73 | 698,213 |
def split_me(strings):
"""
Function to split strings into an array to loop later
from the template.
"""
splited_values = strings.split(",")
return splited_values | 2b62cccac7602054b0e5cde34d0dbfc9964c0970 | 698,218 |
def hamming_distance(Subspace1, Subspace2):
"""
Returns the Hamming distance between to subspaces.
Variables that are free in either subspace are ignored.
**arguments**:
* *Subspace1, Subspace2* (dict): subspaces in dictionary representation
**returns**:
* *Distance* (int): the dis... | f42d13bd1d980b092235aa472a24a1cebe078f44 | 698,219 |
from pathlib import Path
def find_path(paths):
"""Given a search path of files or directories with absolute paths, find
the first existing path.
Args:
paths (list): A list of strings with absolute paths.
Returns:
str: The first path in the list `paths` that exists, or `None` if
... | 53dda06e55c26d0fce43bca5eea0cdc3fca53b11 | 698,224 |
def time_to_str(t):
""" Turns time objects to strings like '08:30' """
return t.strftime('%H:%M') | 6427b9267b63dc6d75dce2afae24bbbd58b0b0dd | 698,227 |
def test(one, two, three, **kwargs) -> int:
"""Return the sum of the arguments."""
return one + two + three + kwargs["four"] + kwargs["five"] + kwargs["six"] | c48a6968b6d4f1c673f7749e810d8d360e8d8d20 | 698,231 |
def _hierarch_keywords(names):
"""
Prepend the 'HIERARCH ' string to all keywords > 8 characters
Avoids FITS VerifyWarning.
Parameters
----------
names : list
keywords
Returns
-------
new_names : list
keywords with HIERARCH prepended as apprpriate
"""
new_na... | 73fc3f1594bf12a7c4a2c79d320aa490eb3d39e9 | 698,235 |
def get_size_of_corpus(filepaths):
""" Given a list of filepaths, it will return the total number of lines
Parameters
----------
filepaths : [ str ]
A list of filepaths
Returns
-------
num_lines : int
The total number of lines in filepaths
... | 46d166f7ae21ed345c45c38b782c7405790a8de2 | 698,239 |
from struct import unpack
from typing import Union
from pathlib import Path
def _tiff2xml(path: Union[Path, str]) -> bytes:
"""Extract OME XML from OME-TIFF path.
This will use the first ImageDescription tag found in the TIFF header.
Parameters
----------
path : Union[Path, str]
Path to ... | 6bd35d09c5edfd6362379ae3375e888e99f4609a | 698,242 |
def DistanceFromMatrix(matrix):
"""Returns function(i,j) that looks up matrix[i][j].
Useful for maintaining flexibility about whether a function is computed
or looked up.
Matrix can be a 2D dict (arbitrary keys) or list (integer keys).
"""
def result(i, j):
return matrix[i][j]
retu... | f3cb95aace0cfe70bfeef9d8778947df16cdd4b1 | 698,249 |
from pathlib import Path
def homedir() -> str:
"""Return the user's home directory."""
return str(Path.home()) | dbd65e7db4cdbf2bd06c1ab42ed1ea3503e14ac2 | 698,250 |
def quote_aware_split(string, delim=',', quote='"'):
""" Split outside of quotes (i.e. ignore delimiters within quotes."""
out = []
s = ''
open_quote=False
for c in string:
if c == quote:
open_quote = not open_quote
if c == delim and not open_quote:
out += [s... | 0ef5f7040eee2a041fa1b6e6d8bf3a773a80f5f9 | 698,256 |
def LMpM_total_size(ell_min, ell_max):
"""Total array size of Wigner D matrix
Assuming an array (e.g., Wigner D matrices) in the order
[[ell,mp,m] for ell in range(ell_min, ell_max+1)
for mp in range(-ell,ell+1)
for m in range(-ell,ell+1)]
this function returns the tot... | 7a6175640236ec3bc905d3b458f99eedbc792e09 | 698,262 |
def get_fcurve_data_path_property(fcurve):
""" Gets fcurve's data path property
Example fcurve's data_path: 'sequence_editor.sequences_all["Transform"].scale_start_x'
For that example path this function will return 'scale_start_x'
:param fcurve: Fcurve instance to get data path from
:return: The la... | 0a7ce5fecdaa5cb1fe0024a18f6b6f057b5fe6cb | 698,263 |
def align(offset, alignment):
"""
Return the offset aligned to the nearest greater given alignment
Arguments:
- `offset`: An integer
- `alignment`: An integer
"""
if offset % alignment == 0:
return offset
return offset + (alignment - (offset % alignment)) | 1f9d8fd4d4ac7798e14ee92d83510bb4b0ba09aa | 698,266 |
def parse_property_string(prop_str):
"""
Generate valid property string for extended xyz files.
(ref. https://libatoms.github.io/QUIP/io.html#extendedxyz)
Args:
prop_str (str): Valid property string, or appendix of property string
Returns:
valid property string
"""
if prop_... | 24a865dcf2cba5b5f840e3e682fd58486b658355 | 698,267 |
from typing import List
def _format_plugin_names_and_versions(plugininfo) -> List[str]:
"""Format name and version of loaded plugins."""
values: List[str] = []
for _, dist in plugininfo:
# Gets us name and version!
name = f"{dist.project_name}-{dist.version}"
# Questionable conveni... | 2313f2f60e71be2209ebb201297d44e8dcad513a | 698,272 |
def star_sub_sections(body:str):
"""
Change
\subsection
\subsubsection
To:
\subsection*
\subsubsection*
"""
body = body.replace(r'\subsection',r'\subsection*')
body = body.replace(r'\subsubsection',r'\subsubsection*')
return body | 06583d16c76393edb614955c4e3786b292c5fa51 | 698,273 |
def rjd_to_mjd(rjd):
"""
RJD (Reduced Julian Date)
days elapsed since 1858-11-16T12Z (JD 2400000.0)
MJD (Modified Julian Date)
days elapsed since 1858-11-17T00Z (JD 2400000.5)
This function transforms RJD in MJD
"""
return rjd - 0.5 | 2b1f4d830670f754fbbc2259face4d261877d335 | 698,275 |
def example_function(a: int) -> int:
"""Takes an integer as input and return it's square
Parameters
----------
a : int
input number
Returns
-------
int
square of a
"""
return a ** 2 | fd519e72ec385aa905868facee198b3eaf57f778 | 698,277 |
import doctest
def _quiet_testmod(module):
"""
Run all of a modules doctests, not producing any output to stdout.
Return a tuple with the number of failures and the number of tries.
"""
finder = doctest.DocTestFinder(exclude_empty=False)
runner = doctest.DocTestRunner(verbose=False)
for te... | 2c788dd128214e7c230124636aad3b0630060dd1 | 698,280 |
def _pango_attr_list_types(attributes):
"""Returns the types of all attributes in the given Pango.AttrList."""
# Pango.AttrList does not appear to have any normal ways to access its
# contents, so this is a bit of a hack.
types = []
attributes.filter(lambda attribute: types.append(attribute.klass.ty... | d14a28fd88eb60cbe8190efaf09e1b5081c437c5 | 698,282 |
import colorsys
def hue_sat_to_cmap(hue, sat):
"""Mkae a color map from a hue and saturation value.
"""
# normalize to floats
hue = float(hue) / 360.0
sat = float(sat) / 100.0
res = []
for val in range(256):
hsv_val = float(val) / 255.0
r, g, b = colorsys.hsv_to_rgb(hue, ... | 816cee4bbf69ee466cdade149b4f4b4547e9b29a | 698,284 |
import jinja2
def render_template(template_file, template_vars, searchpath="./templates/"):
"""
Render a jinja2 template
"""
templateLoader = jinja2.FileSystemLoader(searchpath=searchpath)
template_env = jinja2.Environment(loader=templateLoader)
template = template_env.get_template(template_fi... | d15f5d6e120a22ee5735dbf5b1f8c324a5cae861 | 698,287 |
def dict_sort(dictionary: dict) -> list:
"""Takes in a dictionary with integer values and outputs a list of the keys sorted by their associated values in descending order."""
return list(reversed(sorted(dictionary, key=dictionary.__getitem__))) | 330e6033a9e511341e5d9216a385b366a09eed9c | 698,289 |
import re
def get_citation_form(attributes):
""" Compute the citation form of a pronominal mention.
Args:
attributes (dict(str, object)): Attributes of the mention, must contain
the key "tokens".
Returns:
str: The citation form of the pronoun, one of "i", "you", "he", "she",
... | 2e02063ae0694e7ce76e3be8ce111d9550de7697 | 698,290 |
def bitpos_from_mask(mask, lsb_pos=0, increment=1):
"""
Turn a decimal value (bitmask) into a list of indices where each
index value corresponds to the bit position of a bit that was set (1)
in the mask. What numbers are assigned to the bit positions is controlled
by lsb_pos and increment, as explai... | d7938258c0f2dc523720bc82a48ecba1c2342223 | 698,293 |
def url_compose(camera):
""" Compose URL string for the camera """
# rtsp://88.204.57.242:5533/user=admin&password=******&channel=1&stream=1.sdp?
url: str = f'rtsp://{camera.ip_addr}:{camera.port}/user={camera.login}&password={camera.password}&channel=1&stream=0.sdp?'
return url | 62bf81b993e95a4c5ed7ca8362220cf16102c877 | 698,295 |
def get_first_package_name(name):
"""
Returns first package name.
From `a.b.c` it returns `a`.
:param str name: Full module name
:return: First package name.
:rtype: str
"""
return name.split(".")[0] | 814b175356ef715af46f788dc9eac7e776884b30 | 698,298 |
def _parse_url_work_relation(response):
""" response is
{'resource': 'https://imslp.org/wiki/7_Bagatelles,_Op.33_(Beethoven,_Ludwig_van)',
'relations': [{'source-credit': '',
'target-credit': '',
'type-id': '0cc8527e-ea40-40dd-b144-3b7588e759bf',
'type': 'download for free',
'end': None,
'direct... | 4e36330be029846bc44c235dafb20e6dc9c5f58f | 698,299 |
import toml
import yaml
import json
def mock_settings_file(request, monkeypatch, tmpdir, file_extension):
"""Temporarily write a settings file and return the filepath and the expected settings outcome."""
ext = file_extension
p = tmpdir.mkdir("sub").join("settings" + ext)
expected_result = {"testgrou... | 4899ebbc9efbe31a931387d4a09dcb8c727eaf8d | 698,303 |
def replicate_idx(head):
"""Return a list of indices representing replicate groups"""
h = head
g = h.groupby(['Sample Name', 'Measurement day'])
idx = [i[1].index for i in g]
return(idx) | ac5b80de8d15ef283185b0e93d495516695aa936 | 698,308 |
def str2ascii(string: str) -> list:
"""Convert a string to a list of ascii-codes"""
return [ord(i) for i in string] | a938b0c585e78a455721e9d17e8915b0769a025f | 698,310 |
def rgbToHexColor(r, g, b):
"""Convert r, g, b to #RRGGBB."""
return f'#{int(r):02X}{int(g):02X}{int(b):02X}' | 5cff9abc67c235a4f0fdf258ea555f018d80d1ad | 698,311 |
def filter_refgene_ensgene_exon(var_df_per_chrom, exon_class,
refgene, ensgene):
"""Filter for a refgene function, ensembl function or both.
Args:
var_df_per_chrom (:obj:`DataFrame`): all variants in a chromosome
variant_class (:obj:`str`): annovar variant class ... | 905db5cab873eabce8ee24872231f2dacabcec29 | 698,314 |
def _lin_f(p, x):
"""Basic linear regression 'model' for use with ODR.
This is a function of 2 variables, slope and intercept.
"""
return (p[0] * x) + p[1] | 52bc228dd48ee7939fa60cd052989de70a44b197 | 698,315 |
def mock_user(request):
"""Define a mock user to be used when testing REST API services"""
user = dict(
id="test_id",
name="User Name",
description="I'm a test user",
url="someurl",
)
return user | ff6eee62cd27328130bcd37c6164d3b4b17e2558 | 698,316 |
def get_type_as_string(instance: object) -> str:
"""
>>> x='a'
>>> get_type_as_string(x)
'str'
>>> x=1
>>> get_type_as_string(x)
'int'
>>> import decimal
>>> x=decimal.Decimal(1.00)
>>> get_type_as_string(x)
'Decimal'
>>> x=[]
>>> get_type_as_string(x)
'list'
... | 5fd2dd4362a98b2121f9ad2eb4e44ead83446327 | 698,317 |
def is_property(class_to_check, name):
"""Determine if the specified name is a property on a class"""
if hasattr(class_to_check, name) and isinstance(
getattr(class_to_check, name), property
):
return True
return False | 0f7dce28f1e78e8b6b937a5a6536060886666371 | 698,321 |
from string import ascii_uppercase
def get_cluster_label(cluster_id):
"""
It assigns a cluster label according to the cluster id that is
supplied.
It follows the criterion from below:
Cluster id | Cluster label
0 --> A
1 --> B
2 --> C
25 ... | 06210786dfb375dce31ec3c014cc5f545d019c50 | 698,323 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.