content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def read_key_value(file): """支持注释,支持中文""" return_dict = {} lines = readlines(file) for line in lines: line = line.strip().split(':') if line[0][0] == '#': continue key = line[0].strip() value = line[1].strip() return_dict[key] = value return return...
9fdac43783c066872a05cbd59488add7a2dc54c0
19,733
def binarize_image(image): """Binarize image pixel values to 0 and 255.""" unique_values = np.unique(image) if len(unique_values) == 2: if (unique_values == np.array([0., 255.])).all(): return image mean = image.mean() image[image > mean] = 255 image[image <= mean] = 0 r...
6e4a621b0a2ff06d6a6bf5c0eb45f1028e6d526f
19,734
from typing import Type def LineMatcher_fixture(request: FixtureRequest) -> Type["LineMatcher"]: """A reference to the :class: `LineMatcher`. This is instantiable with a list of lines (without their trailing newlines). This is useful for testing large texts, such as the output of commands. """ re...
86c05df8f099ba66e62ae0bb071b2999cbb4f082
19,735
def Delay(opts, args): """Sleeps for a while @param opts: the command line options selected by the user @type args: list @param args: should contain only one element, the duration the sleep @rtype: int @return: the desired exit code """ delay = float(args[0]) op = opcodes.OpTestDelay(duration=...
c9ecd6cb3dbdcd5ae48c527f2f6769789b05664d
19,736
def logout(): """ Simply loading the logout page while logged in will log the user out """ logout_user() return render_template(f"{app_name}/logout.html")
33191c6870a0aac8fcdebb0349b93196e2ed0ba8
19,737
def duration_to_timedelta(obj): """Converts duration to timedelta >>> duration_to_timedelta("10m") >>> datetime.timedelta(0, 600) """ matches = DURATION_PATTERN.search(obj) matches = matches.groupdict(default="0") matches = {k: int(v) for k, v in matches.items()} return timedelta(**matc...
fcfa67e6667b232a6647cb71fff543a45a6d3475
19,739
async def create_mock_hlk_sw16_connection(fail): """Create a mock HLK-SW16 client.""" client = MockSW16Client(fail) await client.setup() return client
14589398e268a76637994f2883f2cd824a14a81b
19,740
def inv_dist_weight(distances, b): """Inverse distance weight Parameters ---------- distances : numpy.array of floats Distances to point of interest b : float The parameter of the inverse distance weight. The higher, the higher the influence of closeby stations...
c7e857bba312277b193ce5eda7467b8b0bf8bd75
19,741
import pytz def load_inferred_fishing(table, id_list, project_id, threshold=True): """Load inferred data and generate comparison data """ query_template = """ SELECT vessel_id, start_time, end_time, nnet_score FROM TABLE_DATE_RANGE([{table}], TIMESTAMP('{year}-01-01'), TIMESTAMP(...
fba7e007b38d141e91c0608cbd609a2d3b474b4b
19,742
from typing import Any def is_optional(value: Any) -> CheckerReturn: """ It is a rather special validator because it never returns False and emits an exception signal when the value is correct instead of returning True. Its user should catch the signal to short-circuit the validation chain. """ ...
25e45617ca5584dc2470d9e76ef884596c465917
19,743
from typing import Union from typing import Tuple from typing import List def approximate_bounding_box_dyn_obstacles(obj: list, time_step=0) -> Union[ Tuple[list], None]: """ Compute bounding box of dynamic obstacles at time step :param obj: All possible objects. DynamicObstacles are filtered. :re...
3a8fc28c2a47b50b9d0acc49f0818031e357fffa
19,744
def binary_class_accuracy_score(y_pred, data): """LightGBM binary class accuracy-score function. Parameters ---------- y_pred LightGBM predictions. data LightGBM ``'Dataset'``. Returns ------- (eval_name, eval_result, is_higher_better) ``'eval_name'`` : string ...
53f68931a96e3d32bed622dae09239ee2b96d762
19,746
def is_prime(n): """Given an integer n, return True if n is prime and False if not. """ return True
17d2d7bdf95a9d3e037e911a3271688013413fb7
19,748
import logging def get_request_file(): """ Method to implement REST API call of GET on address /file """ try: content_file = open("html/file_get.html", "r") content = content_file.read() except: logging.info("Could not load source HTML file '%s'") raise return ...
7a084d5455b1797d851388ac40de23c5c35fb381
19,752
from collections import Counter from typing import Iterable def sock_merchant(arr: Iterable[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([6, 5, 2, 3, 5, 2, 2, 1, 1, 5, 1, 3, 3, 3, 5]) 6 """ count = Counter(arr).values() ret = sum(n // 2 ...
1b3b8d37ccb3494ed774e26a41ebba32c87a632c
19,753
def new_user_registration(email: str) -> dict: """Alert the CIDC admin mailing list to a new user registration.""" subject = "New User Registration" html_content = ( f"A new user, {email}, has registered for the CIMAC-CIDC Data Portal ({ENV}). If you are a CIDC Admin, " "please visit the a...
ee4c57e45d15b8e65bd8e702633d527bc2f6db1f
19,754
def article_detail(): """文章详情""" id = request.form.get('id') if id is None: raise Exception('ARTICLE_NOT_EXIST') article = Article.find(id) if article is None: raise Exception('ARTICLE_NOT_EXIST') # 获取标签 if article.tags is None: article.tags = [] else: al...
534cb77384b65cb4b88bedd1a82daeb93766714a
19,755
def add_state_names_column(my_df): """ Add a column of corresponding state names to a dataframe Params (my_df) a DataFrame with a column called "abbrev" that has state abbreviations. Return a copy of the original dataframe, but with an extra column. """ new_df = my_df.copy() names_map ...
4a9eb49ef2cda11d8135eb33ec43d99422e067b6
19,756
import glob def list_subdir_paths(directory): """ Generates a list of subdirectory paths :param directory: str pathname of target parent directory :return: list of paths for each subdirectory in the target parent directory """ subdir_paths = glob("{}/*/".format(directory)) return ...
df8ec80096b900ad8ceac3bc013fe47b21b4fd54
19,757
import math def logic_method_with_bkg(plots_per_cycle, cycle_time, sigma_s=160, m=3, n=4): """ :param plots_per_cycle: :param cycle_time: :param sigma_s: :param m: :param n: :return: """ N = plots_per_cycle.shape[0] # number of cycles tracks = [] # ret track_cnt = 0 ...
a77e8a9d116187dce674c33ca098012bb6b22363
19,758
from typing import Union def bias_scan( data: pd.DataFrame, observations: pd.Series, expectations: Union[pd.Series, pd.DataFrame] = None, favorable_value: Union[str, float] = None, overpredicted: bool = True, scoring: Union[str, ScoringFunction] = "Bernoulli", num_iters: int = 10, pena...
735ccc6c3054e981a7aee9681d892e226316ed41
19,759
def int_from_bin_list(lst): """Convert a list of 0s and 1s into an integer Args: lst (list or numpy.array): list of 0s and 1s Returns: int: resulting integer """ return int("".join(str(x) for x in lst), 2)
a41b2578780019ed1266442d76462fb89ba2a0fb
19,760
def validate_array_input(arr, dtype, arr_name): """Check if array has correct type and is numerical. This function checks if the input is either a list, numpy.ndarray or pandas.Series of numerical values, converts it to a numpy.ndarray and throws an error in case of incorrect data. Args: a...
72829dad46aa6e5054cd0d49ff0206083781bddd
19,761
from sklearn.manifold import TSNE from sklearn.cluster import AgglomerativeClustering from sklearn.preprocessing import StandardScaler def ClassifyBehavior(data, bp_1="snout",bp_2="ear_L", bp_3="ear_R", bp_4="tail", dimensions = 2,distance=28,**kwargs): """ Returns an array with the cluster by frame, an array...
002e11bd0b6050fcfa8b50df0f0b24a3cc36bed7
19,762
def grab_inputs(board): """ Asks for inputs and returns a row, col. Also updates the board state. """ keepasking = True while keepasking: try: row = int(input("Input row")) col = int(input("Input column ")) except (EOFError, KeyboardInterrupt): pri...
0fb840348ff645d9f2a48e1c028d99bff0bf31fe
19,763
def start_session(): """ This function is what initializes the application.""" welcome_msg = render_template('welcome') return question(welcome_msg)
ce666a48f078e49a0df98b5087c71cb1e548e905
19,764
def solve(filename): """ Run a sample, do the analysis and store a program to apply to a test case """ arc = Arc(filename) arc.print_training_outputs() return arc.solve()
2a23021bb31508fd67c4be178684bb2da7d1d7c9
19,765
from typing import Sequence def extract_item(item, prefix=None, entry=None): """a helper function to extract sequence, will extract values from a dicom sequence depending on the type. Parameters ========== item: an item from a sequence. """ # First call, we define entry to be a lookup dic...
a4c8c99bcd54baefdbaa95469bb3a289c2811cfc
19,766
def route_counts(session, origin_code, dest_code): """ Get count of flight routes between origin and dest. """ routes = session.tables["Flight Route"] # airports = session.tables["Reporting Airport"] # origin = airports["Reporting Airport"] == origin_code origin = SelectorClause( "Reporting ...
ad35a36b6874bcf45107d7217acdb6bae097b305
19,767
from pathlib import Path def generate_master_bias( science_frame : CCDData, bias_path : Path, use_cache : bool=True ) -> CCDData: """ """ cache_path = generate_cache_path(science_frame, bias_path) / 'bias' cache_file = cache_path / 'master.fits' if use_cache and cache_...
207ca95109694d16e154088c7e3a12880f01d037
19,768
def RetryOnException(retry_checker, max_retries, sleep_multiplier=0, retry_backoff_factor=1): """Decorater which retries the function call if |retry_checker| returns true. Args: retry_checker: A callback function which should take an except...
a721e14c7d5d98e2151f4108dcff18cb0de225e3
19,769
import csv import itertools def ParseCsvFile(fp): """Parse dstat results file in csv format. Args: file: string. Name of the file. Returns: A tuple of list of dstat labels and ndarray containing parsed data. """ reader = csv.reader(fp) headers = list(itertools.islice(reader, 5)) if len(headers...
39381d0f9eaab1ab139d4d660257aeaec6e765ca
19,770
def uid_to_device_name(uid): """ Turn UID into its corresponding device name. """ return device_id_to_name(uid_to_device_id(uid))
e4ec879bb1619fd1e215c94084117b3ce6b237bc
19,771
def zonal_convergence(u, h, dx, dy, dy_u, ocean_u): """Compute convergence of zonal flow. Returns -(hu)_x taking account of the curvature of the grid. """ res = create_var(u.shape) for j in range(u.shape[-2]): for i in range(u.shape[-1]): res[j, i] = (-1) * ( h[j...
42a0ee78e0c4d8f78a600a9dd72aa03aa104f560
19,772
def filterPoints(solutions, corners): """Remove solutions if they are not whithin the perimeter. This function use shapely as the mathematical computaions for non rectangular shapes are quite heavy. Args: solutions: A list of candidate points. corners: The perimeter of the garden (lis...
55c6e824d46e934eb30c6ecca45f516f09f0bff2
19,773
from typing import Set def get_migrations_from_old_config_key_startswith(old_config_key_start: str) -> Set[AbstractPropertyMigration]: """ Get all migrations where old_config_key starts with given value """ ret = set() for migration in get_history(): if isinstance(migration, AbstractProper...
c8224af6e9a675ed940bf61de984a8dd01f634d5
19,774
def bbox_mapping(bboxes, img_shape, scale_factor, flip, flip_direction, # ='horizontal', tile_offset): """Map bboxes from the original image scale to testing scale.""" new_bboxes = bboxes * bboxes.new_tensor(scale_factor) ...
a5fb8283eb6c379ef516db3a72c50d34c58ea8e6
19,775
import torch def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6): """Convert 3x4 rotation matrix to 4d quaternion vector This algorithm is based on algorithm described in https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201 Args: rotation_matrix (Te...
3198dcd9f7a058a54be0d607cc66f543ea8e46f8
19,777
import calendar from datetime import datetime def get_first_day_and_last_day_by_month(months=0): """获取某月份的第一天的日期和最后一天的日期 :param months: int, 负数表示过去的月数,正数表示未来的 :return tuple: (某月第一天日期, 某月最后一天日期) """ day = get_today() + relativedelta(months=months) year = day.year month = day.month # ...
1aea5aa0c1abcc8382212315f0e34cf0f33968b9
19,778
def kmeans(X, C): """The Loyd's algorithm for the k-centers problems. X : data matrix C : initial centers """ C = C.copy() V = np.zeros(C.shape[0]) for x in X: idx = np.argmin(((C - x)**2).sum(1)) V[idx] += 1 eta = 1.0 / V[idx] C[idx] = (1.0 - eta) * C[idx] + ...
3006c10bf9091a39f4808781e4b484fc24f2ae3f
19,779
def data_block(block_str): """ Parses all of the NASA polynomials in the species block of the mechanism file and subsequently pulls all of the species names and thermochemical properties. :param block_str: string for thermo block :type block_str: str :return data_block: all ...
bfcf457e164002cd4ab8c6c852117ebe24f437ab
19,781
from functools import reduce from re import S def risch_norman(f, x, rewrite=False): """Computes indefinite integral using extended Risch-Norman algorithm, also known as parallel Risch. This is a simplified version of full recursive Risch algorithm. It is designed for integrating various clas...
12dd2cbd724566344d73bff48ed46b33d2b84730
19,782
def preprocess_spectra(fluxes, interpolated_sn, sn_array, y_offset_array): """preprocesses a batch of spectra, adding noise according to specified sn profile, and applies continuum error INPUTS fluxes: length n 2D array with flux values for a spectrum interpolated_sn: length n 1D array with relative sn ...
552d42b3835f3bc60930ae6f05f1544c924e940b
19,785
import json def read_config(path=None): """ Function for reading in the config.json file """ #create the filepath if path: if "config.json" in path: file_path = path else: file_path = f"{path}/config.json" else: file_path = "config.json" ...
3e3612879645509acb74f184085f7e584afbf822
19,786
import json def ema_incentive(ds): """ Parse stream name 'incentive--org.md2k.ema_scheduler--phone'. Convert json column to multiple columns. Args: ds: Windowed/grouped DataStream object Returns: ds: Windowed/grouped DataStream object. """ schema = StructType([ Struct...
ad6d6a08906dc5aab5a1ea2d0895eb84eac44f44
19,787
def read_fingerprint(finger_name: str) -> np.ndarray: """ Given the file "x_y_z" name this function returns a vector with the fingerprint data. :param finger_name: A string with the format "x_y_z". :return: A vector (1x256) containing the fingerprint data. """ base_path = "rawData/QFM16_" ...
21b88afffdb016699ad6a0ed635931096ebe8bc1
19,788
def read_data(data_path): """This function reads in the histogram data from the provided path and returns a pandas dataframe """ histogram_df = None # Your code goes here return histogram_df
5b927246c9298743c22d8a9fc497175aa9600c24
19,790
def get_number_of_tickets(): """Get number of tickets to enter from user""" num_tickets = 0 while num_tickets == 0: try: num_tickets = int(input('How many tickets do you want to get?\n')) except: print ("Invalid entry for number of tickets.") return num_tickets
3703a4ed64867a9884328c09f0fd32e763265e95
19,792
def scrape(file): """ scrapes rankings, counts from agg.txt file""" D={} G={} with open(file,'r') as f: for line in f: L = line.split(' ') qid = L[1][4:] if qid not in D: D[qid]=[] G[qid]=[] #ground truth ...
cad6525a9ae43f8366ae7e0efec14dd8b2921d27
19,793
import hashlib import binascii def private_key_to_WIF(private_key): """ Convert the hex private key into Wallet Import Format for easier wallet importing. This function is only called if a wallet with a balance is found. Because that event is rare, this function is not significant to the main pipeline of the ...
20e7a767fdfb689f586fc566a94ec37f86a88e52
19,794
def woodbury_solve_vec(C, v, p): """ Vectorzed woodbury solve --- overkill Computes the matrix vector product (Sigma)^{-1} p where Sigma = CCt + diag(exp(a)) C = D x r real valued matrix v = D dimensional real valued vector The point of this function is that you never h...
875ab6709b82cd8865a4396b88cbd10a2847e608
19,795
def subsample(inputs, factor, scope=None): """Subsamples the input along the spatial dimensions. Args: inputs: A `Tensor` of size [batch, height_in, width_in, channels]. factor: The subsampling factor. scope: Optional variable_scope. Returns: output: A `Tensor` of size [batch, height_out, width_ou...
7e0cbcd5d709405b32ba79c93cbf1ef6e98195f6
19,796
def pvfactors_engine_run(data, pvarray_parameters, parallel=0, mode='full'): """My wrapper function to launch the pvfactors engine in parallel. It is mostly for Windows use. In Linux you can directly call run_parallel_engine. It uses MyReportBuilder to generate the output. Args: data (pandas Da...
1118838fed39e19e31997db9102fdba70283bed8
19,797
def get_service_button(button_text, service, element="#bottom_right_div"): """ Generate a button that calls the std_srvs/Empty service when pressed """ print "Adding a service button!" return str(render.service_button(button_text, service, element))
ce8e2a0ec029762c4e19210c9986aef7e78b55d9
19,798
def create_train_test_set(data, labels, test_size): """ Splits dataframe into train/test set Inputs: data: encoded dataframe containing encoded name chars labels: encoded label dataframe test_size: percentage of input data set to use for test set Returns: data_train: Su...
ffeedf0cf4b7b8b1ffa552f0573d33263d216d99
19,799
def hdf_diff(*args, **kwargs): """:deprecated: use `diff_blocks` (will be removed in 1.1.1)""" return diff_blocks(*args, **kwargs)
3c05a908cc32c2ba4e481ff0de41f78249e2ef02
19,801
import glob def determine_epsilon(): """ We follow Learning Compact Geomtric Features to compute this hyperparameter, which unfortunately we didn't use later. """ base_dir = '../dataset/3DMatch/test/*/03_Transformed/*.ply' files = sorted(glob.glob(base_dir), key=natural_key) etas = [] for ...
a6af243ebeb37e046e9f23c86080822bff4f490d
19,802
def sort_ipv4_addresses_with_mask(ip_address_iterable): """ Sort IPv4 addresses in CIDR notation | :param iter ip_address_iterable: An iterable container of IPv4 CIDR notated addresses | :return list : A sorted list of IPv4 CIDR notated addresses """ return sorted( ip_address_iterable, ...
97517b2518b81cb8ce4cfca19c5512dae6bae686
19,803
def _subattribute_from_json(data: JsonDict) -> SubAttribute: """Make a SubAttribute from JSON data (deserialize) Args: data: JSON data received from Tamr server. """ cp = deepcopy(data) d = {} d["name"] = cp["name"] d["is_nullable"] = cp["isNullable"] d["type"] = from_json(cp["t...
4fde9e1eb456fd42b8ad8e49ad893a62ba01eba4
19,804
def compare_asts(ast1, ast2): """Compare two ast trees. Return True if they are equal.""" # import leo.core.leoGlobals as g # Compare the two parse trees. try: _compare_asts(ast1, ast2) except AstNotEqual: dump_ast(ast1, tag='AST BEFORE') dump_ast(ast2, tag='AST AFTER') ...
32ab70f1fa31f9ae6cab4e9f5ba91ff71a9e79f8
19,805
import json def shit(): """Ready to go deep into the shit? Parse --data from -X POST -H 'Content-Type: application/json' and send it to the space background """ try: body = json.loads(request.data) except Exception as e: abort(400, e) if not body: abort(4...
bdc435566aeaafac8144775188478cb28724802b
19,806
def clear_settings(site_name): # untested - do I need/want this? """update settings to empty dict instead of initialized) """ return update_settings(site_name, {})
a6cbd9bc43ce5bc7159bc75d4cab8c703d73e8cd
19,807
def reorder_jmultis_det_terms(jmulti_output, constant, seasons): """ In case of seasonal terms and a trend term we have to reorder them to make the outputs from JMulTi and sm2 comparable. JMulTi's ordering is: [constant], [seasonal terms], [trend term] while in sm2 it is: [constant], [trend term], [...
91fd48e14addf264f00a6e898af8d934bcd84cca
19,808
def test_require_gdal_version_param_values(): """Parameter values are allowed for all versions >= 1.0""" for values in [('bar',), ['bar'], {'bar'}]: @require_gdal_version('1.0', param='foo', values=values) def a(foo=None): return foo assert a() is None assert a('bar...
de11d8f6f0720c1b3ef6aa957f8386e8436b1e73
19,809
def nav_get_element(nav_expr, side, dts, xule_context): """Get the element or set of elements on the from or to side of a navigation expression' This determines the from/to elements of a navigation expression. If the navigation expression includes the from/to component, this will be evaluated. The resu...
db29b0c2e7832c2b386dd602c77d18a37c2c1307
19,810
def do_pivot(df: pd.DataFrame, row_name: str, col_name: str, metric_name: str): """ Works with df.pivot, except preserves the ordering of the rows and columns in the pivoted dataframe """ original_row_indices = df[row_name].unique() original_col_indices = df[col_name].unique() pivoted = df.p...
70df87eb7d1ca19116ec04854bee635a66f02908
19,811
def batch_norm_for_fc(inputs, is_training, bn_decay, scope): """ Batch normalization on FC data. Args: inputs: Tensor, 2D BxC input is_training: boolean tf.Varialbe, true indicates training phase bn_decay: float or float tensor variable, controling moving average weight scope: ...
e6a13c50b021785ddcb278c449ba6f9be9271106
19,812
def stat(file_name): """ Read information from a FreeSurfer stats file. Read information from a FreeSurfer stats file, e.g., `subject/stats/lh.aparc.stats` or `aseg.stats`. A stats file is a text file that contains a data table and various meta data. Parameters ---------- file_name: string ...
bf64bf488d34a32eebcb66472a3fa567bf5a368d
19,813
def _r_long(int_bytes): """Convert 4 bytes in little-endian to an integer. XXX Temporary until marshal's long function are exposed. """ x = int_bytes[0] x |= int_bytes[1] << 8 x |= int_bytes[2] << 16 x |= int_bytes[3] << 24 return x
7b40bf05c9d47c7921b1377f0d2235c483e6ba2e
19,814
from typing import Union from typing import Dict from typing import Any from typing import Iterable from typing import Type from typing import Optional import dataclasses from typing import TypeVar from typing import cast def parse_model(data: Union[Dict[str, Any], Iterable[Any], Any], cls: Union[Type...
85ba92ac4c3e9df8e96612017b94db73ea53d19e
19,815
def findTopEyelid(imsz, imageiris, irl, icl, rowp, rp, ret_top=None): """ Description: Mask for the top eyelid region. Input: imsz - Size of the eye image. imageiris - Image of the iris region. irl - icl - rowp - y-coordinate of the inner circle centre. rp - radius of the inner circ...
9c01e0966a1800ed76f5370cbc382a801af08d67
19,816
def script_with_queue_path(tmpdir): """ Pytest fixture to return a path to a script with main() which takes a queue and procedure as arguments and adds procedure process ID to queue. """ path = tmpdir.join("script_with_queue.py") path.write( """ def main(queue, procedure): queue.put...
7c2c2b4c308f91d951496c53c9bdda214f64c776
19,817
import configparser def readini(inifile): """ This function will read in data from a configureation file. Inputs inifile- The name of the configuration file. Outputs params - A dictionary with keys from INIOPTIONS that holds all of the plotting parameters. ...
eb5800f00cc8e58557e11fb9ff525e7f407c9eab
19,818
def get_param_store(): """ Returns the ParamStore """ return _PYRO_PARAM_STORE
d71ab10f2029fab735268956590094d8c94dd150
19,819
def secret_add(secret): """ Return a lambda that adds the argument from the lambda to the argument passed into secret_add. :param secret: secret number to add (integer) :return: lambda that takes a number and adds it to the secret """ return lambda addend: secret + addend
151f1cff9f0e0bbb43650d63592ba0c2cb05611e
19,820
def morseToBoolArr(code, sps, wpm, fs=None): """ morse code to boolean array Args: code (str): morse code sps: Samples per second wpm: Words per minute fs: Farnsworth speed Returns: boolean numpy array """ dps = wpmToDps(wpm) # dots per second baseSampleC...
90b4225a2a9979ac7f813a1f964b64ef9310ee23
19,821
import csv import array def LaserOptikMirrorTransmission(interpolated_wavelengths,refractive_index = "100", shift_spectrum=7,rescale_factor=0.622222): """ Can be used for any wavelengths in the range 400 to 800 (UNITS: nm) Uses supplied calculation from LaserOptik Interpolate over selected wavelengths: returns a ...
a3eafd7a788ddcfdedd8e25081f6e7cc1fd03cc5
19,822
import math def menu(prompt, titles, cols=1, col_by_col=True, exc_on_cancel=None, caption=None, default=None): """Show a simple menu. If the input is not allowed the prompt will be shown again. The input can be cancelled with EOF (``^D``). The caller has to take care that the menu will fit ...
d4d24cddf40f314c31415685c4eecdc51da2aca2
19,823
from typing import Dict from typing import Any def dict_to_annotation(annotation_dict: Dict[str, Any], ignore_extra_keys = True) -> Annotation: """Calls specific Category object constructor based on the structure of the `annotation_dict`. Args: annotation_dict (Dict[str, Any]): One of COCO Annotation...
846c353ab4d15a0558c5cabced30e14a57b5ed64
19,824
def getAggregation(values): """ Produces a dictionary mapping raw states to aggregated states in the form {raw_state:aggregated_state} """ unique_values = list(set(values)) aggregation = {i:unique_values.index(v) for i, v in enumerate(values)} aggregation['n'] = len(unique_values) re...
606bee7c7055b8f2a95bc061dc1883713198b506
19,825
def create_anonymous_client(): """Creates an anonymous s3 client. This is useful if you need to read an object created by an anonymous user, which the normal client won't have access to. """ return boto3.client('s3', config=Config(signature_version=UNSIGNED))
1c321d2c42b41b19a4fad66e67199f63c2b04338
19,826
def predictionTopK(pdt, k): """预测值中topk @param pdt 预测结果,nupmy数组格式 @param k 前k个结果 @return topk结果,numpy数组格式 """ m, n = np.shape(pdt) ret = [] for i in range(m): curNums = pdt[i] tmp = topK(curNums.tolist()[0], k) ret.append(tmp) return np.mat(ret)
57740bb3e2f4521d14273194dc024e8a91347241
19,827
import re def parseCsv(file_content): """ parseCsv ======== parser a string file from Shimadzu analysis, returning a dictonary with current, livetime and sample ID Parameters ---------- file_content : str shimadzu output csv content Returns ------- dic ...
cc20a906c23093994ce53358d92453cd4a9ab459
19,831
def s_from_v(speed, time=None): """ Calculate {distance} from {speed} The chosen scheme: speed at [i] represents the distance from [i] to [i+1]. This means distance.diff() and time.diff() are shifted by one index from speed. I have chosen to extrapolate the position at the first index by assuming we st...
42fa996371af55c97235c2260f1c7c873e7e9e5b
19,833
def fake_categorize_file(tmpdir_factory): """Creates a simple categorize for testing.""" file_name = tmpdir_factory.mktemp("data").join("categorize.nc") root_grp = netCDF4.Dataset(file_name, "w", format="NETCDF4_CLASSIC") n_points = 7 root_grp.createDimension('time', n_points) var = root_grp.cre...
17b8e106f19200291bf2a77805542ecf2bb395fe
19,834
def load_unpack_npz(path): """ Simple helper function to circumvent hardcoding of keyword arguments for NumPy zip loading and saving. This assumes that the first entry of the zipped array contains the keys (in-order) for the rest of the array. Parameters ---------- path : string P...
ae5d573a480a87d3c09e8de783d9b94558870c15
19,836
import re def is_valid_email(email): """ Check if a string is a valid email. Returns a Boolean. """ try: return re.match(EMAIL_RE, email) is not None except TypeError: return False
736b3f141e6f3a99644d51c672738d63d64d604e
19,837
import re def _create_matcher(utterance): """Create a regex that matches the utterance.""" # Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL # Pattern matches (GROUP|OPTIONAL): Change light to [the color] {name} parts = re.split(r'({\w+}|\[[\w\s]+\] *)', utterance) # Pattern to...
ecf126488f827c65379efc58794136499dfa87dd
19,838
def top_compartment_air_CO2(setpoints: Setpoints, states: States, weather: Weather): """ Equation 2.13 / 8.13 cap_CO2_Top * top_CO2 = mass_CO2_flux_AirTop - mass_CO2_flux_TopOut """ cap_CO2_Top = Coefficients.Construction.greenhouse_height - Coefficients.Construction.air_height # Note: line 46 / se...
7f294de2f669c2224ccbd09d8200e9b91ddd6ebe
19,840
def coning_sculling(gyro, accel, order=1): """Apply coning and sculling corrections to inertial readings. The algorithm assumes a polynomial model for the angular velocity and the specific force, fitting coefficients by considering previous time intervals. The algorithm for a linear approximation is we...
61f57383488d2d42cb6d63fec5d6d99faa8e2cf2
19,841
def add(): """Add a task. :url: /add/ :returns: job """ job = scheduler.add_job( func=task2, trigger="interval", seconds=10, id="test job 2", name="test job 2", replace_existing=True, ) return "%s added!" % job.name
88ef667e05a37ec190ba6e01df23fd617821afe0
19,842
def magnitude(x: float, y: float, z: float) -> float: """ Magnitude of x, y, z acceleration √(x²+y²+z²) Dispatch <float> Args: x (float): X-axis of acceleration y (float): Y-axis of acceleration z (float): Z-axis of acceleration Returns: float: Magnitude of acceleratio...
ecb0543b52c385a9b294e87e4b17346b9705f3f8
19,843
def dauth( bot, input ): """Toggle whether channel should be auth enabled by default""" if not input.admin: return False if not input.origin[0] == ID.HON_SC_CHANNEL_MSG: bot.reply("Run me from channel intended for the default auth!") else: cname = bot.id2chan[input.origin[2]] ...
a031e1feb45956503c30ddacd40d59a5f65f30ca
19,844
import json def write_to_disk(func): """ decorator used to write the data into disk during each checkpoint to help us to resume the operation Args: func: Returns: """ def wrapper(*args, **kwargs): func(*args, **kwargs) with open("checkpoint.json", "r") as f: ...
d3614b7b75adf40021c31263fbbcdfdda025d1a3
19,845
def get_hourly_total_exchange_volume_in_period_from_db_trades(tc_db, start_time, end_time): """ Get the exchange volume for this exchange in this period from our saved version of the trade history. """ # Watch this query for performance. results = tc_db.query( func.hour(EHTrade.time...
7d46327e8c89d928d7e208d9a00d7b199345e636
19,847
import typing def descending(sorting_func: typing.Any) -> typing.Any: """ Modify a sorting function to sort in descending order. :param sorting_func: the original sorting function :return: the modified sorting function """ def modified_sorting_func(current_columns, original_columns, sorting_f...
30afe7202648950af5d415f3a2da3af5e9ab9d8f
19,848
def circleColor(renderer, x, y, rad, color): """Draws an unfilled circle to the renderer with a given color. If the rendering color has any transparency, blending will be enabled. Args: renderer (:obj:`SDL_Renderer`): The renderer to draw on. x (int): The X coordinate of the center of the ...
6b3475f918cfb0867799710e5c53e5eea326a2c2
19,849
def _get_ref_init_error(dpde, error, **kwargs): """ Function that identifies where the continuous gyro begins, initiates and then carries the static errors during the continuous modes. """ temp = [0.0] for coeff, inc in zip(dpde[1:, 2], error.survey.inc_rad[1:]): if inc > kwargs['header'...
45f4072139f007f65872223c624581b7433ea2aa
19,850
def parse_internal_ballot(line): """ Parse an internal ballot line (with or without a trailing newline). This function allows leading and trailing spaces. ValueError is raised if one of the values does not parse to an integer. An internal ballot line is a space-delimited string of integers of the...
9433a496f26dd3511ff343686402e941a617f775
19,853
def get_fratio(*args): """ """ cmtr = get_cmtr(*args) cme = get_cme(*args) fratio = cmtr / cme return fratio
2a93d1211929346fc333837b711ed0eb01f34b2b
19,854