content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def xor(b1, b2):
"""Expects two bytes objects of equal length, returns their XOR"""
assert len(b1) == len(b2)
return bytes([x ^ y for x, y in zip(b1, b2)]) | 3376df85b52cea276417e29ae81c80208dc28b86 | 13,921 |
import random
import string
def random_string(length=1, unicode=False):
"""
Returns random ascii or unicode string.
"""
if unicode:
def random_fun():
return chr(random.choice((0x300, 0x2000)) + random.randint(0, 0xff))
else:
def random_fun():
return random.c... | 45760b3e3c42e484d51abf76f9eb2ae0c8132fd1 | 13,928 |
import math
def probability(ec, en, t):
"""
Probability function
:param ec: current energy
:param en: next energy
:param t: temperature ratio
:return: probability value
"""
return math.exp((ec - en) / t) | c055081cd93473ecf4abeab1c8b5cc36fb38f0a4 | 13,930 |
def add_ext(name, ext, seq=-1):
"""add_ext constructs file names with a name, sequence number, and
extension.
Args:
name (string) - the filename
ext (string) - the file extension
seq (int) - the number in a sequence with other files
(Default -1) means that it is a standalone
file
"""
#add peri... | 650eee088ae58d182c49f35f37e5b8deac57fa1d | 13,933 |
def get_coding_annotation_fasta(seq_record):
"""
When passed a sequence record object returns an array of FASTA strings for each annotation.
:param seq_record: A Biopython sequence record object.
:return: A FASTA file string containing all sequences record object CDS sequence features.
"""
fasta = []
features =... | 4fa24279ebb89ea7c61eeae6614c1fa309ffad87 | 13,936 |
from typing import Union
def bars_to_atmospheres(bar: float, unit: str) -> Union[float, str]:
"""
This function converts bar to atm
Wikipedia reference: https://en.wikipedia.org/wiki/Standard_atmosphere_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
>>> bars_to_atmospheres(3... | d460021395af77acda01296710f145e9b52d8594 | 13,937 |
def series(expr, x, point=0, n=6, dir="+"):
"""Series expansion of expr around point `x=point`.
See the doctring of Basic.series() for complete details of this wrapper.
"""
return expr.series(x, point, n, dir) | fee3fff7a29136813c7d6bf5d1cf7c576651368d | 13,940 |
def process_transform_funcs(trans_funcs, func_args=None, func_kwargs=None):
"""Process input of the apply_transform_funcs function.
:param iterable trans_funcs: functions to apply, specified the function or a (function, args, kwargs) tuple
:param dict func_args: function positional arguments, specified as ... | 2e9fe4bec55f0a13a0644cfe27ba887f00e85c55 | 13,942 |
import math
def _get_fov(pillow_image) -> float:
"""Get the horizontal FOV of an image in radians."""
exif_data = pillow_image.getexif()
# 41989 is for 'FocalLengthIn35mmFilm'.
focal_length = exif_data[41989]
# FOV calculation, note 36 is the horizontal frame size for 35mm
# film.
return ... | 9b8101010a980079d950b6151a3d5280d5eedb73 | 13,944 |
def pieChartInfoPlus(trips):
"""
Calculates the total distance per activity mode
Parameters
----------
trips : dict - Semantic information (nested)
Returns
-------
list(data): list - labels of the activity modes
list(data.values()): list - distance per activity mode
"""
la... | ad0306b2561b01a33c509b2c454f464e9c6ff8a3 | 13,946 |
def findCharacter(stringList, patternCharacter):
"""
Find the specific character from the list and return their indices
"""
return([ind for ind, x in enumerate(list(stringList)) if x == patternCharacter]) | 32cc8fb5970c6cd3cefd161b9e13e340f1645d13 | 13,949 |
def cell_trap_getter_generator(priv_attr):
""" Generates a getter function for the cell_trap property.
"""
def getter(self):
if getattr(self, priv_attr) is None:
data =\
(
self.gfpffc_bulb_1 - self.gfpffc_bulb_bg
)/self.gfpffc_bulb_bg
... | 15217adbd96ce44b361444867e5d9c6d202440f4 | 13,951 |
def bg_trim(im):
"""
Function to programmatically crop card to edge.
`im` is a PIL Image Object.
"""
# This initial crop is hacky and stupid (should just be able to set device
# options) but scanner isn't 'hearing' those settings.
# w,h = im.size
im = im.crop((443, 0, 1242, 1200))
# ... | b5b59059aa9823cd2be385ead5cc21b135a4e24b | 13,954 |
def get_filtered_query(must_list=None, must_not_list=None):
"""Get the correct query string for a boolean filter. Accept must and
must_not lists. Use MatchList for generating the appropriate lists.
"""
bool_filter = {}
if must_list:
bool_filter['must'] = must_list
if must_not_list:
... | 2190456ad7e91239bb623f7ec3d2c460e521e36f | 13,955 |
def convert_to_letter(grade):
"""Convert a decimal number to letter grade"""
grade = round(grade, 1)
if grade >= 82.5:
return 'A'
elif grade >= 65:
return 'B'
elif grade >= 55:
return 'C'
elif grade >= 50:
return 'D'
else:
return 'F' | 13ce25275750e7a27e0699078a15ba551674a941 | 13,956 |
def time_coord(cube):
"""
Return the variable attached to time axis.
Examples
--------
>>> import iris
>>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/'
... 'fmrc/us_east/US_East_Forecast_Model_Run_Collection_best.ncd')
>>> cube = iris.load_cube(url, 'sea_water_potent... | 12a706f956846e8471d0d7f044367c77210c4486 | 13,957 |
import re
def oneliner(s) -> str:
"""Collapse any whitespace in stringified `s` into a single space. """
return re.sub(r"[\n ]+", " ", str(s).strip()) | ed1d419b4fab8cb2deccdbc2944996ef7be28cc5 | 13,958 |
from typing import Counter
def diff_counts(values : list[int]) -> dict[int, int]:
"""Count the gaps between ordered elements in a list, by size."""
ordered = [0] + sorted(values) + [max(values) + 3]
return Counter(j - i for i, j in zip(ordered, ordered[1:])) | 897cb7fdfed85b37bd8bd7031290e34199c57574 | 13,960 |
def convert_netdict_to_pydict(dict_in):
"""Convert a net dictionary to a Python dictionary.
Parameters
----------
dict_in : dict
Net dictionary to convert.
Returns
-------
dict
Dictionary converted to Python.
"""
pydict = {}
for key in dict_in.Keys:
pyd... | 6aa9bb5ac00ff92d23ff5a449d096caad0d01c9c | 13,963 |
from typing import List
def binary_search(input_array: List[int], target: int):
"""
Given a sorted input array of integers, the function looks for a target or returns None
Returns:
Target index or None
"""
if not input_array or not target:
return None
left_pointer = 0
ri... | b9f389d1b31e5b95bb885bd638549f7775db207e | 13,964 |
def is_superuser(view):
"""Allow access to the view if the requesting user is a superuser."""
return view.request.user.is_superuser | 5a15433200634ca326c36bdc17acbc1ada4e6426 | 13,966 |
from typing import Any
import torch
import numbers
def python_scalar_to_tensor(data: Any, device: torch.device = torch.device("cpu")) -> Any:
""" Converts a Python scalar number to a torch tensor and places it on the given device. """
if isinstance(data, numbers.Number):
data = torch.tensor([data], de... | 83e4ac093a40225f9c5fe121d9b67424f258e039 | 13,969 |
def LIGHTNING(conf):
"""Get Lightning Color code from config"""
return conf.get_color("colors", "color_lghtn") | 08781e469c7262228904e883594e475be634816b | 13,971 |
from typing import Tuple
def InterpolateValue(x: float, xy0: Tuple[float, float], xy1: Tuple[float, float]) -> float:
"""Get the position of x on the line between xy0 and xy1.
:type x: float
:type xy0: Tuple[float, float]
:type xy1: Tuple[float, float]
:return: y
:rtype: float
"""
if ... | 9de4372b593fae65f772c19a8ac369315a8489d0 | 13,975 |
def boolean(prompt=None, yes='y', no='n', default=None, sensitive=False,
partial=True):
"""Prompt for a yes/no response.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
yes : str, optional
Response corresponding to 'yes'.
no : str, optional
... | 159c8be6004e4e9f2c5a271e36facd3610561b61 | 13,978 |
import torch
def compute_local_cost(pi, a, dx, b, dy, eps, rho, rho2, complete_cost=True):
"""Compute the local cost by averaging the distortion with the current
transport plan.
Parameters
----------
pi: torch.Tensor of size [Batch, size_X, size_Y]
transport plan used to compute local cost
... | 3d29e8ae5ef14ab30cd676eebeb6507e9cbfafca | 13,981 |
def electron_binding_energy(charge_number):
"""Return the electron binding energy for a given number of protons (unit
is MeV). Expression is taken from [Lunney D., Pearson J. M., Thibault C.,
2003, Rev. Mod. Phys.,75, 1021]."""
return 1.44381e-5 * charge_number ** 2.39\
+ 1.55468e-12 * char... | 6d5a845b1b11720b44b62500f979f0a621faca0a | 13,985 |
def parse_generic(data, key):
"""
Returns a list of (potentially disabled) choices from a dictionary.
"""
choices = []
for k, v in sorted(data[key].iteritems(), key=lambda item: item[1]):
choices.append([v, k])
return choices | 90d2f2188d5cca7adb53eebca80a80f2c46b04a7 | 13,986 |
def attrs_to_dict(attrs):
"""
Convert a list of tuples of (name, value) attributes to a single dict of attributes [name] -> value
:param attrs: List of attribute tuples
:return: Dict of attributes
"""
out = {}
for attr in attrs:
if out.get(attr[0]) is None:
out[attr[0... | ccf9440d29de2f8556e694f4ab87e95f0bfd9e8a | 13,987 |
def count(i):
"""List or text. Returns the length as an integer."""
return len(i) | d8daf7cd325ce1acfb382723759ff190becd785f | 13,989 |
def find_body(view):
"""
Find first package body declaration.
"""
return view.find(r'(?im)create\s+(or\s+replace\s+)?package\s+body\s+', 0) | b592199e4ef09d079645fc82ade8efbe3c92a895 | 13,994 |
def get_num_objects(tree):
""" Get number of objects in an image.
Args:
tree: Tree element of xml file.
Returns: Number of objects.
"""
num_obj = 0
for e in tree.iter():
if e.tag == 'object':
num_obj = num_obj + 1
return num_obj | 92f937cbbf2eabdc909ef6bc1f06ccb87e0148b7 | 13,999 |
from typing import Union
def _get_tol_from_less_precise(check_less_precise: Union[bool, int]) -> float:
"""
Return the tolerance equivalent to the deprecated `check_less_precise`
parameter.
Parameters
----------
check_less_precise : bool or int
Returns
-------
float
Toler... | 375f7918a04fafb4a79f77abd3f0282cdc74e992 | 14,001 |
def get_arg(cmds):
"""Accepts a split string command and validates its size.
Args:
cmds: A split command line as a list of strings.
Returns:
The string argument to the command.
Raises:
ValueError: If there is no argument.
"""
if len(cmds) != 2:
raise ValueError('%s needs an argument.' % c... | a12b9402cb824748127c9a925850a10f6a9fe022 | 14,003 |
def _magnitude_to_marker_size(v_mag):
"""Calculate the size of a matplotlib plot marker representing an object with
a given visual megnitude.
A third-degree polynomial was fit to a few hand-curated examples of
marker sizes for magnitudes, as follows:
>>> x = np.array([-1.44, -0.5, 0., 1., 2., 3., ... | cb030993c5799da9f84e9bbadb9fe30680d74944 | 14,009 |
def upto(limit: str, text: str) -> str:
""" return all the text up to the limit string """
return text[0 : text.find(limit)] | 0fbe1732954c225fe8d8714badb9126c8ab72a4d | 14,010 |
def check_occuring_variables(formula,variables_to_consider,allowed_variables) :
"""
Checks if the intersection of the variables in <formula> with the variables
in <variables_to_consider> is contained in <allowed_variables>
Parameters
----------
formula : list of list of integers
The formula to cons... | 16faf544cc6f4993afb1cad356037820d54225ba | 14,012 |
def _merge_config_dicts(dct1, dct2):
"""
Return new dict created by merging two dicts, giving dct1 priority over
dct2, but giving truthy values in dct2 priority over falsey values in dct1.
"""
return {str(key): dct1.get(key) or dct2.get(key)
for key in set(dct1) | set(dct2)} | 9d66c10438027254fbac7d8cc91185a07dd9da65 | 14,015 |
def from_list(*args):
"""
Input:
args - variable number of integers represented as lists, e.g. from_list([1,0,2], [5])
Output:
new_lst - a Python array of integers represented as strings, e.g. ['102','5']
"""
new_lst = []
for lst in args:
new_string = ''
for digi... | c3c0a2224433104a00ffabdadf612127d1b0ed3c | 14,017 |
def perpetuity_present_value(
continuous_cash_payment: float,
interest_rate: float,
):
"""Returns the Present Value of Perpetuity Formula.
Parameters
----------
continuous_cash_payment : float
Amount of continuous cash payment.
interest_rate : float
Interest rate, yield or discount r... | 26eb398776ce4f74348b23920b99b0390c462ff9 | 14,018 |
def __avg__(list_):
"""Return average of all elements in the list."""
return sum(list_) / len(list_) | 3204d823e83bd43efccf9886acd3ae8b01e1d7a0 | 14,022 |
import requests
def check_hash(h):
"""
Do the heavy lifting. Take the hash, poll the haveibeenpwned API, and check results.
:param h: The sha1 hash to check
:return: The number of times the password has been found (0 is good!)
"""
if len(h) != 40:
raise ValueError("A sha1 hash should be 30 characters.")
h = ... | 965dd75b5da095bc24ce6a6d733b271d9ec7aa80 | 14,028 |
def get_field_hint(config, field):
"""Get the hint given by __field_hint__ or the field name if not defined."""
return getattr(config, '__{field}_hint__'.format(field=field), field) | 0d374daf93646caf55fe436c8eb2913d22151bbc | 14,030 |
def btc(value):
"""Format value as BTC."""
return f"{value:,.8f}" | 1d883384a6052788e8fa2bedcddd723b8765f44f | 14,032 |
import time
def nagios_from_file(results_file):
"""Returns a nagios-appropriate string and return code obtained by
parsing the desired file on disk. The file on disk should be of format
%s|%s % (timestamp, nagios_string)
This file is created by various nagios checking cron jobs such as
check-rab... | 02697105ad5e9d01dd0eb504e232314f4d15a6a9 | 14,035 |
import math
def _width2wing(width, x, min_wing=3):
"""Convert a fractional or absolute width to integer half-width ("wing").
"""
if 0 < width < 1:
wing = int(math.ceil(len(x) * width * 0.5))
elif width >= 2 and int(width) == width:
# Ensure window width <= len(x) to avoid TypeError
... | 38bdb809167b19b0ef5c7fad6858d2f7016ec310 | 14,036 |
def mb_bl_ind(tr1, tr2):
"""Returns the baseline index for given track indices.
By convention, tr1 < tr2. Otherwise, a warning is printed,
and same baseline returned.
"""
if tr1 == tr2:
print("ERROR: no baseline between same tracks")
return None
if tr1 > tr2:
print("WARN... | 7d1bc958ca9928f54e51935510d62c45f7fc927f | 14,037 |
def datetime_format_to_js_datetime_format(format):
"""
Convert a Python datetime format to a time format suitable for use with
the datetime picker we use, http://www.malot.fr/bootstrap-datetimepicker/.
"""
converted = format
replacements = {
'%Y': 'yyyy',
'%y': 'yy',
'%m'... | a037146b17aae21831bc4c76d4500b12bc34feba | 14,040 |
def make_data(current_data):
""" Formats the given data into the required form """
x = []
n = len(current_data)
for i in range(n - 1):
x.append(current_data[i])
x.append(1)
return x, current_data[n - 1] | 04ff4ba93445895451c4c710e7aae59b9787a07d | 14,042 |
def average_over_dictionary(mydict):
"""
Average over dictionary values.
"""
ave = sum([x for x in mydict.values()])/len(mydict)
return ave | 584e8cb073c298b3790a96e2649dbacfd5716987 | 14,043 |
def treat_category(category: str) -> str:
""" Treats a list of string
Args:
category (str): the category of an url
Returns:
str: the category treated
"""
return category.lower().strip() | a4c08383bdfb40e5e64bbf576df53a7f46fc07da | 14,047 |
def _get_fully_qualified_class_name(obj):
"""
Obtains the fully qualified class name of the given object.
"""
return obj.__class__.__module__ + "." + obj.__class__.__name__ | e427991067254c2ac1963c5ae59468ec2c0835e2 | 14,049 |
import decimal
def new_decimal(value):
"""Builds a Decimal using the cleaner float `repr`"""
if isinstance(value, float):
value = repr(value)
return decimal.Decimal(value) | 023809d3db3e863f66559913f125e61236520a6a | 14,051 |
import unicodedata
def unidecode(s: str) -> str:
"""
Return ``s`` with unicode diacritics removed.
"""
combining = unicodedata.combining
return "".join(
c for c in unicodedata.normalize("NFD", s) if not combining(c)
) | 589dc0403c95e29f340070e3a9e81a6f14950c8e | 14,061 |
def AutoUpdateUpgradeRepairMessage(value, flag_name):
"""Messaging for when auto-upgrades or node auto-repairs.
Args:
value: bool, value that the flag takes.
flag_name: str, the name of the flag. Must be either autoupgrade or
autorepair
Returns:
the formatted message string.
"""
action =... | 7153b7aa44d6d798aa58d9328ac49097016c0879 | 14,062 |
import ast
import collections
import logging
def _get_ground_truth_detections(instances_file,
allowlist_file=None,
num_images=None):
"""Processes the annotations JSON file and returns ground truth data corresponding to allowlisted image IDs.
Args:... | 2650ff4ffeb13d0a7874164474fa47a82880d45d | 14,063 |
def decomp(n):
""" Retorna a decomposição em fatores primos de um inteiro em forma de dicionário onde as chaves são
as bases e o valores os expoentes.
Ex:
>>> decomp(12)
{2: 2, 3: 1}
>>> decomp(72)
{2: 3, 3: 2}
:param n: number
:return: dictionary
"""
expoente = 0
base... | 999d8be04ffd197ebdd14c88b525eb8ca4379bb9 | 14,075 |
import requests
def sendRequest(url, type="POST", params=None, headers=None):
"""
Send a request to a URL
### Input:
- `url` (str) | the url to send the request to
- `type` (str) | the type of request (GET or POST)
- `params` ... | 7f450b8eedf6405b237730b9f7d6da5277c41e7b | 14,080 |
def get_span_row_count(span):
"""
Gets the number of rows included in a span
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
rows : int
The number of rows included in the span
Example
-------
C... | e226e0f78bd6711a7ddbe9c749ed43d1d2bc476c | 14,083 |
def get_logbook_by_name(logbook_name, conn):
"""
Get a logbook by name from a persistence backend connection
:param str logbook_name: The name of the logbook to get
:param obj conn: A persistence backend connection
:return obj logbook: The logbook with the specified name
"""
return next(
... | 7ed83cfca3d7f0313046b39032c2b906c4bff410 | 14,085 |
from typing import List
def get_label_list(labels: List[List[int]]) -> List[int]:
"""Gets a sorted list of all the unique labels from `labels`.
Args:
labels: A list of lists, each corresponding to the label-sequence of a text.
Returns:
All the unique labels the ever appear in `labels`, g... | be795ff63c1eaccd221289708551a8ddd02b2cc5 | 14,088 |
def format_message(date_str, node, msg):
"""Format log message"""
message = f"{date_str}: {node.site_name}: {node.location or node.model} ({node.serial}) {msg}"
return message | 53dc7e2716f935a083c36e40ad4887cfe23c0aad | 14,089 |
def _world2fig(ff, x, y):
"""
Helper function to convert world to figure coordinates.
Parameters
----------
ff : `~aplpy.FITSFigure`
`~aplpy.FITSFigure` instance.
x : ndarray
Array of x coordinates.
y : ndarray
Array of y coordinates.
Returns
-------
coo... | 99df767d948bc1c0807b676e2178de1478a1ac71 | 14,098 |
def is_palindrome(number):
""" Returns True if `number` is a palindrome, False otherwise.
"""
num_str = str(number)
num_comparisons = len(num_str) // 2
for idx in range(num_comparisons):
if num_str[idx] != num_str[-1-idx]:
return False
return True | 391aec57bba8366d7e7ef2c8187fda377f5a786d | 14,099 |
from typing import Iterable
def flatten_list(li: Iterable):
"""Flattens a list of lists."""
if isinstance(li, Iterable):
return [a for i in li for a in flatten_list(i)]
else:
return [li] | 306536fdadf231b0a0f752bb63d7e01317819674 | 14,100 |
import re
def remove_unwanted_chars(x: str, *chars: str, to_replace: str = "") -> str:
"""Remove unwanted characters from a string."""
return re.sub(f"[{''.join(chars)}]", to_replace, x) | 4a1e25b1ad12f47f835d4f6cdbac4a6e08413077 | 14,106 |
def write_the_species_tree(annotated_species_tree, output_file):
"""
this function writes the species tree to file
args:
annotated_species_tree : a string of annotated species tree in .newick format
output_file : a file name to write to
output:
a file containing the annotated sp... | 7db9d5fc10cd27b1e7a5e51427e7de6991a1157a | 14,107 |
import functools
def compose(*functions):
"""
A functional helper for dealing with function compositions. It ignores any None functions, and if all are None,
it returns None.
Parameters
----------
*functions
function arguments to compose
Returns
-------
function or None
... | 8a18b1e0beef43c0cfac4439fa158675a486b560 | 14,108 |
def pretty_print_list(lst, name = 'features', repr_format=True):
""" Pretty print a list to be readable.
"""
if not lst or len(lst) < 8:
if repr_format:
return lst.__repr__()
else:
return ', '.join(map(str, lst))
else:
topk = ', '.join(map(str, lst[:3]))
... | d199261e6b9fd226256a151601d0bd86e7458fe1 | 14,109 |
def _partition(entity, sep):
"""Python2.4 doesn't have a partition method so we provide
our own that mimics str.partition from later releases.
Split the string at the first occurrence of sep, and return a
3-tuple containing the part before the separator, the separator
itself, and the part after the... | 0172ce09bd0451eb538122bd9566a3e70d0dcc15 | 14,117 |
import json
def load_dict_from_json(filename: str) -> dict:
"""
Load the given file as a python `dict`
Parameters
----------
filename: `str` an absolute path to the json file to be loaded.
Returns
-------
`dict` The loaded json file as a python dictionary.
"""
with open(filen... | 1d55e5dbcf33e7f1d21063be7b722a5ed5bc6bb3 | 14,125 |
def get_n_neighborhood_start_stop_indices_3D(volume_shape, point, n):
"""
Compute the start and stop indices along the 3 dimensions for the n-neighborhood of the point within the 3D volume.
Note that this returns an index range where the end is *non-inclusive*! So for a point at x,y,z with 0-neighborhood (... | 6eb1c6f0b4ff537b3d0eb1b647b019a2d61480b7 | 14,128 |
from typing import Dict
from typing import Any
def add_to_dict_with_swapped_keys(old_dict: Dict[Any, Dict],
new_dict: Dict[Any, Dict]) -> Dict[Any, Dict]:
"""
Swap the keys of two nested dictionaries in a new dictionary.
{'Key1': {'Key2': 42}} -> {'Key2': {'Key1': 42}}
... | 2b4d0a0d8bd2734d8c0bc7abde1fa659454f1464 | 14,129 |
import typing
import functools
def build_simple_validator(func: typing.Callable, *args, **kwargs) -> typing.Callable[[typing.Any], typing.Any]:
"""Build a ready-to-use simple validator out of a function.
Args:
- func: callable, the function to be called to validate an input
- args: list, args... | cc8227cce228579e51aa05ceb25d9020d51eb199 | 14,131 |
import torch
def quat_conjugate(a: torch.Tensor) -> torch.Tensor:
"""Computes the conjugate of a quaternion.
Args:
a: quaternion to compute conjugate of, shape (N, 4)
Returns:
Conjugated `a`, shape (N, 4)
"""
shape = a.shape
a = a.reshape(-1, 4)
return torch.cat((-a[:, :3... | 530eb2a8d8b9b87de2bfcaeb48729704908131cc | 14,132 |
def blank_lines(logical_line, blank_lines, indent_level, line_number,
previous_logical):
"""
Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to sepa... | 0f2d89ae662ffd39170e83f8788cf2946f7cd045 | 14,136 |
def shiny_gold_in(bag: str, rules: dict) -> bool:
"""Recursively check for shiny gold bags."""
if "shiny gold" in rules[bag].keys():
return True
elif not rules[bag]: # bag holds no others
return False
else:
for inner in rules[bag]:
if shiny_gold_in(inner, rules):
... | 1859f499b72a938a58a78af5ca1a78e9f7221731 | 14,148 |
def get_position_type(salary_plan):
"""
Given a salary plan code, map to one of the VIVO position types
"""
position_dict = {
'CPFI': 'postdoc',
'CTSY': 'courtesy-faculty',
'FA09': 'faculty',
'FA9M': 'clinical-faculty',
'FA10': 'faculty',
'FA12': 'faculty'... | eaaa64bfe35d27476eb9218d6401e0565126392d | 14,149 |
def str2ms(s):
"""
Convert the time strings from an SRT file to milliseconds.
Arguments:
s: A time value in the format HH:MM:SS,mmm where H, M, S and m are
digits.
Returns:
The time string converted to an integer value in milliseconds.
"""
s = s.strip()
time, ms ... | 552f9ffbd557cc0729c035901dc1a1a1bfae66d8 | 14,153 |
import torch
def get_device(inputs):
""" Get used device of a tensor or list of tensors. """
if isinstance(inputs, torch.Tensor):
device = inputs.device
elif isinstance(inputs, (tuple, list)):
device = inputs[0].device
else:
raise TypeError(f'Inputs can be a tensor or list of t... | eb67cb3a5ae226c4136bc172d37225ba6a64b45f | 14,157 |
def quick_sort(sequence: list) -> list:
"""Simple implementation of the quick sort algorithm in Python
:param sequence: some mutable ordered collection with heterogeneous comparable items inside
:return: the same collection ordered by ascending
"""
if len(sequence) < 2:
return sequence
... | 73470224b8f149568b84c7b723097fc0c2ef353f | 14,161 |
def score_tup(t):
"""
Score an ngram tuple returned from a database ngram table. A higher scoring
term is more deserving of inclusion in the resulting acrostic
:param t: (Term string, initials string, Corpus count, Used count)
:return: Fitness score for this term
"""
term = t[0]
inits = ... | eea34dbf2d6a7dec37dc95cde289560a77c72f7e | 14,163 |
import torch
def get_optimizer(parameters, lr, weight_decay):
"""
Initiate Adam optimizer with fixed parameters
Args:
parameters: filter, parameters to optimize
lr: float, initial learning rate
weight_decay: float, between 0.0 and 1.0
Return:
a torch.optim.Adam optimizer
"""
return torch.optim.Adam(p... | 54b4c6a4cd02672ebfc8ff9c850f0d601fc6510f | 14,165 |
import requests
def get_gist(url):
""" Get gist contents from gist url.
Note the gist url display the raw gist instead of usual gist page.
Args:
url (str) : url containing the raw gist instead of usual gist page.
Returns:
(str): output gist str.
""... | 853623c31af246dc07e22ac8a7dd0b515a74a080 | 14,171 |
import re
def is_email(addr):
"""
判断是否是合法邮箱
:param addr: 邮箱地址
:return: True or False
"""
re_is_email = re.compile("^[a-z0-9]+([._-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z]+$")
if re_is_email.search(addr):
return True
else:
return False | c48d931af7f57420d4b5829da02aa72203275f0f | 14,173 |
def merge_unique(a: list, b: list) -> set:
"""
merges all of the unique values of each list into a new set
>>> merge_unique([1, 2, 3], [3, 4, 5])
{1, 2, 3, 4, 5}
"""
ret = set()
a.extend(b)
for element in a:
ret.add(element)
return ret | 6a969c6beaee46e5618d25c5714cec223ebf1686 | 14,174 |
def get_wanted_parameter(season_data, names, index_para):
""" Take in a list of players' names, a wanted parameter and return
:param season_data: a dictionary of players' statistics
:param names: a list of players' names
:param index_para: index of the wanted parameter depending on the file
:return:... | 0d278abd79f28c922dfcacf4984af7efe14a9070 | 14,175 |
def DL_ignore(answers):
"""Return False if any dictionary-learning method was selected.
Arguments
---------
answers: dict
Previous questions answers.
Returns
-------
bool
True if DL verbosity question should be ignored.
"""
expected = ['ITKrMM', 'wKSVD', 'BPFA']
... | fda853fc0f959dd5302a90bc9d56f012a1d7da8f | 14,183 |
def wait(status, timeout=None, *, poll_rate="DEPRECATED"):
"""(Blocking) wait for the status object to complete
Parameters
----------
status: StatusBase
A Status object
timeout: Union[Number, None], optional
Amount of time in seconds to wait. None disables, such that wait() will
... | 3311714c7aee5cbbecf658bfa563826c363752e2 | 14,186 |
import re
def find_md_links(md):
"""Returns dict of links in markdown:
'regular': [foo](some.url)
'footnotes': [foo][3]
[3]: some.url
"""
# https://stackoverflow.com/a/30738268/2755116
INLINE_LINK_RE = re.compile(r'\[([^\]]+)\]\(([^)]+)\)')
FOOTNOTE_LINK_TEXT_RE = re.compile(r'\[... | d630d22d571e774312516fc4005444087d23392f | 14,187 |
def epoch_time(start_time, end_time):
"""
Computes the time for each epoch in minutes and seconds.
:param start_time: start of the epoch
:param end_time: end of the epoch
:return: time in minutes and seconds
"""
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
... | 8265cb78c26a96a83a1035c09a7dccb0edf8c4d0 | 14,189 |
def base_prob(phred_score):
""" Returns the probabilty that a base is incorrect, given its
Phred score.
"""
prob = 10.0**(-float(phred_score)/10)
return prob | 8231019213204e65d577ea86d1e2e0e7352a3f70 | 14,193 |
import re
def need_format(line: str) -> bool:
"""
Return true if line as a title declaration followed by content
"""
return (
(
re.search("\t+e_\w*[-'\w]*\W*=", line) is not None
and re.search("\t+e_\w*[-'\w]*\W*=\W*{[\w\t]*\n", line) is None
and re.search("... | 61576aa02a745db8b0ce0c9c4c9a4d4589e8d842 | 14,195 |
def builderFor(action, hypervisor=None, template=None, service=None):
"""
This decorator is used to supply metadata for functions which is then used to find suitable methods
during building just by these properties.
:param action: Name of the generic step/action (see planner) that this function impleme... | 1dddfd8dc5dbc87e5a018fc4fb144bef8a8f98e3 | 14,197 |
def undeployed_value_only_calculator(repository, undeployed_value_tuple, deployed_value_tuple):
"""
Just return the undeployed value as the value.
This calculator can be used when there will be no deployed value.
"""
return undeployed_value_tuple[2] | 58294274d37b4c7bb9cad21bb01260986cb0d6ae | 14,198 |
import re
def _remove_inner_punctuation(string):
"""
If two strings are separated by & or -, remove
the symbol and join the strings.
Example
-------
>>> _remove_inner_punctuation("This is AT&T here")
'This is ATT here'
>>> _remove_inner_punctuation("A T & T")
'A T T'
"""
... | 4ca3e7f91e35dba2e0a34f1dfd935e004623875e | 14,199 |
import random
def random_string(length, charset):
"""
Return a random string of the given length from the
given character set.
:param int length: The length of string to return
:param str charset: A string of characters to choose from
:returns: A random string
:rtype: str
"""
n = ... | 1370f86a2e696ba6030b719ec8e32631f1865e01 | 14,206 |
def reverse_spline(tck):
"""Reverse the direction of a spline (parametric or nonparametric),
without changing the range of the t (parametric) or x (nonparametric) values."""
t, c, k = tck
rt = t[-1] - t[::-1]
rc = c[::-1]
return rt, rc, k | 77c239fa8360657ed4ad4c1eb8d18493c97a84a1 | 14,209 |
import importlib
import pkgutil
def list_submodules(package, recursive=True):
"""
Recursively (optional) find the submodules from a module or directory
Args:
package (str or module): Root module or directory to load submodules from
recursive (bool, optional): Recursively find. Defaults to... | a5d69affc4cd19bd3e7c67c2d006c224bbafe80d | 14,210 |
def trainee_already_marked_training_date(trainee, training_date):
"""Check whether trainee already marked the given training date.
If trainee already has training day info it means he/she answered marked the given date.
Args:
trainee(models.Trainee): trainee instance to check whether already marke... | 138006be069201923017e0277ffec6a7c06080b4 | 14,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.