content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def center_to_x1y1x2y2(bbox, width, height):
"""Convert:
(x_center, y_center, width, height)
to
(x_min, y_min, x_max, y_max)
"""
xc = float(bbox[0])
yc = float(bbox[1])
w = float(bbox[2])
h = float(bbox[3])
xmin = int((xc - 0.5*w) * width)
ymin = int((yc - 0.5*h) * height)
... | 2025137ea91a030389be81e0dee5c730fb317fcb | 568,340 |
import hashlib
def compute_hash(text: str) -> str:
"""
:param text: to hash
:return: hash digest
"""
md5 = hashlib.md5()
md5.update(text.encode())
return md5.hexdigest() | 0270b578e6aa606369cb3309c5089d17fe37341e | 568,341 |
import math
def normalize_angle(angle):
"""
Convert an angle to an angle belonging to the range -pi..pi
:param angle: angle value in radians
:return: angle value in radians
"""
angle %= (2 * math.pi)
angle = angle - 2 * math.pi if angle > math.pi else angle
return angle | 7f1474d7f1ae03884739e5da3e265874933d1ad4 | 568,342 |
from tabulate import tabulate
def tableize(df, tablefmt="pretty", is_print=True):
"""
Converts dataframe to a formatted table
For more details, see https://pypi.org/project/tabulate/
:param df: dataframe to save
:type df: df object
:param tablefmt: format of table
:type tablefmt: string
... | 0de3a10e6a6f6a73d9503796d3c68f5105208ad6 | 568,345 |
def generate_neighbours(image):
"""
Generate all neighbours of all pixels in the image
:param image:
:return:
"""
neighbour_dict = dict()
for x in range(image.shape[0]):
for y in range(image.shape[1]):
neighbour_dict[str((x,y))] = list(filter(lambda pos: 0 <= pos[0] < ima... | e484a62624f0775ac90beac344bda48303f3a486 | 568,347 |
def _get_type_name(value):
"""return a string describing the type of value"""
try:
return value.__class__.__name__
except AttributeError:
pass
return repr(type(value)) | 72f424a0f14bd2ddf72262e672a344feddbf81e5 | 568,348 |
def AISC_J24(PlateThck):
"""
From AISC WSD Table J2.4
Minimum Size of Fillet Welds
"""
#
# To 1/4 inclusive
if PlateThck < 6.35:
# Minimum zise 1/8
_MinWeldSize = 3.20
# Over 3/4
elif PlateThck > 19.0:
# Minimum zise 5/16
_MinWeldSize = 8.0
el... | bb9aeb1cda3697599ad129b51d15372cdbebdb5a | 568,350 |
def find_endpoint(dc_type, dc_id):
"""Find a docker cloud endpoint by its name or UUID."""
units = dc_type.list(name=dc_id) # make threaded?
units += dc_type.list(uuid=dc_id)
assert len(units) == 1, "%d objects found, expected 1" % (len(units),)
return units[0] | 988ebb7255fd7d5503a9e5d87007574725070b58 | 568,351 |
from pathlib import Path
def fixture_dir(*dirnames):
"""
Get the path to some fixtures.
Args:
*dirnames (str): Any number of path elements within /fixtures/
Returns:
Path object
"""
base = Path(__file__).resolve().parent
return base.joinpath('fixtures', *dirnames) | 9ce63248a4aef347d35cbb2b8acf54632ae5e9d9 | 568,355 |
def polygon_under_graph(xlist, ylist):
"""Construct the vertex list which defines the polygon filling the space
under
the (xlist, ylist) line graph. Assumes the xs are in ascending order."""
return [(xlist[0], 0.), *zip(xlist, ylist), (xlist[-1], 0.)] | 005080f3549db8db60b571bae8c981c4f52c71db | 568,365 |
def remove_whitespace_chars(s_var):
"""
Removes whitespace characters
@ In, s, string, to remove characters from
@ Out, s, string, removed whitespace string
"""
s_var = s_var.replace(" ", "")
s_var = s_var.replace("\t", "")
s_var = s_var.replace("\n", "")
#if this were python3 this would work:
... | 8c4ef63d59609245923c25852b3ab3bed0a9f939 | 568,367 |
def loadCNFFormula( name ):
"""Load a CNF formula in the DIMACS ascii format from
the file "name" and return it as a list of clauses
Returns (V,F)
V -- highest variable number
F -- list of clauses"""
V = 0
L = []
f = open( name, "r" )
lines = f.readlines()
for l in lines:
s = l.... | 393024bec94858ba6e7fa2a70a4aab5a0ef9f3d7 | 568,368 |
def step_id(value):
"""Return the test id from the test step object.
:param value: The parameterized value from which the id will be generated
:returns: A formatted id for the test
"""
return f"{value.comment} {value.user_input}" | 7107886881eaa9d03a51be098ded2eee1a519be9 | 568,375 |
from typing import Dict
from typing import Any
from typing import Optional
def get_key_if_has_val(mapping: Dict[str, Any], key: str) -> Optional[str]:
"""Gets the key from mapping if it exists and has a value (non empty string)
The assumption here is that the value of the key is str. If it's not str
then... | 966b03322bf5c0026419168d23836b2c8df9150b | 568,378 |
def time_series(items, keys):
"""Convert an array of objects into a compact time series representation
Converts objects of the form
[{"date": d1, k1: v1-1, k2: v2-1}, {"date": d2, k1: v1-2, k2-2: v2}, {"date": dn, k1: v1-n, k2: v2-n}]
To arrays of the form
[[d1, v1-1, v2-1], [d2, v1-2, v2-2], ... [... | d6ec0ab406ee7bed537693d87649d61e249c5cf6 | 568,379 |
from typing import Iterable
from typing import List
def get_services_in_permissions(permissions_set: Iterable[str]) -> List[str]:
"""
Given a set of permissions, return a sorted set of services
Args:
permissions_set
Returns:
services_set
"""
services_set = set()
for permi... | 2b3d271dd7ea7335144d35ab6afd465b93203b85 | 568,381 |
from datetime import datetime
def epoch_time(tstamp):
"""Convert IRIG timestamp into nanoseconds since 1970-01-01T00:00:00Z"""
t = datetime.strptime(tstamp, '%Y/%m/%d %H:%M:%S.%f').timestamp()
return int(t * 1_000_000_000) | ecbebc93bcf37117f4fee09e73121c1d16b8a4bd | 568,382 |
def format_tags(time, tag_key, frequency, resource_type):
"""
Format the tags for ec2 and rds
Args:
time: integer representing hour in utc
tag_key: tag key on-hours or off-hours
frequency: day from M, T, W, H, F, S, U. Can be range M-F
resource_type: ec2 or rds
"""
if... | b6515bd8ab57b93a904c8edc00bf3833981015a8 | 568,384 |
def p_filter(items):
""" split items to p, n, l, d.
for example: (1, a=1, *args, **kwargs)
p: [1] (positional)
n: [a=1] (named)
l: args (positional, by list)
d: kwargs (named, by dict)
"""
p,n,l,d = [],[],None,None
for t in items:
if t.type == 'symbol' an... | 7f9b826e9ad34e687be549513eda23f58dd2870d | 568,385 |
def filter_cands_min_bio_pfams(cands, min_pfams, verbose=1):
"""
Filter candidates by minimum number of biosynthetic pfams
:param cands: Candidate DataFrame to filter
:param min_pfams: Minimum number of biosynthetic pfams
:param verbose: Verbosity
:return: candidates filtered by minimum number o... | f1e61978ae0eba0ff914640c1768a9ba8a1ce2c9 | 568,386 |
from functools import reduce
def deepgetattr(obj, attr, default=None, raise_if_missing=False):
"""Recurses through an attribute chain to get the ultimate value."""
if isinstance(attr, str):
attr = attr.split('.')
try:
return reduce(getattr, attr, obj)
except AttributeError:
if ... | d7d6080277af6f9b00b7717f41135c838a3b7af9 | 568,390 |
def cnf_get_var(literal):
"""
given a literal LITERAL, return the variable it represents
"""
return abs(literal) | 772cfaa8a3ff80edf4e7f6a59227dd4b61eea629 | 568,393 |
import click
import functools
def add_pagination_options(func):
"""Add pagination related options to click commands."""
@click.option(
"--page",
default=1,
type=int,
help="Results page number (to be used with --size).",
)
@click.option(
"--size", type=int, help... | b3cb0304152665a1d1b7d103999e6fd48f82f555 | 568,394 |
import torch
def collate_batch(features):
"""
Take a list of samples from a Dataset and collate them into a batch.
Adapted from transformers DefaultDataCollator but keeps str in the batch
Returns:
A dictionary of tensors
"""
# In this method we'll make the assumption that all `feature... | 1e579fdc019f1dff6896fb4c35b397dd8a1bc302 | 568,396 |
def calculate_lc_substring_length(string1, string2):
"""
Calculate the number of maximum consecutive symbols shared between two
input strings.
Parameters
----------
string1 : str
string to calculate distance from
string2 : str
string to calculate distance to
Return valu... | d98a369e53b22e8ace251f2f4d99aa90df380871 | 568,397 |
import re
def limit(pageurl):
"""Finds the current '?start=' limit from the page"""
b = re.findall('Τέλος.*start=([0-9]+)', pageurl)
slimit = int(b[0])
# print(type(slimit))
return slimit | 3fcaa343aed8e48820db79e14bd1bc9fcf75f2f7 | 568,399 |
import torch
def repeat_arange(counts, dtype=torch.int32):
"""
Repeat each element of arange multiple times
E.g.: repeat_arange([2,1,3]) = [0, 0, 1, 2, 2, 2]
:param counts: a 1D tensor having the same length of 'tensor'
:return: equivalent to torch.cat([torch.tensor([v]).expand(n) for v, n in enu... | 5d24839c70bfc179ef8ce0fe3b567332672a03f3 | 568,402 |
def task_get_all(client, filters=None, marker=None, limit=None,
sort_key='created_at', sort_dir='desc', admin_as_user=False):
"""Get all tasks that match zero or more filters.
:param filters: dict of filter keys and values.
:param marker: task id after which to start page
:param limit:... | 683f3230f150e6b6436451ed8d0e4c9cb970b2ba | 568,404 |
import html
def render_tag(tag, *, close=False, **attrs):
"""Renders a html/svg tag.
>>> render_tag("circle", cx=0, cy=0, r=10)
'<circle cx="0" cy="0" r="10">'
When `close=True`, the tag is closed with "/>".
>>> render_tag("circle", cx=0, cy=0, r=10, close=True)
'<circle cx=... | 0f841045c6a35240721f62d0ec6d34996c881083 | 568,406 |
def ConvertNativeLibs(args):
"""Converts the --native_libs command line argument to an arch -> libs map."""
native_libs = {}
if args is not None:
for native_lib in args:
abi, path = native_lib.split(":")
if abi not in native_libs:
native_libs[abi] = set()
native_libs[abi].add(path)
... | 447ab9c0436216329be6082e764879a68d9d26eb | 568,408 |
def get_fname(url) -> str:
"""
Transforms a URL to a file name.
"""
trash = (('http://', ''),
('https://', ''),
('/', '-'),
(':', '-'),
('%', ''))
for key, value in trash:
url = url.replace(key, value)
return url[0:100] | aff8c5cb3ad41874684cea349d20020212dfd694 | 568,415 |
def prettify_html(element, depth=0):
"""
Turn an HTML element into a nicely formatted string. It is based on
`django.test.html.Element.__str__` method and add indentation.
"""
indent = ' ' * depth
if isinstance(element, str):
return '%s%s' % (indent, element)
output = '%s<%s' % (ind... | 086bd242c66c10f666db88602177f362b61d72af | 568,421 |
def Pa2atm(x):
"""Pa -> atm"""
return x/101325. | c981194bb80d61865726b210aab2d343b07bb49c | 568,426 |
from typing import Dict
from typing import Any
def obj_to_box(obj: Dict[str, Any]):
"""Extract the bounding box of a given object as a list"""
return [obj["x"], obj["y"], obj["w"], obj["h"]] | 68a51e292c0936252bd3e5032eb5c0e704c56710 | 568,427 |
def children_by_tag(xml, tag):
"""Find all matches, at depth 1.
Note that tag may be a tag, or it may be "tag,name". This is ugly
but useful.
"""
name = None
if ',' in tag:
name = ','.join(tag.split(',')[1:])
tag = tag.split(',')[0]
matches = xml.findall(tag)
if name i... | 4e103ff8a46986408042ea0ace77df2670e9d56d | 568,434 |
def active_graph_node(conn, graph_node_pkey, forward):
""" Returns true if an edge in the specified direction exists. """
cur = conn.cursor()
if forward:
cur.execute(
"""
SELECT count(*) FROM graph_edge WHERE src_graph_node_pkey = ? LIMIT 1
""", (graph_node_pkey, )
)... | b19414876484022739a2f6ba46ac61bd06199bc0 | 568,435 |
def LeftShift(v, t=1):
"""Left shitfs (rotates) a vector of bits t times."""
return v[t:] + v[:t] | 70cc552aa3cf61d6d866b74da0b1108a2e281a0c | 568,444 |
def get_percent_identity(a_aln_seq, b_aln_seq):
"""Get the percent identity between two alignment strings"""
if len(a_aln_seq) != len(b_aln_seq):
raise ValueError('Sequence lengths not equal - was an alignment run?')
count = 0
gaps = 0
for n in range(0, len(a_aln_seq)):
if a_aln_se... | 22cbdd3114e78ad2489d4dafecb9c91f1fd857e3 | 568,446 |
def getUnigram(words):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny']
Output: a list of unigram
"""
assert type(words) == list
return words | d405f1d5c5ec8eb38e1c007d26848610aba4b2e3 | 568,448 |
def getCorrectRegionName(region: str):
"""
Sanitize and validate region name variable.
:param region: a string with a name of distribution region
:return: string
"""
region = region.lower()
valid_regions = ["zapad", "sever", "stred", "vychod", "morava"]
if region in valid_regions:
... | 17bfdf45d1066501319eda42ab68e4d525c3b96d | 568,449 |
def tensor_decode_id(img_id_enc):
"""Inverse function of tensor_encode_id"""
ints = img_id_enc.tolist()
img_id = ''.join([hex(part)[2:].zfill(8) for part in ints])
for ind in [8, 13, 18, 23]:
img_id = img_id[:ind] + '-' + img_id[ind:]
return img_id | 0b28d84165cf6c97602a0371b05f244974e944fa | 568,450 |
def transform(data):
"""Prepare the data for plotting
Parameters
----------
data : list
A list of tuples. First element is the title of the question and the
second one is a dictionary which maps the possible answer to the number
of times the answer was given.
[("Question... | 95569a1a7c3b02e0cb96c590297bcd77d3898c95 | 568,451 |
def guarded_find(substring, excerpt, pos=0, endpos=None):
"""Searches for a substring in an excerpt.
:Parameters:
- `substring`: substring that should be looked for
- `excerpt`: excerpt of text that should be searched
- `pos`: starting position of the search
- `endpos`: ending position ... | e6e93a34c546d7dcca046c4e54669712f8037b41 | 568,452 |
import math
def cart2sph(vect):
"""Converts cartesian coords to spherical"""
theta = math.atan2(math.sqrt(vect[0]**2 + vect[1]**2), vect[2])
phi = math.atan2(vect[1], vect[0])
return [theta, phi] | e582a0b47b80a4f07798cf4f92511ba171ef2a20 | 568,454 |
from typing import Union
from typing import Dict
from typing import List
import json
def parse_json(file: str) -> Union[Dict, List]:
"""Parses .json file into corresponding dictionary.
Args:
file: - Path to .json file.
Returns:
Dictionary parsed from .json file.
"""
with open(fi... | d5c77d56e10c3ca5a175abfaa9899d73a123a4d2 | 568,460 |
def find_relative_positions(asteroid_list):
"""
Takes list of asteroid positions.
Finds the relative position of every other asteroid to each asteroid,
and returns a dictionary with keys of asteroid positions and values of a tuple the
relative position of each other asteroid, and its manhattan ... | 5bc4e46e551c3b402cc2519e8709766c9be1ad23 | 568,461 |
import math
def Vcell_Calc(E0, i, i_0, i_n, i_L, R_M, A, B):
"""
Calculate cell voltage.
:param E0: fuel Cell reversible no loss voltage [V]
:type E0 : float
:param i : cell operating current [A]
:type i : float
:param i_0: exchange current at which the overvoltage begins to move from ze... | 34f641fc8d448e10b786831969f4d3c4a8a6de1f | 568,464 |
def setSourcesCategories(df):
"""
Return the DataFrame df with a renamed columns.
The renaming axes set the source's name to its category, i.e
Road traffic → Vehicular
VEH → Vehicular
Secondary bio → Secondary_bio
BB → Bio_burning
Biomass burning → Bio_burning
... | 42e762c2376fe408d11ba7483b80d1cad11acdde | 568,466 |
def fix_doc(func, decorator):
"""Fix a decorated function with docs about its decorator
:param func: Decorated function.
:param decorator: The decorator that decorated func.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Modify func.__doc__ to describe the decorator.
... | a758420694d463052169eef9d0b062a02b966cf9 | 568,471 |
def always_report_collisions(geom1, geom2):
"""
Mocked collision function which always reports that any two geometries have collided.
:param geom1: The first geometry to check
:param geom2: The second geometry to check
:return: True
"""
return True | e9eac7993175e2614c05c486069d316ba34dbad9 | 568,472 |
def difference(list1, list2):
"""Returns difference between two lists. Order matters."""
return [x for x in list1 if x not in list2] | 3121f060e16dc6d45eccf55394ec41728b60bd5f | 568,475 |
from bs4 import BeautifulSoup
from typing import Counter
def get_places(file, num=10):
"""Extract most frequent places from xml files by tag
Args:
file (string): path to .xml file
num (int): number of places returned
Returns:
places_list (list): list of most common places
... | 1af2b792d037bf74df990c76e1f5367411b09838 | 568,476 |
def metric_slug(value):
"""Given a redis key value for a metric, returns only the slug.
Applying this filter to the keys for each metric will have the following
results:
* Converts ``m:foo:s:<yyyy-mm-dd-hh-MM-SS>`` to ``foo``
* Converts ``m:foo:i:<yyyy-mm-dd-hh-MM>`` to ``foo``
* Converts ``m:f... | 69f790c9ec07c3c05bfd76eb29e6709999041b6c | 568,477 |
import math
def euclidean(pt1, pt2):
"""
This function calculates the euclidean distance between two points.
Parameters
----------
pt1 : tuple or list
The coordinates of the first point. Eg. (41.58, -74.35)
pt2 : tuple or list
The coordinates of the... | e93cb453e880d19b5a1f26d2c99a025ea7ddd6a3 | 568,479 |
def key2str(target):
"""
In ``symfit`` there are many dicts with symbol: value pairs.
These can not be used immediately as \*\*kwargs, even though this would make
a lot of sense from the context.
This function wraps such dict to make them usable as \*\*kwargs immediately.
:param target: `Mappin... | 51b2ee4429002062c41da29a23d685228522139f | 568,481 |
def scatter(iterable, n):
"""
Evenly scatters an interable by `n` blocks.
Sourced from:
http://stackoverflow.com/questions/2130016/splitting-a-list-of-arbitrary-size-into-only-roughly-n-equal-parts
:param iterable:
An iterable or preferably a 1D list or array.
:param n:
An inte... | c546a68e1e31926d5a26f1caef7080a0183a5663 | 568,482 |
import posixpath
def url_join(*url_parts):
"""Joins URLs together using the POSIX join method.
Args:
url_parts: Sections of a URL to be joined.
Returns:
Joined URL.
"""
return posixpath.join(*url_parts) | 5570bcb978b97670667f0571e5a7f67caab754e5 | 568,485 |
def value_for_keypath(dict, keypath):
"""
Returns the value of a keypath in a dictionary
if the keypath exists or None if the keypath
does not exist.
"""
if len(keypath) == 0:
return dict
keys = keypath.split('.')
value = dict
for key in keys:
if key in value:
... | b612ee65a9d9d8a674564568c3353ee3c71b04e9 | 568,486 |
def _format_list_actions(*args, **kwargs):
"""Create footer text for nodes with extra list actions
Args:
actions (str): Available actions. The first letter of the action name will be assumed
to be a shortcut.
Kwargs:
prefix (str): Default prefix to use.
Returns:
stri... | ab1a44e1528e5f1710f361e08bac3fa702e217cc | 568,490 |
def changeThreeStar(G, A, i):
"""
Change statistic for three-star
o
/
*--o
\
o
"""
return ( G.degree(i) * (G.degree(i) - 1) * (G.degree(i) - 2) / 6.0
if G.degree(i) > 2 else 0 ) | 128c3470b0e1c46a2e696090cdf7272aa9af7cdb | 568,491 |
def event_to_topic_name(slack_event_type, app):
"""Name the SQuaRE Events Kafka topic for a given Slack event type.
Parameters
----------
slack_event_type : `str`
The name of the Slack event. This should be an item from
`KNOWN_SLACK_EVENTS`.
app : `aiohttp.web.Application` or `dict`... | 7418ea26a6f0b49f3a08150f8069fbcdd8a52bd6 | 568,492 |
import random
def choix_probable_liste(objets, poids):
"""Retourne aléatoirement un choix en fonction de certaines probabilités.
On attend :
objets -- la liste d'objets
poids -- la liste des poids correspondants.
La probabilité indiquée est un poids en terme d'effectif,
pas n... | 12f236b9564d30dfbeeb0ac296133eeb64f73a37 | 568,493 |
def read_script(script_path: str) -> str:
"""Read in IMSDB script as a string
Parameters
----------
script_path : str
Path to the script
"""
with open(script_path, 'r') as f:
file = f.read().splitlines()
all_lines = []
for line in file:
line = " ".join(line... | a540cc0d7ff2fc1c2e9ba5f823080500139b8164 | 568,495 |
def create_headers(session_token):
"""Create headers to use with POST/PUT/GET/DELTE."""
return {"content-type": "application/json", "zt-session": session_token} | cf6d9b23a25858f1b09c6db9b5739079e0d93123 | 568,497 |
def load_environment(env_path):
"""
Loads database credentials (and other environs) from .env
"""
environs = {}
with open(env_path) as env:
for line in env:
if line.startswith('#'):
continue
key, value = line.strip().split('=', 1)
# os.envi... | a02cda63b1aeb914af1322d464991b94fa9aa2f0 | 568,498 |
import mimetypes
def get_extension(mime_type: str) -> str:
"""From a ``mime_type`` return a corresponding file extension, or empty."""
extensions = sorted(mimetypes.guess_all_extensions(
mime_type, strict=False))
return extensions[0] if extensions else '' | 351c8bafcd2ba7f2428445750344d1463e989a1e | 568,503 |
def cv_bbox_to_rectangle(cv_bbox):
"""
Convert the OpenCV bounding box points to a CVAT rectangle points.
:param tuple cv_bbox: Form (x1, y1, width, height)
:return: Form (x1,y1,x2,y2)
"""
return (cv_bbox[0], cv_bbox[1], cv_bbox[0] + cv_bbox[2], cv_bbox[1] + cv_bbox[3]) | e599a9e74bc2bf8d9acb15f1dcf004eaf47bf391 | 568,510 |
import hashlib
def get_md5_hexdigest(email):
"""
Returns an md5 hash for a given email.
The length is 30 so that it fits into Django's ``User.username`` field.
"""
return hashlib.md5(email).hexdigest()[0:30] | 8b301b1863049164c718a6d946709cbf100edc26 | 568,513 |
import math
def float_rgb(mag, cmin, cmax):
"""
Return a tuple of floats between 0 and 1 for the red, green and
blue amplitudes.
"""
try:
x = float(mag - cmin) / (cmax - cmin)
except ZeroDivisionError:
x = 0.5
blue = min((max(4 * (0.75 - x), 0.0), 1.0))
red = min((max((... | c4445ed5e3878ac6361120d332b8150b78761a63 | 568,515 |
def open_file(filename: str):
""" Simple function to open a file """
text = open(filename, 'r')
return text.read() | 35cf180e9259a1fafb6c27511cdd7b0670f892e5 | 568,516 |
def get_file_perm(client, fname):
"""Return file permissions of a given file/dir in as int"""
(exit_code, output, error) = client.execute_command(
f"stat --format '%a' {fname}", quiet=True)
# Make sure we do not test non existent directories
if not "cannot statx" in error:
return int(out... | f97fb582f2cdbfd786605c6de21c107889848449 | 568,519 |
def multiple_returns(sentence):
"""Returns the length of a string and its first character."""
if sentence == "":
return (0, None)
return (len(sentence), sentence[0]) | 9b9e01b64dc881cfdafc95b34326e8414a805d8e | 568,522 |
def list2regex(sclist):
"""
Called by loanpy.adrc.Adrc.reconstruct. \
Turns a list of phonemes into a regular expression.
:param sclist: a list of phonemes
:type sclist: list of str
:returns: The phonemes from the input list separated by a pipe. "-" is \
removed and replaced with a question mark a... | 4d79200dd254a06565366acf695eccc86fde835c | 568,523 |
def get_relative_df(df, ref_col, skip_cols=[], remove_cols=[]):
"""
Compute relative values based on a reference column.
Input
df: pd.DataFrame, input dataframe values.
ref_col: str, reference column.
skip_cols: list, columns to skip.
remove_cols: list, columns to remove fro... | 325de1d98c18b80fdf93297fdead85a0e44f7e3c | 568,525 |
def _build_path(identifiers):
"""
Generate the Python code needed to extract the identified node.
"""
if len(identifiers) == 0:
return ""
else:
return identifiers[0] + "".join("[{}]".format(repr(i)) for i in identifiers[1:]) | 31aaf48dd88ba46b71103d16a098826e85b010a4 | 568,528 |
def make_valid_filename(name):
""" Converts given name to a valid filename. """
return name.replace('/', '_') | 2467b2913bd71b3ff075277143b9237866cb5569 | 568,531 |
def itoa(num, base=10):
""" Convert a decimal number to its equivalent in another base.
This is essentially the inverse of int(num, base).
"""
negative = num < 0
if negative:
num = -num
digits = []
while num > 0:
num, last_digit = divmod(num, base)
digits.append('0123456789... | 297bc917d689c7ca7065d9e53d62efeb84208cf8 | 568,533 |
from typing import Iterable
from typing import List
def truth_filter(itr: Iterable) -> List:
"""
creates a new list containing all elements of this iterable that are true
(i.e. do not evaluate to False in an if statement, like None, 0 and False)
:param itr: some iterable
:return: a list containing... | 31a50fa7019422a220349ceae5965d463bd290fb | 568,534 |
from typing import List
def read_orgmode_file(filename: str) -> List[str]:
"""
Reads in an org-mode file and returns a list of strings, each containing a note.
"""
notes = [] # type: List[str]
lines = [] # type: List[str]
try:
with open(filename, 'r', encoding='utf-8') as inputf:
... | d1e55bd06458bbf805dd1965ca2e339ff00f86a8 | 568,535 |
def clean_url(url, root=True, protocol='http'):
"""
Remove trailing/leading slashes from a url
params
root
if the url starts at the domain level
protocol
ignored if root=False
what protocol should be added to the start of a url
"""
out = '/'.join(f... | ae63da3cc79c098f608f99e8d5303b11182c4dfe | 568,536 |
def get_class_labels(metadata):
"""
image_ids.txt has the structure
<path>,<integer_class_label>
path/to/image1.jpg,0
path/to/image2.jpg,1
path/to/image3.jpg,1
...
"""
class_labels = {}
with open(metadata.class_labels) as f:
for line in f.readlines():
image_i... | 5b786369afdd492482fc1d162420ff9e41f7c59b | 568,537 |
import random
def des_sky_brightness(bands=''):
"""
Sample from the distribution of single epoch sky brightness for DES
"""
# Figure 4 in https://arxiv.org/pdf/1801.03181.pdf
dist = {'g': {'VALUES': [21.016, 21.057, 21.106, 21.179, 21.228, 21.269, 21.326,
21.367, 21.4... | 0b5c1b4a084d640d441b7911dc68462d66a5cd1e | 568,539 |
import random
def random_string(length):
"""Return a random string of the given length with each character
from the printable ASCII range.
"""
result = ""
for _ in range(length):
result += chr(random.randint(33, 126))
return result | 6a25719c39abbfa2a6e85de49e55f1dc6ae2fe33 | 568,540 |
def linear_interp(x, coords, at, dim='model_level_number', keep_attrs=True):
"""
Perform simple linear interpolation to get values at specified
points.
Arguments:
- x: Data set to interpolate.
- coords: Coordinate value for each point in x.
- at: Points at which to inte... | 9a34ffc5808c488faa66fde08fb226e5cc600687 | 568,544 |
import torch
def compress_weights(W, l):
"""Compress the weight matrix W of an inner product (fully connected) layer
using truncated SVD.
Parameters:
W: N x M weights matrix
l: number of singular values to retain
Returns:
Ul, L: matrices such that W \approx Ul*L
"""
# numpy doesn'... | 94b43e1bd4eff1a4e90eb13653de28c0fdfb72a9 | 568,547 |
import json
def load_json(filename):
"""Read a json file from disk"""
with open(filename) as f:
obj = json.load(f)
return obj | 8edd0cf9c81a8c2297dc0199f2b83b83ec5d986f | 568,548 |
def batch(reader, batch_size, drop_last=False):
"""
This operator creates a batched reader which combines the data from the
input reader to batched data.
Args:
reader(generator): the data reader to read from.
batch_size(int): size of each mini-batch.
drop_last(bool, optional): I... | 9e8d5f0fedc1f12a558f476f2c7c89b2e0e5e9ee | 568,550 |
def count_increases(measurements: list[int]) -> int:
"""
Counts the number of times a measurement increases from the previous measurement.
"""
return sum(1 for a, b in zip(measurements[:-1], measurements[1:]) if a < b) | 52b2337bb85e6126b1804e7a38bd2b6ab63ba7f0 | 568,551 |
def _record_row_parser(buf):
"""
Parses the given `buf` as str representation of 'row' into `column`
and `value`.
Additionally, strips leading and trailing whitespace characters.
`buf` should be formatted in::
'<column> : <value>'
Example::
'name : "br1"'
... | 2d6315dd8bddfcc230b60f93c7265bcff413af8b | 568,555 |
def get_base_host_names(hosts_info):
"""
This function returns the base host names. These hosts are the original hosts of the application.
Elascale scales hosts and with same base name that will be concatenated with '.' and the timestamp.
So, if a host name does not contain '.', it means that host is th... | 9e87d4ca869a15fc9d859b259592a06710ba017e | 568,560 |
def image_type_cast(image_list, pixeltype=None):
"""
Cast a list of images to the highest pixeltype present in the list
or all to a specified type
"""
pixtypes = []
for img in image_list:
pixtypes.append(img.pixeltype)
if pixeltype is None:
pixeltype = 'unsigned char'
... | 760e21b68c9040bacdb22370e642fb7307706a56 | 568,567 |
def longest_string(strings):
"""
Method returns the longest string from a list of strings
:param strings: a list of string objects
:return: the longest string from a `strings`
"""
return max(strings, key=len) | c3ac5f5bf44a82b47d6424446a4be7e213de5b49 | 568,573 |
def _censor_password(connection_string):
"""
example connection string:
postgres://user:password@host.com:5439/dev
returns:
postgres://user:*****@host.com:5439/dev
"""
if (not connection_string) or ("@" not in connection_string):
return connection_string
split1 = connect... | 837ef04f1daf3c28aa84255695d69a2305812c53 | 568,574 |
def fully_qualified_stack_name(org: str, project: str, stack: str) -> str:
"""
Returns a stack name formatted with the greatest possible specificity:
org/project/stack or user/project/stack
Using this format avoids ambiguity in stack identity guards creating or selecting the wrong stack.
Note that... | a6f3571722cc62b4d8e0fa9b56d49f8b8ec36c56 | 568,575 |
from typing import Any
from typing import List
def get_methods(obj: Any, access: str = "all") -> List[str]:
"""
Return list of names corresponding to class methods of an object `obj`.
:param obj: class or class object
:param access: allows to select private, public or all methods of
the objec... | 97d65597333034b63555432bed657f9cff4254b6 | 568,576 |
import inspect
def interact_sky(tpf, notebook_url="localhost:8888", aperture_mask="empty", magnitude_limit=18):
"""tpf.interact_sky wrapper to handle different lightkurve versions."""
if "aperture_mask" in inspect.getfullargspec(tpf.interact_sky).args:
# case using a pre-release lightkurve that suppor... | fae7b2a9c9d5fe3a92a7393cf79fe516acda3ac7 | 568,581 |
def rpc_method(f):
"""A decorator for use in declaring a method as an rpc method.
Use as follows::
@rpc_method
def echo(self, s):
return s
"""
f.is_rpc_method = True
return f | 04c679fc3bd18c6abda51436b8be2f7f66c91d9a | 568,583 |
from typing import Optional
import re
def validate_code_postal(code_postal_clean: str) -> Optional[str]:
"""Check the validity of code_postal.
Args:
code_postal_clean(str, optional): code postal extracted and cleaned.
Returns:
None if code_postal_clean is None.
code_postal_clean ... | b1845184bcddafc8ecb3d2ab22dd775ed9266259 | 568,584 |
def monomial_min(*monoms):
"""Returns minimal degree for each variable in a set of monomials.
Consider monomials x**3*y**4*z**5, y**5*z and x**6*y**3*z**9. We
wish to find out what is the maximal degree for each of x, y, z
variables:
>>> monomial_max((3,4,5), (0,5,1), (6,3,9))
(... | 29fc1a3287db3e65d397b4ac9409c9a36ed176ed | 568,585 |
def get_client_ip(request):
"""
X-Forwarded-For stores the client's ip when going
through a proxy or load balancer
Remote-Address is not as reliable as X-Forwarded-For, but if the
server is not configured to include X-Forwarded-For header,
thats the only option
"""
x_forwarded_for = requ... | e484626f0a8e748de1630ff6095091376e8349f8 | 568,588 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.