content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def word_to_forms(word): """Return all possible forms for a word. Args: word (unicode) Returns: forms (set[unicode]) """ forms = set() lemmas = lemmatize(word) for lemma in lemmas: forms.update(lemma_to_forms(lemma)) return forms
eee7fee2389d180664ff6e07718461043716ba7e
9,100
def load_decamCorners(): """ Returns the CCD corners of the DECam camera. Returns: decamCorners : *list* of *float* A list of the angular degree offsets of the CCD corners. """ with open('%s/DECam_corners.dat' % data_dir) as f: corners_dct = eval(''.join(f.readlines())) ...
5dd58af44029c87db5623dfa38a6223570836665
9,101
def reduce_expr(expr): """ Reduces a boolean algebraic expression based on the identity X + XY = X Args: expr (str): representation of the boolean algebraic expression Returns: A string representing the reduced algebraic expression """ reduced = True ...
2c278e6ea6f133c51c5e98796f288f366fd10cb3
9,102
import tempfile import os import shutil def get_mask(images, b_threshold=0) : """ Return a mask computed from baseline image """ b0 = baseline(images, b_threshold) skull_mask = medipy.segmentation.skull(b0) skull = medipy.logic.apply_mask(b0, skull_mask, 0, 0) directory = tempfile.mk...
b1703aad04ebd22a63b4710a70ca1011a08fb9e7
9,103
import os import pickle def get_inputs(): """ inputsdict contains {'Yte': Yte, 'Ytr': Ytr, 'Xtr': Xtr, 'Xte': Xte} where values are np.arrays np. arrays are truncated to evenly split into batches of size = batchsize """ with open(os.path.join(dpath, dfile), 'rb') as f: d_all = pickle.load(...
e96e64104fd5138a03ea15f6cbf3ecaf22e1f9e4
9,104
import json def _apply(input_bundle_name, output_bundle_name, pipeline_class_name, pipeline_args, input_tags, output_tags, output_bundle_uuid=None, force=False): """Apply a pipeline to an input bundle, and save the results in an output bundle. Args: input_bundle_name: The human name of...
811fc5b8da5a882508ea14c808f3989330e448df
9,105
def arcColor(renderer, x, y, rad, start, end, color): """Draws an arc to the renderer with a given color. The start and end of the arc are defined in units of degrees, with 0 being the bottom of the arc circle and increasing counter-clockwise (e.g. 90 being the rightmost point of the circle). If t...
3297a32236afe2881979b105992df17742dd06c3
9,106
def dos_element_spd( folder, element_spd_dict, output='dos_element_spd.png', fill=True, alpha=0.3, linewidth=1.5, sigma=0.05, energyaxis='x', color_list=None, legend=True, total=True, figsize=(4, 3), erange=[-6, 6], spin='up', combination_method='add', fon...
bf20cee25ace85e91a32f3b05016b0cd34f20600
9,107
import yaml def load(m, schema=UPLOAD_MANIFEST_SCHEMA): """ Load and validate a manifest. """ manifest = yaml.load(m) validate( manifest, schema=schema, ) return manifest
2bdbaf856a476b14b7ca0a353c4cdd56b3de2ae0
9,108
def transform_phenotype(inv_root, y, fam_indices, null_mean = None): """ Transform phenotype based on inverse square root of phenotypic covariance matrix. If the null model included covariates, the fitted mean is removed rather than the overall mean """ # Mean normalise phenotype if null_mean is...
d16699bb04a578050608910a9eea0ee6ea0b450d
9,109
import json import requests def download_site_build(event_file: str, download_path: str = "build-site.tar.gz") -> int: """Will download the site bulid if this is a forked PR bulid. Args: event_file (str): event file from the workflow Returns: int: PR num of the build if relevant """ ...
62250aa4a420a11745b76e41cffd111c7d675a3a
9,110
def createVskDataDict(labels,data): """Creates a dictionary of vsk file values from labels and data. Parameters ---------- labels : array List of label names for vsk file values. data : array List of subject measurement values corresponding to the label names in `labels`. Returns -------...
a4669e4a173aaeef534d13faceaeab869eb62cb3
9,111
def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, L, C = x.shape #print(x.shape) #print(window_size[0]) x = x.view(B, H // window_size[0], wind...
cfc97230e044f9d3a8fdfa7dde4b17a43f351169
9,112
def _get_unique(node_list, key, mode=None): """ Returns number or names of unique nodes in a list. :param node_list: List of dictionaries returned by Neo4j transactions. :param key: Key accessing specific node in dictionary. :param mode: If 'num', the number of unique nodes is returned. :return...
8f639dfce0efe9f7d40f2bba5f2b8757706cd6d7
9,113
def calculate_cpufreq_weighted_time_in_state( final_time_in_cpufreq_state_by_cpu, time_in_cpufreq_state_by_cpu): """Calculate the weighted average in each CPU frequency state. Args: final_time_in_cpufreq_state_by_cpu: Final time in each CPU frequency state. See the return value of parse_cpufreq_stat...
8f8f3646bbfef89c1d2c3f65d6b3a56b76fb19e4
9,114
from PIL import Image def array2imgdata_pil(A, format='PNG'): """get png data from array via converting to PIL Image""" if A.shape[2] == 3: mode = 'RGB' elif A.shape[2] == 4: mode = 'RGBA' else: mode = 'L' img = Image.fromstring(mode, A.shape[:2], A.tostring()) return p...
f206dc6eaefec2065c10c02b0ecafa5662f9d21c
9,115
def h_eval(data): """ Function takes dictionary Evaluate values and convert string to correct type (boolean/int/float/long/string) """ if isinstance(data, dict): for _k in list(data.keys()): data[_k] = h_eval(data[_k]) if data[_k] is None or (isinstance(data[_k], dic...
28a3529283719cab321c712a9e8723d5ff314ef8
9,116
def _recursive_simplify(expr): """ Simplify the expression as much as possible based on domain knowledge. """ input_expr = expr # Simplify even further, based on domain knowledge: # windowses = ('WIN32', 'WINRT') apples = ("MACOS", "UIKIT", "IOS", "TVOS", "WATCHOS") bsds = ("FREEBSD", "...
40b9dcc6d0a5b176f36ed2e01fc35a005c3c851f
9,117
import uuid def dropzone(url, **kwargs): """Dropzone component A basic dropzone component that supports drag and drop uploading of files which are posted to the URL provided. >>> zoom.system.site = zoom.sites.Site() >>> zoom.system.site.packages = {} >>> zoom.system.request = zoom.utils.Bunc...
d8626b158b8adb738a4f74f6009da93043365cc4
9,118
import math def fmt_bytes(size_bytes): """Return a nice 'total_size' string with Gb, Mb, Kb, and Byte ranges""" units = ["Bytes", "KB", "MB", "GB"] if size_bytes == 0: return f"{0} Bytes" for unit in units: digits = int(math.log10(size_bytes)) + 1 if digits < 4: ret...
40613403092bdc9d8dca8b0b487d5af6c887b075
9,119
from datetime import datetime def julianDays(year, month, day, hour, minute): """ Calculate the julian day (day of year) based on the known date/time information. :param year: :class:`numpy.ndarray` of the year of all observations. :param month: As for year, but for the month of observation. ...
5a00e840717dc08d4caeb71ec018f7d7d84fd1f7
9,120
from typing import Union import warnings def get_valid_split(records: dict, train_val_test: Union[list, np.ndarray]) -> dict: """ Gets a train, val, test split with at least one instance of every class Keep doing train_test_split until each split of the data has at least one single example of every behavior...
ce575ba0937e32b527e5d70de9855b6fa9f4a686
9,121
def _random_op(sites, ldim, hermitian=False, normalized=False, randstate=None, dtype=np.complex_): """Returns a random operator of shape (ldim,ldim) * sites with local dimension `ldim` living on `sites` sites in global form. :param sites: Number of local sites :param ldim: Local ldimens...
202fe112e896b14abb38a8477afa9eab7689f7f6
9,122
def minimize(system, positions, platform=None, tolerance=1.0*unit.kilocalories_per_mole/unit.angstroms, maxIterations=50): """Minimize the energy of the given system. Parameters ---------- platform : simtk.openmm.Platform or None, optional If None, the global GLOBAL_ALCHEMY_PLATFORM will be use...
d8dc9d1eab96c512aa72da36909490adfa8bbd6f
9,123
import aiohttp async def fetch(url="", headers=DEFAULT_HEADERS, params={}, payload={}, method="GET", loop=None): """fetch content from the url""" if not url: return async with aiohttp.ClientSession(loop=loop, headers=headers) as session: _method = getattr(session, method.lower()) a...
9be522a373532a3452a85ec1e8aae10e7659e999
9,124
import json def retrieve_prefix_fixture(): """Load test fixture data.""" j = json.load(open("./tests/fixtures/s3_prefix_list.json")) return j
5befb33c577263976edee6546bafca40b47e25bb
9,125
def parse_args(version: str) -> Namespace: """ Parse arguments passed to the application. A custom argument parser handles multiple commands and options to launch the desired function. Parameters ---------- version : string A ``string`` of the Bobber version. Returns -----...
20cbacbb611d9495fcd6ad444b258a5588c1bddb
9,126
def grid_reference_to_northing_easting(grid_reference): """ Needs to include reference :param grid_reference: :return: """ grid_reference = grid_reference.strip().replace(' ', '') if len(grid_reference) == 0 or len(grid_reference) % 2 == 1 or len(grid_reference) > 12: return None, No...
3da96e36f9be1e369d0425f2b9c34e432eb5ca77
9,127
import select def tflite_copts_warnings(): """Defines common warning flags used primarily by internal TFLite libraries.""" # TODO(b/155906820): Include with `tflite_copts()` after validating clients. return select({ clean_dep("//tensorflow:windows"): [ # We run into trouble on Window...
c65035d82801cad374db6dfb8f129ff55afff606
9,128
def sn_random_numbers(shape, antithetic=True, moment_matching=True, fixed_seed=False): """Returns an ndarray object of shape with (pseudo)random numbers that are standard normally distributed. Parameters ---------- shape : tuple (o, n, m) Generation of array with shape...
ca173cf02f51a8bb6cd976fc84f42597497cd426
9,129
def blue(N: int) -> np.ndarray: """ Blue noise. * N: Amount of samples. Power increases with 6 dB per octave. Power density increases with 3 dB per octave. https://github.com/python-acoustics """ x = white(N) X = rfft(x) / N S = np.sqrt(np.arange(X.size)) # Filter y = irf...
80e0c449f6548b19546a4e58fa3b3e108f21d6df
9,130
from typing import Dict def _remove_attribute(note_dict: Dict, attribute: str) -> Dict: """ Create a copy of the note where a single attribute is removed """ d = dict(note_dict) d[attribute] = None return d
d2659b887c1a2a7c67f6785889db2aa2039f9627
9,131
from pathlib import Path import yaml def get_config(path: str) -> config_schema: """Load the config from the path, validate and return the dcitionary Args: path (str): Path the config.yaml Returns: config_schema: The configuration dictionary """ config_path = Path(path) c...
bf355508b52192eb78857eadedde923b623ecc56
9,132
def compare_chars(first, second): """ Returns the greater of the two characters :param first: :param second: :return: char """ return chr(max(ord(first), ord(second)))
aee1e5767d6ab767bc8da27d382acc105f62d9f5
9,133
from pathlib import Path import os def get_file_path(filename): """Find filename in the relative directory `../data/` . Args: filename (str): file we're looking for in the ./data/ directory. Returns: str: absolute path to file "filename" in ./data/ dir. """ root_dir = Path(__fil...
7ea5185017f89e0780f4a796ecafd4908b9753ce
9,134
import typing import argparse def parse_arguments() -> typing.Dict[typing.Any, typing.Any]: """Parses command line parameters.""" argument_parser = argparse.ArgumentParser( usage=f"Database transfer tool for Cloud Composer v.{SCRIPT_VERSION}.\n\n" + USAGE + "\n" ) argument_pars...
05a649c95042965fb1e7d12ad759423c3ca89383
9,135
import re def find_author(): """This returns 'The NeuroKit's development team'""" result = re.search( r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format("__author__"), open("../neurokit2/__init__.py").read(), ) return str(result.group(1))
bcf7fb52021cd23ef48b57aae9444676bc26a862
9,136
from ecpy.utils.util import is_enable_native, _native from ecpy.fields.Zmod import ZmodElement from ecpy.fields.ExtendedFiniteField import ExtendedFiniteFieldElement def tate_pairing(E, P, Q, m, k=2): """ Calculate Tate Pairing Args: E: The Elliptic Curve P: A point over E which has order m Q: A poi...
804f8d9730df010f690b363b658ba59361e87f47
9,137
def kl_loss(img,decoded_img,encoder_log_var,encoder_mu): """ LK loss for VAEs """ kl_loss = -0.5 * tf.reduce_sum( (1+encoder_log_var-tf.exp(encoder_log_var)-encoder_mu**2), axis=[1,2,3],name='klloss' ) return tf.reduce_mean(kl_loss,axis=0)
bd6f644bea86fbc2e5c4426e0e556a432256bb07
9,138
import warnings def steady(L, maxiter=10, tol=1e-6, itertol=1e-5, method='solve', use_umfpack=True, use_precond=False): """ Deprecated. See steadystate instead. """ message = "steady has been deprecated, use steadystate instead" warnings.warn(message, DeprecationWarning) return stea...
36cf008c0b2c773359df5f2251282a2eb12dc613
9,139
def and_intersection(map_list): """ Bitwise or a list of HealSparseMaps as an intersection. Only pixels that are valid in all the input maps will have valid values in the output. Only works on integer maps. Parameters ---------- map_list : `list` of `HealSparseMap` Input list of map...
183df05210cdd29bf5dd0a5654ca08297cb9f72a
9,140
import re def parse(url): """Parses a cache URL.""" config = {} url = urlparse.urlparse(url) # Handle python 2.6 broken url parsing path, query = url.path, url.query if '?' in path and query == '': path, query = path.split('?', 1) cache_args = dict([(key.upper(), ';'.join(val)) f...
48328a0863272f17c8ad1e848af0bb29e0118545
9,141
def states_state(id=""): """ displays a HTML page with a list of cities by states """ states = storage.all(State).values() states = sorted(states, key=lambda k: k.name) found = 0 state = "" cities = [] for i in states: if id == i.id: state = i found = 1 ...
b00bd67a8242a2a21f32226b34df69e214db8856
9,142
def make_tree_item(parent, text, icon, first_col_text=None, second_col_text=None): """ 构造树的子项 :param parent: 要构造子项的父节点元素 :param text: 构造的子节点信息 :param icon: 图标,该元素的展示图标对象 :param first_col_text: 第一列隐藏信息 :param second_col_text: 第二列隐藏信息 """ item = MyTreeWidgetItem(parent) item.setIco...
a93e9d75ac9841c27fa472575054f00e6d1b1cb4
9,143
def get_boundary_condition(name): """ Return a boundary condition by name """ try: return _BOUNDARY_CONDITIONS[name] except KeyError: ocellaris_error( 'Boundary condition "%s" not found' % name, 'Available boundary conditions:\n' + '\n'.join( ...
29ba4d456452cb33cf48c44cace337683d1feab8
9,144
from datetime import datetime import json def run(ts): """ Actually do the hard work of getting the USDM in geojson """ pgconn = get_dbconn('postgis') cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor) # Look for polygons into the future as well as we now have Flood products # with...
b9e8f853f5d039fa8bb5fdc70a9f281ea94d7e37
9,145
def mtxslv_user_ratings(user_id, dataset): """ Receives user_id and dataset. Look for all occurences of user_id in dataset and returns such subset. If no user_id is found, return an empty numpy array. """ subset = [] # the same thing as I_i (set of item user_id has voted) for it in range(0,np.shape...
7b494b95af316d93e6f9b0a20a351179eb2906b9
9,146
def random_rotation(min, max, prng=DEFAULT_PRNG): """ Construct a random rotation between -max and max. Args min: a scalar for the minimum absolute angle in radians max: a scalar for the maximum absolute angle in radians prng: the pseudo-random number generator to use. Returns ...
58ae95edf57886164e0e123a89534000ef2f8182
9,147
def country_code_from_name(country_names,l3=False): """2 letter ['BE'] or 3 letter codes ['BEL'] from country names Accepts string or list of strings e.g, 'Serbia' or ['Belgium','Slovakia'] Update 3/1/2022: also accepts non uppercase titles, e.g. ['united Kingdom', 'hungary'] Arguments: *co...
d45a48b4f11de383def2817609c6682157de4443
9,148
def steem_amount(value): """Returns a decimal amount, asserting units are STEEM""" return parse_amount(value, 'STEEM')
12ce78e0c9002dd8cd0b136563ad81ab05817ff7
9,149
def get_edge_angle(fx,fy): """エッジ強度と勾配を計算する関数 """ # np.power : 行列のn乗を計算 # np.sqrt : 各要素の平方根を計算 edge = np.sqrt(np.power(fx.astype(np.float32),2)+np.power(fy.astype(np.float32),2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-5) angle = np.arctan(fy/fx) return edge,angle
80c7acc05867b6443aa7b4643d75d4fb79e792a9
9,150
def write_site_pair_score_data_to_file(sorted_data_list, output_file_path, algorithm_used, max_iterations=None, num_threads=None): """Since site indices are starting from zero within python we add one to each of them when they are being written to output file. """ formater = '#' + '='*100 formater +...
5ee4ec97fbc1b6f86e36946ee6d925604858b063
9,151
def cs_2tuple_list(value): """ Parses a comma separated 2-tuple strings into a python list of tuples >>> cs_2tuple_list('') [] >>> cs_2tuple_list('(foobar, "test")') [('foobar', 'test')] >>> cs_2tuple_list('(foobar, "test"), ('"'barfoo', "' lalala) ') [('foobar', 'test'), ('bar...
f6d5b5d440ef524c9c2f2c79f410c432229a8099
9,152
def expectatedCapacityFactorFromDistribution( powerCurve, windspeedValues, windspeedCounts): """Computes the expected capacity factor of a wind turbine based on an explicitly-provided wind speed distribution """ windspeedValues = np.array(windspeedValues) windspeedCounts = np.array(windspeedCounts) ...
fbcea908265cfbfcd9eb49632ac1027538417bfe
9,153
import os def check_icon_arg(src, default): """ Checks if icon arguments are valid: either a URL or an absolute path. :param src: Source of the icon :param default: default value of the icon :return: src (possibly pre-pended with "file://") """ if src != default: # check if URl ...
33db8c760df0bdf5e26474cdc281e4d6504cca27
9,154
def setup_2d_em_pic(): """ Returns a 2D electromagnetic PIC for testing """ params = { "length": [2 * np.pi, 2 * np.pi], "cells": [32, 32], "dimensions": 2, "nppc": 10, "single_stream": { # defaults for single stream instability "stream_v": ...
136e8e83b63329866dc4c547075dcfd603279de6
9,155
def young_laplace(Bo,nPoints,L): """ Bo = float - Bond number nPoints = int - number of integration points desired L = float - final arc length for range of integration """ #integration range and number of integration points s1=L N=nPoints #set initial values ...
80ceaf8d66e4c309a9f0c16e329c90a26a9b43a0
9,156
import torch def get_uncertain_point_coords_on_grid(uncertainty_map, num_points): """ Find `num_points` most uncertain points from `uncertainty_map` grid. Args: uncertainty_map (Tensor): A tensor of shape (N, 1, H, W) that contains uncertainty values for a set of points on a regular H...
a9d622c232f22359ac030679a49ed6f36345623c
9,157
def amex_credit_card(input_filename, month): """Format is just contents. date, description, amount""" test = _make_month_test(0, month) def transform(xs): return [xs[0], xs[1], '-' + xs[2] if xs[2][0] != '-' else xs[2][1:]] return _csv_transform(input_filename, test, trans...
c60bedd7b0afeda40e1fe9a34e27b0fd796f25f2
9,158
def loadf(file_like, *args, attributes=None, **kwargs): """Read a data file and load it -- scaled -- in memory. This function differs from `read` in several ways: * The output data type should be a floating point type. * If an affine scaling (slope, intercept) is defined in the file, ...
528c11132a83b7d341bb9688a75a4483aa59c155
9,159
import os def download_if_not_exists(filename, url): """ Download a URL to a file if the file does not exist already. Returns ------- True if the file was downloaded, False if it already existed """ if not os.path.exists(filename): down_load_file(filename, url) retu...
3954b8910248409fcfa1a41c1f28831e3a3fa210
9,160
from typing import List def _backsubstitution(A: MatrixData, B: List[float]) -> List[float]: """ Solve equation A . x = B for an upper triangular matrix A by backsubstitution. Args: A: row major matrix B: vector of floats """ num = len(A) x = [0.0] * num for i in range(num - ...
789c94842da2b751008e47a1ef661abeaded2da7
9,161
def deiterize(func): """The inverse of iterize. Takes an "iterized" (a.k.a. "vectorized") function (i.e. a function that works on iterables), and That is, takes a func(X,...) function and returns a next(iter(func([X], ...))) function.""" return Pipe(wrap_first_arg_in_list(func), iter, next)
7ef4786ec858f1cbd8fb79b8cfee0e4b03bcb33c
9,162
def ecg_data(rdb, day, patient, time): """ Returns DatFrame to plot ecg signal """ sql = """SELECT * FROM ECG where "Day"='{0}' and "Patient"='{1}' and "Date"::time='{2}' """.format(day, patient, time) try: df = pd.read_sql(sql, rdb) except: df = pd.DataFrame() return df
4a384f920c0fdf45e1818633d2ef125a29b4a562
9,163
def evaluate(data_set_file_or_name, data_format=None, data_directory=None, map_features=None, feature_selection=None, example_filter=None, noisy_preprocessing_methods=None, preprocessing_methods=None, split_data_set=None, splitting_method=None, splitting_fraction=None...
399411ca9560d9e48e73846c9fb70898f028f90a
9,164
def deploy_new_company(company_id): """ Deploy new company contract :param company_id: Company off chain id for deploy :return: True in case of successful, false otherwise """ try: instance = Company.objects.get(pk=company_id) except Company.DoesNotExist: logger.error('Compan...
3871f2ae9948001a1fe24a4c4d2791b7d12f79d7
9,165
import random def MEMB(G,rb,cycle=0): """ It returns a dictionary with {box_id:subgraph_generated_by_the_nodes_in_this_box} The box_id is the center of the box. cycle: Ignore this parameter. Use the default cycle=0. """ adj = G.adj number_of_nodes = G.number_of_nodes() covered_nodes = ...
dfe522aa1e6140e98d32d2eee039aec366d76a8d
9,166
import os from pathlib import Path from getpass import getuser def set_app_path(required=False): """Find app directory and set value to environment variable.""" matched_path = None config_paths = (Path.home() / "hyperglass-agent", Path("/etc/hyperglass-agent/")) for path in config_paths: tr...
15298cb0a745ee8a4f4b4be8623df0dab08c685a
9,167
def shownames(namespace, **args): """helper method to generate a template keyword for a namespace""" ctx = args['ctx'] repo = ctx.repo() ns = repo.names[namespace] names = ns.names(repo, ctx.node()) return showlist(ns.templatename, names, plural=namespace, **args)
29105570ad822975c69c7b1d30b94e368d554873
9,168
def only_half_radius( subsampled_radius: float, full_diameter: float, radius_constraint: float ): """ Check if radius is smaller than fraction of full radius. """ assert 0.0 <= radius_constraint <= 1.0 return subsampled_radius <= ((full_diameter / 2) * radius_constraint)
565c301932d5445e8bbb594085e65df63814663a
9,169
def complete_from_man(context: CommandContext): """ Completes an option name, based on the contents of the associated man page. """ if context.arg_index == 0 or not context.prefix.startswith("-"): return cmd = context.args[0].value def completions(): for desc, opts in _pars...
4312ff8323a72a405737a8476cb7ad541dbff718
9,170
def sanitise_description(original: str) -> str: """ Remove newlines from ticket descriptions. :param original: the string to sanitise :return: the same string, with newlines as spaces """ return original.replace("\n", " ")
741aa7df758fb342a0d9a0fa182d24a643f5dbbc
9,171
def dnsdomain_get_all(context): """Get a list of all dnsdomains in our database.""" return IMPL.dnsdomain_get_all(context)
fc7bde05cdb35f60c30943f1ebebdb4217af9467
9,172
def mockselect(r, w, x, timeout=0): # pylint: disable=W0613 """Simple mock for select() """ readable = [s for s in r if s.ready_for_read] return readable, w[:], []
920810aea2f7813885805011d646ddaabfd1901c
9,173
import os def load_imgs(path): """Given a path load image(s). The input path can either be (i) a directory in which case all the JPG-images will be loaded into a dictionary, or (ii) an image file. Returns: imgs: A dictionary of of n-dim images. Keys are the original filenames """ #...
149df70018133d29dcc9089a9c7f2fff064a5e44
9,174
def solve_5c2c9af4(x): """ Required Transformation: The input contains 3 cells with non-zero value. The non-zero valued cells are diagonally positioned with some amount of gap between each non-zero valued cells. The program should identify the colour and their position in the grid and form a squared box...
fcb9701c4bccabe237481ed2acd052b7501abd3f
9,175
def kernel_primitive_zhao_vec(x, s0=0.08333, theta=0.242): """ Calculates the primitive of the Zhao kernel for given values. Optimized using nd-arrays and vectorization. :param x: points to evaluate, should be a nd-array :param s0: initial reaction time :param theta: empirically determined cons...
26cd9230e23f4217ec5a7eee2e8522bef0a40c4e
9,176
from io import StringIO import sys def capture_output(function, *args): """ captures the printed output from a function """ @contextmanager def captured_output(): new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.s...
d740030ff3678aed247bb8fb29e636e0fd32b3a6
9,177
def scaled_dot_product_attention(q, k, v, mask): """Calculate the attention weights. q, k, v must have matching leading dimensions. k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v. The mask has different shapes depending on its type(padding or look ahead) but it must be b...
94498a5fd499a09e24a964a6ac975420d702c536
9,178
import sys import re def cvCascades(argv=sys.argv[1:]): """Control the OpenCV cascade Examples. Please see :meth:`cv2ArgumentParser <pycharmers.utils.argparse_utils.cv2ArgumentParser>` for arguments. Note: When you run from the command line, execute as follows:: $ cv-cascades --cam 0 --...
e28a03386e2b38e0f8e9984bac3e4946ea2598dc
9,179
from typing import List from typing import Any from datetime import datetime def extract_data(state: str, data) -> List[List[Any]]: """ Collects """ try: extracted = [] for sample in data['_return']['traces']: for obs in sample['trace']: # TODO-Detail ...
eab79571c4dea5d97790031251862d389260c7bf
9,180
from typing import List def merge(input_list: List, low: int, mid: int, high: int) -> List: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.app...
0d53b0670899b4853563c9dda0eb47a8c66bae00
9,181
def fc_caps(activation_in, pose_in, ncaps_out, name='class_caps', weights_regularizer=None): """Fully connected capsule layer. "The last layer of convolutional capsules is connected to the final capsule layer which has one capsule per output class." We call ...
eb190d36c718d0c518b12c172e2a13b49d7ba012
9,182
def get_optional_relations(): """Return a dictionary of optional relations. @returns {relation: relation_name} """ optional_interfaces = {} if relation_ids('ceph'): optional_interfaces['storage-backend'] = ['ceph'] if relation_ids('neutron-plugin'): optional_interfaces['neutron-...
bdb1dcd04cfd31130e5463772d3d31f8aac7d894
9,183
def splitmod(n, k): """ Split n into k lists containing the elements of n in positions i (mod k). Return the heads of the lists and the tails. """ heads = [None]*k tails = [None]*k i = 0 while n is not None: if heads[i] is None: heads[i] = n if tails[i] is not...
a4a1885ce0c9541c534145d0236996a511cbdd00
9,184
import os def dirname_to_prefix(dirname): """Return filename prefix from dirname""" return os.path.basename(dirname.strip('/')).split("-", maxsplit=1)[1]
8e1124e66669dd051987c55812052d36c78bdc4a
9,185
def find_flats(flats, flat2_finder=find_flat2): """Find flat pairs.""" file1s = sorted([item.strip() for item in flats if item.find('flat1') != -1]) return [(f1, flat2_finder(f1)) for f1 in file1s]
7003bc35ef0ed6a4fe71b1d686b7c46b99e6d8ca
9,186
def binary_accuracy(a,b): """ Calculate the binary acc. """ return ((a.argmax(dim=1) == b).sum().item()) / a.size(0)
5f9b09199b2e88169a0cbe9ee7cb4bb351c09e4a
9,187
def add_ice_post_arrow_hq_lq_arguments2(parser): """Add quiver QV threshold to mark an isoform as high-quality or low-quality.""" # if isinstance(parser, PbParser): # #parser = _wrap_parser(parser) # arg_parser = parser.arg_parser.parser # tcp = parser.tool_contract_parser # tcp....
f2fabe409df095be26b4085ccbd635e4ab6ce88a
9,188
def dev_step(tset, train_m, test_m, net, dataset, args, nd_possible_rating_values): """ Evaluates model on a dev set """ batch_size = 256 #print("tset:",tset) user_te = np.array(list(tset.keys())) #print("user_te:",user_te) user_te2 = user_te[:, np.newaxis] #user_te2 = user_te l...
73c77d15d4221a0116454e06f3d7823ffc66a323
9,189
def email_change_view(request, extra_context={}, success_url='email_verification_sent', template_name='email_change/email_change_form.html', email_message_template_name='email_change_request', form_class=EmailChangeForm): """All...
1b54394a04d07bea0d121574b71ba6a1a840f401
9,190
def check_is_pair(record1, record2): """Check if the two sequence records belong to the same fragment. In an matching pair the records are left and right pairs of each other, respectively. Returns True or False as appropriate. Handles both Casava formats: seq/1 and seq/2, and 'seq::... 1::...' an...
225cd65d8c33968556c04a67ba304ebbc65ad4f2
9,191
import bz2 def decompress_bzip2_from_hdu(hdu): """Decompress data in a PyFits HDU object using libz2. """ data = hdu.data.field(0) source_type = np.dtype(hdu.header['PCSRCTP']) return (np.fromstring(bz2.decompress(data.tostring()), dtype=source_type), numpy_...
0fb99decefdc70ae082728c2d5b1228f79d13264
9,192
def grid_values(grid): """ Convert grid into a dict of {square: char} with '123456789' for empties. Args: grid : string A grid in string form. Returns: grid : dict Keys are the boxes (e.g., 'A1'). Values are the values in each box (e.g., '8'). ...
560fb700d6fc91b3ab94c2a5573a82d92ac4eb9d
9,193
from typing import List import re def get_ftp_files(build_type, tag_name, config) -> List[ReleaseFile] : """! @brief Gets file metadata for nightlies hosted on FTP, as determined by config["ftp"] attributes @param [in] `build_type` Unknown str @param [in] `tag_name` Github tag name of the relea...
f56bc55df5a7880f215c3ebd0a1eeb6796840798
9,194
def variables(i, o): """ WRITEME :type i: list :param i: input L{Variable}s :type o: list :param o: output L{Variable}s :returns: the set of Variables that are involved in the subgraph that lies between i and o. This includes i, o, orphans(i, o) and all values of all intermedia...
18f07280dae8471cd9c4f447061342d733e7b3c7
9,195
def new_instance(): # display_callback=None): """ Create a new instance of Ghostscript This instance is passed to most other API functions. """ # :todo: The caller_handle will be provided to callback functions. display_callback=None instance = gs_main_instance() rc = libgs.gsapi_new...
abc87b413f26366ae91c7f30b84332e81f55c095
9,196
def ldns_resolver_dnssec_cd(*args): """LDNS buffer.""" return _ldns.ldns_resolver_dnssec_cd(*args)
eeaa2f7e7d385d64c575926f93247ad44594d09e
9,197
def spf_record_for(hostname, bypass_cache=True): """Retrieves SPF record for a given hostname. According to the standard, domain must not have multiple SPF records, so if it's the case then an empty string is returned. """ try: primary_ns = None if bypass_cache: primary_...
5013285bb291a22d8ce2565dd605b16b9c730bba
9,198
import os def raw_to_df( rawfile: os.PathLike, n_channels: int = 2048, fmt: np.dtype = ">i8", order: str = "F", ) -> pd.DataFrame: """Read a binary raw data file, and returns a dataframe.""" bin_raw = read_file(rawfile, "rb") dt = np.dtype(fmt) np_data = np.frombuffer(bin_raw, dtype=dt...
56abdf1e3e1aedaa3d2f3ef3f8e87dff05740f29
9,199