content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def construct_engine_data(args): """ create the set of engine data :param args: parser argument class :return: engine_name(string), engine_data(list) """ engine_name = args.engine_name engine_data = [args.takeoff_thrust, args.cruise_thrust, args.BPR, ...
d21d6bf02f8f39705b41d119c051559d754901a0
653,133
def _try_rsplit(text, delim): """Helper method for splitting Email Received headers. Attempts to rsplit ``text`` with ``delim`` with at most one split. returns a tuple of (remaining_text, last_component) if the split was successful; otherwise, returns (text, None) """ if delim in text: ...
ecc57abd82c8a4c63100d2305af1cd21853fa86e
653,134
def _bool(value): """Return env var cast as boolean.""" if isinstance(value, bool): return value return value is not None and value.lower() not in ( "false", "0", "no", "n", "f", "none", )
ebe33128cd74d5fc9051f5c19ce3a44ca22b6718
653,135
def subtract(x, y): """Subtracts x from y and return value""" return y-x
c2f018d47b4764a8541ceaabbbf2005732753f99
653,136
def guessShaper(key): """ REDUNDANT see unetsl.cerberus.__main__ """ kl = key.lower() if "crop" in kl: return "crop" return "upsample"
0012d681e9ce57416ba62daa1fac9e6eaca9fd2d
653,137
from pathlib import Path def chk_dir(src_dir): """To check if the directory exists. Returns boolean """ src_is_dir = Path(src_dir).is_dir() if src_is_dir is False: print(f"Test Directory '{src_dir}' does not exist.") print("Add a directory containing the source images to run this test...
50200b6de34af6ec50abf90b05e6a366502c78fe
653,138
import zlib import pickle def _compress_obj(obj, level): """Compress object to bytes. """ return zlib.compress(pickle.dumps(obj, protocol=2), level)
17c531c350103d27647bbd6c2baece4d2e46db3e
653,140
def display_2Dlist(p): """Prints a piece, or each Piece in a list, to output. Args: p (Union[Piece, List[Piece]]): Piece, or list of Pieces, to print to output """ # helper function to display a piece def dis(p): for row in p: print(row) def is_piece(p): ret...
e1bb93928825702f4b40620ca581797e1747bb62
653,141
from typing import Tuple def parse_fasta_header(fasta_header: str) -> Tuple[str, str, str]: """Parse a fasta header with the following format: db|UniqueIdentifier|EntryName. https://www.uniprot.org/help/fasta-headers Parameters ---------- fasta_header : str A fasta header in the format: d...
c2aac2e94288380646657a9d5c8303b8a5215d12
653,142
def rangify(value): """Return a range around a given number.""" span = 5 min_val = max(value - span, 1) max_val = max(value + span, span * 2) return range(min_val, max_val)
39b4d93b49e90ad2e71723751bb9b49b7dc134ed
653,143
def parse_score_msmarco(output, metric, digits=4): """Function for parsing the output from MS MARCO eval scripts. Currently, the implementation is the same as `parse_score_qa`, but we're keeping separate in case they diverge in the future.""" for line in output.split('\n'): if metric in line: ...
56787c042e5bcd1fb7b2fee872d7bfe27142d2e6
653,144
import requests import shutil import os def _download_file(url, target_path, timeout=10): """Download a file and save it to a folder""" tmpfile = f"{target_path}.incomplete" with requests.get(url, stream=True, timeout=timeout) as response: response.raise_for_status() response.raw.decode_c...
322f47158fccaa23dd603d893a91d88e206a9725
653,146
def read(filename): """Read content of specified test file. :param str filename: Name of file in 'testdata' folder. :return: Content of file :rtype: str """ with open('testdata/' + filename) as f: return f.read()
3d5485021d3a3578485f3b5f3ea59e0badc4a3c7
653,147
def ldexp(x, i): """Return ``x * (2**i)``. This is essentially the inverse of function :func:`frexp`.""" return 0.0
0b9eda2aa440caa7d750508984d3a5cc464b6621
653,150
def num_to_emoji(n): """ Convert number to discord emoji Parameters ---------- n : str string number Returns ------- str discord emoji if valid, False otherwise """ num_emoji_map = { "1": ":one:", "2": ":two:", "3": ":three:", "4": ":four...
1bacf8b2644d40c8ef38a87c0d171a551d1dcc0d
653,152
def is_2numbers(astring): """ (str) -> Boolean returns True if astring has at least two numbers. else return False. >>> is_2numbers('CIS122') True >>> is_2numbers('Ducks') False >>> is_2numbers('ABC-1') False """ digits_ctr = 0 for c in astring: if c.is...
b7ed49e2c0ec59e17d71fdbaf8a500a59b1ea35b
653,153
def value_str_filter(value, *, str_quote="", bool_is_str=False, bool_type=None): """ Convert a value to string that is suitable to be passed to an Backend Internally, this filter use the str() function. :param str_quote: enclosed the given str with this given str_quote :param bool_is_str: whether ...
85c03a69954af69b2317cbdae58e0c0fc31d9d60
653,154
def update_df_chunk(input_stream, dct, key=3): """ Update chunk read from instream into dct dictionary. Parameters ---------- input_stream: stream of dataframes from file dct: output dictionary key: column of input stream dataframes that will be used as dict keys Returns ------- ...
9955b066d4385c093c693910461c83761c37c30b
653,155
from pathlib import Path def run_prediction(predictor, inputs, cleanup_functions): """ Run the predictor on the inputs, and append resulting paths to cleanup functions for removal. """ result = predictor.predict(**inputs) if isinstance(result, Path): cleanup_functions.append(result.unl...
0284523f3a77477757b6236ef3956b451e5bce84
653,156
def num_words(text: str) -> int: """ Counts the number of words using whitespace as delimiter. Args: text: Sentence Returns: Number of words """ return len(text.split())
32b0b6d993772f8a15c3c9c9605c0ebe691fbb1e
653,157
import sys def get_servicedirectory_address(): """ Parse command line arguments Print usage is service directory address is not set. """ if len(sys.argv) != 2: print('Usage : %s qi-service.py directory-address' % sys.argv[0]) print('Assuming service directory address is tcp://127.0.0....
4c5ecffa66f1d211c4eee7a51bc1c4bfec33b730
653,158
def DnsRequestsAndCost(trace): """Returns the number and cost of DNS requests for a trace.""" requests = trace.request_track.GetEvents() requests_with_dns = [r for r in requests if r.timing.dns_start != -1] dns_requests_count = len(requests_with_dns) dns_cost = sum(r.timing.dns_end - r.timing.dns_start ...
a23ede3780b525562cc0abbcc3d9dc723aaaaa01
653,159
def getLine(fname, lnumber): """Jumps to a line number in a file and reads a line. Args: fname (str): path to the input file. lnumber (int): line number. Returns: (str) string containing the contents of the lnumber'th line. """ assert(lnumber > 0), "Error: Invalid line numbe...
a5d02b0148e536c34bf807785c54eb980616dcfa
653,160
def plugin_mount_factory(): """Return a plugin mounter. Copied from http://martyalchin.com/2008/jan/10/simple-plugin-framework/ """ class PluginMount(type): def __init__(cls, name, bases, attrs): if not hasattr(cls, "_plugins"): cls._plugins = {} else: ...
659e9b4454da2eb7b15f1092133bb6844f15ea1d
653,163
def multiply (m1, m2): """ Multiply two matrices. """ m1r = len (m1) m1c = len (m1[0]) m2r = len (m2) m2c = len (m2[0]) rr = m1r rc = m2c assert m1c == m2r, "Matrix multiplication not defined. Invalid dimensions." newRows = [] for i in range (0, rr): newRow...
6e4007cb6e2e348c4c764df52367b88b541d1966
653,165
import shutil def which(program): """Find the program executable Args: program (str): program name Raises: ValueError: Raise if the program isn't found Returns: obj: program executable path """ _executable = shutil.which(program) if not _executable: raise...
c0f920654321bbdfd074d999cb09dc8adeacd4b8
653,166
def import_item(name): """Import and return ``bar`` given the string ``foo.bar``. Calling ``bar = import_item("foo.bar")`` is the functional equivalent of executing the code ``from foo import bar``. Parameters ---------- name : string The fully qualified name of the module/package bein...
23a06089d82023edf7a72628cc7eec89c25473f9
653,167
def delslash(value): """ Remove slash from start and end >>> delslash('/foo/bar/') 'foo/bar' :type str: :rtype: str """ if value.startswith('/'): value = value[1:] if value.endswith('/'): value = value[:-1] return value
edde3a84a1715c5bb3a2f6aa1aca725348a91fa5
653,168
def int2hex(number: int, chars: int = 2) -> str: """ Converts integers to human-readable HEX :param number: integer to convert :param chars: minimal amount of chars(bytes) to show :return: HEX string w/o prefix """ a = hex(number)[2:].upper() chars = max(len(a) // 2, chars) return ('...
9595fb6a4ee3cab58aa99e2e7481ce6defe2f224
653,169
def fit_peak_old(f, x): """ Uses parabola equation to fit to the peak and two surrounding points :param f: :type f: array :param x: index of peak, typically just argmax :type x: :returns: tuple (xindex, yindex) WHERE [type] xindex is... [type] yindex is... """ x1 = x - 1 x2 = x x3 = x + 1 y1 = ...
deaaa7b16cf23baf0f916f39addbd9971f310c6e
653,170
def tuple_incr(t1, idx, val=1): """Return a tuple with the index idx incremented by val""" return t1[:idx] + (t1[idx]+val,) + t1[idx+1:]
bbf7c9d7b669fff5a42e224790b1af9135cce231
653,171
import json def _output_object(name): """Format an object ID as JSON output, for returning from a narr. function. """ return json.dumps({'output': name})
38b3926452b8f3f6e3e2ee5b3204c4507a6b41de
653,172
def script(script_file, **context): """ User-defined script to be loaded into administrative page. :param script_file: location of javascript file (in the service's working directory). Must be a javascript function. :param context: context will be passed to the called script. """ with o...
bef659c1392b9331744759d04f88fc78fc6e339c
653,174
def get_isa_field_name(field): """ Return the name of an ISA field. In case of an ontology reference, returns field['name']. :param field: Field of an ISA Django model :return: String """ if type(field) == dict: return field['name'] return field
79480fb09a1f2a717d1c54472748207b8bf3f6f3
653,176
import torch def nd_cross_entropy_with_logits(logits: torch.Tensor, targets: torch.Tensor, weights: torch.Tensor): """ Multidimensional version of `util.cross_entropy_with_logits`. # Shape: (batch_size, d_1, ..., d_n, num_classes) logi...
4b619cd23d86a60d2a74ae437fc2191a69d2b3d8
653,177
def PM_da_initialized_1d(PM_ds_initialized_1d): """MPI Perfect-model-framework initialized timeseries xr.DataArray.""" return PM_ds_initialized_1d["tos"]
e64171726cbf0ba0c80eeab384af4c0fc49a60dc
653,178
def smooth_series(data, window, method="average"): """Apply a moving average or mean with window of size "window" Arguments: data {Dataframe} -- Pandas dataframe window {int} -- size of window to apply Keyword Arguments: method {str} -- the method applied to smooth the data...
f09b956c0a899de8b8607e08b05bdbc917e473a7
653,179
def adjacent_enemy(inp, rowI, colI, enemy): """Check for enemy in adjacent square""" if any(x[0]==enemy for x in [inp[rowI+1][colI], inp[rowI-1][colI], inp[rowI][colI+1], inp[rowI][colI-1]]): return True return False
1fb36051402d3fef0c4c8b022676bdeb4f121b3a
653,181
def GetTestListPlatformName(): """Returns the name we use to identify the platform in the layout test test list files.""" return "WIN"
9c3cd2b9f6520191a0f91cdc91f2dc2aedb6191a
653,182
def most_frequent_letter(text: str) -> str: """ Return the most frequent letter in lower case as a string. """ l = [] d = {} text = text.lower() for x in text: if x.isalpha() and x not in d: d[x] = d.get(x, 0) + 1 l.append({"name": x, "count": text.count(x...
33e182549ce531a4b1109db3a9d2014fb2ac1b1a
653,183
from typing import Dict def validate_detail(detail: Dict[str, int]) -> bool: """Validates the given detail Parameters ---------- detail : Dict[str, int] The detail to be validated Returns ------- bool True if the detail follows the schema, else False """ detail_ke...
db4e092f57b66fd0035e998c57044919f350205a
653,184
import json def read_json(input_file_path, verbose=False): """ Function reads json file from path and returns list of records :param input_file_path: path to json input file :param verbose: defines if verbose mode :return: list of records """ with open(input_file_path) as json_file: ...
5b1075cc0848c0954d9c5ede4870eddfe0320c81
653,185
def passthrough(result): """Simply return the result.""" return result
3585ed7acf9a259bb497573eb14eca2c72f6e09e
653,187
def score(data_row, positives, negatives, strategy = "+"): """ -- DESCRIPTION -- Implementations of the scoring functions described in the thesis in /docs. This function is designed to be applied row-wise to a pandas dataframe. For example usage refer to the scoring wo...
a6abdb354276b60a6dd48a89d76c71f788834dee
653,188
def build_housenumber(hausnrzahl1, hausnrbuchstabe1, hausnrverbindung1, hausnrzahl2, hausnrbuchstabe2, hausnrbereich): """This function takes all the different single parts of the input file that belong to the house number and combines them into one single string""" hausnr1 = hausnrzahl1 hausnr2 = haus...
81f1f355087021ee15d0afdbcf185afe37f57a02
653,189
def confirm_action(message: str) -> bool: """Basic (Y/n)? wrapper for `input`""" return input(message)[0:1] in "Yy"
6418fa4cbcb78808a6428edd8be7812590e83c18
653,190
import csv import re def getTargetPage(site_id, event_path): """Lookup SITE and PATH to get TARGET""" default_target = None global_target = None request_path = event_path.lower() with open("redirections.csv") as csv_file: fieldnames = ("site_id", "request_path", "target_url") csv_r...
ee3a43ae627f84548391b150befb3a018a78d86d
653,193
def emptycls(): """Create an empty class""" class TestClass: """Test class""" return TestClass
aef7026a249a0aefd757f3f38653dc4b107e2076
653,194
def shrink_parameters(model, ratio): """ Shrink all parameters of a model to a certain ratio :param model: type nn.Module :param ratio: type float :return: """ model_dict = model.state_dict() for i in model_dict: model_dict[i] *= ratio model.load_state_dict(model_dict) re...
ba1cfa8f5ebcc51ea975e7612063b93a9748f7d3
653,195
def split_df(df, columns_split): """Split a dataframe into two by column. Args: df (pandas dataframe): input dataframe to split. columns_split (int): Column at which to split the dataframes. Returns: df1, df2 (pandas dataframes): Split df into two dataframe based on column. The first has the fir...
37aee5783680f6827891c737c9a4ffb9bba89b27
653,196
def render_region(context, regions, region, **kwargs): """ Render a single region. See :class:`~feincms3.renderer.Regions` for additional details. Any and all keyword arguments are forwarded to the ``render`` method of the ``Regions`` instance. Usage:: {% render_region regions "main" %} ...
e7dd5154adcb430d0718a6b40bd5151d7b636154
653,197
def _cli_bytes_from_str(text): """ Python 2/3 compatibility function to ensure that what is sent on the command line is converted into bytes. In Python 2 this is a no-op. """ if isinstance(text, bytes): return text else: return text.encode("utf-8", errors="surrogateescape")
e710819cb60ccfcdcd0a840c20c19882fec709ea
653,198
def remove_empty_lines(txt): """ replace("\n\n", "\n") does not work in cases with more than two empty consective empty lines """ return "\n".join(t for t in txt.splitlines() if t.strip())
8f5a98ece086848fc8bc511918acc7d4c746c68e
653,199
def convertToBase10(numList, base): """ Parses numList and returns the total base 10 value in the list. """ negative = False # If numList contains a negative, then remove it... # and indicate it is negative so the algorithm can continue. if numList[0] == '-': numList.remove('-') negative = True numList ...
b4e15e1ce28c86d45c6093e14211a6fb97058c2c
653,200
import re def getVarList(strLine): """this function takes a string in the format 'i{Am}AString{With}Variables' and parse it for included var entries '{.+}'. The return of the function in case of the example would be: ('Am','With') """ result = [] if strLine is None: return result ...
e4fc66b2af3b5ab3f9ff0e540ed33c9ae0ce9f88
653,201
import itertools def get_all_comb(array, r=None): """ Get all combinations of items in the given array Specifically used for generating variant combination Parameters ---------- array: 1D array. input array r: int. The number of items in a combination Returns ------- result: List...
9c0ec4aeb76abf8339a7bcee5741ca39203f711a
653,202
def format_url(category: str, year: int, month: str, day: str) -> str: """ It returns a URL from The Guardian website with links for the articles of the given date and category :param category: A String representing the category :param year: An integer representing the year :param month: A Str...
5e385659b70efea2117c8b3e5a2534448c446b63
653,203
import os def unique_file(default_name, mode=0o777): """Safely finds a unique file for writing only (by default). :param str default_name: Default file name :param int mode: File mode :return: tuple of file object and file name """ count = 1 f_parsed = os.path.splitext(default_name) ...
9b419fdbbb624d812f6d67ac70977ad3a6602017
653,204
def patch_string_from_method(method: str) -> str: """Get the string that indicates the method to be patched for a calling method.""" switch_dict = { "get": "tentaclio_gs.clients.GSClient._get", "put": "tentaclio_gs.clients.GSClient._put", "remove": "tentaclio_gs.clients.GSClient._remove"...
2ed1ccda154ad7f6ae1dfbad514b2a49eb5ec6c2
653,206
import inspect def iscoroutinefunction(func: object) -> bool: """ Return True if func is a coroutine function (a function defined with async def syntax, and doesn't contain yield), or a function decorated with @asyncio.coroutine. Note: copied and modified from Python 3.5's builtin couroutines.py ...
f392967e86bf233706a7a6a0a8b8fbdafe85f78f
653,207
def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ result_list = [] for idx in range(len(list1)): if idx == 0: result_list.ap...
5c2bcb13e0ee24df6711323d6d0d83f7bb2343b0
653,208
from datetime import datetime def time_to_resolve(time_received, time_resolved): """Returns the time taken to resolve an issue. Args: time_received (datetime): Datetime showing when ticket was received. time_resolved (datetime): Datetime showing when ticket was received. Returns: ...
8f0b17a2ca27b57dd7187fea5accd06452087035
653,209
import argparse def parse_args(): """ Parse command line arguments """ parser = argparse.ArgumentParser() parser.add_argument( "inifile", help="INI File [section] to dump", ) parser.add_argument( "section", help="INI File [section] to dump", ) parser.add_arg...
4a3412721b1b177a54b541057ac504de9b5155c6
653,211
def count_spaces(line): """ Counting the spaces at the start of a line """ return len(line)-len(line.lstrip(' '))
653fb273de0f89229d777d4baaa2a551908e97c4
653,212
def search_node_from_coord(x, y, nodes): """Get node's number from coordinates""" return int(nodes.loc[(nodes['x'] == x) & (nodes['y'] == y)]['n'])
e61bb8351bbad871254a29fc0586da3a0fda0b24
653,213
def data_section(values): """ >>> data_section(range(0, 260)) '0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,...
f7449bbcffed64c24c394abcf60b2d7334524f25
653,214
def to_data(x, name_to_dim=None, **kwargs): """ Extract a python object from a :class:`Funsor`. Raises a ``ValueError`` if free variables remain or if the funsor is lazy. :param x: An object, possibly a :class:`Funsor`. :param OrderedDict name_to_dim: An optional inputs hint. :return: A non-fu...
34d1249a175eb7bb7c3487f6478c7d2939fa8cc3
653,215
def compare_dicts(dict_a, dict_b, excluded_keys=None): """Compare two dict with same keys, with optional keys to exclude from compare""" if excluded_keys is None: excluded_keys = [] return all(dict_a[k] == dict_b[k] for k in dict_a if k not in excluded_keys)
f376c1470cafe2943a0413aaa83aff8c47180f13
653,216
import torch def boxes_to_cornels(box_xy, box_wh): """Convert boxes from x_center,y_center, width, height to x_min, y_min, x_max, ymax Parameters ---------- box_xy : torch.Tensor Predicted xy value shape [batch_size, num_anchors, 2, conv_height, conv_width] box_wh : torch.Tensor ...
cc866e198012555a45ff6686fe8f5b9c787a3304
653,217
def json_default_repr(obj): """Converts an object into a suitable representation for JSON-ification. If obj is an object, this returns a dict with all properties not beginning in '_'. Otherwise, the original object is returned. """ if isinstance(obj, object): return {k: v for k, v in obj.__dict__.ite...
a9e57daa5fe2d6f4a0ece792b04b63eb10804915
653,218
import statistics def to_z_score (scores): """la fonction qui transforme les scores DA ou BLEU en z-scores pour comparer ensuite aux scores BLEU cela fonctionne pour une direction prend en arguments une liste de scores pour une direction ARGS: scores:list """ mean = statistics.mean(scores) standart_dev = sta...
db4e5900f80c19c82bac067c633a1b08c2370fde
653,219
from datetime import datetime import pytz def is_usa_dst(): """ Determine whether or not Daylight Savings Time (DST) is currently in effect for the US - EST is alright as all states are in or out """ first = datetime(datetime.now().year, 1, 1, 0, 0, 0, tzinfo=pytz.timezone('U...
dfb6620a6b5e7d3443edfd0e92636b3d44d832d8
653,220
def get_col_encryption_type(col_name, integrity_info): """ Returns type based on whether the column is encrypted as number (OPE) or symmetrically (Fernet) or asymmetrically (ABE)- this is based on "type" attribute in TinyDB :param integrity_info: { 'device_data': { 'added': {...
3d5d03bcb46433b35fb170768ac8b2310e5437ad
653,222
import re def remove_comments(text): """ Removes inline and general comments (indicated with %), while keeping literal % Also removes training whitespaces :param text : latex file content :type text : str :return : content without comments :rtype : str """ no_comments = [] ...
74a4af905ed075fbc6ad7ce9c26e7912bdde3a2e
653,223
def cmp(lhs, rhs): """cmp function not in py3. >>> cmp(1, 2) -1 >>> cmp(2, 1) 1 >>> cmp(1, 1) 0 """ return (lhs > rhs) - (lhs < rhs)
27db104361406dc8af884fd7a640a25b26659f01
653,224
def get_versions(args): """ Extract versions from the webpage/v directory, which should each contain a manuscript. """ versions = {x.name for x in args.versions_directory.iterdir() if x.is_dir()} versions -= {"freeze", "latest"} versions = sorted(versions) return versions
65eb544518dafe4b4ff88723fa4555dc9323b1a2
653,225
def _interpolate_crop(start: complex, stop: complex, loc: float, axis: int) -> complex: """Interpolate between two points at a given coordinates.""" start_dim, stop_dim = (start.real, stop.real) if axis == 0 else (start.imag, stop.imag) diff = stop_dim - start_dim if diff == 0: raise ValueErro...
3d26955948ce44b752957099b9b81b8f7c302d29
653,226
def make_fispact_material(mat): """ Returns a Fispact material card for the material. This contains the required keywords (DENSITY and FUEL) and the number of atoms of each isotope in the material for the given volume. The Material.volume_in_cm3 must be set to use this method. See the Fispact FUEL k...
013fc761743bef6564e9f5a23aa36474a4bd8246
653,227
import torch def default_local_world_size(): """ If CUDA is available, returns the number of GPU devices on the host. Otherwise returns 1. """ if torch.cuda.is_available(): return torch.cuda.device_count() else: return 1
f9c382e8f1efc5203b47f88839d81ef3f65e064f
653,228
def get_meta_description(content_section): """ Returns a meta description based on the parent section """ if content_section == 'help': return 'Learn how individuals and groups can be active in federal elections. The new fec.gov organizes reporting and compliance guidance by the type of committe...
104395c48d8001599922f2cd40215f9b9cede548
653,230
import torch def instance_norm(x, eps=1e-8): """Instance normalization. """ assert len(x.shape) == 4, "shape of input should be NCHW!" x -= torch.mean(x, dim=(2, 3), keepdim=True) return x * torch.rsqrt(torch.mean(x ** 2, dim=(2, 3), keepdim=True) + eps)
6ad69aaa743f9ddfe43c7d1d4c5c65e850b85c1a
653,231
from typing import Dict def check_keystore_json(jsondata: Dict) -> bool: """ Check if ``jsondata`` has the structure of a keystore file version 3. Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters. Copied from https://github.com/vbuterin/pybitcointools Ar...
d4b0b57b55bcaad3f4fb42a53977df0d95973579
653,232
def check_codeblock(block, lang="python"): """ Cleans the found codeblock and checks if the proglang is correct. Returns an empty string if the codeblock is deemed invalid. Arguments: block: the code block to analyse lang: if not None, the language that is assigned to the codeblock ...
3e65ed5864e96b1936bc17c3769d4c524ae7b188
653,233
def build_tree(items): """ This function takes a Python list of items and turns it into a binary tree of the items, suitable for casting to an s-expression. """ size = len(items) if size == 0: return [] if size == 1: return items[0] half_size = size >> 1 left = build_...
ec38846804a942e25d92cb77cf9e42ed91e963d6
653,234
def inject_globals(): """Available in each path""" return { 'title': 'Audio Alignment', }
cda63bc812c19582ac49bada9aac260ca325e5fb
653,235
import argparse from typing import List def get_args_subset(args: argparse.ArgumentParser, args_subset: List[str]): """ Return an argument subset or an ArgumentParser instance. Args: args (argparse.ArgumentParser): An instance of ArgumentParser. args_subset (List[str]): ...
e81a2b4f485c29d1a55e33093d6c2256cdc3572f
653,236
def compute_accuracy(outputs, y, tokenizer): """Compute model accuracy given predictions and targets. Used in validation. """ # Do not include BOS token target_tokens = y[:, 1:] predicted_tokens = outputs.max(dim=-1)[1][:, :-1] acc = (predicted_tokens == target_tokens).sum(dim=1) == target_token...
f9805d46102285d4ae2b60cd896025989777a432
653,238
def get_depth_fn(depth_multipler, min_depth): """Builds a callable to compute depth (output channels) of conv filters. Args: depth_multiplier: a multiplier for the nominal depth. min_depth: a lower bound on the depth of filters. Returns: A callable that takes in a nominal depth and...
523b6db58096a64e93e4fa29ee989bff2a7bfda9
653,240
def acceleration(force, mass): """ Calculates the acceleration through force devided by mass. @param force: force as a vector @param mass: mass as a numeric value. This should be not 0. @return: acc the acceleration >>> acceleration(300, 30) 10.0 """ #print "mass: ", mass #p...
6e093d9a8dc133701196b99d70a265ff6923542a
653,241
def uniform_t_sequence(steps: int): """ Creates a sequence of t parameters whose values are equally spaced and go from 0 to 1 using the given number of steps. :param steps: number of steps :return: sequence of t values """ return [t / steps for t in range(steps + 1)]
0e94d2e2488271d5f67196fdf4eda9b2ae57974c
653,242
def _validate_not_subset(of, allow_none=False): """ Create validator to check if an attribute is not a subset of ``of``. Parameters ---------- of: str Attribute name that the subject under validation should not be a subset of. Returns ------- validator: Callable Validat...
8b43d44e763f0d11b4a5b4f665d8b27f69291d3b
653,243
import random import string def random_char_sequence(y: int) -> str: """Creates a random char sequence of length y for the job_id name randomization""" return "".join(random.choice(string.ascii_letters) for x in range(y))
39c9bccbe0ab5787b2db557cbc6c3444620861ff
653,244
def _shift_required(tiles): """Determine if distance over antimeridian is shorter than normal distance.""" if tiles[0][0].tile_pyramid.is_global: # get set of tile columns tile_cols = sorted(list(set([t[0].col for t in tiles]))) # if tile columns are an unbroken sequence, tiles are conne...
d204469bd896f1ea9016e983bac0c2d98f9953be
653,245
import copy def copy_miscellanious(misc): """ Returns a deepcopy of an object """ return copy.deepcopy(misc)
745b13d271324c334db07bbfccd0be4059e29fca
653,246
def join(*paths): """ Joins multiple paths into a single path. Arguments: *paths -- path components """ path = "" for component in paths: path += ("/" if path and not path.endswith("/") else "") + component.replace( "\\", "/" ) return path
68b41d4efdf1979347e56b69dc7eb30fc77ae875
653,247
import os def get_cache_dir(cache_id: str, create: bool = False) -> str: """ Get cache dir. Honors $XDG_CACHE_HOME, but fallbacks to $HOME/.cache Args: cache_id [str]: directory under CACHE that will be used create [bool]: create directory if not exists Return path to cache_directory """ ...
4aeb575479e1bbbfe14007c29b7390032ed8d51b
653,249
def parse_egg_dirname(dn): """ Extrahiere die folgenden Informationen aus dem Namen: - den Paketnamen - die Versionsangabe - das Python-Versionstupel >>> parse_egg_dirname('visaplan.tools-1.0-py2.7.egg') ('visaplan.tools', '1.0', (2, 7)) Sonstige Namen werden nicht erkannt: >>> pa...
26552089764c43144f7dd9e367e21aeced4c3681
653,250
def client(app): """用于调用由 app 固件创建的应用 对象""" return app.test_client()
845cd410948bebe750fef81b9ebf708e720bdbaa
653,251
def percentDifference(new,old): """ Parameters ---------- new : float New value being compared old : float Old value being reference for change Returns ------- Float Difference bewteen new and old in percent. """ return (abs(new-old)/abs(old))*100
b268bfb41edc1ebf435811f8e227d77c03591a7b
653,252
def _serialize_time(val): """Create a JSON encodable value of a time object.""" return val.isoformat()
648d71ab4d23dcba787751591160286223e34bda
653,253