content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from datetime import datetime
def get_time_from_header(hdu):
""" Make a datetime object from a fits header.
Include fractional seconds in the returned value
"""
tstring1 = hdu[0].header['DATE-OBS']
t1 = datetime.strptime(tstring1, '%Y-%m-%dT%H:%M:%S.%f')
return t1 | 559165a43a4d7b1de48c7c16a37a2cb58d8442a2 | 622,262 |
def fmt_value(value):
"""format attribute value"""
return value.strip().replace('\r', ' ').replace('\n', ' ') | 7b4669fdf60bddfa68183bce6c3f8ef77f1f299d | 622,263 |
def get_job_exe_input_vol_name(job_exe):
"""Returns the container input volume name for the given job execution
:param job_exe: The job execution model (must not be queued) with related job and job_type fields
:type job_exe: :class:`job.models.JobExecution`
:returns: The container input volume name
... | 8d42866670bd1e10f22e8692144bf1f5b0034e3b | 622,267 |
def floatnan(s):
"""converts string to float
returns NaN on conversion error"""
try:
return float(s)
except ValueError:
return float('NaN') | b618013ea76346e248b21ed0fc5f0b6a3cbbab95 | 622,270 |
def ztwilight(alt) :
"""Estimate twilight contribution to zenith sky brightness, in magnitudes
per square arcsecond.
Evaluates a polynomial approximation to observational data (see source for
reference) of zenith sky brightness (blue) as a function of the sun's elevation
from -0.9 degrees to -18... | 6fcaa4ad0c5986319a84df9ddd75da81ec4b712f | 622,272 |
def _NestedMapCopier(nmap):
"""Returns a function that will DeepCopy the map on each call."""
def Copier():
return nmap.DeepCopy()
return Copier | d6c5840a84138996521bdbf57d94f8a40d1f4b96 | 622,277 |
def read_file(name):
"""Given the path/name of the file, return nthe jobs list with jobs[][0]: weight and jobs[][1]: length.
"""
file = open(name,'r')
data = file.readlines()
jobs = []
for line in data[1:]:
items = line.split()
jobs.append([int(items[0]),int(items[... | 3e6e5b51913f272da80943a2acaa68165bbc0af0 | 622,278 |
def route_file_paths(fpaths,dir_src,dir_dst):
"""Convert list of files to src:dst maps, replacing src with dst filepath
:param fpaths: list of globbed filepaths
:param dir_src: filepath (str)
:param dir_dst: filepath (str)
:return: list of dicts with src:dst filepaths (str)
"""
return [ {'src': f, 'dst': ... | 273015c81b550665eca633926f239f173d542ff0 | 622,279 |
def decode(s):
"""Decode string in format k[str] to str * k
>>> decode('3[a2[c]]')
'accaccacc'
"""
stack = []
for c in s:
if c is ']':
seg, num = '', ''
while stack:
cur = stack.pop()
if cur is '[':
break
... | db649b13e0a75e2ff58fb054bee32f1bcddea914 | 622,288 |
def get_f_C_i_1(region, glass_spec_category):
"""天窓等の屋根又は屋根の直下の天井に設置されている開口部の冷房期の取得日射熱補正係数
Args:
region(int): 省エネルギー地域区分
glass_spec_category(str): ガラスの仕様の区分
Returns:
float: 天窓等の屋根又は屋根の直下の天井に設置されている開口部の冷房期の取得日射熱補正係数
"""
# 表1(b) 天窓等の屋根又は屋根の直下の天井に設置されている開口部の冷房期の取得日射熱補正係数
table_... | a33af4ee97e9e24e4fb79331450b931157932fe4 | 622,289 |
def _create_git_url_from_ssh_url(ssh_url: str) -> str:
"""
Return a git:// URL from the given ssh_url
"""
return ssh_url.replace("/", ":").replace("git@", "git://") | 061b375543a3dcc3d304d43dac6754819d67c0c5 | 622,299 |
def td_to_sec(td):
""" Returns the floating point number of seconds in a timedelta object.
"""
return td.days * 24 * 3600 + td.seconds + td.microseconds * 1e-6 | 1819217b36a11fea6e919eb1454e86791bc1c164 | 622,300 |
import re
def stat_check(string):
"""Validate input of filter string for values like atime, mtime, ctime.
These shuld be integer values prefixed by a + or a - only with no spaces
Eg:
1
5
-10
+20
Invalid:
1.5
abc
$#@
+ 5
a5
... | 2d40873d3838d817cfd0932f436fa8eeb2cdc1b8 | 622,302 |
def preboil_grav(target_og: float,
preboil_vol: float = 7,
postboil_vol: float = 6):
"""Computes preboil gravity to to verify before concluding mash
Args:
preboil_vol: Pre-boil volume in gal
target_og: Target original gravity for primary fermentation e.g. 1.040
pos... | aab73da4e2c7060851db9dad9420c08a10b25ca0 | 622,305 |
from pathlib import Path
def rel_path(path: Path) -> Path:
"""
Returns the path relative to where data_check is started from
if it's relative to this path.
"""
try:
return path.absolute().relative_to(Path(".").absolute())
except ValueError:
return path | cf59273a7256a0a4115ce8f3ffd35a9feb489f44 | 622,306 |
def spacy_format_labels(ys, labels):
"""Convert a list of labels to the format spaCy expects for model training."""
return [{l: int(l in y) for l in labels} for y in ys] | ee4eba97976ff042ff202b97332e14bccb83729d | 622,309 |
def _is_valid(host_dict, filters):
"""Validates host.
Args:
host_dict (dict): Host
filters (dict): Dict of re.match filters.
Returns:
bool: True if host is valid
"""
for key, match in filters.items():
if not match(host_dict[key]):
return False
return... | dc4f707beb65db88554edfb0d002402f074b6f1e | 622,310 |
import torch
def get_elem_size(tensor_obj):
"""
:param tensor_obj: a tensor
:return: the size in bytes of a single element in the tensor based on its
type
>>> t1 = tensor([1,2,3], dtype=torch.int32)
>>> size = get_elem_size(t1)
>>> assert size == 4
>>> del t1
>>> t2 = tensor([1.,... | e71289608540ffb6e3f76e929560a6dcbc98e5af | 622,311 |
def namehassuffix(obj, suffix):
"""
Returns whether obj's name ends with suffix.
"""
return obj.name.endswith(suffix) | 45449eefd48c7382ce7ed72706bc7bfda0fcbb7e | 622,313 |
def get_data_year(year, data_structure):
"""
Retrieve the data for a given year.
:param year: a defined year for which corresponding data will be returned
:param data_structure: the dictionary holding the input data
:return: data dictionary
"""
try:
data_year = data_structure[year]... | f0949866f60d11ed47d5b07099d02466e2231edb | 622,315 |
def emission_spectrum(spectrum_data):
"""Takes spectral data of energy eigenvalues and returns the emission spectrum relative to a state
of given index. The resulting "upwards" transition frequencies are calculated by subtracting from eigenenergies
the energy of the select state, and multiplying the result ... | 9e931370852fc6333421948fee39eb700fa81671 | 622,318 |
def pr_full_name_committer(payload):
"""Returns the full name (ex. <a-user>/optee_os) of the Git project."""
return payload['pull_request']['head']['repo']['full_name'] | 6a591a670579d6a0ee266159833fa6506d37316f | 622,321 |
def _find_outer(tokens, token_list):
"""
This function finds the first occurrence of a token from tokens in
token_list that is not within parentheses. It returns the partition of
token_list by this occurrence, meaning that
result[0] + [token] + result[1] == token_list.
If there is no such occurr... | 9ffa81c90d69e787e6c949e0681daee66f54797a | 622,323 |
def fleur_calc_get_structure(calc_node):
"""
Get the AiiDA data structure from a fleur calculations
"""
#get fleurinp
fleurinp = calc_node.inp.fleurinpdata
structure = fleurinp.get_structuredata(fleurinp)
return structure | abbd39946d83f4dea38d8e10d6f176039fbe930f | 622,324 |
def n_workers_callback(value):
"""Validate the n-workers option."""
if value == "auto":
pass
elif value in [None, "None", "none"]:
value = None
elif isinstance(value, int) and 1 <= value:
pass
elif isinstance(value, str) and value.isdigit():
value = int(value)
els... | 7d9c6edb000b4da3587ba285e2c067c34c58e5be | 622,325 |
import psutil
def num_unused_cpus(thresh=10):
"""
Returns the number of cpus with utilization less than `thresh` percent
"""
cpu_usage = psutil.cpu_percent(percpu=True)
return sum([p < thresh for p in cpu_usage]) | 5dc5368c254f821946c670a4a82931ac31ce5c48 | 622,326 |
def iterative_partition(data, left, right):
"""
Function which partitions the data into two segments,
the left which is less than the pivot and the right
which is greater than the pivot. The pivot for this
algo is the right most index. This function returns
the ending index of the pivot.
:p... | 6145cde4ebc5e1b6af8c5933716ee0cf9c1a6841 | 622,327 |
def reductor(result_set):
"""Do the reduce part of map/reduce and return a list of rows."""
result_list = []
while result_set.qsize() > 0:
result = result_set.get()
for row in result:
result_list.append(row)
return result_list | f2036a1606916cc2d285167bd5c39f8b22b3886f | 622,328 |
def strict_update(d1, d2):
"""For two dicts `d1` and `d2`, works like `d1.update(d2)`, except without
adding any new keys to `d1` (only values of existing keys updated).
Dictonaries are copied, so that this does not have an 'inplace' effect.
"""
assert type(d1) == type(d2) == dict, 'Only for dictio... | 35199d8f1258209b8f0b821aadc4fdcf7e1403fb | 622,329 |
import math
def segment_sieve(begin, end):
"""Enumerates the prime numbers in [`begin`, `end`).
Returns (as a tuple):
- `is_prime`: a list of bool values.
If an integer `i` is a prime number, then `is_prime[i - begin]` is True.
Otherwise `is_prime[i -begin]` is False.
- `primes`: a list ... | 5498a57e5f14eb677546bc57f305ed9a2e8df46a | 622,331 |
from typing import Dict
from typing import Optional
from typing import List
from typing import Tuple
def prepare_individual_spectra_for_pySPLASH(
spectra_dict: Dict, mslevel: Optional[int] = -1
) -> List[Tuple[float, float]]:
""" This function takes a mzmlripper spectra and returns a list
formatted to be ... | 3af45834ba6de2a4798d06a70ab1f8202f39421e | 622,332 |
def matrix_inner_prod(A, B):
"""
Compute the matrix inner product <A, B> = trace(A^T * B).
"""
assert A.shape[0] == B.shape[0]
assert A.shape[1] == B.shape[1]
return A.reshape(-1).dot(B.reshape(-1)) | 8896c6d8a7868857c752987b7e8d1680901b1c2d | 622,335 |
import random
import string
def get_random_string(length=15):
"""
Returns a random string with the length especified
Args:
length (int): string length
Returns:
str
"""
assert isinstance(length, int)
assert length > 0
return ''.join(random.choices(string.ascii_letters+s... | 2b5554155533af4525e7852331498e1d6a4dac55 | 622,336 |
import copy
def remove_pad_sequences(sequences, pad_id=0):
"""Remove padding.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
pad_id : int
The pad ID.
Returns
----------
list of list of int
The processed seque... | 15657e0ce29774ec7bb84c9c16b8ffdd25a38567 | 622,337 |
def not_found(e):
"""Return a 404 if the route is not found."""
status_code = 404
response = {
'success': False,
'message': 'Not a valid endpoint.',
}, status_code
return response | 1714990cc4155cecd574928a7ac2f937b5f3124b | 622,339 |
def _get_step_from_checkpoint_path(path):
"""Extracts the global step from a checkpoint path."""
split_path = path.rsplit("model.ckpt-", 1)
if len(split_path) != 2:
raise ValueError("Unrecognized checkpoint path: {}".format(path))
return int(split_path[1]) | 9c5bb7bec55e678229fbdcd57d8f7b5e88e727cc | 622,341 |
def image_type(image_type):
"""Converts to a three letter image type.
aki, kernel => aki
ari, ramdisk => ari
anything else => ami
"""
if image_type == 'kernel':
return 'aki'
if image_type == 'ramdisk':
return 'ari'
if image_type not in ['aki', 'ari']:
return 'am... | 1c8603bd31e9db7312a81c043c68eca0c1f50ec6 | 622,345 |
import sqlite3
def connect_db(path: str='db.sqlite3') -> object:
"""
Connect to our sqlite3 db.
"""
return sqlite3.connect('db.sqlite3') | 94718c6c81a1a4b6e1cc679c66b6f6ec5e63ad7f | 622,353 |
def scaling_factor(rect, size):
""" Calculate the scaling factor for the current image to be
resized to the new dimensions
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:returns: floating point scaling factor
"""
new_height, new_width... | 0c2eea22837a9f497f9d491a9987eb4ecbdf069f | 622,354 |
import typing
import functools
import asyncio
def executor_function(sync_function: typing.Callable):
"""A decorator that wraps a sync function in an executor, changing it into an async function.
This allows processing functions to be wrapped and used immediately as an async function.
Examples
------... | 6985904d351d5261d6efbf71c87642850d94aa04 | 622,357 |
def almost_flatten(A):
"""Flatten array in all except last dimension"""
return A.reshape((-1,A.shape[-1])) | 03cf9fb5b75f642f10c7f5153d4c5707e0de3350 | 622,359 |
def delete(db_object):
""" Generates a query that deletes the given `db_object` from the DB.
Args:
db_object (DbObject): The DB object being deleted.
"""
id_param = "%sId" % db_object.type_name()
query_str = """mutation delete%sPyApi%s{update%s(
where: {id: $%s} data: {deleted: true... | f5aa5d834a9551f66e260c4a157327dba459f430 | 622,363 |
def clock_to_float(s):
"""given '7:30' return 7.5"""
if ":" in s:
M,S=[int(x) for x in s.split(":")]
return round(float(M+S/60.0),2)
else:
return float(s) | 4d92d3930b46194c4b5ad33a8e7d7d30e68fb6a2 | 622,365 |
import torch
from typing import Set
def get_entities(triples: torch.LongTensor) -> Set[int]:
"""Get all entities from the triples."""
return set(triples[:, [0, 2]].flatten().tolist()) | b4fc6cf6003b088ba64cc5bfdfce871c24254769 | 622,367 |
import re
def normalize_version(version):
"""
Normalize a version string by removing extra zeroes and periods.
"""
return [int(x) for x in re.sub(r'(\.0+)*$', '', version).split('.')] | 24f9db935e67495f6583b17627222c68ad5423ee | 622,368 |
def dict_merge(*dicts):
"""
Merge one or more dicts into one.
>>> d = dict_merge({'a': 'A'}, {'b': 'B'}, {'c': 'C'})
>>> sorted(d.keys()), sorted(d.values())
(['a', 'b', 'c'], ['A', 'B', 'C'])
"""
final = {}
for d in dicts:
final.update(d)
return final | 1aae97250a3256a9f4b95094ecb6415fc39669c7 | 622,371 |
def address_area_or_none(address_area):
"""
Get Formatted Address Area Result
:param address_area: Address object returned on Company
:return: Address as an id name object or None
"""
if address_area:
return {
'id': str(address_area.id),
'name': address_area.name,... | 746c1d5e4e926bc6680a4d432154449d5631a3bb | 622,372 |
def modify_cum_probs(cum_probs):
"""
Insersion prolongs read length.
Therefore, insersion, deletion, and mutation rate must be modified based on expected genarated read length.
E(generated_readlength) = original_readlength * (1 + ci + ci^2 + ci^3 + ... + ci^inf) = original_readlength / (1 - ci)
E(ge... | 7977b48478cb0a42d843bcaabfebaece48e04096 | 622,373 |
def decompose_list(input_):
"""Recusively decompose any list structure into a flat list"""
def dec(input_, output_):
if type(input_) is list:
for subitem in input_:
dec(subitem, output_)
else:
output_.append(input_)
output_ = []
dec(input_, output_... | 7db7f7b884acb5c1f9a7c6d8f171fd3c3e360e8b | 622,374 |
def ssl_scan(url):
"""
Method which change url to ssl url (https).
:param url: Main url of scanned Website.
:return: Link with changed Url (http to https)
"""
if url.startswith('http://'):
return url.replace('http://', 'https://')
return 'https://' + url | 5a3f767781a833bc25284cfad07ad4440cb19dc6 | 622,375 |
def SliceMutator(current, value):
"""Returns a slice of the current value. Value must be a tuple (start, stop) or (start, stop, step)"""
return current[slice(value[0], value[1], value[2] if len(value) > 2 else None)] | 043296b4c13bc27ea6d5c9a26d580c1144cf42a1 | 622,376 |
def parse_range(range_str):
""" Parse the chrom, start and end from the range string
Args:
range_str (str): In format chrom:start-end
Returns:
chrom (str), start (int), end (int)
"""
chrom, start_end = range_str.split(":")
start, end = start_end.split("-")
return str(chrom), ... | e6c60ae211dc1109c08e134adc2a6df0af29988c | 622,377 |
def get_highest_action(life):
"""Returns highest action in the queue."""
if life['actions'] and life['actions'][0]:
return life['actions'][0]
else:
return None | 0c944ea2134094dcc76f0cfbf412c2be5719a5cc | 622,380 |
def default_matrix_multiplication(a: list, b: list) -> list:
"""
Multiplication only for 2x2 matrices
"""
if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2:
raise Exception("Matrices are not 2x2")
new_matrix = [
[a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1... | 129d8d87046f67f6cb4fe1ae41ddc815d7fbee40 | 622,381 |
import itertools
def tag_text(text, tag_info_list):
"""Apply start/end tags to spans of the given text.
Parameters
----------
text : str
Text to be tagged
tag_info_list : list of tuples
Each tuple refers to a span of the given text. Fields are `(start_ix,
end_ix, substrin... | 63eac988d44cc4c21b0bf396adb8256d66b38aa4 | 622,384 |
def format_release(release: dict) -> dict:
"""
Format a raw release record from GitHub into a release usable by Virtool.
:param release: the GitHub release record
:return: a release for use within Virtool
"""
asset = release["assets"][0]
return {
"id": release["id"],
"name... | 24f1d28bd130bd3d1761f3b0019eab1afcef2571 | 622,385 |
from unittest.mock import call
def test(args=None):
"""
Runs the tests.
"""
module = getattr(args, 'module', '')
if module == '':
module = 'tests'
else:
module = 'tests.{}'.format(module)
return call("DJANGO_SETTINGS_MODULE='tests.settings' coverage run "
".... | be87c537803d4e0bee0a80acaa3420c2fb7b5ade | 622,390 |
def const(xx, a):
"""
Returns the constant a for any xx.
"""
return a | b01827d37a37b243926801fad8e74488a6f92441 | 622,393 |
import re
def version_normalize(v):
"""Normalize version string numbers like 3.10.1 so they can be compared."""
return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")] | 55b6e6766ac28dea88a441c423eb548097145fce | 622,394 |
def duplicated_varnames(df):
"""Return a dict of all variable names that
are duplicated in a given dataframe."""
repeat_dict = {}
var_list = list(df) # list of varnames as strings
for varname in var_list:
# make a list of all instances of that varname
test_list = [v for v in var_lis... | dd06736b9713e4dc89fd14bdebc6582445bd85ab | 622,398 |
def convert_color(color):
"""Converts a color object (be it touple-like, or string to an SVG-readable color string)."""
if type(color) == str:
return color
else:
return '#' + ''.join(('0' + hex(int(c))[2:])[-2:] for c in color) | 9e539b91f19f0d5053cdb63d008a9cc34db67493 | 622,407 |
def get_shortest_path(path_list):
"""
Return the shortest path (the uppest path)
(Used for find the uppest path for the files with the same filename)
Parameter
path_list: list[path-like str], e.g. ["./db.json", "./test/db.json", "./config/db.json"]
Return
return the shortest path, e... | 6790705c3242c2b6925f42e9ccc826b12da7c425 | 622,409 |
def getType(v):
"""
Returns a tuple with True if a vsip type is found, plus a string indicating the type.
For instance for
a = vsip_vcreate_f(10,VSIP_MEM_NONE)
will return for the call getType(a) (True,'vview_f')
also returns types of scalars derived from structure. for insta... | 2c7eeccc8a1aafa692a260d8eecfa08459b80dad | 622,418 |
def paths_are_not_structured(paths):
"""
returns true if the list of paths are not yet file system structured.
i.e. if not all paths start with the root path (contribution label)
"""
if not paths:
return False
root = paths[0][: paths[0].find('/', 1)]
for path in reversed(paths):
... | f37e368ea63cf651af00bfcc19fb9c7957138c51 | 622,419 |
def _evaluate(comp):
"""
Evaluates the value of a given expression component.
Parameters
----------
comp : dict
Dictionary of references, coefficient and operator
Returns
-------
v : float
Current value of the expression.
"""
ref = comp['ref']
val = comp['v... | 76fc414e5171dd43b92c585177fe3aab46ed6763 | 622,422 |
def compute_n_trials(trials):
"""
Compute number of trials in trials object
:param trials: trials object
:type trials: dict
returns: int containing number of trials in session
"""
return trials['choice'].shape[0] | f5c43bb0b7dd3137a62b78ce72efe548169268bb | 622,426 |
def correction_byte_table_l() -> dict[int, int]:
"""Table of the number of correction bytes per block for the correction
level L.
Returns:
dict[int, int]: Dictionary of the form {version: number of correction
bytes}
"""
table = {
1: 7, 2: 10, 3: 15, 4: 20, 5: 26, 6: 18, 7: 2... | 8d0b96b603968f27a16d30a2d33a472cfcb3a002 | 622,431 |
import gzip
def smart_open(filename: str, mode="rt", ftype="auto", errors='replace'):
"""
Returns a file descriptor for filename with UTF-8 encoding.
If mode is "rt", file is opened read-only.
If ftype is "auto", uses gzip iff filename endswith .gz.
If ftype is {"gzip","gz"}, uses gzip.
Note:... | 12a8f941880ae96f27e72aa17c738c57017993d1 | 622,433 |
def get_tweet_object_from_tweet_js(seq, num_of_tweet_block):
"""
Helper method to get each smaller tweet blocks.
Tested May 2020 on tweet.js (subject to change as Twitter rolls out new data layout)
Parameters:
seq: (file object) opens a file in read mode.
num_of_tweet_block: (int) ... | 1bbeea97634820a18c3375ce1a5122c6d5b8f693 | 622,437 |
def flatten_list(obj):
"""
Given a set of embedded lists, return a single, "flattened" list.
:param obj:
:return:
"""
if not isinstance(obj, list):
return [obj]
else:
ret_list = []
for elt in obj:
ret_list.extend(flatten_list(elt))
return ret_list | a34c1a50716249458c078f61072029e83c0ab38b | 622,439 |
def verify_brother(brother, user):
""" Verify user is the same as brother """
if user.brother.id == brother.id:
return True
else:
return False | f4d05d83ed9c5f818b0d7ee152372f7933c73c94 | 622,443 |
def _combine_sup_unsup_datasets(sup_data, unsup_data):
"""Combines supervised and usupervised samples into single dictionary.
Args:
sup_data: dictionary with examples from supervised dataset.
unsup_data: dictionary with examples from unsupervised dataset.
Returns:
Dictionary with combined suvervised... | 5dedf07f98317697b08bfd570b623fa88c5be375 | 622,445 |
def _neighborhood_aggregate(G, node, node_labels, edge_attr=None):
"""
Compute new labels for given node by aggregating
the labels of each node's neighbors.
"""
label_list = []
for nbr in G.neighbors(node):
prefix = "" if edge_attr is None else str(G[node][nbr][edge_attr])
label_... | 3569e1a79b654eb31d693f38ba327dd3e1ce6949 | 622,451 |
def my_isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""
Test if a and b are close enough to consider equal.
This function is essentially the same as the math.isclose function which
was added in Python 3.5 but is created here to increase compatibility across
all Python 3 versions.
"""
retu... | f7799e6cd7df7500439de51ed0c9f1d8ecf1c94b | 622,452 |
def keyExists(thisDict, key):
"""Returns true if dictionary contains the key"""
return key in thisDict | 89a1d3efd321057f08e6793733e0c7f3e576de47 | 622,453 |
from typing import Optional
from typing import Union
from typing import Sequence
from typing import Tuple
def _verify_encodings(
encodings: Optional[Union[str, Sequence[str]]]
) -> Optional[Tuple[str, ...]]:
"""Checks the encoding to ensure proper format"""
if encodings is None:
return None
i... | 0937b55034f76c2f69f2fe7c29ffa8108c91011c | 622,454 |
def user_confirm(prompt, default=False):
"""Yes/No question dialog with user.
:param prompt: question/statement to present to user (string)
:param default: boolean value to return if empty string
is received as response to prompt
"""
if default:
prompt_default = "[Y/n]"... | 1c8a131808e8b77f8643b0925587efebfe650722 | 622,455 |
import math
def calculate_vr_from_vm_va(vm, va):
"""
Compute the value of vr from vm and va
Parameters
----------
vm : float
The value of voltage magnitude (per)
va : float
The value of voltage angle (degrees)
Returns
-------
float : the value of vr or None if... | 153a5403e85e8e99243a70259dbbdf97e524d8d4 | 622,457 |
def get_op_tensor_name(name):
"""
Will automatically determine if ``name`` is a tensor name (ends with ':x')
or a op name.
If it is an op name, the corresponding tensor name is assumed to be ``op_name + ':0'``.
Args:
name(str): name of an op or a tensor
Returns:
tuple: (op_name, tensor_name)
"""
if len(nam... | ccf67c9c6f7fa9f82f4886a5dcdd3567f612bd67 | 622,458 |
import heapq
def dijkstra(graph, source, target):
"""
Finds the shortest path and shortest distance from source to target
:param graph: Dictionary linking the vertices using list of tuples
:param source: The vertex to start the path.
:param target: The vertex to end the path.
:return: shortes... | 27df82387ff3139941f1c8d2b27a7e294e52e0c8 | 622,460 |
def parse_line(line):
"""Parse line to (instruction, value) tuple."""
return [int(part) if part.isdigit() else part for part in line.split()] | 9521d236ecf77a727a233385c901dc5c17a6f5a0 | 622,461 |
from typing import Dict
from typing import Any
def has_key(dictionary: Dict[str, Any], key: str) -> bool:
"""
Check whether dictionary has given key is present or not
:param dictionary: Dictionary that need to check if key present or not
:param key: Key value that need to check
:return: Boolean v... | e1bb6eae8b9758b777003a9fd937d21dcd7166a7 | 622,463 |
import time
def retry(func, max_tries = 16, timeout = 0.1):
"""Helper to retry functions and preserve exceptions, handy for network calls."""
acm = 0
while True:
try:
return func()
except Exception as exception:
if acm > max_tries:
raise exce... | 9ea59b768681303605ab0d2a81c04b084a251d7f | 622,464 |
def scale(val, old_scale, new_scale=100):
""" Change scale of a value
:param val: value
:param old_scale: current scale max value
:param new_scale: new scale max value
:return: value converted to new scale """
return float(val * new_scale) / old_scale | 6a44ca50c20799b0d71f74a4a569f8f887dbf49c | 622,466 |
def decide_flow_name(desc):
"""
Based on the provided description, determine the FlowName.
:param desc: str, row description
:return: str, flowname for row
"""
if 'Production' in desc:
return 'Production'
if 'Consumed' in desc:
return 'Consumed'
if 'Sales' in desc:
... | 7831b81fbd78b88d25f4a15f4762b11d5ed59e93 | 622,468 |
def omit_keys(*args):
"""Remove keys from a dictionary"""
*keys, dict_obj = args
return {
field: value
for field, value in dict_obj.items()
if field not in keys
} | c81211d1ccc59b501612dbdbe8546c2c7c0e59cd | 622,470 |
def register_extensions(db, app):
"""Register Flask extensions."""
db.init_app(app)
with app.app_context():
db.create_all()
return None | 5a9ba8aa666a6723180129254a381859ee874e1e | 622,474 |
def tuning_score_distribution(performance_space, nbins=10):
"""
Computes TS_d, the tuning score based on the distribution of configurations in the performance space.
"""
histogram = performance_space.histogram(nbins)
if (histogram[9] / performance_space.size()) >= 0.1:
return ((0.5 / 0.9) *... | ea0d011aab5fd0176348a25fb978734240262030 | 622,477 |
def sliding_window(array, window, step=1, axis=0):
"""Generate chunks for encoding and labels.
Args:
array: Numpy array with the pileup counts
window: Length of output chunks
step: window minus chunk overlap
axis: defaults to 0
Returns:
Iterator with chunks
"""
... | 9bf0b8fc3002ac09e2939072ae5e20fb3e6f7211 | 622,485 |
import torch
def accuracy(output, target):
"""
Accuracy metric for deterministic model for classification.
Args:
output: Output Tensor with shape (examples, classes)
target: Target Tensor with shape (examples)
Returns: float accuracy
"""
with torch.no_grad():
pred = t... | bf6c049c6a3dde68e1b193f1caf3b32d06a4089f | 622,487 |
def vert_init_commodities(vertex_df, commodities, sources=None, inplace=True):
"""Add commodity columns to the vertex DataFrame
with zeros to vertices without commodity source and
source capacity at the vertices provided by `sources`.
Parameters
----------
vertex_df : (Geo)DataFrame
ver... | 235b0bca487a40e7204a99b782679ec7959a5705 | 622,489 |
def select_metadata(metadata, **attributes):
"""Select specific metadata describing preprocessed data.
Parameters
----------
metadata : :obj:`list` of :obj:`dict`
A list of metadata describing preprocessed data.
**attributes :
Keyword arguments specifying the required variable attri... | 9170278b8914c669a126abbf6c795bf44e2d01a3 | 622,492 |
def set_same_eff_all_tech(technologies, f_eff_achieved=1):
"""Helper function to assing same achieved efficiency
Arguments
----------
technologies : dict
Technologies
f_eff_achieved : float,default=1
Factor showing the fraction of how much an efficiency is achieved
Returns
... | ddccfe558e41d82e0a991718a88c2ccee80fe84f | 622,493 |
def smoothstep(a, b, x):
""" Returns the Hermite interpolation (cubic spline) for x between a and b.
The return value between 0.0-1.0 eases (slows down) as x nears a or b.
"""
if x < a:
return 0.0
if x >= b:
return 1.0
x = float(x - a) / (b - a)
return x * x * (3 - 2 * x) | a8648ba11449f3e91f859de77624b4f45570fb8e | 622,494 |
def CalculateNumBonds(mol):
"""
Calculation the number of bonds where between heavy atoms
--->nBond
:param mol: molecule
:type mol: rdkit.Chem.rdchem.Mol
:return: the number of bonds where between heavy atoms
:rtype: int
"""
nBond = mol.GetNumBonds()
retu... | d901301cd60a98aa8df46ce9aefdef858560a5c5 | 622,496 |
from pathlib import Path
from typing import List
def read_fasta(path: Path) -> List[tuple]:
"""Parse the FASTA file at `path` and return its content as a `list` of tuples containing the header and sequence.
:param path: the path to the FASTA file
:return: the FASTA content
"""
data = list()
... | 2e37862544b3353a6a9dfd2119a703488b06f91a | 622,497 |
def quote_str(value):
"""
Return a string in double quotes.
Parameters
----------
value : str
Some string
Returns
-------
quoted_value : str
The original value in quote marks
Example
-------
>>> quote_str('some value')
'"some value"'
"""
return ... | beaa09c517b6c2a92363652f2d53ae7fd6becabe | 622,499 |
def ends_with(suffix):
"""
Returns a function calling endswith using the given prefix on a given value.
>>> ends_with('123')('abc123')
True
>>> ends_with('abc')('abc123')
False
:param suffix: Suffix to check
:return: Function
"""
def _ends_with(s):
return s.endswith(su... | c56a1ce4d40e4c3705ca713a02243e6fb0e0347c | 622,511 |
import pickle
def load_pickle(filename):
"""
Load formatted skeleton data from pickle file
"""
with open(filename, 'rb') as fp:
data = pickle.load(fp)
return data | 65737b533e4315a012fc709a50056607c018f4e3 | 622,516 |
def limit(value, v_min, v_max):
"""
limit a float or int python var
:param value: value to limit
:param v_min: minimum value
:param v_max: maximum value
:return: limited value
"""
try:
return min(max(value, v_min), v_max)
except TypeError:
return None | 65d5214892cf454cddd2a7ab6429c62b74eb96f4 | 622,521 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.