content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def normalize_tourism_kind(shape, properties, fid, zoom):
"""
There are many tourism-related tags, including 'zoo=*' and
'attraction=*' in addition to 'tourism=*'. This function promotes
things with zoo and attraction tags have those values as their
main kind.
See https://github.com/mapzen/vector-datasource/issues/440 for more details.
""" # noqa
zoo = properties.pop('zoo', None)
if zoo is not None:
properties['kind'] = zoo
properties['tourism'] = 'attraction'
return (shape, properties, fid)
attraction = properties.pop('attraction', None)
if attraction is not None:
properties['kind'] = attraction
properties['tourism'] = 'attraction'
return (shape, properties, fid)
return (shape, properties, fid)
|
1318477fc71c6298cc09f12809f3b846554082f5
| 103,865 |
def listfind(values, val):
"""
Return all indices of a list corresponding to a value.
:param list values:
List to analyse.
:param any val:
Element to find in the list.
:return: list
"""
return [i for i in range(0, len(values)) if values[i] == val]
|
4b223ac1cb9d7178a846a74728bf1ad318636034
| 376,666 |
from typing import MutableSequence
def _peel_nested_parens(input_str: str) -> MutableSequence[str]:
"""Extracts substrings from a string with nested parentheses.
The returned sequence starts from the substring enclosed in the innermost
parentheses and moves subsequently outwards. The contents of the inner
substrings are removed from the outer ones. For example, given the string
'lorem ipsum(dolor sit (consectetur adipiscing) amet)sed do eiusmod',
this function produces the sequence
['consectetur adipiscing', 'dolor sit amet', 'lorem ipsumsed do eiusmod'].
Args:
input_str: An input_str string consisting of zero or more nested
parentheses.
Returns:
A sequence of substrings enclosed with in respective parentheses. See the
description above for the precise detail of the output.
"""
start = input_str.find('(')
end = input_str.rfind(')')
if start == -1 and end == -1:
return [input_str]
else:
# Assertions to be re-raised into a meaningful error by the caller.
assert start != -1 # '(' should be present if there is a ')'
assert end != -1 # ')' should be present if there is a '('
assert start < end # '(' should come before ')'
out = _peel_nested_parens(input_str[start + 1:end])
out.append(input_str[:start] + input_str[end + 1:])
return out
|
6958396cf3e7795437b0e28893049fc4805a9b6e
| 202,573 |
def get_child_objects(model):
"""Return a list of all children of an object"""
children = []
for child in model.children:
children.append(child)
return children
|
238ae4e3fcd2deba4bb2af8832c085cde934d6dd
| 558,835 |
from typing import Optional
from typing import Dict
from typing import Any
from datetime import datetime
def get_parameter_response(
name: str,
value: str,
value_type: str = "String",
label: Optional[str] = None,
version: int = 1,
) -> Dict[str, Any]:
"""Generate a mock ssm.get_parameter response."""
selector = "{}/{}".format(name, label or version)
return {
"Parameter": {
"Name": name,
"Type": value_type,
"Value": value,
"Version": 1,
"Selector": selector,
"SourceResult": "",
"LastModifiedDate": datetime.now(),
"ARN": "",
}
}
|
01d9b094a1e9bfc18b612554027502db52a699bc
| 343,580 |
import fnmatch
def field_needed(field, projections):
"""
Check if the name *field* matches any of the *patterns* (ala
:mod:`fnmatch`).
:param str field: field name
:param list(str) projections: list of :mod:`fnmatch` patterns
against which to check field. Can be *None* and *[ ]* (empty).
:returns bool: *True* if *field* matches a pattern in *patterns*
or if *patterns* is empty or *None*. *False* otherwise.
"""
if projections:
# there is a list of must haves, check here first
for projection in projections:
if fnmatch.fnmatch(field, projection):
return True # we need this field
# match projection a to fields a.[x.[y.[...]]]
if field.startswith(projection + "."):
return True
return False # we do not need this field
else:
return True # no list, have it
|
d8534650359a71c8ec901c7c338de5b36c53f9a4
| 430,039 |
def _path_to_target(package, path):
""" Converts a path to a Bazel target. """
return "@{package}//:{path}".format(package = package, path = path)
|
d7fcc55f3758112320a8e1b8b3e2c4980c1a5982
| 604,312 |
def is_overlap_1d(start1: float, end1: float, start2: float, end2: float) -> bool:
"""Return whether two 1D intervals overlaps"""
assert start1 <= end1
assert start2 <= end2
return not (start1 > end2 or end1 < start2)
|
c0fd9f8985adc86bfc356cad5b57122c77f42c0b
| 241,130 |
def declarative_base(decl_type, name, cls, metaclass, **kwargs):
"""Create base class for defining new database classes.
:param decl_type: DeclarativeType enum value.
:param name: Metaclass name
:param cls: Base class(es) for returned class
:param metaclass: Metaclass for registering type information
"""
bases = cls if isinstance(cls, tuple) else (cls, )
class_dict = dict(decl_type=decl_type)
class_dict.update(kwargs)
return metaclass(name, bases, class_dict)
|
e86f26884a74d6fb613919a10e4acfd22b070554
| 499,726 |
def h_file_to_define(name):
"""
Convert a .h file name to the define used for the header
"""
h_name = name[:-2].upper()
h_name = "_" + h_name + "_H_"
return h_name
|
5f2876229d39d1218a0f7731a4f0e4f17f8e34b5
| 569,787 |
def index(queryset, obj):
"""
Give the zero-based index of first occurrence of object in queryset.
Return -1 if not found
"""
for index, item in enumerate(queryset):
if item == obj:
return index
return -1
|
aca5989ca66d72ed7226845d6d966b401ed3f1e9
| 357,960 |
import math
def _rotate(point, angle, origin = (0,0),unit = 'degree'):
"""Rotate a point counterclockwise by a given angle around a given origin.
Angle can be both in radian or degree. Helper function for rotating a layout.
Parameters
----------
point : tuple
position in (x,y) form
angle : float
angle to rotate the point
origin : tuple in (x,y) form
point will rotate with respect to the origin.
unit : 'degree'/'radian' to indicate if the angle is in degrees or radians.
if given in degrees angle is converted to radians.
Returns
-------
tuple
rotated point as (x,y) tuple.
"""
ox, oy = origin
px, py = point
if unit == 'degree':
angle = math.radians(angle)
if unit == 'radian':
angle = angle
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy
|
ec01d3fc7038b2846b1f33626fa1a33b2b23968f
| 694,971 |
def count_points(grid: list[list[int]], minimum: int = 2) -> int:
"""Count the number of points in a 2x2 grid that are higher than "minimum"."""
count = 0
for row in grid:
for number in row:
if number >= minimum:
count += 1
return count
|
28da29250c435200ae2bfb148d797b37e49e6e71
| 488,573 |
def check_unpublished(val: str) -> bool:
"""
Returns True if value is "TBA" or None.
:param val:str:
"""
return val is None or val == "TBA"
|
c8e7282f153f1753cc23d4d9a4678ed463d38edb
| 608,261 |
def list_multiply(a, b):
""" Sums two lists of integers and multiplies them together
>>> list_multiply([3,4],[3,4])
49
>>> list_multiply([1,2,3,4],[10,20])
300
"""
return sum(a) * sum(b)
|
8c03ce5f790a57792a97e41bc538bb0c7941ee4d
| 518,175 |
def lazyprop(fun):
"""
Decorator which only evaluates the specified function when accessed.
"""
name = '_lazy_' + fun.__name__
@property
def _lazy(self):
val = getattr(self, name, None)
if val is None:
val = fun(self)
setattr(self, name, val)
return val
return _lazy
|
8bc961dc7f9e2d7cc5b39c6b02f6bd0382492038
| 519,078 |
def convert_seconds(seconds):
"""Converts the provided seconds value into days, hours, minutes, seconds and returns a tuple containing each of these values"""
# Converting seconds to a standard python float type to resolve the "negative 0 when using numpy.float64 type" issue .
seconds = float(seconds)
# Convert seconds to minutes and store remainder
minutes = seconds // 60
seconds = seconds % 60
# Convert minutes to hours and store remainder
hours = minutes // 60
minutes = minutes % 60
# Convert hours to days and store remainder
days = hours // 24
hours = hours % 24
return days, hours, minutes, seconds
|
664aead3b845243921fe259d7b858fe91f488a37
| 664,871 |
def get_intersection(cx1, cy1, cos_t1, sin_t1,
cx2, cy2, cos_t2, sin_t2):
""" return a intersecting point between a line through (cx1, cy1)
and having angle t1 and a line through (cx2, cy2) and angle t2.
"""
# line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0.
# line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1
line1_rhs = sin_t1 * cx1 - cos_t1 * cy1
line2_rhs = sin_t2 * cx2 - cos_t2 * cy2
# rhs matrix
a, b = sin_t1, -cos_t1
c, d = sin_t2, -cos_t2
ad_bc = a*d-b*c
if ad_bc == 0.:
raise ValueError("Given lines do not intersect")
#rhs_inverse
a_, b_ = d, -b
c_, d_ = -c, a
a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]]
x = a_* line1_rhs + b_ * line2_rhs
y = c_* line1_rhs + d_ * line2_rhs
return x, y
|
c1b1cd45d67ca2466b3f02a4ee5220ed07cc8c5f
| 149,111 |
import pytz
def compare_datetimes(d1, d2):
""" Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2, 0 if they are the same, or +1 is d1 > d2.
"""
if d1.tzinfo is None or d1.tzinfo.utcoffset(d1) is None:
d1 = d1.replace(tzinfo=pytz.UTC)
if d2.tzinfo is None or d2.tzinfo.utcoffset(d2) is None:
d2 = d2.replace(tzinfo=pytz.UTC)
if d1 < d2:
return -1
elif d1 > d2:
return 1
return 0
|
f99ae1c57b9bb1c9ab71c069dadb249d13d4830a
| 233,277 |
import string
import random
def generate_random_string(
length=25, allowed_chars=string.ascii_letters + string.digits
):
"""
Generate a random string.
:param length: The length of the desired string
:type length: int
:param allowed_chars: The set of allowed characters
:type allowed_chars: str
:returns: Random string
:rtype: str
"""
return "".join(random.choice(allowed_chars) for i in range(length))
|
2f33997f2d167bba461ee2102e4cccbceebd19fa
| 110,442 |
def longest_common_prefix(str1, str2):
""" Returns the length of the longest common prefix of two provided strings """
i = 0
while i < min(len(str1), len(str2)):
if str1[i] != str2[i]:
break
i += 1
return i
|
0a3b49cc89c4bf8cd9f6836f9599acc2f9e5621a
| 489,226 |
def train(model, X, y):
"""
Model trainer for models and pipelines that adhere to the sklearn API.
Args:
model (sklearn.model): model that adheres to sklearn model API
X (DataFrame): feature matrix
y (DataFrame): target variable
Returns:
trained_model (sklearn.model): trained model
"""
trained_model = model.fit(X, y)
return trained_model
|
6963e6d3b6c9e5c72bbd81e2d95cd1b70c280b31
| 349,185 |
def filter_sentences_by_mentions(sentences,names):
"""
Recieves a list of sentences and a list of names.
Returns the sentences in which at leas one of the mentioned names appear.
"""
# filter(lambda x: any(name in sentence for name in names),sentences)
sents = []
for sentence in sentences:
if any(name in sentence for name in names):
sents.append(sentence)
return sents
|
89c2fa637a5867478f133dd90aed2310564b0ae9
| 384,620 |
def getDeviceParameter(deviceID, devicePrefix, deviceSuffix = ''):
"""Find the variable parameter of a device based on the ID
IMPORTANT: "removeprefix" and "removesuffix" are only available
for Python >= 3.9
Args:
deviceID (string): ID of the device.
devicePrefix (string): Prefix string in the device that's before the variable parameter
deviceSuffix (string): Any additional fields in the suffix of a device that need to be stripped, optional.
Returns:
parameter (float): variable parameter of the device (unit based on whats in the ID)
"""
parameter = float(deviceID.removeprefix(devicePrefix).removesuffix(deviceSuffix).replace('p','.'))
return parameter
|
23f33cca85761288939a2784f45f223317871914
| 397,225 |
def _GetBrowserPID(track):
"""Get the browser PID from a trace.
Args:
track: The tracing_track.TracingTrack.
Returns:
The browser's PID as an integer.
"""
for event in track.GetEvents():
if event.category != '__metadata' or event.name != 'process_name':
continue
if event.args['name'] == 'Browser':
return event.pid
raise ValueError('couldn\'t find browser\'s PID')
|
1e9a5900a4cd9930f8c634c8f0a932eae4873764
| 670,531 |
def is_private(path):
"""
Determine if a import path, or fully qualified is private.
that usually implies that (one of) the path part starts with a single underscore.
"""
for p in path.split("."):
if p.startswith("_") and not p.startswith("__"):
return True
return False
|
67aef36c292a737e3be3e5434822c85a348b58a8
| 508,458 |
import statistics
def sd(array):
"""
Calculates the standard deviation of an array/vector
"""
return statistics.stdev(array)
|
1710c2174d76649f3d8cce28a74048bd3d6b9b16
| 577,182 |
def parse_wgac_alignment(wgac_alignment):
"""
Parses a WGAC alignment from a list into a tuple of tuples for each sequence
in the alignment.
"""
wgac_alignment[1:3] = map(int, wgac_alignment[1:3])
wgac_alignment[5:7] = map(int, wgac_alignment[5:7])
return (
tuple(wgac_alignment[:4]),
tuple(wgac_alignment[4:])
)
|
41f8130604e54bac8510b785d33ca9c672de69c1
| 624,516 |
def get_formatted_issue(repo, issue, title, url):
"""
Single place to adjust formatting output of PR data
"""
# Newline support writelines() call which doesn't add newlines
# on its own
return("* {}/{}: [{}]({})\n".format(repo, issue, title, url))
|
1f1d2f90b02588c29f2c237981e764b154c9e43b
| 299,208 |
def string_with_arrows(text, pos_start, pos_end):
"""
Produces a string that has arrows under the problem area specified by
pos_start and pos_end.
Example:
class My!Class:
^^^^^^^^
"""
result = ''
# Calculate indices
idx_start = max(text.rfind('\n', 0, pos_start.idx), 0)
idx_end = text.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(text)
# Generate each line
line_count = pos_end.ln - pos_start.ln + 1
for i in range(line_count):
# Calculate line columns
line = text[idx_start:idx_end]
col_start = pos_start.col if i == 0 else 0
col_end = pos_end.col if i == line_count - 1 else len(line) - 1
# Append to result
result += line + '\n'
result += ' ' * col_start + '^' * (col_end - col_start)
# Re-calculate indices
idx_start = idx_end
idx_end = text.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(text)
return result.replace('\t', '')
|
3e10ca9607255ba43592772a2c013c599a202f7c
| 271,758 |
import time
def sleep_check(sleep_time, check_interval, stop=lambda: False):
"""
sleep for an overall period of time, waking up to check for a
stop semaphore to be set, at a given interval
Inputs:
======
sleep_time :: overall time to sleep in seconds
check_interval :: period before semaphore checking, seconds
stop :: semaphore function, returns True when time to exit
Returns:
=======
None
"""
# get initial time when starting
start_time = time.time()
while True:
# check for stop, if present return
if stop():
return None
# sleep for check interval
time.sleep(check_interval)
# get current time
curr_time = time.time()
# exit criteria is when current time i
if curr_time -start_time >= sleep_time:
return None
|
296e7188a377e90dbab39e5c987e79dfc9a75080
| 249,540 |
import inspect
def create_signature(args=None, kwargs=None):
"""Create a inspect.Signature object based on args and kwargs.
Args:
args (list or None): The names of positional or keyword arguments.
kwargs (list or None): The keyword only arguments.
Returns:
inspect.Signature
"""
args = [] if args is None else args
kwargs = {} if kwargs is None else kwargs
parameter_objects = []
for arg in args:
param = inspect.Parameter(
name=arg,
kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
)
parameter_objects.append(param)
for arg in kwargs:
param = inspect.Parameter(
name=arg,
kind=inspect.Parameter.KEYWORD_ONLY,
)
parameter_objects.append(param)
sig = inspect.Signature(parameters=parameter_objects)
return sig
|
011acccada7896e11e2d9bb73dcf03d7dc6e751e
| 4,423 |
def num_ints(lst):
"""
Returns: the number of ints in the list
Example: num_ints([1,2.0,True]) returns 1
Parameter lst: the list to count
Precondition: lst is a list of any mix of types
"""
result = 0 # Accumulator
for x in lst:
if type(x) == int:
result = result+1
return result
|
cba6c06bc1618dae1b7a6f515e7f9b42ca88187b
| 20,375 |
import string
import random
def build_random_string(str_length, use_digits=False, use_punctuations=False):
"""
Create random string
:param str_length: String length
:param use_digits: Takes string.digits as well
:param use_punctuations: Takes string.punctuation
:return: Random string
"""
letters = string.ascii_letters
if use_digits:
letters = letters + string.digits
if use_punctuations:
letters = letters + string.punctuation.replace(" ", "").replace("\\", "").replace("\"", "").replace("\'", "")
return ''.join(random.choice(letters) for _ in range(str_length))
|
10f2a08210ad3d18d95e14703e068f242f6c6f98
| 332,335 |
from typing import Dict
def compose_exists_query(field: str) -> Dict[str, Dict[str, bool]]:
"""
Compose a MongoDB query that checks if the passed `field` exists.
:param field: the field to check for existence
:return: a query
"""
return {field: {"$exists": True}}
|
0817c7a2b3daf5f8ff2fb03851b2e71f773cd2cb
| 538,567 |
def IsInstanceOf(*classes):
"""
Make sure that a feature is an instance of a specific class type.
"""
def test(obj): return isinstance(obj, classes)
return test
|
177c4b79adbe581f7b9f81d4a04451422ee21fc9
| 498,116 |
import math
def euclidean_distance(inst_one, inst_two, length):
"""
Calculate euclidean distance
"""
distance = 0
for x in range(length):
distance += pow((inst_two[x]-inst_one[x]), 2)
return math.sqrt(distance)
|
825286c932cc98e8ce4d87c889738c0e31ef99eb
| 146,213 |
def tupleEqualNoOrder(t1: tuple, t2: tuple) -> bool:
"""Check if two two-element tuples have the same elements."""
assert len(t1) == 2
assert len(t2) == 2
if(t1[0] == t2[0]):
return t1[1] == t2[1]
else:
return t1[0] == t2[1] and t1[1] == t2[0]
|
498c25550afb9556aa9bfd4cfe8f924fe4b0adec
| 378,464 |
def smul(a, x):
"""Multiplies the vector "x" by the scalar "a"."""
R = []
for i in range(len(x)):
R.append(a*x[i])
return R
|
02ba9ec4c100c9e69d01b21e4408d180838f6fe9
| 475,184 |
from bs4 import BeautifulSoup
def clean_field_html(soup: BeautifulSoup) -> str:
"""
Given the raw HTML for a field, such as "question" or "answer", neaten it
up by removing anything that doesn't belong on the Anki card, such as
outer <p> tags and internal links, and return the string of HTML that belongs
in the field.
"""
for elem in soup.find_all("a"):
classes = elem.attrs.get('class', None)
if (classes is not None
and 'href' in elem.attrs
and 'tc-tiddlylink-external' in classes):
# External links lose their attributes but stay links.
elem.attrs = {'href': elem.attrs['href']}
else:
# Internal links just get whacked and replaced with their plaintext.
elem.replace_with(elem.get_text())
return ''.join(str(i) for i in soup.contents)
|
c80fc532555c2fd44193b385415724daf8fc6720
| 307,605 |
import re
def pretty_string(strng):
"""
break camelCase string into words
and turns underscores into spaces
:param string:
:return:
"""
pretty_string_re_1 = re.compile('(.)([A-Z][a-z]+)')
pretty_string_re_2 = re.compile('([a-z0-9])([A-Z])')
s1 = pretty_string_re_1.sub(r'\1 \2', strng)
s2 = pretty_string_re_2.sub(r'\1 \2', s1)
s3 = s2.replace('_', ' ')
return s3.title()
|
20065cd0e0b89ab278d0c090f2aab0d0b7a15b05
| 551,626 |
def square(file_index, rank_index):
"""Gets a square number by file and rank index."""
return rank_index * 8 + file_index
|
374e98e5ac0ff86cf0e1eded12a537ca3b48e2fb
| 686,366 |
def split(n, m, rank=None):
"""
Return an iterator through the slices that partition a list of n elements
in m almost same-size groups. If a rank is provided, only the slice
for the rank is returned.
Example
-------
>>> split(1000, 2)
(slice(0, 500, None), slice(500, 1000, None))
>>> split(1000, 2, 1)
slice(500, 1000, None)
"""
if rank is not None:
work = n // m + ((n % m) > rank)
start = n // m * rank + min(rank, n % m)
return slice(start, start + work)
def generator():
rank = 0
start = 0
while rank < m:
work = n // m + ((n % m) > rank)
yield slice(start, start + work)
start += work
rank += 1
return tuple(generator())
|
1cc5cc183f8b7eb33759fd9cc5482a9e593c70df
| 532,605 |
from typing import Dict
def is_valid_config(
config: Dict,
) -> bool:
"""Validate configuration."""
docs = config.get('docs', None)
if not docs:
print("Missing top-level 'docs' key")
return False
repo = docs.get('repo', None)
if not repo:
print("Missing 'repo' under 'docs'")
return False
versions = docs.get('versions', None)
if not versions:
print("Missing 'versions' under 'docs'")
return False
for version_name, packages in versions.items():
if not isinstance(version_name, str):
print('Versions have to be strings. Invalid version(s):', version_name)
return False
if packages:
# Convert string to list if necessary
packages = [packages] if not isinstance(packages, list) else packages
versions[version_name] = packages
if any(not isinstance(package, str) for package in packages):
print('Packages have to be strings. Invalid package(s):', packages)
return False
return True
|
2853058238c0901ac130a98d52a8cfa2e7f5a69f
| 290,524 |
def filter_devices(ads, func):
"""Finds the AndroidDevice instances from a list that match certain
conditions.
Args:
ads: A list of AndroidDevice instances.
func: A function that takes an AndroidDevice object and returns True
if the device satisfies the filter condition.
Returns:
A list of AndroidDevice instances that satisfy the filter condition.
"""
results = []
for ad in ads:
if func(ad):
results.append(ad)
return results
|
3ec4b214e3b2f3129c7466de6806a4a778df0321
| 610,021 |
import torch
def blur_with_zeros(image, blur):
"""Blur an image ignoring zeros.
"""
# Create binary weight image with 1s where valid data exists.
mask = torch.ones(image.shape, device=image.device)
mask[image <= 0] = 0
# Compute blurred image that ignores zeros using ratio of blurred images.
blurred = blur(image)
weights = blur(mask)
blurred[weights == 0] = 0
weights[weights == 0] = 1
blurred = blurred / weights
return blurred
|
d747f5bf8c8b53f37d735963990b935a02604535
| 651,652 |
def transform_len(val, default=None):
"""
Calculate length
<dotted>|len len(val) or raises
<dotted>|len:<default> len(val) or <default>
"""
try:
return len(val)
except TypeError:
if default is not None:
return default
raise
return val
|
dbdd0757b387214c44a8341ac5b8b56e741a3b7c
| 679,181 |
def my_even(my_number):
"""Checks if a number is even
Keyword arguments:
my_number (int) -- integer
Returns:
Bool -- Whether my_number is even
"""
if my_number % 2 == 0:
return True
else:
return False
#or return my_number % 2 == 0
|
19781ef0a32299036974d9cfaf1d9fd2ff78e668
| 161,080 |
def keywords_first(keywords):
""" Returns a sort key which preferrs values matching the given keywords
before other values which are sorted alphabetically.
"""
assert hasattr(keywords, 'index')
def sort_key(v):
try:
return keywords.index(v) - len(keywords), ''
except ValueError:
return 0, v
return sort_key
|
b3d2bbc7ff7d01e2ed12149195bf5ebaf88d8e89
| 346,424 |
def divide(num1, num2):
"""Divide
Divide num1 by num2
Args:
num1 (int): dividend
num2 (int): divisor
Returns:
float: quotient of num1 / num2
"""
return num1 / num2
|
378dd41cf2d5e070a2d3cd25338bacecc3ee9f26
| 326,114 |
def filter_data(src, trg, min_len=0, max_len=float("inf")):
"""Filters data on source and target lengths
Args:
src (list[int]): Tokenized source data
trg (list[int]): Tokenized target data
min_len (int): Minimum length
max_len (int): Maximum length
Returns:
(list[int], list[int]): The filtered data (tokenized)
"""
filtered_src = []
filtered_trg = []
for src, trg in zip(src, trg):
if min_len <= len(src) <= max_len and min_len <= len(trg) <= max_len:
filtered_src.append(src)
filtered_trg.append(trg)
return filtered_src, filtered_trg
|
7335d9ebff6cbca436e78dba9a85c76dc5c88e95
| 96,020 |
def create_reply(elem):
""" switch the 'to' and 'from' attributes to reply to this element """
# NOTE - see domish.Element class to view more methods
frm = elem['from']
elem['from'] = elem['to']
elem['to'] = frm
return elem
|
aec51671b9b9a024ce87f63028f7bbfc7400bdc2
| 345,696 |
def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
return anon.faker.datetime(field=field)
|
7cd3d19024050f1a2e0d6912ef0824c632e0feb4
| 641,811 |
def getFiducials(d, offset=None):
"""Returns fiducials from the given dict as a list of (x,y) pairs, or None on error.
The fiducials are normally translated relative to CROP_RECT_TOP_LEFT_{XY}, but you can
give an explicit [x,y] offset if you want.
The order of points returned is:
left eye out
left eye in
right eye in
right eye out
mouth left
mouth right
"""
KEYS = 'LEFT_EYE_OUT LEFT_EYE_IN RIGHT_EYE_IN RIGHT_EYE_OUT MOUTH_LEFT MOUTH_RIGHT'.split()
if offset is None:
offset = [int(d['CROP_RECT_TOP_LEFT_X']), int(d['CROP_RECT_TOP_LEFT_Y'])]
try:
ret = [(int(d[k+'_X'])+offset[0], int(d[k+'_Y'])+offset[1]) for k in KEYS]
return ret
except KeyError:
return None
|
47deba7c9ac12b028d404bbb7a16f15697ffa7ad
| 69,679 |
import hashlib
def compute_sha256(path):
"""
Compute the SHA-256 hash of the file at the given path
Parameters
----------
path: str
The path of the file
Returns
-------
str
The SHA-256 HEX digest
"""
hasher = hashlib.sha256()
with open(path, 'rb') as f:
# 10MB chunks
for chunk in iter(lambda: f.read(10 * 1024 * 1024), b''):
hasher.update(chunk)
return hasher.hexdigest()
|
16d0796559f45f7e8fbc7458daa2116e96a4a9ba
| 304,195 |
def _get_translated_node(target_node, target_dom_to_doc_dom):
"""Convenience function to get node corresponding to 'target_node'
and to assign the tail text of 'target_node' to this node."""
dom_node = target_dom_to_doc_dom[target_node]
dom_node.tail = target_node.tail
return dom_node
|
8b356c8acddbad1279b066ebc36a8799994558c3
| 629,547 |
def get_session_id(result):
"""Returns the Session ID for an API result.
When there's no Session ID, returns None.
"""
try:
return result["header"]["header"]["SessionId"]
except TypeError:
return None
|
64e8d4d06e9ceeffd39e9601adee5fde0dbaca43
| 494,875 |
def is_2nd_after_1st(event_stat_1, event_stat_2):
"""Returns true if 2nd event has a later minute / second as the first"""
min_1 = event_stat_1.minute
sec_1 = event_stat_1.second
min_2 = event_stat_2.minute
sec_2 = event_stat_2.second
return min_1 * 60 + sec_1 < min_2 * 60 + sec_2
|
dd2004c70a7b7bbb6fd79e8c50dc2aeb8e467277
| 633,340 |
def format_pdb_code_for_inputs(pdb_code: str, source_type: str):
"""Format given PDB code for prediction inputs."""
return pdb_code[1:3] if source_type.lower() == 'input' else pdb_code.upper()
|
430a97ec59e5c32175f40f2595db5dd90650275a
| 630,436 |
def blocksearch(block, name):
""" Recursive search for name in block (inner blocks)
Args:
name (str): search term
Returns:
Block OR False
"""
if hasattr(block, 'tokens'):
for b in block.tokens[1]:
b = (b if hasattr(b, 'raw') and b.raw() == name else blocksearch(
b, name))
if b:
return b
return False
|
da9f762dddabe762dbabd80addebc0a957b04135
| 697,798 |
def remove(pkgs):
"""Remove a package for a port."""
return ("pkg_delete", "-f") + pkgs
|
caf7aa4feda81f9984a249e201a29fb45d3280e7
| 388,631 |
def is_image_file(filename):
""" Check if given file is image file or not
Parameters
-------
filename: str
input file path
Returns
-------
img_flag: bool
flag for image
"""
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG',
'.ppm', '.PPM',
'.bmp', '.BMP',
'tif', 'TIF', 'tiff', 'TIFF',
]
img_flag = any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
return img_flag
|
3ddb6589a421b91e52cacb3b0bae75c1d682d981
| 17,674 |
import json
def store_barbican_secret_for_coriolis(
barbican, secret_info, name='Coriolis Secret'):
""" Stores secret connection info in Barbican for Coriolis.
:param barbican: barbican_client.Client instance
:param secret_info: secret info to store
:return: the HREF (URL) of the newly-created Barbican secret
"""
payload = json.dumps(secret_info)
secret = barbican.secrets.create(
name=name, payload=payload,
payload_content_type='application/json')
secret_ref = secret.store()
return secret_ref
|
218bf941203dd12bc78fc7a87d6a2f9f21761d57
| 2,912 |
def pyenv(command: str) -> str:
""" Wrap a command to use the pyenv environment.
:param command: original command
:return: modified command
"""
# Testinfra uses a separate /bin/sh invocation for every remote command,
# and ~/.profile is not being sourced, so it needs to be prepended to every
# command.
return f". ~/.profile && {command}"
|
14611f61e5adee4e8f68f1991d45b37faf1372f8
| 447,275 |
import math
def rounds_sig(value, sig=3):
"""Round a float to sig significant digits & return it as a string.
Parameters
----------
value: float
The float that is to be rounded.
sig: int
The number of significant figures.
Returns
----------
str:
The rounded output string.
"""
if value == 0.:
return str(0.)
if value < 0.:
value = abs(value)
return str(-1. *
round(value, sig - int(math.floor(math.log10(value))) - 1))
return str(round(value, sig - int(math.floor(math.log10(value))) - 1))
|
50b63d59b6d77c0adf8e9bb44c284f8fab9046de
| 579,696 |
def simplify_county_names(dframe):
"""
Removes words 'county' and 'parish' and extra white space
from county field of a dataframe
"""
dframe['County'] = dframe['County'].str.replace('County', '')
dframe['County'] = dframe['County'].str.replace('Parish', '')
dframe['County'] = dframe['County'].str.strip()
return dframe
|
625959eafe281d2183d738aefcaa3bc7c6321ea1
| 99,210 |
def build_config_keys_map(spec):
"""Build config keys map
Return
------
Dict where each item:
<config_key>: { "group": <grouping>, "type": <http|message_router|data_router> }
where grouping includes "streams_publishes", "streams_subscribes", "services_calls"
"""
# subscribing as http doesn't have config key
ss = [ (s["config_key"], { "group": "streams_subscribes", "type": s["type"] })
for s in spec["streams"]["subscribes"] if "config_key" in s]
sp = [ (s["config_key"], { "group": "streams_publishes", "type": s["type"] })
for s in spec["streams"]["publishes"] ]
sc = [ (s["config_key"], { "group": "services_calls" })
for s in spec["services"]["calls"] ]
return dict(ss+sp+sc)
|
eacfc2ab76eae95150f8ab94b16c9bdf0064553c
| 508,172 |
import pathlib
def get_source_id_from_file_path(file_path: pathlib.Path) -> str:
"""Extrapolates the source id from the file path.
To retrieve the source id from the file name, the function uses the fact that the
ICE uses a consistent naming convention consisting of the file type accompanied by
the source id and the date the data in the file was generated.
(e.g. COREREF_207_20201023.txt.bz2).
Parameters
----------
file_path: str
The path to the file for which the source id has to be extrapolated.
Returns
-------
str
The source id.
"""
file_name = file_path.name.split(".")[0]
name_components = file_name.split('_')
return name_components[1]
|
03588ef925e3de688451bedd922b3ab29a8042e5
| 19,313 |
def largest_power_of_two(n):
"""Returns the largest j such that 2**j divides n
Based on
https://www.geeksforgeeks.org/highest-power-of-two-that-divides-a-given-number/#:~:text=Highest%20power%20of%202%20that%20divides%205%20is%201.
https://stackoverflow.com/questions/13105875/compute-fast-log-base-2-ceiling-in-python
"""
return((n & (~(n - 1))).bit_length() - 1)
|
fb3b1349580fba643c281685b0c0a5e6f9833a5f
| 235,399 |
def _flatten_list(nested_list):
"""
Given a nested list, returns flat list of all its elements
:param nested_list: nested list
:return: flat list
"""
if not isinstance(nested_list, list):
return [nested_list]
res = []
for sub_list in nested_list:
res += _flatten_list(sub_list)
return res
|
036cc48295e8898c99dcf3b2688c746e0636bb23
| 675,735 |
def _is_sorted(a_list: list) -> bool:
"""
Return True if `a_list` is sorted, False otherwise
"""
for i in range(len(a_list) - 1):
if a_list[i] > a_list[i + 1]:
return False
return True
|
2d19a0e1188131ccb298c8e20dee92babd22f21e
| 355,754 |
import re
def has_added(message):
"""
Function to check if a message contains any word that indicates an addition of lines of code.
"""
if (re.search(
r"add(?:ed)*|implement(?:ed)*|introduce(?:d)*|improve(?:ment|ments)*",
message.lower())):
return True
return False
|
279ca80deafd153e6209c78b0607b8c4f02f546b
| 605,864 |
def extract_arg_default(arg_str):
""" Default strategy for extracting raw argument value. """
args_str_split = arg_str.split(" ", 1)
if len(args_str_split)==1:
args_str_split.append("")
return args_str_split
|
44f139591695ebf015b88cf343c90f7b2d29aff0
| 15,365 |
import re
def extract_text(json_dict):
"""
Pull out the raw text from the dictionary and remove newlines
:param json_dict:
:return:
"""
text = ' '.join([json_dict['title'], json_dict['content']]).strip()
text = re.sub(r"\s+", ' ', text)
return text
|
dde7cd332c565c54bf5acddaec2ff9ab761fbe33
| 271,363 |
def quick_sort(A, start = None, end = None):
"""
Sorts elements of a list in ascending order
"""
start = 0 if start == None else start
end = len(A) if end == None else end
def partition(A, start, end):
"""
Puts an element(last element) of a list in
place (its ordered) position
"""
pivot = A[end - 1]
pIndex = start
for i in range(start, end):
if A[i] <= pivot:
temp = A[i]
A[i] = A[pIndex]
A[pIndex] = temp
pIndex += 1
return pIndex
if (start >= end):
return
partitionIndex = partition(A, start, end)
quick_sort(A, start, partitionIndex - 1)
quick_sort(A, partitionIndex, end)
return A
|
bd28ceebec4422ac7f22640e830c6a2dd1620bcb
| 151,891 |
def lowercase(text):
"""Converts all text to lowercase"""
return text.lower()
|
240526dc35b7c1f255d177fd89e2799de586fbc3
| 293,407 |
def GP_sum(a1:float,r:float,n:int)->float:
"""
等比数列の第n項までの総和を返します。
a1:初項
r:公比
n:第n項
"""
if(r==1.0):return a1*n
return a1*(1-r**n/(1-r))
|
01223a5dc2758570cbaf73c223ea27b0450b04be
| 207,475 |
def wikiEscape(s: str) -> str:
"""Escape wikitext (into wikitext that will show the raw code)."""
return s.replace('<', '<').replace('>', '>') \
.replace('{{', '{<nowiki />{').replace('}}', '}<nowiki />}') \
.replace('[[', '[<nowiki />[').replace(']]', ']<nowiki />]') \
.replace('|', '<nowiki>{{!}}</nowiki>')
|
c3d3500ac48a0c44c1c319e7c607c490080875f8
| 236,216 |
import toml
from pathlib import Path
def get_colordata(name):
"""
Load color map data from setting file.
Parameters
----------
name : str
Colormap name. Currently, ``Dark_rainbow``, ``rainbow2``, ``sls_SAOImage``,
``rainbow3``, ``rainbow_SAOImage``, ``b_SAOImage``, ``spectrum_Starlink``,
and ``Hue_sat_value2`` are supported.
"""
color = toml.load(open(Path(__file__).parent / "colordata" / "cmapdata.toml"))
color_numbers = color["table"][name]
return color_numbers
|
42b86661b793cc9d1796cdb320efc448e8d752b2
| 56,833 |
def stars_template(rating: float) -> list:
"""Flex Message 星星圖示
Args:
rating (float): 餐廳 Google Maps 評價
Returns:
list: 星星圖示
"""
star = {
"type": "icon",
"size": "sm",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png",
}
grey_star = {
"type": "icon",
"size": "sm",
"url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png",
}
star_list = int(rating) * [star] + (5 - int(rating)) * [grey_star]
return star_list
|
4c0296c0787efbf61056ac0be8ad8f498ef94ce1
| 405,299 |
def select_feature_columns_with_profiles(profiles, df_feature_types):
"""
Return names of features in scope for the provided profiles.
Parameters
----------
profiles: list
List with feature profiles in scope (e.g. 'nature', 'culture', ...).
df_feature_types: DataFrame
Data set that tells which features belong to which feature profiles.
Returns
-------
out: list
List with the top x feature names.
"""
return (
df_feature_types.set_index("feature_name")[profiles]
.sum(axis=1)
.loc[lambda x: x > 0]
.index.values
)
|
b003ad3df6ed20116e3c3234d0890b37dc537b72
| 188,339 |
def csv_header_row() -> str:
"""CSV header string"""
return ",".join(
[
"Date",
"Energy (kWh)",
"Cost (GBP)",
"Is partial?",
"Is energy estimated?",
"Is cost estimated?",
]
)
|
d1aa5e159dad364a5af9cf7a010d05a52dc5635e
| 581,456 |
def partition(alist, indices):
"""A function to split a list based on item indices
Parameters:
-----------------------------
: alist (list): a list to be split
: indices (list): list of indices on which to divide the input list
Returns:
-----------------------------
: splits (list): a list of subreads based on cut sites
"""
return [alist[i:j] for i, j in zip([0]+indices, indices+[None])]
|
b14040058d96d66acf81e0bff8eedfe23df20738
| 23,466 |
from typing import List
def _check_detection_overlap(y_true: List[float], y_predict: List[float]):
"""
Evaluate if two detections overlap.
Parameters
----------
y_true: list
Gold standard detection [start,stop]
y_predict: list
Detector detection [start,stop]
Returns
-------
overlap: bool
Whether two events overlap.
"""
overlap = False
# dd stop in gs + (dd inside gs)
if (y_predict[1] >= y_true[0]) and (y_predict[1] <= y_true[1]):
overlap = True
# dd start in gs + (dd inside gs)
if (y_predict[0] >= y_true[0]) and (y_predict[0] <= y_true[1]):
overlap = True
# gs inside dd
if (y_predict[0] <= y_true[0]) and (y_predict[1] >= y_true[1]):
overlap = True
return overlap
|
b07a8c9b02e34303ecece8fce68b88318a613fc9
| 152,671 |
def make_str(s):
"""Casts the input to string. If a string instance is Not given, Ikke gitt or None, return empty string."""
if s == 'Not given':
return ''
if s == 'Ikke gitt':
return ''
if s is None:
return ''
return str(s)
|
c3af6cb891ec069be1846214ae6af3a7e11ab319
| 661,131 |
def grid_count(grid, X):
"""Counts the number of elements on a grid."""
del_elems = X < grid[0]
remaining_X = X[~del_elems]
res = list()
for thre in grid[1:]:
del_elems = remaining_X < thre
remaining_X = X[~del_elems]
res.append(del_elems.sum())
return res
|
891b8761b4b359bfa4c89ccfbb0a7afbb41784b9
| 274,441 |
def replace_extension(file_path, extension):
"""Generate a new file path from existing file path and new extension """
split_path = file_path.rsplit(".", 1)
return ".".join([split_path[0], extension])
|
e3b7bc2f4f80e6ce17bc00ca140e4ebf45dbc971
| 130,468 |
def list_sra_accessions(reads):
"""
Return a list SRA accessions.
"""
accessions = []
if reads is not None:
accessions = reads.keys()
return accessions
|
1028f471610cb32518ed4b3356d9516deb9e5645
| 617,472 |
from typing import Iterable
from typing import Any
def copy_except(iterable: Iterable, exclude: Any) -> Iterable:
"""Copy iterable while excluding all occurrences of exclude.
Args:
iterable: An iterable to copy
exclude: A value to exclude
Returns:
A generator yielding the values of iterable except exclude
"""
return (val for val in iterable if val != exclude)
|
b06809fa66ffacf80efaf5d80f180e222796600f
| 249,390 |
def is_window_in_area(window, area):
"""
Checks if a window is within an area.
To determine whether a window is within an area it checks if the x and y of
the window are within that area. This means a window can "hang out" of an
area but still be considered to be in the area.
Args:
window: A Window instance
area: A Geometry instance
Returns:
True or False
"""
return window.geometry.x >= area.x and \
window.geometry.y >= area.y and \
window.geometry.x < area.x + area.w and \
window.geometry.y < area.y + area.h
|
9bc3c841176042169221cd8cde0127a808ad0498
| 660,469 |
def get_synplas_morph_args(config, precell=False):
"""Get morphology arguments for Synplas from the configuration object.
Args:
config (configparser.ConfigParser): configuration
precell (bool): True to load precell morph. False to load usual morph.
Returns:
dict: dictionary containing morphology arguments.
"""
# load morphology path
if precell:
morph_path = config.get("Paths", "precell_morph_path")
else:
morph_path = config.get("Paths", "morph_path")
return {
"morph_path": morph_path,
"do_replace_axon": config.getboolean("Morphology", "do_replace_axon"),
}
|
3410bf9aa3987dc626310affb8ebbd13b382c5d9
| 44,659 |
import platform
def check_py_version(major: int, minor: int) -> bool:
"""
Checks the version of Python that was used to run the
program to see if it is greater than or equal to the
values passed in
Args:
major (int): the major release version
minor (int): the minor release version
Returns:
Boolean stating whether the Python version meets
the values in the parameters
"""
version = platform.python_version_tuple()
return int(version[0]) >= major and int(version[1]) >= minor
|
75754f09d4047fb3c38f3c35fa356a1a0566e6e7
| 569,252 |
def confirm(prompt=None, resp=False):
"""
Source: http://code.activestate.com/recipes/541096-prompt-the-user-for-confirmation/
prompts for yes or no response from the user. Returns True for yes and
False for no.
'resp' should be set to the default value assumed by the caller when
user simply types ENTER.
>>> confirm(prompt='Create Directory?', resp=True)
Create Directory? [y]|n:
True
"""
if prompt is None:
prompt = 'Confirm'
if resp:
prompt = '%s [Y/n]: ' % (prompt)
else:
prompt = '%s [y/N]: ' % (prompt)
while True:
ans = input(prompt)
if not ans:
return resp
if ans not in ['y', 'Y', 'n', 'N']:
print('please enter y or n.')
continue
if ans == 'y' or ans == 'Y':
return True
if ans == 'n' or ans == 'N':
return False
|
e45c05d9ca4a0068ffb5cc41278fbeadaefe9eb1
| 358,691 |
import hashlib
def hash_color(input_string):
"""
Derives a hex color code from the MD5 hash of an input string.
Returns the resulting hex color code as a string.
"""
digest_chars = list(hashlib.md5(input_string).hexdigest())
color = ""
while len(color) < 6:
color += digest_chars.pop(0)
color += digest_chars.pop(-1)
return color
|
0d04cca8b9491e5e99b05504f27401bd6d62c9b5
| 33,087 |
def domain_to_basedn(domain):
"""
Convert a domain (example.com) to base DN (dc=example,dc=com)
"""
dn = []
for part in domain.lower().split('.'):
dn.append("dc=%s" % (part))
return ','.join(dn)
|
0e10a16304837e1439be5c424657eee27f075505
| 330,970 |
def get_primary_key(entity):
"""
Gets primary key column from entity
:param entity: SqlAlchemy model
:return: SqlAlchemy Column
"""
for column in getattr(entity, "__table__").c:
if column.primary_key:
return column
return None
|
9c0b03beeafa28c2d7b4ac5e9512312ffb256f23
| 454,177 |
from typing import Optional
def iam_user_id(event: dict) -> Optional[str]:
"""
Returns the User ID (ARN) from IAM or None
"""
try:
return event["requestContext"]["identity"]["userArn"]
except (TypeError, KeyError):
return None
|
2de5c824b67f02621a7563eecd383b8ec4db2954
| 316,062 |
import base64
def rest_md5_from_proto(md5):
"""Convert from the gRPC/proto representation of MD5 hashes to the REST representation."""
return base64.b64encode(md5).decode("utf-8")
|
d5f3e254f7a41cd9b7fad286389a1e8695d8a0bd
| 400,563 |
def has_response(response, version='0.0.0'):
"""
Check for none response for anything that you would normally expect to return an entity.
:param response:
:param version:
:return:
"""
if 'id' not in response:
try:
return has_response(response[0])
except:
return False
elif response['id'] == 0:
return False
else:
return True
|
7e625352876669052f2a68cd55d02ce44a674837
| 129,783 |
def get_total(alist, digits=1):
"""
get total sum
param alist: list
param digits: integer [how many digits to round off result)
return: float
"""
return round(sum(alist), digits)
|
27a26f21e74036a56796f1cc05fcfb88efa41a45
| 41,883 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.