content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def get_remote_ip_from_request(request) -> str:
"""Retrieve remote ip addr from request.
:param request: Django request
:type: django.http.HttpRequest
:return: Ip address
:rtype: str
"""
if x_forwarded_for := request.META.get('HTTP_X_FORWARDED_FOR'):
ip_addr = x_forwarded_for.split(',')[0]
else:
ip_addr = request.META.get('REMOTE_ADDR')
return ip_addr | cdafe628d1c4cdcd7a980bb80b19d5983cac4932 | 177,949 |
def hasgetattr(obj, attr, default=None):
""" Combines hasattr/getattr to return a default if hasattr fail."""
if not hasattr(obj, attr):
return default
return getattr(obj, attr) | 5e2dd25469506a71b2ef20293e623ab9dbc1c8cc | 453,602 |
def collapse_codepoints(codepoints):
"""
Convert a list of code points in a list of ranges.
Given a list of code points, extract the ranges with the maximal length from
consecutive code points.
:param: codepoints: List of code points.
:returns: List of ranges (first_cp, last_cp)
>>> ranges = collapse_codepoints([1,2,3,4,7,10,11,12,15])
>>> ranges == [(1,4), (7, 7), (10, 12), (15,15)]
True
"""
result = []
# Sort list
codepoints = sorted(codepoints)
first_cp = codepoints[0]
last_cp = codepoints[0]
for cp in codepoints[1:]:
if cp == last_cp + 1:
# Code point is continuous of last one, extend range
last_cp = cp
else:
# Code point is not successor of last one, create new range
result.append((first_cp, last_cp))
first_cp = cp
last_cp = cp
result.append((first_cp, last_cp))
return result | 7bd9a32cd32047cb42657b6ea6f7867af0d51bd1 | 472,423 |
def cumsum(t):
"""Computes the cumulative sum of the numbers in t.
t: list of numbers
returns: list of numbers
"""
total = 0
res = []
for x in t:
total += x
res.append(total)
return res | e3c1d6c3191f4813af87d2da091d023ff09beaa2 | 414,015 |
import re
def find_date_lines_in_description(description):
"""
output: a list of matches in format
date: the date of the match
line: the full line
line_before: the text matches before the date
line_after: the text matches after the date
"""
description.strip()
output = []
splitdescription = description.splitlines()
for line in splitdescription:
p = re.compile(
r"(?P<line_before>.*?)(?P<date>\d\d*[^0-9]?\d\d?[^0-9]?\d\d+)\s?(?P<line_after>.*)")
matches = p.finditer(line)
for match in matches:
date = match.group("date")
line_before = match.group("line_before")
line_after = match.group("line_after")
output.append({"date": date, "line_before": line_before, "line_after": line_after, "line_full": line })
return output | a042fdc32c1d986ed60dcd98e2e65bd63877a86b | 204,530 |
def data_to_psychomotor(dic):
"""
Returns a dictionary of psychomotor details of each student
{name:{details}}
"""
final_dic = {} #will return to psychomotor
dic_psymo = dic["psychomotor"][0] #the relevant sheet
for key, value in dic_psymo.items():
del value["AGE"]
final_dic[key] = value
del final_dic["Name"]
return final_dic | a544b0ec8c8e3639ed9e5f82c5b0853c3e283a7e | 636,605 |
def album_info_query(album_id: str) -> dict:
"""
Build Album information query.
:param album_id: Album id
:return: Query
"""
return {
"operationName": "AlbumGet",
"query": """query AlbumGet($id: ID!) {
album {
get(id: $id) {
... on Album {...AlbumStandard}
... on MutationError {errors {code message}}
}
}
}
fragment AlbumStandard on Album {
id
title
slug
url
description
created_by {
name
display_name
}
number_of_pictures
number_of_animated_pictures
language {
title
}
tags {
text
}
genres {
title
}
audiences {
title
}
}
""",
"variables": {
"id": album_id
}
} | 8ba2415726c23c38c546168d20f3cd0aae84fb18 | 397,955 |
def github_split_owner_project(url):
"""
Parses the owner and project name out of a GitHub URL
Examples
--------
>>> github_split_owner_project("https://github.com/intel/dffml")
('intel', 'dffml')
"""
return dict(
zip(
("owner", "project"),
tuple("/".join(url.split("/")[-2:]).split("/")),
)
) | ea3d788f92c0936babf48000c51eba3ec2c1ac73 | 72,159 |
def comp_float(x, y):
"""Approximate comparison of floats."""
return abs(x - y) <= 1e-5 | 8f3a520a0c8017aa1181e413f46491dbbec0210e | 400,517 |
def leia_int(msg=''):
"""-> Função que requisita um número e verifica se ele é inteiro, podendo utilizar-se de uma mensagem para isso.
:param msg: valor opcional, mensagem pela qual o programa requisitara inserção de um número.
:return: valor fornecido, se realmente for inteiro."""
valor = input(msg)
while True:
analise = valor.isnumeric()
if analise:
break
else:
valor = input(f"\033[31mERRO!Digite um número inteiro válido\033[m\n{msg}")
return valor | 60680c3f6550c3f26d948f443003bddd5658622e | 191,590 |
from xml.sax.saxutils import escape
def _make_in_prompt(prompt_template, number=None):
""" Given a prompt number, returns an HTML In prompt.
"""
try:
body = prompt_template % number
except TypeError:
# allow in_prompt to leave out number, e.g. '>>> '
body = escape(prompt_template)
return '<span class="in-prompt">%s</span>' % body | 0d9dd26f7d5aad9ad37e8c6fe22b2592d95bb5b6 | 472,200 |
def get_weekday_word(number):
"""
Using weekday index return its word representation
:param number: number of weekday [0..6]
:return: word representation
"""
weekdays = (
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday'
)
return weekdays[number] | d65c10635a4c9bfdf599129a84e37b3fe7c476b4 | 556,205 |
def check_len(key, val, val_len=2, ext='primary'):
"""
Check if the length of the keyword value has a a given length, default value for the length check is 2.
Args:
key: keyword
val: keyword value
val_len: length to be checked against
ext: string, extension number (default value is 'primary')
Returns:
A warning (if the length was not what was expected) or nothing.
"""
if isinstance(val, int):
string_length = len(str(val))
else:
string_length = len(val)
warning = '{:<15} {:<9} {:<25}'.format(key, ext, 'Incorrect length of value. Expected: '+repr(val_len)+', got '+repr(string_length))
if string_length == val_len:
print ('{:<15} {:<9} {:<25}'.format(key, ext, 'Correct format'))
else:
print (warning)
return warning | cfe913a5831f27d2793e17e2c5947ec351a4e1a5 | 245,065 |
import pprint
def pretty(d: dict) -> str:
""" Prettify a dictionary """
return pprint.pformat(d, indent=2, width=100, compact=True) | 013b337de3b610a5fdc044d5087a4b17f0e5c8b5 | 542,247 |
def eval_guess(chosen, guess):
"""Check if the number guessed by the user is the same as the number chosen by the program.
Parameters:
chosen (int>=0): Number chosen by the program.
guess (int>=0): Number guessed by the user.
Returns:
(str): Hint to help the user in the next guess; one of: "Well done!", "Guess lower!", "Guess higher!".
(int): 1 if the guess is the same as the chosen; 0 otherwise.
"""
if guess == chosen:
val = 1
return("Well done!", val)
elif guess > chosen:
val = 0
return("Guess lower!", val)
else:
val = 0
return("Guess higher!", val) | 0e78ea9a06d89962d31cf3987fdb658d30bc79be | 611,957 |
def object_list_check_any_has_attribute(object_list,attr_name):
"""
check if any object in the list has the attribute.
"""
unique = False
for obj in object_list:
if hasattr(obj,attr_name):
unique = True
break
else:
pass
return unique | cac90dab958b4bfc25493a2dba86b72454230222 | 24,162 |
def trim_unknown_energies(casm_query_json,keyword="energy"):
"""
Given a data dictionary from a casm query sorted by property, removes data with null/None values in the designated key
Parameters
----------
casm_query_json : list of dicts
A dictionary from a casm query sorted by property. Loaded directly from query json.
key : str
The key in the data dictionary that corresponds to the value you want to base entry removal. Defaults to 'energy_per_atom'.
Returns
-------
denulled_data: dict
A dictionary with the same keys as the input data, but with entries removed for which the key value is null.
"""
initial_length = len(casm_query_json)
denulled_data = [entry for entry in casm_query_json if entry[keyword] is not None]#
final_length = len(denulled_data)
print("Removed %d entries with null values with key: %s" % (initial_length - final_length, keyword))
return denulled_data | a2d08303bd86deca3ee191f690c7177768179f2b | 143,073 |
def prefilter_by_attractor(networks, attractors, partial=True):
"""
DESCRIPTION:
A function to filter boolean networks based on if they hold certain
attractors or not.
:param networks: [list] boolean networks (dict) to filter based on
their attractors.
:param attractors: [list] attractors (str) to filter the networks.
:param partial: [bool] flag to indicate if the condition should be
relaxed. If partial == True, then it will be enough for the network
to show just one attractor from the list to pass the filter. If False
the network will need to show all the attractors in the list.
"""
# Helper functions
def check_node(node_index, nodes, attractor, network):
node = nodes[node_index]
# Check if the attractor value is 1 or 0
if int(attractor[node_index]):
result = attractor in network['network'][node]
else:
result = attractor not in network['network'][node]
return result
# Iterate over every network
nodes = list(networks[0]['network'].keys())
for network in networks:
# Network might be a None resulting from unsuccessful conflict solving
if network is not None:
attractor_conditions = []
# Check every attractor
for attractor in attractors:
node_conditions = [check_node(node_index, nodes, attractor, network)
for node_index in range(len(nodes))]
attractor_conditions.append(all(node_conditions))
if all(attractor_conditions) or partial and any(attractor_conditions):
yield network | 3fdc1e0051ba2ddcf299f3b8eeb48bae9915b310 | 184,941 |
from typing import Optional
from typing import Callable
def get_custom_attribute(item: dict, attribute_code: str, coerce_as: Optional[Callable] = None):
"""
Get a custom attribute from an item given its code.
For example:
>>> get_custom_attribute(..., "my_custom_attribute")
"0"
>>> get_custom_attribute(..., "my_custom_attribute", bool)
False
:param item:
:param attribute_code:
:param coerce_as: optional callable that is called on the attribute value if it's set.
This is useful to circumvent Magento's limitation where all attribute values are strings.
:return: attribute value or None.
"""
for attribute in item.get("custom_attributes", []):
if attribute["attribute_code"] == attribute_code:
value = attribute["value"]
if coerce_as:
if coerce_as == bool:
# "0" -> False / "1" -> True
return bool(int(value))
return coerce_as(value)
return value | 89b49a39de6269064bf6f99defedda35346c85b2 | 103,286 |
def fromTM35FINToMap(x, y):
"""
Function for moving from TM35FIN coordinates into the coordinates of the
picture
"""
pic_h = 2480
pic_w = 1748
x_min = -40442
y_min = 6555699
x_max = 837057
y_max = 7800801
y_max -= y_min
x_max -= x_min
x_return = pic_w * (x - x_min) / x_max
y_return = pic_h * (y_max - (y - y_min)) / y_max
return x_return, y_return | 6519634fece8b1acc308f2262dc29f5ba45a00dc | 210,238 |
import hashlib
def string_hash(string: str, algo: str = 'sha1') -> str:
"""Returns the hash of the specified string."""
return getattr(hashlib, algo)(string.encode('utf-8')).hexdigest() | c8a4423a3548e7b8b9d7171ec1e5020e5f3012d6 | 553,125 |
def unique_list_order_preserved(seq):
"""Returns a unique list of items from the sequence
while preserving original ordering.
The first occurrence of an item is returned in the new sequence:
any subsequent occurrences of the same item are ignored.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | e4157ee4cb016f514ba70a879fb18a706b5a7743 | 365,178 |
def AddNoGlob(options):
"""
If the option 'no_glob' is defined, add it to the cmd string.
Returns: a string containing the knob
"""
string = ''
if hasattr(options, 'no_glob') and options.no_glob:
string = ' --no_glob'
return string | e44c34a7d9652886080ae4167d80b631ffa8b9f9 | 659,426 |
import math
def round_repeats(depth_coefficient, repeats):
""" Round number of filters based on depth coefficient.
Args:
depth_coefficient: Coefficient to scale number of repeats.
repeats: Number to repeat mb_conv_block.
From tensorflow implementation:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet
/efficientnet_model.py
"""
return int(math.ceil(depth_coefficient * repeats)) | bafa99e8a406e068406806703be122573c68b084 | 46,348 |
def lerp(pt1, pt2, intervals):
"""Linear interpolation.
Args:
pt1: Array of points. When interval is 0, the result is pt1.
pt2: Array of points. When interval is 1, the result is pt2.
intervals: Array of intervals at which to evaluate the
linear interpolation
>>> x = np.array([1, 0, 0])
>>> y = np.array([0, 0, 1])
>>> t = np.linspace(0, 1, 4)[:, np.newaxis]
>>> lerp(x, y, t)
array([[ 1. , 0. , 0. ],
[ 0.66666667, 0. , 0.33333333],
[ 0.33333333, 0. , 0.66666667],
[ 0. , 0. , 1. ]])
"""
t = intervals
return (1 - t)*pt1 + t*pt2 | c0f390025a6b9b22101889bd9cbfa443b3920ef5 | 374,738 |
import statistics
def run_stats(this_set):
""" Find standard deviation and mean (average) for the data set. """
# Simply calculate Mean & StdDev for this set.
# Return TUPLE of FLOATS
return statistics.mean(this_set), statistics.stdev(this_set) | 35ce499654bf7e8fe43d862b5456b0578a093fc7 | 13,289 |
def file_type(infile):
"""Return file type after stripping gz or bz2."""
name_parts = infile.split('.')
if name_parts[-1] == 'gz' or name_parts[-1] == 'bz2':
name_parts.pop()
return name_parts[-1] | 0bc762667bff0f233b176603f7ef8b54d254c6db | 503,403 |
import json
def load_model_info(model_path):
"""Load model info from file.
Args:
model_path (string): the full path of where the model is located.
Raises:
ValueError: raise an error if the path is invalid.
Returns:
dict: the inputs / outputs info dict.
"""
if model_path.endswith(".tflite"):
info_path = model_path.split(".tflite")[0] + ".info"
elif model_path.endswith(".h5"):
info_path = model_path.split(".h5")[0] + ".info"
else:
raise ValueError("Invalid model path")
with open(info_path, "r") as f:
return json.load(f) | 8f9aba13db8ef6f9808d9b59cdf46c332e5fcada | 464,114 |
from typing import Tuple
def pyth_triple(u: int, v: int) -> Tuple[int, int, int]:
"""
Generates a Pythagorean triple (u^2 - v^2, 2uv, u^2 + v^2).
Conditions:
1) u > v >= 1
:param u: natural number
:param v: natural number
:return: A Pythagorean triple with a odd and b even.
"""
if not u > v:
raise ValueError("First argument must strictly be greater than the second.")
elif not v >= 1:
raise ValueError("Second argument must be greater than or equal to 1.")
return u**2 - v**2, 2*u*v, u**2 + v**2 | 1732440074a1755176cf67a5a956c057e6a30621 | 538,792 |
from typing import Dict
from typing import Any
from typing import List
def get_label_ids_by_category(crop: Dict[str, Any],
category: str) -> List[int]:
"""
Get all label ids from a crop that belong to a certain category
Args:
crop: Instance of an entry in the crop database.
category: one of "present_annotated", "present_unannotated", "absent_annotated", "present_partial_annotation"
Returns:
All label ids that belong to the `category` for that crop.
"""
return [ll[0] for ll in crop['labels'][category]] | 2bbc4a79dabe2eedee7438107e1b23c6ae869f24 | 131,721 |
def merge_dicts(*args):
"""
Merge multiple dictionaries each with unique key
:param args: dictionaries to merge
:return: 1 merged dictionary
"""
result = {k: v for d in args for k, v in d.items()}
return result | 34768ac3bd0a79fa9d1a4939122262a6fbd186fc | 100,727 |
import math
def plating_efficiency_multiplier(z):
""" Plating efficiency correction multiplier for number of mutations per culture
from [Steward, 1990].
z is the probability that any given mutant cell will generate a colony.
:param z: fraction of a culture plated (plating efficiency); 0 < z <= 1
:return: correction multiplier for number of mutations per culture
"""
assert 0 < z <= 1
if z == 1:
return 1 # by l'Hôpital's rule
return (z - 1) / (z * math.log(z)) | 645f05bd1e3947cae8135d343241fbe240bea358 | 480,548 |
def set_up_folder_name_1M ( model_file , date_run ):
"""
Produce log_file, plot_folder based on model_file (file name ending with _sd.pt)
If model_file is epoch_1_sd.pt, date_run is 0913: plot_folder 'plot_2d_epoch_1', log file 'log_0913_2d_epoch_1'
"""
# if model_file == '': model_pure = f'ep{ep_ind}'
model_pure = model_file[:model_file.rfind('_sd.pt')]
plot_folder = f'plot_2d_{model_pure}'
log_file = f'log_{date_run}_2d_{model_pure}' # .out This is the log file, recording the printing
return log_file, plot_folder | d7dd24789476279ea8d5fe0b32627aa049731ef7 | 699,081 |
import string
def remove_punctuation(list_of_string, item_to_keep=""):
"""
Remove punctuation from a list of strings.
Parameters
----------
- list_of_string : a dataframe column or variable containing the text stored as a list of string sentences
- item_to_keep : a string of punctuation signs you want to keep in text (e.g., '!?.,:;')
"""
# Update string of punctuation signs
if len(item_to_keep) > 0:
punctuation_list = "".join(
c for c in string.punctuation if c not in item_to_keep
)
else:
punctuation_list = string.punctuation
# Remove punctuation from each sentence
transtable = str.maketrans("", "", punctuation_list)
return [sent.translate(transtable) for sent in list_of_string] | cb9190bc160f8e725479b531afab383c6857ceac | 706,141 |
def get_cv_object(train):
"""
Return Time Based CV Object.
Time based CV scheme: {train month(s) - test month}
{1}-{2}
{1,2}-{3}
{1,2,3}-{4}
{1,2,3,4}-{5,6}
"""
tx_month = train['DayNumber']//30
d = {}
for fold in range(5):
if (fold == 4):
break
elif (fold == 3):
d['fold_'+str(fold)+'_train'] = tx_month.loc[(tx_month <= fold)].index
d['fold_'+str(fold)+'_test'] = tx_month.loc[(tx_month > fold + 1)].index
else:
d['fold_'+str(fold)+'_train'] = tx_month.loc[(tx_month <= fold)].index
d['fold_'+str(fold)+'_test'] = tx_month.loc[(tx_month == fold+2)].index
cvobj = [ (d['fold_' + str(fold) + '_train'], d['fold_' + str(fold) + '_test']) for fold in range(4)]
return cvobj | e5ce051d292588d151d1487f70a8cd254479dfd2 | 592,313 |
def get_and_remove_or_default(dict, key, default):
"""
Get an item from a dictionary, then deletes the item from the dictionary.
If the item is not found, return a default value.
:return: The value corresponding to the key in the dictionary, or the default value if it wasn't found.
"""
if key in dict:
ret = dict[key]
del dict[key]
return ret
else:
return default | 402be98aa112010abfffa1e3dcb2ae9686a12a62 | 71,762 |
def update_pid(df, suffix):
""" Add a customized suffix to the 'patientId'
"""
df_update = df.copy()
df_update["patientId"] = df["patientId"] + suffix
return df_update | b5c4e48cddc36cf8f39e63237da9025d93e7f232 | 399,540 |
def helper_stationary_value(val):
"""
Helper for creating a parameter which is stationary (not changing based on t)
in a stationary fuzzy set. Returns the static pertubation function
Parameters:
-----------
val : the stationary value
"""
return lambda t: val | 1228b3a85a6026c18ebaf57b87841372e73566c6 | 67,306 |
def _to_skybell_level(level):
"""Convert the given Safegate Pro light level (0-255) to Skybell (0-100)."""
return int((level * 100) / 255) | 67f290d5d14372e928a68b2443d3dc7f41cf26cc | 395,991 |
import random
def get_random_integer(number):
"""
This function takes in a number and returns a random integer between 0 and that number
"""
return random.randint(0, number) | e5456480530f01f013428f9c5827421b7aaa12f0 | 671,921 |
def binary_search(value, array, start_idx=None, end_idx=None):
"""
Выболняет бинарный поиск значения в отсортированном по возрастанию массиве.
:param value: Значение, которое необходимо найти.
:param array: Массив поиска.
:param start_idx: Начальный индекс поиска (для рекурсивного вызова)
:param end_idx: Конечный индекс поиска (для рекурсивного вызова)
:return: Возвращает индекс элемента массива, содержащего искомое значение. Либо -1, если такой элемент не найден.
"""
if start_idx is None:
start_idx = 0
if end_idx is None:
end_idx = len(array)
array_length = end_idx - start_idx
if array_length == 1: # Базовый случай рекурсии
if array[start_idx] == value:
return start_idx
else:
return -1
elif array_length <= 0:
return
middle_idx = start_idx + array_length // 2
if value == array[middle_idx]:
return middle_idx
elif value < array[middle_idx]:
return binary_search(value, array, start_idx, middle_idx)
elif value > array[middle_idx]:
return binary_search(value, array, middle_idx, end_idx) | efb1396d00d44cc669c1c8d344d3334894181ae7 | 662,401 |
import math
def wavy(ind, k=10.):
"""Wavy function defined as:
$$ f(x) = 1 - \frac{1}{n} \sum_{i=1}^{n} \cos(kx_i)e^{-\frac{x_i^2}{2}}$$
with a search domain of $-\pi < x_i < \pi, 1 \leq i \leq n$.
"""
return 1. - sum(( math.cos(k * ind[i]) * math.exp(-(ind[i]*ind[i])/2.) for i in range(len(ind)))) / float(len(ind)), | a25c99dc8cf3f9b066dd2bbc21cc8f2b41a249f2 | 69,820 |
def has_count(unit):
""" return true if unit has count """
return unit.get('Count', 0) > 0 | dff8c841c981f0361498865cae1adc50b1c9f77e | 435,663 |
def getmeta(resource_or_instance):
"""
Get meta object from a resource or resource instance.
:param resource_or_instance: Resource or instance of a resource.
:type resource_or_instance: odin.resources.ResourceType | odin.resources.ResourceBase
:return: Meta options class
:rtype: odin.resources.ResourceOptions
"""
return getattr(resource_or_instance, "_meta") | a5e676f75bda3f314ceeec52fb1a44a113734c2d | 589,462 |
def getweakrefs(space, w_obj):
"""Return a list of all weak reference objects that point to 'obj'."""
lifeline = w_obj.getweakref()
if lifeline is None:
return space.newlist([])
else:
result = []
for i in range(len(lifeline.refs_weak)):
w_ref = lifeline.refs_weak[i]()
if w_ref is not None:
result.append(w_ref)
return space.newlist(result) | 304bfbc6075a882cf78b82343df30807e9ced7dc | 594,132 |
import time
def is_bst(st: time.struct_time) -> bool:
"""
Calculates whether the given day falls within British Summer Time.
.. note::
This function does not consider the time of day,
and therefore does not handle the fact that the time changes at 1 AM GMT.
:param st: The :class:`time.struct_time` representing the target date..
:returns: True if the date falls within British Summer Time, False otherwise.
"""
day, month, dow = st.tm_mday, st.tm_mon, (st.tm_wday + 1) % 7
if 3 > month > 10:
return False
elif 3 < month < 10:
return True
elif month == 3:
return day - dow >= 25
elif month == 10:
return day - dow < 25
else:
return False | 7428810629c417cb8a55994b3086a7e9515194b7 | 627,570 |
def resolve_option_flag(flag, df):
"""
Method to resolve an option flag, which may be any of:
- None or True: use all columns in the dataframe
- None: use no columns
- list of columns use these columns
- function returning a list of columns
"""
if flag is None or flag is True:
return list(df)
elif flag is False:
return []
elif hasattr(flag, '__call__'):
return flag(df)
else:
return flag | c6c90d650c4edb762a4c93fb5f85a59969c8c769 | 248,125 |
def pretty_box (rows, cols, s):
"""This puts an ASCII text box around the given string, s.
"""
top_bot = '+' + '-'*cols + '+\n'
return top_bot + '\n'.join(['|'+line+'|' for line in s.split('\n')]) + '\n' + top_bot | aef083621032ec2f5c429974516233a7fa606536 | 433,493 |
def get_output_parameters_of_execute(taskFile):
"""Get the set of output parameters of an execute method within a program"""
# get the invocation of the execute method to extract the output parameters
invokeExecuteNode = taskFile.find('assign', recursive=True,
value=lambda value: value.type == 'atomtrailers'
and len(value.value) == 2
and value.value[0].value == 'execute')
# generation has to be aborted if retrieval of output parameters fails
if not invokeExecuteNode:
return None
# only one output parameter
if invokeExecuteNode.target.type == 'name':
return [invokeExecuteNode.target.value]
else:
# set of output parameters
return [parameter.value for parameter in invokeExecuteNode.target.value] | 56ba0c1f1941a72174befc69646b4bdb6bc9e009 | 41,606 |
import re
def pipe_cleaner(spec):
"""Guess the actual URL from a "pipe:" specification."""
if spec.startswith("pipe:"):
spec = spec[5:]
words = spec.split(" ")
for word in words:
if re.match(r"^(https?|gs|ais|s3)", word):
return word
return spec | 3c5237d3f20391c9bc40bfd3dd16f1e7df422b0a | 593,187 |
def year_slice(df, first_year=None, date_col='start_date'):
"""Return slice of df containing all rows with df[date_col].dt.year >= first_year.
Returns df if first_year is None.
"""
if first_year is None:
return df
if first_year <= df[date_col].min().year:
# No need to slice
return df
return df[df[date_col] >= f"{first_year}-01-01"] | faccb0424f2d019e859bb7a3cbe2262b7255f3b5 | 313,723 |
from typing import Union
from typing import Tuple
def parse_deformation_potential(
deformation_pot_str: str,
) -> Union[str, float, Tuple[float, ...]]:
"""Parse deformation potential string.
Args:
deformation_pot_str: The deformation potential string. Can be a path to a
deformation.h5 file, a single deformation potential to use for all bands
or two deformation potentials separated by a comma for valence and
conduction bands.
Returns:
The deformation potential(s) or path to deformation potential file.
"""
if "h5" in deformation_pot_str:
return deformation_pot_str
deformation_pot_str = deformation_pot_str.strip().replace(" ", "")
try:
parts = list(map(float, deformation_pot_str.split(",")))
if len(parts) == 1:
return parts[0]
elif len(parts) == 2:
return tuple(parts)
else:
raise ValueError
except ValueError:
raise ValueError(
"ERROR: Unrecognised deformation potential format: "
"{}".format(deformation_pot_str)
) | f801e72f4a9ac26905ba55e4e200110429f7ad13 | 599,635 |
from typing import Dict
from typing import Any
def create_default_metadata() -> Dict[str, Any]:
"""Creates a dictionary with the default metadata."""
return {
'title': 'Default title',
'base_url': 'https://example.org',
'description': 'Default description',
'language': 'en-US',
'copyright': 'Licensed under the '
'<a href="http://creativecommons.org/licenses/by/4.0/"> '
'Creative Commons Attribution 4.0 International License.'
} | 2ee6aeffaafd209cb93e33bd42291ac3c12b10d8 | 700,714 |
def strip_suffixes(s, suffixes=()):
"""
Return the `s` string with any of the string in the `suffixes` set
striped. Normalize and strip spacing.
"""
s = s.split()
while s and s[-1].lower() in suffixes:
s = s[:-1]
s = u' '.join(s)
return s | 0f23dfebd402579abc9054b75a97be3dbbc2d4f1 | 327,909 |
def safelower(s):
"""
As string.lower(), but return `s` if something goes wrong.
"""
try:
return s.lower()
except AttributeError:
return s | f9320df8c1a90ab325dc04a10b36d0c8f7aecf34 | 531,386 |
def convert_to_rows(response, agg_layers, prefix={}):
"""
Converts the hierarchical, dictionary type of response from an
an Elasticsearch query into a more SQL-like list of rows (tuples).
The Elasticsearch response is expected to have a specific format, where
a series of bucket aggregations are nested in each other. The names of
these aggregations are listed in order in <agg_layers>, from top to bottom.
The bottom-level bucket (after all these nested aggregations) must contain
a doc_count as well as a numerically-valued aggregation named total_obs.
Each row of the output is a `dict` of values, matching each of the buckets
described in <agg_layers> followed by doc_count and the total_obs value.
The keys in the `dict` are descriptive terms, not necessarily the same as
the property names in Elasticsearch.
:param response: An Elasticsearch query response dictionary.
:param agg_layers: List of aggregation names from top to bottom.
:returns: Contents of the Elasticsearch response in list-of-rows format.
"""
if 'aggregations' in response:
response = response['aggregations']
if len(agg_layers) == 0:
total_files = response['doc_count']
total_obs = int(response['total_obs']['value'])
if total_files == 0:
return []
else:
row = prefix.copy()
row['total_files'] = total_files
row['total_obs'] = total_obs
return [row]
else:
layer_input_name, layer_output_name = agg_layers[0]
remaining_layers = agg_layers[1:]
rows = []
for bucket in response[layer_input_name]['buckets']:
if 'key_as_string' in bucket:
key = bucket['key_as_string']
else:
key = bucket['key']
next_prefix = prefix.copy()
next_prefix[layer_output_name] = key
rows.extend(convert_to_rows(bucket, remaining_layers, next_prefix))
return rows | 0a247d2fb7652e449f18a65e789c9c2ea4ba3dac | 307,557 |
def _pad(block, n=8):
"""Pads the block to a multiple of n
Accepts an arbitrary sized block and pads it to be a multiple of n.
Padding is done using the PKCS5 method, i.e., the block is padded with
the same byte as the number of bytes to add.
Args:
block (bytes): The block to pad, may be arbitrary large.
n (int): The resulting bytes object will be padded to a multiple of this number
Returns:
bytes: a bytes object created from the input string
"""
pad_len = n - (len(block) % n)
block += bytes([pad_len] * pad_len)
return block | e26b08ab4b77a2cde7ad882ddca0b16295db35a7 | 359,346 |
import torch
def _mask_borders(
masks: torch.Tensor,
clip_border: int
) -> torch.Tensor:
"""Masking left/right/top/down borders by setting `masks` to False
Args:
masks (torch.Tensor): mask in shape (..., h, w). torch.bool
clip_border (int): number of border pixels to mask.
Returns:
torch.Tensor: new mask in shape (..., h, w). torch.bool
"""
assert torch.is_tensor(masks), \
f"`masks` should be a torch.Tensor, got {type(masks)}"
assert len(masks.shape) >= 2, "rank of `masks` should be greater than 2"
# clip h
masks[..., :clip_border, :] = False
masks[..., -clip_border:, :] = False
# clip w
masks[..., :clip_border] = False
masks[..., -clip_border:] = False
return masks | 1c1cd6fde1effd0db591eeee9a7cec152946c8f6 | 328,744 |
def double(n):
"""
Takes a number n and doubles it
"""
return n * 2 | 8efeee1aa09c27d679fa8c5cca18d4849ca7e205 | 444 |
import csv
def load_labels(filepath):
"""
Loads and reads CSV MM-Fit CSV label file.
:param filepath: File path to a MM-Fit CSV label file.
:return: List of lists containing label data, (Start Frame, End Frame, Repetition Count, Activity) for each
exercise set.
"""
labels = []
with open(filepath, 'r') as csv_file:
reader = csv.reader(csv_file)
for line in reader:
labels.append([int(line[0]), int(line[1]), int(line[2]), line[3]])
return labels | 067ebedc5db5e61e414fdf142664be20fc22b2a7 | 558,563 |
def _strip_double_quotes(string: str) -> str:
"""Removes encapsulating double quotes, if there are some.
Ignores non-encapsulating double quotes (one side only or inside).
Args:
string: The string to be pruned.
Returns:
The pruned string without encapsulating double quotes.
"""
if not string or string == '""':
return ""
if len(string) >= 2 and string[0] == '"' and string[-1] == '"':
return string[1:-1]
return string | 0c09e6e9579ea4bc7137495aeaf16ae9291a58d0 | 498,549 |
def sort_srv_results(results):
"""
Sort a list of SrvRecords by weight and priority.
"""
results.sort(key=lambda x: (x.priority << 16) | x.weight)
return results | 4090b0e6a25cfbe6b7ba4b1c3452ded311b23e2f | 262,088 |
def timecode_to_milliseconds(code):
""" Takes a time code and converts it into an integer of milliseconds.
"""
elements = code.replace(",", ".").split(":")
assert(len(elements) < 4)
milliseconds = 0
if len(elements) >= 1:
milliseconds += int(float(elements[-1]) * 1000)
if len(elements) >= 2:
milliseconds += int(elements[-2]) * 60000
if len(elements) >= 3:
milliseconds += int(elements[-3]) * 3600000
return milliseconds | 6f25c32fd427692c61b1536d0611cffac1832213 | 201,381 |
def make_ucsc_chr(interval):
"""
Converts interval from ENSEMBL chroms to UCSC chroms
(appends str to each chrom)
"""
interval.chrom = "chr" + interval.chrom
return interval | d5878670494dc51e29922d43a605634f26cd8e00 | 37,207 |
def get_spans_in_offsets(spans, start, end):
"""Return the list of spans (nlplingo.text.text_span.Span) that are within (start, end) offsets
:type spans: list[nlplingo.text.text_span.Span]
Returns:
list[text.text_span.Span]
"""
ret = []
for span in spans:
if start <= span.start_char_offset() and span.end_char_offset() <= end:
ret.append(span)
return ret | ffc1d910595074ba3340ce3187ef0b1566bd2909 | 654,776 |
def addEdges(graph, edges):
"""
This function adds edges to a given graph together with their weights
"""
for i in edges:
graph.add_edge(i[0],i[1], weight=i[2])
return graph | 92af0c4f093126616abeaf1f07a062a4273087d5 | 515,939 |
from typing import List
from typing import Dict
def get_flags(args: List[str]) -> Dict[str, List[str]]:
"""
Returns a dictionary containing the flags within the passed through command line arguments.
# Example
```py
# $ py ./src/main.py normal_argument -flag1 Hello, World -flag2 -flag3 This is the third flag.
flags = get_flags(sys.argv[1::])
expected_flags = {
"-flag1": ["Hello,", "World"],
"-flag2": [ ],
"-flag3": ["This", "is", "the", "third", "flag."],
}
assert flags == expected_flags
```
"""
result: Dict[str, List[str]] = { }
while args:
current = args.pop(0)
if current[0] == "-":
result[current] = [ ] # Flag Parameters
while args:
if args[0][0] == "-": break
result[current].append(args.pop(0))
return result | 2eba1fd243824b8e212b45e70c60b30ec225398d | 645,356 |
import re
def check_valid_dob(dob):
"""
Checks if the dob is in a valid format
"""
x = re.search("[0-9]{4,4}\-[0-9]{1,2}\-[0-9]{1,2}", dob)
return True if x is not None else False | 0c7b516a98d513938bfa304fc0a65ffbc84a512f | 441,627 |
def dna_strength(seq):
"""Calculates DNA strength
Args:
seq (str): sequence of A, C, T, G, N with len > 1
Returns:
DNA strength (float): normalized by length
Raises:
ValueError: if input is None or str shorter than 2
Citation:
Khandelwal et al. 2010. 'A Phenomenological Model for
Predicting Melting Temperature of DNA sequences', PLOS ONE
"""
# Adapted from Table 1 Khandelwal et al (2010).
# Modified for N-containing di-nucleotide (averaged over possible cases)
strength_values = {
"GC": 13,
"CC": 11,
"GG": 11,
"CG": 10,
"AC": 10,
"TC": 8,
"AG": 8,
"TG": 7,
"GT": 10,
"CT": 8,
"GA": 8,
"CA": 7,
"AT": 7,
"TT": 5,
"AA": 5,
"TA": 4,
"AN": 7.5,
"CN": 9,
"GN": 10.5,
"TN": 6,
"NA": 6,
"NC": 10.5,
"NG": 9,
"NT": 7.5,
"NN": 8.25,
}
if not seq or len(seq) < 2:
raise ValueError("Input must be string with 2-nt or longer")
strength = 0
for i in range(len(seq) - 1):
# return 8.25 ('NN'-value) for 2-mer not in the dictionary
strength = strength + strength_values.get(seq[i : i + 2], 8.25)
return strength / len(seq) | 9462ffc34ef6a644e470e23262afcfd6d279564d | 524,530 |
def init_headers(token):
""" Returns a dictionary of headers with authorization token.
Args:
token: The string representation of an authorization token.
Returns:
The headers for a request with the api.
"""
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
return headers | 163a5fc5d5685fcff85a295eca21334fa4dca4a7 | 485,073 |
from typing import OrderedDict
def optimise_autopkg_recipes(recipe):
"""If input is an AutoPkg recipe, optimise the yaml output in 3 ways to aid
human readability:
1. Adjust the Processor dictionaries such that the Comment and Arguments keys are
moved to the end, ensuring the Processor key is first.
2. Ensure the NAME key is the first item in the Input dictionary.
3. Order the items such that the Input and Process dictionaries are at the end.
"""
if "Process" in recipe:
process = recipe["Process"]
new_process = []
for processor in process:
processor = OrderedDict(processor)
if "Comment" in processor:
processor.move_to_end("Comment")
if "Arguments" in processor:
processor.move_to_end("Arguments")
new_process.append(processor)
recipe["Process"] = new_process
if "Input" in recipe:
input = recipe["Input"]
if "NAME" in input:
input = OrderedDict(reversed(list(input.items())))
input.move_to_end("NAME")
recipe["Input"] = OrderedDict(reversed(list(input.items())))
desired_order = [
"Comment",
"Description",
"Identifier",
"ParentRecipe",
"MinimumVersion",
"Input",
"Process",
"ParentRecipeTrustInfo",
]
desired_list = [k for k in desired_order if k in recipe]
reordered_recipe = {k: recipe[k] for k in desired_list}
reordered_recipe = OrderedDict(reordered_recipe)
return reordered_recipe | c48611e6b47c9b9061146ddc5190645339b97578 | 620,187 |
from typing import Tuple
def parse_interval(interval: str) -> Tuple[str, str, str]:
"""
Split the interval in three elements. They are, start time of the working day,
end time of the working day, and the abbreviation of the day.
:param interval: A str that depicts the day, start time and end time
in one string. Ex.: 'SA14:00-18:00'
:return: A tuple with three strings. Ex.: ('SA', '14:00', '18:00')
"""
interval_parsed = interval.split('-')
day = interval_parsed[0][:2] # SU
initial_hour = interval_parsed[0][2:] # '19:00'
end_hour = interval_parsed[1] # '21:00'
return day, initial_hour, end_hour | f2bac53a1b56e1f6371187743170646c08109a27 | 41,547 |
def read_file_from_disk(path, encoding='utf-8'):
"""
Utility function to read and return a file from disk
:param path: Path to the file to read
:type path: str
:param encoding: Encoding of the file
:type encoding: str
:return: Contents of the file
:rtype: str
"""
with open(path, 'r', encoding=encoding) as fp:
return fp.read() | 53274609b3a63a591f87c92df45d552e4e27dd4a | 359,077 |
def update_min_size(widget, width=None, height=None, size=None):
"""Utility function to set minimum width/height of a widget."""
size = size or widget.GetMinSize()
if width: size.SetWidth( max(width, size.GetWidth()))
if height: size.SetHeight(max(height, size.GetHeight()))
widget.SetMinSize(size)
return size | f6efd83e45331c0b21fabff35fb75b48806f1fc1 | 279,256 |
def str_rstrip(S, substr):
"""Strips a suffix from S if it matches the string in `substr'.
"""
# This is akin to ${VAR%$substr} in Bourne-shell dialect.
if len(substr) > 0 and S.endswith(substr):
return S[:-len(substr)]
else:
return S | 2c2c85989880d711fdda8093fda1b4b319063d4a | 215,913 |
import re
def parse_conf(dir):
"""
Extract the Autoinstall and md5sum fields from the
package.conf file
Args:
- dir: directory name
Returns:
(autoinstall value, checksum value), where
autoinstall value is "True" or "False"
"""
md5pat = re.compile('^md5sum=(.*)$')
autopat = re.compile('^Autoinstall=(.*)$')
checksum = None
autoinstall = None
with open(dir + '/package.conf', 'r') as fp:
for line in fp:
m = md5pat.match(line)
if m:
checksum = m.group(1)
else:
m = autopat.match(line)
if m:
autoinstall = m.group(1)
if autoinstall and checksum:
return (autoinstall, checksum)
return (autoinstall, checksum) | d97343e31cb4eba70186623828a3a4a4516cebe4 | 144,588 |
def dms2dd(dms):
"""
DMS to decimal degrees.
Args:
dms (list). d must be negative for S and W.
Return:
float.
"""
d, m, s = dms
return d + m/60. + s/3600. | 26ce439d9a4acc8b8d384ccb88e5142581ddcc99 | 680,238 |
def upload_project_run(upload_context):
"""
Function run by CreateProjectCommand to create the project.
Runs in a background process.
:param upload_context: UploadContext: contains data service setup and project name to create.
"""
data_service = upload_context.make_data_service()
project_name = upload_context.project_name_or_id.get_name_or_raise()
result = data_service.create_project(project_name, project_name)
data_service.close()
return result.json()['id'] | f0313f09c0e9c029648c0c87a93e45b418c13d8a | 448,628 |
def generate_train_config(model_spec, train_batch_spec, val_batch_spec, epoch_size,
n_epochs=100, lr=0.001):
""" Generates a spec fully specifying a run of the experiment
Args:
model_spec: a model spec
train_batch_spec: a batch spec for train
val_batch_spec: batch spec for validation
epoch_size: int
n_epochs: int
lr: learning rate - float
Returns:
train_spec
"""
train_spec = {
'model_spec': model_spec,
'train_batch_spec': train_batch_spec,
'val_batch_spec': val_batch_spec,
'train_spec': {
'epoch_size': epoch_size,
'n_epochs': n_epochs,
'lr': lr
}
}
return train_spec | 0e19dab0263eda8505ddb830fd255b2a760d822c | 696,554 |
def pipe_to_underscore(pipelist):
"""Converts an AFF pipe-seperated list to a CEDSCI underscore-seperated list"""
return pipelist.replace("|", "_") | 94d29e07d2c01be5afffab71cc26f9e91646bd9b | 72,155 |
import re
def split_words(src_string):
"""
Split a sentence at the word boundaries
:param src_string: String
:return: list of words in the string
"""
r = re.findall(r"[\w]+", src_string)
return r | beaf4b72ec79ea9d2779d073acf166960013ce2b | 154,582 |
def metadata_filter_as_dict(metadata_config):
"""Return the metadata filter represented as either None (no filter),
or a dictionary with at most two keys: 'additional' and 'excluded',
which contain either a list of metadata names, or the string 'all'"""
if metadata_config is None:
return {}
if metadata_config is True:
return {'additional': 'all'}
if metadata_config is False:
return {'excluded': 'all'}
if isinstance(metadata_config, dict):
assert set(metadata_config) <= set(['additional', 'excluded'])
return metadata_config
metadata_keys = metadata_config.split(',')
metadata_config = {}
for key in metadata_keys:
key = key.strip()
if key.startswith('-'):
metadata_config.setdefault('excluded', []).append(key[1:].strip())
elif key.startswith('+'):
metadata_config.setdefault('additional', []).append(key[1:].strip())
else:
metadata_config.setdefault('additional', []).append(key)
for section in metadata_config:
if 'all' in metadata_config[section]:
metadata_config[section] = 'all'
else:
metadata_config[section] = [key for key in metadata_config[section] if key]
return metadata_config | b851fdfc759f89571d1b39cf34d82122ad3a3e40 | 626,004 |
def is_sampler(estimator):
"""Return True if the given estimator is a sampler, False otherwise.
Parameters
----------
estimator : object
Estimator to test.
Returns
-------
is_sampler : bool
True if estimator is a sampler, otherwise False.
"""
if estimator._estimator_type == "sampler":
return True
return False | 5a702e92f82a6d7c579112da91a2ce71851e5373 | 165,519 |
from typing import Union
from typing import Tuple
import torch
def conv1x1(in_planes: int, out_planes: int, stride: Union[int, Tuple[int, int]] = 1):
"""
CREDITS: https://github.com/pytorch/vision
1x1 convolution
"""
return torch.nn.Conv2d(
in_channels=in_planes,
out_channels=out_planes,
kernel_size=1,
stride=stride,
bias=False
) | ee3505e1fff51dbedc1b16ba3225e8ee3d4cb014 | 549,072 |
def reorder_columns(columns):
"""
Reorder the columns for creating constraint, preserve primary key ordering
``['task_id', 'dag_id', 'execution_date']``
:param columns: columns retrieved from DB related to constraint
:return: ordered column
"""
ordered_columns = []
for column in ['task_id', 'dag_id', 'execution_date']:
if column in columns:
ordered_columns.append(column)
for column in columns:
if column not in ['task_id', 'dag_id', 'execution_date']:
ordered_columns.append(column)
return ordered_columns | 70532a911eb8444be574ce12d93cd2398b8447e3 | 332,251 |
def read_metadatablockpicture( data ):
"""Extract picture from a METADATA_BLOCK_PICTURE"""
off = 8 + int.from_bytes( data[4:8], 'big' )
off += 4 + int.from_bytes( data[off:off+4], 'big' ) + 16
size = int.from_bytes( data[off:off+4], 'big' )
return data[4+off:4+off+size] | 99a993e30577af610df02123de1df030032b55c8 | 259,192 |
def csnl_to_list(csnl_str):
"""Converts a comma-separated and new-line separated string into
a list, stripping whitespace from both ends of each item. Does not
return any zero-length strings.
"""
s = csnl_str.replace('\n', ',')
return [it.strip() for it in s.split(',') if it.strip()] | cb6743761b1b394b3459f987b02f6d0c9f47b19a | 268,253 |
def switch_player(player):
"""Switch the player from X to O or vice versa and return the player"""
players = {"X": "O", "O": "X"}
return players[player] | 6ca7412a4c1d6adddee38a15c2f3dc7ebed15cf7 | 117,800 |
import re
def is_uid(string):
"""Return true if string is a valid DHIS2 Unique Identifier (UID)"""
return re.compile('^[A-Za-z][A-Za-z0-9]{10}$').match(string) | 9e1c1d8dc2697a8535018b15662a69edfdbc8eaf | 70,821 |
def insertion_sort(arr):
"""
The function insertion_sort() sorts the given list using insertion sort algorithm.
The function returns the list after sorting it.
Arguments
arr : An unsorted list.
"""
for x in arr[1:]:
for y in arr[arr.index(x)-1::-1]:
if x < y:
arr[arr.index(x)] = y
arr[arr.index(y)] = x
return arr | 0c2df7b9ad7bd72f5f7ba26c5b1bc3babe6b30f6 | 634,569 |
import re
def ip_add(string):
"""
Extract IP address from text.
Parameters
----------
string: str
Text selected to apply transformation.
Examples:
---------
```python
sentence="An example of ip address is 125.16.100.1"
ip_add(sentence)
>>> ['125.16.100.1']
```
"""
text = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', string)
return text | efaa5882e63fc3f02091cfcc28f94c643e1ae037 | 461,944 |
import yaml
def parse_metadata(doc,join='\n'):
"""
Parse the metadata from a document and parse it
as a YAML dict and return it.
"""
doc = doc.strip()
if doc.startswith('---\n') and ('...' in doc or '---' in doc[4:]):
# found starting yaml block
yblock = doc[4:].split('...')[0].split('---')[0]
meta = yaml.load(yblock, Loader=yaml.SafeLoader)
for k in meta.keys():
val = meta[k]
if isinstance(val,list):
meta[k] = join.join(val)
meta['metadata_yaml_length'] = len(yblock) + 7
if 'description' not in meta:
body = doc[meta['metadata_yaml_length']:]
first_para = body.strip().split('\n')[0]
meta['description'] = first_para
return meta
else:
# No yaml
return {} | 3cee56b2e6878d1836669c0c1d68b9b932a61cb1 | 547,710 |
def get_ec_params(alg):
"""Return a string representation of a hex encoded ASN1 object X9.62 EC parameter
http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cos01/pkcs11-curr-v2.40-cos01.html
Indicates that EC paramaters are byte arrays of a DER encoded ASN1 objects X9.62 parameter.
This function will return a hex string without the leading 0x representing this encoding.
"""
if alg == "NIST p256":
obj = "2A8648CE3D030107"
elif alg == "NIST p224":
obj = "2B81040021"
elif alg == "NIST p384":
obj = "2B81040022"
elif alg == "NIST p521":
obj = "2B81040023"
else:
raise RuntimeError("alg %s has no EC params mapping" % alg)
# start building the DER object tag + len + obj in hex
der = "06{:02x}{}".format(len(obj) // 2, obj)
return der | 57746eab7368940b41558970531e6db29aa1023d | 117,844 |
def gen_tagset(tags):
"""Create TagSet value from a dict."""
return [{'Key': key, 'Value': value} for key, value in tags.items()] | 0c12c8a901ac52f69098c4fe73da6ecbdf0cabc7 | 621,273 |
def fill_slicer(slicer, in_len):
""" Return slice object with Nones filled out to match `in_len`
Also fixes too large stop / start values according to slice() slicing
rules.
The returned slicer can have a None as `slicer.stop` if `slicer.step` is
negative and the input `slicer.stop` is None. This is because we can't
represent the ``stop`` as an integer, because -1 has a different meaning.
Parameters
----------
slicer : slice object
in_len : int
length of axis on which `slicer` will be applied
Returns
-------
can_slicer : slice object
slice with start, stop, step set to explicit values, with the exception
of ``stop`` for negative step, which is None for the case of slicing
down through the first element
"""
start, stop, step = slicer.start, slicer.stop, slicer.step
if step is None:
step = 1
if start is not None and start < 0:
start = in_len + start
if stop is not None and stop < 0:
stop = in_len + stop
if step > 0:
if start is None:
start = 0
if stop is None:
stop = in_len
else:
stop = min(stop, in_len)
else: # step < 0
if start is None:
start = in_len - 1
else:
start = min(start, in_len - 1)
return slice(start, stop, step) | ed2bcad1246f8f5e238878bf2fc46edfa871a445 | 359,280 |
def _max_full_form_prefix_length(full_form, lemma, min_rule_length):
"""Return the maximum possible length of the prefix (part of the full form preceding the suffix)."""
full_form_prefix = len(full_form) - min_rule_length
return min(len(lemma), full_form_prefix) | b9ee8c850f41c69019bfed6e827d83fe90e416e5 | 560,482 |
import requests
import json
def get_entry(url):
"""Call query URL and check returned entry
Parameters
----------
url : str
POWER query URL
Returns
-------
dict
entry returned by query
Raises
------
RuntimeError
when API returned error
"""
r = requests.get(url)
r.raise_for_status()
entry = json.loads(r.text)
for message in entry.get('messages', []):
if 'Alert' in message:
raise RuntimeError(message)
return entry | 2ce788e1a71dbfe3d576b79812228d3d788a44f6 | 497,834 |
def normalize_rect(rect):
"""
Make rectangle a rotated tall rectangle, which means y-size > x-size
and the angle indicates the "tilt": rotation of the longer axis from vertical
:param rect: OpenCV's rectangle object
:return: OpenCV's rectangle object normalized as described
rect[0] is the coordinates of the center of the rectangle
rect[1] is tuple of the sizes (x, y)
rect[2] is the tilt angle
if width > height, in rect's internal means, then we turn it 90 degrees
which means swap the sizes and turn cw or ccw depending on the previous value
"""
if rect[1][0] > rect[1][1]:
# incoming rect can be a tuple so if swapping reassign the whole thing
rect = (
rect[0], # same center coordinates
(rect[1][1], rect[1][0]), # swap height with width
rect[2] + 90.0 if rect[2] < 0.0 else -90.0
)
return rect | 4796f4e14b16c3e78098fa74df868f18a684e229 | 82,826 |
def ccalc_viridis(x, rgbmax):
"""viridis colour map"""
r = [0.26700401, 0.26851048, 0.26994384, 0.27130489, 0.27259384, 0.27380934, 0.27495242, 0.27602238, 0.2770184, 0.27794143, 0.27879067, 0.2795655, 0.28026658, 0.28089358, 0.28144581, 0.28192358, 0.28232739, 0.28265633, 0.28291049, 0.28309095, 0.28319704, 0.28322882, 0.28318684, 0.283072, 0.28288389, 0.28262297, 0.28229037, 0.28188676, 0.28141228, 0.28086773, 0.28025468, 0.27957399, 0.27882618, 0.27801236, 0.27713437, 0.27619376, 0.27519116, 0.27412802, 0.27300596, 0.27182812, 0.27059473, 0.26930756, 0.26796846, 0.26657984, 0.2651445, 0.2636632, 0.26213801, 0.26057103, 0.25896451, 0.25732244, 0.25564519, 0.25393498, 0.25219404, 0.25042462, 0.24862899, 0.2468114, 0.24497208, 0.24311324, 0.24123708, 0.23934575, 0.23744138, 0.23552606, 0.23360277, 0.2316735, 0.22973926, 0.22780192, 0.2258633, 0.22392515, 0.22198915, 0.22005691, 0.21812995, 0.21620971, 0.21429757, 0.21239477, 0.2105031, 0.20862342, 0.20675628, 0.20490257, 0.20306309, 0.20123854, 0.1994295, 0.1976365, 0.19585993, 0.19410009, 0.19235719, 0.19063135, 0.18892259, 0.18723083, 0.18555593, 0.18389763, 0.18225561, 0.18062949, 0.17901879, 0.17742298, 0.17584148, 0.17427363, 0.17271876, 0.17117615, 0.16964573, 0.16812641, 0.1666171, 0.16511703, 0.16362543, 0.16214155, 0.16066467, 0.15919413, 0.15772933, 0.15626973, 0.15481488, 0.15336445, 0.1519182, 0.15047605, 0.14903918, 0.14760731, 0.14618026, 0.14475863, 0.14334327, 0.14193527, 0.14053599, 0.13914708, 0.13777048, 0.1364085, 0.13506561, 0.13374299, 0.13244401, 0.13117249, 0.1299327, 0.12872938, 0.12756771, 0.12645338, 0.12539383, 0.12439474, 0.12346281, 0.12260562, 0.12183122, 0.12114807, 0.12056501, 0.12009154, 0.11973756, 0.11951163, 0.11942341, 0.11948255, 0.11969858, 0.12008079, 0.12063824, 0.12137972, 0.12231244, 0.12344358, 0.12477953, 0.12632581, 0.12808703, 0.13006688, 0.13226797, 0.13469183, 0.13733921, 0.14020991, 0.14330291, 0.1466164, 0.15014782, 0.15389405, 0.15785146, 0.16201598, 0.1663832, 0.1709484, 0.17570671, 0.18065314, 0.18578266, 0.19109018, 0.19657063, 0.20221902, 0.20803045, 0.21400015, 0.22012381, 0.2263969, 0.23281498, 0.2393739, 0.24606968, 0.25289851, 0.25985676, 0.26694127, 0.27414922, 0.28147681, 0.28892102, 0.29647899, 0.30414796, 0.31192534, 0.3198086, 0.3277958, 0.33588539, 0.34407411, 0.35235985, 0.36074053, 0.3692142, 0.37777892, 0.38643282, 0.39517408, 0.40400101, 0.4129135, 0.42190813, 0.43098317, 0.44013691, 0.44936763, 0.45867362, 0.46805314, 0.47750446, 0.4870258, 0.49661536, 0.5062713, 0.51599182, 0.52577622, 0.5356211, 0.5455244, 0.55548397, 0.5654976, 0.57556297, 0.58567772, 0.59583934, 0.60604528, 0.61629283, 0.62657923, 0.63690157, 0.64725685, 0.65764197, 0.66805369, 0.67848868, 0.68894351, 0.69941463, 0.70989842, 0.72039115, 0.73088902, 0.74138803, 0.75188414, 0.76237342, 0.77285183, 0.78331535, 0.79375994, 0.80418159, 0.81457634, 0.82494028, 0.83526959, 0.84556056, 0.8558096, 0.86601325, 0.87616824, 0.88627146, 0.89632002, 0.90631121, 0.91624212, 0.92610579, 0.93590444, 0.94563626, 0.95529972, 0.96489353, 0.97441665, 0.98386829, 0.99324789]
g = [0.00487433, 0.00960483, 0.01462494, 0.01994186, 0.02556309, 0.03149748, 0.03775181, 0.04416723, 0.05034437, 0.05632444, 0.06214536, 0.06783587, 0.07341724, 0.07890703, 0.0843197, 0.08966622, 0.09495545, 0.10019576, 0.10539345, 0.11055307, 0.11567966, 0.12077701, 0.12584799, 0.13089477, 0.13592005, 0.14092556, 0.14591233, 0.15088147, 0.15583425, 0.16077132, 0.16569272, 0.17059884, 0.1754902, 0.18036684, 0.18522836, 0.19007447, 0.1949054, 0.19972086, 0.20452049, 0.20930306, 0.21406899, 0.21881782, 0.22354911, 0.2282621, 0.23295593, 0.23763078, 0.24228619, 0.2469217, 0.25153685, 0.2561304, 0.26070284, 0.26525384, 0.26978306, 0.27429024, 0.27877509, 0.28323662, 0.28767547, 0.29209154, 0.29648471, 0.30085494, 0.30520222, 0.30952657, 0.31382773, 0.3181058, 0.32236127, 0.32659432, 0.33080515, 0.334994, 0.33916114, 0.34330688, 0.34743154, 0.35153548, 0.35561907, 0.35968273, 0.36372671, 0.36775151, 0.37175775, 0.37574589, 0.37971644, 0.38366989, 0.38760678, 0.39152762, 0.39543297, 0.39932336, 0.40319934, 0.40706148, 0.41091033, 0.41474645, 0.4185704, 0.42238275, 0.42618405, 0.42997486, 0.43375572, 0.4375272, 0.44128981, 0.4450441, 0.4487906, 0.4525298, 0.45626209, 0.45998802, 0.46370813, 0.4674229, 0.47113278, 0.47483821, 0.47853961, 0.4822374, 0.48593197, 0.4896237, 0.49331293, 0.49700003, 0.50068529, 0.50436904, 0.50805136, 0.51173263, 0.51541316, 0.51909319, 0.52277292, 0.52645254, 0.53013219, 0.53381201, 0.53749213, 0.54117264, 0.54485335, 0.54853458, 0.55221637, 0.55589872, 0.55958162, 0.56326503, 0.56694891, 0.57063316, 0.57431754, 0.57800205, 0.58168661, 0.58537105, 0.58905521, 0.59273889, 0.59642187, 0.60010387, 0.60378459, 0.60746388, 0.61114146, 0.61481702, 0.61849025, 0.62216081, 0.62582833, 0.62949242, 0.63315277, 0.63680899, 0.64046069, 0.64410744, 0.64774881, 0.65138436, 0.65501363, 0.65863619, 0.66225157, 0.66585927, 0.66945881, 0.67304968, 0.67663139, 0.68020343, 0.68376525, 0.68731632, 0.69085611, 0.69438405, 0.6978996, 0.70140222, 0.70489133, 0.70836635, 0.71182668, 0.71527175, 0.71870095, 0.72211371, 0.72550945, 0.72888753, 0.73224735, 0.73558828, 0.73890972, 0.74221104, 0.74549162, 0.74875084, 0.75198807, 0.75520266, 0.75839399, 0.76156142, 0.76470433, 0.76782207, 0.77091403, 0.77397953, 0.7770179, 0.78002855, 0.78301086, 0.78596419, 0.78888793, 0.79178146, 0.79464415, 0.79747541, 0.80027461, 0.80304099, 0.80577412, 0.80847343, 0.81113836, 0.81376835, 0.81636288, 0.81892143, 0.82144351, 0.82392862, 0.82637633, 0.82878621, 0.83115784, 0.83349064, 0.83578452, 0.83803918, 0.84025437, 0.8424299, 0.84456561, 0.84666139, 0.84871722, 0.8507331, 0.85270912, 0.85464543, 0.85654226, 0.85839991, 0.86021878, 0.86199932, 0.86374211, 0.86544779, 0.86711711, 0.86875092, 0.87035015, 0.87191584, 0.87344918, 0.87495143, 0.87642392, 0.87786808, 0.87928545, 0.88067763, 0.88204632, 0.88339329, 0.88472036, 0.88602943, 0.88732243, 0.88860134, 0.88986815, 0.89112487, 0.89237353, 0.89361614, 0.89485467, 0.89609127, 0.89732977, 0.8985704, 0.899815, 0.90106534, 0.90232311, 0.90358991, 0.90486726, 0.90615657]
b = [0.32941519, 0.33542652, 0.34137895, 0.34726862, 0.35309303, 0.35885256, 0.36454323, 0.37016418, 0.37571452, 0.38119074, 0.38659204, 0.39191723, 0.39716349, 0.40232944, 0.40741404, 0.41241521, 0.41733086, 0.42216032, 0.42690202, 0.43155375, 0.43611482, 0.44058404, 0.44496, 0.44924127, 0.45342734, 0.45751726, 0.46150995, 0.46540474, 0.46920128, 0.47289909, 0.47649762, 0.47999675, 0.48339654, 0.48669702, 0.48989831, 0.49300074, 0.49600488, 0.49891131, 0.50172076, 0.50443413, 0.50705243, 0.50957678, 0.5120084, 0.5143487, 0.5165993, 0.51876163, 0.52083736, 0.52282822, 0.52473609, 0.52656332, 0.52831152, 0.52998273, 0.53157905, 0.53310261, 0.53455561, 0.53594093, 0.53726018, 0.53851561, 0.53970946, 0.54084398, 0.5419214, 0.54294396, 0.54391424, 0.54483444, 0.54570633, 0.546532, 0.54731353, 0.54805291, 0.54875211, 0.54941304, 0.55003755, 0.55062743, 0.5511844, 0.55171011, 0.55220646, 0.55267486, 0.55311653, 0.55353282, 0.55392505, 0.55429441, 0.55464205, 0.55496905, 0.55527637, 0.55556494, 0.55583559, 0.55608907, 0.55632606, 0.55654717, 0.55675292, 0.55694377, 0.5571201, 0.55728221, 0.55743035, 0.55756466, 0.55768526, 0.55779216, 0.55788532, 0.55796464, 0.55803034, 0.55808199, 0.55811913, 0.55814141, 0.55814842, 0.55813967, 0.55811466, 0.5580728, 0.55801347, 0.557936, 0.55783967, 0.55772371, 0.55758733, 0.55742968, 0.5572505, 0.55704861, 0.55682271, 0.55657181, 0.55629491, 0.55599097, 0.55565893, 0.55529773, 0.55490625, 0.55448339, 0.55402906, 0.55354108, 0.55301828, 0.55245948, 0.55186354, 0.55122927, 0.55055551, 0.5498411, 0.54908564, 0.5482874, 0.54744498, 0.54655722, 0.54562298, 0.54464114, 0.54361058, 0.54253043, 0.54139999, 0.54021751, 0.53898192, 0.53769219, 0.53634733, 0.53494633, 0.53348834, 0.53197275, 0.53039808, 0.52876343, 0.52706792, 0.52531069, 0.52349092, 0.52160791, 0.51966086, 0.5176488, 0.51557101, 0.5134268, 0.51121549, 0.50893644, 0.5065889, 0.50417217, 0.50168574, 0.49912906, 0.49650163, 0.49380294, 0.49103252, 0.48818938, 0.48527326, 0.48228395, 0.47922108, 0.47608431, 0.4728733, 0.46958774, 0.46622638, 0.46278934, 0.45927675, 0.45568838, 0.45202405, 0.44828355, 0.44446673, 0.44057284, 0.4366009, 0.43255207, 0.42842626, 0.42422341, 0.41994346, 0.41558638, 0.41115215, 0.40664011, 0.40204917, 0.39738103, 0.39263579, 0.38781353, 0.38291438, 0.3779385, 0.37288606, 0.36775726, 0.36255223, 0.35726893, 0.35191009, 0.34647607, 0.3409673, 0.33538426, 0.32972749, 0.32399761, 0.31819529, 0.31232133, 0.30637661, 0.30036211, 0.29427888, 0.2881265, 0.28190832, 0.27562602, 0.26928147, 0.26287683, 0.25641457, 0.24989748, 0.24332878, 0.23671214, 0.23005179, 0.22335258, 0.21662012, 0.20986086, 0.20308229, 0.19629307, 0.18950326, 0.18272455, 0.17597055, 0.16925712, 0.16260273, 0.15602894, 0.14956101, 0.14322828, 0.13706449, 0.13110864, 0.12540538, 0.12000532, 0.11496505, 0.11034678, 0.10621724, 0.1026459, 0.09970219, 0.09745186, 0.09595277, 0.09525046, 0.09537439, 0.09633538, 0.09812496, 0.1007168, 0.10407067, 0.10813094, 0.11283773, 0.11812832, 0.12394051, 0.13021494, 0.13689671, 0.1439362]
i = int(round(x * 255, 0))
return [r[i]*rgbmax, g[i]*rgbmax, b[i]*rgbmax] | 88a1a135c3f398d33bc8f5b3a56520ea8461c373 | 122,412 |
import base64
def base64_from_hex(hexstr):
"""
Returns the base64 string for the hex string specified
:param hexstr: The hex string to convert to base64
:return: The base64 value for the specified hes string
"""
return base64.b64encode(bytes(bytearray.fromhex(hexstr))).decode("utf8") | 5d457d08ed47356073bd2238699b65a3c3037df3 | 642,348 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.