content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def sample_constraint(value): """ The value must be within the range of 1-255. """ return 1 <= value <= 0xFF
b71c87699742d609ccdff105be70dd72243e9d36
654,641
def line(a, t, l): """ Linear interpolation between a and b 0 <= t <= 1 """ return a + t * l
123d3108e44058a039cbd7c2954029e91c1a154a
654,642
def combinations(s, K): """ On entry: s sequence of items; K size of the combinations Returns: list of all possible K-combinations without replacement of s. """ N = len(s) assert K<=N, 'Error K must be less or igual than N' S = [[] for i in range(K+1) ] for n in range(1,N+1): ...
c0d048e7978283b2f86b09b3b1a7fe1790b7fa93
654,645
def get_node(data_path): """Return Blender node on a given Blender data path.""" if data_path is None: return None index = data_path.find("[\"") if (index == -1): return None node_name = data_path[(index + 2):] index = node_name.find("\"") if (index == -1): return ...
50856db9efc76482fef30882147a0b0437c1e59e
654,651
from typing import Tuple def _safe_path(path: str, extensions: Tuple[str, ...]) -> str: """Returns safe filename based on given extensions. Args: path (str): filepath extensions (tuple[str, ...]): a list of allowed extensions Raises: `ValueError` if path is invalid """ if...
782b295a717f2083d60cfdb367c48eece00f7bb6
654,653
def grid_to_str(grid): """ Convert grid - our internal representation into an 81-char sudoku string """ return ''.join(str(grid[ndx].pop()) for ndx in range(0, 81))
e1030bdbcf4d9ed805682e6c55eb4bccc3bbac98
654,654
def trim(peaks, troughs): """ Trims the peaks and troughs arrays such that they have the same length. Args: peaks (numpy array): list of peak indices or times troughs (numpy array): list of trough indices or times Returns: peaks (numpy array): list of peak indices or times ...
b07cf06a8175baf9fc5de82d6f432370242b7b6b
654,660
def is_balanced(node): """Check if a BST is balanced; returns (True/False, height of tree).""" # First we ensure the left subtree is balanced; then ensure the right subtree # is balanced too; and ensure the diff betw heights of left & right subtree <=1 if node is None: return True, 0 balanc...
f4db8d2d0ce7e773118a30ce19c19d41097f10b7
654,662
from io import StringIO import csv def export_csv(items, fields): """ Generate the data with csv.writer and stream the response. Use StringIO to write to an in-memory buffer rather than generating an intermediate file. """ data = StringIO() w = csv.writer(data) w.writerow(fields) # ...
b5cd56939930049cc031f1b5e5bb7864c8c4267d
654,667
def compliment_bools(v1, v2): """Returns true if v1 and v2 are both bools and not equal""" return isinstance(v1, bool) and isinstance(v2, bool) and v1 != v2
010630626e56400599e067206c7ad2a56b6758dc
654,670
import itertools import random def nbackseq(n, length, words): """Generate n-back balanced sequences :param n: int How many characters (including the current one) to look back to assure no duplicates :param length: int The total length of the sequence to produce :param words: ...
c55cfb2ef1ce9a14177c1b9bebdc2ed2f5a49150
654,677
def main(*, data, decimals): """entrypoint function for this component Usage example: >>> main( ... data = pd.Series( ... { ... "2019-08-01T15:20:12": -25.054, ... "2019-08-01T15:44:12": None, ... "2019-08-03T16:20:15": -0.2514, ... ...
c83f95003b9e09e1023f879a32564cc00bf9c5c3
654,679
import math def human_size(size): """Return human readable string for Bytes size """ if size <= 0: return "0M" measure = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] expo = int(math.log(size, 1024)) mant = float(size/math.pow(1024, expo)) return "{0:.1f}{1:s}".format(mant, measur...
d9d29ca3b6266e2c22f810d81cd344592edcb495
654,680
def sec_2_index(secs, fr=2048, offset=0): """ :param numpy.ndarray secs: time in seconds to be converted :param float fr: dampling frequency :param float offset: offset in seconds :return: time in samples :rtype: numpy.ndarray """ return (secs*fr - offset*fr).astype(int)
b3e55fcc06ead6260ffa2a0fe93e7cfb144f5407
654,681
def convert_arg_to_int(cmd_args): """Convert str to int as much as possible :param cmd_args: the sequence of args :return the sequence of args """ args = [] for arg in cmd_args: if isinstance(arg, str): # Int will cause TypeError try: arg = int(arg, 0) ...
2b63400165e3b073bc66b83686701f80494dd0e3
654,683
def listHasItems(listOfLists): """ Some of the batched calls return lists of lists. This means that a return value of [ [], [], [], ], say from @ref python.Manager.getRelatedEntities, is hard to easily detect using a boolean cast, as the outer list is not empty. This function checks that some item in the o...
b37d1abcfb31aa6e46e187bc2e2d364f1da1697b
654,684
import re def strip_escape(text: str) -> str: """Remove terminal ascii escape sequences from *text*. Args: text: text to strip escape sequences from Returns: text stripped of escape sequences """ # These are all valid escape sequences... they're probably not # inclusive ...
578a49a32fc3538dea66bf67e8cd364dc622c78d
654,686
import json from typing import OrderedDict def load_ordered(fp, **kwargs): """ Convenience wrapper for json.load() that loads the JSON while preserving the original element ordering/sequence. """ return json.load(fp, object_pairs_hook=OrderedDict, **kwargs)
1e705c0ebac645902f781449a07f96b5276d9b90
654,687
from typing import Union from pathlib import Path def _check_data_dirs( data_directory: Union[str, Path] = Path("../data/") ) -> Path: """ Validates data directory exists. If it doesn't exists, it creates it and creates 'raw/' and 'interim/' directories. """ # set directory's values _data_dire...
10258b7efc2a8621ee44c8930e337b568aeb824c
654,688
import textwrap def wrap(text, width=100): """ Intelligently wrap text. Wrap text without breaking words if possible. Parameters ---------- text : str Text to wrap. width : int, optional Number of characters to wrap to, default 100. """ split_text = text.spli...
b099b45651664d523ac6b612f736ff68e9be07af
654,691
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box): """ Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box """ score = 0 for feature_employe in featur...
650d387f6c46b98086f2cca30e462472ae0aea09
654,692
def convert_string(string, chars=None): """Remove certain characters from a string.""" if chars is None: chars = [',', '.', '-', '/', ':', ' '] for ch in chars: if ch in string: string = string.replace(ch, ' ') return string
131a5c472f96709da98e042a988e026edc41cd2e
654,698
def read_candidates(candidate_path): """Read parent candidates from file. Row number identifies the node and space separated numbers on each row identify the candidate parents. """ C = dict() with open(candidate_path, "r") as f: f = f.readlines() for v, row in enumerate(f): ...
33e51ad300327d033a53c06b4143340b96e7b77f
654,699
from typing import Dict def master_name(tf_vars: Dict) -> str: """Construct master name for provided Terraform deployment.""" return f"det-master-{tf_vars.get('cluster_id')}-{tf_vars.get('det_version_key')}"
4f375768b1b3678d1c3384cdf9bfcc0e3c681430
654,701
import json def load_json(path): """Load JSON file into Python object.""" with open(path, "r") as file_data: data = json.load(file_data) return data
f7420ef1d933c85450815ecaee4f7277b766ebe0
654,702
def tmap(*args, **kwargs): """Like map, but returns a tuple.""" return tuple(map(*args, **kwargs))
1e218555fe6ebe6e82a7536878808e0f29860ac5
654,712
import re def make_clean_input(pattern): """ Enforces that entities or words have parentheses around them and have trailing spaces >>> make_clean_input("@num{3}") '(@(num ) ){3}' >>> make_clean_input("num{3}") '(num ){3}' Entities can sometimes have underscores >>> make_clean_input("@...
ba22c9b07114d7f0cf8c75593553f4b2ca603fa5
654,720
def get_access_headers(app): """ Function to retrieve and format the Authorization Headers that can be passed to various microservices who are expecting that. :param oidc: OIDC object having authorization information :return: A formatted dictionary containing access token as Authorization header...
444dbbca079cc5ec1e1d0229c873970700c14fa2
654,724
def strip_unimportant(source: str) -> str: """ Strips unimportant information like footnotes, alternative names, or weird spaces. """ stripped = "" for char in source: # remove footnotes like RTX 3080[155] if char == "[" or char == "(": break # remove weird sp...
7b9fca2d5e923e9e071a7755d7b2b01b788d8e06
654,726
from typing import List def justify_stringlist(j: List[str], right=False) -> List[str]: """ CONSOLE FUNCTION: justify all str in a list to match the length of the longest str in that list. Determined by len() function, i.e. number of chars, not by true width when printed, so it doesn't work well with JP/CN chars. ...
05e59bdc6038985d90c12687902bf16f30d1b3b8
654,727
def pascal_triangle(rows: int) -> list: """ https://oeis.org/A007318 >>> pascal_triangle(4) [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] """ res = [[1]] for _ in range(rows): row = res[-1] res.append([1, *map(sum, zip(row, row[1:])), 1]) return res
c9430efd4649cd20fc4dcfbbc3c7468c0859c91f
654,733
def clamp(val: float, minimum: float = 0.0, maximum: float = 1.0) -> float: """ Fix value between min an max""" if val < minimum: return minimum if val > maximum: return maximum return val
b6406df3470acb47da9e03cdb4c2ba9d830e9e32
654,734
def find_value(sheet, row): """Finds the best available value. Parameters --------- sheet : workbook.sheet An Excel sheet. row : int The row where the value is located. Returns ------- string The cell value that wasn't 'N/E' (not eligible). """ # We f...
b4273720b4d4a6191f4f6f1979494f00ce24a3ba
654,735
def get_select_indexes(selects, attributes): """ Gets the indexes for all select statements. Args: selects: select values attributes: attributes in the tables Returns: indexes: look up indexes for select values """ if selects[0] != '*': indexes = [] split_se...
62925dd988384dd61f749fbdf51aea10bff31be1
654,736
from typing import Tuple def int_to_rgb(x: int) -> Tuple[int, int, int]: """Return a RGB tuple from integer.""" red = (x >> 16) & 0xFF green = (x >> 8) & 0xFF blue = x & 0xFF return red, green, blue
09f28d6e69a496ee624dbb8a10a39e068f8169f8
654,737
import base64 def is_base64(s): """Function to check whether a string is base64 encoded or not Parameters ---------- s String to check """ try: return base64.b64encode(base64.b64decode(s)) == s except Exception: return False
677aa804f7a76b74f1624796b7eff0ae173a0bf8
654,738
import re def re_match_strings(target, strings): """ Whether or not the string 'target' matches any one string of the strings which can be regular expression string """ return any(name == target or re.match(name, target) for name in strings)
d87cd118912aeeabe592b6943ac8ce68c0054c63
654,739
def uniquify(words): """Remove duplicates from a list. Args: words (list): The list of words Returns: list: An updated word list with duplicates removed. """ return {}.fromkeys(words).keys() if words is not None else words
97916fdbff95989d495de83468cdbaf617db523f
654,740
def transform_ip(block: str) -> str: """ Returns the transformed filters from a list of IPs. >>> transform_ip("localhost:65535,udp") '(host localhost and port 65535 and (udp))' >>> transform_ip("10.28.24.100:65535") '(host 10.28.24.100 and port 65535)' >>> transform_ip("*:80,tcp") '(por...
4b083f13eabb5615140f098403919171b5dbbb29
654,744
import struct def get_hyperheader(file): """ Unpack hypercomplex header parameters to a list. Reads the 28-bytes block header from file and unpacks into a list. Endianness is corrected as needed. Returned list contents: = ======== ================ N Variable Description = ...
6efd6b37695d0f3d7113f1c0a0250838e7f8612a
654,746
def jenkins_node_names(name, count): """Returns the names for `count` production jenkins node prefixed by `name`.""" return ["%s-%s" % (name, i) for i in range(1, count+1)]
44e6f6e32dbcae83632b57bd6aa06cb19cbfad59
654,751
from typing import Optional import requests def get_latest_flexget_version_number() -> Optional[str]: """ Return latest Flexget version from https://pypi.python.org/pypi/FlexGet/json """ try: data = requests.get('https://pypi.python.org/pypi/FlexGet/json').json() return data.get('info'...
7bad9ac1cac3a9a7edaf4d15e5bc8d4074a96243
654,752
def Lambda(zhub, IECedition): """ Calculate the IEC length scale. Lambda = 0.7*min(Zhat,zhub) Where: Zhat = 30,60 for IECedition = 2,3, respectively. """ if IECedition <= 2: return 0.7 * min(30, zhub) return 0.7 * min(60, zhub)
101c87f9a65b05efb831b42038419ba3251ac333
654,754
from typing import List def reverse(s: str) -> str: """ Reverse a string. - Time Complexity: O(len(s)) - Space Complexity: O(len(s)) :param s: a string :return: a reversed string """ length = len(s) rlist: List[str] = [''] * length for i in range(length): rlist[length...
248d2c70b819d05ce1101d08c6365831f8b1929f
654,759
def get_xi(a: float, i: int, delta_x: float) -> float: """ Calculating x_i = a + i * delta_x """ return a + (i * delta_x)
45c15f1c10ff5ffa5f88af10c676d57e5513e5fc
654,763
def legc(leg,col='color'): """Color legend text to match linecolor. :Inputs: 'leg' is a legend object. 'col' sets the field of the leg.get_lines() objects to use to find the color. You may need to refresh the figure to see the changes.""" # 2009-12-14 09:50 IJC: Created tex...
42d08aff3cb72e35a045ea44e8d3fd6172735caf
654,766
import re def regquote(s): """Quote regular expressions. :param s: string to be quoted. """ return re.sub(r'([][.^$*+])', r'\\\1', s)
de68814fd10dafd946e782added79afd4fdf966c
654,767
def _build_dict(words): """Builds a dictionary of words :param list[str] words: words :returns: dictionary of words :rtype: dict """ d = {} for i, word in enumerate(words): try: first, second, third = words[i], words[i + 1], words[i + 2] except IndexError: ...
3f4348b16f120828d293a5ab9e8cc35e71d0f5c3
654,768
import torch def validate_model(model, valid_loader, criterion, device): """Validate the accuracy of the model during training Arguments: model -- The model to validate valid_loader -- Valdation data loader criterion -- Loss function used by the model device -- If it is to tra...
46ff820c3d26c1afe32634650841e7923b7ec3a7
654,769
import inspect def arg_names(receiver): """ Get the expected keyword arguments for a function or class constructor. """ return list(inspect.signature(receiver).parameters.keys())
3267c2cb36ee54ff99f972a7a0e1e8ba90393bef
654,771
def to_language(locale): """Turns a locale name (en_US) into a language name (en-us).""" p = locale.find('_') if p >= 0: return locale[:p].lower() + '-' + locale[p + 1:].lower() else: return locale.lower()
260735d10cd06bf5d149cbed126f1bb99659c0be
654,772
def process_input(input_name): """ Returns the processed input as well as the max size of the ocean matrix """ with open(input_name) as input: max_size = 0 processed = [] for line in input: points = line.strip().split(' -> ') line_array = [] ...
1e4f53e375ca2368027c0f80c36ccd158639b02f
654,774
def get_spans_in_offsets(spans, start, end): """Return the list of spans (nlplingo.text.text_span.Span) that are within (start, end) offsets :type spans: list[nlplingo.text.text_span.Span] Returns: list[text.text_span.Span] """ ret = [] for span in spans: if start <= span.start_c...
ffc1d910595074ba3340ce3187ef0b1566bd2909
654,776
def run_one_phot_method(allInput): """ Do a photometry/spectroscopy method on one file For example, do aperture photometry on one file This is a slightly awkward workaround because multiprocessing doesn't work on object methods So it's a separate function that takes an object and runs the method ...
49e8e119eb7f46ddf3910cf06c6a83bf12be38b9
654,781
def generate_snake_order(teams, n_rounds): """Create a snake draft order Args: teams (iterable): e.g. ('Team1', 'Team2', 'Team3') n_rounds (int): number of rounds in draft Returns: list Examples: >>>generate_snake_order(teams=['A', 'B', 'C'], n_rounds=4) ['A', ...
4dc864fa3c6a9a39b35f1586c41cc50c3e502726
654,782
import math import random def prob_round(x): """ Rounds up with probability proportional to decimal places. """ floor = math.floor(x) if random.random() < x - floor: floor += 1 return floor
62bc7ed686b581cca6b883c08a5232093feeb788
654,784
def make_users_groups_url(base_url, duke_unique_id): """ Create url for fetching a users groups. :param base_url: base group manager url (eg. 'https://groups.oit.duke.edu/grouper-ws/servicesRest/json/v2_1_500/') :param duke_unique_id: str: unique id (number) of the user we want to build a url for :r...
500135d68a71df7d7f0dbedbe587dbc998663295
654,786
def get_stylesheets_for_decorator(decorator: dict, count: int) -> list: """ Gets stylesheets for a decorator. Args: decorator (dict): Decorator config object. count (int): Current page count. Returns: list: List of CSS documents that apply to current usage of decorator. """...
3caade502a3a93c2805ea822d3ba14bb33a3c196
654,787
def count_mismatches_before_variant(reference_prefix, cdna_prefix): """ Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus. Parameters ---------- reference_prefix : str cDNA sequence of a reference transcript before a variant locus cdna...
59754e259de5331f8b330bfa4b5651544ee0d3d4
654,788
def ensure_array(exemplar, item): """Coerces *item* to be an array (linear sequence); if *item* is already an array it is returned unchanged. Otherwise, an array of the same length as exemplar is created which contains *item* at every index. The fresh array is returned. """ try: item[...
5b32b1972713abcbd988eb06969e13408e486f62
654,792
import torch def normalise_quat_in_pose(pose): """Takes a pose and normalises the quaternion portion of it. Args: pose: shape N, 7 Returns: Pose with normalised quat. Shape N, 7 """ pos = pose[:, 0:3] quat = pose[:, 3:7] quat /= torch.norm(quat, dim=-1, p=2).reshape(-1, 1)...
c538c85edbe9b8d69df07885c3c199e0afe8f050
654,793
def get_slurm_directives(user: str, job_name: str = 'BlenderRender', gpu: int = 2, cpu: int = 4, ssd: int = 10, ram: int = 16, days: int = 0, hh:...
f8e95eb336bde17804d45dda6a366b00df450b59
654,794
def socket_read_n(sock, n): """ Read exactly n bytes from the socket. Raise RuntimeError if the connection closed before n bytes were read. """ buf = '' while n > 0: data = sock.recv(n) if data == '': raise RuntimeError('unexpected connection close') buf += da...
166fe86c8c5987177f982f3d49e597f8f750da1b
654,801
def activity_logging_world_check(member): """Returns if an isolated world check is required when generating activity logging code. The check is required when there is no per-world binding code and logging is required only for isolated world. """ extended_attributes = member.extended_attributes ...
fd1ad06df21f0b6c63fe2d15286c128bb1dad273
654,802
def avg_list(jac_list): """Average a list of jaccard results This is useful for computations like pairwise which need summarization """ if len(jac_list) == 0: return 0 return sum(jac_list)/float(len(jac_list))
8f2e07fe82f2a0b85634dde3a6534787359067fb
654,803
def get_jittering(seed_rng, scale_size, translate_size, rotation_size, img_width): """ This method returns uniform random values for scaling, translation, and rotation in the range given by user. Parameters: ------------- scale_size: float in [0,1] the maximum ratio by w...
d257377cfcf88a50011b2c477ef6968ba8598c9b
654,806
def IsEven( x ): """Tests if x is even""" return ( x % 2 ) == 0
e068cae86b19f364e398b05a11b8b5062a35db6a
654,807
def _sorted_images(images, start_name): """Retrieve a sorted list of images with most recent first. """ images = [(i.name, i) for i in images if i.name.startswith(start_name)] images.sort(reverse=True) return [(i.id, name) for (name, i) in images]
7f878983533a31c40ced51522d5d051b75fde96d
654,808
def polyXY2(x,y,coeff): """XY quadratic with cross-terms | - | x | x2| ---+---+---+---+ - | a | b | d | y | c | e | g | y2| f | h | i | """ a,b,c,d,e,f,g,h,i = coeff return a + x*(b + x*d) + y*(c + y*f) + x*y*(e + x*g + y*h + x*y*i)
7721b9588443a657cabaa2b64890a66ffff59d8f
654,812
import math def wrap_always(text, width): """A simple word-wrap function that wraps text on exactly width characters. It doesn't split the text in words.""" return '\n'.join([text[width * i:width * (i + 1)] \ for i in range(int(math.ceil(1. * len(text) / width)))])
f6e5b85007fffc78576c8d5bbe89077400ca96b0
654,814
from pathlib import Path import fcntl import errno def lock_script() -> bool: """ Locks a file pertaining to this script so that it cannot be run simultaneously. Since the lock is automatically released when this script ends, there is no need for an unlock function for this use case. Returns: ...
49e8205992e8c34eeffedffd38e657ac64b2d76d
654,815
def rows(matrix): """ Returns the no. of rows of a matrix """ if type(matrix) != list: return 1 return len(matrix)
4f39ce7793c1dcb92337d04c0c85ac21d0830f1f
654,817
def assignment_explicit_no_context(arg): """Expected assignment_explicit_no_context __doc__""" return "assignment_explicit_no_context - Expected result: %s" % arg
c11ef28d9942d73bea6ed14547aa11648d37f3a9
654,818
def server_supports_alter_user(cursor): """Check if the server supports ALTER USER statement or doesn't. Args: cursor (cursor): DB driver cursor object. Returns: True if supports, False otherwise. """ cursor.execute("SELECT VERSION()") version_str = cursor.fetchone()[0] version = v...
e5c05c3a1c119ef2969792ac7d420c049f127ee2
654,820
def get_insight(df): """ Get insight from a youtube_history dataframe transformed by transform() Parameters ---------- df : DataFrame A youtube_history dataframe transformed by transform() Returns ------- df_info : dictionary Contains informations about a specific youtu...
86e586fe1cdad77d0f3248585c4b2feb8716503f
654,821
def ensure_absent(spec): """ test if an 'Ensure' key is set to absent in dictionary 'spec' """ if 'Ensure' in spec and spec['Ensure'] == 'absent': return True return False
fe6beeb7925934536edde75a2f2514011f679b29
654,823
def expand_hex(x): """Expands shorthand hexadecimal code, ex: c30 -> cc3300""" if len(x) == 3: t = list(x) return "".join([t[0], t[0], t[1], t[1], t[2], t[2]]) else: return x
31f8a58a8d98f2e078a842a6ae1ebec7c95b20cf
654,827
def percentagify(numerator, denominator): """Given a numerator and a denominator, return them expressed as a percentage. Return 'N/A' in the case of division by 0. """ if denominator: return '{:04.2f}%'.format((numerator / denominator) * 100) else: return 'N/A'
d166c5ff9f70acf7938f6a82b8b0d498c466bd50
654,829
import torch def load_model( model_path: str = "saved_models/traced_pspnet_model.pt", ) -> torch.ScriptModule: """Loads and returns the torchscript model from path. Parameters ---------- model_path : str, optional The path to the torchscript model, by default "models/face_blur.pt" Re...
b88225b57b19650ce21334bc12bab0b596bd49fb
654,836
import typing def _versify ( py_version_info: typing.Tuple ) -> str: """ Semiprivate helper function to convert Python version to a point release (a string). py_version_info: Python version info as a named tuple from the operating system, e.g., from [`sys.version_info[:2]`](https://docs.python.org/3/...
d43e617cebeff0f60fbea2173ae9cddd01027dcc
654,838
def secondOrderTrans(high_phase, low_phase, Tstr='Tnuc'): """ Assemble a dictionary describing a second-order phase transition. """ rdict = {} rdict[Tstr] = 0.5*(high_phase.T[0] + low_phase.T[-1]) rdict['low_vev'] = rdict['high_vev'] = high_phase.X[0] rdict['low_phase'] = low_phase.key r...
cad8401f27d2313e38fed5ba3c1221d720ba4ead
654,841
def colorize(text, color): """ Display text with some ANSI color in the terminal. """ code = f"\033[{color}m" restore = "\033[0m" return "".join([code, text, restore])
8dcefe14ba17fbd71cb1460010f2dba49e152738
654,842
def strip(pre, s): """Strip prefix 'pre' if present. """ if s.startswith(pre): return s[len(pre):] else: return s
4fd3a227d2404ed1fdcdfcbea628aad1170cc278
654,844
def id_list_from_editor_output(bs, **kwargs): """bs is a string of console output the lines are: # delete me if you .... (must be deleted) id col1 col2 010101 c11 c22222 ... If first line begins with # then return an empty list Ignore the second line Return a list composed of...
cc45f93f065c00f1394827e3da340471c6c9f11e
654,846
import copy def pop_from_list(lst, items): """Pop all `items` from `lst` and return a shorter copy of `lst`. Parameters ---------- lst: list items : sequence Returns ------- lst2 : list Copy of `lst` with `items` removed. """ lst2 = copy.deepcopy(lst) for item...
a4cd56c42a688a23e861752a871654db622e47d0
654,847
import hashlib def hash_md5(filename, chunk_size=2 ** 16): """ Computes the *Message Digest 5 (MD5)* hash of given file. Parameters ---------- filename : unicode File to compute the *MD5* hash of. chunk_size : int, optional Chunk size to read from the file. Returns --...
37fb69585a8e2ef8c5428eba056f9162e681b2e0
654,852
from typing import Callable import click def variant_option(command: Callable[..., None]) -> Callable[..., None]: """ Option to choose the DC/OS variant for installation. """ function = click.option( '--variant', type=click.Choice(['oss', 'enterprise']), required=True, ...
b36783989911461d37e0597187e4d8999a3bc7be
654,856
def unit_length(ua): """ Computes the unit length in the given units """ return ua.solar_mass * ua.grav_constant / ua.light_speed**2
ef1b70bb65503398f99f35949bb38d460c9935f4
654,857
import base64 def csv_download_link(df, filename): """Returns a link to download the dataframe as the given filename.""" csv = df.to_csv(index=False) b64 = base64.b64encode(csv.encode()).decode() href = f'data:file/csv;base64,{b64}' return f'<a href="{href}" download="{filename}">`{filename}`</a>'
b8b21c396c310de083072d83d91e2e0e034fd8e7
654,858
def datetime_from_msdos_time(data, timezone): """ Convert from MSDOS timestamp to date/time string """ data_high = (data & 0xffff0000) >> 16 data_low = data & 0xffff year = 1980 + ((data_low & 0xfe00) >> 9) month = ((data_low & 0x1e0) >> 5) day = data_low & 0x1f hour = (data_high & ...
7326043515aa7c20ea5c87fdb8bdbafd5f98671a
654,859
def distLInf (a, b): """ Utility method to compute the L-infinity distance between the given two coordinates. """ return max (abs (a[0] - b[0]), abs (a[1] - b[1]))
912fb0284a4d5da022d53e576c71a8b0f947c5cb
654,860
def has_right_component_fragment(root, comp_index): """ Return True if component at comp_index has a component to its right with same comp_num INPUT: - ``root`` -- The forest to which component belongs - ``comp_index`` -- Index at which component is present in root OUTPUT: ``True`` ...
fde0857c06907d8a7b06685b9e5d5f721f5ca1b9
654,864
def negative_log_likelihood(y_true, predicted_distributions): """Calculates the negative log likelihood of the predicted distribution ``predicted_distribution`` and the true label value ``y_true`` # Arguments y_true: Numpy array of shape [num_samples, 1]. predicted_distribution: TensorFlow p...
cb212b478a087cf995be84549dea1ad0869838f5
654,867
def cull_candidates(candidates, text, sep=' '): """Cull candidates that do not start with ``text``. Returned candidates also have a space appended. Arguments: :candidates: Sequence of match candidates. :text: Text to match. :sep: Separator to append to match. >>> cull_candidat...
eec89e178e82dc798fe400825c92ab3ce806fbb5
654,881
import re def original_url_from_httrack_comment(html): """ Extracts the original url from HTTrack comment """ url = "unknown_url" for m in re.finditer( "<!-- Mirrored from ([^>]+) by HTTrack Website Copier", html): url = m.groups()[0] if not url.startswith('http://'): ...
9fd8fbd4fd7005aa42147099c6f7e331bd365144
654,882
def tag_ordinal(tag): """ Given a beautiful soup tag, look at the tags of the same name that come before it to get the tag ordinal. For example, if it is tag name fig and two fig tags are before it, then it is the third fig (3) """ return len(tag.find_all_previous(tag.name)) + 1
e9b9166979c83b0ceb577dc0edbb227d8f1f8a5b
654,889
from functools import reduce def deep_get(dictionary, keys): """ Get the data out of the dictionary at the given nested key path. :param dictionary: Dictionary to retrieve the data from at the given keys path :param keys: ['a', 'b', 'c'] :return: Value """ return reduce(lambda d, key: d.g...
baaeecc6edd5c286afc78d186aa39a8eb362fba8
654,892
import string import secrets def get_random_string(length=12, allowed_chars=string.ascii_letters + string.digits): """Return a securely generated random string. """ return ''.join(secrets.choice(allowed_chars) for _ in range(length))
a4132ee3dc515303a3c032defec544a95aff03ad
654,894
def iterationstopixel(i, iterations): """ Assigns a color based on iteration count. You can implement your own color function here. """ d = int(i / iterations * 255) return d, d, d
e16a99bc24067fa86060cf8ad84e59a9c1966d58
654,895
def cols(matrix): """ Returns the no. of columns of a matrix """ if type(matrix[0]) != list: return 1 return len(matrix[0])
b726cc38efbeec7309c7b640bcc1c9a09e64c444
654,896