content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _find_version_line_in_file(file_path): """ Find and return the line in the given file containing `VERSION`. :param file_path: Path to file to search. :return: Line in file containing `VERSION`. """ with open(str(file_path), "r") as fileh: version_lines = [ line for line ...
ef3e648ac6b4e9f89e67986507eba74ba65ded2d
663,173
def all_but_last(items): """Return a tuple of all but the last item in items. >>> all_but_last([1, 2, 3, 4]) (1, 2, 3) """ return tuple(items[0:-1])
1b13cb2074198cd8351dbbc16561ad33a86a08ed
663,175
def pudl_etl_parameters(etl_settings): """Read PUDL ETL parameters out of test settings dictionary.""" return etl_settings.datasets
c89bfa8087611e5c6106117131383ad1d42b4399
663,177
import getpass def get_user(lower=True): """ Returns the current user :param lower: bool :return: str """ username = getpass.getuser() return username.lower() if lower else username
b1bae74d2dfde860c931a05d56e4f84e4f2386e1
663,182
def get_img_height() -> int: """ Auxiliary method that sets the height, which is fixed for the Neural Network. """ return 32
6c2336f8468397e828f3afa52efa01cc4ecd82d6
663,185
def moveRowDimension(obj, i, j, numrows, numcols, section, more, custom): """Move a row in front of another row. Note that this will change the nesting hierarchy parameters: from: row number to move from to: row number to move to Default action interchanges the first two columns of the row label...
6bef8a01a289a4132d824b5b3b6f254eccb3bbdb
663,187
def pad_to_two_digits(n): """ Add leading zeros to format a number as at least two digits :param n: any number :return: The number as a string with at least two digits """ return str(n).zfill(2)
a26d53563e4dc439750bb729d31f7dd8d775e3fd
663,192
def max_length(choices): """ Returns the size of the longest choice. :param: the available choice strings or tuples :return: the maximum length """ def length(item): if isinstance(item, str): value = item else: value = item[0] return len(value...
90041dc55373bf8bb6ab701e119bc139adb4cc6f
663,197
def _SplitLabels(labels): """Parse the 'labels' key from a PerfKitBenchmarker record. Labels are recorded in '|key:value|,|key:value|' form. This function transforms them to a dict. Args: labels: string. labels to parse. Returns: dict. Parsed 'labels'. """ result = {} for item in labels.strip...
494f038813ae73f8700e89b5d5f93c69747de0f9
663,199
import re def small_titles(markdown): """Make titles smaller, eg replace '# ' with '### ' at the start of a line.""" markdown = re.sub(r'\n# |^# ', '\n### ', markdown) markdown = re.sub(r'\n## |^##', '\n#### ', markdown) return markdown
ffb4fbe96f2ac23f2e02a59c55acfdd24d9abe0c
663,201
def vector_subtract(u, v): """returns the difference (vector) of vectors u and v""" return (u[0]-v[0], u[1]-v[1], u[2]-v[2])
034c07a1e459725744112b51933c2c0c73c60f68
663,204
def _uniq(lst): """ Return the unique elements from a list. Retrieved from https://www.peterbe.com/plog/uniqifiers-benchmark """ seen = set() seen_add = seen.add return [i for i in lst if not (i in seen or seen_add(i))]
801328717979ceb643f4922769a8d3f1f301ee90
663,205
def get_single_message(sqs_queue, wait_time_seconds=5): """Get a maximum of one message from the provided sqs queue.""" messages = sqs_queue.receive_messages( MaxNumberOfMessages=1, WaitTimeSeconds=wait_time_seconds) if messages: return messages[0] else: return None
5ab2043bdae4ecbb8e1026faaff4bbf0032f8121
663,206
def resource_filter(value, resource, field='displayName'): """ Given a mapping (resource), gets the data at resource[field] and checks for equality for the argument value. When field is 'name', it is expected to look like 'organization/1234567890', and returns only the number after the slash. ...
932cb961af6c6969404d694450e5efee1576a59a
663,208
def timeify(time): """Format a time in seconds to a minutes/seconds timestamp.""" time = float(time) mins, secs = time // 60, time % 60 return f"{mins:.0f}:{secs:05.2f}"
42757883048ce930c5cbc40da8da161daeb8324a
663,209
def _verify_limits(limits): """ Helper function to verify that the row/column limits are sensible. Parameters ---------- limits : None|tuple|list Returns ------- None|tuple """ if limits is None: return limits temp_limits = [int(entry) for entry in limits] if ...
f0c846443cc1686da29ea6793744502ea0b1017d
663,212
def timestamp_format_to_redex(time_format): """ convert time stamp format to redex Parameters ---------- time_format : str datetime timestamp format Returns ------- redex : str redex format for timestamp """ time_keys = {'%Y': r'\d{4}', '%m': r...
b5e0f182681c74c51871b7d5cba1e720a468168a
663,214
import itertools def held_karp(dists): """ Implementation of Held-Karp, an algorithm that solves the Traveling Salesman Problem using dynamic programming with memoization. Parameters: dists: distance matrix Returns: A tuple, (cost, path). """ n = len(dists) # Maps ea...
c620d701c6163c89cb07349203062a9dc13e614a
663,216
import re def parse_format(string): """ Parses an AMBER style format string. Example: >>> string = "%FORMAT(10I8)" >>> _parse_format(string) [10, int, 8] """ if "FORMAT" not in string: raise ValueError("AMBER: Did not understand format line '%s'." % string) pstring = str...
a494f4f2ed3708d20579092108ab840a748490e8
663,219
def bb_area(bbox): """ returns area: bbox in format xs, ys, xe, ye if bbox is empty returns 0 """ if bbox.size == 0: area = 0 else: width = bbox[2] - bbox[0] height = bbox[3] - bbox[1] area = width*height return area
0680e24f4a80b34fcae66956964cbe86e7f2957f
663,220
def F1(p, r): """ Calculate F1 score from precision and recall. Returns zero if one of p, r is zero. """ return (2*p*r/(p+r)) if p != 0 and r != 0 else 0
5f7f6fee3bdf94e9942b317114b31fb25c8ecd08
663,221
import torch def rot_z(gamma): """ Rotation around Z axis """ if not torch.is_tensor(gamma): gamma = torch.tensor(gamma, dtype=torch.get_default_dtype()) return gamma.new_tensor([ [gamma.cos(), -gamma.sin(), 0], [gamma.sin(), gamma.cos(), 0], [0, 0, 1] ])
ce2a05f27484ff7fe6cb7d0cfbc777f4eaf2b442
663,222
from typing import List from typing import Dict def describe_topics(mlModel) -> List[Dict[str, float]]: """Obtain topic words and weights from the LDA model. Returns: topics -> List[Dict[str, float]] A list of mappings between the top 15 topic words (str) and their weights (float) for each to...
b9836c9526f025b823a166f23d77ee073569f62e
663,229
def percent(v): """ Transform probability into percentage. """ return v * 100
5b57f52d1eece08783d3fb829693a11f36e863b0
663,234
import re def is_custom(text, regex): """ Checks if the given text matches with a given regex Args: text (str): The text to match regex (str): A regular expression that you wanna match (recomended a raw string: r'') Returns: A boolean value, True if the text matches the string...
5cecf21751864b3d97ecdc5bd8b561d9b385f3ee
663,244
import re def split_auth_header(header): """Split comma-separate key=value fields from a WWW-Authenticate header""" fields = {} remaining = header.strip() while remaining: matches = re.match(r'^([0-9a-zA-Z]+)="([^"]+)"(?:,\s*(.+))?$', remaining) if not matches: # Without qu...
2a893b5b7f9f197b0a179bc63e741f34ba08d74b
663,250
import calendar def get_month_button(month, text=None): """ Get the button corresponding to the given month. If no `text` is given, the name of the month in English will be used. """ if month < 1: month += 12 elif month > 12: month -= 12 return { 'text': text or c...
5724e3b74262709d5f3a45faa3e7ffcbf7e19c96
663,256
import requests def _request(url: str, token: str) -> requests.Response: """ Creates a request for the IUCN API and handles HTTP exceptions. Parameters ---------- url : str IUCN API endpoint. token : str IUCN API authentication token. Returns ------- Response ...
f1c661551693f6eb90a494e56ecc103725f6bdd1
663,260
def parse_topology_str(s) -> list: """Parses node-topology string and returns list of dicts""" topology = [] if s: for a in s.split(','): (ip_port, valency) = a.split('/') (ip, port) = ip_port.split(':') #if resolve_hostname: ip = resolve_hostname(ip) ...
58fb7e9dcc5618b5b4c5d30a212110b86aba3c25
663,266
def numestate_incolour(colour:str) -> int: """Return the number of fields in given colour.""" if colour in {'brown','blue'}: return 2 return 3
7312dc87eaca38cde465a1d17573a505a9196b53
663,270
def strike_through(text: str) -> str: """Returns a strike-through version of the input text""" result = '' for c in text: result = result + c + '\u0336' return result
a178dd99d124f537bc98bcf36cdc0690862fb0bd
663,271
def frohner_cor(sig1,sig2,n1,n2): """ Takes cross-sections [barns] and atom densities [atoms/barn] for two thicknesses of the same sample, and returns extrapolated cross section according to Frohner. Parameters ---------- sig1 : array_like Cross section of the thinner of the two sa...
1024c83df879edaf872d80b67ef28e64b372e81b
663,272
def unblockshaped(arr, h, w): """ Return an array of shape (h, w) where h * w = arr.size If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols), then the returned array preserves the "physical" layout of the sublocks. """ n, nrows, ncols = arr.shape return (arr.reshape...
256471bec79767bfa85bd3f59401eb1e3614a34b
663,275
def filename_ext(filename): """ Function that returns filename extension """ # Taken from http://flask.pocoo.org/docs/1.0/patterns/fileuploads/ return '.' in filename and filename.rsplit('.', 1)[1].lower()
27776ac640ca823bf7bca3f45bae85a54a7cfb68
663,277
import torch def load_saved_model(model : torch.nn.Module, path : str) -> torch.nn.Module: """ Loads a pre-saved neural net model. Args: ---- model (torch.nn.Module) : Existing but bare-bones model variable. path (str) : Path to the saved model. Returns: ------- ...
b241943c4426cd862d402f12f59885b73bb4d1e3
663,278
def item_based_predict(movie_data, u, m1, nn_list): """Returns a prediction from parameters for a movie. Parameters ---------- movie_data : dict Dictionary of the data set. u : str Id of user to be used for prediction. m1 : str Id of mov...
e899e469f9fa1cec11cdebd406e02795a991e7dd
663,280
def _mu(df, formula, temp, cas, full): """ Helper for the `mu_gas` function to determine gas viscosity. Parameters ---------- df : dataframe Dataframe from inorganic or organic data formula : str Molecular formula for the gas temp : float Gas temperature cas : st...
25dda382184769876c1a51cba98d55357251d66a
663,288
import click def validate_section(ctx, param, value): """ Validate that a given section exists. """ config = ctx.obj.config if value and config.has_section(value): raise click.BadParameter( 'Missing or unknown section: {}'.format(value)) return value
7df6bcf5e978e9a0392edc68c86ffbb1ef47c07e
663,289
def extract_local_dets(data): """Extracts the local detectors from the TOD objects Some detectors could only appear in some observations, so we need to loop through all observations and accumulate all detectors in a set """ local_dets = set() for obs in data.obs: tod = obs["tod"] ...
47cccfc99a4f0d5f56c248a1affae07fb8d9a6f0
663,290
import random def randomize_capitalization(data): """ Randomize the capitalization of a string. """ return "".join(random.choice([k.upper(), k]) for k in data)
09b3c79507c2335269fad8fc0e29d7ec0f89698c
663,293
def nvmf_subsystem_get_controllers(client, nqn, tgt_name=None): """Get list of controllers of an NVMe-oF subsystem. Args: nqn: Subsystem NQN. tgt_name: name of the parent NVMe-oF target (optional). Returns: List of controller objects of an NVMe-oF subsystem. """ params = {'...
05f5ffd3cfe5db849e5348af1a18725b7b5f5ca8
663,294
def escape_variables(environ): """ Escape environment variables so that they can be interpreted correctly by python configparser. """ return {key: environ[key].replace('%', '%%') for key in environ}
450809d829df34b26c6ab3eb0000841a8db5600f
663,296
def subscription_name(project, name): """Get subscription name.""" return 'projects/{project}/subscriptions/{name}'.format( project=project, name=name)
80a445c1153d69c879bb2d26f541de14e3f3060a
663,299
from typing import List from typing import Dict from typing import Any import random def conflict_resolution_function(productions: List[Dict[str, Any]]) -> Dict[str, Any]: """ACT-R conflict resolution function. Currently selects a production at random from the already matched productions, since utility values...
26f35140b27cee75ce15a8f44ff061acaeb27786
663,300
def blurb(bio): """ Returns champion blurb which cuts off around 250 characters """ if " " not in bio: return bio bio = bio[0:254] bio = ' '.join(bio.split(' ')[:-1]) try: if bio[-1] == ",": bio = bio[:-1] except Exception: print(bio) return bio + ...
b7256d2b30a9cd3b2df1ef6d1995286ee319817f
663,302
from typing import Dict def is_design(obj): """ Check if an object is a Metal Design, i.e., an instance of `QDesign`. The problem is that the `isinstance` built-in method fails when this module is reloaded. Args: obj (object): Test this object Returns: bool (bool): True if i...
689428ea14e07b35916a0a69db7c503739aa4427
663,303
def fix_angle(ang): """ Normalizes an angle between -180 and 180 degree. """ while ang > 360: ang -= 360 while ang < 0: ang += 360 return ang
c2fad1ba93b8f08b0a63d2d5a4e2920a6a541995
663,309
def ranks_already_set(args) -> bool: """Return True is both local and global ranks have been set.""" is_local_rank_set = args.local_rank > -1 is_global_rank_set = args.global_rank > -1 return is_local_rank_set and is_global_rank_set
771bc2b9b6296c430c26089590f05fc983530202
663,312
def match_all_attrs(token, attrs_to_match): """ Return true if all the values in the given dict match the morphology attributes of the token. So attrs_to_match is a way of filtering out which tokens will be matched. Returns true for an empty dict. :param token: :param attrs_to_match: :retur...
0e5490a1da012a945db897b2315f79fd69dccc7b
663,313
import requests from bs4 import BeautifulSoup def getResultsURLs(URL: str) -> list: """Finds appropriate result page link in the rounds section Args: URL (str): the URL of the division results page breaks (bool, optional): Return the link of the Returns: list: the URL of the requ...
91e0930730c39d243f5c30834051f85a44ca8197
663,315
def IS(attribute, val): """ Check if two values are equal """ return attribute == val
779aded6ba5d01191e9af08200e838a102b61c19
663,319
import statistics def get_password_lengths(creds: list): """ Determine how many passwords have what lengths """ lengths = {} s = 0 for p in creds: if len(p) not in lengths.keys(): lengths[len(p)] = 1 else: lengths[len(p)] += 1 s += len(p) # The reason I didn't make this an orderdict or use Collec...
5b410a3c1e73fdb9893b5ac36d06105bd9a18351
663,321
def normalize_str(x): """ Given a value from an Excel cell, attempt to convert it to a string. Returns that normalized string if possible, or `None` otherwise. """ if not isinstance(x, str): return None return x.strip()
6657f28a4af22170963dbd0faa067a9b43fbab67
663,322
def cast_op_support(X, bXs, tXs): # Type: (XLayer, List[XLayer], List[XLayer]) -> boolean """ Check whether we can execute the provided Cast operator on the dpuv2-ultra96 target """ dtype = X.attrs['dtype'] return dtype == 'float32'
cf3be405707fde71a919aa09033743f19489585f
663,324
def solution2(values, expected): """ determines if exists two elements in values whose sum is exactly expected """ dic = {} for index, value in enumerate(values): diff = expected - value if diff not in dic: dic[value] = index continue return True ...
da8b996f4e693e97ee7724d01f8525e0a7344296
663,331
import json def parse_json(s, **kwargs): """Parse a string into a (nbformat, dict) tuple.""" d = json.loads(s, **kwargs) nbformat = d.get('nbformat',1) return nbformat, d
f77c0418bf935a560737278bb395aa2eb48fc21f
663,336
import base64 def _bytes_to_url64(bytes_data): """Convert bytes to custom-url-base64 encoded string""" return base64.urlsafe_b64encode(bytes_data).decode().replace('=', '~')
cfb16657655f9ef0c6a429ecf9cf36dbed55d08b
663,340
def find_missing_number(arr: list[int]) -> int: """ Complexity: Time: O(n) Space: O(1) Args: arr: array containing n-1 distinct numbers taken from the range [1,n] (n possible numbers) Returns: the single missing number in the range [1,n] missing fro...
105ebb8438b491fdc0f94bbffb714741b5c58291
663,344
def scrap_signature(consensus, fix=b'SIGNATURE'): """ Consume a signature field if there is one to consume. :param bytes consensus: input which may start with a signature. :returns: a tuple (updated-consensus, signature-or-None) """ if not consensus.startswith(b'-----BEGIN ' + fix ...
ca6ee8f64a7d41d5d09257a80c4e1827016a460c
663,346
def _is_sass_file(filename): """Checks whether the specified filename resolves to a file supported by Sass.""" if filename.endswith(".scss"): return True elif filename.endswith(".sass"): return True elif filename.endswith(".css"): return True return False
2e9ef936562482641457dcc71aa049400fdb7215
663,350
def create_city_and_api_groups(data): """ Creates a list of groups based on city name and issue source used in scaling the final predictions. Args: data - a pandas dataframe that contains city and source columns Returns: a list of strings, each string contains the city na...
6cf990d681bc166c29c259ae7b18df2403654c5d
663,352
def provides_dep(package, other_package): """ Check if a package provides a dependency of another package. """ for dep in other_package.alldepends(): if package.providesName(dep.name): return True return False
6d30e7f1e1964d06844c71a879d5aa8364ba556f
663,353
import math def euclidean(vec1, vec2): """ 距离函数: 欧几里得距离. :param vec1: :type vec1: list[numbers.Real] :param vec2: :type vec2: list[numbers.Real] :return: """ d = 0.0 for i in range(len(vec1)): d += (vec1[i] - vec2[i]) ** 2 return math.sqrt(d)
ff407aea238adb32241457564109b2d9faf289c0
663,354
def generate_question_id(example_id, assignment_id, question_per_example_index): """ Identifier assigned to a collected question question_per_example_index: 0-based (if a worker can write multiple questions for a single passage) """ if isinstance(question_per_example_index, int): question_pe...
294bde3f6016a4ab41af3a7ead8d147a6a363b18
663,356
def get_raise(data, key, expect_type=None): """Helper function to retrieve an element from a JSON data structure. The *key* must be a string and may contain periods to indicate nesting. Parts of the key may be a string or integer used for indexing on lists. If *expect_type* is not None and the retrieved...
a0a9a5bb419825720699d57476334637b51e34d8
663,357
def regions_intersect_ogr_p(region_a, region_b): """check if two regions intersect using ogr region_a_ogr_geom.Intersects(region_b_ogr_geom) Args: region_a (region): a region region_b (region): a region Returns: bool: True if `region_a` and `region_b` intersect else False. ...
97a886756e403104f708984705727c2095e866ac
663,363
def dim0(s): """Dimension of the slice list for dimension 0.""" return s[0].stop-s[0].start
730a3d0f8f14fcd12544bbf2333f6f51f83aac00
663,364
def get_aa_counts(table): """ A function that takes a Code and finds the counts of each AA. Returns a dictionary mapping AA to their respective counts. Parameters ---------- dict table: a python dict representing the codon table Returns ------- dict AA_count: a python dict mapping amin...
c0b719f1d2842b5934f19f9816a791f923ea5fa8
663,365
def extract_sql_param_from_http_param(separator: str, http_param: str): """ Extracts sql params from an http param with given separator, returning tuple of db_query_label and query_name """ try: db_query_label, query_name = http_param.split(separator) except ValueError: raise Exc...
79a19490df6494b8ec75f1f1d2484b3e95906f70
663,367
import re def isfloat(value): """ Return whether or not given value is a float. This does not give the same answer as:: isinstance(num_value,float) Because isfloat('1') returns true. More strict typing requirements may want to use is_instance. If the value is a float, this function...
cfeccdf3b8f1e7687b984b15ff3130f58e1250d2
663,368
def is_method_topic(topic): """ Topics for methods are of the following format: "$iothub/methods/POST/{method name}/?$rid={request id}" :param str topic: The topic string. """ if "$iothub/methods/POST" in topic: return True return False
6bf5463e97b14e554caad47af0dfe7999c143695
663,375
from typing import Optional from typing import Union import click def parse_profit_input(expected_profit: str) -> Optional[Union[str, float]]: """Parses user input expected profit and ensures the input is either a float or the string 'YOLO'.""" if expected_profit == "YOLO": return expected_profit ...
e3e1a6eacc5b5c5a4b0f81449bfc9a28e80216be
663,387
def select_supporting_facts(scored_sfs, min_thresholds): """ select supporting facts according to the provided thresholds :param scored_sfs: a list of (sentence_id, score) :param min_thresholds: a list of minimum scores for top ranked supporting facts: [min_score_for_top_ranked, min_score_for...
757f9bc75883b4930166f05874e7e6f102e3fe35
663,389
def strip_quotes(s): """ Remove surrounding single or double quotes >>> print strip_quotes('hello') hello >>> print strip_quotes('"hello"') hello >>> print strip_quotes("'hello'") hello >>> print strip_quotes("'hello") 'hello """ single_quote = "'" double_quote = '"' ...
fbb8650222c53b1bbe354a7d470136e840a395b8
663,390
def project_bucket(project_id, bucket_name): """Return a project-specific bucket name.""" return '{name}.{project_id}.appspot.com'.format( name=bucket_name, project_id=project_id)
b6b8b1c10a2b1e0a748afd1eee15efe27c5a4a22
663,392
def create_buffer(gdf,buffer_distance): """ This function is used to create buffer around given geodataframe with a specified distance Input: - gdf: input geo dataframe Output: - buffer_poly: a buffer around the input gdf with the specified distance """ buffer_po...
a49b051558d600151bac808e9f6376305ebaae67
663,393
def categorical_encoding(item, categories): """ Numerical encoding items for specified categories. If there are no appropriate category, returns -1. :param object item: item to encode. :param list categories: categories to encode by. :return: digit. :rtype: int """ for num, cat in e...
209b2908f05165ea04da6a8e061ca7c841ec88df
663,395
def to_lower(text): """Convert uppercase text into lowercase.""" return text.lower()
bbe4cd3b661d7d73af81352ad88be992697ef0ed
663,396
def yes_no_binarize(df, columns = None, case_sensitive = True, inplace = False): """Replaces ``"Yes"`` and ``"No"`` with ``1`` and ``0``, respectively. Can specify a subset of columns to perform the replacement on using the ``columns`` parameter. :param df: :type df: :class:`~pandas.DataF...
958620dfaad68949e024c7bf66bac4d7a47dc870
663,399
def energy_value(h, J, sol): """ Obtain energy of an Ising solution for a given Ising problem (h,J). :param h: External magnectic term of the Ising problem. List. :param J: Interaction term of the Ising problem. Dictionary. :param sol: Ising solution. List. :return: Energy of the Ising string. ...
866e3175534f5c1e1d606b12e6815cf520a467b0
663,403
def trint(inthing): """ Turn something input into an integer if that is possible, otherwise return None :param inthing: :return: integer or None """ try: outhing = int(inthing) except: outhing = None return outhing
93ecc4b235d8e7e7051b8720cdb832fbd7a04e2e
663,405
import dill def load_fn(path: str): """Load a function from a file produced by ``encode_fn``.""" with open(path, "rb") as file: return dill.load(file)
4ff3afa993474d8ab80adf2967c3b2acd0695075
663,406
def aggregate_values(values_list, values_keys): """ Returns a string with concatenated values based on a dictionary values and a list of keys :param dict values_list: The dictionary to get values from :param str[] values_keys: A list of strings to be used as keys :return str: """ output = ""...
2d867560f41e1487c55e498ccdca74ef0c280d32
663,410
from typing import Union import torch def int2precision(precision: Union[int, torch.dtype]): """ Get torch floating point precision from integer. If an instance of torch.dtype is passed, it is returned automatically. Args: precision (int, torch.dtype): Target precision. Returns: ...
d748f26c628706fee636479cfcbcd0d863ff7d8e
663,414
def get_parent(tree, child_clade): """ Get the parent of a node in a Bio.Phylo Tree. """ if child_clade == tree.root: return None node_path = tree.root.get_path(child_clade) if len(node_path) < 2: return tree.root return node_path[-2]
4352136242ab759d470cad3330f60d74b03cec26
663,419
def geojson_driver_args(distribution): """ Construct driver args for a GeoJSON distribution. """ url = distribution.get("downloadURL") or distribution.get("accessURL") if not url: raise KeyError(f"A download URL was not found for {str(distribution)}") return {"urlpath": url}
092709b281a5f14337583db625e1a25ad9d6876d
663,423
import json def maybe_dumps(s): """ If the given value is a json structure, encode it as a json string. Otherwise leave it as is. """ if isinstance(s, (dict, list)): return json.dumps(s) return s
d39c2c7857b060e2eb9101dd33e62507f1257117
663,424
import html def escape(s, quotes=True): """ Converts html syntax characters to character entities. """ return html.escape(s, quotes)
d7b1fb4e3d4c72b23e873fd80d90aae012e8a70a
663,428
def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y): """ Converts a quadratic Bezier curve to a cubic approximation. The inputs are the *x* and *y* coordinates of the three control points of a quadratic curve, and the output is a tuple of *x* and *y* coordinates of the four control points of the cubic cur...
fb62e1ae1ffe3d062c66e3b323905427f3bd6831
663,429
from typing import List from typing import Optional def parse_xlets(xlet: List[dict]) -> Optional[List[str]]: """ Parse airflow xlets for V1 :param xlet: airflow v2 xlet dict :return: table list or None """ if len(xlet) and isinstance(xlet[0], dict): tables = xlet[0].get("tables") ...
31fd909b3d479bdb2dcc9b6c9a92eeb754522d22
663,434
def let_user_pick(options: list) -> int: """ Present a list of options to the user for selection. Parameters ---------- options : list A list of options to be printed and user to choose from. Returns ------- int The index of the users selection. """ print("Plea...
f51e33e5364b52bc5663dbf631c2090c35cc4818
663,436
import string def filter_term(term, vocabulary): """If a word is not present in a vocabulary, check whether its lowercased or capitalized versions are present. If not and word is not a punctuation sign, then it is OOV. Otherwise, it is replaced by different case. Punctuation signs are omitted completely. ...
df2e014a9eff141f1e3baef7440b6ca70e7482c0
663,437
def boost_nmhc(group, nmhc, med_max_mhc): """ Return a fraction of boost based on total number of MHCs stimulated by peptides from the IAR. :param group::param pandas.core.frame.DataFrame group: The IAR under review. :param float nmhc: The total boost amount allotted to this criterion. :param tuple...
cffbf67858b90d65c9b5d174401bd26ba82ac01b
663,439
def load_sentences(filepath): """ Given a file of raw sentences, return the list of these sentences. """ with open(filepath, 'r') as myfile: sentences = [line for line in myfile if line != '\n'] return sentences
8b136f5be7d15f10a1f1326deb661213b3b07679
663,440
def get_ssl_subject_alt_names(ssl_info): """ Return the Subject Alt Names """ altNames = '' subjectAltNames = ssl_info['subjectAltName'] index = 0 for item in subjectAltNames: altNames += item[1] index += 1 if index < len(subjectAltNames): altNames += ', ' ret...
ce38761c452d9704bdbe3309bdfa1bb46eb9a92a
663,441
def propose(prop, seq): """wrapper to access a dictionary even for non-present keys""" if seq in prop: return prop[seq] else: return None
95e0a64599fc2da29ba4d35cfb8fb24f165af5c6
663,442
def piece_length(size): """ Calculate the ideal piece length for bittorrent data. Piece Length is required to be a power of 2, and must be larger than 16KiB. Not all clients support the same max length so to be safe it is set at 8MiB. Args ----------- size: int - total bits of all ...
ff24857c6a5fbf7dadfad7db533df2a8c2a08945
663,447
def update_lifecycle_test_tags(lifecycle, test, tags): """Returns lifecycle object after creating or updating the tags for 'test'.""" if not lifecycle["selector"]["js_test"]: lifecycle["selector"]["js_test"] = {test: tags} else: lifecycle["selector"]["js_test"][test] = tags return lifecy...
cb347e84eb4b9a11ab78ff138aed46526aa54e79
663,448
def determine(userChoice, computerChoice): """ This function takes in two arguments userChoice and computerChoice, then determines and returns that who wins. """ if(userChoice == "Rock" and computerChoice == "Paper"): return "computer" elif(userChoice == "Rock" and computerChoice...
7a819a80c37da22f5a752bcb3c26953c27472fe7
663,450
from datetime import datetime import pytz def is_in_the_future(dt): """ Is this (UTC) date/time value in the future or not? """ if dt > datetime.now(pytz.utc): return True return False
4334e31472548ab35b291c333ccf3b13061e3fc9
663,451