content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import json
def save_json(input_dict, output_file):
"""save dictionary to file as json. Returns the output file written.
Parameters
==========
content: the dictionary to save
output_file: the output_file to save to
"""
with open(output_file, "w") as filey:
filey.writel... | 05d5c8440f5d7e7a021d91136e2277031de53f18 | 644,636 |
def _is_clustal_seq_line(line):
"""Returns True if line starts with a non-blank character but not 'CLUSTAL'
Useful for filtering other lines out of the file.
"""
return line and (not line[0].isspace()) and\
(not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE')) | 78c9067fa02254409d33fdb9f243c74d549138ce | 696,588 |
def italic(string):
"""
Surrounds the string with underscores (_) so it will be parsed italic when using markdown
"""
if not isinstance(string, str):
raise TypeError("Must be given a string")
return "_" + string + " _" | db93a3e2c529486228b029747eedb770faf1fc3b | 540,701 |
import json
import hashlib
def hash_dict(nested_dict):
""" Returns hash of nested dict, given that all keys are strings
"""
dict_string = json.dumps(nested_dict, sort_keys=True)
md5_hash = hashlib.md5(dict_string.encode()).hexdigest()
return md5_hash | 5f518698154b351ca38b8027f047b4a1153f2c83 | 655,496 |
from math import sin, cos, sqrt, atan2, radians
def lat_lon_2_distance(lat1, lon1, lat2, lon2):
"""
return distance (in km) between two locations (lat1, lon1) and (lat2, lon2)
parameter
---------
lat1, lat2: latitude in degrees
lon1, lon2: longitude in degrees
return
... | d0a03ca3c8f2e0574b1677fe271e2bbbef8f7e6c | 394,438 |
import torch
def convert_half_precision(model):
"""
Converts a torch model to half precision. Keeps the batch normalization layers
at single precision
source: https://github.com/onnx/onnx-tensorrt/issues/235#issuecomment-523948414
"""
def bn_to_float(module):
"""
BatchNorm... | c899bc0e7f97deb8983794e4ea81ceac2551ec22 | 81,814 |
def decode(value, encoding='utf-8'):
"""Decode given bytes value to unicode with given encoding
:param bytes value: the value to decode
:param str encoding: selected encoding
:return: str; value decoded to unicode string if input is a bytes, original value otherwise
>>> from pyams_utils.unicode im... | 8cef7b6d0367d5bff48f5c9b9cb2b5d7c4a883d9 | 15,309 |
def normalize(array):
"""Normalize the array.
Set all the values betwwen 0 and 1.
0 corresponds to the min value and 1 the max.
If the normalization cannot occur, will return the array.
"""
min_ = min(array)
max_ = max(array)
return (
(array - min_) / (max_ - min_) # Normalize
... | 71efcc238a3c2810db9d57e3f32ddad3ef077e56 | 423,759 |
def _adaptive_order_1(q, i, j, recons):
"""
First-order reconstruction.
First-order reconstruction is given by
.. math::
\hat{q}_{i + 1/2} = q_i
"""
recons[2 * i + 1] = q[j]
recons[2 * i + 2] = q[j]
return True | 1a49bed58094988b6e884427c63d3baf5daf1ae8 | 691,891 |
from typing import Iterable
from typing import Any
from typing import Optional
def get(iterable: Iterable[Any], **kwargs) -> Optional[Any]:
"""
Returns the first object that matches the kwargs arguments.
Used in caching.
:param Iterable iterable: The iterable.
:param kwargs: The key arguments.
... | 998cb924b51d10eab86247db7b068c5b50f076ec | 134,954 |
import re
def replace_chrom_name_in_header(line, name_map):
"""
Replaces the Chrom name from header.
Returns new header.
:param line: line from VCF
:param name_map: name-mapping dict
:return: new header line
"""
old_name = re.split('=|,', line)[2]
return line.replace(old_name, ... | 3b1b20d09d4ee0ef77a74d902927c715a05415bc | 181,593 |
def get_job_name(job):
"""Returns job name.
:param Job job: An apscheduler.job.Job instance.
:return: task name
:rtype: str
"""
return job.args[0] | 50c77c537566c533016075fde113f439ed3999f4 | 491,525 |
def sum(gdf, array: list):
"""Return a sum expression."""
expression = " + ".join(map(str, array))
return gdf.eval(expression) | e9a5f3738b8e4925892c424b3505f687f3a8e017 | 132,684 |
def merge(L1: list, L2: list) -> list:
"""Merge sorted lists L1 and L2 into a new list and return that new list.
>>> >>> merge([1, 3, 4, 6], [1, 2, 5, 7])
1, 1, 2, 3, 4, 5, 6, 7]
"""
newL = []
i1 = 0
i2 = 0
# For each pair of items L1[i1] and L2[i2], copy the smaller into newL.
whi... | 9b6423a2ed8ac900668cef3221ca3db7e581500f | 664,145 |
def get_mapping_pfts(mapping):
"""Get all PFT names from the mapping."""
pft_names = set()
for value in mapping.values():
pft_names.update(value["pfts"])
return sorted(pft_names) | 40fc5d5cbd537db203a240e44a0ef6c0358a7019 | 688,923 |
def t02_calc_population(base_population) -> int:
"""
Gets a starting population of fish as input and determines their number after an 256 days period.
Each element in the starting population represents a fish and each element's value represents the
reproduction timer.
Also uses a better storage mana... | c9ef1b5d606d30655a8d367237e56668fd159ef3 | 408,130 |
import re
def remove_special_characters(value: str) -> str:
"""Replaces special characters with '_' while keeping instances of '__'."""
normalized_parts = []
for part in value.split("__"):
part = re.sub(r"[^a-zA-Z0-9_]", "_", part) # Remove special characters.
part = re.sub(r"_+", "_", part) # Remove ... | a2896cf92299c3403fea6455bd8257c4bd15a734 | 257,159 |
import time
def strLocalTime(str_format):
"""
.. _strLocalTime :
Return the system local date and time as a string according to the given format.
Parameters
----------
str_format : str
Date/Time code format.
Example: '%Y-%m-%d, %H:%M:%S'
Returns
-------
str... | e9dd98f0b0ac2f03f36f91b432c65dbab6b41533 | 372,419 |
def str2bool(v):
""" Convert string to a boolean value.
References
----------
https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python/715468#715468
"""
return str(v).lower() in ("yes", "true", "t", "1") | 4e65003e8565536b24c7a47c7983ce1235c8f6c5 | 221,862 |
def downsample_naive(img, downsample_factor):
"""
Naively downsamples image without LPF.
"""
new_img = img.copy()
new_img = new_img[::downsample_factor]
new_img = new_img[:, ::downsample_factor]
return new_img | 9ccda4d23dfd7816a547d8a968136e0595ba6591 | 480,332 |
def url_replace(request, field, value):
"""URL Replace.
Allows us to quickly and easily swap parameters in the request
object in the case of doing complex queries like filtering
a certain search results, feed, or metadata. Pour exemple:
<a href="?{% url_replace request 'viewing' 'unanswered' %}" ... | 5828680cd207689b31175ab952f34350ac62de82 | 62,659 |
def get_admin_extension_href(href):
"""Returns sys admin version of a given vCD url.
This function is idempotent, which also means that if input href is already
an admin extension href no further action would be taken.
:param str href: the href whose sys admin version we need.
:return: sys admin ... | d60d127e3a094e8b5f7ef64da02ab2da6fe45dbc | 278,099 |
def hash_int_pair(ind1, ind2):
"""Hash an int pair.
Args:
ind1: int1.
ind2: int2.
Returns:
hash_index: the hash index.
"""
assert ind1 <= ind2
return ind1 * 2147483647 + ind2 | 131ccb2b35156716eb7e7ef89f3a5ce6e0e1dfdd | 498,025 |
def split(text):
"""
Convenience function to parse a string into a list using two or more spaces
as the delimiter.
Parameters
----------
text : string
Contains text to be parsed
Returns
-------
textout : list
list of strings containing the parsed input text
"""
... | abc45882e8b333a608e65d8e171fc155b9b3e749 | 633,800 |
import itertools
def group_and_create_lookup(things, key_func):
"""
Takes list of things then sorts, groups, and
returns a lookup with result of `key_func`
as the key and list of things grouped on key
as the value
"""
things = things or []
things = sorted(things, key=key_func)
retu... | e85d832dfd908b5055f3165f5271e72a575fd637 | 176,556 |
def _get_coordinate_keys(df):
"""Keys associated to atom coordinate in system's dataframe.
"""
if 'x_coord' in df:
return ['x_coord', 'y_coord', 'z_coord']
else:
return ['r_0', 'r_1', 'r_2'] | 9f8100eb259f207ad83104d65b59f3fd084eb0af | 301,849 |
def corr_well(text):
"""
>>> corr_well('Я колодец') # I am well
'Я в порядке'
>>> corr_well('Я чувствую колодец') # I am feeling well
'Я чувствую себя хорошо'
"""
text = text.replace('колодец', 'хорошо')
if 'чувствую' in text and 'себя' not in text:
text = text.replace('чу... | f44bc752c6ec0a8d7cf4962d34251669a19a812e | 464,280 |
def parse_integer_line(line):
"""
Parse a string of integers (with or without a trailing newline).
Returns an iterator object of integers.
This function allows leading and trailing spaces. ValueError is
raised if one of the values does not parse to an integer.
"""
return (int(s) for s in... | b1be853e0f1329dfb978c4c0d18c33e2226dcd29 | 174,616 |
def note_onsets(a_list, b_list):
"""
Takes two lists of NoteNode objects. These may be NoteList objects.
Returns a list of tuples, each of the form:
(int: bar #, float: beat #)
Each of these tuples represents a time where a note starts in either
a_list, b_list, or both.
"""
changes =... | 2166c6450916891de1d17071a98ed77893fe6616 | 560,195 |
def get_scale(f_min, f_max, q_min, q_max):
"""Get quantize scaling factor. """
return (q_max - q_min) / (f_max - f_min) | 0f48cc32c21b2efe9355124e162f2dd2abfa3d58 | 96,312 |
def seq_format_from_suffix(suffix):
"""
Guesses input format from suffix
>>> print(seq_format_from_suffix('gb'))
genbank
"""
suffixes = {'fasta': ['fas','fasta','fa','fna'],
'genbank': ['gb','genbank'],
'embl': ['embl']}
found = False
for ke... | d7103d3d4bd803d9f55623155c703db3a55683bf | 513,033 |
def query_int(pregunta, opciones):
"""
Query the user for a number in predefined interval
:param pregunta: Question that will be shown to the user
:param opciones: Available choices
"""
opcion = None
while opcion not in opciones:
opcion = input(pregunta + ' [' + str(opcione... | 15f3ddafc47107538d8bbfa46792ee0472e87231 | 83,500 |
def clean_data(df):
"""
Clean the dataset
Args:
df: (pandas.DatFrame) containing data to be cleaned
Returns:
df: (pandas.DataFrame) containing the cleaned dataset
"""
try:
# clean target labels
categories = df.categories.str.split(";", expand=True)
cat_n... | 676f43ebdb426155ce53d3632626aefca09b3b00 | 670,652 |
def add_to_hof(hof, population):
"""
Iterates over the current population and updates the hall of fame.
The hall of fame is a dictionary that tracks the fitness of every
run of every strategy ever.
Args:
hof (dict): Current hall of fame
population (list): Population list
Return... | 5ec67dfd878bc1fcc7abca11cea8f22337935c3f | 450,271 |
def _spark_calc_values_chunk(points):
"""
Compute some basic information about the chunk points values
The returned information are :
* count : the number of points in chunk
* max : the maximum value in chunk
* min : the minimum value in chunk
* sum : the sum of the values in chunk
* sq... | 04dd208038bf1df0172b821943337533f9759291 | 75,114 |
def get_current_temp(soup):
"""Return the current temperature"""
current__temp_find = soup.find_all("span", class_="wxo-metric-hide")[0]
return current__temp_find.get_text() | f35d955288d9390ab7f26e51b240a31ae05afe74 | 444,255 |
def calculate_difference(dsm_array, dtm):
"""Calculate the difference between the dsm and dtm"""
dtm_array = dtm.read(1, masked = True)
difference = dsm_array - dtm_array
difference.data[difference < 0] = 0 # We set to 0 anything that might have been negative
return difference | 962078fe055b27189472fceb4008665aa946b038 | 646,606 |
def homogeneous_to_cartesian(homogeneous_point):
"""
Convert Homogeneous coordinates to Cartesian coordinates
:param homogeneous_point: Homogeneous coordinates
:return: Cartesian coordinates
"""
return homogeneous_point[:, :-1] | 7a2e3571023d28024d8caf1f3626abb051193a32 | 89,384 |
def limit_es(expected_mb):
"""Protection against creating too small or too large chunks."""
if expected_mb < 1: # < 1 MB
expected_mb = 1
elif expected_mb > 10**7: # > 10 TB
expected_mb = 10**7
return expected_mb | 9838c10b4af502811a161e0541bf787daeb2680a | 413,680 |
def traverse(the_module, do_action, traverse_submodules_flag=True):
"""
Traverses ``the_module`` and performs action :func:`do_action` on each of the objects of the structure.
:param the_module: Dictionary ``{'module_obj': module_obj, 'submodules': submodules,
'classes': classes, 'functions': funct... | 7eab757b8223d5305db59f3b8e1c4403ccca458e | 288,579 |
import json
def filter_coverage_file(covfile_handle, cov_functions):
"""Given an input coverage json file and a set of functions that the test
is targeting, filter the coverage file to only include data generated
by running the given functions."""
covdata_out = dict()
covdata = json.load(covfile_h... | 12562e355feaeea18fa4d8386c1f77cf44c167b5 | 451,049 |
from typing import Dict
from typing import Optional
def get_collection_for_id(
id_: str, id_map: Dict, replace_underscore: bool = False
) -> Optional[str]:
"""
Returns the name of the collect that contains the document idenfied by the id.
Parameters
----------
id_ : str
The identifier... | 0473b4cc14e25bca7d2f4cbf8f77a8bdb60359d8 | 370,033 |
from typing import Dict
from typing import List
from typing import Tuple
from bs4 import BeautifulSoup
from typing import OrderedDict
def load_docs_from_sgml(
file_path: str, encoding='utf-8'
) -> Dict[str, List[Tuple[str, str]]]:
"""
Loads documents from given SGML file.
Returns dict mapping documen... | 99074d183c2f66839db50394528453f4517685c9 | 42,236 |
from typing import List
import logging
import re
def python_result_extractor(raw_test_output: str) -> List[bool]:
"""
Function which extracts the test resutls for an execution
@param raw_test_output: output provided by the submission
@return list of bools, where each element on position i means, tha... | c7b487c79db03c7a048301c8f97e89b4692b3b2a | 408,585 |
def load_file(filename: str) -> list:
"""Read file containing survey responses
:param filename: Location of survey response file
:return: List of survey responses by group
"""
groups = []
gp = []
with open(filename, 'r') as f:
for line in f:
if line == '\n':
... | 940f836377e12774fd1e1ec8fba89d4aea496d8e | 381,851 |
from bs4 import BeautifulSoup
import requests
def get_content(url:str) -> BeautifulSoup:
"""Attempts to make get request to url, raises HTTPError if it fails.
Returns the contents of the page.
Args:
url (str): Valid url example: https://www.rescale.com.
Returns:
BeautifulSoup: The c... | dd7ff1a50964ac6a4c51ec0511ba18a3f9035306 | 64,624 |
def get_requirements(rfile):
"""Get list of required Python packages."""
requires = list()
with open(rfile, "r") as reqfile:
for line in reqfile.readlines():
requires.append(line.strip())
return requires | ef707cdf35500cb05f86e5c986e9b9c58968d111 | 484,059 |
import itertools
def flatten(l):
"""
Flatten a 2-dimensional list.
"""
return list(itertools.chain.from_iterable(l)) | bcfe036e44068da0bad1e4024cc767da471d3d4f | 383,321 |
def take_bet(player: dict) -> float:
"""Prompt the player for how much money to bet."""
while True:
print(f"\nYou currently have ${player['money']:.2f}")
bet = input('How much money would you like to bet on this hand? (min: $20)\n> $')
if not bet.isdigit() or float(bet) < 20:
... | b28d48bdd690cd7ec317fbe00da039de86a2423a | 624,285 |
def make_query_result(query_type):
"""Return a function that creates the result of a query."""
def _result(tokens):
return (query_type, tokens)
return _result | 14e6f05b8d5197dda48c11ce8f509fb82c4b24ce | 375,102 |
def get_sig(value):
"""
Extract the signature of a docstring.
"""
return value.__doc__.strip().splitlines()[0] | 229479bfffd5c97cec76d27e31fbfbc6c5f560aa | 152,016 |
def split_name_pos(no_chrom_list):
"""
Splits the name and position in no_chrom_list.
Args:
no_chrom_list (list): list with header info not containing chromosome
Returns:
name_pos_split_list: split name and position list
"""
name_pos_split_list = []
for item in no_chrom_list:... | 6a063908c38bb22e4611ccd17e672e146230a009 | 527,158 |
from typing import List
import re
def split(sentence: str) -> List[str]:
"""
Split a string by groups of letters, groups of digits,
and groups of punctuation. Spaces are not returned.
"""
return re.findall(r"[\d]+|[^\W\d_]+|[^\w\s]+", sentence) | d8e8e3ac0a0b00c4346eedef29693a5d66a7f3a4 | 655,252 |
def edge(node1, node2):
"""Create an edge connecting the two nodes, which may be the same."""
return frozenset({node1, node2}) | 160b1d8c5c9d945d25598b585901d1a7f076d2de | 243,100 |
def getstate(cells, pos, inc):
"""
A helper function to call within a cellular automata's rule function to
access the value of neighbor cells at position pos + inc. See: `states()`.
The new position pos+inc will automatically wrap mod the size of the cells
array so will never go out of bounds.
... | 2328869f9d7e8d1310a9abe6f609ac7f0fa4ba6e | 371,929 |
import torch
def abs_img_point_to_rel_img_point(abs_img_points,
img_shape,
spatial_scale=1.):
"""Convert image based absolute point coordinates to image based relative
coordinates for sampling.
Args:
abs_img_points (Tensor): Im... | 528ea12f13d6e74ce7433824270702760cba2bf8 | 271,070 |
def _CalcThroughput(samples):
"""Calculates the throughput in MiB/second.
@type samples: sequence
@param samples: List of samples, each consisting of a (timestamp, mbytes)
tuple
@rtype: float or None
@return: Throughput in MiB/second
"""
if len(samples) < 2:
# Can't calculate throu... | 0f7c973532833ab75ac41fec85c1f7f80983447b | 589,160 |
from typing import Any
import textwrap
def clean_text(text: Any) -> str:
"""Convert an object to text, dedent it, and strip whitespace."""
return textwrap.dedent(str(text)).strip() | 85427e3c8ef77d334a92490616c4db2ca8de75bc | 276,966 |
def strip_ses_recipient_label(address):
"""
Ensure `address` does not contain any +label.
Address is a simple recipient address given by SES, it does not contain a display name.
For example, 'coder+label@vanity.dev' -> 'coder@vanity.dev'.
"""
name, domain = address.split("@")
if '+' in name:... | 4d6b5503b303b9ea5abf44f3189e04b424abc66f | 122,287 |
import struct
def little_endian_uint32(i):
"""Return the 32 bit unsigned integer little-endian representation of i"""
s = struct.pack('<I', i)
return struct.unpack('=I', s)[0] | 07f72baaf8f7143c732fd5b9e56b0b7d02d531bd | 706,808 |
def adjust_displacement(n_trials, n_accept, max_displacement):
"""Adjusts the maximum value allowed for a displacement move.
This function adjusts the maximum displacement to obtain a suitable acceptance \
of trial moves. That is, when the acceptance is too high, the maximum \
displacement is incre... | cc513be27481d239cf8c937bd260e1db8f182775 | 650,283 |
def sanitize(s, strict=True):
"""
Sanitize a string.
Spaces are converted to underscore; if strict=True they are then removed.
Parameters
----------
s : str
String to sanitize
strict : bool
If True, only alphanumeric characters are allowed. If False, a limited
set ... | 3150b7d118443224630dcfd2925799bf8daea602 | 87,606 |
from pathlib import Path
def get_directory(base_path, vin):
"""Generate directory where data files go."""
path = Path(base_path) / Path(str(vin))
path.mkdir(parents=True, exist_ok=True)
return path | ef3fbda689b7feba527bb014896a170b873f5665 | 578,537 |
def _hbc_P(P):
"""Define the boundary between Region 2b and 2c, h=f(P)
Parameters
----------
P : float
Pressure [MPa]
Returns
-------
h : float
Specific enthalpy [kJ/kg]
References
----------
IAPWS, Revised Release on the IAPWS Industrial Formulation 1997 for t... | 86757a8285960c1805babe61574e160bccdfb891 | 403,732 |
def get_neighbors(x, y):
"""Returns the eight neighbors of a point upon a grid."""
return [
[x - 1, y - 1], [x, y - 1], [x + 1, y - 1],
[x - 1, y ], [x + 1, y ],
[x - 1, y + 1], [x, y + 1], [x + 1, y + 1],
] | 21ec6d4f4143f717388ff20def80fd53127bc1ed | 682,159 |
import struct
import re
import io
def get_size(data: bytes):
"""
Returns size of given image fragment, if possible.
Based on image_size script by Paulo Scardine: https://github.com/scardine/image_size
"""
size = len(data)
if size >= 10 and data[:6] in (b'GIF87a', b'GIF89a'):
# GIFs
... | 1b45563b0f59f5670638d554821406389b5333a6 | 15,612 |
def QuadraticLimbDarkening(Impact, limb1, limb2):
"""Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1"""
return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2 | 1b271c7afec301331b978e015c085ffaaa335240 | 677,194 |
def trusted_division(a, b):
"""
Returns the quotient of a and b
Used for testing as 'trusted' implemntation of division.
"""
return a * 1.0 / b | e544c5b617cd559e207aa1d8c2440b4f88dc056a | 102,167 |
def substitute(message, substitutions=[[], {}], depth=1):
"""
Substitute `{%x%}` items values provided by substitutions
:param message: message to be substituted
:param substitutions: list of list and dictionary.
List is used for {%number%} substitutions and dictionary for
{%name%} subs... | 4a46c46faf1848f1c7e437fed956e21cfdd3a813 | 652,579 |
from typing import List
def split_key(parent_key: List[str]) -> List[List[str]]:
"""Split group key into parts."""
key_parts = []
while parent_key:
key_parts.append(parent_key)
parent_key = parent_key[:-1]
return key_parts[::-1] | 157c02092452c4757e03f963cce9b2cccd456c4b | 590,268 |
def bit_len(i):
"""
Calculate the bit length of an int
:param int i: Int
:return: Length of *i*
:rtype: int
"""
length = 0
while i:
i >>= 1
length += 1
return length | f0e35e6d89870cc05c9ae0a6fe22a6cba896b6ad | 474,861 |
from pathlib import Path
def parse_taxid_names(file_path):
"""
Parse the names.dmp file and output a dictionary mapping names to taxids
(multiple different keys) and taxids to scientific names.
Parameters
----------
file_path : str
The path to the names.dmp file.
Returns
----... | 1d136f73a56ac8d3c02fd53c6e7928a39440e27a | 5,451 |
def num_vertices(G):
"""Counts the number of vertices in the graph."""
return max(v for e in G for v in e) | ef9b396159681d4a379c2c3c727043f8384db8f6 | 365,238 |
def camel_case_split(str):
"""Split up camel case string."""
words = [[str[0]]]
for c in str[1:]:
if words[-1][-1].islower() and c.isupper():
words.append(list(c))
else:
words[-1].append(c)
return [''.join(word) for word in words] | 64e075978aedacdae83845fa26bcf80ab75ef230 | 223,251 |
def clean_col_names(df):
"""
cleans up the column names in the mta dataframe
:param df: mta dataframe
:return: mta dataframe with cleaned columns
"""
df = df.copy()
before = 'EXITS '
df.rename(columns={before: 'EXITS', "C/A":... | 62ee58e79095823c69d18a81bb7845bb6224d1ae | 58,113 |
def minidom_get_text(nodelist):
"""
gets the text in a minidom nodelist for something like
<tag>this text</tag>
nodelist: the childNodes field of the minidom node
"""
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return "".join(rc) | 2f9a781cdd6c675fb0ec0ef5268a824144e8838d | 67,478 |
import re
def extract_top_level_domain_from_uri(uri):
"""
Extract host's top level domain from URIs like 'https://amy.carpentries.org/api/v1/organizations/earlham.ac.uk/' to 'earlham.ac.uk'.
When subdomains are used, as in 'https://amy.carpentries.org/api/v1/organizations/cmist.manchester.ac.uk/' we are o... | 22d965028116d1faaae6de6bc7d7dd877c50b9a2 | 587,600 |
def tokens(_s, _separator=' '):
"""Returns all the tokens from a string, separated by a given separator, default ' '"""
return _s.strip().split(_separator) | cb07414580b7d7a1bfe0917cc220b3951741bc7e | 191,444 |
def get_restaurants(restaurants, category=None):
"""
This function takes a list of dictionaries as an argument and returns a list of strings that includes restaurants' names
Parameters:
restaurants (list): A list of dictionaries, each representing a restaurant
category (list): A list of str... | af61eaec4a0bc632921f030eb6779e5b8f4caac1 | 92,538 |
def email_context(request, application, message=None):
"""
Return a dictionary with the context to be used when constructing
email messages about this application from a template.
"""
fa_app_url = request.build_absolute_uri(application.fa_app_url())
context = {
'user': request.user,
... | 554d32861217b4c3c90c23d410bdbe94b1fb034c | 403,043 |
from typing import List
from typing import Any
def _flatten_non_tensor_optim_state(
state_name: str,
non_tensors: List[Any],
unflat_param_names: List[str],
) -> Any:
"""
Flattens the non-tensor optimizer state given by the values ``non_tensors``
for the state ``state_name`` for a single flatte... | 68199447dc6d3443a0df05f3660893fa0f000697 | 167,123 |
def render_tile(tile):
"""
For a given tile, render its character
:param tile:
:returns str value of tile
"""
# each tile list has the meaning: [Visible (bool), Mine (bool), Adjacent Mines (int)]
# visible, mine, adjacent_mines = tile
if tile[0]:
# if the tile is visible
... | 95e28284d7a8d38b3a850dd81449c405a6528f93 | 302,979 |
def vals_to_array(offset, *content):
"""
Slice all the values at an offset from the content arrays into an array.
:param offset: The offset into the content arrays to slice.
:param content: The content arrays.
:return: An array of all the values of content[*][offset].
"""
slice = []
for ... | 3a6dcb84f6ee8ecebc57ffc8e42ca18f6d56e9c7 | 120,594 |
from typing import Dict
def get_short_namespace(full_ns: str, xml_namespaces: Dict[str, str]) -> str:
"""
Inverse search of a short namespace by its full namespace value.
:param full_ns: The full namespace of which the abbreviated namespace is to be found.
:param xml_namespaces: A dictionary containi... | 5a431defce47dc2e3594c3a1da8c44d2f00c9c38 | 389,773 |
def get_accumulated_value(n: int, P: float, i: float) -> float:
""" "
Повертає нарощену суму на певну кількість років
Parameters
----------
P : float
Початкова величина боргу(позики, кредиту)
i : float
Річна ставка складних відсотків
n : int
Кількість років нарощення... | 0b38575447f3fb97d03f23607e675c2f92aa7ad3 | 548,089 |
def bool_to_string(boolean: bool) -> str:
"""
boolを小文字にして文字列として返します
Parameters
----------
boolean : bool
変更したいbool値
Returns
-------
true or false: str
小文字になったbool文字列
"""
return "true" if boolean else "false" | 74c1c9a8c4b92ae9b41e73c50331c14ed6d9c259 | 152,272 |
import hashlib
def _convert_to_id(name):
"""Convert a string to a suitable form for html attributes and ids."""
hasher = hashlib.md5()
hasher.update(name.encode('utf-8'))
return hasher.hexdigest() | 85ee402cdec9793ef00406f4d06eb6fdd41b5e06 | 561,486 |
def save(sizes: list, hd: int) -> int:
"""
Your task is to determine how many files of the
copy queue you will be able to save into your
Hard Disk Drive.
Input:
Array of file sizes (0 <= s <= 100)
Capacity of the HD (0 <= c <= 500)
Output:
Number of files that can be fully saved in... | 361d05b6145c9eee837bd98bae0c232329cb60d9 | 133,827 |
import functools
import time
def time_method(function_name=None):
"""Times the execution of a function as a decorator.
Parameters
__________
function_name : str
The name of the function to time.
(default is None)
Returns
-------
A decorator function.
"""
def r... | 56d4f75c6ef9ff9e14e79edad1629f3e515884a8 | 536,351 |
import re
def is_base64(text: str) -> bool:
"""Guess whether text is base64-encoded."""
return bool(
re.match(
r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$",
text.replace("\n", ""),
)
) | f3be6a0e77e84715317d7233523b01ff5de92ce5 | 634,407 |
from bs4 import BeautifulSoup
import re
def get_text(connection_or_html) -> str:
"""
Uses BeautifulSoup to get text from HTML
"""
# https://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text/1983219#1983219
if isinstance(connection_or_html, BeautifulSoup):
soup = c... | 3a87fa000732f04cf64d46431e753abc57262ddb | 231,902 |
def count_matches(list, item):
"""
Return the number of occurrences of the given item in the given
list.
"""
if list == ():
return 0
else:
head, tail = list
if head == item:
return 1 + count_matches(tail, item)
else:
return count_matches(ta... | beaf23ee6d915a32fcb18326ac23fd705e10f94d | 582,181 |
def all_jobs_completed(jobs):
"""Returns jobs if they are all completed, otherwise False."""
if all(j.get('status') == 'completed' for j in jobs):
return jobs
else:
return False | b3e7f4dbfbb89080f34eb98673c8d5c469a9e35b | 563,799 |
import shutil
def disk_usage(pathname):
"""Return disk usage statistics for the given path"""
### Return tuple with the attributes total,used,free in bytes.
### usage(total=118013599744, used=63686647808, free=48352747520)
return shutil.disk_usage(pathname) | c7a36e2f3200e26a67c38d50f0a97dd015f7ccfa | 625 |
def pretty_print(params, offset=0, printer=repr):
"""Pretty print the dictionary 'params'
Parameters
----------
params : dict
The dictionary to pretty print
offset : int
The offset in characters to add at the begin of each line.
printer : callable
The function to convert... | 8386626542752a67faf089d71a5ffa1f4b4a20e8 | 238,136 |
def pretty_timer(seconds: float) -> str:
"""Formats an elapsed time in a human friendly way.
Args:
seconds (float): a duration of time in seconds
Returns:
str: human friendly string representing the duration
"""
if seconds < 1:
return f'{round(seconds * 1.0e3, 0)} milliseco... | de49d27f57ce45d3ad967f58377b361b9eda63ef | 315,962 |
import re
def _is_dns_label(name):
""" Check that name is DNS label: An alphanumeric (a-z, and 0-9) string,
with a maximum length of 63 characters, with the '-' character allowed
anywhere except the first or last character, suitable for use as a hostname
or segment in a domain name """
dns_label ... | 513e1eb08c87891e99398509d6fc9d04f8141f47 | 529,973 |
def tocreset(I, Ipickup, TD, curve="U1", CTR=1):
"""
Time OverCurrent Reset Time Function.
Function to calculate the time to reset for a TOC
(Time-OverCurrent, 51) element.
Parameters
----------
I: float
Measured Current in Amps
Ipickup: float
... | 8c26a3aebcb5f51fe884724e4d9460f44454b3d1 | 657,381 |
from typing import Dict
from typing import Any
from typing import List
def process_properties(schema: Dict[str, Any]) -> Dict[str, Any]:
"""Processes a Pydantic generated schema to a confluent compliant schema
:param schema: a valid pydantic schema
:type schema: Dict[str, Any]
:return: schema with `f... | e647ba12f25d2440b6c987f2098995ef6e6280cb | 203,810 |
def construct_api_params(
business_unit=None,
event_type=None,
limit=None,
page_token=None
):
"""
Constructs the parameters object for the API call. Note that startDateUtc and
endDateUtc are not listed here (although they are parameters); this is because
they are included... | 36f4de8a30d6cbf6aff72b08130553843b7eec7d | 623,096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.