content
stringlengths
22
815k
id
int64
0
4.91M
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, penalty: float = 1e-17, mod...
28,900
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)
28,901
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...
28,902
def graph_2d_markers(x: np.ndarray, y: np.ndarray, xaxis_title: str, yaxis_title: str, title: str, dirname: str, filename: str) -> None: """Creates a simple 2D plot using markers. """ path = os.path.join(dirname, filename) fig = go.Figure() fig.add_trace( go.Scatter( x...
28,903
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 with the embedding data in low-dimensional space and the clusterization model. Parameters ---------- data : pandas...
28,904
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...
28,905
def view(filename, show_attributes=False): """ NCVIEW Args: filename: show_attributes: """ import os import netCDF4 as nc if not os.path.isfile(filename): raise IOError("Unknonw file: %s" % filename) if 'gz' in filename: import gzip with gzip.open(...
28,906
def start_session(): """ This function is what initializes the application.""" welcome_msg = render_template('welcome') return question(welcome_msg)
28,907
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()
28,908
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 dictionary if entry is None: ...
28,909
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 ...
28,910
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_file.is_file(): ccd...
28,911
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...
28,912
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) != 5: raise ValueError( ...
28,913
def uid_to_device_name(uid): """ Turn UID into its corresponding device name. """ return device_id_to_name(uid_to_device_id(uid))
28,914
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...
28,915
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...
28,916
def renamePath(dir_path, path): """ Renames a folder to match a standard Plex format { Title (year) }. If the Dry run flag is set then we will just print the text but not make the move. Parameters: ----------- dir_path: Full path to the related folder path: Folder name ...
28,917
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, AbstractPropertyMigration) and \ ...
28,918
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) ...
28,919
def getRNA_X(sample_list, DATAPATH, ctype, lab_type): """ Get X for RNA. The required columns are retained and all other rows and columns dropped. This function also labels the data for building models. Parameters ---------- sample_list : list List of tumour samples to be retained. ...
28,920
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 (Tensor): the rota...
28,921
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 # 获取某年某月的第一天的星期和该月总天数 _, month_range = calenda...
28,922
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] + ...
28,923
def test_make_png(): """Test to ensure that make_png functions correctly.""" # Save random RGBA and RGB arrays onto disk as PNGs using make_png. # Read them back with an image library and check whether the array # saved is equal to the array read. # Create random RGBA array as type ubyte rgba_s...
28,924
def test_deploy_script_register_without_limit( token_address: HexAddress, deployer_0_4_0: ContractDeployer, deployed_raiden_info_0_4_0: DeployedContracts, ) -> None: """ Run token register function used in the deployment script This checks if register_token_network() works correctly in the happy ca...
28,925
def gap_init(points, D, d, C, L=None, st=None, K=None, minimize_K=True, find_optimal_seeds=True, seed_method="cones", seed_edge_weight_type='EUC_2D', use_adaptive_L_constraint_weights=True, increase_K_on_failure=False): #REMOVEME, disable! ...
28,926
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 ...
28,927
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 classes of functions including transcendental elemen...
28,928
def get_vgg(blocks, bias=True, use_bn=False, model_name=None, pretrained=False, root=os.path.join("~", ".torch", "models"), **kwargs): """ Create VGG model with specific parameters. Parameters: ---------- blocks : int Nu...
28,929
def plot_var(ax, var_samples, X, Xnew, y_err): """Plots the median and 95% CI from samples of the variance""" Xnew_ = Xnew.flatten() var_samples = np.exp(var_samples) if var_samples.squeeze().ndim == 1: ax.plot(Xnew, var_samples, "C0", label="Median") else: l, m, u = get_quantiles(va...
28,930
def main(): """This function runs the program""" gui_install_update = AWCGUI awc = AWC try: if not os.path.isfile("config.cfg"): gui_install_update().run() awc() elif os.path.isfile("config.cfg"): awc() # Logs all errors except Exception as e...
28,931
def configure_logger(): """ Declare and validate existence of log directory; create and configure logger object :return: instance of configured logger object """ log_dir = os.path.join(os.getcwd(), 'log') create_directory_if_not_exists(None, log_dir) configure_logging(log_dir) logger =...
28,932
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 ...
28,933
def copy_file(args, day_directory, text_converters, conv_after, file_info): """Copy a single language file to day directory""" # 1. Get full path of output file raw_file_name, raw_file_text = file_info out_file_name = get_file_name(day_directory, raw_file_name, text_converters) # 2. Don't write if...
28,934
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" #load in conf...
28,935
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([ StructField("timesta...
28,936
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_" ...
28,937
def plot_tree(T, res=None, title=None, cmap_id="Pastel2"): """Plots a given tree, containing hierarchical segmentation. Parameters ---------- T: mir_eval.segment.tree A tree object containing the hierarchical segmentation. res: float Frame-rate resolution of the tree (None to use se...
28,938
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
28,939
def test_hash_dict(test_input, expected): """Test hash dict function.""" result = data_obfus.hash_dict(test_input) for key in test_input: check.equal(test_input[key] != result[key], expected)
28,940
def _interpolate_face_to_bar(nodes, eid, eid_new, nid_new, mid, area, J, fbdf, inid1, inid2, inid3, xyz1_local, xyz2_local, xyz3_local, xyz1_global, xyz2_global, xyz3_global, nodal_result, ...
28,941
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
28,942
def p_comment_left(p): """ tag : DOXYGEN_BEGIN skip_doxy DOXYGEN_END """
28,943
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 ...
28,944
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 program and is not timed. ...
28,945
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...
28,946
async def remove_roles(guild): """Remove all roles for this guild.""" Rules = Query() db.remove(Rules.guild == guild.id) del RULES[guild.id]
28,947
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...
28,948
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...
28,949
def generate_suite(pairs, save_path, suite_name, functions): """ Turn pairs produced by the combinator into a syntaxgym suite. Parameters ---------- pairs : [FoilPair] Duh. save_path : str Filepath to save the suite to. suite_name : str Name of suite. functions :...
28,950
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))
28,951
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...
28,952
def connect_to_service(service_name, client=True, env=None, region_name=None, endpoint_url=None): """ Generic method to obtain an AWS service client using boto3, based on environment, region, or custom endpoint_url. """ env = get_environment(env, region_name=region_name) my_session = None if CUS...
28,953
def hdf_diff(*args, **kwargs): """:deprecated: use `diff_blocks` (will be removed in 1.1.1)""" return diff_blocks(*args, **kwargs)
28,954
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 eachfile in fi...
28,955
def hex2twelve(hex_gen): """ 转换16进制为12进制 其中,对于大于10的十六进制数字, 采取随机两种方式: 10 + hex_num - 10 表示,即 a -> 100, f -> 105 11 + hex_num - 6 表示, 即 a -> 114, f -> 119 :param hex_gen: :return: generator() """ for h in hex_gen: h = int(h, 16) if h < 10: yield h ...
28,956
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, ...
28,957
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...
28,958
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') ...
28,959
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(400, "Missing d...
28,960
def process_change(n_of_food, old_val): """ does the nutrient change activate any of our triggers :param n_of_food: :param old_val: :return: """ # Kcal <-> KJoul amino_acids = ['TRP', 'THR', 'ISO', 'LEU', 'LYS', 'MET', 'CYS', 'PHE', 'TYR', 'VAL', 'ARG', 'HIS', 'ALA', '...
28,961
def clear_settings(site_name): # untested - do I need/want this? """update settings to empty dict instead of initialized) """ return update_settings(site_name, {})
28,962
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], [...
28,963
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...
28,964
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...
28,965
def mp_worker(call): """ Small function that starts a new thread with a system call. Used for thread pooling. :param call: :return: """ call = call.split(' ') verbose = call[-1] == '--verbose' if verbose: call = call[:-1] subprocess.run(call) else: #subprocess...
28,966
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...
28,967
def log(ctx, **kwargs): """ \b - DESCRIPTION: Download Log Files of A Specified Job. \b - USAGE: flow job log -j JOB_ID --output-path ./examples/ """ config_data, dsl_data = preprocess(**kwargs) job_id = config_data['job_id'] tar_file_name = 'job_{}_log.tar.gz'.forma...
28,968
def plot_rsp_dists(rsp, rsp_cols, savepath=None): """ Plot distributions of all response variables. Args: rsp : df of response values rsp_cols : list of col names savepath : full path to save the image """ ncols = 4 nrows = int(np.ceil(len(rsp_cols)/ncols)) fig, axes = pl...
28,969
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: ...
28,970
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 ...
28,971
def indented(indentation, lines): """Iterator adaptor which stops if there is less indentation. Blank lines are forwarded as empty lines. """ while True: try: line = lines.peek() except StopIteration: break if line.startswith(' ' * indentation): ...
28,972
def report_advising_load(filename,database,base_set): """ Generate report of advising/coadvising load. Arguments: filename (str) : filename for output stream database (list of dict) : student database base_set (list) : base set of faculty to include, even if unassigned """ repo...
28,973
def updateSiteInfo(self, site, stype='', cache='', enabled=True, ssl=False, fs='', db=''): """updates site record in database""" try: q = SiteDB.query.filter(SiteDB.sitename == site).first() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "U...
28,974
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
28,975
def parse_model(data: Union[Dict[str, Any], Iterable[Any], Any], cls: Union[Type[TModel], Type[Any]], rename_keys: Optional[Dict[str, str]] = None) \ -> Union[TModel, Any]: """Instantiates an object of the provided class cls for a provided mapping. Instantiates an object...
28,976
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...
28,977
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...
28,978
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. """ if inifile ...
28,979
def get_param_store(): """ Returns the ParamStore """ return _PYRO_PARAM_STORE
28,980
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
28,981
def push_terms(obj: State, overwrite: bool, sync_terms: bool): """ Uploads list of terms in your local project to POEditor. """ if not obj.config_path.exists(): raise click.FileError(obj.config_path.name, 'Config file does not exist') config = obj.config client = obj.client referenc...
28,982
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...
28,983
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 function which takes wavel...
28,984
def integrate_to_context(initial_tokens, words): """ initial_tokens.keys() ['ident', 'tree', 'original', 'words'] ident: {'wtypes': set(['NN']), 'words': set(['door']), 'idents': set(['door_NN'])} original: [('open', 'VB'), ('the', 'DT'), ('door', 'NN')] words (list...
28,985
def shake(robot): """ :type robot: rosebot.RoseBot """ robot.drive_system.go_forward_until_distance_is_less_than(10, 50) robot.drive_system.turn_degrees(40, 100) robot.drive_system.turn_degrees(-40, 100) robot.drive_system.turn_degrees(40, 100) robot.drive_system.turn_degrees(-40, 100) ...
28,986
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 in the termina...
28,987
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 dictionaries. ignore_extra_keys (bool, o...
28,988
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...
28,989
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))
28,990
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)
28,991
def test_evaluate_with_quantities(): """ Test evaluation of a single model with Quantity parameters that do not explicitly require units. """ # We create two models here - one with quantities, and one without. The one # without is used to create the reference values for comparison. g = Gau...
28,992
def extract_url(args: argparse.Namespace) -> dict: """Extracts data from products.json endpoint from specified args. Args: args (argparse.Namespace): Parsed args. Returns: dict: Data logged from extraction, including if successful or errors present. """ p = format_url(args...
28,993
def _devive_from_rsrc_id(app_unique_name): """Format devices names. :returns: ``tuple`` - Pair for device names based on the app_unique_name. """ # FIXME(boysson): This kind of manipulation should live elsewhere. _, uniqueid = app_unique_name.rsplit('-', 1) veth0 = '{id:>013s}.0'.forma...
28,994
def fit_noise_1d(npower,lmin=300,lmax=10000,wnoise_annulus=500,bin_annulus=20,lknee_guess=3000,alpha_guess=-4, lknee_min=0,lknee_max=9000,alpha_min=-5,alpha_max=1,allow_low_wnoise=False): """Obtain a white noise + lknee + alpha fit to a 2D noise power spectrum The white noise part is inferred f...
28,995
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 dic with ir...
28,996
def unpackFITS(h5IN, h5archive, overwrite=True): # ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ """ Package contents of an h5 block to multi-extention FITS files """ """ MAJOR BUG: This does not like the ExtendLinked HDF5 files one bit... Only real blocks. No idea why...
28,997
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...
28,998
def get_distinct_elements(items, key=None): """ 去除序列中的重复元素,使得剩下的元素仍然保持顺序不变,对于不可哈希的对象,需要指定 key ,说明去重元素 :param: * items: (list) 需要去重的列表 * key: (hook函数) 指定一个函数,用来将序列中的元素转换成可哈希类型 :return: * result: (generator) 去重后的结果的生成器 举例如下:: print('--- remove_duplicate_elements dem...
28,999