content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import builtins
def any(iterable, pred):
"""Returns True if ANY element in the given iterable is True for the
given pred function"""
return builtins.any(pred(x) for x in iterable) | eb90ad4fdd55432705a1c8e1fa5159c9e9e7081e | 689,244 |
def tri_ravel(l, m1, m2):
"""Ravel indices for the 'stack of triangles' ordering."""
# m1 must be >= m2
if m1 < m2 or m1 > l or m2 > l or m1 < 0 or m2 < 0:
raise ValueError("Invalid indices")
base = l * (l + 1) * (l + 2) // 6
offset = (l - m1) * (l + 3 + m1) // 2 + m2
ind = base + offset... | c7cb59e4c7d1972b5da793ce6dd19cf545c510d7 | 689,245 |
def _create_dictionary(sequences):
"""
Create id/token mappings for sequences.
:param sequences: list of token sequences
:return: mappings from id to token, and token to id
"""
tokens = {}
for s in sequences:
for token in s:
tokens[token] = tokens.get(token, 0) + 1
s... | 50bca05f76522f93e5199cbdb009c638ced4890f | 689,247 |
def lower_bound(arr, value, first, last):
"""Find the lower bound of the value in the array
lower bound: the first element in arr that is larger than or equal
to value
Args:
arr : input array
value : target value
first : starting point of the search, inclusi... | e517abdb0acc636b9010a795b85f720da88b09e1 | 689,248 |
import lzma
import json
def raw_numpy_to_object(numpy_bytes_array):
"""Convert numpy array to a Python object.
Args:
numpy_bytes_array: a numpy array of bytes.
Returns:
Return a Python object.
"""
return json.loads(
lzma.decompress(numpy_bytes_array.tobytes()).decode('ut... | 99f99495c38a3f8bb47d02ae9b04e37957c39263 | 689,249 |
def repeated(pattern, sep, least=1, most=None):
"""
Returns a pattern that matches a sequence of strings that match ``pattern`` separated by strings
that match ``sep``.
For example, for matching a sequence of ``'{key}={value}'`` pairs separated by ``'&'``, where
key and value contains only lowercas... | 7eb857c423e06e8cddd6d9e859b872911c7b19b8 | 689,250 |
def norm_rows(X, stats=None):
"""
Normalize the rows of the data.
X is an M-by-N array to normalize. It is modified in-place. The data is not returned.
If stats is given it must be a sequence of 2 M-length arrays for the min and max statistics to
normalize by instead of calculating them fr... | 9652ba96b164f1b7f9dd0c706cd75c077fd9a695 | 689,251 |
def createboard(rows,columns):
""" Creates a string given rows and columns desired
that can be converted into a matrix through numpy
>>> createboard(5,4)
'0,0,0,0,0; 0,0,0,0,0; 0,0,0,0,0; 0,0,0,0,0'
>>> createboard(3,7)
'0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0'
"""
row_size ... | 2658516d95636242d7c8de49cc76f7c0f1217700 | 689,252 |
def make_histogram(s):
"""Make a map from letters to number of times they appear in s.
s: string
Returns: map from letter to frequency
"""
hist = {}
for x in s:
hist[x] = hist.get(x, 0) + 1
return hist | d5b3b5eb58eda71f87dafa9b702cf39366e74560 | 689,253 |
def omp_get_team_size(level : int):
"""
The omp_get_team_size routine returns, for a given nested
level of the current thread, the size of the thread team to
which the ancestor or the current thread belongs.
Parameters
----------
level : int
"""
return 1 | 672aa667afb6a95726773c5a95f84534305867a4 | 689,254 |
import os
def get_version():
"""Get version number of the package from version.py without importing core module."""
package_dir = os.path.abspath(os.path.dirname(__file__))
version_file = os.path.join(package_dir, 'src/seqdiag/__init__.py')
namespace = {}
with open(version_file, 'r') as f:
... | a63e0cc16077e58dc65141f7e1e137ffa5546b3f | 689,255 |
def invert_color(color):
"""
Инвертировать цвет (выдать комплиментарный по RGB)
"""
return tuple(255 - i for i in color) | 1a11e59afbf642983f63be19337ba57dd04fa99b | 689,256 |
import time
def profile(func):
"""profile execution time of provided function"""
func_start = time.time()
func()
func_end = time.time()
func_delta = func_end - func_start
label = str(func).split()[4].split('.')[2]
return f"'{label}' passed in {func_delta:.2f}s" | 3e81f4f656c375f341d2d31b3d95a8662bad5dcb | 689,257 |
import textwrap
import tempfile
import subprocess
import sys
def interpret_bash_array(pkgbuild, array_name):
"""Return the Bash array array_name in the file at path pkgbuild.
Returns:
A list of strings, or an empty string if the array is not
defined in the PKGBUILD, or None if there was a pro... | fa8f4e6f64cf31d282cd9e873d6e530ed631131d | 689,258 |
import types
def rebuild_code_object(co, code=None, constants=None, filename=None):
"""Rebuild the code object."""
code = code or co.co_code
constants = tuple(constants or co.co_consts)
filename = filename or co.co_filename
params = [co.co_argcount, co.co_kwonlyargcount,
co.co_nlocal... | 98ee5bb2f106790291dfdb0b51745fcc125a703b | 689,259 |
from sympy import Function
def _functions(expr, x):
""" Find the types of functions in expr, to estimate the complexity. """
return set(e.func for e in expr.atoms(Function) if x in e.free_symbols) | 0b325f8acd5fcb58dcca375dfff347a0ad6e3a86 | 689,260 |
import time
def time2int(time_struct, format24=False):
"""Convert time, passed in as a time.struct_time object, to an integer with
hours in the hundreds place and minutes in the units place. Returns 24
hour format if format24 is True, 12 hour format (default) otherwise.
"""
if not isinstance(time_... | 883b0f7656a354b3a0975b9e15a4637659751080 | 689,261 |
def error_response(message):
"""
Construct error response for API containing given error message.
Return a dictionary.
"""
return {"error": message} | 677912817c91725c7079b538bfdf915eb21f3fa0 | 689,262 |
import os
def sort_dir(dir_name, sub_split=-3, param_split=-1):
"""
:param dir_name: Full directory name to be sorted
:param sub_split: Location of subID to split in sorting
:param param_split: Location of parameter to split in sorting
:return: Sorted directory according to first (subID) and third... | 6d8a9ce948b069474547ede29818e5c8fb74a765 | 689,263 |
def make_boulder (fasta,
primer3_input_DIR,
exclude_list=[],
output_file_name="",
sequence_targets=[]):
""" create a boulder record file in primer3_input_DIR from a given fasta STRING.
SEQUENCE_ID is the fasta header, usually the genomic re... | 5c61bec782f1df83ac458bbd6501648e10b7d87d | 689,264 |
def price(company):
"""Get historical price data.
Used in class TestPrice.
"""
return company.historical('2021-8-3', '2021-8-10') | df4e877aa7677cb674b6bd7bf4a16b22105b8a37 | 689,265 |
from io import StringIO
def s3(mocker):
"""Patch Boto3 S3 Calls"""
s3_patch = mocker.patch('boto3.client')
s3_patch.return_value.get_object.return_value = {
'Body': StringIO(u"foo: bar"),
}
return s3_patch | f0bdb0047dfb5019164a2fe012b161e69e732978 | 689,266 |
def unit_width_to_available_footprint(unit_width):
"""Convert a key width in standard keyboard units to the width of the kicad
footprint to use"""
if unit_width < 1.25:
return "1.00"
elif unit_width < 1.5:
return "1.25"
elif unit_width < 1.75:
return "1.50"
elif unit_w... | 158f58c16100499f5d17218a6b6591b2b0a949e9 | 689,267 |
def export_fasta(dic):
"""Export a dictionary."""
fasta = ""
for (k, v) in dic.iteritems():
fasta += ">%s\n%s\n" % (k, v)
return fasta | 2b8df4299028e54059a5eb35af9dc1422cba9fc9 | 689,269 |
def Slope(pt1, pt2):
"""
Calculates the slope of the line connecting 2 points.
:param `pt1`: an instance of `wx.Point`;
:param `pt2`: another instance of `wx.Point`.
"""
y = float(pt2.y - pt1.y)
x = float(pt2.x - pt1.x)
if x:
return y/x
else:
return None | 229bc4e08820e549a1c87f27ddf9262bf0af258d | 689,270 |
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
DONE: Running time: O(n), because the worst-case scenario would require
iterating through the entire array once.
DONE: Memory usage: O(1), because the input array is modified in-place (if at all)."""
# DON... | da5369728821244d7b81ae4926042d3ff6001fcd | 689,271 |
def get_works_with_xml(pages):
"""
Arguments:
pages: result of `get_wiki_content_for_pages`
"""
ret = []
for page in pages:
if "{{XML}}" in page["content"]:
ret.append(page)
return ret | 18c737de8cd8f30ad0e5b1d397e39f0055bed762 | 689,272 |
import mpmath
def cdf(x, dfn, dfd):
"""
Cumulative distribution function of the F distribution.
`dfn` and `dfd` are the numerator and denominator degrees of freedom, resp.
"""
if x <= 0:
return mpmath.mp.zero
with mpmath.mp.extradps(5):
x = mpmath.mp.mpf(x)
dfn = mpmat... | 89d9d2d9278344e1ff50ac9afde415642bd4e472 | 689,273 |
def shift(cube, axis, n=1, cval=0):
"""Returns a cube with the axis shifted.
Ex.
cp.shift(nodo_ejemplo,index_para_ejemplo,1)
"""
return cube.shift(axis,n,cval) | 9676b1b8b16ce1c0ac8480776165f5a7281df0b8 | 689,274 |
import os
def alias_dict(fname):
"""
Aliases hard to read accessions to easier to read names:
NC_045512 wuhan-hu-1
MN996532 raTG13
"""
if not fname or not os.path.isfile(fname):
return dict()
stream = open(fname)
lines = map(lambda x: x.strip(), stream)
lines = filter(la... | 1828d0d5cf886ab96ffa553f02157f6ee1921276 | 689,275 |
def is_iter(obj):
"""
Checks if an object behaves iterably.
Args:
obj (any): Entity to check for iterability.
Returns:
is_iterable (bool): If `obj` is iterable or not.
Notes:
Strings are *not* accepted as iterable (although they are
actually iterable), since string... | d3ae5833dc3fb0610cbf8f9446b58148843083d8 | 689,276 |
def _make_rows(data, headers, defaults={}):
""" extract the values from the data based on the headers
data is a list of dicts
headers is a list of keys
defaults is a dict, where the keys are from the headers list
returns the data in a list or rows (tabulate data format)
"""
... | e67f699faf134ccac79b17b807c917f2f363342c | 689,277 |
def sampling(array, interval=1, offset=0):
"""
Down-sample the input signal with certain interval.
input:
array: numpy array. The input temporal signal. 1d or with multiple dimensions
interval: int. The interval to sample EEG signal. Default is 1, which means NO down-sampling is applied
... | 440df08b95619f446ee498022d509740e2d75637 | 689,278 |
def stat_float_times(newvalue=False):
"""Determine whether :class:`stat_result` represents time stamps as float objects.
If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
``False``, future calls return ints. If *newvalue* is omitted, return the
current setting.... | c5fff0bcaeae4ef0c14aa08dcfaea6d30da14795 | 689,280 |
def acquire_page_list_urls_books(soup):
"""
Take a BeautifulSoup content of a category page.
Return a list of the urls of the books
in the first page for a unique category.
"""
page_list_partial_urls_books = map(
lambda x: x.a['href'][8:],
soup.find_all('h3'),
)
page_list_urls_books = map(
lambda x: f"ht... | d6ac09b85ce0ca3bef2056615efca413f377f1e0 | 689,281 |
def LUT_match(data, lut, idi, idj, mod09):
"""look up table"""
p_aot1 = data[idi][idj] # band 3
p_sur = mod09[idi][idj] # mod09
min_d = 100
aod_v = 0
for i in lut:
p_aot2 = i[2] + (i[1] * p_sur) / (1 - i[0] * p_sur)
_delta = abs(p_aot2 - p_aot1)
if _delta < min_d:... | 2c7aae2e03fd1704add9ba8f85fdf90e13ca0f40 | 689,282 |
def _convert_to_dict(caps_str: str) -> dict:
"""
Parses the VCP capabilities string to a dictionary.
Non continuous capabilities will include an array of
all supported values.
Returns:
Dict with all capabilities in hex
Example:
Expected string "04 14(05 06) 16" is converted to:... | baedf62443eeac9bf4baa5a52acb0ec2dcb5a63e | 689,283 |
import torch
def pck(x, x_gt, perm_mat, dist_threshs, ns):
"""
Percentage of Correct Keypoints evaluation metric.
:param x: candidate coordinates
:param x_gt: ground truth coordinates
:param perm_mat: permutation matrix or doubly stochastic matrix indicating correspondence
:param dist_threshs:... | 75dbd6e34772f9a863fb345d6042aceb68829a12 | 689,284 |
import os
def change_ext(original_file, new_ext):
"""Changes extensions
@returns (new_filename, original_ext)"""
base, original_ext = os.path.splitext(original_file)
new_filename = '{}.{}'.format(base, new_ext)
return new_filename, original_ext | 930901661ecdaf1d632168ed2d030eea1cf9b33c | 689,285 |
def get_line_end(
is_last_line: bool,
) -> str:
"""
Get the characters needed for the end of a row of a TeX table being created by one
of the functions below.
Note that for some TeX-related reason, we can't put the \\ on the last line.
Args:
is_last_line: Whether this is the last line o... | 501cafe42f9b4aede81678286e4bd6cf3d9525aa | 689,286 |
def db2xml(db, rootnode = None, rownode = None, fields = None, expressions = None, primary = False):
"""convert a database view to XML"""
return db.xml( rootnode, rownode, fields, expressions, primary ) | bdad2cea4ef1d91adc82f658048de7e1ca868eaf | 689,287 |
def change_log_level_console(logger, new_level):
"""Change the minimum level that will be logged to the console
Parameters
----------
logger : logger object
As created by "init_root_logger" method
new_level : int
New minimum level to log to console
"""
logger.handlers[1].se... | e52973b71a1ea615dc5c45094b562d15273a63e8 | 689,288 |
import requests
def graph_query(url, proxies, headers, operation='query', payload={}):
"""Perform a query."""
try:
response = requests.post(url,
headers=headers,
cookies=None,
verify=False,
allow_re... | 2e8a672f2d759c8aff195f1bcea557b71ea40f02 | 689,289 |
def writeLabels(label):
"""Format text to be output by LaTeX."""
return label.replace('_', r'\_') | e7ddf5af2508a65729a018d787356cbd0cc85a75 | 689,290 |
def get_public_translation(instance, language_slug):
"""
This tag returns the most recent public translation of the requested content object in the requested language.
:param instance: The content object instance
:type instance: ~integreat_cms.cms.models.pages.page.Page, ~integreat_cms.cms.models.event... | f70d3dc2ede333e34f92b4010d1bf33d9032b5d2 | 689,291 |
def is_cjk(character):
"""
Borrowed from the nltk
https://github.com/alvations/nltk/blob/79eed6ddea0d0a2c212c1060b477fc268fec4d4b/nltk/tokenize/util.py
"""
return any(
[
start <= ord(character) <= end
for start, end in [
(4352, 4607),
... | 368bcd615bcc5561835ef8a30147c87095bad211 | 689,292 |
def openappend(file):
"""Open as append if exists, write if not."""
try:
output = open(file, 'a')
except Exception:
try:
output = open(file, 'w')
except Exception:
return 'error'
return output | cb893ac7c9914a3e10cfe30940e6c80c30a0364e | 689,293 |
def ext_checker(fname, ext):
"""Replaces the extension of fname with ext, or adds ext to fname
if fname doesn't already have an extension."""
ext_begin = -len(fname)
for ind in range(1, len(fname) + 1):
if fname[-ind] == ".":
ext_begin = ind
break
return fname[:-ext_b... | e68f75c06ae21594cea220bba4f61288aeae4893 | 689,294 |
def click(pos):
"""
clicks on the board squares
:return: mouse position in 2D board Array form
"""
rect = (113,113,525,525)
x = pos[0]
y = pos[1]
if rect[0] < x < rect[0] + rect[2]:
if rect[1] < y < rect[1] + rect[3]:
divX = x - rect[0]
divY = y - rec... | bca538e3a25f868c196fe2a148f5f0804c666f2e | 689,295 |
def get_primes(number):
"""
得到小于num的质数
:param number:
:return:
"""
w = [True] * number
li_number = []
for i in range(2, number):
if w[i]:
w[i * i::i] = [False] * (len(range(i * i, number, i)))
li_number.append(i)
return li_number | e4aefe02c8afba84b688743bc7570bf5d615b1aa | 689,296 |
def _air_check( game_data ):
"""
Below-min breath is called exhaustion.
Knowing when to breathe is important.
"""
for p in range( 2 ):
c = game_data[str(p)]['calm']
# Punish will if calm is below zero
if c < 0:
game_data[str(p)]['calm'] = 0
game_data[str(p)]['will'] += c
# Treat Air as maximum Calm
... | cda4e901f77df40de4c7168dfaff697c983198a7 | 689,297 |
def backward_sorted_array(len_arr):
"""
Function generates a backward array of size 2 ** n of integers.
"""
array = []
for i in range(len_arr):
array.append(len_arr-i)
return array | 50ae30d0a6069f6e2bbdb16442626aaeb6403bac | 689,298 |
def asa_scp_handler(ssh_conn, cmd='ssh scopy enable', mode='enable'):
"""Enable/disable SCP on Cisco ASA."""
if mode == 'disable':
cmd = 'no ' + cmd
return ssh_conn.send_config_set([cmd]) | 2f8ac7e7df4329c90043a4c0e22d11f6d34444dd | 689,299 |
def project_client(rubicon_client):
"""Setup an instance of rubicon configured to log to memory
with a default project and clean it up afterwards.
"""
rubicon = rubicon_client
project_name = "Test Project"
project = rubicon.get_or_create_project(
project_name, description="In memory pro... | c933412fa21a3e5542bc930f7d490efc30dadaee | 689,300 |
def progress(status_code):
"""Translate PROGRESS status codes from GnuPG to messages."""
lookup = {
'pk_dsa': 'DSA key generation',
'pk_elg': 'Elgamal key generation',
'primegen': 'Prime generation',
'need_entropy': 'Waiting for new entropy in the RNG',
'tick': 'Generic t... | 7dc7010175ff268b0af8db35e02b62a8790683b9 | 689,301 |
import re
def ir_parsing(text):
"""Parsing IR data to detect solvent,units and spectrum values.
param text:IR data block
return:a dictionary that include all the information about solvent, units and IR spectrum values
"""
IR_Spectroscopy = {"solvent": None, "units": None, "spectrum": {}}
spectrum... | 4d482727bef9fb928377c90956640a76f24a80ca | 689,302 |
def YELLOW(obj):
"""Format an object into string of yellow color in console.
Args:
obj: the object to be formatted.
Returns:
None
"""
return '\x1b[1;33m' + str(obj) + '\x1b[0m' | 33794175a0a8ddbe50992fb0105978669293c853 | 689,303 |
def per_target(imgs):
"""Arrange samples per target.
Args:
imgs (list): List of (_, target) tuples.
Returns:
dict: key (target), value (list of data with this target)
"""
res = {}
for index in range(len(imgs)):
_, target = imgs[index]
if target not... | 27a708a30490dab972f97f9e5fb831741de9d099 | 689,305 |
from datetime import datetime
import time
def uptime(since):
"""Turn an date and time into an uptime value.
The returned value is a number of seconds from the provided value
to the current time. The date/time provided is expected to be a
local time using the following format: 2017-01-10 16:32:21.
... | b9dddfb3b99d9dafb32d9cdc3ee4e8710bde4f0e | 689,306 |
def interpret_word_seg_results(char_seq, label_seq):
"""Transform model output into user-friendly contents.
Example: In CWS, convert <BMES> labeling into segmented text.
:param char_seq: list of string,
:param label_seq: list of string, the same length as char_seq
Each entry is one of ('B',... | 9c83a19360b9498bb57df80cc257b0a5333593c0 | 689,307 |
def _set_model_dict(resource_type_name, properties_target, prefix,
created_at, updated_at):
"""return a model dict set with the passed in key values"""
model_dict = {'name': resource_type_name,
'properties_target': properties_target,
'prefix': prefix,
... | 7e1ff49f7473a69e599fb3d58ae86f993b6595ed | 689,308 |
def get_location_from_event(event):
"""
Append the coordinates of the event in a list of locations for the GMaps
marker locations
"""
location = {}
coordinates = event["_embedded"]["venues"][0]["location"]
location["lng"] = float(coordinates["longitude"])
location["lat"] = float(coordina... | 9b98a41ec7d3868b507acaf2b0c5c4f9501849a5 | 689,309 |
def kw_pop(*args,**kwargs):
"""
Treatment of kwargs. Eliminate from kwargs the tuple in args.
"""
arg=kwargs.copy()
key,default=args
if key in arg:
return arg,arg.pop(key)
else:
return arg,default | 7f02eedd1562f463009daf2ce4db5c2fd4fd76f9 | 689,310 |
import json
def getCustomResponse(responseData, url, params):
"""convert requests lib response data to my custom
response dictionary
Args:
responseData (Response): response class returned from requests lib
url (String): requests uri
params (Dict): params used
Returns:
... | 1fc38595929b2bcb27f971a2ed6466ef4d2a4cfc | 689,311 |
import random
import json
def makeSurveyJson (transaction) :
"""Generates a problem description matching the survey definition in the
working database."""
durations = ["overnight","overnight+", "days", "4-8hours", "minutes", ">1hour",
"hours", "1-2hours"]
problem_types = [ 'full', 'absent'... | 1c498f0a0d3653521401667439ae0981677abd44 | 689,312 |
import os
def filter_audio(f):
"""
Return only pydub supported audio
"""
ext = os.path.splitext(os.path.basename(f))[1][1:]
if ext in ['mp3', 'wav', 'raw', 'ogg', 'aif']:
return f | 91477ab2ab77aaf31ae3ea3c599ec2145c52fd7b | 689,313 |
def drop_duplicate_psites(df):
""" remove duplicate phosphosites. Retain site with maximum intensity across samples """
df2 = df.copy()
samples = [s for s in df2.columns.tolist() if 'sum' in s]
df2['max_int'] = df2[samples].sum(axis=1)
df2 = df2.sort_values('max_int').drop_duplicates(['identifier'],... | a424d1487435a322ec8f81ff68a98b15250e4cf8 | 689,315 |
import importlib
def try_import(path, keys=None, _as=True):
"""Try to import from a module.
Parameters
----------
path : str
Path to module or variable in a module
keys : str or list[str], optional
Keys to load from the module
_as : bool, defualt=True
If False, perform... | 10ad9c39b4d8813d0f056717f05365a28b54ab21 | 689,316 |
def normalize_path_for_settings(path, escape_drive_sep=False):
"""
Normalize a path for a settings file in case backslashes are treated as escape characters
:param path: The path to process (string or pathlib.Path)
:param escape_drive_sep: Option to escape any ':' driver separator (wi... | d48d1bb5dc6ddddeb03dfc3c938451d5d0c05e48 | 689,317 |
def round_robin(w) -> bool:
"""Implements a round-robin association strategy where iots are associated their ssid modulo number of APs.
Return:
Returns true on successful association. False otherwise.
"""
m = len(w.aps)
i = 0
for device in w.iots:
if device.do_associate(w.aps[i%m]) == False:
return False... | 03cb6ea5eac30ff2cad676d9e55388403cd955df | 689,318 |
def create_property_type(data):
"""Create whole/naked property feature."""
data['Tipo_proprietà'] = (data['Tipo proprietà']
.str.lower()
.str.extract('(intera proprietà|nuda'
'proprietà|multiproprietà)',
... | 92b7ab4961c14f2da1f81ffa9bdbf0f1229d0555 | 689,319 |
import numpy
def computeMicrocanonicalRateCoefficients(network, T=1000):
"""
Compute all of the microcanonical rate coefficients k(E) for the given
network.
"""
Elist = network.autoGenerateEnergyGrains(Tmax=2000, grainSize=0.5*4184, Ngrains=250)
# Determine the values of some counters
Ngr... | 58f445f586f7009f892965e1c99c5f2334bfc92e | 689,320 |
def convert_oct_set(oct_set, og_names):
"""
Maps an OCT set on the preprocessed graph to their original vertices.
"""
try:
return list(map(lambda x: og_names[x], oct_set))
except Exception:
print('Error: OCT set', oct_set)
print('Error: og_names', og_names)
print('Pro... | fa2bf23ffaadda64289a0a842d5614c076e627c3 | 689,322 |
def check_dict_is_contained_in_another(filter_data: dict, data: dict) -> bool:
"""
Check if a dict is contained in another one.
* Works with nested dicts by using _dot notation_ in the filter_data keys
so a filter with
`{"base_key.sub_key": "value"}`
will look for dicts containing
`... | 87eefc13b09edeb21e0a6097a09c12ea8d650545 | 689,323 |
import pkgutil
def list_skeletons():
"""List available skeletons for generating conda recipes from external sources.
The returned list is generally the names of supported repositories (pypi, cran, etc.)"""
modules = pkgutil.iter_modules(['conda_build/skeletons'])
files = []
for _, name, _ in modu... | a79365c6abbb8d235c2935df3df0988bd7447fdc | 689,324 |
def inside_bounding_box(bb_minlat, bb_minlon, bb_maxlat, bb_maxlon, start_lat, start_lon, end_lat, end_lon):
"""
Check if two given sets of coordinates (start_lat, start_lon) and (end_lat, end_lon) are
within a bounding box (bb_minlat, bb_minlon, bb_maxlat, bb_maxlon)
Examples:
>>> inside_bounding_... | 817c26ecc4376d3472298408157d39465e9dec80 | 689,325 |
import sys
def is_pytest():
"""This tells if the current process is started by pytest."""
for one_arg in sys.argv:
if one_arg.find("pytest") >= 0:
return True
return False | 4d4e714004d266eba8d2164d64a7985a0cb00eba | 689,326 |
def time_representation(hours, minutes, seconds):
"""Conversion of readable to internal time representation.
Parameters
----------
hours : float or array, shape (n_steps,)
Hours since start
minutes : float or array, shape (n_steps,)
Minutes since start
seconds : float or array... | 2963f25b1603a030f8da4b1a2184a9330ee971cb | 689,327 |
import typing
def get_destination_for_notebook(relative_path: str) -> typing.Any:
"""
Get the destination for a notebook.
The destination can be of a type of your choice, but it must be
serializable with itsdangerous. It will be used by the other methods
defining local behavior to determine where... | 62b248e6ce0cccff3b02ee83b301d527c259048d | 689,328 |
def _update_change_dec(func):
"""
Decorator to track property changes in class. Apply @property.setter after @_update_change_dec
:param func: function object to decorate
:return: decorated function
"""
def _wrapper(self, val):
self._changed = True
func(self, val)
return _wr... | e37ab2ebb787af2d8f04284ef40c1fcde327dee3 | 689,329 |
def generate_properties_test(dataset, abs_path):
"""
:param dataset:
:param abs_path:
:return:
"""
return dataset.to_dict() | 3f0cd464b9c90b7790c1fc29e8c2765830f3d2ca | 689,330 |
def colorclose(color, hsva_expected):
"""
Compares HSV values which are stored as 16-bit integers.
"""
hsva_actual = color.getHsvF()
return all(abs(a-b) <= 2**(-16) for (a,b) in zip(hsva_actual, hsva_expected)) | 453d5ed794736ac4b8f7489a0ca701061f543f54 | 689,332 |
def nice_pypy_mem(mem: str) -> str:
"""Improves formatting of the memory statistics produced by pypy's
garbage collector (which are provided as strings)"""
return mem.replace("KB", " KiB").replace("MB", " MiB").replace("GB", " GiB") | 3c6e30cba768a8f0d3932be133ba12428c9935af | 689,333 |
def swap_short_telos_group_number(row):
"""
swaps all group 1 patients to group 2 & all group 2 patients to group 1
this is done purely for visualization reasons and has no impact whatsoever
on interpretation of results; just swapping #s for interpretability
"""
if row == 1:
row = 2
... | e2f7c99d8f31f9a130b67be72c285c7acb50364c | 689,334 |
def _float_to_int(x: float) -> int:
"""
Symbolic tracing helper to substitute for inbuilt `int`.
Hint: Inbuilt `int` can't accept an argument of type `Proxy`
"""
return int(x) | cab1e1ffbad46b95bd1da5d7dd88013cb60839f2 | 689,335 |
def calculate_board_dim(img_mat, start_pos):
"""
Calculates the length of one side of the board (all info we need to find specific tiles)
"""
x, y = start_pos
dim = 0 # size of one side of the chess board
while img_mat[x, y, 0] != 0 and img_mat[x, y, 1] != 0 and img_mat[x, y, 0] != 0:
d... | 82b194167232f94a3ca61c7630d94ef37eca4c5e | 689,336 |
def update(data):
"""Update the data in place to remove deprecated properties.
Args:
data (dict): dictionary to be updated
Returns:
True if data was changed, False otherwise
"""
changed = False
for cfg_object in data.values():
externals = []
paths = cfg_object.p... | 6a0d2f8a8804423817bd9151df312190664fd031 | 689,337 |
def digit_facorials():
"""Find the sum of all numbers which are equal to the sum of the factorial
of their digits. """
final_list = []
facts = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
for x in range(3, 2500000):
string = str(x)
total = 0
for i in string:
t... | 25ac3d4a9d2a1da93eae66dbc8427d5eaaf1de19 | 689,338 |
def cut_levels(nodes, level):
"""
For cutting the nav_extender levels if you have a from_level in the navigation.
"""
result = []
if nodes:
if nodes[0].level == level:
return nodes
for node in nodes:
result += cut_levels(node.childrens, level)
return result | 86343598072a96de5d4677cae12e8b0447f7111e | 689,339 |
import os
import json
def bids_load_prot_dict(prot_dict_json):
"""
Read protocol translations from JSON file in DICOM directory
:param prot_dict_json: string
JSON protocol translation dictionary filename
:return:
"""
if os.path.isfile(prot_dict_json):
# Read JSON protocol tr... | 9e8c556b9006d28ec62b2eb4be3eb8e52d8f6f66 | 689,340 |
def find_cont_substring(l1, l2, n):
"""Dynamic programming algorithm to find continuous, uninterrupted substrings in two increasing lists.
Given two lists, finds the position in the first one which is proceeded
by n elements from the first list, not interrupted by the second.
For example,
find... | 2f336f87ed93b46187a23e2b5c1a2ac20f1f8d56 | 689,341 |
import torch
def layernorm(x):
"""
:param x: (B, K, L) or (B, K, C, H, W)
(function adapted from: https://github.com/MichaelKevinKelly/IODINE)
"""
if len(x.size()) == 3:
layer_mean = x.mean(dim=2, keepdim=True)
layer_std = x.std(dim=2, keepdim=True)
elif len(x.size()) == 5:
... | 7f4e81ca7d099eb9c6ca21652512148c9c8c0347 | 689,342 |
def add_fdcuk_meta_data(df, filepath):
"""
Accepts a dataframe and a filepath
parses the filepath to get strings representing
nation, league, and season
writes this data to the dataframe
Returns the changed dataframe
"""
season = filepath.stem
str_filepath = str(filepath)
str_fil... | a0bfafc3f0d127fa944e71988bf8e864d712da33 | 689,343 |
def can_link_to(person, contact, model):
"""
Determines whether or not the specified person can form a social network
link to the specified contact.
:param person: The person wanting to link.
:param contact: The contact to determine link eligibility.
:param model: The model to use.
"""
... | 8250b3d2ff7fb5be2cb47e83caa99c827517ea79 | 689,344 |
def tail():
"""
Returns a string that will cover up bleeding output when printing in place
"""
return " \r" | 99b09f0370cc80096fd2dfc666749a77b1f77075 | 689,346 |
def should_show_entry_state(entry, current_api_id):
"""Returns wether or not entry state should be shown.
:param entry: Contentful entry.
:param current_api_id: Current API selected.
:return: True/False
"""
return (
current_api_id == 'cpa' and
(
entry.__dict__.get('... | 30856978bb38b598354e67ed8cf9a0568af448db | 689,347 |
def undefined_context():
"""Fixture. Populate context variable for future tests."""
return {
'cookiecutter': {'project_slug': 'testproject', 'github_username': 'hackebrot'}
} | 19087cdf1c198b297c782697f0e64907033bd753 | 689,349 |
def getCodons(sequence, gap_chars="-."):
"""get codons in sequence."""
codons, codon = [], []
full_codons, full_codon = [], []
for x in range(len(sequence)):
c = sequence[x]
full_codon.append(c)
if c not in gap_chars:
codon.append(c)
if len(codon) % 3 == 0:
... | 017e31bb33d0c305d31f1527453d87783aead81b | 689,350 |
def up(f):
"""Perform computation rounding down."""
return f() | b3243e7474ffbf9c0055415f1e49573fa93144c1 | 689,351 |
def read_results(bq):
"""
Read results
"""
return [row for row in bq.readResult()] | b1e3e490421d2b87e06d5dd19aec7a836a033896 | 689,352 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.