content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def read_certificate_file(certificate_file: Path) -> str:
"""Read the contents of the local X.509 certificate file and returns the string
:param certificate_file: X.509 client certificate to read
:type certificate_file: Path
:return: PEM encoded certificate
:rtype: str
... | 1b014b03880cca14e830f1a6dba0a9529b64b239 | 611,305 |
import math
def alpha_inflate(theta, decl):
"""Compute the ra expansion for a given theta at a given declination
Keyword arguments:
theta, decl are both in decimal degrees.
Return value:
alpha -- RA inflation in decimal degrees
For a derivation, see MSR TR 2006 52, Section 2.1
h... | 2b4791f98f5a7d70e0b5da2ee81a4422611fb595 | 611,312 |
def get_package_json_dict(project: str, score_class: str) -> dict:
"""Returns the template of package.json
:param project: SCORE's name.
:param score_class: SCORE's main class name.
:return: package.json's contents.(dict)
"""
package_json_dict = {
"version": "0.0.1",
"main_modu... | 35f88a2f5783cd19bcab8cbb60a8fb107d6dd349 | 611,317 |
def env_str_multi() -> tuple[str, ...]:
"""Specify environment variables within multiple strings for testing."""
return tuple(
(
f"AWS_ACCESS_KEY_ID_EXAMPLE=AKIAIOSMULTI{i}EXAMPLE\n"
f"AWS_SECRET_ACCESS_KEY_EXAMPLE=wJalrXUtnFEMI/K7MDENG/bPMULTI{i}EXAMPLE\n"
f"CSV_VARI... | 8528920fcb135cc99a928392a50e0738cee303d2 | 611,320 |
def convert_RH_vpa(rh, tmin, tmax):
"""
calculate vapour pressure from rh tmin/tmax assumes tmean is tmin+tmax/2
as per https://www.weather.gov/media/epz/wxcalc/vaporPressure.pdf
:param rh: relative humidity (%, 0-100)
:param tmin: min temperature (degrees c)
:param tmax: max temperature (degre... | c8fc1589d926f527478b65a5eee8bbda3d39aa6e | 611,322 |
def reduce_singular(values):
"""Returns the value in an array of length 1, or
the tuple of an array with a longer lengh.
Parameters
----------
values: array-like
Array to squash
Returns
-------
values: tuple or single value
"""
if len(values) == 1:
return values... | e67742359e86a37cfc3c80bc6ce549901bd73341 | 611,323 |
def pack_float64(float_num):
"""
Package 'std_msgs/Float64' message.
"""
# Place Float into dict
data = float_num
float_msg = {"data": data}
return float_msg | 9a39206caefa89b7a1cab67837ddd0e4ace26137 | 611,324 |
def is_first_letter(val):
"""Check if string starts from a letter"""
return ord(val[0].lower()) in range(ord('a'), ord('z') + 1) | a50e3ba5e9da7aa4286878bd5737499210601cb8 | 611,326 |
def get_cluster_key(obj):
"""Get the cluster key for a given k8s object"""
try:
namespace = obj["metadata"]["namespace"]
name = obj["metadata"]["labels"]["gateway.dask.org/cluster"]
return f"{namespace}.{name}"
except KeyError:
return None | a5e52804c964cdb7b4ec0130ab805a428328c552 | 611,328 |
def GetSubnetMode(network):
"""Returns the subnet mode of the input network."""
if network.get('IPv4Range') is not None:
return 'LEGACY'
elif network.get('autoCreateSubnetworks'):
return 'AUTO'
else:
return 'CUSTOM' | 42e7c60de613e60104742c506ce48da11ff4b63e | 611,329 |
def compose(f, g):
"""
:param f: Second function to apply
:param g: First function to apply
:return: A composition of functions
"""
return lambda *args, **kwargs: f(g(*args, **kwargs)) | 46c3adb1f48a00e8dff9927fa8a61cf0d02f3057 | 611,330 |
import ast
def ast_equivalent(ast1, ast2):
"""Returns whether ast1 and ast2 are structurally equal ASTs.
Two ASTs are considered equivalent if:
1) they are the same type and all their submembers are also equivalent, or
2) they are both expression contexts.
Expression contexts are ignored for equivalen... | b1a50723a4926fb765282367d534fc171776f70b | 611,335 |
import six
def to_unicode(value):
"""
Return the input value as a unicode string.
The input value may be and will result in:
* None -> None
* binary string -> decoded using UTF-8 to unicode string
* unicode string -> unchanged
* list or tuple with items of any of the above -> list with co... | 2b924a7d187c81d76929110b085988ffb175715e | 611,337 |
def touchforms_error_is_config_error(touchforms_error):
"""
Returns True if the given TouchformsError is the result of a
form configuration error.
"""
error_type = touchforms_error.response_data.get('error_type', '')
return any([s in error_type for s in (
'XPathTypeMismatchException',
... | 359fc7bfa195c5adadeec3d230408a892827b8a8 | 611,338 |
import re
def is_alphanumeric(input_string, exact_length=0):
"""Return True if input is a valid alphanumeric, False otherwise
Keyword arguments:
input_string -- string value to check
exact_length -- strict string length check, if 0, it's omitted (default 0)
"""
if exact_length > 0 and len(inp... | 81a2f86449d2eaf75580bf15999f22233f2199fc | 611,339 |
def merge_field_into(s1, key, value):
"""Create a new namedtuple that is a copy of s1 with the key,value replaced."""
dd = {}
for k in s1._fields:
dd[k] = getattr(s1, k)
dd[key] = value
return s1.__class__(**dd) | b77a3e583cd888b3a7a9e2ded9690fd56e693b0f | 611,340 |
def _wpad(l, windowsize, stepsize):
"""
Parameters
l - The length of the input array
windowsize - the size of each window of samples
stepsize - the number of samples to move the window each step
Returns
The length the input array should be so that no samples are leftover
... | 950d4873326d2196d1190dc23b2d9d0cf71bd9b6 | 611,343 |
import logging
def forward_stream_to(source, destination):
"""
Forwards all lines from the source to
the destination.
Arguments
---------
source: Source stream
destination: Destination stream
Returns
-------
None
"""
while True:
try:
li... | b331ce6dee3b79f75cc226c91706f99a098b392a | 611,347 |
def BuildEvals(options, parser):
"""Construct a dict of passed '-e' arguments for evaluating."""
evals = {}
for expression in options.eval:
try:
evals.update(dict([expression.split('=', 1)]))
except ValueError:
parser.error('-e requires VAR=VAL')
return evals | bbe527710e4cfe3f16c1a816cd0367ed9db64487 | 611,352 |
def get_available_username(user_profile):
"""
Determines the username based on information available from slack.
First information is used in the following order:
1) display_name, 2) real_name
:param user_profile: Slack user_profile dict
:return: human-readable username
"""
display_nam... | af75aa4928cf2362abbf6d8cfe1bf4290f0fde35 | 611,354 |
import re
def glob_to_regex(glob):
"""Converts a glob to a compiled regex object.
The regex is anchored at the beginning and end of the string.
Args:
glob (str)
Returns:
re.RegexObject
"""
res = ""
for c in glob:
if c == "*":
res = res + ".*"
... | fdb850f99f65195a02460a9ba348c1ba3f665f46 | 611,356 |
def dup_neg(f, K):
"""Negate a polynomial in `K[x]`. """
return [ -coeff for coeff in f ] | c70cd995e198186ce24b82c533edecf1dd451c39 | 611,359 |
def get_bitslice(obj, topidx, bottomidx):
"""Returns the bits within obj[bottomidx:topidx+1] (Or in architecture format
obj[topidx:bottomidx])
"""
obj = obj >> bottomidx
# Generate a bitmask to get topidx - bottomidx number bits
mask = 1
for bit in range(topidx - bottomidx):
mask = ... | 025a61e50065322d11d6cb5c01a34c692cffabda | 611,363 |
def get_modified_columns(fields, fields_to_replace):
"""
This method updates the columns by adding prefix to each column if the column is being replaced and
joins it with other columns.
:param fields: list of fields of a particular table
:param fields_to_replace: dictionary of fields of a table wh... | 9ea2dba0df0cd7fdceeab759d04238b021974c28 | 611,365 |
def is_wall(x, y, modifier=0):
"""
You can determine whether a given x,y coordinate will be a wall or an open space
using a simple system:
* Find x*x + 3*x + 2*x*y + y + y*y.
* Add the office designer's favorite number (your puzzle input).
* Find the binary representation of that su... | 02f8701fbb8eb8d7360d98ef31bc55aace0f9637 | 611,368 |
def _rev_auth_str(client_api_key, user_api_key):
"""Returns a Rev Auth string."""
return 'Rev %s:%s' % (client_api_key, user_api_key) | 6a19cadf58eaffe7090d24424cbebfeefa3fd16b | 611,369 |
import json
def load_transition_types(transitions_uri):
"""Loads a transition .json file and returns a dictionary mapping
transition ids to their types.
transitions_uri - path to a .json file with the format
{
"modify_landscape_structure": "restoration", ... }
... | 776f5dd548ac0bb7f4447a24623751f8faca7baf | 611,370 |
def distributions_list(distributions, categories): ####### Make a class #########
"""
Map the categories to the fraction of the dataset for each worker subset.
Parameters
----------
distributions: list of lists
The list of the distributions for each categories for each worker.
categori... | 4155c6a0d08bb49743e231941cd295090d52cd92 | 611,372 |
def snake_to_pascal(string: str) -> str:
"""
Converts snake-case to pascal-case.
>>> snake_to_pascal(string="hello_and_good_morning") # Returns "HelloAndGoodMorning"
"""
words = string.split('_')
words_capitalized = list(map(str.capitalize, words))
return "".join(words_capitalized) | 9f5262978ea1c087bcaa90ead3e330fde6f0e2b1 | 611,373 |
from math import prod as mathprod # type: ignore # Python 3.8
from typing import Sequence
from functools import reduce
import operator
def prod(iterable: Sequence[int]) -> int:
"""Implementation of `math.prod()` all Python versions."""
try:
return mathprod(iterable)
except ImportError:
r... | bc9efe015e188a6b34c2982eb3a1fe51708a5f9d | 611,382 |
def same_sentence_check(block: str, pos1: str, pos2: str) -> bool:
"""Check if two words are in the same sentence by looking for sentence delimiters between their starting positions.
:param block: Block of string text the two words are found in
:param pos1: The index of the beginning of word1
:param po... | 0ae912e926204947895d1611f8291ff6c001ecfe | 611,383 |
def correct_time_of_shot(shot, goal_times):
"""
Corrects time of shot (a goal was scored on) by comparing its original time
with a list of actual times of goals scored in the game and finding the
goal incident with the minimum time difference. Optionally correcting the
time of the shot when a non-ze... | 12df0974ff10753b34c831ca20889fda17c2e2f4 | 611,385 |
def getIndexOne(x):
"""Get the Item at index position one.
"""
return x[1] | 2d32465e0746192c3053bf03f6ba8c5ebc812538 | 611,387 |
def getSupportedMedia(media):
"""Returns the supported file types for the specific media as a string"""
if media == "video":
return ".m4v|.3g2|.3gp|.nsv|.tp|.ts|.ty|.strm|.pls|.rm|.rmvb|.mpd|.m3u|.m3u8|.ifo|.mov|.qt|.divx|.xvid|.bivx|.vob|.nrg|.img|.iso|.pva|.wmv|.asf|.asx|.ogm|.m2v|.avi|.bin|.dat|.mpg|... | 2cbe65c987ec56a603244d902bc70e190c352739 | 611,388 |
def first_matching_item(iterable, predicate):
"""
Gets the first item in an iterable that matches a predicate (or None if nothing matches)
Returns:
Matching item or None
"""
return next(filter(predicate, iterable), None) | 9a7f9102b1d54cb98ed8610a8aff4374e1df8f74 | 611,395 |
from typing import List
def bin2dec(x: List[int]) -> int:
"""Converts a binary vector to an integer, with the 0-th
element being the most significant digit.
Args:
x: (list) a binary vector
Returns:
An integer
"""
dec = 0
coeff = 1
for i in range(len(x)):
dec ... | c986c65d0e5e96fb188b602be195e4f3bddf44ee | 611,401 |
def basenumberconverter(dec, base, numbers):
"""
Convert decimal number to number of given base
Parameters:
dec (int) : Decimal to convert
base (int) : Base of the number to convert into
numbers (str): Numbers of the given base
Returns:
str: The converted number in given base
"""
... | 44277abbf19ec894b4f0aceb2369cbc33e15acb2 | 611,403 |
import re
def _ibis_sqlite_regex_extract(string, pattern, index):
"""Extract match of regular expression `pattern` from `string` at `index`.
Parameters
----------
string : str
pattern : str
index : int
Returns
-------
result : str or None
"""
if string is None or pattern ... | 9258ea3a73e51ca71f660c0eac9b0f2c3f418d35 | 611,409 |
def day_of_year(datetimes):
"""Return the day of the year of given dates."""
return (datetimes.astype('datetime64[D]', copy=False) -
datetimes.astype('datetime64[Y]', copy=False)).astype(int) | 9b6d8f517408c26bf2318cfd9d5731962ae25eff | 611,410 |
import re
def text_to_dict(text):
"""Converts a series of key=value lines in a string into a multi-value dict.
"""
parsed = {}
regexp = r'([A-Za-z\-\_]+)\=(.+)\w*$'
for match in filter(None, (re.match(regexp, i) for i in text.splitlines())):
parsed.setdefault(match.group(1), []).append(match.group(2))
... | 431f66872d998f46ac7e78719cf3276f9c90001d | 611,412 |
def compile_rule(rule):
"""
Compiles a rule in string format. Basically checks that is valid python format.
:param rule:
:return:
"""
if len(rule) == 0:
return None
try:
c_rule = compile(rule, "<string>", "exec")
return c_rule
except:
return None | c4e18bb48402379f38913f2a7c45fdd05653097f | 611,413 |
def accuracy(Y_pred, Y_test):
"""
Calculates the accuracy of the model
Arguments:
Y_pred (np.array): shape [n_test_examples,] an array of model predictions
Y_test (np.array): shape [n_test_labels,] an array of test labels to
evaluate the predictions against
Return... | 03a0a7cedf7388574a3dd8b3d8b197a0312d8e26 | 611,414 |
def split_tensor_tuple(ttuple, start, end, reduce_dim=False):
""" Slice each tensor in the input tuple by channel-dim.
Since the SSL algorithms always split labeled and unlabeled samples in each batch,
this function is implemented here as a common tool.
Arguments:
ttuple (tuple): tuple of a to... | 3bc639572c0639aceb08eb3aebf0d3af5b2b33ea | 611,418 |
def to_text(source):
""" Generates a text value (an instance of text_type) from an arbitrary
source.
* False and None are converted to empty strings
* text is passed through
* bytes are decoded as UTF-8
* rest is textified via the current version's relevant data model method
"""
if sour... | b471e03eebd4a3e9c41742d555123e5958b95013 | 611,419 |
import math
def extrapolate_lines(lines, img_shape, min_slope=0.3):
"""Aggregate detectes lines into two lanes by extrapolation
Args:
lines (list<list<tuple>>): detected lines
img_shape (tuple<int>): image shape
min_slope (float, optional): minimum slope to consider the edge as being ... | 23577346e432e2bafad3cb0fd3d90427aec1561b | 611,421 |
def human_size(bytes):
"""Return number of bytes as string with most appropriate unit."""
if bytes == 0:
return '0 B'
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'YB']
bytes = float(bytes)
i = 0
while bytes >= 1024 and i < (len(suffixes) - 1):
bytes /= 1024.0
i += 1
... | 887122f25136f77242e82994e3fa2f3ade25e31f | 611,422 |
import hashlib
def hash_from_code(msg):
"""Return the SHA256 hash of a string or bytes."""
# hashlib.sha256() requires an object that supports buffer interface,
# but Python 3 (unicode) strings don't.
if isinstance(msg, str):
msg = msg.encode()
# Python 3 does not like module names that st... | 1174e86f8a92f27557ed39e0e81817ffa7f1edf0 | 611,424 |
def getbitvalue(binstr, pos):
""" get value of the bit at position 'pos' in binary string 'binstr' """
return (binstr >> pos) & 1 | c0dca0b790a7ed8f72cbe762c0ba5c39679748e5 | 611,426 |
def get_task_and_ann_id(ex):
"""
single string for task_id and annotation repeat idx
"""
return "%s_%s" % (ex["task_id"], str(ex["repeat_idx"])) | ea77eeafa5f924eea946130bec0f3383f60dc434 | 611,435 |
def getRCC(radius, height, position, surfaceNum, comment):
"""Create a right circular cylinder in the z direction."""
surfaceCard = "{} RCC {} {} {} 0 0 {} {} {}".format(surfaceNum, position[0], position[1], round(position[2], 5),
round(height, 5), round(r... | 2299f3396db166fca605ed4501443583b1dd48d3 | 611,440 |
def zelite_nadaljevati(niz):
"""
Uporabnika vpraša, če želi nadaljevati. Vrne True oz False.
"""
print('=============================')
print(niz)
print('1.) DA')
print('2.) NE')
while True:
try:
izbira = int(input('> '))
if izbira == 1:
r... | 7358dee451664023cf0e5c8e0d8457dce37a00dd | 611,454 |
from pathlib import Path
def class_ns_as_path(name: str) -> Path:
"""Split a namespace into a multi-directory level directory
Args:
name (str): The namespace
Returns:
Path: The path to the directory
"""
return Path(name.replace(".", "/")) | c458a3b1fc4b75aa6e1020a15fec8a3291767e45 | 611,455 |
def combine_limits(*limits):
"""
Combines given data sets limits to single limits.
Args:
limits: (((float, float), ), )
Data sets limits.
Returns:
((float, float), ) or None
Combined limits or None if no limits.
"""
limits = [lim for lim in ... | 9e65f211d97e1b6502b6357bf2ddc297a73c60a3 | 611,456 |
def n_layers(request):
"""Number of layers."""
return request.param | e567ba7172f572b838c5cbda067e69163c229f5c | 611,460 |
def get_subsequences_matching_query(hit_obj):
"""Takes a SearchIO hit object, and returns a list with the first element
being a string representing the coordinates of the query to which the
subject sequence aligns, and the second being the corresponding subject
subsequence(s).
"""
# ***Eventuall... | f2382cb92d7b95289b2f4fc35bb08f25a5b830e0 | 611,463 |
def text2vector(filename):
"""convert list delimited by newlines in a text file into a vector"""
content = []
with open(filename) as f:
for line in f:
content.append(line.strip())
return (content) | a76bdd109b5bc91cce5a05feca3cbcdd49a64b14 | 611,466 |
def all_prefixes(li):
"""
Returns all prefixes of a list.
Args:
li: list from which to compute all prefixes
Returns:
list of all prefixes
"""
return [tuple(li[:i + 1]) for i in range(len(li))] | 7698d1d8039374ea38e785f01d53a74f05d1ad77 | 611,469 |
import struct
def address_to_bytes(address: int) -> bytes:
"""Convert an address to bytes, in little endian."""
return struct.pack('<L', address) | 42139771a291450f8393f6ce290dc4bd9b7d8a80 | 611,471 |
def fit_into(value, min_, max_):
""" Return value bounded by min_ and max_.
"""
return max(min_, min(max_, value)) | 1e752c200a148a6d36c019b05c9e192c60c6b013 | 611,474 |
def tick(frameNum, pts, beak, birds):
""" Update function for animation """
birds.tick(frameNum, pts, beak)
return pts, beak | e22fcad89d00ed042d94a3c6cb709395ab7bc21f | 611,476 |
import copy
def _set_defaults_temporal(config_in):
"""Return modified config when no temporal args are provided.
If 'median' is true use "--all" otherwise set "--latest=1"
"""
config = copy.deepcopy(config_in)
temporal_args = ('dayofyear', 'month', 'day',
'year', 'latest', '... | df6333419d5fc44643bc31c61ca047a489d73805 | 611,477 |
def getUrl(host, port):
""" return url for host and port """
return f"http://{host}:{port}" | 64a783753cf0a599c0adbffa5f386243836eaeb3 | 611,479 |
def _is_type_hint(obj):
""" Check if object is stored along with its type in the typical format:
[str, str] => [typehint, value] e.g. ['$complex', (3 + 4j)]
"""
return isinstance(obj, list) \
and len(obj) == 2 \
and isinstance(obj[0], str) \
and obj[0][0] == '$' | 49efbf211ce465a925525c99f4d2b02e69373992 | 611,483 |
def file_lines(file_path) -> int:
""" Calculate number of lines in file. """
with open(file_path) as f:
i = 0
for i, l in enumerate(f, start=1):
pass
return i | b90f2786a1332863de33bb4f2fd11344497da3c3 | 611,485 |
import re
def strip_multi_whitespace(str_json):
"""
strip multi white space like " " to a single " "
:param str_json: string
:return: string
"""
str_json = re.sub(' +', ' ', str_json) # kills multi whitespace
return str_json | 70724d17953adbae4c507cb4bc54a00714ead019 | 611,486 |
def smallest_distance(vertexes, dist):
"""Returns the smallest distance in dist where key is in vertexes."""
smallest_k = vertexes[0]
smallest_d = dist[smallest_k]
for v in vertexes:
if dist[v] < smallest_d:
smallest_d = dist[v]
smallest_k = v
return smallest_k | d2401225f70344ce91e33977f86511b5ac1d2d1c | 611,488 |
def sharedLangCost(criterion, frRow, exRow):
"""Returns 1 if the two do not share a language, else 0"""
fluentQ = criterion['fluentQ']
learningQ = criterion['learningQ']
frLangs = [set(frRow[fluentQ].split(',')),
set(frRow[learningQ].split(','))]
exLangs = [set(exRow[fluentQ].split('... | 11d6f6db627f93ecc726407eee29a3e46cea6cc0 | 611,489 |
def get_feat_names_from_base_feats(feat_names: list, base_feat_names: list):
"""Generate feature names in feat_names that stem from features in base_feats
"""
feats = set()
for base_feat_name in base_feat_names:
for feat_name in feat_names:
if base_feat_name in feat_name:
... | 9ab52b2e7c2eba50a2eb6dc56e554f5820852f7b | 611,493 |
def _compare_baseline_results(baseline, results):
"""Compare a baseline list of issues to list of results
This function compares a baseline set of issues to a current set of issues
to find results that weren't present in the baseline.
:param baseline: Baseline list of issues
:param results: Curren... | 31bf636a2305fd986deda834b640dafc51e74a71 | 611,496 |
def snake2camal(string: str) -> str:
"""
Change string from snake_case to CamalCase
:param string: (str) string to convert
:rtype (str): converted string
"""
return ''.join(word.title() for word in string.split('_')) | 50d386b1bc9246c880f1f2a2ac29c1620c435d58 | 611,500 |
def interpret_map(m):
"""Interpret a map-like object.
Accepts anything that dict() accepts for its first argument.
Returns a list of pairs (key, value).
"""
try:
d = dict(m)
except Exception:
raise ValueError("not a map")
return d.items() | 7ccd8416febe9d108c5c3db80adedf1d3c8317b6 | 611,507 |
from typing import Iterable
from typing import Union
from typing import Tuple
from typing import List
def _process_sorts(sorts: Iterable[Union[str, Tuple[str, bool]]]) -> List[str]:
"""Process a top-level query's sort_by attribute into a list.
This mostly handles the sorting direction tuples.
:param sor... | ac67ffc2f4f75b89e9175348d6c2153a169df225 | 611,508 |
def round_to_base (value, base=1):
"""
This method expects an integer or float value, and will round it to any
given integer base. For example:
1.5, 2 -> 2
3.5, 2 -> 4
4.5, 2 -> 4
11.5, 20 -> 20
23.5, 20 -> 20
34.5, 20 -> 40
The default base is '1'.
"""
r... | c34bfb7e73624ce7f8652aed146218f0b6a86489 | 611,509 |
def _check_technology_advancements_for_partition(ta):
"""Checks the technology advancment input to :py:func:`partition_demand_by_sector`
and :py:func:`partition_flexibility_by_sector`.
:param str ta: The input technology advancement that will be checked. Can be any of:
*'Slow'*, *'Moderate'*, or *'... | 0888285098fdf3467c5e91346a0a874416506bc1 | 611,517 |
import copy
def MergeCallingServiceAccountWithOwnerPermissionsIntoBindings(env, properties):
"""
A helper function that merges the acting service account of the project
creator as an owner of the project being created
"""
service_account = ('serviceAccount:{0}@cloudservices.gserviceaccount.com'.format(env['pr... | 20ec2fd5b86c1be70d7d9bd9709b5ddfe0075bfa | 611,522 |
def epochTime(startTime: int, endTime: int):
"""Calculate elapsed (elapsedMins, elapsedSecs) of epoch"""
elapsedTime = endTime - startTime
elapsedMins = int(elapsedTime / 60)
elapsedSecs = int(elapsedTime - (elapsedMins * 60))
return elapsedMins, elapsedSecs | 728fd74c84efef0f436fbbcbde2bb4e3da669729 | 611,527 |
def get_clc(goods):
"""Return a list of the unique control list entries for all goods in the supplied list.
A single good may be passed instead of a list of one item.
"""
if not isinstance(goods, list):
goods = [goods]
clcs = {clc["rating"] for good in goods for clc in good.get("good", {})... | 8f824c6a19193870cef79da2a7d0cb9cd43a64cc | 611,530 |
def get_ref_path(openapi_major_version):
"""Return the path for references based on the openapi version
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3.
"""
ref_paths = {2: 'definitions',
3: 'components/schemas'}
... | f0e29f0e02cb38f503bad0e14b2516b5a2d2ac9f | 611,531 |
def dissect_reference(refs: list, from_class: str, from_id: str,
from_prop: str) -> list:
"""
Dissect a reference list into the parametes required for a batch request.
Parameters
----------
refs : list
A list of references to be dissected.
from_class : str
... | 719c67e2cf19a014951575bfe4570272106adbbb | 611,532 |
def default_flist_reader(flist):
"""
flist format: impath label\nimpath label\n ...(same to caffe's filelist)
"""
imlist = []
with open(flist, 'r') as rf:
for line in rf.readlines():
impath, imlabel = line.strip().split()
imlist.append( (impath, int(imlabel)) )
r... | ab36bb79207c0fce7e8c221a0c2f84f194854acc | 611,533 |
def is_profile_flag(flag):
""" return true if provided profile flag is valid """
return flag in ('cpu', 'mem', 'block', 'trace') | 27931fe812840ffa935595d145b80c8073de0c70 | 611,537 |
def get_number_of_published_papers(data):
"""
This function will return number of ids that have associated published papers
:param data:
:return: dict with yes and no as keys and number of documents for each category
"""
paper_published_data = {
'yes': 0,
'no': 0
}
for it... | 6b4a375e985de04a4689488452d6c24541204f1b | 611,538 |
def rgbu8_size(width, height):
"""Calculate rgb 24bit image size
Args:
width: image width
height: image height
Returns:
rgb 24bit image data size
"""
return int(width * height * 3) | 904a7a3d704183580e323758c2dbba80c3880e5d | 611,539 |
from typing import List
from typing import Callable
def abstract_calc_sim(query: List[str],
content: List[List[str]],
func_vec: Callable[[List[str], List[str]], float]) -> List[float]:
"""
Calculate the sim_scores for every query compared to each element of content
... | 85b58c82ec2babe7c1e1f2f199212ec792290ad8 | 611,542 |
def removeDuplicates(a_list: list) -> list:
"""
Removes duplicates from a list and returns it.
Type needs to implement __eq__
"""
return list(dict.fromkeys(a_list)) | d4099bad061ea8a08051dbd15ee07cd0efcdb056 | 611,543 |
def whole_inference(imgs, model):
"""Inference with full image."""
preds = model(imgs)
return preds | 19c7667d527c0ae346bd418c7ad238a76bbfd945 | 611,544 |
def snakecase(string: str) -> str:
"""
Turns any string into a snakecase string
"""
return string.lower().replace(' ', '_') | 07478b7173bea802e9c2bde1cfaabb881875c7d3 | 611,547 |
def required_keys_avaiable(readme_dict):
"""
Check if the required key in the readme dictionary are available
Required key are the ones I need for further processing.
These are:
* base_runs
* username
* email
* info_block
* sub_date
* solver
Parameters
---------... | b54b50ac26e1a5c5135ceafabe96234ac5ff31ec | 611,548 |
import inspect
def class_(obj):
"""Return a class from an object
Often in itk, the __class__ is not what the user is expecting.
class_() should do a better job
"""
if inspect.isclass(obj):
# obj is already a class !
return obj
else:
return obj.__class__ | 60f03fb880bc54e8084d01d4eb9eaa11f615b4cb | 611,549 |
def _select_long_short_ports(df, portvar, top_minus_bot=True):
"""
Finds the appropriate portfolio number and returns (long number, short number)
"""
#Get numbered value of highest and lowest portfolio
top = max(df[portvar])
bot = min(df[portvar])
if top_minus_bot:
return top, bot
... | bbd338d697afadfaea7c3a8743363a302757fc1d | 611,555 |
def structure_list(text):
"""Returns a list of punctuation and the location of the word 'Python' in a text"""
punctuation_marks = "!?.,:;"
punctuation = []
for mark in punctuation_marks:
if mark in text:
punctuation.append(mark)
return punctuation, text.find('Python') | ce5060b8fc058eefbf38b6f7889b50a8afce0790 | 611,556 |
from typing import Tuple
def prepare_chunk(playbook, chunk: str) -> Tuple[str, str, str]:
"""Parse a chunk of ansible-playbook output.
Given an ansible-playbook output chunk, like:
TASK [staging : Install sudo] ********************************************
ok: [staging1.eeple.net]
return a tree-... | aa567c0007d9caeb658550a0cab237ea92e4b0e1 | 611,563 |
import io
import json
def load_json_file(json_file):
"""
Load json file
:param json_file: json file path
:return: file content
"""
with io.open(json_file, encoding='utf-8') as f:
json_content = json.load(f)
return json_content | d5eafad4fa5d636e31240a3503699f490cbea5fc | 611,565 |
def is_noun(tag):
"""True if tag corresponds to treebank noun tags"""
return tag in ['NN', 'NNS', 'NNP', 'NNPS'] | b436fbddaa60349cb1e6bff49cf47f47ee932209 | 611,566 |
def get_first_non_none_parsed_value(parsed_values):
"""
Gets the first non-`None` parsed value.
Parameters
----------
parsed_values : `None`, `list` of `Any`
The parsed value.
Returns
-------
value : `None`, `Any`
The parsed value if any.
"""
if (parsed_valu... | 3ff84e3d16914829636d0cd671445c10b981f332 | 611,567 |
def is_not_nullprice(data):
"""
used by the filter to filter out the null entries
:param data: input data
:return: true if it's not null, false if null
"""
return data and data["MinimumPrice"] != None | 3c52fa29994a5d0f0ef01657fb17e60a4b831ab9 | 611,568 |
def has_lt_10_percent_na(series):
"""Auxiliary function that checks whether less than 10% of a series's
values are missing
:param series: The series to check
:type series: pandas.Series
:return: Whether less than 10% of the series's values are missing
:rtype: bool
"""
return series.isna... | 88bdcfff1ee346501fcf395bfc337682fbe7180e | 611,569 |
def get_first_value(num_list: list):
"""Find the first value in iterable."""
return num_list[0] | 7aac21b4fbb3f2c83ebbeb753ab72fd6ab1fb514 | 611,571 |
def get_patch_ids(butler):
"""
Get the patch ids from the SkyMap object.
Parameters
----------
butler: lsst.daf.persistence.Butler
Data butler for the desired data repo.
Returns
-------
dict: A dictionary of patch IDs, keyed by tract ID.
"""
skymap = butler.get('deepCoa... | 252abe775783498f2e34003de5c2277e892bed1c | 611,572 |
def GroupConsecutiveCodepoints(codepoint_list):
"""Takes sorted codepoint list and groups by consecutive code points."""
result = []
prev = None
current = []
for codepoint in codepoint_list:
if prev is not None and codepoint != prev + 1:
result.append(current)
current = []
current.append(... | f63dd93f9226c9996dd338279b472949c25ec2c6 | 611,576 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.