content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def parse_word_expression(expr):
"""
Parses a word expression such as "thermoelectric - PbTe + LiFePO4" into positive and negative words
:param expr: a string expression, with " +" and " -" strings separating the words in the expression.
:return: Returns a tuple of lists (positive, negative)
"""
... | 9872e05f7ce86f2973efec8c5e0d5306d718419a | 46,162 |
import random
import string
def rand_string(count=12):
"""Return random string of length count with letters and numbers, mixed case. Uses Python randomness."""
return ''.join(random.choice(string.ascii_letters + string.digits) for x in range(count)) | bc800528c6b45a7cc468ec2727ee1ce00136238d | 46,164 |
def setBits( lst ):
"""
set the bits in lst to 1.
also set bits 18, 20, 22, 24, and 28 to one (since they should always be set)
all other bits will be 0
"""
res = 0
for b in lst + [18,20,22,24,28]:
res |= (1 << b)
return res | 645509278a7f974c6da163935b3ee3e2e3724a06 | 46,168 |
from typing import List
from typing import Callable
def create_matcher(queries: List[str], query_type: str) -> Callable[[str], bool]:
"""
Create a matcher for a list of queries
Parameters
----------
queries : list
List of queries
query_type: str
Type of query to run: ["or"|"a... | cc7cb37cab30728a70ac03446ed985ed0f71b9fc | 46,174 |
def reverseSentence(s):
"""i am a student. -> student. a am i"""
s = s[::-1]
sNums = s.split(' ')
for i in range(len(sNums)):
sNums[i] = sNums[i][::-1]
return " ".join(sNums) | 25e74f96182d94dd9031627e46d0a89235ffb796 | 46,175 |
def remove_suffix(s: str, suffix: str) -> str:
"""Remove the suffix from the string. I.e., str.removesuffix in Python 3.9."""
# suffix="" should not call s[:-0]
return s[: -len(suffix)] if suffix and s.endswith(suffix) else s | 17474d37726249dc84aa89f0861fe43db43bf1e9 | 46,177 |
import re
def split_camel_cased(text: str) -> str:
"""Split camelCased elements with a space.
Arguments:
text:
The text to be processed.
Returns:
The text with all camelCased elements split into different elements.
"""
return re.sub("(?!^)([A-Z][a-z]+)", r" \1", text) | 4ecc9e30bd50fb9898c23955917c953b3827b9a3 | 46,178 |
import math
def triangle(v):
"""
Return a value corresponding to a triangle wave
"""
return (2 * abs(v - math.floor(v + (1/2)))) - 1 | 85b5824a5686b56a0ab2455d8aaba60ee0c45d6d | 46,182 |
def filter_tagged_vocabulary(tagged_vocabulary, vocabulary, split="|"):
"""Filters tagged_vocabulary (tokens merged with tags) for tokens
occurring in vocabulary.
Parameters
----------
tagged_vocabulary : collection
vocabulary of tokens (can be merged with tags)
vocabulary : collection
... | a84ded5b44db2a4075591fd56847dc9529eefc7a | 46,184 |
def _f(X, y, clf):
"""Returns the flattened coefficients of a fitted classifier.
This function exists at the module level instead of as an anonymous or
subordinate function so that it is importable by `multiprocessing`.
Parameters
----------
X : array
Design matrix.
y : array
... | 209d60f77168d39b541e3b091a8d342ed8c7fead | 46,185 |
def load_languages(language, languages_dict):
"""loads the language from the string-dict loaded from the config
Args:
language (str): selectbox choice for the language model from the user
languages_dict (dict): dict containing to-evaluate strings of the language
Returns:
tfhub lang... | 3f7d945ab5154a44249755a067fc53d7ff7c4d9f | 46,187 |
def inputthis(question='-> ', expected_tuple=('Y', 'N'), error='ERRO! Resposta inesperada!'):
"""
:param question: Input text
:param expected_tuple: Tuple containing all the options from wich the user should choose from
:param error: Error message for when the input isn't cointained in the tuple
:re... | 36c3d47f0ba0c73d12a1323241e1d6173aecd621 | 46,189 |
def _find_match(needle: dict, haystack: list, keys: list):
"""Find a dictionary in a list of dictionary based on a set of keys"""
for item in haystack:
for key in keys:
if item.get(key) != needle[key]:
break
else:
return item
return None | 4cc009583cd3238bba3b4e3da94257229ee37894 | 46,194 |
def get_cached_stickers(context, fuzzy=False):
"""Return cached search results from a previous inline query request."""
query_id = context.inline_query_id
cache = context.tg_context.bot_data[query_id]
if fuzzy:
results = cache["fuzzy"]
offset = context.fuzzy_offset
else:
res... | c3399ac727d4f412f35b4442390c10abc7eb1ad5 | 46,199 |
from typing import List
from typing import Tuple
def find_two_smallest(L:List[float]) -> Tuple[int, int]:
""" (see above) """
# Find the index of the minimum and remove that item
smallest = min(L)
min1 = L.index(smallest)
L.remove(smallest)
# Find the index of the new minimum item in the list... | 6847fc028d01fa5539b3fd4a3e8de416089150ab | 46,201 |
def get_attribute(name):
""" Gets the value of the element's attribute named ``name``. """
def evaluator(element):
return element.attrib.get(name)
return evaluator | 8ffc06ae088f09284509d3a47ef85f32175385f3 | 46,202 |
from typing import Counter
def unique_words_by_tag(tokens, tag_value='N/A'):
"""Return a counter of the tokens with the given tag value."""
nouns = []
for word, tag in tokens:
if tag.startswith(tag_value) or tag_value == 'N/A':
nouns.append(word.lower())
return Counter(nouns) | b56dc9dbcdcb25b8d81fe2ebc79784008d848d23 | 46,204 |
def total_per_person(single_plan):
"""Returns total cost per person
Parameter
single_plan: single plan from database
Returns: total cost per person"""
costs = single_plan.cost_set.all()
if costs:
total_cost = 0
for cost in costs:
cost_per_person = round(cost.cost /... | 0019267cfa754e4a64631b812f026fcd8534f8b8 | 46,205 |
def writeable(doc):
"""
Return a writeable tuple for doc.
writeable tuple is any 2-tuple of `output_path`, `bytes`.
`lettersmith.write` knows how to write these tuples to disk.
"""
return doc.output_path, doc.content.encode() | 186580eee94dc537968b3c6edac1f5a755f858ed | 46,207 |
def fsm_submit_button(transition):
"""
Render a submit button that requests an fsm state transition for a
single state.
"""
fsm_field_name, button_value, transition_name = transition
return {
'button_value': button_value,
'fsm_field_name': fsm_field_name,
'transition_name... | e4fedef1a489dd96e573027639f0eec2cbf13711 | 46,209 |
def pointOnTrianglePlane(P, A, B, C):
"""
Projects the point P onto the plane containing traingle A, B, C
"""
N = (B - A).cross(C - A).normalize()
return P + (-(P - A).dot(N))*N | c70c02c31905208fa8a0942df7a12d33316f0afa | 46,212 |
from typing import Dict
from typing import Tuple
from typing import List
from typing import Any
def _traverse_foreign_key_tree(
tree: Dict[str, Dict[Tuple[str, ...], dict]], name: str, fields: Tuple[str, ...]
) -> List[Dict[str, Any]]:
"""Traverse foreign key tree.
Args:
tree: Foreign key tree (s... | 37bafd03fed849031939159fab03bf5708ebffb7 | 46,219 |
from typing import List
from typing import Dict
def generate_currency_endowments(
agent_addresses: List[str], currency_ids: List[str], money_endowment: int
) -> Dict[str, Dict[str, int]]:
"""
Compute the initial money amounts for each agent.
:param agent_addresses: addresses of the agents.
:param... | 0dbf36a09c88eb3cdb1278862bdb37b2927fcec0 | 46,220 |
def sort_list_by_other(to_sort, other, reverse=True):
"""Sort a list by an other."""
return [el for _, el in sorted(zip(other, to_sort), reverse=reverse)] | 9672bd28349fe0f3cc0d8d122f59724965d53f35 | 46,224 |
def update_analyze_button(disabled):
"""
Updates the color of the analyze button depending on
its disabled status
:param disabled: if the button is disabled
"""
if not disabled:
style = {"width": "100%", "text-transform": "uppercase",
"font-weight": "700", "background":... | 5a0056879fd5ecde05b7b4fbadbeb7e3aeb1d679 | 46,228 |
def format_id(ident):
"""
Convert a message ID to its canonical string form
"""
return '%016X' % ident | 633ce965ca74ff3dac2b7bf9910186c88e892111 | 46,232 |
def read_classes(classes_path):
"""Reads classes from file.
Args:
classes_path (str):
Path to file containing names of all classes.
Returns:
list: List containing names of all classes.
"""
with open(classes_path) as f:
class_names = f.readlines()
cla... | fcfcd3f7391e096fd71a7091eb33e4a9c8a21581 | 46,235 |
import torch
def generate_sparse_one_hot(num_ents, dtype=torch.float32):
""" Creates a two-dimensional sparse tensor with ones along the diagnoal as one-hot encoding. """
diag_size = num_ents
diag_range = list(range(num_ents))
diag_range = torch.tensor(diag_range)
return torch.sparse_coo_tensor(
... | 3a71c72acfca4fe9fbfe1a6848519e9726fe72d9 | 46,237 |
def split_string_by_fields(string, fields):
"""
Helper function to split a string by a set of ordered strings,
primarily used for Maccor metadata parsing.
>>>split_string_by_fields("first name: Joey last name Montoya",
>>> ["first name:", "last name"])
["Joey", "Montoya"]... | 7722f5fd80a581a113c18495d2ad21d1af41748d | 46,250 |
def footer(id1, id2 = None):
"""
Build SMT formula footer
Args:
id1 (str): ID of policy 1 in SMT formula
id2 (str, optional): ID of policy 2 in SMT formula. Defaults to None.
Returns:
str: SMT footer
"""
smt = '(assert {}.allows)\n'.format(id1)
if id2:
smt... | c9af2ad7453282e1611e7b2010f4269ca8ac0bc0 | 46,252 |
def area_square(length):
"""
Calculates the area of a square.
Parameters
----------
length (float or int) length of one side of a square
Returns
-------
area (float) - area of the square
"""
return length ** 2 | 122ce824bc47651aa56f424618b1b18c7fd0aa19 | 46,253 |
def calculate_time(cents_per_kWh, wattage, dollar_amount):
""" Returns the time (in hours) that it would take to reach the monetary price (dollar_amount)
given the cost of energy usage (cents_per_kWh) and power (wattage) of a device using that energy.
"""
return 1 / (cents_per_kWh) * 1e5 * dollar_am... | 86c261d8b72089d39935468dd349eef8e9611cdd | 46,257 |
def flatten(filenames):
"""Takes a list which may contain other lists and returns a single,
flattened list
Args:
filenames (list): list of filenames
Returns:
flattened list of filenames
"""
flat_filenames = [file for i in filenames for file in i]
return flat_filenames | 5a81b0c3d9395142c4991052cf494226b3516bc3 | 46,258 |
def vals_vec_from_lmfit(lmfit_params):
"""Return Python list of parameter values from LMFIT Parameters object."""
vals = [value.value for value in lmfit_params.values()]
return vals | 6fac3ac8dd364dca3ae19a6cac36be072e32fdb7 | 46,259 |
def _get_yaml_path(path, parameter):
"""Compose the parameter path following the YAML Path standard.
Standard: https://github.com/wwkimball/yamlpath/wiki/Segments-of-a-YAML-Path#yaml-path-standard
"""
yaml_path = []
if path:
yaml_path.extend(path)
if parameter:
yaml_path.append(... | 7b4c8807cbc8a030ad2b541bb21dc59e3204324f | 46,260 |
def strip_yaml(text):
"""
strip starging yaml, between first --- and next --- from text
:param text:
:return:
"""
if text[:3] != '---':
return text
else:
stext = text.split('\n')
stext.pop(0)
n = 0
for ln in stext:
if ln != '---':
... | 288ed60333b90acb6387746760415aa281fb2dd0 | 46,264 |
def unique_test_name(request):
"""Generate unique test names by prepending the class to the method name"""
if request.node.cls is not None:
return request.node.cls.__name__ + "__" + request.node.name
else:
return request.node.name | c7d0f732ad69c5a1e528cf7f2a64789c3080f215 | 46,266 |
def accidental2string(acc_number):
"""Return a string repr of accidentals."""
if acc_number is None:
return ""
elif acc_number > 0:
return "#" * int(acc_number)
elif acc_number < 0:
return "b" * int(abs(acc_number))
else:
return "n" | 622b0952ba9c9bcc2428761da8b44dbef991911c | 46,268 |
def _IsRemoteBetter(new_name, old_name):
"""Indicates if a new remote is better than an old one, based on remote name.
Names are ranked as follows: If either name is "origin", it is considered
best, otherwise the name that comes last alphabetically is considered best.
The alphabetical ordering is arbitrary, b... | 49ca158c596a173b881db169fe30531d8a77b9ae | 46,271 |
from typing import Tuple
def get_chunk_type(tok: str) -> Tuple[str, str]:
"""
Args:
tok: Label in IOB format
Returns:
tuple: ("B", "DRUG")
"""
tag_class = tok.split('-')[0]
tag_type = tok.split('-')[-1]
return tag_class, tag_type | 67a112c4f3f5c3d9594572a4f28ad83dcb53404a | 46,276 |
def el (name, content):
"""Write a XML element with given element tag name (incl. element attributes) and the element's inner content."""
return "<%s>%s</%s>" % (name, content, name.partition(" ")[0]) | 8100779aa7935eb3ca0ea0c720508c1728c1874d | 46,287 |
import math
def add_radians(a, b):
"""Adds two radian angles, and adjusts sign +/- to be closest to 0
Parameters:
:param float a: Angle a
:param float b: Angle b
Returns: The resulting angle in radians, with sign adjusted
:rtype: float
"""
return (a + b + math.pi) % (2 * ma... | 43f33ba646899e2431fee4967335b8a724cad194 | 46,289 |
def str2int(string):
"""Convert input string into integer. If can not convert, return 0"""
try:
value = int(string)
except ValueError:
value = 0
return value | 20b370a9243b05240ffb39b968d139d8c67c7fea | 46,296 |
import torch
def fft_rec_loss2(tgt, src, mask):
"""Calculate FFT loss between pair of images. The loss is masked by `mask`. FFT loss is calculated on GPU and, thus, very fast. We calculate phase and amplitude L1 losses.
Args:
tgt (torch.Tensor): Target image. Shape [B,C,H,W]
src (torch.Tensor... | 5ab462edb99cab347bc7e57c66a604d10dd3e98f | 46,302 |
def area_to_capacity(statistical_roof_model_area_based, power_density_flat, power_density_tilted):
"""Maps area shares to capacity shares of statistical roof model.
The statistical roof model defines roof categories (e.g. south-facing with tilt 10°) and their
shares in a population of roofs. This function ... | 0e57c01bfa7c44743edb260b6a1b406ebf0fb82b | 46,305 |
import torch
def kron(A, B):
"""
Kronecker Product.
Works with batch dimemsion(s) - requires both A and B have same batch dims.
"""
A_shp, B_shp = A.shape, B.shape
assert A_shp[:-2] == B_shp[:-2]
kron_block = torch.matmul(
A[..., :, None, :, None], B[..., None, :, None, :]
)
... | 065b5c5b49c509f74733b5af6dfd7e76649cadfd | 46,310 |
def get_all_model_fields(connector,model_name):
"""Utility function to get the full list of field names from a model,
INCLUDING field names that are eventually derived fro mthe connector's UNPACKING list in the manifest."""
model = connector.MODELS[model_name]
unpacking = connector.UNPACKING
base... | 4985f67ce565ed6d0f309387d4123ce9a594dc61 | 46,316 |
def j_map_to_dict(m):
"""Converts a java map to a python dictionary."""
if not m:
return None
r = {}
for e in m.entrySet().toArray():
k = e.getKey()
v = e.getValue()
r[k] = v
return r | 401bc3ceeafbbdd6f07b309cdef227caf56680d4 | 46,317 |
def _create_union_types_specification(schema_graph, graphql_types, hidden_classes, base_name):
"""Return a function that gives the types in the union type rooted at base_name."""
# When edges point to vertices of type base_name, and base_name is both non-abstract and
# has subclasses, we need to represent t... | 3b72a6865982638a280d0678f7092f564180ccb9 | 46,319 |
def _ends_in_by(word):
"""
Returns True if word ends in .by, else False
Args:
word (str): Filename to check
Returns:
boolean: Whether 'word' ends with 'by' or not
"""
return word[-3:] == ".by" | d6a080f8d3dcd5cab6ad6134df3dd27b3c2ceeea | 46,321 |
def is_subnet_of(a, b):
"""
Check if network-b is subnet of network-a
"""
if a.network_address != b.network_address:
return False
return a.prefixlen >= b.prefixlen | 32ae825937aa4e48098884e121f9238fbbd2ffec | 46,322 |
def str_join(lst, sep=' '):
"""join(list, [sep]) -> string
Behaves like string.join from Python 2."""
return sep.join(str(x) for x in lst) | 145520980df426fc84bda1eec0ef0eadcdaeaaec | 46,323 |
def get_slots(slot_line, utterance, slot_dict):
"""
Formats slot labels for an utterance. Ensures the multiword
slot labels are grouped together. For example the words
'birthday party' should be grouped together under the
same event_name label like event_name(birthday party)
instead of event_n... | 52b68870d51ef394871ea77470fd10a0fddeea3a | 46,324 |
def get_current_period(root_arr: list):
"""
Iterates through all xml-root objects in given list and returns the highest period incremented by 1 (since uploading the result of period `x` indicates that user wants to simulate period `x+1`).
Parameters
-----------
`root_arr`: list
List of xml r... | 7c31f6943d4a79b8b80d02d0b132b21b13581794 | 46,328 |
def get_labels(labels_path):
"""
Extract classes from label.txt
:param labels_path: str, path to file with labels
:return : list with labels
"""
labelsfile = open(labels_path, 'r')
labels = []
line = labelsfile.readline()
while line:
labels.append(line.split(' ', 1)[1].r... | 09ac5ed89733c1454874816fb353f2f00ae143f1 | 46,330 |
def split(target_list, num_anchor_list):
"""For each target and num_anchors: split target to a list of sub-target"""
target_list = [
label_targets.split(num_anchors, 0)
for label_targets, num_anchors in zip(target_list, num_anchor_list)
]
return target_list | 3c8e834e2f654c1c434f5f4ecd43b5ed2f54450d | 46,333 |
def epilog(text):
"""Adds an 'epilog' property to a CMD function.
It will be shown in the epilog. Usually useful for examples.
"""
def hook(fn):
fn.epilog = text
return fn
return hook | 87e8b23f319a73b8568d9290e9c366893a602b7b | 46,338 |
from pathlib import Path
def doRelocateFile(src, dst, overwrite=False):
"""
Relocate file `src` to the path `dst`.
If dirname(dst) is not exist yet, mkdir'ed silently.
If file is already exist as `dst`, raise ``FileExistsError``, unless
``overwrite=True``.
Parameter
---------
s : pa... | 380c3d2ad8f95eb4e4065a8a49699705c655eef7 | 46,339 |
async def health():
"""Check integrity of the server."""
return "The {{ cookiecutter.library_name }} API server is healthy." | a9140a5183cbb331700a5df05e789df7900298a9 | 46,341 |
def preprocess_call_name(name):
""" map an event name to a preprocess call name """
return 'preprocess_{}'.format(name) | b6e24ab1403f0b17d1970a6d2b8abacc9df094ea | 46,342 |
def get_catalog_path(layer):
"""Get the catalog path for the designated layer if possible. Ensures we can pass map layers to the subprocess.
If it's already a string, assume it's a catalog path and return it as is.
Args:
layer (layer object or string): Layer from which to retrieve the catalog path... | c32bf25878d3e2633461549e9a762997a5cbc1ab | 46,345 |
def get_instance_fields(instance):
"""Return parameter attributs managed by django-algolia
Tests:
>>> class ManagedClass(object): ALGOLIA_INDEX_FIELDS = ['some', 'fields']
>>> managed_instance = ManagedClass()
>>> get_instance_fields(ManagedClass)
['some', 'fields']
>>> ... | 989ff1a1fe59ad63397151832be2416acff2e4c8 | 46,347 |
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/t... | bafa99e8a406e068406806703be122573c68b084 | 46,348 |
from datetime import datetime
def timestamp(dt:int, fmt:str):
"""Helper function to convert timestamp to string
Arguments:
dt {int} -- timestamp
fmt {str} -- datetime format
Returns:
str -- datetime string
"""
return datetime.fromtimestamp(int(dt)).strftime(fmt) | 49b54e934a90eaac415738bc609cd129fbfbc002 | 46,349 |
import torch
def build_loss(property_map, loss_tradeoff):
"""
Build the loss function.
Args:
property_map (dict): mapping between the model properties and the
dataset properties
loss_tradeoff (dict): contains tradeoff factors for properties,
if needed
Returns:... | 0aa23419d845df460f3ef534eff304de4af436aa | 46,353 |
def get_objects(graph, predicate, subject=None):
"""Return a set of all the objects that match a predicate (and subject).
:graph: The policy graph.
:predicate: The predicate of the rules to match.
:subject: The subject of the rules to match (defaults to any).
:return: A set of all the objects that ... | 0da1a08e4da38e2de05920d92f65ecbc627bc06f | 46,354 |
def twoNumberSum(array : list, targetSum : int) -> list:
"""Finds the two numbers in the array needed to get targetSum
This solution has O(n) time complexity | O(n) space complexity
Args:
array: A list containing all the candidate numbers
targetSum: The target number we want to get by addin... | ed0ffe1efeb2072b2f96f231bfc1d396723c98ec | 46,359 |
def freqs2probs(freqs):
"""Converts the given frequencies (list of numeric values) into probabilities.
This just normalizes them to have sum = 1"""
freqs = list(freqs)
total = float(sum(freqs))
return [f/total for f in freqs] | 6d82756e428f289b804ebeed68262b34568b2720 | 46,366 |
import re
def get_info(var, entry):
"""Return a value for a user selected field in a line from a vcf (provided as a list split by whitespace)"""
ret_val = None
try:
#Loop through vcf fields backwards
for field in var[::-1]:
#First try fields seperated with an ':' e.g. GT:AO 0... | 4d8e785a8e3576f81bdfbd436af4a7f8239ca1cc | 46,370 |
def trim_from_start(s, substring):
"""Trims a substring from the target string (if it exists) returning the trimmed string.
Otherwise returns original target string."""
if s.startswith(substring):
s = s[len(substring) :]
return s | a4d68169a50672159af939855734fabff1fd8426 | 46,373 |
def nz(i:int, y=0):
""" Same as the nz() function of Pinescript, for ints:
Returns y if i is None, or 0 if y is None too """
if i is None:
if y is None:
return 0
return y
return i | b6331d4ef5030968b2df188ff649d4eb695de30f | 46,376 |
def subject(headers):
"""
Searches for the key 'Subject' in email headers
then returns the value of this key (the email
subject title).
"""
for header in headers:
if header['name'] == 'Subject':
return header['value'] | 8ef3f1b9cd105f6d3fb9e0a739d07bfcbf510ce4 | 46,377 |
def join_str_list(str_list):
"""Join a list of strings, handling spaces appropriately"""
return "".join(s[2:] if s.startswith("##") else " " + s for s in str_list) | c25dcc78bbb94767a02a33fe54439289f23975de | 46,384 |
import torch
def get_mention_token_dist_tensors(m1, m2):
""" Returns distance in tokens between two mentions """
succ = m1[0] < m2[0]
first = m1 if succ else m2
second = m2 if succ else m1
d = second[0] - (first[1] - 1)
if d < 0:
return torch.tensor(0, dtype=torch.long, device=m1.devi... | f2bf78ed5d2f1c743aeda67a2cb19e1029991407 | 46,391 |
def _lenlastline(s):
"""Get the length of the last line. More intelligent than
len(s.splitlines()[-1]).
"""
if not s or s.endswith(('\n', '\r')):
return 0
return len(s.splitlines()[-1]) | 68b425e28818fccabac61803b05a2967a2ccc93b | 46,392 |
def compile_krass_conditional(krass_conditional):
"""
Compile Krass conditional statements to Python conditional statements.
"""
# change true to True, && to and etc.
changes = [
("true", "True"),
("false", "False"),
("&&", " and "),
("||", " or "), # keep an eye on this one, for regex or non
("!", " no... | b29c01f4e62cfe4b1ffcbde37e3d0599db1565d3 | 46,395 |
def get_exception_kwargs(e):
""" Extracts extra info (attributes) from an exception object. """
kwargs = {}
for attr, value in vars(e).items():
if not attr.startswith('_') and attr not in ('args', 'message'):
kwargs[attr] = value
return kwargs | 45b5a78c766c02ee49a3af4ed793a61025e9424a | 46,396 |
def is_valid_name(name: str) -> bool:
"""Returns Ture if a given string represents a valid name (e.g., for a
dataset). Valid names contain only letters, digits, hyphen, underline, or
blanl. A valid name has to contain at least one digit or letter.
"""
allnums = 0
for c in name:
if c.isalnum():
all... | ef59211145ea8172b2a8796ca4ce2b204f200c53 | 46,398 |
def name(obj):
"""
Utility function that adds space before 'Serv' in the name of the object
Args:
obj (any): object
Returns:
str: returns human readable name of name of the specified object
"""
return type(obj).__name__.replace("Serv", " Serv") | 424772f9f3680c091865909f8b5c6856ddcb9a0f | 46,416 |
def val2bits(val, nbits):
"""Convert decimal integer to list of {0, 1}."""
# We return the bits in order high to low. For example,
# the value 6 is being returned as [1, 1, 0].
return [int(c) for c in format(val, '0{}b'.format(nbits))] | c1ceaf9f65c3115260943996737020d6cea1fe89 | 46,418 |
import torch
def batch_linear(x, W, b=None):
"""Computes y_i = x_i W_i + b_i where i is each observation index.
This is similar to `torch.nn.functional.linear`, but a version that
supports a different W for each observation.
x: has shape [obs, in_dims]
W: has shape [obs, out_dims, in_dims]
b... | 1cac8de9ad6b0941149f254a925da310f2c67fc6 | 46,428 |
import re
def timedur_standardize(timedur: str) -> str:
"""
Convert a user-input ambiguous time duration string to standard
abbreviations, following the rules:
1. No space.
2. One letter represents unit.
3. s,m,h,d,W,M for seconds, minutes, hours, days, weeks and months.
:param t... | c3d3922fa11ef7b2af3d1d1395d17c300400f473 | 46,429 |
def hr_button_id(button_id):
"""Convert a button identifier to human readable format."""
buttons = {
1: 'LEFT',
2: 'MIDDLE',
3: 'RIGHT'
}
return buttons[button_id] | 1ca6e943e20856c7a570972d9b3f9299c59e4b49 | 46,431 |
def ql_patchplot(ax,vals,plottitle,grid,heatmap=None):
"""
Make patch plot of specific metrics provided in configuration file
Args:
ax: matplotlib subplot
vals: QA metric to be plotted
plottitle: plot title from configuration file
grid: shape of patch plot
Optional:
... | 6dfc2001805ebe3ec68e5ed05a9c9eb971f55aad | 46,441 |
import re
def note_filename_from_query(fn: str) -> str:
"""
Remove characters from note title that could cause filename problems
"""
fn = re.sub(r"[^a-zA-Z0-9 _\-\/]", "", fn)
fn = re.sub(r"\s+", " ", fn)
fn = re.sub(r"^\s+", "", fn)
fn = re.sub(r"\s+$", "", fn)
return fn | c660631b9b76fc38744f78b9e898ebf5e563f15e | 46,443 |
import uuid
def get_client_token(**_):
"""Generate a random client token."""
return str(uuid.uuid4()) | 6125447f3f4d7fc4d0b3efef743c272acf9e186a | 46,445 |
def groups_per_user(group_dictionary):
"""The groups_per_user function receives a dictionary, which contains group names
with the list of users. Users can belong to multiple groups. It returns a
dictionary with the users as keys and a list of their groups as values."""
user_groups = {}
for group, users in group_di... | 5a48a376c8489024747af12609303617d5a57843 | 46,447 |
def save_fill(C, J):
"""Fill question marks at beginning, up to one before the first digit."""
first_digit = 0
for c, j in zip(C, J):
if c != '?' or j != '?':
break
first_digit += 1
for i in range(first_digit-1):
if C[i] == '?':
C = list(C)
C[i... | 2b7e22027b90c32b104cd2471bc57b64f630a6c7 | 46,451 |
def set_firewall_fail_open_behavior(api, configuration, api_version, api_exception, fail_open, policy_id):
""" Configures Firewall to operate in fail open or fail closed mode for a policy. Demonstrates how to configure multiple policy settings.
:param api: The Deep Security API modules.
:param configuratio... | 6770eb4f32f7b436d1a01dc39a5c75f0ad8cfc7c | 46,452 |
from pathlib import Path
def dir_is_empty(dir_path, start_pattern="."):
"""
Check that the directory at `dir_path` is empty,
except maybe for some files starting with `start_pattern`
"""
# Ensure input is a Path type
dir_path = Path(dir_path)
dir_files = list(dir_path.rglob(f'[!{start_patt... | 6d5d863483d4c3ce5fca9cf2f96273744f0a71ef | 46,453 |
def get(attr):
""" record.__getitem__(attr) """
def wrapped(record):
return record[attr]
return wrapped | 6184bf18b23cef43a9f31ce37f49158ba96b701f | 46,456 |
import requests
def is_website_online(path, timeout):
"""
Checks wether a given website is currently online. To do that, it reads the
HTTP status code. However, you could also add addidtional checks, e. g. testing
if a specific text is returned.
Parameters
----------
- path : str
... | 066804d8d93db69861dcb80134a237ab7edadbab | 46,467 |
def lightness_correlate(Y_b, Y_w, Q, Q_w):
"""
Returns the *Lightness* correlate :math:`J`.
Parameters
----------
Y_b : numeric
Tristimulus values :math:`Y_b` the background.
Y_w : numeric
Tristimulus values :math:`Y_b` the reference white.
Q : numeric
*Brightness*... | 854785cf9de0a03dcfc16a4e094dd39298f9abd7 | 46,469 |
def ScalarProperty(cdescriptor):
"""Returns a scalar property for the given descriptor."""
def Getter(self):
return self._cmsg.GetScalar(cdescriptor)
def Setter(self, value):
self._cmsg.SetScalar(cdescriptor, value)
return property(Getter, Setter) | d27505a9038503a4e567ba52b5792aac56e5170b | 46,475 |
from typing import Optional
from typing import Union
from typing import List
from typing import Set
from typing import Tuple
def enforce_list(scope: Optional[Union[str, List, Set, Tuple]]) -> List:
"""
Converts a space separated string to a list of scopes.
Note:
If an iterable is passed to this m... | e87e85b7be9f964a2f8afc112b937175283c11da | 46,479 |
def bani(registers, opcodes):
"""bani (bitwise AND immediate) stores into register C the result of the
bitwise AND of register A and value B."""
test_result = registers[opcodes[1]] & opcodes[2]
return test_result | dfc5ba9c19d53aa11c5a0a37bbaf6f09632d729d | 46,480 |
def _apply_if_callable(maybe_callable, obj, **kwargs):
"""
Evaluate possibly callable input using obj and kwargs if it is callable,
otherwise return as it is
"""
if callable(maybe_callable):
return maybe_callable(obj, **kwargs)
return maybe_callable | 21c101b32caadd208dcbeccfc7ef84ace11d848c | 46,484 |
def F(p, d=2):
"""
Given the depolarizating probabilty of a twirled channel in :math:`d`
dimensions, returns the fidelity of the original gate.
:param float p: Depolarizing parameter for the twirled channel.
:param int d: Dimensionality of the Hilbert space on which the gate acts.
"""
r... | 05dd2a0f9f1a00e3e62a9d00e5bda4998caadb28 | 46,490 |
def get_role_features_from_annotations(role_annotations):
"""Splits the verb and role information (in original annotations file) to separate values"""
head, role = role_annotations.split(")] ")
head_pos, head_wf = head.lstrip("[(").split()
span, tokens = role.split(maxsplit=1)
span, label = span.rst... | 2d7f3c012c9469ec9e492063237e8ce54a1b9d41 | 46,494 |
def filter_song_md(song, md_list=['id'], no_singletons=True):
"""Returns a list of desired metadata from a song.
Does not modify the given song.
:param song: Dictionary representing a GM song.
:param md_list: (optional) the ordered list of metadata to select.
:param no_singletons: (optional) if md_... | f592c0dd422e16868cb565395237c5da333be1a7 | 46,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.