content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def prices_from_returns(returns):
"""
Calculate the pseudo-prices given returns. These are not true prices because
the initial prices are all set to 1, but it behaves as intended when passed
to any PyPortfolioOpt method.
:param returns: (daily) percentage returns of the assets
:type returns: pd... | be8ea9a9f17bd9a625c4cda8eb11d9313fa334d1 | 640,980 |
def do_complicated_mathematics() -> int:
"""Do complicated mathematics.
Returns:
int: The result
"""
return 1 + 1 | fbfddd15fd63dcac7bc7e6e12fa6f66ed0d254cf | 640,982 |
def new_duplicate_dict(d):
""" Create a duplicate of the given dictionary """
d1 = {}
for p in d.keys():
d1[p] = d[p]
return d1 | 64879b5e916d16a40f6f07bd92f1c24b09cbf224 | 640,983 |
def cleanup_url(url: str) -> str:
"""Cleans up the text to be a valid URL.
Returns:
str: The cleaned up URL.
"""
url = url.replace(" ", "-")
if url.startswith("http://") or url.startswith("https://"):
return url
else:
return f"https://{url}" | b3eed31d45f7bfaa975c60212949dd8fe0e43729 | 640,985 |
def results(person, result, rate):
"""
Checks if the current person is in the dict, if not adds them with their current rate
if they are, adds the current rate to the current person
:param person: the current person
:param result: the output result
:param rate: the current tax rate
:return: ... | 05cfff6046b90a9cbc1ab4352d69125d44505201 | 640,986 |
import hashlib
def hash_object(*objects, hasher=None):
"""Hash the given object(s) and return the hashlib hasher instance
If no hasher argument is provided, then automatically created
a hashlib.md5()
"""
if hasher is None:
hasher = hashlib.md5()
for obj in objects:
if... | 7e072d27d625f47dde75f5119a5bb1f8e57202fb | 640,991 |
import math
def shannon_entropy(p):
"""Computes the Shannon Entropy at a distribution in the simplex."""
s = 0.
for i in range(len(p)):
try:
s += p[i] * math.log(p[i])
except ValueError:
continue
return -1.*s | e5e8bdf40a04e7c532c464e2438626d4b98a2cfb | 640,993 |
import torch
def Ax(A, x):
"""Returns the Matrix-vector product Ax.
Arguments:
A (function or torch.Tensor): Matrix-vector product function or
explicit matrix.
x (torch.Tensor): A vector.
"""
if callable(A):
Ax = A(x)
else:
Ax = torch.mm(A, x)
... | 21e20f8db65bfa7e1bd571bc5861d27c1e5a8be5 | 640,994 |
def create_pad(size, pad_id):
"""
Create a padding list of a given size
Args:
size: nd list shape
pad_id: padding index
Returns:
- padding list of the given size
"""
if len(size) == 1:
return [pad_id for _ in range(size[0])]
else:
return [create_pad(... | 31593a5ac6f4aa7991b0b3025ff0a3b84be89c4f | 640,996 |
def get_file_data(path):
"""
read data from a given file
:param path: file path
:return: file data
"""
data = ""
try:
_file = open(path, 'r')
data = _file.read()
_file.close()
except EnvironmentError as e:
print("File operation failed, Error: %s" % e)
... | 75ce2aa918288e91a3a321c27f72146074296a58 | 640,997 |
def roi_center(roi):
"""Return center point of an ``roi``."""
def slice_center(s):
return (s.start + s.stop) * 0.5
if isinstance(roi, slice):
return slice_center(roi)
return tuple(slice_center(s) for s in roi) | ae6f9fc6af535ed1643481fb7b38f4dd8aa6de72 | 640,998 |
import textwrap
def ssplit(str_, length=420):
"""
Splits a into multiple lines with a maximum length, without
breaking words.
:param str_: The string to split.
:param length: Maximum line length.
"""
buf = list()
for line in str_.split('\n'):
buf.extend(textwrap.wrap(line.rstr... | 8f4100e73e57ad896bf1d754ccf78d2be7366fcd | 641,000 |
import pickle
def read_magnitude_catalogue(pkl_data_fname):
"""Function to read magnitude catalogue output by get_event_moment_magnitudes() into python.
Arguments:
Required:
pkl_data_fname - The filename of the python dict containing the magnitudes information.
This is an outp... | 96d79d76810fb58904afac726fd5fe2c3c78a394 | 641,002 |
from typing import Counter
def get_fine_regions(columns, min_samples=50):
"""
Select regions that have at least ``min_samples`` samples.
Remaining regions will be coarsely aggregated up to country level.
"""
# Count number of samples in each subregion.
counts = Counter()
for location in co... | 40a1ec404b689091532ed452568cadc944eb863b | 641,003 |
def check_consecutive(labels):
""" Check that the input labels are consecutive and start at zero.
"""
diff = labels[1:] - labels[:-1]
return (labels[0] == 0) and (diff == 1).all() | 9c567e857d4814a299935320fdbfff2f454eca2a | 641,004 |
def merge_dicts(*args, **kwargs):
"""Outputs a merged dictionary from inputs. Overwrites data if there are conflicts from left to right.
:param args: (dict), tuple of input dictionaries
:param kwargs: dict, input kwargs to merge
:return: dict, combined data.
"""
data = {}
for input_dict in ... | fb35fbeda9606019c6fd67b6b47a77af704e1aab | 641,007 |
import random
def random_tour(num_of_cities):
"""
Returns a random valid tour
"""
tour = list(range(num_of_cities))
random.shuffle(tour)
return tour | f6e8edf4b57cbaa8a4402e27639f3b6b8467198f | 641,008 |
import six
def clear_dict_empty_lists(to_clear_dict):
"""
Removes entries from a nested dictionary which are empty lists.
param to_clear_dict dict: python dictionary which should be 'compressed'
return new_dict dict: compressed python dict version of to_clear_dict
Hints: recursive
"""
ne... | 4f2e7461fab27487dcd493e4af886d4ca7332b26 | 641,014 |
def per_hour_to_per_second(per_hour):
"""
Transform a per hour rate to a per second rate.
:param per_hour: quantity per hour
"""
return per_hour / 3600 | f4f15c972f59b09b7a5af6b667bfd8721da40a27 | 641,016 |
def decide_produced(desc):
"""Based on the provided description, determine the ActivityProducedBy."""
if 'Production' in desc:
return desc.split('Production')[0].strip()
return 'None' | f219c63cc6ea30dffaa35d004c544f889499de51 | 641,018 |
from typing import Counter
def preprocess(text):
"""
Converts any puctuation into tokens, creates a counter dictionary of the data,
and trims the data dictionary of words with occurrances less than five
Input:
* text: a text file containing words
Output:
* returns a trimmed counter dictionary of tokeniz... | 6799256a0ddaa254c0298bf36218fdac0566da8e | 641,019 |
def shekel_gradient(point, p, matrix_test, C, b):
"""
Compute Shekel gradient at a given point with given arguments.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the gradient.
p : integer
Number of local minima.
matrix_test : 3-D arra... | 8d6628243de1f40aea3ab6b45211579e3633924d | 641,021 |
import re
def __valid_word(word, stopword, language):
"""
Check if the word is in the stopword list
Return a boolean
word = string
stopword = stopword object (cf stopwords.py)
language = string (french or english)
"""
# print(word)
# print(language)
# print(word not in stopword... | ef1850a9b01a26708fdacacf9536cc24ad6f6323 | 641,023 |
def ignore_filter(topics):
"""filter topics starts with !"""
result = [t for t in topics if not t['title'].startswith('!')]
for topic in result:
more_topics = topic.get('topics', [])
topic['topics'] = ignore_filter(more_topics)
return result | 8e330ddc56b2b2638288059d679050eefa11441c | 641,025 |
def point_in_rectangle(point, rectangle):
"""
Determine if the given point is inside the rectangle
Args:
point(tuple): tuple of points x and y
rectangle
Returns:
bool: True if point in the rect, False otherwise
"""
left_sides = 0
for i in rang... | 3404e13413ff0568fc2933df419b19cc0adc46d5 | 641,027 |
import math
def get_conv_output_shape(in_shape, kernel, stride=1, padding=0, dilation=1, out_channels=32):
""" infer output shape after 1 layer of conv
reference: https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d
"""
_, h, w = in_shape
out_h = math.floor(
(h + 2 * padding - dilation... | 8882e9363e66b82c692abf3470645ebddd6d6252 | 641,029 |
import re
def parsePWDResponse(response):
"""
Returns the path from a response to a PWD command.
Responses typically look like::
257 "/home/andrew" is current directory.
For this example, I will return C{'/home/andrew'}.
If I can't find the path, I return L{None}.
"""
match = r... | 5e74777bf5d5fb882f9ca20d3e0ac6dac97ae19e | 641,030 |
from typing import Dict
import json
def get_unambiguous_roots(base_forms_file: str) -> Dict[str, Dict[str, str]]:
"""Get the list of words repleaceable with an unambiguous lemma.
This is a dictionary having the ISO 3-letter code of each language as
a key, and as values dictionaries mapping words with the... | 879ed6678655a731940cac8457d347ce9de8c4ac | 641,039 |
import re
def _convert_to_regex(input_format: str):
"""Return regex of input_format."""
return re.compile(input_format.replace("(", "\\(")
.replace(")", "\\)")
.replace("<artiste>", "(.+)")
.replace("<track>", "(\\w+)")
.r... | d93687b03684b96a9e0d6d0b2ce957e8079f47ba | 641,041 |
def which_one(iterable):
"""Index of the first True value in an iterable."""
it = enumerate(iterable)
i, x = next(it)
while not x:
i, x = next(it)
return i | 9efa3d85717fec7ff7c19b9c5d0d9fe831ff19b0 | 641,043 |
import torch
def rotation_from_axis(axis):
"""
Expects Bx1x3 axis Tensor
The axis is x, y, z with the angle being norm(axis).
Returns a Bx3x3 rotation matix tensor
"""
device = axis.device
# Trick for batch_size broadcasting
theta = torch.norm(axis, p=2, dim=2).view(-1, 1, 1)
axis... | 566a71ff883afb7952221429e6749d3550566898 | 641,054 |
def get_number_of_verb(sentence_token):
"""Return number of verbs in sentence
Args:
sentence_token (tuple): contains length of sentence and list of all the token in sentence
Returns:
int: number of verb in sentence
"""
number_of_verb = 0
for word in sentence_token[1]:
i... | 7f9d404e204612ef8a5379566bde802997fc30ef | 641,055 |
def chunkify(files_list, chunksize=1000):
"""
Create a list of chunks.
Each chunk is a list itself, with size `chunksize`.
Arguments:
files_list: list: A list of Path objects
chunksize: int: Size of each chunk
Return:
chunks: list: A list of lists. Each nested list has size
... | 6040bd067a96490c3da627ee0883df20ec663083 | 641,057 |
def _trunk(port_data):
"""Return trunk for specific ifIndex.
Args:
port_data: Data dict related to the port
Returns:
trunk: True if port is in trunking mode
"""
# Initialize key variables
trunk = False
# Determine if trunk for Cisco devices
if 'vlanTrunkPortDynamicSta... | eebbe1fcaaeeaa1295ce1aaf9f8a42eddf583c79 | 641,058 |
def construct_index_dict(field_names, index_start=0):
"""This function will construct a dictionary used to retrieve indexes for cursors.
:param - field_names - list of strings (field names) to load as keys into a dictionary
:param - index_start - an int indicating the beginning index to start from (default ... | 45f0193d0053c9ea01a35e248782fc414f06cdb1 | 641,060 |
from typing import BinaryIO
import hashlib
def get_md5(f: BinaryIO) -> str:
"""Make an MD5 hash of the page's contents."""
BLOCKSIZE = 65536
hasher = hashlib.md5()
buf = f.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(BLOCKSIZE)
return hasher.hexdigest() | 91e9729df86d1c3ab33f129a3c864580ddf5ced1 | 641,061 |
def create_json(sensor):
"""Simple function that creates a json object to return for each sensor
Args as data:
sensor object retrieved from MongoDB
Returns:
{
Formatted sensor object as below
}
"""
json_object = {'building': sensor.get('building'),
... | a0227dc91158b89e71dc827161c9e23d8262e8ee | 641,065 |
def contains(script, keywords):
"""Performs DFS on the script to determine if keyword exists."""
# The keyword must be the first item in a list.
if type(script) != list or not script:
return False
if script[0] in keywords:
return True
# Iterate over all children.
return any(co... | dd7e05d63f153e4755b2c91744de1b699ca79a43 | 641,066 |
def dict_get(D, k1, k2, default = 0.0):
"""
Custom retrieval from nested dictionary.
Get D[k1][k2] if it exists, otherwise default.
"""
if k1 in D and k2 in D[k1]:
return D[k1][k2]
else:
return default | 0d186374a930f2dc76b894e128f7918dc47cdc05 | 641,068 |
import requests
def get_pokeapi_data(pokemon):
""" Retrieve data on Pokemon from PokeAPI in JSON format. """
endpoint = 'http://pokeapi.co/api/v2/pokemon/' + pokemon
r = requests.get(endpoint)
r.raise_for_status()
return r.json() | 29b0209ae455b4fe9ab7abc8950350f988e3ddb6 | 641,069 |
def parse_qstat_jobid(output, job_id):
"""Parse and return output of the qstat command run with options
to obtain job status.
:param output: output of the qstat command
:type output: str
:param job_id: allocation id or job step id
:type job_id: str
:return: status
:rtype: str
"""
... | ce2afb877fdafc1ff71d9f55a066b5d0e0871f93 | 641,070 |
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
def find_element_in_list(
element_list: List[Dict[str, Any]], **fields
) -> Optional[Dict[str, Any]]:
"""
Find element with some fields in list of elements
>>> element_list = [dict(n="a", v=2), dict(n="... | 655bbd1e343cf967d57d20fabaa97f5fb7700c49 | 641,071 |
def scatter_props(event):
"""
Get information for a pick event on a PathCollection artist (usually
created with ``scatter``).
Parameters:
-----------
event : PickEvent
The pick event to process
Returns:
--------
A dict with keys:
"c": The value of the color array at the point clicked.
"s": Th... | 8c25bbb04ce37f9a4511d3893cfa992324ba6e90 | 641,074 |
import ipaddress
def validate_print_ip_address(ip_address):
"""Validates the given IP address and returns a printable version. For IPv4 addresses no
changes are made, for IPv6 addresses brakets are added.
Args:
ip_address: IP address to validate as string.
Returns:
A printable ve... | 991a42a96a1041ea02e5b525aa1edab979b642a9 | 641,079 |
def contains_any(str, set):
""" Check whether sequence str contains ANY of the items in set. """
return 1 in [c in str for c in set] | b2bc6146bd7ad38e240b06ed30c6df2b26156aeb | 641,081 |
def trajs_matmul(trajs, coeffs):
"""Right matrix multiply coefficients to all trajectories."""
result = []
for traj in trajs:
result.append(traj @ coeffs)
return result | 19ade7cb2927719123c2f401e48310c5a62f2f68 | 641,083 |
def read_file(filename):
"""Read the given file and return a list of lines of text read from it."""
with open(filename, "r") as file:
lines_list = file.readlines()
return lines_list | 0cf25c6fe6cc23fcf538060c008f6080e2d35824 | 641,084 |
def _listset(i):
"""create a list of unique values from iterable `i`, and
return those as comma-separated string
"""
return ", ".join(list(set(i))) | 6984924852112a7f3bb5b6b4740dbce650396b3c | 641,085 |
def tolerance(dimension_mm, itg):
"""
Returns the tolerance in micrometers using ISO standard
using the given dimension and ITG number
"""
return 10 ** ((itg - 1) / 5) * (0.45 * dimension_mm ** (1 / 3) + dimension_mm / 1000) | c862974eb83270ea170f1f660d19dc4dea0e5507 | 641,086 |
import copy
def topological_sort(structure):
"""Does the topological sorting of the given structure.
Args:
structure: A 'list' of the nodes, following the format described in
architecture_graph.py.
Returns:
A list of ordered indexes.
"""
structure = copy.deepcopy(structure)
set_l = []
s... | 5762fb0e3ed6e6299fc4b6b1c19b2b6b94f61753 | 641,089 |
def _unpadd_symetric(arrays, p, paddtype):
""" Helper function to unpadd in an assymetric way arrays.
Parameters
----------
arrays : np.ndarray or list of np.ndarray
array or list of arrays to padd.
p : int,
length of padding.
paddtype : ['left', 'right'],
where to pl... | 550041627a585997b3270163af6edb7dacb331fa | 641,095 |
def define_plot_layout(mapside, plotzoom, expidx):
"""Establish the visual of the igraph plot
Args:
mapside(int): side size of the map
plotzoom(int): zoom of the map
expidx(int): experiment index
Returns:
dict: to be used by igraph.plot
"""
# Square of the center surrounded by rad... | 8160e6d228528d72129ca657177ec167b6b08761 | 641,097 |
def convert_flux_to_nanoJansky(flux, fluxmag0):
"""Convert the listed DM coadd-reported flux values to nanoJansky.
Based on the given fluxmag0 value, which is AB mag = 0.
Eventually we will get nJy from the final calibrated DRP processing.
"""
#pylint: disable=C0103
AB_mag_zp_wrt_Jansky = 8.90 ... | 3889a4ef671b3afe6689c0c2766e6d3e96eeaf0c | 641,101 |
def filter_by_substance_composition(
data_set, compositions_to_include, compositions_to_exclude
):
"""Filters the data set so that it only contains properties measured for substances
of specified compositions.
This method is similar to `filter_by_smiles`, however here we explicitly define
the full ... | a952aec4cf369209919d632991fd5d9424c0b282 | 641,102 |
def ZonalStats(valueCollection, zoneCollection, statistic, scale = 10, tileScale = 16):
"""Computes zonal statistics across an image collection as a table.
An output value is computed:
1) For every zone in the input zone collection.
2) For every image in the value collection.
Keyword arguments... | 523fb117ff0e369fff5b2692be3614962604c4fd | 641,104 |
def compute_average(grades):
"""
Computes the average of all the grades in the list
Parameters: grades (list)
Returns: the average (float) rounded up to one decimal
"""
average = round(sum(grades)/len(grades), 1)
return average | 3a85a59c4047ef14b64e074c00bb6e0c7d95931d | 641,106 |
def get_masks(tokens, max_seq_length):
"""Mask for padding"""
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq length!")
return [1]*len(tokens) + [0] * (max_seq_length - len(tokens)) | 72472a07b246dafce44d430d3de89e7f189d6c72 | 641,118 |
def orientation(u, v, w):
"""Computes the orientation (+/-1) of a basis"""
det = u.dot(v.cross(w))
if det >= 0:
return +1
else:
return -1 | 1b6d99c1f38ca944d9a535ce48e065ff821dbaa9 | 641,119 |
import requests
from bs4 import BeautifulSoup
def get_lyrics_soup(url):
"""
Get a BeautifulSoup4 representation of a url
:param str url: URL to read
:rtype: BeautifulSoup
:return: BeautifulSoup4 object of the loaded url
"""
html_text = requests.get(url).text
soup = BeautifulSoup(html... | c5cdbe4adf1ff67b71cc39575e5005e7854d854e | 641,120 |
import json
def open_locale_file(fname):
"""Opens a locale file"""
with open(fname) as json_file:
return json.load(json_file) | 903414bddf5335d5a1d1b51e835d59cc5df0b06b | 641,121 |
def plsPredict(pls, X, realY):
"""Given a PLSR model pls, and independent variables X, predict
Y, and calculated difference to realY
"""
predY = pls.predict(X)
dY = realY - predY
return predY, dY | bd7d67f928af73ab06720daa7cb806603c3e09ca | 641,125 |
import json
def dumpJson(path: str, data: dict):
"""
Dump data to json path.
Returns
-------
`tuple(path or exception, True or False)` :
First item in tuple is a path if dumping succeeds, else it's an exceptions. Same thing goes for the second tuple
"""
try:
with open(pat... | 22d568e0833ee325a273967c4752e15ca469c3e8 | 641,128 |
import json
def document_contents_differ(old, new, threshold=20):
"""Returns whether the two document contents differ sufficiently to merit a new backup."""
# In both the road and schedule file formats, the significant differences would occur in the
# second level of the JSON object.
if old == new:
... | a6f5248949bb630458ba2c34eff0f0d569dac131 | 641,135 |
def uuid(anon, obj, field, val):
"""
Returns a random uuid string
"""
return anon.faker.uuid(field=field) | 69eb794505b871c39178e561f263f0bbb9ef384e | 641,140 |
def safe_eval(command, module, allowed):
"""
A wrapper for the python eval() function that enforces the use of a list of
allowable commands and excludes python builtin functions. This enables the
use of an eval statement to convert user string input into a function or
method without it being readily... | 73e3d452c1af16d0dcf4c939ddacd0a2e47c5911 | 641,141 |
def normalize( df, baseline = 0.1 ):
"""
Normalize all spectrum.
:param df: The Pandas DataFrame to normalize.
:param baseline: Baseline correction threshold or False for no correction.
[Default: 0.1]
:returns: The normalized DataFrame.
"""
df = df.copy()
df /= df.max()
if b... | 65a7a0238736c2c5a5e21b4bfc0205aca9f9f778 | 641,145 |
import re
def literals(choices, prefix="", suffix=""):
"""Create a regex from a space-separated list of literal `choices`.
If provided, `prefix` and `suffix` will be attached to each choice
individually.
"""
return "|".join(prefix+re.escape(c)+suffix for c in choices.split()) | 6e5aa234b11560738c72b31bd5c8090d4a673635 | 641,148 |
def get_underlying_type_name(parameter_type: str) -> str:
"""Get the underlying type name of the given type.
Strip away information from type name like brackets for arrays, leading "struct ", etc. leaving
just the underlying type name.
"""
return parameter_type.replace("struct ", "").replace("[]", ... | a2974b8bee3d7ead5772079442b77e2465fcd9c8 | 641,153 |
def round_time(time):
"""Round up or down time based on set break_point."""
minutes = time.minute if time.second < 30 else time.minute + 1
hours = time.hour
break_point = 7 # minutes
if minutes > 45 + break_point:
hours += 1
minutes = 0
elif minutes > 30 + break_point:
m... | 90a175efd631b60e485ca514d8a119f0f894b260 | 641,155 |
from pathlib import Path
import gzip
def gzip_archive(directory: str, glob_pattern: str) -> None:
"""GZip files, deletes, and places results in nested '/archive' subdirectory"""
filepath = Path(directory)
archivepath = Path(directory) / "archive"
files = [file for file in filepath.glob(glob_pattern) i... | 34a1726fa43ecbae4e94122d80741dc420e5d13b | 641,160 |
import json
def load_category_names(category_names_file):
"""
Load the category file names of flowers
Parameters:
category_names_file - path name (starting from app current working directory) including the filename and its extension
Returns:
catalog of flower classes and labels
"""
... | 8093c23fe1b627d0f0019e3110a2e788a79599be | 641,161 |
def to_coverage(total_n_reads, species_abundance, read_length, genome_size):
"""Calculate the coverage of a genome in a metagenome given its size and
abundance
Args:
total_n_reads (int): total amount of reads in the dataset
species_abundance (float): abundance of the species, between 0 and ... | 86ac080ecd95983f40394dd546a0cab4fa85cc9a | 641,163 |
def get_targets_in_network_of_expansion(node_file):
"""
In the network of expansion, the targets are scored 1.00.
This function gets the targets in the network by identifying the nodes with score 1.
"""
targets_in_network = set()
with open(node_file, 'r') as node_fd:
for line in node_fd:... | f210f55a2e23d15dd287a1b12162577dd72007e2 | 641,165 |
def get_title(obj, objid):
"""
Returns title value of the object with given ID.
:param obj: Structure containing YAML object ( nested lists / dicts ).
:param objid: YAML ID of given node.
:return: Title of given ID.
"""
result = None
if isinstance(obj, dict):
for key, val in o... | eac7045d937a27319b32acfbb431d5126243801a | 641,169 |
import pytz
def get_utc(dt):
""" Converts datetime to UTC timezone
More info: http://pytz.sourceforge.net/
"""
return dt.replace(tzinfo=pytz.utc) | 50268554b3e22946f08cff46ef2b6d74f60f1b41 | 641,171 |
import random
def rand_int(start=1, end=10, seed=None):
"""
Returns a random integer number between the start and end number.
.. versionadded:: 2015.5.3
start : 1
Any valid integer number
end : 10
Any valid integer number
seed :
Optional hashable object
.. vers... | e7e56a2b3f6b7684fe75c26ac96b59215db953f0 | 641,172 |
import hashlib
def hash(input: str):
"""
Function to hash a sentence
Parameters
----------
input : str
Input sentence to hash.
Returns
-------
n : int
Hashed value of the sentence.
"""
t_value = input.encode("utf8")
h = hashlib.sha256(t_value)
n = int... | 4790611af2eacd9edc3c6e3550a1ccb46652b069 | 641,173 |
from typing import Any
def format_with_optional_units(value: Any, units: str) -> str:
"""
Ex:
> format_with_optional_units(25.0, "cm") # returns "25.0 cm"
> format_with_optional_units(25.0, None) # returns "25.0"
"""
if units is None:
return f"{value}"
if units == "%":
ret... | 3e763bbfdaa35dfd5c4ab294a2a1e3d4ae8d6a4e | 641,177 |
def get_variables(interface1, interface2, interface3):
"""Create and return a dictionary of test variables.
:param interface1: Name of an interface.
:param interface2: Name of an interface.
:param interface3: Name of an interface.
:type interface1: string
:type interface2: string
:type inte... | 3910b1d4454409fcdb2f30d6bf6e7ca2210d3b65 | 641,178 |
def add_host(data, host):
"""Make the image path absolute for those served by the server."""
for i in range(len(data)):
data[i]['image'] = f'http://{host}/{data[i]["image"]}'
return data | dbf5ced19a545a84ee6f0e85a072f18a31d19cf3 | 641,179 |
def format_content(article):
"""
This function takes an Intercom article and formats its content
as the HTML we'll use for the Guru card. Because Intercom has some
extra fields on its articles, like the # of views, conversations, and
counts of user reactions and we don't have these fields in Guru, we
displa... | 78274dca56bc1657c0af5ddee1c6967bc5c233a5 | 641,182 |
def remove_duplicates(n):
""" Removes duplicates in a given list (referenced list)
Returns a list of all duplicates.
"""
seen = []
duplicates = []
# determine duplicates
for x in n:
if x in seen:
duplicates.append(x)
else:
seen.append(x)
# m... | 3c275f08056c8c7e369a0490c71384adaee2107a | 641,183 |
from pathlib import Path
def save_binary_file(path: str, data: bytes):
"""
Save binary data to given path
:param path: file path
:param data: binary data
"""
return Path(path).write_bytes(data) | b911ceb147360117d4753cacfb0eed9a276d1d63 | 641,186 |
def mkmdict(seq, *, container=None):
"""Make multi-dict {key: [val, val]...}."""
if container is None:
container = {}
for key, val in seq:
container.setdefault(key, []).append(val)
return container | 6597d53d90d72dba67b23b172d714b3ebc8a4020 | 641,188 |
def get_center(x_min: int,y_min: int,x_max:int,y_max:int):
"""Get center of bounding box.
Args:
x_min (int): Minimum x value in pixels.
y_min (int): Minimum y value in pixels.
x_max (int): Maximum x value in pixels.
y_max (int): Maximum y value in pixels.
Returns:
t... | 5b1095703cd3131fc02270e6cf8679826ca88ac2 | 641,190 |
from typing import Dict
from typing import List
import random
def generate_chain(model: Dict[str, List[str]], length: int, order: int) -> str:
"""Build a Markov chain from the given model.
Args:
model: A dictionary mapping ngrams to possible following words.
length: The length of the markov c... | aaa2e2f1b586e7c17c88dad504d83918259e85d7 | 641,192 |
def dataset_metadata_fixture() -> dict:
"""Test fixture returning an example dataset metadata response dict
Returns:
dict: Example Dataset metadata response dict
"""
data = {
"@context": ["metadata-v1"],
"@type": "dcat:Dataset",
"dct:title": "An example workflow definiti... | f56245e13748f9971df5aa1d67d27be95c3d1485 | 641,196 |
from typing import OrderedDict
import json
def load_watermark(wm_file, wm_size, name_feat_map=None):
""" Load watermark mapping data from file.
:param wm_file: (str) json file containing the watermark mappings
:param wm_size: (int) sixe of the trigger
:param name_feat_map: (dict) mapping of feature n... | e819846320da1d097f439f343cbb382688743a8a | 641,199 |
def url_from_key(key):
"""Given an OSF project key, retrieve the URL of the project metadata.
"""
return ('https://files.osf.io/v1/resources/{}'
'/providers/osfstorage/'.format(key)) | be2ba050e739e903b7c58286d63e6e27070fbff1 | 641,200 |
def T(*args):
"""A function that always returns true. Any passed in parameters are ignored"""
return True | c12005ec896968318bf84dfd04005a4344327cc5 | 641,201 |
def flip(matrix):
"""
Flip a matrix vertically.
Returns an immutable matrix.
Example:
1 2 --> 2 1
3 4 4 3
"""
return tuple([row[::-1] for row in matrix]) | 0af446ef680af0272ee8c19e477fa44caea0e82a | 641,203 |
import base64
def encode_images_from_file(image_paths):
"""
Encodes the processed image(s).
Args:
image_paths: List of input image filepath Strings ex).jpg , .png, .tiff
Returns: A list of encoded image(s) as ByteStrings
"""
ret = []
for path in image_paths:
with open(pat... | 848cbef53d9d676d9efdf7231d21798722bfed8f | 641,206 |
def is_yes(indicator):
"""
Check if `indicator`represents positive state
:param indicator: the bool literal like 'y', 'yes', 'true' and 'True'
:type indicator: str
:return: bool value to indicate positive or not
:rtype: bool
"""
assert(type(indicator) == str)
value_list = ('y', 'y... | e5cf9c011418f1ca8c3d850b7a6af35e33ea9ab3 | 641,207 |
def invcdf_uniform(val: float, lb: float, ub: float) -> float:
"""Returns the inverse CDF lookup of a uniform distribution. Is constant
time to call.
Args:
val: Value between 0 and 1 to calculate the inverse cdf of.
lb: lower bound of the uniform distribution
ub: upper bound of ... | a113171c9d4ced58d06e41c1289e5e30200b8d09 | 641,209 |
from typing import Sequence
def entity_dict_has_primary_key(pk_names: Sequence[str], entity_dict: dict) -> bool:
""" Check whether the given dict contains all primary key fields """
return set(pk_names) <= set(entity_dict) | aefc0ff6bfb10bedaaa180977f4da5075e4a478b | 641,213 |
def sequence_index_word(sequence, index_word_dict, pad_value=' ', join=False):
"""Sequence index transfer to sequence word.
Args:
sequence: pd.Series or np.array or List of lists, sample sequence.
index_word_dict: dict, {index: word}.
pad_value: fillna value, if word not in index_wo... | a585cfd854e7c62290041b4afdae296bda0dc1a3 | 641,216 |
def valid_alleles(alleles):
"""Return if alleles are valid (i.e. at least one non-symbolic alt)."""
return len(alleles) > 1 and not any('<' in a or '[' in a or ']' in a for a in alleles) | a91c103f3fb68ebc62e07a95e3dc155727da8cb2 | 641,219 |
from typing import List
import math
def fizzbuzz(n: int) -> List[str]:
"""Conunts and reterns N FizzBuzz numbers. The first number is "1", and the players
then count upwards in turn. However, any number divisible by three is replaced by
the word fizz and any number divisible by five by the word buzz. Numb... | 7b921c000662eefa30d4d808ea755f6fbcd4e38f | 641,221 |
def strip_trailing_zeroes(num) -> str:
"""Remove trailing zeroes, e.g. 0.500 --> 0.5 and 1.000 -> 1"""
s = "{:.3f}".format(num)
return s.rstrip("0").rstrip(".") if "." in s else s | 99d76bfc769dde5f4c40686426e0a7a5c246ff82 | 641,223 |
def rotate(string_one, string_two):
"""Determines if one string is a rotation of the other.
Args:
string_one: any string of characters.
string_two: any string of characters.
Returns:
True: if string_one is a rotation of string_two
False: if string_one is not a rotation ... | 6a35df127be54b66f0749766218e1b9884c64f7b | 641,228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.