content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def in_box(coords, box): """ Find if a coordinate tuple is inside a bounding box. :param coords: Tuple containing latitude and longitude. :param box: Two tuples, where first is the bottom left, and the second is the top right of the box. :return: Boolean indicating if the coordinates are in the box....
ed4082b6311929e4982b4196ceaa566b05dfd714
682,804
def batch_delete(query, session): """ Delete the result rows from the given query in batches. This minimizes the amount of time that the table(s) that the query selects from will be locked for at once. """ n = 0 query = query.limit(25) while True: if query.count() == 0: ...
eb10e259267882011581a46409a5464520304852
682,805
def to_triplets(colors): """ Coerce a list into a list of triplets. If `colors` is a list of lists or strings, return it as is. Otherwise, divide it into tuplets of length three, silently discarding any extra elements beyond a multiple of three. """ try: colors[0][0] return...
809a8c57d2f590fb2984124efe86814850bb8921
682,807
import random import string def random_text(n) : """Generate random text 'n' characters""" return ''.join([random.choice(string.digits + string.ascii_letters) for x in range(n)])
c8f6b14983a5f5712d6da8f6374dca8f5997ed07
682,808
import six import re def to_bytes(value): """Convert numbers with a byte suffix to bytes. """ if isinstance(value, six.string_types): pattern = re.compile('^(\d+)([K,M,G]{1})$') match = pattern.match(value) if match: value = match.group(1) suffix = match.gro...
a2e686d56bd2bed9918ea4e8a165de36d54994e8
682,810
def is_perfect_slow(n): """ decides if a given integer n is a perfect number or not this is the straightforward implementation """ if n <= 0: return(False) sum = 0 for i in range(1,n): if n % i == 0: sum += i return(sum == n)
efd570f4d4e7eb4d6fde87705f4f0e515d0abe24
682,812
def licence_name_to_file_name(licence_name: str) -> str: """ Converts a licence name to the name of the file containing its definition. :param licence_name: The licence name. :return: The file name. """ return licence_name.lower().replace(" ", "-") + ".txt"
d74bd90f5b6c65cd662b88dc69f361507dc47bb2
682,817
def format_position(variant): """Gets a string representation of the variants position. Args: variant: third_party.nucleus.protos.Variant. Returns: A string chr:start + 1 (as start is zero-based). """ return '{}:{}'.format(variant.reference_name, variant.start + 1)
215534a2905622835a99f6945b73ac4fbe13e1f1
682,820
def score(goal, test_string): """compare two input strings and return decimal value of quotient likeness""" #goal = 'methinks it is like a weasel' num_equal = 0 for i in range(len(goal)): if goal[i] == test_string[i]: num_equal += 1 return num_equal / len(goal)
c50a2c3f2ff95d129e8816e4384d9b39ebd0e44b
682,827
import copy def pad_1d_list(data, element, thickness=1): """ Adds padding at the start and end of a list This will make a shallow copy of the original eg: pad_1d_list([1,2], 0) -> returns [0,1,2,0] Args: data: the list to pad element: gets added as padding (if its an object, ...
2228307755053728f3ab11540d6673f5d6e8fa1f
682,831
def process_single(word): """ Process a single word, whether it's identifier, number or symbols. :param word: str, the word to process :return: str, the input """ if word[0].isnumeric(): try: int(word) except ValueError: raise ValueError("Expression {} no...
0a08fd6ed7402fb4351adff8fb7f59106fbe4ca8
682,833
def remove_non_seriasable(d): """ Converts AnnotationType and EntityType classes to strings. This is needed when saving to a file. """ return { k: str(val.name).lower() if k in ('annotation_type', 'entity_type') else val for k, val in d.items() ...
30a9b50685ca5140ff99c7c98586fdee86d21212
682,836
def merge_dictionaries(dict1, dict2): """Merge dictionaries together, for the case of aggregating bindings.""" new_dict = dict1.copy() new_dict.update(dict2) return new_dict
cd1445c458a42414a90b7d8c3810885ab351b46e
682,838
def transpose(matrix): """ Compute the matrix transpose :param matrix: the matrix to be transposed, the transposing will not modify the input matrix :return: the transposed of matrix """ _transposed = [] for row in range(len(matrix)): _transposed.append( [matrix[i...
2dd0db2737fe1691d414c207c88fd8419c1860b6
682,843
def rivers_with_station(stations): """Given a list of stations, return a alphabetically sorted set of rivers with at least one monitoring station""" river_set = set() for station in stations: river_set.add(station.river) river_set = sorted(river_set) return river_set
16161ababf034709e095406007db42e10b47c921
682,845
def permute(lst, perm): """Permute the given list by the permutation. Args: lst: The given list. perm: The permutation. The integer values are the source indices, and the index of the integer is the destination index. Returns: A permutation copy of lst. """ return tuple([...
b12be0a40251d51e314e313996e1e11c60e4748c
682,849
import socket def gethostbyaddr(ip): """ Resolve a single host name with gethostbyaddr. Returns a string on success. If resolution fails, returns None. """ host = None try: host = socket.gethostbyaddr(ip)[0] except OSError: pass return host
5e7c041171ea4fbaa75fa477f64121db5f05cd39
682,851
import torch import math def gain_change(dstrfs, batch_size=8): """ Measure standard deviation of dSTRF gains. Arguments: dstrfs: tensor of dSTRFs with shape [time * channel * lag * frequency] Returns: gain_change: shape change parameter, tensor of shape [channel] """ ...
a64840f2d7d46869c226614da0977b21bc0140b9
682,854
def multiply(*fields, n): """ Multiply ``n`` to the given fields in the document. """ def transform(doc): for field in fields: doc = doc[field] doc *= n return transform
7697b0c21ecb6e77aedbaa60035c73f1fcee8239
682,855
def to_matrix_vector(transform): """Split an homogeneous transform into its matrix and vector components. The transformation must be represented in homogeneous coordinates. It is split into its linear transformation matrix and translation vector components. This function does not normalize the matri...
ff64c6e93bfe8794e0a342bdc449bb42a05dc577
682,858
def prompt_int(prompt): """ Prompt until the user provides an integer. """ while True: try: return int(input(prompt)) except ValueError as e: print('Provide an integer')
9352b78cd01466654d65ed86482f7163000ec1c4
682,860
def check_overlap(stem1, stem2): """ Checks if 2 stems use any of the same nucleotides. Args: stem1 (tuple): 4-tuple containing stem information. stem2 (tuple): 4-tuple containing stem information. Returns: bool: Boolean indicating if the two stems overlap....
3d1381eb5e8cedf7cfe37a8263bbba670240d575
682,863
import ast def str_to_list(string: str) -> list: """ convert list-like str to list :param string: "[(0, 100), (105, 10) ...]" :return: list of tuples """ return ast.literal_eval(string)
152e247a08d7ee50a85bfe5044ea6d3a9ce05169
682,866
import json def json_load(path, verbose=False): """Load python dictionary stored in JSON file at ``path``. Args: path (str): Path to the file verbose (bool): Verbosity flag Returns: (dict): Loaded JSON contents """ with open(path, 'r') as f: if verbose: ...
ac099f33666c6502a253e91c6c03db434fa361cc
682,870
def center_crop(img_mat, size = (224, 224)): """ Center Crops an image with certain size, image must be bigger than crop size (add check for that) params: img_mat: (3D-matrix) image matrix of shape (width, height, channels) size: (tuple) the size of crops (width, height) returns: ...
5a65f44f3bc6e5fb7b768769580a3a0706e60673
682,871
def reorder_columns(frame, front_columns): """ Re-order the columns of frame placing front_columns first. Good for looking specifically at certain columns for specific file in pipeline. """ # reorder columns into appropriate order new_cols = list(frame.columns) for d in front_columns: ...
7f0bfabe04ee1551c9ad1384a53478f5e0ad656a
682,874
def plot_line(m, line, colour='b', lw=1, alpha=1): """ Plots a line given a line with lon,lat coordinates. Note: This means you probably have to call shapely `transform` on your line before passing it to this function. There is a helper partial function in utils called `utm2lola` w...
4cf04142b7205116ff52c93ab32825a4874a28db
682,877
def _get_orientation(exif): """Get Orientation from EXIF. Args: exif (dict): Returns: int or None: Orientation """ if not exif: return None orientation = exif.get(0x0112) # EXIF: Orientation return orientation
d05b8e7f2029a303d40d049e8d3e1cb9da02fcef
682,879
import random def generate_layers(layer_limit: int, size_limit: int, matching: bool): """ Helper function for generating a random layer set NOTE: Randomized! :param layer_limit: The maximum amount of layers to generate :param size_limit: The maximum size of each layer :param matching: Specif...
27807566aee5d00f290821323e6aadce3733a8c7
682,885
def expand_resources(resources): """ Construct the submit_job arguments from the resource dict. In general, a k,v from the dict turns into an argument '--k v'. If the value is a boolean, then the argument turns into a flag. If the value is a list/tuple, then multiple '--k v' are presented, ...
5e7edff0ceaf9b24a1d69cb9dcb3e9473e1d7b66
682,892
def gen_workspace_tfvars_files(environment, region): """Generate possible Terraform workspace tfvars filenames.""" return [ # Give preference to explicit environment-region files "%s-%s.tfvars" % (environment, region), # Fallback to environment name only "%s.tfvars" % environment...
a1e822451b9652b846eaf21c6323943678e75d84
682,893
def comma_sep(values, limit=20, stringify=repr): """ Print up to ``limit`` values, comma separated. Args: values (list): the values to print limit (optional, int): the maximum number of values to print (None for no limit) stringify (callable): a function to use to convert values to ...
748f1956ed8383fc715d891204056e77db30eb4b
682,895
def myround (val, r=2): """ Converts a string of float to rounded string @param {String} val, "42.551" @param {int} r, the decimal to round @return {string} "42.55" if r is 2 """ return "{:.{}f}".format(float(val), r)
50e11ccae07764a3773e0a8adf45f010925f41b5
682,897
def normaliseports(ports): """Normalise port list Parameters ---------- ports : str Comma separated list of ports Returns ------- str | List If None - set to all Otherwise make sorted list """ if ports is None: return 'all' if ports in ('all', ...
125b73f0889cd99d5c0128a968b47ae4867cba7e
682,898
def review_pks(database): """ Check that all tables have a PK. It's not necessarily wrong, but gives a warning that they don't exist. :param database: The database to review. Only the name is needed. :type database: Database :return: A list of recommendations. :rtype: list of str """ p...
830c0a988ac6ccc593b979d113a0a9d88a0cca0c
682,899
import re def read_sta_file(sta_file): """ Read information from the station file with free format: net,sta,lon,lat,ele,label. The label is designed with the purpose to distinguish stations into types. """ cont = [] with open(sta_file,'r') as f: for line in f: line = line.r...
4dad0b3227dadf4cf098f7df552cfac285862910
682,901
def read_file(file_name): """Returns the content of file file_name.""" with open(file_name) as f: return f.read()
560b6ec2eeb507d694b9c10a82220dc8a4f6ca52
682,905
def t_add(t, v): """ Add value v to each element of the tuple t. """ return tuple(i + v for i in t)
da2e58a7b2ff7c1cc9f38907aaec9e7c2d27e1d0
682,908
def fix_nonload_cmds(nl_cmds): """ Convert non-load commands commands dict format from Chandra.cmd_states to the values/structure needed here. A typical value is shown below: {'cmd': u'SIMTRANS', # Needs to be 'type' 'date': u'2017:066:00:24:22.025', 'id': 371228, ...
59bcce8af2c1779062d7a10d7186b170434bb244
682,917
import copy def _update_inner_xml_ele(ele, list_): """Copies an XML element, populates sub-elements from `list_` Returns a copy of the element with the subelements given via list_ :param ele: XML element to be copied, modified :type ele: :class:`xml.ElementTree.Element` :param list list_: List of...
772218e66aebb99e8d4f0901979969eeda128b99
682,918
def construct_fixture_middleware(fixtures): """ Constructs a middleware which returns a static response for any method which is found in the provided fixtures. """ def fixture_middleware(make_request, web3): def middleware(method, params): if method in fixtures: r...
46720c2a6e158dc931bb2c474dee9d6ffc6ef264
682,919
def can_leftarc(stack, graph): """ Checks that the top of the has no head :param stack: :param graph: :return: """ if not stack: return False if stack[0]['id'] in graph['heads']: return False else: return True
352fdebf1612f79a32569403cc4fd1caf51a456d
682,922
def concatenate_dictionaries(d1: dict, d2: dict, *d): """ Concatenate two or multiple dictionaries. Can be used with multiple `find_package_data` return values. """ base = d1 base.update(d2) for x in d: base.update(x) return base
d35391843b299545d6d7908e091ac9b9af274979
682,934
def nulls(x): """ Convert values of -1 into None. Parameters ---------- x : float or int Value to convert Returns ------- val : [x, None] """ if x == -1: return None else: return x
d87c6db9755121ec8f2ec283fb6686050d31b009
682,936
from typing import List def compute_skew(sequence: str) -> List[float]: """Find the skew of the given sequence Arguments: sequence {str} -- DNA string Returns: List[float] -- skew list """ running_skew = [] skew = 0 for base in sequence.upper(): if base =...
678510360d2c8ab39c5f91351e90d08ddad3f9bb
682,937
import base64 import hashlib def generate_hash(url): """ Generates the hash value to be stored as key in the redis database """ hashval = base64.urlsafe_b64encode(hashlib.md5(url).digest()) hashval=hashval[0:6] return hashval
51add11d40c5a9538d5794de8d5724705436c0ea
682,938
def Fplan(A, Phi, Fstar, Rp, d, AU=False): """ Planetary flux function Parameters ---------- A : float or array-like Planetary geometric albedo Phi : float Planetary phase function Fstar : float or array-like Stellar flux [W/m**2/um] Rp : float Planetary ...
5f7b92e31ba22bd44f2e710acb4048fd9860409b
682,941
def create_inventory(items): """ Create an inventory dictionary from a list of items. The string value of the item becomes the dictionary key. The number of times the string appears in items becomes the value, an integer representation of how many times. :param items: list - list of items to c...
9fb15b9c742d03f197c0e0fc402caa94d47f65b4
682,945
import six def get_paramfile(path, cases): """Load parameter based on a resource URI. It is possible to pass parameters to operations by referring to files or URI's. If such a reference is detected, this function attempts to retrieve the data from the file or URI and returns it. If there are an...
e9a55bf9459f609f9a39678cd97541318a0ba48f
682,949
def adds_comment_sign(data: str, comment_sign: str) -> str: """Adds comment signs to the string.""" return "\n".join(list(f"{comment_sign} {line}".strip() for line in data.split("\n")[:-1]))
a78d21fd1ae5325911e9b3e5bec3bf81f86757d1
682,952
def positive_coin_types_to_string(coin_dict): """ Converts only the coin elements that are greater than 0 into a string. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: (string): The resulting string. """ plat = "" gold = "" silver = "...
e4ad715e008fd836992b8023772a71cba16818bf
682,956
def finalize_model(input_model): """ Extracts string from the model data. This function is always the last stage in the model post-processing pipeline. :param input_model: Model to be processed :return: list of strings, ready to be written to a module file """ finalized_output = [] for m...
88c03ed9b4b6158895ac6e88ef27b573de2b0027
682,961
from typing import OrderedDict def load_object(worksheet): """ Converts worksheet to dictionary Args: object: worksheet Returns: object: dictionary """ #d = {} #d = OrderedDict() d = OrderedDict() for curr_col in range(0, worksheet.ncols): liste_elts = work...
d9c70f6805fbe906042d9a94293b4b989bee02b1
682,962
def getConstructors(jclass): """Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.""" return jclass.class_.getConstructors()[:]
c7dc893002ab913b55ce6e6e121af322fd6ab7b6
682,975
def ask_move(player: int) -> int: """Ask the player which pawn to move. Returns an integer between 0 and 3.""" while True: try: pawn_number = int(input(f"Player {player}: Choose a piece to move (0-3): ")) except ValueError: continue else: if 0 <= paw...
b5b23052fe24078f44ff4bddb52e4bbd693807d0
682,976
def find(arr, icd_code=False): """Search in the first column of `arr` for a 'Yes' and return the respective entry in the second column.""" search = [str(item) for item in arr[:,0]] find = [str(item) for item in arr[:,1]] try: idx = [i for i,item in enumerate(search) if "Yes" in item] ...
87fe9d1e98a4feece19222e8a84a3e6ffb90540d
682,981
from typing import IO def open_file_or_stream(fos, attr, **kwargs) -> IO: """Open a file or use the existing stream. Avoids adding this logic to every function that wants to provide multiple ways of specifying a file. Args: fos: File or stream attr: Attribute to check on the ``fos`` ob...
9f7955a0ced009039095f35c7f7deb1eb25f97b9
682,983
def find_max_sub(l): """ Find subset with higest sum Example: [-2, 3, -4, 5, 1, -5] -> (3,4), 6 @param l list @returns subset bounds and highest sum """ # max sum max = l[0] # current sum m = 0 # max sum subset bounds bounds = (0, 0) # current subset start s = 0 ...
ebf42b58f9fea4276d0ba7d15b02faed4558efc6
682,984
def f_W(m_act, n, Wint): """ Calculate shaft power """ return m_act * n - Wint
4e1182c1fd55a0fb688a7146038cf7c2d0916a3c
682,988
def _formatDict(d): """ Returns dict as string with HTML new-line tags <br> between key-value pairs. """ s = '' for key in d: new_s = str(key) + ": " + str(d[key]) + "<br>" s += new_s return s[:-4]
be9749e5f69c604f3da95902b595f9086b01baa5
682,989
from typing import List def clusters_list(num_clusters: int) -> List[list]: """Create a list of empty lists for number of desired clusters. Args: num_clusters: number of clusters to find, we will be storing points in these empty indexed lists. Returns: clusters: empty list of lists. ...
d6130f67e72d1fd31def20f2bac1fd81c6878ba5
682,990
def number_format(num, places=0): """Format a number with grouped thousands and given decimal places""" places = max(0,places) tmp = "%.*f" % (places, num) point = tmp.find(".") integer = (point == -1) and tmp or tmp[:point] decimal = (point != -1) and tmp[point:] or "" count = 0 formatted = ...
6d6f2412fa94857f77043a30ec2a14f809c5f039
682,991
def get_cdm_cluster_location(self, cluster_id): """Retrieves the location address for a CDM Cluster Args: cluster_id (str): The ID of a CDM cluster Returns: str: The Cluster location address str: Cluster location has not be configured. str: A cluster with an ID of {cluster_id...
f8d3aa787b625e5461fd22eb11f2495a33bace0b
682,995
def is_session_dir(path): """Return whether a path is a session directory. Example of a session dir: `/path/to/root/mainenlab/Subjects/ZM_1150/2019-05-07/001/` """ return path.is_dir() and path.parent.parent.parent.name == 'Subjects'
474096a74068222ca8672fed838dc2703668648e
682,998
def coalesce(*xs): """ Coalescing monoid operation: return the first non-null argument or None. Examples: >>> coalesce(None, None, "not null") 'not null' """ if len(xs) == 1: xs = xs[0] for x in xs: if x is not None: return x return None
2210de29cb2fbc9571bd4bed9fc8a89feddbb8c8
683,001
import re def __is_rut_perfectly_formatted(rut: str) -> bool: """ Validates if Chilean RUT Number is perfectly formatted Args: rut (str): A Chilean RUT Number. For example 5.126.663-3 Returns: bool: True when Chilean RUT number (rut:str) is perfectly formatted ** Only valida...
42fbeb3968a1c2536e44154ab9e690817a57ccd4
683,007
def create_single_object_response(status, object, object_naming_singular): """ Create a response for one returned object @param status: success, error or fail @param object: dictionary object @param object_naming_singular: name of the object, f.ex. book @return: dictionary. """ return {"...
9626fc5594e5677196454594e719ebf415fc1ebc
683,016
def _query_item(item, query_id, query_namespace): """ Check if the given cobra collection item matches the query arguments. Parameters ---------- item: cobra.Reaction or cobra.Metabolite query_id: str The identifier to compare. The comparison is made case insensitively. query_namesp...
f3e418ab5cf2830d2c1dd6b4e83275e14dc8f4c8
683,020
import re def strip_html_tags(text): """Strip HTML tags in a string. :param text: String containing HTML code :type text: str :return: String without HTML tags :rtype: str :Example: >>> strip_html_tags('<div><p>This is a paragraph</div>') 'This is a paragraph' >>> strip_html_ta...
e7b060bdea980cfee217d81feccf56cf964f5557
683,022
def get_next_open_row(board, col): """ Finds the topmost vacant cell in column `col`, in `board`'s grid. Returns that cell's corresponding row index. """ n_rows = board.n_rows # check row by row, from bottom row to top row ([0][0] is topleft of grid) for row in range(n_rows - 1, -1, -1): ...
7f6e45a0c136e53482a10264fc88020168056d8a
683,024
import csv def proc_attendees(att_file, config): """Opens the attendee list file, reads the contents and collects the desired information (currently first name, last name and email addresses) of the actual attendees into a dictionary keyed by the lowercase email address. This collection is returned. ...
e9a4a59ec557c999b2ff423df8a02ca04a4545a8
683,026
import re def _parse_arn(arn): """ ec2) arn:aws:ec2:<REGION>:<ACCOUNT_ID>:instance/<instance-id> arn:partition:service:region:account-id:resource-id arn:partition:service:region:account-id:resource-type/resource-id arn:partition:service:region:account-id:resource-type:resource-id Returns: r...
c267a63cb82ce3c9e2dd0dadaea3ac5a53630d53
683,027
from pathlib import Path def is_subpath(parent_path: str, child_path: str): """Return True if `child_path is a sub-path of `parent_path` :param parent_path: :param child_path: :return: """ return Path(parent_path) in Path(child_path).parents
6852efb5eede8e16871533dca9d0bf17dd7454bb
683,030
def getIPaddr(prefix): """ Get the IP address of the client, by grocking the .html report. """ addr="Unknown" f=open(prefix+".html", "r") for l in f: w=l.split(" ") if w[0] == "Target:": addr=w[2].lstrip("(").rstrip(")") break f.close() return(addr...
de1e80e978eeef8ca74b05a7a53e0905e79a29e0
683,031
import re def clean_text(text, max_words=None, stopwords=None): """ Remove stopwords, punctuation, and numbers from text. Args: text: article text max_words: number of words to keep after processing if None, include all words stopwords: a list of words to skip d...
c5fe9bb01928355d81b566ad4ebee1232ebae810
683,033
def array_value(postiion, arr): """Returns the value at an array from the tuple""" row, col = postiion[0], postiion[1] value = arr[row, col] return value
d8a83ef4870d304fefe33220e38b78c8c8afee56
683,039
def get_padding(ks, s, hw): """ choose padding value to make sure: if s = 1, out_hw = in_hw; if s = 2, out_hw = in_hw // 2; if s = 4, out_hw = in_hw // 4; """ if hw % s == 0: pad = max(ks - s, 0) else: pad = max(ks - (hw % s), 0) if pad % 2 == 0: return pad // 2 ...
1fffec0037275bb71566b1967015f1ed7fb6a9bb
683,040
def generate_header_list(unsorted_keys): """Return a list of headers for the CSV file, ensuing that the order of the first four headers is fixed and the remainder are sorted.""" unsorted_keys.remove('identifier') sorted_remainder = sorted(unsorted_keys) header_list = ['identifier', 'label1', 'lab...
18cb8d4be40e16da1b3c05070494dc791a7e4e02
683,041
def hamming_distance(str1, str2): """Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: ValueError: Strings not same length """ if len(str1) != len(str2...
8ca962c82b1321c32c34052ccf8f9a74d0f9245d
683,042
import requests def get_all_topk_articles(day_range): """ Accepts a list of dicts with year, month, and day values Returns a dictionary (article titles as keys) with all articles that were in the topk list during those dates and the pageview counts for each of the dates the article appeare...
4dfad93b94ef4efed2d9018b62bee721edf54b89
683,043
def sync(printer, ast): """Prints a synchronization "chan(!|?)".""" channel_str = printer.ast_to_string(ast["channel"]) op_str = ast["op"] return f'{channel_str}{op_str}'
ae3c9045a48a169e37602df13eb88da8ac9a65b6
683,045
from typing import Union from typing import List import pickle def parse_list(data: Union[str, List], indicator: int = 0, query=['MCF7']) -> List: """Filter the data based on compound, cell line, dose or time This function takes the directory of dataset, indicator that indicates w...
67a0fa75c659a5bcbff2aa44e131a56096bf8865
683,047
def extend_flight_distance(distance: float) -> float: """Add factor to shortest flight distance to account for indirect flight paths Following https://www.icao.int/environmental-protection/CarbonOffset/Documents/Methodology%20ICAO%20Carbon%20Calculator_v11-2018.pdf section 4.2 we add a correction factor to...
a4dedcbfcba663be757ba97cd28b6afac1c77a01
683,055
def triwhite(x, y): """ Convert x,y chromaticity coordinates to XYZ tristimulus values. """ X = x / y Y = 1.0 Z = (1-x-y)/y return [X, Y, Z]
dd2dd418c4643e10d3b9fd685bd6df1a3cc5afd7
683,056
def create_header(args): """Constructs the header row for the csv""" header = ["Propublica Number", "Org Name", "Tax Year", "Data Source", "PDF URL"] if args.totalrev: header.append("Total Revenue") if args.totalexp: header.append("Total Functional Expenses") if args.ne...
b47dd3254262624e63b32cd269bef8890883707d
683,059
def predict_large_image(model, input_image): """Predict on an image larger than the one it was trained on All networks with U-net like architecture in this repo, use downsampling of 2, which is only conducive for images with shapes in powers of 2. If different, please crop / resize accordingly to avoid...
f762c997c953487df32e111babfb25059a2d344d
683,060
import logging def get_logger(*components) -> logging.Logger: """Get a logger under the app's hierarchy.""" name = '.'.join(['skipscale'] + list(components)) return logging.getLogger(name)
9060f07091ac19ae90a61b69b2eca3ef1daf1d05
683,065
def convert_to_SimpleIndex(data, axis=0): """ Converts the index of a DataFrame to a simple, one-level index The target index uses standard SimCenter convention to identify different levels: a dash character ('-') is used to separate each level of the index. Parameters ---------- data: Dat...
2f6ce3af39fd01314feeb0933821dbe67dbe8c1c
683,073
from typing import Iterable def hr_bytes(data: Iterable[int], delimiter: str = ' ') -> str: # pragma: no cover """ Print bytes (or another int iterable) as hex and delimiters :param data: Bytes or iterable object :param delimiter: Delimiter (str value) :return: str valu...
a399b1da61fc5cef6ff071ea2ae7566036ae1726
683,075
def create_path(network, user_A, user_B, path=[]): """ Finds a connections path from user_A to user_B using recursion. It has to be an existing path but it DOES NOT have to be the shortest path. Circular loops returns None (for example, A is connected to B. B is connected to C. C is connected to B.)...
b3e88f4e18c0ab86c971706ea74e0a1739a61a2e
683,077
import math def chunk(iterable, n): """Splits a list into n equal parts""" iterable = [e for e in iterable] avg_length = int(math.ceil(len(iterable) / n)) return [iterable[i * avg_length:(i + 1) * avg_length] for i in range(n)]
74d649b8db2625861db6110733a0ea8342541657
683,079
def first_down(items): """Return True if the first item is down.""" return items[0] == '-'
e24afe79971572de01676bda608a317c83fb7792
683,080
def unsort(sorted_list, oidx): """ Unsort a sorted list, based on the original idx. """ assert len(sorted_list) == len(oidx), "Number of list elements must match with original indices." _, unsorted = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))] return unsorted
fc54770d389029d36e598035b82264b325d76940
683,083
def figure_linguistic_type(labels): """ Gets linguistic type for labels Parameters ---------- labels : list of lists the labels of a tier Returns ------- the linguistic type """ if len(labels) == 0: return None elif len(labels) == 1: return lab...
14151917bb9ad8f49717ce6c436c496ee3ccfc77
683,084
def get_rank(cutoff: dict, coverage: float, quality: float, length: int, contigs: int, genome_size: int, is_paired: bool) -> list: """ Determine the rank (gold, silver, bronze, fail) based on user cutoffs. Args: cutoff (dict): Cutoffs set by users to determine rank coverage (float): Estimat...
2cd31199cb555c6bbbc4cec87e806ed4fcf6c983
683,086
def filter_empty_values(mapping_object: dict) -> dict: """Remove entries in the dict object where the value is `None`. >>> foobar = {'username': 'rafaelcaricio', 'team': None} >>> filter_empty_values(foobar) {'username': 'rafaelcaricio'} :param mapping_object: Dict object to be filtered """ ...
582e7874c96b261779f5a2d6b5a6e5a37b89ec81
683,091
def axis_ticklabels_overlap(labels): """Return a boolean for whether the list of ticklabels have overlaps. Parameters ---------- labels : list of ticklabels Returns ------- overlap : boolean True if any of the labels overlap. """ if not labels: return False try:...
8b9edc2b97ae00976a573aefac5067568328ae05
683,092
def logreg_classifier_to_dict(classifier, feature_names=None): """ Serialize sklearn logistic regression classifier Inspired by https://stackoverflow.com/questions/48328012/python-scikit-learn-to-json Parameters ---------- classifier : sklearn.linear_model.LogisticRegression Logistic r...
081330c53eb4dcded9b92c0ee9f878b4bf208b13
683,098
def add(x, y): """This is a doc string :param x: first value to add :param y: second value to add :returns: x + y """ return x + y
421e7d34f7549235694cbdf4b9ec97021e06b46b
683,099
def remove_atom_maps(mol): """ Iterates through the atoms in a Mol object and removes atom maps Parameters: mol (rdkit.Mol): Rdkit Mol Object Returns: mol (rdkit.Mol): Rdkit Mol Object without atom maps or 'nan' if error """ try: for atom in mol.GetAtoms(): ...
213b155d5ed8142e7ca75d594ad3a8e296b44804
683,108