content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _flatten(d):
""" Pack a hierarchical dictionary of variables into a list
Sorting is important as it ensures the function is called with
the inputs in the same order each time!
"""
l = []
# This sorting is important!
for (k,v) in sorted(d.items(), key=lambda t: t[0]):
if ... | d1aea2b85e161747262ec424e9b63fb336967236 | 22,093 |
def gwas(batch, vcf, phenotypes):
"""
QC data and get association test statistics
"""
cores = 2
g = batch.new_job(name='run-gwas')
g.image('gcr.io/<MY_PROJECT>/1kg-gwas:latest')
g.cpu(cores)
g.declare_resource_group(ofile={
'bed': '{root}.bed',
'bim': '{root}.bim',
... | 0f0b523a9a5976119219c7e746b602470f56be1d | 22,094 |
def mod_sqrt(n: int, p: int, is_odd: bool) -> int:
""" Find Square Root under Modulo p
Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists.
https://www.geeksforgeeks.org/find-square-root-under-modulo-p-set-1-when-p-is-in-form-of-4i-3/
"""
n %= p
y = pow(n, (p + ... | 9a04db0965f5db32fab29ba78e9963c25c72eefc | 22,095 |
def dealer_options(dealer_score):
"""
This function allows the dealer to hit or stay.
"""
if dealer_score < 17:
return True
else:
return False | 5c208d5ab330102ecd11ad6266c8a155e8220e9c | 22,096 |
def get_logging_options_string(args):
""" This function extracts the flags and options specified for logging options
added with add_logging_options. Presumably, this is used in "process-all"
scripts where we need to pass the logging options to the "process" script.
Args:
args (n... | 070ed0cd906845abf784bd566118a1959af875f2 | 22,097 |
def to_bytes(text, encoding='utf-8'):
"""Make sure text is bytes type."""
if not text:
return text
if not isinstance(text, bytes):
text = text.encode(encoding)
return text | 367da58c31dddd4c243c56a9780b47ef6682bee2 | 22,098 |
def email_get_unread(imap, from_email_address):
"""Returns (status, list of UIDs) of unread emails from a sending email address.
"""
search = '(UNSEEN UNFLAGGED FROM "{}")'.format(from_email_address)
status, response = imap.search(None, search)
if status != 'OK':
return status, response
... | 48c4cf036e24acadec425bb7bb8ac9395488229a | 22,099 |
def _lambda_risk_mapper(risk_level: int) -> str:
"""Helper methods
Parameters
----------
risk_level: int
number from range 0-4 represents risk factor for given vault
Returns
-------
string:
text representation of risk
"""
mappings = {0: "Non Eligible", 1: "Least", 2:... | e19ef85b82d4b36bb6e0dfdcae373f25a894dbff | 22,100 |
import math
def torsion_angle(c1, c2, c3, c4):
"""
float <- torsion_angle(a, b, c, d)
returns the torsion angle in degrees between 3D pts a,b,c,d
"""
v1 = (c1[0]-c2[0], c1[1]-c2[1], c1[2]-c2[2])
v2 = (c2[0]-c3[0], c2[1]-c3[1], c2[2]-c3[2])
v3 = (c3[0]-c4[0], c3[1]-c4[1], c3[2]-c4[2])
... | 32eb380fd8e4d0645481ab816a32e01144fb3c7b | 22,101 |
import argparse
def arg_parse():
"""
Parse command line arguments to the detector
"""
parser = argparse.ArgumentParser(description = " Red Neuronal Yolo V3")
parser.add_argument('--images',
dest = 'images',
help = 'Directorio donde se encuentran l... | 10a9880636c9569fa09094767128a5e53e69917a | 22,103 |
def accumulate(instructions: list) -> dict:
"""
Read and execute instructions until an infinite loop if found:
acc +12 -> add 12 to 'acc'
jmp +48 -> jump to the instruction located at 'index' + 48
nop -56 -> do nothing & go to the next instruction
if an instruction has already been ... | bf5a5bb278e71e783968eafed6a790ff2bdf77c1 | 22,105 |
from math import sqrt
def library_sqrt(x):
"""Uses math library"""
return sqrt(x) | e1b3df0e6fe6d5b62de8efea1bcc3df7ae994d1d | 22,106 |
def build_sampler( sampler_class, pe_method, force_method, T = 1.0e-4, \
dt = 1.0e-1, traj_len = 100, absxmax = 1.0e2, dt_max = None, min_rate = 0.6, \
max_rate = 0.7, gaussianprior_std = None ):
"""Builds a sampling.Sampler class object of type sampler_class.
Args:
sampler_class : Sampler... | 528966ec88dd8d4a910753290e19849f7919cf22 | 22,107 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_sep package"""
reload_params = {"package": u"fn_sep",
"incident_fields": [],
"action_fields": [u"sep_artifact_type_scan_results", u"sep_domain_name", u"sep_fingerprintlist_name", u"sep_fullpathna... | dcb34b8533c0356a12b6efcf2ae97e4e39dcf752 | 22,108 |
import time
from datetime import datetime
def SecondsToZuluTS(secs=None):
"""Returns Zulu TS from unix time seconds.
If secs is not provided will convert the current time.
"""
if not secs: secs = int(time.time())
return(datetime.utcfromtimestamp(secs).strftime("%Y-%m-%dT%H:%M:%SZ")) | 2ca96ed779020037eb360a1250243dfe628f6195 | 22,109 |
def _LookupMeOrUsername(cnxn, username, services, user_id):
"""Handle the 'me' syntax or lookup a user's user ID."""
if username.lower() == 'me':
return user_id
return services.user.LookupUserID(cnxn, username) | 68ef5ea6d6c3076717660848a0b8a9c3cb4847d4 | 22,111 |
def get_max_df(df, column):
"""
Get maximum of a dataframe column
Parameters:
----------
df: pandas dataframe
A data frame with multiple columns
column: str
Name of the column to get the maximum
Returns:
-------
"""
idx_max = df[column].idxmax... | 6511dda522f25d5cc69b6f8dd8ac37791015936d | 22,114 |
import torch
def attn_norm(weights, self_loop=False):
"""
weights: aggregation weights from a node's neighbours
add_eye:
"""
weights = weights.t()
weights = weights * (1 - torch.eye(weights.shape[0])).type_as(weights)
if self_loop:
weights = weights + torch.eye(weights.shape[0]).ty... | 156423493950bbbd369201fe9f0f9a6bdfb8844d | 22,117 |
import hashlib
import ctypes
def size_t_hash(key):
"""Hash the key using size_t.
Args:
key (str): The key to hash.
Returns:
str: The hashed key.
"""
hash_digest = hashlib.blake2b(key.encode()).hexdigest() # pylint: disable=no-member
return '%u' % ctypes.c_size_t(int(hash_dig... | 19aa7ec430c9c0fbbba45baa9812f755d19a4cfe | 22,120 |
def transpose(matrix):
"""转置矩阵 list
:param matrix: matrix list
:return: transpose matrix list
>>> matrix = [[1, 1, 2], [2, 2, 1], [3, 3, 2], [3, 4, 5]]
# [1, 1, 2]
# [2, 2, 1]
# [3, 3, 2]
# [3, 4, 5]
>>> transpose(matrix)
[[1, 2, 3, 3], [1, 2, 3, 4], [2, 1, 2, 5]]
# [1, 2, ... | 5a7798146f434eeb1c3b61c67b134499ff02030e | 22,121 |
import json
def get_expected_legacy_permit_list():
"""returns legacy expected permit list from mock"""
return json.loads("""{"TESTBLAH P-2187964": {"application_id": "P-2187964",
"dba_name": "TESTblah", "address": "420 Bud St, SF, California 94102", "parcel": "no idea", "activities": "retailer (medical an... | 882fc81bf62bbb4abd3c9f0c86270767ceabf701 | 22,126 |
def check_scenarios(scenes):
"""
Make sure all scenarios have unique case insensitive names
"""
assert len(scenes) == len(dict((k.lower(), v) for k, v in scenes))
return scenes | c9b437d396a4d0ca17c17a85cb99e8574cc78fe3 | 22,127 |
def filter_names(name):
"""
This is just the filter function
for the framework search
:param name:
:return:
"""
return name.lower() | dcb3246ad241347c38ff2d049b5f7a5c406a8c10 | 22,128 |
def is_even_permutation(seq1, seq2):
""" Determine whether a permutation of a sequence is even or odd.
:param seq1: the first sequence
:param seq2: the second sequence, which must be a permuation of the first
:returns: True if the permutation is even, False if it is odd
:rtype: bool
"""
siz... | 921f8a642241021f6bd41a42e231f92dc0565442 | 22,130 |
import re
def get_title(filename: str) -> str:
"""Locate the first title in a HTML document."""
with open(filename, 'r') as index:
raw_html = index.read()
res = re.search('<title>(.*?)</title>', raw_html)
if res and len(res.groups()):
return res.group(1)
return '~somebody' | bd363e0ee12a4c5bd714001c4b0498999fe3e235 | 22,131 |
def fix_tract(t):
"""Clean up census tract names.
:param t: Series of string tract names
:returns: Series of cleaned tract names
"""
if type(t) == str:
return t
return str(t).rstrip("0").rstrip(".") | e8e2f6bee61596c57bb805717e9a34eb88f1c91e | 22,132 |
def destructure(d, keys):
"""Custom object destructuring"""
return [d[k] if k in d else None for k in keys] | 5fdf0a4f732612005a5528b5f1c569fdb7d52927 | 22,134 |
def moving_avg_features(df):
"""
Function to calculate the exponential moving averages and moving averages over different intervals of days
Input: Dataframe
Output: Dataframe with new moving average features
"""
df['EMA_9'] = df['Close'].ewm(9).mean().shift()
df['EMA_9'] = df['EMA_9'].fillna(... | 820eb6b0ad42592393d50d93d5718a6a10562907 | 22,135 |
def _old_style_nesting(vocab):
"""Detect old-style nesting (``dict[str, List[Tuple[str, Field]]]``)."""
return isinstance(vocab, dict) and \
any(isinstance(v, list) for v in vocab.values()) | bce0ba4ee2fe7de4916f970c6f765b493ccdf0db | 22,136 |
def err_exception(line=""):
"""
list the exceptions even if there is an error in the line
"""
if "414" in line:
return True
if "ValueError" in line:
return True
if "TypeError" in line:
return True
if '503' in line:
# twitter service overloaded, try again later... | 18963c67e7ddc078dc8040e86b60edb7f66c3e2c | 22,137 |
from datetime import datetime
import re
def twitterTime(t):
"""Return Twitter's time format as isoformat."""
return datetime.strptime(re.sub('[+\-][0-9]{4}\s', '', t), '%a %b %d %X %Y').isoformat() | 63b5763edd01d78902c97d3a9c4d059e1fb76a23 | 22,138 |
import functools
def conditional_decorator(dec, condition, *args, **kwargs):
"""Apply arbitrary decorator to a function if condition is met
Parameters
----------
dec : decorator
Decorator to apply
condition : bool
condition that must be met for decorator to be applied
args : t... | c6854d6fb3d6fd37a5a36ddb0aaf40eadf1bbd22 | 22,139 |
from datetime import datetime
def convert_date(date_string):
"""Convert the date_string to dd-mm-YYYY format."""
date = datetime.strptime(date_string, "%d.%m.%Y")
return date.strftime('%d-%m-%Y') | 33a67ba33fed1f195812e9839a811411de1e2987 | 22,140 |
def metadata_default_dict_factory_fn():
"""Factory function that can be passed to defaultdict to provide default
values for
"""
return {'passing_sample_ids': set()} | 12aef48a549d87b97fb03424ace39aa53022abb4 | 22,141 |
def squeeze_whitespace(text):
"""Remove extra whitespace, newline and tab characters from text."""
return ' '.join(text.split()) | ef476f4ed6cd524c1cb115345151e4bc18c616b5 | 22,142 |
def iso_string_to_sql_date_sqlite(x: str) -> str:
"""
Provides SQLite SQL to convert a column to a ``DATE``, just by taking the
date fields (without any timezone conversion). The argument ``x`` is the
SQL expression to be converted (such as a column name).
"""
return f"DATE(SUBSTR({x}, 1, 10))" | 349c560589d4f03938538f74dbc188577ac63a2d | 22,143 |
from pathlib import Path
def save_NN_sequential(model, model_name):
"""
Saving a Neural Network as h5 file
:param model: sequential model
:param model_name: name to save the model
:return: True
"""
file_name = 'Model_' + model_name
file_path = Path().joinpath('Pickles', file_name + ".h... | a7481ace8971debb1be3af2140f6fdd33b3f679b | 22,144 |
def mask(x):
"""Turn a string into an equal-length string of asterisks"""
try:
return len(x) * '*'
except TypeError: # not a string - perhaps None - just return it as-is
return x | 4d17c3c5a7f8745353e01b84a9fe8b048bddd27d | 22,145 |
def get_second_validate_param(tel_num):
"""
Assemble param for get_second_validate
:param tel_num: Tel number
:return: Param in dict
"""
param_dict = dict()
param_dict['act'] = '1'
param_dict['source'] = 'wsyytpop'
param_dict['telno'] = tel_num
param_dict['password'] = ''
par... | efbd31c56e3fdd4cb0e75bcae92cf51d996aac5d | 22,146 |
def filter_text(text, letters):
"""Remove letters that are not in the dataset."""
all_letters = set(text)
letters_out = set(all_letters).difference(letters)
letters_out = letters_out.difference(" ")
for letter in letters_out:
text = text.replace(letter, "")
return text | 53c47499445508e1d3f2f6a4d60a789cefe38796 | 22,147 |
def nautobot_vlan_status(status: str) -> str:
"""Method to return VLAN Status from mapping."""
statuses = {
"Active": "ASSIGNED",
"Deprecated": "UNASSIGNED",
"Reserved": "RESERVED",
}
return statuses[status] | efbc87b350953e3ff4ce379f9299f59e741520f8 | 22,148 |
def typeless_equals(entity1, entity2, check_class, check_instance):
"""
Checks if entities are equal. The check is different whether
entities are classes or instances, which is specified in
corresponding parameters. If neither checks are specified,
True is returned
"""
if check_class:
... | a0f1360509d8f2f1191c158426fa29ec42d3a3c8 | 22,149 |
def node_name(node):
"""Return lxml node name without the namespace prefix."""
try:
return node.tag.split('}')[-1]
except AttributeError:
pass | 0e61ae70563784b5c845a73a82c3b2265ce63202 | 22,150 |
def get_most_read_or_features(
amb_sams: list,
counts: dict) -> list:
"""
Get the samples that have the most
counts (reads of features).
Parameters
----------
amb_sams : list
Sample IDs.
counts : dict
Count per Sample ID.
Returns
-------
cur_best... | 147a9e3a1df579f1673a832bf7dd3a7267ac4394 | 22,151 |
from typing import Counter
def can_rearrange_to_palindrom(string):
"""
Returns True if string can be rearranged to a palindrom
"""
occurrences = Counter(string)
return sum(count % 2 != 0 for count in occurrences.values()) < 2 | c562b7e14f93a964d55fc4c1ca903470fa44a95d | 22,153 |
def play_game(player_1: list, player_2: list, part_two: bool=False) -> tuple:
"""Play a game of (Recursive) Combat returning winner and their hand.
Args:
player_1: List of player one's card values.
player_2: List of player two's card values.
Return:
Tuple of winner's number (1/2) a... | 2b20970bd7f1d792ba195d2aab280aca0c3d7ccc | 22,154 |
def find_index_unsafe(val, bin_edges):
"""Find bin index of `val` within binning defined by `bin_edges`.
Validity of `val` and `bin_edges` is not checked.
Parameters
----------
val : scalar
Assumed to be within range of `bin_edges` (including lower and upper
bin edges)
bin_edge... | 08f89f8f6096d930e5d6c043374567d6646e9a37 | 22,156 |
from typing import Union
import json
def encode_message(message: Union[str, dict]) -> bytes:
"""
Кодирование сообщения
"""
if isinstance(message, str):
message = json.loads(message)
return json.dumps(message).encode() | 02ec60f1dc33424d736c58b681e489b0d607dadd | 22,157 |
import time
def func_to_time(x):
"""This is sleeps for x seconds for timing tests."""
time.sleep(x)
return 'Slept for {0} second(s)'.format(x) | 8698514f6efe4b7b58aab3da5687cb72c2083fd7 | 22,158 |
import os
import sys
import shlex
def get_original_command(max_width=80, full_python_path=False):
"""
Return the original command line string that can be replayed nicely and wrapped for 80 char width.
Args:
max_width (`int`, `optional`, defaults to 80):
The width to wrap for.
... | 57f680f223923df605111cd5a75e8845c16d6f87 | 22,159 |
def to_float_str(
val):
"""to_float_str
convert the float to a string with 2 decimal points of
precision
:param val: float to change to a 2-decimal string
"""
return str("%0.2f" % float(val)) | c15c4e43e788ab416170f21413906fc2d218b345 | 22,160 |
import time
import hashlib
def user2cookie(user, max_age, cookie_key):
"""
计算加密cookie
:param user:
:param max_age:
:param cookie_key:
:return:
"""
# build cookie string by: id-expires-sha1
expires = str(int(time.time() + max_age))
s = '%s-%s-%s-%s' % (user.id, user.password, ex... | 136d122c93c28f3b270af98f961099e118ab0380 | 22,161 |
def replicate_filter(compiled, replicate_threshold):
"""collect only those seen in threshold replicates"""
df = compiled.copy()
replicates = df.groupby('Sequence').count()['Proteins']
rep_sequences = replicates[replicates == replicate_threshold].reset_index()['Sequence']
return df[df['Sequence'].isi... | ded0c1936afb2a3ea616cfb05c7feeff52f36b95 | 22,162 |
def find_closest(val1, val2, target):
"""Contain get_closest value to a certain target."""
return val2 if target - val1 >= val2 - target else val1 | 62b2ee13b0c92d6445819a86d353b848def0239c | 22,164 |
def get_id():
"""
Returns the ID.
"""
return "*IDN?" | 65e63f1f4e53952264e58684d835bae3c4ee24a7 | 22,165 |
def limits2slice(limits):
"""
Create a set of slice objects given an array of min, max limits.
Parameters
----------
limits: tuple, (ndarray, ndarray)
Two tuple consisting of array of the minimum and maximum indices.
Returns
-------
slices : list
List of slice objects w... | f796f1e468f560d72e7d037e27a110ee50d3a45d | 22,166 |
def create_clip_xml_info(readlen, adapl, adapr, quall, qualr):
"""Takes the clip values of the read and formats them into XML
Corrects "wrong" values that might have resulted through
simplified calculations earlier in the process of conversion
(especially during splitting of paired-end reads)
"""
... | d57833595f61cf798bc40816a6097c747dc198db | 22,167 |
def has_clockwise_numbering(coords):
""" tests if a polygon has clockwise vertex numbering
approach: Sum over the edges, (x2 − x1)(y2 + y1). If the result is positive the curve is clockwise.
from:
https://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-o... | e9d55bfe9c5ef66e4b3e611c579c3ca940ba98d2 | 22,168 |
def convert_to_float(value: str) -> float:
"""
Get the float value from, for example, "R9 323.46".
"""
return float(value[1:].replace(' ', '')) | 5ebea176aa6cbfaf6318b246fda73ff443efd092 | 22,169 |
def sift(iterable, predicate):
"""
Sift an iterable into two lists, those which pass the predicate and those who don't.
:param iterable:
:param predicate:
:return: (True-list, False-list)
:rtype: tuple[list, list]
"""
t_list = []
f_list = []
for obj in iterable:
(t_list ... | 347ae7cd9f79bccdc6fc6ae1efa1a29b5563322a | 22,170 |
def compare_datetime(date, span):
"""
Compare information within datetime object with a span
Parameters
----------
date: datetime
Datetime to compare.
span: Span
Span to compare.
Returns
-------
bool
True if match.
"""
return span.text in str(date) | d2bd942d7b6c536ac35d1cd18b10ed57a465622a | 22,173 |
def reduce_list(data_set):
""" Reduce duplicate items in a list and preserve order """
seen = set()
return [item for item in data_set if
item not in seen and not seen.add(item)] | e84b87b45c8a7aea14beee3b7822f55a0a99151e | 22,174 |
def validate_knot(knot):
""" Confirm a knot is in the range [0, 1]
Parameters
----------
knot : float
Parameter to verify
Returns
-------
bool
Whether or not the knot is valid
"""
return (0.0 <= knot <= 1.0) | 61ab023d61248268db74febd72df6ecf3ef0c056 | 22,175 |
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
if len(array) == 0:
return 0
elif len(array) == 1:
return array[0] ** 2
return sum([x for i, x in enumerate(array) if i % 2 == 0]) * array[-1] | 7d712f406b959f95ccc97075296a720b2ec65d22 | 22,176 |
import subprocess
import click
import os
import shutil
def init():
"""Initialize minion aliases for git repository."""
# check if git repository
if subprocess.call(["git", "status"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) != 0:
click.echo("This is not a git repository!")
return 1
... | e203100a297380e9502b0704a67ca94497068fd4 | 22,177 |
def create_forwards_regex(input_symbol: str) -> str:
"""Creates a regular expression pattern to match the forwards symbology.
To create the regular expression, the function uses the fact that within the ICE
consolidated feed all the forwards contracts are identified by the root symbol (a
unique mnemoni... | 1404f4757675fc634ed3cecdfa4689c5b63020d2 | 22,179 |
def _get_all_deps(*, deps, split_deps_keys = []):
"""Returns a list of all dependencies from a Label list and optional split attribute keys.
Args:
deps: Label list of (split) dependencies to traverse.
split_deps_keys: (optional) List of split attribute keys to use on split deps.
Returns:
... | 30521b0ce646c3ee51b1d45d06e05aeb71058456 | 22,180 |
import csv
def ftt_lookup(organism, experiment=""):
"""Import the ftt file and process as a dictionary of lookup values
indexed on Synonym (i.e., Locus Tag)
{'VF_0001': {'locus': 'CP000020', 'start': ...},
'VF_0002': {'locus': 'CP000020', 'start': ...}}
"""
ftt_list = []
with open(
... | 4935ec6f3e749d9f84864e79cde73c48a4dfebab | 22,181 |
def get_time_string(codetime):
"""
Utility function that takes the codetime and
converts this to a human readable String.
Args:
codetime (`float`):
Code execution time in seconds (usually the difference of two time.time() calls)
Returns:
`str`: A string indicating the t... | 2cdc53ba83e06297c3c09b59095553db72d41643 | 22,184 |
def remove_duplicates(lst):
"""
This function removes all duplicate object from a list.
:param lst: A list.
:return: The same list, with all its elements appearing just once.
"""
if len(lst) == 1:
return lst
return [i for n, i in enumerate(lst) if i not in lst[:n]] | bf28a109a1af4760c39e31fdda88ea30b1e55f8a | 22,185 |
def aln_abuts_unknown_bases(tx, fasta):
"""
Do any exons in this alignment immediately touch Ns?
:param tx: a GenePredTranscript object
:param fasta: pyfasta Fasta object for genome
:return: boolean
"""
chrom = tx.chromosome
for exon in tx.exon_intervals:
if exon.start == 0: # ... | ceb31739be0091b3b52f763c0c0d6d15b1aebd19 | 22,188 |
import inspect
def typedtuple(*typesig):
"""Return a new function to generate an n-tuple with.
That works only if the entire type signature is identical when called.
>>> Somefoo = typedtuple([int, list, float, str])
>>> foo = Somefoo(3, [1, 2], 0.3, 'hello')
But this throws an error:
>>> fo... | 4bac75b2962b700baa147d08dcd65a51e6470840 | 22,189 |
import json
import hashlib
def get_md5(obj, trans_func=None):
"""get a object md5, if this obj is not supported by `json.dumps` please provide a trains_func.
Args:
obj (object): obj to get md5
trans_func (function, optional): use this to trans obj to str. Defaults to None.
"""
if tran... | ae7da1f0bab1815a2d357617dd93d26e020a2316 | 22,190 |
import re
def extract_courts(s: str) -> list:
"""
Extract a list of court numbers listed in the statute's text.
Args:
s (str): The text of the statute that lists the court numbers.
Returns:
(list): A list court numbers, all cleaned up.
"""
my_s = re.sub(r'[^0-9\s]', '', s)
... | d15e279ca2368d23fc75c7c2151329cfd60bb43a | 22,191 |
def _remove_trailing_zeros(lst):
"""
Removes any zeros at the end of the list.
"""
k=0
for k, value in enumerate( lst[::-1] ):
if value != 0:
break
lst_no_trailing_zeroes = lst if k == 0 else lst[:-k]
return lst_no_trailing_zeroes | 7b1d78716138eb25b635a962482b21d4fbb35284 | 22,192 |
def fa_attachment(extension):
"""
Add fontawesome icon if found. Else return normal extension as string.
:param extension: file extension
:return: matching fontawesome icon as string
"""
if extension == 'pdf':
return "<i class='fa fa-file-pdf-o fa-lg'></i>"
elif extension == 'jpg' o... | 3add6bf4c177cba893a2242df352fd0ae619ee90 | 22,194 |
def get_worksheet_keys(data_dict, result_info_key):
"""Gets sorted keys from the dict, ignoring result_info_key and 'meta' key
Args:
data_dict: dict to pull keys from
Returns:
list of keys in the dict other than the result_info_key
"""
keys = set(data_dict.keys())
keys.remove(re... | 1092eee46980a5e4f745d3a99ff6abe7d5c9db62 | 22,196 |
def add_options(click_options):
"""
Decorator that adds multiple Click options to the decorated function.
The list is reversed because of the way Click processes options.
Note: This function has its origins in the
https://github.com/pywbem/pywbemtools project (Apache 2.0 license)
Parameters:
... | fe6c5bda8f0606cc7fcdec87dd3332d1abb9b695 | 22,197 |
import itertools
def _expand(the_set, expand_fn):
"""Returns a concatenation of the expanded sets.
I.e.
Returns a set of all elements returned by the expand_fn function for all
elements in the_set.
E.g.
With expand_fn = lambda x: (10*x, 100*x) and the_set = set([1, 2, 3])
this function returns set([10... | 694661c0cc6d2d09d72d65ea63cc1241fc32d4d5 | 22,198 |
import re
def ingredients_from_food(food):
"""
Extract ingredients from food description
:param food: A string, value from the Food column
:return: A list of ingredients (strings) or empty list
"Салат "Папарать-Кветка"(Говядина,ветчина,помидоры,огурцы)" -> ["говядина", "ветчина", "помидоры", "огур... | 4314bce50e602f0e3c0d8db4d7c22ef2bd693c2a | 22,201 |
import json
def json_content(directory, file_name):
"""
This function gets the content of a json file and
returns as dictionary.
:param directory: String
The folder where the json file is located
:param file_name: String
The name of the jso... | 98cf97b4a1d6853cae9b4087fd02a1d316afb492 | 22,202 |
def check_login(db, usernick, password):
"""returns True if password matches stored"""
cur = db.cursor()
# retrieve user information from the database
rows = cur.execute("SELECT nick, password FROM users")
for item in rows:
if(item[0] == usernick and item[1] == db.crypt(password)): # if the... | e4f6d2dbb621699865c21276b6a42d23941aed39 | 22,203 |
import math
def rice_list(size=8, approx_ln=False):
"""return the list of rice number"""
approx_fn = (lambda x: x) if approx_ln else (lambda x: math.floor(math.log10(x) + 1))
lines = []
for y in range(8):
line = []
for x in range(8):
line.append(approx_fn(2**(x + 8*y)))... | 02051b05465cadec0d7af24a5077d300c37faf52 | 22,205 |
def index_dict(d: dict, x: float):
""" return a value from d for range x 0-1 the best range"""
keys = list(d.keys())
index = int(x * (len(keys) - 1))
return d[keys[index]] | 653324369bef1eb9873853c634d27d63ba0675e7 | 22,208 |
def get_cai_ptr(X):
"""
Function gets the pointer from an object that supports the
__cuda_array_interface__. Raises TypeError if `X` does not support it.
"""
if hasattr(X, '__cuda_array_interface__'):
return X.__cuda_array_interface__['data'][0]
else:
raise TypeError("X must supp... | 467e4437b34693e37f3f90e822899dc3a548710e | 22,209 |
def validate_float(s):
"""Convert s to float or raise a ValueError."""
try:
return float(s)
except ValueError:
raise ValueError('Could not convert {0!r} to float'.format(s)) | 1559e4b8465e4d380c74784f0dab68aaf7965dbc | 22,210 |
def show_element(elem):
""" Output whole a element as it is. """
return elem | bcb8d2ae273c105524a7518a2f4247a5aa48410f | 22,212 |
def exists_icd(db, icd):
"""
Search bar
MongoDB:
db.icd_info.find({'icd': 'RH141'}, fields={'_id': False})
SciDB:
aggregate(
filter(icd_info, icd = 'RH141'),
count(*));
SciDBnew:
res = db.get_phenotype_fields(association_set=str(db.list_association_sets()['name'][... | 664858d08bc64efaaa1bed797f1de59d63058747 | 22,213 |
import re
import warnings
def parse_psp_name(psp_name):
"""
Parse the name of vasp's psp
Parameter
psp_name: str
The name of vasp's psp, e.g. GGA, LDA, potpaw_LDA
Return
psp_name_norm: str
The normalized psp name
"""
psp_name = psp_name.upper()
psp_... | 0b5e025fa503f23fc17101690b978d414003197b | 22,214 |
def _csv_lst_convert(data_repr, csv_lst, var_name):
"""
csv convert list or dict
"""
# csv中list or dict转换
try:
col_val = csv_lst.strip()
if col_val != '':
tmp_eval = eval(csv_lst)
if isinstance(tmp_eval, list) or isinstance(tmp_eval, dict):
da... | 44adc7e04af67e251443421196bd04d39468d5ed | 22,215 |
def _format_list_items(list_items):
"""Generate an indented string out of a list of items."""
list_string = ''
if list_items:
for item in list_items:
list_string = list_string + " '" + item + "',\n"
list_string = "[\n {}\n]".format(list_string.strip()[:-1])
else:
... | dd677277650e5d3105c01f6636518b8bbd2a1bff | 22,216 |
import torch
import math
def importance_sampling_cross_validation(logp):
"""Compute the importance-sampling cross validation (ISCV) estimate.
The ISCV estimates the holdout log-likelihood from just an approximation to
the posterior predictive log-likelihoods on the training data.
### References:
... | 9bef3b3c3775e359d52a321a8e72b69d38f0fcb7 | 22,217 |
import re
def convert_character(text : str):
"""
Convert consecutive full-size numbers to half-size numbers.
Convert a single half-size number into a full-size number.
Convert half-size English characters to full-size ones.
Parameters
----------
text : str
input text
Retu... | f388de9eac9c92daceb96a46fce3efc525ce3eff | 22,218 |
def add_hover_description(df):
"""
Add the column 'text' with the numbers and description
shown on the app when selecting one postalcode area.
:return: the updated data frame
"""
list = []
for _, row in df.iterrows():
list.append('<b>' + str(row['Area']) + '</b><br>' +
... | 324efae5c1587d9b86407d1f0b33e7d0b8a23c83 | 22,223 |
import json
def others(request):
"""
Display others menu with activities to choose
:param request: POST request from "Others" dialogflow intent
:return: Json with others menu
"""
speech_text_pl = "Wybierz jedną z poniższych opcji, która Cię interesuje"
display_text_pl = "Która z poniższych... | 245546d7b0691b5ffb3ba1794e76cd974bfd67e8 | 22,225 |
def _create_html_file_content(translations):
"""Create html string out of translation dict.
Parameters
----------
tralnslations : dict
Dictionary of word translations.
Returns
-------
str:
html string of translation
"""
content = []
for i1, t in enumerate(transl... | 377fee1d5a45e9d6a1ae1c96a858f13f78b8c499 | 22,226 |
import time
def retry(func, exc=Exception, tries=3, delay=1):
"""
Call ``func()`` up to ``tries`` times, exiting only if the function
returns without an exception. If the function raises an exception on
the final try that exception is raised.
If given, ``exc`` can be either an `Exception` or a t... | 5384afd77840b77b2cb278502d8fc64890af6be7 | 22,227 |
def select_table_level_gmeta_fields(metabase_cur, data_table_id):
"""
Select metadata at data set and table levels.
"""
date_format_str = 'YYYY-MM-DD'
metabase_cur.execute(
"""
SELECT
file_table_name AS file_name,
format AS file_type,
... | ccc1bd9fd051125113b51f7da2e276722319ea99 | 22,228 |
def positionsDictionary():
"""
Creates a dictionary with corresponding names and their positions
Return Value: the ordered dictionary
"""
stats = open('volleyball_stats.csv', 'r', encoding="utf-8") #imports csv file
names = [] #creates empty lists
positions = []
line = stats.readli... | c42a9611b9474137b884f35701e4fc593862892a | 22,229 |
import json
def _get_entry_count(doi_file):
"""
Given a file path, will return the number of entries in that file. If the file reading files, returns None.
"""
try:
with open(doi_file) as f:
content = json.load(f)
return len(content)
except:
return None | fba5a3152811fbc01f4d91b72bdbe5659a65a152 | 22,230 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.