content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def dominant_sign(elements): """ A function to calculate the dominant sign of a set of numbers :param elements: a list of numbers :return: the dominant sign """ return sum(elements) / abs(sum(elements))
732b23ab87a8ade41f8aac5b84e44a2a7ad2931e
659,343
def generate_managed_policy(resource_name: str, permissions): """Generate an IAM Managed Policy resource""" return { resource_name: { "Type": "AWS::IAM::ManagedPolicy", "Properties": { "PolicyDocument": {"Version": "2012-10-17", "Statement": permissions} ...
c0a8e6c4856753ac7aa3ada4c0c33d4059ec1767
659,347
def print_break(text): """Helper function to print clean sections to console.""" print("") print("#" * 64) print("# " + text) print("#" * 64) return None
6c2ab4a964ca6f08a3668a8c2031382603065bcc
659,349
import math def multiply(int1, int2): """ An implementation of the Karatsuba algorithm for integer multiplication. Returns product of int1 and int2. """ # Base case if (int1 < 10 and int1 > -10) or (int2 < 10 and int2 > -10): return int1 * int2 # Set up strInt1 = str(int1) ...
da4ca6d0e96420283542d335f37762c35f1c397a
659,352
import re def trim_alphanum(name, length=100): """Replace non alphanum charss with '-', remove leading, trailing and double '-' chars, trim length""" return re.sub( '^-|-$', '', re.sub('[-]+', '-', re.sub('[^-a-zA-Z0-9]', '-', name[0:length])) )
33804f7af1f4e6d764ac408924e4cfedb76515b5
659,353
def normalize(np_array, x_max=255, x_min=0): """ Normalize data to a scale of: [0,1] Default: normalizing pixel values [0,255]. """ return (np_array - x_min) / (x_max - x_min)
88140a4519b451d4b5dce381e1d8f75acef00a6a
659,355
def generate_normalized_name(name_tuple): """ Generates a normalized name (without whitespaces and lowercase) """ name_arr = list(name_tuple) name_arr.sort() name_str = ''.join(name_arr) return name_str.lower()
598ef66ad8fe71cf5a1fba8719be184aa7bd4d9a
659,356
def name_equality_check(setup_deps, pipfile_deps): """ Checks that all names present in either dependency file are present in both dependency files Args: setup_deps (dict<str, list<tuple<str, str>>>): Dictionary from setup.py dependency name keys to a list of tuples as a...
c46a99b09c58916af53f2abf535e001f6ef0e810
659,357
import pkg_resources def _registered_commands(group='mupub.registered_commands'): """ Get our registered commands. Iterates the entry points and returns the registered commands as a dictionary. :param str group: The group in setup.py to iterate. :return: A table containing command-name:command p...
b7bab437273fad534b08ab48833257a82ee7bb86
659,359
import requests def is_reachable(url: str, redirects: bool) -> bool: """ Test if a web site is reachable. This test has two different uses in the certmgr container: 1. Test if the NGINX server is up; and 2. Test if the device, e.g. the NUC, is connected to the internet. Args: url...
b73f903b68971bb398564e7fbdc344c5fcbd9a83
659,362
def output_formatter(value): """ Output formatter for environment variable values. Parameters ------------ value Value to format. Returns -------- :class:`str` Formatted value. """ if value is not None and not isinstance(value, bool): return str(value) ...
e0bd03f9580ee17d9464178a43b1406e763d1d73
659,363
import six import json def load_config(config): """Load configuration. """ if isinstance(config, six.string_types): with open(config, "r") as f: return json.load(f) elif isinstance(config, dict): return config else: raise NotImplementedError("Config must be a js...
34d51056170709aa236a43d713c77f511caeb479
659,364
from typing import List from typing import Dict from typing import Any def type_match(object_: List[Dict[str, Any]], obj_type: str) -> bool: """ Checks if the object type matches for every object in list. :param object_: List of objects :param obj_type: The required object type :return: True if al...
8e9e4eefc8e90b9e4932e983c5b1055d25baf8b7
659,373
def obs_filter_step(distance, view): """ Perfectly observe the agent if it is within the observing agent's view. If it is not within the view, then don't observe it at all. """ return 0 if distance > view else 1
3760fb8444ee5c83cf42266a64c7cf980a9d4451
659,374
def from_hex(string): """This function is the inverse of `to_hex`.""" return bytes.fromhex(string.replace(":", ""))
368873082a09bad38c98f357162afea64c0e8075
659,375
def flatten(seq): """Transforms tree lists like ['a', ['b', 'c'], 'd'] to strings like '(a, (b, c), d)', enclosing each tree level in parens.""" ret = [] for one in seq: if type(one) is list: ret.append(flatten(one)) else: ret.append(one) return "(" + ", ".join(re...
38275adcd1aea4872b6cf74293e1adf7ee5c4478
659,376
def dupTest(object): """Checks objects for duplicates enabled (any type) object: Blender Object. Returns: Boolean - True if object has any kind of duplicates enabled.""" if (object.is_duplicator): return True else: return False
bd57bab0cd87fbdd22e90bd1d0fafdb4dca3a653
659,379
def m_shape(A): """ Determines the shape of matrix A. """ rows = len(A) columns = len(A[0]) if A else 0 return rows, columns
85e9346d6432f2cb544e48ea8225b93791f16ad4
659,380
def get_loco_connlines(track, loco): """ Returns a dict of lines representing each locos base connections. """ # Build loco to base connection lines loco_connlines = [] for conn in [c for c in loco.conns.values() if c.connected()]: linepath = [] linepath.append({'lat': conn.conn_to.c...
68b762ae7e60076f29b829f4fb019ea814726929
659,381
import re def clean(text, newline=True, quote=True, bullet_point=True, link=True, strikethrough=True, spoiler=True, code=True, superscript=True, table=True, heading=True): """ Cleans text (string). Removes common Reddit special characters/symbols: * \n (newlines) * &gt; (>...
42e317731c43e3cafe270fa1a40734f09606d333
659,382
def _spec_arg(k, kwargs, v): """ Specify a default argument for constructors of classes created from .mat files. Used in autogenerated classes like ModelParameters. Parameters ---------- k : string Name of variable whose value will be assigned kwargs : dict Dictionary of ke...
36dd882105299ec297972ec35c651ea108f691d5
659,385
import jinja2 def load_template(filename, **kwargs): """Wrapper for loading a jinja2 template from file""" templateLoader = jinja2.FileSystemLoader( searchpath="./powerhub/templates/payloads/" ) templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = filename template =...
d30e104d618581f8b24ad54e1eafa9a0c85191a0
659,387
def sort_by_length(arr): """Sort list of strings by length of each string.""" return sorted(arr, key=len)
29b0b73456af386d4cf8a9380558b5780060abde
659,388
def remove_id(iterable, obj_id): """ Removes any entry from iterable with matching ID :param iterable: list - A collection of objects (ie. Dataset, Model) :param obj_id: int - The ID matching the objects contained in iterable :return: The iterable without an entry for the filter ID """ retu...
834f774fa249eb174fab4ac52238b2d84d14a902
659,392
def removeAlias(aname: str) -> str: """Return a query to remove a character's alias.""" return (f"DELETE FROM alias " f"WHERE aname='{aname}';" )
24cb87ee158792c3060f105bded02a826adaede0
659,396
import functools def pmg_serialize(method): """ Decorator for methods that add MSON serializations keys to the dictionary. See documentation of MSON for more details """ @functools.wraps(method) def wrapper(*args, **kwargs): self = args[0] d = method(*args, **kwargs) #...
7bb59ce3e2edf97c53f6bb25c1a1850c80ca130d
659,399
def init_field(height=20, width=20): """Creates a field by filling a nested list with zeros.""" field = [] for y in range(height): row = [] for x in range(width): row.append(0) field.append(row) return field
0b61b12bec1ad506da357715139bef37b407b576
659,400
def _x_zip_matcher(art): """ Is this artifact the x.zip file? """ return art['name'].endswith('.zip')
b018870a12ad3f5ad54aec28f346973c575f9241
659,404
def calc_death_rate(confirmed, deaths): """ Calculates the daily death rate in confirmed cases. :param confirmed: DataFrame of confirmed cases :param deaths: DataFrame of deaths :return: DataFrame of daily death rate """ death_rate = (deaths / confirmed) * 100 death_rate = death_rate.fil...
61f6e445d52b4495c3d07cf115692620c047fc75
659,405
def get_users_location(data: dict) -> list: """ Get users' names and location from dictionary with information about these users. Return a list of users. >>> get_users_location(get_json("@BarackObama")) [['Bill Clinton', 'New York, NY'], ['Kamala Harris', 'California']] >>> get_users_location(...
33d182386fdd01faa0bfe5d0d782d68d86fe3f03
659,408
import click import json def echo_event(data): """Echo a json dump of an object using click""" return click.echo(json.dumps(data, sort_keys=True, indent=2))
939003989c5bf02015ee75a67538be109115a079
659,410
def read_txt(file_path, comment_str="#"): """Txt file reader that ignores comments and empty lines """ out = [] with open(file_path, "r", encoding="utf-8") as f: for line in f: line = line.partition(comment_str)[0] line = line.strip() if len(line) > 0: ...
5a03ed90474c3cec7beb2065e5c380ae97e24439
659,411
def conform_speaker(speaker, main_character): """ Normalize speaker names using the predefined map. """ CHARACTERS_MAP = { 'a' : 'amicus', 'm' : main_character, 'unk': '?????', 'com': 'computer', 'c' : 'cassius', 'ca' : 'cato', 'al' : 'alexios'...
9a5e4ab5a8be3f77fc25a098494defc924331248
659,415
def add (x, y): """returns the sum of two vectors""" return x [0] + y [0], x [1] + y [1]
dd2d0dca541a01852ae60f5ea21e7be3becaff8b
659,416
def poentry__cmp__( self, other, compare_obsolete=True, compare_msgstr=True, compare_occurrences=True, ): """Custom comparation ``__cmp__`` function for :py:class:`polib.POEntry`. This function acts like a workaround for https://github.com/izimobil/polib/pulls/95 and add custom entries ...
454e46abdef3b545a84bffeba47da6467a08fb81
659,417
def _range_intersection(a, b): """ Returns the range where the two given ranges intersect. Parameters ---------- a, b: Each is a list of two coordinate values designating a min-max range. Returns ------- A range (a list of two numbers) where the two given ranges int...
7baf50aa162a6ef2e71a98e64d483d18fc45a0ac
659,420
def index_of_value(a,value): """ Get value of index that is closest to value in the array/list a. """ return min(range(len(a)),key=lambda i: abs(a[i] - value))
80f780d4cccf8f92b6d151249ad3cfddb743a033
659,422
def convert_ube4b_seqid(seqid): """ convert the ube4b sequence ids in the raw data to the standard mutation format """ ube4b_wt = "IEKFKLLAEKVEEIVAKNARAEIDYSDAPDEFRDPLMDTLMTDPVRLPSGTVMDRSIILRHLLNSPTDPFNRQMLTESMLEPVPELKEQIQAWMREKQSSDH" positions, replacements = seqid.split("-") positions = [int(p) for p ...
6634884b06ff441192d16c3be0b1e992bbd7996d
659,423
import torch def gather_states(all_states, indices): """Gathers states from relevant indices given all states. Args: all_states: States for all indices (N x T x d) indices: Indices to extract states from (N) Returns: gathered_states: States gathers at given indices (N x d) ""...
0d1f37c8736e41afb14fd95d4cdf8a3057dd9338
659,425
def AddNoGlob(options): """ If the option 'no_glob' is defined, add it to the cmd string. Returns: a string containing the knob """ string = '' if hasattr(options, 'no_glob') and options.no_glob: string = ' --no_glob' return string
e44c34a7d9652886080ae4167d80b631ffa8b9f9
659,426
def parse_mime_type(mime_type): """Carves up a mime_type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xht...
00fa105b4175abb9175dc3cdedab3cdf7ee0869a
659,428
import torch def check_models_have_same_weights(model_1: torch.nn.Module, model_2: torch.nn.Module): """ Checks whether two networks have the same weights @param model_1: Net to be checked @param model_2: Net to be checked @return: True iff the two networks have the same weights """ model...
f6541d5abebdc28892556dacfc77135f29727596
659,430
import pkg_resources def package_version(package): """Retrieve python package version.""" try: version = pkg_resources.get_distribution(package).version except pkg_resources.DistributionNotFound: version = "0.0.1.dev1" return version
81156ba343580bb1682eb436adbe1299ab970033
659,431
def solve_quad_mod (a, b, c, n): """ Solve a quadratic equation modulo n. Find all solutions to the quadratic equation a*x^2 + b*x + c = 0 mod n for integer n. Here a, b, c are integers. """ solutions = [] for x in range (n): poly_val = (a*x*x + b*x + c) % n if poly...
4675b8a83c0e11714c3ad0f2893a263de4332b82
659,433
def case_insensitive_header_lookup(headers, lookup_key): """Lookup the value of given key in the given headers. The key lookup is case insensitive. """ for key in headers: if key.lower() == lookup_key.lower(): return headers.get(key)
32441029ac7bbf0bb5db4afa3a31b7ab067113e1
659,435
def key_to_idx(key): """convert a binary LMDB key to an integer index""" return int(key)
b12e813ceeb5909fbe8c57de3bfbd0110bfd2696
659,439
def wrap_markdown(text): """ Wraps text in multiline markdown quotes. """ return '```' + text + '```'
9dc497d09d4411302d31634520f218cdb4abc532
659,440
def image_extents(product, geotransform, step=1): """Get the corner coordinates from the opened raster. Fetches a list of latitude and longitude values for the boundary of a given satellite product with a given pixel step along the border. :param product: the opened Gdal dataset :type product:...
bc5f74c168118336603a05767e6c28cf82b7dff9
659,441
def add_boundary_ummg(ummg: dict, boundary_points: list): """ Add boundary points list to UMMG in correct format Args: ummg: existing UMMG to augment boundary_points: list of lists, each major list entry is a pair of (lon, lat) coordinates Returns: dictionary representation of u...
6274e3e04a73bbc42f33e89b46688c7f70c1ca26
659,443
def reserved(word): """Parse for any reserved words. This is needed for words such as "class", which is used in html but reserved in Python. The convention is to use "word_" instead. """ if word == 'class_': return 'class' return word
0cc36290c0457e567584a2918aec8706e1f69ea5
659,446
def CheckExtractedInformationValid(rootGroup, verbose=False): """ **CheckExtractedInformationValid** - Checks for valid extracted information given a netCDF root node Parameters ---------- rootGroup: netCDF4.Group The root group node of a Loop Project File verbose: bool A fl...
8a06f5034c7017a165ab8971bf3ce7ec02120c9c
659,448
def merge_pept_dicts(list_of_pept_dicts:list)->dict: """ Merge a list of peptide dict into a single dict. Args: list_of_pept_dicts (list of dict): the key of the pept_dict is peptide sequence, and the value is protein id list indicating where the peptide is from. Returns: dict: the key i...
e9f9f5d1a6cbbe4acb2f59ebb55e79d67db78b0b
659,450
def downsample(state): """Downsamples an image on the first 2 dimensions Args: state: (np array) with 3 dimensions """ return state[::2, ::2, :]
2956632153d7d9b1f294fd4e1e0dd7bd7ee234bc
659,451
import string import itertools def _tokenize_by_character_class(s): """ Return a list of strings by splitting s (tokenizing) by character class. For example: _tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':', '54', ':', '52', ' ', 'M...
fb90698c8af15b596ac9850b41349d642b6d3b10
659,455
def _par_indices(names): """ Given a list of objects, returns a mapping of objects in that list to the index or indices at which that object was found in the list. """ unique = {} for idx, name in enumerate(names): # Case insensitive name = name.upper() if name in unique...
1694434c9de591af4f3c70ba63c2c19cc109d0e9
659,456
def offset_limit(func): """ Decorator that converts python slicing to offset and limit """ def func_wrapper(self, start, stop): offset = start limit = stop - start return func(self, offset, limit) return func_wrapper
85976c86ecf69a30b85832e0cb8d3024d8476f73
659,460
from typing import Dict def readGenomeSizeFromTxt(fname) -> Dict[str, int]: """ Read genome information. Args: ----- fname: a txt file contains genome information Returns: ----- A dictionary contains SQ as key and SL as value, otherwise None """ # first check if fname...
4287936f24f409809758f45492b06ab7ea22fdd4
659,462
def input_yesno(prompt, default=None): """ ask the user to enter Yes or No prompt: string to be shown as prompt default: True (=Yes), False (=No), or None (can not leave empty) """ while True: value = input(prompt).strip() if not value: if default is None: ...
7e38febe24d59a215d4c369f53d4ab524799891d
659,468
def get_edge_string(edge, is_incoming_edge, to_node=True): """ Create string representing the edge. :param edge: Edge object :param is_incoming_edge: Boolean, True if edge is incoming from the perspective of a node :param to_node: Boolean, output both from and to node labels if True :return: Str...
596db7dd324e3d0341e90b9131a33075c3a01638
659,469
import glob def get_files(root_dir): """ Get all files in the root directory. """ return list(glob.iglob(root_dir + '**/**', recursive=True))
cf6b88d32f8cc15c623037b5d6bf5c71b422c5cb
659,471
def get_parm_val(parm=None,key=None): """ Return the value of a key >>> get_parm_val(parm={'test':'val'},key='test') 'val' >>> get_parm_val(parm={'test':'val'},key='foo') >>> """ if parm and key in parm.keys(): return parm[key] else: return None
5841986976bac3b86b84f7532b8871839b5e8e6e
659,473
import getpass import socket from datetime import datetime def update_header(header, comments=[], remove_keywords=[], update_keywords={}, remove_old_comments=False, write_meta=True): """Update FITS header. Parameters ---------- header : astropy.io.fits.Header FITS header. ...
c8e8e12d4ed0de95cdeada32fb268c431831b9c1
659,474
def convert_to_list(data): """Convert input into a list for further processing.""" if data is not None: if isinstance(data, list): return data else: return [data]
133eede8cf012ebf58b270ae8ef10dd33926b8e6
659,476
import yaml def load_yaml_file(filename): """Loads dictionary from yaml file. Args: filename: file to read from Returns: Dict """ with open(filename) as f: contents = yaml.load(f, Loader=yaml.FullLoader) return contents
a6e70c21d4f0001f301c519409abdf12a42d71b5
659,477
import string def get_objects_list(n, np_random_state = None): """ Generates a list of (object, weight) tuples of size n :param n: list size :return: (object, weight) tuples list of size n """ alphabet_string = string.ascii_uppercase weights = list(range(1, n + 1)) if np_random_state: ...
fe178484e25c39b1dcec9e6388d32141de02f080
659,479
def tokenize(entity, field_name): """Convert an entity and a field_name into a unique string token.""" return "%s###%s" % (entity.name, field_name)
d7b1f449b761f5db13b250a81d38d1d51f06fc92
659,480
def GetAllFieldInDocument(document, field_name): """Find and return all fields with the provided name in the document.""" fields = [] for f in document.field_list(): if f.name() == field_name: fields.append(f) return fields
9764951551b40e3c4e858d2bb6ffb688dd02f7a1
659,483
def get_po_line_created_date(po_line_record): """Get created date from PO Line record or return a note that it was not found.""" if po_line_record.get("created_date") is not None: po_line_created_date = "".join( filter(str.isdigit, po_line_record["created_date"][2:]) ) else: ...
6ab97ff4382d719d9c6692419428da0764ae2e6b
659,486
import json def __read_json_report(directory): """ Reads json report. :param directory: The path to store the report. :return returns json report. """ with open(directory + '/report.json', 'r') as f: json_report = json.load(f) return json_report
03bea580e1c8a55c2fe7e1bf2722df0bf886a73b
659,487
def floyd_warshall(graph): """ Takes an adjacency matrix graph of edge distances and returns a matrix of shortest distances between all pairs of vertices. Distances of -1 indicate there is no path between a pair of vertices. See: http://www.cs.cornell.edu/~wdtseng/icpc/notes/graph_part3.pdf :r...
7a04809f47811ba93c5f310b9f2a1f3b44526c3e
659,489
def strip_from_end(s, c): """ Remove all 'c' from the end of 's' :param s: a string. :param c: character or substring to remove :return: remainder of 's' """ if c: while s.endswith(c): s = s[:-len(c)] return s
6b0eba07bc41e827d9791cf121855992f5ffe54c
659,492
def path_to_DNA_read_pairs(path: list, dist: int) -> str: """Convert a path of substrings to a condensed string :param path: the ordered path of substring pairs :type path: list (of tuples (of strs)) :param dist: the distance between the read-pairs :type dist: int :returns: the overall string ...
ce04452dd5a03686cd98d0c274db1e6aa559ab25
659,495
import inspect def run_unit_test(c, verbose=True): """ Runs all methods in a unit test class. Parameters ---------- c : Class Unit test class """ if verbose: print('BEGIN testing {}'.format(c.__name__)) methods = inspect.getmembers(c, predicate=inspect.isfunction) ...
9f7c87b76e5bbc8645d46518613d60ffe633f10f
659,504
import logging def infolog(caplog): """Sets the log capture level to ``logging.INFO``.""" caplog.set_level(logging.INFO) return caplog
fcddbcd53ce7caf4577bf43c3f83420d4b2a6d01
659,505
import binascii def hex2b64(hex_string): """Convert a hex string into a base64 encoded string.""" return binascii.b2a_base64(binascii.a2b_hex(hex_string)).strip()
9af02ed09923682726a9087f0a141a4a459bf484
659,511
import pyarrow.parquet as pq def parquet_decoder(stream): """ Read parquet formatted files """ table = pq.read_table(stream) return table
c45522e686101d93cd798d2334b5a58c43b96080
659,512
import itertools def hyperparameter_combinations(hyperparameters): """ Generate all possible combinations of hyperparameters. Inputs: hyperparameters: dict containing pairs of hyperparameter names and set of values to try. Example: {"learning_rate": [0.1, 0.2], "epoch...
15fc39acf3caafa27c5da4eb541a43d984aaac05
659,514
import ntpath def cleanUpPath(path): """ This function: 1) Removes extra beginning/trailing quotes, spaces and newlines. 2) Normalizes the paths. 3) Appends './' to all paths. All paths are assumed to be relative to the Makefile. Returns a clean up path. """ # Remove extra quotes and ...
5ef6adf496aa4d3de1360ccbceaf49d7d9c7647e
659,517
def rotate_pitches(chord, n=1): """ Given a chord (tuple) of pitch classes, such as (1, 2, 3, 4), returns the next rotation of pitches, such as (2, 3, 4, 1), depending on what n is. Params: * chord (tuple): an ordered pitch class set * n (int): number of places to shift. A positive...
e9f29d891d79e47ca351a9ef4b934e2422b04ca7
659,518
def blanknone(v): """ Return a value, or empty string if it's None. """ return '' if v is None else v
76c472257e4c19da55136353de950ab00b1531e0
659,519
import math def calculate_rmse(y, yhat): """ Calculates Root Mean Square Error :param y: Actual values as series :param yhat: Predicted values as series :return: RMSE value """ error_sqr = (y - yhat)**2 error_sqr_rooted = list(map(lambda x: math.sqrt(x), error_sqr)) rmse = sum(erro...
ae939377e3430eeb8fdca6fa6fa4ce1136328ac6
659,522
import re def remove_tags(s): """Removes xml-style tags.""" return re.sub('</*.*?>', '', s)
6f9824aca918c13e3f78ae1b2b0e5226524a6900
659,524
import json def make_json_writer(func, *args, **kwargs): """ Return a function that receives a file-like object and writes the return value of func(*args, **kwargs) as JSON to it. """ def writer(f): json.dump(func(*args, **kwargs), f, indent=1, ensure_ascii=False) return writer
f320312f292081804ac196ae778b3171baa2d9fb
659,537
def dequote(string: str) -> str: """ Return string by removing surrounding double or single quotes. """ if (string[0] == string[-1]) and string.startswith(('\'', '"')): return string[1:-1] return string
f4becde62a4c095daee1ece013485562445638b5
659,538
def _ConvertOldMastersFormatToNew(masters_to_blacklisted_steps): """Converts the old masters format to the new rules dict. Args: masters_to_blacklisted_steps: A dict in the format: { 'master1': ['step1', 'step2', ...], 'master2': ['step3', 'step4', ...] } Returns: A dict in the l...
94d4259c20be9b7231b3d1e06524fc7896737841
659,539
import re def remove_tags(tweet): """ Takes a string and removes retweet and @user. """ tweet = re.sub('(^rt:? @[a-z]+[a-z0-9-_]+)|(\W+rt:? @[a-z]+[a-z0-9-_]+)', ' ', tweet) # remove retweeted at tweet = re.sub('(@[a-z0-9]+[a-z0-9-_]+)', ' ', tweet) # remove users return t...
d2adcc0b90b3eaddda765997d8a1f1037d897392
659,544
def merge(arr1: list, arr2: list) -> list: """Merge two arrays for merge sort Args: arr1 (list): the first array arr2 (list): the second array Returns: list: the merged array """ merged = [] # Compare elements for both arrays while arr1 and arr2: if (arr1[0...
792011afc178c72cd1496b4889567c9c995ff097
659,548
import string import random def generate_keyword(chars=None, k_length=None): """ Generate keyword for annotators and batches. Args: chars (str): type of characters used to generate keyword, *default:* ``string.ascii_letters+string.digits`` k_length (int): length of the keyword, *default:* ``random.randin...
cd0e22e747a3045e25e65ea265ab722323d05567
659,555
def format_size(size): """ Format into byes, KB, MB & GB """ power = 2**10 i = 0 power_labels = {0: 'bytes', 1: 'KB', 2: 'MB', 3: 'GB'} while size > power: size /= power i += 1 return f"{round(size, 2)} {power_labels[i]}"
a7a9294e86ecc7c4b8e08db7588c82e03ce7d664
659,556
def get_user_decision(soup, code_block): """Gets user input on a comment it's not able to classify. Separate multiple languages in a single post with a '/'. """ print("Need input.", soup.prettify(), sep="\n") while True: language = input("Language (<Enter> for None): ") or "None" ...
c3c765e54ae6c325540338e8dbd3ce17cb3cc3ba
659,559
from typing import Dict import json def read_dict(file_path: str) -> Dict: """ Read dictionary from path""" with open(file_path) as f: return json.load(f)
6b3201f6e6573dafd4f65d3ae9e63ac244027f37
659,562
def patch_save_intermediate_df(mocker): """Patch the save_intermediate_df function.""" return mocker.patch("src.make_feedback_tool_data.make_data_for_feedback_tool.save_intermediate_df")
6c668407857c3ddbd1b3a29aa5e0e24dfae19d72
659,565
def pretty(sbox): """ Return a pretty printed SBox. """ # List of Columns p = '\nS-BOX ' for i in range(16): p += '%02x' % i + ' ' p += '\n' for i in range(70): p += '-' p += '\n' # Row for i in range(16): p += '%02x' % i + ' | ' # Entries ...
78228c3fa64e26c60f3d99df6d9ba9a035b263b2
659,568
import mimetypes def getMimeType(pathToFile): """returns mime type Args: pathToFile (String): absolute path Returns: String: mime type """ mime = mimetypes.guess_type(pathToFile, strict=True) return mime[0]
388d7512322f72166d5a936b6a6ad9086ec60379
659,574
def minimal_generalizations_cons(h,d): """returns all minimal generalizations of h that are consistent with positive example d""" generalizations=set() mg=[f for f in h] for i,f in enumerate(h): if f!=d[i]: if f!="0": mg[i]="?" else: mg...
4357581b305265118e7e38010e537cf9e132baf6
659,578
def human_file_size(num): """Readable file size""" for unit in ["", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"]: if abs(num) < 1024.0: return "%3.1f %s" % (num, unit) num /= 1024.0 return "%.1f%s" % (num, "YB")
7faf231d5daca8d1c66ad6cb894b61013f37ac78
659,582
import itertools def partition(iterable, k): """ Partition finite iterable into k almost-equal partitions in round-robin manner. :type iterable: iterable :param iterable: A finite iterable. :type k: int :param k: Number of partitions. :rtype: list :returns: List of lists of partition...
5f298cb56cbe58b125d06fcd9f42227d91e59af5
659,584
def set_name_from_dict(string, dictionary, key, leading, trailing): """Replaces the string with the value from a specified dictionary key, prepending and appending the leading/trailing text as applicable""" return "{}{}{}".format(leading, dictionary[key], ...
4641822ccca293b59a39f666fd715329d884c529
659,585
def hourly_indicators(df, capacity): """ Compute the indicators based on the df profile >>> df = pd.Series([0.2, 0, 0, 1] , index=pd.date_range('2000', ... freq='h', periods=4)) >>> hourly_indicators(df, 1) (1.2, 2, 1.2) """ # there is no difference by using integration ...
a211fb9c1e3e0b1a0df33ea5f46102f26459e64b
659,587
def toStringArray(name, a, width = 0): """ Returns an array (any sequence of floats, really) as a string. """ string = name + ": " cnt = 0 for i in a: string += "%4.2f " % i if width > 0 and (cnt + 1) % width == 0: string += '\n' cnt += 1 return string
870b6cb1c9ee306a7e1360f43c8a681d95a15dbc
659,591