content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def map_age(age):
"""Map ages to standard buckets."""
try:
age = int(age)
if age >= 90:
return '90+'
lower = (age // 10) * 10
upper = age+9 if age % 10 == 0 else ((age + 9) // 10) * 10 - 1
return f'{lower}-{upper}'
except:
if 'month' in age.lower... | 032fe2f2fe358c8def6c008458941d111c745330 | 684,754 |
def remove_url_trailing_slash(url):
"""
Returns the input url without any trailing / if it had a trailing slash. This is useful for repository url
where https://github.com/lwhjon/repo-labels-cli/ and https://github.com/lwhjon/repo-labels-cli both are equivalent
hence for consistency we remove the traili... | 29d35d2f2512762fa7997cc26a6159608a769855 | 684,755 |
def J(param, *args):
"""最小化を目指すコスト関数を返す"""
u, v = param
# パラメータ以外のデータはargsを通して渡す
a, b, c, d, e, f = args
return a*u**2 + b*u*v + c*v**2 + d*u + e*v + f | 5fe8b88ff7cb5a54368663b53ef3ff8d9ad24a08 | 684,756 |
def set_intersection(*sets):
"""Return the intersection of all the given sets.
As of Python 2.6 you can write ``set.intersection(*sets)``.
Examples
========
>>> from sympy.core.compatibility import set_intersection
>>> set_intersection(set([1, 2]), set([2, 3]))
set([2])
>>> set_inters... | 0e8639af9a00d0d57e0855bbdfd19a32c8f5786b | 684,758 |
def warshall_floyd(cost, num_v):
"""
ワーシャルフロイド法
:param cost: 隣接行列
:param num_v: 頂点数
:return: 各頂点からの最短距離
"""
for k in range(num_v):
for i in range(num_v):
for j in range(num_v):
cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j])
return cost | 7e0f41f54f9b64a064a86119bc7261839405b334 | 684,759 |
import torch
def topk_errors(preds, labels, ks):
"""Computes the top-k error for each k."""
err_str = "Batch dim of predictions and labels must match"
assert preds.size(0) == labels.size(0), err_str
# Find the top max_k predictions for each sample
_top_max_k_vals, top_max_k_inds = torch.topk(
... | dd1877e73d05820b78b002e4bb47db9fadc9209e | 684,760 |
def get_mf6_blockdata(f, blockstr):
"""Return list with all non comments between start and end of block
specified by blockstr.
Parameters
----------
f : file object
open file object
blockstr : str
name of block to search
Returns
-------
data : list
list of d... | 5363b566dfb48190db5945875f9924294a7d0b3b | 684,761 |
def filter_genre(genre):
"""
Create filter function for row of pandas df
:param genre: string genre to filter out
:return: Function that returns True if genre is in the row genre string
"""
def wrap(row):
genres = row['genre']
if isinstance(genres, str):
return genre... | 8d8a2a7fc2bc370f2c42974406d4d65f6a45c1dd | 684,762 |
def stackplot(self, *args, **kwargs):
""" Draws a stacked area plot.
Wraps matplotlib stackplot()
See stackplot documentation in matplotlib for accepted keyword arguments.
"""
if len(self.dims) > 2:
raise NotImplementedError("plot can only be called up to two-dimensional dimarrays.")
kw... | f3aabda746bae4feda98bb0f8618b3e0aaa89716 | 684,763 |
def GenerateContext(kind, project_id, location, cluster_id):
"""Generates a kubeconfig context for an Anthos Multi-Cloud cluster.
Args:
kind: str, kind of the cluster e.g. aws, azure.
project_id: str, project ID accociated with the cluster.
location: str, Google location of the cluster.
cluster_id:... | a1b48af02f78a31829e26b5b2366337160e41f32 | 684,764 |
def _split_uppercase(word: str) -> set:
"""
EverGreen -> Ever, Green
"""
pos_upper = [pos for pos, letter in enumerate(word) if letter.isupper()]
pos_upper.append(len(word))
simple_words = set([])
for left, right in zip(pos_upper[:-1], pos_upper[1:]):
simple_words.add(word[left: righ... | 261df0487471b6161c80b45b2a07edf0b5e460aa | 684,765 |
def fix_ncesid(ncesid, mode):
"""
Applies standard formatting (zero padding and typecasting) to
both schools' and districts' NCES IDs.
Args:
ncesid (int): Target NCES ID to fix (e.g. 100005).
mode (str): Should be either "school" or "district".
Returns:
str: Standardi... | 02d0db477039ef30beefff5470ec3781de9fc052 | 684,766 |
import glob
import os
def load_articles(article_folder): # , techniques_folder):
"""
Function for loading the articles
(based on the baseline model coming with the task)
"""
file_list = glob.glob(os.path.join(article_folder, '*.txt'))
# techniques_list = glob.glob(os.path.join(techniques_fol... | 1ceafee9226d791ec0cee64ffef7c0d08125fc2f | 684,768 |
def predict(clf, test_data, probabilities=True):
"""
Returns an array of predictions for the given *test_data* using the classifier *clf*.
If *probabilities* is True and the classifier supports it, the predictions will be Preictal probabilites.
Otherwise, the class labels are used.
:param clf: The ... | 3ec17f338a245e476d891ffb99d0b515fe9b4072 | 684,769 |
import random
import string
def _generate_postcode() -> str:
"""
Generates a postcode string. This is not guaranteed to be valid currently, but will
have the properties of
- One letter
- 1 or 2 numbers
- A space
- A number and 2 letters.
:returns: Postcode string
"""
firs... | e2d34f14bd6b12b944daf45d7961aa37b017463d | 684,770 |
def rename_aesthetics(obj):
"""
Rename aesthetics in obj
Parameters
----------
obj : dict or list
Object that contains aesthetics names
Returns
-------
obj : dict or list
Object that contains aesthetics names
"""
if isinstance(obj, dict):
for name in tup... | e426245ccc1f209dc7755d6601ae72cf5c7b933d | 684,771 |
import json
def _response(**resp):
"""
Return an API Gateway compatible response.
"""
return {'body': json.dumps(resp)} | 66c8f9f2cdf9043bd4b9f1224aae4070978ee6b8 | 684,772 |
def build_independent_priors(priors):
""" Build priors for Bayesian fitting. Priors should has a (scipy-like) ppf class method."""
def prior_transform(u):
v = u.copy()
for i in range(len(u)):
v[i] = priors[i].ppf(u[i])
return v
return prior_transform | 7749b596e38d928ef4262a296d72cece433fca88 | 684,773 |
import subprocess
def cpunodes():
"""The number of NUMA nodes, where physical CPUs are located.
Used to evaluate CPU index from the affinity table index considering the
NUMA architecture.
Usually NUMA nodes = physical CPUs.
"""
return int(subprocess.check_output(
[r"lscpu | sed -rn 's/^NUMA node\(s\).*(\w+)$... | d84a26a3fa1b28d34c0bd3394ec031315e22561c | 684,774 |
import re
def is_valid_recurrence(text):
"""Check that text is a valid recurrence string.
A valid recurrence string is 'DAILY', 'ONCE', 'WEEKDAYS', 'WEEKENDS' or
of the form 'ON_DDDDDD' where D is a number from 0-7 representing a day
of the week (Sunday is 0), e.g. 'ON_034' meaning Sunday, Wednesday... | 442eb71463b54216b2c9d4b580916939c4091acc | 684,775 |
import re
def split_into_attributes(s):
"""Split each purchase into a list of its attributes"""
return re.split(r"\t",s) | 883c6cb1c0eaaa8a9fd37825a7ae0fa1373b43db | 684,776 |
from typing import Tuple
import re
def parse_func_path(path: str) -> Tuple[str, str]:
"""
Parses a function path 'file_or_module::func'.
Parameters
----------
path : str
path should have the format: 'file_or_module::func', where `file_or_module`
is a filename or python module and ... | cc20236ec36f474b2d2ef6e4815224ddf2ce3d23 | 684,777 |
def aten__set_item(mapper, graph, node):
""" 构造对dict加入元素的PaddleLayer。
TorchScript示例:
= aten::_set_item(%features.1, %out_name.1, %x.3)
参数含义:
%features.1 (list): dict。
%out_name.1 (-): dict的key。
%x.3 (-): dict的value。
"""
scope_name = mapper.normalize_scope_name(no... | d54196409c8cf9032ee481b359ec1d045f7ead93 | 684,778 |
def make_patterns(dirs):
"""Returns a list of git match patterns for the given directories."""
return ['%s/**' % d for d in dirs] | 65c5d5c91a2e149aeebaa40d2a265ba4da62bd0f | 684,779 |
def normalize_basename(s, force_lowercase=True, maxlen=255):
"""Replaces some characters from s with a translation table:
trans_table = {" ": "_",
"/": "_slash_",
"\\": "_backslash_",
"?": "_question_",
"%": "_percent_",
... | 8b6c6fee3a55b3d704294d8bdaa7f72101ac477b | 684,780 |
import struct
def opt_int64(buf, byte_order):
"""
Convert to a signed 64-bit integer.
"""
opt_val, = struct.unpack(byte_order+"q", buf)
return opt_val | dfe811da21698bf407c0e4fe8c33f9797bff0894 | 684,782 |
def _FindLocations(input_api, search_regexes, files_to_check, files_to_skip):
"""Returns locations matching one of the search_regexes."""
def FilterFile(affected_file):
return input_api.FilterSourceFile(
affected_file,
files_to_check=files_to_check,
files_to_skip=files_to_skip)
no_presubmit... | 7ada656de609e7661cd167340c5364b9294ece7f | 684,783 |
def escape_html(text: str, *, upper: bool = False) -> str:
"""Escape some of the special characters that are replaced by FAB/SSO.
:param text: a string to escape
:param upper: (optional) change to upper case before escaping characters
:return: a string with escaped characters
"""
html_escape_ta... | 9b0cb4da765cc78f3117826b1c6f2dd50b3d2650 | 684,784 |
import math
def entropy_calc(item, POP):
"""
Calculate reference and response likelihood.
:param item : TOP or P
:type item : dict
:param POP: population
:type POP : dict
:return: reference or response likelihood as float
"""
try:
result = 0
for i in item.keys():
... | 217e9f8c02d1745aceb19833e7e41efdacd3201e | 684,785 |
def transport_priority(packet):
"""パケットの transport_priority を返す"""
return (packet[1] & 0x20) >> 5 | 3a5cd21ce67cafc738f1d7066f2806606846ae12 | 684,786 |
import numpy
def gradient_array(grad_list):
"""convert gradient python list to gradient numpy ndarray
:param grad_list: gradient list
:type grad_list: str
:return: gradient list
:rtype: numpy array
"""
return numpy.array(grad_list) | 92e7b9a4fddb07eebbbab7d89261590b1806d284 | 684,787 |
from typing import Callable
def format_exp_floats(decimals) -> Callable:
"""
sometimes the exp. column can be too large
"""
threshold = 10 ** 5
return lambda n: "{:.{prec}e}".format(n, prec=decimals) if n > threshold else "{:4.{prec}f}".format(n, prec=decimals) | 74db40ff36107571203ebd30c917416c95ddc6da | 684,788 |
def get_line_offsets(block):
""" Compute the list of offsets in DataBlock 'block' which correspond to
the beginnings of new lines.
Returns: (offset list, count of lines in "current block")
"""
# Note: this implementation based on string.find() benchmarks about twice as
# fast as a list comprehe... | 1409b3c028f76e144280936030f664285db9c7e0 | 684,789 |
def numbertoampm(hour: int, minute: int) -> tuple:
"""
Convert time in hh:mm format to AM/PM.
"""
if hour < 12 or hour == 24:
period = 'AM'
else:
period = 'PM'
hour = hour % 12
if hour == 0:
hour = 12
return (hour, minute, period) | 0aa1d52f9f93928d7ecc6167c64fc85e0e65d0e0 | 684,790 |
import sys
def str_or_unicode(text):
""" handle python 3 unicode and python 2.7 byte strings """
encoding = sys.stdout.encoding
if sys.version_info > (3, 0):
return text.encode(encoding).decode(encoding)
return text.encode(encoding) | b6a0713e53bb8dce0a12b0d56a26844a90d5f755 | 684,791 |
def reported_news(file_paths):
"""Check if Misc/NEWS has been changed."""
return True if 'Misc/NEWS' in file_paths else False | eed3c6a31f7fb16f25202e9d117d944d628985c2 | 684,792 |
def filter_in_out_by_column_values(column, values, data, in_out):
"""Include rows only for given values in specified column.
Given a DataFrame, column, and an iterable, Series, DataFrame, or dict, of values,
return a DataFrame with rows containing value in values or all rows
that do not containe a va... | 41a63d99d657d3e348d86cac0322e27f6ee98b20 | 684,794 |
import copy
def fuzzy(data, byte, begin, end):
"""
overwrite data[begin:end] <= bytes ...
"""
ndata = copy.deepcopy(data)
for i in range(begin, end):
ndata[i] = byte
return ndata | 2a390fec71ccec531b7f88ee802bc2dc94ccab6d | 684,795 |
def _replace_weird_hyphen(text: str) -> str:
""" Replace weird '–' hyphen that's not recognized as a delimeter by spacy.
e.g. '4–15 kg' -> '4-15 kg'
(You may not see a difference, but there fucking is. This motherfucker '–' is not recognized by spacy as a delimeter.)
Args:
text (str): Th... | b9ca00f70167ac0307a5658da833a6b846f0acac | 684,796 |
def heuristic_distances(judgments, repeats):
"""
Returns a numeric value for each distance (i, j) in judgments: d = (a + 1)/ (a + b + 2)
a is number of times a distance is greater than another
:param repeats: number of times each pairwise comparison is repeated
:param judgments: (dict) key: pairs of... | 4788286b53cca8b6b51d9b52791f0f0028dbcd64 | 684,797 |
import requests
import json
def getUrl(articleName, fqdn='https://en.wikipedia.org/', apiPath='w/api.php', exceptNull=False):
"""Uses the WikiMedia API to determine the ID of a page with the given
title, which is then used to construct a stable URL for the corresponding
page.
"""
queryString... | ef667eb6bd758a620317f87138e2dc283cbb56c8 | 684,798 |
def load_array_torch(data, data_arrays, batch_size, is_train=True):
"""构造一个PyTorch数据迭代器。"""
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset, batch_size, shuffle=is_train) | a5a17e67729afcb2ec752b9a084ef0447de832dd | 684,799 |
def add_css_classes(f, **kwargs):
"""
Credits go to Ramen
http://djangosnippets.org/snippets/2097/
Formfield callback that adds a CSS class to every field indicating what kind of field it is.
For example, all CharField inputs will get a class of "vCharField". If the field's widget already has a... | 69b5eb7256cd762a168126bd7e3a0e5b9496d283 | 684,800 |
import struct
def set_int(bytearray_: bytearray, byte_index: int, _int: int):
"""Set value in bytearray to int
Notes:
An datatype `int` in the PLC consists of two `bytes`.
Args:
bytearray_: buffer to write on.
byte_index: byte index to start writing from.
_int: int value ... | b2c6a6770afab55ee15ebdbb63a63d9be8f2e998 | 684,801 |
def title(s: str) -> str:
"""Capitalize sentence.
``"foo bar" -> "Foo Bar"``
``"foo-bar" -> "Foo Bar"``
"""
return ' '.join(
p.capitalize()
for p in s.replace('-', ' ')
.replace('_', ' ').split()) | a2de8c3d39d86b2cba920853310a0e47dbd861b6 | 684,802 |
import argparse
def check_positive(value):
""" Checks if the passed argument is a positive integer."""
try:
ivalue = int(float(value))
except ValueError:
raise argparse.ArgumentTypeError("{} is not a positive integer value!".format(value))
except TypeError:
raise argparse.ArgumentTypeError("{} is not a posi... | 56da0c5ad1e76a15f910228561b9419ae0a63c56 | 684,804 |
from typing import Dict
def find_intermodule_signal(sig_list, m_name, s_name) -> Dict:
"""Return the intermodule signal structure
"""
filtered = [
x for x in sig_list if x["name"] == s_name and x["inst_name"] == m_name
]
assert len(
filtered
) == 1, "Error on finding the inte... | ef177ffe389f08628d0555ac917cf718564cce14 | 684,805 |
def load_models(config, snapshots, device, side):
"""Loads models generated by model_getter into list.
Useful when dealing with an ensemble.
Parameters
----------
model_getter : function or class
returns a model object, into which we will load the state
snapshots : list or tuple
... | 632be36a3cfd0c78b326d4a55879fd7c7f6f65bc | 684,807 |
def train_calc_split(pd_shots, match_id, features, label='is_goal'):
"""
INPUT
pd_shots: (pandas) shots data (all type / on Target)
match_id: statsbomb match_id
features: list of features (column names)
label: label column name
OUTPUT
train_x: shots data
calc_... | d1a65daa65f0382408db7f4274ce497b804f0675 | 684,808 |
import json
def jsonify(data):
"""Return data as json object"""
return json.loads(data.decode('utf-8')) | f5fb1b087bb4f507572a20c396e1d72e346b54e6 | 684,809 |
def get_max_split(splits, keyfunc):
""" Returns the split in a transaction with the largest absolute value
Args:
splits (List[dict]): return value of group_transactions()
keyfunc (func): key function
Returns:
(Tuple[str]): splits collapsed content
Examples:
>>> from op... | 4a3141337fb6e55bd2eb657b78783016bb0e80b3 | 684,810 |
def breadcrumbs_li(links):
"""Returns HTML: an unordered list of URLs (no surrounding <ul> tags).
``links`` should be a iterable of tuples (URL, text).
"""
crumbs = ""
li_str = '<li><a href="{}">{}</a></li>'
li_str_last = '<li class="active"><span>{}</span></li>'
# Iterate over the list, exc... | eaf510564366858767f0e8823503c2d660028b45 | 684,811 |
def _has_only_empty_bbox(anno):
"""has only empty bbox"""
return all(any(o <= 1 for o in obj["bbox"][2:]) for obj in anno) | b079c395e91997c2f3c40918c1e612b1f227f566 | 684,812 |
def patch(source_metadata: dict, destination_metadata: dict) -> dict:
"""
Will only patch selected fields from source_metadata object to destination_metadata object.
:param source_metadata: Metadata of a dataset provided by user with patched fields
:param destination_metadata: The latest versioned metad... | 384e5dd6fd6df348853952a42f34afe0ebabe374 | 684,813 |
def heuristicPortMatch(p1, p2):
"""takes two ports and returns 1 if exact match,
0 if partial match, -1 if no match
"""
if p1.db_moduleId == p2.db_moduleId:
return 1
elif p1.db_type == p2.db_type and \
p1.db_moduleName == p2.db_moduleName and \
p1.sig == p2.sig:
... | 0e620e8687f5eb171e5922d78e76b47537c5e46f | 684,814 |
def get_sentences(in_data):
""" Custom redefinition to support Python 3.6, load sentences from a SyntaxGym Suite item """
sentences = []
for item in in_data["items"]:
for cond in item["conditions"]:
regions = [region["content"].lstrip() for region in cond["regions"] if region["content"].... | 65276cea7d2deae10992ac3caeafdea5eade3ae1 | 684,815 |
def magic_index_duplicates(seq, start = None, end = None):
""" Return the magic index, or -1 if it does not exist. """
if start is None:
start = 0
if end is None:
end = len(seq) - 1
if start > end:
return -1
# If there can be duplicate elements, we cannot determine on whi... | 8a1a56d3d5f0d19c467da9ff50ab8fb8e9be1b35 | 684,816 |
def make_dict(list1, list2):
"""
Makes a dictionary using the provided lists.
Input:
list1 (list): List to be used for keys.
list2 (list): list to be used for values.
Output:
out_dict (dict): Dictionary using the input lists
"""
out_dict = {}
i = 0
for item in list1:
... | c2731540b3a957a08b4a204ade9a54f91339ab0b | 684,817 |
def new_divider():
"""
Description: creates a new devider. A single new line divider. For example
-------------------------------------------------
Argument(s):
NONE
Returns:
The JSON format string for a divider in slack
"""
response = '{ "type": "divder... | e4b17e722dfd3f4e20c593a9c653fd196dbb8073 | 684,818 |
def partition_fxn(output_string):
""" Reads the parition function from the MESSPF output
:param str output_string: string of lines for MESSPF output file
:return temps: List of temperatures
:rtype: list: float
:return logq: loq(Q) where Q is partition function
:rtype: list: ... | b10a871af81d804c020944501135826d296bf030 | 684,819 |
import os
def load_complexity_classes(file_path: str, complexities_to_use=[0,1,2], eval_log=None, verbose=False):
"""
Load a file with the specification of the table complexity classes
"""
print(f"Loading table complexity classes for each file from '{file_path}'; classes: {complexities_to_use}", ... | d36f67e5b5ea1d3356e0c020c282f4893544ba4e | 684,820 |
def df_to_formatted_json(df, sep="."):
"""
The opposite of json_normalize
"""
result = []
for idx, row in df.iterrows():
parsed_row = {}
for col_label,v in row.items():
keys = col_label.split(".")
current = parsed_row
for i, k in enumerate(keys):
... | 02904da6afab772d657801127fc25fe4001e4da5 | 684,821 |
import os
def choose_file(fname=None, env=None, choices=[]):
"""
Chooise existing file
Returned file path is user-expanded
Args:
fname: if specified, has top priority and others are not chechked
env: if specified and set, has second-top priority and choices are not
inspec... | 1f7f285b581c1f1ed6556cceb39f5ff215991fe7 | 684,822 |
def box_normalized_to_raw(box, image_width, image_height):
"""Reformat box as needed for mm lib.
:param list box: [x1, y1, x2, y2]
:param int image_width: width of the total image in px
:param int image_height: height of the total image in px
:return: box as needed for the mm lib
"""
x1, y1... | 3cab5fecc0d622d6b31c3fa9a7db5a824958b391 | 684,825 |
def quick_sort(arr):
"""
:param : arr
:return: sorted arr
:pros : tidy and terse, no write operation on original data, good for multi-threading
:cons : passing by copy, quite high space complexity compared with C.L.R.S way.
"""
if len(arr) < 2:
return arr
pivot = arr[0]
less ... | e4a4f8bcf0e1e2f9e780153a3f9b50bae22059a3 | 684,826 |
from typing import List
def _parse_cpu_set(cpu_list: str) -> List[int]:
"""Parse a set of comma separeted CPU index. Ranges of CPUs are specified by the first and last
CPU in the range separated by a hyphen.
Example: '0,1,4-6,8-10' uses CPUs 0, 1, 4, 5, 6, 8, 9, 10
:returns: An ordered list of CPU i... | 3a31213d76759808808f5509210e95a943efe94e | 684,828 |
def Swap(tensors):
"""Swap"""
x, y = tensors
return y, x | 9472e467415c33f06cb0ecae1c22dcb20d0a524d | 684,829 |
def summa(value1, value2):
""" Summa function"""
return value1 + value2 | b7503dd2506f34663946cefd84b0df5ebe34a65f | 684,831 |
import math
def pmelt_T_iceVII(T):
"""
EQ 5 / Melting pressure of ice VII
"""
T_star = 355.0
p_star = 2216.0
theta = T / T_star
p1 = 0.173683E1 * (1 - (theta ** -1))
p2 = 0.544606E-1 * (1 - (theta ** 5))
p3 = 0.806106E-7 * (1 - (theta ** 22))
pi_melt = math.exp(p1 - p2 + p3)
... | 684d7892a4eb29b94a32d29d121eb5f680e3e756 | 684,832 |
def mixin_enabled(plugin, key, *args, **kwargs):
""" Return if the mixin is existant and configured in the plugin """
return plugin.mixin_enabled(key) | 0d89dbbc381d875d2b5f401635d74e4403267269 | 684,833 |
from functools import wraps
import click
def raise_on_error(view_func):
"""Raise a click exception if returned value is not zero.
Click exits successfully if anything is returned, in order to exit
properly when something went wrong an exception must be raised.
"""
def _decorator(*args, **kwargs... | 74aada1a3bb08d27c31f989f4aa6ea7e8f5cb571 | 684,834 |
import math
def millify(n):
"""Convert integer to human readable format.
Parameters
----------
n : int
Returns
-------
millidx : str
Formatted integer
"""
millnames = ["", " KB", " MB", " GB", " TB"]
# Source: http://stackoverflow.com/a/3155023/756986
n = fl... | b209f96e28bd1d6f3403370975ea925c235b2107 | 684,835 |
def search_no_size(reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
a = 2
while reader.get(a) != 2147483647:
if reader.get(a) == target:
return a
elif reader.get(a) > target:
break
else:
a *= 2
d... | cb1e5806e314fe1a225532707376bab029da9bdc | 684,836 |
def load_registries():
"""Fixture to control the loading of registries when setting up the hass fixture.
To avoid loading the registries, tests can be marked with:
@pytest.mark.parametrize("load_registries", [False])
"""
return True | 32c343a2f9bbcca477a00f2f10de6e36c38a0da5 | 684,837 |
def services_json(hass):
"""Generate services data to JSONify."""
return [{"domain": key, "services": value}
for key, value in hass.services.services.items()] | b5e50c3b79fa2cf6778f4dd0ac67155b2c79c64f | 684,838 |
async def get_url_ohlcv(interval: str) -> str:
"""A function that returns the url for an ohlcv request
Args:
interval (str): "day", "minute1", "minute3", "minute5", "week", "month"
Returns:
str: API url
"""
if interval in ["day", "days"]:
return "https://api.upbit.com/v1/c... | 113a0ab0121733258f189ea5f81ed40744497de1 | 684,839 |
def tetra_clean(instr: str) -> bool:
"""Return True if string contains only unambiguous IUPAC nucleotide symbols.
:param instr: str, nucleotide sequence
We are assuming that a low frequency of IUPAC ambiguity symbols doesn't
affect our calculation.
"""
if set(instr) - set("ACGT"):
ret... | 8e11bcb9896e21f06b8ed6f673942a2022ce5a13 | 684,840 |
def transform_contact_details(data):
"""
Takes a dictionary of contact details and flattens every entry to {key: {label: label, value: value} .
"""
transformed_data = {}
for key, value in data.items():
if 'label' in value:
transformed_data[key] = value
else:
... | f3f0ecd61dc40c6b55174681883acf81db045e04 | 684,842 |
def get_concordance(tokens: list, word: str, left_context_size: int, right_context_size: int) -> list:
"""
Gets a concordance of a word
A concordance is a listing of each occurrence of a word in a text,
presented with the words surrounding it
:param tokens: a list of tokens
:param word: a word-b... | 723ce706d7f7bd27b4ddfd1c18ed7c59e1479992 | 684,843 |
def encode_file_name(file_name):
"""
encodes the file name - i.e ignoring non ASCII chars and removing backslashes
Args:
file_name (str): name of the file
Returns: encoded file name
"""
return file_name.encode('ascii', 'ignore') | dfa0408979ec3079c1d1fa5a06dcd132a8d1fde4 | 684,844 |
def task_test():
"""Perform all tests."""
return {
"actions": [],
"task_dep": ["unittest", "style", "docstyle"],
} | 33763d84978dbc9ed0ea952b866e5c8c636be11c | 684,845 |
import hashlib
def hash_worker(offset, block_size, filename, method):
"""Worker function to be run in child processes."""
with open(filename, "rb") as handle:
handle.seek(offset)
context = hashlib.new(method)
context.update(handle.read(block_size))
return offset, context.hexdig... | d38043aee01bf830b2d22fa1bd6c3dbfe24ce90e | 684,847 |
import re
def remove_citations(text: str) -> str:
"""
Removes the citations that consist of a pair of brackets having a substring
containing at least one digit inside them.
Args:
text (str):
Returns:
"""
text = re.sub("\[[a-zA-Z]\]", "", text)
return re.sub(r"\[(\s|\w)*\d+(\s... | ecd48cb90ff5c4a4e19e2f5e67f9e6b5a854bc9f | 684,850 |
def get_mode_two_ramping_capability(t2, min_loading, current_mode_time, effective_ramp_rate):
"""Get ramping capability when @CurrentMode = 2"""
# Amount of time remaining in T2
t2_time_remaining = t2 - current_mode_time
# Time unit is above min loading level over the dispatch interval
min_loading... | f4c8264552aa081012daef1fdecc057aba344b3a | 684,851 |
def check_lammps_sim(out_file, verbose=True):
"""
Check if LAMMPS simulation is finished.
"""
FINISHED = False
try:
with open(out_file, 'r') as f:
lines = f.readlines()
if 'Total wall time' in lines[-1]:
FINISHED = True
except Exception as e:
if ve... | a8266c9652c47cc4831f6bdfc1a4050bac6e94ce | 684,852 |
import re
def _date_tuple(strdate):
"""_date_tuple(strdate)
Converts a date string of the format "[YY]YY/[M]M/[D]D" into a 3-tuple
of month, day, and year integers.
Positional arguments:
strdate (str) - date string of the format "[YY]YY/[M]M/[D]D"
Returns:
tuple ((int, int, int)... | 48da1e5d2cf26480a931360b0872340d44da0eca | 684,853 |
def find_motif_positions(sequence: str, motif: str):
"""
Returns the start and end position(s) of a core motif in a sequence
Args:
sequence: string of nucleotides
motif: string of nucleotides representing a motif
Returns:
startpositions: list of start position(s) of core motif ... | 5dea5868601e8c0bc080b1268fdf84a14e0ed180 | 684,854 |
def zeta_a(eN,cL,w):
"""
EnKF-N inflation estimation via w.
Returns zeta_a = (N-1)/pre-inflation^2.
Using this inside an iterative minimization as in the iEnKS
effectively blends the distinction between the primal and dual EnKF-N.
"""
N = len(w)
N1 = N-1
za = N1*cL/(eN + w@w)
return za | d7626d43b88bfb8c9d0dc0ec68949e9145c0a7dc | 684,855 |
def delay(df, period=1):
"""
Wrapper function to estimate lag.
:param df: a pandas DataFrame.
:param period: the lag grade.
:return: a pandas DataFrame with lagged time series
"""
return df.shift(period) | c58729d654a278442ef7dbac38b1f1c78bf41e3a | 684,856 |
import platform
def platform_system():
"""
For example: windows/linux
"""
return platform.system().lower() | 1d000ffa699fe13b9e48add95dc7f8286fc975bd | 684,857 |
def _interpolate_spectrum(sp1, sp2, par):
"""Interpolate spectra to the given parameter value."""
spectrum1 = sp1.pop()
spectrum2 = sp2.pop()
par1 = sp1.pop()
par2 = sp2.pop()
if par1 == par2:
sp = spectrum1
else:
a = (par1 - par) / (par1 - par2)
b = 1.0 - a
... | c9a85c80f6f903ceefd9bec4dcc9a2d34a693a91 | 684,858 |
def get_ptf_server_intf_index(tor, tbinfo, iface):
"""Get the index of ptf ToR-facing interface on ptf."""
mg_facts = tor.get_extended_minigraph_facts(tbinfo)
return mg_facts["minigraph_ptf_indices"][iface] | 3939174488f26607d7870bced1b4adfc8d8c185d | 684,859 |
import ctypes
def async_raise(tid, exctype):
"""
Raises an exception in the threads with id tid
:param tid:
thread id in python
:param exctype:
exception class, e.g. IOError
"""
return ctypes.pythonapi.PyThreadState_SetAsyncExc(
tid,
ctypes.py_object(exctype)
... | 73b6fd9a9a3ecd80602e7524104e202a147468d1 | 684,860 |
def get_unique_locations(db):
"""
Gets an iterator to the unique locations (lat, lon)
:param db: Source database (VedDb)
:return: Iterator to the unique locations
"""
sql = "select distinct latitude, longitude from signal"
locations = db.query_iterator(sql)
return locations | 50b404303c1738840d29d4f189252ae963452c2f | 684,861 |
def fun(x):
""" (function) -> float
<x> is the function to differentiate
"""
return 3 * x ** 2 + 5 | 7266287291280d1012ea8b110cf86db2eadc28e6 | 684,862 |
def get_link_cost(latency_dict, s1, s2):
"""
returns the link cost
@param latency_dict:
@param s1: switch 1
@param s2: switch 2
@return:
"""
link_cost = latency_dict[s2][s1]
return link_cost | ee1582907941205d4ad0275ff2a057a74399e996 | 684,863 |
def choose_init(module):
"""
Select a init system
Returns the name of a init system (upstart, sysvinit ...).
"""
# Currently clearlinux only has systemd.
return 'systemd' | 29e3a332f94ce5d0a676bed68501b42342c181a5 | 684,864 |
def preplace(schema, reverse_lookup, t):
"""
Replaces basic types and enums with default values.
:param schema:
the output of a simplified schema
:param reverse_lookup:
a support hash that goes from typename to graphql type, useful to navigate the schema in O(1)
:param t:
... | d0276e9f14f0e0c6558a5646e2c102aefe901a3f | 684,865 |
def get_sale_head(date_head):
"""Return the date of the livestock sale."""
head_string = date_head[-1].replace("\n","").strip()
return head_string | afbf27170dc6c4a5d35e2ae7412f5c7b71dfe1a1 | 684,867 |
import pandas
def read_beast_log(logfile, nearest_leaf_date, take_last_lines=500):
"""
Reads the log file, produced by Beast. Note the column names are defined in
the Beast template file from the resources. If another template used, make
sure the column names are the same.
Args:
- logfile(s... | a81681b673e48e33df620ac84d40084d46bc09f7 | 684,868 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.