content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def append_s(value): """ Adds the possessive s after a string. value = 'Hans' becomes Hans' and value = 'Susi' becomes Susi's """ if value.endswith('s'): return u"{0}'".format(value) else: return u"{0}'s".format(value)
a98f494a109c661eafc5ff51230d86646646339c
657,805
def price_format_conversion(digital_value, rounding_threshold): """ example: >>> price_format_conversion(0.000000082725, 9) '0.000000082' """ if rounding_threshold <= 0: return str(int(digital_value)) string_value = str(float(digital_value)) if 'e' in string_value: string...
67a0a0572519cb06098c92eb495383a06e22cfdd
657,806
def mydecorator(func): # noqa: D401 """Dummy decorator.""" return func
53d8f533f1164ee2187c3cad812ebfb93b8995c9
657,807
def _zone(index): """Chooses a GCP zone based on the index.""" if index < 6: return 'us-central1-a' elif index < 12: return 'us-east1-b' elif index < 18: return 'us-east4-c' elif index < 24: return 'us-west2-a' else: raise ValueError('Unhandled zone index')
9d5a86ce022530e59301f82e73cf3bc90cf6df87
657,809
def compounds_need_updating(compounds, dismissed): """Checks if the list of compounds for a variant needs to be updated. Returns True or False. Args: compounds (list): list of compounds dictionaries dismissed (list): list of case dismissed variant ids Returns: True or False (bool) ...
41948cdaab7371c69ca160a1c7070fb1bf2b95ab
657,810
def merge(left, right): """Merge sort merging function.""" left_index, right_index = 0, 0 result = [] while left_index < len(left) and right_index < len(right): if left[left_index] < right[right_index]: result.append(left[left_index]) left_index += 1 else: ...
6dc23e69f8ed558539344ea2a45819f48fd5a6ae
657,811
import torch def change_box_order(boxes, order, dim=-1): """Change box order between (x_min, y_min, x_max, y_max) and (x_center, y_center, width, height). Args: boxes: (tensor) bounding boxes, sized [N, 4]. order: (str) either 'xyxy2xywh' or 'xywh2xyxy'. Returns: (tensor) converted bou...
c9e2a2b2569f365eaba6f0fc8dca3c44c8706455
657,812
def clip(text, max_len=80): """Return max_len characters clipped at space if possible""" text = text.rstrip() if len(text) <= max_len or ' ' not in text: return text end = len(text) space_at = text.rfind(' ', 0, max_len + 1) if space_at >= 0: end = space_at else: spac...
01530ebe0e25a03c4f49204b7816d0f000796a43
657,813
import re def validate_name(name: str) -> str: """Validate a name string against a set of rules""" if not re.match("^[a-zA-Z0-9_-]*$", name): raise ValueError("Value does not match name requirements") return name
daf8218e48ad3e3dd0228a569bf0bd4b87acc921
657,814
def gq_add_vertex_collection(coll): """Create the gremlin query that creates a Vertex for a collection in the Tree Entry table """ name = coll.entry.container.split('/')[-1] if not name: # root name = '/' query = "graph.addVertex(T.label, 'collection', " query += "'name', '{}', ...
57492e959b008804b5138dbb751f4d06854f850e
657,815
import pickle def load_clifford_table(picklefile='cliffords2.pickle'): """ Load pickled files of the tables of 1 and 2 qubit Clifford tables. Args: picklefile - pickle file name. Returns: A table of 1 and 2 qubit Clifford gates. """ with open(picklefile, "rb") as ...
25382d151456b926a317e3c820d29d650e28e31c
657,816
import random def make_random(): """ Make a list of 10 random integers between 1 and 100. """ numlis = [] for i in range(0,10): numlis.append(random.randint(1,100)) return numlis
1604fc566a0f93a33c1dbfdb3a1b4033cc5a53f0
657,818
def linear_combination(landscapes: list, coeffs: list): """ Compute a linear combination of landscapes Parameters ---------- landscapes : list of PersistenceLandscape objects coeffs : list, optional Returns ------- None. """ result = coeffs[0]*landscapes[0] for c, L in enum...
045ff416f1151427bd63eb273247fbdd059b8e4e
657,819
import ast def format_nasdaq(companies): """ Convert the parsed companies list to format that is interpretable by dash_core_components.dropdown """ companies_list = ast.literal_eval(companies) options=[] # Get the company name and symbol. for i in range(len(companies_list)): new_co...
d2f6782c0d9f37b749241ed6cd9f4cd7508f2f77
657,820
def cds_record_matches_prot_id(cds_obj, prot_id): """Take a CDS record object (constructed using gffutils) and a protein sequence ID, and return true if the CDS record is linked to the protein sequence ID (the CDS is part of the sequence encoding that peptide). Some SQL databases will be structured dif...
3f643b07c7893fcc26cae49748f4d833b701a196
657,821
def make_coordinates(df, index_col='index'): """ Formats a geopandas.GeoDataFrame (from a shapefile that contains junction information) to a coordinate table. Parameters ---------- catchments : geopandas.GeoDataFrame Must contain a geometry field with points. index_col : str ...
a870b0e0624860f5cfcc4e130ef468559f39c329
657,822
def log_cls(curr_cls): """ A smaller version of log_scope, registering only the current class. Why the class is passed explicitly is explained there. """ return f'{curr_cls.__name__=}'
721ceb03703e187d21469c369b9ef128350beed0
657,824
def unpack_flags(value, flags): """Multiple flags might be packed in the same field.""" try: return [flags[value]] except KeyError: return [flags[k] for k in sorted(flags.keys()) if k & value > 0]
f9ef174cf4f79bf55f5f767b4d569dd603713059
657,825
def alt_file_map_duplicate_dest(): """ Alternate file map with duplicate dest filenames. """ return """ abc 123 MY NEW FILE 1 xyz 999 MY NEW FILE 1 """
63e7a550139a51d86cf9dcbe2e12428fbf130877
657,826
from typing import Sequence from typing import List def lst_inc(inc: Sequence, seq: Sequence) -> List: """ Returns the intersection of two sequences. Similar to the built-in method ``set.intersection``, but duplicate (non-unique) items are not discarded. Args: inc: Sequence E...
bf8ead302c44e1d46c6d1a30c198a837f2682ec4
657,827
def _strip_or_pad_version(version, num_components): """Strips or pads a version string to the given number of components. If the version string contains fewer than the requested number of components, it will be padded with zeros. Args: version: The version string. num_components: The d...
8d8829c551fe799852098db60c2df5f1cd68a4c3
657,828
import os import random def rand_bytes(n, secure=True): """ Returns n random bytes. Args: n (int): number of bytes to return. secure (bool): If True, uses os.urandom to generate cryptographically secure random bytes. Otherwise, uses random.randint() which generates pse...
96669151a4a7ed8f5525becde7524d4979640cfb
657,829
import torch def wait(future): """ Forces completion of a `torch.jit.Future[T]` asynchronous task, returning the result of the task. See :func:`~fork` for docs and examples. Arguments: func (torch.jit.Future[T]): an asynchronous task reference, created through `torch.jit.fork` Returns: ...
ff7165315cd9dfac46abf8a1508706b73478d299
657,830
def rebuild_source(source, full_base_url): """ Completes the links on a web page. """ source = source.replace('src="//', 'src="http://') source = source.replace('src="/', 'src="%s' % full_base_url) source = source.replace('src="../', 'src="%s' % full_base_url) source = source.replace('src="./', 'src...
1c70dc592b95172ec83846b879eaffe90ccda9fc
657,831
def _block_format_index(index): """ Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``. """ idx_str = ''.join('[{}]'.format(i) for i in index if i is not None) return 'arrays' + idx_str
849a345869d9080010c306751e3ea537bc583e78
657,832
def urljoin(*path): """Joins the passed string parts into a one string url""" return '/'.join((part.strip('/') for part in path))
977ee60d90977fda9041da45d9db1ea17e45f773
657,833
def fill_with_po3(df): """ Fill missing values in a time series data using interpolation (polynomial, order 3) """ df = df.fillna(df.interpolate(method='polynomial', order=3)) assert df.count().min() >= len(df) - 1 # fill the first item with second item return df.fillna(df.iloc[1])
f4d045a0d293218de4e8aaefce145fea3b965198
657,835
import os import pickle def get_latest_train_data(): """ load the data used in the latest training """ data_file = os.path.join("models",'latest-train.pickle') if not os.path.exists(data_file): raise Exception("cannot find {}-- did you train the model?".format(data_file)) with open(...
f79857cff2c992b09704894471513b0c8b309d8c
657,836
def create_inv_codon_map(): """ Creates a dictionary: keys = 1-letter protein code entries = corresponding codons Written by Jennifer Pfaff """ inverse_codon_map = { 'K': ["AAA", "AAG"], 'N': ["AAC", "AAU"], 'T': ["ACA", "ACC", "ACG", "ACU"], 'R': ["AGA", "AGG...
f2a62ba62dae4b9e0a02e8a2007b2c7cc9657a13
657,837
def euler14(lim=1000000): """Solution for problem 14.""" collatz = {1: 1} for i in range(2, lim): if i not in collatz: chain = [] while i not in collatz: chain.append(i) i = (3 * i + 1) if i % 2 else (i // 2) stop = collatz[i] + 1 ...
6a89c4b2ee996f22ea67a3d032b4259326487586
657,838
def adjusted_weight(initial, baseline_mean, baseline_stdev, transformer, scaler): """ Correct an initial weight/score as per specified transform and scale methods (applied in that order) """ transformed_score = transformer.transform(initial, baseline_mean) scaled_score = scal...
6a9fb408560876fdc992a9d9f57296ede5361de3
657,839
def obj_to_dotpath(obj): """Get the dotpath reference for an object >>> from inspect import Signature >>> obj_to_dotpath(Signature.replace) 'inspect.Signature.replace' >>> # note that below, it's not a "full path" >>> obj_to_dotpath(func_to_dotpath)[-21:] # the :21 is because the full string i...
e1153155d97b3da406f06907bfd239f379b2c7f2
657,840
def check_rule(m, number, board, row, col): """ 如果遵循每一行,每一列,每一区域都包含1-9数字,且不重复的规则,返回真 number: 被校验的数字 board: 当前九宫格所有的元素(9x9的二维列表) row, col: 当前行数,当前列数 """ flag = True # 检查行 if number in board[row]: flag = False # 检查列 if not all([row[col] != number for row in board])...
3d192f3a0d84fe97869da1bcb08ca30874c85f44
657,841
import sys def calc_hhl(hfl): """Interpolate from full levels to half levels. Args: hfl (1d array): values of a variable defined on N full model levels Returns: 1d array values of this variable interpolated to N-1 half model levels """ if hfl.ndim == 1: hhl = hfl[...
83807e79b2419b53191cadb497c81d915acc8b3e
657,843
import six def dtype(spec): """ Allow Python 2/3 compatibility with Numpy's dtype argument. Relevant issue: https://github.com/numpy/numpy/issues/2407 """ if six.PY2: return [(str(n), str(t) if type(t)==type else t) for n, t in spec] else: return spec
b3e154dc59a821b6c20d01dff2706c90f40d7372
657,844
def SetViewParameters(ref, args, request): """Ensure that view parameters are set properly tables create request.""" del ref # unused if not args.view: request.table.view = None return request
7051d492054a59dd680d7f0a8bff9deb4458ce38
657,845
def get_collection_keys(cleaned_zot_files): """ Gets the collection (folder) id keys for each entry in the cleaned Zotero files """ col_keys = [] if 'collections' in cleaned_zot_files['data'].keys(): if len(cleaned_zot_files['data']['collections']) > 1: for i in cleaned_zot_files...
52274c04a3c9ec0e9218914a36fdd33418e4aaa6
657,846
def find_all_stacktraces(data): """Given a data dictionary from an event this returns all relevant stacktraces in a list. If a frame contains a raw_stacktrace property it's preferred over the processed one. """ rv = [] def _probe_for_stacktrace(container): raw = container.get('raw_stac...
a8f81201cb18dcd6f54a7ab9058d02c17688a93f
657,847
def dict_get_item(dictionary, key): """ Get a value out of a dictionary to use in templates """ return dictionary.get(key)
3dcf01cf1565d912460eaedb440bd1324557e5b8
657,849
import secrets def generate(*, charset: str, length: int) -> str: """Return a cryptographically secure password of len length using characters only from the given charset.""" return "".join(secrets.choice("".join(charset)) for i in range(length))
fae8e1d96deb5af58e1ae6c7b34c02a2f9d90418
657,850
def ensure_dtype(data): """ To ensure that input file and output file are comparable, data types should be the same in all files. #Input: @data: pandas DataFrame #Output: @data_trans: transformed pandas DataFrame with corrected dtype """ # dtypes taken from Hestia website data_tr...
bb99607a93cd5ef383c754e5d2dba62ed5478c06
657,851
import os def checkFileOut(filename): """ Function which checks that a file exists or add a '_N' at the end. IN: * filename (with extension) * filename_N (with extension) """ filename_out = filename n_file_name = 0 while(os.path.exists(filename_out) is True): ...
ab3d7355a46b98eaa5368159fd7230ecc99a4bbb
657,852
def signal_choices_string(message): """Returns the signal choices as a string. """ lines = [] for signal in message._signals: if signal.choices: lines.append('') lines.append(signal.name) for value, text in sorted(signal.choices.items()): l...
ea922913cdf2c7d121a55385eab4758eef88d3af
657,853
def dump_matrix_ranking(value): """dump matrix_ranking""" return value
d3ee2cb8956c9199e7048b8ca69008120faa1d71
657,854
import os def testdata(): """ Simple fixture to return reference data :return: """ class TestData(): def __init__(self): self.datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') def fn(self, fn): return os.path.join(self.datadir, fn...
5bbc7418a5a27c0542cd1d80f9a8261695a6ef8b
657,855
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
2a63e85022b6b91e18ea4240437605028ee21266
657,857
def is_interval_subset(interval1, interval2): """Checks whether interval1 is subset of interval2.""" # Check the upper bound. if (interval1[1] == "inf" and interval2[1] != "inf") or \ (interval1[1] != "inf" and interval2[1] != "inf" and interval1[1] > interval2[1]): return False # C...
6f8e7baf1245fbfc0c72390913db64716239f263
657,858
import random def generate_mac_address(): """Generate an Ethernet MAC address.""" mac = [0xfa, 0x16, 0x3e, random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff)] return ':'.join(map(lambda x: "%02x" % x, mac))
79d725bd1a046b9da88f772570c89f74a14c4f84
657,859
def normalize(min, max, array): """Normalizes 'value' between min and max.""" normalized = (array - min) / (max - min) return normalized
3baaa1ba07f19206fd6c78ac8603b12f9ab83ae7
657,860
def _bsj_junction_to_bed(info_str): """junction: chr|gene1_symbol:splice_position|gene2_symbol:splice_position|junction_type|strand junction types are reg (linear), rev (circle formed from 2 or more exons), or dup (circle formed from single exon) """ seq_name, gene_splice_1, gene_sp...
0a9ed01bfd569e3d577fb81dc59b6a7893b3ee83
657,861
def get_city_from_team(cityteam): """Returns a city and teamname from teamname in lower case. It should return the contents of class wide-matchup from the NHL schedule For historical reasons: This function used to return a city from a team name, citydict1 had entries like: "Washington" : "Washin...
2905cf665794ca013579cd998536cf619c311ad6
657,863
def find_nested_attr(config, attr): """ Takes a config dictionary and an attribute string as input and tries to find the attribute in the dictionary. The attribute may use dots to indicate levels of depth within the dictionary. Example: find_nested_attr({'one': {'two': {'three': 3}}}, 'one.two....
3f449553d409b255989f12f1d96c945e2d076e8b
657,864
def insertion_sort(array): """ Insertion sort implementation Arguments: - array : (int[]) array of int to sort Returns: - array : (int[]) sorted numbers """ for i in range(len(array)): j = i while j > 0 and array[j] < array[j-1]: array[j], array[j-1] = a...
ad39beaffc80aa662496b9bef4e3462549cb6680
657,865
import requests import json def json_to_object(address): """ Requests the JSON at the specified address and attempts to convert to object Returns the object if successful; None otherwise """ try: request = requests.get(address, timeout=5) if request.status_code != 200: ...
9fd6161d6bfcf2bba32ceb93246c0ff7c7929ca7
657,867
def decimal_to_binary(num): """Convert a Decimal Number to a Binary Number.""" binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 return "".join(str(e) for e in binary)
01be9bfa9c816b64b84f941920e2bdf66fc3f11f
657,868
from typing import OrderedDict import json def JsonUXStub(ux_type, **kwargs): """Generates a stub message for UX console output.""" output = OrderedDict() output['ux'] = ux_type.name extra_args = list(set(kwargs) - set(ux_type.GetDataFields())) if extra_args: raise ValueError('Extraneous args for Ux Ele...
765688c49ca2d6e5465b3c8bb910648e4de5b935
657,869
def initialize_dataset(input_data): """ Input dictionary should be of the form created by parse_star_file function. Returns a new dictionary of the form: { 'class001.mrc' : [ (%_it1, %_it2, ...), (res_it1, res_it2, ...), (iteration value1, ...) ] } """ new_dictionary = {} for entry in input_...
556b92cd4b1afef1204d6f5dac97297cd8ca2c80
657,870
def simple_fill(text:str, width:int=60) -> str: """ Split `text` into equal-sized chunks of length `width` This is a simplified version of `textwrap.fill`. The code is adapted from: http://stackoverflow.com/questions/11781261 Parameters ---------- text : string The text to split ...
8491ebb8ee91eb4ea6fcc3e295cf35a59eb39012
657,871
def prod(a, b): """ Example operator function. Takes in two integers, returns their product. """ return a * b
0c0f2a60cec78d3a145dc649cab72fb2a666b26c
657,872
def paginate_list(items, page_number): """ returns a sliced list of a list for pagination """ items_per_page = 12 start = (page_number - 1) * items_per_page end = page_number * items_per_page paginated_items = items[start:end] return paginated_items
3aac36dbee883ca72ceccdedd3d8ce437490be1c
657,873
def get_decrypted_file_path(enc_file, config): """ returns the path to the decrypted copy of the file """ result = enc_file.replace('.gpg','').replace(config.enc_mainfolder + '/', '').replace('_HOME', '$HOME') return result
6c77877cf6647d525b66a0775f8f20e2c8e6133d
657,875
def assertWrapperExceptionTypes(self, deferred, mainType, reasonTypes): """ Assert that the given L{Deferred} fails with the exception given by C{mainType} and that the exceptions wrapped by the instance of C{mainType} it fails with match the list of exception types given by C{reasonTypes}. This is...
e6a2d0781d83a7ecbceacd9ebf76cfed93de9b60
657,876
def get_remote_boot_volume(task): """Identify a boot volume from any configured volumes. :returns: None or the volume target representing the volume. """ targets = task.volume_targets for volume in targets: if volume['boot_index'] == 0: return volume
5953c954e1e8109c7013d13c94566e5242623913
657,877
def extract_pairs(data_list, tag='mean_trajectory_return'): """Extract data from positive and negative alpha evaluations. Args: data_list: A list of dictionaries with data. Dictionary should contain 'pos' and 'neg' keys which represent going forward and backward in the parameter space. Each key sho...
5c593b9f4803e31ef14b6461e5bf62b2c2ad0c2f
657,878
import os def get_name_to_files_map(input_dir): """ Gets a map of the name of a given skier to a list of files in a directory with that name. This assumes that the input directory provided to this tool has the following format: dir - | - Person 1 | - Day_1.gpx | - Day_2.gpx | - Per...
4866879df9484e04685f778ef921befa8ee8680d
657,879
import copy def calibrate_mp(pixel): """ This is a helper function in order to use multiprocessing to invoke the calibrate() method for an array of Pilatus_Pixel objects. """ pixel.calibrate() return copy.copy(pixel)
e2dd19a13d46b6fd8c7173eadb60957c72e7f539
657,881
import torch def symsqrt(matrix): """ Compute the square root of a positive definite matrix. Retrieved from https://github.com/pytorch/pytorch/issues/25481#issuecomment-544465798. """ _, s, v = matrix.svd() # truncate small components above_cutoff = s > s.max() * s.size(-1) * torch.finfo(s...
30c46f762068a85c60740b4614b1ac0794d194a2
657,882
from typing import Collection def A000120(start: int = 0, limit: int = 20) -> Collection[int]: """1's-counting sequence: number of 1's in binary expansion of n (or the binary weight of n). """ return ["{:b}".format(n).count("1") for n in range(start, start + limit)]
36bd316ad43a12ac5b5e6acd7abcf697ea8d3ec6
657,883
import argparse def check_port(value): """Verifies valid 1-4 gamecube controller port""" ivalue = int(value) if ivalue < 1 or ivalue > 4: raise argparse.ArgumentTypeError("%s is an invalid controller port. \ Must be 1, 2, 3, or 4." % value) return ivalue
3e6f991057c2ab825b2fcf64818b8e4552cb1a05
657,885
def _telegram_escaped_string(s): """Replaces characters in a string for Markdown V2.""" for c in "_*[]()~>#+-=|{}.!": s = s.replace(c, "\\" + c) return s
55284d0331713b30b851550672d251fcbbd2a76d
657,886
def _source_description(data, edit_scope, parameter_key, old_value): """Return the description of the source.""" source_type_name = data.datamodel["sources"][data.source["type"]]["name"] source_description = ( f"source '{data.source_name}'" if edit_scope == "source" else f"all source...
e4789ce7df7d672daec6c6e93b1a99965711fb90
657,887
from datetime import datetime def get_anterior_datetime(offset = 300): """ Returns an anterior date given an offset time in seconds :param offset: offset interval in seconds (default: 300s) :return datetime: the anterior datetime :raises Exception: Invalid time offset """ if off...
6e122851ea6e15f0c020911e7a13fe82ebb439dd
657,889
def exclude_regions_by_bedtool(bt, filter): """ take a bedtool and filter bedtool to exclude any intervals that overlap the blacklist """ if filter.any_hits(bt): return(False) else: return(True)
91e7a6b17ddebc29eff277efc18e0e3ca8e91ca1
657,890
import traceback def within_flit(): """\ Checks if we are being imported by flit. This is necessary so flit can import __version__ without all depedencies installed. There are a few options to make this hack unnecessary, see: https://github.com/takluyver/flit/issues/253#issuecomment-737870438 ...
1c865d1645851fe0d70d36d9e07929ab529c7cb8
657,891
def is_palindromic(input_string): """Return True if input string is a palindromic""" return input_string == input_string[::-1]
927d701c9d67facc85281e7c15ddb893a35decb8
657,892
def gmx_bonds_func_1(x, a, b, c): """ Gromacs potential function 1 for bonds. """ return a / 2 * (x - b) ** 2 + c
47cfdce9ff7e5e9b7daca0fe53a0e5fb7284e5a7
657,895
import uuid def create_analysis_id(): """Create a universally unique id for a given analysis. Used by the inference routine to uniquely associated results with analyses. """ return str(uuid.uuid4())
a03e2511f4e00d826d162bf641a25bd595aec20b
657,897
import logging def get_middleware_logger(name: str): """ get middleware logger :param name: middleware name :return: middleware logger """ return logging.getLogger('MIDDLEWARE_' + str(name).upper())
52343a3fc5a0e551500d7d8096cbf28454a69870
657,898
def expand(step, num_steps): """A single step in the series expansion""" return 1 / (1 + ((step-0.5) / num_steps)**2)
28d05c332eda7f295fdff9dbcca67df84b736c00
657,899
import math def gammanu_to_tthphi(gamma, nu): """Transfer gamma-nu to ttheta-phi. gamma is the angle in the equatorial plane nu is the angle between equatorial plane and scattering neutron [-pi/2, pi/2] return ttheta is diffraction angle phi is polar angle ...
f7ffb6c1703fcf5d7cfb0eea69cfdd49a522adaf
657,900
import struct def SetVersionBit(protocol=1): """Generate the Version bit""" return struct.pack("<B", protocol)
5ca1cb45a6adb7627e0344ece3f837d3313ffedd
657,901
import os def get_size_paths(paths): """Extend the `paths` iterator to yield sizes too.""" return ((os.path.getsize(p), p) for p in paths)
17cfe63c287a31eb17fe64b2d9c82001ee502a12
657,902
import argparse def argument_parser(): """ Define and return the arguments. """ description = ('Colorize a las or laz file with a WMS service. ' 'By default uses PDOK aerial photography.') parser = argparse.ArgumentParser(description=description) required_named = parser.add_...
ca61f91fad6c658e3c8e877bb39fe0757a0a6a5c
657,903
def get_out_of_borders_prop(codon_table, miss_exons): """Compute a proportion of out-of-chain-borders bases.""" gene_len = len(codon_table) m_codons_len = 0 for m_exon in miss_exons: # ++ lengths of missing exons m_codons_len += len([c for c in codon_table if c["t_exon_num"] == m_exon]) ...
454f7103f89ed6780caa2c53a330f892467bccda
657,904
def build_pathnet_graph(p_inputs, p_labels, p_task_id, pathnet, training): """Builds a PathNet graph, returns input placeholders and output tensors. Args: p_inputs: (tf.placeholder) placeholder for the input image. p_labels: (tf.placeholder) placeholder for the target labels. p_task_id: (tf.placeholder...
c283ac433ea8ec8864b61c7943af8735c9da6045
657,905
from pathlib import Path def store_secret(tmp_path: Path, name: str, secret: bytes) -> Path: """Store a secret in a temporary path. Parameters ---------- tmp_path : `pathlib.Path` The root of the temporary area. name : `str` The name of the secret to construct nice file names. ...
c8a2e27f2762bf65ef4a33fd35e548fd90d77216
657,906
import textwrap def wrap_summary(summary, initial_indent, subsequent_indent, wrap_length): """Return line-wrapped summary text.""" if wrap_length > 0: return '\n'.join( textwrap.wrap(summary, width=wrap_length, initial_indent=initial_inde...
9ad28c412b8f5086f9255a133b3037031017205d
657,907
import torch def iou(inp,tar): """iou for only the first mask, the apical lesions""" inp = inp[:,0,...] tar = tar[:,0,...] pc = (torch.sigmoid(inp)).float() tc = tar.float() pc_sum = pc.sum(-1).sum(-1) tc_sum = tc.sum(-1).sum(-1) intersection = (pc*tc).sum(-1).sum(-1) union = ...
67e5079cfa3e232cac4fa574be153e0478aaf0ee
657,908
import re def parse_version(module_file): """ Parses the version string from the specified file. This implementation is ugly, but there doesn't seem to be a good way to do this in general at the moment. """ f = open(module_file) s = f.read() f.close() match = re.findall("__version...
b3c35b5ab6a12a794659008e4acd98815602afb2
657,910
from typing import List from typing import Union def wipe_empty_fields(card: List[Union[str, int, float, None]]) -> List[Union[str, int, float, None]]: """ Removes any trailing Nones from the card. Also converts empty strings to None. Allows floats & ints, but that's not the intended value, though...
fdbed42cde29ac965259c6e290322db0a558b910
657,911
def reuss_avg(M1, M2, f1, f2): """ Reuss average for a 2 mineral mixture Usage: M = reuss_avg(M1, M2, f1, f2) Inputs: M1 & M2 = Elastic moduli for each phase (float) f1 & f1 = Volume fraction of each phase (float) Output: M = Reuss average of elastic moduli (float)...
f78a04314d0c6e33bc6856871fa62576f323bc49
657,912
def cleanparameters(parameters, torem='username passwd passwdconf Login Register'.split()): """Cleans parameters by removing sensitive information from it""" for k in torem: if k in parameters: del parameters[k] return parameters
2ce40481e5772009393cb2c1db3c5a0188dc2508
657,913
def get_item_table(conn, node_name, item): """ """ project = (node_name,) sql = 'SELECT {:} FROM tb_Nodes WHERE name = ?'.format(item) cur = conn.cursor() cur.execute(sql, project) record = cur.fetchone() return record
0cfb4f63fafe7de1198b743eea1a2056c684d4e3
657,914
def display_file_length(file_size): """格式化文件长度""" if file_size < 1024: return '{0:.1f}B'.format(file_size) elif 1024 <= file_size < 1048576: return '{0:.1f}kB'.format(file_size / 1024) elif 1048576 <= file_size < 1073741824: return '{0:.1f}MB'.format(file_size / 1048576) else...
1d7261111945d626709419e26277022dad82478f
657,915
def index_to_bytes(i): """ Map the WHATWG index back to the original BIG5 bytes. """ lead = i // 157 + 0x81 trail = i % 157 offset = 0x40 if trail < 0x3f else 0x62 return (lead, trail + offset)
455fbca75854dd018ffd3811e46d8627b4a9d3b9
657,916
import six import re def keys_by_pattern_dict(in_dict, patterns, matchs=None): """ Recursive dictionary lookup by regex pattern. Args: in_dict (dict): Input dict. patterns (list): Lookup regex pattern list. matchs (list): Match accumulator (recursive call only). ...
2dff14f92adc6cd9ecb93f495661e9ab402e18bc
657,918
import csv def __construct_INFO__(name_file): """ Lit le fichier 'structure' et retourne la liste INFO """ f_struc = open(name_file, "r") reader = csv.reader(f_struc, delimiter = '\t') info = [] #Liste des info contenues dans le fichier permettera d'accéder aux données dans le ficher brut for ro...
57eb06f1e419f5fb24f2891a212642a66112cd4b
657,919
def polinomioQuocienteRacional(p, b, a) : """Devolve a lista que representa o polinômio quociente da divisão p(x)/(ax-b) e o resto dessa divisão, onde p(x) é o polinômio cujos coeficientes estão na lista p e b/a é uma raiz de p(x). p -- a lista dos coeficientes do polinômio a ser dividido ...
138c510428b6b19b7cb6a1b90f81400016467f32
657,920
import argparse def get_args(): """ Get command-line arguments. """ parser = argparse.ArgumentParser( description='Program for computing satellite/airborne crossovers.') parser.add_argument( 'input', metavar='ifile', type=str, nargs=2, help='name of two input files to ...
3fdb107bc5e8cbaf269f78c569e90d733890a73b
657,921
import uuid def command_options(request, aiida_localhost, tmp_path): """Return tuple of list of options and entry point.""" options = [request.param, '-n', '--label', str(uuid.uuid4())] if request.param == 'core.code.installed': options.extend(['--computer', str(aiida_localhost.pk), '--filepath-e...
16c04475fa65d9c81b3eb114c1f508e3acf3fdfd
657,922