content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import glob def collect_factories(rootpath): """ Will collect (recursively) and return all factories found under given root path """ factories_collected = {} # <factory name> : <factory class> factory_files = glob.glob(f"{rootpath}/**/factories.py", recursive=True) for factory_file in factor...
73563107e620d5c6d6419600ebf51bc267710cca
3,615,432
def _get_hop_2_neighbours(graph, input_list: list, hop_n: int) -> list: """ Find hop_n neighbours of each item in input_list :param graph: NetworkX graph object :param input_list: Input list :param hop_n: Hop hop_n :return: hop_n hop neighbours of the input list's items """ full_list = ...
a51f1286aec2719b72665e35fec29d7d2b93b38e
3,615,434
import asyncio def create_worker(host='localhost', port=4730, loop=None): """XXX :param host: :param port: :param loop: :return: """ loop = loop or asyncio.get_event_loop() conn = yield from create_connection(host=host, port=port, loop=loop) return GearmanWorker(conn)
8ee679baf652476f520df75b3dc4fa3bf6728031
3,615,435
import re def prepare_template_data(fill_pairs): """ Prepares formatted data for filling template. It produces mutliple variants of keys (key, Key, KEY) to control format of filled template. Args: fill_pairs (iterable) of tuples (key, value) Returns: ...
a6082093bcbe39ba429decd2735fb2797c6c11dd
3,615,436
def get_tokens(): """ Returns a tuple of tokens in the format {{site/property}} that will be used to build the dictionary passed into execute """ return (SECURITY_ENABLED_KEY, KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY, HIVE_PRINCIPAL_KEY, HIVE_PRINCIPAL_KEYTAB_KEY, HIVE_USER_KEY, STACK_ROOT, LLAP_APP_NAM...
6c05f16b3707d31af797fdb7bfc65fe8a1b78482
3,615,437
def largest_cc(mask): """ Return the largest connected component of a 3D mask array. Parameters ----------- mask: 3D boolean array 3D array indicating a mask. Returns -------- mask: 3D boolean array 3D array indicating a mask, with only one connected component. """ ...
617d7a1474ab6b7a5a9ad6393c942cb874d49744
3,615,438
def _expand_to( a: tp.Union[np.number, np.ndarray, Variable], ndim_or_shape: tp.Union[int, tp.Tuple[int, ...]], axis: tp.Union[None, int, tp.Tuple[int, ...]] = None, keepdims: bool = False, ) -> tp.Union[np.ndarray, Variable]: """Return expanded array. Parameters ---------- a : tp.Tuple...
fe1c979ba9c5c781edc4a525c0b87a13b0d39f8d
3,615,439
def get_feedback_average(action): """returns the average feedback rating for the given action.""" return ActionFeedback.objects.filter( action=action).aggregate(avg=Avg('rating'))['avg'] #query_set = get_action_feedback(action) #total = 0 #for i in xrange(1, 6): # total += query_set....
f42125f7fdf7d3f8ee3ef97fe34fbb7f40567cb8
3,615,440
def display_method_to_choose_etfs(selected_method_choose_dates, all_etfs, etf_data, sl_obj): """ Generates various streamlit options for selecting which ETFs to display. Parameters ---------- selected_method_choose_dates : list of str Strings of the various methods of selecting ETFs. al...
6f2c65a5472b445dcdeb921d10c8c13397ef5d97
3,615,441
def cband(): """Pre-define idealized critical band filter bank. :return: idealized critical band filter bank """ return np.array( [ 0, 100, 200, 300, 400, 510, 630, 770, 920, ...
1648adff3d9dce05be2f4879e34d4a6aa9acc8f2
3,615,443
def get_power_spectrum(array): """Calculate DFT and power spectrum from the given array. :param array: a 2D array :return: DFT array and the power spectrum """ fourier = np.fft.fft(array) power = abs(fourier)**2 return fourier, power
14066876f7b0d4925477e96301def89fc856b1b4
3,615,444
import scipy def compute_intensity_features(im_label, im_intensity, num_hist_bins=10, rprops=None): """ Calculates intensity features from an intensity image. Parameters ---------- im_label : array_like A labeled mask image wherein intensity of a pixel is th...
9a064d70028417f83368083fc488939a17aa747f
3,615,445
from pathlib import Path from typing import Callable from typing import Any def readFileLines(filepath: Path, f: Callable[[str], Any] = str) -> list: """Reads the lines in a file Args: filepath (Path): The path of the file to be read. f (Callable[[str], Any], optional): Transformation for the lines. ...
21df2445f6132085d7da36276f371170ff0f2a4e
3,615,446
def get_default(arr, idx, default_value): """get arr[idx] or return default_value """ try: return arr[idx] except IndexError: return default_value
038b943da7fa1d36038444880264160da8e031f4
3,615,447
def chat_words_conversion(text): """ converts common chat acronyms into it's fully spelled out phrase """ new_text = [] for w in text.split(): if w.upper() in chat_words_list: new_text.append(chat_words_map_dict[w.upper()]) else: new_text.append(w) retur...
5d97ce53a2103190ff0abb585e62923c0fad8f21
3,615,448
def second(xs): """ Returns the second element of a list, or None if the list is empty """ if not xs: return None return xs[1]
e5a915116d61e01842f86623aafcf6e2e6c8b5a3
3,615,449
import logging def get_logger(module: str, file: str) -> logging.Logger: """Configure a file logger for use in a script. Parameters ---------- module : str The name of the module from which the logger is called file : str The name of the log file to which the logger will write ...
c9a68d216ca9a04ccb208dd546621e051dd37e36
3,615,450
def filled_grasp_grid(empty_grasp_grid, grid_file): """Return a GraspGrid instance filled from the grid_file.""" empty_grasp_grid.read(grid_file) grid_file.close() return empty_grasp_grid
97ed623c09b9d42642a208451b004e5bec4910ed
3,615,451
import warnings def calculate_boot_stats(sample, rep, n="auto", level=0.95, estimator="mean", random_seed=None, pass_dist=False): """Calculates a bootstrapped confidence interval for a sample. A bootstrapped confidence interval for the desired estimator for the provided sample is calculated for a confide...
354cf103105f3bc22decb3b27cbab694f7a7d9c9
3,615,452
import pickle def get_camera_params(): """ Return a default camera parameter matrix """ pickle_in = open("config.pickle", "rb") data_dict = pickle.load(pickle_in) return data_dict['mtx'] # return np.array([[800, 0, 320], [0, 800, 240], [0, 0, 1]])
51292054e8db77058ea37b2dbe06bf105183969b
3,615,453
def _distributed_edge_access(g, edges, issue_remote_req, local_access): """A routine that fetches local edges from distributed graph. The source and destination nodes of local edges are stored in the local machine and others are stored on remote machines. This code will issue remote access requests fir...
1217fcce3a7b1256587298ec266627caa208c28b
3,615,454
def check_letters(): """ Check if all letters from input is in other string """ word = input("Give me a word: ").lower() letters = input("Give letters to check for in word: ") for l in letters: if l not in word: print("No match") return 0 print("Match")
4c419e5c3c70c383d06079ead7e105b38e6ca91e
3,615,457
def case_json(ses): """ returns a list of JSON fomratted output for case object """ return _get_case_json(ses, '/case')
00447375c926521001f0b3039251a86ce6bc1336
3,615,458
def bernoulli_action_log_prob(logit, action): """Calculate the log p of an action with respect to a Bernoulli distribution. Use logit rather than prob for numerical stability.""" if action == 0: return F.logsigmoid(-logit) else: return F.logsigmoid(logit)
a1974fbe2d12fe878f875c5e1364cf3cc36d676c
3,615,459
def get_1d_coords(p, i, j): """ Finds index of site in 1d chain from 2d lattics based on snake decomposition, ie 1d coords on 2d lattice look like: 0, 1, 2, 3, 7, 6, 5, 4, 8, 8, 10, 11 Args: p - dictionary that contains the relevant system parameters i - row index...
2852ec9d57c99f922380fc8b671bdd757e8decf4
3,615,460
def unpack_offset(msr_response): """ Extract the offset component of the response and unpack to voltage. >>> from undervolt import unpack_offset >>> unpack_offset(0x0) 0.0 >>> unpack_offset(0x40000000000) 0.0 >>> unpack_offset(0x100f3400000) -99.609375 """ plane_index = int(m...
408ba805fe92fbc0c7fd4498d2e16d6701180eb3
3,615,461
def check_early_stop( perf_history, minimum_length=20, short_history=3, long_history=5, fail_function=np.less_equal): """ Determine whether to stop early. Using deepgaze criteria: We determine this point by comparing the performance from the last three epochs to ...
f730004bf4cbac1cfd12e260bdc8240193c4197d
3,615,462
import math def getAngle(v1,v2,prec=1E-6): """ Helper function to get angle between two vectors inputs -------- v1,v2 (list,list): two vectors outputs -------- angle (float, radians): angle between v1,v2 """ return(math.acos((np.dot(v1,v2))/np.l...
19e54f1bdd3b2ea95e77188eb383f98e6300d5ce
3,615,463
def evaluate_cdr_hit(query, target, result={}, same_length=False): """ Compare query and target sequence positions in CDR3 and framework regions, return number of matches and % identity If previous 'result' is provided, return (None, None) if an improvement has not been found. """ if same_lengt...
1cc292c28ea5209f01cae9472cf20a13cf0864fa
3,615,464
from typing import Sequence import random def make_burst_emitter( center_xy: Point, filenames_and_textures: Sequence[FilenameOrTexture], particle_count: int, particle_speed: float, particle_lifetime_min: float, particle_lifetime_max: float, particle_scale: float...
63a2b4cc0975f03711dc4824e8cdf431e3d61db6
3,615,465
import ctypes def cusolverDnSsyevd_bufferSize(handle, jobz, uplo, n, a, lda, w): """ Calculate size of work buffer used by culsolverDnSsyevd. References ---------- `cusolverDn<t>gebrd <http://docs.nvidia.com/cuda/cusolver/index.html#cuds-eigensolver-reference>`_ """ lwork = ctypes.c_int(...
a16df1725e6db9471836bf517e7efa977c50fdf7
3,615,467
from typing import Dict def get_github_repo_url(project_urls: Dict[str, str]) -> [str, None]: """ Get repo url for github. :param project_urls: project urls to get github repo url from :return: repo url if one is available, else None """ source_code_url = get_attribute(project_urls, ["Source ...
358f35544c50ad65c7f276a2fdbdbf1abb91f039
3,615,468
import json def abrir_freq(file): """ Abre o ficheiro json com o dicionário das frequências das regras. :param file: ficheiro json :return: dicionário com as frequências das regras no corpus. """ with open(file) as f: freq_svo_dict = json.load(f) return freq_svo_dict
b1cbb7c98146cf72390b511428d7734881f0b944
3,615,469
def update_user_phone(): """ 用户修改电话号码 """ userid = g.userinfo.get("id") requstsData = request.get_json() phone = requstsData.get("phone") code = requstsData.get("code") if phone and code: dbres = db.query("select id,code from tb_sms_log where phone = '{}' and status = '0' and c...
1b7fb8763a35f9fc2e221e4c03788b3827bd7a67
3,615,470
import common.api as api import base64 def file_update_complete_response( volume, reply ): """ Sign a protobuf ms_reply structure, using Syndicate's private key """ # sign each directory entry in the reply with the Syndicate key, # so the MS attests to its index information for ent_pb in reply.l...
607b9fe4f155b39de72c5c8d9dafcd1ba8bfe7ce
3,615,472
def destructure_decorated_lambda(tree): """Get the AST nodes for ([f, g, h], lambda) in f(g(h(lambda ...: ...))) Input must be a tree for which ``is_decorated_lambda`` returns ``True``. This returns **the original AST nodes**, to allow in-place transformations. """ def get(tree, lst): if t...
1c7a63fb7497a26f5a841556dbdb1114880c7388
3,615,473
from datetime import datetime def get_data_type(v): """ Infers type from value. Returns tuple of (type, value) """ if isinstance(v, datetime.datetime): return ("date", msecs_since_epoch(v)) elif isinstance(v, bool): return ("boolean", str(v).lower()) elif isinstance(v, float): ...
8e6d65ca328859e4b9c6a1493cf732e4a9b17c64
3,615,474
def replace_around(i, l, r, f_nones=True): """Replace the three elements centered at i with r.""" if f_nones: r = filter_nones(r) return l[: max(i - 1, 0)] + r + l[i + 2 :]
4e1c6b002714b07385f5f4871ca001aa956b3e06
3,615,475
def dictionariesToDataframe(): """converts dictionaries on CSPP holdings to dataframes return: - [holdingsECB, holdingsECBDates]""" matrixData = [] # 2D array with row per ISIN and columns for different data for ISIN, dataInDictionary in dictionaryBondsECB.items(): item = [ISIN] + dat...
8fa2afd551d337e52808cbecac4ec411cfb7360f
3,615,476
def get_model_parameters(model): """Extract model arguments that were used during training""" params = ModelParameters() names = [layer.name for layer in model.layers] params.num_codes = model.get_layer(name='embedding').input_dim-1 params.emb_weights = model.get_layer(name='embedding').get_weights...
b216b3d8f010d33f767e76252d1422ffa778b4df
3,615,478
def transpone(l): """transpones a list of multiple lists if the entrys do not have the same length, an empty string will be put in their place""" nestedlist=[] length=[] transponedlist=[] for i in range(len(l)): length.append(len(l[i])) for i in range(max(length)): for j in...
27d904910be743d4116fba5ba7479cfdc62ec18b
3,615,479
def to_df(records_tree, event_name, instrument_name): """ Converts a `get_records_tree()[event][instrument]` to a pandas DataFrame """ # get instrument records records = records_tree[event_name][instrument_name] # build dataframe rows from records acc = [] for s, entries in records.item...
91805a4878eedeab3d5efdb1a4277966728543f3
3,615,480
def compare(value1, value2, comparison): """ Compare 2 values """ if isnum(value1) and isnum(value2): comparison = comparison.lower() if comparison == 'equals': return value1 == value2 elif comparison == 'not equal': return value1 != value2 elif co...
49c6c3806224f864670f8078733d2baeea653792
3,615,481
def get_minsep_range(minseps, cap=None): """ Create ranged minseps from an ensemble of minsep entries Args: minseps (list): A list of minsep dictionaries cap (tuple): Minimum-maximum caps Returns: minsep (dict): A minsep where values are minimum and maximum values """ ...
e60392fa70f7f2b0989f4894ce90c7bd78aac7d2
3,615,482
def ga_exp(B, verbose = False): """ This is an expansion of the exponential of a general rotation and translation Presented by R. Wareham (Applications of CGA) B must be a general rotation object on the format $ \phi*P + t n_{\inf}} $ $P$ is a 2 blade in real space. $$\phi \in \mathcal{...
3abcadbcffe625bf473d28d5698fbf94e1d3318a
3,615,483
import tqdm def get_progress_bar(percentage, increment): """Get a progress bar string given a percentage.""" initial = percentage total = 100 bar_format = generateProgressbar( percentage) + "\n" + "{percentage:04.1f}%" + f"[{increment:+03.1f}]" with tqdm(initial=initial, total=total, bar_...
29957960090063903d1f231dd5f41532691dd05b
3,615,484
def elsym(edgelen, order=1): """ Elementary symmetric polynomial of a given order """ l = len(edgelen) if order == 0: return 1 r = 0 for v in combinations(range(l), order): r += np.product([edgelen[vv] for vv in v]) return r
6939704c2bfcec935e762d23a1cb05f2cd8c593f
3,615,485
def shorturl(request, key): """ Redirect the client. """ return redirect(get_object_or_404(ShortURL, pk=key).url)
7f6700215f8cc60f5e090fa3ef1a3d4e7035ff6e
3,615,486
import itertools def group_by_day(list_all_objects): """ Recebe uma lista de objetos onde cada um deles possui um atributo tipo date e logo ordena eles por dia. :param: list_all_objects: Register.objects.all(): django.db.models.query.QuerySet :return: objects_day_ordered: [[objetos_do_dia_1][objetos_d...
39feb54a2232e9e7a0965b72f2c6eb2509c7b610
3,615,487
def get_root_model(models): """ Get a root model class from an iterator over `obj_tables.Model` classes The root model is obtained by name, rather than from `core.Model`, because `models` may have been obtained from `obj_tables` migration, which loads other versions of `wc_lang.core` in private imports...
aabe0e445ff96036008eddc4c2127516554a4adc
3,615,489
def datetime_to_iso(date, only_date=True): """ Convert datetime format to ISO 8601 time format This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format, e.g. ``2017-09-14`` :param date: datetime instance to convert :type date: datetime :param ...
676a7e65de2c9e4de60cfe8d832ab342aa46af4f
3,615,490
def _copy_agave_agave(src_uri, dest_uri, agave): """ Copy Agave data using AgavePy Wrapper. Args: src_uri: Source URI parsed into dict with URIParser. dest_uri: Destination URI parsed into dict with URIParser. agave: dict that contains: agave_wrapper: Agave wrapper objec...
0dd5e5627cd4adc87b83b22cb63e5eda1f3dae11
3,615,491
def load(path_or_strm, container, **opts): """ :param path_or_strm: input config file path or file/file-like object :param container: callble to make a container object :param opts: keyword options passed to :class:`configobj.ConfigObj` """ return container(configobj.ConfigObj(path_or_strm, **op...
cccc2d780ab7d16996ac9b6658550773b307a4df
3,615,493
import numpy def default_unexpected(x): """Define unexpected values.""" large = 1.e3 small = -numpy.float('inf') return (x is None) or x > large or x < small or numpy.isnan(x)
4afe63f1969b568c691fcc4e4fbfa91ace53fdfb
3,615,494
def predict_hot_pxl(sqr, model): """takes a numpy array (colour image) size 64x64 and a ML model, returnes float number between 0 - 1 for hot pixel detection, for 0 no hot pixel detected, 1 hot pixel detected""" predict = model.predict(sqr.reshape(1,64,64,3)) y_pred = [i[0] for i in predict] ret...
e533c2b27df280f0f62b2727b1dd960a828fdee0
3,615,495
import traceback def write_to_file(file_name, dir_path, content): """ Rewrite or create and write to file. Parameters: file_name (string): file name dir_path (string): root path which file contains content (string): content to be written ...
b3ade139d6455f57e54d3ae03ab4988dc5718644
3,615,496
from typing import Tuple from typing import Optional from typing import Dict def _build_meta_block( payload_spec: PayloadSpec, ) -> Tuple[Optional[Block], Block, Dict]: """ Performs validations in the meta specification and returns o Args: payload_spec (dict): Payload specifications. Ret...
33ae726c2c73e964c8e157b00cb1a417446b7b9a
3,615,497
def _unit_state_progress(uid, current, target): """ This method will ensure a unit state progression in sync with the state model defined above. It will return a tuple: [new_state, passed_states] where 'new_state' is either 'target' or 'current', depending which comes later in the state model, and ...
6549118b894a3f475200e08b74a4042f4b75c805
3,615,498
from typing import List from datetime import datetime def search( bounds: List[float], min_cloud: float = 0, max_cloud: float = 100, min_date='2013-01-01', max_date=datetime.today(), period: str = None, period_qty: int = 1, stac_collection_limit: int = 5...
a807308439d1ba3ce2a52890f7da43f2b6a831a4
3,615,499
import itk def get_label_object_attributes(dataset, progress_callback=None): """Compute shape attributes of integer-labeled objects in a dataset. Returns an ITK shape label map. An optional progress_callback function can be passed in. This callback is expected to take one argument, a floating-point number...
bcf7e813492c94d132bd716f482c36709e540240
3,615,500
from aiida.orm import StructureData def generate_structure(): """Return a ``StructureData`` representing either bulk silicon or a water molecule.""" def _generate_structure(structure_id="Si"): """Return a ``StructureData`` representing bulk silicon or a snapshot of a single water molecule dynamics. ...
7fc610d9dcb36e56953c98fcd4e067c6db33fd5b
3,615,501
def get_lat_bin(lat, nbins=NBINS): """ get latitude bin """ if lat < LATLIM[0]: return 0 if lat > LATLIM[1]: return nbins return int((lat-LATLIM[0]) * nbins / (LATLIM[1]-LATLIM[0]))
cc6f67f0c9afb209416caa43b101c5a5174bfd43
3,615,502
def get_aff_trafo(xy0=None, xy1=None, theta=0, por=(0, 0), ax=None, patch=None): """ :param xy0: current position of the object, if not provided patch.get_xy() is used :param xy1: desired position of the object :param theta: rotation in degrees :param por: point of rotation relative to the objects ...
958249e940bf21cc10c68d2e2b7142d0fee62e15
3,615,503
from typing import Dict from typing import Any from typing import cast def get_sig_alg(sig: key.Signature) -> Dict[str, Any]: """ Create `SignedDigestAlgorithm` structure. """ if sig.meta.algorithm == key.AsymmetricAlgorithm.RSA: return get_sig_alg_rsa(cast(rsa.RsaSignature, sig)) if sig....
02a244ff0a8c67027a29c827e4101598a19fa455
3,615,504
def descendants(node, lst=None): """Return a list of all the descendants beneath a node""" if lst is None: lst = [] for child in node.children: lst.append(child) descendants(child, lst=lst) return lst
5fe6fb9d9fbfd63bbeb161fdbe1d0e54d20edf9e
3,615,506
def read_uncompressed_dataset(file): """ Get a file path and return the uncompressed dataset""" try: return pd.read_pickle(file) except: try: return pd.read_csv(file) except: print("%s cannot be read" % file) return
61accb9fa81e59b4b1324c40b567a5ce4e718fa6
3,615,508
def _run_reformulator_eval(questions, annotations, reformulator_instance, environment_fn, batch_size): """Runs eval with just the reformulator, using greedy decoding.""" f1s = [] for (questions_batch, annotations_batch) in batch(questions, annotations, ...
0ba54ac97a0f33bf7a0c77c968036c01d946ea3e
3,615,509
def _get_single_node_name_from_collection(meta_graph_def, collection_key): """Obtain a node name that is the single element of a collection.""" if collection_key not in meta_graph_def.collection_def: return None collection = meta_graph_def.collection_def[collection_key] if not collection.node_list.value: ...
160ddf3f178f69fe31cfa8301516395f46ee6740
3,615,510
def test_create_plots_create_matrix_deletion_raw_count(): """ """ #ref_seq, total_dels, total_ins, cov = crispr_count_indels._count_indels("15_dels_ladder_for_matrix.fasta") ref_seq, ref_seq_id = count_indels._get_ref_seq("15_dels_ladder_for_matrix.fasta") cov = count_indels._get_coverage("15_d...
473d86545ff3669279e7e5aed65b0fe920eef48c
3,615,511
def wire_mutual_inductance(wire_i, wire_j, ref): # di0: float, dj0: float, dij: float, rw0: float): """Inductance between wire i and wire j, with reference wire 0. Uses widely separated assumption, di0/rw > 4 """ if type(ref) == Wire: rw0 = ref.radius di0 = wire_i.distance_to(ref) ...
484027eca8864a4d66e78988d4f2580fbf12644b
3,615,512
from typing import Any from typing import Tuple def parl_to_kaldi_test_pairs(request: Any) -> Tuple[str, str]: """Return an embedded statement from the above list using given index.""" index: int = request.param return parl_to_kaldi_pairs[index]
5b830e2daf852358bafe2caf365438a3cd1301d0
3,615,515
def global_pairwise_align_protein(seq1, seq2, gap_open_penalty=11, gap_extend_penalty=1, substitution_matrix=None, penalize_terminal_gaps=False): """Globally align pair of protein seqs or alignments with Needleman-...
b2494fb60f5735eae0aa9d1eda0185884f905d92
3,615,516
import requests def client(api_client): """Returns HttpClient instance with retrying feature skipped.""" api_client = api_client(disable_retry_status_list={503, 404}) # This won't work with Httpx but will save us about 10 mins for this test alone api_client.session = requests.Session() return api_...
615756a81fd243d4d7495bafca4538e19775f7b4
3,615,517
def create_elem_dict(row): """ Create new element dictionary from row with metadata common to all nodes/ways/relations. """ elem = { 'id': row.id, 'version': row.version, 'userId': row.user_id, 'userName': row.user_name, 'timestamp': row.timestamp, 'ta...
d97b712cd4b0bc6e79f5aa09f212491d715f1c69
3,615,518
from typing import Dict from typing import Any from typing import Tuple from typing import Optional def source_ip_and_reverse_dns( message: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]: """ Extract the source IP and reverse DNS information from a canary request. """ reverse_dns, sour...
df2a9b6c4a177073fc019e88c33234f4d6124ccb
3,615,519
import typing def spark_flatMap(func: typing.Callable[[pyspark.rdd.RDD], pyspark.rdd.RDD]=default_function(1)): """Spark's flatMap :param Callable func: The function to apply. :input RDD data: The RDD to convert. :output RDD result: The resulting RDD. """ def inner(data: pyspark.rdd.RDD) -> R...
9f7d6fa9a18d844f6e0d140063ab0dc5684217a6
3,615,520
def fCO2_to_CO2(fCO2, Ks): """ Calculate CO2 from fCO2 """ return fCO2 * Ks.K0
2b71b46147291e7fffb99d51d0acb59ea4cd0c69
3,615,521
def summary_stats(tile_summary): """ Obtain various stats about the slide tiles. Args: tile_summary: TileSummary object. Returns: Various stats about the slide tiles as a string. """ return "Original Dimensions: %dx%d\n" % (tile_summary.orig_w, tile_summary.orig_h) + \ "Original Tile Siz...
8e36e9b10ec721cd567eccb54c9afecad13f2eea
3,615,523
def soundnet5_model_params(model_filename=None, num_classes=None, scope='SoundNet'): """ Load model parameters from Torch file. """ def retrieve_if_not_none(local_net, layer_num, var_name): return None if local_net is None else \ local_net['modules'][layer_num][var_name] def transpose_if_n...
305e06bbadb67b9beab060c1763e68423c64b393
3,615,524
def landsat457_cloud_mask_func(img): """Apply basic ACCA cloud mask to a daily Landsat 4, 5, or 7 image""" cloud_mask = ee.Algorithms.Landsat.simpleCloudScore(img).\ select(['cloud']).lt(ee.Image.constant(50)) return img.mask(cloud_mask.mask(cloud_mask))
50b01ef70f41be0788952c5e0ca2a55c8b6ccff5
3,615,525
def check_if_in_team(api, team_id, person): """ Checks if a person is in a given team :param api: CiscoSparkAPI instance to query Spark with. :param team_id: The ID of the team to check for :param person: The person to check against the team """ team_memberships = api.team_memberships.list(te...
b20a5ee41485b2dd397c7dd23407ef95d0f34e4a
3,615,526
def handle_public_events(iterable): """Report private repositories being made public, and new releases.""" lines = [] unused = iterable # Private -> Public Transitions events, unused = partition_type('PublicEvent', unused) for event in events: tmpl = 'made {} public' lines.appen...
7608bbf011729c2bf78a9c5a62e5061760aa50ae
3,615,527
def generate_sub_tetrahedrons(a, b, c, d): """ Generate sub-tetrahedrons. Returns tuple of tetrahedrons. ARGUMENTS: a, b, c, d - vertices of tetrahedron """ sub_tetra = [] sub_tetra.append((a, midpoint(a, b), midpoint(a, c), midpoint(a, d))) sub_tetra.append((midpoint(a, b), b, midpoin...
9f4a379092d62162109da199589393f2a02ccab1
3,615,528
def ExtractMemoryDumpIds(trace_builder): """Get a list with the ids of 'GlobalMemoryDump' events found in a trace. Args: trace_builder: A TraceDataBuilder object; trace data is extracted from it and the builder itself is cleaned up. """ event_ids = _SerializeAndProcessTrace( trace_builder, _GET...
4a102b4d897fceeb63a493bc5799e22f7d0f044c
3,615,529
from azure.mgmt.keyvault import KeyVaultManagementClient import re def get_vm_format_secret(secrets, certificate_store=None): """ Format secrets to be used in `az vm create --secrets` :param dict secrets: array of secrets to be formatted :param str certificate_store: certificate store the secret will ...
5f97ae86c07250864012f869bd718fb3513b6a8e
3,615,530
import builtins def instance(type_cls, cls): """ Decorator for creating a typeclass instance. Examples: >>> from abc import ABC, abstractmethod >>> from pycats import typeclass, instance >>> >>> @typeclass ... class Functor(ABC): ... ... @abstractme...
acd655661d2106e18004f7c22f6c8395287a20d4
3,615,531
def get_inputs(seq_len: int) -> tensorflow.Tensor: """Get input layers. See: https://arxiv.org/pdf/1810.04805.pdf Args seq_len: Length of the sequence or None. """ names = ['Token', 'Segment'] # , 'Masked'] return [ keras.layers.Input( shape=(None,), ...
3742ff634a7b46e17e19d509ea20dcac79660060
3,615,532
def replace_self_attention_layer_with_sparse_self_attention_layer( config, layers, # SparsityConfig parameters needs to be set accordingly sparsity_config=SparsityConfig(num_heads=4)): """This function replaces the self attention layers in attention layer with sparse self attention. For sparsity...
381b7c876a90ff2d6f135db4fd92ba3b4114aa94
3,615,533
def mape(y_true: pd.Series, y_pred: pd.Series) -> float: """Compute Mean Absolute Percentage Error (MAPE) Args: y_true (pd.Series): actual values y_pred (pd.Series): predict values Returns: float: mape value """ return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
a1959cd422db225ec0ddd77fc47ca55c78a686d9
3,615,534
def list_mutations(context): """ :type context: Context """ assert context.mutation_id == ALL mutate(context) return context.performed_mutation_ids
a78ba96202c910df057d86dac13cc549b6951e06
3,615,535
from typing import Optional import json async def make_keyboard_from_json(query: str, message: Message) -> Optional[Message]: """ Запрос в конструктор из json формата :param query: JSON запрос :param message: Объект сообщения пользователя """ try: data = json.loads(query) retur...
7f4b9fd01776b486c450e8515ae38e8854530202
3,615,537
def group_per_category(bkgs): """ Groups a flat list of datasets into sublists with the same category E.g. [ ttjet, ttjet, ttjet, qcd, qcd ] --> [ [ttjet, ttjet, ttjet], [qcd, qcd] ] """ cats = list(set(bkg.get_category() for bkg in bkgs)) cats.sort() return [ [ b for b in bkgs if b.get_cate...
c331456b1b3066f667c94e6ed7d00c8421ec2160
3,615,538
def subtract_params(param_list_left: list, param_list_right: list): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ return [x - y for x, y in zip(param_list_left, param_list_right)]
f8563cae337af0e30621428103afa10bde614e93
3,615,539
def rebin_or(newbins, oldbins, oldvalues): """Deprecated as of 2015-02-15. Use rebin instead.""" return rebin(newbins, oldbins, oldvalues, method='or')
d58c3334f2789c1d01f618e78ff5a519a9c88c4d
3,615,540
from typing import List def mkrefpath(r:DRef, items:List[str]=[])->RefPath: """ Construct a [RefPath](#pylightnix.types.RefPath) out of a reference `ref` and a path within the stage's realization """ assert_valid_dref(r) return [str(r)]+items
04a1b10478d71d0751898d69e521119549102d62
3,615,542
import re def resize(url, width): """ Return a url to a resized version of the given image at the url -- only works for files hosted on your MEDIA_ROOT --- CACHE THIS HEAVILY """ width = int(width) regex = get_media_url_regex() # check to see if the url is one we can handle, othe...
0ddaed81e450d00e4c76682c4c059b1155f0e975
3,615,543
async def me( request: Request, scopedTo: ScopedTo = ScopedTo( [UserScope.admin, UserScope.auditor, UserScope.guardian, UserScope.voter] ), ) -> UserInfo: """ Get user info for the current logged in user. """ token_data = scopedTo(request) if token_data.username is None: ...
a4ff28f2eccaf36383894e9af103d67c752aa7c1
3,615,544
def crop_center(image): """Returns a cropped square image.""" shape = image.shape new_shape = min(shape[1], shape[2]) offset_y = max(shape[1] - shape[2], 0) // 2 offset_x = max(shape[2] - shape[1], 0) // 2 image = tf.image.crop_to_bounding_box( image, offset_y, offset_x, new_shape, new_s...
bf069a5388ec40f8c07671cf514bb88442674cbd
3,615,545
def load_video(video_data, *, config=VideoLoaderConfig()): """Load a video into the database""" video_id = video_data.pop("video_id") platform = video_data.pop("platform") topics_data = video_data.pop("topics", None) offered_bys_data = video_data.pop("offered_by", None) with transaction.atomic(...
93d18d2d8bb067e85747641478555d21d1fe2148
3,615,546
from typing import Union async def is_float(obj: Union[Message, CallbackQuery]) -> bool: """ Checks if message text can be converted to float :return: True if so """ obj = await _to_message(obj) return obj.text and obj.text.isnumeric()
55fe1160431027f0c9546023ad5760455e3c632b
3,615,547