content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def closestMedioidI(active_site, medioids, distD): """ returns the index of the closest medioid in medioids to active_site input: active_site, an ActiveSite instance medioids, a list of ActiveSite instances distD, a dictionary of distances output: the index of the ActiveSite close...
379f98a84751c0a392f8f9b1703b89b299979676
708,308
def _to_native_string(string, encoding='ascii'): """Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ if isinstance(string, str): out = string ...
b50fd0fc62b2cfc024c847b98e1f85b4b67d07e3
708,311
def login(client, password="pass", ): """Helper function to log into our app. Parameters ---------- client : test client object Passed here is the flask test client used to send the request. password : str Dummy password for logging into the app. Return ------- post re...
5adca2e7d54dabe47ae92f0bcebb93e0984617b1
708,316
def mock_datasource_http_oauth2(mock_datasource): """Mock DataSource object with http oauth2 credentials""" mock_datasource.credentials = b"client_id: FOO\nclient_secret: oldisfjowe84uwosdijf" mock_datasource.location = "http://foo.com" return mock_datasource
8496f6b9ac60af193571f762eb2ea925915a1223
708,319
def generateFromSitePaymentObject(signature: str, account_data: dict, data: dict)->dict: """[summary] Creates object for from site chargment request Args: signature (str): signature hash string account_data (dict): merchant_account: str merchant_domain: str ...
149434694e985956dede9bf8b6b0da1215ac9963
708,322
def convert_millis(track_dur_lst): """ Convert milliseconds to 00:00:00 format """ converted_track_times = [] for track_dur in track_dur_lst: seconds = (int(track_dur)/1000)%60 minutes = int(int(track_dur)/60000) hours = int(int(track_dur)/(60000*60)) converted_time = '%...
3d5199da01529f72b7eb6095a26e337277f3c2c9
708,327
def sync_xlims(*axes): """Synchronize the x-axis data limits for multiple axes. Uses the maximum upper limit and minimum lower limit across all given axes. Parameters ---------- *axes : axis objects List of matplotlib axis objects to format Returns ------- out : yxin, xmax ...
a377877a9647dfc241db482f8a2c630fe3eed146
708,328
def total_length(neurite): """Neurite length. For a morphology it will be a sum of all neurite lengths.""" return sum(s.length for s in neurite.iter_sections())
854429e073eaea49c168fb0f9e381c71d7a7038a
708,330
def init_columns_entries(variables): """ Making sure we have `columns` & `entries` to return, without effecting the original objects. """ columns = variables.get('columns') if columns is None: columns = [] # Relevant columns in proper order if isinstance(columns, str): columns ...
49a12b0561d0581785c52d9474bc492f2c64626c
708,333
import base64 def data_uri(content_type, data): """Return data as a data: URI scheme""" return "data:%s;base64,%s" % (content_type, base64.urlsafe_b64encode(data))
f890dc1310e708747c74337f5cfa2d6a31a23fc0
708,340
def next_line(ionex_file): """ next_line Function returns the next line in the file that is not a blank line, unless the line is '', which is a typical EOF marker. """ done = False while not done: line = ionex_file.readline() if line == '': return line ...
053e5582e5146ef096d743973ea7069f19ae6d4d
708,341
def response_GET(client, url): """Fixture that return the result of a GET request.""" return client.get(url)
b4762c9f652e714cc5c3694b75f935077039cb02
708,343
def _get_realm(response): """Return authentication realm requested by server for 'Basic' type or None :param response: requests.response :type response: requests.Response :returns: realm :rtype: str | None """ if 'www-authenticate' in response.headers: auths = response.headers['www...
346b3278eb52b565f747c952493c15820eece729
708,344
def get_in(obj, lookup, default=None): """ Walk obj via __getitem__ for each lookup, returning the final value of the lookup or default. """ tmp = obj for l in lookup: try: # pragma: no cover tmp = tmp[l] except (KeyError, IndexError, TypeError): # pragma: no cover ...
73dfcaadb6936304baa3471f1d1e980f815a7057
708,346
def system(_printer, ast): """Prints the instance system initialization.""" process_names_str = ' < '.join(map(lambda proc_block: ', '.join(proc_block), ast["processNames"])) return f'system {process_names_str};'
f16c6d5ebe1a029c07efd1f34d3079dd02eb4ac0
708,356
def blend_multiply(cb: float, cs: float) -> float: """Blend mode 'multiply'.""" return cb * cs
d53c3a49585cf0c12bf05c233fc6a9dd30ad25b9
708,357
def my_func_1(x, y): """ Возвращает возведение числа x в степень y. Именованные параметры: x -- число y -- степень (number, number) -> number >>> my_func_1(2, 2) 4 """ return x ** y
9572566f1660a087056118bf974bf1913348dfa4
708,358
def matrix_mult(a, b): """ Function that multiplies two matrices a and b Parameters ---------- a,b : matrices Returns ------- new_array : matrix The matrix product of the inputs """ new_array = [] for i in range(len(a)): new_a...
5e0f27f29b6977ea38987fa243f08bb1748d4567
708,359
def clear_bit(val, offs): """Clear bit at offset 'offs' in value.""" return val & ~(1 << offs)
e50e5f8ccc3fe08d9b19248e290c2117b78379ee
708,363
def _ExtractCLPath(output_of_where): """Gets the path to cl.exe based on the output of calling the environment setup batch file, followed by the equivalent of `where`.""" # Take the first line, as that's the first found in the PATH. for line in output_of_where.strip().splitlines(): if line.startswith('LOC:'...
6a0c0d4aa74b4e84de69de023e2721edd95c36bd
708,364
def get_edges_out_for_vertex(edges: list, vertex: int) -> list: """Get a sublist of edges that have the specified vertex as first element :param edges: edges of the graph :param vertex: vertex of which we want to find the corresponding edges :return: selected edges """ return [e for e in edge...
21485073df1c754e7c8e2b7dd9cafef284e601e7
708,367
def build_job_spec_name(file_name, version="develop"): """ :param file_name: :param version: :return: str, ex. job-hello_world:develop """ name = file_name.split('.')[-1] job_name = 'job-%s:%s' % (name, version) return job_name
55a45052852e6b24cb4370f7efe5c213da83e423
708,369
def single_from(iterable): """Check that an iterable contains one unique value, and return it.""" unique_vals = set(iterable) if len(unique_vals) != 1: raise ValueError('multiple unique values found') return unique_vals.pop()
c8fb8864083195ad913ff1ddf0114b5a50068902
708,373
def api_2_gamma_oil(value): """ converts density in API(American Petroleum Institute gravity) to gamma_oil (oil relative density by water) :param value: density in API(American Petroleum Institute gravity) :return: oil relative density by water """ return (value + 131.5) / 141.5
20e625f22092461fcf4bc2e2361525abf8051f97
708,378
def remove_empty(s): """\ Remove empty strings from a list. >>> a = ['a', 2, '', 'b', ''] >>> remove_empty(a) [{u}'a', 2, {u}'b'] """ while True: try: s.remove('') except ValueError: break return s
98778e4cc90f11b9b74ac6d26b203cbfc958fd7b
708,388
import hashlib def md5_hash_file(fh): """Return the md5 hash of the given file-object""" md5 = hashlib.md5() while True: data = fh.read(8192) if not data: break md5.update(data) return md5.hexdigest()
f572ec27add8024e5fa8b9a82b5d694905e4d0f8
708,390
def find_first_img_dim(import_gen): """ Loads in the first image in a provided data set and returns its dimensions Intentionally returns on first iteration of the loop :param import_gen: PyTorch DataLoader utilizing ImageFolderWithPaths for its dataset :return: dimensions of image """ for x,...
3ccaccdfb20d7b2ca4d339adacd3c706a460fdef
708,393
from typing import List def metadata_partitioner(rx_txt: str) -> List[str]: """Extract Relax program and metadata section. Parameters ---------- rx_txt : str The input relax text. Returns ------- output : List[str] The result list of partitioned text, the first element ...
dd09aff9ea517813d43ff307fb9fc425b7338943
708,395
def fin(activity): """Return the end time of the activity. """ return activity.finish
ed5b1d1e0f29f403cfee357a264d05d5cc88093e
708,398
def solve(in_array): """ Similar to 46442a0e, but where new quadrants are flips of the original array rather than rotations :param in_array: input array :return: expected output array """ array_edgelength = len(in_array[0]) # input array edge length opp_end = array_edgelength*2-1 # used...
0af23e82caf65bea64eeeae6da8400ef6ec03426
708,399
def extract(d, keys): """ Extract a key from a dict. :param d: The dict. :param keys: A list of keys, in order of priority. :return: The most important key with an value found. """ if not d: return for key in keys: tmp = d.get(key) if tmp: return tmp
9985e2f1079088251429fa26611fa6e15b920622
708,403
from pathlib import Path def get_output_filename(output_folder: str, repository_type: str, repository_name: str, filename: str) -> Path: """Returns the output filename for the file fetched from a repository.""" return ( Path(output_folder) / Path(repository_type.lower()) ...
23b806f98265b45b799dbcc177760d5ceb8248fb
708,404
def b_2_d(x): """ Convert byte list to decimal :param x: byte list :return: decimal """ s = 0 for i in range(0, len(x)): s += x[i]*2**i return s
e865700ea30be535ad014908d6b6024186cc5ac6
708,407
import pathlib import stat def check_file(file_name): """ test if file: exists and is writable or can be created Args: file_name (str): the file name Returns: (pathlib.Path): the path or None if problems """ if not file_name: return None path = path...
5b8ff64795aa66d3be71444e158357c9b7a1b2c0
708,412
def echo(word:str, n:int, toupper:bool=False) -> str: """ Repeat a given word some number of times. :param word: word to repeat :type word: str :param n: number of repeats :type n: int :param toupper: return in all caps? :type toupper: bool :return: result :return type: str ...
62a68c1ff577781a84a58f124beec8d31b0b456c
708,413
import math def mul_pdf(mean1, var1, mean2, var2): """ Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var, scale_factor). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gau...
8ecb925273cd0e4276b867687e81b0a26419f35f
708,416
def obfuscate_email(email): """Takes an email address and returns an obfuscated version of it. For example: test@example.com would turn into t**t@e*********m """ if email is None: return None splitmail = email.split("@") # If the prefix is 1 character, then we can't obfuscate it if l...
36c230ed75fc75fc7ecd6dd2ea71a6b3310c4108
708,417
def parse_boolean(arg: str): """Returns boolean representation of argument.""" arg = str(arg).lower() if 'true'.startswith(arg): return True return False
2f0a214212aa43a8b27d9a3be04f14af67c586bc
708,418
def ascending_coin(coin): """Returns the next ascending coin in order. >>> ascending_coin(1) 5 >>> ascending_coin(5) 10 >>> ascending_coin(10) 25 >>> ascending_coin(2) # Other values return None """ if coin == 1: return 5 elif coin == 5: return 10 elif coi...
e927d8ac3f38d4b37de71711ac90d6ca2151a366
708,419
def get_key(rule_tracker, value): """ Given an event index, its corresponding key from the dictionary is returned. Parameters: rule_tracker (dict): Key-value pairs specific to a rule where key is an activity, pair is an event index value (int): Index of event in event log Returns: ...
1921e9a68d0df0867248ca83e2ba641101735fc7
708,421
def check_values_on_diagonal(matrix): """ Checks if a matrix made out of dictionary of dictionaries has values on diagonal :param matrix: dictionary of dictionaries :return: boolean """ for line in matrix.keys(): if line not in matrix[line].keys(): return False return Tru...
bc7979adcfb5dc7c19b3cdb3830cf2397c247846
708,423
import csv def build_gun_dictionary(filename): """Build a dictionary of gun parameters from an external CSV file: - Key: the gun designation (e.g. '13.5 in V' or '12 in XI') - Value: a list of parameters, in the order: * caliber (in inches) * maxrange (maximum range in yard...
b9e38d766430d44b94ae9fa64c080416fdeb8482
708,425
def _can_be_quoted(loan_amount, lent_amounts): """ Checks if the borrower can obtain a quote. To this aim, the loan amount should be less than or equal to the total amounts given by lenders. :param loan_amount: the requested loan amount :param lent_amounts: the sum of the amounts given by lenders ...
6fd717f3d0e844752e07e9dd435ff72eaa4b34c9
708,429
def to_dict(eds, properties=True, lnk=True): """ Encode the EDS as a dictionary suitable for JSON serialization. """ nodes = {} for node in eds.nodes: nd = { 'label': node.predicate, 'edges': node.edges } if lnk and node.lnk is not None: nd...
c1a777a0a81ad2e3b9197b3df5e0d35a5174d61f
708,441
def SieveOfEratosthenes(limit=10**6): """Returns all primes not greater than limit.""" isPrime = [True]*(limit+1) isPrime[0] = isPrime[1] = False primes = [] for i in range(2, limit+1): if not isPrime[i]:continue primes += [i] for j in range(i*i, limit+1, i): isPr...
6d1e12d289c9bfcdfadf64f764deba077a09ffd1
708,443
import torch def iou_overlaps(b1, b2): """ Arguments: b1: dts, [n, >=4] (x1, y1, x2, y2, ...) b1: gts, [n, >=4] (x1, y1, x2, y2, ...) Returns: intersection-over-union pair-wise, generalized iou. """ area1 = (b1[:, 2] - b1[:, 0] + 1) * (b1[:,...
ba9b445223fea5ea8332a189b297c8c40205a4e5
708,444
def updating_node_validation_error(address=False, port=False, id=False, weight=False): """ Verified 2015-06-16: - when trying to update a CLB node's address/port/id, which are immutable. - when trying to update a CLB node's weight to be < 1 or > 100 At leas...
68c5fdda121950c679afe446bfd7fb19331deb40
708,448
def parse_numbers(numbers): """Return list of numbers.""" return [int(number) for number in numbers]
ee79d4e15cbfb269f7307710d9ad4735687f7128
708,449
def _non_blank_line_count(string): """ Parameters ---------- string : str or unicode String (potentially multi-line) to search in. Returns ------- int Number of non-blank lines in string. """ non_blank_counter = 0 for line in string.splitlines(): if li...
dfa6f43af95c898b1f4763573e8bf32ddf659520
708,450
def encode_direct(list_a: list): """Problem 13: Run-length encoding of a list (direct solution). Parameters ---------- list_a : list The input list Returns ------- list of list An length-encoded list Raises ------ TypeError If the given argument is not ...
9a20ffd2051003d5350f7e059d98c35310bc9bbe
708,451
import math def truncate(f, n): """ Floors float to n-digits after comma. """ return math.floor(f * 10 ** n) / 10 ** n
ae7e935a7424a15c02f7cebfb7de6ca9b4c715c0
708,454
def get_core_blockdata(core_index, spltcore_index, core_bases): """ Get Core Offset and Length :param core_index: Index of the Core :param splitcore_index: Index of last core before split :param core_bases: Array with base offset and offset after split :return: Array with core offset and core le...
85efb96fa45ecfa3f526374c677e57c70e3dc617
708,455
from datetime import datetime def timestamp(date): """Get the timestamp of the `date`, python2/3 compatible :param datetime.datetime date: the utc date. :return: the timestamp of the date. :rtype: float """ return (date - datetime(1970, 1, 1)).total_seconds()
a708448fb8cb504c2d25afa5bff6208abe1159a4
708,457
def getdate(targetconnection, ymdstr, default=None): """Convert a string of the form 'yyyy-MM-dd' to a Date object. The returned Date is in the given targetconnection's format. Arguments: - targetconnection: a ConnectionWrapper whose underlying module's Date format is used - y...
21d27c3ef4e99b28b16681072494ce573e592255
708,459
from datetime import datetime def datetime_to_epoch(date_time: datetime) -> int: """Convert a datetime object to an epoch integer (seconds).""" return int(date_time.timestamp())
73767c663d66464420594e90a438687c9363b884
708,465
from functools import reduce def inet_aton(s): """Convert a dotted-quad to an int.""" try: addr = list(map(int, s.split('.'))) addr = reduce(lambda a,b: a+b, [addr[i] << (3-i)*8 for i in range(4)]) except (ValueError, IndexError): raise ValueError('illegal IP: {0}'.format(s)) r...
abc16c14e416f55c9ae469b4b9c1958df265433c
708,466
from typing import Optional from typing import Any def get_or_create_mpc_section( mp_controls: "MpConfigControls", section: str, subkey: Optional[str] = None # type: ignore ) -> Any: """ Return (and create if it doesn't exist) a settings section. Parameters ---------- mp_controls : MpConfigC...
60b741f35e0a1c9fe924b472217e0e3b62a1d31e
708,471
def _url_as_filename(url: str) -> str: """Return a version of the url optimized for local development. If the url is a `file://` url, it will return the remaining part of the url so it can be used as a local file path. For example, 'file:///logs/example.txt' will be converted to '/logs/example.txt'...
d1aef7a08221c7788f8a7f77351ccb6e6af9416b
708,474
def CheckStructuralModelsValid(rootGroup, xyzGridSize=None, verbose=False): """ **CheckStricturalModelsValid** - Checks for valid structural model group data given a netCDF root node Parameters ---------- rootGroup: netCDF4.Group The root group node of a Loop Project File xyzGri...
d11ce42b041b8be7516f827883a37b40f6f98477
708,475
def link_name_to_index(model): """ Generate a dictionary for link names and their indicies in the model. """ return { link.name : index for index, link in enumerate(model.links) }
ba0e768b1160218908b6ecf3b186a73c75a69894
708,476
import requests def get_session(token, custom_session=None): """Get requests session with authorization headers Args: token (str): Top secret GitHub access token custom_session: e.g. betamax's session Returns: :class:`requests.sessions.Session`: Session """ sessi...
88bf566144a55cf36daa46d3f9a9886d3257d767
708,482
import json def json_formatter(result, _verbose): """Format result as json.""" if isinstance(result, list) and "data" in result[0]: res = [json.dumps(record) for record in result[0]["data"]] output = "\n".join(res) else: output = json.dumps(result, indent=4, sort_keys=True) re...
68aae87577370d3acf584014651af21c7cbfa309
708,484
def pipe_hoop_stress(P, D, t): """Calculate the hoop (circumferential) stress in a pipe using Barlow's formula. Refs: https://en.wikipedia.org/wiki/Barlow%27s_formula https://en.wikipedia.org/wiki/Cylinder_stress :param P: the internal pressure in the pipe. :type P: float :param D: the ou...
9985d35c2c55e697ce21a880bb2234c160178f33
708,485
def PositionToPercentile(position, field_size): """Converts from position in the field to percentile. position: int field_size: int """ beat = field_size - position + 1 percentile = 100.0 * beat / field_size return percentile
c75869f3d7f8437f28d3463fcf12b2b446fe930a
708,496
def chessboard_distance(x_a, y_a, x_b, y_b): """ Compute the rectilinear distance between point (x_a,y_a) and (x_b, y_b) """ return max(abs(x_b-x_a),abs(y_b-y_a))
9b11bf328faf3b231df23585914f20c2efd02bf9
708,502
def str_with_tab(indent: int, text: str, uppercase: bool = True) -> str: """Create a string with ``indent`` spaces followed by ``text``.""" if uppercase: text = text.upper() return " " * indent + text
3306ba86781d272a19b0e02ff8d06da0976d7282
708,503
def mvg_logpdf_fixedcov(x, mean, inv_cov): """ Log-pdf of the multivariate Gaussian distribution where the determinant and inverse of the covariance matrix are precomputed and fixed. Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is irrelevant ...
648d1925ed4b4793e8e1ce1cec8c7ccd0efb9f6b
708,506
def extrode_multiple_urls(urls): """ Return the last (right) url value """ if urls: return urls.split(',')[-1] return urls
34ec560183e73100a62bf40b34108bb39f2b04b4
708,508
def take_last_while(predicate, list): """Returns a new list containing the last n elements of a given list, passing each value to the supplied predicate function, and terminating when the predicate function returns false. Excludes the element that caused the predicate function to fail. The predicate fun...
19468c9130e9ab563eebd97c30c0e2c74211e44b
708,509
def abs_p_diff(predict_table, categA='sandwich', categB='sushi'): """Calculates the absolute distance between two category predictions :param predict_table: as returned by `predict_table` :param categA: the first of two categories to compare :param categB: the second of two categoreis to compare :r...
235bfc7df29ac4a2b67baff9dfa3ee62204a9aed
708,512
def validate_engine_mode(engine_mode): """ Validate database EngineMode for DBCluster Property: DBCluster.EngineMode """ VALID_DB_ENGINE_MODES = ( "provisioned", "serverless", "parallelquery", "global", "multimaster", ) if engine_mode not in VALID_DB...
69f7952a998b6ca593106c92710909104e21f55f
708,514
def num_false_positives(df): """Total number of false positives (false-alarms).""" return df.noraw.Type.isin(['FP']).sum()
6aa339b86d15072c6a6910a43e70281575da5d36
708,515
def gcd_recursive_by_divrem(m, n): """ Computes the greatest common divisor of two numbers by recursively getting remainder from division. :param int m: First number. :param int n: Second number. :returns: GCD as a number. """ if n == 0: return m return gcd_recursive_by_div...
bd25d9cea4813e523ea6bb9bd85c24bf43dd2744
708,516
def make_list_table(headers, data, title='', columns=None): """Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the ...
569370b8359ad25bf255f940b5a89d93d896804d
708,530
def pre_process(dd, df, dataset_len, batch_size): """Partition one dataframe to multiple small dataframes based on a given batch size.""" df = dd.str2ascii(df, dataset_len) prev_chunk_offset = 0 partitioned_dfs = [] while prev_chunk_offset < dataset_len: curr_chunk_offset = prev_chunk_offset...
a0a19916d60476430bdaf27f85f31620f2b5ae2a
708,532
def _make_unique(key, val): """ Make a tuple of key, value that is guaranteed hashable and should be unique per value :param key: Key of tuple :param val: Value of tuple :return: Unique key tuple """ if type(val).__hash__ is None: val = str(val) return key, val
65d746276f635c129aa0a5aeb9b9f467453c0b2a
708,533
def headline( in_string, surround = False, width = 72, nr_spaces = 2, spacesym = ' ', char = '=', border = None, uppercase = True, ): """return in_string capitalized, spaced and sandwiched: ============================== T E S T...
1848d91bbf6c9d2216338f35433a26bcd3854664
708,534
def get_label_names(l_json): """ Get names of all the labels in given json :param l_json: list of labels jsons :type l_json: list :returns: list of labels names :rtype: list """ llist = [] for j in l_json: llist.append(j['name']) return llist
bab12bedc8b5001b94d6c5f02264b1ebf4ab0e99
708,536
def interpolate_peak(spectrum: list, peak: int) -> float: """ Uses quadratic interpolation of spectral peaks to get a better estimate of the peak. Args: - spectrum: the frequency bin to analyze. - peak: the location of the estimated peak in the spectrum list. Based off: htt...
0e74057908e7839438325da9adafdf385012ce17
708,539
import hashlib def calc_fingerprint(text): """Return a hex string that fingerprints `text`.""" return hashlib.sha1(text).hexdigest()
8be154e4e32ae9412a73e73397f0e0198ae9c862
708,541
def has_balanced_parens(exp: str) -> bool: """ Checks if the parentheses in the given expression `exp` are balanced, that is, if each opening parenthesis is matched by a corresponding closing parenthesis. **Example:** :: >>> has_balanced_parens("(((a * b) + c)") False :par...
f76c7cafcf6aadd0c2cb947f0c49d23835a9f6e4
708,543
def _is_binary(c): """Ensures character is a binary digit.""" return c in '01'
b763a5a8ba591b100fea64a589dcb0aea9fbcf53
708,544
def strip_trailing_characters(unstripped_string, tail): """ Strip the tail from a string. :param unstripped_string: The string to strip. Ex: "leading" :param tail: The trail to remove. Ex: "ing" :return: The stripped string. Ex: "lead" """ if unstripped_string.endswith(str(tail)): ...
dbd09fe9a58b0fb3072a680a9c7ac701257ebfcd
708,549
from typing import Optional def q_to_res(Q: float) -> Optional[float]: """ :param Q: Q factor :return: res, or None if Q < 0.25 """ res = 1 - 1.25 / (Q + 1) if res < 0.0: return None return res
98380be0c8fbd3bfd694d7851f35488d74cdd862
708,554
def id_str_to_bytes(id_str: str) -> bytes: """Convert a 40 characters hash into a byte array. The conversion results in 160 bits of information (20-bytes array). Notice that this operation is reversible (using `id_bytes_to_str`). Args: id_str: Hash string containing 40 characters. Returns...
cd6a702343f1267e17710305f9aed70613feacb3
708,555
import math def sieve(n): """ Returns a list with all prime numbers up to n. >>> sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] >>> sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> sieve(10) [2, 3, 5, 7] >>> sieve(9) [2, 3, 5, 7] >>> sieve(2) [2] ...
f6c930c604839ba1872bd3168c76b353606ee8ee
708,558
def is_trueish(expression: str) -> bool: """True if string and "True", "Yes", "On" (ignorecase), False otherwise""" expression = str(expression).strip().lower() return expression in {'true', 'yes', 'on'}
7d958c068281deb68de7665dc1eeb07acf5e941f
708,559
import re def contains_order_by(query): """Returns true of the query contains an 'order by' clause""" return re.search( r'order\s+by\b', query, re.M|re.I) is not None
4f4eebadfd5dc4cb1121378db4ef5f68d27bf787
708,560
def mean(l): """ Returns the mean value of the given list """ sum = 0 for x in l: sum = sum + x return sum / float(len(l))
74926c9aaafd2362ce8821d7040afcba1f569400
708,564
from typing import OrderedDict def merge_nodes(nodes): """ Merge nodes to deduplicate same-name nodes and add a "parents" attribute to each node, which is a list of Node objects. """ def add_parent(unique_node, parent): if getattr(unique_node, 'parents', None): if parent.name ...
1f5a2a7188071d9d6f8b6ab1f25ceff1a0ba8484
708,566
def find_records(dataset, search_string): """Retrieve records filtered on search string. Parameters: dataset (list): dataset to be searched search_string (str): query string Returns: list: filtered list of records """ records = [] # empty list (accumulator pattern) for ...
c6cbd5c239f410a8658e62c1bbacc877eded5105
708,567
def filter_spans(spans): """Filter a sequence of spans and remove duplicates or overlaps. Useful for creating named entities (where one token can only be part of one entity) or when merging spans with `Retokenizer.merge`. When spans overlap, the (first) longest span is preferred over shorter spans. ...
3b15a79b14f02ffa870b94eb9b61261c4befc0eb
708,571
from typing import Optional from typing import List def to_lines(text: str, k: int) -> Optional[List[str]]: """ Given a block of text and a maximum line length k, split the text into lines of length at most k. If this cannot be done, i.e. a word is longer than k, return None. :param text: the block of...
1797f45ce4999a29a9cc74def3f868e473c2775a
708,575
def product_except_self(nums: list[int]) -> list[int]: """Computes the product of all the elements of given array at each index excluding the value at that index. Note: could also take math.prod(nums) and divide out the num at each index, but corner cases of num_zeros > 1 and num_zeros == 1 make code inele...
15090d4873b0dec9ea6119e7c097ccda781e51fa
708,576
def get_option(args, config, key, default=None): """Gets key option from args if it is provided, otherwise tries to get it from config""" if hasattr(args, key) and getattr(args, key) is not None: return getattr(args, key) return config.get(key, default)
54d77c6ae3e40b2739156b07747facc4a952c237
708,580
import re def parse_extension(uri): """ Parse the extension of URI. """ patt = re.compile(r'(\.\w+)') return re.findall(patt, uri)[-1]
5ed4eee77b92f04e62390128939113168d715342
708,581
import math def rotz(ang): """ Calculate the transform for rotation around the Z-axis. Arguments: angle: Rotation angle in degrees. Returns: A 4x4 numpy array of float32 representing a homogeneous coordinates matrix for rotation around the Z axis. """ rad = math.radia...
4332242c5818ccc00d64cbebf7a861727e080964
708,582
def getBits(data, offset, bits=1): """ Get specified bits from integer >>> bin(getBits(0b0011100,2)) '0b1' >>> bin(getBits(0b0011100,0,4)) '0b1100' """ mask = ((1 << bits) - 1) << offset return (data & mask) >> offset
0bdae35f5afa076d0e5a73b91d2743d9cf156f7d
708,583
def replace_ext(filename, oldext, newext): """Safely replaces a file extension new a new one""" if filename.endswith(oldext): return filename[:-len(oldext)] + newext else: raise Exception("file '%s' does not have extension '%s'" % (filename, oldext))
33ab99860cfe90b72388635d5d958abe431fa45e
708,587
import torch def normalized_grid_coords(height, width, aspect=True, device="cuda"): """Return the normalized [-1, 1] grid coordinates given height and width. Args: height (int) : height of the grid. width (int) : width of the grid. aspect (bool) : if True, use the aspect ratio to scal...
7ddd1c5eda2e28116e40fa99f6cd794d9dfd48cc
708,594