content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def preprocess_img(img):
"""Preprocessing function for images."""
return img/255 | 11651a809288d5c3aa776b318099b7eb750d28ec | 6,292 |
def cdf(vals, reverse=False):
"""Computes the CDF of a list of values"""
vals = sorted(vals, reverse=reverse)
tot = float(len(vals))
x = []
y = []
for i, x2 in enumerate(vals):
x.append(x2)
y.append((i+1) / tot)
return x, y | 3cc64dcb8876f7620f02da873e29569e77477823 | 6,295 |
def check_for_solve(grid):
""" checks if grid is full / filled"""
for x in range(9):
for y in range(9):
if grid[x][y] == 0:
return False
return True | 5fc4a8e7a2efaa016065fc0736aa5bdb7d4c92f8 | 6,299 |
import copy
def _normalize_annotation(annotation, tag_index):
"""
Normalize the annotation anchorStart and anchorEnd,
in the sense that we start to count the position
from the beginning of the sentence
and not from the beginning of the disambiguated page.
:param annotation: Annotation object
:param tag_inde... | a7da5810711ada97a2ddcc308be244233fe813be | 6,301 |
import click
def parse_rangelist(rli):
"""Parse a range list into a list of integers"""
try:
mylist = []
for nidrange in rli.split(","):
startstr, sep, endstr = nidrange.partition("-")
start = int(startstr, 0)
if sep:
end = int(endstr, 0)
... | 321496a1170b81d02b8378d687d8ce6d6295bff6 | 6,303 |
def encode_label(text):
"""Encode text escapes for the static control and button labels
The ampersand (&) needs to be encoded as && for wx.StaticText
and wx.Button in order to keep it from signifying an accelerator.
"""
return text.replace("&", "&&") | b4402604f87f19dab9dbda4273798374ee1a38d8 | 6,306 |
from warnings import filterwarnings
def calcRSI(df):
"""
Calculates RSI indicator
Read about RSI: https://www.investopedia.com/terms/r/rsi.asp
Args:
df : pandas.DataFrame()
dataframe of historical ticker data
Returns:
pandas.DataFrame()
dataframe of calcula... | 4c2c76159473bf8b23e24cb02af00841977c7cd3 | 6,307 |
def question_input (user_decision=None):
"""Obtains input from user on whether they want to scan barcodes or not.
Parameters
----------
user_decision: default is None, if passed in, will not ask user for input. string type.
Returns
-------
True if user input was 'yes'
False is... | afb7f3d4eef0795ad8c4ff7878e1469e07ec1875 | 6,310 |
def remove_whitespace(sentences):
"""
Clear out spaces and newlines
from the list of list of strings.
Arguments:
----------
sentences : list<list<str>>
Returns:
--------
list<list<str>> : same strings as input,
without spaces or newlines.
"""
return [[w.... | ed50124aec20feba037ea775490ede14457d6943 | 6,313 |
import traceback
def get_err_str(exception, message, trace=True):
"""Return an error string containing a message and exception details.
Args:
exception (obj): the exception object caught.
message (str): the base error message.
trace (bool): whether the traceback is included (default=T... | 0ede3de80fb1097b0537f90337cf11ffa1edecf7 | 6,316 |
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | 685ff34e14c26fcc408e5d4f9219483118bfd3c0 | 6,317 |
from typing import Any
def check_int(data: Any) -> int:
"""Check if data is `int` and return it."""
if not isinstance(data, int):
raise TypeError(data)
return data | 814155f2407cd0e8b580372679f4cecfcc087d9e | 6,319 |
def getFirstValid(opts, default):
"""Returns the first valid entry from `opts`, or `default` if none found.
Valid is defined as ``if o`` returns true."""
for o in opts:
if o: return o
return default | 799a6ea4a993f0a112fa38b882566d72a0d223e0 | 6,320 |
def check_string_is_nonempty(string, string_type='string'):
"""Ensures input is a string of non-zero length"""
if string is None or \
(not isinstance(string, str)) or \
len(string) < 1:
raise ValueError('name of the {} must not be empty!'
''.format(string_type))... | 527e60b35f6a827ee9b1eae3c9a3f7abc596b7ff | 6,322 |
import hashlib
def md5(filename):
"""Hash function for files to be uploaded to Fl33t"""
md5hash = hashlib.md5()
with open(filename, "rb") as filehandle:
for chunk in iter(lambda: filehandle.read(4096), b""):
md5hash.update(chunk)
return md5hash.hexdigest() | 35068abafee2c5c4b1ac672f603b0e720a8c9a8c | 6,326 |
def dustSurfaceDensitySingle(R, Rin, Sig0, p):
"""
Calculates the dust surface density (Sigma d) from single power law.
"""
return Sig0 * pow(R / Rin, -p) | 441466f163a7b968cf193e503d43a1b014be7c5d | 6,327 |
def compute_edits(old, new):
"""Compute the in-place edits needed to convert from old to new
Returns a list ``[(index_1,change_1), (index_2,change_2)...]``
where ``index_i`` is an offset into old, and ``change_1`` is the
new bytes to replace.
For example, calling ``compute_edits("abcdef", "qbcdzw"... | f729addf84207f526e27d67932bb5300ced24b54 | 6,328 |
def get_sec (hdr,key='BIASSEC') :
"""
Returns the numpy range for a FITS section based on a FITS header entry using the standard format
{key} = '[{col1}:{col2},{row1}:row2}]'
where 1 <= col <= NAXIS1, 1 <= row <= NAXIS2.
"""
if key in hdr :
s = hdr.get(key) # WITHOUT CARD COMMENT
ny = hdr['NAXIS2']
sx = ... | 3927e6f5d62818079fa9475976f04dda1824e976 | 6,338 |
def string_to_gast(node):
"""
handles primitive string base case
example: "hello"
exampleIn: Str(s='hello')
exampleOut: {'type': 'str', 'value': 'hello'}
"""
return {"type": "str", "value": node.s} | a3dcd89e893c6edd4a9ba6095cd107bb48cc9782 | 6,341 |
def estimate_operating_empty_mass(mtom, fuse_length, fuse_width, wing_area,
wing_span, TURBOPROP):
""" The function estimates the operating empty mass (OEM)
Source: Raymer, D.P. "Aircraft design: a conceptual approach"
AIAA educational Series, Fourth edition (2006)... | 5b9bed8cef76f3c10fed911087727f0164cffab2 | 6,342 |
def box_strings(*strings: str, width: int = 80) -> str:
"""Centre-align and visually box some strings.
Args:
*strings (str): Strings to box. Each string will be printed on its own
line. You need to ensure the strings are short enough to fit in the
box (width-6) or the results wi... | b47aaf020cf121b54d2b588bdec3067a3b83fd27 | 6,345 |
def buildDictionary(message):
"""
counts the occurrence of every symbol in the message and store it in a python dictionary
parameter:
message: input message string
return:
python dictionary, key = symbol, value = occurrence
"""
_dict = dict()
for c in message:
if ... | 71b196aaccfb47606ac12242585af4ea2554a983 | 6,348 |
import six
def logger_has_handlers(logger):
"""
Check if given logger has at least 1 handler associated, return a boolean value.
Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself.
"""
if six.PY3:
return logger.hasHandlers()
else:
c =... | dc0093dd25a41c997ca92759ccb9fa17ad265bdd | 6,350 |
def add_lists(list1, list2):
"""
Add corresponding values of two lists together. The lists should have the same number of elements.
Parameters
----------
list1: list
the first list to add
list2: list
the second list to add
Return
----------
output: list
... | e4efbc079a981caa4bcbff4452c8845a7e534195 | 6,352 |
def read_file(filename):
"""
read filename and return its content
"""
in_fp = open(filename)
content = in_fp.read()
in_fp.close()
return content | c707a412b6099591daec3e70e9e2305fee6511f9 | 6,354 |
import torch
def l1_loss(pre, gt):
""" L1 loss
"""
return torch.nn.functional.l1_loss(pre, gt) | c552224b3a48f9cde201db9d0b2ee08cd6335861 | 6,358 |
def get_image_unixtime2(ibs, gid_list):
""" alias for get_image_unixtime_asfloat """
return ibs.get_image_unixtime_asfloat(gid_list) | 2c5fb29359d7a1128fab693d8321d48c8dda782b | 6,361 |
def wrap_arr(arr, wrapLow=-90.0, wrapHigh=90.0):
"""Wrap the values in an array (e.g., angles)."""
rng = wrapHigh - wrapLow
arr = ((arr-wrapLow) % rng) + wrapLow
return arr | e07e8916ec060aa327c9c112a2e5232b9155186b | 6,364 |
def largest_negative_number(seq_seq):
"""
Returns the largest NEGATIVE number in the given sequence of
sequences of numbers. Returns None if there are no negative numbers
in the sequence of sequences.
For example, if the given argument is:
[(30, -5, 8, -20),
(100, -2.6, 88, -40, -... | b7326b3101d29fcc0b8f5921eede18a748af71b7 | 6,365 |
def dump_cups_with_first(cups: list[int]) -> str:
"""Dump list of cups with highlighting the first one
:param cups: list of digits
:return: list of cups in string format
"""
dump_cup = lambda i, cup: f'({cup})' if i == 0 else f' {cup} '
ret_val = ''.join([dump_cup(i, cup) for i, cup in enumerat... | 5fe4111f09044c6afc0fbd0870c2b5d548bd3c1a | 6,368 |
def init(strKernel, iKernelPar=1, iALDth=1e-4, iMaxDict=1e3):
"""
Function initializes krls dictionary. |br|
Args:
strKernel (string): Type of the kernel
iKernelPar (float): Kernel parameter [default = 1]
iALDth (float): ALD threshold [default = 1e-4]
iMaxDict (int): Max... | 652e0c498b4341e74bcd30ca7119163345c7f2cc | 6,369 |
from typing import Iterable
def prodi(items: Iterable[float]) -> float:
"""Imperative product
>>> prodi( [1,2,3,4,5,6,7] )
5040
"""
p: float = 1
for n in items:
p *= n
return p | 3b8e52f40a760939d5b291ae97c4d7134a5ab450 | 6,372 |
def hexString(s):
"""
Output s' bytes in HEX
s -- string
return -- string with hex value
"""
return ":".join("{:02x}".format(ord(c)) for c in s) | 22c1e94f0d54ca3d430e0342aa5b714f28a5815b | 6,373 |
from typing import List
def normalize_resource_paths(resource_paths: List[str]) -> List[str]:
"""
Takes a list of resource relative paths and normalizes to lowercase
and with the "ed-fi" namespace prefix removed.
Parameters
----------
resource_paths : List[str]
The list of resource re... | ec7e5020ae180cbbdc5b35519106c0cd0697a252 | 6,374 |
def rangify(values):
"""
Given a list of integers, returns a list of tuples of ranges (interger pairs).
:param values:
:return:
"""
previous = None
start = None
ranges = []
for r in values:
if previous is None:
previous = r
start = r
elif r ==... | 672b30d4a4ce98d2203b84db65ccebd53d1f73f5 | 6,376 |
def get_scaling_desired_nodes(sg):
"""
Returns the numb of desired nodes the scaling group will have in the future
"""
return sg.get_state()["desired_capacity"] | 5a417f34d89c357e12d760b28243714a50a96f02 | 6,379 |
def notas(* valores, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param valores: uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando se deve ou não adicionar a situação
:return: dicionário com várias informações sobre a situação da turma... | a6915e9b7b1feef0db2be6fdf97b6f236d73f282 | 6,381 |
def is_private(name):
"""Check whether a Python object is private based on its name."""
return name.startswith("_") | d04dfd84884bbc8c8be179c6bc5fc1371f426a78 | 6,385 |
def count_ents(phrase):
"""
Counts the number of Named Entities in a spaCy Doc/Span object.
:param phrase: the Doc/Span object from which to remove Named Entities.
:return: The number of Named Entities identified in the input object.
"""
named_entities = list(phrase.ents)
return len(named_en... | 7e592442ebaf504320a903c4084454ff73896595 | 6,388 |
def sample(x, n):
"""
Get n number of rows as a sample
"""
# import random
# print(random.sample(list(x.index), n))
return x.iloc[list(range(n))] | 3802f976f2a97a08945d8246093784c06fb07e67 | 6,394 |
from typing import Any
def is_none_or_empty(obj: Any) -> bool:
"""Determine if object is None or empty
:param obj: object
:return: if object is None or empty
"""
return obj is None or len(obj) == 0 | a90245326e4c776ca1ee0066e965a4f656a20014 | 6,397 |
def reshape2D(x):
"""
Reshapes x from (batch, channels, H, W) to (batch, channels, H * W)
"""
return x.view(x.size(0), x.size(1), -1) | 29851e54bb816fb45184d3ea20e28d786270f662 | 6,398 |
def add_to_group(ctx, user, group):
"""Adds a user into a group.
Returns ``True`` if is just added (not already was there).
:rtype: bool
"""
result = ctx.sudo(f'adduser {user} {group}').stdout.strip()
return 'Adding' in result | abb7b432f4e4206a3509d1376adca4babb02e9f0 | 6,400 |
import torch
def load_ckp(model, ckp_path, device, parallel=False, strict=True):
"""Load checkpoint
Args:
ckp_path (str): path to checkpoint
Returns:
int, int: current epoch, current iteration
"""
ckp = torch.load(ckp_path, map_location=device)
if parallel:
model.modu... | 4fe4e368d624583216add3eca62293d5d1539182 | 6,402 |
def dump_adcs(adcs, drvname='ina219', interface=2):
"""Dump xml formatted INA219 adcs for servod.
Args:
adcs: array of adc elements. Each array element is a tuple consisting of:
slv: int representing the i2c slave address plus optional channel if ADC
(INA3221 only) has multiple channels. ... | b9c0aec3e6098a5de28a467910f4861e8860d723 | 6,408 |
def is_isbn_or_key(q):
"""
判断搜索关键字是isbn还是key
:param q:
:return:
"""
# isbn13 13位0-9数字;isbn10 10位0-9数字,中间含有 '-'
isbn_or_key = 'key'
if len(q) == 13 and q.isdigit():
isbn_or_key = 'isbn'
if '-' in q:
short_q = q.replace('-', '')
if len(short_q) == 10 and short_q... | cf35f13e8188741bd37715a1ed91cf40667cff40 | 6,409 |
def get_upright_box(waymo_box):
"""Convert waymo box to upright box format and return the convered box."""
xmin = waymo_box.center_x - waymo_box.length / 2
# xmax = waymo_box.center_x+waymo_box.length/2
ymin = waymo_box.center_y - waymo_box.width / 2
# ymax = waymo_box.center_y+waymo_box.width/2
... | 2c301e3d60078ba416446dfe133fb9802c96f09c | 6,410 |
def update_two_contribution_score(click_time_one, click_time_two):
"""
user cf user contribution score update v2
:param click_time_one: different user action time to the same item
:param click_time_two: time two
:return: contribution score
"""
delta_time = abs(click_time_two - click_time_one... | df959e4581f84be5e0dffd5c35ebe70b97a78383 | 6,411 |
def fix_text_note(text):
"""Wrap CHS document text."""
if not text:
return ""
else:
return """* CHS "Chicago Streets" Document:\n> «{}»""".format(text) | 56cbcbad7e8b3eee6bb527a240ad96701c4eea2f | 6,412 |
def is_block_comment(line):
""" Entering/exiting a block comment """
line = line.strip()
if line == '"""' or (line.startswith('"""') and not line.endswith('"""')):
return True
if line == "'''" or (line.startswith("'''") and not line.endswith("'''")):
return True
return False | ea38c248964eeaec1eab928182022de6ecccad69 | 6,415 |
from typing import List
from typing import Dict
import requests
def get_airtable_data(url: str, token: str) -> List[Dict[str, str]]:
"""
Fetch all data from airtable.
Returns a list of records where record is an array like
{'my-key': 'George W. Bush', 'my-value': 'Male'}
"""
response = re... | f91326938a663ddedd8b4a10f796c7c36981da4e | 6,416 |
def displayname(user):
"""Returns the best display name for the user"""
return user.first_name or user.email | aecebc897803a195b08cdfb46dbeb4c9df9ede09 | 6,417 |
import shlex
def shell_quote(*args: str) -> str:
"""
Takes command line arguments as positional args, and properly quotes each argument to make it safe to
pass on the command line. Outputs a string containing all passed arguments properly quoted.
Uses :func:`shlex.join` on Python 3.8+, and a for ... | b2d0ecde5a2569e46676fed81ed3ae034fb8d36c | 6,419 |
import torch
def normalized_state_to_tensor(state, building):
"""
Transforms a state dict to a pytorch tensor.
The function ensures the correct ordering of the elements according to the list building.global_state_variables.
It expects a **normalized** state as input.
"""
ten = [[ state[sval] ... | 4aea246f388f941290d2e4aeb6da16f91e210caa | 6,420 |
def disabled_payments_notice(context, addon=None):
"""
If payments are disabled, we show a friendly message urging the developer
to make his/her app free.
"""
addon = context.get('addon', addon)
return {'request': context.get('request'), 'addon': addon} | b77dc41cf8ac656b2891f82328a04c1fe7aae49c | 6,422 |
def construct_futures_symbols(
symbol, start_year=2010, end_year=2014
):
"""
Constructs a list of futures contract codes
for a particular symbol and timeframe.
"""
futures = []
# March, June, September and
# December delivery codes
months = 'HMUZ'
for y in range(start_... | 2917a9eb008f5ab141576243bddf4769decfd1f3 | 6,423 |
from typing import Dict
from typing import Any
def merge_dicts(dict1: Dict[str, Any],
dict2: Dict[str, Any],
*dicts: Dict[str, Any]) -> Dict[str, Any]:
"""
Merge multiple dictionaries, producing a merged result without modifying
the arguments.
:param dict1: the firs... | 869399774cc07801e5fa95d9903e6a9f2dadfc25 | 6,428 |
def get_total_obs_num_samples(obs_length=None,
num_blocks=None,
length_mode='obs_length',
num_antennas=1,
sample_rate=3e9,
block_size=134217728,
... | 0d5c3de03723c79d31c7f77ece29226daaf4f442 | 6,437 |
def get_page_index(obj, amongst_live_pages=True):
"""
Get oage's index (a number) within its siblings.
:param obj:
Wagtail page object
:param amongst_live_pages:
Get index amongst live pages if True or all pages if False.
:return:
Index of a page if found or None if page d... | fd1950533a398019ab0d3e208a1587f86b134a13 | 6,441 |
import math
def plagdet_score(rec, prec, gran):
"""Combines recall, precision, and granularity to a allow for ranking."""
if (rec == 0 and prec == 0) or prec < 0 or rec < 0 or gran < 1:
return 0
return ((2 * rec * prec) / (rec + prec)) / math.log(1 + gran, 2) | f8debf876d55296c3945d0d41c7701588a1869b6 | 6,446 |
def get_matrix_header(filename):
"""
Returns the entries, rows, and cols of a matrix market file.
"""
with open(filename) as f:
entries = 0
rows = 0
cols = 0
for line in f.readlines():
if line.startswith('%'):
continue
line = line.s... | 66200661715cb9a67522ced7b13d4140a3905c28 | 6,447 |
def get_satellite_params(platform=None):
"""
Helper function to generate Landsat or Sentinel query information
for quick use during NRT cube creation or sync only.
Parameters
----------
platform: str
Name of a satellite platform, Landsat or Sentinel only.
params
"""
... | 2298c100eed431a48a9531bc3038c5ab8565025d | 6,451 |
def list_agg(object_list, func):
"""Aggregation function for a list of objects."""
ret = []
for elm in object_list:
ret.append(func(elm))
return ret | b2d8eef9c795e4700d111a3949922df940435809 | 6,459 |
def all_children(wid):
"""Return all children of a widget."""
_list = wid.winfo_children()
for item in _list:
if item.winfo_children():
_list.extend(item.winfo_children())
return _list | ca52791b06db6f2dd1aeedc3656ecf08cb7de6d8 | 6,466 |
def _mgSeqIdToTaxonId(seqId):
"""
Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId")
@param seqId: sequence id used in mg databases
@return: taxonId
@rtype: int
"""
return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[... | 2ce74f453e3496c043a69b4205f258f06bfd0452 | 6,471 |
def url_to_filename(url):
"""Converts a URL to a valid filename."""
return url.replace('/', '_') | db3023c582590a47a6adc32501a2e3f5fd72f24f | 6,472 |
def get_params_out_of_range(
params: list, lower_params: list, upper_params: list
) -> list:
"""
Check if any parameter specified by the user is out of the range that was defined
:param params: List of parameters read from the .inp file
:param lower_params: List of lower bounds provided by the user... | 67a8ca57a29da8b431ae26f863ff8ede58f41a34 | 6,483 |
def limit(value, limits):
"""
:param <float> value: value to limit
:param <list>/<tuple> limits: (min, max) limits to which restrict the value
:return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to t... | 55fb603edb478a26b238d7c90084e9c17c3113b8 | 6,485 |
def _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices):
"""Filter substructure match atom indices by atom map indices corresponding to
atom map numbers.
"""
if AtomMapIndices is None:
return list(AtomIndices)
... | 3594a11452848c9ae11f770fa560fe29d68aa418 | 6,490 |
from typing import Any
from typing import Set
import inspect
from unittest.mock import Mock
def _get_default_arguments(obj: Any) -> Set[str]:
"""Get the names of the default arguments on an object
The default arguments are determined by comparing the object to one constructed
from the object's class's in... | 483fe82dd79aadfe1da387fb0c602beb503f344b | 6,493 |
import csv
def main(file_in, file_out):
"""
Read in lines, flatten list of lines to list of words,
sort and tally words, write out tallies.
"""
with open(file_in, 'r') as f_in:
word_lists = [line.split() for line in f_in]
# Flatten the list
# http://stackoverflow.com/questions/95... | 225dd5d5b4c2bcb158ee61aa859f78e1e608a5fe | 6,500 |
def load_atomic(val):
"""
Load a std::atomic<T>'s value.
"""
valty = val.type.template_argument(0)
# XXX This assumes std::atomic<T> has the same layout as a raw T.
return val.address.reinterpret_cast(valty.pointer()).dereference() | 307bcc9d3eae2eede6a8e2275104280a1e7b4b94 | 6,501 |
def dataId_to_dict(dataId):
""" Parse an LSST dataId to a dictionary.
Args:
dataId (dataId): The LSST dataId object.
Returns:
dict: The dictionary version of the dataId.
"""
return dataId.to_simple().dict()["dataId"] | 77b7566492b80a8c6e2becacafff36737c8a7256 | 6,502 |
def _get_exploration_memcache_key(exploration_id):
"""Returns a memcache key for an exploration."""
return 'exploration:%s' % exploration_id | 1400607cc86f84c242201c9c9fe36a7a06cd2357 | 6,505 |
def pairs_from_array(a):
"""
Given an array of strings, create a list of pairs of elements from the array
Creates all possible combinations without symmetry (given pair [a,b], it does not create [b,a])
nor repetition (e.g. [a,a])
:param a: Array of strings
:return: list of pairs of strings
"""
pairs = l... | 50c489d660a7e82c18baf4800e599b8a3cd083f0 | 6,507 |
from typing import Any
def complex_key(c: complex) -> Any:
"""Defines a sorting order for complex numbers."""
return c.real != int(c.real), c.real, c.imag | 55c17b0d4adf8bcfb39b50c66d5bd8133f5bb814 | 6,510 |
def get_campaign_goal(campaign, goal_identifier):
"""Returns goal from given campaign and Goal_identifier.
Args:
campaign (dict): The running campaign
goal_identifier (string): Goal identifier
Returns:
dict: Goal corresponding to goal_identifer in respective campaign
"""
i... | 1a8738416ee8187ad2a6a977b36b68f66052bfe8 | 6,511 |
def _unsigned16(data, littleEndian=False):
"""return a 16-bit unsigned integer with selectable Endian"""
assert len(data) >= 2
if littleEndian:
b0 = data[1]
b1 = data[0]
else:
b0 = data[0]
b1 = data[1]
val = (b0 << 8) + b1
return val | 22feb074aca7f4ab7d489eacb573c3653cad9272 | 6,515 |
def calculate_term_frequencies(tokens):
"""Given a series of `tokens`, produces a sorted list of tuples in the
format of (term frequency, token).
"""
frequency_dict = {}
for token in tokens:
frequency_dict.setdefault(token, 0)
frequency_dict[token] += 1
tf = []
for token... | b764175cd59fe25c4a87576faee2a76273097c5e | 6,516 |
import math
def _rescale_read_counts_if_necessary(n_ref_reads, n_total_reads,
max_allowed_reads):
"""Ensures that n_total_reads <= max_allowed_reads, rescaling if necessary.
This function ensures that n_total_reads <= max_allowed_reads. If
n_total_reads is <= max_allowed_r... | d09b343cee12f77fa06ab467335a194cf69cccb4 | 6,521 |
def load_dict(path):
""" Load a dictionary and a corresponding reverse dictionary from the given file
where line number (0-indexed) is key and line string is value. """
retdict = list()
rev_retdict = dict()
with open(path) as fin:
for idx, line in enumerate(fin):
text = line.stri... | 31a67c2a28518a3632a47ced2889150c2ce98a78 | 6,525 |
def get_square(array, size, y, x, position=False, force=False, verbose=True):
"""
Return an square subframe from a 2d array or image.
Parameters
----------
array : 2d array_like
Input frame.
size : int
Size of the subframe.
y : int
Y coordinate of the center of the s... | 8d83d4d16241e118bbb65593c14f9f9d5ae0834c | 6,530 |
import json
def read_json(json_file):
""" Read input JSON file and return the dict. """
json_data = None
with open(json_file, 'rt') as json_fh:
json_data = json.load(json_fh)
return json_data | 4e1ea153d040ec0c3478c2d1d3136eb3c48bfe1c | 6,531 |
def alt_or_ref(record, samples: list):
"""
takes in a single record in a vcf file and returns the sample names divided into two lists:
ones that have the reference snp state and ones that have the alternative snp state
Parameters
----------
record
the record supplied by the vcf reader
... | abaccfeef02ee625d103da88b23fce82a40bc04c | 6,534 |
def is_const_component(record_component):
"""Determines whether a group or dataset in the HDF5 file is constant.
Parameters
----------
record_component : h5py.Group or h5py.Dataset
Returns
-------
bool
True if constant, False otherwise
References
----------
.. https://... | 4adb2ff7f6fb04086b70186a32a4589ae9161bb5 | 6,535 |
def compat(data):
"""
Check data type, transform to string if needed.
Args:
data: The data.
Returns:
The data as a string, trimmed.
"""
if not isinstance(data, str):
data = data.decode()
return data.rstrip() | 51d2d37b427e77b038d8f18bebd22efa4b4fdcce | 6,541 |
def rsa_decrypt(cipher: int, d: int, n: int) -> int:
"""
decrypt ciphers with the rsa cryptosystem
:param cipher: the ciphertext
:param d: your private key
:param n: your public key (n)
:return: the plaintext
"""
return pow(cipher, d, n) | 33822a0a683eca2f86b0e2b9b319a42806ae56cc | 6,542 |
import yaml
def config_get_timesteps(filepath):
"""Get list of time steps from YAML configuration file.
Parameters
----------
filepath : pathlib.Path or str
Path of the YAML configuration file.
Returns
-------
list
List of time-step indices (as a list of integers).
"... | 8a51e1437edbf2d73884cb633dbf05e9cfe5a98d | 6,543 |
from typing import List
from typing import Tuple
def _broads_cores(sigs_in: List[Tuple[str]],
shapes: Tuple[Tuple[int, ...]],
msg: str
) -> Tuple[List[Tuple[int, ...]], List[Tuple[int, ...]]]:
"""Extract broadcast and core shapes of arrays
Parameters
... | 228cbe06e4bc1e092cf92034255bfd60f01664c1 | 6,545 |
def cal_rank_from_proc_loc(pnx: int, pi: int, pj: int):
"""Given (pj, pi), calculate the rank.
Arguments
---------
pnx : int
Number of MPI ranks in x directions.
pi, pj : int
The location indices of this rank in x and y direction in the 2D Cartesian topology.
Returns
------... | 97146de9f69dd2f62173c19dfdb98d8281036697 | 6,549 |
def filter_matches(matches, threshold=0.75):
"""Returns filterd copy of matches grater than given threshold
Arguments:
matches {list(tuple(cv2.DMatch))} -- List of tupe of cv2.DMatch objects
Keyword Arguments:
threshold {float} -- Filter Threshold (default: {0.75})
Returns:
li... | c2cbec1da42d96575eb422bfdda6a1351e24508b | 6,553 |
import string
import random
def createRandomStrings(l,n,chars=None,upper=False):
"""create list of l random strings, each of length n"""
names = []
if chars == None:
chars = string.ascii_lowercase
#for x in random.sample(alphabet,random.randint(min,max)):
if upper == True: ... | 678b5aeb3cc98ae2b47822500fcbaff05081058a | 6,554 |
def get_previous_quarter(today):
"""There are four quarters, 01-03, 04-06, 07-09, 10-12.
If today is in the last month of a quarter, assume it's the current quarter
that is requested.
"""
end_year = today.year
end_month = today.month - (today.month % 3) + 1
if end_month <= 0:
end_year -= 1
end_mo... | 4175c80d2aa75c0e3e02cdffe8a766c4a63686d0 | 6,555 |
def get_payload(address):
"""
According to an Address object, return a valid payload required by
create/update address api routes.
"""
return {
"address": address.address,
"city": address.city,
"country": str(address.country),
"first_name": address.first_name,
... | 34fde5090aae774a24a254ea7dd7f03cc0f784be | 6,556 |
import torch
def string_to_tensor(string, char_list):
"""A helper function to create a target-tensor from a target-string
params:
string - the target-string
char_list - the ordered list of characters
output: a torch.tensor of shape (len(string)). The entries are the 1-shifted
ind... | eb6c7fcccc9802462aedb80f3da49abec9edc465 | 6,562 |
def _add_sld_boilerplate(symbolizer):
"""
Wrap an XML snippet representing a single symbolizer in the appropriate
elements to make it a valid SLD which applies that symbolizer to all features,
including format strings to allow interpolating a "name" variable in.
"""
return """
<StyledLayerDescri... | 971199333570d5bc7baefec88f35b92922ef6176 | 6,564 |
def sequence_names_match(r1, r2):
"""
Check whether the sequences r1 and r2 have identical names, ignoring a
suffix of '1' or '2'. Some old paired-end reads have names that end in '/1'
and '/2'. Also, the fastq-dump tool (used for converting SRA files to FASTQ)
appends a .1 and .2 to paired-end reads if option -I ... | 645ac09011cc4b94c5b6d60bf691b6b1734d5b6b | 6,565 |
def _check_type(value, expected_type):
"""Perform type checking on the provided value
This is a helper that will raise ``TypeError`` if the provided value is
not an instance of the provided type. This method should be used sparingly
but can be good for preventing problems earlier when you want to rest... | a18ecfe9d63e6a88c56fc083da227a5c12ee18db | 6,570 |
def addCol(adjMatrix):
"""Adds a column to the end of adjMatrix and returns the index of the comlumn that was added"""
for j in range(len(adjMatrix)):
adjMatrix[j].append(0)
return len(adjMatrix[0])-1 | 29ee11953cbdb757e8ea80e897751059e42f1d90 | 6,572 |
def _compound_register(upper, lower):
"""Return a property that provides 16-bit access to two registers."""
def get(self):
return (upper.fget(None) << 8) | lower.fget(None)
def set(self, value):
upper.fset(None, value >> 8)
lower.fset(None, value)
return property(get, set) | 00f315cc4c7f203755689adb5004f152a8b26823 | 6,577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.