content
stringlengths
22
815k
id
int64
0
4.91M
def fix_community_medium( tax, medium, min_growth=0.1, max_import=1, minimize_components=True, n_jobs=4, ): """Augment a growth medium so all community members can grow in it. Arguments --------- tax : pandas.Dataframe A taxonomy specification as passed to `micom.Communi...
42,500
def get( ctx, pathspec, path, hash=None, type=None, id=None, follow_resumed=False, ): """ Get the HTML string of the card based on pathspec.\n The pathspec can be of the form:\n - <stepname>\n - <runid>/<stepname>\n - <runid>/<stepname>/<taskid>\n Sav...
42,501
def _p_wa_higher_wb(k1, k2, theta1, theta2): """ :param k1: Shape of wa :param k2: Shape of wb :param theta1: Scale of wa :param theta2: Scale of wb :return: """ a = k2 b = k1 x = theta1 / (theta1 + theta2) return betainc(a, b, x)
42,502
def noisify_binary_asymmetric(y_train, noise, random_state=None): """mistakes: 1 -> 0: n 0 -> 1: .05 """ P = np.eye(2) n = noise assert 0.0 <= n < 0.5 if noise > 0.0: P[1, 1], P[1, 0] = 1.0 - n, n P[0, 0], P[0, 1] = 0.95, 0.05 y_train_noisy = multiclass...
42,503
def get_solved_problems(user_id, custom=False): """ Get the solved and unsolved problems of a user @param user_id(Integer): user_id @param custom(Boolean): If the user_id is a custom user @return(Tuple): List of solved and unsolved problems """ if user_id is None: r...
42,504
def ispickle(filename): """Is the file a pickle archive file""" return isfile(filename) and os.path.exists(filename) and (((fileext(filename) is not None) and fileext(filename).lower() in ['.pk', '.pkl']) or (filename[-4:] == '.pkl'))
42,505
def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Self Correction for Human Parsing") parser.add_argument("--dataset", type=str, default='lip', choices=['lip', 'atr', 'pascal']) par...
42,506
def multi_threaded_client(connection): """ This function create multiple threads for multiple clients :param connection: New Connection request :return: null """ connection.send(str.encode('Server is working:')) global ros_service_status while True: data = connection.recv(20...
42,507
def zFitting(h5_name, parameters, fit_tracks): """ Does z fitting for the '3d' model. """ [wx_params, wy_params] = parameters.getWidthParams() [min_z, max_z] = parameters.getZRange() z_step = parameters.getAttr("z_step", 1.0e-3) if fit_tracks: fitzC.fitzTracks(h5_name, ...
42,508
def run_link(ctx: click.Context, link: str, language: str) -> Optional[Union[list, str]]: """ Make a multiline prompt for code input and send the code to the api. The compiled output from the api is returned. """ console = ctx.obj["console"] args = helpers.get_args(console) stdin = helpers....
42,509
def config_command(db=None, config=None, clear=True): """ Effectively does an init then load of a config to get you started quicker: m2sh config -db config.sqlite -config tests/sample_conf.py Like the other two, this will nuke your config, but we'll make it safer later. """ init_c...
42,510
def cdiff(alpha, beta): """ Difference between pairs :math:`x_i-y_i` around the circle, computed efficiently. :param alpha: sample of circular random variable :param beta: sample of circular random variable :return: distance between the pairs """ return center_angle(alpha - beta)
42,511
def check_preview_exists(source_id: str, checksum: str) -> Response: """ Handle request to check whether preview exists. Parameters ---------- source_id : str Unique identifier for the source package. checksum : str State of the source package to which this preview corresponds. ...
42,512
def split_buffer(buffer): """Returns a tuples of tuples in the format of (data, separator). data should be highlighted while separator should be printed unchanged, after data. Args: buffer (str): A string to split using SPLIT_RE. """ splits = SPLIT_RE.split(buffer) # Append an empty se...
42,513
def save_verify_img(browser, id): """ Save the verification code picture in the current directory. :param: browser :param: id return: verify_code """ verify_img = browser.find_element_by_id(id) # Get the coordinates of the specified label left = verify_img.location['x'] top = ver...
42,514
def add_parser_arguments(parser): """Add parser arguments for func_bug_reducer""" parser.set_defaults(func=invoke_function_bug_reducer) parser.add_argument('input_file', help='The input file to optimize') parser.add_argument('--module-cache', help='The module cache to use') parser.add_argument('--sd...
42,515
def write_values(value): """Write a `*values` line in an LTA file. Parameters ---------- value : [sequence of] int or float or str Returns ------- str """ if isinstance(value, (str, int, float)): return str(value) else: return ' '.join([str(v) for v in value])
42,516
def denormalize_spectrogram(S, is_mel): """Denormalize log-magnitude spectrogram.""" if is_mel: return S * hp.mel_normalize_variance + hp.mel_normalize_mean else: return S * hp.lin_normalize_variance + hp.lin_normalize_mean
42,517
def info(txt): """ Log info message """ global LG LG.info(txt)
42,518
def get_pixel(color: str, intensity: float): """Converts a color and brightness to a Pixel""" return Pixel(*[int(i*intensity) for i in color])
42,519
def findOverlapOrNearest(gs, ts, tree, start, end): """ first to check direct overlap with TSS, if no or multiple items, then get the close one @param gs: {tss: cLoops2.ds.Gene}, tss is key and int @pram ts: [tss] @param tree: KDTree from TSSs @param start: query start @param end: query end ...
42,520
def record_to_csv_line(record: dict, schema: dict, data_flattening_max_level: int = 0) -> str: """ Transforms a record message to a CSV line Args: record: Dictionary that represents a csv line. Dict key is column name, value is the column value s...
42,521
async def cows(ctx): """Cow list for the cowsay command""" await ctx.send("Current list of cows:```{}```".format(", ".join(cowList.keys())))
42,522
def get_front_types(locating_var_matrix_m01_s01, warm_front_percentile=DEFAULT_FRONT_PERCENTILE, cold_front_percentile=DEFAULT_FRONT_PERCENTILE): """Infers front type at each grid cell. M = number of rows in grid N = number of columns in grid :param locating_var...
42,523
def add_parser(tool_subparsers, **kwargs): """ Adds subparser for this analysis to a nascent argument parser **Arguments:** :*tool_subparsers*: <argparse._SubParsersAction> to which to add :*\*\*kwargs*: Passed to *tool_subparsers*.add_parser(...) """ from MDclt import h5_defau...
42,524
def execute(): """Add missing Twilio patch. While making Twilio as a standaone app, we missed to delete Twilio records from DB through migration. Adding the missing patch. """ frappe.delete_doc_if_exists('DocType', 'Twilio Number Group') if twilio_settings_doctype_in_integrations(): frappe.delete_doc_if_exists(...
42,525
def rainfall_rate(radar, gatefilter, kdp_name, zdr_name, refl_name='DBZ_CORR', hydro_name='radar_echo_classification', temperature_name='temperature'): """ Rainfall rate algorithm from csu_radartools. Parameters: =========== radar: Py-ART radar structure. r...
42,526
def get_wrestlers(): """Grabs a list of all of the wrestlers from the database. @return A list of Wrestler objects, or an empty list if no wrestlers have been created. """ wrestlers = db.get_wrestlers() return map(lambda w: Wrestler(**w), wrestlers)
42,527
def get_user_check_cls_def(user_def_file): """Get 'class UserCheck(object):' statement from userCheck.py. Args: user_def_file: The path of userCheck.py. Returns: xml_head_str: The 'class UserCheck' statement of userCheck.py. """ if not os.path.isfile(user_def_file): logging.e...
42,528
def show_banner(): """ Show the banner of the program > :return: banner """ print(BANNER)
42,529
async def test_form_cannot_connect(hass: HomeAssistant) -> None: """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "opengarage.OpenGarage.update_state", side_effect=...
42,530
def masterUniversalTransferSubacc(fromAccountType, toAccountType, asset, amount, fromEmail="", toEmail="", recvWindow=""): """# Universal Transfer (For Master Account) #### `POST /sapi/v1/sub-account/universalTransfer (HMAC SHA256)` ### Weight: 1 ### Parameters: Name |Type |Mandatory |Description --------|-------...
42,531
def allpass(source, g): """First order Shroeder all pass filter. y[n] + g y[n-1] = g.conjugate() x[n] + x[n-1].""" return polezero(source, 1.0, g.conjugate(), g, 1.0)
42,532
def read_data_and_split(train_csv_path = '../data/clean/bank_train.csv', test_csv_path = '../data/clean/bank_test.csv'): """ Reads the data from the given paths and returns predictors and response variables separately for train and test sets Parameters ---------- train_c...
42,533
def get_bro(fn_config, readonly=True): """ Convenience function to get a bro with a datastore initialized with a config file Args: fn_config: path to the config file readonly: load database readonly? Returns: A true bro """ store = datastore.DataStore() store.read...
42,534
def get_sample_metadata_token() -> str: """Get sample-metadata Bearer auth token for Azure or GCP depending on deployment config.""" deploy_config = get_deploy_config() if deploy_config.cloud == "azure": scope = f"api://smapi-{deploy_config.sample_metadata_project}/.default" return get_azur...
42,535
def replace_module_params(source, target, modules): """Replace selected module params in target by corresponding source values.""" source, _ = hk.data_structures.partition( lambda module, name, value: module in modules, source) return hk.data_structures.merge(target, source)
42,536
def get_cdk_stacks(module_path, env_vars, context_opts): """Return list of CDK stacks.""" LOGGER.debug('Listing stacks in the CDK app prior to ' 'diff') return subprocess.check_output( generate_node_command( command='cdk', command_opts=['list'] + context_opts...
42,537
def get_knmi_at_locations(model_ds, start='2010', end=None, nodata=-999): """get knmi data at the locations of the active grid cells in model_ds. Parameters ---------- model_ds : xr.DataSet dataset containing relevant model grid information ...
42,538
def coordinate_x_and_y_as_ndarray(x, y): """ Utility function to coordinate the two scalar/np.ndarray variables x and y as NumPy Arrays. The following cases are considered: 1) if x is array of length n; y is array of length m, then: x, y ---> (m, n) shaped arrays creating a mesh...
42,539
def cos_sim(vec1, vec2): """ Returns the cosine similarity between given two vectors """ return vec1.dot(vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
42,540
def makeTrans(tup: tuple): """ 生成一个字典格式的单词释义""" def toStr(s): return s if type(s) is str else str(s, encoding="utf-8") res = None if len(tup) >= 4: res = { "word": toStr(tup[0]), "phonetic": toStr(tup[1]), "translation": toStr(tup[2]), "exc...
42,541
def _keepbits_interface(da, keepbits): """Common interface to allowed keepbits types Parameters ---------- da : :py:class:`xarray.DataArray` Input data to bitround keepbits : int, dict of {str: int}, :py:class:`xarray.DataArray` or :py:class:`xarray.Dataset` How many bits to keep as int...
42,542
def calc_fraction(i, q, u, transmission_correction=1): """ Method for determining the fractional polarization. Parameters ---------- i : float Stokes I parameter. q : float Stokes Q parameter. u : float Stokes U parameter. transmission_correction : float (Default...
42,543
def label(node: Union["SQLNode", None]) -> Symbol: """Returns a default alias for the node; to use when rendering to SQL. The implementation for subclasses of SQLNodes is defined in `nodedefs.py`. """ if node is None: return S("_") else: raise NotImplementedError( f"label...
42,544
def mean(list): """Function that returns the mean of a list""" sum = 0 for num in list: sum += num return sum/len(list)
42,545
def control_loopback_wvalue(device, request_id, increment=None): """Test writing/reading from a single 16-bit location. :param device: The USB device instance. :param request_id: The request identifier. :param increment: The increment value. The test runs from 0 to 2**16 - 1. The device firmware ...
42,546
def replace( key, value, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN, ): """ Replace a key on the memcached server. This only succeeds if the key already exists. This is the opposite of :mod:`memcached.add <salt.modules.memca...
42,547
def cpu(): """Defined in :numref:`sec_use_gpu`""" return torch.device('cpu')
42,548
def get(name): """ Get configuration identified by name """ return CONFIGS[name]
42,549
def gpu_layout_factory(op): """ Generates a list of possible layouts given an op Arguments: op: Computation graph op which runs on the device Returns: List of possible layout assignment descriptors """ if isinstance(op, AssignOp): return GPULayoutAssignment.generate_ew_...
42,550
def dropout(tensor, noise_shape=None, random_mask=None, probability=0.1, scale=True, seed=None, return_mask=False, name="dropout"): """ With probability `probability`, outputs `0` otherwise outputs the input element. If ``scale`` i...
42,551
def get_words_for_board_optimize_fast(word_tuples, board_size, packing_constant=1.1): """Try different combinations of words to maximize the overlap_avoidance_probability metric First try to maximize the minimum, and if that can be easily achieved, then maximize the mean.""" # Identify the longest words inc...
42,552
def p_optionlist(p): """optionlist : TRANSACTION_OPT EQ field optionlist""" eq = ParseTreeNode('EQ', raw='assign') opt = ParseTreeNode('OPTION', raw=p[1]) p[3].role = 'VALUE' if opt.raw in boolean_options: p[3].nodetype = 'BOOLEAN' eq.add_children([opt, p[3]]) p[0] = [eq] + p[4]
42,553
def list_compliance_items(Filters=None, ResourceIds=None, ResourceTypes=None, NextToken=None, MaxResults=None): """ For a specified resource ID, this API action returns a list of compliance statuses for different resource types. Currently, you can only specify one resource ID per call. List results depend on th...
42,554
def parse_timedelta(time_str: str) -> timedelta: """ Parse a time string e.g. (2h13m) into a timedelta object. Stolen on the web """ regex = re.compile( r"^((?P<days>[\.\d]+?)d)?((?P<hours>[\.\d]+?)h)?((?P<minutes>[\.\d]+?)m)?((?P<seconds>[\.\d]+?)s)?$" ) time_str = replace( tim...
42,555
def testSetInvalidPathShouldFail(env): """Test that invalid paths fail""" r = env invalid = ['', ' ', '\x00', '\x0a', '\x0c', # '\xff' TODO pending https://github.com/RedisLabsModules/redismodule-rs/pull/15 '."', '.\x00', '.\x0a\x0c', '.-foo', '.43', '.foo\n.bar...
42,556
def delSceneGraph( cls ): """Delete the scenegraph associated with a prototype""" from vrml import node return node.PrototypedNode.scenegraph.fdel( cls )
42,557
def get_node_active_learning_heuristic_by_name( name: str, **kwargs: Any, ) -> NodeActiveLearningHeuristic: """ Factory method for node active learning heuristics. :param name: The name of the heuristic. :param kwargs: The keyword-based arguments. :return: An instan...
42,558
def apply_elastic_transform_intensity(imgs, labels, strength=0.08, shift=0.3, sigma_max=0.2, N=20, random_state=None): """This function wraps the elastic transform as well as adding random noise and gamma adjustment to augment a batch of images. Parameters ---------- imgs : numpy array array o...
42,559
def add_social(name, address): """Write a social address directly to the db. Parameters ---------- name : str Name of the service. address : str Address of the account. """ s = Social(name=name, address=address) db.session.add(s) db.session.commit()
42,560
def byte_size(num, suffix='B'): """ Return a formatted string indicating the size in bytes, with the proper unit, e.g. KB, MB, GB, TB, etc. :arg num: The number of byte :arg suffix: An arbitrary suffix, like `Bytes` :rtype: float """ for unit in ['','K','M','G','T','P','E','Z']: ...
42,561
def reduce_grid_info(grid_fnames, noise_fnames=None, nprocs=1, cap_unique=1000): """ Computes the total minimum and maximum of the necessary quantities across all the subgrids. Can run in parallel. Parameters ---------- grid_fnames: list of str subgrid file paths noise_fnames: list...
42,562
def display_info(): """Update the display of the currently analysed files.""" global files, dirs, size, threads, screen screen.acquire() clear() print(f"Treads: {len(threads)}") print(f"Directories: {dirs}") print(f"Files: {files}") print(f"Size: {human_size(size)}") screen.releas...
42,563
def generate_record( category_name: str, x1: float, y1: float, x2: float, y2: float, sample_data_token: str, filename: str, ) -> OrderedDict: """Generate one 2D annotation record given various informations on top of the 2D bounding box coordinates. Args: category_name (s...
42,564
def show_galaxies(images, ra, dec, display_radec=True, title=None, is_previous_lens=None, is_new_lens=None, label_lenses=False, nx=8, npix_show=96, nplt=None, savepath=None, panel_size=[3,3], lw_rect=3, lw_border=1, ls_border='-', fontsize=12, colors=['C0', 'red']):...
42,565
def create_fan_in_profile(): """Create the fan in profile.""" regions = [ MetricRegion("1-10", 1, 10), MetricRegion("11-20", 11, 20), MetricRegion("21-50", 21, 50), MetricRegion("50+", 51, 1001), ] return MetricProfile("Fan in", regions)
42,566
def from_parmed( structure, compound=None, coords_only=False, infer_hierarchy=True ): """Backend-specific loading function - parmed. Parameters ---------- structure : pmd.Structure New structure to be loaded. compound : mb.Compound, optional, default=None Host mb.Compound that w...
42,567
def get_transform(x: float, y: float, z: float, angle: float, scale_x: float = 1, scale_z: float = 1) -> list: """ Compute transformation matrix :param x: X position of center :param y: Y position of center :param z: Z position of center :param angle: Rotation of object about Y axis, in degrees....
42,568
def test_nodes_are_strings(net): """ Checks to make sure that the nodes are a string. For expediency, checks only 1/4 of the nodes. """ for n in net.nodes(): assert isinstance(n, str)
42,569
def create_strain_maps(folder, delta, outfolder='strain-maps', radius=2, i_max=None, vmin=1, vmax=1.5, ticks_strains=[ 1, 1.1 , 1.2 , 1.3, 1.4, 1.5]): """ Creates 2D Strain maps for a time series. (and single plot with mean and maximal strain for eacht time step) folder: containing the defromation...
42,570
def update_navies_and_armies(adjust_armies=False, adjust_navies=True, replace=False): """ Script we ran a single time in order to update domains with navies. Args: adjust_armies (bool): Whether we adjust their armies too, or just their navies adjust_navies (bool): Whet...
42,571
def test_get_mediatype(conn_args, set_zabbix_version, mock_login): """ query_submitted = { "params": {"filter": {"description": 10}, "output": "extend"}, "id": 0, "auth": "251feb98e3c25b6b7fb984b6c7a79817", "method": "mediatype.get"} """ module_return = [ { "mediatypeid": "10", ...
42,572
def read_json(file_path: str): """ Load json files. Args: file_path: path to the file """ with open(file_path) as f: return json.load(f)
42,573
def uniform_initialize_linears(mod: torch.nn.Module): """Initialize ``e3nn.o3.Linear``s with ``unit_uniform_init_``""" if isinstance(mod, e3nn.o3.Linear) and mod.internal_weights: unit_uniform_init_(mod.weight)
42,574
def index_form(texts): """Turn a set of strings into the appropriate form for indexing.""" results = [] total_len = 0 for text in texts: # We don't want to store more than INDEX_MAX_LEN of text per doc if total_len > INDEX_MAX_LEN: # TODO: there might be nicer techniques for...
42,575
def test_merger_conflict_1(): """ Merges dict with value int, float, str """ a = {"a": 1} b = {"a": {"b": 1}} try: merge({}, [a, b]) except ValueError: assert True a = {"a": {"b": 1}} b = {"a": 1} try: merge({}, [a, b]) except ValueError: as...
42,576
def plot_means(df): """ Plots the mean value for each labeled event Args: df: Pandas dataframe that contains classified events """ try: mean_values = df.groupby('Label').mean() except KeyError: print('Column \'Label\' does not exist.') print('Is this the...
42,577
def ds_from_df_from_dtypes(df, y_columns, standardize_X=False): """ Convert a pandas dataframe into a dataset with the respective d_types of the input features. Parameters: ---------- df: pandas dataframe the dataframe used for the conversion. y_columns: string or list of strings ...
42,578
def login_cookies(): """working login """ cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) html = opener.open(LOGIN_URL).read() data = parse_form(html) data['email'] = LOGIN_EMAIL data['password'] = LOGIN_PASSWORD encoded_data = urllib.urlenco...
42,579
def no_ygrid_hook(plot, element): """Hook for disabling x-grid lines. This function is never called, but used as one of the hooks passed as the hooks kwarg, e.g. as `hv.opts.BoxWhisker(hooks=[no_ygrid_hook])`. """ plot.handles["plot"].ygrid.grid_line_color = None
42,580
def list_images(args): """List deployed images.""" table = repos.Repo(args.root).get_images() for image_id in sorted(table): podvs = table[image_id] if podvs: podvs = ' '.join('%s@%s' % pv for pv in podvs) print('%s %s' % (image_id, podvs)) else: p...
42,581
def parse_args(): """ args for fc testing. """ parser = argparse.ArgumentParser(description='PyTorch SiamFC Tracking Test') parser.add_argument('--arch', default='Ocean', type=str, help='backbone architecture') parser.add_argument('--resume', default='snapshot/OceanV19on.pth', type=str, help='pr...
42,582
def restore_uuid_file_name(filepath): """ remove uuid in filename, and get filepath with file extension """ orig = os.path.splitext(filepath) return f'{orig[0][:-33]}{orig[1]}'
42,583
def inscription_summary(request, pk): """ Print a PDF summary of inscription """ candidat = get_object_or_404(Candidate, pk=pk) buff = io.BytesIO() pdf = InscriptionSummaryPDF(buff) pdf.produce(candidat) filename = slugify('{0}_{1}'.format(candidat.last_name, candidat.first_name)) + '.pd...
42,584
def hello(name='persona', lastmane='exposito'): """Function that return 'name and last name'. name: strung, lastname:string, return: string, """ if name != 'persona': return f'¿Como estas {name}?' return f'Hola {name} {lastname}'
42,585
def get_num(prompt: str) -> float: """Function to check if users input is a num""" while True: try: num = int(input(prompt)) return num except Exception as e: print(e)
42,586
def create_negative_mentions(doc, pos_mention_spans, neg_mention_count, max_span_size, context_size, overlap_ratio=0.5): """ Creates negative samples of entity mentions, i.e. spans that do not match a ground truth mention """ neg_dist_mention_spans, neg_dist_mention_sizes = [], [] ...
42,587
def show_item(item_id): """Show individual item.""" try: item = db_session.query(Item).filter_by(id=item_id).one() except: flash("This item does not exist") return redirect(url_for('index')) # Make sure that user is authorised to see the item if item.public or item.user_id ==...
42,588
def yaw_from_pose(pose): """ Extract the yaw (orientation) from a pose message. """ quat = np.array([pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w]) euler = tf.transformations.euler_from_quaternion(quat) return euler[2]
42,589
def create_influxdb_datasource_config(influxdb_parameters, cert, key) -> dict: """ :param influxdb_parameters: The retrieved InfluxDB parameter JSON :param cert: The InfluxDB cert for HTTPS. :param key: The InfluxDB key for HTTPS. :return: data: The datasource JSON to add. """ data = {} ...
42,590
def get_file_size(file_name): """Returns the size of the file.""" with open(file_name, "r") as fh: fh.seek(0, os.SEEK_END) return fh.tell()
42,591
def render_incrementals(iterable, **kwds): """helper function for simple incremental_expansion calls :param iterable: sequence of items to incrementally stack :param kwargs: options to pass to incremental_expansion :return: a set of the rendered results from incremental_expansion """ s = set() ...
42,592
async def test_deprecated_lovelace_ui(hass, hass_ws_client): """Test lovelace_ui command.""" await async_setup_component(hass, 'lovelace') client = await hass_ws_client(hass) with patch('homeassistant.components.lovelace.load_config', return_value={'hello': 'world'}): await clien...
42,593
def get_queues_labels(queue_labels_data): """Returns parsed data for main metrics. Converts input string with raw data to a dictionary.""" queue_regexp = r'QUEUE\(([^)]+)\)' curdepth_regexp = r'CURDEPTH\(([^)]+)\)' maxdepth_regexp = r'MAXDEPTH\(([^)]+)\)' queue_type_regexp = r'TYPE\(([^)]+)\)' ...
42,594
def is_auto(item): """ Checks if a parameter should be automatically determined """ if isinstance(item, float): if item == 9999.9: return True elif isinstance(item, str): if 'auto' in item.lower(): return True return False
42,595
def black_scholes_price(S: float, K: Union[float, np.ndarray], is_call: bool, vol: Union[float, np.ndarray], disc: float, T: float, div_disc: float = 1.0): """ Price st...
42,596
def has_group_perm(user_level, obj, ctnr, action): """ Permissions for groups Groups are assigned a subnet """ if not obj.subnet in [ip_range.subnet for ip_range in ctnr.ranges.all()]: return False return { 'cyder_admin': True, #? 'ctnr_admin': action == 'view', #? ...
42,597
def get_tags_with_sha(repo_dir): """ _get_tags_with_sha_ Get list of tags for a repo and return a map of tag:sha """ repo = git.Repo(repo_dir) return {tag.name: tag.commit.hexsha for tag in repo.tags}
42,598
def get_reference_sample_name(sample_list: List[Tuple[str, str]]) -> str: """Gets the name from the reference sample, raising an exception if it does not exist in the sample table.""" for sample, sample_type in sample_list: if sample_type == 'yes': return sample else: raise NoRef...
42,599