content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def login(request): """登录视图""" if request.session.get('is_login',None): logger.info(request) return redirect("/index/") if request.method == "POST": login_form = UserForm(request.POST) message = "请检查填写的内容!" if login_form.is_valid(): username = login_form.c...
b9ea5492bcc9f7224f75e2121a6e8e3e6a1d9827
3,614,900
def setup_platform(hass, config, add_devices, discovery_info=None): """ Set up the Visonic Alarm platform. """ hub.update() visonic_alarm = VisonicAlarm(hass) add_devices([visonic_alarm]) # Create an event listener to listen for changed arm state. # We will only fetch the events from the API on...
cd345fec39db4388b06e7efed8cf392e2797fcdc
3,614,901
def pipeline_send_op(node, destination, comm, stream=None, ctx=None): """Make a new instance of PipelineSendOp and call the instance. Parameters: ---- node : Node The Node to be send. destination : scalar value The gpu index for destination. Returns: ---- A new Node ins...
29db37670805705032cb293d8606d20bc4bc6bb1
3,614,902
import signal import math def synth(**kwargs): """return ricker wavelet synthetic data""" # defaults if 'pol' not in kwargs: kwargs['pol'] = 0. if 'delta' not in kwargs: kwargs['delta'] = 1. if 'split' not in kwargs: kwargs['split'] = [] if 'noise' not in kwargs: kwargs['noise'] = 0.0...
8186c37add652e63ecdfe610866abc00d08eefe6
3,614,903
import yaml import random import string def tmp_config_file(dict_: dict) -> str: """ Dumps dict into a yaml file that is saved in a randomly named file. Used to as config file to create ObservatoryConfig instance. :param dict_: config dict :return: path of temporary file """ content = yaml...
d4ea42a8dc1824757df7f9823f44f7fc181b29aa
3,614,904
import re def get_bootstrap_assets(self, platform=None): """ :param self: :param platform: optional, defaults to current build's platform :return: Asset type requested for the supplied platform in bootstrap.cfg """ if platform is None: platform = self.env['PLATFORM'] bootstrap_cfg ...
55510ed1d15c3ec7323b257b5596cd601bad2316
3,614,905
def calc_checksum(packet): """ Calculates the checksum of a given packet. This function is only for use in environments where 16-bit words are used. :param packet: A list with 16-bit numbers as Integers. :return: The checksum of the packet as Integer """ # validate the input try: ...
7fd61f9cd15bf7acc7e87255cd6813aa84216266
3,614,906
def interpolate_with_degree(nodes, values, deg, use_mp=False): """Compute a rational function which interpolates the given nodes/values with given degree `m` of the numerator and `n` of the denominator. Args: nodes (array): the interpolation nodes values (array): the values at the interpola...
19f5ffa5ac4f1b18de4d489b68ba7726a4c8851a
3,614,907
def preprocess_input(title, overview, vectorizer): """ Extract TF-IDF features from a single title and overview input. :param title: Str. Movie title. :param overview: Str. Movie plot. :param vectorizer: Fitted sklearn.feature_extraction.text.TfidfVectorizer object. :return: Tf-IDF features matr...
0de37a8e7c870eef185baa3aa1a497ea8d353201
3,614,908
def _generate_image_info(im, params): """"generate url and tokens for image""" image = ee.Image(im) if "sld_style" in params: m = image.sldStyle(params.get("sld_style")) del params["sld_style"] elif "palette" in params: m = image.visualize( **{ "min":...
13a6bc4a6ad9eb7dd549682d707b1dd7aabb65fe
3,614,909
import typing def forced_attribute_type(name: str, type_accessor: typing.Callable[[], typing.Type], may_subclass=False, source_source=None): """ Forced a certain data type on an object attribute Not validated, but allows optimisations to happen! Can speed up calls by a lot """ def annotation...
2e1d56e5b3d93d392381f008b6acfda6b47ba6d5
3,614,910
def _setup_fig(ncols, nrows, figsize_width, figsize_height): """ Parameters: ----------- ncols Number of columns in the figure. type: int nrows Number of rows in the figure. type: int figsize_width Scaler adjustment of figure width default: 1 ...
cf6c75101220620a8bf7c04d59ba9642ba339779
3,614,911
def unconfirmed(): """Catch users with unconfirmed emails.""" if current_user.is_anonymous or current_user.confirmed: return redirect(url_for('main.index')) return render_template('account/unconfirmed.html')
04c40e63a48da389fdec7897c8db049cde572228
3,614,912
import sys def local_str(arg): """ Преобразует arg в unicode, а затем в строку с кодировкой для вывода на текущем терминале """ e = sys.stdout.encoding if not e: e='cp1251' return unicode(arg).encode(e, 'ignore')
4fc08dac4d1da64ad35e47a6c01fc60d5623b0e6
3,614,913
def computeAlleleFrequency (f_C, f_T): """3 f_C = minor allele count f_T = major allele count minor_allele_frequency = f_C/ (f_C+f_T) 7""" minor_allele_frequency = f_C/(f_C+f_T) return minor_allele_frequency
984a7364bfd3ff2c724c885dedd97f61f959b7e6
3,614,914
def update_m(obj, ia, rcut=9.0, pbc=None): """ retrieve local structure around atom `ia for periodic systems (or very large system) """ zs, coords, c = obj v1, v2, v3 = c vs = ssd.norm(c, axis=0) nns = [] for i,vi in enumerate(vs): n1_doulbe = rcut/li n1 = int(n1_dou...
5ee6752f1c5cc1274557e523acb12394a9b33f56
3,614,915
def crext_TruncatedHMAC(): """Create a Truncated HMAC extension.""" return ExtensionType.truncated_hmac.value + lenprefix(b"")
4d9dbc4156e4bc1855e241bd493aa7b7149e800a
3,614,916
def microcycle_days(weekly_training_days, weeks): """generates indexes of training days during the weeks""" training_day_indexes = [] for w in range(weeks): for d in weekly_training_days: training_day_indexes.append(w * 7 + d.value) return training_day_indexes
5c0364b1dc58d2c0205d4e6442d590a23519e5f4
3,614,917
def reduced_supercell_vectors(ab, n): """ Returns all possible reduced in-plane lattice vectors and transition matrices for the given starting unit cell lattice vectors(ab) and the supercell size n """ uv_list = [] tm_list = [] for r_tm in get_trans_matrices(n): uv = get_uv(ab, r...
7c75258e19037ee8e09858793b3232690313add8
3,614,918
from typing import List def make_polygon_from_coords(coords: List[float]): """ Creates a `Polygon` instance using the passed in coordinates: `[x1 y1 x2 y2 ... xn yn]`. It raises a `ValueError` if the coordinates list does't have an even number of entries. :param coords: list of the coordinat...
7aa7c46d9f769f57a1bfdbe962bb2f942ab08e96
3,614,919
def fibonacciMemoization(n: int): """ :param n: range numbers to be visited in fibonacci series :return: nth value in the fibonacci sequence """ global fibb_memo if n in fibb_memo: return fibb_memo[n] if n <= 2: return 1 fibb_memo[n] = fibonacciMemoization(n - 1) + fi...
affd30d81fc6a0564c4acddb2b676a26fcb9846a
3,614,920
def scatter(data, **kwargs): """I dont like this. Viewing code should not reside in model logic.""" fig, ax = plt.subplots(1, 1, figsize=(6, 5)) ax.scatter(*data.cpu().numpy().T[:2], **kwargs) plt.close() return fig
b89416ded88c872585a3db75651b393d5d319b79
3,614,921
def build_training_model_component(): """ Build training model component Returns: training_model_component: training model component """ model_training_stage = [] rfor = RandomForestClassifier(featuresCol=FEATURES, labelCol=TARGET, seed=RANDOM_SEED) model_training_stage.append(rfor) ...
7bbb6f830bb8f4719e95dd3b18121e3ba8ab23cc
3,614,922
import torch def cka(k_x: torch.Tensor, k_y: torch.Tensor, centered: bool = False, unbiased: bool = True) -> torch.Tensor: """Compute Centered Kernel Alignment (CKA). :param k_x: n by n values of kernel applied to all pairs of x data :param k_y: n by n values of kernel on y data :param centered: whet...
a0abf43f33e79f67a2974d7524730f04ae86dd93
3,614,923
import os import logging import google def _run_dag_and_wait(): """Run and wait for the DAG to finish. Returns: state: The end state of the DAG. """ artifacts_path = os.path.join(prow.get_gcs_output(), "artifacts") logging.info("Artifacts will be saved to: %s", artifacts_path) conf = { "PULL_NUM...
fde39f8665c09c000b354eb280465b88e4f18f21
3,614,924
from typing import OrderedDict def columns(table, missing=None): """ Construct a :class:`dict` mapping field names to lists of values. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] >>> cols = etl.columns(table) >>> cols['foo'] ...
2938710112da2b8317fda65b8d873f48e1e2dc40
3,614,925
import sys def get_output_encoding(): """ Get the output encoding used for output to management commands. :return: ``sys.stdout.encoding`` """ return sys.stdin.encoding or sys.getdefaultencoding() or DEFAULT_ENCODING
ef9bf322ced4d4d1d179ebf618cf1965e5934398
3,614,926
def _project_vertices(v, w, h, cam_r, cam_t): """projects vertices onto image plane""" V = ch.array(v) U = ProjectPoints(v=V, f=[w * 2, w * 2], c=[w / 2., h / 2.], # camera intrinsics k=ch.zeros(5), t=cam_t, rt=cam_r) return U
db7f664a531abb4949c66499ef9ef7bfd3cff047
3,614,927
import pprint def check_overlapping(features): """Check for elements of `features` with overlapping ranges. In the case of overlap, print an informative error message and return names and positions of overlapping features. """ features = features[:] overlapping = [] for i in range(len(fea...
6a246aca29c01b32091d7890b6a55d66367e8e14
3,614,928
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.): """ Predict next position using the Kalman filter state propagation equations. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array() State Transition matrix ...
fb6002c528489f5d595acd8137f1606416eb6678
3,614,929
def update_hosts(hosts_list=None, user='root'): """ @param_post{hosts_list} @param_post{user} (optional, default: @val{root}) """ if user is None: missing_parameter('user') if hosts_list is None: missing_parameter('host_list') try: f = open("/etc/hosts", "r") ...
2e95445363814befe67757d517590d2b112bf871
3,614,930
def get_file_to_load(): """Open a popup window to select a file to load""" return sg.popup_get_file( 'Select a file to open', EVENT_OPEN, initial_folder=USER_HOME, no_window=True, default_extension=EDITOR_EXTENSION, )
3ab90ed642d460dd0db0fbdf63d09dc900d19715
3,614,931
from operator import concat def renew(alias, sub_nas, args): """ :param alias: :param sub_nas: \n:param args [expiration, type]: \n:returns new expiration if success or False if failed: \nif sub_nas defined passes call to sub_nas otherwise we try to renew alias """ # handle sub_nas...
c252c72f51c19b798d7af53eb9a064991bbc5a98
3,614,932
def create_train_op(total_loss, optimizer, global_step=_USE_GLOBAL_STEP, update_ops=None, variables_to_train=None, transform_grads_fn=None, summarize_gradients=False, gate_gradient...
ad2033022d628c4b82da453b0ba772f72028abd6
3,614,933
def does_asyncio(func): """Simple decorator for running a test inside an asyncio event loop.""" def wrapper(*args, **kwargs): get_event_loop().run_until_complete(func(*args, **kwargs)) return wrapper
8f1d9a37400204cfa63ec5edaa25592558219b4d
3,614,934
def correct_baseline(raw_data, mode, smoothing=True, transform=False, **kwargs): """ Calculate baseline data for raw_data with generate_baseline(...). Takes the same arguments like generate_baseline, for details see docstring of generate_baseline. """ return raw_data - gene...
b9e3b278cfd1e33bb606a32866eea2be5cb75bef
3,614,935
def article(*args, **kwargs): """ The HTML <article> element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). This could be a forum post, a magazine or newspaper article, a b...
79405862e88865296aa16ae477f2a6c5d2323ac9
3,614,936
from typing import Dict def validate(business: Business, cod: Dict) -> Error: """Validate the Change of Directors filing.""" if not business or not cod: return Error(HTTPStatus.BAD_REQUEST, [{'error': babel('A valid business and filing are required.')}]) msg = [] msg_directors_addresses = val...
937b74506eb4e3a9d73bc135394f78b42a32e861
3,614,937
def index(): """ Basic index view, listing online users. """ msg = 'Online: %s' % ', '.join(get_online_users()) return make_response(msg)
a74c95ec7d25f46c3a5c30203ec6ce34260d35ba
3,614,938
def pixel2wave (pix, c, model='linear') : """ Inverse function for a given pixel(wave) model. Converts a pixel position pix into a wavelength w using one of several invertable models: 'linear','quadratic','cubic' w(pix) = invert_polynomial(pix,c) because pix(w) = c[0]+c[1]*w+... 'exp' w(pix) = -ln[(pix-c2)...
e8722d739bcf7fa76a5b8dbda34edddc76915496
3,614,939
def compute_level(id, tree): """ compute the level of an id in a tree """ topic = tree[id] level = 0 while (id != 0): level += 1 id = topic['parent'] topic = tree[id] return(level)
fb7fbc1c1f97e85c03abdd453a3deb3411960e45
3,614,940
import os def is_db_weather(weather_path): """True, if the ``weather_path`` is one of the pre-installed weather files that came with the CEA""" weather_name = get_db_weather_name(weather_path) if weather_name in LOCATOR.get_weather_names(): # could still be a custom weather file... db_weat...
85dbaa618d5607183169ecca7e671ef30f0ac23f
3,614,941
import csv def ReadDirectoryFromFile(file_name, hub_map): """directory_tools.ReadDirectory INPUTS: - file_name -- name of the file containing the MemberHub directory dump - hub_map -- dictionary that maps hub names to hub IDs OUTPUTS: - directory -- list of families read from the MemberHub d...
3ed042a2b26436f4061e8d0b628f4887a8982a10
3,614,942
from typing import Sequence from typing import Any from typing import Optional from typing import Union from typing import List def flatten(sequence: Sequence[Any], depth: Optional[int] = -1, **kwargs) -> Union[List[Any], Any]: """ Receives values, whether arrays of values, regardless of their shape and flatn...
bfdd0ed66d3eaac5ec3b6c17e43f917bfbbadc69
3,614,943
import random import sympy def change_four_variables_in_expr(latex_dict: dict) -> str: """ >>> latex_dict = {} >>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}] >>> latex_dict['feed'] = [parse_latex('')] >>> latex_dict['output'] = [{'LHS': parse_latex(''), 'RHS': parse_l...
81385dc30fcd84d1e9e72326383849cc88f1ada3
3,614,944
def polyglot_1st_pronoun(s): """Get first pronoun from the sentence. Parameters ---------- :param s: string Sentence Returns ------- :returns: string first pronoun """ pronouns = polyglot_pronouns(s) return pronouns[0]
c0c27ae6bdb5be5b6317cf6751242759538de41c
3,614,945
def filter_by_pvalue_strand_lag(ratios, pcutoff, pvalues, output, no_correction, name, singlestrand): """Filter DPs by strang lag and pvalue""" if not singlestrand: zscore_ratios = zscore(ratios) ratios_pass = np.where(np.bitwise_and(zscore_ratios > -2, zscore_ratios < 2) == True, True, False) ...
394b7b6561c869ba97bbb2ad1d015b2600b71b26
3,614,946
def write_user_playlist(username, text_file=None): """ Write user playlists to text_file """ links = get_playlists(username=username) playlist = internals.input_link(links) return write_playlist(playlist, text_file)
2ab684f2f7eec1484d76427fe179fe8620e60da8
3,614,947
def is_float(db_type): """Return True if the database type is a float supported type, False otherwise. """ return db_type in ACCEPTED_FLOAT_DB_TYPES
114657762f76afce67739aac011539b6a0c081e6
3,614,948
import time def generate_papernot(): """ Train the second/distilled model using uncertaity array :return: distilled model """ sigmas = np.load(PROJ_PATH + 'mnist_papernot/sigmas.npz')['sigmas'] start = time() model_papernot = train_papernot(sigmas) end = time() print("Papernot trai...
d526855245b05fcc5f2107952082239e8121674c
3,614,949
def inverse_stft_window_fn(frame_step, forward_window_fn=window_ops.hann_window, name=None): """Generates a window function that can be used in `inverse_stft`. Constructs a window that is equal to the forward window with a further pointwise amplitude cor...
73a17762231915b35409c05119c1b39eace851b2
3,614,950
def Vegas(integrand, ndim, userdata=NULL, epsrel=EPSREL, epsabs=EPSABS, flags=0, ncomp=1, seed=None, mineval=MINEVAL, maxeval=MAXEVAL, nstart=NSTART, nincrease=NINCREASE, nbatch=NBATCH, gridno=GRIDNO, statefile=NULL, nvec=1): """ *nstart*: the number of integrand evaluations per iteration to start...
0762180ec96902b045ff0a16e9f389a7917287ea
3,614,951
def human_annotations(human_file): """ Generates JSON from TSV files """ zipped_rows = get_rows_from_file(human_file, '\r') # Too many processes causes the http requests causes the remote to respond with error pool = mp.Pool(processes=1) annotations = pool.map(human_single_annotation, zipped...
965b3f8d1ab557ae79e3f2fa2f0e8e635b568842
3,614,952
import torch import math def eval_gather_inds(len_, num_samples=7): """ get the gather indices """ inds = torch.arange(0, num_samples, dtype=torch.long) mul = math.ceil(len_ / num_samples) output = inds.repeat(mul)[:len_] return output
516ca54ff5c3b442bc93becd15d1bdabd8c8025f
3,614,953
def vap_lapserate(temp,pres,dvap=None,chkvals=False,chktol=_CHKTOL, dvap0=None,chkbnd=False,mathargs=None): """Calculate water vapour adiabatic lapse rate. Calculate the adiabatic lapse rate of water vapour at temperature and pressure. :arg float temp: Temperature in K. :arg float pres...
6597bd3d0faef483d7db9c46e0c01a4cb3fc9922
3,614,954
def none_or_valid_float_value_as_string(str_to_check): """ Unless a string is "none", tries to convert it to a float and back to check that it represents a valid float value. Throws ValueError if type conversion fails. This function is only needed because the MATLAB scripts take some arguments eithe...
54f3c63fab0752678cb5a69723aa7790ab11a624
3,614,955
def hunkify_lines(lines, context=3): """ Return a list of line hunks given a list of lines `lines`. The number of context lines can be control with `context` which will return line hunks surrounded with `context` lines before and after the code change. """ # Find contiguous line changes rang...
c5acde8c6335b82173af724ba3c8c34058fa23b6
3,614,956
from typing import Dict from typing import Union def _from_node_reqs_to_dask_resources( node_reqs: NodeRequirements, ) -> Dict[str, Union[int, float]]: """Dask resources are set such as {"CPU": X.X, "GPU": Y.Y, "RAM": INT}""" dask_resources = node_reqs.dict(exclude_unset=True, by_alias=True) logger.de...
0aeace41a5a3267e23b1c81406c500db0983e199
3,614,957
def init_policy(states, Q): """ Define initial target policy of off-policy MC method Parameters ---------- states : list of tuples States consist of positions and velocity of agent Q : dict Dictionary with q values of each action in each state Returns ------- pi : d...
1c354291668c3489695cd5d25ea11bb3d00d5531
3,614,958
def gaussianFWHM(x, fwhm, norm = 'area'): """ Calculate a Gaussian function. Parameters ---------- x : array_like Input array fwhm : scalar The full-width at half-maximum value. norm : {'area', 'amplitude'} The normalization convention. The default is 'area'. See...
3df6f2b531669862322bc34796d315c1e8d6f2e2
3,614,959
def S_moving_average_filter(_data_list, _smoothing=1): """ Returns moving average data without data lag. Use the smoothing factor to get required overall smoothing where the smoothing factor is greater than zero. """ ma_data = [] ds = len(_data_list) s = _smoothing mas = int((ds...
763bff294c6225260cb67e2e38440eb4d514c126
3,614,960
def StripKey(key): """Returns key with header, footer and all newlines removed.""" key = key.strip() key_lines = key.split(b'\n') if (not key_lines[0].startswith(b'-----') or not key_lines[-1].startswith(b'-----')): raise OpenSSLException( 'The following key does not appear to be in PEM format...
bed4f367759098fcb001c315791f3cf25328993e
3,614,961
def get_expanse_certificate_context(data): """ provide custom context information about certificate with data from Expanse API """ return { "SearchTerm": data['search'], "CommonName": data['commonName'], "FirstObserved": data['firstObserved'], "LastObserved": data['lastOb...
cf5c1d38ae7ed3474171ccff7d437d7b622cbcec
3,614,962
def find_polygon_divisions(line_pts, polygon_pts, angle): """ Esta función primero genera una recta, con un ángulo definido por angle, en cada punto contenido dentro de line_pts. Luego, para cada recta generada, encuentra la intersección con cada mitad del polígono definido en polygon_pts. R...
41add86abc9ad47be8cec00a0029d83f067b864b
3,614,963
def factorial(x: i32) -> i32: """ Computes the factorial of `x`. """ if x < 0: return 0 result: i32 result = 1 i: i32 for i in range(1, x+1): result *= i return result
31daab3c0e27756346154c6e1d1576363b81e83d
3,614,964
import argparse def parseargs(): # pragma: no cover """Sets up command-line arguments and parser Parameters: Returns: parser Raises: """ parser = argparse.ArgumentParser(description='Metrics BeeGFS-Sqlite to elastic') parser.add_argument("-f", "--cfgfile", help='Specify the config file (....
bc4a82545fc493c0b386a63b25d393ab0dfdc3cb
3,614,965
from datetime import datetime def convert_time(time_str): """Convert iso string to date time object :param time_str: String time to convert """ try: dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%Mz") return dt except Exception: return time_str
4ba3d5b8af4305cc44afb60d02eeb1b1d041fab9
3,614,966
def get_common_words(): """Finds all common words in Redis""" redis_connection = get_redis_connection() words = redis_connection.keys(get_word_key("*")) return set([word[2:].decode('utf-8') for word in words])
888b6f8e77954ce6ed6f45d647156da53338faf3
3,614,967
import numpy def complex_to_amp_phase(lookup_table): """ This constructs the function to convert from complex64 or 128 to AMP8I_PHS8I format data. Parameters ---------- lookup_table : numpy.ndarray Returns ------- callable """ _validate_lookup(lookup_table) def converte...
92acec01b2a166a17b36a6d32352805ae0a6c7ce
3,614,968
def suck_out_formats(reporters): """Builds a dictionary mapping edition keys to their cite_format if any. The dictionary takes the form of: { 'T.C. Summary Opinion': '{reporter} {volume}-{page}', 'T.C. Memo.': '{reporter} {volume}-{page}' ... } In other ...
a0db907839573ca53f7c96c326afe1eac5491c63
3,614,969
import time import logging def tsne_embeddings(X, include_svd=True, n_svd_components=50, tsne_params=dict()): """ Computes t-SNE embeddings of the tf-idf vectors. By default it first performs a dimensionaly reduction using truncated SVD, as recommended in the scikit-learn documentation. This i...
186d9f67e6142e51b87fdfca2d2f4a6e05a60b7a
3,614,970
def get_expected_return( rewards: tf.Tensor, gamma: float, standardize: bool = True) -> tf.Tensor: """Compute expected returns per timestep.""" n = tf.shape(rewards)[0] returns = tf.TensorArray(dtype=tf.float32, size=n) # Start from the end of `rewards` and accumulate reward sums # int...
a8b5a2dbd67eaaf000dba05340239bc0fca1a563
3,614,971
def cast_bytes(data, encoding='utf8'): """ Cast str, int, float to bytes. """ if isinstance(data, str) is True: return data.encode(encoding) elif isinstance(data, int) is True: return str(data).encode(encoding) elif isinstance(data, float) is True: return str(data).enco...
01ac5d7cd4a728e401075334900808a6a579deef
3,614,972
from typing import Dict from typing import Any from typing import Sequence from typing import Tuple def anchormap(refs: Dict[Any, Any] = {}) -> Sequence[Tuple[Location, Location]]: """ Return all lexical references Performs compilation up to and including the type resolution, but doesn't start executing ...
dbf0f3bbee8c071245b0b3f75a348ea0524f9d69
3,614,973
def deep_access_list(x, keylist, key_value_eq=None): """ >>> deep_access_list({"a":2}, ["a"]) 2 >>> deep_access_list({"a":[{"a":2, "b":5}, {"a":1, "b":6}]}, ["a", "a"]) 3.0 >>> deep_access_list({"a":[{"a":"cat1", "b":"cat2"}, {"a":"cat3", "b":"cat2"}]}, ["a", "a"], "cat1") 1.0 >>> deep_a...
cdc3491c5b99ec02a40fcf518cd9f4e40e743f8a
3,614,974
def plot_roc_curve(y_true_arr, y_pred_proba_arr, labels_arr, pos_label=None, plot_thres_for_idx=None, log_wandb=False): """Function for plotting ROC curve Args: y_true_arr (list/np.array): list of all GT arrays y_pred_proba_arr (list/np.array): list of all predicted probabili...
46f4e1b3ab25183f72d724e6c13f8e2320125158
3,614,975
def _pillow2array(img, flag='color', channel_order='bgr'): """Convert a pillow image to numpy array. Args: img (:obj:`PIL.Image.Image`): The image loaded using PIL flag (str): Flags specifying the color type of a loaded image, candidates are 'color', 'grayscale' and 'unchanged'. ...
70800bd3174a6ab33389ca51c4204d21d19e3d16
3,614,976
import torch from typing import Optional from typing import Tuple def get_eval_fn(model: torch.nn.Module): """Get the evaluation function for server side. Parameters ---------- model The model we want to evaluate. Returns ------- evaluate The evaluation function """ ...
918b4e62422f0c645ffa68da346aae1c5e588413
3,614,977
def build_rnn_dataset(dataframes, tokenizer=lambda s: s.split()): """ Given an SST reader, return the dataset as (X, y) training pairs. Parameters ---------- dataframes : pd.DataFrame or list of pd.DataFrame The dataset or datasets to process, as read in by `sentiment_reader`. ...
71feeeed3369a8e6ddc3d2d62b56161da8da336a
3,614,978
def api_user_current_bar(): """Request endpoint to change a user's current bar :param int user_id: ID of the user to modity :param int bar_id: ID of the bar to set as user's current view default If 0, will use the configured default bar :param string next: Should be the URL of the current page s...
5353640a895ab8260d8919609a1ba661cf391d48
3,614,979
def _default_line_time_factory(self: "Kymo"): """Line time in seconds""" if self.timestamps.shape[1] > 1: ns_to_sec = 1e-9 return (self.timestamps[0, 1] - self.timestamps[0, 0]) * ns_to_sec else: raise RuntimeError( "This kymograph consists of only a single line. It is no...
075242606bacac1b9963d62f5e3794a5b276412e
3,614,980
def B(i,j,k): """ Tensor B used in constructing ROMs. Parameters ---------- i : int j : int k : int Indices in the tensor. Returns ------- int Tensor output. """ if i == j + k: return -1 elif j == i + k or k == i + j: return 1 el...
b4969759fd2f07bd2bd2baed48a2adfd8669987a
3,614,981
def magic(data): """Mime-Type anhand eines Datenstroms raten.""" if data[0:2] == '\xff\xd8': # JPEG Start of Image return 'image/jpeg', '.jpg' elif data[0:4] == '\x89PNG': return 'image/png', '.png' elif data[0:4] == '%PDF': return 'application/pdf', '.pdf' else: LOG...
16043cee7c05f81973702e624344447c23fe8677
3,614,982
import os import json def read_metadata(input_dir): """Read metadata JSON file in +input_dir+ into a dictionary""" metadata_path = os.path.join(input_dir, METADATA_FILENAME) with open(metadata_path) as src: return json.load(src)
fa6a6a4c6c5293ac0438ca596c7bf9784a3e5775
3,614,983
def logout(): """登出""" session.pop("user_id", None) session.pop("nick_name", None) session.pop("mobile", None) # session.pop('user_id', None) # session.pop('nick_name', None) # session.pop('mobile', None) session.pop('is_admin', None) return jsonify(errno=RET.OK, errmsg="退出登录成功")
7c0abc3be1c097e63cfb1ae08af13f38dd806cad
3,614,984
def boost_python_pattern_generator(asg, pattern=None, *args, **kwargs): """ """ return boost_python_generator(asg, asg.declarations(pattern=pattern), *args, **kwargs)
21c6e1f653376a155ea12104b0884e2ac3bdc0c7
3,614,985
def make_upload_chart(gfunc, yaml_path, json_path, title): """Create an upload chart Args: gfunc: the group by function yaml_path: the template path json_path: the path to write to title: the title of the chart Retuns: the chart JSON """ return pipe( gfunc, ...
db9636700faa099ffe018a9f8b60293c531cca8b
3,614,986
import torch import time from re import X def _yuzu_ism(model, X_0, precomputation, device='cpu', use_layers=use_layers, ignore_layers=ignore_layers, terminal_layers=terminal_layers, verbose=False): """Perform ISM using compressed sensing to reduce the necessary compute. This function will take a model,...
5cf32eafc131380609d6f27e4baa9f638a5c3754
3,614,987
import os import jsonschema import json def check(schema: dict) -> dict: """ Validate JADN schema against JSON schema, Validate JADN schema against JADN meta-schema, then Perform additional checks on type definitions """ # Add empty Fields if not present schema_types = [TypeDefinition(*t) ...
c545a30f4a59160ba2a1b88559659651023c2a27
3,614,988
def resmlp_24_224(): """ ResMLP-24 Paper: ResMLP: Feedforward networks for image classification... Link: https://arxiv.org/abs/2105.03404 """ cfg = MLPMixerConfig( name="resmlp_24_224", url="[timm]", patch_size=16, embed_dim=384, nb_blocks=24, mlp_...
d92f9e483ec19a950771e076ba786755ca92469e
3,614,989
import math def h2abc(h): """Returns a description of the cell in terms of the length of the lattice vectors and the angles between them in radians. Takes the representation of the system box in terms of an upper triangular matrix of column vectors, and returns the representation in terms of the ...
aaaf35381bc447398a2339180e39a488530cd313
3,614,990
def get_joint_distribution( trials, mean_prior=lambda: tfd.Uniform(0., 1.), inverse_concentration_prior=lambda: tfd.HalfNormal(5.)): """Returns a joint distribution over parameters and successes.""" param_shape = ps.shape(trials)[:1] mean = tfd.Sample(mean_prior(), param_shape) inverse_concentration...
cc1a2eacad8870048d92eb573af13244a3405a8c
3,614,991
import io def format_data(data, indent): """Format a bytestring as a C string literal. Arguments: data: Bytestring to write indent: Indentation for each line, a string Returns: A multiline string containing the code, with indentation before every line including the first. There is...
260e2b296addeb1113d657b086302197a8e365bb
3,614,992
from re import A def survey_series_rheader(r): """ The series rheader """ if r.representation == "html": db = current.db s3db = current.s3db tablename, record = s3_rheader_resource(r) if not record: series_id = current.request.vars.series t...
c4d35cec80f32e575cb505e43113dc656682b9ca
3,614,993
def sample(bn, cond=None): """ Sample every variables of a Bayesian Network :param bn: a Bayesian Network :param cond: dict, given variables :return: """ g = bn.DAG cond = cond if cond else dict() if any(nod not in cond for nod in bn.Exo): raise ValueError('Exogenous nodes do...
81606afea08f1e80b73d115ed6a6a2581c13890c
3,614,994
from typing import Any import json async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" # Currently we only support a single device device = hass.data[DOMAIN][entry.entry_id][VICARE_DEVICE_CONFIG] da...
cee924ef4bff944a53dfffd7b8aff84b369691bc
3,614,995
import os def load_image_lists(frame_list_file, prefix="", return_list=False): """ Load image paths and labels from a "frame list". Each line of the frame list contains: `original_vido_id video_id frame_id path labels` Args: frame_list_file (string): path to the frame list. prefix ...
82f55d9c13db80f8f07481689640b9eb284e80f3
3,614,996
from typing import List def predict_single(classifier: GaussianNB, test_data:List[Text], num: int = 200): """ predicts the most probable class value for the given test tokens and model Parameters ---------- classifier: GaussianNB model that holds the bag of words model test_d...
2f0e136a1bc0c4988219e76e7145c8ba19e29a99
3,614,997
def psf_to_inhg(psf): """Convert lb/ft^2 to inches of mercury.""" return psf * 0.014139030952735
c1a482c71ad86ae31efece5f1a395fa354db8c3e
3,614,998
def post_request_with_retries(url, json_payload, verify_ssl=True): """This function performs a POST request with a total of 5 retries in case of timeouts or connection issues. .. versionchanged:: 3.2.0 The query URL is now made into an absolute URL as necessary before performing the API request. .....
b3b37e5819d82cfd1871c614db1b9715ede05fe4
3,614,999