content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def list2string(ls): """Print a list as a string""" s = " ".join(ls) return s
2c9e5b3a04cb2bf6f06c15bdf11ad9e3b827ce75
634,635
import random def shred(d, prefix=None, existing=False, contigs=10000, minsize=500, maxsize=10000): """ Generate random shreds of input fasta file :param d: Dictionary of sequences :param prefix: Prefix string to append to random contigs :param existing: Use existing prefix string ('|' ...
1bad7ebb04613c4edce26704fca533fe4bcf6121
634,636
def str2int(val): """ Converts a decimal or hex string into an int. Also accepts an int and returns it unchanged. """ if type(val) is int: return int(val) if len(val) < 3: return int(val, 10) if val[:2] == '0x': return int(val, 16) return int(val, 10)
dadddb6a82b3243735c1b0136a6ccc266820bd5b
634,638
def check_file_extension(filename, extension_list): """ Check if the extension file match with the authorized extension list :param string filename: Filename to check :param list extension_list: The list of extension the file have to match to :return: True if the extension is correct, False...
91f184fc940b8d71c77ebd56a5d229a864906421
634,639
def human_bytes(n): """ Return the number of bytes n in more human readable form. """ if n < 1024: return '%d B' % n k = n/1024 if k < 1024: return '%d KB' % round(k) m = k/1024 if m < 1024: return '%.1f MB' % m g = m/1024 return '%.2f GB' % g
ddd920d7ccf62eabac882e05409e0625e3517b07
634,642
def format_integer(number, group_size=3): """Formats integers into groups of digits.""" assert group_size > 0 number = str(number) parts = [] while number: number, part = number[:-group_size], number[-group_size:] parts.append(part) number = ' '.join(reversed(parts)) return number
2e690a3bd1beb1cd5cb2c8f3504fc938ae63b377
634,643
def surrogate_pairs(code_point): """Return the UTF-16 high and low surrogates for a unicode code point. Arguments: code_point -- A string representation of the form 'U+xxxxx' or '\Uxxxxxxxx' Returns: A tuple containing the surrogate pairs as hexadecimal strings: (high, low), or (code_point,) i...
79f6e3dcbcc29001080fb3e656e1feb9747d635e
634,647
import colorsys def get_spaced_colors(n): """Create n evenly spaced RGB colors :param n: number of colors needed source: https://stackoverflow.com/questions/876853/generating-color-ranges-in-python """ hsv_tuples = [(x * 1.0 / n, 0.5, 0.5) for x in range(n)] rgb_tuples = map(lambda x: colorsy...
95245962fe719ec6eb13d79d2b5dcbf23900a2ae
634,659
def get_all_moves(coord): """ Return a list of all coordinates reachable from this one """ return [{'x': coord['x'], 'y': coord['y'] + 1}, {'x': coord['x'], 'y': coord['y'] - 1}, {'x': coord['x'] + 1, 'y': coord['y']}, {'x': coord['x'] - 1, 'y': coord['y']}]
307459c52f5d6baa68ec1a1b9088e74d6629d6b7
634,670
def below(prec, other_prec): """Whether `prec` is entirely below `other_prec`.""" return prec[1] < other_prec[0]
20337d8d507fc3b4a85c5c2abe5c8c014437d3af
634,673
def _find_lines_from_point(d={}, ptag=-1): """Find lines that have the given point tag Parameters ---------- d : Dictionary GMSH dictionary ptag : int point tag Returns ------- ltag : int List of line tags """ lines = list() for s_data in d.values():...
de2d5234161208906c05c5a013b70312e9c056c1
634,674
def _crc_update(crc, data, mask, const): """ CRC8/16 update function taken from _crc_ibutton_update() function found in "Atmel Toolchain/AVR8 GCC/Native/3.4.1061/ avr8-gnu-toolchain/avr/include/util/crc16.h" documentation. @param[in] crc current CRC value @param[in] data next byte of data @p...
6538b1720faca541b3ab741451e0dc9dcd20c77c
634,678
def xor(bytes_1, bytes_2): """XOR two bytearrays of the same length.""" l1 = len(bytes_1) l2 = len(bytes_2) assert l1 == l2 result = bytearray(l1) for i in range(l1): result[i] = bytes_1[i] ^ bytes_2[i] return result
69e2b5bb175280da88eac2cecba7f512bf18ab8a
634,682
def cgi2dict(form, linelist): """Convert the form from cgi.FieldStorage to a python dictionary""" params = {'linelist': linelist.value} for key in form.keys(): if key != 'linelist': params[key] = form[key].value return params
c935c8f3393439a6632cd4a70c7a684c3ce42a85
634,683
def _2d_distance_squared(position1, position2): """calculate the square of the distance bwtween two 2D coordinate tuples""" return (position1[0] - position2[0]) ** 2 + (position1[1] - position2[1]) ** 2
3ad48b310fa6cbd238dc8c52738432d49a1263de
634,685
def read_target_positions(file_path, filter_chromosomes): """ reads a bed file and returns a list of tuples containing genomic coordinates """ if filter_chromosomes==None: filter_chromosomes = [] else: print('filtering out: ' + ' '.join(filter_chromosomes)) with open(file_path) a...
37f03029ebfb5e6be70c5f9d0abd59d1887ff8ac
634,687
from typing import List from typing import Tuple from typing import Dict from typing import Union def tags_to_filter( tags: List[Tuple[str, str]] ) -> List[Dict[str, Union[str, List[str]]]]: """Turn list of tuples with tag name and value in to AWS format.""" return [{"Name": f"tag:{tag[0]}", "Values": [ta...
5d44342d1611b1e1b1d70bb400bd3d600bcfe05b
634,688
def get_unbound_arg_names(arg_names, arg_binding_keys): """Determines which args have no arg binding keys. Args: arg_names: a sequence of the names of possibly bound args arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is in arg_names Returns: a sequence of...
92d5ff319c1f96bb246a5d65c93b05b3440df508
634,689
def apply_type_recognizers(recognizers, type_obj): """Apply the given list of type recognizers to the type TYPE_OBJ. If any recognizer in the list recognizes TYPE_OBJ, returns the name given by the recognizer. Otherwise, this returns None.""" for r in recognizers: result = r.recognize(type_obj)...
199c99016a33979638c2fb14b8ed38a125267f7b
634,692
def rgb_color(color: str) -> tuple: """Convert an RGB color string to an RGB tuple. >>> rgb_color('#fff') (15, 15, 15) >>> rgb_color('#500100') (80, 1, 0) """ color = color.lstrip('#') if len(color) == 3: return (int(color[0], 16), int(color[1], 16), ...
7b3d6e39db1940190cc695df2bd2a1b234594423
634,693
def huffman_encoding_recursion(node, code=''): """ Encoding characters using recursion Args: node(HuffManTreeNode): leaf to save data and non-leaf node assign 0 and 1 to edges code(str): Assign 0 to the left edge and 1 to the right edge Returns: encode_map(dict) : huffman coding map...
ef1f6ec37e895ba12065ac32034a9f64886ad0e2
634,695
def label2nodename(label): """ convert label e.g. '(1,2)' to nodename e.g. 'n1c2' """ lsplit = label.split(',') return 'n' + lsplit[0][1:] + 'c' + lsplit[1][:-1]
aebb5120d4ea539fe8f91de888c08ed802280539
634,697
import socket def is_ipv6(ip: str) -> bool: """ A helper function that checks if a given IP address is a valid IPv6 one. Parameters ---------- ip: :class:`str` A string representing an IP address. """ try: socket.inet_pton(socket.AF_INET6, ip) return True e...
271e52c2b34fe0675e7039212f31308f3a4fa2c3
634,700
def read_form_field_string(model, form, field_name, transformation=None): """ :param model: Model containing string field :param form: Form data from front-end :param field_name: Name of field shared by model and form :param transformation: Transformation of form data to perform before inserting int...
f1b2730189f99dbd0a32ab1912b00d3a20bac268
634,701
def MAV(data): """ Mean absolute value: the average of the absolute value of the signal. Parameters ---------- data: array-like 2D matrix of shape (time, data) Returns ------- MAVData: 1D numpy array containing average absolute value Reference --------- Hudgins, B., Parker, P., & Scott, R. N. ...
3d67b7057b26807694c26dc850cc518dac042623
634,704
def linear_interpolation(pos): """ Easing function for animations: Linear Interpolation. """ return pos
b632d1efb0d3383a5b53cfc43dd9385793427148
634,705
def get_github_path(owner: str, repo: str) -> str: """Get github path from owner and repo name""" return "%s/%s" % (owner, repo)
189cae1d577ccb32ed5fa0c6f0a0a98fb74768c4
634,708
import itertools def natoms(self): """ Sequence of number of sites of each type associated with the Poscar. Similar to 7th line in vasp 5+ POSCAR or the 6th line in vasp 4 POSCAR. """ return [len(tuple(a[1])) for a in itertools.groupby(self.syms)]
e4348815be3768a280766addbccfaf5d659ccfca
634,711
def recookie(wrapped): """ Decorator to mark a session as needing to recookie. This is necessary when setting a new max-age/etc :param wrapped: a function to wrap with this decorator. :returns wrapped_recookie: a wrapped function. """ def wrapped_recookie(session, *arg, **kw): resu...
c9d525ff4f8e70be266b9143ba1cef15a07a0552
634,713
def convertDate(time): """ Returns the converted time, accept only this format DD/MM/YYYY Parameters: time (string) Returns: time (int): return converted time as this format YYYYMM, so year and month """ tmp = time.split("/") retu...
135a148e3a5b5d82c7e8706e92c766ee118a9ebb
634,714
def mutindex2pos(x, start, end, mut_pos): """ Convert mutation indices back to genome positions """ if x == -.5: return start elif x == len(mut_pos) - .5: return end else: i = int(x - .5) j = int(x + .5) return (mut_pos[i] + mut_pos[j]) / 2.0
06e09a0a3281ab2de076e28a32cc08e37c610fce
634,718
def peel(event): """ Remove an event's top-level skin (where its flavor is determined), and return the core content. """ return list(event.values())[0]
47e1cf4f98cd42f4a7e34bdad83cff76c4f54df0
634,725
from typing import Dict import json def cors_web_response(status_code: int, body: Dict[str, str]): """Create a response when dealing with CORS.""" return { 'statusCode': status_code, 'headers': { 'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,X-Amz-Security-Token,Authoriz...
8bbc5c7a8acb96f727e74ef31c31af3084c8260c
634,727
def parse_env_var_args(env_var_args): """ :param List[str] env_var_args: List of arguments in the form "VAR_NAME" or "VAR_NAME=VALUE" :return: Dict[str,str] Mapping from "VAR_NAME" to "VALUE" or empty str. """ env_vars = {} if env_var_args is not None: for arg in env_var_...
ab18432454eb10ee2459aac3e2f690a23988f145
634,733
def get_active_sessions_orchestrator( self, ) -> list: """Get all current active sessions on Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - activeSessions - GET - /session/activeSessions :return:...
3dd38d66816e2bdace27ab24b6609ec44ee02057
634,734
def file_parser_old(line, config): """ Parse Markdown page for compomics.github.io pages: - Replace wiki URLs to pages URLs """ line = line.replace( "https://github.com/{}/{}/wiki/".format(config['user'], config['project_name']), "https://compomics.github.io/projects/{}/wiki/".forma...
aee0e7d106422d2b94838949eb029680b454dc5b
634,735
import re def preprocess_sentences(sentences, SOS, EOS): """ Preprocess the input text by lowercasing adding space around punctuation removing strange characters tokenizing on whitespace (optional) reversing the words as suggested by the Seq2Seq paper adding <SOS> and <EOS>...
2710e2f2e8a5f475fedf1620e05b7abf83eb9c10
634,736
def moving_avg(xyw, avg_len): """ Calculate a moving average for a given averaging length :param xyw: output from collapse_into_single_dates :type xyw: dict :param avg_len: average of these number of points, i.e., look-back window :type avg_len: int :return: list of x values, list of y value...
5dbd2c596942638f0c0158e11c6b24e6f5a1ef4b
634,737
import copy def _filter_change_sets(change_sets: list, artifact_filter) -> list: """Filter the change sets with given artifact filter """ result = [] for commit in change_sets: mod_commit = copy.deepcopy(commit) # grab only source files mod_commit["file_path"] = list( ...
2a680214ae29b3e736077c864b2f7d9339d2a6fa
634,738
def _tls_version_check(version, min): """Returns if version >= min, or False if version == None""" if version is None: return False return version >= min
cead61442b56de46ae79af80c58bc2b8f2586c26
634,743
def get_serializer_error_response(error): """ Returns error response from serializer :param str error: message :return: error_response :rtype: object """ error_response = {"status": 422, "data": [], "message": error} return error_response
a9e7555535e8f75e5fbac2e427b26035fdcc5487
634,748
def standardize(X): """Z-transform an array param X: An N x D array where N is the number of examples and D is the number of features returns: An N x D array where every column has been rescaled to 0 mean and unit variance """ return (X - X.mean())/X.std(ddof=1)
35e60ed5d73de36fdc80b1d2189033d0c81a6d9b
634,749
def default_prompt(category: str) -> str: """Create the user prompt for selecting categories of options. Args: category (str): The type of thing being selected (assignment, section, etc) Returns: str: The user prompt """ return f"Which {category} would you like to grade? >>> "
9ac72c6ce3e82630197d7301d256d6867ac7fa32
634,750
from typing import List from typing import Tuple import torch def create_grid( grid_sizes: List[int], grid_bounds: List[Tuple[float, float]], extend: bool = True, device="cpu", dtype=torch.float, ) -> List[torch.Tensor]: """ Creates a grid represented by a list of 1D Tensors representing t...
f784bcf1177579e61f7794cecc645c0bbc338929
634,757
import uuid def generate_slug(model) -> str: """Generate a unique slug Args: model (cls): Django Model Returns: slug (string) """ query_manager = model.objects slug = uuid.uuid4().hex[:6] while query_manager.filter(slug=slug).exists(): slug = uuid.uu...
5219320b740083843a10055eb8b78409624fcebf
634,760
def extract_indices_python( original_indices, selected_indices, pid, selected_pid, preserve_particle_index ): """ Go through the sorted arrays `pid` and `selected_pid`, and record the indices (of the array `pid`) where they match, by storing them in the array `selected_indices` (...
6d5d4259ca01ae7bff38cf2017d8c7a1382063f3
634,766
def get_biggest_face(array_of_faces): """ :param array_of_faces: array of faces returned from detector.detectMultiScale() :return: a 1x4 array containing the face with the biggest area (width*height) """ largest_area = 0 largest_face = None for face in array_of_faces: area = face[2] ...
904fafe95756ee164da09e49f286027d8ceceefb
634,767
def escapeAttr(sText): """ Escapes special character to HTML-safe sequences. """ sText = sText.replace('&', '&amp;') sText = sText.replace('<', '&lt;') sText = sText.replace('>', '&gt;') return sText.replace('"', '&quot;')
38fdd523bd69c0239e722a3368a585c04b1106a7
634,770
def area(r, shape_constant): """Return the area of a shape from length measurement R.""" assert r > 0, 'A length must be positive' return r * r * shape_constant
e3a3a1178d053ee6857b2cb33b1106d2c5ee294b
634,772
import hashlib def generate_hash(value, hash='sha1'): """ Generate a hash for a given value. By default generate a `sha1` hash. Other hash can be specified. If so all supported hash algorithms are listed in `hashlib.algorithms`. Returns a String. """ sha_obj = getattr(hashlib, hash...
b14aee9b4091020f27cdca1c5df2cef19eaf2f41
634,773
import re def extract_words(sentstr, stops): """ simple utility to word tokenize a text string and remove stop words :param sentstr: input string of text :param stops: list of stop words to remove :return: """ words = re.sub(r"[^\w]", " ", sentstr).split() cleaned_text = [w.lower() for...
8868af10e3ee4924a7fe341b8a5fa0e624fe1bba
634,774
def TTD_TT_UB_rule(M, i, j, w, t): """ Every day of every week for each (window, ttype), there can be no more people scheduled (TourTypeDay) than number of people assigned to TourType[window, ttype]. :param M: Model :param i: window :param j: day :param w: week :param t: tour type ...
7ff1cbd45e518a76bf94dd30d09e1a1da1bef5a1
634,775
def word_count(data): """ 输入一个字符串列表,统计列表中字符串出现的次数 参数 ---- data: list[str],需要统计的字符串列表 返回 ---- re: dict,结果hash表,key为字符串,value为对应的出现次数 """ re = {} for i in data: re[i] = re.get(i, 0) + 1 return re
40edfdcf65e5312ee302b341ba61921fd9f5a46e
634,777
import random def gen_next_match_pick_randomly(population): """ Decides next two player indexes who will play against each other by randomly selecting two players from the list of players available""" available_players = [player for player in population if player.available] p1 = random.choice(availab...
50d980169fe39f356831be06d50500eab959bb21
634,780
def list_or_none(lst): """Returns a stringified list or 'None'.""" return ",".join(map(str, lst)) if lst else "None"
5cd555fb07c99e6570d3e53bea5c216d2dcb7cbf
634,781
def GetDimensions(line): """ Parse and extract X, Y and Z dimensions from string Parameters ---------- line: string Line containing x, y, z dimensions Returns ------- (nx,ny,nz): (int,int,int) The dimensions on x, y, and z coordinate respectively ...
39d314cc6892f89a7c5cbfbd363fc2167c319071
634,782
def get_serial_number_key(serial_num: str) -> str: """Get the compressed search serial number key for the MH serial number.""" key: str = '' if not serial_num: return key key = serial_num.strip().upper() if len(key) > 20: return key[0:20] return key
a1dc1836bf5dbc71d2b7275c6b180c1c15e49c36
634,784
def isValidId(id_, v=0x0110000100000000, y=1): """Reverse Steam ID formula taking full community ID and decoding the account ID. Args: id_ (int) : steam community id v (int, optional) : account type, defaults to user: 0x0110000100000000 y (int, optional) : account universe, defaults to p...
8f9a2b8809ba855095c758c33984f714c8b3b33f
634,788
import re def cut_iframes(value): """ Filter which cut <iframe> tags. """ pattern = re.compile(r'<p><iframe .*</iframe></p>') return re.sub(pattern, '', value)
a8ab5e1f0c1c55a225c7d041374aba041d10e6d2
634,791
from datetime import datetime def timestamp_from_dt(dt, epoch=datetime(1970, 1, 1)): """ Convert a datetime to a timestamp. https://stackoverflow.com/a/8778548/141395 """ delta = dt - epoch # return delta.total_seconds() return delta.seconds + delta.days * 86400
700486da04340fd433aa427ef7a537a72554a371
634,796
def _get_specie_str(specie, include_phase): """Gets the specie string Parameters ---------- specie : :class:`~pmutt.empirical.nasa.Nasa` object Specie to use include_phase : bool, optional If True, includes the reaction phase. Default is True Returns ------- ...
33c4e11e7476f12e49b9ce3dd69fa17808d0d6b1
634,797
def critical_events_in_outputs(healthcheck_outputs): """Given a list of healthcheck pairs (output, healthy), return those which are unhealthy. """ return [healthcheck for healthcheck in healthcheck_outputs if healthcheck[-1] is False]
38a36b0f2d3d42fb5e86ebf0ab69efbe121b576a
634,814
def align_origin(origin, w, h, align=('left','top')): """Calculates size of text box and returns an origin as if aligned from the given origin. Accepted alignments are: left, center, right top, center, bottom""" if align==('left','top'): return origin aligns = {'left': 0, 'center':...
2fbc673a309c73177251107016e7e2c8a42f469e
634,815
import inspect def _build_transform_name(lag, tfm, *args) -> str: """Creates a name for a transformation based on `lag`, the name of the function and its arguments.""" tfm_name = f'{tfm.__name__}_lag-{lag}' func_params = inspect.signature(tfm).parameters func_args = list(func_params.items())[1:] # re...
38efdf4a815a33a1d6620f16b475068b77c9d475
634,816
def _GetFailedRevisionFromCompileResult(compile_result): """Determines the failed revision given compile_result. Args: compile_result: A dict containing the results from a compile. Please refer to try_job_result_format.md for format check. Returns: The failed revision from compile_results, or None i...
c30a537102a785ddf2d93a98fd3e16c552048215
634,820
import urllib.request def read_url(url): """Send a GET request to a given URL and read the response. References ---------- - https://docs.python.org/3/howto/urllib2.html - https://docs.python.org/3/library/http.client.html#httpresponse-objects """ with urllib.request.urlopen(url) as res...
9b84ac0969a38b39a689780f4aa2d89108b0e6c5
634,821
def k_func(h,s_H,s_K,g,n,alpha,phi,delta,k): """args:     h     (float): Human capital     s_h   (float): Investments in human capital     s_k   (float): Investments in physical capital     g     (float): Growth in technology     n     (float): Growth rate of population/labour force     delta (float): Depreciation ...
732fbea0c3c7ef2e710593f6825574a0577f1313
634,823
def agenda_format_day( number_of_days_before, date_start, cfg_today, cfg_tomorrow, cfg_in_days, ): """ Formats the string who indicates if the event is today, tomorrow, or else in an arbitrary number of day. Args: number_of_days_before (int): The number of days before th...
770fd712d0a6bf56ca8ae80132b40bc4802e4f34
634,824
def minmax(x): """ Returns a tuple containing the min and max value of the iterable `x`. .. note:: this also works if `x` is a generator. >>> minmax([1, -2, 3, 4, 1, 0, -2, 5, 1, 0]) (-2, 5) """ (minItem, maxItem) = (None, None) for item in x: if (minItem is None) or (item < m...
f2127bf8cb6d444d97f23b147590d94265b5480c
634,826
def daily_return(t_df): """ add daily return column to the data frame """ dlyr = t_df['Close'].shift(1) / t_df['Close'] - 1 t_df['Daily Return'] = dlyr * 100 return t_df
b6a1d8e5dee0dfaa4226e8c63ccc45fb7ee9f95c
634,829
def count_entities(entities, project=None, locale=None): """Count the number of entities (i.e. source strings) with the given project and/or locale.""" count = 0 for ent in entities: if (project is None or project == ent["project"]) and ( locale is None or locale == ent["locale"] ...
84d3c9837f6d8f1826bd81322628879fb960c387
634,831
import struct def read_spectrum(filestream, n): """Reads n mz and intensity pairs from existing .sbd filestream. Assumes double precision for mass and single for intensity. Returns: Tuple:tuple of mz and intensity vectors """ mzs = struct.unpack("<%dd" % n, filestream.read(8 * n))...
69727085c671d43a6be53f2af7623fe8108c1560
634,832
def crop_image(new_width, new_height, image): """ Method to crop a given input image to new width and height specifications given. Args: new_width: Width of the cropped image new_height: Height of the cropped image image: Image object to be processed Returns: The croppe...
26b447955785b988b1ff39c3199df0de8469a9a4
634,837
import pytz def local_time_obj(time, course): """ Get a Datetime object in a course's locale from a TZ Aware DT object.""" if not time.tzinfo: time = pytz.utc.localize(time) return time.astimezone(course.timezone)
27e916cbeff884d90ed4d9f5adc7ebb67ffe9866
634,838
from typing import Sequence def moving_average(source: Sequence[float], window_size: int): """ Compute a simple moving average from a source list. Arguments: source: The source list of data from which to compute the moving average. window_size: The size of the moving average to com...
83f7d3f2e20f143749e21eb4fc4ac1afa2d452e1
634,840
def minimum_grade(parsed_list, passing_grade, overall_min=True): """ This function calculates the minimum grade from the given grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_min: True, when calculating the minimum of all th...
2ffbecd3177964ae89be8bedf8ee7a0884affea0
634,844
def detect_faces(image, cascade, scale_factor, min_neighbours): """ Detect faces visible on the image. :param cascade: cascade object used for detection :param image: analyzed image :param scale_factor: subsequent detections scaling coefficient :param min_neighbours: minimum detection neighbours...
973d08e53c8ba58efab72855b52ba012f88c08c5
634,845
def cuberoot(x): """Finds the cube root of x""" return x**(1./3.)
64adfcc3307c42c86677c0cc405099150b92d1b6
634,849
def strip_tags(body): """Delete the first and last line if they full of hashtags. Also strip every line of unnecessary whitespaces.""" lines = body.split('\n') # remove last line if full of hashtags for word in lines[-1].split(): if word[0] != '#': break else: del li...
c05d7874cad5f76668e78b55911688afdb1865e3
634,853
def createProtein(element): """ Create dictionary representation of Protein element from Percolator XML output """ defns = element.nsmap[None] #default namespace protein = {} protein["ID"] = element.get("{{{}}}protein_id".format(defns)) protein["q-value"] = float(element.find("{{{}}}q_v...
42eb7283d61eaad68cd8e01e7a1ad0f3d4d930f6
634,855
def get_params_fit(data_pt, params_fix): """Returns the fitted parameters a specific data point depends on.""" data_pt_params = ( ( data_pt.get_fitting_parameter_names() | data_pt.get_fixed_parameter_names() ) - params_fix ) return data_pt_params
5bb33377ac6e99537617997c9ac37e69fa73981b
634,858
def _re_word_boundary(r): """ Adds word boundary characters to the start and end of an expression to require that the match occur as a whole word, but do so respecting the fact that strings starting or ending with non-word characters will change word boundaries. """ # we can't use \b as it c...
bdd97d11f610c11380323ecacd9351d0be1c29a4
634,859
import re def split_documents_by_feature_value(input_dict): """ Split Annotated Document Corpus by conditions with features and values. :param adc: Annotated Document Corpus :param feature_condition: split condition. :param discard_filtered_out default-false: discard documents that do not fulfil...
2eec11d18110f5602be189131c6a9d55e39bd524
634,863
def get_properties(schema): """ Return the three properties we have to enforce for this schema. Returns tuple of (enforce, default, and required), where enforce is a custom function, default is the default value for this attribute, and required is a boolean. """ if isinstance(schema, dict): ...
e0dbe110138aad66277b68c8b1f896dd66f735a0
634,864
from typing import Optional def _get_reasonable_file_label(uri: str) -> Optional[str]: """ Get a label for the dataset from a URI.... if we can. >>> uri = '/tmp/some/ls7_wofs_1234.nc' >>> _get_reasonable_file_label(uri) 'ls7_wofs_1234.nc' >>> uri = 'file:///g/data/rs0/datacube/002/LS7_ETM_NBA...
1d01642355bf1ba557fd67bf14cfaf7351373cda
634,865
def merge(nums1, nums2): """ Merge two given sorted arrays by merge sort :param nums1: first array :type nums1: list[int] :param nums2: second array :type nums2: list[int] :return: merged array :rtype: list[int] """ result = [] i = j = 0 while i < len(nums1) and j < len(...
4ec45d0c65bb85f45d9b8266bba268ace22177f6
634,872
def is_audit_type(*args): """This audit is included in the specified kinds of audits. :param *args: List of AuditTypes to include this audit in :type args: List[AuditType] :rtype: Callable[Dict] """ def _is_audit_type(audit_options): if audit_options.get('audit_type') in args: ...
8ad52d1313f3529f8bb2aef10ccbbf31d0f2dfba
634,873
def count_blocks(documents): """ Counts the total number of blocks in a list of documents Args: documents(metadata.MetaDocument): The list of documents Returns: int: Size of the list """ return sum([len(doc.blocks) for doc in documents])
947a051478a2202c5880a678cdf6ab7fd4a33958
634,875
def get_day_offset(day, number): """ Returns an integer representing the day number shifted by the given amount """ day -= number if day < 0: day += 7 return day
6713f43144993f14b56626539bf2f10f17fd722d
634,876
def is_logged_in(soup): """ checks from code snippet whether user is logged in phpbb signatures Not Logged in <a href="./ucp.php?mode=login" title="Anmelden" accesskey="x" role="menuitem"> <i class="icon fa-power-off fa-fw" aria-hidden="true"></i><span>_log on message_</span> ...
5aa165ac70110eb46316841bcf3a91145a5f39f1
634,883
import uuid def generate_uuid(length): """Generates hex uuid with customized length. Example: d9f3a7e8 Args: length (int): number of digits of uuid """ return str(uuid.uuid4().hex)[:length]
f3526392cb968bc1eb6ccdf84f262a34320960eb
634,884
import re def normalize_whitespace(string): """Normalize whitespace in string Deletes consecutive spaces and newlines """ return re.sub("\n+", "\n", re.sub(" +", " ", string))
88d6ece45f2d1c538fcde17e6ed26f4cea617aaf
634,885
def get_api_key(filepath): """Read a local file with your API key.""" api = [] with open(filepath) as f: for line in f: api.append(line.strip()) assert len(api) == 1, "API key should be only one line long." return api[0]
26ebc04945d561a73e09a546d65da922444dcff5
634,886
def count_non_ascii_chars(file_path: str) -> int: """Counts non ascii characters and returns their amount. Args: file_path: the pathname (absolute or relative to the current working directory) of the file to be opened. Returns: amount of non ascii characters. """ amount = ...
7401779ddab968b9793f988fd04d90043a95ce5a
634,888
def sample_var_var(std, n): """ The variance of the sample variance of a distribution. Assumes the samples are normally distributed. From: //math.stackexchange.com/q/72975 `std`: Distribution's standard deviation `n`: Number of samples """ return 2.0 * std ** 4 / (n - 1.0)
12b86fdfd244255d0e0df58633ebf1e2cd249e8a
634,890
import re def is_input(line): """ Determines whether or not a read in line contains an uncommented out \input{} statement. Allows only spaces between start of line and '\input{}'. """ #tex_input_re = r"""^\s*\\input{[^}]*}""" # input only tex_input_re = r"""(^[^\%]*\\input{[^}]*})|(^[^\%]*\\in...
90c1781b4b1355458fd79aa39b14987ec080840f
634,899
def DoSlash(sDirName): """Add a tailing slash if missing. """ return sDirName if sDirName[-1]=="/" else sDirName+"/"
a61b8cc4b901ebf69ac5223c642c42d347160faf
634,902
def create_bucket_list(domain, affixes=[]): """ Create a set of buckets based on a domain name and a list of affixes. Note: This will be very large. Args: domain (str): Domain to add affixes to, such as google.com regions (list): List of AWS regions to query against. affixes (...
519d33445f022b475385bf1b99efd5a00c1fe464
634,903
import secrets def get_random_number(min: int, max: int) -> int: """ Gets a random number between min and max inclusive. """ rand = secrets.SystemRandom() return rand.randint(min, max)
51c247f09521afa9257b3b347ec7b566e2474569
634,904
import math def round_decimals_up(number, decimals=2): """ Returns a value rounded up to a specific number of decimal places. """ if not isinstance(decimals, int): raise TypeError("decimal places must be an integer") elif decimals < 0: raise ValueError("decimal places has to be 0 o...
5a5a305d81b05e25437d96d7d45e7902df2a2494
634,906