content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def rgb2hex(r: int, g: int, b: int) -> str: """ Convert rgb values to a hex code. """ return '{:02x}{:02x}{:02x}'.format(r, g, b)
51b4de282cde906167ced2e52f5e532af661bcf6
625,123
def get_version_without_patch(version): """ Return the version of Kili API removing the patch version Parameters ---------- - version """ return '.'.join(version.split('.')[:-1])
62ee0544520d135d1357db20e965f6aaaaa05b08
625,125
def snaps_to_hydroobject(gdf, datamodel, method, tolerance=0.001, dtype=bool): """ Check if geometries snap to HydroObject Parameters ---------- gdf : ExtendedGeoDataframe ExtendedGeoDataFrame, typically a layer in a HyDAMO datamodel class datamodel : HyDAMO HyDAMO datamodel cla...
6f0a82ce5a043fb26e67438bcca8a9e2ab2e5f56
625,127
def pretty_kwargs(kwargs): """pretty prints the keyword arguments in a string """ return ", ".join([ f"{key}={repr(value)}" for key, value in kwargs.items() ])
6d35d6447376fcf5464a60db3f1688f5f5937979
625,129
def divceil(divident, divisor): """Integer division with rounding up""" quot, r = divmod(divident, divisor) return quot + int(bool(r))
ec51fa6fc9c88e1549f3cdd804c8c6274b523413
625,131
from typing import Dict def collect_dataset(input_file: str) -> Dict: """Read and parse lines from dataset files Args: input_file (str): path to input file Returns: Dict: return dict of dataset """ dataset = {} lcount = 0 with open(input_file, "r", encoding="latin-1") as ...
830ede2000ae2b55f33dd224755962f04d2ef9c6
625,134
def is_odd(number): """Return True if number is odd, else False.""" return number % 2 != 0
819a05e7a0c2445805b4bbdfde9bc0c019f351c5
625,144
def add_four(num): """Add four to num""" return num + 4
f8e630059a3c755d35b01c14f827c0fc9261e697
625,147
from typing import List from typing import Dict from typing import Any from typing import ChainMap def combine_dictionaries(dicts: List[Dict[str, Any]]) -> Dict[str, Any]: """Merge a list of dictionaries into a single dictionary. Where there are collisions the first value in the list will be set as this ...
8a92f1487d7df950d6c6ac2680c2843cb9061a66
625,148
import hashlib def compute_md5_hash(string): """Gets md5 digest from a string.""" md5_hash = hashlib.md5() # noqa: S303, W291 md5_hash.update(string.encode('utf-8')) return md5_hash.hexdigest()
5a7aa538078d937a80cd27c25e131454be6f494d
625,151
def accuracy(gold, cand): """Compute fraction of equivalent pairs in two sequences.""" return sum(a == b for a, b in zip(gold, cand)) / len(gold)
9f21ffa532926a2a52a4009845ef9d4d44a4f734
625,152
def getStatusWord(status): """Returns the status word from the status code. """ statusWord = 'owned' if status == 0: return 'wished' elif status == 1: return 'ordered' return statusWord
a9c6bcf971755e74f880b73a88d4d8f16fc5d9ae
625,154
def IDM_parameters(*args): """Suggested parameters for the IDM/MOBIL.""" # time headway parameter = 1 -> always unstable in congested regime. # time headway = 1.5 -> restabilizes at high density cf_parameters = [35, 1.3, 2, 1.1, 1.5] # note speed is supposed to be in m/s # note last 3 paramete...
d0762a3f613905fc76f85cb222a8e2e147701727
625,155
def tohex(s): """Convert a string to hexadecimal""" return ''.join([hex(ord(c))[2:].zfill(2) for c in s])
4918aa8fa25a0fc8f8688dd15e2ba52598848c70
625,156
def filename_from_url(url): """ Similar to Django slugify http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python :param url: url to convert :return: a valid filename """ filename = "".join(i for i in url if i not in "\/:*?<>|") return filename
094b5053f52cb7c6d60ec21d7625d722493f2014
625,157
def to_unicode(data_str: bytes, encoding: str) -> str: """Convert a str object to unicode using the encoding given Characters that cannot be converted will be converted to ``\\ufffd`` (the unicode replacement character). """ return data_str.decode(encoding, "replace")
a95f0ad53e1209b6cfa3bb94251512a334af5896
625,159
def add(*args: float) -> float: """Returns the sum of all input arguments.""" return sum(args)
040ff84cf899c127bc05ec3b6567fdbc8b1bd7ea
625,164
def _format_host_port_alias(host, port, alias): """Format a host, port, and alias so it can be used for comparison or display.""" if alias: return f"{alias}@{host}:{port}" return f"{host}:{port}"
adaaee9a063df78e35a9df521173478c170e75c5
625,167
def channelparse(channel, cachedjson): """Get json data for a specific channel.""" if channel in cachedjson: channeldata = cachedjson[channel] return channeldata, cachedjson return False
d487b3690459353f324132cc26bed2ef0ba77650
625,170
def read_file(file): """Reads Whatsapp text file into a list of strings""" x = open(file, 'r', encoding='utf-8') # Opens the text file into variable x but the variable cannot be explored yet y = x.read() # By now it becomes a huge chunk of string that we need to separate line by line content = y.split...
72c50a4df343e0b8d186808901a24fbed13826b1
625,175
def lowercase_subset(A, B): """Check that A is a subset of B when case is ignored.""" set_a = set([a.lower() for a in A]) set_b = set([b.lower() for b in B]) return set_a.issubset(set_b)
52c046bc915ed470bcdc7d2ff6aed26709fe7adb
625,176
import re def extract_keywords(text, keywords): """Extracts keywords from text. Args: text (str): Text from which the keywords will be extracted. keywords (list): Keywords to look for. Returns: list: All keywords found in text. """ # Construct an alternative regex patter...
4ff9d24012320950e72998a94e1a49fcee089fbb
625,178
def __similarity(s1, s2, ngrams_fn, n=3): """ The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching """ ngrams1, ngr...
9d78d77bab8543c2c57dbf203f6b3ad9f8f25c3a
625,183
import string def integerToLetter(i) -> str: """Returns letter sequence string for integer i.""" # William Chapman, Jorj McKie, 2021-01-06 ls = string.ascii_uppercase m = int((i - 1) / 26) # how many times over n = (i % 26) - 1 # remainder str_t = "" for _ in range(0, m + 1): st...
9c5b9c477ea2ebbbaba87d70511763b43760baf1
625,184
import numbers def is_number(x): """Test if `x` is a number.""" return isinstance(x, numbers.Number)
cb8d6507800dc4a56b939747642c099c8c1de5c0
625,185
def to_bool(bool_str): """Parse a boolean environment variable.""" return bool_str.lower() in ("yes", "true", "1")
ed9393d2d6ceba0313cfd9b61a99462b9a097d9c
625,186
def license(_): """Return the contents of the LICENSE.txt file.""" with open('LICENSE.txt') as flicense: return flicense.read()
50e9572537dee41a36b0859cee5596f136d14fbb
625,191
import re def split_camel(word): """ Separate any words joined in Camel case fashion using a single space. >>> split_camel('esseCarthaginienses') 'esse Carthaginienses' >>> split_camel('urbemCertimam') 'urbem Certimam' """ m = re.match('[a-z]+[A-Z][a-z]', word) if m: _, end...
f0ed7214c348e7beac3a1eba2ade12d66eadd18d
625,194
def add_python_snippet(txt: str, expandable: bool = True): """ Add a python snippet. :param txt: A string object. :param expandable: If true, puts code in <details></details> syntax. :return: Python string markdown syntax. """ md_str = f"\n```python\n{txt}\n```" if expandable: ...
749820d9da60d1b3e7897d329ebc6479587564aa
625,196
def field_verbose_name(value, field): """ Django template filter which returns the verbose name of an object's, model's or related manager's field. """ if hasattr(value, "model"): value = value.model return value._meta.get_field(field).verbose_name.title()
219682d0dd8cedc4c35bb49c8bbd65ac9c5a4f72
625,199
def base_url(skin, variables): """ Returns the base_url associated to the skin. """ return variables['skins'][skin]['base_url']
2d02cbee1f412bab17cb3a734c5c3d7b9576c203
625,201
import hashlib def _get_hash(data): """Compute the sha256 hash of *data*.""" hasher = hashlib.sha256() hasher.update(data) return hasher.hexdigest()
27227a093d0f227f452a23ee166e28047f851a86
625,205
from typing import Union import torch def get_scalar_vl(x: Union[torch.Tensor, float]) -> float: """ Helper function to always return either a float no matter the input. Args: x: The object to get the float from Returns: flt: The valuea s a float """ if isinstance(x, torch.Ten...
894d358134b56929865b766b23d470544ca89365
625,207
def is_related(field): """ Return True if the given field definition is a ForeignKey, OneToOneField, or ManyToManyField. >>> is_related(('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})) False >>> is_related(('django.db.models.fields.related.ForeignKey', [], {'r...
498675e501cefcb81862323f88a0e59cf5c4ccd0
625,208
import time def wait_for(condition, max_tries=60): """Wait for a condition to be true up to a maximum number of tries """ cond = False while not cond and max_tries > 1: try: cond = condition() except Exception: pass time.sleep(1) max_tries -= 1 ...
eb8f77c6cc26324222f6ccbc973046c14bb93a56
625,210
def get_size_to_render(plugin_config): """Get size to render an image.""" height = plugin_config.get("height", -1) width = plugin_config.get("width", -1) return height, width
63d58c022ad807ae2f4424bffcb72ed383207bac
625,214
def _get_element_from_list_with_delay(item_list, element, delay): """ A little util for faking delay of data stream. e.g. ``` l = [] get = generate_delay(l, 3) for i in range(10): print get(i) ``` prints 0 0 0 1 2 3 4 5 6 :param item_list list: list of items :param ...
8b5c3203e87b8ae956c8ba9673bc8c0fd6e038ac
625,216
def is_level_correct(level): """Checking that insert level is correct ("EASY", "MEDIUM", "HARD")""" levels = ["EASY", "MEDIUM", "HARD"] if level in levels: return True else: return False
575198164d28e31c07aef67ec6391a5fedb20dd7
625,220
def get_alert(paramalertLS, paramalertLQ, parampopLS, parampopLQ, hazbinLS=[1., 10., 100.], popbinLS=[100, 1000, 10000], hazbinLQ=[10., 100., 1000.], popbinLQ=[100, 1000, 10000]): """ Get alert levels Args: paramalertLS (float): Hazard statistic of preferred landslide mo...
55b09f3f5e7febd8f9fc08738135592c11c54797
625,221
import math import random def interim_move_helper(stats, c): """ Function to return a key for the interim move helper :param stats: List of stats :param c: Exploration parameter :return: Function for interim move helper to use as a key """ top = math.log(sum(stat[0] for stat in stats)) ...
03326eeea8ce0d155675caea8e5d78c2f9ab34c4
625,222
def make_terms_from_string(s): """turn string s into a list of unicode terms""" u = s return u.split()
1b4a3d2587f5edeefb4c91449a0700caf9d9aa91
625,224
def requires(*methodList): """ Optional decorator for shard functions to list any dependencies. If a shard uses methods it does not provide/import, it should declare them using this function or by setting the __requiresMethods attribute manually. If this attribute is not present, it wi...
fd7c1f6da0c3f3e0b29bd1dbc67d4c0265d43063
625,225
def _convert_tensor_base(tensor_data): """Convert tensor object to dict.""" tensor_data_dict = { 'dtype': tensor_data.dtype, 'shape': tensor_data.shape, 'data_size': tensor_data.data_size } return tensor_data_dict
54cfd44546b880f9f429636e30e6a12c1ad437b8
625,227
def get_qual_name(o, lower=False): """ Returns the qualified name of an object o. """ if not isinstance(o, type): o = o.__class__ if lower: return o.__qualname__.lower() else: return o.__qualname__
166672a8242a6d388d46e707155363d13f09b066
625,228
def _CreateAptPkgRepo(messages, repo_name): """Create an apt repo in guest policy. Args: messages: os config guest policy api messages. repo_name: repository name. Returns: An apt repo in guest policy. """ return messages.PackageRepository( apt=messages.AptRepository( uri='http:/...
9d1eea651d71b494cb165681a7eaf8f105245799
625,229
def _get_defines(header): """ Returns list of define statements Parameters ---------- header : str CppHeader Returns ------- defines : list List of define directive strings """ defines = [] for inc in header.defines: defines.append(f'#define {inc}') ...
a21d5268c73a5ee57ca9aebab89b77eaa95add5d
625,232
def get_hertz(reg, key): """Returns the hertz for the given key and register""" return int(reg * 2 ** (key / 12))
5a5945036f3538e313ab6932f800f7c050b8395d
625,235
def cpf_int_validation(cpf: int) -> bool: """ Validation CPF integer. Args: cpf (int): CPF. Returns: bool: If CPF real True else False. """ clean_cpf = str(cpf).zfill(11) digito = {} digito[0] = 0 digito[1] = 0 a = 10 total = 0 for c in range(0, 2): ...
415808dc469b58fef3676665a933b43427a449f8
625,236
import math def parent(level, idx): """ Return the parent of a given healpix pixel (in nested format) :param level: Resolution level :param idx: Index at the given level :return: Tuple (lvl, idp) including the level and the index of the parent pixel """ assert idx < 12 * 2 ** (2 * level) ...
d933089ab56baa8e692981ebda2741421f91a8a6
625,239
from typing import List import re def _split_strip_string(string: str) -> List[str]: """Split the string into separate words and strip punctuation.""" string = re.sub(r"[!()*+\,\-./:;<=>?[\]^_{|}~]", " ", string) string = re.sub(r"[\'\"\`]", "", string) return re.sub( r"([A-Z][a-z]+)", r" \1"...
08bb28277b00f4c178a87f96c9df8b31c4b7273b
625,240
def get_address_type(ip_type): """ Return the address type to reserve. """ if ip_type in ['GLOBAL', 'REGIONAL']: return 'EXTERNAL' return 'INTERNAL'
ef0674f82a82936b940ad2a0ddbda597ec0434c5
625,244
def ss_to_index(ss): """Secondary structure symbol to index. H=0 E=1 C=2 """ if ss == "H": return 0 if ss == "E": return 1 if ss == "C": return 2 assert 0
e239d7a257c0380ada1205fb6ef1d9fdc77aebef
625,245
import random import string def random_alphanumeric(length=5, upper_case=False): """Generate a random alphanumeric string of given length :param length: the size of the string :param upper_case: whether to return the upper case string """ if upper_case: return ''.join(random.choice( ...
d9072421639d629516911b72b451905d08063cc9
625,247
def multi1(vals): """ This will either return the common value from a list of identical values or the single character '?' """ uniq_vals = list(set(vals)) num_vals = len(uniq_vals) if num_vals == 0: return None if num_vals == 1: return uniq_vals[0] if num_vals > 1: ...
82738cabd851d9ae49546b08700b1b0f532175f7
625,251
def ternary(value, result_true, result_false): """ Implements a ternary if/else conditional. """ return result_true if value else result_false
dfe9fa86b4304520b8995f73e8718b4882b65734
625,255
def square(x): """ Squares given number """ return x ** 2
d08f1a4d006d9ff3cd1cc2c0aa75e1db3a1a197a
625,256
def flatten_dict(tree, parent_key='', sep=' '): """ Recursively flatten a nested dictionary into a single level whose keys are phrases. For example, given the following dict: ..code-block:: python { 'my': { 'git': { 'branch': 'master' ...
9929772d1eb382fdafe6e890bb34e76c361ee160
625,257
import re def detect_timestamp_format(timestamp): """ Given an input timestamp string, determine what format is it likely in. :param string timestamp: the timestamp string for which we need to determine format :return: best guess timestamp format """ time_formats = { 'epoch': re.compile(r'^[0-9]{10...
20eb2f8fc2f14525b64e3ee66d776f29a3907e88
625,260
import io def read_img_bin(img_fn): """Get image binary from an image file. Args: img_fn: image file path. Returns: image binary data as bytes. """ with io.open(img_fn, "rb") as f: img_bin_bytes = f.read() return img_bin_bytes
05b7b049a0778da8dc7b28b0b478022cb41be95a
625,262
def calculate_common_period(a_times, b_times): """ Calculate the common period between two time series. Parameters ---------- a_times, b_times: numpy arrays of numpy datetime64s Arrays of datetimes. Returns ------- start_time: the latest of the two series start times. finis...
96d511179e46364863c6b45c60e239ae6c959417
625,263
def operation_1(request): """ This will be in description """ return {"docstrings": True}
8d9de8583bf7ddb111e40ac95ace2e2c17aad002
625,266
def isWithinUnitedStates(latitude, longitude): """Returns true if the latitude longitude pair is roughly within the boundaries of the United States. Returns false otherwise""" return (25 < latitude and latitude < 50) and (-127 < longitude and longitude < -65)
ca1ea79dbf221895b16d3a6dd04e217eb1f88262
625,268
from typing import Union def _get_optional_type(type_): """Check if a type is an ``Union`` permitting ``None``. For ``Optional``-like unions permitting only ``None`` and another type, returns the other type. For other ``None``-permitting unions, returns ``True``. For everything else, returns ``False``. ...
d727bd47d0edeb5ef208d63b8270fbafa2955ac2
625,271
def timestamp2date(ts): """ Converts Timestamp object to str containing date """ date = ts.date().strftime("%Y-%m-%d") return date
972173fce1120db8e71b4ae5ff4347191b4c876f
625,273
import time def time_delta_now(t_start: float) -> str: """ Convert the difference of the given timestamp and now into a human readable timestring. Args: t_start (float): Start timestamp. Returns: Human readable timestring of time passed between `t_start` and now. """ a = t_sta...
86e54939cddb8d262649780644dec2678fcb85f1
625,275
import math def convert_kelvins_to_rgb_bartlett(color_temperature: float) -> tuple: """ Convert Kelvin temperature to black body emission RGB color using approximation by Neil Bartlett Author used the ideas of Tanner Helland and came up with a slightly better approximation Source: http://www.zombiepro...
8f71ae983c8db7fbc5be764c6d763d7ffa3d8a99
625,278
def reverse(s: str) -> str: """ For a string s return the reversed string s[::-1]. """ return s[::-1]
2e56beb19f839e3304b58ab31c3f2ddf831e48c9
625,282
def get_db_connection_tz(cursor): """ Return time zone of the Django database connection with which the specified cursor is associated. """ cursor.execute("SHOW timezone;") return cursor.fetchall()[0][0]
4a0adac1ee4c47073b67af743a41b77ba10f5df6
625,284
import math def probability_to_bayeselo(probability): """ Takes a probability: P['win'], P['loss'] Returns elo, draw_elo """ assert (0 < probability['win'] < 1 and 0 < probability['loss'] < 1) elo = 200 * math.log10( probability['win'] / probability['loss'] * (1 - probability['...
33bf719798ad5bec4d93ff463df0f20963b321d1
625,286
def hex_to_bin(hex_value) -> str: """ Convert all hex digits to binary representation, with leading zeroes """ bin_len = 4*len(hex_value) # 4 bits per hex return "{0:0{width}b}".format(int(hex_value, 16), width=bin_len)
259c67a5ce3b8437645ec2b28075843b7656ec1d
625,287
from typing import Dict from typing import Any from typing import List def handle_price_rows( card_data: Dict[str, Any], card_uuid: str ) -> List[Dict[str, Any]]: """ This method will take the card data and convert it, preparing for SQLite insertion :param card_data: Data to process :param car...
8f33bdcef0b6cc048199dd7c12f680b8886e164b
625,291
def zif_bank_code(zif_pinout: list): """ Return a list encoding even/odd ZIF pins in the data acquisition order. Empirically, this has been useful for finding differential offsets in array maps (although the ZIF even-/odd-ness tends to overlap with other pin breakouts). >>> print(zif_pintout(zif_by...
195e8a96c1a2aa985c3e87563ed298aded4a6517
625,296
import pathlib def gef_makedirs(path: str, mode: int = 0o755) -> pathlib.Path: """Recursive mkdir() creation. If successful, return the absolute path of the directory created.""" fpath = pathlib.Path(path) if not fpath.is_dir(): fpath.mkdir(mode=mode, exist_ok=True, parents=True) return fpath....
88915dfcbafc51e4066c6491b60f56c028ee1814
625,302
def convert_line_graph_path(path: list) -> list: """ Converts the given shortest path for the line graph into the min cost path in the original path. In principle, this means extracting the nodes in the right order from the given line graph path. The given line-graph path looks like: (n1, n2), (n3, n4) ...
d8c9ff0a5e41ae18d95af1919ffab3cf6c7e8869
625,303
def replace_first(base, old, new): """Replace the first substring with new string""" return base.replace(old, new, 1)
dc8746532ed6f0a3f85b16e77836824ffe9bc16a
625,304
def parse_nuclide(nuclide: str) -> str: """ Parses a nuclide string from e.g. '241Pu' or 'Pu241' format to 'Pu-241' format. Not this function works for both radioactive and stable nuclides. Parameters ---------- nuclide : str Nuclide string. Returns ------- str Nucl...
685d41a4007c09da33cc19919c0aa3b8191442fe
625,305
import torch def bbox_cxcywh_to_xyxy(bbox): """Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, x2, y2). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes. """ cx, cy, w, h = bbox.split((1, 1, 1, 1), dim=-1) bbox_new = [(cx - 0.5 * w), (c...
8af287f1bcf1d4b26ed8c6bbc2aab9b45d6b730d
625,310
def factorial(num): """ This function calculates factorial of a number recursively. n! = n*(n-1)*(n-2)*...*2*1 Parameters ---------- num : uint64 Input positive integer to calcuate factorial. Returns ------- uint64 Factorial of input positive integer. """ ...
e2e145c73ab1cbf647fbea97f84f8e93d701983d
625,312
def _encode_string(s: str) -> bytes: """ Encode a python string into a bencoded string. """ return f"{len(s)}:{s}".encode("utf-8")
7d9d3c7c12a1ca1d0d18f4d8649ebb0fea7a9c0b
625,313
def _get_downcast_field(class_reference): """Get the downcast field name if set, None otherwise.""" return getattr(class_reference, "__deserialize_downcast_field__", None)
6851aaf6889c0a9e2441f0a59b2d12e6e4a50ce0
625,316
def prefixes(s: str): """ Returns the prefixes of the string given in parameter """ return (s[:i] for i in range(len(s) + 1))
9408a961dd2784dbb9f5c404ec0c6a35a9a25304
625,319
def get_dim_inds(generalized_tensor): """ Returns a tuple 0..length, where length is the number of dimensions of the tensors""" return tuple(range(len(generalized_tensor.shape)))
0df852b109431c33511736c3527086eedf9c4c75
625,325
def request_method_predicate(self, obj, request): """match request method. Predicate for :meth:`morepath.App.view`. """ return request.method
1852ec8f8b0391b3191eeeddf8f240b16f4ff570
625,326
import requests def create_http_reader(url): """ Simple reader for an HTTP resource. """ def http_reader(): return requests.get(url).content return http_reader
384457e603222d7a2fd23d08c1a1c72a7dd718f0
625,328
import io def generate_generic_error_message(exception: Exception, lineno: int) -> str: """ Generate a generic error message in the following format: { exception.__class__.__name } in line { lineno }: { str(exception) } """ buffer = io.StringIO() buffer.write('\n') buffer.write(excep...
9a5b04dd20451d0a3b0868a75f8e8be46e367086
625,329
import textwrap def format_ordinary_line(source_line, line_offset): """Format a single C++ line with a diagnostic indicator""" return textwrap.dedent( f"""\ ```cpp {source_line} {line_offset * " " + "^"} ``` """ )
504f23b9ac2026ff59cd3d1ab184d9ad236fca96
625,340
def _flatten_list_of_lists(_2d_list): """Input a list of lists and output one single list""" flat_list = [] # Iterate through the outer list for element in _2d_list: if type(element) is list: # If the element is of type list, iterate through the sublist for item in ele...
40c5ba01d789cf80cc1bf59c1ec2875cce3eff6f
625,346
def has_core_metadata(response, file_type): """ Return True if a query response contains core metadata, False otherwise. """ try: # try to access the core_metadata response["data"][file_type][0]["core_metadata_collections"][0] except: return False return True
57d472d8f8311dcd981c8e39f9918fc271e0ab70
625,348
import platform def get_system_type() -> str: """Attempts to determine what type of system we're on, limited to systems this addon can usefully do things with""" system = platform.uname()[0].lower() if system in ["windows"]: return system return "unknown"
a10f417089eecbff138cdfa3c7eb216bdb95828d
625,355
import string def filter_unicode(data): """ Function to remove all non-printable characters from a string :param data: str: String to be analysed :return: String with all non-printable characters removed """ return "".join(c for c in str(data) if c in string.printable)
97acaabbe0d67cc4733d6f94d421517e06cb3e09
625,356
def quantile(xs, q=(0.25, 0.5, 0.75), sort=True): """Returns the qth quantile of an unsorted or sorted numeric vector. There are a number of different ways to calculate the sample quantile. The method implemented by igraph is the one recommended by NIST. First we calculate a rank n as q(N+1), where N i...
1a5fc9eff79118a4b4b31bb1b7d35174b640ffe2
625,359
import asyncio def create_checked_task(coro_or_future): """ Wrapper for `asyncio.ensure_future` that always propagates exceptions. """ def raise_any_exc(task): return task.result() task = asyncio.ensure_future(coro_or_future) task.add_done_callback(raise_any_exc) return task
f1c0df2858bacf679ff07de28463b677d33d40bd
625,361
def scalar_function(x, y): """ Returns the f(x,y) defined in the problem statement. """ if x <= y: return x * y return x / y
8a18b4a1f0e6c67a2b9331cf8a819ebc7fda9525
625,363
def _clean_accounting_column(x: str) -> float: """ Perform the logic for the `cleaning_style == "accounting"` attribute. This is a private function, not intended to be used outside of `currency_column_to_numeric``. It is intended to be used in a pandas `apply` method. :returns: An object with...
a14d717ca4d37b7e443f64d78c78cedfa885b8b9
625,365
def bytes_to_int(b: bytes): """ Convert a byte array to an integer. :param b: the byte array :return: the integer """ neg = False # Have we determined the value to be negative? We'll see. i=0 # This is the variable in which we'll store the value. # Now we need to do some tap dancing ...
db9b1e205def6e3652aa6de0aca0a00c54dad4a2
625,370
import pickle import hashlib def generate_hash(data_in): """ Generate a hash from the data_in that can be used to uniquely identify equivalent data_in. Args: data_in (any): The data from which a hash is to be generated. This can be of any type that can be pickled. ...
3d7b2fb97c3d82325a8f4819247b33365a3042cc
625,377
def eat_ghost(power_pellet_active: bool, touching_ghost: bool) -> bool: """ Args: power_pellet_active (bool): does the player have an active power pellet? touching_ghost (bool): is the player touching a ghost? Returns: bool """ return power_pellet_active and touching_ghost
0123309f491b5773b08460f4c0411bf3e238f571
625,379
def fastaRecordSizer(recordLines): """ Returns the number of charcters in every line excluding: the first (header) line whitespace at the start and end of lines """ size=0 for i in range(1,len(recordLines)): size+=len(recordLines[i].strip()) return size
328b2e6fca07098616ba305520c7c64d754d4225
625,387
def argmin(list_obj): """Returns the index of the min value in the list.""" min = None best_idx = None for idx, val in enumerate(list_obj): if min is None or val < min: min = val best_idx = idx return best_idx
6b01fff02d9be5dc0bda6ad170f0b964b10373d9
625,388
def remove_prefix(text, prefix): """ Remove the prefix from the text if it exists. >>> remove_prefix('underwhelming performance', 'underwhelming ') 'performance' >>> remove_prefix('something special', 'sample') 'something special' """ null, prefix, rest = text.rpartition(prefix) re...
90399fec8ede1cbd2b13e8ec93d1d5ef6624d069
625,389