content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
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
6,437
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
6,439
def get_page_index(obj, amongst_live_pages=True): """ Get oage's index (a number) within its siblings. :param obj: Wagtail page object :param amongst_live_pages: Get index amongst live pages if True or all pages if False. :return: Index of a page if found or None if page d...
fd1950533a398019ab0d3e208a1587f86b134a13
6,441
def depth(data): """ For each event, it finds the deepest layer in which the shower has deposited some E. """ maxdepth = 2 * (data[2].sum(axis=(1, 2)) != 0) maxdepth[maxdepth == 0] = 1 * ( data[1][maxdepth == 0].sum(axis=(1, 2)) != 0 ) return maxdepth
aa48c88c516382aebe2a8b761b21f650afea82b1
6,442
import argparse def parse_args(args): """Parse the command line arguments.""" parser = argparse.ArgumentParser( description='STOMP client for Network Rail\'s public data.' ) subparsers = parser.add_subparsers() # Creation of new configuration files create_parser = subparsers.add_parser...
632b3702f6a3b3837b58ca39b7290081e7a3fb94
6,443
def env_start(): """ returns numpy array """ global maze, current_position current_position = 500 return current_position
ed377adedc48159607a4bb08ea6e3624575ec723
6,444
import math def plagdet_score(rec, prec, gran): """Combines recall, precision, and granularity to a allow for ranking.""" if (rec == 0 and prec == 0) or prec < 0 or rec < 0 or gran < 1: return 0 return ((2 * rec * prec) / (rec + prec)) / math.log(1 + gran, 2)
f8debf876d55296c3945d0d41c7701588a1869b6
6,446
def get_matrix_header(filename): """ Returns the entries, rows, and cols of a matrix market file. """ with open(filename) as f: entries = 0 rows = 0 cols = 0 for line in f.readlines(): if line.startswith('%'): continue line = line.s...
66200661715cb9a67522ced7b13d4140a3905c28
6,447
def minOperations(n): """ finds min. operations to reach and string """ if type(n) != int or n <= 1: return 0 res = 0 i = 2 while(i <= n + 1): if (n % i == 0): res += i n /= i else: i += 1 return res
c26cbd71c6e675adea79938b6e7248a4c093e63f
6,449
import numpy def gfalternate_createdataandstatsdict(ldt_tower,data_tower,attr_tower,alternate_info): """ Purpose: Creates the data_dict and stat_dict to hold data and statistics during gap filling from alternate data sources. Usage: Side effects: Called by: Calls: Author: PRI ...
a1690fb9e53abcd6b23e33046d82c10a2ca7abc0
6,450
def get_satellite_params(platform=None): """ Helper function to generate Landsat or Sentinel query information for quick use during NRT cube creation or sync only. Parameters ---------- platform: str Name of a satellite platform, Landsat or Sentinel only. params """ ...
2298c100eed431a48a9531bc3038c5ab8565025d
6,451
import os import http async def process_file(path, request_headers): """Serves a file when doing a GET request with a valid path.""" sever_root="/opt/vosk-server/websocket/web" MIME_TYPES = { "html": "text/html", "js": "text/javascript", "css": "text/css" } if "Upgrade" in...
d51d2ff1ec27185c31fc4eff3dfed8243e6d1764
6,453
import requests def get_token(corp_id: str, corp_secret: str): """获取access_token https://open.work.weixin.qq.com/api/doc/90000/90135/91039 """ req = requests.get( f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}' ) return req.json().get('access_t...
9a9c3fcdb74312b5d2d7c62588aea3cf78796ec9
6,456
def list_agg(object_list, func): """Aggregation function for a list of objects.""" ret = [] for elm in object_list: ret.append(func(elm)) return ret
b2d8eef9c795e4700d111a3949922df940435809
6,459
def parse_word(word: str) -> str: """Compile a word of uppercase letters as numeric digits. Non-uppercase letter words are returned unchanged.""" if not word.isupper(): return word compiled_word = " + ".join([letter + "*" + str(10**index) for index, letter in enumerate(word[:: -1])]) return "(" ...
aa246c7d5e92035f14476327f5b2b694b383f7e1
6,460
import os def check_directory(directory, verbose): """ Inputs: graph_directory- the directory for the graphs to be place verbose- the verbose flag Checks to see if the graph directory exists. If it doesn't exit, the folder is created. """ cwd = os.getcwd() + '/' if not os...
2d76f00f4438a97e4fc91d3b23b74c94015385c5
6,461
def relu_backward(dout, cache): """ Backward pass for the ReLU function layer. Arguments: dout: numpy array of gradient of output passed from next layer with any shape cache: tuple (x) Output: x: numpy array of gradient for input with same shape of dout ...
3384ddf789ed2a31e25a4343456340a60e5a6e11
6,462
import os def via_sudo(): """ Return `True` if Blueprint was invoked via `sudo`(8), which indicates that privileges must be dropped when writing to the filesystem. """ return 'SUDO_UID' in os.environ \ and 'SUDO_GID' in os.environ \ and 'blueprint' in os.environ.get('SUDO_COMMAND',...
c30c3e21f5bd780e42c37a0248a1406edf44bd44
6,463
import collections def find_identities(l): """ Takes in a list and returns a dictionary with seqs as keys and positions of identical elements in list as values. argvs: l = list, e.g. mat[:,x] """ # the number of items in the list will be the number of unique types uniq = [item for item, coun...
db7b64cc430ab149de7d14e4f4a88abafbadbe34
6,465
def all_children(wid): """Return all children of a widget.""" _list = wid.winfo_children() for item in _list: if item.winfo_children(): _list.extend(item.winfo_children()) return _list
ca52791b06db6f2dd1aeedc3656ecf08cb7de6d8
6,466
def getGeneCount(person, geneSetDictionary): """ determines how many genes a person is assumed to have based upon the query information provided """ if person in geneSetDictionary["no_genes"]: gene_count = 0 elif person in geneSetDictionary["one_gene"]: gene_count = 1 else: ...
0fef236dd805ae77f04a22670752031af15ca5b2
6,468
def _mgSeqIdToTaxonId(seqId): """ Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId") @param seqId: sequence id used in mg databases @return: taxonId @rtype: int """ return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[...
2ce74f453e3496c043a69b4205f258f06bfd0452
6,471
def url_to_filename(url): """Converts a URL to a valid filename.""" return url.replace('/', '_')
db3023c582590a47a6adc32501a2e3f5fd72f24f
6,472
def get_definitions_query_filter(request_args): """ Get query_filter for alert_alarm_definition list route. """ query_filters = None display_retired = False valid_args = ['array_name', 'platform_name', 'instrument_name', 'reference_designator'] # Process request arguments if 'retired' in req...
a087cbd9ca6ffe9b38afc2d8802c12e4dfd47e50
6,475
import re def targetInCol(df, target): """ Return meta information (Line or Area) from information in a column of DF. Arguments: doc -- csv Promax geometry file target -- meta information to get (Line or Area) """ c = list(df.columns) ptarget = r''+re.escape(target) i = [i for i, ...
5d40cf251bd2a7593a46a5b63b5de3a56f8cec29
6,476
def add_transformer_enc_hyperparams_args(parser): """Only applicable when args.model_name is 'transformer_enc'""" parser.add_argument('--hid_dim', type=int, default=128) parser.add_argument('--num_enc_layers', type=int, default=3) parser.add_argument('--num_enc_heads', type=int, default=8) parser.ad...
bc38c3cc1d9fc7e87cebfbf7bdc74f8e9d0a124e
6,478
import os def get_data_path(): """ Return the path to the project's data folder :return: The path to the data folder """ project_folder = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) return os.path.join(project_folder, "data")
351d11a22b56567f59858e0e0f092661beedaed6
6,479
import math def calc_mupen_res(N,region_w,region_h): """find res to fit N mupen instances in region""" results = [] for row_length in range(1,N+1): col_length = math.ceil(N/float(row_length)) instance_width = int(math.floor( min(640, region_w/float(row_length) ))) instance_height = int(math.floor(...
35b5e739102097d856b7c2e154516d4e866a1567
6,480
def package_dir_path(path): """Return package path to package install directory""" return path + '/.pkg'
edd4b97256ccf02a3f1165b99cae746826e8aee0
6,481
def get_params_out_of_range( params: list, lower_params: list, upper_params: list ) -> list: """ Check if any parameter specified by the user is out of the range that was defined :param params: List of parameters read from the .inp file :param lower_params: List of lower bounds provided by the user...
67a8ca57a29da8b431ae26f863ff8ede58f41a34
6,483
from pathlib import Path def read_file(in_file: str): """Read input file.""" file_path = Path(in_file) data = [] count = 0 with open(file_path) as fp: for line in fp: data.append(line) count = count + 1 return ''.join(data), count
4fbae8f1af7800cb5f89784a0230680a1d6b139a
6,484
def limit(value, limits): """ :param <float> value: value to limit :param <list>/<tuple> limits: (min, max) limits to which restrict the value :return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to t...
55fb603edb478a26b238d7c90084e9c17c3113b8
6,485
import random def DiceRoll(): """A function to simulate rolling of one or more dice.""" def Roll(): return random.randint(1,6) print("\nRoll Dice: Simulates rolling of one or more dice.") num = 1 try: num = int(input("\nEnter the number of dice you wish to roll: ")) except: print...
90e9587473fb06541ec9daa2ec223759940a5ecb
6,486
import sys def do_verify(options, _fuse): """ @param options: Commandline options @type options: object @param _fuse: FUSE wrapper @type _fuse: dedupsqlfs.fuse.dedupfs.DedupFS """ tableOption = _fuse.operations.getTable("option") curHashFunc = tableOption.get("hash_function") ...
cba45a78cf57422bcca2b01909666fe0fdcb72a1
6,488
def is_byte_array(value, count): """Returns whether the given value is the Python equivalent of a byte array.""" return isinstance(value, tuple) and len(value) == count and all(map(lambda x: x >= 0 and x <= 255, value))
16793415885ea637aecbeeefe24162d6efe9eb39
6,489
def _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices): """Filter substructure match atom indices by atom map indices corresponding to atom map numbers. """ if AtomMapIndices is None: return list(AtomIndices) ...
3594a11452848c9ae11f770fa560fe29d68aa418
6,490
def worker_mode(self): """ bool: Whether or not all MPI ranks are in worker mode, in which all worker ranks are listening for calls from the controller rank. If *True*, all workers are continuously listening for calls made with :meth:`~_make_call` until set to *False*. By default, this is *False...
45d256e47bfeffe9e3878297c6009061801e5d8d
6,491
from typing import Any from typing import Set import inspect from unittest.mock import Mock def _get_default_arguments(obj: Any) -> Set[str]: """Get the names of the default arguments on an object The default arguments are determined by comparing the object to one constructed from the object's class's in...
483fe82dd79aadfe1da387fb0c602beb503f344b
6,493
def collatz(number): """If number is even (number // 2) else (3 * number + 1) Args: number (int): number to collatz Returns: int: collatz number """ if (number % 2) == 0: print(number // 2) return number // 2 print(3 * number + 1) return 3 * number + 1
221fd238bd6d0c40c9cb80be2c58746bb206c17b
6,494
def get_disk_at(board, position): """ Return the disk at the given position on the given board. - None is returned if there is no disk at the given position. - The function also returns None if no disk can be obtained from the given board at the given position. This is for instance...
4b793ce1947b2f71d666b1d1676ca894f43c3b58
6,495
def firstUniqChar(s): """ :type s: str :rtype: int """ if len(s) == 0: return -1 if len(s) == 1: return 0 hash_table = {} for i in s: if i not in hash_table: hash_table[i] = 1 else: hash_table[i] += 1 for i in s: if hash...
25148de95099094991339bb0fe6815644e5b94cb
6,496
from typing import Optional from typing import Tuple import re def parse_test_stats_from_output(output: str, fail_type: Optional[str]) -> Tuple[int, int]: """Parse tasks output and determine test counts. Return tuple (number of tests, number of test failures). Default to the entire task representing a si...
8ec67d226c2280eb08de3589cba7b6aa0a09024c
6,497
from typing import List from typing import Tuple from typing import Dict def _constraint_items_missing_from_collection( constraints: List[Tuple], collection: Dict[str, int] ) -> List[str]: """ Determine the constrained items that are not specified in the collection. """ constrained_items = se...
918667f1e8b001637c9adf00ef5323b2e8587775
6,498
import csv def main(file_in, file_out): """ Read in lines, flatten list of lines to list of words, sort and tally words, write out tallies. """ with open(file_in, 'r') as f_in: word_lists = [line.split() for line in f_in] # Flatten the list # http://stackoverflow.com/questions/95...
225dd5d5b4c2bcb158ee61aa859f78e1e608a5fe
6,500
def load_atomic(val): """ Load a std::atomic<T>'s value. """ valty = val.type.template_argument(0) # XXX This assumes std::atomic<T> has the same layout as a raw T. return val.address.reinterpret_cast(valty.pointer()).dereference()
307bcc9d3eae2eede6a8e2275104280a1e7b4b94
6,501
def dataId_to_dict(dataId): """ Parse an LSST dataId to a dictionary. Args: dataId (dataId): The LSST dataId object. Returns: dict: The dictionary version of the dataId. """ return dataId.to_simple().dict()["dataId"]
77b7566492b80a8c6e2becacafff36737c8a7256
6,502
def getHoliday(holidayName): """Returns a specific holiday. Args: holidayName (str): The name of the holiday to return. Case-sensitive. Returns: HolidayModel: The holiday, as a HolidayModel object, or None if not found. """ print(holidayName) return None
15b67fd6ac607d1ff12a216cc3c4baab61305be6
6,503
import six import hashlib def hash_mod(text, divisor): """ returns the module of dividing text md5 hash over given divisor """ if isinstance(text, six.text_type): text = text.encode('utf8') md5 = hashlib.md5() md5.update(text) digest = md5.hexdigest() return int(digest, 16) % d...
3f127837bb072df5ee609b3afa80dd04e4f7b794
6,504
def _get_exploration_memcache_key(exploration_id): """Returns a memcache key for an exploration.""" return 'exploration:%s' % exploration_id
1400607cc86f84c242201c9c9fe36a7a06cd2357
6,505
def pairs_from_array(a): """ Given an array of strings, create a list of pairs of elements from the array Creates all possible combinations without symmetry (given pair [a,b], it does not create [b,a]) nor repetition (e.g. [a,a]) :param a: Array of strings :return: list of pairs of strings """ pairs = l...
50c489d660a7e82c18baf4800e599b8a3cd083f0
6,507
def shared_options(option_list): """Define decorator for common options.""" def _shared_options(func): for option in reversed(option_list): func = option(func) return func return _shared_options
7ef551ea9879b708e6b449ce1155d47b662efd3d
6,509
from typing import Any def complex_key(c: complex) -> Any: """Defines a sorting order for complex numbers.""" return c.real != int(c.real), c.real, c.imag
55c17b0d4adf8bcfb39b50c66d5bd8133f5bb814
6,510
def get_campaign_goal(campaign, goal_identifier): """Returns goal from given campaign and Goal_identifier. Args: campaign (dict): The running campaign goal_identifier (string): Goal identifier Returns: dict: Goal corresponding to goal_identifer in respective campaign """ i...
1a8738416ee8187ad2a6a977b36b68f66052bfe8
6,511
def getChanprofIndex(chanprof, profile, chanList): """ List of indices into the RTTOV chanprof(:) array corresponding to the chanlist. NB This assumes you've checked the chanlist against chanprof already. """ ilo = sum(map(len, chanprof[:profile-1])) ichanprof = [] for c in chanList: ...
e61e210e8b05fdfbf3a769f4b5b388d765d436b9
6,512
import argparse def parse_args(): """Accepts path arguments for eml or directory.""" outpath = "C:\\Utilities\\Logs" parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="Path to EML file", required=False) parser.add_argument("-p", "--path", help="Dir...
61c4fcc5bd4278a2dd3c32aa3fd9a779f0f2ff3e
6,513
import bisect def find_dataset_ind(windows_ds, win_ind): """Taken from torch.utils.data.dataset.ConcatDataset. """ return bisect.bisect_right(windows_ds.cumulative_sizes, win_ind)
76abcbdf9718cc59f1d2b7ca8daacc062970b253
6,514
def _unsigned16(data, littleEndian=False): """return a 16-bit unsigned integer with selectable Endian""" assert len(data) >= 2 if littleEndian: b0 = data[1] b1 = data[0] else: b0 = data[0] b1 = data[1] val = (b0 << 8) + b1 return val
22feb074aca7f4ab7d489eacb573c3653cad9272
6,515
def calculate_term_frequencies(tokens): """Given a series of `tokens`, produces a sorted list of tuples in the format of (term frequency, token). """ frequency_dict = {} for token in tokens: frequency_dict.setdefault(token, 0) frequency_dict[token] += 1 tf = [] for token...
b764175cd59fe25c4a87576faee2a76273097c5e
6,516
def get_dlons_from_case(case: dict): """pull list of latitudes from test case""" dlons = [geo[1] for geo in case["destinations"]] return dlons
666ab789761e99749b4852a51f5d38c35c66bd2a
6,517
def horiLine(lineLength, lineWidth=None, lineCharacter=None, printOut=None): """Generate a horizontal line. Args: lineLength (int): The length of the line or how many characters the line will have. lineWidth (int, optional): The width of the line or how many lines of text the line will take spa...
64a4e9e22b480cbe3e038464fe6e0061e023d2c2
6,520
import math def _rescale_read_counts_if_necessary(n_ref_reads, n_total_reads, max_allowed_reads): """Ensures that n_total_reads <= max_allowed_reads, rescaling if necessary. This function ensures that n_total_reads <= max_allowed_reads. If n_total_reads is <= max_allowed_r...
d09b343cee12f77fa06ab467335a194cf69cccb4
6,521
import os from pathlib import Path def getFilesFromPath(path): """returns all files corresponding to path parameter""" raw = os.listdir(Path(path)) files_to_return = list() for i in raw: if i != ".DS_Store": files_to_return.append(i) return files_to_return
a2248b0a57a722fd9412bb80f49d3d8e8b5b6b69
6,522
import logging import os def get_pages(root_path): """ Reads the content folder structure and returns a list of dicts, one per page. Each page dict has these keys: path: list of logical uri path elements uri: URI of the final rendered page as string file_path: physical path of the...
acc6887638e2d6f6950d4e38556b155e22a6999f
6,524
def load_dict(path): """ Load a dictionary and a corresponding reverse dictionary from the given file where line number (0-indexed) is key and line string is value. """ retdict = list() rev_retdict = dict() with open(path) as fin: for idx, line in enumerate(fin): text = line.stri...
31a67c2a28518a3632a47ced2889150c2ce98a78
6,525
def strip(string, p=" \t\n\r"): """ strip(string, p=" \t\n\r") """ return string.strip(p)
1be2a256394455ea235b675d51d2023e8142415d
6,528
def get_square(array, size, y, x, position=False, force=False, verbose=True): """ Return an square subframe from a 2d array or image. Parameters ---------- array : 2d array_like Input frame. size : int Size of the subframe. y : int Y coordinate of the center of the s...
8d83d4d16241e118bbb65593c14f9f9d5ae0834c
6,530
import json def read_json(json_file): """ Read input JSON file and return the dict. """ json_data = None with open(json_file, 'rt') as json_fh: json_data = json.load(json_fh) return json_data
4e1ea153d040ec0c3478c2d1d3136eb3c48bfe1c
6,531
def alt_or_ref(record, samples: list): """ takes in a single record in a vcf file and returns the sample names divided into two lists: ones that have the reference snp state and ones that have the alternative snp state Parameters ---------- record the record supplied by the vcf reader ...
abaccfeef02ee625d103da88b23fce82a40bc04c
6,534
def is_const_component(record_component): """Determines whether a group or dataset in the HDF5 file is constant. Parameters ---------- record_component : h5py.Group or h5py.Dataset Returns ------- bool True if constant, False otherwise References ---------- .. https://...
4adb2ff7f6fb04086b70186a32a4589ae9161bb5
6,535
import pytz def isodate(dt): """Formats a datetime to ISO format.""" tz = pytz.timezone('Europe/Zagreb') return dt.astimezone(tz).isoformat()
d07118e188772ec6a87d554c6883530164eeb550
6,536
def _ncells_after_subdiv(ms_inf, divisor): """Calculates total number of vtu cells in partition after subdivision :param ms_inf: Mesh/solninformation. ('ele_type', [npts, nele, ndims]) :type ms_inf: tuple: (str, list) :rtype: integer """ # Catch all for cases where cell subdivision is not perf...
981db31a7729c0cac88575b1cb12505a30cf0abb
6,537
def isStringLike(s): """ Returns True if s acts "like" a string, i.e. is str or unicode. Args: s (string): instance to inspect Returns: True if s acts like a string """ try: s + '' except: return False else: return True
73fc002843735536c159eed91cf54886f52e78e7
6,538
def compat(data): """ Check data type, transform to string if needed. Args: data: The data. Returns: The data as a string, trimmed. """ if not isinstance(data, str): data = data.decode() return data.rstrip()
51d2d37b427e77b038d8f18bebd22efa4b4fdcce
6,541
def rsa_decrypt(cipher: int, d: int, n: int) -> int: """ decrypt ciphers with the rsa cryptosystem :param cipher: the ciphertext :param d: your private key :param n: your public key (n) :return: the plaintext """ return pow(cipher, d, n)
33822a0a683eca2f86b0e2b9b319a42806ae56cc
6,542
import yaml def config_get_timesteps(filepath): """Get list of time steps from YAML configuration file. Parameters ---------- filepath : pathlib.Path or str Path of the YAML configuration file. Returns ------- list List of time-step indices (as a list of integers). "...
8a51e1437edbf2d73884cb633dbf05e9cfe5a98d
6,543
def merge_cv_results(cv_results): """ Means across CV """ dtypes = ["train", "dev", "test"] props_l1 = ["mean_loss", "mean_accuracy", "mean_positive_f1", "UL-A", "Joint-A"] props_l2 = ["accuracy", "positive_f1"] merged_results = {} for dtype in dtypes: merged_results[dt...
854b0672ec31103136ad3c7285311f865a098159
6,544
from typing import List from typing import Tuple def _broads_cores(sigs_in: List[Tuple[str]], shapes: Tuple[Tuple[int, ...]], msg: str ) -> Tuple[List[Tuple[int, ...]], List[Tuple[int, ...]]]: """Extract broadcast and core shapes of arrays Parameters ...
228cbe06e4bc1e092cf92034255bfd60f01664c1
6,545
import json import logging def _ParseStepLogIfAppropriate(data, log_name): """PConditionally parses the contents of data, based on the log type.""" if not data: return None if log_name.lower() == 'json.output[ninja_info]': # Check if data is malformatted. try: json.loads(data) except Valu...
4f2ef1f451c271adf0285ae90f88cf10b6e8d9be
6,546
import os def check_bash_path(fname): """Check if file is in your bash path and executable (i.e. executable from command line), and prepend path to it if so. Arguments: ---------- fname : str Filename to check. Returns: -------- fname : str Potentially updated filename w...
09269ac74daa21c9e47ca50c85f89db3212e40bc
6,548
def cal_rank_from_proc_loc(pnx: int, pi: int, pj: int): """Given (pj, pi), calculate the rank. Arguments --------- pnx : int Number of MPI ranks in x directions. pi, pj : int The location indices of this rank in x and y direction in the 2D Cartesian topology. Returns ------...
97146de9f69dd2f62173c19dfdb98d8281036697
6,549
def _chg_float(something): """ floatに変換できたらfloatに変換する """ try: f = float(something) return f except ValueError: pass return something
d0119c255b0842b2de4e60293c8037ff6f75b181
6,551
def filter_matches(matches, threshold=0.75): """Returns filterd copy of matches grater than given threshold Arguments: matches {list(tuple(cv2.DMatch))} -- List of tupe of cv2.DMatch objects Keyword Arguments: threshold {float} -- Filter Threshold (default: {0.75}) Returns: li...
c2cbec1da42d96575eb422bfdda6a1351e24508b
6,553
import string import random def createRandomStrings(l,n,chars=None,upper=False): """create list of l random strings, each of length n""" names = [] if chars == None: chars = string.ascii_lowercase #for x in random.sample(alphabet,random.randint(min,max)): if upper == True: ...
678b5aeb3cc98ae2b47822500fcbaff05081058a
6,554
def get_previous_quarter(today): """There are four quarters, 01-03, 04-06, 07-09, 10-12. If today is in the last month of a quarter, assume it's the current quarter that is requested. """ end_year = today.year end_month = today.month - (today.month % 3) + 1 if end_month <= 0: end_year -= 1 end_mo...
4175c80d2aa75c0e3e02cdffe8a766c4a63686d0
6,555
def get_payload(address): """ According to an Address object, return a valid payload required by create/update address api routes. """ return { "address": address.address, "city": address.city, "country": str(address.country), "first_name": address.first_name, ...
34fde5090aae774a24a254ea7dd7f03cc0f784be
6,556
def Material (colorVector): """ Material color. """ if colorVector == None: return None else: assert isinstance (colorVector, (list, tuple)) assert len (colorVector), 3 for cid in range (0, 3): assert colorVector[cid] >= 0 assert colorVector[ci...
89cee73c485669786f1a7cc4855ad8460c9db023
6,558
import math def auto_border_start(min_corner_point, border_size): """Determine upper-right corner coords for auto border crop :param min_corner_point: extreme corner component either 'min_x' or 'min_y' :param border_size: min border_size determined by extreme_frame_corners in vidstab process :return:...
e09d48a8c8c59053516357cbfd320cf92a080cc4
6,559
import configparser def bootPropsConfig(artifact, resources, targetDir, scalaVersion = "2.13.1"): """Create the configuration to install an artifact and its dependencies""" scala = {} scala["version"] = scalaVersion app = {} app["org"] = artifact.org app["name"] = artifact.name app["vers...
66b8a4d641b3b1728e1d99c3f7bd7104806cdc50
6,560
import tempfile import subprocess def convert_BigWig2Wig(fname, path_to_binary=None): """ uses the UCSC bigwigToWig to do the conversion, ready for reading """ tmp_path = tempfile.mkdtemp() success=subprocess.check_call(["BigWig2Wig", fname, "%s/out.wig" % ...
97286ac5b36257f5522e94ae15ffd5772d54d726
6,561
import torch def string_to_tensor(string, char_list): """A helper function to create a target-tensor from a target-string params: string - the target-string char_list - the ordered list of characters output: a torch.tensor of shape (len(string)). The entries are the 1-shifted ind...
eb6c7fcccc9802462aedb80f3da49abec9edc465
6,562
def _add_sld_boilerplate(symbolizer): """ Wrap an XML snippet representing a single symbolizer in the appropriate elements to make it a valid SLD which applies that symbolizer to all features, including format strings to allow interpolating a "name" variable in. """ return """ <StyledLayerDescri...
971199333570d5bc7baefec88f35b92922ef6176
6,564
def sequence_names_match(r1, r2): """ Check whether the sequences r1 and r2 have identical names, ignoring a suffix of '1' or '2'. Some old paired-end reads have names that end in '/1' and '/2'. Also, the fastq-dump tool (used for converting SRA files to FASTQ) appends a .1 and .2 to paired-end reads if option -I ...
645ac09011cc4b94c5b6d60bf691b6b1734d5b6b
6,565
def get_wccp_service_group_settings( self, ne_id: str, cached: bool, ) -> dict: """Get per-group WCCP configuration settings from appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - wccp - GET - /wccp...
75e07296893eabafbbf0285134cf33cb3eb46480
6,566
import os import re def commonpath(paths): """py2 compatible version of py3's os.path.commonpath >>> commonpath([""]) '' >>> commonpath(["/"]) '/' >>> commonpath(["/a"]) '/a' >>> commonpath(["/a//"]) '/a' >>> commonpath(["/a", "/a"]) '/a' >>> commonpath(["/a/b", "/a"])...
94b92bd6802cc7483db2e3e05b8fb6a8a9630372
6,568
def map_currency(currency, currency_map): """ Returns the currency symbol as specified by the exchange API docs. NOTE: Some exchanges (kraken) use different naming conventions. (e.g. BTC->XBT) """ if currency not in currency_map.keys(): return currency return currency_map[currency]
98b235952b042109a4e2083ce6c8fd85690c22e3
6,569
def _check_type(value, expected_type): """Perform type checking on the provided value This is a helper that will raise ``TypeError`` if the provided value is not an instance of the provided type. This method should be used sparingly but can be good for preventing problems earlier when you want to rest...
a18ecfe9d63e6a88c56fc083da227a5c12ee18db
6,570
def get_patch_info(shape, p_size): """ shape: origin image size, (x, y) p_size: patch size (square) return: n_x, n_y, step_x, step_y """ x = shape[0] y = shape[1] n = m = 1 while x > n * p_size: n += 1 while p_size - 1.0 * (x - p_size) / (n - 1) < 50: n += 1 w...
b681f355ffbf3c7f5653996cd021950e2c9689d4
6,571
def addCol(adjMatrix): """Adds a column to the end of adjMatrix and returns the index of the comlumn that was added""" for j in range(len(adjMatrix)): adjMatrix[j].append(0) return len(adjMatrix[0])-1
29ee11953cbdb757e8ea80e897751059e42f1d90
6,572
import subprocess def get_shell_python_version(command='python -V'): """ Get version of Python running in shell | None --> tuple Use command keyword to test python3 instead of python if python version is Python 2. Minor version is not used at present but is included in case it is needed in futur...
27e441adb062c236881e4fc85d9e55db0962e4bc
6,573
def calculate_average(result): """Calculates the average package size""" vals = result.values() if len(vals) == 0: raise ValueError("Cannot calculate average on empty dictionary.") return sum(vals)/float(len(vals))
ea4b66b41533b0e8984b5137c39c744eec9d3e1f
6,575