content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import json def json_loader(text, metadata): """A loader function for json.""" if text: return json.loads(text) else: return {}
caee5dcb5fc006fa099819c1ac5cc24e11badc0f
570,777
def mean_flame_height_pd_7974( Q_dot_star: float, fuel_type: int, fire_diameter: float ): """Calculates mean flame height in accordance with Clause 8.3.2 in PD 7974-1:2019 :param Q_dot_star: dimensionless heat release rate. :param fuel_type: 0 Natural gas 10 cm to 50 cm diameter...
ecdc2dff1424492b8ca1159dcc2c78c78213cd60
570,784
import pickle def pickle_load(fname): """ Loads pickle by filename """ return pickle.load(open('./database/' + fname,'rb'))
6f245389128d969b445b09399e262accced4eadf
570,785
from datetime import datetime def parse_datetime(datetime_str): """Convert ISO date time from string to datetime""" if 'T' in datetime_str: if '.' in datetime_str: return datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.%f') else: return datetime.strptime(datetime_st...
2c9fe060c1e769666109e68c1b64d5d27d829017
570,789
def map_offsets(characters_bboxes: list) -> dict: """ Map the position of the character to its offset. E.g.: characters: x, y, z, w characters offsets: 2, 3, 20, 22 The first character (x) has the offset 2. The fourth character (w) has the offset 22. ... offsets_map: {0: 2, 1: 3, ...
8e82be572d022f2a28d1ea93e3305db088bb157b
570,790
def bool_to_str(value: bool) -> str: """Converts boolean to 'ON' or 'OFF' string.""" if type(value) is bool: return 'ON' if value is True else 'OFF' else: raise Exception(f"bool_to_str: unsupported variable type '{type(value)}', value '{value}'. Only boolean values are supported.")
0e08c039df03415352257e69afdb6e1c0d922c30
570,792
import socket import fcntl import struct def get_ip_address(ifname): """Get IP address of an interface with the given name. """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR ...
d878d3a9aadf90530087a881285017609633f613
570,795
def flatten_dict(dic: dict, prefix="", sep=".") -> dict: """ Flatten a nested dictionary into a flat dictionary with dotted namespace. """ out = {} for k, v in dic.items(): k = f"{prefix}{k}" if isinstance(v, dict): out.update(flatten_dict(v, f"{k}{sep}")) else: ...
0baad478c083f5138c2919fdea6fdd7d2a04743e
570,798
from pathlib import Path def setup_results_dir(experiment_name): """Create the directories for the results.""" root = Path(__file__).parent.parent result_path = root / "batchpredict" results_dir = ( result_path / experiment_name ) results_dir.mkdir(parents=True, exist_ok=True) ...
17e79aa996538f31b26f5d4d2aaa523c5b2037d0
570,803
from typing import List def pad_to_length(sentence: List, length: int, pad_ix: int) -> List: """ Forces np_arr to length by either truncation (if longer) or zero-padding (if shorter) :param pad_ix: :param np_arr: :param length: Length to pad to :return: a new numpy array with the data from np_...
8ed70c3f8cc41894caabc181d2ba6e14f25939c8
570,804
from datetime import datetime def get_solstice_type(date): """Returns a string representing the type of solstice based on what month the solstice occurs on. It is assumed the date being passed has been confirmed to be a solstice. Keyword arguments: date -- a YYYY-MM-DD string. """ month ...
407b61edb4d5b1e4ec74d03b39744d427c2cc46e
570,807
import math def _percent_to_integer(percent): """ Internal helper for converting a percentage value to an integer between 0 and 255 inclusive. """ num = float(percent.split('%')[0]) / 100.0 * 255 e = num - math.floor(num) return e < 0.5 and int(math.floor(num)) or int(math.ceil(num))
4b36741b42384f88390aea3c8a1792b251e52bcb
570,808
import re def de_bracket ( url: str, ) -> str: """ Extract the URL value from its RDF "bracketed" representation. url: input URL string returns: de-bracketed URL string """ s = re.search(r"\<(.*)\>", url) if s: url = s.group(1) return url
f6d15ce692d12b0a1d1e431a5103953d9920228d
570,811
def in_permissions(permissions, value): """ Given a permissions mask, check if the specified permission value is within those permissions. :param permissions: permissions set as integer mask :param value: permission value to look for :type permissions: int :type value: int :return: is val...
50a4a0db406c24799caf17e0f109a82a480ea100
570,812
def in_range(num: str, mi: int, ma: int) -> bool: """True if `num` between `mi` and `ma` inclusive & ignoring all non-digit chars.""" clean = "".join(char for char in num if char.isdigit()) return int(clean) in range(mi, ma + 1)
ceeb6d1e309254c10c807c8976a90a31a01943e0
570,814
def _ordered_append(dataframe, other): """ Append `other` to `dataframe` while keeping the order of the columns in both. The `append` method that comes with pandas Dataframes alphabetizes the order of the columns, which may not always be desired. This function provides an alternative. :par...
486ad8743c54d09b57d8953abbede408c784908c
570,816
def format_seq(seq, start, end, pad, retain_end=True): """Makes each sequence end when the first `end` or `pad` is encountered.""" formatted_seq = [] for id in seq: if id == start: continue if id == end: if retain_end: formatted_seq.append(id) ...
1fff868664c14c8fa3445e1547846a633f2c52bf
570,818
def CompactBlocks(blocks): """Compacts adjacent code blocks. In many cases 2 adjacent blocks can be merged into one. This allows to do some further processing on those blocks. Args: blocks: [(offset1, size), ...] Returns: A list with the same structure as the input with adjacent blocks merged. ...
2e1a7d88815bad43f2fa0404a8dec5bc0120efa7
570,822
def to_fqdn(name: str) -> str: """ Append trailing dot to FQDN-like DNS records lacking it. :param name: the DNS record name to attempt to convert to a FQDN. """ if "." in name and not name.endswith("."): return f"{name}." return name
80eb4068b312e97df245db54a3badf0a4186e697
570,823
import ast def make_lambda(call): """Wrap an AST Call node to lambda expression node. call: ast.Call node """ empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]) return ast.Lambda(args=empty_args, body=call)
451bc95e3930822dd28e1507890fe9a447761ba5
570,825
def format_diff(differ, diff): """ Formats the given differ and diff for mongo storage. :param differ: the differ object :param diff: the diff :return: a dict for storage """ return {u'id': differ.differ_id, u'd': diff}
fd4f06f4a7808c64f72b49cf950068024f255a50
570,830
import random def create_passphrase(x: int) -> str: """Create a passphrase that is x words long Args: x (int): Number of words to sample from the word list Returns: str: passphrase """ with open("/usr/share/dict/words", "r") as words: word_list = words.readlines() ...
f133eeb0f0ae788f413f9e3d9b0df4ee436cbb36
570,833
def getLatLons(xcoord,ycoord): """ Returns a list of lon/lats for an input meshgrid. Parameters: ----------- meshgrid {array}: meshgrid of lon/lat points. Returns: -------- lonlats {list}: A list of lon/lat coordinates. """ lonlats = [] for x in zip(xcoord.flatten(), y...
4161fa1c0e684b8f6a4e09f89b25b2bf22312b86
570,834
import string import random def random_string(length=6): """Generate a random string Parameters ---------- length : length of the random string (Default value = 6) Returns ------- type random string """ char_set = string.ascii_uppercase + string.digits random...
da70fcb3c4766de776d477f3558ec41e6dd7bddb
570,841
from typing import Union from typing import List from typing import Tuple def _tupleize_compound_value( v: Union[List, bool, str, int, float]) -> Union[List, Tuple]: """ list of lists -> list of tuples list of primitives -> tuple of primitives single primitive -> length-1 tuple of that primitive ...
6849d20313dc809eb05d682eaa8f79c8ee12b291
570,850
def prepend_chr(ser): """ prepend_chr(ser) Add "chr" to the beginning of every element in the Series. If the "chr" prefix has already exist, nothing will be appended but the type of Series elements will be changed into str. Parameters ---------- ser: pd.Series A Series of the ch...
9059bb5dfd2ac4708d46aa096daa2000f991ef76
570,851
def get_handler_name(handler): """ Name (including class if available) of handler function. Args: handler (function): Function to be named Returns: string: handler name as string """ if '__self__' in dir(handler) and 'name' in dir(handler.__self__): return handler.__self__....
f53ffb4f5dba58ffa1092bb2e3bfa86581fe9bac
570,852
def count_sublist_lengths(list_of_lists): """Get the lengths of sublists""" lengths = [] for mylist in list_of_lists: lengths.append(len(mylist)) return lengths
487f79ba39ce77028fad6f974ea43482f78637c0
570,855
def get_host(request): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if 'HTTP_X_FORWARDED_HOST' in request.META: host = request.META['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in request.META: host = reques...
9e9f72465fc1538ac9963c88a8ec0dca6211146f
570,856
def get_term_description(term, go_dag, ipr_map, pfam_map): """Takes an `InterPro`, `Gene Ontology` or `Pfam` annotation and returns it's description. Returns ------- str String description or None if one could not be found. """ term = term.upper() if 'IPR' in term: retur...
c307aecd7eab1f8bcf0cafbda509f18b7865b260
570,857
def scheme_true(val): """All values in Scheme are true except False.""" return val is not False
550342a39a3d1e06b9d8632f0517c2e30b5f9bb0
570,859
import six def _expand_variable_match(positional_vars, named_vars, match): """Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Ma...
19221d802dc8d857f95db3c0a191a478b721588d
570,863
def find_parents(graph, node): """ Get the governing nodes of a given node in the graph """ return graph.reverse()[node].keys()
22f63019f9725f3764b4c59392acc1cefaf433c9
570,867
import re def parse_losses_from_log_file(file_name: str): """ Read a log file produced by VISSL and extract the losses produced at each iteration """ iterations = [] losses = [] regex = re.compile(r"iter: (.*?); lr: (?:.*?); loss: (.*?);") with open(file_name, "r") as file: for...
1eedcc7f4439100609a85aceb8bf72a7615b6090
570,869
def position_to_variant_id( chromosome: str, position: int, ref_allele: str, alt_allele: str ) -> str: """EPACTS-format variant ID, with human-readable comma delimiters""" return f"{chromosome}:{position:,}_{ref_allele}/{alt_allele}"
a2fe4105ccebbec8c5fc983bd812edccfa9a84ac
570,872
import torch def batched_rnms(bboxes, scores, inds, nms_cfg, class_agnostic=False): """Performs non-maximum suppression in a batched fashion. Modified from https://github.com/pytorch/vision/blob /505cd6957711af790211896d32b40291bea1bc21/torchvision/ops/boxes.py#L39. In order to perform NMS independen...
161845a455eea0f7190d724bce3259c00c18a3db
570,874
import importlib import imp def reload_module(module): """Backport of importlib.reload of Python 3.3+.""" try: if not hasattr(importlib, 'reload'): # python <=3.3 raise ImportError except ImportError: return imp.reload(module) else: return importlib.reload(module)
4a3fefd7a1f322084e627f9aa8bc592c6fc481cb
570,876
def gen_ControllerLog(log_string, drone_id): """Generate a Controller log object from log string.""" controllerlog = { "@type": "ControllerLog", "LogString": log_string, "DroneID": drone_id, } return controllerlog
84aad0bb88b83a9b68a88acc04de6997f67d18dc
570,878
import secrets import string def get_nonce() -> str: """ Generate a 64 bytes random string. Returns: str: The 64 bytes random string. """ return "".join([secrets.choice(string.ascii_letters + string.digits) for _ in range(64)])
740dad41ff2cbecb3e32efa8270da0ddc8f39f70
570,879
from bs4 import BeautifulSoup from typing import cast def back_to_str(html: BeautifulSoup) -> str: """Retrieve content of the HTML body. Useful for converting back and forth between str and HTML (`BeautifulSoup`), so that in final concatenated HTML we don't end up with multiple <head>-s.""" return cas...
f5dbb75279296ab99cb5c135fa6e78b38534e288
570,881
def alg_to_index(sqr): """ Convert algebraic notation to a bit index """ index = ord(sqr[0]) - 97 index += (int(sqr[1]) - 1) * 8 return index
6c3ec035b6faaa2ffc67d309925d6b92d2505ee0
570,882
def normalize_data(raw_data): """ Converts raw accelerometer data to normalized values. """ data = [0, 0, 0] # Convert to numbers data[0] = (raw_data[0] << 4) + (raw_data[1] >> 4) data[1] = (raw_data[2] << 4) + (raw_data[3] >> 4) data[2] = (raw_data[4] << 4) + (raw_data[5] >> 4) # Fix 2's ...
7a3a1f79b741dced08ef8b846ab953df2a83acd3
570,884
def make_dict_with_words(file_name): """Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are.""" words2dict = dict() fin = open(file_name) for line in fin: key = line.strip() if key not in words2dict: ...
15b02ade7c5a7123849e63e1eee028fc1cbe2b97
570,886
def drop_zeroes_errors(X, Y, Z): """ Drops data points where y = 0 or z = 0""" x_dropped = [] y_dropped = [] z_dropped = [] for x, y, z in zip(X, Y, Z): if y != 0 or z != 0: x_dropped.append(x) y_dropped.append(y) z_dropped.append(z) return x_dropped, ...
afbe1e93f90020be358137e3bea93d3e92231364
570,889
def symlink_tree_commands(dest_dir, artifact_dict): """Symlink_tree_commands returns a list of commands to create the dest_dir, and populate it according to the given dict. Args: dest_dir: The destination directory, a string. artifact_dict: The mapping of exec-path => path in the dest_dir. Returns: ...
3beee1c4904a5ca770de7fb490b15ab6ddc0da98
570,895
import re def number_suffix(text): """Wraps date suffix in <span class="ord"> so they can be styled with CSS. >>> number_suffix("10th") u'10<span class="rod">th</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. """ suffix_finder = re.compile(r'(?P...
28e13bf97ec598c096aa3e92b672faa959c16477
570,900
def is_npy(s): """ Filter check for npy files :param str s: file path :returns: True if npy :rtype: bool """ if s.find(".npy") == -1: return False else: return True
28263f183974b64762a69e3e41d57e92265175b5
570,903
def flatten_list(lst_of_lsts): """ Flattens the list of lists lst_of_lsts. :param lst_of_lsts: a list of lists :return: flattened list """ if all([isinstance(e, (list, tuple)) for e in lst_of_lsts]): return [e for l1 in lst_of_lsts for e in l1] elif any([isinstance(e, (list, tuple)) ...
168064ddf69021643b69e0d9268046abe7ad0c0e
570,904
def _has_input_node(node): """ Returns whether the node has input node. Args: node (NodeGraphQt.BaseNode). Returns: bool. """ for p in node.input_ports(): if p.view.connected_pipes: return True return False
32d0c7b66b40b9a287a9803dd1b4b671069769cc
570,907
def _SI_prefix_to_factor(unit): """Convert an SI prefix to a numerical factor Parameters ---------- unit : str The unit whose first character is checked against the list of prefactors {"M": 1e6, "k": 1e3, "m": 1e-3} Returns ------- factor : float or `None` The appropr...
878a64d85897122b388fd38b661a0bde38416af2
570,910
import struct def parse_pstring(data, i): """Parses and returns a Pascal string.""" if i >= len(data): raise ValueError('pstring too short.') size, = struct.unpack('>B', data[i : i + 1]) i += 1 if i + size > len(data): raise ValueError('pstring data too short.') return data[i : i + size], i + size
5d10b4816746653e174540e01cabb474aa2ce7a5
570,913
import re def ComputeHeaderGuard(file_path): """Computes the header guard for a file path. Args: file_path: The path to convert into an header guard. Returns: The header guard string for the file_path. """ return re.sub(r'[.+/\\]', r'_', file_path.upper()) + '_'
23a45766efa967f20afd6fb9bfdd981a3e1139be
570,918
def rgb_to_hex(value1, value2, value3): """ Convert RGB value (as three numbers each ranges from 0 to 255) to hex format. >>> rgb_to_hex(235, 244, 66) '#EBF442' >>> rgb_to_hex(56, 28, 26) '#381C1A' >>> rgb_to_hex(255, 255, 255) '#FFFFFF' >>> rgb_to_hex(0, 0, 0) '#000000' >>>...
4c91543f93ee34b96979820e0a6f20bcbfae8de4
570,919
def _get_indent(marker, s, tab_width=8): """_get_indent(marker, s, tab_width=8) -> (<indentation-of-'marker'>, <indentation-width>)""" # Figure out how much the marker is indented. INDENT_CHARS = tuple(' \t') start = s.index(marker) i = start while i > 0: if s[i-1] not in INDENT_...
d15e592b1311939f6be8aeed5d862d1b7d958ccf
570,924
def byte_mask(n): """ Returns a mask that covers just the nth byte (zero-indexed), starting from the least-significant digits. """ return (1 << (8 * n)) * 0xff
76f6dbc2155b0530a2574adf8c180cdebabf03a1
570,925
def h(size): """Format 'size' (given in bytes) using KB, MB, GB, or TB as needed.""" if abs(size) < 1024: return f"{size:,.0f} bytes" elif abs(size) < 1024**2: return f"{size/1024:,.2f} KB" elif abs(size) < 1024**3: return f"{size/1024**2:,.3f} MB" elif abs(size) < 1024**4...
284111f5f4255de5ab3009cd9eb46b426a77a288
570,929
import hashlib def hash_all(data:list) -> bytes: """ - Do a hash on all of the given data Returns: hash_data(bytes): Note that this function returns bytes and not a hex string """ h = hashlib.blake2b(digest_size=32) for d in data: if isinstance(d, str): h.update(d.encode()) elif isinstance(d, list)...
58e9f42577c3cc7e8b3264539b1b991061e92e05
570,931
import copy def single_mutation_tuple_intSetRep(random, candidate, args): """Returns the mutant produced by a single mutation on the candidate (when the representation is a set of integers). The candidate size is maintained. Args: random : the random number generator object candidate : t...
696752fc7446a02b09b04d1c76c5c5c2f21f1d5e
570,933
import yaml def _dump_config_dict(dic): """Dump a config dict into a YAML string""" return yaml.dump(dic, default_flow_style=False)
9be147996f851ea8bcd9c9550cda6566d7fbcb25
570,938
def get_caselessly(dictionary, sought): """Find the sought key in the given dictionary regardless of case >>> things = {'Fred' : 9} >>> print(get_caselessly(things, 'fred')) 9 """ try: return dictionary[sought] except KeyError: caseless_keys = {k.lower(): k for k in dictiona...
cd486121373de8047f0a02f59f9691bcc6d9ac47
570,942
from typing import Union from pathlib import Path def path_to_pathlib(path: Union[Path, str]) -> Path: """If a string is passed to the function, it turns into Path from pathlib. Args: path: string of path or Path from pathlib. Returns: Path from pathlib. """ return Path(path) if isin...
1edd00821b2278189f7ac117d051a90f9b5f4468
570,946
def is_inferior_running(inferior): """Check if the inferior is a running process For the purposes of this check, running does not necessarily mean currently executing, but rather that there is a running process on the system for the inferior. If this function is being run in the first place then the in...
ea97fa4d63e4e75d7b6cf1dab8c4f9df59a2806b
570,950
def null_terminated(byte): """Filter to return true when the byte is 0x00.""" return byte == b"\x00"
5ceacd595eaed36e3de0cafc729a0235ea1a341a
570,951
def parse_info_dict(blob): """ Parse a blob of text as .PKGINFO or .BUILDINFO file. The results are returned as a dictionary with each key having a list of values. """ result = {} for line in blob.splitlines(): if len(line) == 0 or line[0] == '#': continue key, value = line.split('=', 1) key = key.s...
0c2e3824dbfa0f6c7c72b31e9a90baabde9164c0
570,952
import math def sphere_to_unit(v): """ Convert (theta, phi) to (x, y, z) """ sin_theta = math.sin(v[0]) cos_theta = math.cos(v[0]) return (sin_theta * math.cos(v[1]), sin_theta * math.sin(v[1]), cos_theta)
54d133e2e6a1cb5eefdca03a5cfb10273a51f8f9
570,953
def filter_list(obj): """ Filters a list by removing all the None value within the list. """ if isinstance(obj, (list, tuple)): return [item for item in obj if item is not None] return obj
2d1a84d92b2773292b4688c5d2018e17374b7aee
570,954
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in earlier dicts. Modified from http://stackoverflow.com/a/26853961/554546 :param list[dict] dict_args: An iterable of dictionaries. :return: A dictionary merge...
2acff5022059ccd958d8118194cdbd94257840bb
570,955
def get_attribute_value(element, attribute): """Returns value of element's 'attribute' Args: element (xml.Element): xml.Element object to check attribute (str): attribute name to get Returns: str: returns attribute value """ value = None if element.hasAttribute(attribu...
7af26c22797afe1e1eea09e1e9e50f520082fac5
570,959
def split_by_punctuation(text, puncs): """splits text by various punctionations e.g. hello, world => [hello, world] Args: text (str): text to split puncs (list): list of punctuations used to split text Returns: list: list with split text """ splits = text.split() sp...
f5905a0a992a9b7fcd32b1d7a17e4f39750c78b8
570,963
def att_to_s(att): """ Constructs a "wordification" word for the given attribute :param att: Orange attribute :rtype: str """ return str(att).title().replace(' ', '').replace('_', '')
4b7d014bf9fee83942d742645fe30ec256bbb5d8
570,964
import hashlib def _checksum(fname, hashalg): """Calculate hashes for a file. """ if not hashalg: return {} m = { h:hashlib.new(h) for h in hashalg } chunksize = 8192 with fname.open('rb') as f: while True: chunk = f.read(chunksize) if not chunk: ...
03ca356ccc4b3f84bd7e68ea4c060b22e876754f
570,965
def remove_sub_strings(predicted_txt, tokens=['ᐛ ', ' ✬', '<unk>']): """ remove the list of strings (tokens) from predicted_txt """ for token in tokens: predicted_txt = predicted_txt.replace(token, "") return predicted_txt
9bfef283cb3e9a1f8b94de2742bb28ef8065a9fb
570,967
def _invert_dependencies(deps): """Given a dictionary of edge -> dependencies representing a DAG, "invert" all the dependencies.""" ideps = {} for k, v in deps.items(): for d in v: l = ideps.get(d, None) if l: l.append(k) else: ...
0ff91054ce94b37b99513efcb7828b1d98d29727
570,971
import string def UsesConstantSyntax(value): """Check if |value| follows our style for JavaScript constants.""" allowed_characters = set(string.ascii_uppercase + string.digits + '_') # This uses set difference to find any characters in |value| that don't appear # in |allowed_characters|. Then it uses boolea...
6ef9ebbff1acbf2bf559c191b23e0d8cf6128598
570,978
def _get_color(color_tuple): """ Converts and returns the color in the following format: In canse of a rgb tuple: #%02x%02x%02x (i.e: #00FFCC) In case of a rgba tuple: rgba(color_tuple) """ if len(color_tuple) == 3: return '#%02x%02x%02x' % color_tuple return 'rgba%s'...
ffa43137538a5a5f4a6ee2bd3bdd9525d8a94767
570,981
def cached_property(fget): """Create a read-only attribute that caches its value.""" def cached_getter(self): try: return self._cache[fget.__name__] except KeyError: pass value = fget(self) self._cache[fget.__name__] = value return value return...
c6bdf7362ae036091fca1de9b11139a8bc2f7051
570,982
def gaussian_likelihood(f, x, y, ey): """Gaussian likelihood function usable in Curve.objective and Curve.fit. Expression: (f - y)**2 / ey**2 or 0 if ey == 0 where f is the value of the curve at x, y is the data, and ey is the uncertainty in the data (one Gaussian sigma). """ ...
963e9183288cea7817b32da5bfa979ec9a786ff0
570,984
def multi_to_single(gdf): """A MultiPoint geometry type to a Point geometry type converter. This function converts all MultiPoint geometries into Point geometries by way of creating centroids, then swapping the geometry column with the new centroid-geometry column. Parameters ----...
812f2b3f9102d89d4ea63d8b53476a07152e0951
570,985
def load_owm_api_key() -> str: """Loads the Open-Weather-Map API key. :return The api key as a string """ with open("OWM_API_KEY") as infile: return infile.read().strip()
9b41fa7feb472945b34a6fa471863a6c6dd00a2a
570,987
def process_line(line): """ Split a Line in key, value pairs """ key, value = line.partition("=")[::2] return key, value.rstrip()
aa98d036a37a20dab753d44a05b6d5c489ad1f2a
570,991
def is_producttype(product, ptype): """Returns True if product is ptype""" if ptype in product.get_subtypes(): return True else: return False
11f8e8e5dff1e24db89e3b8f495a2eff39fb6d18
570,993
import socket import fcntl import struct def get_address(ifname='ib0'): """ Get the address associated with a network interface. Parameters ---------- ifname : str, default ib0 The network interface name to find the address for. By default, 'ib0' is used. An OSError is raised for ...
8d641715d03823d4d3cb023fea72dce2472acf92
570,995
def to_num(text): """ Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. """ try: return int(text) except ValueError: try: return floa...
1862319c06de7c646a16fdf8fabdef679f81f5c7
570,996
def angle_difference(angle1: float, angle2: float) -> float: """The difference of two angle values. Args: angle1, angle2: The values are expected in degrees. Returns: Value in the range [-180.0, 180.0]""" return (abs(angle1 - angle2) + 180) % 360 - 180
455e2a189784e4788150721657e7ce0e647a889b
570,997
def _dasherize_underscored(self, string_value): """ Converts a string value with multiple words in underscore case to a dasherized notation, i.e., different words separated by dashes. :type string_value: String :param string_value: The string value to dasherize, in underscore and without consec...
cfda4ab25b26f4939041799d19d36dab9c06656f
570,999
def generate_gbaoab_solvent_solute_string(K_p=2, K_r=1, slow_group=[0], fast_group=[1]): """Following appendix of g-baoab paper. Let's say we want to evaluate force group 0 once per timestep and force group 1 twice per timestep. Using the default arguments above should give us V0 (V1 R^K_r O R^K_...
5ac654f7473c4ac24ee161fd0d72c21f09df1511
571,000
from pathlib import Path def get_local_path(value): """Get local path for the value.""" value = Path(value) # Return if exists and a file if value.exists() and value.is_file(): return value return ""
562276194a4bdccdf8a883e263c972b32bef5773
571,003
def getShortContigId(contigHeader): """ Gets the short contig name out of the contig Header. """ return contigHeader.strip('>').split(' ', 1)[0]
7caa0da87bd46c683d8061f3fc2862adf7f3e57c
571,004
def parse_columns(df, included_pattern=None, excluded_pattern=None, columns=None, dtypes=None): """ Get filtered set of columns from dataframe. :param DataFrame df: :param list(str) included_pattern: keep columns in this list. :param list(str) excluded_pattern: keep columns not int this list. :...
abddfb31db8d734834ed86b21821b354ba833cc1
571,005
import copy def _make_ml_graph(mm_g, corrections): """ Create a ML/MM graph, using an MM graph, and corrections to that. Parameters ---------- mm_g : nx.DiGraph() Graph object with MM results corrections : dict(int:(float,float)) Stored per-ligand corrections in the format lig...
8e9cac27e6989c119507b89ccb53a8c7d1134b80
571,009
def rgb_to_hsv(r, g, b): """ Convert a color from rgb space to hsv :param r: red composant of rgb color :param g: green composant of rgb color :param b: blue composant of rgb color :return: h, s, v composants """ maxc = max(r, g, b) minc = min(r, g, b) v = m...
045b6b9fb513b4fc3a633e27988032212937be1b
571,012
def GetFunctionParamPrototype(scope, param): """Gets the string needed to declare a parameter in a function prototype. Args: scope: the scope of the prototype. param: the Function.Param to declare Returns: a string that is the declaration of the parameter in the prototype. """ bm = param.type_de...
187a4d7e9cc9b255104d297931c65d02c3265f06
571,015
def resolution_matches(video, screen_size=None, **kwargs): """Whether the video matches the `resolution`. :param video: the video. :type video: :class:`~subliminal.video.Video` :param str screen_size: the video resolution :return: whether there's a match :rtype: bool """ return video.r...
119e6a75efe30676fd45367f65507bef6fbc7648
571,018
import io def build_wsgi_environ(scope, body): """ Builds a scope and request body into a WSGI environ object. This code snippet is taken from https://github.com/django/asgiref/blob /36c3e8dc70bf38fe2db87ac20b514f21aaf5ea9d/asgiref/wsgi.py#L52 WSGI specification can be found at https://www.p...
57c80dcdc63904ee2323378d20d3e9da7c45fa6e
571,020
def compute_device_name(ha_device): """Return the HA device name.""" return ha_device.name_by_user if ha_device.name_by_user else ha_device.name
55ad21c459ba36c7c247e6d84a3823cabcad84df
571,022
def OR(a, b): """ Returns a single character '0' or '1' representing the logical OR of bit a and bit b (which are each '0' or '1') >>> OR('0', '0') '0' >>> OR('0', '1') '1' >>> OR('1', '0') '1' >>> OR('1', '1') '1' """ if a == '0' and b == '0': retur...
af2944bd3e70a2c36683bbf66285e35b132c958f
571,027
def assumed_role_to_principle(assumed_role_arn): """Return role ARN from assumed role ARN.""" arn_split = assumed_role_arn.split(":") arn_split[2] = "iam" base_arn = ":".join(arn_split[:5]) + ":role/" return base_arn + assumed_role_arn.split("/")[1]
b756ddb7a28d5ab301ba0e5fc86d73f85732d442
571,028
def _is_likey_optimizer(op): """Return True if op is likely an optimizer. All operations are considered likely except those known to NOT be optimizers. These are '+' (the general batch op) and 'random'. Ideally the operation would indicate if it is an optimizer but Guild doesn't support an interfa...
4bdb3ee5dea709ccc9b232887b80539bcef97dc8
571,030
def minutes_readable(minutes): """ convert the duration in minutes to a more readable form Args: minutes (float | int): duration in minutes Returns: str: duration as a string """ if minutes <= 60: return '{:0.0f} min'.format(minutes) elif 60 < minutes < 60 * 24: ...
9115070cb17786cbb866d7849ad2b261ad6652e6
571,031
def selection_sort(arr): """ My Python implementation of selection sort Sorts a list of numbers and returns the sorted list Time complexity: O(n^2) Space complexity: O(1) """ for i in range(len(arr)): # Initialize current value as min min = i for j in range(i + 1,...
1db88c0b3637376e9405abfbd143b505c7e16c4b
571,035