content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_multiple_new_predictions(monkeypatch): """ Mock prediction model method to ensure no duplicate prediction in predictions table. """ @classmethod async def mockfunc_get_one_by_username(cls, username): """Return a user record from the users table.""" hashed_pwd = bcrypt...
27608239ba1d1d5da0cf464d9ab1f752ec7057b6
32,700
def tidy_split(df, column, sep, keep=False): """ Split the values of a column and expand so the new DataFrame has one split value per row. Filters rows where the column is missing. Params ------ df : pandas.DataFrame dataframe with the column to split and expand column : str ...
4e4138cf4f5fab924d4e9e792db5e1c954ee8032
32,701
def greedyClustering(v_space, initial_pt_index, k, style): """ Generate `k` centers, starting with the `initial_pt_index`. Parameters: ---------- v_space: 2D array. The coordinate matrix of the initial geometry. The column number is the vertex's index. initia...
ac90d1d6c461a969a2bcb71f3df3a822496b3a65
32,702
def s2_matrix(beta, gamma, device=None): """ Returns a new tensor corresponding to matrix formulation of the given input tensors representing SO(3) group elements. Args: beta (`torch.FloatTensor`): beta attributes of group elements. gamma (`torch.FloatTensor`): gamma attributes of group...
20d08d1b75f22bddfaf5295751f05d43ea7fe6bb
32,703
import threading def cache(func): """Thread-safe caching.""" lock = threading.Lock() results = {} def wrapper(*args, **kwargs): identifier = checksum(args, kwargs) if identifier in results: return results[identifier] with lock: if identifier in results:...
c17a6550ec91edcfcad6d898a1f81fa4b878757a
32,704
import subprocess def run(cmd): """ Run system command, returns exit-code and stdout """ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) txt = p.stdout.read() return p.wait(), txt
303af44fd885edeed25721f0a16c3fad6a01f102
32,705
import platform def hide_console(): """Startup-info for subprocess.Popen which hides the console on Windows. """ if platform.system() != 'Windows': return None si = sp.STARTUPINFO() si.dwFlags |= sp.STARTF_USESHOWWINDOW si.wShowWindow = sp.SW_HIDE return si
faf25cdf48ffddd2ae7185c457d1abe60a0ec181
32,706
from typing import Dict from typing import Any def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any], *dicts: Dict[str, Any]) -> Dict[str, Any]: """ Merge multiple dictionaries, producing a merged result without modifying the arguments. :param dict1: the firs...
869399774cc07801e5fa95d9903e6a9f2dadfc25
32,707
def decode(model, inputs): """Decode inputs.""" decoder_inputs = encode_onehot(np.array(['='])).squeeze() decoder_inputs = jnp.tile(decoder_inputs, (inputs.shape[0], 1)) return model( inputs, decoder_inputs, train=False, max_output_len=get_max_output_len())
632b57ab86b9dd670d3e7203197575130ded7057
32,708
from typing import Sequence from typing import List def combinations_all(data: Sequence) -> List: """ Return all combinations of all length for given sequence Args: data: sequence to get combinations of Returns: List: all combinations """ comb = [] for r in range(1, len(d...
7e0b31189a5afe3ac027a4c947aca08b3a2075ff
32,709
def templateSummary(): """ """ # Load Model tablename = "survey_template" s3db[tablename] s3db.survey_complete crud_strings = s3.crud_strings[tablename] def postp(r, output): if r.interactive: if len(get_vars) > 0: dummy, template_id = get_vars.viewi...
6151e040b8e1c2491b3e282d0bb90fe278bf6dd8
32,710
import time def suffix_array(text, _step=16): """Analyze all common strings in the text. Short substrings of the length _step a are first pre-sorted. The are the results repeatedly merged so that the garanteed number of compared characters bytes is doubled in every iteration until all substrings are ...
1ed14feb5fa69b5d01d99128c56559c983df4e04
32,711
def get_main_image(): """Rendering the scatter chart""" yearly_temp = [] yearly_hum = [] for city in data: yearly_temp.append(sum(get_city_temperature(city))/12) yearly_hum.append(sum(get_city_humidity(city))/12) plt.clf() plt.scatter(yearly_hum, yearly_temp, alpha=0.5) plt...
b9845a44b868353e878b53beb6faf9c17bdf07d6
32,712
def get_PhotoImage(path, scale=1.0): """Generate a TKinter-compatible photo image, given a path, and a scaling factor. Parameters ---------- path : str Path to the image file. scale : float, default: 1.0 Scaling factor. Returns ------- img : `PIL.ImageTk.PhotoImage ...
02402574e0641a1caced9fe0b07434db5c84dee5
32,713
import gc def MCLA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, o...
f7059c0afd6f346d82ec36eae90f6c3fa8459dad
32,714
import logging import sys def parse_sampleids(samplelabel,ids): """ Parse the label id according to the given sample labels Parameter: samplelabel: a string of labels, like '0,2,3' or 'treat1,treat2,treat3' ids: a {samplelabel:index} ({string:int}) Return: (a list of index, a list of index labels...
448795c6f7736f52dfdb2e9d894b185fae1e17e2
32,715
from datetime import datetime def iso_date(iso_string): """ from iso string YYYY-MM-DD to python datetime.date Note: if only year is supplied, we assume month=1 and day=1 This function is not longer used, dates from lists always are strings """ if len(iso_string) == 4: iso_string =...
7f29b22744d384187e293c546d4c28790c211e99
32,716
def summary_dist_xdec(res, df1, df2): """ res is dictionary of summary-results DataFrames. df1 contains results variables for baseline policy. df2 contains results variables for reform policy. returns augmented dictionary of summary-results DataFrames. """ # create distribution tables groupe...
408bf1c8916d5338dbc01f41acb57dcc37e009e9
32,717
def is_app_running(appname): """Tries to determine if the application in appname is currently running""" display.display_detail('Checking if %s is running...' % appname) proc_list = get_running_processes() matching_items = [] if appname.startswith('/'): # search by exact path mat...
4d8a7c50ce38b36c6900d3482a8e6aadb98c7b5d
32,718
def moore_to_basu(moore, rr, lam): """Returns the coordinates, speeds, and accelerations in BasuMandal2007's convention. Parameters ---------- moore : dictionary A dictionary containg values for the q's, u's and u dots. rr : float Rear wheel radius. lam : float Steer...
f599c2f5226dc4a12de73e1ddc360b6176d915ed
32,719
def get_username(sciper): """ return username of user """ attribute = 'uid' response = LDAP_search( pattern_search='(uniqueIdentifier=' + sciper + ')', attribute=attribute ) return response[0]['attributes'][attribute][0]
9da92bb2f1b0b733a137ed0bf62d8817c9c13ed8
32,720
def number_to_string(s, number): """ :param s: word user input :param number: string of int which represent possible anagram :return: word of alphabet """ word = '' for i in number: word += s[int(i)] return word
7997b20264d0750e2b671a04aacb56c2a0559d8c
32,721
def mean(num_lst): """ Calculates the mean of a list of numbers Parameters ---------- num_lst : list List of numbers to calculate the average of Returns ------- The average/mean of num_lst Examples -------- >>> mean([1,2,3,4,5]) 3.0 """ ...
bc6f86fc793bad165afc8f319a3094f3fae91361
32,722
import pandas def development_create_database(df_literature, df_inorganics, df_predictions, inp): """ Create mass transition database. Create mass transition database based on literature, inorganic and prediction data. Parameters ---------- df_literature : dataframe Dataframe wit...
58b52d84ca98d770d3ace4a0b4dae4b369883284
32,723
import requests from typing import IO import hashlib def _stream_to_file( r: requests.Response, file: IO[bytes], chunk_size: int = 2**14, progress_bar_min_bytes: int = 2**25, ) -> str: """Stream the response to the file, returning the checksum. :param progress_bar_min_bytes: Minimum number of ...
44d0529a5fdb0a14ac4dcddbfecf23442678a75a
32,724
def get_user(key: str, user: int, type_return: str = 'dict', **kwargs): """Retrieve general user information.""" params = { 'k': key, 'u': user, 'm': kwargs['mode'] if 'mode' in kwargs else 0, 'type': kwargs['type_'] if 'type_' in kwargs else None, 'event_days': kwargs['event_days'] if 'event_days' in kwargs els...
1b7a5c144267c012a69aff2f02f771d848e8883a
32,725
def infer_schema(example, binary_features=[]): """Given a tf.train.Example, infer the Spark DataFrame schema (StructFields). Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to disambiguate these types for Spark DataFrames DTypes (StringType and BinaryType), so we requ...
bd952c278fafa809342b27755e2208b72bd25964
32,726
import sys def mongo_sync_status(remongo=False, update_all=False, user=None, xform=None): """Check the status of records in the mysql db versus mongodb. At a minimum, return a report (string) of the results. Optionally, take action to correct the differences, based on these parameters, if present and...
3e643de52e51d85913cb01a859bef17b7e47d939
32,727
import collections def create_batches_of_sentence_ids(sentences, batch_equal_size, max_batch_size): """ Groups together sentences into batches If max_batch_size is positive, this value determines the maximum number of sentences in each batch. If max_batch_size has a negative value, the function dynamically create...
8db116e73e791d7eb72f080b408bb52d60481db7
32,728
def com_com_distances_axis(universe, mda_selection_pairs, fstart=0, fend=-1, fstep=1, axis='z'): """Center of mass to Center of mass distance in one dimension (along an axis). This function computes the distance between the centers of mass between pairs of MDAnalysis atoms selections across the the MD traje...
7005d13e1f18597865ca5c5dc14ec09efd7c63e1
32,729
def min_vertex_cover(G, sampler=None, **sampler_args): """Returns an approximate minimum vertex cover. Defines a QUBO with ground states corresponding to a minimum vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that each edge of the graph is incident ...
b8681077d0bbb8504cdf5c96250e668bbcfe6d4e
32,730
def update_message_id(message_id, peername): """ Update message id for peername in global PEERS_MESSAGE_IDS dict. Return True iff message_id was updated, else False. """ global PEERS_MESSAGE_IDS if peername not in PEERS_MESSAGE_IDS.keys(): print('[DEBUG] No record of latest message_id f...
93905e9a485a6f1688fb082de2ebb53d1c048139
32,731
def quantile_bin_array(data, bins=6): """Returns symbolified array with equal-quantile binning. Parameters ---------- data : array Data array of shape (time, variables). bins : int, optional (default: 6) Number of bins. Returns ------- symb_array : array Conver...
87d8c64a30581b700d1a4674e4527882be99444f
32,732
import _socket def wrap_socket(sock: _socket.socket) -> AsyncSocket: """ Wraps a standard socket into an async socket """ return AsyncSocket(sock)
70a6829bdf9048514ffe5bd5b831952f1ecd8e89
32,733
def _calculate_outer_product_steps(signed_steps, n_steps, dim_x): """Calculate array of outer product of steps. Args: signed_steps (np.ndarray): Square array with either pos or neg steps returned by :func:`~estimagic.differentiation.generate_steps.generate_steps` function n_steps (i...
18aeadc5cb7866e6b99b5da9a2b9e6bc6ebb7c44
32,734
def compute_lima_on_off_image(n_on, n_off, a_on, a_off, kernel): """Compute Li & Ma significance and flux images for on-off observations. Parameters ---------- n_on : `~gammapy.maps.WcsNDMap` Counts image n_off : `~gammapy.maps.WcsNDMap` Off counts image a_on : `~gammapy.maps.Wc...
a9bde10722cbed4dab79f157ee478c9b5ba35d86
32,735
def data_preprocess(ex, mode='uniform', z_size=20): """ Convert image dtype and scale imge in range [-1,1] :param z_size: :param ex: :param mode: :return: """ image = ex['image'] image = tf.image.convert_image_dtype(image, tf.float32) image = tf.reshape(image, [-1]) image = i...
95131b5e03afbc0a3c797570a48d49ca93f15116
32,736
def p2wpkh(pubkey: PubKey, network: str = 'mainnet') -> bytes: """Return the p2wpkh (bech32 native) SegWit address.""" network_index = _NETWORKS.index(network) ec = _CURVES[network_index] pubkey = to_pubkey_bytes(pubkey, True, ec) h160 = hash160(pubkey) return b32address_from_witness(0, h160, ne...
ecb4c60871e0dc362d3576d2f02d8e07cd47614e
32,737
import re def is_not_from_subdomain(response, site_dict): """ Ensures the response's url isn't from a subdomain. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines if the response's url is from a subdomain """ root...
d3fa99cc8a91942de5f3ec9cb8249c62c7488821
32,738
import random def get_affiliation(): """Return a school/organization affiliation.""" return random.choice(AFFILIATIONS)
41356c95447352b9ab96db5783efb5ce511e0d00
32,739
def update_item_feature(train, num_item, user_features, lambda_item, nz_users_indices, robust=False): """ Update item feature matrix :param train: training data, sparse matrix of shape (num_item, num_user) :param num_item: number of items :param user_features: factorized user features, dense matrix ...
95b56754830cdcd8ddbfcabc25adcad1698903af
32,740
def generate_mutation(model, mutation_type): """ Generate a model mutation. Create the mutation class Parameters: model (dict): the model dictionary from settings mutation_type (str): the mutation type (create, delete, update) Returns: graphene.Mutation.Field: the mutation field ""...
1e1c39a76508c8f33179087786c08203af57c036
32,741
import warnings import subprocess def call_and_return_stdout(args: tp.Union[str, tp.List[str]], timeout: tp.Optional[tp.Union[str, int]] = None, encoding: tp.Optional[str] = None, expected_return_code: tp.Optional[int] = None, ...
781de2cc7b3dbdfc3676bcb234db33ba985b7633
32,742
def _wf_to_char(string): """Wordfast &'XX; escapes -> Char""" if string: for code, char in WF_ESCAPE_MAP: string = string.replace(code, char.encode('utf-8')) string = string.replace("\\n", "\n").replace("\\t", "\t") return string
9270f4ff5a03265956d006bd08d04e417a0c5a14
32,743
from datetime import datetime def agg_15_min_load_profile (load_profile_df): """ Aggregates 1-Hz load profile by taking average demand over 15-min increments. """ s_in_15min = 15 * 60 # prepare idx slices start_idxs = np.arange(0, len(load_profile_df), s_in_15min) end_idxs = np....
6a92abf10b6f976d4b48bc7e6bfb4c0e44b1f4c5
32,744
import os def icon(image): # type (str) -> dict """Creates the application folder icon info for main menu items""" return {"icon": os.path.join(MEDIA_URI, image)}
151e20b26bcdcb001d3bcfc51e833157e1c202d3
32,745
def get_gitbuilder_hash(project=None, branch=None, flavor=None, machine_type=None, distro=None, distro_version=None): """ Find the hash representing the head of the project's repository via querying a gitbuilder repo. Will return None in the case of a 404...
980abab1d3ff8bf1acdd0aec43f6ce5d5a2b6c45
32,746
def get_b16_add_conv_config(): """Returns the ViT-B/16 configuration.""" config = ml_collections.ConfigDict() config.patches = ml_collections.ConfigDict({'size': (16, 16)}) config.split = 'non-overlap' config.slide_step = 12 config.hidden_size = 768 config.transformer = ml_collections.Config...
eae5f7f33acaf5931b11c7ed2f6d1b554c8a5254
32,747
def real_proto(request) -> programl_pb2.ProgramGraph: """A test fixture which enumerates one of 100 "real" protos.""" return request.param
84f604626a1545e370aa92ab509329cc23e26aa5
32,748
def flat(arr): """Return arr flattened except for last axis.""" shape = arr.shape[:-1] n_features = arr.shape[-1] return arr.reshape(np.product(shape), n_features)
8b9dd1b92c4fffe087345fa74fbc535e2ee41fbf
32,749
import unittest import sys def test(): """Runs the tests without code coverage""" tests = unittest.TestLoader().discover("project/tests", pattern="test*.py") result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 sys.exit(result)
eac0edb1cdd76085cb0a958f10ee15876cf3fd34
32,750
from datetime import datetime import time def wait_while(f_logic, timeout, warning_timeout=None, warning_text=None, delay_between_attempts=0.5): """ Внутренний цик выполняется, пока вычисление `f_logic()` трактуется как `True`. """ warning_flag = False start_time = datetime.now() while True:...
0261083b54b1572833ea146663862fce5fe690a5
32,751
def acute_lymphocytic_leukemia1(): """Human Acute Lymphocytic Leukemia dataset (Patient 1). This dataset was introduced in :cite:`Gawad_2014` and was used in: * :cite:`B-SCITE` Figure 5. * :cite:`infSCITE` Figure S16. The size is n_cells × n_muts = 111 × 20 Returns ------- :class:`an...
76f15e7a19da71fe5e4451104698dfaffdbf1799
32,752
def extract_module(start_queue, g, locality="top", max_to_crawl=100, max_depth=10): """ ([rdflib.URI], rdflib.Graph) -> rdflib.Graph resource (rdflib.URI): resource for which we extract module g (rdflib.Graph): RDF graph """ ontomodule = Graph() ontomodule.namespace_manager = g.namespace_m...
78e60670a8c8ed53471062380d5a9cf0aab70848
32,753
import torch def softmax(x): """Softmax activation function Parameters ---------- x : torch.tensor """ return torch.exp(x) / torch.sum(torch.exp(x), dim=1).view(-1, 1)
739219efe04174fe7a2b21fb8aa98816679f8389
32,754
def comp_raw_bool_eqs(eq1str, eq2str): """ Will compare two boolean equations to see if they are the same. The equations can be written using the characters '&', '+' and '!' for 'and', 'or' and 'not' respectively. """ (eqn1, eqn1vars) = OqeFuncUtils.get_vars_bool_eqn(eq1str) (eqn2, eqn2v...
ce7af289add4294bf8a2a7835414cfb51358bc92
32,755
def get_integrated_scene(glm_files, start_scene=None): """Get an integrated scene. Given a set of GLM files, get a scene where quantities are summed or averaged or so. """ ms = satpy.MultiScene.from_files( glm_files, "glm_l2", time_threshold=10, group...
71744bc23f961e630013ace0a85b1788f92924ff
32,756
def _pt_to_test_name(what, pt, view): """Helper used to convert Sublime point to a test/bench function name.""" fn_names = [] pat = TEST_PATTERN.format(WHAT=what, **globals()) regions = view.find_all(pat, 0, r'\1', fn_names) if not regions: sublime.error_message('Could not find a Rust %s fun...
580cacda4b31dff3fd05f4218733f5f0c6388ddb
32,757
def load_log_weights(log_weights_root, iw_mode): """Loads the log_weights from the disk. It assumes a file structure of <log_weights_root>/<iw_mode>/*.npy of mulyiple npy files. This function loads all the weights in a single numpy array, concatenating all npy files. Finally, it caches the result in a file ...
78f633d55e1d3eedc31851a315294e6a15d381a0
32,758
import requests import logging def pipelines_is_ready(): """ Used to show the "pipelines is loading..." message """ url = f"{API_ENDPOINT}/{STATUS}" try: if requests.get(url).status_code < 400: return True except Exception as e: logging.exception(e) sleep(1)...
219b0935092d09311a05816cf0c4345f9abee9f6
32,759
import os def invTransect(T, sorted_ring_list, warnifnotunique=True): """Finds a transect that ends at T. In the case there are more than one, if warnifnotunique=True, user will be warned, but this may slow down transect generation. IS `warnifnotunique` IMPLEMENTED? Maybe not ... Returns: ...
b553f17bec27b09411babf2d230cb12358af78a8
32,760
import cmath def gamma_from_RLGC(freq,R,L,G,C): """Get propagation constant gamma from RLGC transmission line parameters""" w=2*np.pi*freq return cmath.sqrt((R+1j*w*L)*(G+1j*w*C))
9e4f09dc233f87b3fa52b9c7488b7fb65791289d
32,761
from typing import Optional from typing import List from typing import Union from pathlib import Path def get_abs_paths(paths: Optional[List[Union[str, Path]]]) -> List[Union[str, Path]]: """Extract the absolute path from the given sources (if any). :param paths: list of source paths, if empty this functions...
93a785fbf679664b96c5228a9cf008cba7793765
32,762
async def async_setup_gateway_entry(hass: core.HomeAssistant, entry: config_entries.ConfigEntry) -> bool: """Set up the Gateway component from a config entry.""" host = entry.data[CONF_HOST] euid = entry.data[CONF_TOKEN] # Connect to gateway gateway = IT600Gateway(host=host, euid=euid) try: ...
d70644b2c4423798007272777bb9c081e79fc778
32,763
import requests def import_from_github(username, repo, commit_hash): """Import a GitHub project into the exegesis database. Returns True on success, False on failure. """ url = 'https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1'.format( username, repo, commit_hash) headers = {'Ac...
a685fc79ad374ab499823696102d22b5d49201ed
32,764
import os def MakeConfigFilenameRelative(absolute_filename): """Determine an absolute filename's path relative to the monolith. Args: absolute_filename: str Returns: str NB: looks at MONOLITHIC_CODEBASE_NAME to determine where the monolithic codebase starts. e.g., if MONOLITHIC_CODEBASE_NAM...
45ca5417c7636762d04432dcb20a6ab195f6e6ce
32,765
import getpass import os def get_checks(): """ Returns a list of Entry """ manager = Manager() add = manager.add JOY_DEVICE = '/dev/input/js0' this_is_a_duckiebot = on_duckiebot() this_is_a_laptop = on_laptop() this_is_circle = on_circle() username = getpass.getuser() ...
36f5b3c8e6d22a687b215f71dbb10cacc73ac747
32,766
def substructure_matching_bonds(mol: dm.Mol, query: dm.Mol, **kwargs): """Perform a substructure match using `GetSubstructMatches` but instead of returning only the atom indices also return the bond indices. Args: mol: A molecule. query: A molecule used as a query to match against. ...
1b6f4f7e17defae555ea750941be5ec71047cc87
32,767
def remove_element(nums, val): """ :type nums: List[int] :type val: int :rtype: int """ sz = len(nums) while sz > 0 and nums[sz - 1] == val: sz -= 1 i = 0 while i < sz: if nums[i] == val: nums[i], nums[sz - 1] = nums[sz - 1], nums[i] sz -= 1 ...
4d29e8a8d43f191fe83ab0683f5dff005db799ec
32,768
def get_fm_file(file_name): """Read facilitymatcher file into dataframe. If not present, generate the file via script""" file_meta = set_facilitymatcher_meta(file_name, category='') df = load_preprocessed_output(file_meta, paths) if df is None: log.info('%s not found in %s, writing facility ...
b83743b8f56376148b12fc13c3731471cd24b6a5
32,769
def call_dot(instr): """Call dot, returning stdout and stdout""" dot = Popen('dot -T png'.split(), stdout=PIPE, stderr=PIPE, stdin=PIPE) return dot.communicate(instr)
f77c9f340f3fcbebb101c5f59d57c92b56147a11
32,770
def add_bank_member_signal( banks_table: BanksTable, bank_id: str, bank_member_id: str, signal_type: t.Type[SignalType], signal_value: str, ) -> BankMemberSignal: """ Add a bank member signal. Will deduplicate a signal_value + signal_type tuple before writing to the database. Callin...
214f064f152648c78d7ee5c6b56fb81c62cb4164
32,771
async def async_migrate_entry(hass, config_entry): """Migrate old entry.""" _LOGGER.debug("Migrating from version %s", config_entry.version) # Flatten configuration but keep old data if user rollbacks HASS if config_entry.version == 1: config_entry.data = {**config_entry.data, **config_entry.d...
96bb3ba729a59188b91edd55e80a0d868d75e89b
32,772
import os def get_flow1_datasets_result_path(create=True): """ local path for flow1 results file """ path = os.path.join(get_base_path(), 'flow1-datasets-results.json') if not os.path.isfile(path): open(path, 'w').close() return path
09ecf3a9c1c34f4f12e39a560f91f3f38aaf7010
32,773
from typing import List def map_zones(full_system) -> List[Zone]: """Map *zones*.""" zones = [] if full_system: for raw_zone in full_system.get("body", dict()).get("zones", list()): zone = map_zone(raw_zone) if zone: zones.append(zone) return zones
e5996460bc66a2882ac1cabee79fdff6e4da71cd
32,774
def betternn(x, keep_prob): """ Builds a network that learns to recognize digits :param x: input tensor of shape (N_examples, 784) as standard MNIST image is 28x28=7845 :param keep_prob: probability for dropout layer :return: y - a tensor of shape (N_examples, 10) with values equal to probabilit...
83b1155daa564b257fc1379811ddbde72d18ec4f
32,775
def get_valid_scsi_ids(devices, reserved_ids): """ Takes a list of dicts devices, and list of ints reserved_ids. Returns: - list of ints valid_ids, which are the SCSI ids that are not reserved - int recommended_id, which is the id that the Web UI should default to recommend """ occupied_ids ...
a5b4341fbee75e7d555c917587678dc5ea918b9f
32,776
def check_password_and_delete(target: dict, password) -> dict: """ :param target: :param password: :return: """ if "password" in target: if md5(str(password).encode()).hexdigest() == target["password"]: target = dell(target["password"]) Bash().delete({ ...
c06f5064d8a85065c3312d09bda9b9602b772ae1
32,777
def lingodoc_trigger_to_BIO(doc): """ :type doc: nlplingo.text.text_theory.Document """ ret = [] for sentence in doc.sentences: token_labels = [] for token_index, token in enumerate(sentence.tokens): token_labels.append(EventTriggerFeatureGenerator.get_event_type_of_toke...
7237650ef6e9649b3d0e14867d907c9f6aa5b71a
32,778
def build_coiled_coil_model(): """Generates and returns a coiled-coil model.""" model_and_info = build_and_record_model( request, model_building.HelixType.ALPHA) return jsonify(model_and_info)
9eeca3d1de581559129d3a4fe529c4e13727bd71
32,779
def get_input_fn(config, is_training, num_cpu_threads=4): """Creates an `input_fn` closure to be passed to TPUEstimator.""" input_files = [] for input_pattern in config.pretrain_tfrecords.split(","): input_files.extend(tf.io.gfile.glob(input_pattern)) def input_fn(params): """The actu...
23992d8d4fd1bd09f12aa4c28c695a47edca420e
32,780
def control_modes_available(): """API to call the GetCtrlModesCountSrv service to get the list of available modes in ctrl_pkg (autonomous/manual/calibration). Returns: dict: Execution status if the API call was successful, list of available modes and error reason if call fails. ...
eec46b860791d305cce14659a633b461c73143f0
32,781
def reproject_bbox(source_epsg=4326, dest_epsg=None, bbox=None): """ Basic function to reproject given coordinate bounding box (in WGS84). """ # checks # reproject bounding box l, b, r, t = bbox return transform_bounds(src_crs=source_epsg, dst_crs=dest_e...
449a1cb793cb2239ed9d46449d03f77500fab031
32,782
import os import sys import py_compile def compile_py_files(toc, workpath): """ Given a TOC or equivalent list of tuples, generates all the required pyc/pyo files, writing in a local directory if required, and returns the list of tuples with the updated pathnames. In the old system using ImpTracker, ...
846a68a20d574f1dd3c9e56c1e032a1ef41d68a4
32,783
from bs4 import BeautifulSoup import re def parse_cluster_card_info(soup: BeautifulSoup): """ App lists from GET requests follow a redirect to the /cluster page, which contains different HTML and selectors. :param soup: A BeautifulSoup object of an app's card :return: A dictionary of available ba...
0d4d0ba75a4e29b4d33e1f1a4e40239adcd80626
32,784
def get_joint_occurrence_df(df, row_column, col_column, top_k=10): """ Form a DataFrame where: - index is composed of top_k top values in row_column. - columns are composed of top_k top values in col_column. - cell values are the number of times that the index and column values occur together in...
19701a0a355733c1eb8d3aa3046fc6e00daed120
32,785
def get_total_obs_num_samples(obs_length=None, num_blocks=None, length_mode='obs_length', num_antennas=1, sample_rate=3e9, block_size=134217728, ...
0d5c3de03723c79d31c7f77ece29226daaf4f442
32,786
from pathlib import Path def documents_glossary_term(response: Response, request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST), term_id: str=Path(..., title="Glossary Term ID or Partial ID", description=opasCo...
0f20aa49fdd2cfb37390f2d0db2b88a97ae15d08
32,787
def number( x: Scalar, c: str = 'csl', w: int = 5, ) -> str: """ Return a notation of the number x in context c. Input: x (Scalar): number c (str): context w (int): width of the output string Output: s (str): notation of x """ S = 0 if x>=0 else 1 # ...
3a36d66f9166e82bb51e39e483f9366f83f72ff8
32,788
def remove_helm_repo(repos_array): """ Execute 'helm repo remove' command on input values repos_array is an array of strings as: ['stable', 'local', 'nalkinscloud', ...] :param repos_array: array of strings :return: return code and value from execution command as dict """ status = 0 ...
4b2a778122caaabf1b7cca971d2d9f2b57dbf84e
32,789
def evaluate_fio(baselines: dict, results: dict, test_name: str, failures: int, tolerance: int) -> int: """ Evaluate the fio test results against the baseline. Determine if the fio test results meet the expected threshold and display the outcome with appropriate units. Parameters ...
d5ad4ca319163409a526fe9d8b43be13de49680a
32,790
def f1_3D(x1, x2, x3): """ x1 dependant from example 2.1 in iterative methods """ return -0.2*x2 - 0.2*x3 + 0.8
09e5a337f5fa62a4c3cddd9ae0dd701867c52b22
32,791
import typing def encrypt(message: typing.Union[str, bytes], n: int, e: int) -> bytes: """ Encrypt MESSAGE with public key specified by N and E """ pub_key = rsa.PublicKey(n, e) if isinstance(message, str): message = message.encode("utf-8") elif isinstance(message, bytes): pass...
fb89606b0d3263c5d10479970868c5336d14679b
32,792
def _safe_div(numerator, denominator): """Divides two tensors element-wise, returning 0 if the denominator is <= 0. Args: numerator: A real `Tensor`. denominator: A real `Tensor`, with dtype matching `numerator`. Returns: 0 if `denominator` <= 0, else `numerator` / `denominator` """ t = tf.trued...
04e9856b1283bf83cd63bb56c65f1d1e2667bcc6
32,793
def build_embedding_model(): """ Build model by stacking up a preprocessing layer and an encoding layer. Returns ------- tf.keras.Model The embedding model, taking a list of strings as input, and outputting embeddings for each token of the input strings """ # Links for the...
ecf835f8543d9815c3c88b5b596c0c14d9524b66
32,794
def event_date_row(event_names_and_dates): """ Returns the third row of the attendance csv. This is just a list of event dates. :param list[(str, datetime)] event_names_and_dates: A list of names and dates for each event that should appear on the csv :returns: the row to be printed :rt...
5b51eaef8cde99040a1aff9a0c6abaaef5e52896
32,795
def moving_tajima_d(ac, size, start=0, stop=None, step=None, min_sites=3): """Calculate the value of Tajima's D in moving windows of `size` variants. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. size : int The window size (number of...
df5217180cf5b25ccb09ee88974d82290bff43ce
32,796
def sample_member(user, name='Attila'): """ Create and return a sample tag :param user: :param name: :return: """ return Member.objects.create(user=user, name=name)
ac171a5da2495436596bd6e597b0b9ea498c8bcf
32,797
import uuid def _create_feed(client, customer_id): """Creates a page feed with URLs Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. Returns: A FeedDetails instance with information about the newly created feed. """ # Retrieve ...
738e940abd1a7ec90382c4011b26d757c8a916a4
32,798
def cal_pj_task_ind(_st_date, _ed_date): """ 计算产品研发中心资源投入到非产品事务的指标。 :param _st_date: 起始日期 :param _ed_date: 截止日期 :return: 统计指标 """ global extTask _pj_info = handler.get_project_info("project_t") # logging.log(logging.WARN, ">>> cal_pj_task_ind( %s, %s )" % (_st_date, _ed_date)) ...
7a998a01a87abbc1f80147cf067b231429124001
32,799