content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def GetCaId(settings):
"""Get ca_id to be used with GetCaParameters().
Args:
settings: object with attribute level access to settings parameters.
Returns:
str like "FOO" or None (use primary parameters)
"""
return getattr(settings, 'CA_ID', None) | cb94f5a27281c17a1b1eb9b13382e651bdf2b441 | 652,214 |
from typing import List
def _find_interval_range(category_configs, interval: float) -> List[dict]:
"""Finds the range the interval is in and returns the configured mappings to the TransportGroups"""
for interval_category in category_configs:
min_interval = interval_category['min-interval'] if 'min-int... | 1c7df995c328e83d372995b5045e0ad0c731f4b0 | 652,215 |
def convert_segmentation_bbox(bbox: dict, page: dict) -> dict:
"""
Convert bounding box from the segmentation result to the scale of the characters bboxes of the document.
:param bbox: Bounding box from the segmentation result
:param page: Page information
:return: Converted bounding box.
"""
... | 953669d41c2b74816aa5a5b93841713fe9901c6a | 652,219 |
def resize_image(image, width, height):
"""Resize image to explicit pixel dimensions."""
width = int(width)
height = int(height)
aspect_ratio = image.width / image.height
if height == 0:
new_width = width
new_height = int(round(width / aspect_ratio, 0))
elif width == 0:
n... | a1dba4a83e4a60e602aa4e43460eee5a827615d2 | 652,220 |
def round_to_nearest(value, round_value=1000):
"""Return the value, rounded to nearest round_value (defaults to 1000).
Args:
value: Value to be rounded.
round_value: Number to which the value should be rounded.
Returns:
Value rounded to nearest desired integer.
"""
if round... | 4fee90f07e6106ded18f3bedfe31deceac3913c0 | 652,221 |
def is_bbox_correct(bbox, width, height):
"""
:param bbox: bbox composed of 4 integer values [xmin, ymin, xmax, ymax]
:param height: height of the image
:param width: width of the image
:return: True if bbox inside image, False otherwise
"""
# Check bbox inside image
if b... | 85c369dcb6589207d34bb6fe3f726a678af8eeda | 652,222 |
def to_time (wmi_time):
"""
Convenience wrapper to take a WMI datetime string of the form
yyyymmddHHMMSS.mmmmmm+UUU and return a 9-tuple containing the
individual elements, or None where string contains placeholder
stars.
@param wmi_time The WMI datetime string in yyyymmddHHMMSS.mmmmmm+UUU format
@... | c607ece580715d7e3ed5907a3564e2b5923dfae0 | 652,223 |
import ast
def is_yield(statement):
"""
Is this a statement of the form `yield <expr>`
"""
return (isinstance(statement, ast.Expr)
and isinstance(statement.value, ast.Yield)) | 56bff246a5a4b47ed8cd7d39e08fa2262a704f03 | 652,224 |
def get_genes(prefix, percentile):
""" Gets a list of genes from three files. One representing all genes in a
sample, one representing the upper tail of a distribution of those genes,
and one representing the lower tail of a distribution of those genes. """
allList = []
botList = []
topList = []... | f662591e01e09230474799a8a23af900992c2f89 | 652,227 |
def feet_to_meters(feet):
"""Convert feet to meters."""
try:
value = float(feet)
except ValueError:
print("Unable to convert to float: %s", feet)
else:
return (0.3048 * value * 10000.0 + 0.5) / 10000.0 | d651507e6cd4c3a2506dbf6944afaf4d5062dcbb | 652,228 |
def concatenate_files(filenames):
""" Concatenate the specified files, adding `line directives so the lexer can track source locations.
"""
contents = []
for filename in filenames:
contents.append('`line 1 "%s" 1' % filename)
with open(filename, 'rb') as f:
contents.append(f.... | ba991594d1ed4151cd358fa07c7817f6a9bd3a91 | 652,229 |
def get_request_value(req, key):
"""
Return the value of the request object's JSON dictionary.
"""
request_json = req.get_json()
if req.args and key in req.args:
return req.args.get(key)
elif request_json and key in request_json:
return request_json[key]
else:
return ... | fa68a4c851e5ca1d8991c76a11c0e0e8f60dd983 | 652,231 |
def parse(resp: dict):
"""
Parse response data for the repo commits query.
"""
branch = resp["repository"]["defaultBranchRef"]
branch_name = branch.get("name")
commit_history = branch["target"]["history"]
total_commits = commit_history["totalCount"]
commits = commit_history["nodes"]
... | e716673398b9fd0194114af64b618effb0b8e9a0 | 652,232 |
def strip_hyphen(s):
"""
Remove hyphens and replace with space.
Need to find hyphenated names.
"""
if not s:
return ''
return s.replace('-', ' ') | 7cc0c23e3c414ec742a86bf651b507aa0df31485 | 652,235 |
def last_column(worksheet) -> int:
"""
Quick way to determine the number of columns in a worksheet. Assumes that data is within the `CurrentRegion` of cell A1.
:param worksheet: Excel Worksheet COM object, such as the one created by code like:
app = win32com.client.Dispatch("Excel.Application")
... | dfd8231214aede9fa9e9f362e8bad70b02ff4489 | 652,236 |
def GetTag(node):
"""Strips namespace prefix."""
return node.tag.rsplit('}', 1)[-1] | 8796a1a42db5c97c173301a1d671b2adc0f60235 | 652,237 |
def pad_func(before, after):
"""
Padding function. Operates on vector *in place*, per the np.pad
documentation.
"""
def pad_with(x, pad_width, iaxis, kwargs):
x[:pad_width[0]] = before[-pad_width[0]:]
x[-pad_width[1]:] = after[:pad_width[1]]
return
return pad_with | 3996e40231a03b2fa5dd6a50a7307259f13662ca | 652,239 |
def merge_blocks(a_blocks, b_blocks):
"""Given two lists of blocks, combine them, in the proper order.
Ensure that there are no overlaps, and that they are for sequences of the
same length.
"""
# Check sentinels for sequence length.
assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size... | 04991de7c8c0ac2896bc81451a8c2d76dd2ccfa4 | 652,248 |
def transform_list_of_dicts_to_desired_list(curr_list, nested_key_name, new_list=[]):
"""
Returns a list of key values specified by the nested key
Args:
curr_list (list): list of dicts to be dissected
nested_key_name (str): key name within nested dicts desired
new_list (list): used ... | 2b44b2b6b94ac48f17ccf29cb3558139b75e406a | 652,249 |
import mmap
def map_fb_memory(fbfid, fix_info):
"""Map the framebuffer memory."""
return mmap.mmap(
fbfid,
fix_info.smem_len,
mmap.MAP_SHARED,
mmap.PROT_READ | mmap.PROT_WRITE,
offset=0
) | 0b87815b09f6cdc58c033a1a7e41faf465a11dbc | 652,255 |
def square_of_digits(number: int) -> int:
"""Return the sum of the digits of the specified number squared."""
output = 0
for digit in str(number):
output += int(digit) * int(digit)
return output | 7b1e1d6de1db292970d346b99d7048088b6a4fca | 652,259 |
def check_int(x):
"""
Check whether a int is valid
:param x: The int
:return: The result
"""
return 0 <= x <= 2147483647 | 9a53ea1afb0f50e2528eb811d03f949517cdd652 | 652,260 |
def index(predicate, seq):
"""
Returns the index of the element satisfying the given predicate, or None.
"""
try:
return next(i for (i, e) in enumerate(seq) if predicate(e))
except StopIteration:
return None | c0a7b055e386a6766d4a280aadbfb523e1060514 | 652,264 |
def get_score(winner):
"""
You get 1 point for winning, and lose 1 point for losing.
>>> get_score('tie')
0
>>> get_score('human')
1
>>> get_score('ai')
-1
"""
if winner == 'human':
return +1
if winner == 'ai':
return -1
return 0 | 591b91c97218ab074929011707d79d7b52c143db | 652,270 |
def strip_markup(text):
"""Strip yWriter 6/7 raw markup. Return a plain text string."""
try:
text = text.replace('[i]', '')
text = text.replace('[/i]', '')
text = text.replace('[b]', '')
text = text.replace('[/b]', '')
except:
pass
return text | 026f72fc9dcbf91d8ff87157a69140537911e5bd | 652,271 |
def tokenize_spec(spec):
"""Tokenize a GitHub-style spec into parts, error if spec invalid."""
spec_parts = spec.split('/', 2) # allow ref to contain "/"
if len(spec_parts) != 3:
msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=spec)
if len(spec_parts) == 2 ... | 994e0b3d8043db3779bf1ad7a2303b43e28c5363 | 652,272 |
def get_overall_misclassifications(H, training_points, classifier_to_misclassified):
"""Given an overall classifier H, a list of all training points, and a
dictionary mapping classifiers to the training points they misclassify,
returns a set containing the training points that H misclassifies.
H is repr... | e940f29ac43eacae0c0642285319cad0fb8eb644 | 652,273 |
def list_to_string(list_):
"""
Returns a string from the given list
>>> list_to_string(['1,', '2', '3'])
>>> # 1, 2, 3
:param list_: list
:return:str
"""
list_ = [str(item) for item in list_]
list_ = str(list_).replace("[", "").replace("]", "")
list_ = list_.replace("'", "").rep... | 28185348a5f983905e6d8ce74c636b9dd4216d9e | 652,276 |
import torch
def _gaussian_kernel_1d(size: int, sigma: float) -> torch.Tensor:
""" Create 1-D Gaussian kernel with shape (1, 1, size)
Args:
size: the size of the Gaussian kernel
sigma: sigma of normal distribution
Returns:
1D kernel (1, 1, size)
"""
coords = torch.arange(size).to(dtype=torch.flo... | 6440154b8cb24ab776161affbffe9bc09899af63 | 652,277 |
def merge_paths(base_uri, relative_path):
"""Merge a base URI's path with a relative URI's path."""
if base_uri.path is None and base_uri.authority is not None:
return '/' + relative_path
else:
path = base_uri.path or ''
index = path.rfind('/')
return path[:index] + '/' + rel... | f2cda0ad9a49cb92187d5318d80f459080b9657b | 652,286 |
def _df_to_vector(distance_matrix, df, column):
"""Return a grouping vector from a ``DataFrame`` column.
Parameters
----------
distance_marix : DistanceMatrix
Distance matrix whose IDs will be mapped to group labels.
df : pandas.DataFrame
``DataFrame`` (indexed by distance matrix ID... | 7b205f8783b0e11cfbe9206f9ff381f18ca74ae7 | 652,288 |
def _compute_negative_examples(
label,
all_items,
pos_items,
item_to_labels,
label_graph,
assert_ambig_neg
):
"""
Compute the set of negative examples for a given label.
This set consists of all items that are not labelled
with a descendant of the ... | 1e09ea6b88f03801eeb04103deeb62f642d54747 | 652,293 |
def get_or_create(table, **fields):
"""
Returns record from table with passed field values.
Creates record if it does not exist.
'table' is a DAL table reference, such as 'db.spot'
fields are field=value pairs
Example:
xpto_spot = get_or_create(db.spot, filename="xptoone.swf", \
descrip... | 55e1fea3dfa3df2548bbd525bef17b762a4be06a | 652,300 |
def get_py_param_type(context):
"""convert a param type into python accepted format.
Related to the formats accepted by the parameter under dynamic reconfigure
Args:
context (dict): context (related to an interface description)
Returns:
str: variable type in python format related to pa... | e8703b4d89350f2388a1d9bbcea894a5e1f4685f | 652,301 |
def get_city_by_id(item_id):
"""Get City by Item ID.
Given the item ID of a luxury good, return which city it needs to be brought to.
Args:
item_id (str): Item ID
Returns:
str: City name the item should be brought to.
"""
ids_to_city = {
"RITUAL": "Caerleon",
... | a596de15dfa96e75fd468ef0a38af294b64ba677 | 652,303 |
import json
def get_url_mapping(api, headers=None):
"""Fetch the mapping of project id to url from luci-config.
Args:
headers: Optional authentication headers to pass to luci-config.
Returns:
A dictionary mapping project id to its luci-config project spec (among
which there is a repo_url key).
"... | 5fe78885f9423758a9b356189c10b4b5567397cd | 652,313 |
def low16(i):
"""
:param i: number
:return: lower 16 bits of number
"""
return i % 65536 | fbb4aab069ccc2cdecec86517dde820df73559fe | 652,316 |
def gcd(a,b):
"""gcd(a,b) returns the greatest common divisor of the integers a and b."""
a = abs(a); b = abs(b)
while (a > 0):
b = b % a
tmp=a; a=b; b=tmp
return b | 1c97e04e39b4aff0f97b58e98b500965f58b9c66 | 652,326 |
def average_height(team, num_team_players):
"""Calculates the average height(inches) for the team"""
team_total_height = 0
for player in team['team_players']:
team_total_height += player['height']
return round(team_total_height / num_team_players, 1) | 087097e46d8267d82fac7c03193bf932f611a2fd | 652,327 |
def flesch_kincaid_grade_level(word_count, syllable_count):
"""Given a number of words and number of syllables in a sentence, computes the
flesch kincaid grade level.
Keyword arguments:
word_count -- number of words in the sentence
syllable_count -- number of syllables in the sentence
"""
r... | 1bf91db4e5bd0aa8aff88a99f383bfa756e67ebf | 652,329 |
def merge(defaults, file, env):
"""Merge configuration from defaults, file, and environment."""
config = defaults
# Merge in file options, if they exist in the defaults.
for (k, v) in file.items():
if k in config:
config[k] = v
# Merge in environment options, if they exist in t... | bc79ae7041a82bcddb190f292db3aefc2d88bac2 | 652,340 |
def factorial(number):
"""Return the factorial of a number."""
accumulator = 1
for n in range(1, number + 1):
accumulator *= n
return accumulator | 8d52e741feb0555b674a3f9fbeabacc8a13a333c | 652,343 |
def remove_whitespace(x):
"""
Helper function to remove any blank space from a string
x: a string
"""
try:
# Remove spaces inside of the string
x = "".join(x.split())
except:
pass
return x | d592d72959fc3096acee89d43b13a66f35a54d18 | 652,344 |
def get_clean_messages(author, dataframe, limit=None, min_interval=None, max_interval=None, rand=False):
"""Retrieve the cleaned messages by a given author from a dataframe.
min_interval, max_interval allow for only messages with a certain range of
messageInterval to be selected. if True, rand will randomiz... | a3cb78d208e154c8a04fad1584d44a479636c048 | 652,346 |
def progressBar(curr, total, b_length=60, prefix='', suffix='', decimals=0):
"""Return the progress bar
Code from https://gist.github.com/aubricus/f91fb55dc6ba5557fbab06119420dd6a
"""
str_format = "{0:." + str(decimals) + "f}"
percents = str_format.format(100 * (curr/ float(total)))
filled_len ... | e91e516707800fbb901b710199bc625affc69af6 | 652,348 |
import binascii
def hex_decode(string):
"""
Hex decode string
Parameters
----------
string : str
String to be decoded from hexadecimal
Returns
-------
str
Text string with ASCII / unicode representation of hexadecimal input string
"""
return binascii.a2b_hex(st... | 5513101514bded4b28f1a6b0038ce9a6f2dfac87 | 652,350 |
def parse_mdout(file):
"""
Return energies from an AMBER `mdout` file.
Parameters
----------
file : str
Name of output file
Returns
-------
energies : dict
A dictionary containing VDW, electrostatic, bond, angle, dihedral, V14, E14, and total energy.
"""
vdw, ... | 1cd0fab9342baa70f1ac96bcb917a1f1586a16a7 | 652,351 |
import re
def changeAllAttributesInText(text, attribute, newValue, append):
"""
Changes the specified attribute in all tags in the provided text to the
value provided in newValue. If append is 0, the value will be replaced.
If append is anything else, the value will be appended to the end
of the o... | 4da10f29eaa032c5d44ba40d9776d66fb1ae59f2 | 652,353 |
def make_count_column(array):
"""Make column name for arrays elements count
>>> make_count_column('/tender/items')
'/tender/itemsCount'
>>> make_count_column('/tender/items/additionalClassifications')
'/tender/items/additionalClassificationsCount'
>>> make_count_column('/tender/items/')
'/t... | fe3dcfb5077e0293e74fc299189d7b09cf0f9249 | 652,354 |
def camelcase(s):
"""Turn strings_like_this into StringLikeThis"""
return ''.join([word.capitalize() for word in s.split('_')]) | bedb2b7a39cca2c2cb27fd24f912bc52a5bb386a | 652,356 |
from datetime import datetime, timedelta
def check_date_past_interval(check_date, interval=None):
"""Return True if given check_date is past the interval from current time.
:param check_date: Datetime string like '2021-08-23 18:14:05'
:type check_date: str
:param interval: Hours amount to check in pa... | 8df45d0e89427e96020e3620de391afe66f7dc3c | 652,358 |
def fix_negatives(num):
"""
Some scopes represent negative numbers as being between 128-256,
this makes shifts those to the correct negative scale.
:param num: an integer
:return: the same number, shifted negative as necessary.
"""
if num > 128:
return num - 255
else:
re... | b8e5694c96d8199e9488940bd5f47d1da9f0800e | 652,362 |
def identifyCategoricalFeatures(x_data,categorical_cutoff):
""" Takes a dataframe (of independent variables) with column labels and returns a list of column names identified as
being categorical based on user defined cutoff. """
categorical_variables = []
for each in x_data:
if x_data[each].nuni... | 531eb49871155b5042de08b0c7b3189a15e55ca2 | 652,363 |
def _net_get_tx_id(id_offset: int, index: int) -> int:
"""
Returns the transmission id of a board, given its type's start_id and its index.
"""
return 2 * (id_offset + index) | 0e4531054cefcdd01d0d04f960a60b8e634424d4 | 652,364 |
import pickle
def read_results(pickle_file_name):
"""Reads results from Pickle file.
:param pickle_file_name: Path to input file.
:return: result_dict: Dictionary created by `run_sfs`.
"""
pickle_file_handle = open(pickle_file_name, 'rb')
result_dict = pickle.load(pickle_file_handle)
pic... | 9909ef3100e3b976eb2cc4346e8a02370556b35b | 652,366 |
import string
def capitalize(string_raw):
"""Capitalize a string, even if it is between quotes like ", '.
Args:
string_raw (string): text to capitalize.
Returns:
string
"""
# return re.sub(r"\b[\w']", lambda m: m.group().capitalize(), string.lower())
return string.capwords(... | 7228fbf56d99c9ee0e8bf165cb3c993ef8d551c0 | 652,370 |
from typing import Counter
from typing import OrderedDict
def get_stats_document(document: Counter) -> OrderedDict:
"""
Résumé
---
Pour un document donné calcule des statistiques liées à ce document comme le nombre unique de terme, la fréquence maximum
d'un terme dans le document ou la fréquence m... | afd386796324631f7a1069ae67be75fb3af4bfdd | 652,374 |
def fastq_infer_rg(read):
"""
Infer the read group from appended read information, such as produced by the
samtools fastq command.
Requires the read to be formatted such the rg tag is added to the end of the
read name delimited by a ``_``. Returns the read group tag.
"""
rgstr = read.name.s... | a908c2a75f3a7d72e76633595d9ad62e053cd70f | 652,377 |
import re
def replace_g5_search_dots(keywords_query):
"""Replaces '.' with '-' in G5 service IDs to support old ID search format."""
return re.sub(
r'5\.G(\d)\.(\d{4})\.(\d{3})',
r'5-G\1-\2-\3',
keywords_query
) | 3784af8c674c667e10d51bcd1b84e0df767564be | 652,379 |
def replace_tags(template, tags, tagsreplace):
"""Replace occurrences of tags with tagsreplace
Example:
>>> replace_tags('a b c d',('b','d'),{'b':'bbb','d':'ddd'})
'a bbb c ddd'
"""
s = template
for tag in tags:
replacestr = tagsreplace.get(tag, '')
if not replacestr:
... | 78b875a16940d577115eda5128475867c7454a65 | 652,381 |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
zeros = []
ones = []
twos = []
for input in input_list:
if input == 0:
zeros.append(input)
... | d39f1b7ad04913b1930acdcb9137269e11632887 | 652,383 |
def maybe_encode(value):
"""If the value passed in is a str, encode it as UTF-8 bytes for Python 3
:param str|bytes value: The value to maybe encode
:rtype: bytes
"""
try:
return value.encode('utf-8')
except AttributeError:
return value | 48588e31d7ca9a8eb09c41213eec13c13a9a3a8c | 652,391 |
def _broadcast_params(params, num_features, name):
"""
If one size (or aspect ratio) is specified and there are multiple feature
maps, we "broadcast" anchors of that single size (or aspect ratio)
over all feature maps.
If params is list[float], or list[list[float]] with len(params) == 1, repeat
... | de1f93a8a3ab19679f1936e5d6fb581475fa1893 | 652,395 |
def get_fort46_info(NTRII, NATM, NMOL, NION):
"""Collection of labels and dimensions for all fort.46 variables, as collected in the
SOLPS-ITER 2020 manual.
"""
fort46_info = {
"PDENA": [r"Atom particle density ($cm^{-3}$)", (NTRII, NATM)],
"PDENM": [r"Molecule particle density ($cm^{-3... | 8ea70691172399b5592f0a129945a64e4a399bf9 | 652,399 |
def modify_axis(axs, xtick_label, ytick_label, xoffset, yoffset, fontsize, grid=True):
"""Change properties of plot axis to make more beautiful"""
axs.spines['top'].set_visible(False)
axs.spines['bottom'].set_visible(True)
axs.spines['left'].set_visible(True)
axs.spines['right'].set_visible(False)
... | 38197fc3e5121a56906b0efb6bfa08afec839b80 | 652,402 |
def remove_trailing_characters_from_list(element_list, char_list):
"""
This function removes trailing characters from a all strings in a list
Args:
element_list: list of strings to be formatted
char_list: List of characters to be removed from each string in the list
Returns:
ele... | b63e188a895ded71c513bbcc629002f60c1847f3 | 652,408 |
def norm_text_angle(a):
"""Return the given angle normalized to -90 < *a* <= 90 degrees."""
a = (a + 180) % 180
if a > 90:
a = a - 180
return a | 424df499823743144567c83cc44d9fa809710613 | 652,409 |
import sympy
def is_quad_residue(n, p):
"""
Returns True if n is a quadratic residue mod p.
"""
return sympy.ntheory.residue_ntheory.is_quad_residue(n, p) | e4f9e820c88fc3c696d6157581d1392a30eda449 | 652,412 |
def dir(p_object=None): # real signature unknown; restored from __doc__
"""
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attribute... | c9b21689037760f6c7c9d19d32acc918814fc049 | 652,414 |
import io
def fread(file_path):
"""Read data from file"""
with io.open(file_path, "r", encoding="utf8") as f:
return f.read() | f0c6ce8782e1921d6a1fef4b7c9063437315f4dc | 652,415 |
def action(maximize, total_util, payoffs):
"""
>>> action(True, 0.9, [1.1, 0, 1, 0.4])
0
>>> action(True, 1.1, [1.1, 0, 1, 0.4])
1
>>> action(False, 0.9, [1.1, 0, 1, 0.4])
0.9
"""
if maximize:
return int(total_util > payoffs[2])
else:
return total_util | bd57083666ff80469f53a578c6290876b68052ab | 652,418 |
def clean_view(view_orig, superunits):
"""
Define a view of the system that comes from a view of another one.
Superunits are cleaned in such a way that no inconsistencies are present
in the new view.
Args:
view_orig (dict): the original view we would like to clean
superunits (list): l... | f5042d1cedd51d72524f177b00cf3c0635729381 | 652,420 |
def bounds(total_docs, client_index, num_clients, includes_action_and_meta_data):
"""
Calculates the start offset and number of documents for each client.
:param total_docs: The total number of documents to index.
:param client_index: The current client index. Must be in the range [0, `num_clients').... | 0d517300f10aaa511f341f2e8214a70739d8640e | 652,421 |
def is_valid_coordinate(x0: float, y0: float) -> bool:
"""
validates a latitude and longitude decimal degree coordinate pairs.
"""
if isinstance(x0, float) and isinstance(y0, float):
if -90 <= x0 <= 90:
if -180 <= y0 <= 180:
return True
return False | c2833a2786515aa218c329686b3ea4c29b32dc2d | 652,425 |
def fibonacci_py(v):
""" Computes the Fibonacci sequence at point v. """
if v == 0:
return 0
if v == 1:
return 1
return fibonacci_py(v - 1) + fibonacci_py(v - 2) | 4db3932fd1aa9d8a431d2d3b5861c3cf89f3bde4 | 652,426 |
import six
def get_varval_from_locals(key, locals_, strict=False):
"""
Returns a variable value from locals.
Different from locals()['varname'] because
get_varval_from_locals('varname.attribute', locals())
is allowed
"""
assert isinstance(key, six.string_types), 'must have parsed key into ... | 9bd7ef67b58f561fe3e2594e50592c8e5e4227ef | 652,430 |
import math
def rotate(v1, angle):
"""
rotates the vector by an angle around the z axis
:param v1: The vector that will be rotated
:param angle: The angle to rotate the vector by
:return: The vector rotated around the z axis by the angle
"""
x, y, z = v1
# Rotation transformation
... | 7d71f8c7126122f13ea99b3cde4a03d6a0605757 | 652,437 |
def is_waiting_state(state, num_of_servers):
"""Checks if waiting occurs in the given state. In essence, all states (u,v)
where v > C are considered waiting states.
Set of waiting states: S_w = {(u,v) ∈ S | v > C}
Parameters
----------
state : tuple
a tuples of the form (u,v)
num_o... | 335b488f52688baa606928ee137cfb189ee36434 | 652,438 |
import bz2
def bz2_open(file_name, mode):
"""
Wraps bz2.open to open a .bz2 file.
Parameters
----------
file_name : str
mode : str
Returns
-------
file
Raises
------
RuntimeError
If bz2 is not available.
"""
assert mode in ('r', 'w')
if bz2 is None:
raise RuntimeError('bz2 m... | 79ff4c0284b585a8082e1360ac2b87e114c1ebba | 652,442 |
def reshape_fortran(tensor, shape):
"""The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result
"""
return tensor.T.reshape(tuple(rever... | 4b4afc1fb30507213d7ecb6869cc07aa33f75d88 | 652,449 |
def get_non_conflicting_name(template, conflicts, start=None, get_next_func=None):
""" Find a string containing a number that is not in conflict with any of
the given strings. A name template (containing "%d") is required.
You may use non-numbers (strings, floats, ...) as well. In this case
... | 9ec399179144ac651d55c8e645de1901805097ae | 652,451 |
def onebindingsite(x, A, B, C, D):
"""One binding site model
y = A * x / (B + x) + C * x + D
A is max
B is Kd
C is nonspecific
D is background
"""
return A * x / (B + x) + C * x + D | 540280a89a94bd115325d3592c560dc079355b15 | 652,452 |
from typing import Tuple
import re
import warnings
def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
"""Parse glibc version.
We use a regexp instead of str.split because we want to discard any
random junk that might come after the minor version -- this might happen
in patched/forked vers... | 547df79704865287060b07742a5a1fb0f589da3e | 652,453 |
from typing import Optional
def decode_cookies(string_to_decode: Optional[str] = None) -> Optional[str]:
"""
Decode the latin-1 string, and encode it to utf-8.
Args:
string_to_decode: string to decode
Returns:
Optional[str]: decoded string
"""
if string_to_decode:
ret... | f2b3b06af321a0e168d4075ea287c51f0392c824 | 652,455 |
def perplexity(self, text):
"""
Calculates the perplexity of the given text.
This is simply 2 ** cross-entropy for the text.
:param text: words to calculate perplexity of
:type text: Iterable[str]
"""
return pow(2.0, self.entropy(text)) | 3959f87c4b765f7db2e50542a7d896a0fcf70cea | 652,462 |
def valid_limit(limit, ubound=100):
"""Given a user-provided limit, return a valid int, or raise."""
limit = int(limit)
assert limit > 0, "limit must be positive"
assert limit <= ubound, "limit exceeds max"
return limit | abfcfa5de9f51055f0bfc8910ce8d98e03159af7 | 652,468 |
def crop(image):
"""Crop the image (removing the sky at the top and the car front at the bottom)
Credit: https://github.com/naokishibuya/car-behavioral-cloning
"""
return image[60:-25, :, :] | d2ae9039b8941a7b7a10d3659d6272de3d6f0987 | 652,470 |
def get_content_type(result_set):
""" Returns the content type of a result set. If only one item is included
its content type is used.
"""
if len(result_set) == 1:
return result_set[0].content_type
else:
return "multipart/related" | a771110f6db874ea9cc5284e95db2e023395e1de | 652,471 |
def chk_enum_arg(s):
"""Checks if the string `s` is a valid enum string.
Return True or False."""
if len(s) == 0 or s[0].isspace() or s[-1].isspace():
return False
else:
return True | 25d906b539b75031bf2ec040f2531bd78caecf8e | 652,475 |
from pathlib import Path
def _sqlite_uri_to_path(uri: str) -> Path:
"""Convert a SQLite URI to a pathlib.Path"""
return Path(uri.split(':')[-1]).resolve() | 1cd71c8f6957f84818086f3382449c55c2004f2c | 652,476 |
def BytesFromFile(filename):
"""Read the EDID from binary blob form into list form.
Args:
filename: The name of the binary blob.
Returns:
The list of bytes that make up the EDID.
"""
with open(filename, 'rb') as f:
chunk = f.read()
return [int(x) for x in bytes(chunk)] | 47d13dd1ea1443c53302c655d478aa4ef8773c7d | 652,477 |
import pathlib
def tmp_yaml(tmp_path: pathlib.Path) -> pathlib.Path:
"""Temporary copy of path.yaml."""
dest_path = tmp_path / "path.yaml"
src_path = pathlib.Path("tests/data/path.yaml")
text = src_path.read_text()
dest_path.write_text(text)
return dest_path | dfa35cd3877e72e1d51696276463c540fc8c3fef | 652,486 |
def get_parameter_for_sharding(sharding_instances):
"""Return the parameter for sharding, based on the given number of
sharding instances.
Args:
sharding_instances: int. How many sharding instances to be running.
Returns:
list(str). A list of parameters to represent the sharding config... | b4d844b9248002b638be4546aba13410d1081400 | 652,488 |
def _set_default_junction_temperature(
temperature_junction: float,
temperature_case: float,
environment_active_id: int,
) -> float:
"""Set the default junction temperature for integrated circuits.
:param temperature_junction: the current junction temperature.
:param temperature_case: the curre... | 3cf1adadab18d76ed72548df4deaac0743a55e8d | 652,489 |
from typing import List
def erase_overlap_intervals_count(intervals: List[List[int]]) -> int:
"""
LeteCode 435: Non-overlapping Intervals
Given a list of intervals, find the minimum number of intervals you need to remove
to make the rest of the intervals non-overlapping.
Examples:
1. i... | 3766b368079f8bd71d51976d41f15a10b130aced | 652,493 |
def remove_title(soup):
"""Deletes the extra H1 title."""
h1 = soup.find('h1')
if h1:
h1.extract()
return soup | 3017bc18ddb8a6fe4a4be1333de9e7ff3d7150c7 | 652,499 |
import re
def _convert_to_db_type(sval):
""" Detect which database type (string, int, float) is most appropriate for sval
and convert it to its corresponding database type. """
# floats: Ex. 1.23, 0.23, .23
if re.search(r'^\s*\d*\.\d+\s*$', sval):
return float(sval)
# ints: Ex. 0, 12... | acb1f0d05f6307b73c77b95f4166957bf748a6f9 | 652,504 |
def source_key(resp):
"""
Provide the timestamp of the swift http response as a floating
point value. Used as a sort key.
:param resp: httplib response object
"""
return float(resp.getheader('x-put-timestamp') or
resp.getheader('x-timestamp') or 0) | 80d56dfe1e4e0ddc9e1eeabb20a05e9b19357cb8 | 652,505 |
def calculate_c_haines_index(t700: float, t850: float, d850: float) -> float:
""" Given temperature and dew points values, calculate c-haines.
Based on original work:
Graham A. Mills and Lachlan McCaw (2010). Atmospheric Stability Environments
and Fire Weather in Australia – extending the Haines Index.
... | 153a994a5437faedfc275689f7682f426b390504 | 652,506 |
def is_mol_parameter(param):
"""Identify if a parameter is a `mol` parameter."""
parts = param.split("_")
return param.startswith("mol_") \
and parts[-1].isdigit() \
and len(parts) > 2 | 5c6d3324922d393b5d17ed26f5c665f8e98a1d24 | 652,511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.