content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def build_matrix_row(all_vfs, accepted_hits, score=None): """ Populate row given all possible hits, accepted hits and an optional score :param all_vfs: a list of all virulence factor ids :param accepted_hits: a list of a hits that passed the cutoof :param score: the value to fill the matrix with (d...
6c463fefc658236d88eb203981bbe088481dc576
580,857
def remove_if_starts_with(haystack, needle): """ Removes needle from haystack if haystack starts with needle. Haystack remains unchanged otherwise. print(remove_if_starts_with("python", "py")) # thon print(remove_if_starts_with("python", "pyx")) # python :type haystack: str :type needle:...
1d766aac001f57de9e6a33b68ba2a5afac42bb18
580,860
def heuristic_cost_estimate(node, target) -> float: """Calculate the heuristic of th node :param node: node to test :param target: the final node :return: the heuristic between the node to test and the target """ return abs(target.x - node.x) + abs(target.y - node.y)
75dd9b002685e31e14e8058ad2c79def424d6520
580,862
def is_odd(x): """ takes integer input outputs true if in is odd else outputs false """ return x%2==1
1d23f0dc36362518b19c515d741f84f9d28f1a54
580,864
def apply_model(model, pairs, T=None): """ Applies the model on a given set of pairs. If model.T does not contains entries for the fiven set of pairs, these entries must be provided in T argument. :param model: A PathL model. :param pairs: An iterable with node pairs. :param T: A path dictionary...
dce6d0456b92777123225d3fb447db8abbd4397e
580,865
def strip_line_comment(line: str) -> tuple[str, str, str] | tuple[str, None, None]: """ Finds the start of a comment in the line, if any, and returns the line up to the comment, the token that started the comment (#, //, or /*), and the line after the comment token """ comment_tokens = ['#', '//...
301a337a4cc74a9700cb34c1f08d299be5344653
580,873
def _af_commutes_with(a, b): """ Checks if the two permutations with array forms given by ``a`` and ``b`` commute. Examples ======== >>> from sympy.combinatorics.permutations import _af_commutes_with >>> _af_commutes_with([1,2,0], [0,2,1]) False See Also ======== Permutat...
b42b7928df67c729fc669dd804d1e951c7c87c1a
580,877
def unisafe(val): """safely convert to unicode >>> unisafe(None) '' >>> unisafe(b'123') '123' >>> unisafe( ... b'\\xe3\\x81\\x93\\xe3\\x82\\x93\\xe3\\x81\\xab\\xe3\\x81' ... b'\\xa1\\xe3\\x81\\xaf\\xe4\\xb8\\x96\\xe7\\x95\\x8c' ... ) 'こんにちは世界' >>> unisafe(1) '...
55a373cc787589b99a9136a31b023c4fce22c5db
580,879
def get_return(funct_string) -> str: """ Get the return documentation for a function :param funct_string: The documentation to pull the return from :return: A string of the return documentation """ ret = '' for line in funct_string.split('\n'): if 'return:' in line: split...
3c8d99dc257ba4cbf33c4c77b64582a5ddce6524
580,890
from typing import Tuple def is_system_set_up(gcp_storage_blueprint, storage_resource_type) -> Tuple[bool, str]: """ Checks that the inputs are all true, returning a """ if not gcp_storage_blueprint: message = ( "the sync plugin for GCP Buckets must be set on the Discovery tab of a...
76d6fc225bbc68288dbc3f39bc014ae22bbf1f1a
580,892
def merge_to_string(block): """Convert a block back into a string.""" return '\n'.join(''.join(line) for line in block)
21e139bbfd406d362415a00ed9023f96185a7427
580,898
def offset_from_peak(peak_ind, freq, prepeak): """Compute data offset index from location of first peak. Args: peak_ind (int): location of first peak as index value freq (float): data frequency in Hz prepeak (int/float): desired start point of data stream in s prior to first...
9a0e602c5e2cbf5ee5ce1c4b952e165158e5aa2f
580,899
def dict_factory(cursor, row): """Convert database row objects to a dictionary. This is useful for building dictionaries which are then used to render a template. Note that this would be inefficient for large queries. """ output = {} for idx, col in enumerate(cursor.description): ou...
6cbacf38db778f3aeb559c84860354dfa3296344
580,907
import stat def repr(flags: int) -> str: """ Returns a string representation of the access flags *flags*. """ template = 'rwxrwxrwx' order = (stat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR, stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP, stat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH) return ''.join(temp...
cdbdb10d795c4e0ea2d04fa7584e5fa592f32404
580,909
def exists(sim): """ Defines a pynbody derived array which determines the time steps a clump exists at """ return (sim['N'] > 0)
6de42218c86c1724336031c10d9db0ab0244bdbc
580,910
import re def parse_protobuf(lines): # pragma: no cover """Parse the protobuf text format just well enough to understand recipes.cfg. We don't use the protobuf library because we want to be as self-contained as possible in this bootstrap, so it can be simply vendored into a client repo. We assume all fiel...
ed8e55ade7719ad6fa8c68fe3e07f551bf728508
580,911
def is_color_similar(color1, color2, overlap=0.05): """Checks if colors are similar. :param tuple[int, int, int] color1: original color. :param tuple[int, int, int] color2: color to check. :param float overlap: overlap parameter. If colors similarity > overlap then colors are similar. :rtype: bool...
49d5122dfd1b4f101276e54e1d4c94b1363e91e0
580,912
def isanint(trystring): """ Checks a string to see if it is a valid integer via cast and exception :param trystring: string to check :return: True, if the string evaluates to a valid integer """ try: int(trystring) return True except ValueError: return False
be2f98293ad5a03a2e9dacb8f926e4f87780d238
580,916
def readbinary(filename): """Given a filename, read a file in binary mode. It returns a single string.""" filehandle = open(filename, 'rb') thisfile = filehandle.read() filehandle.close() return thisfile
1fb214aa355e3a3b8b2b5674e73aa28807b7023d
580,920
from datetime import datetime def olderthanhours(obj, nhours): """ Returns True if obj's is older than nhours. False otherwise. """ objdate = datetime.strptime(obj.last_modified, '%Y-%m-%dT%H:%M:%S.%f') delta = (datetime.now() - objdate) return (delta.seconds / 3600) + (delta.days * 24) > nhou...
d6393933cbdcb09e5385fefa1b2bb87270eafbb5
580,924
import requests from bs4 import BeautifulSoup import re def check_url(url): """Checks the provided URL for the latest item id, and returns it. If no item_id can be found (due to invalid url or other erros), an exception will be raised.""" # Get the page where the items are listed. r ...
6520f41e4122f714775498eb2465e94f51405511
580,925
def get_decode_and_transmit_cycles(n_neurons_in_cluster, size_out): """Cycles required to decode spikes and transmit packets.""" # Based on thesis profiling return 2*n_neurons_in_cluster*size_out + 143*size_out + 173
e8da877fb6c7fa40012cd8cdea800bada5a696b7
580,926
import random import string def device_name_list(min_devices=0, max_devices=10): """ Return a function that returns a random list of device names based on parameters. """ def the_func(): return [ "/dev/%s" % "".join( random.choice(string.ascii_upper...
b8733f5d8a9a1d2b62df85be37cd5f098b29adf4
580,930
def load_requirements(fname): """ load requirements from a pip requirements file """ with open(fname) as f: line_iter = (line.strip() for line in f.readlines()) return [line for line in line_iter if line and line[0] != "#"]
ea0972fba101daf632aab44f0d149086cb57879f
580,931
from bs4 import BeautifulSoup def sanitise_xml(s): """ Use BeautifulSoup to extract all text within HTML/XML tags, except those in <code> blocks. Remove the line breaks, replace unicode character for space Parameters ---------- s - UTF-8 string Returns ------- Cleaned up ...
2af634fbdf8939a0533a052095b043832e39b6d4
580,932
def curverad_center_dist_texts(left_curverad, right_curverad, center_dist): """ Generates texts for curvature radius and center distance. :param left_curverad: left curvature radius. :param right_curverad: right curvature radius. :param center_dist: center distance. :return: list of strings. ...
516ee7472e86ed97adb47cc8cadb62d8bedc58c9
580,933
from typing import Union import pathlib import csv def read_csv(filename: Union[pathlib.Path, str]): """Read a CSV file. **Example**: >>> read_csv('/path/to/data.csv') [{ 'name': 'foo' }] :param filename: Path to CSV file. :return: A Python representation of the CSV document...
d2a1c46adeffa1ddae0c56cb24f0c43be011ab3d
580,934
def _get_TZIDs(lines): """from a list of strings, get all unique strings that start with TZID""" return sorted(line for line in lines if line.startswith('TZID'))
7c2b620c77cb0a72283ac7223622f16eaeb06290
580,940
def get_content_file_url(content_file_data, is_page=False): """ Calculate the best URL for a content file. Otherwise, use the S3 URL - this should be converted to the appropriate CDN url if needed on the front end. Args: content_file_data (dict): content file data is_page (bool): True f...
9ab22f40ccd86b04ca114157cb8ca7d6964d701a
580,941
import time def timestamp() -> str: """ Gets the current time since the Epoch is seconds. Milliseconds are ignored. :return: a string with the current time since Epoch. """ return str(time.time()).split(".")[0]
5e280758fa1de414335f131e212a63a420ff928f
580,944
def read_rpm_spec_file(specfile): """ Read the RPM spec file, and return info :param specfile: the RPM spec file to read returns a tuple of (name, version, source, url) """ name, version, source, url = ('', '', '', '') with open(specfile, "r", errors="backslashreplace") as f: for lin...
3efcdb31c8af02a6c80147c6a596bab75eaca8f8
580,945
def key_exists(search_key: str, search_dict: dict): """Returns bool if a key exists at the top level of a dict""" return search_key in search_dict.keys()
aab578b707f9dc2b2c0efc1be43718b997390920
580,946
import re def has_special_characters(target): """Check whether the target strings contained a special characters or not. Definition of special characters `~!@#$%^&*()=_-+<>?:"{},./;'[]\ :param target: test strings :return: True if contained or False if not """ pattern = r'[`~!@#$%^&*...
7fb545a0bcd0137267183b74ce0dc0647beba16d
580,950
def subst_char(buffer, v, row, col): """To substitute a character in the buffer with the given character at the given position. Return the substituted character.""" if row >= len(buffer): raise ValueError("row index out of bound") new_line = list(buffer[row]) if col >= len(new_line): ...
5eb9861b76ca4f6f7e557fedcab6f3e25ef4b7ee
580,951
import json def simplify_fraction(f): """ .. function:: simplify_fraction(Fraction) -> int or float or Fraction Takes as input a Fraction and returns the equivalent int or float. In the case the int or float cannot be represented, the function returns the Fraction in json format Examples: >>...
e0044dfbb0e718b3a13d08cfcdb64fbdf9d0a7d6
580,953
def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space...
5fe61ed2da2ea011e8f989c2b40a84a90cb1addc
580,957
def get_L_star(tasks): """ Get the L* value for the given periodic task set. Parameters ---------- tasks : list of pSyCH.task.Periodic Set of periodic tasks, for which the L* value needs to be computed. Returns ------- float L* value for the task set. """ L = 0...
338ee4062d9024da7c369e81dad3e7a475be6a9e
580,963
def internalNodeIP(node_id): """Return IP address of radio node on internal network""" return '10.10.10.{:d}'.format(node_id)
304adf6a6864ef44c6277a03d0b2da65c01567b1
580,970
def hard_limit(val, limits): """ Check if a value is outside specified limits :param val: value to be tested :param limits: two membered list of lower and upper limit :type val: float :type limits: list of floats :return: 1 if the input is outside the limits, 0 otherwise :retur...
a3c65e0bfe13d1a064bf09d35523884df4b8de40
580,971
def print_num_stats(stats, units=None, formats=None, file=None): """ Utility function to print results of `num_stats` function. >>> print_num_stats(num_stats(range(10)), units={'count':'iterations'}, formats={'sum':'%.5f'}) count 10 iterations sum 45.00000 mean 4.500 sd 2.872 min 0.000 ...
45f4c4ae8fe89bb95afd6ae878b74370687e63a4
580,973
def _supports_alg(user_alg: bytes, peer_alg: bytes) -> bool: """ Return whether the peer supports the algorithm specified by the user. :param user_alg: Service ID requested by user :param peer_alg: Service ID offered by privacy peer :return: True, if algorithm is supported by the peer """ ...
5d7dd4a4425477a3b1092a3b1585f43424f9d2d7
580,974
from datetime import datetime def has_no_time(at): """Returns True if the given object is an ``adatetime`` where ``hour``, ``minute``, ``second`` and ``microsecond`` are all None. """ if isinstance(at, datetime): return False return (at.hour is None and at.minute is None and at.second is ...
3ff57cd2188b84ae2fb22b8daa3cbcd2e76dcab5
580,977
def int_of_string_opt(s, base=10): """ Convert string to integer without raising exceptions :param s: integer string :param base: numbering base :return: integer value or None on failure """ try: return int(s, base) except: return None
3695da53bac73909e65cc1eea39c5696762299c5
580,978
def clean_predictor_name(predictor: str) -> str: """Strip-off redundant suffix (e.g. "_enc" or "_bin") from the predictor name to return a clean version of the predictor Args: predictor (str): Description Returns: str: Description """ return (predictor.replace("_enc", "").repla...
1854c7747a0670ee4b40b0d8b7db755f8fced00c
580,982
def set_feature_file(data_type, network = 'Resnet50'): """ Construct file name for the bottleneck file """ return network + '_features_' + data_type + '.npz'
543f57f47b4b2cfffca7283aa816433ab3ef4ebe
580,983
def _is_mutect2_somatic(rec): """MuTect2 does not use SOMATIC flag, instead using presence of tumor TLOD and PASS. """ return rec.INFO.get("TLOD") is not None and rec.FILTER is None
642d06183056d7c3104c3e18a917f76b96effe3b
580,984
from typing import List def evaluar(p: List[float], x: float) -> float: """Evalua un polinomio en x :param p: polinomio :p type: list :param x: valor a evaluar :x type: float :return: valor del polinomio en x :rtype: float """ return round(sum(p[i]*x**i for i in range(len(p)))...
09e0fc30ac7626fca194549f29157bd7915d9016
580,985
def countCharactersInFile( filename ): """ Spočítá počet výskytů znaků anglické abecedy a čísel. Rozlišuje mezi velkými a malými písmeny. Parametry: ---------- filename: string Jméno souboru, ve kterém má znaky spočítat. Vrací: ------ list Pole slož...
fedb0df205763c3d6eaf2abb290d396117c2a1ab
580,987
from typing import List def get_scores(true_pos: int, false_pos: int, false_neg: int) -> List[float]: """ calculate scores of performances with criteria of the computed confusion matrix : precision, recall or sensibility and F1-score. :param true_pos: number of correct detections :type true_pos: ...
a917033018e551f55290f4f9ce20f90ba4c50ad1
580,988
def getStudentProposalRedirect(entity, params): """Returns the student proposal redirect for the given org and student. """ result ='/%s/apply/%s?organization=%s' % ( params['url_name'], params['student_key'], entity.link_id) return result
f44912a4512413b450aed32a64a863f3deea2a4f
580,993
import string def _convert_column_to_number( col_letter: str ) -> int: """ Convert spreadsheet-style column letter to its corresponding number, starting with 0. Args: col_letter: e.g. A, L, AB Returns: col_number: e.g. 0, 11, 27 """ col_number = 0 for c in col_let...
8bcde8c11439fb811389c99db9e8dceaa73393df
580,995
def convert_bbox_coord(coord, im_height_or_width=512): """ Simple function designed to be used in a pd.apply() statement. Converts TF's preferred format for bounding box coordinates (float percent to PASCAL VOC's preferred format (pixel coordinates, top left origin). NOTE: this currently...
4b4124b7c7935461108fb0bca8abfa35887ab286
581,003
from itertools import groupby def group_count(i): """An iteration that returns tuples of items and the number of consecutive occurrences. Thus group_count('aabbbc') yields ('a',2), ('b',3), ('c',1) """ return [(item, sum(1 for n in group)) for item, group in groupby(i)]
b8e9dd4238583c934533b5026d1830808375e3d8
581,004
def is_latitude(coord): """ Determines if a coordinate is latitude. :param coord: coordinate of xarray dataset e.g. coord = ds.coords[coord_id] :return: (bool) True if the coordinate is latitude. """ if "latitude" in coord.cf and coord.cf["latitude"].name == coord.name: return True ...
9ad19e987aa4b5c83bc1f20110b9b11b837d0f60
581,008
def formatted_param_type(ptype): """Return the short name for a type. Special treatment for by-name and var args""" pt_name = ptype["name"] if pt_name.startswith("<byname>"): pt_name = pt_name.replace("<byname>[", "=> ")[:-1] elif pt_name.startswith("<repeated>"): pt_name = pt_name.repla...
69e3fcf13e16988de4e83f95b00a4dfbe33fa6dd
581,010
from datetime import datetime def datetime_to_timestamp(dt=datetime.now()): """Convert a datetime in local timezone to a unix timestamp""" delta = dt - datetime.fromtimestamp(0) return delta.seconds + delta.days * 24 * 3600
ac33be18eae7784b9949d5e81c5e47a464b550ad
581,019
def make_divisible( v: int, div: int ) -> int: """Decrease a number v until it is divisible by div. Parameters ---------- v : int The number to be made divisible. div : int The divisor value. Returns ------- int The new value of v which is divisible by d...
a0a5dd8e33607a9e94c74ac0dbfeb842a002f6a4
581,020
def _adjust_coefficient(user_input: str, variable: str): """ A function that converts Nx --> N×x :param user_input: A mathematical expression e.g. y=c+2x :param variable: The variable to be adjusted :return: String with the conversions, e.g. y=c+2*x """ if variable not in user_input: ...
999732dff7b8b6b5534ce2200edcff024fa41b20
581,021
def extract_oversampled(a, xf, yf, kernel_oversampling, kernelwidth): """ Extract the (xf-th,yf-th) w-kernel from the oversampled parent Offsets are suitable for correcting of fractional coordinates, e.g. an offset of (xf,yf) results in the kernel for an (-xf,-yf) sub-grid offset. We do not wa...
e7db6e67dca05310c5be5218f288272a76227636
581,024
def pos(user_1, user_2): """ Compares if user_1 has a better ranking than user_2 """ if user_1.resolved == user_2.resolved and user_1.score == user_2.score: return False return True
c4089198db93794a3e933be8ef6da50cff2a6e3d
581,027
def get_dictvals(mydict): """This function recursively gets all non-dict items in a hierarchical dict data structure. The order of the items have no intended meaning. e.g. myheir = { 0: '0.0', 1: '0.1', 2: {0: '1.0', 1: '1.1'}, 3: {0: '1.2', 1: {0: '2.0', 1: '2.1', 2: {0: '3.0'}, 3:'2.2'}}, 4: {0: '...
2d94b21224090a49f60ae3ca89c06458ae29e896
581,030
def get_elaspic_proteins(core_data, interface_data): """ Given ELASPIC result dataframes core_data and interface_data, get unique proteins from both dataframes. Merge these proteins and return. Parameters ---------- core_data : <DataFrame> ELASPIC results which are all `cor...
357d964d29835447283fde19ad8c6701428b3019
581,039
def version_lower_than(gaphor_version, version): """Only major and minor versions are checked. >>> version_lower_than("0.3.0", (0, 15, 0)) True """ parts = gaphor_version.split(".") return tuple(map(int, parts[:2])) < version[:2]
89e026a6a9b12b5c64d28e899c1c3a1ee4232fbc
581,044
from typing import Union import math def ceil(i: Union[int, float]) -> int: """ Converts a Float value into an Int by rounding up to the next higher integer. """ return math.ceil(i)
118ba2b5380c572135c02277cd8776d114399199
581,045
from typing import List def data_string_to_list(string_data: str) -> List: """Transforms a data string of the form key1.key2.key3 to list. Validation checks are applied here. :param string_data: The data string :return: The serialized data as a single list """ return string_data.split(".")
871c03e4509955bb5818f6eec25ba7235b968865
581,047
def strip_short(s, minsize=3): """ Remove words with length lesser than `minsize` from `s`. """ return " ".join(e for e in s.split() if len(e) >= minsize)
2febdf890e1cbc6ff1ba0ae87c70a8d8cf9c0128
581,049
def truncate_dataset(dataset, truncation_point): """ Abstraction of numpy slicing operation for 2D array truncation. :param dataset: 2D np.array :param truncation_point: int of truncation index to test :return: np.array """ assert (len(dataset.shape) == 2) # Assert data_column is a 2D numpy...
3cf6648dbbaaf34810af6ad922354eb0fb350d65
581,050
def date_is_within_year(date, year): """True if the passed date (datetime) is within year, False otherwise""" return date.year == year
82f469528d4db31b1795906108471717e5e353e7
581,056
def _latex_tabular(rows): """Creates a string of text that denotes a tabular entity in LaTeX Parameters ---------- rows : list Nested list, with each sublist containing elements of a single row of the table. Returns ------- table : str LaTeX-formated table Exam...
c262f76d89981d87cb408aca57289997ee3c543b
581,058
def _indent(s, width=4, skip_first_line=False): """_indent(s, [width=4]) -> 's' indented by 'width' spaces The optional "skip_first_line" argument is a boolean (default False) indicating if the first line should NOT be indented. """ lines = s.splitlines(1) indentstr = ' '*width if skip_firs...
85c61d9c94b46383058fa54f5c111043a43a5cbc
581,059
def index_range(raw): """Parse index ranges separated by commas e.g. '1,2-5,7-11'.""" if not raw: return None indices = set() try: with open(raw, 'r') as f: for l in f: l = l.strip() if len(l) == 0 or l[0] == '#': continue ...
1699abbb4b6ec8c4cfc69cd7428a01e84066caca
581,060
def _is_blob_type(item_json): """Determine if one drive file type can be represented as a CBlob""" return ('file' in item_json or 'photo' in item_json or 'audio' in item_json or 'video' in item_json)
4bd8ab1683a3920a389eda8467a99fbc5a69a0b7
581,062
from typing import OrderedDict def transform_templateListItem(result): """Transforms an item from a template list into a row in a table""" result = OrderedDict([('Template Id', result['id'] if 'id' in result else ''), ('Title', result['title'] if 'title' in result else ''), ...
8980fc1612d4820045b78246a589502c5a5f7412
581,066
def num_stuff(x): """Adds 5 to the supplied number""" return x + 5
19e13fb58cd05fada46b91b0673f0fe0cfd4c8f6
581,067
def _get_disk_free_size_mb(disk, pending_delete): """Return the size of free space on the disk in MB. :param disk: a PhysicalDisk object. :param pending_delete: Whether there is a pending deletion of all virtual disks. """ return disk.size_mb if pending_delete else disk.free_size_mb
170913b00ee9b97f754b86c81c3ccaa7583917d2
581,068
def count_bags_contained(bag: str, parsed_restrictions: list) -> int: """Count of bags that a given bag must contain (inc. itself) :param bag: Type of bag to check :param parsed_restrictions: List of bag-containing restrictions :return: Count of the total number of bags the given type contains """ ...
0f7bfabda07575a065c41bab6740bf04b0a78eb3
581,073
def UnpackResDat(resdat): """ Unpack 'res' data :param str resdat: 'res' data :return: resnam(str),resnmb(int),chain(str) :seealso: lib.PackResDat() """ # resdat: resnam:resnmb:chain -> resnam,resnum, chain name resnam=''; resnmb=-1; chain='' if len(resdat) > 0: item=resdat...
3bbcd7df24d1962ef774e0432074edc2ab8a19cf
581,077
def padTime(timestring): """ Returns a 12 digit string as time by padding any missing month, day, hour or minute values. """ padder = "000001010000" if len(timestring) < 12: timestring = timestring + (padder[len(timestring):]) return timestring
7e986d3de4f34ba00942d0dbd64c0a72a90f7469
581,081
def format_string(format_config, target_value): """ Formats number, supporting %-format and str.format() syntax. :param format_config: string format syntax, for example '{:.2%}' or '%.2f' :param target_value: number to format :rtype: string """ if (format_config.startswith('{')): re...
0c51863ced37b4acb79b741ef5989ab409a86f7e
581,083
import inspect def check_eddb_base_subclass(obj): """ Simple predicate, select sublasses of Base. """ return inspect.isclass(obj) and obj.__name__ not in ["Base", "hybrid_method", "hybrid_property"]
911e04c60167b23f537bb46526622e0a56a255d4
581,085
from typing import Iterable from typing import Set import re def _regex_filter(seq: Iterable, regexps: Iterable[str]) -> Set[str]: """Filter items matching at least one of the regexes.""" matched: Set[str] = set() for regex in regexps: pattern = re.compile(regex) matched.update(filter(patt...
d3a6e4123278a25857d9a6fe9ddb44c932180340
581,088
import csv def get_versions(csv_dir): """Get version of pokemon's games. Args: csv_dir (pathlib.Path): Path to csv directory. Returns: list: List of dict containing infos to build pokediadb.models.Version object. Raises: FileNotFoundError: Raised if versions.csv ...
345936880377e6a0eb5c0826a9ea844a73486c99
581,089
def get_parentheses(s, stop_on_closing=False): """Looks up opening/closing parentheses pairs in a string. Args: s (str): input string. stop_on_closing (bool): If True, parsing stops upon reaching a closing parenthesis of the first opening one. If False, the parser contin...
3f00084cf39838d393059b41ce100cffe2ae8aec
581,093
def adapt_scoring_function(scoring_function): """Adapt the scoring function. Ax's optimize function calls the scoring function with a dict object, however our challenges recieve them as kwargs. """ def adapted_function(params): return scoring_function(**params) return adapted_function
0637f0ecfb53fffc6db8a09df853abbd354a8b04
581,094
def _reg2float(reg): """Translate the register value to a floating-point number. Note ---- The float precision is specified to be 1 digit after the decimal point. Bit [31] (1 bit) -> Sign (S) Bit [30:23] (8 bits) -> Exponent (E) Bit [22:0] (23 bits) -> M...
36842c4c41c8489fa7e3f7cd105e52438e81d03b
581,100
def get_unit_element(group, component): """ Get unit element of a group component (ZR, G1, G2, or GT) :param PairingGroup group: a group object :param int component: a group component (ZR, G1, G2, or GT) """ return group.random(component) ** 0
5b6be035358940d6bc35f501b374ad1007f41004
581,101
from typing import List def _IntRange(mask: str) -> List[int]: """Converts an integer mask into a sorted list of integers. _IntRange('0,1,5-7') == [0, 1, 5, 6, 7] Args: mask: String integer mask as from MPI pinning list Returns: Sorted list of integers from the mask """ ints = [] for raw in m...
df21fb4dcbd01c77e583a06394719c047c33263e
581,105
def get_groups_from_inventory(inventory): """ Return groups from Ansible Inventory :param inventory: Inventory :return: Groups """ groups = inventory.groups del groups['all'] return groups
7412f8738c663d871cd65d3627d065d4fa3beb02
581,113
def conflicting_indices(X): """Finds where the indices are in the rest of feature matrix. This assures that the correct indices are dropped. Parameters ---------- X : 2D array The embed indices. This is the same shape as the actual embedded time series. Returns ------- ...
4eb52cdd0c287a79b37cc93d38684a0234e053a2
581,114
def drop_nan_nodata(xx): """ We pass this function to the native_transform parameter of load_with_native_transform in order to strip off the no-data values """ for dv in xx.data_vars.values(): if dv.attrs.get("nodata", "") == "NaN": dv.attrs.pop("nodata") return xx
94b6076566b000b8d9b74ad6aa15947b8351dda4
581,120
def path_actions(node): """The sequence of actions to get to this node.""" if node is None: return [] if node.parent is None: return [] return path_actions(node.parent) + [node.action]
e6d5a9e2dbcc34aa1aa4407f5c2fefeee0326f25
581,121
from typing import ByteString import base64 def b64_url_enc(data: ByteString) -> str: """ Encode Base64url. https://tools.ietf.org/html/rfc7515#section-2 """ return base64.urlsafe_b64encode(data).decode().rstrip('=')
1d2d6b77c45af62d5a79524f285721549e116286
581,124
import math def solar_zenith_angle(lat, solar_decline, hour_angle): """Returns Solar Zenith Angle in Degrees, with Latitude, lat, Solar Decline (Degrees), solar_decline, Hour Angle (Degrees), hour_angle.""" solar_zenith_angle = math.degrees( math.acos( math.sin(math.radians(lat)) * ma...
e7dbdca0195efccdf8eca7187c79b4f1ce519a75
581,129
def error_match(actual, expected): """Check that an actual error message matches a template.""" return actual.split(":")[0] == expected.split(":")[0]
332f5f0e54e4ae6c07644456fd37105fdff470ff
581,130
def _is_int(num_str): """ Returns whether or not a given string is an integer :param num_str: The string to test :return: Whether or not the string is an integer """ try: int(num_str) return True except ValueError: return False
656c86f9cc666ae88fd49dd42831b7de0bbb85c9
581,132
from typing import Optional def encode_str(buffer: bytearray, position: int, value: 'Optional[str]', encoding: str) -> int: """ Encode the string value. :param buffer: Buffer to fill :param position: Start position :param value: Value to encode (can be None or empty string) :pa...
ef4aebcbf406d29c999e3c7fa885ca10cf4dc78b
581,134
import base64 def urlsafe_base64_encode(s): """ Encode a bytestring to a base64 string for use in URLs. Strip any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=').decode('ascii')
beb00646c24e11a76ad791aaa7c7fd2860e819fc
581,135
def _apply_epa_correction(pm, rh): """Applies the EPA calibration to Purple's PM2.5 data. We floor it to 0 since the combination of very low pm2.5 concentration and very high humidity can lead to negative numbers. """ return max(0, 0.534 * pm - 0.0844 * rh + 5.604)
49102e3f321e357295c5395ecd2265fb7a8eb6b3
581,136
def linear_cx(cx, w_in, w_out, *, bias=False): """Accumulates complexity of linear into cx = (h, w, flops, params, acts).""" h, w, flops, params, acts = cx["h"], cx["w"], cx["flops"], cx["params"], cx["acts"] flops += w_in * w_out + (w_out if bias else 0) params += w_in * w_out + (w_out if bias else 0) ...
1387f07768dfecb15e3fcf98721f18cd95691495
581,138
import math def resize_crop(image, size): """ Crop the image with a centered rectangle of the specified size image: a Pillow image instance size: a list of two integers [width, height] """ img_format = image.format image = image.copy() old_size = image.size left = (old_s...
b8daa6028a380f0814680a29e4dbc959e0c57b09
581,139