content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def one(iterable):
"""Return the single element in iterable.
Raise an error if there isn't exactly one element.
"""
item = None
iterator = iter(iterable)
try:
item = next(iterator)
except StopIteration:
raise ValueError('Iterable is empty, must contain one item')
try:
next(iterator)
except StopIteration... | 49cbb2e829bccaeb3ba5337b00c8bb19c2842b02 | 629,750 |
def GetDetailedHelpForAddIamPolicyBinding(collection,
example_id,
role='roles/editor',
use_an=False,
condition=False):
"""Returns a detailed_help for ... | 78d835b89535db5051d8d9a5bd40e31eee7873de | 629,752 |
def flatten(image, char):
"""
Given a layered image (typically (y, x, RGB)), return a plain 2D image
(y, x) according to a spec.
Args:
image (np.ndarray): The image to flatten
char (char): One of (R, G, B, or V (=value))
Returns:
np.ndarray - The 2D image.
"""
if im... | 6cc504876032ab78350d42d24d475302cfc2bb5f | 629,756 |
def get_translation_data(struct, key):
"""Returns translation data set by set_translation_data().
Args:
struct: type. A Struct class.
key: any object.
Raises:
KeyError: Translation data for the key is not defined.
"""
return struct._translation_data[key] | 4af9f908be917a6c13c563ddb62766728cb472e3 | 629,757 |
def guess_multi_value(value):
"""
Make the best kind of list from `value`. If it's already a list, or tuple,
do nothing. If it's a value with new lines, split. If it's a single value
without new lines, wrap in a list
"""
if isinstance(value, (tuple, list)):
return value
if isinstanc... | a742a9f37f84bbcc04f550fc3525a8df0fce43b9 | 629,759 |
def calc_us_in_name(name):
"""
calculate how many underscore is in name.
:param name: a string.
:return: a number
"""
cnt = 0
for ch in name:
if ch == '_':
cnt += 1
return cnt | 0c5f25de0718e615350a49176859a5b987276f84 | 629,760 |
import re
def process_text(text):
"""
This method is responsible for performing all pre-processing steps for the text.
It converts text to all lower case and performs some basic cleanup using regex.
"""
text = text.encode('ascii', errors='ignore').decode()
text = text.lower()
text = re.su... | a49fe0861b00f7e92612cc265c5c19dfd935ecb1 | 629,767 |
def read_gems(directory, file_name):
"""
Read a GEM file of the form "PlinePgem".
Args:
directory (str): directory of the file location (ex: '/Users/kimm/')
file_name (str): name of the file (ex: 'SHG0008H.Fragnum_PlinePgem')
Returns:
in_gems (list): tab-separated lists of lists
... | d583cc9f8d3b53fb42dd4e45f2d74531716e8ab5 | 629,769 |
def aggregate_count(items, col):
"""
Function to use on Group by Charts.
accepts a list and returns the count of the list's items
"""
return len(list(items)) | 4053079bc0c0623c549c178a65e4b5af9a8b7d09 | 629,771 |
def _replace_and_save(md, fns, replacing_fn):
"""
Replaces functions in `fns` list in `md` module with `replacing_fn`.
Returns the dictionary with functions that were replaced.
"""
saved = dict()
for check_f in fns:
try:
fn = getattr(md, check_f)
setattr(md, chec... | a57fdca4ffad6a3f5d4567e47e14d40cb59c7ea7 | 629,772 |
def as_list(val):
"""
Helper function, always returns a list of the input value.
:param val: the input value.
:returns: the input value as a list.
:Example:
>>> as_list('test')
['test']
>>> as_list(['test1', 'test2'])
['test1', 'test2']
"""
treat_single_value = str
i... | d696d22233c853d180e4eefba59be81e4e7f783f | 629,773 |
def quantize_dequantize(quantization, tensor):
"""Simple helper to quantize and dequantize."""
quantized_tensor, context = quantization.quantize(tensor)
dequantized_tensor = quantization.dequantize(quantized_tensor, context)
return quantized_tensor, dequantized_tensor, context | 435e14a99b61c4cdb88dc7927280e0322e880ffc | 629,776 |
import platform
def get_current_prefab_platform() -> str:
"""Get the name of the running platform.
Throws a RuntimeError on unsupported platforms.
"""
system = platform.system()
machine = platform.machine()
if system == 'Darwin':
# Currently there's just x86_64 on mac;
# will ... | b81158e0364a98f288f81c73c37878113719be43 | 629,779 |
import pytz
def GetUtcTime(dt, tz):
"""Converts from a local time to UTC using timezone translation.
The returned time does not have any timezone information. This allows
comparison with times coming from the datastore (which do not have timezone
either).
Args:
dt: A datetime.datetime instance with no... | c652ebf9a010173fedaa7a9d4771bf03f8764888 | 629,780 |
def concat_path(path, child):
"""Concat path with subfolder or file."""
newpath = path + "/" + child
return newpath | 1d31a4bc9e453377a05cc6f097142a103b3b11b2 | 629,785 |
def velocity(vo2):
"""
A regression equation relating VO2 with running velocity. Used in conjuction with the "vO2" equation to create the Jack Daniel's VDOT tables. Initially retrieved from "Oxygen Power: Performance Tables for Distance Runners" by Jack Daniels.
J., Daniels, and J. Daniels. Conditioning fo... | 7fb604ff63d7b54e943233a53c09e2b2851168b9 | 629,786 |
def GetTMIndex(iRes, posTM):# {{{
"""Get index of TM helix given a residue position
Return -1 if iRes is not within TM region
"""
for i in range(len(posTM)):
(b, e) = posTM[i]
if iRes >= b and iRes < e:
return i
return -1
# }}} | aded5661c6deea1b16d78f8ff0dbd3ab1f8a94d3 | 629,787 |
import re
def get_valid_filename(s: str) -> str:
"""Return a filename-compatible version of the given string s
:param s: String to be used as the base of the filename. You may also pass
non-string objects that will however be able to convert to strings via the
str operator.
>... | a4c72b6b84452b5552fcfb10f7e96c9518c69649 | 629,789 |
def cpu_processing_time(cycles: int, freq: float):
"""
:param cycles
:param freq: MHz
:return: seconds
"""
return (cycles / (freq * pow(10, 6))) * pow(10, 3) | 4b8fe7fd1b0f25b1cde270b129aa104b2a4652e2 | 629,790 |
def subList(l, sl) :
"""return the index of sl in l or None"""
lLen = len(l)
slLen = len(sl)
for i in range(lLen - slLen + 1):
j = 0
while j < slLen and l[i + j] == sl[j]:
j += 1
if j == slLen:
return i
return None | 520966384a538989b662e490e86991a95661cb90 | 629,795 |
import torch
def jitter_soma_depth(feats, scale=10):
""""
Apply jitter to soma depth.
Args:
feats: features per node
scale: scale factor of jittering
"""
new_feats = feats.copy()
new_feats[:, 1] += torch.randn(1).numpy() * scale
return new_feats | 188cb75555c330402c2b703ef9038de40eebd15c | 629,797 |
def translate_name(name):
"""
Convert names with underscores into camelcase.
For example:
"num_rows" => "numRows"
"very_long_json_name" => "veryLongJsonName"
"build_GBM_model" => "buildGbmModel"
"KEY" => "key"
"middle___underscores" => "middleUnderscores"
"_e... | 3c79e7530c28ef47e8b88960908ffa2310e462b7 | 629,798 |
def calc_rank(someset, n):
"""
Calculates the rank of a subset `someset` of {1, 2, ..., `n`}
in the ordering given by grey sequenccce of characteristic vectors.
"""
assoc_seq = [k + 1 in someset for k in range(n)]
bit = False
rank = 0
for k, x in enumerate(assoc_seq):
bit ^= x
rank += bit * 2**... | 4b3a7a226d90a5431d7622788e1d84ab406b40c3 | 629,799 |
def BuildFileName(url):
"""Construct the file name from a given URL.
Args:
url: the given URL
Returns:
filename: the constructed file name
"""
filename = url.strip('\r\n\t \\/')
filename = filename.replace('http://', '')
filename = filename.replace(':', '_')
filename = filename.replace('/', '_... | 89f06c884b708a17981a7ce3f439fb6a022a627b | 629,804 |
def _parse_suspected_cls(predator_result):
"""Parse raw suspected_cls into dict."""
if not predator_result:
return None
# The raw result contains some additional information that we don't need here.
# Everything we're concerned with is a part of the "result" object included
# with the response.
predato... | 0f4d72542fc138512d4bbfe3c997f8e9b940a96c | 629,806 |
import uuid
def get_uuid(key=None):
"""
生成UUID
:param key: 默认空 按照UUID-1方式生成,如果有值,者按照UUID-3规则生成。但是前提业务需保证key具有唯一性,如手机号
:return:
"""
'''
Python uuid 5种算法
1、uuid1()——基于时间戳
由MAC地址、当前时间戳、随机数生成。可以保证全球范围内的唯一性,
但MAC的使用同时带来安全性问题,局域网中可以使用IP来代替MAC。
2... | db29859cd123d2c852258420907c5958a3fd6e10 | 629,807 |
import re
def is_string_valid_source_package_name(pkgname: str) -> bool:
"""
Check if a package name is debian compliant
The source package name should be all in lower case, and can contain letters, digits, and dashes.
Some other characters are also allowed.
:param pkgname: string to check
:... | 3f0d4fa4d54fad4aac5a6df1a580497d7959a647 | 629,808 |
def _is_primitive(obj):
"""
Check if the given object is a primitive type
Args:
obj: the object to test
Returns:
True if the object is primitive i.e. hasn't a __dict__ attribute
"""
return not hasattr(obj, '__dict__') | b0ad6673f472d8e78d59ab9f7dd67eee557dbd8f | 629,811 |
def real_basename(path):
"""Python's os.path.basename is not basename."""
if path.rsplit('/', 1)[1] is '': return None
return path.rsplit('/', 1)[1] | 6d36a20dec3d5732c56edc33d3f5bbe232464ab5 | 629,812 |
import logging
def get_logger(name):
"""
Create new logger with the given name
:param name: Name of the logger
:return: Logger
"""
logger = logging.getLogger(name)
return logger | 80a7e545be7badd71277d38dbb202e70643f6ecb | 629,815 |
import re
import random
def choose(phenny, input):
""".choose <red> <blue> - for when you just can't decide"""
origterm = input.groups()[1]
if not origterm:
return phenny.say(".choose <red> <blue> - for when you just can't decide")
c = re.findall(r'([^, ]+)', origterm)
fate = random.choice... | e9432ea7fb89526ca33c299b493a0fb1ecdd365a | 629,818 |
import math
def complex_from_angle(phi, radius):
"""Return the complex number with argument 'phi' and absolute value 'radius'."""
return complex(math.cos(phi) * radius, math.sin(phi) * radius) | 153c961d9095fcbb91226cb8430071efd63ab205 | 629,821 |
async def get_all_entities(entities):
"""Get all entities on the same dict.
Watson API will return a list containing dictionaries for each,
entity found. On large numbers of entities it becomes hard to get
what we want, this function is meant to be an helper function to get
all the entities into a ... | 48256e4b519079106fe5bb165c64a27f3467d115 | 629,825 |
def let_user_choose(first, second, separator='|'):
"""
This function append both value (as string) inserting a separator inbetween.
:param first: First value.
:param second: Second value.
:param separator: Optional separator.
:return: first + separator + second.
>>> let_user_choose("first",... | 4aedc0a2c860071c515cfd2e676032a4f3317a69 | 629,830 |
def duration(t):
"""
Give a nice short and readable string representation of a given time
duration in seconds, e.g. how long it took to render the whole project.
Usage
-----
>>> timetag = duration(t)
Parameters
----------
The time that has passed in seconds (int or float).
... | f037a8b88d939e192dd16d25c1189f8e730f66b0 | 629,831 |
def get_es_result(mode, current, best_so_far):
"""Returns true if monitored metric has been improved"""
if mode == 'max':
return current > best_so_far
elif mode == 'min':
return current < best_so_far | e3183d571fb148776713989bcbdd12d5c57d57d7 | 629,832 |
import sympy
def is_multiplication_by_reciprocal(sympy_mul: sympy.Mul) -> bool:
"""Check if given sympy multiplication is of the form x * (1 / y)."""
args = sympy_mul.args
return len(args) == 2 and isinstance(args[1], sympy.Pow) and args[1].args[1] == -1 | 8bc7c11ca28ed681042747b0eff2b293e96a7e5d | 629,834 |
def get_param(gates, sweepgate):
""" Get qcodes parameter from scanjob argument """
if isinstance(sweepgate, str):
return getattr(gates, sweepgate)
else:
# assume the argument already is a parameter
return sweepgate | 50b08ef2fcbcad3bac5a1d392eac44fbdc451a18 | 629,838 |
def filter_selected(list_values, value):
"""
Check if a value exists in a list.
Parameters:
list_values = A non-empty list.
value = A value
Returns: True if the value exists in the list.
"""
return value in list_values | 0d0a707fc3b327a89cdc455b49a9aaf1b6090b2b | 629,839 |
def _filter(lst, func=None):
"""Filter a list according to a predicate.
Takes a sequence [o1,o2,..] and returns a list contains those which
are not `None` and satisfy the predicate `func(o)`
:param lst: Input iterable (not a dictionary)
:param func: Predicate function. If ``none``, this function a... | 1782b133459be053310067c98e23a0e92ee46f67 | 629,845 |
def next_month_id(monthid):
"""
Return a month id that is one month ahead of the input.
Argument:
monthid - a valid month id in the format of YYYYMM
"""
month = monthid % 100
year = monthid // 100
if month == 12:
year += 1
month = 1
else:
month += 1
... | 099c49aed1e0e97787b061f0746b706cd08d24eb | 629,846 |
def get_frame_index_int(image_file):
"""Returns an int-type index of the image file"""
return int(image_file.split('_')[-1].split('.')[0]) | c27fd9a1ee880b8edeb28671bd7a557128181f91 | 629,847 |
def find_free_game(games):
"""
finds the Free Game of the Day on MLB.TV
:param games: list of GameData() objects
:return: the free game's unique id: game_pk
"""
for game in games:
if game.free == 'ALL':
return game.game_pk | 3edfb6e3285e19af3a1319e6d8bcfafd241ceac5 | 629,852 |
def _base64_len(length):
"""Converts a length in 8 bit bytes to a length in 6 bits per byte base64 encoding"""
# Every 24 bits (3 bytes) becomes 32 bits (4 bytes, 6 bits encoded per byte)
# End is padded with '=' to make the result a multiple of 4
units, trailing = divmod(length, 3)
if trailing:
... | a3e0b182825413d2694c7dcb739c5569911a95a4 | 629,853 |
from typing import Union
from pathlib import Path
from typing import List
def get_files(path: Union[Path, str], extension='.wav') -> List[Path]:
""" Get all files from all subdirs with given extension. """
path = Path(path).expanduser().resolve()
return list(path.rglob(f'*{extension}')) | b7f1c8a7af34ecb90a00c5f126c6eba20e6a9ed4 | 629,857 |
def skipForLogfile(fragment, msg):
"""Return a decorator that skips the test for logfiles containing fragment."""
def testdecorator(testfunc):
def testwrapper(self, *args, **kwargs):
if fragment in self.logfile.filename:
self.skipTest(msg)
else:
te... | 97b6f30ae870cff635229e1276d0a8a51ade8dc5 | 629,859 |
from typing import List
from typing import Any
def flatten_list_of_lists(list_of_lists: List[List[Any]]) -> List[Any]:
"""Flattens a list of lists."""
output = []
for one_list in list_of_lists:
output += one_list
return output | 8b4dc6e38c50f510f210f804443a8a78f74894a9 | 629,861 |
import pathlib
def parse_requirements(filename):
"""Load requirements from a pip requirements file."""
with pathlib.Path(filename).open() as fp:
lines = (line.split('#')[0].strip() for line in fp)
return [line for line in lines if line and not line.startswith('--')] | d2104307736a3899591506e64cb372cc21a7ceae | 629,863 |
import typing
import itertools
def generate_permutations_with_replacement(width: int, seq_length: int) -> typing.List[typing.Tuple[int, ...]]:
"""
Generates a list containing all seq_length**width possible permutations
:param width: The length of each combination.
:param seq_length: The amount of eac... | 628b2c3553173098bd58d51421226f7db814f458 | 629,864 |
def coarse_pos_e(tags):
"""
Coarse POS tags of Treebank corpus: N: Noun, V: Verb, A: Adjective,
D: Adverb, Z: Pronoun, T: Determiner, E: Preposition, P: Postposition,
U: Number, J: Conjunction, O: Punctuation, R: Residual, L: Classifier,
I: Interjection
>>> coarse_pos_e(['Nasp---', 'pers', 'pro... | 93ac495c9f029108f07638abde797c98e31302a6 | 629,865 |
import inspect
def get_calling_frame_variables( call_depth ):
"""
Uses the inspect module to get hold of the calling frames leading to this
function, picks the frame 'call_depth' back (up the call stack), then
gets the local and global variables as they exist in the scope of that
caller function. ... | 2c16075cb7560618bf1f43fe23cd22dd2d22ef10 | 629,867 |
def error_response(error_message: str) -> dict:
"""
Form an error REST api response dict.
:param error_message: string error message
:return:
"""
return {
"success": False,
"error": error_message,
"data": None,
} | 43045e3c31a29e966da7f6f705d70c71a7af0cba | 629,868 |
def remaining_G9_12_cap(k12):
"""
Remaining enrollment capacity available at the school.
"""
return (k12['G9_12_cap'] - k12['G9_12']).clip(0) | 68d31e3b24ff3405b50cd53691be0f92baee0ba9 | 629,869 |
def _none_2_empty(text) -> str:
"""Translate None to empty string."""
if text is None:
return ""
return text | 1235492bf3e4a8879de1fd3767503d2cdc9ddcea | 629,873 |
def process_string(string: str) -> str:
"""Change escape sequences to the chars they match
ex: process_string("\\\\n") -> "\\n\""""
replacements = [
("\\\\", "\x00"),
("\\n", "\n"),
("\\t", "\t"),
("\\r", "\r"),
('\\"', '\"'),
("\\'", "'"),
("\x00", "\\"),
]
for search, replace in replacements:
str... | e7f2270be8126cb9484afd8e14668fc14e5288c4 | 629,874 |
def parse(query: str) -> str:
"""
Parse URL query into correct SQL syntax.
:param query: SQL query pulled from URL argument.
:return: Parsed query converted to valid SQL syntax.
"""
query_split = query.split("+")
return " ".join(query_split) | 2f7d990a3c06b632e4b7be2a4af9460bcf4838f8 | 629,876 |
def format_changes(changes):
"""
Format changes so it will look better.
ref on changeset:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets-view.html
"""
parts = []
for change in changes:
change_ = change["ResourceChange"]
l... | 7f4fac8b601411d637d02ec3a454129961b97e6f | 629,877 |
def _make_style_str(styledict):
"""
Make an SVG style string from the dictionary. See also _parse_style_str also.
"""
s = ''
for key in styledict.keys():
s += "%s:%s;"%(key, styledict[key])
return s | 48da4f00570c49ba2283fd1dbe8d08ae1b25ee41 | 629,879 |
def chem_pot_cols(chems):
"""Return columns corresponding to the chemical potential
:chems: str
:returns: list str
"""
return ["param_chem_pot({})".format(c) for c in chems] | 1728f0cff75d1cbb4f1134ad66707a835ee589bc | 629,886 |
def annotated_frames(scribbles_data):
""" Finds which frames have a scribble.
# Arguments
scribbles_data (dict): Scribble in the default format.
# Returns
list: Number of the frames that contain at least one scribble.
"""
scribbles = scribbles_data['scribbles']
frames_list = [i... | 9b3a08879110beb4c9d2b6d43f871c030e4abe9f | 629,887 |
def find_fusion_energy_per_reaction(reactants: str) -> float:
"""Finds the average fusion energy produced per fusion reaction in joules
from the fuel type.
Args:
reactants: the isotopes that are combined in the fusion even. Options
are "DD" or "DT"
Returns:
The average energy... | 8121802f096a027c885d7569149dafb4a6a70548 | 629,890 |
def window_bounds(i, n, wn):
"""Start and stop indices for a moving window.
Parameters
----------
i : int
Current index
n : int
Total number of points
wn : int, odd
Total window size
Returns
-------
start : int
Start index
stop : int
Stop... | 2a409322190b1ec362481a751e53ae6dbc2782f9 | 629,891 |
from typing import Optional
def linear_search(numbers: list[int], target: int) -> Optional[int]:
"""Search a target from the input using linear search algorithm
:param numbers: a collection with comparable items (not required to be sorted)
:param target: item value to search
:return: index of found i... | f082db3706a0f985bc551292334f31f027c9e8b1 | 629,893 |
def clipping(X, lo, hi):
"""
Helper function for clipping.
Args:
-- X: Pytorch tensor of shape (N, C, H, W)
-- lo: list, lower bound for each channel
-- hi: list, upper bound for each channel
Returns:
-- X: Pytorch tensor of shape (N, C, H, W)
"""
for c in range(3):
X.d... | d4cc5d381f1b4cdc63828fdb45e31ccc70702c01 | 629,894 |
def percentage(value):
"""Converts a fraction to a percentage."""
return '{:.0f}'.format(value * 100) | c4ae32eafec50f52b4021fc1a404295558a45d83 | 629,896 |
def first_where(L,val):
"""
First index of list L that equals val
"""
for pos,l in enumerate(L):
if l == val:
return pos
return None | d7a5257d24a5ad2d7c0dc4609c8f972668f1bc28 | 629,897 |
def join_anchor_base_score(anchor_df, base_df):
"""Join anchor DataFrame with Base LFCs on anchor_guide
Parameters
----------
anchor_df: DataFrame
DataFrame with anchor and target guides
base_df: DataFrame
Base LFC DataFrame
Returns
-------
DataFrame
"""
joined_... | 24a3ff90894f942c9ab07fe7e351999393ef9c5b | 629,898 |
def _IsSuccessfulDmlOrDdlJob(printable_job_info):
"""Returns True iff the job is successful and is a DML/DDL query job."""
return ('Affected Rows' in printable_job_info or
'DDL Operation Performed' in printable_job_info) | 6b03fb121213e35c7515c8d8e8c2c079dbe75f16 | 629,901 |
def merge_sort(items):
""" the merge sort algorithm takes in an unsorted list of numbers.
returns a list in ascending order.
Parameters
----------
items : list
list of unordered numbers
Returns
-------
list
list of elements in items in ascending order
"""
d... | d0c6f17378663c7feca8d217d08fdab37dfdcbb8 | 629,905 |
from tabulate import tabulate
def list_to_html(data, has_header=True, table_format=None):
"""
Convenience function to convert tables to html for attaching as message text.
:param data: Table data
:type data: list of lists
:param has_header: Flag whether data contains a header in the first row.
... | 3b136afb9703758dec30aa6f8a6dab74ef491d86 | 629,906 |
def seconds_to_minutes(seconds):
"""
Returns a number of seconds formatted as minutes:seconds.
"""
return '{}:{:0>2}'.format(int(seconds / 60), seconds % 60) | f1a237db1dc58f64c608504c341731cb77cdbc2a | 629,912 |
def has_no_e( word ):
"""Retruns True if the given word have no 'e', False otherwise.
"""
for i in word:
if i == 'e':
return False
return True | 41f44bd79119405b697406c08e036f6caf851d5b | 629,913 |
def get_materials_dict(lm):
"""Build the list of coordinates corresponding to each material"""
d = {}
for x in range(lm.nx):
for y in range(lm.ny):
mat = lm.cells[x][y].material.name.lower()
if mat in d:
d[mat].append((x,y))
else:
d... | 1ab43d42c5af23cc0a609ba9b4de1c76a6eb1df1 | 629,917 |
def return_index_name(collection_name, doc_type_str, sep="__"):
"""Return formatted index string"""
index_name = f"{collection_name}{sep}{doc_type_str}".lower()
return index_name | e1d5dd8bc1dbcf767a6b163899c20ae9b5545af1 | 629,919 |
def cTA(H, DIC, BT, TP, TSi, TS, TF, Ks, mode="multi"):
"""
Calculate Alkalinity. H is on Total scale.
Returns
-------
If mode == 'multi' returns TA, CAlk, PAlk, SiAlk, OH
else: returns TA
"""
# negative
Denom = H ** 2 + Ks.K1 * H + Ks.K1 * Ks.K2
CAlk = DIC * Ks.K1 * (H + 2 * Ks... | 3af5a082f2082274c43a70a224df7a999853eeb7 | 629,926 |
def process_somaticsniper_vcf(job, somaticsniper_vcf, work_dir, univ_options):
"""
Process the SomaticSniper vcf for accepted calls. Since the calls are pre-filtered, we just
obtain the file from the file store and return it.
:param toil.fileStore.FileID somaticsniper_vcf: fsID for a SomaticSniper gen... | 9273fbb330be8da05eb52ed281eed97528ed56f3 | 629,928 |
def _split_divisible(num, num_ways, divisible_by=8):
"""Evenly splits num, num_ways so each piece is a multiple of divisible_by."""
assert num % divisible_by == 0
assert num / num_ways >= divisible_by
# Note: want to round down, we adjust each split to match the total.
base = num // num_ways // divisible_by *... | bfa7dce06054325e50ecca644ad085a3eec1e0b3 | 629,933 |
def array_split(ary,n):
"""
>>> data = [1,2,3,4,5]
>>> array_split(data,3)
[[1, 2], [3, 4], [5]]
>>> grps = array_split(range(0,1121),8)
>>> total_len = 0
>>> for grp in grps: total_len += len(grp)
>>> assert(total_len == len(range(0,1121)))
"""
step = int(round(len(ary)/float(n)... | a36bb14778ba9b3ed8a2bd77990ad6baf0d14271 | 629,934 |
def objdict_to_dict(objdict):
""" Convert an objdict structure into a dict structure
Args:
obj (objdict): the objdict to convert
Returns:
dict: the objdict as standard dictionnary
"""
d = {}
if objdict:
for k, v in objdict.items():
if type(v) == dict:
... | 11e0cbe6e208e69742822fcf643a19975b431330 | 629,937 |
def type_check(name, correct_type):
"""
decorator function for checking correctness of input type
name: attribute name --> str
correct_type: correct_type of name attribute --> type
Procedure:
1. call type_check first,return prop setter,and convert name to private attribute. Store private_name &... | 7c04f60484e63aedebec6346cb4a10e676ae5514 | 629,941 |
def _str(uni):
"""
Make inbound a string
Encoding to utf-8 if needed
"""
try:
return str(uni)
except:
return uni.encode('utf-8') | e341073a69319b8f8ffb86bd13371d7b57921714 | 629,945 |
def create_query(keyword, start_date, end_date, max_results) -> dict:
"""
Creates the params part in the GET request
Parameters
----------
keyword : str
The key word/words that you want to be included in your search
start_date : str
The start of the time period that you would li... | 029aabdd2f972406237266edf2d7f5bad25bfc9d | 629,952 |
def clean_text(identifica, ementa, fulltext):
"""
Given a DOU article titles `identifica` and an abstract `ementa`,
remove the first title in `identifica`, `ementa` and the hard-coded
footnote from the full text of the DOU article `fulltext`.
"""
# ATTENTION: this code should reproduce the clea... | 06d3b3db514dfa9a410ba22d7c5585fb42752e16 | 629,954 |
def is_basestring(s):
"""Return True for any string type (for str/unicode on Py2 and bytes/str on Py3)."""
return isinstance(s, (str, bytes)) | f1fa4f9a755a47aadda35e788ce8f511b1d1412d | 629,956 |
def _hc2rgb1(h, c):
"""
Takes the hue and chroma and returns the helper rgb1.
Parameters
----------
h float The hue in degrees
c float The chroma in [0, 1]
"""
try:
h = float(h)
c = float(c)
except ValueError:
raise ValueError("h (%s) and c (%s) must be (convertible to) floats" %
(str(h), str(c)... | 62439e5cb6baee1673b2fb48b6f09a70bd8f894c | 629,957 |
def is_segment_tokenized(segment):
"""Return True, iff the segment is already tokenized.
Examples
--------
>>> s = ('<segment id="1"><sign pos="ART">Die</sign>'
... '<sign pos="NN">Antwort</sign></segment>')
>>> is_segment_tokenized(seg)
True
>>> seg = etree.fromstring('<segment i... | 62e1dd16945fb1fc5d0fa8754dc51373bca43640 | 629,962 |
def int_to_mask(mask_int):
""" Convert int to mask
Args:
mask_int ('int'): prefix length is convert to mask
Returns:
mask value
"""
bin_arr = ["0" for i in range(32)]
for i in range(int(mask_int)):
bin_arr[i] = "1"
tmpmask = ["".join(bin_arr[i * ... | fd1ae66b10552f163e9ab152c3679fb903a6ddd6 | 629,964 |
import torch
def _coordinate_grid(dims, align_corners=False):
"""
Creates a homogenous coordinate system.
Args:
dims (Tuple[int*]): height / width or depth / height / width
align_corners (bool):
returns a grid where the left and right corners assigned to the
extre... | dba819955dfce059077d1836dcf1255c8cdd5ea1 | 629,965 |
def str_to_orientation(value, reversed_horizontal=False, reversed_vertical=False):
"""Tries to interpret a string as an orientation value.
The following basic values are understood: ``left-right``, ``bottom-top``,
``right-left``, ``top-bottom``. Possible aliases are:
- ``horizontal``, ``horiz``, ``h... | 359e3fb09a70027160b942a13da0fc6686f059f9 | 629,966 |
def is_valid_pid(value: str) -> bool:
"""
Return if value is a valid pid (passport id).
Parameter
---------
value: str
a pid.
Return
------
bool
True if pid is valid, False othewise.
"""
return len(value) == 9 and all((char.isdigit()) for char in value) | acf8511922dc4efc73724f69c74edb0035066bcd | 629,971 |
def swap_columns(df, col1, col2):
"""Swaps the two given columns of the DataFrame."""
col_list = list(df.columns)
a, b = col_list.index(col1), col_list.index(col2)
col_list[b], col_list[a] = col_list[a], col_list[b]
return df[col_list] | 615f43515d52e4f6ff5f1851c54f4bd9ba6cabdb | 629,972 |
def is_value_1(for_):
"""check if for_["value"] == 1"""
v = for_.get("value", None)
return v == 1 | a707f0e9490dfcd890818a193b0f4d9a401172b7 | 629,973 |
def find_first_list_element_above(a_list, value):
"""
Simple method to return the index of the first element of a list that is greater than a specified value.
Args:
a_list: List of floats
value: The value that the element must be greater than
"""
if max(a_list) <= value:
Val... | 475b290bbd4b84d34528c69a6763c935af27d712 | 629,974 |
def scale(value):
"""Scale an value from 0-65535 (AnalogIn range) to 0-255 (RGB range)"""
return int(value / 65535 * 255) | 2c0601234648047b7ea28c691e5cfd8871aebea4 | 629,975 |
def date_to_iso8601(date):
"""Converts a date to an ISO 8601 date"""
return '%s-%02d-%02d' % (date.year, date.month, date.day) | 402ac680afaec9a1c9f163a737a838b61d1a9d25 | 629,976 |
def depth(data):
"""
Get the depth of a dictionary
Args:
data: data in dictionary type
Returns: the depth of a dictionary
"""
if isinstance(data, dict):
return 1 + (max(map(depth, data.values())) if data else 0)
return 0 | eee917ab77f35c10ca4f01cbc78f1bc8493fede7 | 629,977 |
import pickle
def load_obj(name: str):
"""Load object as a pickle file to a given path."""
with open(f'{name}.pkl', 'rb') as f:
return pickle.load(f) | dccb41bb9afcca9bf0ec455520d47dc2ff37d987 | 629,979 |
import time
def timeit(do=True, name=""):
"""
Decorator to print the time that the function has taken to execute.
"""
def inner0(function):
if not do: return function
def inner(*args, **kw):
start = time.time()
val = function(*args, **kw)
end = time.... | 77b44e5657d98cfb5f48c5a28025823983d7ff8f | 629,981 |
def gmail_timestamp_to_epoch_seconds(epoch_time_ms: int) -> int:
"""
Convert GMail `internalDate` into epoch time in seconds.
Arguments:
epoch_time_ms {int} -- the GMail `internalDate` epoch time which is in milliseconds.
Returns:
int -- epoch time in seconds
"""
epoch_time_sec... | d9a3bc4ab6ea41f4c627ae606ceaa19a0d2c5433 | 629,984 |
def derivative_polynomial_latitude(lon_norm, lat_norm, alt_norm, coeff):
"""
Compute latitude derivative polynomial equation
:param lon_norm: Normalized longitude position
:type lon_norm: float 64
:param lat_norm: Normalized latitude position
:type lat_norm: float 64
:param alt_norm: Normal... | de8c9811a882e39ce1a7d0c039d03ebead8de2a6 | 629,987 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.