content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def get_obs_path( full_obsid, basedir ): """ Finds the full path for a given full OBSID (in the style of '20140910_003955_3860358888'). Parameters ---------- full_obsid : str full OBSID of the observation as a string basedir : str base directory for search (where...
e96232104091fc7f1c55dd55f66fb5635e7ebb34
673,408
import re def IsValidFolderForType(path, component_type): """Checks a folder is named correctly and in a valid tree for component type. Args: path: a relative path from ontology root with no leading or trailing slashes. Path should be the top level for the component. component_type: the base_lib.Co...
32b1fdbcec72d9289bb05cad9e93a2090aaaeff2
673,410
import requests def get_latest_version_number() -> str: """ Gets the latest pip version number from the pypi server. Returns: (str) the version of the latest pip module """ req = requests.get("https://pypi.org/pypi/monolithcaching/json") return req.json()["info"]["version"]
12c291049ec873c4d68cc36b9356d481d0ceb090
673,412
def convert_021_to_022(cfg): """Convert rev 0.21 to 0.22 The rev 0.22 only affected the fuzzy logic methods. The membership shape is now explicit so that the user has the freedom to choose alternatives. """ assert ("revision" in cfg) and (cfg["revision"] == "0.21") cfg["revision"] = 0.22 f...
cc3bf75f041008f26441aa554b311cd756c17962
673,413
import fnmatch def filter_tests(tests, filters): """Returns a filtered list of tests to run. The test-filtering semantics are documented in https://bit.ly/chromium-test-runner-api and https://bit.ly/chromium-test-list-format, but are as follows: Each filter is a list of glob expressions, with ea...
065c2fd7e0d9a8b65ad8da620980ea730080da64
673,414
def get_all_descendants(root, children_map): """ Returns all descendants in the tree of a given root node, recursively visiting them based on the map from parents to children. """ return {root}.union( *[get_all_descendants(child, children_map) for child in children_map.get(root, ...
8a6485c25f05a572e97ec88b35223c0171a90128
673,415
from typing import Iterable def decimalify_trailing(char_set: Iterable[str], text: str) -> str: """Replace last character with decimal representation if it's included in `char_set`.""" if not char_set or not text: return text last_char = text[-1] if last_char in char_set: return f"...
442b00371fc8847f6dca9e1afdab1c18e4d96f7c
673,416
def schedule(epoch, lr_init, swag_start, swa_lr_factor=2): """ SWA Gaussian learning rate schedule. """ swa_lr = lr_init/swa_lr_factor t = (epoch) / (swag_start) lr_ratio = swa_lr / lr_init if t <= 0.5: factor = 1.0 elif t <= 0.9: factor = 1.0 - (1.0 - lr_ratio) * (t - 0....
28984175d0a008b7b7980df6a890fd3b7afdcce7
673,417
def not_x_or_y(x_or_y, K_sets, on_keys=None): """not tags-any=x_or_y""" s_xy = set(x_or_y) xy_s = [k for k, S in K_sets.items() if (on_keys is None or k in on_keys) and len(S & s_xy) == 0] return xy_s
795a466292fe9f83a5c10449147fe1941ebfb568
673,418
import time def curr_time() -> int: """Return the current time in ms.""" return int(time.perf_counter() * 1000)
242df05bb6134261b1c98f945effb247c64ecd93
673,419
def team_game_result(team, game): """Return the final result of the game as it relates to the team""" if game.winner == team: return "Win" elif game.winner and game.winner != team: return "Lose" elif game.home_team_score > 0: return "Tie" else: return "Scoreless Tie"
fb5e71326be4c3b4227a3df83d7745478b6ae954
673,420
def get_assay_collections(assays, irods_backend): """Return a list of all assay collection names.""" return [irods_backend.get_path(a) for a in assays]
72cbd753676515dbcb9894a90c1d1c84a92d83bf
673,421
def decoder(conv_func): """ Convert bytestrings from Python's sqlite3 interface to a regular string. """ return lambda s: conv_func(s.decode())
bea6bb13189e4fa1620900f4a363389cb74d954b
673,424
def fact(n): """ Factorial function :arg n: Number :returns: factorial of n """ if n == 0: return 1 return n * fact(n - 1)
64fbfc1870fa4714f1e6f5e219f0e751d339328f
673,425
def has_no_overlap(r1, r2): """Returns True if the two reads overlap. """ r1_start, r1_end = r1.reference_start, r1.reference_end r2_start, r2_end = r2.reference_start, r2.reference_end return (r2_end <= r1_start) or (r1_end <= r2_start)
54e5c50ed37c8d3ca473dc62a0fd3c21318d4df0
673,426
def jaccard_similarity(x, y): """Calculates the minskowski's distance between the vectors x and y Keyword arguments: x,y -- the vectors between which the distance is to be calculated """ intersection = len(set.intersection(*[set(x), set(y)])) union = len(set.union(*[set(x), set(y)]))...
14c6314dc2d5f13ffbd66617113d091c7bdac744
673,427
def pick(*args): """ Returns the first non None value of the passed in values :param args: :return: """ for item in args: if item is not None: return item return None
acbdf1a47050303c0d2c033f64d793b8821bbbc9
673,428
import json def decode_json_response_for_content(response): """reponse.content is in binary, need to decode it to get access to it in python dictinary format""" return json.loads(response.content.decode('utf-8'))
bb746e5cbff2d10243d15385ba3fab62f5d74229
673,429
import requests def get(url, api_key=None): """Do the GET.""" headers = {} if api_key: headers["x-api-key"] = api_key response = requests.get(url, headers=headers) response.raise_for_status() return response.json()
7723973516774edd4185ac76a5bde1294a37fc73
673,430
def buildargs(*args, **kwargs) : """Constructs a printable list of arguments suitable for use in source function calls.""" arguments = "" for arg in args : arguments = arguments + ("%s, " % repr(arg)) for (kw, val) in kwargs.items() : arguments = arguments+ ("%s=%s, " % (kw, repr(val))) ...
901813c1270b47fdf1924b1d087c1746bfc6b4cf
673,431
def get_dataframe_name(s): """ Split dataframe and variable name from dataframe form field names (e.g. "___<var_name>___<dataframe_name>__"). Args: s (str): The string Returns: 2-tuple<str>: The name of the variable and name of the dataframe. False if not a properly formatted string. ...
20b3a72b19717d6c428d2c41a98ab3fa001b8536
673,432
def get_print_name(node, simple_form=True): """Get the name of the node For example, a node containing an instance of interfaces.fsl.BET would be called nodename.BET.fsl """ name = node.fullname if hasattr(node, '_interface'): pkglist = node._interface.__class__.__module__.split('.') ...
bd4160514c2e4f4f8ba98a4fb0ca55150d9c59e5
673,434
def problem038(): """ Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved ...
1a297a2ecff5c38c10b18ab92246057fdbb8ee8b
673,435
def serialize_tree(tree, node_id=0): """serialize_tree.""" s = tree.nodes[node_id]['label'] n_neighbors = len(list(tree.neighbors(node_id))) if n_neighbors > 0: s = '(' + s for i, u in enumerate(tree.neighbors(node_id)): s += serialize_tree(tree, u) if i < n_neigh...
66717aaa7ee888483213bc599ac64300c4c7f51f
673,436
from typing import Iterable from typing import Any def count_bool(blist: Iterable[Any]) -> int: """ Counts the number of "truthy" members of the input list. Args: blist: list of booleans or other truthy/falsy things Returns: number of truthy items """ return sum([1 if x else...
25c0e1d06ce059f39d5238364ea6a59f93876af8
673,437
import re def WrapWords(textlist, size, joiner='\n'): """Insert breaks into the listed strings at specified width. Args: textlist: a list of text strings size: width of reformated strings joiner: text to insert at break. eg. '\n ' to add an indent. Returns: list of strings """ # \S*? is a...
8fba790437b643da960897ecf00d6c4ba24c1c5f
673,438
def set_params(context, *interleaved, **pairs): """construct a copy of the current request's query parameters, updated with the given parameters. parameter keys and values may be specified either as named keyword argument pairs: set_params query='cookie' page=2 and/or as interleaved keys ...
326251daafa3a9e01f3188dd227bf1820f0bc042
673,439
def _format_param_value(key, value): """Wraps string values in quotes, and returns as 'key=value'. """ if isinstance(value, str): value = "'{}'".format(value) return "{}={}".format(key, value)
c6989a4ac03a94e7c680f6cd2ea5f3570812f02d
673,440
import subprocess def overlay(video, image): """ The script uses FFMPEG to overlay an image over a video. It accepts two inputs. -> video: string (location of video) -> image: string (location of string) Example outputs: -> Overlay a snow animation over village ...
78bd070c79b5c250969f5a6fd7f307347cd873a7
673,441
import re import torch def get_devices(devices): """ Get devices for running model :param devices: list of devices from profile :type devices: list :return: list of usable devices according to desired and available hardware :rtype: list[str] """ def parse_cuda_device(device): ...
196823d92f818b65b3688202b123e4b7c4460b27
673,442
def get_number_months(): """ Return a string list of month numerics """ return ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
0afbca237c20cc15daf6d8051fe3e92de99549a0
673,443
def mod_file(sourcefile, ext, unique=True, generate_non_unique=True, cntr=1): """Try to modify sourcefile to have ext, if dest exists and dest must be unique, then either generate a unqie version with numbers appended or raise""" if cntr > 1: destfile = sourcefile.parent.joinpath(sourcefile.stem + s...
7feba2f6d659cd7e678f72f8c65340ba985e4f10
673,444
import os import csv def CSV_list_columns(f_csv): """ Iterate over the columns of a .csv file. Args: f_csv (string): Location of the .csv file Returns: return tuple(reader.next()): DOCUMENTATION_UNKNOWN """ if not os.path.exists(f_csv): msg = "File not found {}".forma...
cc51f8dc40ddfada6886948133fc857dfeb95d72
673,446
def echo_args(*args, **kwargs): """Returns a dict containng all positional and keyword arguments. The dict has keys ``"args"`` and ``"kwargs"``, corresponding to positional and keyword arguments respectively. :param *args: Positional arguments :param **kwargs: Keyword arguments :rtype:...
383c36b6a8c0d7ae3dbecbbcfc59808106a8ce1e
673,447
import os def collect_clusterfiles_path(path_to_mirna_folder): """ Takes the MIRNAs/ folder and returns a list of cluster files from that folder """ list_of_cluster_files = [os.path.join(path_to_mirna_folder,f) for f in os.listdir(path_to_mirna_folder)] return list_of_cluster_files
9df87558eb76ff5246f0978c1b70e2280de62e5f
673,448
import os import pickle def load_metadata(tfrecord_filename): """ Loads the metadate belonging to a given tfrecord filename Args: tfrecord_filename (_type_): _description_ Returns: metadata: metadata associated with tfrecord file """ filename = os.path.abspath(tfrecord_filename) ...
da615c76d20035baf3ed1a6770920b4fe4f63915
673,449
import sys def convert_to_simple_format_graph(tree_data): """ Parser.load(fname)で読み込んだデータを扱いやすい形式に変換する Parameters ---------- tree_data : [{"x": float, "y": float, "z": float, "diameter": float, "label": int, "parent_label": int}] Returns ------- links : [(int, int)]...
a5eb37fce3bef9b87935fdbe94b122fdb4ccd486
673,452
import glob import os def check_dump_quota(quota, ext): """Check if sum of the files with ext is within the specified quota in megabytes.""" files = glob.glob("*." + ext) size_sum = 0 for file_name in files: size_sum += os.path.getsize(file_name) return size_sum <= quota
4ff358e735ccb796e45e075fddfcef5a640ee8f2
673,453
from pathlib import Path def resolve_import(import_: str, location: str, file: Path) -> str: """Resolve potentially relative import inside a package.""" if not import_.startswith('.'): return import_ import_parts = import_.split('.') up_levels = len([p for p in import_parts if p == '']) i...
aed1b736a84f2fb3670e89e4f3a2dfd529162a95
673,454
import re def is_uuid(string): """ retun True if string is a UUID """ if re.match(r'[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}', string): return True return False
38d0c092cc1cab6db4b404b2e6afac55395db7f4
673,455
def time2int(float_time): """ Convert time from float (seconds) to int (nanoseconds). """ int_time = int(float_time * 10000000) return int_time
7fd785ac7eade1336ddf08d4c6c4ac1116287380
673,456
def fp_rate(FP, neg): """ Gets false positive rate. :param: FP: Number of false positives :type FP: `int` :param: neg: Number of negative labels :type neg: `int` :return: false positive rate :rtype: `float` """ if neg == 0: return 0 else: return FP / neg
afb9e78dd601c3f9f559001c8f0f2727ccdb0c5f
673,459
def _iterify(x): """make x iterable""" return [x] if not isinstance(x, (list, tuple)) else x
0fd61bb16384ad844fac7726ad4e5656ccd41f3c
673,460
def soup(): """Soup.""" return 'The rats appreciate the soup.'
a9404d851c8fa884273294b77720d6738fae40b0
673,461
def cmd_automation_event_lost(msg): """ (From protocol docs) Panel's automation buffer has overflowed. Automation modules should respond to this with request for Dynamic Data Refresh and Full Equipment List Request. """ return { }
9394a98c3b1eb81cf16946252cd82c60cda2bbb5
673,462
import os def _lock_filename(filename): """ Return the pathname of the lock_filename. """ pathname, basename = os.path.split(filename) lock_filename = os.path.join(pathname, '.%s' % basename) return lock_filename
b74aab4faf7ba117c81641dba1afe98368c7c658
673,463
def str2bool(str): """ bool('False') is True in Python, so we need to do some string parsing. Use the same words in ConfigParser :param Text str: :rtype: bool """ return not str.lower() in ["false", "0", "off", "no"]
896b7bcc0789f42b5a4c567a9a624fddc4374074
673,464
def columns_to_nd(array2reshape, layers, rows, columns): """ Reshapes an array from columns layout to [n layers x rows x columns] """ if layers == 1: return array2reshape.reshape(columns, rows).T else: return array2reshape.T.reshape(layers, rows, columns)
4fb11743406ca1f1c099e7783381fe0463141683
673,465
def convert_none_type_object_to_empty_string(my_object): """ replace noneType objects with an empty string. Else return the object. """ return ('' if my_object is None else my_object)
52d0cb756f85adba0cd537c0f1b7b74b4c0d23b8
673,466
import ipaddress def str_to_hops(endpoint): """Take a string such as '127.0.0.1:9001|192.168.1.1:9002|[::1]:9000' representing a multihop SOCKS 5 proxied connection (here for example including an IPV6 address), and return a list of (ip, port) tuples""" result = [] for hop in endpoint.split('|'): ...
ff8fcd81e4ab067b1b3def91c5e8d2602eb0c231
673,467
from numpy import column_stack,ravel def interl(a,b): """Combine two arrays of the same length alternating their elements""" return ravel(column_stack((a,b)))
25b58cc1ba1bad2e21b61708252149b438d9e00f
673,468
def df_cols_lower(df_in, col='name'): """Find in a DataFrame any column matching the col argument in lowercase and rename all found columns to lowercase""" # Make a copy to avoid tampering the original df = df_in.copy() # Find and rename any column "Name" or "NAME" to lowercase "name" namecols = df....
7266ee51f6ad2fda465cdefaf5f5637b1570d8a8
673,470
import re def is_weight(word): """ is_weight() Purpose: Checks if word is a weight. @param word. A string. @return the matched object if it is a weight, otherwise None. >>> is_weight('1mg') is not None True >>> is_weight('10 g') is not None True >>> is_weight('78 mcg') ...
45bafa2176056babbbd5bc18d93ed6f96c341b6e
673,471
def insert(connection, shop_id, shop_name): """Add a new shop to the database. Args: connection (sqlite3.Connection) shop_id (str) shop_name (str) """ cur = connection.cursor() cur.execute('''INSERT INTO Shop (shopID, shopName) VALUES (?,?)''', (shop_id, shop_name)) con...
f4181739fb2d7011480625b0d0bdf438b7f510b5
673,473
def fill_null(data, table): """ Fills a Dataframe with less columns as the DB table with None """ data_cols = data.columns table_cols = table.__table__.columns.keys() uniq = list(set(table_cols) - set(data_cols)) for un in uniq: data[un] = None return data
79e2faa8252844c52df60f670b790705bc8185f7
673,474
def shallow(left, right, key, default): """Updates fields from src at key, into key at dst. """ left_v = left.get(key, default) if key in right: right_v = right[key] if key in left: if isinstance(left_v, dict) and isinstance(right_v, dict): return dict(left_v, **r...
4ea7e52d1d9dacac257c0af928d38858fb63d9af
673,475
import re def get_locus_info(locus): """ Returns chrom, start and stop from locus string. Enforces standardization of how locus is represented. chrom:start_stop (start and stop should be ints or 'None') """ chrom, start_stop = locus.split(':') if chrom == 'None': chrom = None star...
b09efb7c8c8433c12c7738bbe926df0dad04d9e8
673,476
def incl_intervals(): """ Queries the included intervals. Note: timespans will not be able to be queried if their interval is not included. """ return ["yearly", "monthly", "weekly", "daily"]
b5276a57cdf25e94c73a370882cf286692087ae3
673,477
from typing import Callable import click def enable_selinux_enforcing_option(command: Callable[..., None], ) -> Callable[..., None]: """ An option decorator for setting the SELinux mode to "enforcing". """ function = click.option( '--enable-selinux-enforcing...
f56ce83b39b92554dd68d9bf0b08e6de514ac26f
673,478
def check_convergence(lines): """Returns all the geometry convergence results""" convergence_result = 'MAXIMUM GRADIENT' convergence_list = [] for i, line in enumerate(lines): if convergence_result in line: convergence_list.append(''.join(lines[i + 2].strip())) return convergenc...
9bf727949b7b8c31fefc944a129f430bdaf1f894
673,479
def create_instance(tokenizer, text, max_length=None): """A single sample instance for LM task.""" sentence = text.strip().split("\t") ids = tokenizer.encode(sentence[0]) pair_ids = None if len(sentence) == 2: pair_ids = tokenizer.encode(sentence[1]) output = tokenizer.prepare_for_mode...
718b5622a604d0320dd66350394719711de9e751
673,480
def gameboard(level): """ This function will generate a gameboard, determined by the level size parameter. To keep the rows equivalent for both the user and the player, the board_size is guarenteed to be a multiple of two. Parameters: ----------- level: required parameter. Level determin...
538120cf0e5789074c1f2e0c6e16f6440d0a4524
673,481
def strategy_expensive(cookies, cps, time_left, build_info): """ this strategy should always select the most expensive item you can afford in the time left. """ items = build_info.build_items() priciest_cost = float("-inf") priciest_item = None for item in items: if build_info.get_...
2bea65fb2baf535a526226bfe9f0e910d7f44b58
673,482
import numpy def check_arrays(*arrays): """Left for consistency version of sklearn.validation.check_arrays :param list[iterable] arrays: arrays with same length of first dimension. """ assert len(arrays) > 0, 'The number of array must be greater than zero' checked_arrays = [] shapes = [] ...
b71674beeec0f9e5d5d137674d56376b9b10d0d8
673,483
from typing import List def get_min_pair_sum(values: List[int]) -> int: """ Returns the minimum possible maximum sum out of two values It seems that the optimal solution to the problem would be: 1. Sort the array => O(n log(n)) 2. Iterate over half the array and make pairs from st...
9a2ba9c45c2e76c6b50f530d792f13ce28d3ba51
673,484
import time def convert_time(longTime): """ Ignore time of day to help with grouping contributions by day. 2018-01-03 00:00:00 --> 2018-01-03 """ try: t = time.strptime(longTime, "%Y-%m-%d %H:%M:%S") except ValueError: return longTime ret = time.strftime( "%Y-%m-%d", t) ...
d27f66ec817af5a35a0d406de3f922af1a4f9c6a
673,485
def computeRR(self): """ Compute the rectangularity ratio (RR) of the max-tree nodes. RR is defined as the area (volume) of a connected component divided by the area (volume) of its bounding-box. """ xmin,xmax = self.node_array[6,:], self.node_array[7,:] + 1 ymin,ymax = self.node_array[9,:], s...
745413a672dcdcdb2717c8c45b12ce66f1a0b258
673,486
def zeros(n): """Mimic np.zeros() by returning a list of zero floats of length n. """ if isinstance(n, int): if n > 0: return [0.]*n msg = "zeros() should be called with positive integer, got: %s" % n raise ValueError(msg)
5b1b87a5b54e2b90c22d1bd400fcb02d825c15a2
673,488
def shape3d_to_size2d(shape, axis): """Turn a 3d shape (z, y, x) into a local (x', y', z'), where z' represents the dimension indicated by axis. """ shape = list(shape) axis_value = shape.pop(axis) size = list(reversed(shape)) size.append(axis_value) return tuple(size)
72282a25629ecb864efde13f5c8eb238120d74e5
673,489
def repeatedSubstringPatternB(s): """ :type s: str :rtype: bool """ return s in (s + s)[1:-1]
10bac6e71fe92ec196fb8fdbdd27dcf273e385ed
673,490
import os def cellranger_count_output(project,sample_name=None, prefix="cellranger_count"): """ Generate list of 'cellranger count' outputs Given an AnalysisProject, the outputs from 'cellranger count' will look like: - {PREFIX}/{SAMPLE_n}/outs/metrics_summary.csv ...
5414ae81b9d77a3697b8723cd157f34fb6574bad
673,491
def orsample(df): """ Return the bitwise-OR of every value in the data frame. >>> orsample(empty) 0 >>> result = 1 | 3 | 5 | 6 | 8 >>> assert result == orsample(sample) """ if len(df) == 0: return 0 result = 0 for val in df.iloc[::, 0]: if val > 0: re...
d027397953cff1939fe5218b7ae345d6dd4a80b2
673,492
def camels_to_move(camel_dict, space, height): """Getting information about camels that need to move Parameters ---------- camel_dict : nested dict Dictionary with current camel positions space : int Space the camel is on height : int Height of the camel Returns ...
cc8737d6a7d544775af32b90a3c9486e7ffb3060
673,493
def make_feasible(x_0, c): """ Returns a feasible x with respect to the constraints g_3, g_4, g_5, and g_6. :param np.array x_0: (n,) Initial, infeasible point. :param dict c: Constants defining the constraints. :return np.array: (n,) Initial, feasible point. Notes: - x_0 should follow: x0...
b4a04ccb25d29962b32601593fd3f2bb7582348a
673,494
def binary_sum(S, start, stop): """Return the sum of the numbers in implicit slice S[start:stop].""" if start >= stop: # zero elemetns in slice return 0 elif start == stop - 1: return S[start] # one element in slice else: # two or more ...
3d21dfe3afcf47f29d95ae67dc46a5970ed39515
673,495
def status(): """Status endpoint returns the status of the plug-in.""" return("The SBOL2Excel Download Plug-In is currently running.")
2934359a171a7e598368feae2012b74be44f0626
673,496
import logging import hashlib from pathlib import Path import subprocess def upload_file(local_path: str, destination_path: str, sas_token: str) -> str: """For NNI maintainers to add updated static files to the Azure blob easily. In most cases, you don't need to calculate the hash on your own, it will be auto...
0d0db907b3fcf128ce2bfe64cd358812be164e76
673,497
from typing import List def gen_string(i: int, base: int, digits: List[str]): """Returns a string representation of an integer given the list of digits. Args: i (int): The integer to generate base (int): The base representation of the number. (based on the length of the list) digits (...
ad7fe50db1f72fdc4bc5e53e09a6abdea5ff1bd7
673,499
import requests def sonar_project_exists(project_key: str) -> bool: """Return boolean representing if given sonar project exists.""" try: return "project not found" not in requests.get( "https://sonarcloud.io/api/project_badges/measure?project={project_key}&metric=coverage".format( ...
3deca8b5fd3db923f0bc2ce073223ac367840c10
673,500
import math def round_up_to_multiple(x: int, base: int) -> int: """ Round a positive integer up to the nearest multiple of given base number For example: 12 -> 15, with base = 5 """ return base * math.ceil(x / base)
c7e9d1442e198e995511193f631e666a1fdd344b
673,501
def module_name_join(names): """Joins names with '.' Args: names (iterable): list of strings to join Returns: str: module name """ return '.'.join(names)
873eb6281f2de5da1fa17f5d89e17a1de4202b4f
673,503
import os def get_filename(filepath): """ Returns the name of the file without the extension """ filename = os.path.split(filepath)[1].split(".")[0] return filename
f5d2d7bff79918d56c4667d46b4811c816524bb0
673,504
def splitf(delim): """ Returns a function that splits string with a given delimiter. Examples -------- >>> f = splitf(", ") >>> f('apples, pears, oranges') ['apples', 'pears', 'oranges'] """ return lambda x: x.split(delim)
16bc8a15f356971042ab3472253604cba7807915
673,505
def remap_kalibr_config(kalibr_config, mapping): """Map relevant fields from kalibr to kimera.""" kimera_config = {} for kimera_key, kalibr_key_map_pair in mapping.items(): kalibr_key, transform_func = kalibr_key_map_pair if transform_func is None: kimera_config[kimera_key] = ka...
ad29746d234a8f30d9f3352b5e0ada0cbda616c9
673,506
def number_of_variants(annoted_clinvarome): """ take the clinvarome and count the number of molecular consequences reflecting the number of variants by genes. """ annoted_clinvarome["variant_number"] = ( annoted_clinvarome["missense_inframe"] + annoted_clinvarome["other"] ...
3d94441bc20aa6a653f8e096ba7c1496606882b6
673,507
def get_posts(): """Split the posts file content into a list of individual posts""" with open("posts.md") as post_file: content = post_file.read() posts = content.split("{end}")[:-1] return posts
525cef886d30f958167613270d5c39bad190a23e
673,508
def _calculate_texture_sim(ri, rj): """ Calculate texture similarity using histogram intersection """ return sum([min(a, b) for a, b in zip(ri["texture_hist"], rj["texture_hist"])])
62168687a737446a77a9a90e3f7227007f23088b
673,509
def pp_value(TP, FP): """ Gets positive predictive value, or precision. :param: TP: Number of true positives :type TP: `int` :param: FP: Number of false positives :type FP: `int` :return: positive predictive value :rtype: `float` """ if TP == 0 and FP == 0: return 0 ...
73486b177d9da992777c5f90b98909341467899d
673,510
def intToColorHex(color_number): """Convert an integer to a hexadecimal string compatible with :class:`QColor` Args: color_number (int): integer value of a RGB color Returns: str: QColor compatible hex string in format '#rrggbb' """ return '#%0.6x' % (color_number)
997c2b34ff25771313673890b1dfd3144f9d461d
673,511
def cal_time_travel(G, vi, vj, t_vi = 0): """ G : graph vi : departure vi : destination t_vi : departure time from vi """ time_travel = 0 dict_temp = G.get_edge_data(vi,vj) time_travel = dict_temp[0]["length"] return time_travel
96bdbe52a1e5edde9ed063c3a2f2d863d6caf5c5
673,513
def _no_pending_images(images): """If there are any images not in a steady state, don't cache""" for image in images: if image.status not in ('active', 'deleted', 'killed'): return False return True
e39b5e3959095599a64a43d517ea206a0b12bc9c
673,514
def get_data(fname: str) -> list: """ Read the data file into a list. """ with open(fname) as f: return [int(line) for line in f]
077dd25a97e61a9bd4abbd76746b1bc7503d068f
673,515
def pos_constrain(val, max_val=498, min_val=0): """Constrain values from 0 to 498 Args: val: value to be constrained Returns: val: value after map and constrain """ val = val + 60 return min(max_val, max(min_val, val))
16e1275ad2510f6cc880de15a5d62aeea6930c12
673,516
import typing import click def create_tag_table(tags: typing.Dict, sep: int) -> str: """Helper method to create a table from dictionary of image tags -- used by info cli""" table = "" for idx, (k, v) in enumerate(tags.items()): name = f"{k}:" row = f"{click.style(name, bold=True):<{sep}} {...
98d74139833608cb7777ee421eff6af39071045a
673,517
def format_skills(text: str, ents: list) -> list: """ Get the list of skills according to the HrFlow.ai Job format @param text: text description of the job @param ents: list of entities in the text @return: list of skills """ skills = [{ "name": text[ent["start"]:ent["end"]].lower(), "value"...
852e340574e5017792aabb51608bd2d66b2e047a
673,518
import csv def write_csv(f, extract, fields=None): """ Writers extract to file handle Parameters __________ f : file handle (string mode) extract: list of dicts fields: list of str Field names to include in CSV. Returns _______ f : file handle (string mode) """ key...
c54b797a71af725eace6958950b5d91bce7e64fb
673,519
from typing import List def _replace_with(items: List[int], value: int) -> List[int]: """Replaces all values in items with value (in-place).""" length = len(items) del items[:] items.extend(length * [value]) return items
4983459883cc34f8d1bf0ca1bfb289e07fc17116
673,520
import requests def token(code, redirect_uri, client_id, client_secret): """Generates access token used to call Spotify API Args: code (str): Authorization code used to generate token redirect_uri (str): Allowed redirect URL set in Spotify's developer dashboard client_id (str): Appli...
a834a0361972fe0828d11d2ff8a29464a30b34c6
673,521
def dropna(df, inplace=True): """remove columns which have all Nans. TO DO: is this needed?""" return df.dropna(axis=1, inplace=inplace)
c3bf9ec89e92d9dc488597df9b9599bebcf555f3
673,522
import hashlib def calculate_pbkdf2_response(challenge: str, password: str) -> str: """ Calculate the response for a given challenge via PBKDF2 """ challenge_parts = challenge.split("$") # Extract all necessary values encoded into the challenge iter1 = int(challenge_parts[1]) salt1 = bytes.fromhex...
61602d59a51aed5992f4b1df9c7171e29b6134f4
673,523