content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def is_mongo_configured(accessor): """ works out if mongodb is configured to run with trackerdash i.e. first time running """ return accessor.verify_essential_collections_present()
c0487f6d899e6cee4f6bbb31bffbd17890812c30
3,946
import ast def maybe_get_docstring(node: ast.AST): """Get docstring from a constant expression, or return None.""" if ( isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str) ): return node.value.value elif ( is...
23171c739f3c9ae6d62ecf3307ac7c3409852d6b
3,947
def _find(xs, predicate): """Locate an item in a list based on a predicate function. Args: xs (list) : List of data predicate (function) : Function taking a data item and returning bool Returns: (object|None) : The first list item that predicate returns True for or None """ ...
94d8dd47e54e1887f67c5f5354d05dc0c294ae52
3,949
def version_for(plugin): # (Plugin) -> Optional[str] """Determine the version of a plugin by its module. :param plugin: The loaded plugin :type plugin: Plugin :returns: version string for the module :rtype: str """ module_name = plugin.plugin.__module__ ...
6d7c4ccc868d11d28c92d1264d52488e22d7f5e5
3,952
def _extract_action_num_and_node_id(m): """Helper method: Extract *action_num* and *node_id* from the given regex match. Convert *action_num* to a 0-indexed integer.""" return dict( action_num=(int(m.group('action_num')) - 1), node_id=m.group('node_id'), )
f1e5f0b81d6d82856b7c00d67270048e0e4caf38
3,953
import re def get_uid_cidx(img_name): """ :param img_name: format output_path / f'{uid} cam{cidx} rgb.png' """ img_name = img_name.split("/")[-1] assert img_name[-8:] == " rgb.png" img_name = img_name[:-8] m = re.search(r'\d+$', img_name) assert not m is None cidx = int(m.group())...
29363f4fc686fa972c2249e5e1db1a333625be36
3,954
import os def file_get_size_in_bytes(path: str) -> int: """Return the size of the file in bytes.""" return int(os.stat(path).st_size)
e9692259d2f5cb8f536cb8c6a0ae53e0b7c6efd1
3,958
def git2pep440(ver_str): """ Converts a git description to a PEP440 conforming string :param ver_str: git version description :return: PEP440 version description """ dash_count = ver_str.count('-') if dash_count == 0: return ver_str elif dash_count == 1: return ver_str.s...
7c4a5185305627c22118722b73b2facfa830875a
3,959
import math def iucr_string(values): """Convert a central value (average) and its s.u. into an IUCr compliant number representation. :param values: pair of central value (average) and s.u. :type values: tuple((float, float)) :return: IUCr compliant representation :rtype: str """ if values...
c6c6602aa0ba481ed5467ed62df59a16f26a8091
3,960
def sse_pack(d): """For sending sse to client. Formats a dictionary into correct form for SSE""" buf = '' for k in ['retry','id','event','data']: if k in d.keys(): buf += '{}: {}\n'.format(k, d[k]) return buf + '\n'
a497c7ab919115d59d49f25abfdb9d88b0963af3
3,961
def filter_dictionary(dictionary, filter_func): """ returns the first element of `dictionary` where the element's key pass the filter_func. filter_func can be either a callable or a value. - if callable filtering is checked with `test(element_value)` - if value filtering is checked ...
f5fa77a51241323845eb9a59adc9df7f662f287b
3,964
def spike_lmax(S, Q): """Maximum spike given a perturbation""" S2 = S * S return ((1.0 / Q) + S2) * (1 + (1.0 / S2))
ba845e3255e4d3eb5116d279a209f4424062603b
3,965
def _get_urls(): """Stores the URLs for histology file downloads. Returns ------- dict Dictionary with template names as keys and urls to the files as values. """ return { "fsaverage": "https://box.bic.mni.mcgill.ca/s/znBp7Emls0mMW1a/download", "fsaverage5": "https://box...
697cf29b3caaeda079014fd342fbe7ad4c650d30
3,966
import struct def guid_bytes_to_string(stream): """ Read a byte stream to parse as GUID :ivar bytes stream: GUID in raw mode :returns: GUID as a string :rtype: str """ Data1 = struct.unpack("<I", stream[0:4])[0] Data2 = struct.unpack("<H", stream[4:6])[0] Data3 = struct.unpack("<H"...
23f013b48806d1d2d4b4bec4ab4a5fcf6fc2e6b0
3,967
from typing import List def two_loops(N: List[int]) -> List[int]: """Semi-dynamic programming approach using O(2n): - Calculate the product of all items before item i - Calculate the product of all items after item i - For each item i, multiply the products for before and after i L[i] = N[i-1] *...
3620aa19833b2e967b2c295fa53ba39bf3b6b70d
3,968
def rgb_to_hex(r, g, b): """Turn an RGB float tuple into a hex code. Args: r (float): R value g (float): G value b (float): B value Returns: str: A hex code (no #) """ r_int = round((r + 1.0) / 2 * 255) g_int = round((g + 1.0) / 2 * 255) b_int = round((b + 1...
a5181c475c798bbd03020d81da10d8fbf86cc396
3,969
def odd(x): """True if x is odd.""" return (x & 1)
9cd383ea01e0fed56f6df42648306cf2415f89e9
3,971
import glob import os def get_file_paths_by_pattern(pattern='*', folder=None): """Get a file path list matched given pattern. Args: pattern(str): a pattern to match files. folder(str): searching folder. Returns (list of str): a list of matching paths. Examples >>> ge...
467485dd4b162654bd73cf412c93558fa43a5b8e
3,972
import re def remove_conjunction(conjunction: str, utterance: str) -> str: """Remove the specified conjunction from the utterance. For example, remove the " and" left behind from extracting "1 hour" and "30 minutes" from "for 1 hour and 30 minutes". Leaving it behind can confuse other intent parsing...
67313565c7da2eadc4411854d6ee6cb467ee7159
3,973
def othertitles(hit): """Split a hit.Hit_def that contains multiple titles up, splitting out the hit ids from the titles.""" id_titles = hit.Hit_def.text.split('>') titles = [] for t in id_titles[1:]: fullid, title = t.split(' ', 1) hitid, id = fullid.split('|', 2)[1:3] titles.a...
fa5bbb47d26adbc61817e78e950e81cc05eca4a6
3,974
from typing import List def read_plaintext_inputs(path: str) -> List[str]: """Read input texts from a plain text file where each line corresponds to one input""" with open(path, 'r', encoding='utf8') as fh: inputs = fh.read().splitlines() print(f"Done loading {len(inputs)} inputs from file '{path}...
27b00f4dfcdf4d76e04f08b6e74c062f2f7374d0
3,975
def distance_constraints_too_complex(wordConstraints): """ Decide if the constraints on the distances between pairs of search terms are too complex, i. e. if there is no single word that all pairs include. If the constraints are too complex and the "distance requirements are strict" flag is set, ...
43429fd64dbf5fa118e2cbf1e381686e1a8518c9
3,976
def _file_path(ctx, val): """Return the path of the given file object. Args: ctx: The context. val: The file object. """ return val.path
7c930f2511a0950e29ffc327e85cf9b2b3077c02
3,977
def Mapping_Third(Writelines, ThirdClassDict): """ :param Writelines: 将要写入的apk的method :param ThirdClassDict: 每一个APK对应的第三方的字典 :return: UpDateWritelines """ UpDateWriteLines = [] for l in Writelines: if l.strip() in list(ThirdClassDict.keys()): UpDateWriteLines.extend(Thir...
eb94db36d06104007cbbacf8884cf6d45fee46b5
3,978
def total_angular_momentum(particles): """ Returns the total angular momentum of the particles set. >>> from amuse.datamodel import Particles >>> particles = Particles(2) >>> particles.x = [-1.0, 1.0] | units.m >>> particles.y = [0.0, 0.0] | units.m >>> particles.z = [0.0, 0.0] | units.m ...
8eca23b7b1a8fc8a7722543f9193f0e4a3397f24
3,979
def find_contiguous_set(target_sum: int, values: list[int]) -> list[int]: """Returns set of at least 2 contiguous values that add to target sum.""" i = 0 set_ = [] sum_ = 0 while sum_ <= target_sum: sum_ += values[i] set_.append(values[i]) if sum_ == target_sum and len(set...
64b6c1f99946856a33a79fed3d43395a5a9c1000
3,981
def move_character(character: dict, direction_index=None, available_directions=None) -> tuple: """ Change character's coordinates. :param character: a dictionary :param direction_index: a non-negative integer, optional :param available_directions: a list of strings, optional :precondition: char...
cc5cc3115437d0dc4e9b7ba7845565ee8147be30
3,982
def scrap_insta_description(inst) -> str: """ Scrap description from instagram account HTML. """ description = inst.body.div.section.main.div.header.section.find_all( 'div')[4].span.get_text() return description
898fa0d1cb44606374b131b8b471178a22ab74ed
3,983
import six import os def file_size(f): """ Returns size of file in bytes. """ if isinstance(f, (six.string_types, six.text_type)): return os.path.getsize(f) else: cur = f.tell() f.seek(0, 2) size = f.tell() f.seek(cur) return size
f999382958a972abbcf593c02e8e8e3609d8f44a
3,984
def __get_from_imports(import_tuples): """ Returns import names and fromlist import_tuples are specified as (name, fromlist, ispackage) """ from_imports = [(tup[0], tup[1]) for tup in import_tuples if tup[1] is not None and len(tup[1]) > 0] return from_imports
28df8225ad9440386342c38657944cfe7ac3d3ca
3,985
import logging import os import sys def logger(): """ Setting upp root and zeep logger :return: root logger object """ root_logger = logging.getLogger() level = logging.getLevelName(os.environ.get('logLevelDefault', 'INFO')) root_logger.setLevel(level) stream_handler = logging.StreamH...
b7f3af5555eae953825c42aed18869deafa9f38d
3,986
def some_function(t): """Another silly function.""" return t + " python"
2bd8adc315e97409758f13b0f777ccd17eb4b820
3,987
import random import hmac def hash_password(password, salthex=None, reps=1000): """Compute secure (hash, salthex, reps) triplet for password. The password string is required. The returned salthex and reps must be saved and reused to hash any comparison password in order for it to match the ...
cac468818560ed52b415157dde71d5416c34478c
3,988
import argparse def _parse_args(): """ Parse arguments for the CLI """ parser = argparse.ArgumentParser() parser.add_argument( '--fovs', type=str, required=True, help="Path to the fov data", ) parser.add_argument( '--exp', type=str, ...
ecea45baba3c89e3fd81613a256c5be300e01051
3,989
def calculate_ani(blast_results, fragment_length): """ Takes the input of the blast results, and calculates the ANI versus the reference genome """ sum_identity = float(0) number_hits = 0 # Number of hits that passed the criteria total_aligned_bases = 0 # Total of DNA bases that passed the cri...
09b649dda337d2b812f5c5fd9ec75b34737e3f15
3,992
def mixed_social_welfare(game, mix): """Returns the social welfare of a mixed strategy profile""" return game.expected_payoffs(mix).dot(game.num_role_players)
72c465211bdc79c9fcf2b1b9d8c7dd5abae5d8df
3,993
def init_app(app): """init the flask application :param app: :return: """ return app
6e460eb1fdc19553c6c4139e60db06daec507a2d
3,995
def _rec_filter_to_info(line): """Move a DKFZBias filter to the INFO field, for a record. """ parts = line.rstrip().split("\t") move_filters = {"bSeq": "strand", "bPcr": "damage"} new_filters = [] bias_info = [] for f in parts[6].split(";"): if f in move_filters: bias_inf...
496056126bdf390a6213dfad5c40c4a14ec35caa
3,996
def classNumber(A): """ Returns the number of transition classes in the matrix A """ cos = 0 if type(A[0][0]) == list: cos = len(A) else: cos = 1 return cos
a71bce468f7429746bfe246d94f5dcebb85c41d4
3,997
def fix_CompanySize(r): """ Fix the CompanySize column """ if type(r.CompanySize) != str: if r.Employment == "Independent contractor, freelancer, or self-employed": r.CompanySize = "0 to 1 Employees" elif r.Employment in [ "Not employed, but looking for work", ...
bd34bb3e72920fb7ef37279a743198387b1c4717
3,998
def upper_camel_to_lower_camel(upper_camel: str) -> str: """convert upper camel case to lower camel case Example: CamelCase -> camelCase :param upper_camel: :return: """ return upper_camel[0].lower() + upper_camel[1:]
e731bbee45f5fc3d8e3e218837ccd36c00eff734
3,999
def get(isamAppliance, cert_dbase_id, check_mode=False, force=False): """ Get details of a certificate database """ return isamAppliance.invoke_get("Retrieving all current certificate database names", "/isam/ssl_certificates/{0}/details".format(cert_dbase_id))
34ade7c42fcc1b1409b315f8748105ee99157986
4,000
import random def t06_ManyGetPuts(C, pks, crypto, server): """Many clients upload many files and their contents are checked.""" clients = [C("c" + str(n)) for n in range(10)] kvs = [{} for _ in range(10)] for _ in range(200): i = random.randint(0, 9) uuid1 = "%08x" % random.randint(...
384aa2b03169da613b25d2da60cdd1ec007aeed5
4,002
import xxhash def hash_array(kmer): """Return a hash of a numpy array.""" return xxhash.xxh32_intdigest(kmer.tobytes())
9761316333fdd9f28e74c4f1975adfca1909f54a
4,004
def PyCallable_Check(space, w_obj): """Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds.""" return int(space.is_true(space.callable(w_obj)))
e5b8ee9bbbdb0fe53d6fc7241d19f93f7ee8259a
4,006
def idxs_of_duplicates(lst): """ Returns the indices of duplicate values. """ idxs_of = dict({}) dup_idxs = [] for idx, value in enumerate(lst): idxs_of.setdefault(value, []).append(idx) for idxs in idxs_of.values(): if len(idxs) > 1: dup_idxs.extend(idxs) return ...
adc8a0b0223ac78f0c8a6edd3d60acfaf7ca4c04
4,007
def aslist(l): """Convenience function to wrap single items and lists, and return lists unchanged.""" if isinstance(l, list): return l else: return [l]
99ccef940229d806d27cb8e429da9c85c44fed07
4,008
import argparse def get_args(): """Parse command line arguments and return namespace object""" parser = argparse.ArgumentParser(description='Transcode some files') parser.add_argument('-c', action="store", dest="config", required=True) parser.add_argument('-l', action="store", dest="limit", type=int, ...
8d811d1ff9437eef6fe5031618f9561248e40940
4,009
import os def _write(info, directory, format, name_format): """ Writes the string info Args: directory (str): Path to the directory where to write format (str): Output format name_format (str): The file name """ #pylint: disable=redefined-builtin file_name = name_forma...
c8f595769607151aa771b4d8d841b4beee77bc9e
4,010
def enough_data(train_data, test_data, verbose=False): """Check if train and test sets have any elements.""" if train_data.empty: if verbose: print('Empty training data\n') return False if test_data.empty: if verbose: print('Empty testing data\n') retu...
f11014d83379a5df84a67ee3b8f1e85b23c058f7
4,011
def compute_time_overlap(appointment1, appointment2): """ Compare two appointments on the same day """ assert appointment1.date_ == appointment2.date_ print("Checking for time overlap on \"{}\"...". format(appointment1.date_)) print("Times to check: {}, {}". format(appointmen...
c459ef52d78bc8dd094d5be9c9f4f035c4f9fcaa
4,012
import hashlib def hash64(s): """Вычисляет хеш - 8 символов (64 бита) """ hex = hashlib.sha1(s.encode("utf-8")).hexdigest() return "{:x}".format(int(hex, 16) % (10 ** 8))
e35a367eac938fdb66584b52e1e8da59582fdb9a
4,014
def inc(x): """ Add one to the current value """ return x + 1
c8f9a68fee2e8c1a1d66502ae99e42d6034b6b5c
4,015
import os import hashlib def hash_file(filename): """ computes hash value of file contents, to simplify pytest assert statements for complex test cases that output files. For cross-platform compatibility, make sure files are read/written in binary, and use unix-style line endings, otherwise hashes ...
e26f92869a44c0e60fcd58764069b0c7828dee95
4,018
def predict_to_score(predicts, num_class): """ Checked: the last is for 0 === Example: score=1.2, num_class=3 (for 0-2) (0.8, 0.2, 0.0) * (1, 2, 0) :param predicts: :param num_class: :return: """ scores = 0. i = 0 while i < num_class: scores += i * ...
ee4038583404f31bed42bed4eaf6d0c25684c0de
4,019
import time def offsetTimer(): """ 'Starts' a timer when called, returns a timer function that returns the time in seconds elapsed since the timer was started """ start_time = time.monotonic() def time_func(): return time.monotonic() - start_time return time_func
348105a408ccedd1fcb840b73d5a58dfd59dd8cc
4,022
import os def _get_sender(pusher_email): """Returns "From" address based on env config and default from.""" use_author = 'GITHUB_COMMIT_EMAILER_SEND_FROM_AUTHOR' in os.environ if use_author: sender = pusher_email else: sender = os.environ.get('GITHUB_COMMIT_EMAILER_SENDER') return ...
09167bfd09ff031d60b4ca033fbb0cad206393f9
4,023
from datetime import datetime def parse_iso8601(dtstring: str) -> datetime: """naive parser for ISO8061 datetime strings, Parameters ---------- dtstring the datetime as string in one of two formats: * ``2017-11-20T07:16:29+0000`` * ``2017-11-20T07:16:29Z`` """ return...
415a4f3a9006109e31ea344cf99e885a3fd2738d
4,026
def splinter_session_scoped_browser(): """Make it test scoped.""" return False
a7587f6edff821bab3052dca73929201e98dcf56
4,028
def maskStats(wins, last_win, mask, maxLen): """ return a three-element list with the first element being the total proportion of the window that is masked, the second element being a list of masked positions that are relative to the windown start=0 and the window end = window length, and the third bein...
b5d75d2e86f1b21bf35cbc69d360cd1639c5527b
4,030
import re def is_youtube_url(url: str) -> bool: """Checks if a string is a youtube url Args: url (str): youtube url Returns: bool: true of false """ match = re.match(r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$", url) return bool(match)
97536b8e7267fb5a72c68f242b3f5d6cbd1b9492
4,031
def time_nanosleep(): """ Delay for a number of seconds and nanoseconds""" return NotImplementedError()
9ec91f2ef2656b5a481425dc65dc9f81a07386c2
4,032
def item_len(item): """return length of the string format of item""" return len(str(item))
7d68629a5c2ae664d267844fc90006a7f23df1ba
4,033
def is_numeric(array): """Return False if any value in the array or list is not numeric Note boolean values are taken as numeric""" for i in array: try: float(i) except ValueError: return False else: return True
2ab0bb3e6c35e859e54e435671b5525c6392f66c
4,034
import platform import os def get_develop_directory(): """ Return the develop directory """ if platform.system() == "Windows": return os.path.dirname(os.path.realpath(__file__)) + "\\qibullet" else: return os.path.dirname(os.path.realpath(__file__)) + "/qibullet"
5654b3c5b2417e8429a3ec2ca310567a185d78a1
4,036
def contains_message(response, message): """ Inspired by django's self.assertRaisesMessage Useful for confirming the response contains the provided message, """ if len(response.context['messages']) != 1: return False full_message = str(list(response.context['messages'])[0]) return...
4afcdba84603b8b53095a52e769d0a8e3f7bbb17
4,037
import re def since(version): """A decorator that annotates a function to append the version of skutil the function was added. This decorator is an adaptation of PySpark's. Parameters ---------- version : str, float or int The version the specified method was added to skutil. Exam...
e6b29b5e4c67ba4a213b183a0b79a1f16a85d81c
4,038
def striptag(tag): """ Get the short representation of a fully qualified tag :param str tag: a (fully qualified or not) XML tag """ if tag.startswith('{'): return tag.rsplit('}')[1] return tag
f0193e3f792122ba8278e599247439a91139e72b
4,039
def equal(* vals): """Returns True if all arguments are equal""" if len(vals) < 2: return True a = vals[0] for b in vals[1:]: if a != b: return False return True
dbd947016d2b84faaaa7fefa6f35975da0a1b5ec
4,041
def get_command(tool_xml): """Get command XML element from supplied XML root.""" root = tool_xml.getroot() commands = root.findall("command") command = None if len(commands) == 1: command = commands[0] return command
8d50b2675b3a6089b15b5380025ca7def9e4339e
4,043
def get_elements(xmldoc, tag_name, attribute): """Returns a list of elements""" l = [] for item in xmldoc.getElementsByTagName(tag_name) : value = item.getAttribute(attribute) l.append( repr( value ) ) return l
2cda65802d0dc1ebbb7796f6a43fa9bacfbe852e
4,044
import os def get_tests_directory() -> str: """ Returns the path of the top level directory for tests. Returns: The path of the top level directory for tests. This is useful for constructing paths to the test files. """ module_file_path = os.path.abspath(__file__) return os.path.dirname(m...
35b445342ea6cf6c6f659118d32b0b8c9724a7e8
4,046
import re def ParseTimeCommandResult(command_result): """Parse command result and get time elapsed. Args: command_result: The result after executing a remote time command. Returns: Time taken for the command. """ time_data = re.findall(r'real\s+(\d+)m(\d+.\d+)', command_result) time_in_seconds...
fc92d4b996716ddb2253bf4eb75ed9860c43b2d7
4,047
def getNumberOfPublicIp(): """Get the total number of public IP return: (long) Number of public IP """ #No need to calculate this constant everytime return 3689020672 # Real implementation: #ranges = getValidPublicIpRange() #number_of_ip = 0 #for range in ranges: # number_of_ip = number_of_ip + (r...
79221376f64d0a44da06746bc28f0bb7db808b0f
4,048
import socket def check_reverse_lookup(): """ Check if host fqdn resolves to current host ip """ try: host_name = socket.gethostname().lower() host_ip = socket.gethostbyname(host_name) host_fqdn = socket.getfqdn().lower() fqdn_ip = socket.gethostbyname(host_fqdn) return host_ip == fqdn_ip ...
4979ba32d03782258f322ec86b2cd1c24fb4de2c
4,049
def get_grains_connected_to_face(mesh, face_set, node_id_grain_lut): """ This function find the grain connected to the face set given as argument. Three nodes on a grain boundary can all be intersected by one grain in which case the grain face is on the boundary or by two grains. It is therefore su...
cb4adff2d6ffe3c32e2a1fc8058e6ad1fed9b2c9
4,050
def argmin(x): """ Returns the index of the smallest element of the iterable `x`. If two or more elements equal the minimum value, the index of the first such element is returned. >>> argmin([1, 3, 2, 0]) 3 >>> argmin(abs(x) for x in range(-3, 4)) 3 """ argmin_ = None min_...
8d6778182bf3c18ffa6ef72093bf19a818d74911
4,051
def find_spot(entry, list): """ return index of entry in list """ for s, spot in enumerate(list): if entry==spot: return s else: raise ValueError("could not find entry: "+ str(entry)+ " in list: "+ str(list))
e218822e5e56a62c40f5680751c1360c56f05f4a
4,052
import os def getPath(path=__file__): """ Get standard path from path. It supports ~ as home directory. :param path: it can be to a folder or file. Default is __file__ or module's path. If file exists it selects its folder. :return: dirname (path to a folder) .. note:: It is the ...
ef1a0997de2febea075b9ce44414c533806f6125
4,053
def geom_to_tuple(geom): """ Takes a lat/long point (or geom) from KCMO style csvs. Returns (lat, long) tuple """ geom = geom[6:] geom = geom.replace(" ", ", ") return eval(geom)
003f25a0ebc8fd372b63453e4782aa52c0ad697c
4,054
import sys def argumentParser(listOfArguments): """Parses arguments""" argumentParserFilter = {} for argument in listOfArguments: if argument in sys.argv: argumentParserFilter[listOfArguments[argument]] = True else: argumentParserFilter[listOfArguments[argument]] ...
939cfea9c6b4f8deec08b4afb73427183b551ccc
4,055
def get_reg_part(reg_doc): """ Depending on source, the CFR part number exists in different places. Fetch it, wherever it is. """ potential_parts = [] potential_parts.extend( # FR notice node.attrib['PART'] for node in reg_doc.xpath('//REGTEXT')) potential_parts.extend( ...
33f4c2bb9a4e2f404e7ef94a3bfe3707a3b1dd93
4,056
def my_join(x): """ :param x: -> the list desired to join :return: """ return ''.join(x)
bffc33247926c2b1ebe1930700ed0ad9bcb483ec
4,058
def template(spec_fn): """ >>> from Redy.Magic.Classic import template >>> import operator >>> class Point: >>> def __init__(self, p): >>> assert isinstance(p, tuple) and len(p) is 2 >>> self.x, self.y = p >>> def some_metrics(p: Point): >>> return p.x + 2 * p...
a8fd64926cdbec73c1a31c20a27174c86af3405e
4,060
def iou_set(set1, set2): """Calculate iou_set """ union = set1.union(set2) return len(set1.intersection(set2)) / len(union) if union else 0
f0087b640e8b9a87167d7e2b645aca3c565e09c1
4,061
import time def time_measured(fkt): """ Decorator to measure execution time of a function It prints out the measured time Parameters ---------- fkt : function function that shall be measured Returns ------- None """ def fkt_wrapper(*args, **kwargs): t1 =...
43fe9fa24fdd27f15e988f5997424dd91f7d92c9
4,062
def test_find_codon(find_codon): """ A function to test another function that looks for a codon within a coding sequence. """ synapto_nuc = ("ATGGAGAACAACGAAGCCCCCTCCCCCTCGGGATCCAACAACAACGAGAACAACAATGCAGCCCAGAAGA" "AGCTGCAGCAGACCCAAGCCAAGGTGGACGAGGTGGTCGGGATTATGCGTGTGAACGTGGAGAAGGTCCT" "GGAG...
1e8906441d7812fbaefd7688a1c02876210ba8b8
4,063
def compose_paths(path_0, path_1): """ The binary representation of a path is a 1 (which means "stop"), followed by the path as binary digits, where 0 is "left" and 1 is "right". Look at the diagram at the top for these examples. Example: 9 = 0b1001, so right, left, left Example: 10 = 0b1010, ...
cffb984c5bacf16691648e0910988495149087ad
4,065
def group_masses(ip, dm: float = 0.25): """ Groups masses in an isotope pattern looking for differences in m/z greater than the specified delta. expects :param ip: a paired list of [[mz values],[intensity values]] :param dm: Delta for looking +/- within :return: blocks grouped by central mass ...
918fc4f20fee7c2955218e3c435f9e672dc55f7d
4,066
import os def get_compliment(file_list, file): """Returns a file path from the provided list that has the same name as the file passed as the second arugment. :param file_list: A list of paths with the same filetype. :type file_list: list :param file: A single path with an opposite filetype. ...
9841207dc2ead05a1fde42baeea72e05323fb6ea
4,067
def load_string_list(file_path, is_utf8=False): """ Load string list from mitok file """ try: with open(file_path, encoding='latin-1') as f: if f is None: return None l = [] for item in f: item = item.strip() if ...
600c2678fdcdf6d5fa4894dd406f74c1ae4e5a96
4,068
import math def point_based_matching(point_pairs): """ This function is based on the paper "Robot Pose Estimation in Unknown Environments by Matching 2D Range Scans" by F. Lu and E. Milios. :param point_pairs: the matched point pairs [((x1, y1), (x1', y1')), ..., ((xi, yi), (xi', yi')), ...] :ret...
2d691bbf04d14e3e5b0f9273a7501d934bd0eef4
4,069
def bind_port(socket, ip, port): """ Binds the specified ZMQ socket. If the port is zero, a random port is chosen. Returns the port that was bound. """ connection = 'tcp://%s' % ip if port <= 0: port = socket.bind_to_random_port(connection) else: connection += ':%i' % port ...
5613bae6726e2f006706b104463917e48d7ab7ca
4,071
def update_target_graph(actor_tvars, target_tvars, tau): """ Updates the variables of the target graph using the variable values from the actor, following the DDQN update equation. """ op_holder = list() # .assign() is performed on target graph variables with discounted actor graph variable values f...
15f0d192ff150c0a39495b0dec53f18a8ae01664
4,072
def strtime(millsec, form="%i:%02i:%06.3f"): """ Time formating function Args: millsec(int): Number of milliseconds to format Returns: (string)Formated string """ fc = form.count("%") days, milliseconds = divmod(millsec, 86400000) hours, milliseconds = divmod(millsec, 3...
9a1cff92086491941d8b27857169bf7744da8324
4,073
import argparse def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Run train or eval scripts for Gated2Depth') parser.add_argument("--base_dir", help="Path to dataset", required=True) parser.add_argument("--train_files_path", help="Path to file with train fi...
afb3f6d55b87c917225811f3716b9ecf1fcb494e
4,074
def plugin_last(): """This function should sort after other plug-in functions""" return "last"
d2d6c00bc8d987363bd4db0013950d9b3f524c2f
4,075
def extract_shebang_command(handle): """ Extract the shebang_ command line from an executable script. :param handle: A file-like object (assumed to contain an executable). :returns: The command in the shebang_ line (a string). The seek position is expected to be at the start of the file and will b...
27174f96f2da3167cf7a7e28c4a2f1cec72c773c
4,076
import json def clone_master_track(obj, stdata, stindex, stduration): """ ghetto-clone ('deep copy') an object using JSON populate subtrack info from CUE sheet """ newsong = json.loads(json.dumps(obj)) newsong['subsong'] = {'index': stindex, 'start_time': stdata['index'][1][0], 'duration': std...
6721a87abfc88d9dd75f597ff24caf5857be594a
4,077
def create_graph(num_islands, bridge_config): """ Helper function to create graph using adjacency list implementation """ adjacency_list = [list() for _ in range(num_islands + 1)] for config in bridge_config: source = config[0] destination = config[1] cost = config[2] ...
b961f5ee2955f4b8de640152981a7cede8ca80b0
4,078