content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def is_long_tensor(tensor: torch.Tensor) -> bool: """ Returns True if a tensor is a long tensor. """ if torch.is_tensor(tensor): return tensor.type().endswith("LongTensor") else: return False
164b5a27f04d920fd9f186a30b8af5bdfbb71d60
657,516
def _as_friendly_string(s): """Converts a bytestring to a text string. To avoid encoding errors caused by arbitrary high characters (allowed in PICO-8 source), this replaces all high characters with underscores. Args: s: The bytestring. Returns: The text string with high character...
9853b3024b04408795db5a42917222d5c27c981f
657,518
import torch def build_classifier_confidence(input_channels: int) -> torch.nn.Sequential: """ Create sequential module for classifier confidence score. :param input_channels: Number of input activation maps. :return: Sequential module. """ return torch.nn.Sequential( torch.nn.Linear(i...
8ff194c19f6ab175a56c7d959e495a550cae6f6a
657,520
def get_bitstream_type(field, db_object): """Retrieves the bitstream type from the device image object""" device_image = getattr(db_object, 'image', None) if device_image: return device_image.bitstream_type return None
6b2fbef569a5b078e8e26dfd5edc563c43218a83
657,521
def startswith(x, lst): """ Select longest prefix that matches x from provided list(lst) :param x: input string :param lst: prefixes to compare with :return: longest prefix that matches input string if available otherwise None """ longest_prefix = None for prefix in lst: if x.starts...
bbffef79e3f3c03fb5e41564310df143eef5484d
657,524
def bytes_to_str(value): """Return UTF-8 formatted string from bytes object.""" return bytes(value).decode('UTF-8')
8e43de7f21cbcde55b79f3ea118b7e29b4e78aa1
657,526
def convert(ruta): """Función para convertir una lista a string con las posiciones de la ruta separadas por '-' Args: ruta: Una lista con las posiciones de la ruta Returns: ruta_c: Un string con las posiciones de la ruta separadas por '-' """ s = [str(i) for i in ruta] rut...
64bfbad8a8eae9b85e1b2d245b89e568af2254a0
657,527
import functools def rgetattr(obj, attr, *args): """Get chained properties. Usage ----- >>> class Pet: def __init__(self): self.favorite_color = "orange" >>> class Person: def __init__(self): self.pet = Pet() >>> p = Person() >>> rge...
c41d2a490c1a47251f7d307787be9836995d63ff
657,530
def same_entries(a, b): """ checks if entries a and b represent the same publication """ for key in ['ID', 'doi', 'hal_id', 'title', 'chapter']: if key in a and key in b and a[key].lower() == b[key].lower(): return True if 'title' in a and 'chapter' in b and a['title'].lower() == b['chap...
88ea6155ad342703ef8a74b20938e8099c582f34
657,531
def create_technologies(connector, technology_list): """ Creates the ``technologies`` table in Temoa. Parameters ---------- connector : sqlite connector The connection to an sqlite database technology_list : list of ``Technology`` objects All of the technologies initialized in ...
ebf9148b7299a367064531659a5d2b55566a14aa
657,532
def get_security_args(security, d): """ Returns the parameters in d that are prepended with the string in security. """ ud = {} for key in d: if security + '_' in key: if key.startswith(security + '_'): ukey = key.replace(security + '_', '') ud[uke...
7b5aeb9cd54cce3851c3973ebbb6fb5d8b59e577
657,535
def vaporViscosity(T, vVP): """ vaporViscosity(T, vVP) vaporViscosity (micropoise) = A + B*T + C*T^2 Parameters T, temperature in Kelvin vVP, A=vVP[0], B=vVP[1], C=vVP[2] A, B, and C are regression coefficients Returns vapor viscosity in micropoise at T """ r...
2b5ef247e2f42e986d6a601ab7023fff82a17ab9
657,536
def bubble_sort(arr): """ My Python implementation of bubble sort Sorts a list of numbers and returns the sorted list Time complexity: O(n^2) Space complexity: O(1) """ # One iteration for each element for i in range(len(arr)): # One pass through list for for j in ran...
62694ae73379834137c332385e2a4ab98d6ec27a
657,538
import mimetypes def guess_mime_type(filepath): """Guess the MIME type for the given file path. If no reasonable guess can be determined, `application/octet-stream` is returned. Args: filepath: path to the file Returns: the MIME type string """ return mimetypes.guess_type(fil...
e797da8eb55e2a0843b4d2e58812c3c0481708ed
657,540
from pydantic import BaseModel # noqa: E0611 from typing import Any def diff_models(from_: BaseModel, to_: BaseModel) -> dict[str, Any]: """ Return a dict with differences of the second in relation to the first model. Useful for getting only the fields that have changed before an update, for example....
bb52c913c2249d9a13d897df17b67edd15085a64
657,541
from typing import Optional import torch def mask_from_lens(lens, max_len: Optional[int] = None): """Return an element-wise boolean mask of length less that `max_len`. Args: lens ([type]): [description] max_len (Optional[int]): max length. Defaults to None. Returns: tensor: "...
4e0f16a23a5fdc9a842f6c1ba5ac79581e6180d0
657,543
def check_args(argv): """ Validates `main()` input arguments :param argv: program arguments :return: True/False """ if len(argv) != 3: print("Github login and password are expected as script parameters") return False return True
7763f5b2f3ddb2e15da47eb7e3bb06f842758e2b
657,544
def time_to_str(sec): """Convert seconds to days, hours, minutes and seconds.""" days, remainder = divmod(sec, 60 * 60 * 24) hours, remainder = divmod(remainder, 60 * 60) minutes, seconds = divmod(remainder, 60) _str = "" if days > 0: _str += "{:d} days, ".format(int(days)) if hours ...
d678d8f8b14fd643438778414116515efff5305c
657,545
def filedate(filename): """Extract the date from the filename""" return filename[1:9]
fa3f8668668b4fc10f547dca7b12f420febb3ac8
657,549
def read_emb(src_path: str, trg_path: str, pass_header: bool=True, top_tokens: int=50_000): """ Read tokens of word2vec style embeddings to List[str]. :param src_path str: path to word2vec-style source language embeddings :param trg_path str: path to word2vec-style target language embeddings :param...
b03f0d71aec99b8b97a77c7605be74cca8b32380
657,550
def standardize(x): """ Standardizes a Series or DataFrame. """ return (x - x.mean()) / x.std()
8fd95bea1515461e3726bd1499c26660df519226
657,552
from datetime import datetime def sanitize(output): """Sanitize a dictionary or a list of dictionaries as follows: * remove 'tel:+'/'alias:' prefixes from 'to'/'from'/'address' keys' values * add 'obfuscated' key when 'from' key is present * convert 'timestamp' keys' values to datetime obje...
c4bc02afbddc771197eacf2ed27e350f34fa5a52
657,557
def hex2rgb(color): """Turns a "#RRGGBB" hexadecimal color representation into a (R, G, B) tuple. Arguments: color -- str Return: tuple """ code = color[1:] if not (len(color) == 7 and color[0] == "#" and code.isalnum()): raise ValueError('"%s" is not a valid color' % color...
75db92c4ddf2d9ac70a7ee1b0a99b57143d08182
657,562
from typing import Dict def build_trial_facets(trial_file_counts: Dict[str, int]): """ Convert a mapping from trial ids to file counts into a list of facet specifications. """ return [ {"label": trial_id, "count": count} for trial_id, count in trial_file_counts.items() ]
bb9bdb2086c4af9b338f78f7fd0aa4c4090345df
657,565
def XmlDataTable_to_XmlFile(xml_data_table,file_name="test.xml"): """Converts the XMLModel DataTable to a file on disk using the save method""" xml_data_table.save(file_name) return file_name
ac95bbc85d2a61a82dc5972bd78f70435eae3624
657,570
def set_default_attr(obj, name, value): """Set the `name` attribute of `obj` to `value` if the attribute does not already exist Parameters ---------- obj: Object Object whose `name` attribute will be returned (after setting it to `value`, if necessary) name: String Name of the attri...
651538a814dee5c3af69a99f1a97be0e49734d88
657,571
from typing import Tuple def get_next_branch_state(branch_symbol: str, state: int) -> Tuple[int, int]: """Enforces the grammar rules for SELFIES Branch symbols. Given the branch symbol and current derivation state, retrieves the initial branch derivation state (i.e. the derivation state that the new ...
642010289c78c0ca54cebebe86fb3101d3cccfa2
657,572
def A_approx_deph(Qload_deph, deltaT_diff_deph, Kt_approx): """ Calculates the approximate heatransfer area. Parameters ---------- Qload_deph : float The heat load of dephlegmator, [W] , [J/s] deltaT_diff_deph : float The coefficient difference of temperatures, [C] Kt_approx ...
0a811b019763d480865ed7221bdf82e159722b38
657,574
def update_dict_using_dict(dict1, dict2, operator): """ Updates the elements of dict1 with the elements of dict2 using the given operator. Returns a Args: dict1 (dict): Dictionary. dict2 (dict): Dictionary. operator (function): Can use the operator module to get basic operators...
4ed1305bf4f299ab16f50885301081188c080f12
657,575
import requests import json def get_push_shift_data(query, after, before, sub): """ Gets comments for a given keyword between two dates for a single subreddit up to a limit of 1000 Args: - query: keyword to search for - after: start search date as a unix timestamp ...
039df15eca41aa48364f44370803dcb72f363e2b
657,580
def _report_error(info): """ Interprets the return code of the odr routine. Parameters ---------- info : int The return code of the odr routine. Returns ------- problems : list(str) A list of messages about why the odr() routine stopped. """ stopreason = ('Blank', ...
2420429b8f4ef9d98a91712b5fa9e6ae44f0d91b
657,581
def cs_to_ms(cs): """Convert Centisecods to Milliseconds""" return cs * 10
58e44e3607763935744391e183023d0662c6ab12
657,584
import re def get_life_range(source): """ Return the birth and death year from _source (as a tuple). Return empty strings if not available. """ years = [] for event in ["from", "to"]: if source["lifespan"].get(event): date = source["lifespan"][event].get("date", "") ...
c85e9446ebcf8ed6f8019f84a61c07989ad1c8f0
657,589
def reverse_and_add(n): """Returns n + reversed(n).""" return n + int(str(n)[::-1])
67052b91a66d921dc13e6d481c83180d388a90ca
657,590
def one(s): """Get one element of a set""" return next(iter(s))
45ce1607e5d4b6bf2fc53cfc2da5602ccdc83910
657,591
def boxes_to_geojson(boxes, class_ids, crs_transformer, class_map, scores=None): """Convert boxes and associated data into a GeoJSON dict. Args: boxes: list of Box in pixel row/col format. class_ids: list of int (one for each box) crs_transformer: CRSTransformer use...
ddf258d8a25a227ff00b7d036149408e7a2afe59
657,593
def perturb(x, prn): """ Randomly perturb an integer point. Parameters ---------- x : tuple of int Point to be perturbed prn : prng.MRG32k3a object Returns ------- tuple of float The perturbed point """ q = len(x) return tuple(x[i] + 0.3*(prn.random() - ...
ea3156b3b6ca2993d7d6c9c713d9f5ae93b0d9cd
657,594
import re def generate_content_type(type, version=2): """ Generate the Content-Type header, including a version number Content-Types look like: application/vnd.ozp-iwc+json;version=1 """ try: version = re.findall(r'version=(\d+)', type)[0] # version number found already - just use...
7aa9669f9c567a4526de45da3b57bf952cb22011
657,596
def LogFiles(log_prefix): """Determines the filenames for the instmake log and the make output log by using an arbitrary prefix. Returns a tuple of the two filenames (instmake_log, make_log).""" imlog = log_prefix + ".imlog" mklog = log_prefix + ".make.out" return (imlog, mklog)
f96644abdf557a4300226200b130a42093a84add
657,601
def mapVal(inputPos, in_min, in_max, out_min, out_max): """ This function will linearly scale an incoming value belonging to a certain range (in_max - in_min) to a new value in the out range (out_max - out_min). """ scale = ((out_max - out_min) / (in_max - in_min)) return float(((in...
ce360266bd061ed82771e08b2480300b4c64ec8e
657,608
from pathlib import Path import re from typing import Dict def find_latest_xml_file(dir_name: Path) -> Path: """ Find the latest timestamped xml files, with un-timestamped files as a fallback if no timestamped file is found :raise FileNotFoundError: if either file can't be found """ name_pattern ...
ebfa9496ac46714092fe9b5dd35ea2b5a890197e
657,612
def translate(text, conversion_dict, before=lambda _: _): """ Translate words from a text using a conversion dictionary @brief text The text to be translated @brief conversion_dict The conversion dictionary @brief before A function to transform the input """ # if empty: if not text: return ...
d597246ed74205e5911d1a2d6a8485546e390c8d
657,613
def prune_by_tum_detect(iqms): """Prunes to only contain IQMs for imgs with identifiable tumour Parameters ---------- iqms : dict The dict of IQMs for one beamformer Returns ------- pruned_iqms : dict The dict of the IQMs for all images which had an identifiable tum...
ebddbc482190b420d9ae1fad8be4d3e35b07aaad
657,614
import logging from datetime import datetime def log_time(target, message, log_method=None, target_args=None, target_kwargs=None): """Execute target and log the start/elapsed time before and after execution""" logger = logging.info if log_method is not None: logger = log_method start_time = datetime.now() lo...
9a7387338fea9c26807ab71f40caebc0b378adbe
657,615
def lowercase_f(x): """ Returns all strings in a Pandas Series `x` in lowercase. """ return x.str.lower()
6573cc1d0b5d28ea916ff9a4632ed89fa0038456
657,617
from typing import Any def invert_results_dict( results: dict[str, dict[str, dict[str, dict[str, list]]]] ) -> list[dict[str, Any]]: """ Flatten the results nested dictionary into a CSV-writable format. Results has the following nested structure as input: dict[directory, dict[trial, dict[cut, dict...
99fdfad9a8d72ee155f2e50168d9e71220c7e85f
657,618
def _construct_grounding_map(rows): """Construct grounding map from rows in a grounding_map csv file Parameters ---------- rows : list List of rows from a grounding map csv file. File should contain seven columns, the first of which is an agent text. The remaining columns contai...
54b6dfdba6b2e9dd9ece2bb8c902efc4e0e33aad
657,621
from typing import Optional def get_next_id(current_id: int, size: int, total: int) -> Optional[int]: """Get next id. Assumes a simple list. Args: current_id: Current element index. size: Size of a page. total: Total elements. Returns: ``None``, if there is no next p...
bfaf133973f34383e335b85693170905035c3e04
657,624
def _parse_offset_limit(request): """Parse offset and limit values from a given Flask request and return a tuple containing both. """ offset = request.args.get("offset", default=0, type=int) limit = request.args.get("limit", default=None, type=int) if limit is not None: limit = offset + ...
61ac9d1ed69b82cade39754612d08749a4566d3b
657,625
def location(self) -> str: """Get the raw location inside the document :returns: The location inside the document """ return self.url.split("#")[1]
191a0041645ecd4179dd901d111b863daec908ab
657,633
def ucfirst(string): """ Convert the first character of a string to uppercase. """ return string[:1].upper() + string[1:]
95b495be087e4a779713626ea22628e558c6c6a7
657,634
import csv def read_lun_file(filename): """Read lun csv file and return the list.""" lunlist = [] with open(filename, 'r') as cvsfile: filereader = csv.reader(cvsfile, delimiter=',') for row in filereader: lunlist.append(row) del lunlist[0] return lunlist
4ad633dcb673c50fc43d9ee81edb88d34c4b2f89
657,639
def IC_NIS(ic_cc, ic_ca, ic_pp, ic_pa, p_nis_a, p_nis_c): """ Calculates the predicted binding affinity value based on the IC-NIS model. """ return -0.09459*ic_cc + -0.10007*ic_ca + 0.19577*ic_pp + -0.22671*ic_pa \ + 0.18681*p_nis_a + 0.13810*p_nis_c + -15.9433
8b4d549cd2eb9162c33a8f984c295a516cb88ad3
657,641
import re def omitCommas(row): """ Locates data parts with double quotes and removes commas within them. Parameters: row (str): The csv string to be searched for double quotes. Returns: (str): The same string without double quotes and extra commas. """ cases = re.findall('"[^"]+"', row) replaced = [re....
014d90a3d0fa373a58e767a1b8efdb845720737b
657,645
def d8n_get_all_images_topic_bag(bag): """ Returns the (name, type) of all topics that look like images. """ tat = bag.get_type_and_topic_info() consider_images = [ 'sensor_msgs/Image', 'sensor_msgs/CompressedImage', ] all_types = set() found = [] topics = tat.t...
1093cb8bb13946a170acf2333bcae1617db163d9
657,652
def get_window_content(center, whole_context, windows_size): """given whole context, center then return window's content in range windows_size by character Args: center(str): center word whole_context(str): whole context windows_size(int): window size Returns: list: window'...
bcc4dfda2fd7344a92d8315717df339e7784fc4f
657,654
import re def sanitize_filename(filename, allow_spaces=False): """Strips invalid characters from a filename. Considers `POSIX "fully portable filenames" <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_282>`__ valid. These include: A-Z a-z 0-9 ._- Filename...
a239c4488c97a6c1af1a4531a2cec1723353ce1f
657,661
def get_zip_filename(book_id): """ Get the filename for a zip document with the book identifier. """ return book_id + ".zip"
2919ca946c887a4c51a98af2d7abea1c74816161
657,662
def eta1_Vargaftik_and_Yargin(TK): """Dynamic viscosity of Li monomers Dynamic viscosity of the monomers as a function of temperature. Parameters ---------- TK K, temperature Returns ------- η, Pa s References ---------- Vargaftik, N B, and V S Yargin. Ch 7.4:...
f8c08b3f59d9b0ed97ade08f89928e58c0d546a8
657,663
def composeMap(fun1, fun2, l): """ Returns a new list r where each element in r is fun2(fun1(i)) for the corresponding element i in l :param fun1: function :param fun2: function :param l: list :return: list """ # Fill in new = [] for i in l: t = fun2(fun1(i)) ...
f063444936dcdf06059cd89a85bbcf69dc0ded4f
657,671
def indented(text, level, indent=2): """Take a multiline text and indent it as a block""" return "\n".join("%s%s" % (level * indent * " ", s) for s in text.splitlines())
8de1460106745de2c33fdba4baacb2d0141340ee
657,673
def _test_data(**overrides): """Returns a valid set of test data to use during API integration tests overrides allows the caller to replace one or more items in the returned dictionary without having to specify the entire thing every time. """ test_data = { 'sender': 'someemail@somedomain.c...
10a8d7eae8547b2d95d4f2baca31a14e1e65e21b
657,674
def list_to_dict(l): """Turn a l of tuples into a dictionary.""" return {k: v for v, k in l}
85ac67fabd89e8ff95ddd833dd85e25722ca276c
657,676
def make_range_partition(min_val, max_val): """ Returns a new partitioning function that partitions keys in the range *[min_val:max_val]* into equal sized partitions. The number of partitions is defined by the *partitions* parameter """ r = max_val - min_val f = "lambda k, n, p: int(round(f...
a86cae26fc79e73974fa05def8a4db531f31a829
657,679
def load_alist(path): """Read `alist`-file [MacKay]_ and return nested list describing the parity-check matrix of a code. Many code examples can be found in [UniKL]_. Input ----- path:str Path to file to be loaded. Output ------ alist: list A nested list containing...
08579269ae33eb00f6c41b511f201531eb34f9c7
657,681
def CreateLocalSsdMessage(resources, messages, device_name, interface, zone=None): """Create a message representing a local ssd.""" if zone: disk_type_ref = resources.Parse('local-ssd', collection='compute.diskTypes', ...
b7bec14dbdd68314c0b6f1e24663a5130067326c
657,685
def get_fixture_value(request, name): """Get the given fixture from the pytest request object. getfuncargvalue() is deprecated in pytest 3.0, so we need to use getfixturevalue() there. """ try: getfixturevalue = request.getfixturevalue except AttributeError: getfixturevalue = re...
d50ef248dd63d64c0927f80ae5a86928dd975105
657,687
def hex_to_rgb(color): """Convert the color from HEX coordinates to RGB coordinates.""" color = color.lstrip('#') size = 1 if len(color) == 3 else 2 factor = 2 if len(color) == 3 else 1 return tuple(int(color[i * size:i * size + size] * factor, 16) for i in range(3))
d17d1144d44fdbb37b26279c22b8bbcac4f3a984
657,689
def perc_unaligned(n_items, n_aligned, n_targs, **kwargs): """ Calculates the percent of items that are unaligned Args: n_items: ndarray (same dims as n_targs) n_aligned: ndarray (same dims as n_targs) n_targs: ndarray (same dims as n_items) Returns: perc: float ...
7d58aaa8911cc711396f7c282b7d39948875ec8d
657,693
import pickle def load_data(file): """Load (preprocessed) data from file.""" with open(file, 'rb') as dr: X = pickle.load(dr) gene_names = pickle.load(dr) return X, gene_names
8e1729e2cf9b76ce47ae4fcbbecda97f235cdb8e
657,700
from typing import Optional from typing import List import re import itertools def get_expanded_article_pages(page_ref: Optional[str]) -> List[int]: """['p. D-D', 'p. D', 'p. D, D ', 'p. D, D-D ', 'p.D-D', 'p.D', 'p. D-D, D ', 'page D', 'p., D-D', 'p. D-D, D-D ']""" if page_ref is None: return []...
8c412dd8785aec2e4d8e7d3b574c07e0eec374db
657,708
def norm_grid_description(grid_desc): """Normalize a grid description into a canonical form. Examples -------- >>> from landlab.grid.create import norm_grid_description >>> grid_desc = [ ... (3, 4), {"xy_spacing": 4.0, "xy_of_lower_left": (1.0, 2.0)} ... ] >>> normed_items = list(n...
bfc4c72dd09467d9a638aa0ab50b1c6f13a6b8a5
657,710
def remove_label(sentence): """ Input: A sentence picked out from the dataset with the label at the end. Output: A tuple (sentence, label) """ return (sentence.strip()[: -1].strip(), sentence.strip()[-1])
e0c67e417298d7b07f64485aab7f7401c1b0196e
657,714
import logging import random def load_apprentice_persona_list(personas_fpath: str, shuffle: bool): """ Reads a list of curated apprentice personas. """ logging.info('Loading personas.') with open(personas_fpath, 'r') as pf: personas = [p.strip() for p in pf if p.strip()] logging.info(f...
08a4eeaa897838eb46cd8ded1f8364392ca5f59e
657,716
def layout_one(title): """Formating layout for plotly visualization graph containing multiple variables of one company Args: title of graph Returns: layout configuration """ layout = dict(title = title, legend = dict( orientation = 'h', x = -0.01, ...
4eb7a73bfc808d27b385e9c65a63d0e22332056d
657,719
import ast def replace_fields(node, **kwds): """ Return a node with several of its fields replaced by the given values. """ new_kwds = dict(ast.iter_fields(node)) for key, value in kwds.items(): if value is not new_kwds[key]: break else: return node new_kwds.upd...
bc37c0a6b24ffc1d2a2bcbd055efe26234909466
657,720
def lookup(obj, *path): """Lookups repeatedly the items in the list `path` of the object `obj`. In case any `IndexError` or `KeyError` is thrown, `None` is returned. For example the call `safe_lookup(obj, "a", 0, "b")` returns `obj["a"][0]["b"]` when it exists and `None` otherwise.""" try: r...
464f1950517285af2f23031a57ab5ae96fdba11d
657,724
def stripnl(s): """remove newlines from a string (and remove extra whitespace)""" s = str(s).replace("\n", " ") return ' '.join(s.split())
7fd7a169c5a067178c7a5866383b2789d71aee79
657,727
def mod_12(any_int): """ Returns the value of the input modulo 12 Params: * any_int (int): any integer Returns: * the integer modulo 12 """ return any_int % 12
766b89e71083a624d457b875db1879e4103a58b5
657,728
def map_color(text, key='fontcolor'): """Map the text to a color. The text is mapped to a color. :param text: string of text to be mapped to a color. 'error' and 'fail' in the text will map to 'red'. :param key: in returned dictionary, the key to use that corresponds to ...
d60e27d128123fbef833b85021420c9e95409ec2
657,731
def compute_cumulants(moments): """ Compute the cumulants from the moments up to order 4 """ assert len(moments) >= 4, "You must have moments at least up to order 4." kappas = [0] * 4 kappas[0] = moments[0] kappas[1] = moments[1] - moments[0] ** 2 kappas[2] = moments[2] - 3 * moments[1]...
4d81f65b8016204a890437042c1dcbcae90f529f
657,732
def _bbox(pts): """Find the AABB bounding box for a set of points""" x, y = pts[0] ax, ay, bx, by = x, y, x, y for i in range(1, len(pts)): x, y = pts[i] ax = x if x < ax else ax ay = y if y < ay else ay bx = x if x > bx else bx by = y if y > by else by return...
95802ea790153020fcd6c20193536e1b19ca6102
657,737
import math def rnd(x): """ Round a number so that the output SVG doesn't have unneeded precision """ digits = 6 if x == 0 or not math.isfinite(x): return x digits -= math.ceil(math.log10(abs(x))) return round(x, digits)
bcb40d726a31716c73886fe9e8c5ecc00f1d32b5
657,739
import requests def store_document(url, document): """ Stores a document in the database :param url: the base url of the REST server :param document: document string :returns response.text: document_id is returned if successful """ url += "/documents" headers = {"Content-Type": "appli...
0e2dc9ad1ec2f0da2c3006ae1d3df1d830c893fe
657,740
def is_positive(example): """ Check if the example is positive. :param example: the example :type example: Atom :return: `True` if the example is positive; otherwise, `False` :rtype: bool """ return example.weight > 0.0
55a754a961459c28ac341e5e06cacb0c9ccff393
657,743
import random def odds(poweroftwo): """ Return True with odds 2**-poweroftwo , else False For example, odds(2) will be True roughly 1/4 of the time, odds(3) will be True about 1/8 of the time, and so on. """ # # To test this look at for example this count of the errors # >> (a,b)...
8dc283c88fe735eab01be228aa7fe2ac1f86cd2e
657,747
from typing import Union from typing import Any import ipaddress def check_ip(val: Union[str, Any]) -> Any: """ Function to check whether a value is valid ip address """ try: return bool(ipaddress.ip_address(val)) except ValueError: return False
9a1e125552a6aa3e6fcb767227682aa1397b1fbc
657,749
import math def entropy(probabilities): """ Calcola entropia della distribuzione di probabilità :param probabilities: lista contenente una distribuzione di probabilità :return: valore dell'entropia relativa alla distribuzione in input """ entropy = 0.0 for i in range(len(probabilities)): entropy += probabil...
81b7f4b4b95664804a2ed17086c12a43125ac6b6
657,752
def TENSOR_AXIS_IN_RANGE_APPLY_FILTER(arg_values): """Ensures the axis is less than the rank of the tensor.""" tensor, axis = arg_values return axis.value < len(tensor.shape)
8908b38192ec3d11e681c7304fd62a96220315d1
657,755
import re def has_ancillary_files(source_type: str) -> bool: """Check source type for indication of ancillary files.""" if not source_type: return False return re.search('A', source_type, re.IGNORECASE) is not None
ced6e6bf339cd7e01577ea69cd97dc658948ef85
657,756
def safefloat(value): """safely converts value to float or none""" try: return float(value) except ValueError: return None
59c3f08b0b2df2f1d66fbf6892d659cd93f86da3
657,757
def get_bit(number, position): """Returns the bit at the given position of the given number. The position is counted starting from the left in the binary representation (from the most significant to the least significant bit). """ if position < 0 or position > 31: return 0 return (number...
426fb4822eedd4b5b1fbc559b549bce7d1488c1f
657,760
def reverse(t): """Return a tuple with reversed order""" return tuple([t[i] for i in range(len(t)-1, 0, -1)])
bef4b8ecc48a2fc1e90a1cb99bdcb0706d3768c3
657,763
import glob def number_of_netcdf_files(source_dir): """ Counts the number of netcdf files in the given directory :param source_dir: :return: """ netcdf_pattern = source_dir + "/*.nc" netcdf_list=sorted(glob.glob(netcdf_pattern)) return len(netcdf_list)
2963c842eb9e55200c6bff894ef575f054ba8a67
657,764
def parse_access_variable(v): """ Parses the accessibility arguments from a variable anme. Should be structued as <variable_name>_<dir>_within<travel_time>_mode. For example: `sb_jobs_sector92_to_within20_OpAuto`: - variable: sb_jobs_sector92 - direction: travel towards the zone ...
83ac0d8bfda29a18f6785a5bea5dfa7a4fdb004e
657,765
import struct def _encode_int64(value: int) -> bytes: """Encodes an int64 in big-endian stripping leading zeros.""" return struct.pack(">Q", value).lstrip(b"\x00")
30a372c6f6e19272457415b4f0512ea8fce681d7
657,766
def intersect(a, b): """Find intersection of two lists, sequences, etc. Returns a list that includes repetitions if they occur in the inputs.""" return [e for e in a if e in b]
987d3bcecfcac90dc7eecb44ff32282164d807c6
657,773
def mask_deltar_first(backend, objs1, mask1, objs2, mask2, drcut): """Masks objects in the first collection that are closer than drcut to objects in the second collection according to dR=sqrt(dEta^2 + dPhi^2) Args: backend (library): either hepaccelerate.backend_cpu or hepaccelerate.backend_cud...
d110ae6510163fc210b971076a545d0682e96824
657,775
def running_paren_sums(program): """ Map the lines in the list *program* to a list whose entries contain a running sum of the per-line difference between the number of '(' and the number of ')'. """ count_open_parens = lambda line: line.count('(') - line.count(')') paren_counts = map(count_o...
16b9e502f0df98c47b55eb57d04f944468bc6ce7
657,776
def pretty_str_time(dt): """Get a pretty string for the given datetime object. Parameters ---------- dt : :obj:`datetime` A datetime object to format. Returns ------- :obj:`str` The `datetime` formatted as {year}_{month}_{day}_{hour}_{minute}. """ return "{0...
388e1b81b10d67193b2f7834f72a69a2c3716c7f
657,778