content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def getattrs(attrs, getclasses):
"""return all attributes in the attribute list attrs, which are
instances of one of the classes in getclasses"""
return [attr for attr in attrs if isinstance(attr, tuple(getclasses))] | c687931ba953d6c238ebd0a47b18e72c3a6fefe4 | 656,458 |
import time
def utcut2dow(ut):
"""UTC UT -> day-of-week: 0..6 (Mon..Sun)."""
return time.gmtime(ut).tm_wday | 993c3ada97e9cea0ff96ebc0d16f5db8e8acdb97 | 656,462 |
import torch
def _safe_det_3x3(t: torch.Tensor):
"""
Fast determinant calculation for a batch of 3x3 matrices.
Note, result of this function might not be the same as `torch.det()`.
The differences might be in the last significant digit.
Args:
t: Tensor of shape (N, 3, 3).
Returns:
... | 24f326d520cdb55ed4332c5542226c188260472f | 656,464 |
import types
from typing import Sequence
from typing import Tuple
def get_public_symbols(
root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]:
"""Returns `(symbol_name, symbol)` for all symbols of `root_module`."""
fns = []
for name in getattr(root_module, "__all__"):
o = getattr(... | 7ad0c30e48a80650429cf7e07a6625cdfc31faa5 | 656,467 |
def bud_cons(c1, r, e1, e2):
""" Defines the budget constraint
e = e1 + e2/(1+r) is total endowment
"""
e = e1 + e2/(1+r)
return e*(1+r) - c1*(1+r) | e80657afde4578d7ceeaa3788ace1d6ac9bbbc63 | 656,468 |
import importlib
def get_absolute_path_from_module_source(module: str) -> str:
"""Get a directory path from module source.
E.g. `zenml.core.step` will return `full/path/to/zenml/core/step`.
Args:
module: A module e.g. `zenml.core.step`.
"""
mod = importlib.import_module(module)
retur... | 3c089e7cc6e73b7490382ab9d4f5af0ad97c9f20 | 656,475 |
def write_peak_bedtool_string(cluster):
"""
Format Peak into NarrowBed format
:param cluster: Peak object
:return: str, format to NarrowBed format with tab-delimited, [chrom, start, stop, name, pval, strand, thick_start, thick_stop]
"""
cluster_info_list = [
cluster.chrom,
cluste... | 2890e478549a2a0e63d3056ce92397669697ce7b | 656,476 |
def remove_empty_string_list(str_list):
"""
Removes any empty strings from a list of strings
:param str_list: List of strings
:return: List of strings without the empty strings
"""
return list(filter(None, str_list)) | d268796d753bdf34a29c44b76a68b1d032b50997 | 656,480 |
import re
def upper_to_under(var):
"""
Insert underscore before upper case letter followed by lower case letter and lower case all sentence.
"""
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', re.sub('(.)([A-Z][a-z]+)', r'\1_\2', var)).lower() | 69e0b1f6b6d40688c9eac91e8026b1f1b7991a75 | 656,483 |
def compress(s: str) -> str:
"""
Compress `s` by dropping spaces before ' ,.' characters and
ensuring there is exactly one space before question mark
"""
dest = ""
for a, b in zip(s, s[1:]):
if a == ' ' and b in " ,.":
pass # do not append to dest
elif a != ' ' and b == '?':
dest += a + ' '
else:
d... | 306d088eff7ea9fd89e57ec5df79c3244d0295e9 | 656,485 |
from datetime import datetime
import pytz
def to_iso_time(timestamp):
"""Receives an arbitrary timestamp in UTC format (most likely in unix timestamp) and returns it as ISO-format.
:param timestamp: arbitrary timestamp
:return: timestamp in ISO 8601 and UTC timezone
"""
if isinstance(timestamp, (... | b180dd0f7ff581121b4f8f5ea0574e6df6825a42 | 656,486 |
def get_fields(feature):
"""Return a dict with all fields in the given feature.
feature - an OGR feature.
Returns an assembled python dict with a mapping of
fieldname -> fieldvalue"""
fields = {}
for i in range(feature.GetFieldCount()):
field_def = feature... | 5a9779fd74244fbd9b9611bb6158fce09bdba1b8 | 656,487 |
def _format_inputs(x):
"""Transform inputs into (m,n,1) format for cost/activation functions.
Returns formatted array.
"""
if x.ndim == 1: # vector
return x.reshape(1, -1, 1)
elif x.ndim == 2:
if x.shape[0] == 1: # either single-row matrix or 1x1 matrix
return x.T.resh... | 106328e5c2612e64f385d5750b5ef1429a1b7778 | 656,490 |
def _GetPrincipleQuantumNumber(atNum):
"""
Get the principle quantum number of atom with atomic
number equal to atNum
"""
if atNum<=2:
return 1
elif atNum<=10:
return 2
elif atNum<=18:
return 3
elif atNum<=36:
return 4
elif atNum<=54:
return 5... | 3dc3b41e6e31ab61608e7e4138a88c017a19fb94 | 656,491 |
def mjd2lst(mjd, lng):
""" Stolen from ct2lst.pro in IDL astrolib.
Returns the local sidereal time at a given MJD and longitude. """
mjdstart = 2400000.5
jd = mjd + mjdstart
c = [280.46061837, 360.98564736629, 0.000387933, 38710000.0]
jd2000 = 2451545.0
t0 = jd - jd2000
t = t0/36525.
... | 9df6b672fdf0c958e21cffd1f07938845974c95f | 656,494 |
def postpend_str(base_word: str, postpend: str, separator: str='') -> str:
"""Appends str:postpend to str:base_word
with default str:separator, returns a str
"""
return f'{base_word}{separator}{postpend}' | 6cf5c2e0fbd6f79e84c3b26fc27590904293b9eb | 656,499 |
def uniform(n: int) -> tuple:
"""
Return a Uniform(n) distribution as a tuple.
"""
return (1.0 / n, ) * n | caabbe375f980339abf94356f9dca5f80e1b2014 | 656,501 |
def extended_euclidean_algorithm(a, b):
"""Extended Euclidean algorithm
Returns r, s, t such that r = s*a + t*b and r is gcd(a, b)
See <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm>
"""
r0, r1 = a, b
s0, s1 = 1, 0
t0, t1 = 0, 1
while r1 != 0:
q = r0 // r1
... | 7a121b3769bcbb7c11f8552503db23cf489addbf | 656,508 |
def rotate(text, key):
"""
Caesar cipher the provided text with the provided key.
:param text string - Text to cipher.
:param key string - The key to use in the cipher.
:return text - ciphered text
"""
alpha = 'abcdefghijklmnopqrstuvwxyz'
out = ''
for index, char in enumerate(text):... | 3e0d4a80297f8b6f2884c1787e2a9eed909345d5 | 656,511 |
def isoformat(dt):
""" Formats a datetime object to an ISO string. Timezone naive datetimes are
are treated as UTC Zulu. UTC Zulu is expressed with the proper "Z"
ending and not with the "+00:00" offset declaration.
:param dt: the :class:`datetime.datetime` to encode
:returns: an en... | 621a0b652909bc171f421e17f578fde5797c5c96 | 656,512 |
def get_region_dir(hparams):
"""Return brain region string that combines region name and inclusion info.
If not subsampling regions, will return :obj:`'all'`
If using neural activity from *only* specified region, will return e.g. :obj:`'mctx-single'`
If using neural activity from all *but* specified ... | 3e06dc029b052f7f7c4e9998a7334bdfcfb653e8 | 656,513 |
def _call(partial, *args, **kwargs):
"""Calls a partial created using `make`.
Args:
partial: The partial to be called.
*args: Additional positional arguments to be appended to the ones given to
make.
**kwargs: Additional keyword arguments to augment and override the ones
... | daec08955bc02642f7579bb68c8e68c0525da999 | 656,517 |
from datetime import datetime
def from_isoformat(t):
"""Converts time from ISO-8601 string to datetime object"""
return datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%f") | 3c606528093ec8807475a848b7388b04fded0018 | 656,519 |
from typing import Callable
from typing import Optional
import types
def copy_definition(
definition: Callable, name: Optional[str] = None
) -> Callable:
"""
Copies a definition with same code, globals, defaults, closure, and
name.
Parameters
----------
definition
Definition to be... | abeebf6c97b1d8fa1da1cd8c05e636fecf2d1ecf | 656,525 |
import itertools
def sublists(lst, min_elmts=0, max_elmts=None):
"""Build a list of all possible sublists of a given list. Restrictions
on the length of the sublists can be posed via the min_elmts and max_elmts
parameters.
All sublists
have will have at least min_elmts elements and not more than m... | cb882a88498dbeb5352e935e794b5d45d92f2b42 | 656,526 |
import zipfile
def create_xml_list_from_zip(filepath):
"""
Opens the .zip file and extracts a list of .xml filenames
:param filepath: filepath to the .zip file
:return: list of .xml filenames
"""
return list(filter(lambda x: x[-3:] == 'xml', zipfile.ZipFile(filepath, 'r').namelist())) | b388d4e2728e4bc382de893a711732e46d065fea | 656,527 |
import re
def extractIdentifierFromFullURL(url):
"""Extracts just the PID from a full URL. Handles URLs on v1 or v2 and
meta/object/resolve/etc endpoints.
Arguments:
url : str
Returns: None if no match. Otherwise returns the identifier as a string.
"""
if not isinstance(url, str):
... | 90da2fa4b2d9880a9f65eb2bde8c925288a12ea4 | 656,531 |
def find_length_from_labels(labels, label_to_ix):
"""
find length of unpadded features based on labels
"""
end_position = len(labels) - 1
for position, label in enumerate(labels):
if label == label_to_ix['<pad>']:
end_position = position
break
return end_position | 3c5a839ed2d2b1bcbb08f80ef908437a76c7f870 | 656,533 |
def fileContents(fn):
"""
Return the contents of the named file
"""
return open(fn, 'rb').read() | 2475af0b7d33956897a137d3d8a066f6c4ce725d | 656,535 |
def count_elements(seq) -> dict:
"""Tally elements from `seq`."""
hist = {}
for i in seq:
hist[i] = hist.get(i, 0) + 1
return hist | 6e0a37ec23faede811c203229aff08cd4eb848bb | 656,537 |
import re
def parse_attributes_block_identifier(block):
"""Return the identifier in `block`.
Parameters
==========
block : string
Block to search in
Returns
=======
Either:
identifier : string
If identifier found
None
If no identifier found... | 29792d4803003df84eb81ed63bfe994af5a35710 | 656,545 |
import re
def find_matching_pattern(List, pattern):
""" Return elements of a list of strings that match a pattern
and return the first matching group
"""
reg_pattern=re.compile(pattern)
MatchedElements=[]
MatchedStrings=[]
for l in List:
match=reg_pattern.search(l)
if m... | 07b013a5662f2ae3210c605f8938a95f3a020600 | 656,546 |
def get_total(taxa_list, delim):
"""Return the total abundance in the taxa list.
This is not the sum b/c taxa lists are trees, implicitly.
"""
total = 0
for taxon, abund in taxa_list.items():
tkns = taxon.split(delim)
if len(tkns) == 1:
total += abund
return total | f76b36cdf810ffdbbe3f8508dff2e90d2ce497e7 | 656,552 |
import re
def punctuation_density(text, punctuation=r'[^\w\s]'):
"""Returns the punctuation density of the given text.
Arguments:
text (str): The input text.
punctuation (str): A regex pattern for matching punctuation characters.
Defaults to r'[,.!?:;\\/]'.
Returns:
(f... | e8e61737f67e2473b7593a6db6b3070bf0bb5dba | 656,553 |
def create_subparser(subparsers):
"""Creates this module's subparser.
Args:
subparsers: Special handle object (argparse._SubParsersAction) which can
be used to add subparsers to a parser.
Returns:
Object representing the created subparser.
"""
parser = subparsers.add_pa... | d47704ca2bd5cd23d6c98f6984323c3dce248013 | 656,555 |
def validate(message):
"""
Check if the message is in the correct format.
"""
if not ('x' in message and 'y' in message):
return False
if not(isinstance(message['x'], float)) or not(isinstance(message['y'], float)):
return False
return True | 2c8d16d2e789a47931b80bd13af028a220e5a4ae | 656,557 |
def linearize(solution):
"""Converts a level-ordered solution into a linear solution"""
linear_solution = []
for section in solution[0]:
for operation in section:
if not (operation.op[0] == 'P' and operation.op[1].isupper()):
linear_solution.append(operation)
return... | d2f9665890a336dee6abf7650596e5c58af19179 | 656,560 |
def option_to_cblas(x):
"""As above, but for CBLAS data-types"""
return {
'layout': "CBLAS_ORDER",
'a_transpose': "CBLAS_TRANSPOSE",
'b_transpose': "CBLAS_TRANSPOSE",
'ab_transpose': "CBLAS_TRANSPOSE",
'side': "CBLAS_SIDE",
'triangle': "CBLAS_UPLO",
'diago... | e333c99d0603a4dff89b382d2009a5d2a5db6d22 | 656,561 |
def get_remote_name(spec):
"""
Return the value to use for the "remote_name" parameter.
"""
if spec.mitogen_mask_remote_name():
return 'ansible'
return None | 1c9859ee69dc28db6da942dfb86f3c26c6756ec9 | 656,563 |
def _is_module(pkg):
""" Is this a module pacakge. Eg. foo-1-2.module+el8.1.0+2940+f62455ee.noarch
or for el9: foo-1-2.module_el9+96+b062886b """
return '.module+' in pkg.release or '.module_' in pkg.release | a630a4fbbabe45961afa46674832661673a11957 | 656,564 |
def arg_hex2int(v):
""" Parse integers that can be written in decimal or hex when written with 0xXXXX. """
return int(v, 0) | 670354e4a227e0057ea3b5b41167ec22c929004c | 656,567 |
import math
def Urms_calc(ua,ub,uc):
"""Function to calculate rms value of scalar phasor quantities."""
return math.sqrt((pow(abs(ua),2)+pow(abs(ub),2)+pow(abs(uc),2))/3.0)/math.sqrt(2) | ac6f370878d010e1bbc323185e1bd607e43a6b94 | 656,569 |
import csv
def load_log(filename):
""" Load the contents of a single log file.
"""
time = []
code = []
mesg = []
with open(filename, "r") as csvfile:
reader = csv.reader(csvfile)
for t, c, m in reader:
time.append(float(t))
code.append(int(c))
... | 4629b588d3ac65210f6116a94a6dcd116d88102a | 656,570 |
def is_junk(c):
"""
Return True if string `c` is a junk copyright that cannot be resolved
otherwise by the parsing.
It would be best not to have to resort to this, but this is practical.
"""
junk = set([
'copyrighted by their authors',
'copyrighted by their authors.',
'co... | d4c50d484c68a48b932c229bc405142b5d70f46f | 656,573 |
def readval(file, ty):
"""Reads a line from file with an item of type ty
:param file: input stream, for example sys.stdin
:param ty: a type, for example int
:returns: an element of type ty
"""
return ty(file.readline()) | c7b6c649cf92f1ba110dd79fd7296ea8a4487c38 | 656,578 |
import jinja2
def render_template(template_body: str, **template_vars) -> str:
"""render a template with jinja"""
if template_vars:
template_body = jinja2.Template(template_body).render(**template_vars)
return template_body | 26f4975a10f7aff5bdf5f3ce38a107b76e2816bd | 656,583 |
def formatter_str(formatstr):
"""
Creates a formatter function from format string, i.e. '%s, %s' etc
:param formatstr: The formatting string
:return: Formatter function using formatstr
"""
return lambda item: formatstr % item | 817d5bd7f21be932a7ca9419fe87918316e229f3 | 656,586 |
import requests
import hashlib
def get_hash(resource_url):
""" Access the URL provided and calculate an MD5 hash of whatever is returned.
Throw an exception, if the URL is not accessible.
"""
req = requests.get(resource_url, stream=True)
m = hashlib.md5()
for chunk in req.iter_content(chunk_si... | 4cd8f79f5e34bbd5992fb6522b130b8461ce82cf | 656,587 |
def line_strip(line):
"""
Remove comments and replace commas from input text
for a free formatted modflow input file
Parameters
----------
line : str
a line of text from a modflow input file
Returns
-------
str : line with comments removed and commas replaced
... | 0c643b37c377c3ba65b25852316a3bae3f45b13e | 656,588 |
def _merge(left, right):
"""
Function merges left and right parts
Args:
left: left part of array
right: right part of array
Returns:
Sorted and merged left + right parts
"""
merge_result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if lef... | db112a9ae55605ecfd7a4ebcc293c48732850889 | 656,592 |
def _get_input_output_names(onnx_model):
"""
Return input and output names of the ONNX graph.
"""
input_names = [input.name for input in onnx_model.graph.input]
output_names = [output.name for output in onnx_model.graph.output]
assert len(input_names) >= 1, "number of inputs should be at least 1... | 50b40334d69cb4fdaf7afdcd29809cbac675f27a | 656,594 |
def read_lines(file_path):
""" read file as a list of lines """
with open(file_path) as f:
return [l.strip() for l in f.readlines()] | 4127653af7b17d10f770d1302d5ac10a12111de6 | 656,596 |
def convert_red(string):
"""Return red text"""
return f"{string}" | 4b05b32c50ebeb062d6504544885fadd68626081 | 656,599 |
def _h_3ab(P):
"""Define the boundary between Region 3a-3b, h=f(P)
>>> "%.6f" % _h_3ab(25)
'2095.936454'
"""
return 0.201464004206875e4+3.74696550136983*P-0.0219921901054187*P**2+0.875131686009950e-4*P**3 | 68e8974cbcbeb873ac06fc1f61b32058b34899a3 | 656,602 |
def fnorm(f, normalization):
""" Normalize the frequency spectrum."""
return f / normalization | 453fba23dd9a07a7e82ead88f787ff9b6f47743d | 656,608 |
def neighbours( x, y, world ):
"""
Získá počet sousedů dané buňky.
Parametry:
x (int) X-ová souřadnice
y (int) Y-ová souřadnice
world (list) 2D pole s aktuálním stavem.
Vrací:
int Počet sousedů buňky na souřadnicích [x;y]
"""
# Počet sousedů
... | d780d79d31b99d1b753ed4a19bc3593e15a5af82 | 656,609 |
from typing import List
from typing import Dict
def remap_list(target_list: List[int], mapping: Dict[int, int]) -> List[int]:
"""
Take a list of atom indices and remap them using the given mapping.
"""
return [mapping[x] for x in target_list] | 8672f531490fbee6442eaca72b53df10c8844a14 | 656,611 |
import ast
from typing import Optional
from typing import List
def read_object_name(node: ast.AST, name: Optional[List[str]] = None) -> str:
"""Parse the object's (class or function) name from the right-hand size of an
assignement nameession.
The parsing is done recursively to recover the full import pat... | 0d0e9f32b14c5e121271d29a3f14151264c9cc5a | 656,616 |
import re
def get_one_match(expr, lines):
"""
Must be only one match, otherwise result is None.
When there is a match, strip leading "[" and trailing "]"
"""
# member names in the ld_headers output are between square brackets
expr = rf'\[({expr})\]'
matches = list(filter(None, (re.search(e... | 02be5aff39c90c7555618e9e87cb3f2d19e845ed | 656,624 |
import json
def _get_synset_labels(filepath: str) -> dict:
"""
Gets synsets from json file in a dict
Args:
filepath: json file path
Returns:
Dict having the following structure:
{str id : (int synset_ID, str label_name )}
"""
with open(filepath, "r") as f:
ra... | bc119f8930dcbe5b5f1a67521e0ff82d4b8aa925 | 656,625 |
def is_cap(word: str) -> bool:
"""Return True if the word is capitalized, i.e. starts with an
uppercase character and is otherwise lowercase"""
return word[0].isupper() and (len(word) == 1 or word[1:].islower()) | 78787ca4ed8a4c70b0b19a0c92aa6ae9d72ee2f1 | 656,629 |
def get_depth(od):
"""Function to determine the depth of a nested dictionary.
Parameters:
od (dict): dictionary or dictionary-like object
Returns:
int: max depth of dictionary
"""
if isinstance(od, dict):
return 1 + (max(map(get_depth, od.values())) if od else 0)
return... | d0b84853e4fb38e3f0e4329a36e4d48d2658df2f | 656,631 |
def add_dicts_by_key(in_dict1, in_dict2):
"""
Combines two dictionaries and adds the values for those keys that are shared
"""
both = {}
for key1 in in_dict1:
for key2 in in_dict2:
if key1 == key2:
both[key1] = in_dict1[key1] + in_dict2[key2]
return both | 9061e1abf09899e2f8a93c9c02899e2f8ba769a9 | 656,634 |
from pathlib import Path
def get_output_stem(attributes):
"""Get output file stem, specific to HYPE."""
short_to_stem = dict(tas="Tobs",
tasmin="TMINobs",
tasmax="TMAXobs",
pr="Pobs")
shortname = attributes["short_name"]
if sh... | 5bc226f157b7cca2b72bb70bcb77a61fbabd9416 | 656,635 |
from typing import Collection
from typing import Optional
def max_offset(offsets: "Collection[Optional[str]]") -> "Optional[str]":
"""
Return the most "recent" offset from a collection of offsets.
:param offsets: A collection of offsets to examine.
:return: The largest offset, or ``None`` if unknown.... | e34c64be7d52e99a9d4cc4aeb49c6e4d7587d93a | 656,638 |
def calculate_distance(P1, P2):
"""Calculates the distance of given points (1D to infinity-D)."""
if len(P1) != len(P2):
raise ValueError('Different dimension of given points.')
square_sum = 0
for i in range(len(P1)):
square_sum += (P1[i] - P2[i])**2
return square_sum**(1 / 2) | 079820b5e90dd485813e00e467b841d47d2f0fc7 | 656,639 |
def chunk_it(seq, num):
"""Split a sequence in a 'num' sequence of ~same size
"""
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return sorted(out, reverse=True) | 22273e199f0c02cb15b3c4efffb87d55eb173c5d | 656,640 |
def _ensure_unix_line_endings(path):
"""Replace windows line endings with Unix. Return path to modified file."""
out_path = path + "_unix"
with open(path) as inputfile:
with open(out_path, "w") as outputfile:
for line in inputfile:
outputfile.write(line.replace("\r\n", "... | c811eed0860f92dc58b2a184ec6d2a866ef6ee46 | 656,643 |
def cut_off_ringing(k, P, ir_cutoff=5e-5, uv_cutoff=1e2):
"""
Cut off ringing tail at high and low k
Parameters
----------
k: 1d numpy array
Note does not need to be ln-space
P: 1d numpy array
Function evaluated at corresponding k
"""
if ir_cutoff < k.min(): ir_cutoff = k.min()
if uv_cutoff > k.max(): uv_... | 50e343db69fd8ec53f2c632ae2b84eac8b7f3726 | 656,647 |
def grab_value_from_file(filename):
"""
Return the value from the first line of a file.
"""
return open(filename, 'r').readline().strip().split()[0] | 02fcf33e04fd5acae9f0e3ea7d4d19b753b8657e | 656,651 |
import ipaddress
def is_ipv4_address(ip_address):
"""
Checks if given ip is ipv4
:param ip_address: str ipv4
:return: bool
"""
try:
ipaddress.IPv4Address(ip_address)
return True
except ipaddress.AddressValueError as err:
return False | d225f7627655265959976fe6451903b06ef393d9 | 656,652 |
def _is_kanji(char):
""" Check if given character is a Kanji. """
return ord("\u4e00") < ord(char) < ord("\u9fff") | 6c785eca322002b80ff20212d1a914e538d684ab | 656,654 |
def multiline_input(prompt):
"""Prompt for multiline input"""
lines=[]
print(prompt+" (input will end after entering a blank line) : >")
while True:
line=input()
if not line.strip():
break
else:
lines.append(line)
return "\n".join(lines) | e2841d59b249cda46b47f9690de4ff04efdc29ff | 656,655 |
def fatorial(numero=1, show=False):
"""
-> Calcula o Fatorial de um número.
:param numero: O número a ser calculado.
:param show: (opcional) Mostrar ou não a conta.
:return: O valor do Fatorial de um número n.
"""
fat = 1
ext = ''
for i in range(numero, 0, -1):
... | d83804f839ef36a20fdf8af69d85a9d5a2f9fdfc | 656,658 |
def test_add_to_registry(
CallableRegistry, # noqa: N803
PropertyRegistry,
CachedPropertyRegistry,
CallableParamRegistry,
PropertyParamRegistry,
CachedPropertyParamRegistry,
):
"""A member can be added to registries and accessed as per registry settings."""
@CallableRegistry.registry()... | 5396b034dbe81d04d8b6b1e6d9ae805dc5e86ffe | 656,660 |
def loss(y, ybar, sparm):
"""Loss is 1 if the labels are different, 0 if they are the same."""
return 100.0*int(y != ybar) | 2e6e8d1c13117839c4cb2432e5d92fcdf2bcc8f8 | 656,661 |
def flat_correct(ccd, flat, min_value=None, norm_value=None):
"""Correct the image for flat fielding.
The flat field image is normalized by its mean or a user-supplied value
before flat correcting.
Parameters
----------
ccd : `~astropy.nddata.CCDData`
Data to be transformed.
flat ... | abcd91b54f0664ae05b294fcc64b42f04dfdccef | 656,662 |
def format_response_data(sparkl_response):
"""
Builds easy-access object from response data sent back by SPARKL.
"""
# Get name of response/reply and list of output fields
try:
response_name = sparkl_response['attr']['name']
fields_data_list = sparkl_response['content']
# Retur... | bb952b9eb4cb54b0079887e1d9d7d5c76db1ae7f | 656,667 |
def coding_problem_12(budget, choices):
"""
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a
function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 un... | 034dc1ece7c03bd1ebfbc4614c291166448a6a57 | 656,669 |
from typing import Sequence
from functools import reduce
from operator import mul
def prod(digits: Sequence[str]) -> int:
"""
Returns the product of a string of digits.
"""
return reduce(mul, map(int, digits)) | 016e29bd6a9da420883157c4f4e38f353ad71e86 | 656,675 |
def truncate_term_rankings( orig_rankings, top ):
"""
Truncate a list of multiple term rankings to the specified length.
"""
if top < 1:
return orig_rankings
trunc_rankings = []
for ranking in orig_rankings:
trunc_rankings.append( ranking[0:min(len(ranking),top)] )
return trunc_rankings | bd2724e83311b0f1ac35188087a9ec329e3955ac | 656,676 |
import math
def calculate_sin(x):
"""
Return the sine of x (measured in radians).
"""
return math.sin(x) | c86ead20f04ffd4ada1fd40ad45a79d5186da3b4 | 656,678 |
import struct
import socket
def inet_ntoa(i):
"""Like `socket.inet_nota()` but accepts an int."""
packed = struct.pack('!I', i)
return socket.inet_ntoa(packed) | 143bbf3652633b57b66d8398dae5058b3de92314 | 656,679 |
def format_sec_to_dhm(sec):
"""Format seconds to days, hours, minutes.
Args:
sec: float or int
Number of seconds in a period of time.
Returns: str
Period of time represented as a string on the form ``0d\:00h\:00m``.
"""
rem_int, s_int = divmod(int(sec), 60)
rem_int, m_int,... | 0dff0fb83f904465f5177cf7d38368ac1f44e8e4 | 656,680 |
import ast
from typing import List
from typing import Tuple
def get_scr119(node: ast.ClassDef) -> List[Tuple[int, int, str]]:
"""
Get a list of all classes that should be dataclasses"
ClassDef(
name='Person',
bases=[],
keywords=[],
body=[
... | eef10160a580c4b09451e69dd3054499e1d6ab91 | 656,690 |
import click
def style_prompt(message):
"""Returns a unified style for click prompts."""
return click.style(message, fg="cyan") | f04246be8f5b6afd689c46eae5529d3565f8fb7d | 656,692 |
def is_prime(n):
"""Return True if n is a prime."""
if (n % 2 == 0 and n > 2) or n == 1:
return False
return all(n % i for i in range(3, int(n**0.5) + 1, 2)) | 4c1518664a464275f62a214c26c4b21796155c29 | 656,695 |
def _cache_name(request):
"""
Name for a preset cache.
"""
return "cache_%s" % request.user.username | ef722856d763c7288da12abcaa579b92af5c0a23 | 656,697 |
def book_value_per_share(book_value, total_shares):
"""Computes book value per share.
Parameters
----------
book_value : int or float
Book value (equity) of an enterprice
total_shares : int or float
Total number of shares
Returns
-------
out : int or float
Book ... | 80abcbb505892f1e028c2f45d7c725c763c1d33e | 656,698 |
from typing import List
import json
def str_to_list_of_ints(val) -> List[int]:
"""Accepts a str or list, returns list of ints. Specifically useful when
num_hidden_units of a set of layers is specified as a list of ints"""
if type(val) == list:
return val
else:
return [int(v) for v in... | d1a8c471f0eb6bad828fdb6eb5bb42febfb2b36d | 656,700 |
def center_crop(image, crop_size=None):
"""Center crop image.
Args:
image: PIL image
crop_size: if specified, size of square to center crop
otherwise, fit largest square to center of image
Returns:
cropped PIL image
"""
width, height = image.size
#... | 8159de83517289c8997ba5507bc62871eea3144c | 656,704 |
from typing import List
from typing import Dict
def get_syntax_coloring_dicts(self) -> List[List[Dict]]:
"""
Converts the text in the editor based on the line_string_list into a list of lists of dicts.
Every line is one sublist which contains different dicts based on it's contents.
We create a dict f... | 250569c0a2079cb9de2b709cc7f069caab776279 | 656,708 |
def name_version_release(spec_fh):
"""
Take the name, version and release number from the given filehandle pointing at a sepc file.
"""
content = {}
for line in spec_fh:
if line.startswith('Name:') and 'name' not in content:
content['name'] = line[5:].strip()
elif line.st... | 6599beaaf980c133c3748c6d8433e58be2fc20e2 | 656,709 |
import pathlib
import collections
import logging
def get_text(directory):
"""
Return a concatenated string of section texts from the specified directory.
Text files should be UTF-8 encoded.
"""
section_dir = pathlib.Path(directory)
paths = sorted(section_dir.glob('[0-9]*.md'))
name_to_text... | 81d8483ee3f5943b0b15923fd9d451e7849a7df7 | 656,715 |
def import_class(class_path):
"""
Imports a class having dynamic name/path.
Args:
class_path: str
Path to class (exp: "model.MmdetDetectionModel")
Returns:
mod: class with given path
"""
components = class_path.split(".")
mod = __import__(components[0])
for c... | 7f7957a28b90c01509e0a4490ba03ef2cd0f7abb | 656,716 |
import re
def rmPunct(string) :
"""Remove punctuation"""
return re.sub(r'[^\w\s]','',string) | 5257273f2eda6d9746b05c26aca3172a63e1cdb8 | 656,717 |
def remove_min_count(df, min_count):
"""
Function remove_min_count: This function removes data that is all zeros in a column
best used once merging has taken place to get rid of all features that are zero in both conditions
:param df: @type pandas dataframe: The data to remove counts below min_count... | 6d18de9fc5acbec2e5324daf4ce3c3d6f50bd713 | 656,719 |
def sort_by_score(iterable):
"""Sorts a collection of objects by their score attribute, descending.
Args:
iterable: iterable collection of objects with a score attribute.
Returns:
The collection sorted by score descending.
"""
return sorted(iterable, key=lambda x: x.score, reverse=True) | 3b79220b4605bd9ddf754f6ba2356f2df7e1485f | 656,721 |
import math
def next_power_of_two(x: int) -> int:
"""Return next highest power of 2, or self if a power of two or zero."""
if x == 0:
return 0
assert x >= 1, f"x must be 1 or greater; was: {x}"
result = int(2 ** math.ceil(math.log2(x)))
assert result >= x
return result | 84b253d86cc4531362c7592d10a56d056519834f | 656,723 |
def escape_filter_chars(assertion_value,escape_mode=0):
"""
Replace all special characters found in assertion_value
by quoted notation.
escape_mode
If 0 only special chars mentioned in RFC 4515 are escaped.
If 1 all NON-ASCII chars are escaped.
If 2 all chars are escaped.
"""
if escape_mo... | 62a01c646001b6ed996225e21bfe37af95252e08 | 656,725 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.