content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def are_equal_on_common_keys(dict1, dict2):
"""
Return True if and only if all (nested) values of the dicts are the same for the keys (paths) they share
:param dict1:
:param dict2:
:return:
"""
for k in dict1:
if k in dict2:
v1 = dict1[k]
v2 = dict2[k]
... | e864c9885538da6bd211d57232198ef7f3a6c6c5 | 593,830 |
import json
def get_input(decision):
"""
From the decision response, which is JSON data form SWF, get the
input data that started the workflow
"""
try:
input = json.loads(decision["events"][0]["workflowExecutionStartedEventAttributes"]["input"])
except KeyError:
input = None
... | 0050d10304d367acd03c5e9053156054a6eed336 | 593,831 |
def TmpDir(tmpdir_factory):
"""Create a temporary directory to store testing files."""
dir_path = tmpdir_factory.mktemp("test_results")
return dir_path | 3b1ce915cd54d67b9276c6cc385dcaa6b0fb49c1 | 593,836 |
import collections
def get_top(iterator, top_size=10):
""" Return a list of the top_size most common elements and their counts from iterator """
return collections.Counter(iterator).most_common(top_size) | 44356253475425c63e73c02147df81c25ae95d9e | 593,838 |
import torch
def mixture_bernoulli_loss(label, log_theta, log_alpha, adj_loss_func,
subgraph_idx):
"""
Compute likelihood for mixture of Bernoulli model
Args:
label: E * 1, see comments above
log_theta: E * D, see comments above
log_alpha: E * D, see... | 5a823c1613de75c777101d4b25d60b96ea5b986c | 593,843 |
def bondi_constraints(self, lhs=True, rhs=True):
"""Compute Bondi-gauge constraint equations
Bondi gauge establishes some relations that the data must satisfy:
ψ̇₀ = ðψ₁ + 3 σ ψ₂
ψ̇₁ = ðψ₂ + 2 σ ψ₃
ψ̇₂ = ðψ₃ + 1 σ ψ₄
ψ₃ = -∂ðσ̄/∂u
ψ₄ = -∂²σ̄/∂u²
Im[ψ₂] = -Im[ð²σ... | 136e34922c496ce96eb5eb12cc4794024e4b51bf | 593,848 |
import re
def github_qualify_references(log, repo_userorg, repo_name):
""" Replace "unqualified" GitHub references with "fully qualified" one
GitHub automatically links issues and pull requests if they have a specific
format. Links can be qualified with the user/org name and the repository
name, or u... | b6b8421ace259c19f0adeba61e1dc3c686a5cb23 | 593,850 |
def make_sample_id(gloss_id, lang1, lang2, index1, index2):
"""
Sample IDs should uniquely identify a feature row.
Sample sample ID: 98/English,German/1,1
"""
assert lang1 < lang2
s = str(gloss_id) + '/'
s += lang1 +','+ lang2 + '/'
s += str(index1) +','+ str(index2)
return s | 4a935605788c4561aab06fe8bd2e88675d81c7a0 | 593,856 |
def latest(scores):
"""Return last score."""
return scores[-1] | 5f9475c17776ea5ceb15ba15c3029c5c4031b2cd | 593,858 |
def load_label_dict(labeldict_pth):
"""Load label dictionary
Args:
labeldict_pth: path to the label description
Return:
lbl_dict: label dictionary {lbl_name: lbl_id}
inv_lbl_dict: inverse label dictionary {lbl_id, lbl_name}
"""
lbl_list = open(labeldict_pth).read().splitlin... | d76c3dedf2e5a5bf47af995659652bcff30d1bed | 593,865 |
import math
def less_than_one(value):
"""Recalculate the maximum for a series if it is less than one
by scaling by powers of 10 until is greater than 1
"""
value = abs(value)
if value < 1:
exp = int(math.log10(value))
return 10**((abs(exp)) + 1) | b5a5bfc22a2eba82bd22807a23a6aa40e5bf768e | 593,867 |
def _IsIn(matcher, value, operand):
"""Applies matcher to determine if value matches/contains operand.
Both value and operand can be lists.
Args:
matcher: Boolean match function that takes value as an argument and
returns True if the value matches/contains the expression operand.
value: The key va... | 413c716e0e608455512a671d388fe7f93fe0d258 | 593,868 |
import logging
def create_log_handler(name, log_level=None, style_adaptor=None):
"""Create a logger.
"""
log = logging.getLogger(name)
if log_level:
log.setLevel(log_level)
if style_adaptor:
log = style_adaptor(log)
return log | 29d5b13868b4eb8d0fcdd5514d33380d4988fd84 | 593,869 |
def _join_host_port(host, port):
"""
Returns joined host:port, wrapping host in brackets if it looks like an IPv6 address
:param str host:
:param int port:
:return str:
"""
if ':' in host:
return '[%s]:%s' % (host, port)
else:
return '%s:%s' % (host, port) | cdcfb2c532c58db420cc712a962a96569157a55a | 593,871 |
def break_str(prereqs):
"""
Break a string into multiline text.
"""
return ' \\\n\t'.join(prereqs) | 53093b1c0257b6e9f7028b347c347f34f996b08f | 593,876 |
import itertools
def model_to_dict(instance, fields=None, exclude=None):
"""
Return a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, return only the
named.
``exclude`` is an o... | 29d61835456988a68e65e62f859a227ad18edf01 | 593,882 |
def denormalize(x, dl, dh, nl, nh):
"""
An inverse function of the range normalize operation.
Parameters
-----------
:param x: The number/vector to be normalized
:param dl: The minimum possible value of x.
:param dh: The maximum possible value of x.
:param nl: The minimum possible value... | 07cb1acd6d7830866f659a52351b3ff3e6dedd8c | 593,883 |
def _y_limits(ref_DFT, y):
"""
Sets the y_limits of each plot to encompass both the data points and reference data, making sure the distributions are to the same scale.
Args:
ref_DFT (np.array): 1D array of reference lattice parameter values in same order as labels.
y (np.array): lattice pa... | f1e0489ca2b004716513420ab5cd1d757066f550 | 593,886 |
def convertVariableName(variable):
"""
Return the mixedCase version of a SERPENT variable.
Parameters
----------
variable: str
``SERPENT_STYLE`` variable name to be converted
Returns
-------
str:
Variable name that has been split at underscores and
converted to ... | 0d2c8f9e845438a2ce860eac36a09abd63b74769 | 593,888 |
def finmag_to_oommf(f, oommf_mesh, dims=1):
"""
Given a dolfin.Function f and a mesh oommf_mesh as defined in
finmag.util.oommf.mesh, it will probe the values of f at the coordinates
of oommf_mesh and return the resulting, oommf_compatible mesh_field.
"""
f_for_oommf = oommf_mesh.new_field(3)
... | 35372e02e0eaad9e66380d031602a943460018a3 | 593,889 |
def get_gl(variant_call):
"""Returns the genotype likelihoods of the VariantCall.
Args:
variant_call: VariantCall proto. The VariantCall for which to return GLs.
Returns:
A list of floats representing the genotype likelihoods of this call.
"""
return variant_call.genotype_likelihood | 320916b93ad4a630acfb3071cb5207592aaf563a | 593,891 |
import json
def save_files_tmp(data, file_format: str, file_name: str):
"""
# SAVE FILES ON TEMPORARY
Save files on `./tmp` to upload more easily into the storage.
Parameters
----------
data
The information to be saved on the storage.
file_format : str
The type of format ... | 4b85ff57266f7fca29913f775da6650e8bcdd12b | 593,898 |
def dmarc_find_organizational_domain(domain, public_suffix_list):
"""
Find the organizational domain of the given domain.
Uses mainly the algorithm found at https://publicsuffix.org/list/ to get
the organizational domain. Could return "" if none is found.
"""
# The algorithm could be more elab... | a6cf238765d19e578d366396358b0d35d6652f8c | 593,901 |
def check_nocachekey(option):
"""
checks if an option is a NoCacheKey option or Etag
:param option:
:return:
"""
return ((option.number & 0x1E) == 0x1C) | (option.number == 4) | dc277e3ffc3a5dc6228eba72ec732d1e2f465c08 | 593,902 |
def formatLevel(level: int, s: str) -> str:
"""Helper to indent a string with a number of tabs"""
return "\t" * level + s | 09a1de1959d0d9fc9fc25ebb7df938133d879f42 | 593,904 |
def get_filenames_from_urls(urls):
""" Returns a list of filenames from a list of urls"""
return [url.split("/")[-1] for url in urls] | ca02bcb0efe88beb008a45c572b276cd9bd4ae9f | 593,905 |
import torch
def pose2mat(pose):
"""Convert pose matrix (3x5) to extrinsic matrix (4x4) and
intrinsic matrix (3x3)
Args:
pose: 3x5 pose matrix
Returns:
Extrinsic matrix (4x4) and intrinsic matrix (3x3)
"""
extrinsic = torch.eye(4)
extrinsic[:3, :] = pose[:, :4]
... | 635aa636fa38c54c5592b625ec6690b0264f63a4 | 593,906 |
def identity(filename):
"""
For use with key_from_filename parameter.
This give the full filename (with suffixes) as the key.
"""
return filename | 463e5d96f6d346a981e4120b9eae489f1163be87 | 593,910 |
def _find(value, in_string):
"""true if the value is in the string"""
str_value = str(value)
return in_string.find(str_value) > -1 | 340dd2407c1311c8cd9013a019ce40be771c8dd4 | 593,911 |
def normalized_digest(digest, digest_type='sha512'):
"""Normalize the digest to return version that enables string comparison.
All forms (except the spec example forms) are case insensitive. We
use lowercase as the normalized form.
"""
if digest_type in ('sha512-spec-ex', 'sha256-spec-ex'):
... | 5d4b7699babaa0fa4fb6cd87db719dc81c91800f | 593,912 |
def split_list_by_index(alist, indices, include=False):
""" Split a list by index ranges
:param alist:
:param indices:
:param include: include index value as a "pivot" (end and start of broken sub-lists): True or False
:return:
"""
# Be sure there is no repetitive indices
indices = list... | 0f439e0644e1cb0aa63ebd7e440ba8ee0c213f8c | 593,926 |
def utilization_graph(utilization, warning_threshold=75, danger_threshold=90):
"""
Display a horizontal bar graph indicating a percentage of utilization.
"""
if utilization == 100:
bar_class = 'bg-secondary'
elif danger_threshold and utilization >= danger_threshold:
bar_class = 'bg-d... | bdac686c4f971f062c882f9c4f146b1628ce3431 | 593,927 |
def _clockwise(pnt1, pnt2, pnt3):
"""Return True if pnt2->pnt2->pnt3 is clockwise"""
vec1 = (pnt2[0] - pnt1[0], pnt2[1] - pnt1[1])
vec2 = (pnt3[0] - pnt2[0], pnt3[1] - pnt2[1])
return vec1[0] * vec2[1] - vec1[1] * vec2[0] < 0 | 45238f469949726d5a22a8b7f3c45d6ff5f3e6ca | 593,928 |
import csv
def csv_to_list_of_dicts(string):
""" Takes a CSV string. Creates a list of dictionaries by
using the headers of the CSV as keys, and the values in each row as values. """
reader = csv.DictReader(string.splitlines())
list_of_dicts = []
for row in reader:
list_of_dicts.append(di... | 4178f7d68aa8f41d4f46030b6cedf9bbf367735d | 593,931 |
def _coerce_run_param(name, val):
"""Ensures that named param is valid for the run command."""
if name == "flags":
return tuple(val)
return val | c5c533c8d92ebb64d78e720dadf03a6e5d0dab4a | 593,935 |
import ast
def define_lambda(name, args, body):
"""
Construct AST lambda assignment with specified name, args and
body. Because lambdas are anonymous, we must assign them to some
variable in order to reference them. This variable is returned to
end-user.
"""
return ast.Assign(
t... | ed8ce0f803d322a499786f508eaaa92a150982a8 | 593,936 |
def on_segment(p, q, r):
"""
Checks to see if given three collinear points p, q, r, the function checks if
point q lies on line segment 'pr'.
p: First endpoint of line 'pr' described by a tuple.
q: Point being tested described by a tuple.
r: Second endpoint of line 'pr' described by a tuple.
... | 4135bb66504166ce78569cbddc50299f4c24fb85 | 593,942 |
from typing import Iterable
from typing import Tuple
import functools
def min_max(x: Iterable[int]) -> Tuple[int, int]:
""" Returns both the min and max of a sequence.
This, rather than calling min(x), max(x), will work when a generator (or other single-use iterator) is passed in
"""
try:
seq ... | 381be58127d0e610bd9c3ac8998cda56fa172c6f | 593,944 |
def can_comment(user):
"""Checks if a user can post comments to product"""
return user.permissions['perm_comment'] | ec21e94e741048822c951c71f677e54887490ec1 | 593,945 |
import pathlib
def is_gz(file_path):
"""Check if given file_paht is gzipped based on suffix"""
if isinstance(file_path, pathlib.Path):
file_path = file_path.name
return file_path.endswith(".gz") or file_path.endswith(".z") | 861788eaea0fb5dc575a1dd84cc7ed810b8e7991 | 593,946 |
def normalizeURL(url: str) -> str:
""" Remove trailing / from the url. """
if url is not None:
while len(url) > 0 and url[-1] == '/':
url = url[:-1]
return url | 6c706c7780d401bc0610d051fc62ef5fd58bdaff | 593,948 |
def position_to_index(pos, nelx, nely):
"""
Convert a position vector to the index of the element containing it
"""
index = int(pos[0])*nely + int(pos[1])
return index | b94d337462381ffe318f8cd58922def725b6299e | 593,950 |
def posix_path_join(*parts):
"""This function works similar to os.path.join() on posix
platforms (using "/" as separator)."""
parts = [p for p in parts if p != ""]
return "/".join(parts) | b0d233cad8ce18333f2496cac2cf64e3cf6d2ff7 | 593,951 |
def input_number(prompt, minimum, maximum, default=None):
"""
Prompt for a numerical input between minimum and maximum.
If the default is not specified, the default is the minimum.
"""
if not default:
default = minimum
if minimum == maximum:
return minimum
if minimum > maximu... | 7f35219cbf2b8e295227b739482a9db56e8c19c2 | 593,952 |
import torch
def get_numerical_characteristics(data):
"""
返回数据(data)的 4 个数字特征(numerical characteristics):
1. mean:均值
2. std:标准差
3. skewness: 偏度
4. kurtosis: 峰度
:param data: 数据
:return: 一维数据: torch.Size([4])
"""
mean = torch.mean(data)
diffs = data - mean
var = torch.me... | 9ea636b38f98d83304753a9e68712d1f4e81edd5 | 593,955 |
from typing import Tuple
import math
def calc_differential_steering_angle_x_y(b: int, dl: float, dr: float, o: float) -> Tuple[float, float, float]:
"""
Calculate the next orientation, x and y values of a two-wheel
propelled object based on the differential steering principle.
:param b: the distance ... | bd9c2bac7296e188930b51b7d5c1775f6af2ad9f | 593,958 |
def foo1(x):
"""
Returns x+1
Parameter x: The number to add to
Precondition: x is a number (int or float)
"""
assert type(x) in [int,float], repr(x)+' is not a number'
return x+1 | ce29e70abef3d7c565d42aed3686fb1ace887235 | 593,962 |
def strategy_cheap(cookies, cps, history, time_left, build_info):
"""
Always buy the cheapest item you can afford in the time left.
"""
items = build_info.build_items()
costs = {}
for item in items:
cost = build_info.get_cost(item)
costs[cost] = item
cheapest = min(costs)
... | 725512e43f8aa0c8222ffd0e5021226ae131adf4 | 593,966 |
import hashlib
def sha256sum(filename):
"""
Efficient sha256 checksum realization
Take in 8192 bytes each time
The block size of sha256 is 512 bytes
"""
with open(filename, 'rb') as f:
m = hashlib.sha256()
while True:
data = f.read(8192)
if not data:
... | 711032b57692629720ce817b9095d3ad193ac1bd | 593,971 |
def select_to_text_vals_only(caption, choices):
"""
A function to convert a select item to text in a compact format.
Format is:
[question], choices: [choice1], [choice2]...
"""
return "%s, choices: %s" % (caption, ", ".join(choices)) | 36fee87d17e22db10608ed5721fdd7e6dade7126 | 593,980 |
def cond_include(should_include, template_name, data):
"""A tag to conditionally include a template."""
return {
'should_include': should_include,
'template_name': template_name,
'data': data,
} | 113995b83d29664e1bb4012e36f4f8eace9fced4 | 593,982 |
def red_channel(image):
"""
Changes the image as follows:
For every pixel, set green and blue values to 0, yielding the red channel.
Return the changed image.
"""
for pixel in image:
pixel.green = 0
pixel.blue = 0
return image | cabc1d81a5b15a56692d6d7d67e26662aad31afd | 593,984 |
from typing import List
def column_to_list(data:List[List[str]], index:int) -> List[str]:
""" Transforma uma colunas em uma lista.
A partir de uma lista de listas e de um índice de coluna, gera uma nova lista com o conteúdo da coluna requisitado.
:param data: Lista de lista contendo linhas e colunas.
... | bd85fd53bec96d116c235e857c18266aeedccf02 | 593,992 |
def _later_date(date1, date2):
"""_later_date(date1, date2)
Compares two (month, day, year) tuples to see which is later.
Positional arguments:
date1 (tuple) - first date tuple
date2 (tuple) - second date tuple
Returns:
bool - True if the first date is later than the second, F... | 505273cab7e53a727b5e9d6a3be32f0d780157b7 | 593,993 |
def normalized_probs(p_mem, p_non, p_a):
"""
Walker 2009 equation 11
Parameters
----------
p_mem: np.array
p_non: np.array
p_a: np.array
Returns
-------
norm_probs: np.array
"""
p_m = (p_mem*p_a)/(p_mem*p_a + p_non*(1.0 - p_a))
return p_m | 190cf14baf39c17e0bef2a7b544ad14b70ea967a | 593,994 |
import hashlib
from typing import OrderedDict
def compute_identity(sample, size):
"""Compute a unique hash out of a dictionary
Parameters
----------
sample: dict
Dictionary to compute the hash from
size: int
size of the unique hash
"""
sample_hash = hashlib.sha256()
... | 4ab0038f23c49e07d0efee1bbfd7bb9b55eb143c | 593,998 |
def _get_model_prediction(service, project, model='demo_model',
version=None, body=None):
"""
Helper function to infer a model prediction
Args:
service: Google API Service object
project: GCP project id (str)
model: AI Platform model name (str, default: 'de... | 1da19eff52fb3c0d7235c0e7dbec618e63168d3d | 594,006 |
def _get_inputs_tensor_info_from_meta_graph_def(meta_graph_def,
signature_def_key):
"""Gets TensorInfo for all inputs of the SignatureDef.
Returns a dictionary that maps each input key to its TensorInfo for the given
signature_def_key in the meta_graph_def
Args:... | f0b10da9d70050510a35ba6e0f805bdafda506c7 | 594,010 |
import math
def isprime_ver3(n):
"""
Returns True if n is prime, False otherwise.
* Only check up to the square root of n.
* Start checking at 3 and skip evens.
"""
if n < 2:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
i = 3
limi... | 382eaef747dc09ed90b0107d4822c32716914a5f | 594,014 |
def get_binary(number):
"""
Return the binary string of number (>=0) without 0b prefix.
For e.g 5 returns "101", 20 returns "10100" etc.
"""
return bin(number)[2:] | 77341c0a4ac49a789a86fe0e9877ed57556090f1 | 594,017 |
import math
def safe_sqrt(val):
"""
Safely calculates the square root of a value. If the value is -1 (unknown),
then the result is -1 (unknown).
"""
return -1 if val == -1 else math.sqrt(val) | 77d1d61d81a29f226054685b2f92be1baf6bdcb6 | 594,018 |
def _myDet(p, q, r):
"""Calc. determinant of a special matrix with three 2D points.
The sign, "-" or "+", determines the side, right or left,
respectivly, on which the point r lies, when measured against
a directed vector from p to q.
"""
# We use Sarrus' Rule to calculate the determinant.
... | 3bd72aa726039018616cc434611948e29e7bd982 | 594,022 |
def Overlaps(j, k):
"""Inputs, j and k, are tuples/lists with a start and a end
coordinate as in: (start, end). If they overlap True is returned,
if they do not overlap, False is returned.
"""
j = sorted([int(i) for i in j])
k = sorted([int(i) for i in k])
jk = sorted([j,k], key=lambda x:x... | 1a36f5c5a9ee1c658a32403ddbfe26ccfc67078d | 594,025 |
def equal_but_for_ellipses(got, want):
"""Compare two strings, but match "..." to zero or more characters"""
ellipsis = "..."
# Cut trailing whitespace from the comparisons
given = got.rstrip()
musts = want.rstrip().split(ellipsis)
# Require each fragment between "..." ellipses, in order
... | 2f2cac855c427b42b64b01734f74279921b5b89f | 594,026 |
def compute_average_unit_cell(unit_cell_list):
"""Compute the weighted average unit cell based on a list of
((unit cell), nref)
tuples."""
w_tot = 0.0
a_tot = 0.0
b_tot = 0.0
c_tot = 0.0
alpha_tot = 0.0
beta_tot = 0.0
gamma_tot = 0.0
for cell, n_ref in unit_cell_list:
... | 40c592751f4e7b3a6bc6e02f348f72174239f3eb | 594,034 |
def iterative_replace_line (input_line: str, case: str, source: dict, add_line: str) -> str:
"""
Iterative replacer. Iteratively copy-pastes `input_line` each time with a new substitution of a templated variable depending on the `case`.
Parameters:
input_line (str) : input li... | 5b2564f1c36dcb420fcfec704e56f591c8eb6406 | 594,038 |
def new_database_connection_message(payload):
"""
Build a Slack notification about a new database connection.
"""
connection_url = payload['connection']['url']
connection_name = payload['connection']['name']
connection_vendor = payload['connection']['vendor']
connection_provider = payload['... | 58b0b2fa1b50291c9b0ae92e4d6d52b3a5a1ad64 | 594,039 |
def bprop_exception(x, out, dout):
"""Backpropagator for primitive `exception`."""
return x, | d77ba1bfcf8fa80910492584c24b3e48efdfb9f6 | 594,040 |
import re
def regex_objects_from_patterns(patterns):
""" returns regex_objects compiled from regular expression patterns"""
regex_objects = []
for pattern in patterns:
regex_object = re.compile(pattern)
regex_objects.append(regex_object)
return regex_objects | b3007884ef5dea5012e63de510238341006cf45d | 594,046 |
def _dart_web_application_outputs(dump_info, deferred_lib_count):
"""Returns the expected output map for dart_web_application."""
outputs = {
"js": "%{name}.js",
"deps_file": "%{name}.js.deps",
"sourcemap": "%{name}.js.map",
}
if dump_info:
outputs["info_json"] = "%{name}.js.info.json"
f... | f7dc13b2ced07a010baa86b03304acc17817befe | 594,051 |
def closest_fraction(x, N):
"""Compute (a, b) such that a/b is closest to x from below, and with 0 <= a, b < N"""
best_num = 0
best_den = 1
best_approx = 0.0
assert(x >= 0)
for den in range(1, N):
num = round(den * x)
approx = num / den
if x - approx >= 0 and x - approx... | 6186751b49f4d46341814de1b3c591a3533d2c1a | 594,055 |
def _create_youtube_video_asset(
client, customer_id, youtube_video_id, youtube_video_name
):
"""Creates a asset with the given YouTube video ID and name.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID str.
youtube_video_id: a str of a YouTu... | 459555ea8e67a5a9c8a568e108ec14411ed80692 | 594,061 |
import math
def calc_bearing_great_circle(lat_ref, lon_ref, lat_loc, lon_loc):
"""
Calculate the great circle bearing
:param lat_ref: float
:param lon_ref: float
:param lat_loc: float
:param lon_loc: float
:return: float bearing in degrees (north zero deg)
"""
y = math.sin(lon_loc ... | 3ab94d74e053c61e831abf414a1409b13b7b9b42 | 594,069 |
import itertools
def counter(counter=itertools.count()):
"""
Each time we're called, return the next integer in the natural numbers.
"""
return next(counter) | 74c46e70abe47ff59b57103ea76ffd4051829d49 | 594,075 |
def add(augend, addend):
"""Adds the augend and addend together
This function add augend and addend together only when they are either
integers or floats
Args:
augend(int/float): The number to which an addend is added
addend(int/float): The number that is added to another
>>> add(... | ed53b219836fac67a066a9251281ad074f1619af | 594,076 |
def _length_checker(length, content):
"""Helper function to check if a string is shorter than expected length of not.
:param int length: Maximum length of an expected string.
:param str content: A string to be validated.
:return str: A string of error message if validation fails, or an empty string if... | 3ef7813142e6ad36c9a27e0223dd612e6b0d63c1 | 594,077 |
import re
def is_valid_ttl(ttl):
"""Check that ttl value is valid (ie. positive signed 32 bit number)"""
if len(ttl) == 0:
return False
match = re.search(r"[^0-9]", ttl)
if match is not None:
return False
value = int(ttl)
if not (0 <= value < 2 ** 31):
return False
... | 267a2ead566b9dfe5a7e881995a592257b103e43 | 594,080 |
def parse_requires(requires):
"""
Return a list of requirement lines extracted from the `requires` text from
a setup.cfg *_requires section such as the "install_requires" section.
"""
requires = [c for c in requires.splitlines(False) if c]
if not requires:
return []
requires = [''.j... | 1d09d2d490a32fb3261bca30389402c1de2e07ba | 594,081 |
def _compute_durations(start, stop):
"""Get duration of event based on BVs. Add 1 because duration is inclusive"""
return (stop - start) + 1 | 22ab8397aab04657d8998d6e8b78bf5520d6ac67 | 594,082 |
import torch
def unique(inputs):
"""Return the unique elements of the input tensor."""
return torch.unique(inputs) | 472179502b893fb888f8e33c1e9f5c4432a9fda6 | 594,083 |
import mimetypes
def get_mimetype(pathname):
"""for the given file path return the mime type"""
return mimetypes.guess_type(pathname,strict=True) | a05ff6ce73e735e7e7bdc855c02bf0b91664e59c | 594,084 |
def _xpath_attrib(attrib, value):
"""Returns string ``[@attrib="value"]``.
"""
return '[@' + str(attrib) + '="' + str(value) + '"]' | 0b2e13db39bd47ec79842ece299a72ddf5c9a072 | 594,085 |
def get_parent(fullpath):
"""
Parse the string and return a path corresponding to the parent.
Assumes normalized fullpath string.
"""
parent = "/".join(fullpath.split('/')[:-1])
if parent == '': # a top-level hack
parent = '/'
return parent | 83fc466e88f85c0641d95bbcb1433c55028c1c19 | 594,086 |
def isApplicable(tweet, data, limit):
"""
Determines if a tweet should be factored into calculations about the sentiment surrounding a search term
:param tweet: Text of a tweet
:param data: An object of type SentimentData
:param limit: The number of words inside the tweet which must also be accounte... | 6799d21b0f009115bef713571269e2fb365c7bf1 | 594,088 |
import json
def prepare_data(
json_path # type: str
):
# type: (...) -> dict
"""Loads data from json-file.
Args:
json_path (str): Path to json-file from which data should be loaded
"""
with open(json_path) as file_:
data = json.load(file_)
return data | c24615b19581b22802db3379735294c0a2f04fac | 594,093 |
def pad_sents(sents, pad_token):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should be at the end of each sentence.
@param sents (list[list[str]]): list of sentences, where each sentence
is represented as a list of words
... | dcfe2a730b0b7ca44648db7a23d83f15fb790422 | 594,097 |
def output_log(msg_enum, **kwargs):
"""Output the specified message to the log file and return the message."""
return msg_enum.output_log(**kwargs) | 8a187a1ba8b65f682c675557ff16fc26dda367d4 | 594,100 |
def is_binary_file(filename):
"""Return true if a file contains binary (non-text) characters."""
text_chars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F})
try:
with open(filename, "rb") as fp:
return bool(fp.read(1024).translate(None, text_chars))
except (I... | 3abd2d92e8650f3aac3ac95700af241f39b94979 | 594,101 |
def _build_message(input_table, output_table, current_date):
"""Returns a JSON object containing the values of the input parameters.
Args:
input_table: A string containing the BQ table to read from
output_table: A string containing the BQ table to write to
current_date: The processing date to suffix th... | 19fe9697c9c1d1666adee55de491f72e7d0b6e7e | 594,111 |
from typing import Counter
def build_vocab(annotations, threshold=1):
""" Create vocabulary for text captions.
Args:
annotations: Dictionary with data, including text captions.
threshold: Threshold on word occurrences in all captions.
Returns:
word_to_idx: Vocabulary as python di... | 48063d9079befe33d9d53803ecf7a06ee61f3942 | 594,113 |
import torch
def invert_permutation(perm):
"""Return the inverse of a permutation
Parameters
----------
perm : (..., N) tensor_like
Permutations. A permutation is a shuffled set of indices.
Returns
-------
iperm : (..., N) tensor
Inverse permutation.
Examples
---... | 3f756336cc2a22a197e0e56efddebf4a10efe4c1 | 594,114 |
def issolved(cube: list) -> bool:
"""
Return True if the cube is solved, False otherwise.
A cube is a solved cube if every sticker of each side of the cube is
the same.
"""
return all(all(x == s[0][0] for y in s for x in y) for s in cube) | bb6d0e35061b54a0476adfd90e80bd5a3b878807 | 594,115 |
import math
def MakeLogTicks(xs):
"""Makes a pair of sequences for use as pyplot ticks.
xs: sequence of floats
Returns (xs, labels), where labels is a sequence of strings.
"""
lxs = [math.log10(x) for x in xs]
labels = [str(x) for x in xs]
return lxs, labels | da733b8e5d949093649f0496ed741277149a212f | 594,118 |
def pack_cache_path(root, log_param):
"""generate cache file path
Parameters
----------
root : str
cache directory
log_param : Param
Returns
-------
cache_path : str
cache fiel path of log_param
"""
str_log_param = "_".join(map(str, log_param))
cache_path = ... | 7a655819bc6c2f9ff7f8d578141a8f57e42373be | 594,122 |
from typing import Mapping
def answers_from_file(answer_file: str) -> Mapping[str, int]:
"""Loads problem answers from a file and returns them as a dictionary."""
answers = {}
with open(answer_file) as input_file:
for line in input_file:
tokens = line.rstrip().split()
prob_... | 23901137e55ee6cbb78d423d00548388c46a78a8 | 594,123 |
from textwrap import dedent
def trim(text):
"""Like textwrap.dedent, but also eliminate leading and trailing
lines if they are whitespace or empty.
This is useful for writing code as triple-quoted multi-line
strings.
"""
lines = text.split('\n')
if len(lines) > 0:
if len(lines... | 0c1bc710b6bf1e9bb7b42d990942423c8ebf7cf9 | 594,126 |
def getweakrefs(space, w_obj):
"""Return a list of all weak reference objects that point to 'obj'."""
lifeline = w_obj.getweakref()
if lifeline is None:
return space.newlist([])
else:
result = []
for i in range(len(lifeline.refs_weak)):
w_ref = lifeline.refs_weak[i]()... | 304bfbc6075a882cf78b82343df30807e9ced7dc | 594,132 |
def get2(item, key, if_none=None, strict=True):
"""
similar to dict.get functionality but None value will return then
if_none value
:param item: dictionary to search
:param key: the dictionary key
:param if_none: the value to return if None is passed in
:param strict: if False an empty ... | 9e387a2a910636a4c1db029aa6ce26c739358cbc | 594,133 |
import re
def rx(pat):
"""Helper to compile regexps with IGNORECASE option set."""
return re.compile(pat, flags=re.IGNORECASE) | 7cae6aeff40dff0242c39c0961aace7cd042a0b6 | 594,134 |
import mpmath
def mean(k, theta):
"""
Mean of the gamma distribution.
"""
k = mpmath.mpf(k)
theta = mpmath.mpf(theta)
return k * theta | 2fb3221f749eb33127759c99daeb9093674b84bc | 594,137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.