content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def anypats(pats, opts):
"""Checks if any patterns, including --include and --exclude were given.
Some commands (e.g. addremove) use this condition for deciding whether to
print absolute or relative paths.
"""
return bool(pats or opts.get(b'include') or opts.get(b'exclude')) | 5895e90ac21fa408ab8619df899dec29e3881da9 | 672,044 |
def extract_tests(api_response, defined_tests):
"""
Create and return a dict of test name to test data.
If api_response is None, return a dict with an empty dict.
api_response: the JSON response from the Proctor API in Python object form.
defined_tests: an iterable of test name strings defining th... | d81e621cd26605fe9d8469a0fab2e7983416c0b6 | 672,045 |
import math
def calc_distance(pos1, pos2):
"""
Calculate euclidean distance between two positions
"""
return round(math.sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2), 3) | 429f36effa3103db1843e38016a61eaba06c35df | 672,046 |
def get_account_id_from_arn(trail_arn):
"""Gets the account ID portion of an ARN"""
return trail_arn.split(':')[4] | d13f72357e9932459a44f76cfb28462b38a92f46 | 672,047 |
import json
def load_model_config(filename):
"""
Load model configuration from json file and return it
"""
with open(filename, 'r') as fp:
data = json.load(fp)
return data | f03473aea608fe4efdce4144e17068d8e47b973a | 672,048 |
import os
def normpath(filepath):
"""Normalize `filepath`. That is call os.path.norm path, and expand user/vars"""
return os.path.normpath(
os.path.expandvars(
os.path.expanduser(filepath)
)
) | dbf4dd191de2dbad4be2d8c6efec83dd2759f052 | 672,049 |
import warnings
def is_lili_subset(sub_lili, full_lili):
""" sub_indicator and full_indicator should pertain to
the same master pattern set. """
if len(sub_lili) != len(full_lili):
warnings.warn("Inputs should have same length")
for i, li in enumerate(sub_lili):
if len(li) > 0 and ... | beba46367a80615318e2ebb64e9367da88fdc7d6 | 672,050 |
def tensor2numpy(tensor):
"""Convert tensor to ndarray
"""
return tensor.cpu().detach().numpy() | 805c54c3915d5d685dab295cac7e0afb5673e955 | 672,051 |
import argparse
def parse_args(args):
"""Take care of all the argparse stuff.
:returns: the args
"""
parser = argparse.ArgumentParser(description='Create Co-added Chi-squared db.')
parser.add_argument('star', help='Star names')
parser.add_argument("obsnum", help="Observation number")
pars... | d36725a8313185191996998527c9e14021857d62 | 672,052 |
def _get_normalized_vm_statuses(vm_iv):
"""Iterate over a list of virtual machine statuses and normalize them.
Arguments:
vm_iv (dict): Raw virtual machine instance view record.
Returns:
dict: Normalized virtual machine statuses
"""
normalized_statuses = {}
for s in vm_iv.get(... | b8fc8a14ccda4574fbe6838716bc944196a09c2e | 672,053 |
def extension_without_gz(path):
"""Get the file extension ignoring .gz if present"""
suffixes = path.suffixes
last = len(suffixes)
if suffixes[last] == ".gz":
extension = suffixes[last - 1]
else:
extension = suffixes[last]
return extension | 211ed82b7a853dfcd42258ef8f2e7f7184f781fa | 672,054 |
import os
def validate_directory(val):
"""
Input validator function for a directory name.
"""
return os.path.exists(val) | 49440cefd435270aa330c7619acc1cd7605c198e | 672,055 |
def _dol_to_lod(dol):
"""Convert a dict of lists to a list of dicts."""
return [{key: dol[key][ii] for key in dol.keys()}
for ii in range(len(dol[list(dol.keys())[0]]))] | 1e85cdebf64bdb6910545dc2a832a268a9b69add | 672,056 |
import json
def load_names_from_metadata(fpath, expr):
"""
:param fpath:
:param expr:
:return:
"""
with open(fpath, 'r') as infile:
try:
md = json.load(infile)
assert 'md' in expr, 'Missing metdata keyword "md" in expression: {}'.format(expr)
sample_... | 75293c5375fb29609629e7a8bf4457581e5bf945 | 672,057 |
def create_mapping(dico):
"""
Create a mapping (item to ID / ID to item) from a dictionary.
Items are ordered by decreasing frequency.
"""
sorted_items = sorted(dico.items(), key=lambda x: (-x[1], x[0]))
id_to_item = {i: v[0] for i, v in enumerate(sorted_items)}
item_to_id = {v: k for k, v i... | 226b0c3bf35fdf2736ca1df90616c2ad97de9588 | 672,058 |
import torch
def add_id(df):
"""
Add the identity to a tensor with the shape of the Jacobian
Args:
df (torch.tensor): batched `(n,m,m)` tensor
Returns:
torch.tensor: :code:`df` plus a batched identity of the right shape
"""
return df + torch.eye(df.shape[1], device=df.devi... | 475e46185c95becc5680109e6cd72f04aa7030bd | 672,059 |
import argparse
def _construct_argument_parser(spec, suppress_missing=False):
"""Constructs an argparse.ArgumentParser given a ConfigSpecification.
Setting suppress_missing to True causes the parser to suppress arguments
that are not supplied by the user (as opposed to adding them with
their default ... | ffa92a733a1db511f5d3b349281d7f15790e36e4 | 672,060 |
import time
def with_retries(N):
""" Catch all exceptions and retry N times"""
def actual_decorator(f):
def wrapper(*args, **kwargs):
timeout = 1
for _ in range(0, N - 1):
try:
return f(*args, **kwargs)
except:
... | 176c6ee729a94f70962f8c62f32d3001e14f573a | 672,061 |
def rvr(rvr):
"""Function to format runway visual range"""
d = {'parsed' : 'None', 'runway' : 'None', 'value' : 'None',
'unit' : 'None', 'string' : 'N/A'}
if rvr == "None":
return d
d['parsed'] = rvr
cache_split = rvr.split("/")
d['unit'] = 'feet'
d['runway'] = f'{cach... | f8a634f63ba779fc4cd6ab1323ee9e26a1fee907 | 672,062 |
def varintToNumber(byteArray):
"""
Converts a varlen bytearray back into a normal number, starting at the most
significant varint byte, adding it to the result, and pushing the result
7 bits to the left each subsequent round.
"""
number = 0
round = 0
for byte in byteArray:
roun... | 2d99767d79e2e1f96a6f6f85a18955db8fd9f4dc | 672,063 |
def list_users(iam_conn, path_prefix):
"""List IAM users."""
users = []
marker = None
while True:
if marker:
response = iam_conn.list_users(PathPrefix=path_prefix,
Marker=marker)
else:
response = iam_conn.list_users(Pat... | 1d849e928177d13cc6c300c138dc6bed01651ab0 | 672,064 |
def wrapstr(x):
""" return 'str' if object is str"""
if isinstance(x, str):
return "'" + x + "'"
else:
return str(x) | de1044442b54e880604c5cc20e8de0f311c58183 | 672,065 |
def _get_max_size(x, y, map_info):
"""
Get the size of the biggest square matrix in the map
with first point: (x, y)
Arguments:
x -- column index
y -- line index
map_info -- a dict of the map and its information
Returns:
size -- biggest square matrix size
"""
x_max ... | 5180fdd9894ef368fba36b50939f5661418147d2 | 672,066 |
import unicodedata
def to_half_string(s: str) -> str:
"""normalize
Example:
>>> to_half_string('123XYZ')
'123XYZ'
"""
return unicodedata.normalize("NFKC", s) | 746b5e32d59afd1e761a9a216c25447d3d4fbe65 | 672,068 |
import requests
def pulsar_list(addr, auth):
"""
Return a list of the all the pulars in the database.
Args:
addr: hostname or ip address of database server.
auth: tuple of username and password.
"""
path = '{0}/{1}/'.format(addr, 'pulsar_list')
r = requests.get(url=path, ... | 61dd51ae1cb1a83753735a66695ff4f7a2653385 | 672,069 |
import sys
import re
def heading_speed_input() -> tuple:
"""
The function asks for the unit's heading and speed (online).
"""
try:
while True:
try:
heading_data = input('New course >>> ')
except KeyboardInterrupt:
print('\n\n*** Closing t... | 0843d4d2a42e8a70c1cf8ff42d487294611aa07d | 672,071 |
from pathlib import Path
def get_product_name_from_path(path):
"""
Extract S2 product name from the path.
"""
parents = list(Path(path).parents)
if len(parents) > 1:
first_dir = Path(parents[len(parents) - 2])
if first_dir.suffix == '.SAFE':
return first_dir.stem | 35c608afd98ecbf071244167855e22cae728463f | 672,072 |
import random
def mutate(a,b):
"""how a mutation on a parameter can be definied"""
return random.uniform(a,b) | a8c910bba951e8195396bf11b7398268cc188cbf | 672,075 |
def isPrime(x):
"""
Checks whether the given
number x is prime or not
"""
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3, int(x ** 0.5) + 1, 2):
if x % i == 0:
return False
return True | 5c1e3614a67263d57eed6bf6f60d5ff5572f4026 | 672,076 |
def genwhctrs(anchor):
"""Return width, height, x center, and y center for an anchor (window).
"""
base_w = anchor[2] - anchor[0] + 1 # 15 + 1
base_h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (base_w - 1)
y_ctr = anchor[1] + 0.5 * (base_h - 1)
return base_w, base_h, x_ctr, y_ctr | 99aebcabe18ccd68aefa4f404cf8028ce0f21fcf | 672,077 |
def get_email_cc(current_cc=None, additional_cc=None):
"""Get current email cc and additional cc and combines them together.
Args:
current_cc: Current email cc.
additional_cc: Additional email cc.
Returns:
str. Email's cc
"""
if current_cc:
if additional_cc:
... | b3afc4dbcf8379efeb14fbd03e3ea77666359c0b | 672,078 |
def _get_coordinator(hostname, port=9001):
""" Generates the coordinator section of a Myria deployment file """
return '[master]\n' \
'0 = {}:{}\n\n'.format(hostname, port) | dba81eac4d18219833e17aa52d8271ee19f25f6e | 672,079 |
def _fixKeywordArgs(kwargs):
"""
The new API uses real enums instead of stringly typed values.
The names of each tag matches, so the conversion is trivial.
Also handles "iocontext" and "sourcetype" although those two
are not in either interface yet.
"""
result = {}
for key, value in kwar... | 02742f3f34c3af50f568a368199714c21ca2b96c | 672,080 |
def lr_poly(base_lr, iteration, max_iterations, power):
"""
:param base_lr:
:param iteration:
:param max_iterations:
:param power:
:return:
"""
return base_lr * ((1 - float(iteration) / max_iterations) ** (power)) | 72185c8e3e9762024778f1f0a3876b6669912f09 | 672,081 |
def look_and_say(seq, times):
""" Recursively play look-and-say on the sequence """
if times == 0:
return seq
newseq = ''
currentc = ''
count = 1
for c in seq:
if c == currentc:
count += 1
else:
if currentc != '':
newseq += str(coun... | 6471c4234761da8f4727051f49b71ac5c446c2f1 | 672,082 |
import os
def auth_header() -> dict:
"""
Returns the API Key auth header based on environment variables.
"""
username = os.environ['CCHQ_USERNAME']
api_key = os.environ['CCHQ_API_KEY']
return {'Authorization': f'ApiKey {username}:{api_key}'} | 7f6a1304cd8790a26d053ed72c9d3196dc1f70a5 | 672,083 |
import argparse
def parse_arguments():
"""Parse passed arguments using argument parser.
Returns:
Object with parsed arguments.
"""
parser = argparse.ArgumentParser(description='Prepare server')
# register additional parameters for Report Portal integration
parser.add_argument('--rp_e... | 72433ed3e14491293c14c1a142e761409d65d98c | 672,084 |
def mock_client(mocker):
"""A magicmock for omnisci.connection.Client"""
return mocker.patch("omnisci.connection.Client") | 9499e18c53c491e143d821435fb0efaacbd318ce | 672,085 |
def mocked_system(mocker):
"""Mocking `plaform.system`"""
return mocker.patch("platform.system") | 3c0b52c2a8fa0a5ff84431fb0c7c067ed33a8381 | 672,087 |
def test_triangle(dim):
"""
Tests if dimensions can come from a triangle.
dim is a list of the three dimensions (integers)
"""
dim = [int(x) for x in dim]
dim.sort()
if dim[0] + dim[1] > dim[2]:
return True
else:
return False | bd36868a680c1114585baf19aa8ecf6eee33e481 | 672,088 |
def asymptotic_relation_radial(enn,numax,param):
"""
Compute the asymptotic frequency for a radial mode.
Parameters
----------
enn : int
The radial order of the mode.
numax : float
The frequency of maximum oscillation power
param : array_like
Collection of the asypm... | 8575c62b3ff5a54fa831b033d1578dfa40cf018e | 672,089 |
def from_db(db, power=False):
"""Convert decibel back to ratio.
Parameters
----------
db : array_like
Input data.
power : bool, optional
If ``power=False`` (the default), was used for conversion to dB.
"""
return 10 ** (db / (10 if power else 20)) | 6dad85046424893c04cf0935f34a8aa81e3c702d | 672,090 |
def cipher(text, shift, encrypt=True):
"""
Encrypt or Decrypt a string based on Caesar cipher.Each letter is replaced by a letter some fixed number of position down the alphabet.
Parameters
----------
text : string
A string you wish to encrypt or decrypt.
shift : integer
A in... | aad52df5a2750b04dd8e1dfb8cafef42c087277e | 672,091 |
def minimise_xyz(xyz):
"""Minimise an (x, y, z) coordinate."""
x, y, z = xyz
m = max(min(x, y), min(max(x, y), z))
return (x-m, y-m, z-m) | 78005610682605beec77a4bc2e7a84de876d7e8f | 672,092 |
def transpose(data):
"""
Utility function for transposing a 2D array of data.
"""
return zip(*data) | 5fae54f27d7eb46904a5c269c02cafc0936a3b58 | 672,093 |
def validate5(s,a):
"""validate5(s,a): convert s to set and compare to set alphabet"""
return set(s).issubset(a) | e8cedba1b1ca8eb732f5e72b29881eebf98fb130 | 672,094 |
import os
import gzip
def smart_open(filename, mode='r'):
"""
A function to open a file. If the file is compressed
(with a '.gz' extension) it is decompressed before being
opened. Otherwise, the function is opened normally.
Args:
-----
filename (str) -- the absolute pathname of the fi... | 9a8869b35effafb899cc28274641b5c4b175d477 | 672,095 |
import torch
def to(input, dtype):
"""Convert input to dtype."""
if dtype == 'long':
dtype = torch.long
elif dtype == 'uint8':
dtype = torch.uint8
elif dtype == 'float32':
dtype = torch.float32
return input.to(dtype) | a71ecbfc0b5b22af8d57813dfd81fad02fb0a065 | 672,096 |
import math
def _pitch_sync_hanning(period_pre, period, fftlen):
""" Pitch synchronous hanning window """
hlen = fftlen // 2
s = hlen - (period_pre // 2)
e = hlen + (fftlen % 2) + (period // 2)
def _hann(n, N):
return 0.5 * (1. - math.cos(2.0 * math.pi * n / (N - 1.)))
def _val(f):
... | 73478ba3970e171f6e35b31189f7a9dbab6f64ef | 672,097 |
import re
def clean_column(s):
""" utils function that clean a string to be a cleaner name of column
Parameter
---------
s : string
the string to clean
Return
------
cleaned string
"""
if s is None:
return None
r = s.strip().lower()
r = ... | dfb26fa641738729d4d4c3dc3d1d16e32f575fc3 | 672,098 |
def count_increase(list_int):
"""
This function calculates the number of times a measurement increases.
This is the answer to the first puzzle.
Parameters:
list_int (list): list of measurements(integers)
Returns:
n (int): number of times a measurement inctreases.
"""
n = 0... | 63e63a8399209aa51cb22ef94c2cbd1f22d9fefc | 672,099 |
from typing import Dict
import json
def load_data(file_path: str) -> Dict[str, list]:
""" Loads the json file in as a Python dictionary.
Parameters
----------
file_path : str
Absolute file path to the Frew model.
Returns
-------
json_data : Dict[str, list]
A Python dictio... | cb86a9ff5f5c73b7bd246497d3a33d4d4939a87c | 672,100 |
def _s3_glob(s3_filepath, my_bucket):
""" Searches a directory in an S3 bucket and returns keys matching the wildcard
Parameters
----------
s3_filepath : str
the S3 filepath (with wildcard) to be searched for matches
my_bucket : boto3 bucket object
the S3 bucket object containing th... | 69549ae41e7af13c192ddde8331433a24a1a9997 | 672,101 |
def v2_to_internal(menu):
"""Convert a v2 menu object to an internal menu object"""
if not menu['open']:
return {'open': False}
def soup_to_soup(soup):
return {
'price': soup['price'],
'name': soup['name']
}
def other_to_other(other):
return {
... | 2f262fc66a3af35494f886aa107b2e97af222ea5 | 672,102 |
import re
import random
def scramble(word):
"""For words over 3 characters, shuffle the letters in the middle"""
if len(word) > 3 and re.match(r'\w+', word):
middle = list(word[1:-1])
random.shuffle(middle)
word = word[0] + ''.join(middle) + word[-1]
return word | af0a638544a860515c1f3a062941a99b9ea2a370 | 672,103 |
def nested_parameter_dict():
"""Nested Parameter as a dictionary."""
return {
'key': 'nested',
'type': None,
'multi': None,
'display_name': None,
'optional': None,
'default': None,
'description': None,
'choices': None,
'parameters': [],
... | e0cd1b799b3ef52838e0c9fe8d81689550f2450c | 672,104 |
def parse_owner(URL):
"""
There are two common ways to specify a submolde URL, either with the git@
syntax, or the http/git syntax. Examples:
git@github.com:zfsonlinux/zfs.git
https://github.com/zfsonlinux/zfs.git
git://github.com/zfsonlinux/zfs.git
one trick is that the owner and repo have ... | 9c08ff7634fc17367fe32da3f716dcf21886f92e | 672,105 |
def max_bitrate_ext(val):
"""
Given ESM value, return extended maximum bit rate (Kbps).
Please refer to 10.5.6.5, TS24.008 for more details.
:param val: the value encoded in the ESM NAS message
"""
if val <= 74:
return 8600 + val * 100
elif val <= 186:
return 16000 + (val - ... | ee8c139ad28d836d01b43f1b24d795550844f695 | 672,106 |
import torch
def ConstantTensor(value, *size, dtype=torch.float, device='cuda:0'):
"""
Returns a Tensor containing only value
Parameters
----------
value : int or float
the value of every item in the Tensor
*size : int...
the shape of the tensor
dtype : type (optional)
... | b89484afebd0311b5c66cd3ac66d22de9a46bc29 | 672,107 |
def get_figsize(columnwidth=241.14749, wf=1.0, hf=(5. ** 0.5 - 1.0) / 2.0, b_fixed_height=False):
"""Parameters:
- wf [float]: width fraction in columnwidth units
- hf [float]: height fraction in columnwidth units.
Set by default to golden ratio.
- columnwidth [float]: width... | d0d7ed41bc14e5f4d5ec21837f8d899aa57e9c34 | 672,108 |
def isKanji(char):
""" return true if char is a kanji or false if not """
code = ord(char)
return 0x4E00 <= code <= 0x9FFF | 1c83d77b0296590dc892ef29691fde27966bcfd0 | 672,109 |
from typing import Tuple
def route_color(agency: str, traction: str) -> Tuple[str, str]:
"""Generate route_color and route_text_color given an agency and route_type"""
# Colors from mzkzg.org map
# ZTM Gdańsk
if agency == "1":
if traction in {"0", "900"}:
return "D4151D", "FFFFFF"... | fc54b64bf5db29814d272d1e1d0d65f316f4bc15 | 672,110 |
def add_spam(menu=None):
"""Print each word from a menu plus spam.
Args:
menu: The base menu.
"""
if menu is None: # kinda redundant as we require menu
menu = [] # this avoids spamming! [spam, spam, spam etc.]
menu.append('spam')
return menu | d83803c1878161da7e0d6c8e5430501fe43600a7 | 672,111 |
def is_track_in_tracks(song_uri, tracks):
"""
Checks whether song is within a list of songs
:param song_uri: ID of target song
:param tracks: Page object of track or playlist track objects
:return: Whether or a not a song is within a list of tracks
"""
for track in tracks['items']:
t... | d035c9c2515cdaa2f7fc89c12a5a754259815eec | 672,112 |
import re
import json
import collections
def LoadJSON(filename):
"""
Read `filename`, strip its comments and load as JSON.
"""
with open(filename, "r") as f:
match_cpp_comments = re.compile("//.*\n")
# The order in which structures are described in JSON matters as we use them
# as a seed. Computin... | 9e0f3375a76048ef64502908833c25bc33a8c92f | 672,113 |
import ast
def batch_metrics(log_events):
"""Batch together metrics.
Parameters:
log_events (list): A list of
log events whose 'message'
field contains metrics.
Returns:
metrics (list): A list of metrics to
be put to cloudwatch.
"""
metrics_list = []
... | d452c416cf4f4ff35dbf47dec061f7a2b9755d5c | 672,115 |
def update_speed_limit(intersection, new_speed):
"""
Updates the speed limit of the intersection
:param intersection: intersection
:param new_speed: new speed value
:type intersection: Intersection
:type new_speed: int
:return: updated intersection
"""
return intersection.update_spee... | a531ff9152611299499d347cb0639faba559d153 | 672,116 |
def hash_key(key: int, size: int) -> int:
"""
Return an integer for the given key to be used as an index to a table of
the given size.
>>> hash_key(10, 7)
3
"""
return key % size | 212d1c74aa7882695fbe3cd15ca62301386344b6 | 672,117 |
def ptc_dummy_dist(t, eps=5):
"""Calculate the distance between a track and a dummy track
By definition, this is the number of labeled points times epsilon.
See http://www.bioimageanalysis.org/track/PerformanceMeasures.pdf
Parameters
----------
t: ndarray
2D array of [X,Y,T] points of ... | 6b4dc3a5ff0a285ac4ec7af8ad087eefac65220b | 672,118 |
def isWord(s):
"""
See if a passed-in value is an identifier. If the value passed in is not a
string, False is returned. An identifier consists of alphanumerics or
underscore characters.
Examples::
isWord('a word') ->False
isWord('award') -> True
isWord(9) -> False
... | 84df75643db356fb583e4bbc20fc887779dfdb74 | 672,119 |
def flatten_tuple(t):
"""
flatten tuple output
:param t: (cen_idx, (point, 1))
:return:
"""
return tuple(list(t[1][0])+[t[0]]) | e28a9c3d3c294b4d779f1b21fd366198d42f16d8 | 672,120 |
def is_better_sol(best_f, best_K, sol_f, sol_K, minimize_K):
"""Compares a solution against the current best and returns True if the
solution is actually better accordint to minimize_K, which sets the primary
optimization target (True=number of vehicles, False=total cost)."""
if sol_f is None or so... | 15ab7dd0294226870e476731066130253ae2986a | 672,121 |
def cmpstr(str1, str2):
"""String*String->float
Renvoie le coefficient de ressemblance entre deux chaînes de caractères.
L'algorithme est LOIN d'être parfait, ceci dit. En effet, pour qu'il soit
davantage efficace, il aurait fallu calculer les distances entre les lettres
afin de déterminer de quel t... | 99598917900b1caf5bef9e7b2f29b33699387955 | 672,122 |
def lineAtPos ( s, pos ):
"""
lineAtPos: return the line of a string containing the given index.
s a string
pos an index into s
"""
# find the start of the line containing the match
if len(s) < 1:
return ""
if pos > len(s):
pos = len(s)-1
while pos > 0:
if s[pos] == '\n':
pos = pos + 1
break
... | f78b52947573ebc4cb6dfb8b88bd75a4bac7fb62 | 672,123 |
def upperColumn(r, c):
"""
>>> upperColumn(5, 4)
[(5, 4), (4, 4), (3, 4), (2, 4), (1, 4)]
>>> upperColumn(6, 4)
[(6, 4), (5, 4), (4, 4), (3, 4), (2, 4), (1, 4)]
"""
x = range(r, 0, -1)
y = [c, ] * r
return zip(x, y) | 7add4a6efdeae222dadbd2c74c7746c74ea0344d | 672,124 |
def max_and_sum(_sum, number_pair):
"""From the best sum, current sum, and a new value, generate the new best and current sum"""
best_sum, current_sum = _sum
number, _ = number_pair
current_sum = max(0, current_sum + number)
best_sum = max(best_sum, current_sum)
return best_sum, current_sum | 3db9d10a414e0658f938390bceb28b14e4e4bd23 | 672,125 |
import json
import subprocess
def goal_state():
"""Juju goal state values"""
cmd = ['goal-state', '--format=json']
return json.loads(subprocess.check_output(cmd).decode('UTF-8')) | e9854fe6f07019afce01f8aa50cd3cd84ca1d032 | 672,126 |
def extract_part_names(splitted):
"""Extract the QuaLiKiz-transport-coefficient-names from list of parts"""
if isinstance(splitted, str):
raise TypeError("Given a string, should be given a list-like object")
return splitted[slice(0, len(splitted), 2)] | 4db13acc39b944024e0b1c4fbf84a511364a28f3 | 672,127 |
def is_even_for_rounding(c, exp):
"""General-purpose tiebreak used when rounding to even.
If the significand is less than two bits,
decide evenness based on the representation of the exponent.
"""
if c.bit_length() > 1:
return c & 1 == 0
else:
return exp & 1 == 0 | b39e402e973d28e31911d14cb388a9ffed047994 | 672,128 |
import inspect
def wants_args(f):
"""Check if the function wants any arguments
"""
argspec = inspect.getfullargspec(f)
return bool(argspec.args or argspec.varargs or argspec.varkw) | bf34e92240e5580edd32cfec7f21e10b53851371 | 672,129 |
from typing import Tuple
def split_templated_class_name(class_name: str) -> Tuple:
"""
Example:
"OctreePointCloud<PointT, LeafContainerT, BranchContainerT>::Ptr"
("OctreePointCloud", (PointT, LeafContainerT, BranchContainerT), "::Ptr")
"""
template_types = tuple()
pos = class_name.... | a2f0ee818a1985ee943cc975928be4e18470882b | 672,130 |
def check_fields_present(passport, validity_checks):
"""Check that all of the required fields are present as keys in the input dictionary"""
return validity_checks.keys() <= passport.keys() | ef1782c0cc15b520b2d80ac1a1c2211d66452dfb | 672,131 |
import re
def clean_phone_number(text):
"""
strip non-numeric characters and add '%2B' at the front
"""
non_decimal = re.compile(r'[^\d.]+')
plus = '+'
cleaned_text = "%s%s" % (plus, non_decimal.sub('', text))
return cleaned_text | fd41341e1e0fe5a48e49aac7c42dc856855583a2 | 672,132 |
import logging
import os
def get_envvars(
env_file=".env", set_environ=True, ignore_not_found_error=False, exclude_override=()
):
"""
Set env vars from a file
:param env_file:
:param set_environ:
:param ignore_not_found_error: ignore not found error
:param exclude_override: if parameter fo... | f8d18c7f88540597a9c5c2fbf2ce0310a4d8109f | 672,133 |
def validate_type(data_dict: dict, type_name: str) -> dict:
"""Ensure that dict has field 'type' with given value."""
data_dict_copy = data_dict.copy()
if 'type' in data_dict_copy:
if data_dict_copy['type'] != type_name:
raise Exception(
"Object type must be {}, but was i... | cbb492d3ed27beba5e24f78c5f526585d7b47585 | 672,134 |
import glob
import os
import tempfile
import shutil
import subprocess
def glob_file_to_blob(glob_filename, name):
"""Copy a file, zip it, and return the zip-file as a binary blob."""
glob_filenames = glob.glob(glob_filename)
if len(glob_filenames) != 1:
raise RuntimeError("Expected to find 1 filen... | e9ef9624845c38490b410767d1e9ee30ef35e82f | 672,135 |
def power_set(array: list)-> list:
"""DP, explore the DAG
"""
res = []
def dp(sub, current=[]):
if not sub: res.append(current); return
dp(sub[1:], current + [sub[0]]) # we take it
dp(sub[1:], current) # or we dont...
dp(array)
return res | 06f0b442bdee2d96a0b49b4ef920721fc51048b4 | 672,136 |
def board_voters_on_proposal(proposal):
""" potential board voters """
if proposal.decided_at_meeting:
board_attn = proposal.decided_at_meeting.participations.board()
else:
c = proposal.issue.community
board_attn = c.memberships.board().filter(
user__in=c.upcomin... | 249dd4a3af3cedc54e1d09bada1813594875b556 | 672,137 |
from typing import List
from typing import Any
def all_same(list: List[Any]) -> bool:
"""Decide whether or not a list's values are all the same"""
return len(set(list)) == 1 | 1a3f22c2b2d1a5b114712bcf39e9ef50a3e10555 | 672,138 |
def build_elem_balls(gr):
""" Build balls of elements around each node
"""
if gr._node2elems is not None:
del gr._node2elems
# build array for point->element lookup
# Use set for later convenience
gr._node2elems = [set() for _ in range(len(gr.hgrid.mesh.nodes))]
for elem_i in range(... | 6967b11b1d440c7dbf213afd208e9da7d608d41c | 672,139 |
import torch
def linear_2_oklab(x):
"""Converts pytorch tensor 'x' from Linear to OkLAB colorspace, described here:
https://bottosson.github.io/posts/oklab/
Inputs:
x -- pytorch tensor of size B x 3 x H x W, assumed to be in linear
srgb colorspace, scaled between 0. and 1.
Re... | f732e2b268c8bd1ffae92197b100cfd265033baa | 672,140 |
def point_in_polygon(S, q):
"""determine if a point is within a polygon
The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu>
(see URL below) with some minor modifications for integer. It returns
true for strictly interior points, false for strictly exterior, and ub
for points on the boun... | 81f73ded677991552927914ef478b0ce308c2d35 | 672,141 |
import requests
def get_networks(base_uri, headers):
"""
Get networks
"""
network_url = base_uri + '/api/NetworkConfigurationService/Networks'
network_response = requests.get(network_url, headers=headers, verify=False)
if network_response.status_code == 200 or network_response.status_code == 2... | 4e3df61dc7d14e2af314176c9808b933e4d41112 | 672,143 |
def query(question, default_answer="", help=""):
"""Ask user a question
:param question: question text to user
:param default_answer: any default answering text string
:param help: help text string
:return: stripped answer string
"""
prompt_txt = "{question} [{default_answer}] ".format(que... | ecfc894091cc3a77d07712ee3d74fcc46ae8a9df | 672,145 |
def path_to_major_minor(node_block_devices, ndt, device_path):
""" Return device major minor for a given device path """
return node_block_devices.get(ndt.normalized_device_path(device_path)) | a229ad002912678cfe7f54c484218069f2fbc6ae | 672,146 |
def except_text(value):
"""
Creates messages that will appear if the task number is entered incorrectly
:param value: 'список', 'задача', 'цифра'. Depends on what messages are needed
:return: 2 messages that will appear if the task number is entered incorrectly
"""
if value == 'список':
... | 8394ca2f2cb5b513069877d29d070adf79709ac3 | 672,147 |
from typing import Dict
import random
def generate_sentence_from_grammar_tree(gram_tree: Dict, target: str) -> str:
"""
根据自定义的语法模板进行过句子生成
:param gram_tree: 自定义语法模板
:param target: 目标句式结构,如simple_sentence
:return: 根据随机模板生成的句子
"""
if target not in gram_tree:
return target
expanded... | d13809c5d5064c7b0b83b33045cf83f243d0a18b | 672,148 |
import re
def normalize_ja(s, segmenter):
""" Processes a Japanese string by removing non-word characters and separating tokens with spaces.
"""
s = s.strip()
s = re.sub(r"[^\w.!?。]+", r" ", s, flags=re.UNICODE)
s = " ".join(segmenter.tokenize(sentence=s, is_feature=False, is_surface=True).convert... | 0b43649d7f22ed13fc3eafb6899ab90cbfb463ee | 672,150 |
def get_the_number_of_params(model, is_trainable=False):
"""get the number of the model"""
if is_trainable:
return sum(p.numel() for p in model.parameters() if p.requires_grad)
return sum(p.numel() for p in model.parameters()) | 78c321dfd6c10af73bd4cccdc7a11e91e4a92603 | 672,151 |
import time
import random
def site_id(prefix: str)->str:
"""
处理指定前缀/获取时间戳
:param prefix:
:return:
"""
_id = str(int(time.time()*1000))+str(int(random.random()*100000))
return prefix+_id if prefix is not None else _id | 57a6feb092bd7a8b6c028aa7ddff4f31ea26e8d3 | 672,152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.