content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def listNorm(list1, list2): """ RETIRED, used in tests input two lists of tensors of same length convert/vectorize the tensors in each list compute their 2-norm :param list1: [K1, K2, K3,....] where Ki is a tensor :param list2: [A1, A2, A3,....] where Ai is a tensor :re...
8e67a34f3ee94d1d5bf359a386ad014715bef62a
652,120
def objects(obj_list): """Helper to return singular or plural of the word "object". Parameters: obj_list - any list Returns: string "object" or "objects" depending on the list length """ ret = 'objects' if len(obj_list) != 1 else 'object' return ret
5780624618de4abafaff321315d89c25d21cb6ae
652,121
import pandas as pd def load_df(name, engine='pickle', key='df', **kwargs): """Load a dataframe from disk. """ func = "read_{}".format(engine) if engine == 'hdf': kwargs['key'] = key return getattr(pd, func)(name)
fd63f547e621a16cf29bdd31afa3cf7f0f98cf0e
652,122
import numpy def particle_counter_box(positions, counter_shape=None, counter_position=None): """Return number of particles in observation box over time. Also return the indices of particles that were counted. """ dimensions = positions.shape[-1] if counter_shape is None: counter_shape = ...
58fe7a5c1970f32d308f68e5dd75f7992ad1508f
652,123
def write_rex_file(bytes, path: str): """Write to disk a rexfile from its binary format""" new_file = open(path + ".rex", "wb") new_file.write(bytes) return True
4dccd6cc2dfe2fcfe7065b829803d325b4fcdfcb
652,124
def write_gao_weber_potential(parameters): """Write gao-weber potential file from parameters Parameters ---------- parameters: dict keys are tuple of elements with the values being the parameters length 14 """ lines = [] for (e1, e2, e3), params in parameters.items(): if ...
b65ceae808991cbe7a995f1dcf994d55c50ce9af
652,125
def symbol_filename(name): """Adapt the name of a symbol to be suitable for use as a filename.""" return name.replace("::", "__")
e26966e133874c5704aa7232b4abb27d2ed286e7
652,127
import argparse def parse_args(): """Parses arguments.""" parser = argparse.ArgumentParser(description='Compute hdff file from recarray.') parser.add_argument('--inputfilename', type=str, help='Name of the input rearray numpy datafile.', required=True) parser.add_argument('--outputfilename', type=str,...
3e08a93e15b7471a5cbdfe8fee753e4e1a1a41b6
652,129
def euler_criterion(a, p): """p is odd prime, a is positive integer. Euler's Criterion will check if a is a quadratic residue mod p. If yes, returns True. If a is a non-residue mod p, then False""" return pow(a, (p - 1) // 2, p) == 1
bed5820ba39bbd11ada039ea2846fabf87a1b931
652,130
def viz_b(body): """Create HTML b for graphviz""" return '<B>{}</B>'.format(body)
3dfdf329977826b5ed791f1896538dacc18a041f
652,131
def op_table_md(op_sel, op_name, L1, L2): """Generate this (ish): | 6'h00 | add | a+b+d |(a+b+d) gte 2^16 | Addition | | 6'h01 | sub | a+~b+1 |(a+~b+1) gte 2^16 | Subtraction | | 6'h03 | abs |(a lt 0)? (0-a) : a | a[15] | Abso...
86525efc68baf2a0f8046a504fef430e07c05e08
652,132
def remove_tails(data, t=15): """remove the timeseries having at least "t" zero values Arguments: data {Dataframe} -- Pandas dataframe Keyword Arguments: t {int} -- the threshold number of zeros to consider to remove a series (default: {15}) Returns: Dataframe -- C...
9ddd9c70e0b1ae63c082ae4062f75c6c90918c60
652,134
def _logpdf_row(view, targets, cluster): """Return joint density of the targets in a fixed cluster.""" return sum( view.dims[c].logpdf(None, {c:x}, None, {view.outputs[0]: cluster}) for c, x in targets.iteritems() )
29d5beb35de73fa76c06ecb6aa3772eaba52024c
652,135
def _unscale(x,rmin,rmax,smin,smax): """ Undo linear scaling. """ r = (smax-smin)/(rmax-rmin) x_ = smin + r * (x-rmin) return x_
bddba9da51c2b6a20f47d09bfc214989e6d6fb71
652,136
def _escape_filename(filename): """Escape filenames with spaces by adding quotes (PRIVATE). Note this will not add quotes if they are already included: >>> print _escape_filename('example with spaces') "example with spaces" >>> print _escape_filename('"example with spaces"') "example with ...
a27f4b1c9d5b8ad971a4e76441c6f30f05a86395
652,137
import numpy def calculate_noise_blockvisibility(bandwidth, int_time, diameter, t_sys, eta): """Calculate noise rms per visibility :param bandwidth: (Hz) :param int_time: Integration time (s) :param diameter: Diameter (m) :param t_sys: (K) :param eta: Efficiency :returns: Sigma [nrows, nc...
e88dc568405388bec3357a0663892f0859ff6083
652,138
import os def psnrFileAnalysis(psnrFilePath): """ 读取psnr文件,识别psnr&mse的值 Args: psnrFile: psnr文件 Returns: None """ # psnrFilePath = '/Users/zhangyu57/Downloads/psnr.log.1' if not os.path.exists(psnrFilePath): return pic_x_list = [] mse_avg_list = [] mse_y_...
c586d5e44d35f1b42e433eb9a5864260f2bb3391
652,140
def dimacs_file_to_cnf(file_path): """ Load a cnf from a dimacs file Parameters ---------- file_path :string Path of the file that contains the cnf wirtten in dimacs format Returns ------- list[set[(string,bool)]] The object that represents t...
56653d646cc2e54d25d2340d05b4f62969ea1b9d
652,141
def check_upgrades_link_back(item_id, all_items_data): """Every upgrade this item can build into should list this item as a component. Return a list with the errors encountered.""" item_data = all_items_data[item_id] if 'into' not in item_data: return [] errors = [] upgrades = item...
b677e18be25dfb585dd866fe9dde850eeeccc7fb
652,142
import os def change_filename(filename): """ Generate new filename to avoid overwriting an existing file change: ``path/to/file.fits`` into : ``path/to/file.astrom.fits`` Parameters ---------- filename: str The full path to the file which is to be changed Returns -------...
40cfd1f46a933527eca42b5bf044c4d607705b09
652,143
import os def DataDir(): """Returns the path to the data dir chrome/test/data.""" return os.path.normpath( os.path.join(os.path.dirname(__file__), os.pardir, "data"))
06beadb46d3888ff89a18a89dc14d11a3b1e4667
652,144
def validate_instructions(instructions, _): """Check that the instructions dict contains the necessary keywords""" instructions_dict = instructions.get_dict() retrieve_files = instructions_dict.get('retrieve_files', None) if retrieve_files is None: errmsg = ( '\n\n' 'no...
0b30579a633d6953c8cec5ac7a05cddef7e7d1df
652,146
import logging def get_loglevel_from_name(name_or_int): """ converts a logging level name to the numeric representation """ # see whether it is already an integer if isinstance(name_or_int, int): return name_or_int # convert it from the name level = logging.getLevelName(name_or_int.up...
b4d5e677d687cfcbf83eaee45845cdb3498b5d41
652,147
import os import requests def get_aqi_rate(city:str, state:str): """ Parameters: city: Name of city in US state: Two-letter abbreviation of state """ openweather_key =os.getenv("openweathermap_api") requ = requests.get(f"http://api.openweathermap.org/geo/1.0/direct?q={city},{state},USA&limit={1}&app...
2f9b9019d62fddde74019c9429d039ba0c40c04f
652,148
from typing import Optional from datetime import datetime def from_litter_robot_timestamp( timestamp: Optional[str], ) -> Optional[datetime]: """Construct a UTC offset-aware datetime from a Litter-Robot API timestamp. Litter-Robot timestamps are in the format `YYYY-MM-DDTHH:MM:SS.ffffff`, so to get t...
a0b82c9d7a1b44ba4779efbe847cee4bad28e2e3
652,149
def calculate_score(move): """ Calculate the chance of this being a "good move" based on the following criteria: :moves_available: number of moves to choose between\n :move_num: how many moves we are into the game\n :num_pieces_self: how many pieces pieces we have left\n :num_pieces_opp: how ma...
a7aa720c47aba65115ee96e840bdbda6ccb1f67a
652,150
import argparse def get_args(): """Command line argument parsing""" parser = argparse.ArgumentParser() parser.add_argument("--security-code", "-s", type=str, required=True, help="reMarkable security code. Get one here: https://my.re...
ac4511d237104262e6f39b83a49ad0dbe2d30fcc
652,151
def upload_path(instance, filename): """Return path to save FileBackup.file backups.""" return f'examiner/FileBackup/' + filename
361e31f8618eb4476883f1c9bfe3a0dcdfe47d2c
652,152
def is_palindrome(number): """Check if number is the same when read forwards and backwards.""" if str(number) == str(number)[::-1]: return True return False
7ce67718a2e7ba0a1d9e276cd35b8d1b4c0e58cd
652,154
import os def pathjoin(*args): """Safe wrapper for os.path.join: asserts that all but the first argument are relative paths.""" for seg in args[1:]: assert seg[0] != "/" return os.path.join(*args)
2927b455023cfa5c6cc01cef9a4a5eb24bdcc252
652,155
def solution(array): """Returns the first ten digits of the sum of the array elements. >>> import os >>> sum = 0 >>> array = [] >>> with open(os.path.dirname(__file__) + "/num.txt","r") as f: ... for line in f: ... array.append(int(line)) ... >>> solution(array) '553...
6305c64263e65d8a8ccfe23af9d00f5cbd50dec6
652,156
def get_planet_and_moons_list(): """Return a list of valid JPL HORIZONS targets. The JPL HORIZONS interface accepts a strict set of target names. In order to NOTE: This is only here to support get_mtarg below. Once Wally merges his branch, uncomment the import from build_masters_finder_table abo...
cf1dc4fc66936a0fdbbe90b219d9658a16194e10
652,157
from typing import Any def safe_getattr(value: object, attr: str, default: object) -> Any: """Whether this value has the given attribute, ignoring exceptions.""" try: return getattr(value, attr) except Exception: return default
77622cd3cb136d94f06aff54a5c4eedfbd53ad3d
652,159
import torch def seq_mask(seq_len, max_len): """Create sequence mask. :param seq_len: list of int, the lengths of sequences in a batch. :param max_len: int, the maximum sequence length in a batch. :return mask: torch.LongTensor, [batch_size, max_len] """ mask = [torch.ge(torch.LongTensor(seq...
18ed8032ecf8c1fb80faebde9e0561e731698867
652,160
def convertAttributeProto(onnx_arg): """ Convert an ONNX AttributeProto into an appropriate Python object for the type. NB: Tensor attribute gets returned as the straight proto. """ if onnx_arg.HasField('f'): return onnx_arg.f elif onnx_arg.HasField('i'): return onnx_arg.i ...
e0a5b9629871a947714b81ca0a2527eb6458e4da
652,161
from pathlib import Path def print_path(path: Path) -> str: """ Stringify path as relative to cwd if possible. """ if path.is_absolute(): try: path = path.relative_to(Path.cwd()) except ValueError: return path.as_posix() if len(path.parts) == 0: retu...
f8e62e912fe88efc3d29df935a4febe9690b619f
652,163
def _lum(_c): """ :param c: x by x by 3 matrix of rgb color components of pixels :return: x by x by 3 matrix of luminosity of pixels """ return (_c[:, :, 0] * 0.299) + (_c[:, :, 1] * 0.587) + (_c[:, :, 2] * 0.114)
c2c3b8597a5ca90cef63fc1691412b7f2695b506
652,164
def query_humanize(str,fieldname,table,is_string=True): """ busca en 'str' un asignacion del campo 'fieldname' para cambiarlo por el format de la 'table' y con el is_string = True tiene en cuenta que sea un cadena """ sep='"' if is_string else ' ' strout=str fieldname0=fieldname+"="+sep ...
1a713a7479679cb01c3642084ea54cf5160bc970
652,165
import torch def roll_n(X: torch.Tensor, axis: int, n: int) -> torch.Tensor: """Inputs: X: tensor of shape nxhxw, this is the n different real components of the fourier transforms of the image of size hxw axis: axis n: shift amount """ f_idx = tuple( slice(None, None, None) if i !...
360ad9d843b50f49588af24981eb2399d6aa9c43
652,166
import gzip import bz2 import lzma def open_file(filename: str, mode='r', encoding=None): """Get the file extension and process the file based on the file extension Else, open the file using the provided encoding spec or just do ASCII-based read WARNING: This code DO NOT check if the provided mode an...
f5565eaeb17b364297d7c3a6cebfac607ab68526
652,168
import subprocess def get_pip_pkgs(pkg_list): """Returns a dictionary in which each key is the name of a pip-installed package and the corresponding value is the package's version. Instead of using: `pip show pkg | grep Version | awk '{print $2}'` to get each package's version, we save the output of `...
6709b69c79773ff6e0001637d44b8775741f2639
652,169
def simple_goal_subtract(goal, achieved_goal): """ We subtract the achieved goal from the desired one to see how much we are still far from the desired position """ assert goal.shape == achieved_goal.shape return goal - achieved_goal
bf35fa91fa848f070c813ba2313891672f005de9
652,170
import functools def _any_to_refid(f): """Transform a method that takes a refid into one that takes a character "r" or "t" and either a refid or a target.""" @functools.wraps(f) def _f(self, line): try: type, refid_or_target, *extra = line.split() except ValueError: ...
2f8b6eeb569e79711e7c2d0e792d968b4896d95f
652,171
def wavelength_nm_from_energy_ev(E_eV=6000) : """Returns wavelength in nm, evaluated from photon energy in eV (1Angstroms = 10**-10m) E=h*v = h*c/lambda 6keV approx. = 2A """ #h/2pi = 6.58211928e-16 # eV*s (PDG 2014) reduced Planck constant #h = 2 * math.pi * h/2pi # Planck constant...
e73972d324a64c4f13e379806e4d5947aa9cea21
652,172
from typing import Optional from datetime import datetime def determine_vaccine_date(vaccine_year: str, vaccine_month: str) -> Optional[str]: """ Determine date of vaccination and return in datetime format as YYYY or YYYY-MM """ if vaccine_year == '' or vaccine_year == 'Do not know': retur...
bec792faf0312ab5a7691af69b55b76a1f162267
652,173
def has_kanji_and_kana(word_reading): """Returns True if there is both kanji and kana in the word reading. Args: word_reading: A dict that might have a 'word' or 'reading' key. Returns: True if 'word' and 'reading' are keys in the dict. """ return 'word' in word_reading and 'reading'...
95e197e4227c5f5ca9430071bd1e6943d612c264
652,174
import torch def renormalize(log_p, alpha): """ Take the model-computed log probabilities over candidates (log_p), apply a smoothing parameter (alpha), and renormalize to a q distribution such that the probabilities of candidates sum to 1. Return the log of q. """ alpha_log_p = alpha * log_p ...
54a1a215ad9c0442f3a7d9006dfe795d0ea05716
652,175
def format_table(table, key_space=5): """ Accepts a dict of {string: string} and returns a string of the dict formatted into a table """ longest = 0 for k in table: if len(k) > longest: longest = len(k) result = '' for k, v in table.iteritems(): k += (longest...
8c7966434e07992ad4c32fbadcc79df0206bb1ec
652,176
def Altitude(altitude, velocity, i): """Returns the altitude at timestep i. Args: altitude (float): Altitude calculated at timestep i-1 velocity (float): From rocket.Velocity(), The Instantaneous velocity of the rocket i (int): Iterator used for Euler's method Returns: altitu...
ae7f80c0530cd353f55a78d554aa0e70a21f8d8a
652,177
def swap_and_flatten01(arr): """ swap and then flatten axes 0 and 1 """ if arr is None: return arr s = arr.shape return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
5861ee2df79c285a57920f67ec015861168c7b79
652,178
import json def loads(s): """Potentially remove UTF-8 BOM and call json.loads()""" if s and isinstance(s, str) and s[:3] == '\xef\xbb\xbf': s = s[3:] return json.loads(s)
95e403745c9738711813cf5ce2d23e54f290de0e
652,179
import torch def check_tensorboard(net, writer, step, step_size=30, saved_layers=None): """ recursively record Parameters ---------- net: pytorch nn model, GNN network writer: tensorboardx writer step: int, current step index step_size: int, interval size for the tensorboard writer ...
b8ced2c9d10538c6894376892be8f5c21169b1b7
652,180
def query_hash(query_url): """ Generate a compact identifier from a query URL. This idenifier is then used for @ids of Ranges and Annotations. IIIF URI pattern: {scheme}://{host}/{prefix}/{identifier}/range/{name} {scheme}://{host}/{prefix}/{identifier}/annotation/{name} ...
16932924ef50437fd09b65afa6244645ae603d9e
652,182
import json def get_dataset_metadata(dataset_path: str): """ Many datasets outputted by the sklearn bot have a first comment line with important meta-data """ with open(dataset_path) as fp: first_line = fp.readline() if first_line[0] != '%': raise ValueError('arff data ...
2f0b2de4812ae1918ef3cc4bb677cdc8319a74dd
652,184
def _get_metric_value(metrics, metric_name, sample_name, labels): """Get value for sample of a metric""" for metric in metrics: if metric.name == metric_name: for sample in metric.samples: if sample.name == sample_name and sample.labels == labels: return s...
09cd422a4a536170004261ee1c5603eb1dff95ed
652,185
def getStripes(stages, stretchesV): """Infer horizontal stripes from a set of vertical bars. A vertical bar defines a stripe on the page, i.e. a horizontal band that contains that bar. Between the vertical bars there are also stripes, they are undivided stripes. We assume the vertical bars split ...
119b313d5f727fd8ec1c257384c9090094d08da9
652,186
def tf(tokens): """ Compute TF Args: tokens (list of str): input list of tokens from tokenize Returns: dictionary: a dictionary of tokens to its TF values """ d = {} s = len(tokens) for w in tokens: if w not in d: d[w] = 1.00/s else: d...
c427fd282dd04624e7fbceed764116146e6c64ae
652,187
def prepareNameSuffix(results): """Parse and prepare name_suffix based on results.""" counts = {'country_code': [], 'city': [], 'name': []} # Separate different country codes for row in results: for field in counts.keys(): if field not in row: continue if...
aae43a981a719f1e2cf9bee42b4926f0e2fe16de
652,188
def handle_replace_if_row_null(df, col_name): """ Handles blank to zero conversion for rows which are null for a given scale. """ for i, row in df.iterrows(): # If all column values are empty for this row, then leave it all null if sum(row.isnull()) == len(row): continue ...
29c4eab4866a888b26ebd8f4648b66e85962d46c
652,189
from pathlib import Path import os from datetime import datetime def create_logging_dir(name: str) -> Path: """Create a directory for writing logs to. Defaults to ~/logs/compiler_gym base directory, set $COMPILER_GYM_LOGS=/path/to/dir to override this. Usage: >>> create_logging_dir("my_scrip...
bac7bc55021696687c66d4be84e5a782613965ad
652,190
def read_jpg(filename): """ Read jpg or jpeg files data. Args: filename (string): filename with .jpg or .jpeg extention. Returns: [tupple]: Width,Height,Image data. """ width = int() height = int() img = list() return width,height,img
c9b5477060b29f2998495f9e3c7c10a56451614c
652,191
def find_range(nums): """Calculate the range of a given set of numbers.""" lowest = min(nums) highest = max(nums) r = highest - lowest return lowest, highest, r
0fc6275517e804a2eac018ee8474b6cddee8f898
652,192
from typing import Tuple from typing import List from typing import Dict import os def find_classes(dir: str) -> Tuple[List[str], Dict[str, int]]: """ Finds the class folders in a dataset. Args: dir (string): Root directory path. Returns: tuple: (classes, class_to_idx) where classes ...
cfb448665a90f70182c0f5547f1277d812c075d1
652,193
from sys import stdin def readarray(typ): """ function to read an array """ return list(map(typ, stdin.readline().split()))
e57cf7c0ec64ff5fe87d7ef19433a9fe0f2dd5c5
652,194
def remove_initative(brawl): """ Removes initative from brawl """ # remove the initative key from monsters monsters = [ {k: v for k, v in m.items() if k not in {'initiative'}} for m in brawl ] # update brawl's monster list brawl = monsters # return modified bra...
f80d1b595c3d79401759789025b4297aa3f1fd3f
652,195
def get_bit_elements(vector, bit, value): """Return a list with the elements of vector that has bit with value.""" subvector = [] found = 0 max_found = len(vector)//2 for i in range(len(vector)): bin_i_rev = ("{:0" + str(2**bit) + "b}").format(i)[::-1] if int(bin_i_rev[bit]) == value...
5cefee242ac2336bf5138590524d13aba53be9ea
652,196
def work_up_string(work_str): """ Переводит plain-text в html Делает: - удаляет пробелы; - удаляет начальный символ \\n; - заменяет символы \\n на теги </br> - заменяет символы </ на &lt;&frasl; - заменяет символы < на &lt; - заменяет символы > на &gt; для того, чтобы в текст мо...
a5213bf3c692347bff81cd53801978dbc0de2a7b
652,197
import os def checkout_base(): """Return the base destination path. Note that this assumes you're running the tool from a Subversion checkout (or that your filesystem layout is the same as our repository).""" return os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..", "..") ...
b61700536410dae3dbd161693ff1fe6c7f0af786
652,198
def division_euclidienne_decimale(a, b): """renvoie le quotient et le reste de la division euclidiennede a par b""" q = 0 while a > b: n = 0 while 10 ** n * b <= a: n += 1 n -= 1 c = 0 while c * 10 ** n * b <= a: c += 1 c -= 1 q...
360a7d3b3ffd88cdf4cb70228bec0023f1ffcae7
652,199
def distance_calculator(focal_length, real_width_of_object, width_in_frame): """ This function is used to calculate the estimated distnace using triangle similarity :param1 (focal_length): The focal_length in the reference image as calculated :param2 (real_width_of_object): The real width of the ob...
8ca86eaba6eaaaa429c162b93a5ad95d2d46ec49
652,200
import numpy def upsample3(x): """ Up-sample a 2D array by a factor of 3 by interpolation. Result is scaled by a factor of 9. """ n = [x.shape[0] * 3 - 2, x.shape[1] * 3 - 2] + list(x.shape[2:]) y = numpy.empty(n, x.dtype) y[0::3, 0::3] = 9 * x y[0::3, 1::3] = 6 * x[:, :-1] + 3 * x[:, ...
9c9b2e2af7ddb21be1805962401ceca9b4c82b39
652,201
import os def pathToAudio(PATH, extension='wav'): """ searching for audiofiles in PATH directory :param PATH: path to directory :param extension: audiofile etension, wav or flac :return: list of strings - paths to audiofiles """ audiopaths = [] for path, directories, files in os.walk(...
d18230e159364d76f44c9700c6bef7b1ebb3551e
652,202
from pathlib import Path from typing import List def get_sorted_version_directories(changelog_path: Path) -> List[Path]: """Get all version directories and return them sorted as list.""" directories = [item for item in changelog_path.iterdir() if item.is_dir()] return sorted( directories, ...
30f8743f853af5efeb332c397e1b44fcdfdcbd99
652,203
def _shape_to_size(shape): """ Compute the size which corresponds to a shape """ out = 1 for item in shape: out *= item return out
54fbe7d2f630ebea39ea9c86ea321af445d11d78
652,205
def time_to_str(time_min:str, time_max:str): """ Replace ':' to '-' from the time variables. Parameters ---------- time_min: str Time variable with ':'. time_max: str Time variable with ':'. Returns ------- time_min_str: str Time vari...
0d7441d8b43d3d53d991033fd2aea0dc3c1c5690
652,206
import sys def get_conflicting_pkgs(package): """Returns list of packages that contain some files that are also found in 'package'. These packages should be listed as dependencies. """ if package in ["basic", "fontsrecommended", "games", "luatex", "music", "plaingeneric", "publisher...
82dfee0744e4f078f12d95692c8bea210873ac7e
652,207
import os def normalize_path(path: str) -> str: """ Convert a path in a path that will work well with blob storage and unix It will replace backslashes with forwardslashes and return absolute paths. """ path = os.path.abspath(os.path.expanduser(path)) path = path.replace("\\", "/") if path...
abbcbc3edcc0135bd9cf01c08668f8d6ccade605
652,208
import argparse def process_argument(): """ Retrieves and parse the command line arguments. """ parser = argparse.ArgumentParser() # Default argument parser.add_argument("data_dir", type=str, help="Directory of data") # Optional arguments parser.add_argument("--save_dir", default='', t...
d524617c16c118d2bf5ab24dc6b279b32cf9cb2d
652,209
from pathlib import Path from typing import Union def multi_cat(*paths: Path) -> Union[int, bytes, None]: """ Attempts to read the content of multiple files which may not exist. Returns the content of the first file which can be read. If none of them can be read return None. Returns an integer if the ...
fb80cb1dba6b964f2ec3c5e8b5c775e82a4faf8b
652,210
def data_is_valid(data): """Check to see if data is valid for this class. Returns a tuple of (bool, string) indicating valididty and any error message. """ if isinstance(data, dict) and len(data) == 0: return True, "OK" return False, "Data is not an object or not empty."
171a68da52fdfc33d5d529879c764d6824f1004f
652,211
import functools def switch_sign(func): """Switch sign of all outputs of a function.""" @functools.wraps(func) def wrapper(*args, **kwargs): unswitched = func(*args, **kwargs) if isinstance(unswitched, dict): switched = {key: -val for key, val in unswitched.items()} el...
5bbf4ad05298c20a58ebd8a1338fb5136e46345f
652,213
def GetCaId(settings): """Get ca_id to be used with GetCaParameters(). Args: settings: object with attribute level access to settings parameters. Returns: str like "FOO" or None (use primary parameters) """ return getattr(settings, 'CA_ID', None)
cb94f5a27281c17a1b1eb9b13382e651bdf2b441
652,214
from typing import List def _find_interval_range(category_configs, interval: float) -> List[dict]: """Finds the range the interval is in and returns the configured mappings to the TransportGroups""" for interval_category in category_configs: min_interval = interval_category['min-interval'] if 'min-int...
1c7df995c328e83d372995b5045e0ad0c731f4b0
652,215
import argparse def positive_float_type(arg): """Check an argument for a positive float type. Arguments: arg: Argument value. Returns: Argument of valid type. """ arg_float = float(arg) if arg_float < 0.0: raise argparse.ArgumentTypeError("invalid positive_float_type value: '{}', must be positive".forma...
a189f77cf7f63fa83e3010118f0168fd5b289360
652,216
import os from datetime import datetime def make_saved_dir(saved_dir): """ :param saved_dir: :return: {saved_dir}/{%m-%d-%H-%M-%S} """ if not os.path.exists(saved_dir): os.mkdir(saved_dir) saved_dir = os.path.join(saved_dir, datetime.now().strftime('%m-%d-%H-%M-%S')) if not os.path...
b9d522e642443932693d1c52169b028e0cff7b94
652,218
def convert_segmentation_bbox(bbox: dict, page: dict) -> dict: """ Convert bounding box from the segmentation result to the scale of the characters bboxes of the document. :param bbox: Bounding box from the segmentation result :param page: Page information :return: Converted bounding box. """ ...
953669d41c2b74816aa5a5b93841713fe9901c6a
652,219
def resize_image(image, width, height): """Resize image to explicit pixel dimensions.""" width = int(width) height = int(height) aspect_ratio = image.width / image.height if height == 0: new_width = width new_height = int(round(width / aspect_ratio, 0)) elif width == 0: n...
a1dba4a83e4a60e602aa4e43460eee5a827615d2
652,220
def round_to_nearest(value, round_value=1000): """Return the value, rounded to nearest round_value (defaults to 1000). Args: value: Value to be rounded. round_value: Number to which the value should be rounded. Returns: Value rounded to nearest desired integer. """ if round...
4fee90f07e6106ded18f3bedfe31deceac3913c0
652,221
def is_bbox_correct(bbox, width, height): """ :param bbox: bbox composed of 4 integer values [xmin, ymin, xmax, ymax] :param height: height of the image :param width: width of the image :return: True if bbox inside image, False otherwise """ # Check bbox inside image if b...
85c369dcb6589207d34bb6fe3f726a678af8eeda
652,222
def to_time (wmi_time): """ Convenience wrapper to take a WMI datetime string of the form yyyymmddHHMMSS.mmmmmm+UUU and return a 9-tuple containing the individual elements, or None where string contains placeholder stars. @param wmi_time The WMI datetime string in yyyymmddHHMMSS.mmmmmm+UUU format @...
c607ece580715d7e3ed5907a3564e2b5923dfae0
652,223
import ast def is_yield(statement): """ Is this a statement of the form `yield <expr>` """ return (isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Yield))
56bff246a5a4b47ed8cd7d39e08fa2262a704f03
652,224
import json import base64 import binascii def extract_notification_from_request(request): """Extract and return a base64-encoded notification parameter from the request.""" encoded = request.GET.get('notification') or request.POST.get('notification') if not encoded: return ('', '') try: ...
83bd7f01593e2a3889ebd8fe8f13765be9d7aaab
652,226
def get_genes(prefix, percentile): """ Gets a list of genes from three files. One representing all genes in a sample, one representing the upper tail of a distribution of those genes, and one representing the lower tail of a distribution of those genes. """ allList = [] botList = [] topList = []...
f662591e01e09230474799a8a23af900992c2f89
652,227
def feet_to_meters(feet): """Convert feet to meters.""" try: value = float(feet) except ValueError: print("Unable to convert to float: %s", feet) else: return (0.3048 * value * 10000.0 + 0.5) / 10000.0
d651507e6cd4c3a2506dbf6944afaf4d5062dcbb
652,228
def concatenate_files(filenames): """ Concatenate the specified files, adding `line directives so the lexer can track source locations. """ contents = [] for filename in filenames: contents.append('`line 1 "%s" 1' % filename) with open(filename, 'rb') as f: contents.append(f....
ba991594d1ed4151cd358fa07c7817f6a9bd3a91
652,229
def CROSS(K, D): """ 金叉 死叉 :param K: 预信号 :param D: 周转信号 :return: """ status = K - D return status
60276a2550486640bf519635457b07314ac2a225
652,230
def get_request_value(req, key): """ Return the value of the request object's JSON dictionary. """ request_json = req.get_json() if req.args and key in req.args: return req.args.get(key) elif request_json and key in request_json: return request_json[key] else: return ...
fa68a4c851e5ca1d8991c76a11c0e0e8f60dd983
652,231
def parse(resp: dict): """ Parse response data for the repo commits query. """ branch = resp["repository"]["defaultBranchRef"] branch_name = branch.get("name") commit_history = branch["target"]["history"] total_commits = commit_history["totalCount"] commits = commit_history["nodes"] ...
e716673398b9fd0194114af64b618effb0b8e9a0
652,232
def get_raw_connection(engine): """psycopg2 connection.""" alchemy_conn = engine.connect() alchemy_conn.detach() raw_connection = alchemy_conn.connection.connection return raw_connection
466c18471461b6adbc7677c69d61244aa3f46516
652,233
import sys def rollTreatFinder(rolled): """ """ _rolled = str(rolled).lower() _rolled = _rolled.replace('rolled','') _rolled = _rolled.replace('heat','') _rolled = _rolled.replace('treatment','') _rolled = _rolled.replace('thread','') _rolled = _rolled.replace('limit','') _rolled =...
0742699ebf57a42f8ca5b61847e5c0c31f923dc3
652,234