content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reorder_by_driver(driver, driven): """ Reorders timeseries of driver and driven variable by driver quicksort. """ idx_sort = np.argsort(driver, kind='quicksort') driver = driver[idx_sort] driven = driven[idx_sort] return driver, driven
772737c8918363dd6ce59eeb3c79474292d9c9a2
3,634,500
import os def linux_sys_new(): """ """ path = None # Some systems seem to have BAT1 but not BAT0, so use the first one we # encounter. for i in range(0, 4): p = '/sys/class/power_supply/BAT{}'.format(i) if os.path.exists(p): path = p break if path is ...
fabc9d22b0415dc84057e04da3223ac44e747118
3,634,501
import uuid def get_bucket_policy(s3bucket): """ Gets S3 Bucket policy :param s3bucket: S3 bucket to get the policy :return: Bucket Policy Object """ s3_client = boto3.client('s3') try: bucket_policy = s3_client.get_bucket_policy(Bucket=s3bucket) except: bucket_policy = {u'...
33a4f16df595b040b255ea73354d18719ccba8b5
3,634,502
def is_gregorian( y, m, d ): """ The `is_gregorian` function enables array input. Documentation see the `_is_julian` function. """ years = np.array(y,ndmin=1) months = np.array(m,ndmin=1) days = np.array(d,ndmin=1) years_count = np.size(years) dim_check = ((years_count == np.size(mon...
2e91330242cde9ef4a3483700d0a029a488e2bc5
3,634,503
import json def parse(filename): """ Decode filename into an object """ template = None template_lines = None try: (template, template_lines) = tf_plan_json.load(filename) except tf_plan_json.JSONDecodeError: pass except json.decoder.JSONDecodeError: # Most ...
d0dec4d63da1d8a92f6e025148ac69c6efde9234
3,634,504
def get_feature_dropping_corrections(bird_id='z007', session='day-2016-09-09', feat_type: str = 'pow', verbose=True): """ Import the results of make_parameter_sweep :param bird_id: :param session: :param verbose: :return: accuracy : ndarray, (bin_widths, offsets, num_folds, frequencies) ...
1e7ee58c892673475369d0f6649cc42b96606f3a
3,634,505
def build_pretraining_pipeline( input_file, output_dir, output_suffix, config, dupe_factor, min_num_rows, min_num_columns, num_random_table_bins = 1_000, add_random_table = False, num_corpus_bins = 1_000, add_numeric_values = True, ): """Pipeline that maps interactions to T...
f8401afb557a7fdcfa9f69aa86e0c60f1807c44f
3,634,506
import logging def parse_arg_params(parser, upper_dirs=None): """ parse all params :param parser: object of parser :param list(str) upper_dirs: list of keys in parameters with item for which only the parent folder must exist :return dict: parameters """ # SEE: https://docs.python.org/...
b770224cf54b7dc23896db88eb63d258c96b9da6
3,634,507
def rgb_to_hex_string(value): """Convert from an (R, G, B) tuple to a hex color. :param value: The RGB value to convert :type value: tuple R, G and B should be in the range 0.0 - 1.0 """ color = ''.join(['%02x' % x1 for x1 in [int(x * 255) for x in value]]) return '#%s' % color
6449d5ecf8f3134ca320c784293d8ece44a84148
3,634,508
def view(): """ This intercepts the /view URL get request. Displays the Page details for a application in a specific category. It reads the query parameters given when passing in the URL :return: """ application_category = request.args.get("show").upper() result_data = application.get(sessi...
d2e62b12f2cc6e351d5b264a09c1c95a29f9baba
3,634,509
def ancestors(G, x, G_reversed=None): """ Set of all ancestors of node in a graph, not including itself. :param G: target graph :param x: target node :param G_reversed: you can supply graph with reversed edges for speedup :return: set of ancestors """ if G_reversed is None: G_rev...
11a6930038807a677c3645d908a45b068c0f013b
3,634,510
def range_to_list(): """ This function is used to create an array of values from a dataset that's limits are given by a list lower and upper limits. THIS IS CONFIGURED FOR MY COMPUTER, CHANGE THE DIRECTORY TO USE. """ dat1, filename1 = pick_dat(['t', 'm'], "RDAT_Test", "Select dataset to draw from")...
f4cd269f13a4580d43a4279a539d8b6a87a06683
3,634,511
def compute_a2b2(Q): """ Given the second moment matrix, compute a^2 and b^2 """ Q11 = Q[0, 0] Q22 = Q[1, 1] Q12 = Q[0, 1] a2t = 0.5 * (Q11 + Q22 + np.sqrt((Q11 - Q22) ** 2 + 4 * Q12 ** 2)) b2t = 0.5 * (Q11 + Q22 - np.sqrt((Q11 - Q22) ** 2 + 4 * Q12 ** 2)) a2, b2 = max(a2t, b2t), min...
60d363066389d17a2d2bafa9b1c3733d884a7bcb
3,634,512
import sys import yaml def configure_app(args): """ configure the app, import swagger """ global application # global beacon_api global g2p_api def function_resolver(operation_id): """Map the operation_id to the function in this class.""" if '.' in operation_id: _, func...
7894b86cfeff66b1fd3a48fd6468b593151c6a22
3,634,513
def GausCV(traj,sample): """ returns matrix of gaussian CV's """ #m=7 - good m=10 pen=0. x = np.linspace(-5,5,m) y = np.linspace(-5,5,m) sigma_squared = 3.0 xx, yy = np.meshgrid(x,y) d = m**2 #print(xx) mu = np.concatenate((xx.reshape((-1,1)),yy.reshape((-1,1))),axis...
d366b5bc94fb1fb3b3201e0e54eaed3336067776
3,634,514
def _rgb_to_hex_string(rgb: tuple) -> str: """Convert RGB tuple to hex string.""" def clamp(x): return max(0, min(x, 255)) return "#{0:02x}{1:02x}{2:02x}".format(clamp(rgb[0]), clamp(rgb[1]), clamp(rgb[2]))
eafd166a67ac568cfad3da1fa16bdfcd054a914a
3,634,515
import math def update_one_contribute_score(user_total_click_num): """ itemcf update sim contribution score by user """ return 1/math.log10(1 + user_total_click_num)
b6dadc87150e33e1ba2d806e18856f10fd43035a
3,634,516
def NewtonRaphson(F, J, X0, eps=1e-4, mxiter=100): """ Solve nonlinear system F=0 by Newton's method. J is the Jacobian of F. Both F and J must be functions of x. At input, x holds the start value. The iteration continues until ||F|| < eps. Required Arguments: ------------------- F:...
f93858c5e540d67a8d78315705a6b199e2cba365
3,634,517
def export2tf2onnx(model_onnx, opset=None, verbose=True, name=None, rename=False, autopep_options=None): """ Exports an ONNX model to the :epkg:`tensorflow-onnx` syntax. :param model_onnx: string or ONNX graph :param opset: opset to export to (None to select the one from the ...
3ef4234a3e7e86634db3d7178a006789f0cac9d9
3,634,518
def default_interest_payment_date(): """ 利払日オブジェクトのデフォルト値 """ return { f'interestPaymentDate{index}': '' for index in range(1, 13) }
77d51cd5c7c76347a5c53e3d816985eeac1a568b
3,634,519
from datetime import datetime def log_message_prefix_generator(log_level: str) -> str: """ Parameters ---------- text: log_level log level e.g. "INFO", "WARN", ... Returns ---------- str logger prefix e.g. "[2020-06-17 20:21:12] [INFO]" """ ...
3b573632a9fce77a555531043eb3be0c92a862d5
3,634,520
from typing import Collection def delete_beatmap(request, collection_id, beatmap_entry_id): """View for delete beatmap entry""" collection = get_object_or_404(Collection, id=collection_id) beatmap_entry = get_object_or_404(BeatmapEntry, id=beatmap_entry_id, collection=collection) if request.user != co...
ce894b94287efa0a4b779537bde4122b78bd3378
3,634,521
import requests def interactors_form(path, name): """ Parse file and retrieve a summary associated with a token :param path: Absolute path to file to be read with custom interactor :param name: Name which identifies the sample :return: """ headers = { 'accept': 'application/json...
e193f0d8e1b9cf1fadcf4fff2668a09f755dab41
3,634,522
def _parent(child): """ Given a toast tile, return the address of the parent, as well as the corner of the parent that this tile occupies Returns ------- Pos, xcorner, ycorner """ parent = Pos(n=child.n - 1, x=child.x // 2, y=child.y // 2) left = child.x % 2 top = child.y % 2 ...
918feb49611be02c3ae686cbb0f06bf089187e92
3,634,523
from typing import List from typing import Dict import json def get_all_set_list(files_to_ignore: List[str]) -> List[Dict[str, str]]: """ This will create the SetList.json file by getting the info from all the files in the set_outputs folder and combining them into the old v3 structure. :param...
2f13a73d9a07e9790d23f0e6d961b6f3d058949f
3,634,524
def extinction_afterglow_galactic_dust_to_gas_ratio(time, lognh, factor=2.21, **kwargs): """ Extinction with afterglow models and a dust-to-gas ratio :param time: time in observer frame in days :param lognh: log10 hydrogen column density :param factor: factor to convert nh to av i.e., av = nh/facto...
1d1bd28482361e5efc666f0111270c2c15500a7c
3,634,525
def get_md_module(force_field): """ Returns the specific interface module that is referenced by force_field. """ if force_field.startswith('GROMACS'): return gromacs elif force_field.startswith('AMBER'): return amber elif force_field.startswith('NAMD'): return namd else: raise ValueError...
c6cc1c082f98cce3150f5e22b5cf0a6c3d654dd1
3,634,526
def select_student(database): """ Query student :param database: database name :return: student """ conn = create_connection(database) with conn: cur = conn.cursor() cur.execute("SELECT * FROM student") student = cur.fetchone() conn.commit() return student
8ab7f01d769af28df95bd3de62634cb7148d9829
3,634,527
import torch import copy def clones(module, N): """Produce N identical layers. """ return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
2def7cf89def4d598253ca48cb04e670ecb54dfd
3,634,528
import json def validate_search_results(search_results): """ Expects a list of mongo objects """ if not search_results: return json.dumps({"Result Count": 0, "Results": []}) final_objs = format_mongo_objs(search_results) response = {"Result Count": len(final_objs), "Re...
9209cf534a6553b0f1a3354a68e833dc832dc62b
3,634,529
def format_command_args(args): """Format a command by removing unwanted values Restrict what we keep from the values sent (with a SET, HGET, LPUSH, ...): - Skip binary content - Truncate """ length = 0 out = [] for arg in args: try: if isinstance(arg, (binary_typ...
2d79adce1f4ec466f2ffc56f93a8fade8421dca5
3,634,530
import unittest def suite() -> TestSuite: """You need to change the name of the test class here also.""" testSuite: TestSuite = TestSuite() # noinspection PyUnresolvedReferences testSuite.addTest(unittest.makeSuite(TestCoordinates)) return testSuite
ba8c21072dd6ee178ca4070b21607e95bcef3d93
3,634,531
def flow_diffusion_ode(C, X, pars): """ Scott's master, p. 60. X is the new Y and Z is the new X. """ C_N = C[-1] C_ = C[0] - pars["alpha"] * (C[0] - pars["Cg"]) * pars["dZ"] C_up = np.append(C[1:], C_N) C_down = np.append(C_, C[:-1]) d2CdZ2 = (C_up - 2 * C + C_down) * pars["1/dZ**2"] ...
8c0af7a42c3821cc6735a0971555e624c30b693f
3,634,532
import math def bl2xy(lon: float, lat: float): """ 大地2000,经纬度转平面坐标,3度带 Param: lon (float): 经度 lat (float): 纬度 Returns: (x , y) : x坐标对应经度,y坐标对应纬度 """ # 3.1415926535898/180.0 iPI = 0.0174532925199433 # 3度带 zoneWide = 3 # 长半轴 a = 6378137 # 扁率 f = 1...
4f2166d7878998da5373a4fa6aff5fcee6f32c61
3,634,533
import numpy def process_image(obj, img, config, each_blob=None, care_about_ar=True): """ :param obj: Object we're tracking :param img: Input image :param config: Controls :param each_blob: function, taking a SimpleCV.Blob as an argument, that is called for every candidate blob :return: Mask w...
e0de830cb843d6644634b08e80ace4ec911d16c5
3,634,534
def szepes_ml(local_d): """maximum likelihood estimator from local FSA estimates (for k=1) :param numpy.ndarray of float local_d: local FSA estimates :return: global ML-FSA estimate """ return hmean(local_d) / np.log(2)
00dd82e634f8606c7bbde24daf2fc1c64ac8492a
3,634,535
import os import distutils def find_aapt(): """Find the aapt (Android Asset Packaging Tool). Returns: Path to aapt if successful, empty string otherwise. """ # NOTE: This is far from perfect since this will pick up the first instance # of aapt installed and not necessarily the newest version. # Use t...
a2640fdc5f4e64207cb0f8450c583d4130e077c0
3,634,536
import math def create_low_latency_conv_model(fingerprint_input, model_settings, is_training): """Builds a convolutional model with low compute requirements. This is roughly the network labeled as 'cnn-one-fstride4' in the 'Convolutional Neural Networks for Small-footprint Key...
964be361d32e3b79e8909be4628ef6897f8d16e6
3,634,537
def sampling_from_enum_with_dirichlet_lm(enum_pool_dict_all, df_log2prob_by_syl, orig_seg_syl_df, lm_orig_dict, scale_num = 1000): """ get a sample lexicon with a orig language model params: @enum_pool_dict_all: enumerated words of all syllable lengths (filtered to make sure that all words are ...
94016dad1dc453ee217e57ade39f6478b670a9b5
3,634,538
def action_store(raw_val): """Auto type convert the value, if possible.""" if raw_val not in EMPTY_VALUES: return auto_type_convert(raw_val) else: return raw_val
3bed313c12f2a348cafd73111d3704c8c09198d9
3,634,539
def haversine_distance(coordinate: Point) -> float: """ Obtain the haversine distance between two cordinates points in the map :param coordinate: shapely.geometry.point :return: haversine distance in km: """ # MKAD coordinate lat1, lon1 = 55.755826, 37.6173 # address coordi...
6a730ec1afb9e5e131fd05be11176155c14a19b9
3,634,540
def route_home(): """ Renders the default page of the webserver, the leaderboard display""" return render_template("home.html", data=leaderboard_manager.get_sorted_data())
94c44fb65615e40b67d1729d706e3e968434be71
3,634,541
def get_org_details(organization_id): """ Return the details for an organization CLI Example: .. code-block:: bash salt-run digicert.get_org_details 34 Returns a dictionary with the org details, or with 'error' and 'status' keys. """ qdata = salt.utils.http.query( "{}/or...
4c19248b4ce0f6984e667924f481f914d8ba4fa8
3,634,542
def updatelimit(): """Update sensorlimits.""" script_root() print(request.form['id']) print(request.form['value']) #limit = SensorLimit.query.filter_by(id=request.form['id']).first() #print(request.form['id']) #print(limit) #limit.value = request.form['value'] #db.session.commit(...
46c67e995e642d84816e484017b22104b1867289
3,634,543
def trip_from_staging(conn, service, id_type = 'NUMERIC'): """Calculates the voronoi polygons for every active station in CitiBike and BayWheels Parameters ---------- conn: psycopg2.extensions.connection The connection to the database service: str The bike station service who...
cec99e09848f6fe828758960c5e53401a3f6116f
3,634,544
def six_plot(ts, *plotargs, **plotkwds): """ Output a matplotlib figure with full spectra, absorbance, area and stripchart. Figure should be plotly convertable through py.iplot_mpl(fig) assuming one is signed in to plotly through py.sign_in(user, apikey). Parameters ----------- title : st...
4977eb62f7cc72c50599f5c5e64383b79881ef3f
3,634,545
def woodbury_solve(vector, low_rank_mat, woodbury_factor, shift): """ Solves the system of equations: :math:`(sigma*I + VV')x = b` Using the Woodbury formula. Input: - vector (size n) - right hand side vector b to solve with. - woodbury_factor (k x n) - The result of calling woodbury_fa...
92b25fe675671408c560008e4093c1e4b35d3c42
3,634,546
import os def create_callbacks(model, data, ARGS): """At the end of each epoch, determine various callback statistics (e.g. ROC-AUC) :param model: Keras model :type model: :class:`tensorflow.keras.Model` :param data: Validation data - data sequences (codes, visits, numeric values) and classifier. ...
9a6075958dd2cb668de8228e139b42e3f0beaa16
3,634,547
from typing import Dict from datetime import datetime import decimal import socket def nxlog_callback(ch, method, properties, body): """ Callback on consumed message :param ch: consuming channel :param method: :param properties: :param body: message from queue :return: """ def nx...
f0199302b3e8f63ec3e6f6be0a9dc680954cfcc9
3,634,548
def get_user_by_email(email, create_pending=False): """finds a user based on his email address. :param email: The email address of the user. :param create_pending: If True, this function searches for external users and creates a new pending User in case ...
668230ec815c42ac48dfaffd8c79d9d8d9032fca
3,634,549
def get_offset_from_var(var): """ Helper for get_variable_sizes)_ Use this to calculate var offset. e.g. var_90, __saved_edi --> 144, -1 """ instance = False i=0 # Parse string i = var.rfind(' ')+1 tmp = var[i:-1] # Parse var if tmp[0] == 'v': tmp = tmp[4:]...
6cf58d6dc2ffcb7a78d98ed83c2dbcf05933af76
3,634,550
def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score): """ Takes as input a set of characters alphabet and three scores diag_score, off_diag_score, and dash_score. The function returns a dictionary of dictionaries whose entries are indexed by pairs of characters in alphabet plus '-'...
703c3ef7fb6899a46a26d55dae740705b6953adb
3,634,551
def _foldl_jax(fn, elems, initializer=None, parallel_iterations=10, # pylint: disable=unused-argument back_prop=True, swap_memory=False, name=None): # pylint: disable=unused-argument """tf.foldl, in JAX.""" if initializer is None: initializer = nest.map_structure(lambda el: el[0], elems) el...
1f876a90c25d52f52b9d0315670d68f1d58e9791
3,634,552
def MAD(a, c=0.6745, axis=None): """ Median Absolute Deviation along given axis of an array: median(abs(a - median(a))) / c c = 0.6745 is the constant to convert from MAD to std; it is used by default """ a = ma.masked_where(a!=a, a) if a.ndim == 1: d = ma.median(a) m...
39762026de548a077ccb4c599ad540a04d6c508e
3,634,553
import json def save_browser_tree_state(): """Save the browser tree state.""" data = request.form if request.form else request.data.decode('utf-8') old_data = get_setting('browser_tree_state') if old_data and old_data != 'null': if data: data = json.loads(data) old_data =...
6bdc8abc6c2189a6329f42f3df63f93c20aa9794
3,634,554
def prompt_yes_no(msg, default=False): """Prints the given message and continually prompts the user until they answer yes or no. Returns true if the answer was yes, false otherwise.""" default_str = "no" if default: default_str = "yes" result = prompt_w_default(msg, default_str, "^(Yes|yes|...
e42eb8e41c9251d0c5b046d445a6519b694cde4c
3,634,555
def persistence_distance( x: np.ndarray, y: np.ndarray, dimension: int=0, persistence_feature: str="persistence_landscape" ) -> float: """Distances are euclidean on persistence features. Args: x: First datset. y: Second dataset. dimension: Dimension for persistence diagr...
17f9242ae56ed1ff12111d17da3359060aaec963
3,634,556
import os def get_user_pysit_path(): """ Returns the full path to the users .pysit directory and creates it if it does not exist.""" path = os.path.join(os.path.expanduser('~'), '.pysit') if not os.path.isdir(path): os.mkdir(path) return path
a37f762642ce986dbf3d488bcf5760512d5a0b6c
3,634,557
def plot_pit_qq(pdf_ens, ztrue, qbins=101, title=None, code=None, show_pit=True, show_qq=True, pit_out_rate=None, outdir="", savefig=False) -> str: """Quantile-quantile plot Ancillary function to be used by class Metrics. Parameters ---------- pit: `PIT` object ...
565aa0f3e4920f2e4e7340081d46a58647386b79
3,634,558
def rel_mole_weight(ion, ion_num, oxy_num): """ Calculating Relative Molecular Weight :param ion: Each cation :param ion_num: Number of cations per cation :param oxy_num: The number of oxygen atoms corresponding to each cation :return: Relative molecular weight """ ion_dict = {'Si':28.0...
c1d38209fb5468cac693bc90cfb333afff43100b
3,634,559
def get_admin_token(chat_id): """ Get a administrador chat_id """ session = Session() admin = session.query(Admin).\ filter_by( chat_id=chat_id).first() session.close() if admin: return admin.token else: return None
dca8be42237f62fc6336cb3d22637d2406aedfc6
3,634,560
import os def _get_vocab(name: str): """Retrieve model configuration. Arguments: ---------- name {str} -- Name of the model. Raises: ------- FileNotFoundError: No vocab file provided with model. ValueError: Bad name or unavailable model. Returns: -------- ...
606cb864323cd3ace8a7c5b241fe74a8573a9e91
3,634,561
import os def filter_directory(directory: str, extension: str = '.py') -> str: """ Delete all files within the given directory with filenames not ending in the given extension """ for root, dirs, files in os.walk(directory): [os.remove(os.path.join(root, fi)) for fi in file...
e0ad4853c6ca8c2337dbd3c7b9901c7e6e9ce6a4
3,634,562
from typing import List import os def get_batches_for_prefix(gcs_client: storage.Client, prefix_path: str, ignore_subprefix="_config/", ignore_file=SUCCESS_FILENAME) -> List[List[str]]: """ This function creates batches of GCS ur...
172838ea9cd92f008eba453dbf45b13a569499b9
3,634,563
import collections import string def index_of_coincidence(text): """Index of coincidence of a string. This is low for random text, higher for natural langauge. """ stext = sanitise(text) counts = collections.Counter(stext) denom = len(stext) * (len(text) - 1) / 26 return ( sum(max...
a8a5e0f50dab24c3f3be525f30b6c5c5112a8a48
3,634,564
def get_allocations(jm_id:str) -> dict: """ Get Allocations Get project allocations for user currently connected to remote system. Parameters ---------- jm_id : str ID of Job Manager instance. Returns ------ allocations : dictionary Dictionary containing informatio...
d3ad268b7f56bd48d51b1d150644e39ee6e8b7f3
3,634,565
import struct def set_real(bytearray_: bytearray, byte_index: int, real) -> bytearray: """Set Real value Notes: Datatype `real` is represented in 4 bytes in the PLC. The packed representation uses the `IEEE 754 binary32`. Args: bytearray_: buffer to write to. byte_index: ...
bda32caab27adeae7c6710d4c26743b93533ccff
3,634,566
def LogNormalAddLoc(builder, loc): """This method is deprecated. Please switch to AddLoc.""" return AddLoc(builder, loc)
761522963da65b2ab05e4a687cad3ea44ebe3d1d
3,634,567
def newton_raphson(x, y): """ The implementation of the `Newton-Raphson <https://en.wikipedia.org/wiki/Newton%27s_method>`_ optimization procedure. It fits the knee curve :math:`f(x)` to the :math:`y` s of the corresponding :math:`x` s by tweaking the shape parameter :math:`c` from an initial guess....
6038effed89df29275123811f837f3d3e0f286a7
3,634,568
def _vx_no_BRST_check_massive_pp_zero(nhel, nsvahl): """ Parameters ---------- nhel: tf.Tensor, boson helicity of shape=() nsvahl: tf.Tensor, helicity times particle|anti-particle absolute value of shape=() Returns ------- tf.Tensor, of shape=(None,4) and dty...
bbe3fe72786f7944263254092da82d062310e10c
3,634,569
def rst2node(data, env): """Converts a reStructuredText into its node""" if not data: return parser = docutils.parsers.rst.Parser() document = docutils.utils.new_document("<>") document.settings = docutils.frontend.OptionParser().get_default_values() document.settings.tab_width = 4 d...
7ab3f8f80860a73e35cfb8ae2f1421c4b8a09533
3,634,570
def current_branch(): """ Return the current branch """ return f'{REPO.active_branch}'
c995896fbde35b2d07a06139efb8fc9bc72dd667
3,634,571
from datetime import datetime import hashlib def _create_config_txn(pubkey, signing_key, setting_key_value): """Creates an individual sawtooth_config transaction for the given key and value. """ setting_key = setting_key_value[0] setting_value = setting_key_value[1] nonce = str(datetime.dateti...
5a4057657dc41c6403983d9ecded8b7194c5989e
3,634,572
def round_unit(x, unit): """ 按特定单位量对x取倍率 round_int偏向于工程代码简化,round_unit偏向算法,功能不太一样,所以分组不同 Args: x: 原值 unit: 单位量 Returns: 新值,是unit的整数倍 >>> round_unit(1.2, 0.5) 1.0 >>> round_unit(1.6, 0.5) 1.5 >>> round_unit(7, 5) 5 >>> round_unit(13, 5) 15 """ r...
b59f5f74fbf4622d1fa5b3fd7af6386b39eac784
3,634,573
import os import io def read(*paths): """Read a text file.""" basedir = os.path.dirname(__file__) full_path = os.path.join(basedir, *paths) contents = io.open(full_path, encoding='utf-8').read().strip() return contents
30b2310917a8b3f42fed6ab27dca2c087db02436
3,634,574
def centroid_1D(image, xpeak, xhw, debug=False): """ Fine location of the target by calculating the centroid for the region centered on the brightest checkbox. Performs the centroid calculation on the checkbox region calculated using the function checkbox_1D(). Keyword arguments: ...
49d8c3054c62bc00e96e028a17d7c662ef0b7066
3,634,575
import typing import json async def async_get_preference(connection, key: PreferenceKey) -> typing.Union[None, typing.Any]: """ Gets a preference by key. :param key: The preference key, from the `PreferenceKey` enum. :returns: An object with the preferences value, or `None` if unset and no default ex...
4c3c5d4ee71d0e7dc85b7ef85075137dd639ee25
3,634,576
def index(): """ View function for the index page. """ user: User = current_user return \ "<div>" +\ f"<a href=\"{url_for('auth.logout')}\">Log out</a>" +\ f"<h1>Welcome {str(user)}</h1>" +\ "</div>"
161d6bf4968bd3bed65d81470e33fff45a101329
3,634,577
import socket def wait_for_socket(hostname, port): # TODO: upstream this modified version into flocker (it was copied from # flocker.acceptance.test_api) """ Wait until remote TCP socket is available. :param str hostname: The host where the remote service is running. :return Deferred: Fires ...
d62c0f3ecb253fa3bdd5794f85171fb3fc794ad9
3,634,578
import typing def format_event_pull_request(data: typing.Dict[str, typing.Any]) -> str: """ Format a GitHub pull_request event into a string. """ resp = f"{format_author(data['sender'])} " description = f"{format_issue_or_pr(data['pull_request'])} in {format_repo(data['repository'])}" if data[...
1c5dad5c4ca0218b14c46da6abc0615dbe7f8b6b
3,634,579
import math def project_gdf(gdf, to_crs=None, to_latlong=False): """ lovingly copied from OSMNX <https://github.com/gboeing/osmnx/blob/master/osmnx/projection.py> Project a GeoDataFrame to the UTM zone appropriate for its geometries' centroid. The simple calculation in this function works well fo...
984d3f4cdfdaec434ffc1049d189e0e7532afeae
3,634,580
import pathlib import glob import shutil import sys def _HadoopMovePartFile(local_path, file_extension: str): """ Internal function moving the single part file from a hadoop path to the local path Args: local_path: the local path where to export file_extension: the file extension whic...
c236aa7c154296cf178255a913da57fdd4d65904
3,634,581
def get_shape(obj): """ Get the shape of a :code:'numpy.ndarray' or of a nested list. Parameters(obj): obj: The object of which to determine the shape. Returns: A tuple describing the shape of the :code:`ndarray` or the nested list or :code:`(1,)`` if obj is not an instance of ...
d02d755f4b9e4a4dbde6c87ddfe0b5729a8c158e
3,634,582
import builtins def help_ui_check_answer(capsys, r_input): """a function to calculate an equation from a combination of four numbers to get 24""" final_result = '' with mock.patch.object(builtins, 'input', lambda _: r_input): g_c.ui_check_answer() out, err = capsys.readouterr() ...
1cae7d98ef1a87c4a53416f44d5c49312fced197
3,634,583
import collections def precision_recall(classifier, testfeats): """ computes precision and recall of a classifier """ refsets = collections.defaultdict(set) testsets = collections.defaultdict(set) for i, (feats, label) in enumerate(testfeats): refsets[label].add(i) observed = classif...
97a76fe595b26a9a5a307e799659fb96f1642941
3,634,584
import logging def set_power_state_xavier(power_state: XavierPowerState) -> None: """Record the current power state and set power limit using nvpmodel.""" # Set power limit to the specified value if is_xavier_agx(): platform = "xavier_agx" elif is_xavier_nx(): platform = "xavier_nx" ...
8b843acfff292b61dccf8ebc6433cb04446e5a7e
3,634,585
from typing import Any from typing import List def as_list(x: Any) -> List[Any]: """Wrap argument into a list if it is not iterable. :param x: a (potential) singleton to wrap in a list. :returns: [x] if x is not iterable and x if it is. """ # don't treat strings as iterables. if isinstance(x, ...
4b1b26857d209a9f5b142908e3a35b1ce7b05be4
3,634,586
def _sort_destinations(destinations): """ Takes a list of destination tuples and returns the same list, sorted in order of the jumps. """ results = [] on_val = 0 for dest in destinations: if len(results) == 0: results.append(dest) else: while on_val <...
302480ef09f4b5a402a5c568c5d35d717db8c851
3,634,587
def Q8(): """ Return the matroid `Q_8`, represented as circuit closures. The matroid `Q_8` is a 8-element matroid of rank-4. It is a smallest non-representable matroid. See [Oxl2011]_, p. 647. EXAMPLES:: sage: from sage.matroids.advanced import setprint sage: M = matroids.named_ma...
469ca05d13655ee19618dd9ffa3001c0792982ac
3,634,588
import re def remove_url(text): """ Supprime les URLs :param text: texte à transformer :return: texte transformé """ return re.sub(r'http\S+', '', text)
d0f3716808863d5e868da1efc4a7bb16ffa47ac1
3,634,589
def T_sun(a: float, m2_over_m1: float) -> float: """ T = 2 * pi * sqrt(a^3) / (K * sqrt(1 + m2/m1)) :param a: semi-major axis :type a: float :param m2_over_m1: m2 / m1 :type m2_over_m1: float :return: translation period :rtype: float """ return 2 * np.pi * np.sqrt(a * a * a / m...
6b88aba027a57a6a2b1d66bd7accdcde75d5f20d
3,634,590
def deleteDuplicates(head: ListNode) -> ListNode: """解法:重点已排序""" if not head or not head.next: return head pre, ptr =head, head.next while pre and ptr: if pre.val == ptr.val: pre.next = ptr.next ptr = pre.next else: pre = ptr ptr = ptr.next...
09ac88103f9fb4ef85550ab201e0b05e1dd96dca
3,634,591
def predict_spectrum(svrs, X_, mask=None, scaler=None): """ predict a single spectrum given a list of svrs & mask Parameters ---------- svrs : list a list of svr objects X_ : ndarray the labels of predicted spectra mask : None | bool array predict the pixels where mask==...
49bc83c6f9a5bce2bdadc6a8b72313c95ab89c85
3,634,592
def _type_operand(): """ Parser for argument of a binary type operation. """ return binder_type() | agda_vars()
308b95cdd5378d7347ec4dd583ce387776e178cd
3,634,593
def kernel(process): """ Get the kernel id from a process """ for arg in process.cmdline(): if arg.endswith('.json') and '/kernel-' in arg: return splitext(basename(arg).replace('kernel-', ''))[0]
27e1235cf47bbb6c4db6f1853d51b2710a913212
3,634,594
import json def debug_status(status, error) -> str: """Return a debug string for the autoscaler.""" if not status: status = "No cluster status." else: status = status.decode("utf-8") as_dict = json.loads(status) lm_summary = LoadMetricsSummary(**as_dict["load_metrics_report...
579fa8aba2a62f7dcd44a09343060e033aa552b9
3,634,595
def solve_ciknock( Sigma, tol=1e-5, num_iter=10, ): """ Computes S-matrix used to generate conditional independence knockoffs. Parameters ---------- Sigma : np.ndarray ``(p, p)``-shaped covariance matrix of X tol : float Minimum permissible eigenvalue of 2Sigma - S and S...
bf4183a3c7a0660d0f99bab27d83213e67892bc6
3,634,596
def main(request): """ Main view. Just shows the status of repos, with open prs, as well as a short list of recent jobs. Input: request: django.http.HttpRequest Return: django.http.HttpResponse based object """ limit = 30 repos, evs_info, default = get_user_repos_info(request...
4c9cdffeca6eaf0494c82bc834cf872ef67086aa
3,634,597
def is_match(text, full_hashed_value, **options): """ gets a value indicating that given text's hash is identical to given full hashed value. :param str text: text to be hashed. :param str full_hashed_value: full hashed value to compare with. :rtype: bool """ return get_component(HashingP...
fbafabe38626c5e189827c984d0c7af970623460
3,634,598
def remove_metrics(metrics_in, metric_collection, reduced_set=False, portraitplot=False): """ Removes some metrics from given list Inputs: ------ :param metrics_in: list of string List of metrics. :param metric_collection: string Name of a metric collection. **Optional argum...
2c7c26a1dfcb9d58ac095caf76e618d52b761eca
3,634,599