content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import csv
def parse_csv_dict(filename):
""" Parses csv file and returns header columns and data. """
data = []
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
return reader.fieldnames, data | 8ffc34a6906cf59926ef618076732eb24f0561fa | 17,334 |
def combineRulesWithOperator(listOfRules, operator):
"""
Takes a list of rules and makes an overall rule that ties them together
with the AND or the OR operator
Parameters
----------
listOfRules: list
A list of string representation of rules
operator: str
Should be either AN... | 7dfc4988f9c56e05318704a7bd6990fc9b00d604 | 17,335 |
def make_product(digits, k, start):
"""
Compute k numbers product from start position.
:param digits:
:param k:
:param start:
:return: (product, next_start)
"""
index = 0
product = 1
while index < k and start + index < len(digits):
if digits[start + index]:
pr... | caa4b9da545c7c575291ed2af1ae2579a681930d | 17,340 |
def _get_image_offsets(width, height, segments_x, segments_y):
"""
Gets offsets for the segments
:param width: map width
:param height: map height
:param segments_x: number of x segments
:param segments_y: number of y segments
:return: lists of x offsets, lists of y offsets
"""
offse... | 97fbde70318ca592643f99af332cfa1862da00f0 | 17,346 |
import torch
def compute_N_L(lambda_L, Gram_L, G_out):
"""Compute N_L using KRR
Parameters
----------
lambda_L: float
Last layer regularization parameter
Gram_L: torch.Tensor of shape (n_samples, n_samples)
Last layer Gram matrix
G_out: torch.Tensor of shape (n_sam... | 53ab4781898ae262e491d5a6ca577bcdd7fa8144 | 17,347 |
def Mceta(m1, m2):
"""Compute chirp mass and symmetric mass ratio from component masses"""
Mc = (m1*m2)**(3./5.)*(m1+m2)**(-1./5.)
eta = m1*m2/(m1+m2)/(m1+m2)
return Mc, eta | fa55e1cfc669f3e180aed1a3cc838ed82147ddbc | 17,349 |
def split_sents(notes, nlp):
"""
Split the text in pd.Series into sentences.
Parameters
----------
notes: pd.Series
series with text
nlp: spacy language model
Returns
-------
notes: pd.DataFrame
df with the sentences; a column with the original note index is added
... | 0aae3af46a2a0c29fff9c3bb5725b0ddcb8ed796 | 17,354 |
def _is_header_line(line: str) -> bool:
"""
Determine if the specified line is a globals.csv header line
Parameters
----------
line : str
The line to evaluate
Returns
-------
is_header_line : bool
If True, `line` is a header line
"""
return "kT" in line | 06f8ff10deeac60e92b2fd92059873d5abafa367 | 17,358 |
from typing import Set
def parse_modes(modes: Set[str]) -> Set[str]:
"""A function to determine which modes to run on based on a set of modes potentially containing blacklist values.
```python
m = fe.util.parse_modes({"train"}) # {"train"}
m = fe.util.parse_modes({"!train"}) # {"eval", "test", "inf... | 312467ea55d3d254f7b6cd601a2e8b999539508f | 17,359 |
def _patch_center(patch, orient='v'):
"""
Get coordinate of bar center
Parameters
----------
patch : matplotlib patch
orient : 'v' | 'h'
Returns
-------
center : float
"""
if orient not in 'v h'.split():
raise Exception("Orientation must be 'v' or 'h'")
if ori... | 235da0e3fdca40d62dd0313d8e8a500a7c533b8d | 17,361 |
import hashlib
def get_sha256_of_string(the_string):
"""Returns SHA-256 hash for given string."""
new_hash = hashlib.new("sha256")
new_hash.update(bytes(the_string, "utf-8"))
return new_hash | 1657bd433e62c9342d5474fae472fc9dff649575 | 17,364 |
import re
def decamelize(s):
"""Decamelize the string ``s``.
For example, ``MyBaseClass`` will be converted to ``my_base_class``.
"""
if not isinstance(s, str):
raise TypeError('decamelize() requires a string argument')
if not s:
return ''
return re.sub(r'([a-z])([A-Z])', r... | fc30254742bcc79047dd6803d0d7b87c951a9f10 | 17,365 |
def match_with_batchsize(lim, batchsize):
"""
Function used by modify_datasets below to match return the integer closest to lim
which is multiple of batchsize, i.e., lim%batchsize=0.
"""
if lim % batchsize == 0:
return lim
else:
return lim - lim % batchsize | c37226946c51144df6192adeaf265326ee3bb701 | 17,376 |
def superset_data_db_alias() -> str:
"""The alias of the database that Superset reads data from"""
return 'superset-data-read' | c6bab8ae745f915c442145bbc7c4bcffa4141310 | 17,380 |
def _fully_qualified_typename(cls):
"""Returns a 'package...module.ClassName' string for the supplied class."""
return '{}.{}'.format(cls.__module__, cls.__name__) | f290a5fb3394f151476f5cf3b4785c5935e942b1 | 17,387 |
def user_prompt(prompt_string, default=None, inlist=None):
"""
Takes a prompt string, and asks user for answer
sets a default value if there is one
keeps prompting if the value isn't in inlist
splits a string list with commas into a list
"""
prompt_string = '%s [%s]: ' % (
... | 5879c8cd7853426d9c94b763292f6b04e9f26e78 | 17,388 |
import re
def remove_links(text):
"""
Method used to remove the occurrences of links from the text
Parameters:
-----------------
text (string): Text to clean
Returns:
-----------------
text (string): Text after removing links.
"""
# Removing all the occurrences of l... | 0bf0208459f0c93e7bac2848476959791369b5c0 | 17,395 |
def rgb_to_hsl(rgb_array):
"""!
@brief Convert rgb array [r, g, b] to hsl array [h, s, l].
@details RGB where r, g, b are in the set [0, 255].
HSL where h in the set [0, 359] and s, l in the set [0.0, 100.0].
Formula adapted from https://www.rapidtables.com/convert/color/... | 2c197b7966f5248566fdff41a62bf3f89c222c48 | 17,396 |
def logstash_processor(_, __, event_dict):
"""
Adds @version field for Logstash.
Puts event in a 'message' field.
Serializes timestamps in ISO format.
"""
if 'message' in event_dict and 'full_message' not in event_dict:
event_dict['full_message'] = event_dict['message']
event_dict['m... | f395bc7e4a7c09cdbe9ef29c3dbfdd45a448c21e | 17,400 |
def normalise_series(series):
"""Normalise a Pandas data series.
i.e. subtract the mean and divide by the standard deviation
"""
ave = series.mean()
stdev = series.std()
return (series - ave) / stdev | 97d53c0697a56e5ab559d2564c5d7386125ed254 | 17,402 |
def is_empty_placeholder(page, slot):
"""A template filter to determine if a placeholder is empty.
This is useful when we don't want to include any wrapper markup in our template unless
the placeholder unless it actually contains plugins.
"""
placeholder = page.placeholders.get(slot=slot)
retur... | 032f6e1d038a10e0f6c5459648dcabaf7e4c0259 | 17,404 |
def anti_join(df1, df2, **kwargs):
"""
Anti-joins two dataframes.
:param df1: dataframe
:param df2: dataframe
:param kwargs: keyword arguments as passed to pd.DataFrame.merge (except for 'how'). Specifically, need join keys.
:return: dataframe
"""
return df1.merge(df2, how='left', ind... | 6fdc7481da6728b51549c072879204a6c3d2bcd6 | 17,410 |
import math
def get_n(k, e, n_max):
"""
TS 38.212 section 5.3.1
"""
cl2e = math.ceil(math.log2(e))
if (e <= (9/8) * 2**(cl2e - 1)) and (k / e < 9 / 16):
n1 = cl2e - 1
else:
n1 = cl2e
r_min = 1 / 8
n2 = math.ceil(math.log2(k / r_min))
n_min = 5
n = max(min(n1, n2... | 4129821ac4c89c47d8c5b4391a77da83cfee2505 | 17,414 |
def architecture_is_64bit(arch):
"""
Check if the architecture specified in *arch* is 64-bit.
:param str arch: The value to check.
:rtype: bool
"""
return bool(arch.lower() in ('amd64', 'x86_64')) | 4303a53c3d1c8c1e844593aed3203dbedb448d61 | 17,415 |
import re
def match(text, pattern, limit = -1):
"""
Matches all or first "limit" number of occurrences of the specified pattern in the provided text
:param text: A String of characters. This is the text in which we want to find the pattern.
:param pattern: The pattern to look for. Expected to be a reg... | 656c49ebd197e538acd1c57eb4bc1daf98e5639a | 17,416 |
def _getVersionTuple(v):
"""Convert version string into a version tuple for easier comparison.
"""
return tuple(map(int, (v.split(".")))) | 57d6c1edbfb2ec66bfcc875fe511357266ffc816 | 17,421 |
def to_ssml(text):
"""Adds SSML headers to string.
"""
return '<speak>'+ text + '</speak>' | 0f2fda09507e09c5fdf64d5df2e50630b26629ec | 17,424 |
def remove_headers(markdown):
"""Remove MAINTAINER and AUTHOR headers from md files."""
for header in ['# AUTHOR', '# MAINTAINER']:
if header in markdown:
markdown = markdown.replace(header, '')
return markdown | 5e25c86c72819e42d09459d77e57fa3267748797 | 17,425 |
import time
import logging
def timed_func(process_name):
"""
Adds printed time output for a function
Will print out the time the function took as well as label this output with process_name
:param process_name: human name of the process being timed
"""
def decorator(f):
def wrapper(*a... | e07c9b9a72df8b06308de0812d07428cf18af325 | 17,426 |
def is_start_byte(b: int) -> bool:
"""Check if b is a start character byte in utf8
See https://en.wikipedia.org/wiki/UTF-8
for encoding details
Args:
b (int): a utf8 byte
Returns:
bool: whether or not b is a valid starting byte
"""
# a non-start char has encoding 10xx... | 8d27198671436c4e9accd80198dfe934c43f679b | 17,427 |
def get_s3item_md5(item):
"""
A remote item's md5 may or may not be available, depending on whether or
not it was been downloaded. If a download hasn't occurred, the checksum
can be fetched using the files HTTP ETag.
"""
if item.md5 is not None:
return item.md5
else:
# Remove... | 121c2f3b5d2159e23f37a0770b54e818a7d712bd | 17,429 |
from typing import List
def list_params(pop: list, gen: int, lamarck: bool, multicore: bool,
**extra_params: dict) -> List:
"""
Internal function to list execution parameters.
For advanced users only.
Parameters
----------
pop : list
List of individuals.
gen : int... | d08629029f24a85df1adaeeb3db865c2b4a9507f | 17,430 |
import re
def isdatauri(value):
"""
Return whether or not given value is base64 encoded data URI such as an image.
If the value is base64 encoded data URI, this function returns ``True``, otherwise ``False``.
Examples::
>>> isdatauri('data:text/plain;base64,Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIH... | 43a50554c17b1fd180a9234f2a4631689f14c823 | 17,431 |
def list_all_items_inside(_list, *items):
"""
is ALL of these items in a list?
"""
return all([x in _list for x in items]) | 5f7f2b93d966a7e7fffeede3924a7c86309ef90f | 17,433 |
def outer(x, y):
"""Compute the outer product of two one-dimensional lists and return a
two-dimensional list with the shape (length of `x`, length of `y`).
Args:
x (list): First list, treated as a column vector. 1 dimensional.
y (list): Second list, treated as a row vector. 1 dimensional.
... | 24f912d4a3152be96d8656f5a387fa526320fd19 | 17,435 |
def _get_step_inout(step):
"""Retrieve set of inputs and outputs connecting steps.
"""
inputs = []
outputs = []
assert step.inputs_record_schema["type"] == "record"
for inp in step.inputs_record_schema["fields"]:
source = inp["source"].split("#")[-1].replace("/", ".")
# Check if ... | d2cc2002792b83d01bcdb7566332c8f37c0aae99 | 17,436 |
def get_intersect_list(lst1, lst2):
"""
Find the intersection of two lists
:param lst1: List One
:param lst2: List Two
:return: A list of intersect elements in the two lists
"""
lst3 = [value for value in lst1 if value in lst2]
return lst3 | c7895c948b3a5132bd769e9320e40139c8aac3ad | 17,437 |
def get_instrument_survey_automated_invite(proj, id):
"""Given an instrument id return the automated invite definition if defined"""
xpath = r"./Study/GlobalVariables/redcap:SurveysSchedulerGroup/redcap:SurveysScheduler[@survey_id='%s']" % id
return proj.find(xpath, proj.nsmap) | cf458584f6fa6ab46c42bcdb11c5743639607030 | 17,449 |
def search_bt(t, d, is_find_only=True):
"""
Input
t: a node of a binary tree
d: target data to be found in the tree
is_find_only: True/False, specifying type of output
Output
the node that contans d or None if is_find_only is True, otherwise
the node that... | 4ac48982d17dc2d79ce86004a22167f314b8f99b | 17,450 |
def rgb_to_hex(r, g=0, b=0, a=0, alpha=False):
"""
Returns the hexadecimal string of a color
:param r: red channel
:param g: green channel
:param b: blue channel
:param a: alpha channel
:param alpha: if True, alpha will be used
:return: color in a string format such as #abcdef
"""
... | 90e5854f06948bba35a4ae40a6bb77eaef5a1120 | 17,457 |
def get_supervisors(employee):
"""
Given an employee object, return a list of supervisors. the first
element of list will be the intial employee.
"""
if employee.supervisor:
return [employee] + get_supervisors(employee.supervisor)
else:
return [employee] | 8b4fe897290834930096654dacdad2f480d11276 | 17,459 |
def mjd2jd(mjd):
"""
Converts Modified Julian Date to Julian Date. Definition of Modified Julian Date (MJD): MJD = JD - 2400000.5
Parameters
----------
mjd : float
The Modified Julian Date
Returns
-------
jd : float
:math:`$mjd + 2400000.5 = jd$`, the corresponding ordi... | e9250a61e1c3374f4989105ff24fd9efc825d7a1 | 17,462 |
def is_superincreasing(seq):
"""Return whether a given sequence is superincreasing."""
ct = 0 # Total so far
for n in seq:
if n <= ct:
return False
ct += n
return True | 836be03cb7dbb215baaa9a1ba5fd83c39de843d7 | 17,467 |
def bawl2(text):
"""
Return text in the following format.
t e x t .
e e
x x
t t
. .
"""
return ' '.join(text) + ''.join('\n' + char + ' '*(2*idx + 1) + char
for idx, char in enumerate(text[1:])) | 887006a1cb18970ef9889b1b8f1d61ca4aaa69ed | 17,472 |
from typing import List
def check_interval_coverage(intvl_upper_limit: int, sub_intvl_positions: List[int], range_length: int = 1) -> bool:
"""
Method that checks if given sub-intervals are correctly situated to cover all the original segment.
:param intvl_upper_limit: upper bound of the interval
:pa... | cfaa5d60d6caf59edade474946e2b5b0a7b825f1 | 17,476 |
def python_3000_backticks(logical_line):
"""
Backticks are removed in Python 3000.
Use repr() instead.
"""
pos = logical_line.find('`')
if pos > -1:
return pos, "W604 backticks are deprecated, use 'repr()'" | 2c25077b71bc6b10dca0fb168c711ecdcffeab14 | 17,482 |
def ticklabel_format(value):
"""
Pick formatter for ytick labels. If possible, just print out the
value with the same precision as the branch value. If that doesn't
fit, switch to scientific format.
"""
bvs = str(value)
if len(bvs) < 7:
fp = len(bvs) - (bvs.index(".") + 1) if "." in ... | 7de96c52c527a5295d7ca6e832313386fd80564c | 17,483 |
def transfer_function_Rec1886_to_linear(v):
"""
The Rec.1886 transfer function.
Parameters
----------
v : float
The normalized value to pass through the function.
Returns
-------
float
A converted value.
"""
g = 2.4
Lw = 1
Lb = 0
# Ignoring legal t... | 7a2a2a2348d701e7fd7dd90c5d016dbf8a2e0c56 | 17,484 |
def gen_apsubset(AP, intrep):
"""Generate set of atomic propositions corresponding to integer
>>> gen_apsubset(AP=("p", "q"), intrep=2)
set(['q'])
"""
return set([AP[i] for i in range(len(AP)) if ((intrep >> i) & 1) != 0]) | ab219b40c0eda5a0eef4f657f8b06da0f5d782d8 | 17,485 |
def does_classes_contain_private_method(classes, method):
"""
Check if at least one of provided classes contains a method.
If one of the classes contains the method and this method has private access level, return true and class
that contains the method.
"""
for class_ in classes:
if ha... | 544bd9c5c3f03352ab8674b2665eb583328ac437 | 17,486 |
import re
def parse_fatal_stacktrace(text):
"""Get useful information from a fatal faulthandler stacktrace.
Args:
text: The text to parse.
Return:
A tuple with the first element being the error type, and the second
element being the first stacktrace frame.
"""
lines = [
... | 20d26d3e0d69b5fd3bba1fbf1dbe6877b58b125a | 17,489 |
from typing import Dict
def dict_sort(d: dict, key=lambda item: item[1]) -> Dict:
"""sort a dictionary items"""
return {k: v for k, v in sorted(d.items(), key=key)} | 3686867a4b302fc9d9a5014b3cdadccbc8175d39 | 17,490 |
import re
def extract_variables(sFormula):
""" Extract variables in expression, e.g. {a}*x + {b} -> ['a','b']
The variables are replaced with p[0],..,p[n] in order of appearance
"""
regex = r"\{(.*?)\}"
matches = re.finditer(regex, sFormula, re.DOTALL)
formula_eval=sFormula
variables=[]
... | 7ae5b836504876c815b15c87bad774334fd4dd80 | 17,493 |
def select_files(files, search):
"""Select files based on a search term of interest.
Parameters
----------
files : list of str
File list.
search : str
String to use to keep files.
Returns
-------
list of str
File list with selected files kept.
"""
retur... | 91fc2e08645c349b14425b5f6e86c38906156601 | 17,496 |
def file_writer(filename):
"""
Open a file for writing.
Args:
filename: (string) the name of the path/file to open for writing.
Returns:
file object.
Raises:
IOError: If filename is not writeable.
"""
try:
fileobj = open(filename, 'w')
except IOError as... | c04e684b5cb35c8442d4a75762d63c0974745b9c | 17,501 |
def doAddition(a,b):
"""
The function doAddition accecpts two integer numbers and returns the sum of it.
"""
return a+b | c4afcdab6c5e4570eff848b2f6a0aa07713f0dda | 17,507 |
def get_binsize(bins):
"""
Infer bin size from a bin DataFrame. Assumes that the last bin of each
contig is allowed to differ in size from the rest.
Returns
-------
int or None if bins are non-uniform
"""
sizes = set()
for chrom, group in bins.groupby("chrom"):
sizes.update... | cd8a7127083a24bc24f79be4aa8225884efa643a | 17,508 |
def _replace_revision(raw_header: bytes, revision: bytes) -> bytes:
"""Replace the 'revision' field in a raw header."""
return raw_header[:8] + revision + raw_header[8 + 4 :] | a9c251528ae7e374c815db5b83ce4fbd164a7afd | 17,511 |
def keyword_list(value):
"""Ensure keywords are treated as lists"""
if isinstance(value, list): # list already
return value
else: # csv string
return value.split(',') | 9ab8f75fed9d85164d2b450da2c2fcdfc6e070c1 | 17,512 |
from bs4 import BeautifulSoup
def standardize_html(html):
"""Clean and format html for consistency."""
cleaned = html.replace(". ", ". ").replace(" ", "").replace("\n", "")
parsed = BeautifulSoup(cleaned, "lxml").prettify().strip()
return parsed | fd1d60f97ae7de313acb43fb327dee6864324109 | 17,514 |
import hashlib
def get_model_hash(rvt_model_path):
"""
Creates a hash of provided rvt model file
:param rvt_model_path:
:return: hash string
"""
BLOCKSIZE = 65536
hasher = hashlib.sha256()
with open(rvt_model_path, "rb") as rvt:
buf = rvt.read(BLOCKSIZE)
while len(buf)... | 1ee0f2935112eda8729df84e41b1d0fee2d224a1 | 17,515 |
from typing import Tuple
from typing import List
def _check_dissipator_lists(gammas, lindblad_operators) -> Tuple[List, List]:
"""Check gammas and lindblad operators are lists of equal length."""
if gammas is None:
gammas = []
if lindblad_operators is None:
lindblad_operators = []
asse... | 4071be282667b6c688cffdf28cd3a5e4ce8f6dbf | 17,517 |
def steps(current, target, max_steps):
""" Steps between two values.
:param current: Current value (0.0-1.0).
:param target: Target value (0.0-1.0).
:param max_steps: Maximum number of steps.
"""
if current < 0 or current > 1.0:
raise ValueError("current value %s is out of bounds (0.0-1... | 0287efec583bfb8c37907a34ca5adf7c0aa61886 | 17,519 |
def findUniqueNumber(n: int):
"""
Given a set of numbers present twice except the unique number, it finds the unique number among the set of numbers.
:param n : Size of the input
:return : The unique integer
"""
ans = 0
vec = [int(x) for x in input("Enter set of numbers separated by space\n"... | bf9a64bf0474a354dec8f0b891a6f0134aa53c73 | 17,520 |
from typing import Any
def expand_to_tuple(item: Any) -> tuple[Any, ...]:
"""Wraps anything but tuple into a tuple.
Args:
item: any sequence or a single item.
Returns:
a tuple.
>>> from redex import util
>>> util.expand_to_tuple((1,))
(1,)
>>> util.expand_to_tuple((1,2))... | 7f7f072759ec4b5e493d5f55678f853eb99fe765 | 17,524 |
def add_zeros(x, length=4):
"""Zero pad x."""
strx = str(x)
lenx = len(strx)
diff = length - lenx
for _ in range(diff):
strx = '0' + strx
return strx | ed46c2005dec2324229629341309148fecd7c14f | 17,529 |
def get_plural(val_list):
""" Get Plural: Helper function to return 's' if a list has more than one (1)
element, otherwise returns ''.
Returns:
str: String of 's' if the length of val_list is greater than 1, otherwise ''.
"""
return 's' if len(val_list) > 1 else '' | b86387cb2abd3c5176f5dcefbf7bc3e1a49a346c | 17,535 |
def _is_variable_argument(argument_name):
"""Return True if the argument is a runtime variable, and False otherwise."""
return argument_name.startswith('$') | cf74d6dfd1c0ea1b560bf3766e2fac8af1dbafda | 17,537 |
def vote_smart_candidate_object_filter(one_candidate):
"""
Filter down the complete dict from Vote Smart to just the fields we use locally
:param one_candidate:
:return:
"""
one_candidate_filtered = {
'candidateId': one_candidate.candidateId,
'firstName': one_candidate.firstName,... | 56fbbe3c2f128364d800d05fe6690eedb9f5f748 | 17,539 |
def get_capability(capabilities, capability_name):
"""Search a set of capabilities for a specific one."""
for capability in capabilities:
if capability["interface"] == capability_name:
return capability
return None | 4d83ec53a06b75313a47ea3ba618161ecd5f3782 | 17,543 |
import torch
def mpjae(predicted, target):
"""
Mean per-joint angle error (3d bone vector angle error between gt and predicted one)
"""
assert predicted.shape == target.shape # [B,T, K]
joint_error = torch.mean(torch.abs(predicted - target).cuda(), dim=0) # Calculate each joint angle
print('... | 07e2cadb9b38c39514558791b3d5c605a19a0dc4 | 17,545 |
def get_ciphers(fw_conn, service):
"""Get Ciphers
Args:
fw_conn (PanDevice): A panos object for device
service (str): A string containing either mgmt or ha for ciphers
Returns:
results (Element): XML results from firewall
"""
base_xpath = ("/config/devices/entry[@name='loca... | 2fe9837c884d1257afb48982721c7e273ddf7fc9 | 17,548 |
def stdout_to_list(stdout):
"""Convert stdout (str) to list of stripped strings"""
return [x.strip() for x in stdout.split('\n') if x.strip()] | ec641d29201bbfc60a083952daf0b9e696b786dc | 17,550 |
def Cumfreq(symbol, dictionary):
"""
This Function Takes as inputs a symbol and a dictionary containing
all the symbols that exists in our stream and their frequencies
and returns the cumulative frequency starting from the very
beginning of the Dictionary until that Symbol.
Arguments:
symbol {[t... | b5dffb0512b4704bd76c49eac4bb3e9714ebbcb1 | 17,552 |
def parseCoords(coordList):
"""
Pass in a list of values from <coordinate> elements
Return a list of (longitude, latitude, altitude) tuples
forming the road geometry
"""
def parseCoordGroup(coordGroupStr):
"""
This looks for <coordinates> that form the road geometry, and
then parses them into (l... | 7c358973fc4279e03cf8d535ff41de7571f0a7d2 | 17,554 |
from datetime import datetime
def datetime_from_salesforce(d):
"""Create a Python datetime from a Salesforce-style ISO8601 string"""
return datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f%z") | ca9cbeb5dff44860166a27c771da1cdb8f3d395a | 17,560 |
def listGetShiftedGeometricMean(listofnumbers, shiftby=10.0):
""" Return the shifted geometric mean of a list of numbers, where the additional shift defaults to
10.0 and can be set via shiftby
"""
geommean = 1.0
nitems = 0
for number in listofnumbers:
nitems = nitems + 1
nextnumb... | 904bb38a199052b086b7a2c695ce675011f65019 | 17,561 |
def similarity_hash(hash_digests):
# type: (list[bytes]) -> bytes
"""
Creates a similarity preserving hash from a sequence of equal sized hash digests.
:param list hash_digests: A sequence of equaly sized byte-hashes.
:returns: Similarity byte-hash
:rtype: bytes
"""
n_bytes = len(hash_... | 804619477bdea3f7a79c6473d47e55c5106a586a | 17,564 |
import binascii
def mkauth(username: str, password: str, scheme: str = "basic") -> str:
"""
Craft a basic auth string
"""
v = binascii.b2a_base64(
(username + ":" + password).encode("utf8")
).decode("ascii")
return scheme + " " + v | b9dd22c830e8c493ac4239ff6f4800e554d1e439 | 17,565 |
def eta_Mc_M(Mc, M):
"""
Computes the symmetric-mass-ratio from the Chirp Mass and
total mass
input: Mc, M
output: eta
"""
return (Mc/M)**(5./3.) | 535e2ac7cd08d4b0c7df49bbd1c69287012b65ca | 17,566 |
import random
def randit(it, rand=None):
""" Random object from iterable.
Return an occurrence at random from the given iterable, using `rand` if
given or else a new `Random` object.
"""
return it[(rand or random.Random()).randrange(0, len(it))] | fa8c4bb78ae90923cd3149af4714a7e89f85afde | 17,582 |
def calc_focal_length(distance, width, pixels):
"""
Calculates the focal length based off the input
Parameters:
distance(int): distance from camera to the object
width(int): actual width of the object
pixels(int): width in pixels of the object
return: focal length of the ca... | 5a8ba34ad7d1c408552ec50015aa3df7e18f555c | 17,583 |
def create_greeting(moment):
"""Prints customized welcome string based on time
Args:
moment (timestamp): current time
Returns:
greeting (string): the final welcome string
"""
if moment.hour < 12:
greeting = 'Good morning'
elif moment.hour < 20:
... | 6dfc2d113b27a95c631186ee3688f7054e6cc923 | 17,584 |
import re
def preprocess_summary(text):
"""Pre-process an episode summary string by removing repeated whitespaces, bracketed text, and citations."""
text = re.sub('[\(\[].*?[\)\]]', '', text) # remove brackets
text = re.sub(' +', ' ', text) # remove multiple whitespaces
text = re.sub('\s+\.\s+', '. ... | ef950787a28487a29106a6a5ef959adbf52c3703 | 17,588 |
def create_segmented_sequence(length, seq_initializer):
""" Create a segmented test_sequence
A segment is a list of lists. `seq_initializer` is used to create `length`
individual segments, which allows for the using any of the pre-supplied
initializers for a regular genomic test_sequence, or for makin... | bfe4296a91b0ea122c20501347cfd68fbc8ff16c | 17,589 |
import re
def convert_keys(input_value):
"""
Convert all of the keys in a dict recursively from CamelCase to snake_case.
Also strips leading and trailing whitespace from string values.
:param input_value:
:return:
"""
retn = None
if isinstance(input_value, list):
retn = []
... | c0727ac011362f2449d2e5ced694752df529dfeb | 17,590 |
def search_colorspaces(config, aces_id):
""" Search the config for the supplied ACES ID, return the color space name. """
for cs in config.getColorSpaces():
desc = cs.getDescription()
if aces_id in desc:
return cs.getName()
return None | b47f7b9105db178904ce272ad8b0002412d96f82 | 17,591 |
def get_upload_folder_structure(file_name):
"""
Return the structure in the upload folder used for storing and
retrieving uploaded files.
Two folder levels are created based on the filename (UUID). The
first level consists of the first two characters, the second level
consists of the third char... | 3a231d820de6a67d8d9a0af77055092cc24c3a48 | 17,601 |
def find_matching_edge(m, i, j):
"""Return corresponding edge for a given arc. """
if (i,j) in m.edge:
return (i,j)
else:
return (j,i) | 4bbc182116c210dd9cdb3ca4719a6bc1be8e882e | 17,602 |
def sanitize_result(data):
"""Sanitize data object for return to Ansible.
When the data object contains types such as docker.types.containers.HostConfig,
Ansible will fail when these are returned via exit_json or fail_json.
HostConfig is derived from dict, but its constructor requires additional
ar... | 6058f5ec32fadd2de6869f91747d7968c4437ce9 | 17,603 |
def abbrev_key (
key: str,
) -> str:
"""
Abbreviate the IRI, if any
key:
string content to abbreviate
returns:
abbreviated IRI content
"""
if key.startswith("@"):
return key[1:]
key = key.split(":")[-1]
key = key.split("/")[-1]
key = key.split("#")[-1]
return key | 6cb2058f32d6320f1be118d8831cc074cd0cc56f | 17,608 |
from typing import Tuple
def split_platform(platfrm: str) -> Tuple[str, str, str]:
"""
Split a platform string into its (os, architecture, variant) form.
"""
parts = platfrm.split("/", maxsplit=2)
return (
parts[0],
parts[1] if len(parts) > 1 else "",
parts[2] if len(parts)... | 75b4594a874c03cc5977472b396ecc94d41206e3 | 17,612 |
def basic_ttr(n_terms, n_words):
""" Type-token ratio (TTR) computed as t/w, where t is the number of unique
terms/vocab, and w is the total number of words.
(Chotlos 1944, Templin 1957)
"""
if n_words == 0:
return 0
return n_terms / n_words | 3d56fd414d6d462c722a2d29bd15bb7ef8bf7559 | 17,621 |
import torch
from typing import OrderedDict
def load_statedict(model_path):
"""Loads model state dict.
Args:
model_path: model path
Returns: state dict
"""
print(f"Loading model from {model_path}.")
state_dict = torch.load(model_path, map_location=lambda storage, loc: storage)
pr... | d556db551dca3176ffcfa88af99fc89f36d9b444 | 17,622 |
def GetCacheKeyPolicy(client, args, backend_bucket):
"""Returns the cache key policy.
Args:
client: The client used by gcloud.
args: The arguments passed to the gcloud command.
backend_bucket: The backend bucket object. If the backend bucket object
contains a cache key policy already, it is used ... | 202d1cce49478051255bd48f0b9e117dd19ed63f | 17,624 |
def multi_powmod(bases, exponents, modulus):
"""
raise all bases in xs to the respective powers in ys mod n:
:math:`\prod_{i=1}^{len(bases)} base_i^{exponent_i} \pmod{modulus}`
:param bases: the bases
:param exponents: the exponents
:param modulus: the modulus
:return: the calculated result... | b8b0bcc32e7938996d20044fcd4e0649273d0ee5 | 17,626 |
def ticks(group):
"""Wrapper function for .add_steps method.
"""
pheno, steps, sim_id = group
pheno.add_steps(steps)
return pheno, sim_id | f567d9e14d7421fb196921543bab9587ca040fa4 | 17,632 |
def update_output_div(input_value):
"""Format the input string for displaying"""
return 'You\'ve entered "{}"'.format(input_value) | 615a671775ed836712978485230403d9a331f366 | 17,635 |
def get_xy_coords(storms):
"""
Takes Polygons of storm masks as paired coordinates and returns seperated x and y coordinates
Args:
storms: List of polygon storms [x, y]
Returns:
x: list of x coordinates
y: list of y coordinates
"""
x, y = [], []
[(x.append(list(polyg... | 444ba53cf8ffabe1f9e4bea5a7d8a70d6b41a056 | 17,636 |
def reducemap(func, sequence, initial=None, include_zeroth = False):
"""
A version of reduce that also returns the intermediate values.
:param func: A function of the form x_i_plus_1 = f(x_i, params_i)
Where:
x_i is the value passed through the reduce.
params_i is the i'th el... | 7c3fbd5e60777ecaf82ff2d7745aafab879abd10 | 17,637 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.