content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def rotate_point_by_angle(origin, point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
"""
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy... | df96d8ce6af8b94bd39774ca30620bebad897130 | 594,657 |
import click
def common_mqtt_options(func):
"""Supply common mqtt gateway options."""
func = click.option(
"-r",
"--retain",
is_flag=True,
default=False,
help="Turn on retain on published messages at broker.",
)(func)
func = click.option(
"--out-prefix",... | 13fd8d74add94fa3f0f5cf58f4ebedab965d9e84 | 594,662 |
import time
def agent_dies(agent, nsproxy, timeout=1.0):
"""
Check if an agent dies within a given period.
Parameters
----------
agent : str
Name of the agent, as registered in the name server.
nsproxy : NSProxy
Proxy to the name server.
timeout : float
After this ... | e8219a05f95299d759d1358ca70b53ef3b783615 | 594,664 |
def utility(z,psi):
""" Calculates utility of given some assets, z, and relative risk aversion, psi.
Args:
z (float): the agents assets
psi (float): the agents relative risk aversion
Returns:
(float): utility of assets
"""
return (z**(1+psi))/(1+psi) | 22d6eef07ae68b6c95d7a7c90c3ae306f9fbcfed | 594,665 |
import math
def _MeanAndStddev(data, precision=4):
"""Computes mean and standard deviation from a list of numbers.
Args:
data: A list of numeric values.
precision: The integer number of decimal places to which to
round the results.
Returns:
A 2-tuple (mean, standard_deviation), in which each... | 0795dff0c62a7b9304ec8c6b8586086ae7847c48 | 594,669 |
from datetime import datetime
from dateutil import tz
def calc_days_from_2dates_diff(prev_date):
"""Calculates the difference bewteen today and a previous date in days."""
utc_time_now = datetime.utcnow().replace(tzinfo=tz.tzutc())
# ndays_back = utc_time_now - timedelta(days=prev_date)
ndays_back = ... | 6772db8f601f77a190d51ea0b8614a447d0b4120 | 594,670 |
def clitable_to_dict(cli_table):
"""Converts TextFSM cli_table object to list of dictionaries."""
objs = []
for row in cli_table:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[cli_table.header[index].lower()] = element
objs.append(temp_dict)
return ob... | 5ac64986868b7a8a0145918179ea2016dc2a5157 | 594,672 |
def _intersect(C, n, weights, IC, pt0, pt1, tol):
"""
Find the intersection points of a half-closed simplex
(pt0, pt1] and IC constraints.
Parameters
----------
C : ndarray(float, ndim=2)
The 4 by 2 array for storing the generated points of
one action profile. One action profile... | 070537175575597a9bcd134b186175956f69e3b7 | 594,675 |
def palindrome(value: str) -> bool:
"""
This function determines if a word or phrase is a palindrome
:param value: A string
:return: A boolean
"""
value = "".join(value.split()).lower()
if len(value) <= 1:
return True
if value[0] != value[-1]:
return False
return pali... | 3f089c5e0330ff4b4b340c5ede07a9531805b63c | 594,676 |
def check_accessible_cases(item, user):
"""Check if all cases of a cohort are accessible for a user."""
if user == item.user or user.is_superuser:
return True
return set(item.cases.filter(project__roles__user=user)) == set(item.cases.all()) | e8a83e4691f4f1d661422f3a10a226d0c37b3056 | 594,678 |
def auto_intercept(with_intercept, default):
"""A more concise way to handle the default behavior of with_intercept"""
if with_intercept == "auto":
return default
return with_intercept | 1c11eef225cf5a75c78a306ad134ffda3c231100 | 594,683 |
def h_eval(C, n, x):
"""
Evaluate h_n(x), the n-th normalized hermite polynomial. It is assumed
that the coefficients have already been multiplied by sqrt(n!) to make the
polynomials orthonormal.
"""
xpow = 1.0
sm = C[n, 0]
for i in range(1, n+1):
xpow = xpow * x
sm += C... | e4fb5151fe5677ee2e65b15ca184beb81f7da391 | 594,689 |
def interval_intersection(min1, max1, min2, max2):
"""
Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval,
or None if they do not overlap.
"""
left, right = max(min1, min2), min(max1, max2)
if left < right:
return left, right
return None | 5c39ce275803413f53cde8b79187574195f4c218 | 594,690 |
from typing import List
def _certificate_to_oct(num_vertices: int,
certificate: List[int]) -> List[int]:
"""Transform a VC certificate into an OCT certificate
Parameters
----------
num_vertices : int
The number of vertices present in the VC formulation graph. This grap... | 233a36ca9f7a4ed59152b2930686117f518d8e79 | 594,692 |
import random
def die_roll(olist):
"""
olist is a list of tuples, each tuple containing the outcome name and the frequency of that outcome
"""
total = sum([tup[1] for tup in olist])
r = random.randint(0, total)
count = 0
outcome = olist[0][0]
for t in olist:
count += t[1]
... | 5b931b01add87d191d4d1ebdb407a2c5294e6534 | 594,699 |
def head(xs):
"""
head :: [a] -> a
Extract the first element of a list, which must be non-empty.
"""
return xs[0] | 9005eb081f9d6050a93b9da74beef4499e9fa3d2 | 594,700 |
def to_arcgis_date(datetime_obj):
""" Converts a datetime to an ArcGIS timestamp.
:param datetime_obj: A datetime.datetime
:return: An int expressing the same date/time as an ArcGIS timestamp.
"""
if datetime_obj is not None:
return datetime_obj.timestamp() * 1000
return None | 8ab55beddcdffa154a86c74732fe5d6f9a303cba | 594,701 |
import re
def parse_idx_range(s):
"""Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints."""
range_re = re.compile(r'^(\d+)-(\d+)$')
m = range_re.match(s)
if m:
return list(range(int(m.group(1)), int(m.group(2)) + 1))
vals = s.split(',')
... | 27c1f0b2d31c753463bf6066968c910167c54848 | 594,708 |
def add(one, two):
"""Helper function for adding"""
return(one + two) | 8342836f5ba5db597295459dbba5180f6799ce58 | 594,710 |
def default_options(endpoint_path):
"""Returns the default options with the given endpoint path."""
return {
'endpoint_path': endpoint_path,
'api_key': None,
'custom_user_agent': None,
"timeout_seconds": None,
} | 946ad965a8d1f79586e43e7abe8229e6683511db | 594,711 |
import calendar
def monthdelta(date, delta):
""" Calculate a date x months from now, in the past or in the future """
m, y = (date.month + delta) % 12, date.year + (date.month + delta - 1) // 12
if not m:
m = 12
d = min(date.day, calendar.monthrange(y, m)[1])
return date.replace(day=d, mon... | d400aca28d81ed800fddaaa4f60704dfb541f178 | 594,714 |
def deep_merge(a, b):
"""
Merges b into a, recursively.
This is a special recursive dictionary merge, made specifically for docker compose files.
If a and b are both dictionaries, their keys are recursively merged. Keys in b write over keys in a.
If a and b are both lists, the elements of b are adde... | 11ece71708cfa8404efd6dd2ba471b4f3744b898 | 594,718 |
import secrets
import string
def create_test_set(n):
"""Create a test set of random strings.
Input size of lexicon.
Output list of words."""
test_set = []
for i in range(n):
random_word = ''.join(secrets.choice(string.ascii_lowercase) for i in range(5))
test_set.append(random_word)... | 8f58c76a286bc4741b82b31665d92ad237a1450b | 594,719 |
import random
def randbytes(size):
"""Return a string of random bytes."""
return ''.join(chr(random.randint(0, 255)) for _ in range(size)) | 0faba2433d1015f8c83b169b88785bef31d83cbc | 594,725 |
from typing import Type
from typing import Any
def partialclass(cls: Type[Any], *base_args, **base_kwargs):
"""Builds a subclass with partial application of the given args and keywords."""
class _NewClass(cls):
def __init__(self, *args, **kwargs):
bound_args = base_args + args
bound_kwargs = bas... | dd4ec2d477f3ad202d095f3ec3d9e0b171c285bd | 594,726 |
def ninjaenc(s):
"""
Encodes string s for use in ninja files.
"""
return s.replace('$', '$$') | 62162e65d345279557068abcf1e98016f946ada9 | 594,727 |
def letter_counts(sentence: str) -> dict:
"""
returns the unique counts of letters in the specified sentence
:param sentence: the sentence
:return: dictionary of counts per letter that exists in the sentence
"""
letters_in_sentence = [c for c in sentence if c.isalpha()]
# use dictionary co... | f6407e02f0fe73c9d993898c2e6ee63388840f85 | 594,732 |
def split_byte(bs):
"""Split the 8-bit byte `bs` into two 4-bit integers."""
mask_msb = 0b11110000
mask_lsb = 0b00001111
return (mask_msb & bs[0]) >> 4, mask_lsb & bs[0] | e3908f68b9d615c7f76251e152bbad339e8b1925 | 594,733 |
def get_like_status(like_status, arg_1, arg_2):
"""
Fetches a string for a particluar like_status
args:
like_status(boolean): It's either a True for a like
or False for a dislike
arg_1(str)
arg_2(str)
Returns:
arg_1(str): Incase the like_st... | b8d975bf90386bf0f2fa3a3b96d3d3a83862f36b | 594,737 |
def extract_datestring (gcal_event):
""" Given a google calendar event dictionary,
grab either the datetime string or the date string.
"""
#print("gcal_event: {}".format(gcal_event))
try:
if 'dateTime' in gcal_event['start']:
retval = gcal_event['start']['dateTime']
... | 3fc16b696e9b80f70df6b8eaa10076589b08ad4c | 594,739 |
def calc_resize_with_apect(size, max_dimension):
"""
calculate new image size that preserves the aspect ratio but does not exceed the max dimension
size: tuple, current image size
max_dimension: int, dimension not to exceed
"""
w = size[0]
h = size[1]
# if min(size) > min_dimension:
... | c76062ff280d7b516d09c3dcd2428c01f21fe98d | 594,740 |
def select_atoms(mdsys):
""" Return the selection of atoms that are of interest in the simulation
"""
# Change this selection in case you have different lipids, and update the
# onehot encoder dictionary accordingly
asel = mdsys.select_atoms("resname DPPC or resname DOPC or resname DOPX or \
... | 5c61ca352cb2d4137125dd55622341438cb76a59 | 594,742 |
from typing import Tuple
def should_query_for_nodes_topology(**kwargs) -> Tuple[bool, bool]:
"""Check the user cli arguments to ascertain whether we should query for
nodes and the topology value of a deployment.
:returns: Whether we should query for nodes and topology
:rtype: bool, bool
"""
sp... | 496856c9de6eb8e88a6bc54985407ef024962716 | 594,743 |
def calculate_one_moving_and_one_stationary(
poly1, poly1_offset, poly1_velocity, poly2, poly2_offset
):
"""
Determine if the moving polygon will intersect the stationary polygon.
This is the simplest question. Given two polygons, one moving and one not,
determine if the two polygons will ever ... | ca5adc12a5671e46d3e6fadf12dc5218b0525cdf | 594,745 |
def reverse(input_list):
"""
Reverses a list
:param input_list: A list of strings (any list would work though)
:return: A list, in reverse order
"""
output_list = []
list_length = len(input_list)
for index in range(list_length-1, -1, -1): # Pay attention to the range here; why'd I ... | b19382c034de792735da018d0a9f30af2faf589f | 594,748 |
def hamming_distance(s1, s2):
"""Calculate the Hamming distance between two strings of equal lengths.
Raise ValueError if strings are of unequal length.
"""
if len(s1) != len(s2): raise ValueError('strings of unequal length')
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) | 1b49e48a14ff5af69564fe78f1720c531c6b0768 | 594,749 |
def sanitise(dic):
"""Adds underscores to keys in dictionary"""
new_dic = dict()
for key, value in dic.items():
new_dic["_{}".format(key)] = value
return new_dic | a070ac864667cceb0a9d7b7930453c3279600663 | 594,755 |
def reverse_truncatechars(string, start):
"""Inverse of truncate chars. Instead of the first x characters,
excludes the first nth characters.
"""
return string[start:] | ee3df2e3489ee4ba2c3f8ad154142093a54e45d8 | 594,757 |
def nullBasedArray(length):
"""
Returns an array with the given length filled with zeros
"""
array = []
for i in range (0,length):
array.append(0)
return array | 68df8950de1a8e36a67414e47ecbea53cc3dc404 | 594,759 |
def smallest_side(l, w, h):
"""Return the area of the smallest side of a box"""
return min([(l * w), (w * h), (h * l)]) | af22607775a4dee3034415f963d2916effee0587 | 594,760 |
def _index_no_throw(l, item, start_index=0):
"""Finds index of item in l, None otherwise."""
if item in l:
return l.index(item, start_index) + len(item)
return None | 2b94a89e49f42e13ce307db762e5199391da728c | 594,762 |
import inspect
def is_from_module(obj, module):
"""Return whether `obj` is from module `module`."""
mod = inspect.getmodule(inspect.unwrap(obj))
return mod is None or mod.__name__ == module.__name__ | 1ec842e353b0c81c32fd2d56c07b34ca24b139e5 | 594,764 |
def build_validator_call(path, ignore_headers=False, ignore_subject=True):
"""Build a subprocess command to the bids validator"""
# build docker call
command = ['bids-validator', '--verbose', '--json']
if ignore_headers:
command.append('--ignoreNiftiHeaders')
if ignore_subject:
com... | ec587426f7984885ad20db5430c460183af1fccb | 594,766 |
def single_label_s3(classifier, image_data):
"""
Classifies a single image, given the image data
Args:
classifier (ClassifierABC):
image_data (dict): With keys=['id', 'content']
Returns:
dict: With key=['id', 'labels']
"""
labels = classifier.get_image_labels_from_bytes(... | b0d0de415da53079bcb1a08b7b0350124fc825da | 594,774 |
def flatten(lol):
"""Returns a list of the contents of a list of lists."""
result = []
for sub in lol:
result.extend(sub)
return result | 9c67c483753258d417847d4534b1a3ed62901fef | 594,775 |
def average(A_matrices, B_vectors):
"""
Average over cost function matrices.
The cost functions contain the three objects of the cost function: A, B, C
A is a quadratic matrix (97x97), B a vector (d=97), and C is a constant.
In the end, we are interested in the best-fit charges Q which are the solution... | a30ab24be30d07340b1c8dd05a328a3f2b6ebc1a | 594,776 |
def ext(app):
"""Extension instance."""
return app.extensions['flask-webpackext'] | 636c211a6cca36279b09132e819dee402fde83ca | 594,779 |
def is_valid_subnet_ID(subnet_ID, subnets):
"""
Check if given subnet_ID is a valid subnet given subnet list
"""
if type(subnet_ID) is not int or subnet_ID < 1 or subnet_ID > len(subnets):
return False
return True | f9421a07cf400d1af2de919b5654e8da02de02df | 594,780 |
def _handleLookupType2Format1(subtable):
"""
Extract a kerning dictionary from a Lookup Type 2 Format 1.
"""
kerning = {}
coverage = subtable.Coverage.glyphs
valueFormat1 = subtable.ValueFormat1
pairSets = subtable.PairSet
for index, leftGlyphName in enumerate(coverage):
pairSet ... | b7b4f51604f84e943a6c4d3a91197832a0a8db12 | 594,781 |
import torch
def cuda(args, tensor):
"""
Places tensor on CUDA device (by default, uses cuda:0).
Args:
tensor: PyTorch tensor.
Returns:
Tensor on CUDA device.
"""
if args.use_gpu and torch.cuda.is_available():
return tensor.cuda()
return tensor | cfc3b4dfa89f61729560988d259469b2d96a0db8 | 594,786 |
def form_get_request_to_list_songs_of_playlist(playlist_id, api_key, page_token='', max_results='50'):
"""
Form get request to list all playlist items of a certain playlist.
"""
get_request = 'https://www.googleapis.com/youtube/v3/playlistItems/?maxResults={}&playlistId={}&part=snippet%2CcontentDetails&key={}... | b304ce65c5c570135f385189d645a75f6217a960 | 594,789 |
import re
def _construct_new_key(name, units=None):
"""Construct an MDF safe key from the name and units"""
to_replace = ["/", "\\", "*", "^", "#", " ", "\n", "\t", ",", ".", ")", "(", "'", "`", "-"]
to_remove = ["$", "{", "}"]
cat = name
if units:
cat = "_".join([name, units])
for c ... | 4a3fc6079a60afc2526ff156a17a8943c19ffdd5 | 594,790 |
def get_kernel_rpm_release(rpm):
"""
Get the release of a kernel RPM as an integer.
:param rpm: An instance of an RPM derived model.
"""
return int(rpm.release.split('.')[0]) | c81e78457e70da29a2b2a4e8d13eb65ef4a16a10 | 594,794 |
def remove_nullchars(block):
"""Strips NULL chars taking care of bytes alignment."""
data = block.lstrip(b'\00')
padding = b'\00' * ((len(block) - len(data)) % 8)
return padding + data | 288700f97bcdef96c78ac6086754175182cb0f1a | 594,795 |
import click
import functools
def with_dryrun(f):
"""Wrap a command to add the option dryrun, which if True means not to overwrite the files."""
@click.option(
"--dryrun/--no-dryrun",
default=False,
help="If True, do not actually write files, just log the output. Defaults to False.",
... | 180e52ce708a5b59466e64f5c4c51af40192114d | 594,797 |
def public(func):
"""
Decorator that marks a route as not needing authentication.
This needs to wrap the inner function, or it won't take effect, e.g.
@app.route(...)
@public
def route...
"""
func._public = True
return func | 3c533da30d9cef47c4fed49046d0efbcae5a3689 | 594,800 |
def set_date(cdate, is_first_loop, is_force_read_cache, arg_date):
"""set date given context
(read cache, get today date or set date argument)
Parameters
----------
is_first_loop : bool
true on first calendar call
is_force_read_cache : bool
force date from cache
arg_date : ... | 8ec3e542657497b71471bc9755d99191438aa530 | 594,801 |
def view_is_transient(view):
"""Return whether a view can be considered 'transient'.
For our purpose, transient views are 'detached' views or widgets
(aka quick or input panels).
"""
# 'Detached' (already closed) views don't have a window.
window = view.window()
if not window:
retu... | b6c238c568b3298ec15d53a002604098a26d4a79 | 594,804 |
def check_aliases(kwargs, aliases, default=None):
"""Check a dictionary input for a list of potential key aliases.
Parameters
----------
kwargs : dict
Dictionary to check for elements labelled with possible aliases.
aliases : list
List of possible key value labels.
default
... | 35a9708ff1e2f513fe2ce210e77c6bd05ba127bc | 594,807 |
def getBackgroundColor(im):
"""
Detect the background color of an image.
The color is assumed to be the the most common
pixel color along the border of the image.
"""
borderPixels = []
borderColors = []
for x in range(im.size[0]):
# Get pixel along top
px = im.getpixel((x... | cac58748e933324f9fbd7160b10bee39a1997ea5 | 594,809 |
def format_bytes(nbytes):
"""Format ``nbytes`` as a human-readable string with units"""
if nbytes > 2 ** 50:
return "%0.2f PiB" % (nbytes / 2 ** 50)
if nbytes > 2 ** 40:
return "%0.2f TiB" % (nbytes / 2 ** 40)
if nbytes > 2 ** 30:
return "%0.2f GiB" % (nbytes / 2 ** 30)
if nb... | 6996b7632dcd638edb9ae9ef1d3168e583bc87ff | 594,818 |
from typing import List
def split_params(param: str, delimiter=",", maxsplit=-1) -> List[str]:
"""Splits the string parameter of a function and removes trailing/leading empty spaces from each resulting string.
:param param: The string to be split.
:param delimiter: The delimiter to be used for the split.... | 539c575995f3af267978a7330b15cc6b15b1a55f | 594,820 |
def glyphNameToFileName(glyphName, glyphSet):
"""Default algorithm for making a file name out of a glyph name.
This one has limited support for case insensitive file systems:
it assumes glyph names are not case sensitive apart from the first
character:
'a' -> 'a.glif'
'A' -> 'A_.glif'
'A.alt' -> 'A_.a... | 3230b7ac0f185e02ecb4fcf12b55af0847f7243e | 594,821 |
def order(A):
"""Returns the order of the matrix.
Args
----
A (compulsory)
A matrix.
Returns
-------
tuple
the order of the given matrix in the form (rows, columns).
"""
return (len(A), len(A[0])) | 448cb5423bff369962b0c200e0a2ead18098c43e | 594,822 |
import importlib
def safe_import(module):
"""
Try to import a module by (dotted) name and return None if
the import fails by any reason.
"""
try:
return importlib.import_module(module)
except:
return None | 92c8fcbbfb7cfd71e5acc6214324633860905003 | 594,824 |
def get_link_text(link):
"""
Return text of <a> element: either its string contents or the 'alt'
of <img> tags inside.
"""
txt = ' '.join(link.xpath('string()').extract())
if not txt:
txt = ' '.join(link.xpath('.//img/@alt').extract())
return txt | 563ebd6a8177f7c2fa8fd7de077c917803776978 | 594,825 |
import hashlib
def compute_checksum(checksums):
"""
Checksum created by sorting alphabetically then concatenating first layer of bundles/objects.
Args:
checksums (list): list of checksums from the first layer of bundles and objects
Returns:
md5 checksum
"""
checksums.sort()
... | 032a950b3de3c2193e021a34b178434ad62d46c0 | 594,829 |
def locateTimeline(profiles, txnId):
"""
Performs a lookup of timeline object with txnId
:param profiles: profiles holding a collection of timelines
:param txnId: txnId of the timeline to lookup
"""
for profile in profiles:
for timeline in profile.current.timelineCollection:
if timeline.txnId ==... | e89cbd1b392cd56a9a8533da2c1421045a61cea6 | 594,834 |
import torch
def _lambertw_winitzki_approx(z: torch.Tensor) -> torch.Tensor:
"""Compute an approximation of the lambertw function at z.
Args:
z: The input to the lambertw function.
Returns:
An estimated value of lambertw(z).
"""
log1pz = torch.log1p(z)
return log1pz * (1. - t... | 1ecf623b7ee6124b8d19e5bc5c222476299f3fcf | 594,835 |
def _odd_vertices_of_MST(M, number_of_nodes):
"""
Returns the vertices having Odd degree in the Minimum Spanning Tree(MST).
"""
odd_vertices = [0 for i in range(number_of_nodes)]
for u, v, _ in M:
odd_vertices[u] = odd_vertices[u] + 1
odd_vertices[v] = odd_vertices[v] + 1
odd_ver... | 8bbcf99326c5038385115d534b28066a5b12992c | 594,838 |
import torch
def mult(x1, x2):
"""
returns product of complex torch tensors x1 and x2
"""
y = torch.empty_like(x1)
y[..., 0] = x1[..., 0]*x2[..., 0] - x1[..., 1]*x2[..., 1]
y[..., 1] = x1[..., 0]*x2[..., 1] + x1[..., 1]*x2[..., 0]
return y | caa2dade1aa8c964a32b307a73578d2c336b9851 | 594,842 |
def get_detection_rate(stats):
"""Get detection rate as string."""
return f'{stats["malicious"]}/{sum(stats.values())}' | 1b294eee3b2ddafddaf4851d5a256e63b4b80705 | 594,845 |
import yaml
def open_inventory(filename):
"""
Open YAML-file, get inventory from there and close
Args:
filename: name of YAML-file
Returns: inventory (dict)
"""
with open(filename) as file:
inv = yaml.safe_load(file.read())
return inv | 759889d3c5a3d4724be08a2ce46df133f7eda96c | 594,850 |
def vertical_link_count(shape):
"""Number of vertical links."""
assert len(shape) == 2
return (shape[0] - 1) * shape[1] | c195322455064385f8c178866bfbc1adecc5649b | 594,852 |
def voter_address_save_doc_template_values(url_root):
"""
Show documentation about voterAddressSave
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
... | 8bf59c4b48f9da6ef150fd8fbfea9da9c2659692 | 594,858 |
def request_url(api_key, on_date, zipcode):
"""Form the base request url for weather underground
:param api_key: str weather underground API key
:param on_date: datetime.date date to query
:param zipcode: str zip code to query
:return: str query url
"""
template = ("http://api.wunderground.... | 81fa772d0d4eb276a85322d531464c218fb90fe5 | 594,860 |
def secsToNearestMilli(value):
"""\
Return value converted to the nearest number of milliseconds
:param value: seconds as a floating point number
:return: value expressed in integer number of milliseconds (rounded)
"""
return int(round(value * 1000)) | 667b1c649bf1c85a0de4481d5c26cc0a93b7ca80 | 594,867 |
import typing
def deep_get(
obj: typing.Union[typing.Mapping, typing.Sequence],
key: typing.Sequence[typing.Union[str, int]],
default=None,
):
"""
Utility to get deeply nested element in a list, tuple or dict without
resorting to some_dict.get('k1', {}).get('k2', {}).get('k3', {})....etc.
... | c9d589520d6cbe83de08c16ee6be7e2fc7977cde | 594,871 |
def str_rstrip(text):
"""Strips whitespaces from the end of the text."""
return text.rstrip() | 95136f1153d3710703a5a22f34bc91e83d8da1d7 | 594,872 |
import collections
def topological_sort(edges):
"""
edges: {<node>: [<target-node>, ...]}
Returns a list of node IDs in (a) topological order.
"""
MARK_UNVISITED = 0
MARK_TEMPORARY = 1 # Visited (but not all children visited yet)
MARK_PERMANENT = 2 # Node and all its reach... | 1ba5d8399d550f28eebb72225bc6004a365268c9 | 594,874 |
def dataset_stats(churn_data,metric_cols,save_path=None):
"""
Take basic stats of the data set. Saving it is optional.
:param churn_data: Pandas data frame containing the data set
:param metric_cols: Columns which are metrics (and will have stats taken)
:param save_path: If specified, will save to ... | a4a46d68b720a43cad95bdb8766d8710fb2ccef4 | 594,875 |
import hashlib
def sha1_hash(value):
"""Calculates the SHA1 has of a string
:arg:
value (str): String to be hashed
:return
(str): SHA1 hash
"""
# add salt to the value
salt = "!@3`tHy:'hj6^&7m4qG9[6"
salted_value = value + salt
# ... | 2c4226f0475eeec1baca84b3d844635e721e0741 | 594,877 |
import re
def re_flags_to_string(flags: int=0) -> str:
"""
Turn a set of `re` flags into a string suitable for inclusion in a regex.
>>> import superexpressive as se
>>> se.re_flags_to_string(re.A)
'(?a)'
>>> import superexpressive as se
>>> se.re_flags_to_string(re.IGNORECASE | re.LOCAL... | acc5dfb8b84fe73634fa7434c4aaeae43ab1c21f | 594,885 |
def _from_hass_temperature(temperature):
"""Convert Home Assistant color temperature units to percentage."""
return (temperature - 154) / 346 | 9f8b19fca0537de337917958e5be353ad6b7f97f | 594,889 |
def u_component(y,x):
"""Return the component of uncertainty in ``y`` due to ``x``
:arg y: :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex` or :class:`.UncertainArray`
:arg x: :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex` or :class:`.UncertainArray`
If ``x`` and ... | 72ca3ee2d98d719d85519a02127ebbfeba485f6f | 594,893 |
def build_url(city: str, unit: str, key: str) -> str:
"""
Build API call url.
Parameters:
city (str): City name.
unit (str): Units system (metric or imperial).
key (str): API key.
Returns:
full_url (str): API call URL.
"""
api_url = 'http://api.openweathermap.org/data/2.5/weather?q='
if unit == 'm':
unit... | d1e02d37717909dfbdeb936bd5a64a1e7e97873c | 594,898 |
def _parse_placekey(placekey):
"""
Split a Placekey in to what and where parts.
:param placekey: Placekey (string)
:return: what (string), where (string)
"""
if '@' in placekey:
what, where = placekey.split('@')
else:
what, where = None, placekey
return what, where | c50b40c6ef249351207be774be49b9fc669ab817 | 594,903 |
import copy
def deep_update(base, updates):
"""
Update one recursive dict with values from another.
Modified from:
http://www.xormedia.com/recursively-merge-dictionaries-in-python/
Special case: If an updated value is None,
then the whole subtree is removed from the original dict.
"""
... | 971956cf40102bcb150ccc18c5d036f8d8be8bc1 | 594,906 |
def tech_level(template_group):
"""Returns the maximum tech level of the template group."""
tl = 0
for template in template_group:
for build_order in template:
tl = max(tl, build_order.unit.tech_level)
return tl | fd6100f21047f6204fb2f3aa44941f2d71bf740a | 594,910 |
import re
def pull_zip(address):
"""Isolates and formats zipcode of address, if available"""
try:
zipcode = re.findall(r"([a-zA-Z]{2,}) (\d{5})", address)[0][1]
except:
zipcode = ""
return zipcode | 3ff351dad0e15d8e5969008edce55170fe9ffa94 | 594,912 |
def backtrace(node):
"""
Backtrace according to the parent records and return the path.
(including both start and end nodes)
"""
path = [(node.x, node.y)]
while node.parent:
node = node.parent
path.append((node.x, node.y))
path.reverse()
return path | 2c3c7cd698d915461f3ffd30fa7a328ff998b894 | 594,913 |
def remove_phrases(words: list) -> list:
"""
Removes phrases from Synsets. Phrases are expressions with multiple words linked with _.
:param words: The list of words in a synset
:return: All the words that are not phrases or parts of phrases.
"""
# We need to sanitize synsets from phrasal expres... | e93473076554bd852560b2357df7d0b274b68ffe | 594,918 |
def tree_label(tree):
"""Returns the label on the root node of tree."""
if isinstance(tree, list):
return tree[0]
else:
return tree | 89d6cc4fee8eb0ba7256a4075cdab6d4027cc64c | 594,920 |
from pathlib import Path
from bs4 import BeautifulSoup
def _parse_html(file_path: Path) -> list:
"""
Parse the table from the HTML.
Keyword arguments:
file_path -- the Path to the HTML file
Returns: a list of lists of strings
"""
# Get the HTML
html = open(file_path).read()
# Pa... | 2edbe5aa94752e04a6c728c1ad2a092df1fd12a6 | 594,921 |
def _is_power_of_2(x):
"""
Returns True if `x` is a power of 2.
"""
# see:
# https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
return x != 0 and (x & (x - 1)) == 0 | 219488c8703b6fcc09603f8b24f3d13bfdb0ac1d | 594,924 |
def parse_j2000(name):
"""Takes the J2000 name stored in the results and returns it in a format astropy can understand."""
return ' '.join([name[1:3], name[3:5], name[5:7], name[7:10], name[10:12], name[12:]]) | 617b4c95b42475096c736afd0fedce7e6f191e36 | 594,927 |
def STR_LEN_CP(expression):
"""
Returns the number of UTF-8 code points in the specified string.
https://docs.mongodb.com/manual/reference/operator/aggregation/strLenCP/
for more details
:param expression: The string or expression of the string
:return: Aggregation operator
"""
return {'... | 9b119584df3b94e3df99bbf037c45c9ec429ddce | 594,929 |
def get_atom_indices_from_zmat_parameter(param):
"""
Get the atom indices from a zmat parameter.
Examples:
'R_0_2' --> ((0, 2),)
'A_0_1_2' --> ((0, 1, 2),) corresponding to angle 0-1-2
'D_0_1_2_4' --> ((0, 1, 2, 4),)
'R_0|0_3|4' --> ((0, 3), (0, 4))
'A_0|0|0_1|1|1_2|... | 60452bc42d7e2b9d534b47927429d813ed23fd58 | 594,930 |
def reverse_crc32_4bytes(crc: int,
poly=0xedb88320, invpoly=0x5b358fd3,
initxor=0xffffffff, finalxor=0xffffffff) -> int:
"""
"Reverses" a CRC32 operation computed over a 4-byte (32-bit) input.
This implementation is just a simplification of Listing 6 from ... | e3e1424cd78acc839da49c854421751ac3805c6c | 594,932 |
def mongodb_uri(mongodb_url, mongodb_port, db_name='tuplex-history'):
"""
constructs a fully qualified MongoDB URI
Args:
mongodb_url: hostname
mongodb_port: port
db_name: database name
Returns:
string representing MongoDB URI
"""
return 'mongodb://{}:{}/{}'.forma... | a7a7ab645d6490669907f1f016c116cf65d75980 | 594,937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.