content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import time
def seconds_since(t):
"""seconds_since returns the seconds since `t`. `t` is assumed to be a time
in epoch seconds since time.time() returns the current time in epoch seconds.
Args:
t (int) - a time in epoch seconds
Returns
int: the number of seconds since `t`
"""
... | db398fa2a18689c5ccd05d365948e9b5cd1f99d5 | 24,519 |
def intersect(box1, box2):
"""Calculate the intersection of two boxes."""
b1_x0, b1_y0, b1_x1, b1_y1 = box1
b2_x0, b2_y0, b2_x1, b2_y1 = box2
x0 = max(b1_x0, b2_x0)
y0 = max(b1_y0, b2_y0)
x1 = min(b1_x1, b2_x1)
y1 = min(b1_y1, b2_y1)
if x0 > x1 or y0 > y1: # No intersection, return No... | 70daa13f0f0e59bbb21f52a74434935a4424dc68 | 24,520 |
def donottrack(request):
"""
Adds ``donottrack`` to the context, which is ``True`` if the ``HTTP_DNT``
header is ``'1'``, ``False`` otherwise.
This context processor requires installtion of the
``donottrack.middleware.DoNotTrackMiddleware``.
Note that use of this context processor is not stric... | 50dc0c60ed70137c9aa1473ae436e48ef859ae9a | 24,522 |
def _sort_orders(orders):
"""Sort a list of possible orders that are to be tried so that the simplest
ones are at the beginning.
"""
def weight(p, d, q, P, D, Q):
"""Assigns a weight to a given model order which accroding to which
orders are sorted. It is only a simple heuristic that mak... | a164aa850e44ddb59429436b78ea2cf0603a1aae | 24,524 |
def ToGLExtensionString(extension_flag):
"""Returns GL-type extension string of a extension flag."""
if extension_flag == "oes_compressed_etc1_rgb8_texture":
return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
# unfortunate.
uppercase_words =... | 78d767beba572291193c9819f885c8eb46650c1c | 24,525 |
def uniqued(iterable):
"""Return unique list of items preserving order.
>>> uniqued([3, 2, 1, 3, 2, 1, 0])
[3, 2, 1, 0]
"""
seen = set()
add = seen.add
return [i for i in iterable if i not in seen and not add(i)] | 51bc142d6872a2e811724cd0371f982a390d8f06 | 24,528 |
def genKgris(k):
"""
Calcule une liste de ``k`` teintes de gris allant du noir au blanc.
Paramètre:
k --> nombre de teintes (>=2)
La liste génére doit nécessairement commencer par la couleur noir (0,0,0)
et nécessairement terminer par la couleur blanc (255,255,255).
Les autres valeurs... | 3e480d5bba5f60e3448392da97c7d7738f5decad | 24,531 |
def fromRoman(r):
"""Return the numeric value of a valid roman numeral."""
# Handle subtractions by trying to match two characters first.
# If this fails, match only one character.
romanMap = dict((('M', 1000), ('CM', 900), ('D', 500),
('CD', 400), ('C', 100), ('XC', 90),
... | b03c49bf1dfb3f72585ff2667cf9df2eea9e7a4c | 24,532 |
import glob
def summfile(ifldpth,idx):
""" Find _x1dsum file ending with idx + '_x1dsum.fits'
Parameters
----------
ifldpth : str
path to the files
idx : str
the file ends with idx + '_x1dsum.fits'
e.g. idx = '10'
Returns
-------
fname : str
sum file name... | 05f6778276487de8feb684dca41c326321335049 | 24,534 |
def get_hashable_cycle(cycle):
"""
Cycle as a tuple in a deterministic order.
Args
----
cycle: list
List of node labels in cycle.
"""
# get index of minimum index in cycle.
m = min(cycle)
mi = cycle.index(m)
mi_plus_1 = (mi + 1) if (mi < len(cycle) - 1) else 0
... | 28e81992a4fc306151e8ac87426721f41d516beb | 24,535 |
def get_susceptibility_matrix_index(age):
"""
The age matrix is 16x16 and it's split in groups of 4,
We can use whole division to quickly get the index
"""
if age >= 75:
return 15
else:
return age // 5 | 6efb3665f8578820d4bd1c969538c3026f2bdcf9 | 24,541 |
def truncate(string, length=60):
"""Truncate the given string when it exceeds the given length."""
return string[:length - 4] + '.' * 3 if len(string) > length else string | c3bfc6d78703830e23240e671bc5c29f1cdcb19d | 24,543 |
from PIL import Image
def pilnew_imageobject(image_file: str):
"""Returns a PIL image object from a referenced image file.
Args:
image_file (str): Reference an existing image file.
Returns:
PIL.Image.Image: Returns a PIL image object
"""
#
image_object = Image.open(image_... | f80e8b2cb9a4a93f94fe1d3005c53caa54c00877 | 24,545 |
def string_handler(item):
"""
Create a string out of an item if isn't it already.
Parameters:
- item: The variable to make sure it is a string.
Returns:
The input as a string.
"""
return (
str(item)
if not isinstance(item, str) else
item
) | dcd767d1e05bab1f2ce770347b578b627005acf4 | 24,546 |
import random
def random_word_swap(sentence, p):
"""Swaps words from a sentence with probability p."""
def swap_word(new_words):
idx_1 = random.randint(0, len(new_words) - 1)
idx_2 = idx_1
counter = 0
while idx_2 == idx_1:
idx_2 = random.randint(0, len(new_words) - 1)
counter += 1
... | f81467776a3c1e8bae3fdb411bd95f8c6440fea2 | 24,550 |
def is_array_type(rtype):
"""
Test to see if return type parameter is a NumPy array.
:param str rtype: Return type parameter.
:return: *True* if return type parameter is a NumPy array, *False* if not.
:rtype: bool
"""
if rtype.lower() in ['ndarray', 'array', 'arr', 'np', 'a']:
retu... | 6973a9e1830b89fea87c70e42df97bbfc39e49c2 | 24,554 |
def check_magnetic_atoms(in_path: str) -> list:
"""
Args:
in_path (str) - path for the prepared to siman structure reader POSCAR type file.
Returns:
magnetic_atoms (list) - list of magnetic atoms in prepared
structures with "fake" atoms
e.g
... | b0428fea0767688823b30cab14a11052fed0d149 | 24,560 |
import torch
from typing import Callable
from typing import Iterable
from typing import Tuple
def make_batcher(
x: torch.Tensor, y: torch.Tensor, batch_size: int
) -> Callable[[], Iterable[Tuple[torch.Tensor, torch.Tensor]]]:
"""Returns a function that can be called to yield batches over x and y."""
asser... | 2bcb36b9eca07f86aed565a437bdb2b9b5cb21f6 | 24,564 |
import re
def munge_subject_to_filename(subject):
"""Derive a suitable filename from a commit's subject"""
if subject.endswith('.patch'):
subject = subject[:-6]
return re.sub(r'[^A-Za-z0-9-]+', '_', subject).strip('_').lower() + '.patch' | b67350f2f4003f04c234103a2e3f7f1bf34dedbf | 24,567 |
def abstract_class(cls_):
"""Decorate a class, overriding __new__.
Preventing a class from being instantiated similar to abc.ABCMeta
but does not require an abstract method.
"""
def __new__(cls, *args, **kwargs):
if cls is cls_:
raise TypeError(f'{cls.__name__} is an abstract c... | 15e6f5472b3a6e29ad26fd9c705ea418e9917ceb | 24,569 |
def is_upvoted(submission):
"""
If a comment is upvoted, we assume the question is welcomed, and that
there's no need for a template answer.
"""
min_score = 3
min_comment_count = 1
return (
submission.score > min_score and
len(submission.comments) > min_comment_count
) | 90fe43e6cd681a15daa97dba039e7fa94ac617ca | 24,572 |
def get_label(filename, labels=["head", "body", "arm","tail", "leg", "ear"]):
"""
If the filename contains the word in the list called labels, it returns a pair of name and id number.
example:
get_labels(./raccoon/labels/head.ply, ["head, leg"]): It will return ("head",0)
get_label... | 6c83e714de6c0b4959524110ac8dbe2f5210485d | 24,581 |
def _get_dropbox_path_from_dictionary(info_dict, account_type):
"""
Returns the 'path' value under the account_type dictionary within the main dictionary
"""
return info_dict[account_type]['path'] | 0869c08cd9d0f70d9dcdeb5bee843a6c9046d5bc | 24,585 |
def binary_search(array, value):
"""Search for value in sorted array, using binary search
Continually divide (sub-) array in half until value is found, or entire
array has been searched. Iterative approach.
Parameters
array : list
List to search. Must be sorted.
value : any
Val... | 08fc6be6571854a0003a7ccc354c397dfb791059 | 24,586 |
from typing import Tuple
def blend_colors(
rgba: Tuple[int, int, int, float], rgb: Tuple[int, int, int]
) -> Tuple[int, int, int]:
"""Get the resulting RGB color of an RGBA color rendered over an RGB color."""
red = (rgba[0] * rgba[3]) + (rgb[0] * (1 - rgba[3]))
blue = (rgba[1] * rgba[3]) + (rgb[1] * (1 - rgba[... | bf48b7193002a48aa8996c543c3bd5633ae06362 | 24,587 |
def stripnl(s):
"""remove newlines from a string"""
return str(s).replace("\n", " ") | da0a46707b19b6faa054cd1e4dad96b9651b3f0b | 24,589 |
from typing import List
def solution(board: List[List[int]]) -> int:
"""
입력된 2차원 배열에서 가장 큰 1로 된 정사각형을 구하라
Args:
board (List[List[int]]): 각각의 원소가 1이나 0으로 되어 있는 2차원 배열
Returns:
int: 가장 큰 정사각형의 넓이
"""
row, calumn = len(board), len(board[0])
global_max = 0
for i in range(... | a34b7decafc1dc79bce566335e4edba7900e7744 | 24,592 |
import re
def distribute(string, delim, groups=[r'\S+', r'\S+']):
"""Distributes one part of a string to other parts of that string (seperated
by a delimiter), returning a list of strings.
Args:
string: input string
delim: regex matching delimiter between two parts of string to be
... | 3b64474cabdf755bd41088e9e7f8d8a6e20adec4 | 24,593 |
import random
def generateColor(text):
"""Deterministically generates a colour for a given text."""
random.seed(text)
return ('#%06X' % random.randint(0,0xFFFFFF)) | 6577ba33642b68bdef3d1cec914078fa1d2b8b27 | 24,600 |
def unit_size(size):
""" Convert Byte size to KB/MB/GB/TB.
"""
units = ['KB', 'MB', 'GB', 'TB']
i = 0
size = size / 1024
while size >= 1024 and i<(len(units)-1):
i = i + 1
size = size / 1024
return '%.2f %s'%(size, units[i]) | 9f174d94cd7c3e57399f0689d67c35fe97da5e23 | 24,607 |
def tally_output(cons_file, output_path, file_stem):
"""Writes a tally file for easy graphing/analysis."""
tally_file = "{}/{}.tally".format(output_path, file_stem)
with open(cons_file, "r") as reader, open(tally_file, "w") as writer:
for line in reader:
if line.startswith('#'):
writer.write(line.split(... | 02c1b20a1e71482344e5ad8516a2f8ed86429a60 | 24,608 |
def project_is_connected(project, user):
"""
Return True if the given project is connected (joined and authorized).
"""
return project.is_joined(user) | 7d513406f1ec66eb57d8f7a6f0dc5688d521f755 | 24,617 |
def filter_lower_case_keys(dict):
"""
Filter dict to include only lower case keys.
Used to skip HTTP response fields.
:param dict: Dict with all capabilities parsed from the SSDP discovery.
:return: Dict with lower case keys only.
"""
return {key: value for key, value in dict.items() if k... | f441202f6ae66ab023431c42680f349169ea0f79 | 24,627 |
def supports_int(value: object) -> bool: # noqa: E302
"""Check if an int-like object has been passed (:class:`~typing.SupportsInt`).
Examples
--------
.. code:: python
>>> from nanoutils import supports_int
>>> supports_int(1.0)
True
>>> supports_int(1.5)
Fal... | c7a920837a080030d1300c99951d887ed4917091 | 24,637 |
from typing import Callable
from typing import Dict
from typing import Any
def memoized(func: Callable) -> Callable:
"""Decorator that caches values returned by a function for future calls.
The first time func is called with a particular sequence of arguments, the
result is computed as normal. Any subseq... | fd348711215713aff3361cfc47609634a457de88 | 24,638 |
def intify_and_make_intron(junction):
"""Convert start and stop strings to ints and shorten the interval
Interval is shortened to match the introns of SJ.out.tab files from STAR
Parameters
----------
junction : tuple
(chrom, start, stop, strand) tuple of strings, e.g.
('chr1', '100... | 200a8504e0a28194ea70fe9e9702094b6ddeb1f1 | 24,640 |
def get_value_for_key_from_json(key, data_structure):
"""
Given a data_structure return the *first* value of the key from the first dict
example:
data_structure: [ { "id": 1, "name": "name1" }, { "id": 2, "name": "name2"} ]
key: "id"
return 1
:param key: key of a dict of which t... | 071d6c771d750bdef99a209ba537d0709c1d9582 | 24,641 |
import pickle
def predict(dataX):
""" Predict dependent variable from a features vector """
# load model
model = pickle.load(open('model.pickle', 'rb'))
# predict
predY = model.predict(dataX.values.reshape(-1, dataX.shape[1]))
return predY | 85505d3435ad8593542851680aef7491058a0239 | 24,642 |
def format_pci_addr(pci_addr):
"""Pad a PCI address eg 0:0:1.1 becomes 0000:00:01.1
:param pci_addr: str
:return pci_addr: str
"""
domain, bus, slot_func = pci_addr.split(':')
slot, func = slot_func.split('.')
return '{}:{}:{}.{}'.format(domain.zfill(4), bus.zfill(2), slot.zfill(2),
... | 9da677c2f1ff832cfbe86f19dffcada1fb33003a | 24,643 |
import re
def make_url_pattern(url: str, version: str) -> str:
"""Returns a regular expression for matching versioned download URLs.
Args:
url: Existing download URL for `version`.
version: Version corresponding to `url` (must be a substring).
Returns:
Regular expression that matches URLs similar ... | 384a58bf8ef02b75f510fe5884445e297862f0ef | 24,647 |
import re
def parse_not_to_prune(model, config):
"""Returns a list of names of modules not to prune in the model"""
patterns = [re.compile(s) for s in config.not_to_prune]
parsed_not_to_prune = []
for name, module in model.named_modules():
if type(module).__name__ in config.prune_layer_types:
... | 71e56a5c3d9a2502e8309225feeb127b8b98f7eb | 24,648 |
def right(x):
"""Helper function: argument x must be a dot.
Returns dot right of x."""
return (x[0]+1,x[1]) | bbb9b16ddbecd8bb452d941e5a871c9799f2ca7a | 24,651 |
def isMatch(peak, biomarker, tolerance):
"""Check if spectral peak matches protein biomarker
Args:
peak: Spectral peak obatained from experiment, float
biomarker: An array of biomarker values
tolerance: Maximal difference between experimental weight and
theoretical one that coul... | a81a67deca75a4d41c17707dc2e8e528c8fc3949 | 24,654 |
def create_stratum_name(stratification_name, stratum_name, joining_string="X"):
"""
generate a name string to represent a particular stratum within a requested stratification
:param stratification_name: str
the "stratification" or rationale for implementing the current stratification process
:p... | d778f2538c3e9c451bcafba287ef34fcc5bed07b | 24,658 |
import socket
def get_node_address(node_name=''):
"""
Return the IP address associated to the node's domain.
This is by no means perfect and should not be
relied upon aside from testing purpose.
"""
return socket.gethostbyname(socket.getfqdn(node_name)) | d3f8b5c39118cf05e195d82430f024ef27d01c21 | 24,659 |
def extract_muMax(df_Annotations):
"""
Extracts the growth rate (Slope) for each sample.
Parameters
----------
df_Annotations : pandas.DataFrame
The dataframe contains the results of a linear fit through the
exponential growth phase.
Returns
-------
df_mu : pandas.DataF... | 63ca33ddf29c0bfc1ee1af49ef5b6ad4f89829ff | 24,663 |
def _parse_system_prop(line):
"""Returns the name and value of a system property (The line is preceded by @).
Args:
line (str): The definition of the system property.
Returns:
str, str: Pair of name, value.
"""
return line[1:].split("#")[0].split("=") | f2822175a717f9ee96524438eaa610898f7fb613 | 24,664 |
def pentad_to_month_day(p):
"""
Given a pentad number, return the month and day of the first day in the pentad
:param p: pentad number from 1 to 73
:type p: integer
:return: month and day of the first day of the pentad
:rtype: integer
"""
assert 0 < p < 74, 'p outside allowe... | 183c3954fe6ee003af28ca13d2a2207812d66483 | 24,665 |
def balance_from_utxos(utxos):
"""Return balance of a list of utxo.
Args:
utxos: A list of utxo with following format.
[{
txid: ''
value: 0,
vout: 0,
scriptPubKey: '',
}]
... | e20373db24483bb33189b396da44b2c453b717d9 | 24,678 |
from typing import Counter
def most_common_letter(s: str) -> str:
"""Returns the most common letter in a string."""
return Counter(s).most_common(1)[0][0] | 9cf0d1fb6790a2f5a72dff976423868c0dce9a89 | 24,685 |
def captcha_halfway(numbers):
"""Sum the digits that match the one half way around a cyclic string."""
total = 0
for i in range(int(len(numbers) / 2)):
if numbers[i] == numbers[i + int(len(numbers) / 2)]:
total += int(numbers[i])
return total * 2 | c772c194c038484c144337dd32d93ab74e1d9370 | 24,696 |
def get_all_regions(config):
"""Retrieve a set of all regions used by the declared integration tests."""
regions = set()
for feature in config.get("test-suites").values():
for test in feature.values():
for dimensions_config in test.values():
for dimensions_group in dimens... | c2dfddc73601f3661f482cf0ed5547b9b8434689 | 24,697 |
def keras_name_to_tf_name_block(keras_name,
keras_block='block1a',
tf_block='blocks_0',
use_ema=True,
model_name_tf='efficientnet-b0'):
"""Mapping name in h5 to ckpt that belongs to a block.... | 6a249f992be1c1232ba8415523b8408be5680133 | 24,699 |
def _format_version(name):
"""Formats the string name to be used in a --version flag."""
return name.replace("-", "_") | 9b0bb72d6cef2836dce1f6c0d167ba41ce5a487b | 24,705 |
import math
def rho2_rho1(M, beta, gamma):
"""Density ratio across an olique shock (eq. 4.8)
:param <float> M: Mach # upstream
:param <float> Beta: Shock angle w.r.t initial flow direction (radians)
:param <float> gamma: Specific heat ratio
:return <float> Density ratio r2/r1
"""
m1sb =... | 20de69d2ac14100cd8c88e3f51eb14220052195b | 24,706 |
import logging
import pathlib
def collector(name, fields, filepath, append=False, format_types=None, delimiter='|'):
"""
Returns a function for collecting rows with fields :fields: (along with
datetime information) in a CSV log file located at :filepath:.
We often want to collect some data about choi... | 0f6f9fd0df1e262d2b0d0a8d4965f8038722e649 | 24,717 |
def print_network(net, out_f=None):
"""
Prints the number of learnable parameters.
:param net: the network.
:type net:
:param out_f: file
:type out_f:
:return: number of learnable parameters.
:rtype: int
"""
num_params = 0
for param in net.parameters():
num_params +=... | 9dcfd7da51eab385dacb90d35bfeb139ed785be1 | 24,720 |
def _skip_first_max_pooling(inputs):
"""Whether to skip the first max pooling layer in ResNet.
For 128x128 inputs, we skip the first 3x3 2-stride max pooling layer.
Args:
inputs: The inputs passed to ResNet.
Returns:
Whether to skip the first max pooling layer in ResNet.
"""
dims = inputs.shape.d... | 45425522c23191e014c9cb687baf1a5d123fc443 | 24,723 |
def is_hom(G, H, hom):
"""
Check whether hom is a homomorphism from G to H.
Works for both directed and undirected.
"""
assert set(G.vertices()) == set(hom.keys())
assert set(H.vertices()).issuperset(set(hom.values()))
for e in G.edges():
u, v = e[0], e[1]
if not H.has_edge(hom[u], hom[v]):
... | 256ed3b2b496ed72bcd4e23f6f28bcc742049e15 | 24,725 |
from typing import List
from typing import Any
def lazy_content(__list: List, /, nvals: int, ellipsis: Any = ...) -> List:
"""Return list at most {nvals} items from object
Extra values are replaced with mid_value
Examples:
>>> lazy_content([1, 2, 3, 4, 5], 3)
... [1, ..., 5]
"""
... | 7af6fe6766c677b0bd9261c305e1e5301567045f | 24,728 |
def clear_form(n_clicks):
"""Empty input textarea"""
return "" | a1d72b827f61d14d898170129d8dee75adf2a88a | 24,729 |
def wrap_to_pmh(x, to2):
"""Wrap x to [-to/2,to/2)."""
to = to2/2
return (x + to)%to2 - to | 29a1ce74e903fb23c316ec841097bf571f561a40 | 24,735 |
def return_index(lbound, ubound, cells, position):
"""
Give the position of a node on a 1D mesh this function will return the corresponding index
of that node in an array that holds the node positions.
lbound: Lower bound of mesh domain.
ubound: Upper bound of mesh domain.
cells: Number of ... | dcb0fb35f6ec8b5d7d948b951ce6677d27023a95 | 24,736 |
import huggingface_hub
def list_metrics(with_community_metrics=True, with_details=False):
"""List all the metrics script available on the Hugging Face Hub.
Args:
with_community_metrics (:obj:`bool`, optional, default ``True``): Include the community provided metrics.
with_details (:obj:`bool`... | db833a683cb3a549ba040cd5ef3c020c7286624e | 24,742 |
def pathCount(stairs: int):
"""number of unique ways to climb N stairs using 1 or 2 steps"""
#we've reached the top
if stairs == 0:
return 1
else:
if stairs < 2:
return pathCount(stairs - 1)
return pathCount(stairs - 2) + pathCount(stairs - 1) | 69992b4f1a0043935a34ae15a3370f78d0bbf274 | 24,744 |
def _split_comment(lineno, comment):
"""Return the multiline comment at lineno split into a list of comment line
numbers and the accompanying comment line"""
return [(lineno + index, line) for index, line in
enumerate(comment.splitlines())] | 07a4f160ce47d9391b90646cf8b43b18eb32ed14 | 24,751 |
def ts_path(path):
"""Make a URL path with a database and test suite embedded in them."""
return "/api/db_<string:db>/v4/<string:ts>/" + path | c007887e752af8aa4be6936f1fceb3df873d9d61 | 24,752 |
def display_formatter(input_other_type):
"""
Used by QAbstractItemModel data method for Qt.DisplayRole
Format any input value to a string
:param input_other_type:
:return: str
"""
return str(input_other_type) | 8f5e619d98e666f3d6820ec119dd01b11d357555 | 24,753 |
def first_name(s):
"""
Returns the first name in s
Examples:
last_name_first('Walker White') returns 'Walker'
last_name_first('Walker White') returns 'Walker'
Parameter s: a name 'first-name last-name'
Precondition: s is a string 'first-name last-name' with one or more... | ca37032ac865981ff83d8f076b3c827334e2fc58 | 24,757 |
def replace_keys(d, old, new):
"""replace keys in a dict."""
return {k.replace(old, new): v for k, v in d.items()} | 44e44308741e37a3b499aac4518cff74f087a589 | 24,761 |
from typing import Union
import io
def _hash(fn, buffer: Union[io.StringIO, io.BytesIO]):
"""Partial function for generating checksum of binary content."""
buffer.seek(0)
hashsum = fn()
for chunk in iter(lambda: buffer.read(4096), b''):
hashsum.update(chunk)
return hashsum.hexdigest() | c2b7b3ba1487273b7759d396d29e0aece15b5efa | 24,766 |
import inspect
def _num_required_args(func):
""" Number of args for func
>>> def foo(a, b, c=None):
... return a + b + c
>>> _num_required_args(foo)
2
>>> def bar(*args):
... return sum(args)
>>> print(_num_required_args(bar))
None
borro... | dacc2ed0165ea8bc1e4be45bf2a9477778d2fe45 | 24,768 |
def expand(values, index, padding=128):
""" Modify in place and return the list values[] by appending
zeros to ensure that values[index] is not out of bounds.
An error is raised if index is negative.
"""
assert index >= 0, f"Oops: negative index in expand(values, index={index})"
if index... | 6f4d09244972e7af28b6119706a8095bedbc629d | 24,769 |
import typing
import dataclasses
def dataclass_from_dict(cls: type, src: typing.Dict[str, typing.Any]) -> typing.Any:
"""
Utility function to construct a dataclass object from dict
"""
field_types_lookup = {field.name: field.type for field in dataclasses.fields(cls)}
constructor_inputs = {}
f... | f91ddb784d3a0ef4a2c5d78205f4a7908b79a1b3 | 24,772 |
from typing import Any
def pm_assert(
condition: Any,
exc: Any=Exception,
context: Any=None,
msg: str="",
) -> Any:
""" Generic assertion that can be used anywhere
@condition: A condition to assert is true
@exc: Raise if @condition is False
@context: The relevant da... | a99f0ed3f460f95c84a1391664cc2bc169f17201 | 24,775 |
def resize_halo_datasets(halos_dset, new_size, write_halo_props_cont, dtype):
"""
Resizes the halo datasets
Parameters
-----------
halos_dset: dictionary, required
new_size: scalar integer, required
write_halo_props_cont: boolean, required
Controls if the individual halo properti... | a5461a776a0991eda04fc5d0e1d2a2a14e6e1f5f | 24,780 |
def checksum(sentence):
"""Calculate and return checsum for given NMEA sentence"""
crc = 0
for c in sentence:
crc = crc ^ ord(c)
crc = crc & 0xFF
return crc | 841c35f11c5f4a46cfb62efc04379fa54772e739 | 24,784 |
def _apply_affine_scalar(i, j, k, affine_matrix):
"""
Applies an affine matrix to the given coordinates. The 3 values i, j and k must be scalars. The affine matrix consists of a 3x3 rotation matrix and a 3x1 transposition matrix (plus the last row).
Parameters
----------
i, j, k: numeric scalars
... | a548ac37cad242549e7f40ab799a2361dc2733ff | 24,791 |
import re
def get_dict(post, key):
""" Extract from POST PHP-like arrays as dictionary.
Example usage::
<input type="text" name="option[key1]" value="Val 1">
<input type="text" name="option[key2]" value="Val 2">
options = get_dict(request.POST, 'option')
... | 35649820407161432f5e3d01816376e67b19ea82 | 24,799 |
import json
def json_load(file):
"""
load json data from file.
"""
with open(file, 'r', encoding='utf8') as _file:
data = json.load(_file)
return data | 9d2ef792a9d2b201a5608601057f4f76e7905662 | 24,804 |
from typing import Dict
from typing import Any
def severity(event: Dict[str, Any]) -> str:
"""Maps `score` of a Qualys event to `severity`.
Possible `score` values:
0 = Known Good [File/Process/Network]
1 = Remediated [File/Process/Network]
2 = Suspicious Low File event
3 ... | 4952bbf5b76f7d5f7ab16d1ef9f475a9a5f54582 | 24,805 |
def get_diff(df, column1, column2):
"""Get the difference between two column values.
Args:
df: Pandas DataFrame.
column1: First column.
column2: Second column.
Returns:
Value of summed columns.
Usage:
df['item_quantity_vs_mean'] ... | 1fc5ec361cfdd28775257980c28b4924fdab4eeb | 24,810 |
def int_to_bytes(number: int) -> bytes:
"""Convert integer to byte array in big endian format"""
return number.to_bytes((number.bit_length() + 7) // 8, byteorder='big') | 1158b63b71774c6202aa4c96dae54eca2fae2c0a | 24,811 |
import random
def DEFAULTPOLICY(state):
"""
random policy
:param state: from this state, run simulation with random action
:return: final reward after reaching the final state
"""
while state.terminal() == False: # simulate until terminal state
random_action = random.randint(0, 3)
... | 99a281406c5a293a9040b2c772ca60fdc7b6a2eb | 24,814 |
import hashlib
from pathlib import Path
def label_generator(predictions, processor, filename):
"""Generates a unique label for the image based on the predicted class, a hash,
and the existing file extension.
Parameters
----------
predictions : np.array
Output from model showing each targe... | 8baba1aad6ad9a7f4d69b499a76b1b4079e79cb5 | 24,817 |
import re
def parse_csl_item_note(note):
"""
Return the dictionary of key-value pairs encoded in a CSL JSON note.
Extracts both forms (line-entry and braced-entry) of key-value pairs from "cheater syntax"
https://github.com/Juris-M/citeproc-js-docs/blob/93d7991d42b4a96b74b7281f38e168e365847e40/csl-jso... | 2a9076c646cd3efff12a4f2bbc3d639e2104a5b3 | 24,822 |
def field_is_required(field):
""" Returns true if the field is required (e.g. not nullable) """
return getattr(field, 'required', False) | 15eaf261ef0316c06272b1c38e0ec65bd16e77e6 | 24,834 |
from datetime import datetime
def date_to_datetime(value):
"""Get datetime value converted from a date or datetime object
:param date/datetime value: a date or datetime value to convert
:return: datetime; input value converted to datetime
>>> from datetime import date, datetime
>>> from pyams_ut... | 5ba2d15d8169d923b87181545eb910f1715ac4c2 | 24,836 |
def filter_set_options(options):
"""Filters out options that are not set."""
return {key: value for key, value in options.items() if value} | e6605af08626189a501895973c59d6dd9956cb55 | 24,838 |
def not_in_dict_or_none(dict, key):
"""
Check if a key exists in a map and if it's not None
:param dict: map to look for key
:param key: key to find
:return: true if key is in dict and not None
"""
if key not in dict or dict[key] is None:
return True
else:
return False | 2bc3f2194b82e978ab8edb2ffaac7a88a58e9c9e | 24,841 |
def to_digits_base10(n):
"""
Return the digits of a number in base 10.
"""
digits = []
remaining = n
while remaining > 0:
digit = remaining % 10
remaining = (remaining - digit) // 10
digits.append(digit)
return digits[::-1] | 5acc6a2ef1e10bc3142371944232c7d1bcad3a32 | 24,843 |
def pbc(rnew, rold):
"""
Periodic boundary conditions for an msd calculation
Args:
rnew (:py:attr:`float`, optional): New atomic position
rold (:py:attr:`float`, optional): Previous atomic position
Returns:
cross (:py:attr:`bool`, optional): Has the atom cross a PBC?
rn... | 67260f98371fbb95d2eca5958f75d80c76b89371 | 24,847 |
import requests
def submit_task(task: dict, username: str, password: str) -> str:
"""
Submits a task using the AppEEARS API.
Parameters
----------
task: dictionary following the AppEEARS API task object format
username: Earthdata username
password: Earthdata password
Returns
... | fd75b86b5258f9b4b0abd02f8fb289a7467149df | 24,848 |
def compare_int(entry, num):
"""Return True if the integer matches the line entry, False otherwise."""
if int(entry) == num:
return True
else:
return False | e779829b0d9a8343d3c48e6a66542e8e6ee62494 | 24,851 |
def _prepare_params(params):
"""return params as SmashGG friendly query string"""
query_string = ''
if len(params) == 0:
return query_string
prefix = '?expand[]='
query_string = prefix + '&expand[]='.join(params)
return query_string | 9fc0573961d50536ee28ae576ac030197eae0cf2 | 24,852 |
def load_settings(path='api/settings'):
"""Loads the user settings located under `api/`"""
with open(path, 'r', encoding='utf-8') as file:
return {
l.strip(): r.strip()
for l, r in (l.split('=') for l in file if l.strip())
} | 1a89c3f80f0a8b4013429fbb060b453f5f447aa5 | 24,853 |
def get_mask(source, source_lengths):
"""
Args:
source: [B, C, T]
source_lengths: [B]
Returns:
mask: [B, 1, T]
"""
B, _, T = source.size()
mask = source.new_ones((B, 1, T))
for i in range(B):
mask[i, :, source_lengths[i]:] = 0
return mask | 8466ff5113ca22488b4218f86c43bfea248197d1 | 24,855 |
import glob
def get_all_html_files(directory):
"""
Returns list of html files located in the directory
"""
return glob.glob(directory + "/*.html") | 5e92a8b4fc52ea63e5c65c5eb7b2487556b08a3d | 24,857 |
import csv
def load_csv(csv_filename):
"""Load csv file generated py ```generate_training_testing_csv.py``` and parse contents into ingredients and labels lists
Parameters
----------
csv_filename : str
Name of csv file
Returns
-------
list[str]
List of ingredient ... | 704151f36424f9e72ecb1d0dce9f8f7e8f77c1f1 | 24,870 |
def largest_common_substring(query, target, max_overhang):
"""Return the largest common substring between `query` and `target`.
Find the longest substring of query that is contained in target.
If the common substring is too much smaller than `query` False is returned,
else the location `(start, end)` ... | 4e0e1e1ee9d5d37fe5e56601fcedab66621ac9fb | 24,871 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.