content
stringlengths
22
815k
id
int64
0
4.91M
def vectorsToRotMatrix(v1,v2): """ Given two points v1 and v2 in 3D space. Suppose furthermore that v2 is generated by v1 multiplied by a rotation matrix over the origin. We will determine this rotation matrix using this method :rtype: float list :return: Rotation matrix (unhomegeni...
55,400
def test_read_participants_data(tmpdir): """Test reading information from a BIDS sidecar.json file.""" bids_path = _bids_path.copy().update(root=tmpdir, datatype='meg') raw = _read_raw_fif(raw_fname, verbose=False) # if subject info was set, we don't roundtrip birthday # due to possible anonymizati...
55,401
def missing_impact(df: dd.DataFrame, bins: int) -> Intermediate: """ Calculate the data for visualizing the plot_missing(df). This contains the missing spectrum, missing bar chart and missing heatmap. """ cols = df.columns.values (nulldf,) = dask.persist(df.isnull()) nullity = nulldf.to_dask...
55,402
def flush_screen() -> NoReturn: """Flushes the screen output.""" sys.stdout.flush() sys.stdout.write("\r")
55,403
def svn_stream_write(stream, data): """svn_stream_write(svn_stream_t * stream, char const * data) -> svn_error_t""" return _core.svn_stream_write(stream, data)
55,404
def build_word_dict(args, examples): """Return a dictionary from sentence words in provided examples. """ word_dict = Dictionary() for w in load_words(args, examples): word_dict.add(w) return word_dict
55,405
def define_preprocess_args( sub_parsers: argparse._SubParsersAction, # pylint:disable=protected-access ): """ Define the arguments needed for the preprocess command """ parser = sub_parsers.add_parser("preprocess", help="Preprocess the dataset") parser.add_argument( "--tokenizer", type=...
55,406
def test_parametrized_estimators_fitting(estimators, est_name, X, y): """Test parametrized estimators fitting process.""" pe = _ParametrizedEstimators(estimators, est_name) pe.fit(X, y) fitted_estimator = dict(estimators).get(est_name) assert isinstance(fitted_estimator, pe.estimator_.__class__)
55,407
def test_args_workflow_file_from_cli(tmp_path): """Test the workflow for starting a Krake component with support of the :class:`ConfigurationOptionMapper`. Let the mapper use the content of a configuration file whose path was provided as parameter. """ # Prepare the configuration file given as ...
55,408
def train_test_split(df, index, split_by=None, stratify_by=None, test_split=0.1, seed=None): """Split pandas dataframe into train and test splits. Options to split by group (i.e. keep groups together) and stratify by label. ...
55,409
def get_data_ce_duals_active_all(): """() -> list Returns a list of all of the active ce cards in the database, sorted in ascending order by start date.""" query = ( f''' SELECT active_product_nick, active_product_titles, CAST (CAST (active_product_prices AS text) AS money), active_pr...
55,410
def _import_project_sections(nt_client, monday_client, nt_project_id, project, limits: dict): """Import monday lists as project sections""" nt_api_sections = apis.ProjectSectionsApi(nt_client) def _parse_timestamp(monday_timestamp: Optional[str]) -> Optional[models.TimestampNullable]: """Parses mon...
55,411
def evaluate_wos_layer(epoch_predicts, epoch_labels, vocab, threshold=0.5, top_k=None): """ :param epoch_labels: List[List[int]], ground truth, label id :param epoch_predicts: List[List[Float]], predicted probability list :param vocab: data_modules.Vocab object :param threshold: Float, filter probab...
55,412
def convert_weighted(array : np.array) : """ 3D-array to 2D-array (R^2 + G^2 + B^2) / (R+G+B) """ sqrd = array**2 sqrd = sqrd.sum(axis = -1) norm = array.sum(axis = -1) return np.nan_to_num(sqrd/norm, nan=0)
55,413
def empty_init(): """Returns True if trying to initialize an Interactionobseng without any arguments fails.""" try: BaseObservationEngine() return True except TypeError: return False
55,414
def smooth_column(args): """Low-level helper function for smoothing single column Parameters ---------- args : tuple Tuple containing data to smooth in 1d array, smoothing kernel in 1d array, whether to ignore nans, and data dtype Returns ------- np.ndarray ...
55,415
def get_session() -> Session: """Function to get the current database session. Yields: Database session. """ session = Session() try: yield session finally: session.close()
55,416
def check_all_H(structure): """ Parameters ---------- structure : Biopython protein structure object made with PDBParser(). Returns ------- all_ligands : dataframe of all distances between each amino acid residue and ligand from the protein structure. """ heteros = get_hetero...
55,417
def get_file_join_name(input_path=None, file_name=None): """Function for getting join name from input path.""" name_list = [] file_join_name = '' if os.path.exists(input_path): files = os.listdir(input_path) for f in files: if file_name in f and not f.endswith('.done') and no...
55,418
def get_example_jwt_auth_signer(**kwargs): """ returns an example jwt_auth_signer instance. """ issuer = kwargs.get('issuer', 'egissuer') key_id = kwargs.get('key_id', '%s/a' % issuer) key = kwargs.get( 'private_key_pem', get_new_rsa_private_key_in_pem_format()) algorithm = kwargs.get('algor...
55,419
def main(ns, rc): """Prints help or usage messages for the various commands.""" msg = get_help(ns.options) if msg: print msg
55,420
def generate_id(hksess): """ Generates a unique session id based on the start_time, process_id, and hksess description. Args: hksess (so3g.HKSessionHelper) """ # Maybe this should go directly into HKSessionHelper elements = [ (int(hksess.start_time), 32), (os.getpid(...
55,421
async def close_trades(ctx): """Ends free agency in the identified league.""" if ctx.author.id not in admin_ids: return await ctx.send("This is an admin-only command.") for l in leagues: if l.get_channel() == ctx.channel.id: league = l break else: return a...
55,422
def generate_set_None(gen_dict, class_dict): """Generate the code for the _set_None method of the class Parameters ---------- gen_dict : dict Dict with key = class name and value = class dict (name, package, properties, methods...) class_dict : dict Dictionnary of the class to gene...
55,423
def drive_volume_fmm(traversal, expansion_wrangler, src_weights, src_func, direct_evaluation=False, timing_data=None, reorder_sources=True, reorder_potentials=True, **kwargs): """ Top-level driver routine for volume potential calculation via fas...
55,424
def k_from_m1m2(m1,m2, P, i, e=0): """ Parameters ---------- i: float inclination with units FIXME: Add in non-zero eccentricity """ f1 = m2**3*np.sin(np.radians(i))**3/(m1+m2)**2 f2 = m1**3*np.sin(np.radians(i))**3/(m1+m2)**2 K1 = ((f1*2*np.pi*const.G/P)**(1/3.)).si...
55,425
def unescape_ssml(text: str) -> str: """Unescapes XML control characters in SSML. See: https://console.bluemix.net/docs/services/text-to-speech/http.html#escape We first unescape the text in case it already contains escaped control characters. """ return xml.sax.saxutils.unesc...
55,426
def descSetupInEipMode(): """ Setting up an EIP/ELB enabled zone with netscaler provider """ zs = cloudstackConfiguration() for l in range(1): z = zone() z.dns1 = "8.8.8.8" z.dns2 = "8.8.4.4" z.internaldns1 = "192.168.110.254" z.internaldns2 = "192.168.110.25...
55,427
async def send_expr(bot: NoneBot, ctx: Context_T, expr: Expression_T, **kwargs): """Sending a expression message ignoring failure by default.""" return await send(bot, ctx, expression.render(expr, **kwargs))
55,428
def read_settings(path=os.getenv('MOASTROCONFIG', os.path.expandvars('$HOME/.moastro.json'))): """Read the Mo'Astro JSON configurations file. Parameters ---------- path : str Path to the ``.moastro.json`` file. Returns ------- settings : dict The settings, as ...
55,429
def ssd_model_build(): """create network""" ssd = ssd_inception_v2(configs=config) if config.feature_extractor_base_param != "": ssd.init_parameters_data() param_dict = load_checkpoint(config.feature_extractor_base_param) load_param_into_net(ssd, param_dict) return ssd
55,430
def record_task_status_for_volume(task, volume_id): """ Context manager to record in volume.task_statuses whether the given task succeeds or fails. """ try: yield except Exception as e: volume = VolumeMetadata.objects.get(pk=volume_id) volume.task_statuses[task.name] = { ...
55,431
def last_update_import_id(): """ For better filtering. @return: """ last_run = app.session.query(func.max(ImportLog.import_id)).filter(ImportLog.status == STATUS_FINISHED).first()[0] if last_run is None: max_import_id = -1 else: max_import_id = last_run return max_import...
55,432
def is_valid(value, cast_fn, expected_data_type, allow_none=False): """ Checks whether a value can be converted using the cast_fn function. Args: value: Value to be considered cast_fn: Function used to determine the validity, should throw an exception if it cannot e...
55,433
def maybe_pool(processes: int = None, *args, **kwargs): """Create ``multiprocessing.Pool`` if multiple CPUs are allowed Examples -------- >>> from divik.core import maybe_pool >>> with maybe_pool(processes=1) as pool: ... # Runs in sequential ... pool.map(id, range(10000)) >>> ...
55,434
def get_kanji(seg_content: str) -> dict: """Split raw lesson content into individual character entries and process each one.""" ret = {} entries = [entry for entry in re.split(KANJI, seg_content) if entry] for kanji, desc in zip(entries[::2], entries[1::2]): ret[kanji] = parse_kanji(desc) re...
55,435
def range_transformation(value: float, input_range: list, output_range: list = [-1, 1]): """Range transformation from [input_range[0], input_range[1]] to [output_range[0], output_range[1]] Args: value (float): variable input_range (list): desired input variable range output_range (list,...
55,436
def get_authen_roles(): """ Get the authentication roles Returns: arr[str]: Array of associated roles """ return g.get(AUTHEN_ROLES, [])
55,437
def test_enable(ignore_list, code, expected_list): """Verify that enabling a plugin removes it from the ignore list.""" options = mock.Mock(ignore=ignore_list) optmanager = mock.Mock() plugin = manager.Plugin(code, mock.Mock()) plugin.enable(optmanager, options) assert options.ignore == expect...
55,438
def check_required_environment_variables_present(env, config): """ If we are in PROD, we want to fail fast if any config is missing """ if env == 'PROD': missing_vars = [var for var in config['REQUIRED_VARS'] if config.get(var) is None] if missing_vars: raise MissingEnvironmentVariab...
55,439
def _mkanchors(ws, hs, x_ctr, y_ctr): """ Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack((x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (h...
55,440
def explode(dataframe: DataFrame, col: str, new_col: str = None) -> DataFrame: """Explode a list in a cell to many rows in the dataframe :param str col: name of the column to explode :param str new_col: name of the new column to explode to, could be exploded column """ tmp_new_col = new_col if new_...
55,441
def ensure_type(name, var, *types): """ Checks if a variable with a name has one of the allowed types. Arguments --------- name: variable name var: python object *types: allowed types """ for ty in types: if not isinstance(ty, type): raise ValueError(...
55,442
def median_buffer_range(mag, magerr): """This function returns the ratio of points that are between plus or minus 10% of the amplitude value over the mean :param mag: the time-varying intensity of the lightcurve. Must be an array. :param magerr: photometric error for the intensity. Must be an array...
55,443
def test_exclude_glob_case4b(): """Test case 4b - include and exclude specified, with excluded glob.""" incl_dom = {} incl_glob = {} incl_ent = {"binary_sensor.working"} excl_dom = {} excl_glob = {"binary_sensor.*"} excl_ent = {"light.ignoreme", "sensor.notworking"} testfilter = generate...
55,444
def multiply(a, b): """Multiply simple numbers, vectors, and 2D matrices.""" is_a_num = is_number(a) is_b_num = is_number(b) is_a_vec = not is_a_num and is_number(a[0]) is_b_vec = not is_b_num and is_number(b[0]) is_a_mat = not is_a_num and not is_a_vec is_b_mat = not is_b_num and not is_b_...
55,445
def two_qubit_matrix_to_diagonal_and_operations( q0: 'cirq.Qid', q1: 'cirq.Qid', mat: np.ndarray, allow_partial_czs: bool = False, atol: float = 1e-8, clean_operations: bool = True, ) -> Tuple[np.ndarray, List['cirq.Operation']]: """Decomposes a 2-qubit unitary to a diagonal and the remainin...
55,446
def test_magnetization_density(chgcar_parser): """Test that the content returned by the CHGCAR parser returns the correct charge and magnetization density. """ charge_density = chgcar_parser.charge_density magnetization_density = chgcar_parser.magnetization_density assert np.allclose(charg...
55,447
def log_f(theta): """log of unnormalized target probability density function""" log_var = theta[0] var = np.exp(log_var) xx = theta[1:] return -0.5*log_var**2 - (0.5/var)*np.dot(xx, xx) - 0.5*xx.size*log_var
55,448
def search(database, search_params=None, limit=0, order_by='last_updated desc'): """ Searches for one or more resources in the database using the specified parameters. Args: database: The current database context. limit: The maximum number of results to return. search_params: The di...
55,449
def pd_series_to_instapost(timeseries:pd.core.series.Series, pathname:str, units:str, timezone:str)->dict: """ Args: series: a pd.core.Series time series with a time stamp index pathname: pathname the data is to be stored at units: the units the data is in ...
55,450
def main_CL(): """ Command line parsing and and defaults method """ parser = OptionParser(usage=usage(), version='%s'%version) parser.add_option("-p", "--prog", dest="prog", default="python2.3", help="program to search in processes") parser.add_option("-t", "--ago", dest="ago", default=600, ...
55,451
def iou_batch(bb_test, bb_gt): """ From SORT: Computes IUO between two bboxes in the form [l,t,w,h]...
55,452
def action_interaction_additive_reward_function( context: np.ndarray, action_context: np.ndarray, action: np.ndarray, base_reward_function: Callable[[np.ndarray, np.ndarray], np.ndarray], action_interaction_weight_matrix: np.ndarray, is_cascade: bool, len_list: int, reward_type: str, ...
55,453
def main(argv): """ RAIL Evaluation module - command line mode: * Compute all metrics available and display them in a table. * Make PIT-QQ plot and save it a PNG file. Parameters: ----------- argv: `sys.argv`, `list` list of parameters inserted on command line Usage: ------ ...
55,454
def test_2(): """ Query : Find mean of NA_Sales weighted by EU_Sales for each platform Dataset Used - https://www.kaggle.com/gregorut/videogamesales (The query does not makes much sense analytically) """ table = pandas.read_csv('data/data_for_test_weighted_mean/vgsales.csv') result_tabl...
55,455
def butter2d_lp(shape, f, n): """ Designs a lowpass 2D Butterworth filter. Modified from Peirce JW (2009) Generating stimuli for neuroscience using PsychoPy. Front. Neuroinform. 2:10. doi:10.3389/neuro.11.010.2008. Parameters ---------- shape : tuple Size of the filter. f :...
55,456
def run_model(network, nodes, demand_per_person_kw_peak, mg_gen_cost_per_kw, mg_cost_per_m2, cost_wire_per_m, grid_cost_per_m2): """ """ # First calcaulte the off-grid cost for each unconnected settlement for node in nodes: if node[5] == 0: node[7] = node[4]*demand_per_person_kw_pe...
55,457
def read_circuit(file): """ Read a Revlib circuit file and create a Qiskit circuit objetc :param file: Revlib circuit file :returns a Qiskit circuit object """ with open(file, mode="r") as file: lines = [] begin = end = 0 variables = '' for index, line in enum...
55,458
def global_reconstruction_error( X, Y, test_idx=None, train_idx=None, scaler=None, estimator=None, ): """Computes the global reconstruction error using the source X to reconstruct the features or samples of target Y based on a minimization by linear regression: .. math:: GRE...
55,459
def api_mobsfy(request): """POST - MobSFy API.""" if 'identifier' not in request.POST: return make_api_response( {'error': 'Missing Parameters'}, 422) resp = operations.mobsfy(request, True) if resp['status'] == 'ok': return make_api_response(resp, 200) return make_api_re...
55,460
def test_sarcastic_long(): """Test sarcastic-ifying a long string.""" expected = sarcastic("Hey Alex") actual = "HeY aLeX" assert actual == expected
55,461
def numero_lista(df): """ Función destinada a obtener el número de lista de clases :parameter: dataframe :return: numero de lista de clases """ # Selecciono la columna clase del dataframe y realizo unas modificaciones df['clase'] = df['clase'].str.replace( '[', '').str.replace(']...
55,462
def Fingerprint(path, params): """Check for a Python app. Args: path: (str) Application path. params: (ext_runtime.Params) Parameters passed through to the fingerprinters. Returns: (PythonConfigurator or None) Returns a module if the path contains a python app. """ log.info('Checking f...
55,463
def generate_tray_hash(xlist, ylist, floor, wall, depth, round): """ This method generates a unique identifier for a given tray for the given version of this script (based on the version.txt file). This allows us to generate a given tray one time, and then it can be saved to a central location and pull...
55,464
def calc_spatialCorrHeightLev(varx,vary,levs,lons,weight,levelq): """ Calculates spatial correlation from pearson correlation coefficient for grids over vertical height (17 pressure coordinate levels). Change the weighting for different level correlations Parameters ---------- varx : 2...
55,465
def v_relative(v, met): """Estimates the relative air speed which combines the average air speed of the space plus the relative air speed caused by the body movement. Vag is assumed to be 0 for metabolic rates equal and lower than 1 met and otherwise equal to Vag = 0.3 (M – 1) (m/s) Parameters ...
55,466
def fully_qualified_name(entry): """ Calculates the fully qualified name for an entry by walking the path to the root node. Args: entry: a BeautifulSoup Tag corresponding to an <entry ...> XML node, or a <clone ...> XML node. Raises: ValueError: if entry does not correspond to one of the ...
55,467
def lab( jupyter_lab: t.Tuple[BrowserContext, Path, int], ) -> t.Callable: """Provide function-scoped fixture leveraging longer lived fixtures.""" context, tmp, port = jupyter_lab path = tmp / f"notebook-{uuid4()}.ipynb" return lambda json_in: _lab( json_in, context=context, ...
55,468
def load(env_name): """Loads the train and eval environments, as well as the obs_dim.""" # pylint: disable=invalid-name kwargs = {} if env_name == 'sawyer_push': CLASS = SawyerPush max_episode_steps = 150 elif env_name == 'sawyer_drawer': CLASS = SawyerDrawer max_episode_steps = 150 elif env...
55,469
def get_pkg_info( package_name: str, additional: Iterable[str] = ("pip", "flit", "pbr", "poetry", "setuptools", "wheel"), ) -> Dict[str, str]: """Return build and package dependencies as a dict.""" dist = distribution(package_name) dependencies = {package_name: dist.version} for requirement in d...
55,470
def manage_devices(devices): """ Enable/disable a device :param devices: A device object """ prologue_text = "\n".join( [ "{} ({})".format(d.name, "Enabled" if d.is_enabled else "Disabled") for d in devices ] ) menu = ConsoleMenu(title="Emulation > Dev...
55,471
def sort_tasks_by_exec_time(tasks): """ Sort tasks in descending order by the execution time Args: tasks (list(Node) Returns: list(Node) """ n = len(tasks) for i in range(n): for j in range(0, n - i - 1): if tasks[j].get_exec_time() < tasks[j+1].get_exe...
55,472
def csr_sort_indices(*args): """ csr_sort_indices(int n_row, int Ap, int Aj, signed char Ax) csr_sort_indices(int n_row, int Ap, int Aj, unsigned char Ax) csr_sort_indices(int n_row, int Ap, int Aj, short Ax) csr_sort_indices(int n_row, int Ap, int Aj, unsigned short Ax) csr_sort_indices(int n_r...
55,473
def rdkit_functional_group_label_features_generator(mol: Molecule) -> np.ndarray: """ Generates functional group label for a molecule in RDKit. :param mol: A molecule (i.e. either a SMILES string or an RDKit molecule). :return: A 1D numpy array containing the RDKit 2D features. """ smiles = Che...
55,474
def pmap(func, seq, chunksize=1, nworkers=mp.cpu_count(), fargs=None, parallel=True): """ parallel map, ordered version if you are curious about the parameters, refer to multiprocessing library documentation (Pool.imap) fargs: first args for each 'func' unless fargs is ...
55,475
def append(log: immutables.Map, after: model.Index, *entries: model.Entry) -> immutables.Map: """Append entries to `log` *after* the given index. :param log: Log object to append entries to. :param after: Log index after which entries will be appended. :raises AppendError: If the operation is unsucces...
55,476
def get_ids(conn, sql_class, columns, data): """ Get row ids based on data and column_names. This function returns only the first id per data point. Be careful if the columns do not ensure uniqueness. """ return [ _get_data( conn=conn, sql_class=sql_class, ...
55,477
def get_special_search_qnodes(search_term): """ Searches for the search_term and returns a list of candidates from the wikidata search api """ if search_term == '': return [] url = "https://www.wikidata.org/w/api.php" params = { "action": "query", "list": "search...
55,478
def run(spark): """Indexes Protobuf files by updating the S3Prefixes and VehPosPb tables Args: spark: Spark Session object """ log = utils.get_logger() with DBConnCommonQueries() as conn: dbtables.create_if_not_exists(conn, dbtables.S3Prefixes) dbtables.create_if_not_exists(conn, dbtables.VehPo...
55,479
def use_emulator(emulate=False): """Set the sensehat service to use an emulator. Arguments: emulate: True if the Sense HAT Emulator should be used. This requires the Emulator to be installed and running on the desktop. """ if emulate: from sense_emu import SenseHat else: f...
55,480
def custom(colors, bins=None, bin_method=BinMethod.quantiles): """Create a custom scheme. Args: colors (list of str): List of hex values for styling data bins (int, optional): Number of bins to style by. If not given, the number of colors will be used. bin_method (str, optiona...
55,481
def unhandledExceptionMessage(): """ Returns detailed message about occurred unhandled exception """ errMsg = "unhandled exception occurred in %s. It is recommended to retry your " % VERSION_STRING errMsg += "run with the latest development version from official Gitlab " errMsg += "repository a...
55,482
def convert_vdot_to_time(vdot, distance): """Given a VDOT score, returns an approx time for a given distance.""" # Get equation parameters c = VDOT_TO_TIME[VDOT_TO_TIME.Distance==distance].iloc[0].Intercept m1 = VDOT_TO_TIME[VDOT_TO_TIME.Distance==distance].iloc[0].Coef1 m2 = VDOT_TO_TIME[VDOT_TO_TI...
55,483
def exception_response(status_code, **kw): """Creates an HTTP exception based on a status code. Example:: raise exception_response(404) # raises an HTTPNotFound exception. The values passed as ``kw`` are provided to the exception's constructor. """ exc = status_map[status_code](**kw) retur...
55,484
def get_latest_installed(dataset_path): """Return the latest version number installed in a dataset directory. Parameters: dataset_path (str): The path to the dataset of interest. Returns: str: The latest version installed locally. Returns None if no versions are installed. """ dirs = [dir....
55,485
def _mask_iou(mask1: np.ndarray, mask2: np.ndarray) -> ScalarMetricValue: """Computes iou between two binary segmentation masks.""" return np.sum(mask1 & mask2) / np.sum(mask1 | mask2)
55,486
def shorten_int_name(interface_name): """ Returns the Cisco shortened interface name from a full one. If the full interface name is invalid, this will return None """ short = None regex = "(\w{2}).*?(\d+(?:/\d+)?(?:/\d+)?)" match = re.match(regex, interface_name) if match...
55,487
def invalidate_cache(function, obj=None): """ Clears the internal function cache :param function: the function object :param obj: when the target is object bound, this is the object """
55,488
def test_new_attribute_is_added(db_session): """Test new attribute is added to database.""" new_att = Attribute( label="test_label", desc="test_desc" ) db_session.add(new_att) query = db_session.query(Attribute).all() assert len(query) == 1
55,489
def read_version(): """Read version from the first line starting with digit """ regex = re.compile('^(?P<number>\d.*?) .*$') with open('../CHANGELOG.rst') as f: for line in f: match = regex.match(line) if match: return match.group('number')
55,490
def x86_cmovns(ctx, i): """mov if not sign""" conditional_mov(ctx, i, conditional.NS)
55,491
def version_to_semver(version): """ Convert an SDK version string to an npm compatible semver :param version: should be major[.minor] :return: "major.minor.0" """ return "{}.{}.0".format(*parse_sdk_version(version))
55,492
def RefDefaults(): """ Returns dictionary of default values for all properties. These are used to provide defaults to fields that we do not want to automatically calculate dimensions for """ return { 'phi': { 'min':-180, 'max':180...
55,493
def load_json(path: str): """ Load the contents of a json file into a python dictionary """ with open(path) as f: content = json.load(f) return content
55,494
def test_lossy_socket_timeout_with_loss(): """Recv timeout is respected when loss rate is non-zero.""" def mock_recvfrom(size): gevent.sleep(0.1) socket = mock.MagicMock() socket.recvfrom.side_effect = mock_recvfrom s = LossySocket(socket, loss_rate=0.99) s.settimeout(0.0) with py...
55,495
def set_weight_decay(model, alpha): """ This function can be applied to Conv2D, Dense or DepthwiseConv2D """ for layer in model.layers: if isinstance(layer, keras.layers.DepthwiseConv2D): layer.add_loss(lambda: keras.regularizers.l2(alpha)(layer.depthwise_kernel)) elif isinst...
55,496
def get_taxa_to_create( es, opts, *, taxonomy_name="ncbi", taxon_ids=None, asm_by_taxon_id=None, ): """Create a dict of taxa to create.""" taxa_to_create = {} if not taxon_ids: return {} if asm_by_taxon_id is None: asm_by_taxon_id = {} taxonomy_template = taxo...
55,497
def usecase5(x, N): """ Base on test4 of https://github.com/numba/numba/issues/381 """ for k in range(N): print(x[k].f1, x.s1[k], x[k].f2)
55,498
def repopulate(opt: Optimizer, selected_data: pd.DataFrame, target_size: int) -> Population: """ Create new generation. """ fittest_pop = Population(selected_data, opt.population.blueprint) offspring_pop = make_new_generation(n=target_size, parent_fitness_data...
55,499