content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Tuple from typing import Dict def load_vocabulary(vocabulary_path: str) -> Tuple[Dict[str, int], Dict[int, str]]: """ Loads vocabulary from vocabulary_path. """ vocab_id_to_token = {} vocab_token_to_id = {} with open(vocabulary_path, "r") as file: for index, token in...
dccd51bee2427f98f29919533fa687e6820d9cff
67,077
def load (filename): """Loads the two dimensional Conway Cubes puzzle input and returns a mapping of all active coordinates, i.e. `active[coord] = True`. """ active = { } with open(filename) as stream: for y, line in enumerate( stream.readlines() ): line = line.strip() ...
e183d7d741a98d3ff6c0d7613f63180ac7f5af56
67,078
def convert_row_to_sql_tuple(row): """ Take an amended source CSV row: ['1', '01001', '2008-01-01', '268', '260', '4', '1', '0', '3', '2891'] and turn it into an SQL load tuple: "(1,'01001','2008-01-01',268,260,4,1,0,3,2891)" """ return "({},'{}','{}',{},{},{},{},{},{},{})".format(*row)
124bc6a60704659fa7e0474b679ab1dce54c1137
67,083
def get_triangle_number(n: int) -> int: """Get Triangle number `T_n=n(n+1)/2` for a given number `n`.""" return (n * (n + 1)) // 2
825ccf96ae767392134b32eb847b8b2367e28322
67,087
def sub_kernel(kernel, dim1, dim2): """ Constructs a sub-kernel of a kernel. Args: kernel (tensor) : kernel matrix dim1 (tuple) : start, end dim2 (tuple) : start, end """ sub_kernel = kernel[dim1[0]:dim1[1],dim2[0]:dim2[1]] return sub_kernel
519f2ad90577ff0e6a04b0e3ebc1a26c1a214af5
67,090
def percentile(seq,q): """ Return the q-percentile of a list """ seq_sorted = list(seq) seq_sorted.sort() return seq_sorted[int((len(seq_sorted)-1)*q)]
d2608e4e4bfe5ef4692d23eaae6d1a74ef4f935c
67,091
from typing import Counter from functools import reduce def create_maps(words, tags, min_word_freq=5, min_char_freq=1): """ Creates word, char, tag maps. :param words: word sequences :param tags: tag sequences :param min_word_freq: words that occur fewer times than this threshold are binned as <u...
f873ebc6447eb2024f3abac4aec0a0feccd08470
67,097
def get_client_region(client): """Gets the region from a :class:`boto3.client.Client` object. Args: client (:class:`boto3.client.Client`): The client to get the region from. Returns: string: AWS region string. """ return client._client_config.region_name
6727f8e21fee77a2d869c1c4f3aa077a22145f1d
67,098
import math def rotatePoint(x, y, z, ax, ay, az): """Returns an (x, y, z) point of the x, y, z point arguments rotated around the 0, 0, 0 origin by angles ax, ay, az (in radians). Directions of each axis: -y | +-- +x / +z """ # Rotate around x axi...
39a2f6491ac8df4780f9f39be863d1b46433825c
67,099
def select_db(cli, dbname): """ Select a database with name :param cli: Client instance :param dbname: Database name :return:A database object """ db = cli[dbname] return db
a1149ba33128980cb52ea1e84e45a6eaeaa4aeaa
67,103
def login_exempt(view): """A decorator to mark the view as not requiring authentication.""" view.login_exempt = True return view
d337b3ab4add24dcf2314bf261fa2fb9b4d3fda0
67,112
def parse_aws_tags(tags): """ When you get the tags on an AWS resource from the API, they are in the form [{"key": "KEY1", "value": "VALUE1"}, {"key": "KEY2", "value": "VALUE2"}, ...] This function converts them into a Python-style dict(). """ result = {} for aws_ta...
d3d2b9a2b4e0484d95bc149b4cb855b1ba88ee9b
67,113
def _hsnalgomac(group, switch, port): """ Returns the string representation of an algorithmic mac address """ # A mac address is 48 bits # [ padding ][ group ][ switch ][ port ] # [ 28 bits ][ 9 bits ][ 5 bits ][ 6 bits ] # Bit 41 (in the padding) must be set to indicate "locally assigned" ma...
f3482f3eaa40488609fe463138e507f35d63c795
67,114
import collections def _asdict(self): """ Return a new ``collections.OrderedDict`` which maps fieldnames to their values. """ return collections.OrderedDict(zip(self._fieldnames, self))
1398a28a1404391c3818943032ac49fb1a49b11f
67,119
def create_plot_data(convert_data: list, batch_size: int, smooth_window: int=1): """ Convert metric data into x, y graph data :param convert_data: list of metric objects with keys [batch, epoch, value] :param batch_size: maximum number of batches in one epoch :param smooth_window: values are average...
544f28786031894bb0354afdd7144554edbebc83
67,127
def to_fix(*args): """ Join a series of strings into a FIX binary message, a field list separated by \x01 """ return '\x01'.join(args) + '\x01'
b88c794f395d07768048a83b3bd2903039fba4e3
67,131
def factorial(num: int) -> int: """ Calculate factorial of a number :param num: the number ad `int` :return: factorial of the number """ fact = 1 if num == 0: return 1 for j in range(1, num): fact = fact + fact * j return fact
38d70efafaf8a311a8ee0d710cecfcac0679df81
67,133
def pooling_output_shape(dimension_size, pool_size, padding, stride, ignore_border=True): """ Computes output shape for pooling operation. Parameters ---------- dimension_size : int Size of the dimension. Typically it's image's weight or height. filter_...
3726fdc72ddc8813957db5f38754119a47256282
67,137
def check_type(lst, t): """Checks if all elements of list ``lst`` are of one of the types in ``t``. :param lst: list to check :param t: list of types that the elements in list should have :return: Bool """ for el in lst: if type(el) not in t: return False return True
6fc39d180e177991d11659fb5c8099c87e3453d8
67,147
import yaml def load_config(path: str) -> dict: """ Load a config from a yaml file. Args: path: The path to the config file. Returns: The loaded config dictionary. """ with open(path, 'r') as f: return yaml.load(f, Loader=yaml.FullLoader)
e701f41a954804edafb0d9f2888910a03a480019
67,148
import re def sanitise(string: str) -> str: """Sanitise string for use as group/directory name""" return "_".join(re.findall(re.compile("[^ @&()/]+"), string))
6529968687dd90a0189bb67162e8a6e3ec105dce
67,149
def _coerce_to_integer(value): """ Attempts to correctly coerce a value to an integer. For the case of an integer or a float, this will essentially either NOOP or return a truncated value. If the parameter is a string, then it will first attempt to be coerced from a integer, and failing that, a float. :param ...
1cb8594b0c16651ae212d4da649500057f09f35b
67,160
def emulator_uses_kvm(emulator): """Determines if the emulator can use kvm.""" return emulator["uses_kvm"]
654ec1207180e0ac90af71d9333acf3ef431add6
67,164
import configparser import itertools def get_imputation_featureset_combis(imputations: list, featuresets: list, target_column: str) -> list: """ Function delivering imputation and featureset combinations which make sense :param imputations: imputations to use :param featuresets: featuresets to use ...
14a02e872449c6fd88be50c0da453e0bee4e4035
67,165
import random def calc_next_exponential_backoff_delay( current_delay_secs, backoff_factor, max_delay_secs, with_jitter=False ): """Calculate the delay (in seconds) before next retry based on current delay using exponential backoff, with optional jitter. See http://www.awsarchitectureblog....
57196a4901a61a389a7bdc55278ee0a1386454bb
67,168
import pathlib from typing import List def get_nested_directories(directory: pathlib.Path) -> List[pathlib.Path]: """Return all directories inside directory and its child directories.""" nested_directories = [] for item in directory.iterdir(): if item.is_dir(): nested_directories.appen...
7fda096919a58ce1bf5a0f97bcc2fe8a3754c8db
67,169
def fibList(n): """ returns first n fibonacci suequence as list """ fibs = [1, 1] for i in range(2, n): fibs.append(fibs[-1]+fibs[-2]) return fibs
b7c303bae7d2a4ae1df4a339e24a27d207e8333d
67,171
import csv def ReadCVS(filename): """ Reads a CSV file and returns a list of lists. """ with open(filename, 'r') as f: reader = csv.reader(f) return list(reader)
0f6c01ade8acdaaa5116a8491aad20af2396fa3f
67,173
import six def get_process_signature(process, input_parameters): """ Generate the process signature. Parameters ---------- process: Process a capsul process object input_parameters: dict the process input_parameters. Returns ------- signature: string the proce...
0004870baaf3a00c35eae815dfcbf4c6965cec51
67,174
def set_to_list(obj): """ Helper function to turn sets to lists and floats to strings. """ if isinstance(obj, set): return list(obj) if isinstance(obj, float): return str('%.15g' % obj) raise TypeError
d9db10d550e23d02e4a1ae89e5a2203202eae8aa
67,176
import re def extract_waveunit(header): """ Attempt to read the wavelength unit from a given FITS header. Parameters ---------- header : `sunpy.io.header.FileHeader` One `~sunpy.io.header.FileHeader` instance which was created by reading a FITS file. For example, `sunpy.io.fits.ge...
2574b7b2e8d8a5b76a94d3b025688e11b968e702
67,182
def is_end_word(word): """ Determines if a word is at the end of a sentence. """ if word == 'Mr.' or word == 'Mrs.': return False punctuation = "!?." return word[-1] in punctuation
9165fede070654b3d0b10b2bb02855307f9ab0c5
67,187
def norm(angle): """ Normalizes an angle between 0 and 360. """ return angle % 360
04acc963b226e31c8892a7bb56394eab52436eae
67,190
def area(l, w): """ Calculates the area using the length and width of squares and rectangles """ area = (l * w) return area
2b4ad1363ada89db784a8dcafb63f7cc17139df0
67,192
def _wildcarded_except(exclude=[]): """ Function factory for :mod:`re` ``repl`` functions used in :func:`re.sub``, replacing all format string place holders with ``*`` wildcards, except named fields as specified in ``exclude``. """ def _wildcarded(match): if match.group(1) in exclude: ...
5de34232ea0c0b2e1baf893dbf0bf8d20c6128a1
67,197
def text2caesar(text,shift = 3): """ Returns the encrypted text after encrypting the text with the given shift Parameters: text (str): The text that needs to be encrypted in Caesar's cipher shift (int): The shift that should be used to encrypt the text Returns: result (str): The encrypted text """ ...
84dc3307224c3773132b5aa33d4e9f31bd83dd64
67,201
import logging def _add(num1, num2): """Add two numbers""" result = float(num1) + float(num2) logging.info("%s + %s = %s", num1, num2, result) return result
7f7d405d5735662296e5cf5beea6f75b86a56623
67,203
def get_previous_timestep(timesteps, timestep): """Get the timestamp for the timestep previous to the input timestep""" # order_dict starts numbering at zero, timesteps is one-indexed, so we do not need # to subtract 1 to get to previous_step -- it happens "automagically" return timesteps[timesteps.orde...
da897b2df0192ec4678fe468a6901df72c0f8d1f
67,204
from typing import Union def _find_assign_op(token_line) -> Union[int, None]: """Get the index of the first assignment in the line ('=' not inside brackets) Note: We don't try to support multiple special assignment (a = b = %foo) """ paren_level = 0 for i, ti in enumerate(token_line): s =...
fb0770f31c54ed29239c70cfad7070495314cb80
67,207
import importlib def load_migration_module(package_name): """Import the named module at run-time. """ try: return importlib.import_module(package_name) except (ImportError, ValueError) as e: return None
49d9c82a777a18052f37e0466361df09bcc402ef
67,209
import time def _waitfn(ind, func, wait, *args, **kwds): """waits based on ind and then runs func""" time.sleep(wait * ind) return func(*args, **kwds)
c9a100210f84795e91a7e536c1187350d2f03aeb
67,210
def _repl_args(args, key, replacement): """Replaces occurrences of key in args with replacement.""" ret = [] for arg in args: if arg == key: ret.extend(replacement) else: ret.append(arg) return ret
504616e94b6aa3368868a97827e41a5fea85dea9
67,211
def tidy_input(cmd_line_args): """ :param cmd_line_args: vars(args()) :return: input arguments, with all keys made uppercase """ out_args = {} for arg in cmd_line_args: if cmd_line_args[arg]: if isinstance(cmd_line_args[arg], str): out_args[arg] = cmd_line_ar...
f519091849f7ba48e9e0d1e2eab658c4d897ef6a
67,212
def _get_template_module(name, req, **context): """Get template module for a request email notification template. :param name: template name :param req: :class:`Request` instance :param context: data passed to the template """ context['req'] = req return req.definition.get_notification_temp...
5cfff3a9f76259b4033e1f448842f40e18291c3c
67,215
def fits(bounds_inside, bounds_around): """Returns True if bounds_inside fits entirely within bounds_around.""" x1_min, y1_min, x1_max, y1_max = bounds_inside x2_min, y2_min, x2_max, y2_max = bounds_around return (x1_min >= x2_min and x1_max <= x2_max and y1_min >= y2_min and y1_max <= y2_ma...
35b7e075bd2246d13979d69bc3893006e738623b
67,218
import re def parseRange(text): """ convert a range string like 2-3, 10-20, 4-, -9, or 2 to a list containing the endpoints. A missing endpoint is set to None. """ def toNumeric(elt): if elt == "": return None else: return int(elt) if re.search(r'-', t...
bec19909188ffdb1de1de233a5f33675fa1ea48b
67,221
def logged_client(django_user_model, client): """A Django test client instance with a new user authenticated.""" user = django_user_model.objects.create_user('user test') client.force_login(user) return client
0cd72b462969fad577ffd3a9a38968d8bb00c80c
67,223
def compute_nyquist(fs): """Compute the Nyquist frequency. Parameters ---------- fs : float Sampling rate, in Hz. Returns ------- float The Nyquist frequency of a signal with the given sampling rate, in Hz. Examples -------- Compute the Nyquist frequency for a ...
febf380a892dd1ad9958d69ded10dd9e36583b8c
67,224
def get_crashreport_key(group_id): """ Returns the ``django.core.cache`` key for groups that have exceeded their configured crash report limit. """ return u"cr:%s" % (group_id,)
484fcd0140fdadadebd5faea01e420d39ed66992
67,229
def translate(x: str, d: dict) -> str: """ Convert english digits to persian digits. :param x: string to translate :param d: dict for using on translate :return: translated string """ if not isinstance(x, str): raise TypeError("x is not string") if not isinstance(d, dict): ...
826f12cc6713e7da814f547cc8de565004910fec
67,234
def check_path_exists(path, search_space): """Return True if the path exists in search_space""" if not isinstance(search_space, dict): return False if path[0] in search_space: if len(path) > 1: current_value = search_space.get(path[0]) return check_path_exists(path[1:...
4cfe64e4b7b627a41317a9b5f0d20552a52cc753
67,235
def convertNumber(t): """Convert a string matching a number to a python number""" if t.float1 or t.float2 or t.float3 : return [float(t[0])] else : return [int(t[0]) ]
9fde8c0813e684b702fd9d6bb3c8d2df1967d134
67,237
def add_title(df): """ Add Title to DataFrame (Mr., Miss., etc) :param df: Input Titanic DataFrame (with Name column) :return: df with ['Title'] column """ # Creates 'names' pd.Series names = df['Name'] # Split 'names' by ', ' and get the latter value proc_names = names.str.split(...
6856200ab24434d54f38b764b49320cd165b1e35
67,240
def isEmpty(text: str = "") -> bool: """ Check if string or text is empty. """ if text.replace(" ", "") == "": return True elif text == None: return True else: return False
ab0e56e30c0045e364e8c55a658e0096a4e51513
67,243
def apply_to_one(f): """Calls the function f with 1 as its argument""" return f(1)
1bc58df883901e7651be50219bd8beec438d49d4
67,249
def extract_qword(question): """ Function used to extract question word in question sentence Question words: who | which """ if 'who' in question.lower(): return 'who' elif 'which' in question.lower(): return 'which' return None
e44c86249afa4c83f596d8b8e56ce93fe73e0343
67,250
from bs4 import BeautifulSoup def get_script_by_id(source_html:str, script_id:int): """ This function finds a script in a specific index in the page source html. @param source_html: The source html of the page in which we want to find the script tag. @type source_html: str @param script_id: The i...
1befdcaf59ec85dc53ea839e58a16911331648e4
67,252
def get_node_info(node, ws): """ Args: node (Node): ws (list(int)): knowledge weights. [cdscore, rdscore, asscore, stscore] Returns: return node information for a searched tree analysis node information: self node, parent node, depth, score, RDScore, CDScore, STScore, ASScor...
d17ce544acbedc6171b1af11a27b1a3356ea3a0e
67,258
def _error_with_fields(message, fields): """ Helper function to create an error message with a list of quoted, comma separated field names. The `message` argument should be a format string with a single `%s` placeholder. """ return message % ', '.join('"%s"' % f for f in fields)
b29466d41fe8b83a73330710469dfdcafa729714
67,259
def find_vm_interface(ports=[], vnic_type='normal'): """find vm interface The function receive port list and search for requested vnic_type. :param ports: ports connected to specific server :param vnic_type: vnic_type nomal/direct/direct_physical return port_id, ip_addre...
981b698fd6eebe4b53d6e74d8ac3c1a1ee1d1919
67,263
from typing import OrderedDict def _split_table(table: OrderedDict): """Splits an OrderedDict into a list of tuples that can be turned into a HTML-table with pandas DataFrame Parameters ---------- table: OrderedDict table that is to be split into two columns Returns ------- t...
a1083ea842202dda4c75b1a0ba880dcfd0a76942
67,264
import re def unindent(string): """ Return an unindented copy of the passed `string`. Replace each occurrence in `string` of a newline followed by spaces with a newline followed by the number of spaces by which said occurrence exceeds the minimum number of spaces in any such occurrence. Further ...
abca940c9ab95f93c23199f1a20a14e2e24a4860
67,266
import random def get_rand_index(n, exclude=None, has_byes=False): """ Return a random integer in range(n), given constraints. The ``exclude`` parameter excludes a single integer value. The ``has_byes`` parameter indicates that every fourth integer should be skipped as those are occupied by b...
1078b853a315cada9dc9affee92f0cd720768c92
67,267
def compress(v, slen): """ Take as input a list of integers v and a bytelength slen, and return a bytestring of length slen that encode/compress v. If this is not possible, return False. For each coefficient of v: - the sign is encoded on 1 bit - the 7 lower bits are encoded naively (binary...
ce45538933efa74e2673d713eae14a9b47e5c020
67,274
def dedup_list(list): """ deduplicate list """ new_list = [] for item in list: if item not in new_list: new_list.append(item) return new_list
712e236576d1dbfde1a56914aefcd78dcfbd6acc
67,275
def magic_to_dict(kwargs, separator="_") -> dict: """decomposes recursively a dictionary with keys with underscores into a nested dictionary example : {'magnet_color':'blue'} -> {'magnet': {'color':'blue'}} see: https://plotly.com/python/creating-and-updating-figures/#magic-underscore-notation Paramete...
108f574d912cca379a458781317554a093ce9f85
67,276
def _get_eth_link(vif, ifc_num): """Get a VIF or physical NIC representation. :param vif: Neutron VIF :param ifc_num: Interface index for generating name if the VIF's 'devname' isn't defined. :return: A dict with 'id', 'vif_id', 'type', 'mtu' and 'ethernet_mac_address' as keys """ ...
1e3d0fe2dbe09991f6bd2929dfb5c7d60978013b
67,278
def apply_penalty(tensor_or_tensors, penalty, **kwargs): """ Computes the total cost for applying a specified penalty to a tensor or group of tensors. Parameters ---------- tensor_or_tensors : Theano tensor or list of tensors penalty : callable **kwargs keyword arguments passed ...
ad4c6ac9102f96ff7b1e27a5700051f5ad70bfd6
67,286
def tree_in_path(map_line,map_x_coord): """ Checks if a tree is in the x-cord of the map line, looping if x is > len(map_line) returns: True if a tree is in the path, False otherwise rtype: Bool """ offset = map_x_coord % len(map_line) # module operater for rollover return map_line[offset]=...
b71f805dcb92d61bc3911ab9c1eee17973b89198
67,289
def get_neighbours(position, width, height, grown, up, down): """ Return connected neighbours that are not already "grown" (i.e. added to the region) """ x = position[0] y = position[1] neighbours = [] # Left if x > 0 and not grown[y, x - 1]: neighbours.append((x - 1, y)) #...
a3a7c5b70191e1cbbf51776dc05918ff1dc3c876
67,297
import logging def get_logger(name): """ Gets a logger with the given name. """ log = logging.getLogger(name) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s/%(module)s: %(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) log.addHandler...
c74abdbb3f5c3dc16de49cf019f064732533ace8
67,301
def decode_reply(reply_code): """ Returns True if the RETS request was successful, otherwise False Intended to fill the response dict's 'ok' field as an alternative to the RETS specification's wonky reply code bullshit. :param reply_code: a RETS reply code :type reply_code: str :rtype: boo...
a3a8aac63f3eee5a88f587801731aad8576e5b02
67,303
import yaml def _parse_yaml_file(path): """Load and parse local YAML file Args: path: either a local file system path or a GCS path Returns: a Python object representing the parsed YAML data """ with open(path, 'r') as stream: try: return yaml.safe_load(strea...
f3f96c50122bafa36a301353a3b9dd4167987062
67,305
def helper_stationary_value(val): """ Helper for creating a parameter which is stationary (not changing based on t) in a stationary fuzzy set. Returns the static pertubation function Parameters: ----------- val : the stationary value """ return lambda t: val
1228b3a85a6026c18ebaf57b87841372e73566c6
67,306
def _CreateGroupLabel(messages, assignment_group_labels): """Create guest policy group labels. Args: messages: os config guest policy api messages. assignment_group_labels: List of dict of key: value pair. Returns: group_labels in guest policy. """ group_labels = [] for group_label in assignme...
80c721f300e8b08fb8b53109e3632057589bf5e6
67,307
def impedance(vp, rho): """ Compute acoustic impedance. """ return vp * rho
6be115c3d92b394a5b98cbf502d2bc753522a8a6
67,309
def print_id(id): """Print id in n1.n2.n3 form.""" return ".".join(str(i) for i in id)
0cc7a1c999e6aabae9256599df59060d6a407a4c
67,311
def dict_of_lists_to_list_of_dicts(dl): """ Thanks to Andrew Floren from https://stackoverflow.com/a/33046935/142712 :param dl: dict of lists :return: list of dicts """ return [dict(zip(dl, t)) for t in zip(*dl.values())]
c6d90a463c31f2f0d2dc9e4d72c8b09bdba6ccf5
67,317
def get_sentences_from_files(files): """ Read files line by line into a list """ sentences = [] for file_name in files: with open(file_name, 'r') as fp: sentences.extend(fp.readlines()) return sentences
54212df80ee2dc71c66f39c4c9075831e2403a25
67,321
def get_columns_from_data_range_rows(data, start_row, end_row, columns): """ This function is a wrapper around the indexing of pandas data frames. This function gets some of the rows from the data frame specified by the start_row and end_row. :param data: Pandas data frame :param start_row: int valu...
550a2ec731d6d7ff817263fd01940f1948752001
67,324
import json def is_valid_json(file_path: str) -> bool: """Return True if the file is valid json. False otherwise.""" try: with open(file_path) as fil: json.load(fil) except json.JSONDecodeError: return False else: return True
bc46fa011caa82a80daeb7e765e2185f5b08d51d
67,332
def snr(signal, bg): """ returns snr as (signal - bg)/bg """ return (signal - bg) / bg
9bdf25734bbb27f56854731f869b31fcdc6800a9
67,334
def world_to_pixel(header, axis, value): """ Calculate the pixel value for the provided world value using the WCS keywords on the specific axis. The axis must be linear. :param header: The FITS header describing the zxes. :param axis: The number of the target axis. :param value: The world value...
d436616cde7993f8dce8c142ba5623c7de5d1564
67,335
def find_cuds_object(criterion, root, rel, find_all, max_depth=float("inf"), current_depth=0, visited=None): """ Recursively finds an element inside a container by considering the given relationship. :param criterion: function that returns True on the Cuds object that is se...
b8432d8831c78ccaaf147d131b1314e0dc32c7e2
67,337
from typing import List def dedupe_loops(loops: List[List]) -> List: """ Deduplication of loops with same members. For example: for nodes 1, 2, 3 in the graph below [ [0, 1, 1], [1, 0, 1], [1, 1, 0], ] Loops of length 3 are 0->1->2 and 0->2->1. We...
5576ca769e7c592e8c10f6066f7cefaba83f5e62
67,338
import textwrap def compact_simple_list(match): """Callback function. Given a simple list match, compact it and ensure that it wraps around by 80 characters. Params: match The regular expression match Returns: The string to replace the expression with """ # Calculate the ini...
5889affc8dc10f747c25eece663cb07aa44c95c2
67,341
import re import urllib.parse def parse_stdout(stdout: str): """ Parses stdout to determine remote_hostname, port, token, url Parameters ---------- stdout : str Contents of the log file/stdout Returns ------- dict A dictionary containing hotname, port, token, and url ...
7a27362369a54ba32e8e0eec4482150318b40608
67,342
def get_study_period_ranges(data_length: int, test_period_length: int, study_period_length: int, index_name: str, reverse=True, verbose=1) -> dict: """ Get study period ranges, going backwards in time, as a dict :param data_length: Number of total dat...
19d1560278ade920b7063ecd0a2c89ded68b1216
67,345
from typing import Sized import random import binascii def generate_pad(message: Sized) -> bytes: """ Generates the One Time Pad (OTP) to be used for encrypting the message. Arguments: message: bytes - the message to generate a pad for Returns: bytes - the randomly generated pad as a hex str...
1100477eb34045052cf69f89d8702d775259026d
67,351
def label_date(ax, label, date, df): """Helper function to annotate a date ``date`` is assumed to be in the index of ``df`` Parameters ---------- ax : Axes The axes to draw to label : str The text of the label date : object in index of df The x coordinate df :...
d70e104b0e00b590daaa00a156db54908e7461a2
67,353
def _ul_subvoxel_overlap(xs, x1, x2): """For an interval [x1, x2], return the index of the upper limit of the overlapping subvoxels whose borders are defined by the elements of xs.""" xmax = max(x1, x2) if xmax >= xs[-1]: return len(xs) - 1 elif xmax <= xs[0]: ul = 0 return u...
21a6ed3e6b7d718250aff829ceb5d863677f3e3d
67,358
def encodewithdict(unencoded, encodedict): """encodes certain characters in the string using an encode dictionary""" encoded = unencoded for key, value in encodedict.iteritems(): if key in encoded: encoded = encoded.replace(key, value) return encoded
730966b84a596cc9352f0af651d153381b115019
67,360
def round_to_factor(value, factor): """ Round value to nearest multiple of factor. Factor can be a float :param value: float :param factor: float :return: float """ return factor * round(value / factor)
ab23b290dddacec5d4bb4f349851845109fc1b8e
67,361
def keywords_mapper(keywords, package): """ Update package keywords and return package. This is supposed to be an array of strings, but sometimes this is a string. https://docs.npmjs.com/files/package.json#keywords """ if isinstance(keywords, str): if ',' in keywords: keyword...
841a7fafe5f51fe3359e39d4015f94be7626f6bc
67,363
import hashlib def md5(file_paths, chunk_size=1024*1024*1024): """ Calculate a md5 of lists of files. Args: file_paths: an iterable object contains files. Files will be concatenated orderly if there are more than one file chunk_size: unit is byte, default value is 1GB Returns: ...
79b12ac941a761ee15b243a72b0e5b04d6a61980
67,364
import mimetypes def guess_extension(content_type): """ Guess extension Parameters ----------- content_type: str MIME type Returns -------- str Extension or None if not found """ if content_type == "text/plain": ext = ".txt" else: ext = mim...
6a8d91cd33ea00aaf74584aa2124154e50216bca
67,366
def _read_text(file): """ Read a file in utf-8 encoding.""" with open(file, mode='r', encoding='utf-8') as f: return f.read()
4bc7e9a83a02bdc6dee250958e67e99e7aea4950
67,369
def _list_of_command_args(command_args, conf_args_dict): """ Creates a reduced list of argument-only commands from the namespace args dictionary by removing both non-argument commands and None arguments from the namespace args. Parameters ---------- command_args(dict): A dictionary object tha...
8ccce893396cabd41661ec13b20f1551ffc7c4ce
67,374
def dns_label_count(rows, args): """Returns the number of labels in a given domain (eg: www.example.com = 3)""" label = rows[args[0]] parts = label.split(".") # deal with www.exmaple.com. with a trailing dot if parts[-1] == "": return (str(len(parts)-1),'') return (str(len(parts)),'')
f0ef232277dc7908449d799d2156dbedbadb21d0
67,375
from typing import Dict def remove_answers(squad_dict: Dict) -> Dict: """Remove answers from a SQuAD dev or test file""" for dp in squad_dict: for para in dp['paragraphs']: for qa in para['qas']: qa['answers'] = [] return squad_dict
149b23b07dfab32a3d5a5c57f8967d2b059b66c6
67,376