content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import aiohttp async def get(url, indicator): """ A simple async get function, tailored to tracking failures Parameters ---------- url : str The URL to make a request to indicator : str The name of the indicator being retrieved (to make tracking easier) Returns -------...
c68306c01d5d21f6b96382fad4ce94f48596e04e
616,131
def new_capacity_rule(mod, g, p): """ New capacity built at project g in period p. """ return mod.DRNew_Power_Capacity_MW[g, p]
ea9eba2fcf301dfc7153a67a713de7f694d2bed2
616,136
import math def rescale_js( value: float, deadzone: float = 0, exponential: float = 0, rate: float = 1 ) -> float: """Rescale a joystick input, applying a deadzone, exponential, and max rate. Args: value: the joystick value, in the interval [-1, 1]. deadzone: the deadzone to apply. ...
a81843f1bd946dbf8c9e4587282a5136280b74fc
616,137
def get_log_slice(db, job_id, start, stop): """ Get a slice of the calculation log as a JSON list of rows :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: a job ID :param start: start of the slice :param stop: end of the slice (the last ele...
17b11c3c2758e45038fa7ba29245ae9a56b9c1e7
616,142
import unicodedata def normalize(text: str) -> str: """Prepare the `text` for string comparison. Replaces composed characters by basic ones and converts to lowercase. """ text = unicodedata.normalize('NFKD', text) output = [] for c in text: if not unicodedata.combining(c): ...
db127986bdda48332b5ce56d5b1a782bdf8ca05c
616,145
def lines(a, b): """Return lines in both a and b""" # Get lines lines_of_a = a.split('\n') lines_of_b = b.split('\n') # Use a set to store the line, beacuse # it's a better structure for string # and avoids duplicates values equal_lines = set() # Compares the lines for line_of_...
0c00d03c39d9357e48f5aa443d551a0bf289f38e
616,147
import random def reservoir_sample(filename, n_samples=1, random_seed=None): """Return a random subset of lines from a file Parameters ---------- filename: path File to be loaded n_samples: int number of lines to return random_seed: int or None If set, use this as the ...
6b6f174a0fc1b383b55ddcd4ef624d749808edf8
616,148
import re def batch_settings( content ): """ Gets the batch settings. :param content: Content to search. :returns: Dictionary of settings with their index. :raises RuntimeError: If settings section could not be found. """ section_pattern = '\*{3} Overview of batch settings \*{3}\n\n(.+?)\...
407bd5949181093a023f3abda3e9003c4836c042
616,150
from datetime import datetime def calculate_duration(start): """ Returns the difference in seconds between start and now :param: start: datetime to begin :returns: Seconds between start and end """ timing = datetime.utcnow() - start duration = timing.seconds + timing.microseconds / 1000000...
c046f24ad30d56ec9af6e89e3695e9e93608e9b2
616,151
import re def output_content(content, print_output, text_filter, headline): """ Builds the human readable output return from stdout commands according to print_output and text_filter Args: content: stdout returned from running ad hoc command or job print_output: if True human readable is s...
30ca29b7131fc320235f1f464807916accfd8e5f
616,152
import math def calculate_sinwave(i): """Create a sinusoidal statistic.""" return 10 + math.sin(math.radians(i)) * 50
e420387c3cc0900c84867def94ea5d9a9f3312a9
616,155
def packman_api_name(api_name): """Changes an pipeline kwarg API name to format expected by Packman""" return api_name.replace('-', '/')
e5a42838efd104373adf4796181dbf6ebe53dda9
616,156
from typing import Any def is_reference(key: Any) -> bool: """Is this key a reference to output from elsewhere in the chores. A reference has the form ^chore(.output)? where `chore` is the name of the node you are consuming output from and `output` is either a name or a number to tell which part of t...
4e68a9903c57435ff73b7f652a8d6d9efded5ca9
616,164
def dirhandler(directory, defaultdir): """ If directory is None, turn it into defaultdir. :param directory: Target directory. :type directory: str :param defaultdir: Default directory. :type defaultdir: str """ directory = defaultdir if directory is None else directory return direc...
a99b7e53553d36cef3ae0a154174062de4ecffdd
616,168
def categorical_features(df): """ Return categorical features of dataframe :param df: pandas dataframe :return: summary: list that contains categorical features """ categorical_col = df.select_dtypes(include=['object']).columns.tolist() return categorical_col
8644720d22602dd4aab28570e8b0407f9727a361
616,170
def check_predicates(goal, atom): """ Checks if the predicates match in name and arity. :param goal: the goal :type goal: Atom :param atom: the atom :type atom: Atom :return: `True`, if they match; otherwise, `False` :rtype: bool """ return goal.predicate == atom.predicate
fc02b9cc41de080a51a31433ad2305f5323ab1e0
616,171
import random import math def randomPointOnSphere(r=1., center=(0.,0.,0.)): """compute random point on sphere with uniform distribution on surface. Usage can be as simple as that: >>> p = randomPointOnSphere() We expect a point with 3 coordinates and distance 1 from the origin: >>> len(p) # three c...
0e13aee2d312c361af094e30f5dda2d75a700794
616,172
def linereader_int(file): """Read input file and return a tuple with content converted to ints.""" file = open(file, "r") return tuple(map(int, [line.rstrip("\n") for line in file.readlines()]))
7c9cd7b9b1a568aebc5740d8da36499a98ae812c
616,173
def q_to_q(q): """ identity map from q to q Surrogates with this parameterization expect its user intput to be the mass ratio q, and "map" to the internal surrogate's parameterization which is also q The surrogates training interval is in mass ratio """ return q
28f3b1be5b11fe1b350746e8fccf24940e4f3738
616,177
def is_project_user(user, project): """Return if user is a member of project.users.""" return user in project.users.all()
7eac8a92bff1a533c6c047cb833017ffdb05e181
616,179
def partition(sequence, predicate): """ Partition the sequence into two lists, according to the function provided. Args: sequence: A sequence of elements. predicate: A function of one argument, returning bool. Returns: A tuple of lists, where the first list contains all ...
b04f49cff337caf530a40198ddbabac5c8c7b117
616,180
import sqlite3 def get_db_connection(db_file: str): """ Connect to DB :param db_file - a string filepath to the sqlite db file :return: sqlite_connection and cursor """ conn = sqlite3.connect(db_file) cursor = conn.cursor() return conn, cursor
eb41fcbc0ad5b9d791c8067b1d9bb6f7bddea5ad
616,181
def _combine_odds(odds): """Combine the odds of different outcomes.""" combined_odds = 1 / (1 / odds).sum(axis=1) return combined_odds
7b2b91c2e9cc484bf1d05fabc95b1561c360ff6a
616,185
def zeros_matrix(rows, cols): """ Creates a matrix filled with zeros. :param rows: the number of rows the matrix should have :param cols: the number of columns the matrix should have :return: list of lists that form the matrix """ M = [] while len(M) < rows: M.append(...
f57ea770eca82a1172ace4bf7966d6f694f1229f
616,188
def getPageContent(r): """ Returns the source code of a web page """ return r.text
9a4d8fd48b70f9268bc58708595c3804393648dd
616,192
def get_processing_speech(vocab_speech = None): """ Function: Return function that maps the speech key to a set of interval and word ids Args: vocab: dict[key] = idx Returns: f("2005-A-10-1-5") = ([12, 4, 32], 12345) = (list of interval ids, word id) """ ...
ac36f4bdb8df24a3e6224ca4205bfc0ffab79b02
616,195
import re def is_mixed_case(s): """ >>> is_mixed_case('HiThere') True >>> is_mixed_case('Hi There') True >>> is_mixed_case('hi there') False >>> is_mixed_case('h') False >>> is_mixed_case('H') False >>> is_mixed_case(None) False """ if not isinstance(s...
9f7244597fc0823e70db584f32d5e3d66df759b0
616,196
def to_binary(n, N): """ Get binary representation of input n :param n: Integer of which to get binary representation :param N: Length of bitstring :return: str """ return bin(n).replace('0b', '').zfill(N)
d7e8ac34d5205b9692410d4380a492b75dd275f0
616,197
def _encode_module(module): """Encode a :class:`~schedsi.module.Module` to a :obj:`dict`.""" return {'name': module.name}
b11845514f2182bd9a2c1e4b8b96e82bc3affcc1
616,198
def _extract_name_arg(args, kwargs, name_index): """Extracts the parameter `name` and returns `(args, kwargs, name_value)`.""" if name_index < 0: name_value = None elif name_index < len(args): name_value = args[name_index] args = args[:name_index] + args[name_index + 1:] else: name_value = kwarg...
00d18bd3a44a687e67ecbd88fa788a4347236e6e
616,199
def coefficient_of_drag_morrison(state, only_in_range=False): """ Calculate the coefficient of drag using the equation provided from http://www.chem.mtu.edu/~fmorriso/DataCorrelationForSphereDrag2013.pdf Enter: state: a dictionary of the current state. Includes Reynolds and mach numb...
21f3de7dc851816ccec1e63eb9aed307770baab2
616,204
def factors_pairs(num): """ (int) -> list Builds a list of factor pairs for a positive integer <num>. for example, tuple (2, 15) is a factor pair for the number 30 because 2 x 15 is 30. Returns the list of factor-pair tuples """ return [(x, num//x) for x in range(1, num + 1) if num % x ==...
ac4d2d07c00112336b00b853f41ad7fe4b99299d
616,205
def non_fm_sex(row): """Return True if sex is not F or M.""" return row["sex"] not in ["F", "M"]
b0b4cb8be91a0cee3e8b0ffd2d0e11cdbfd5db7f
616,206
def getFormat( self ) : """Checks if self has a getFormat method. If it does not, then None is returned. If it does then: 1) if getFormat returns a string or None then it is returned else getFormat must return an integer, n1. If n1 is 12 (default for legacy ENDL) then None is returned else returns string ...
4896e0b32af8fe1aacf3d0d4856f079b99bc382b
616,208
import math def quantize(number, stepsize): """Quantizes number to a given step size.""" return math.floor( (number/stepsize) + .5) * stepsize
8d9bda701427022c943ed8c44b8048fb71d07cf8
616,212
import re def safe_content(content: str) -> str: """Make content safe. Replaces variable with ellipsis and strips any HTML tags. :param (str) content: Input string. :returns (str): Modified string. """ if content is not None: # Replace piping with ellipsis content = re.sub(r"...
4c2a0a671b3a532c308b31025d9a4f0ab8151687
616,218
def sum_runs(df): """Adds together all the runs to get a value for total profit Parameters: df (pandas.core.frame.DataFrame): data frame containing the simulation Returns: dictionary: dictionary containing the results summed up for the total profit visualisation. """ lists = [i for i i...
f1ed9b104272fe5497b5c2f7287119e5025ca1a7
616,219
def to_id(file_name): """ Converts the file name of an image to the corresponding base name. Example: image.jpg -> image :param file_name: the name of an image file (JPG) :return: the base name of the given image file """ if file_name[-4:] == ".jpg": file_name = file_name[:-4] re...
fca89138bbbc52fcc868b6c7eb5823a6da1a7d66
616,227
def parse_sintax_fasta_entry(text, known_species=None): """Extract the species from SINTAX taxonomy annotation. See https://drive5.com/usearch/manual/tax_annot.html which defines this taxonomy annotation convention as used in USEARCH and VSEARCH. The tax=names field is separated from other fields in th...
282cdda011dd48da920c477db1ccfb91c0638421
616,228
def parse_html(soup): """Parses BeautifulSoup object and returns the table :param soup: BeautifulSoup object :return: List of the rows that make up the table """ table = soup.find("table", {"id": "minecraft_items"}) data = [ [td.get_text() for td in row.find_all("td")] for row in table....
80138e419e7443eb57364c829efc0915ad42218d
616,230
import torch def sequence_masking(x: torch.Tensor, mask: torch.Tensor, axis=1, mode='add', inf=1e12): """序列 mask Args: x: 2D 或 2D 以上张量,必须包含 batch_size 和 seq_len 两个维度 mask: 形如 (batch_size, seq_len) 的 0/1 矩阵 axis: 需要 mask 的维度,即 seq_len 所在维度,默认为...
7a2fdc0403ad90a8995c99127887f5173410596c
616,233
def compute_iou_tk(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) ...
4b6f53045ee032beedf89e46c8435e9d1f85b101
616,235
from datetime import datetime def anomaly(dset, clim_freq, slice_mon_clim_time=None, time_coord_name=None): """Compute anomalies for a specified time frequency Parameters ---------- dset : xarray.Dataset The data on which to operate clim_freq : str Climatology frequency alias....
0d762e3fe8d8a3ae2a9c1eca9c1e3c3f0c10f754
616,236
import grp def get_group_from_gid(gid): """Return group name from GID Looks up group name matching the supplied GID; returns None if no matching name can be found. """ try: return grp.getgrgid(int(gid)).gr_name except (KeyError,ValueError,OverflowError): return None
eb84d4cdb56df29d283e86cb94880e28995666e4
616,239
def readfile_to_list(pathin, strip=True): """Read file into a list of lines. Strip off newline symbols if strip=True""" f=open(pathin,'r') listin=f.readlines() f.close() if strip: listout = [line.strip() for line in listin] else: listout = listin return listout
d850322ea808c0bbd0631c05e4837b1720e85285
616,240
import torch def normalize_batch_per_example(tensor, normalize_mean=True, normalize_std=True): """Normalize batch of tensors by mean and variance Mean and variance are computed per channel and example Parameters ---------- tensor : torch.Tens...
9f904e35e265e04b636338623e67a1f7fa0167ec
616,241
def pad_b64(b64s): """Pad Base64 encoded string so that its length is a multiple of 4 bytes""" pad = len(b64s) % 4 if pad != 0: return b64s + '=' * pad return b64s
a4e862e1fa80ad8469cead1818dc874da8c4bda6
616,244
def _dataframe_formatter(x): """Format a dataframe element.""" return f"<DF {x.shape[0]}x{x.shape[1]}>"
d25e73749258ebf9b5e1f95666af9b1b09abe019
616,245
def remove_formatting(formatted_text): """Throw away style info from prompt_toolkit formatted text tuples.""" return ''.join([formatted_tuple[1] for formatted_tuple in formatted_text])
c4632da8b02c8ba2eaa38109b5297cffbbbaaf00
616,247
def contains(indices1, indices2): """Returns a boolean indicating whether indices1 contain indices2""" if indices1[0] <= indices2[0] and indices1[1] >= indices2[1]: return True else: return False
43cb704dac4366b97720ab194efc4b04870bb257
616,249
def is_classifier(estimator): """Return True if the given estimator is (probably) a classifier. Parameters Function from base.py in sklearn ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a classifier and False othe...
7e761ee94316be286798331e5eafedca55d1b3cc
616,251
def create_two_embedding_dicts(dict_snapshots, dict_projections): """ First initialization of the two wanted embedding dictionaries. They are first embed with the nodes of the first snapshot and their embeddings. :param dict_snapshots: Dict where keys are times and values are a list of edges for each ti...
80780fcf8f3deff2ed4c8237c9de4bba0f5c597b
616,253
def collided_with_level(player_state, previous_position): """ Called whenever the player bumps into a wall. Usually, you just want to set player_state["position"] = previous_position :param player_state: Our state :param previous_position: Where were we before be bumped into the wall? :...
5e1acee48e06eaf2775110fe788efb8951c2183f
616,256
def sort(df, sort_column, ascending=True): """ Sorts a given DataFrame by a given column and returns it. :param df: (pandas DataFrame) the data to be sorted. :param sort_column: (string) describes which column on the given DataFrame to sort. Raises KeyError if the column does no...
b2bc3d2deefbd5134c0294824d7ab2cf83fc4549
616,258
def to_weekly(series, method='ffill', how='end'): """ Convenience method that wraps asfreq_actual with 'M' param (method='ffill', how='end'). """ return series.asfreq_actual('W', method=method, how=how)
c054a46765e9d1834b98356aa9c46874314362db
616,264
import hashlib import struct def _hash_dimensions(dimensions_json): """Returns a 32 bits int that is a hash of the dimensions specified. dimensions_json must already be encoded as json. The return value is guaranteed to be non-zero so it can be used as a key id in a ndb.Key. """ digest = hashlib.md5(dim...
9e78beff2a1163461fff1f8197571b5a4d72ad7e
616,266
def get_edge(from_node, to_node, properties, edge_relationship_name, encoder): """converts a NetworkX edge into a Geoff string. :param from_node: the ID of a NetworkX source node :param to_node: the ID of a NetworkX target node :param properties: a dictionary of edge attributes :param edge_relation...
777e9431d4f545d37caf4e2024ee88964c027c33
616,271
def _bold() -> str: """Internal function returning ANSI escape sequence bolding foreground color""" return '\033[1m'
1c3cea13b16379feda2f9e6d4a9f944cfbaef824
616,275
import inspect def call_func(f_callable, only_mandatory=False, **kwargs): """Calls a function with the given parameters given in kwargs if they exist as parameters in f_callable. Parameters ---------- f_callable : callable The function or object that is to be called only_mandatory : b...
6e5f769759b6e4a7d30c1166c8d3627329dec1c0
616,280
import torch def load_model(model, checkpoint_path, gpu_ids, return_step=True): """Load model parameters from disk. Args: model (torch.nn.DataParallel): Load parameters into this model. checkpoint_path (str): Path to checkpoint to load. gpu_ids (list): GPU IDs for DataParallel. ...
2bfefe0fa4cc325df9869108d2fcb39c0ef7627b
616,281
from typing import Tuple import pathlib def _covert_legacy_entry(entry: Tuple[str, ...], info: Tuple[str, ...]) -> str: """Convert a legacy installed-files.txt path into modern RECORD path. The legacy format stores paths relative to the info directory, while the modern format stores paths relative to the...
272b01fdd1c4fdc3bf5b6dd48155a68a65ffdc50
616,284
def findAlleleIndex(record, allele): """ Find the index of an allele in a VCF record """ alleles = [record.ref] + record.alt; if allele not in alleles: return -1; else: return alleles.index(allele);
c50d4e28d01d4afd03103a12697cbf111e35dcef
616,285
import struct def int_to_float(n): """ convert from an 4-byte integer to 4-byte floating point number :param n: 4-byte integer :return: 4-byte floating point number """ return struct.unpack('@f', struct.pack('@I', n))[0]
d97e7e3d4c94f2666e13bdf987966fdb5893013c
616,286
def read_target_source(target): """ Processes file so we can write newly minted docstrings. :param target: Target file :returns: List of lines in target file """ f = open(target.__file__) file_contents = f.readlines() return file_contents
6241dcb7417b1dce5f0e52cd2b965b45cab81882
616,288
def grad_flow(model): """ Returns a dictionary containing the mean of each layer gradient Parameters ---------- model : torch.nn.Module the module to extract the gradient flow from Returns ------- dict a dictionary with the key being the layer name and its value being t...
cd6003e19b9b5649d4266dc252d7df4fad50c566
616,289
def _create_neighbor_dict(codons): """ Create minimum neighbor distances for each amino acid given the genetic code. Parameters ---------- codons : dict dictionary mapping codons to single-letter amino acid codes Returns ------- neighbor_dict : dict dictionary mappi...
127ea6faf41dba526c3d7bcb43a1095560445c2c
616,291
import pathlib def patch_extr_svs_npy_read(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction svs_read npy. Download sample patch extraction svs_read npy for pytest. """ return remote_sample("patch-extraction-svs-read-npy")
4776d16760bc20a85e96cd5870cf27bf90a5233d
616,293
def _rounder(val, tol): """ Utility function to round numbers to arbitrary tolerance """ return round((1.0 * val) / tol) * tol
ebef5d02f990968c9f495d3712524714db7498d1
616,294
import pkg_resources async def version(): """Get dependency versions """ versions = {} for name in ('instagrapi', ): item = pkg_resources.require(name) if item: versions[name] = item[0].version return versions
b89ce1ae5472b7e6df3d3151b2781ed872c2c0f4
616,298
def merge(x, y): """Merge two ordered lists :param x: :param y: x,y are non decreasing ordered lists :returns: union of x and y in order :complexity: linear """ z = [] i = 0 j = 0 while i < len(x) or j < len(y): if j == len(y) or i < len(x) and x[i] <= y[j]: # priority ...
d7e4f77be7e1c46d244038d52ba618d985082a37
616,300
import re def station_name_hyphenate(sub: str) -> str: """Hyphenates names like 'Dapto to Wollongong' as 'Dapto-Wollongong'.""" return re.sub(r"\ To\ ", "-", sub, re.IGNORECASE)
ce372285828e41f366e3ca9d420f92537f16472c
616,301
def center_trim(tensor, reference): """ Center trim `tensor` with respect to `reference`, along the last dimension. `reference` can also be a number, representing the length to trim to. If the size difference != 0 mod 2, the extra sample is removed on the right side. """ if hasattr(reference, "s...
30d90c748f3e26629983cc7580d0523193d8806f
616,304
def factorial(n): """return n factorial The factorial is defined as n! = n*(n-1)! Note: The recursive factoial implementation will break down if n is too large """ if(n==0): return 1 else: return n*factorial(n-1)
8073a7b5f816e0092577fc632431145eb76c7bfe
616,306
import glob def make_filelist(path): """Makes a list of files through which the program may iterate Args: path (str): a string indicating the path in which the tweets are stored """ #initial array for the read-in tweets files = glob.glob(path) files.sort() return files
e3f49ae0d7f1815445bf5bff9576fc33febcedf3
616,307
def add_lines(name, content, is_file, boundary, lines): """Add content to lines with proper format needed for multipart content type. :param name: name of the request parameter :param content: contents of the request parameter :param is_file: is the parameter a file type (for adding filename) :...
79852a25fd55de65639cdc18e3847962eb5abeb7
616,308
def square_frame_size(radius): """Compute the number of pixels of the external frame of square neighbourhoods of the given radii. Parameters ---------- radius : list of int Radii of the local neighborhoods. Returns ---------- points : list of int Number of pixels of the...
a6030a575c6fa9d763ee278eb15c83295a3f72ca
616,310
def bNoNL(p): """check if contains any RC, NL or FF chars""" for c in p: if c in [0xA, 0xC, 0xD]: return False return True
3ae2328f10e3a032a57654e8b1197b5d4833376c
616,313
def y(P): """ Return :class:`P.y` or :class:`P[1]`. Args: P (:class:`list`): ``secp256k1`` point Returns: :class:`int`: y """ return P[1]
7923157e13806d14e08cac9dce50f5333253b20c
616,316
import uuid def generate_request_id(original_id=''): """Generate request id.""" new_id = uuid.uuid4() if original_id: new_id = '{}, {}'.format(original_id, new_id) return new_id
b38d8bae4db8fdf1cdd8ec5d0f2906b9889c40bb
616,321
import torch def are_broadcastable(a: torch.Tensor, b: torch.Tensor) -> bool: """ Returns True if the two tensor are broadcastable to each other, False otherwise. """ return all((m == n) or (m == 1) or (n == 1) for m, n in zip(a.shape[::-1], b.shape[::-1]))
4708aebbae8898c99a45dbcf5ccca6379d662145
616,323
import textwrap def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. Taken from https://github.com/ipython/ipython_genutils/text.py """ if text.star...
deaa59646a9bd35ee40f6d3b5b4c39e5b8288d53
616,324
def bdev_split_create(client, base_bdev, split_count, split_size_mb=None): """Create split block devices from a base bdev. Args: base_bdev: name of bdev to split split_count: number of split bdevs to create split_size_mb: size of each split volume in MiB (optional) Returns: ...
7e236b76d1a1b9f4945ecae1a37b5649ef48fdac
616,326
import socket import struct def tcp_socket_constructor(linger_time=10, tcp_no_delay=1): """ Create a new TCP socket with reasonable socket options set. :param linger_time: The linger time after closing the socket to allow buffers to flush. Default: 10 :type linger_time: int :param tcp_no_delay: 1...
966bb112ba062f8f34c8b4ae44e70d4b149ec5ee
616,330
def is_pos_int(val): """Check if value is positive integer""" return isinstance(val, int) and val > 0
36f0151062f471dd0cb87fc8a19114f381c9c32d
616,335
def append_all(src_str, append, delimiter): """ Add the append string into each split sub-strings of the first string(=src=). The split is performed into src string using the delimiter . E.g. appendAll("/a/b/,/c/b/,/c/d/", "ADD", ",") will return /a/b/ADD,/c/b/ADD,/c/d/ADD. A append string with null...
7fb88e1ec81eb3a033fd7299b319a026fcb9bea6
616,336
import click def confirm_choice(choice, default=True, abort=True): """Returns a bool from a yes/no question presented to the end user. Args: choice (str): the question presented to the end user. default (bool): the default for the confirmation answer. If True the default is Y(es),...
3d5331502b518eb3817f0739fa83dc64af6c15a1
616,344
import logging def get_logger(name): """ Return a :class:`~py:logging.Logger` object with the specified name. A :class:`~py:logging.NullHandler` handler is added to the logger if it does not have any handlers yet and if it is not the Python root logger. This prevents the propagation of log reques...
27f8f29a4b794afb512b0b90a99234183d271eb6
616,348
import yaml def read_yaml(fname): """Parse yaml file and return a dict.""" metadict = {} try: with open(fname, 'r') as yaml_file: metadict = yaml.safe_load(yaml_file) except Exception as e: print("Error loading {file}\n{error}".format(file=fname, error=e)) return meta...
0773e881801bbbc64e931f846103b69c07e0d35e
616,349
def ansible_hostname(hostname: str): """Convert hostname to ansible format""" return hostname.replace("-", "_")
c963d9c61c0f1ea04383a95e2a6fb4fe4fc22bb7
616,350
def cobb_douglas_output(k, alpha, **params): """Cobb-Douglas output (per unit effective labor supply).""" return k**alpha
539baafc931b1bc8ecd398b44662710c5ce6073b
616,351
import torch def from_coord_to_patch(ortho, fps, big_fp): """Returns an n batch of the input ortho using fps (footprints).""" image_patches = [] for fp in fps: partial_patch = ortho[:, fp.slice_in(big_fp)[0], fp.slice_in(big_fp)[1]] image_patches.append(partial_patch) image_patches = t...
7935f8876fac1b49980565f23ecc0be17431431d
616,357
def zero_dose(t, X): """Dose function returns zero dose at all times. :param t: current time point :type t: float :param X: amount of dose administered :type X: float :return: zero :rtype: float """ return 0.
49a70cf1b554c681862c8cc2e806acdd4c412ca9
616,361
def localize_url(url, locale_code): """Append language tag to URL and return""" if not locale_code: return url if url and 'languageId' not in url: delimiter = '&' if '?' in url else '?' return "{url}{delimiter}languageId={locale_code}".format( url=url, delimiter=delimiter...
b804e782d848021795ae01ff91df84a519b65a73
616,367
def autorange(timer, callback=None): """Return the number of loops so that total time >= 10. timer should be a timeit.Timer instance. Calls the timeit method with *number* set to successive powers of two (1, 2, 4, 8, ...) up to a maximum of 2**21, until the time taken is at least 10 seconds, or th...
22dba6dec804b37e1a1a3da23893dcc986546a25
616,368
import math def shield_rating(shield, max_shield): """ Calculate a 0%-100% shield recharge/capacity rating for a ship Given the actual shield recharge or capacity value as well as the perfect value for the total mass of a ship, give it a rating between 0% and 100% using a smoothed curve that increase...
74b2dad6298d4ea5b58570c8240f01ea0f03ba1e
616,369
def version_update_handler(version, version_update_strategy): """ This method takes the current version and a function that produces a new version, and removes and re-adds non-numeric version qualifiers (such as "-SNAPSHOT"), if necessary. 1st argument: the current version 2nd argument: a func...
16a686a327d11ac570f65242ffd6c0238ccaf2bb
616,370
from typing import List def make_ngrams(n: int, tokens: List[str]): """ Create N-grams for given set of tokens. example: -------- > make_ngrams(2, ["have", "a", "good", "day"]) < [("have", "a), ("a", "good"), ("good", "day")] """ ngrams = zip(*[tokens[i:] for i in range(n)]) retu...
df4bb81926a3a828532fea56c6cec23df2e0f378
616,373
def readInQuery(textFile): """Read in a textfile with an HTSQL query""" #read in text file query='' for line in open(textFile): query+=line query=query.strip() return query
36ae428f002f113bf443fc9bff6a386c38d97098
616,374
import re def parse_python_version(output): """Parse a Python version output returned by `python --version`. Return a dict with three keys: major, minor, and micro. Each value is a string containing a version part. Note: The micro part would be `'0'` if it's missing from the input string. """ ...
1b4c346491715278ff472abde3bc702792d2c3b9
616,376
def get_filename(start, stop): """ Create filename for time interval Parameters ---------- start : integer Start year stop : integer Stop year Returns ------- filename : string Filename """ # Set filename filename = '_%4.4d-%4.4d' % (start, stop)...
146fa3df8526da7f1e63a0a1b892397d8295c62d
616,377