content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional from typing import Tuple def is_decimal(value: Optional[str]) -> Tuple[bool, Optional[Decimal]]: """ none is not a numeric value, otherwise try to parse it by float function """ if value is None: return False, None try: v = float(value) return True, Decimal(v) except ValueError...
0d56f329d5063d3788b426e7cb2d7ab1b3246107
54,135
from typing import Dict import yaml def load_config_file(file_path: str) -> Dict: """ Load a YAML config file. Uses UnsafeLoader :rtype: Dict """ with open(file_path, 'r') as yaml_file: cfg = yaml.load(yaml_file, Loader=yaml.UnsafeLoader) return cfg
52024a77e8e940f919245bb7b5093043f6d2158c
54,136
def remove_zero_area(shape, properties, fid, zoom): """ All features get a numeric area tag, but for points this is zero. The area probably isn't exactly zero, so it's probably less confusing to just remove the tag to show that the value is probably closer to "unspecified". """ # remove the...
51b3b4aaa940d14261d857c3abcb6315ca82d83d
54,137
def get_w(roll_mat_csr, sale_usd): """ """ # Calculate the total sales in USD for each item id: total_sales_usd = sale_usd.groupby( ['id'], sort=False)['sale_usd'].apply(np.sum).values # Roll up total sales by ids to higher levels: weight2 = roll_mat_csr * total_sales_usd r...
8fc48e55c00d400c1c449bd35f9493b5149349f5
54,138
def is_latin_square(row_length: int, array: str) -> bool: """Return whether array is a latin square.""" # check horizontally row = 1 column = 0 numbers = [] for index, digit in enumerate(array): # check for new row if index % row_length == 0: row += 1 col...
f85721f93f27b72797702849375992e43314a847
54,139
def convert_to_JSON(graph): """Converts an igraph into a D3-compatible json file :returns a json Object """ nodes = [] for node in graph.vs: nodes.append({'id': node['name'], 'label': node['label'], 'size': node['totalCred'], ...
70bef265f139cc8a33d2f7ffc78ec6202f86c5dc
54,140
import random def spin_the_roulette() -> str: """ Returns one of 'red', 'black', 'green' in random, using the ROULETTE_COLORS chances. """ return random.choice(ROULETTE_COLORS)
1d6f5d38de3128d2682e33f94b695a40a9dfa925
54,141
def root_mean_square_f(a, axis=None, weights=None, masked=False): """The RMS along the specified axes. :Parameters: a: array-like Input array. Not all missing data axis: `int`, optional Axis along which to operate. By default, flattened input is used. ...
7f5f706a1f3a603904f0b7945977dd8d900504fa
54,142
def format_links( links, decimals=4, headers=False, delimiter=None, ): """Generates a summary table for a hit cluster. Args: hits (list): collection of Hit objects decimals (int): number of decimal points to show show_headers (bool): show column headers in output ...
678615ea2eb3f58ea0290e0360638a063fc82280
54,143
def _apply_slice(data, s): """ Apply slice s (given as a string) to the data. Parameters ---------- data : np.array The data to be sliced. s : str A string representation of the slice, e.g. '[...]', '[0, :]', etc. Returns ------- np.array The sliced data. ...
42a8e876cbf40ac85a216ba067b0108f7f489a82
54,144
import numpy import math def FindPriorRanges(xs, num_points, num_stderrs=3.0, median_flag=False): """Find ranges for mu and sigma with non-negligible likelihood. xs: sample num_points: number of values in each dimension num_stderrs: number of standard errors to include on either side Returns...
0bb7fadeaee74ea2c0a1e50f48bf98f2c55721ef
54,145
def split_color_string(color_string): """Split a ``color_string`` by whitespace into a list of it's ``components``. """ if not color_string: return [] return [thing for thing in regexes["whitespace"].split(color_string) if thing]
a980c43519275332930cfae2aff81eb514dfb4af
54,147
def ask_for_confirmation(title, message): """Ask the user to finally remove title from the Kodi library""" return xbmcgui.Dialog().yesno(heading=title, line1=message)
b333c381b0808842025731270bc09d14d6129e38
54,148
def serpentine(rows, columns): """ Make a serpentine pattern """ rows = range(rows) columns = range(columns) pos = [] for column in columns: for row in rows: pos.append((row,column)) rows.reverse() return pos
162c762a4fce76549955ea71b2053f8bc01fc0ce
54,149
def _identity_metric_nested(name, input_tensors): """Create identity metrics for a nested tuple of Tensors.""" update_ops = [] value_tensors = [] for tensor_number, tensor in enumerate(nest.flatten(input_tensors)): value_tensor, update_op = _identity_metric_single( name="{}_{}".format(name, tensor_n...
ecbbb0cff935c95236862a744f954722c47f1377
54,150
def lenient_chain_to_quadratic(chain, target_adjacency, chain_strength): """Determine the quadratic biases that induce the given chain. Args: chain (iterable): The variables that make up a chain. target_adjacency (dict/:class:`networkx.Graph`): Should be a dict of the f...
90b96904463fb53c225af006db401f8b88949b94
54,151
def parse(content: str) -> GherkinDocument: """ Parse the content of a file to an AST. """ parser = Parser() try: parse_result = parser.parse(StringOnlyTokenScanner(content)) except ParserError as e: raise InvalidInput(e) from e try: result = converter.structure(par...
630488a29b9a1eeb61d28674d2c99d6df8e5c3f9
54,153
from re import T def pql_tables(state: State): """Returns a table of all the persistent tables in the database. The resulting table has two columns: name, and type. """ names = state.db.list_tables() values = [(name, state.db.import_table_type(name, None)) for name in names] tuples = [sql.Tup...
b50814b3e489801591d45d3da47822ede7bbef63
54,154
from shapely import speedups def speedups() -> bool: """ Speedups are now enabled by default if they are available. You can check if speedups are enabled with the enabled attribute. """ return speedups.enabled
84ca1180b5aefaaa166c6ab52bda0a1c34314813
54,156
from pathlib import Path def graph_to_filenames(graph,root,masks,indir,prefix): """ Generate a list of filenames for the sequences of nested taxids from a root. """ filenames = defaultdict(list) def descend(root): """ Iteratively descend from a root to generate a list of f...
98436e407b5ba11c1d9e575c4f1f40bf24b39c72
54,157
def _dask_or_eager_func(name, eager_module=np, list_of_args=False, n_array_args=1): """Create a function that dispatches to dask for dask array inputs.""" if has_dask: def f(*args, **kwargs): if list_of_args: dispatch_args = args[0] else: ...
a10bddbed986545c1881844f742eac496919c804
54,158
def load_star_image(): # pragma: no cover """Load an optical image with stars. Returns ------- hdu : `~astropy.io.fits.ImageHDU` Image HDU Examples -------- .. plot:: :include-source: from photutils import datasets hdu = datasets.load_star_image() ...
958761688d2c817e424bd30dd3acfc2fe6a17e10
54,160
def build_huffman_tree(list_hufftrees): """ 构造huffman树 """ while len(list_hufftrees) > 1: # 1. 按照 weight 对 huffman 树进行从小到大的排序 list_hufftrees.sort(key=lambda x: x.get_wieght()) # 2. 挑出weight 最小的两个huffman编码树 temp1 = list_hufftrees[0] temp2 = list_hufftrees[1] ...
5ce7f1080a922e7957ad562ac3e3c5549d4e1bd3
54,161
import random def split_data(data, prob): """splits the data into fractions [prob, 1-prob]""" results = [], [] for row in data: results[0 if random.random() < prob else 1].append(row) return results
eb092cff35f9f98498c343162780921981a45ba0
54,162
def mp3_get_file_info(filename: str) -> SoundFileInfo: """Fetch some information about the audio file (mp3 format).""" filenamebytes = _get_filename_bytes(filename) with ffi.new("drmp3 *") as mp3: if not lib.drmp3_init_file(mp3, filenamebytes, ffi.NULL): raise DecodeError("could not open...
50f47784d670f7c5c590da70975e79743af2c6ab
54,164
from typing import Tuple from typing import List from typing import Dict from typing import Any def generate_test_data( method: constants.Method, num_rows=1, remove_merchant_id=False ) -> Tuple[List[bigquery.Row], constants.Batch, constants.BatchIdToItemId, Dict[ str, Any]]: """Generates a tuple con...
79064b6f27e1e972f40e23cc42d99968cad36571
54,165
import itertools def enumerate_space(extent): """Enumerate all the points in a space with the given extent. Use this function to ensure spaces are always enumerated in the same order. """ return itertools.imap(np.asarray, itertools.product(*map(xrange, extent)))
eed3897debf1370b4631e822a54aba25f6e7c5be
54,166
from pathlib import Path from typing import Any from typing import Iterable def file_resource( path: Path | str, value_type: type = Stream, compress: Any = None, writeable: bool = False, publish: bool = True, policies: Iterable[Policy] | None = None, ) -> type: """ Return a new resourc...
9ed41395a2db5f0abaa810266fa50867608a0e7e
54,168
import tqdm def sc_get_patient_df_dict(all_file_paths): """ Loads all the methylation DF and returns them as a dictionary :param all_file_paths: List of all the methylation files :return: A dictionary were the keys are the patient and the values a dictionary of chromosome and the methylation df ""...
21dfadc1ca965a64e9b2280adf7ad53071b52ae5
54,169
def rgba2rgb(rgba, background=(255,255,255)): """ Converts a 4-channel image array to a 3-channel image array Inputs: rbga: 4-channel array of image pixel data Output: An np array containing the 3-channel array respresenting the pixel values of the image """ row, col, ch = rgba.shape ...
43d2152eac868f6ef4d19eb7d1a1eb3fbb7ae697
54,170
def _handle_no_answer(prediction, ground_truths): """Check if there is no groundtruth answer and compute no-answer score.""" score = None # Check for no-answer: ground_truths can look like ['', '', ''] # the reason there are multiple empty values because we operate at batch # and append '' to the maximum...
058d812cc53d10f77db40ebad48902c74f5248d4
54,173
def recover_request_key_and_name(recovery_date, recovery_secret1): """Download the private information about this ID from Freenet.""" secret1 = recovery_date + "--" + recovery_secret1 uploadprefix = recovery_secret_to_ksk(secret1) return fastget(uploadprefix + "--identity")[1]
5e8483121034530cc4bc932a5ef3207a9ae6fcc2
54,174
def load_motchallenge(matrix_data, min_confidence=-1): """Load MOT challenge data. This is a modification of the function load_motchallenge from the py-motmetrics library, defined in io.py In this version, the pandas dataframe is generated from a numpy array (matrix_data) instead of a text file. Param...
78ed277044bbfee2fd1a10f907d5ca0d3534ae70
54,176
import re def verify_route_four_byte_as(device, expected_as_path, peer_address, target_address=None, protocol_type=None, protocol='bgp', no_protocol_type=False, max_time=60, check_interval=10): """ Verify best path counter Args: dev...
5a26469c26cf3eb2f9bb7cfeba5a7443ed08f161
54,177
from typing import List from typing import Dict async def get_resources_from_events(policy_changes: List[Dict]) -> Dict[str, dict]: """Returns a dict of resources affected by a list of policy changes along with the actions and other data points that are relevant to them. Returned dict format: { ...
81a9758ae92ed191dc74248f57ce96136b4e8d73
54,178
import time def doSiteStable(site_id, site_type='cntr'): """Check if site is created or not :param site_id: Enter site id :type site_id: string :param site_type: Enter site type :type site_type: string """ if site_type == 'cntr': b = Sites() elif site_type == 'vcs': b ...
38b3f2605ee54aba3c013644e8ea7710ab3e8d4b
54,179
def get_instance_fields(derived_col_names, target_name): """ It returns the Instance field element. Parameters ---------- derived_col_names : List Contains column names after preprocessing. target_name : String Name of the Target column. Returns ------- ...
885c9804c50d0e790c044dcafcc0de8eaf0d5dd1
54,180
def BFGS(f, x, iters=10, tol=1e-10): """ Run the gradient descent algorithm to minimize a function f. Parameters ---------- f: callable (function) x: int, float, or `Variable` object initial guess/starting point for minimum iters: integer maximum number of iterations tol: float thi...
c16cf2e4a69f9ddf3b89f870b5ed7d48ba7064ea
54,183
from django.template.loader import get_template from django.template import Context def get_admin_options(item_container, user_perms): """ Personen mit manager-Rechten koennen bestimmte Optionen auswaehlen """ if not user_perms.perm_manage: return '' tSection = get_template('app/survey/admin_options.html') ...
67fe7dd8a4daa49c3475c43fb4591cc377fd46e2
54,184
from io import StringIO def FromString(s, more_formatters=lambda x: None, _constructor=None): """Like FromFile, but takes a string.""" f = StringIO.StringIO(s) return FromFile(f, more_formatters=more_formatters, _constructor=_constructor)
3dbf74df2ee49bcaccf316c755a07dd7ea9d3cf0
54,185
def xacto(fields,x,y,z): """xacto is a function which takes a list of strings iterates through this list until it reaches a passed index 'x' it then runs the recursive function digimon to find the first letter in the string,finds the index of that letter in the string, splits the string into just numbers 'TopT...
860101ec00e2ed3734348b3ad2ea12b0da944b58
54,186
def get_tooltip(mod): """Returns the tooltip for the given mod.""" return manifest.get_cfg('mods', mod).get_string('tooltip')
dfce300e9ebd5c479c8352354b5835743ed746f2
54,187
def divergence( ts, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): """ Computes average pairwise divergence between two random choices from x over the window specified. """ windows = ts.parse_windows(windows) if indexes is None: indexes = [(0, 1)] me...
4d66bbf0eac364c2573d053f6092484065c8e0b6
54,189
def get_recipe_options(recipe): """Retrieves additional options for the given recipe Args: recipe: Project recipe Returns: dic: Contains recipe params w/ following potential keys, BAIT TARGET MSKQ MARKDUPLICATES For Example: {'BAIT': '/path/to/HemeBrainPACT_v1_BAITS.interval_list', ...
98bc2961072aba1452011c03d257fb7a8e7aa7a1
54,190
def plot_data_type(frag): """ Create the plot :param: frag pd.DataFrame - :param: """ data = [] labels = [] for st_pair, st in SUBSTITUTION_TYPES_COMBINED: st_sizes = frag[frag['Var'].isin(st_pair)]['Size'] if len(st_sizes) > 1: data.append(st_sizes) ...
708f0f82b5b198597306025eca8d7034a5804003
54,191
from typing import Mapping from typing import List import more_itertools def _pick_first_with_field( datasets_wide: Mapping[MultiRegionDataset, pd.DataFrame], timeseries_field_datasets: Mapping[FieldName, List[MultiRegionDataset]], ) -> Mapping[MultiRegionDataset, pd.DataFrame]: """Creates a DataFrame for...
5637b84f183d2b0a55871fc4c62ff39951ac01a6
54,192
def hash_id(note): """Return hashed id from seed note :param note: Pytest fixture :return: hash string from note.id """ return hashids.encode(note.id)
c28740cdc355ef1b711bd8fc7599277ff4403a92
54,194
def build_data(document, publication): """ Maps the variables of pt_law_downloader to our form """ return {'creator_name': publication['creator'], 'type': publication['type'], 'number': publication['number'], 'text': publication['text'], 'summary': publica...
1fc7353a288eb0a66be95786a9a6bb69139baf8d
54,195
def get_credit_card(): """ gets a valid credit card from the user via console """ print("- PAYMENT INFORMATION -") print("Please enter your credit card information. This information will NOT be saved.\n") card_number = input("Please type your CREDIT CARD NUMBER: ").strip() card_expiry= input...
1d949b591f39708f61ec202c5cc1dd28f6378a06
54,196
def gmx_cluster(input_structure_path: str, input_traj_path: str, output_pdb_path: str, input_index_path: str = None, properties: dict = None, **kwargs) -> int: """Execute the :class:`GMXCluster <gromacs.gmx_cluster.GMXCluster>` class and execute the :meth:`launch() <gromacs.gmx_cluster.GMXCluster.launch>` metho...
b365edb07554cc31572efd61a3d19aa92c192fd2
54,198
def precision_and_recall(true_labels, labels_limits): """Estimate the precision and recall :param true_labels: true labels :param labels_limits: predicted labels :return: precision and recall """ _, fp, fn, tp = confusion_matrix(true_labels, labels_limits).ravel() return tp / (fp + tp), tp...
eb978787f53a4e471e2940350684e2027405c15b
54,199
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_unicode, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case fi...
0ce84751d3e81c976da7c0ac76a4f601cf7e5e4b
54,200
def _get_grid_points_by_rotations(bz_gp, bz_grid: BZGrid, rotations): """Grid point rotations without surface treatment.""" rot_adrs = np.dot(rotations, bz_grid.addresses[bz_gp]) grgps = get_grid_point_from_address(rot_adrs, bz_grid.D_diag) return bz_grid.grg2bzg[grgps]
f6815ed9201e6a11444b67601890ca5c5a841094
54,201
def lstm(xs, ms, s, scope, nh): """LSTM layer for policy network, using same weight and bias initialization as LSTM in reward redistribution model Based on baselines.ppo2.policies.py; These initializations were taken directly from the redistribution model LSTM and could be optimized; """ nbatch...
336ed0b274364251abe66f6e6870023f5bbab805
54,202
def move_left(point): """Return a copy of `point`, moved left along the X-axis by 1. This function returns a tuple, not a Vector2D instance, and should only be used if performance is essential. Otherwise, the recommended alternative is to write `point + LEFT`. """ x, y = point return x - 1...
4e06e6f0a7eb0f944c42c3952955441cf9b83728
54,203
def get_ensembl_gene(ensembl_id, ENSEMBL_REST_SERVER = GRCH37_ENSEMBL_REST_SERVER): """ Get gene details from name * string Returntype: Gene """ key = (ensembl_id, ENSEMBL_REST_SERVER) if key not in known_genes: known_genes[key] = fetch_gene_id(ensembl_id, ENSEMBL_REST_SERVER) return known_genes[key]
d0b83377d71261fa1cfc8840c211af3ec20c5464
54,204
def list_notes_by_itinerary(itin_id): """serialize notes list to jsonify""" notes_author = db.session.query(User.fname, Note.comment, Note.day).join(User) itin_notes = notes_author.filter(Note.itinerary_id == itin_id).all() json_notes = [] for note in itin_notes: n_dict = {} n_dic...
62d3828ab7bb578a3f0a1401d82198472b0c0ff1
54,205
def set_dist_ang(a, b, dist, ang=0): """Returns point distance and angle away from a towards b""" c = normalize(b - a) * dist cr2d = rotate2D(*c[:2], ang) cr = cr2d if len(a) == 2 else a3([*cr2d, c[2]]) return cr + a
84b7afac6e9d5f0182f99699d240da12c932b300
54,206
def get_share_in_repo_list(request, start, limit): """List share in repos. """ username = request.user.username if is_org_context(request): org_id = request.user.org.org_id repo_list = seafile_api.get_org_share_in_repo_list(org_id, username, ...
d27901b75f1bbb273bf7d1267c9f89cd3aded537
54,207
def load_data(args, device): """Loads the data into three different data loaders. (Train, Test, Evaluation) Split the training dataset into a train / test dataset. Args: args: arguments passed to the python script """ train_dataset = CSVDataset(args, args.train_files, device) ...
2644a416086de2de83854f7f76bf3642b3094f32
54,208
def check_freq(session, freq): """ Check the frequency of the radar with the table, hfrSystemTypes. Return the frequency id :param session: SQLAlchemy database session instance :param freq: Frequency floating point number :return: ID of the appropriate system type in hfrSystemTypes table """ ...
dfb6adbe6488ff111d6abd7ffc6f5ae16fc0d141
54,209
from typing import Generic def yesterday_and_today(): """Prode `date` (d) and `str` (s) versions of yesterday and today.""" d = Generic() d.today = date.today() d.yesterday = d.today - timedelta(1) s = Generic() s.today = d.today.isoformat() s.yesterday = d.yesterday.isoformat() result...
559dd3d1977e8c54e2b79348d09c2c0526618815
54,210
def pix_to_sky(idx, nside): """Convert the pixels corresponding to the input indexes to sky coordinates (RA, Dec)""" theta, phi = hp.pix2ang(nside, idx) ra = np.rad2deg(phi) dec = np.rad2deg(0.5 * np.pi - theta) return ra, dec
65a0e33fc2c7b89f8b686296c2b9aeba0b95e79c
54,211
def stoi(x): """Converts strings to integers""" if type(x) != str: raise ValueError("Input value not a string") try: ans = 0 for d in x: ans = 10 * ans + dic[d] return ans except: raise ValueError("Input value not a string")
a791e2d030330f1521e4b61ede7f706d0f562786
54,212
def brightness(): """Set brightness value for camera.""" # Catch ajax request with form data brightness_val = 'error' if request.method == 'POST': brightness_val = request.form.get('brightness') if brightness_val is not None: app.logger.info('Form brightness submitted: %s', b...
81faca06170c78282e32b37da8eb6d41bab2ecda
54,213
from typing import List def fraction_low_base_quality(channels: List[np.ndarray], threshold: int = 127) -> float: """Gets fraction of bases that have low base quality scores in a pileup. Args: channels: A list of channels of a DeepVariant pileup image. This only uses c...
bf24d61ef8485f4da8925b9a1aec88f745a76538
54,214
def draw_corr(img0, pix_pos0, img1, pix_pos1, num=None): """ Draw matches, numpy version. Parameters are the same as draw keypoints """ if num is None: inds = np.arange(len(pix_pos0)) num = len(pix_pos0) else: inds = np.linspace(0, len(pix_pos0), num, endpoint=False).astype(n...
1994655337260663af424ba8450d2abdc48db2c1
54,216
from typing import Tuple import tqdm def calc_stft(protocol_df: pd.DataFrame, path: str) -> Tuple[np.ndarray, np.ndarray]: """ This function extracts spectrograms from raw audio data by using FFT. Args: protocol_df(pd.DataFrame): ASVspoof2019 protocol. path(str): Path to ASVSpoof2019 Retu...
341fb31f78974db6407c22e99bdc901e6b508ae5
54,217
import yaml def dict_to_yaml(dict_data): """Return YAML from dictionary. :param dict_data: Dictionary data :type dict_data: dict :returns: YAML dump :rtype: string """ return yaml.dump(dict_data, default_flow_style=False)
eba7896f63d499ef6c55b057320933dc0ff86333
54,218
def fixed_variables_only_in_inequalities(block): """ Method to return a ComponentSet of all fixed Var components which appear only within activated inequality Constraints in a model. Args: block : model to be studied Returns: A ComponentSet including all fixed Var components which ...
d5b5b7c4521ee2e729a18b45322f1a5b32bde27c
54,220
def generate_white_pawn_attack_bb_from_square(from_square: int) -> np.uint64: """ Returns the white pawn attack bitboard on an otherwise empty board from the provided square :param from_square: starting square from which to generate white pawn attacks :return: np.uint64 bitboard representation of white ...
1c6083e577d44cde593d91e8ce6a525e0772d839
54,221
def is_subscription(service_type): """ check service type is subscription or empty """ return not service_type or service_type == SUBSCRIPTION_SERVICE_TYPE
cd480020d251ec6a90ec3a5eb9be1871ad42ad4d
54,223
def df_to_list(df): """Convert a pandas DataFrame values to a list of lists. Args: df (pandas.DataFrame): A DataFrame to convert to a dictionary. Returns: list: A list of lists """ return [df[column_name].values.tolist() for column_name in df.columns]
6bff41874f195783ee67a859f203f6fb20969269
54,225
def load_config(config_file_name): """Load the JSON configuration file and return its structure.""" try: with open(config_file_name, 'r') as f: retval = json.load(f) return retval except Exception as e: print "ERROR reading config file:" raise e
a0cb80162c8cd45f56e4d348f8aeb0d6b159f50e
54,226
def findNearestDate(date_list, date): """ Find closest datapoint of each uppermost sensor in time window. Adapted from https://stackoverflow.com/a/32237949/3816498 . Parameters ---------- date_list : array-like List of dates date : datetime The date, to which the nearest da...
431f93212e6ffeddb994e727d94db8ccfe67315c
54,227
from functools import reduce def prod(stuff): """ prod(stuff): compute the product (i.e. reduce with '*') of the elements of 'stuff'. 'stuff' must be iterable.""" return reduce(lambda x, y: x*y, stuff)
5ddaaaced8c187018d9a5113ea3a91a21deb6e0b
54,228
def GetIonPositions(names_and_pos, ion_input): """ input: names_and_pos dict<string, Vector3>: dictionary that contains the position of each labelled element present. input: ion_input dict<string, Ionic>: dict of Ionic class wich contains info with no radius value output: dict<string, Vector3>: refined ...
51cbcdd34256546bc37414dd5ec5fb06d0af0035
54,229
import requests from bs4 import BeautifulSoup def get_archive_posts(): """Get post links from codingdose archive.""" base_url = 'https://codingdose.info/archives/' paging_url = base_url + 'page/' ordered_list = [] for page in range(1, get_num_pages()): url = base_url if page < 2 else pagin...
f0735432a466875242d6562f1b7319865ea0c00f
54,230
def normalize(X): """Normalize the dataset""" scaler = MinMaxScaler() scaler.fit(X) return scaler.transform(X)
1be9088497d10d52ff36798d985c402e76d05a1d
54,231
def project_3d_to_2d(points3d, intrinsics): """Projects 3d points, (in the Google format) to pixel location using the intrinsic matrix. The intrinsic matrix must be scaled if the image is scaled. Args: points3d ([list]): List of 3D points in camera frame. intrinsics ([np.array]): Intrin...
1d8f449358fc51782332b5945e952c683ece73c5
54,232
from typing import List from typing import Dict def compute_images2labels(images: List[str], labels: List[str]) -> Dict: """Maps all image paths to a list of labels. Args: images (List[str]): The list of image paths. labels (List[str]): The list of labels. Returns: Dict: The mapp...
1af99cd93bea7530857502665d4ce388a9d8f9ba
54,233
import difflib def similarString(inString, inList): """ check if there is an object that resembles the given string in the list :param inString: string to check for :type inString: string :param inList: list of strings to choose from :type inList: list :return: the string that resembles the i...
c61b9a767b0cd1fa063b1c23a45b3e4063a7fa55
54,234
from typing import Optional def __validate_enabled_entity(request: Request, db_issue: Optional[Issue], entity, entity_id): """ Get entity-id from path and query it in the database. Check if it belongs to the queried issue and if it is disabled. :param request: :param db_issue: :param entity: ...
780c433d11996795c22eca492edb7675801a6665
54,235
def _has_constant_term(p, x): """ Check if ``p`` has a constant term in ``x`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import _has_constant_term >>> R, x = ring('x', QQ) >>> p = x**2 + x + 1 ...
76bd944244a72d84876441b9c1b4bbd4e2a9f02a
54,237
def values_to_percent_growth(values): """ Turn a series of values into a series giving the growth from one period to the next :param values: a list of floats :return: another list, of length one less than values >>> rate = 0.05 >>> n_periods = 5 >>> initial_investment = 100 >>> values =...
33cf3a10e2c13a0365b31d8a1b77e4a409de6ba8
54,238
from typing import Dict def get_listing_by_url(conn: "SQLite connection", url: Dict[str, str]): """Collect records by URL Args: conn (sqlite connection): connection to zillow db url (Dict[str,str]): dictionary with key='url' and value=url string """ c = conn.cursor() c.execute( ...
2fd1c702f694cf1b40ffb4cdb74c8f2329dd3d94
54,240
import re def AbsolutePathToModule(file_path: str) -> str: """Determine module name from an absolute path.""" match = re.match(r'.+\.runfiles/phd/(.+)', file_path) if match: # Strip everything up to the root of the project from the path. module = match.group(1) # Strip the .py suffix. module = m...
81c51cb3227ce11bda9a1f90759cdfd1770ea715
54,241
def sum_counts(fname, R1=False): """Collect the sum of all reads for all samples from a summary count file (e.g. from collect_counts)""" count = 0 with open(fname, 'r') as infh: for line in infh: l = line.split() if R1: if l[2] == "R1": cou...
6ce7e156e1100f3106836e0b34caf6750baa18e1
54,242
import numpy def vappressure(temp): """Approximate vapour pressure over ice. Approximate the vapour pressure over ice at the given temperature. :arg float temp: Temperature in K. :returns: Vapour pressure in Pa. :Examples: >>> vappressure(270.) 470.061877574 """ ...
115e2bbb92d26428122da141cf8444d2c214aebe
54,243
def parse_tags(tag_list): """ >>> 'tag2' in parse_tags(['tag1=value1', 'tag2=value2']) True """ tags = {} for t in tag_list: k, v = t.split('=') tags[k] = v return tags
962c7ba737c56b46f9783912c528e4da6e4ee145
54,244
def resnetv1(num_classes=[1000]): """Encoder for instance discrimination and MoCo""" return resnet50(num_classes=num_classes)
972bc4823271493f76a52aa8db62146b69c6cc39
54,245
def radial_distrubtion_pair(p1, p2, bins=100, range=None, weighted=False, dim=None): """ Compute a pair radial distribution function. Returns (counts, bin_edges) Arguments: p1[T,N1,ndim] particle group 1 positions p1[T,N2,ndim] particle group 2 positions bins nu...
100436a6c0caefbb721d8c07e0b8b405d9b0749c
54,246
from typing import Any from typing import Dict from typing import Union from typing import AsyncIterable from typing import cast from typing import Awaitable async def create_source_event_stream( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, vari...
8c2f36a8fe476e4e7fb77fdbbec7bf2e271fcc2b
54,247
def unread_count_for(user): """Returns the number of unread messages for the specified user.""" return InboxMessage.objects.filter(to=user, read=False).count()
0ea68b9f1baf7bde7c45e91a4a2555c394fcde7f
54,249
def is_available(): # type: () -> bool """Returns whether visualization is available or not. .. note:: :mod:`~optuna.visualization` module depends on plotly version 4.0.0 or higher. If a supported version of plotly isn't installed in your environment, this function will return :obj...
23d44a26e50508b8b12e43fca725d1ee8c88e7fe
54,250
def coerce_bool(value): """Coerce a string to a bool, or to None""" clean_value = str(value).strip().lower() if clean_value in ["yes", "1", "true", "t"]: return True elif clean_value in ["no", "n0", "0", "false", "f"]: return False elif clean_value in ["", "na", "n/a", "none"]: ...
dd979b73717b2c86fe28cf7d1bdcc89020eda163
54,251
def gen_points_GMM(optNK, optCP, optPT, time, numClusters): """Generates points from a scikit-learn GMM object for a fit NK, CP and PT""" GMM = GaussianMixture(n_components=optNK.size, covariance_type="full") precisions = covFactor_to_precisions(optPT) means = tl.cp_to_tensor((None, np.asarray(optCP, dt...
ad82e782ea93641872cf029da3ac8d78559d3b31
54,253
def expand_mask_targets(masks, mask_class_labels, resolution, num_classes): """Expand masks from shape (#masks, resolution ** 2) to (#masks, #classes * resolution ** 2) to encode class specific mask targets. """ assert masks.shape[0] == mask_class_labels.shape[0] # Target values of -1 are "don't...
e68fa5f5b9c42fcdd6658e27c2d4a63d51760645
54,254
import torch def supervised_loss(R_tgt_src_pred, t_tgt_src_pred, batch, config, alpha=10.0): """This function computes the L1 loss between the predicted and groundtruth translation in addition to the rotation loss (R_pred.T * R) - I. Args: R_tgt_src_pred (torch.tensor): (b,3,3) predicted rotat...
b98b32c6cc8c0ecb1fde50d531e4d3479716bab1
54,255
import numpy def smooth_data(indices_, tag_counts_, sigma=20, width=120, size=None): """ #sigma = 20 #width = 120 #epsilon = 0 #some minimum peak height #size, epsilon = data_size, minimum_peak_size """ if size is None: size = max(indices_) lo, hi, normal = normal_function...
ba7c8399f7516499cb3987acc82b1c23fa550178
54,256