content
stringlengths
22
815k
id
int64
0
4.91M
def entropy_approximate(signal, delay=1, dimension=2, tolerance="default", corrected=False, **kwargs): """Approximate entropy (ApEn) Python implementations of the approximate entropy (ApEn) and its corrected version (cApEn). Approximate entropy is a technique used to quantify the amount of regularity and t...
5,323,200
def ir_typeref_to_type( schema: s_schema.Schema, typeref: irast.TypeRef, ) -> Tuple[s_schema.Schema, s_types.Type]: """Return a schema type for a given IR TypeRef. This is the reverse of :func:`~type_to_typeref`. Args: schema: A schema instance. The result type must exist in it...
5,323,201
def get_releases_query(session: db.Session, current_user: UserType, show_legacy=False): """Returns the query necessary to fetch a list of releases If a user is passed, then the releases will be tagged `is_mine` if in that user's collection. """ if current_user.is_anonymous(): query = session.qu...
5,323,202
def get_total_supply(endpoint=_default_endpoint, timeout=_default_timeout) -> int: """ Get total number of pre-mined tokens Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returnss -------...
5,323,203
def mat_to_h5(load_addr, h5_dir, keep_meta=False, loadkwargs={}, **kwargs): """ Convert mat file to HDF5 via dictionary. """ sqm = loadkwargs.pop('squeeze_me', True) matdict = loadmat(load_addr, squeeze_me=sqm, **loadkwargs) if not keep_meta: matdict = dict((mk, mv) for mk, mv in matdi...
5,323,204
def download_image( i_ee, index: int, image_download_method: Callable, serialized_image_list: Dict[str, Any], name_prefix: str, out_dir: Optional[Path], download_kwargs: Optional[Dict[str, Any]] ) -> None: """ Hidden function to be used with download_image_collection. As we want comp...
5,323,205
def _is_css(filename): """ Checks whether a file is CSS waveform data (header) or not. :type filename: str :param filename: CSS file to be checked. :rtype: bool :return: ``True`` if a CSS waveform header file. """ # Fixed file format. # Tests: # - the length of each line (283 c...
5,323,206
def extract_versions(): """ Extracts version values from the main matplotlib __init__.py and returns them as a dictionary. """ with open('lib/matplotlib/__init__.py') as fd: for line in fd.readlines(): if (line.startswith('__version__numpy__')): exec(line.strip())...
5,323,207
def check_range(coord, range): """Check if coordinates are within range (0,0,0) - (range) Returns ------- bool Success status """ # TODO: optimize if len(coord) != len(range): raise ValueError( "Provided coordinate %r and given range %r" % (coord, range) ...
5,323,208
def static_pressure_bm3(vv): """ Outputs the static pressure (in GPa) at the volume (vv) Args: vv: volume """ static(plot=False) k0=info.popt[1] kp=info.popt[2] v0=info.popt[0] p_static_bm3=bm3(vv,v0, k0,kp) ps=p_static_bm3*conv/1e-21 print("Static pressure at th...
5,323,209
def make_df(raw_data, add_annotations = True): """ Basic preprocessing of data: * Turn dictionry into a pandas dataframe * Add annotator column to DF -- stored as string * Name columns according to body part, etc """ df = [] labels = [] seqs = [] for seq_id in raw_data['sequences...
5,323,210
def _merge_kwargs(base, kwargs): """Merge custom values into kwargs then update base with kwargs Args: base (dict): computed defaults kwargs (dict): passed in from setup.py """ for k in 'cmdclass', 'entry_points': if not k in kwargs: continue v = kwargs[k] ...
5,323,211
def cyclic_tdma(lower_diagonal, main_diagonal, upper_diagonal, right_hand_side): """The thomas algorithm (TDMA) solution for tri-diagonal matrix inversion with the sherman morison formula applied Parameters ---------- lower_diagonal: np.ndarray The lower diagonal of the matrix length n, the fir...
5,323,212
def print_task_output(batch_service_client, job_id, encoding=None): """Prints the stdout.txt file for each task in the job. :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient` :param str job_id: The id of the job with task output files to print. ...
5,323,213
def lico2_ocp_Ramadass2004(sto): """ Lithium Cobalt Oxide (LiCO2) Open Circuit Potential (OCP) as a a function of the stochiometry. The fit is taken from Ramadass 2004. Stretch is considered the overhang area negative electrode / area positive electrode, in Ramadass 2002. References ---------- ...
5,323,214
def doctestobj(*args, **kwargs): """ Wrapper for doctest.run_docstring_examples that works in maya gui. """ return doctest.run_docstring_examples(*args, **kwargs)
5,323,215
def _return_model_names_for_plots(): """Returns models to be used for testing plots. Needs - 1 model that has prediction interval ("theta") - 1 model that does not have prediction interval ("lr_cds_dt") - 1 model that has in-sample forecasts ("theta") - 1 model that does not have in-...
5,323,216
def _convert_input_type_range(img): """Convert the type and range of the input image. It converts the input image to np.float16 type and range of [0, 1]. It is mainly used for pre-processing the input image in colorspace convertion functions such as rgb2ycbcr and ycbcr2rgb. Args: img (Asce...
5,323,217
def test_access_to_non_dict_message(): """Only works if the message is a dictionary. """ message = ('attribute', 'value') resp = response.create_success_response(message=message) with pytest.raises(exceptions.FieldException): assert resp.attribute == 'value'
5,323,218
def test_vectors() -> None: """BIP39 test vectors https://github.com/trezor/python-mnemonic/blob/master/vectors.json """ fname = "bip39_test_vectors.json" filename = path.join(path.dirname(__file__), "_data", fname) with open(filename, "r", encoding="ascii") as file_: bip39_test_vectors...
5,323,219
def collect_derivatives(derivatives_dir, subject_id, std_spaces, freesurfer, spec=None, patterns=None): """Gather existing derivatives and compose a cache.""" if spec is None or patterns is None: _spec, _patterns = tuple( loads(Path(pkgrf('aslprep', 'smriprep/data/io_...
5,323,220
def aten_meshgrid(mapper, graph, node): """ 构造对每个张量做扩充操作的PaddleLayer。 TorchScript示例: %out.39 : int = aten::mshgrid(%input.1) 参数含义: %out.39 (Tensor): 输出,扩充后的结果。 %input.1 (Tensor): 输入。 """ scope_name = mapper.normalize_scope_name(node) output_name = mapper._get_outputs...
5,323,221
def bearing_example(): """This function returns an instance of a simple bearing. The purpose is to make available a simple model so that doctest can be written using it. Parameters ---------- Returns ------- An instance of a bearing object. Examples -------- >>> bearing = ...
5,323,222
def parsing_check(dataset, source, attr): """ The annotator gets a contextualized patent citation displayed - the patent citation is highlighted - the title (h3 + bold + purple) is the value of the parsed attribute (e.g. orgname) - the citation has an href linking to the patent webpage (on google pa...
5,323,223
def create_data(): """Create some random exponential data""" #np.random.seed(18) pure = np.array(sorted([np.random.exponential() for i in range(10)])) noise = np.random.normal(0,1, pure.shape) signal = pure + noise return signal
5,323,224
def fetch_accidents(data_home=None): """Fetch and return the accidents dataset (Frequent Itemset Mining) Traffic accident data, anonymized. see: http://fimi.uantwerpen.be/data/accidents.pdf ==================== ============== Nb of items 468 Nb of transactions ...
5,323,225
def align_nodes(nodenet_uid, nodespace): """ Automatically align the nodes in the given nodespace """ return runtime.align_nodes(nodenet_uid, nodespace)
5,323,226
def cindex(y_true: np.array, scores: np.array) -> float: """AI is creating summary for cindex Args: y_true (np.array): An array of actual values of target scores (np.array): An array of predicted score of target Returns: [float]: Returns C-Index score """ return lifelines.u...
5,323,227
def match_tones( left, right, eps=2000., shift_from_right=0., match_col='fr', join_type='inner'): """Return a table with tones matched. This function makes use the ``stilts`` utility. Parameters ---------- left: astropy.Table The left model params table. right: ...
5,323,228
def name(ea, string, *suffix, **flags): """Renames the address specified by `ea` to `string`. If `ea` is pointing to a global and is not contained by a function, then by default the label will be added to the Names list. If `flags` is specified, then use the specified value as the flags. If the boolea...
5,323,229
def verify( symbol_table: intermediate.SymbolTable, ) -> Tuple[Optional[VerifiedIntermediateSymbolTable], Optional[List[Error]]]: """Verify that C# code can be generated from the ``symbol_table``.""" errors = [] # type: List[Error] structure_name_collisions = _verify_structure_name_collisions( ...
5,323,230
def find_workflow_component_figures(page): """ Returns workflow component figure elements in `page`. """ time.sleep(0.5) # Pause for stable display. root = page.root or page.browser return root.find_elements_by_class_name('WorkflowComponentFigure')
5,323,231
def select_best_features(tx, selected_features, rho_exp, w, number_of_select): """Selects features by the highest value of the weights Parameters ---------- tx : np.ndarray Original features selected_features : [(int, int)] Best features from previous iteration rho_exp : np.nda...
5,323,232
def make_pol_lookup(codes): """ Returns a lookup table from a list of polarization codes """ codes = unique(codes) codes.sort() lookup = {} for code in codes: if code == 'X' or code == 'XX' or code == 'H': lookup[code] = -5 elif code == 'Y' or code == 'YY' or code == 'V' or code == 'E': ...
5,323,233
def write_data(data, filename): """ write data in gzipped h5 format with type uint16 """ f = h5py.File(filename, 'w', libver='latest') dset = f.create_dataset('array', shape=(data.shape), data=data, dtype=np.uint16, compression='gzip', compression_opts=9) f.close()
5,323,234
def _calc_best_estimator_optuna_univariate( X, y, estimator, measure_of_accuracy, estimator_params, verbose, test_size, random_state, eval_metric, number_of_trials, sampler, pruner, with_stratified, ): """Function for calculating best estimator Parameters ...
5,323,235
def get_users_info_async(future_session: "FuturesSession", connection, name_begins, abbreviation_begins, offset=0, limit=-1, fields=None): """Get information for a set of users asynchronously. Args: future_session: Future Session object to call MicroStrategy REST Se...
5,323,236
def load_sparse(fname): """ .. todo:: WRITEME """ f = None try: if not os.path.exists(fname): fname = fname + '.gz' f = gzip.open(fname) elif fname.endswith('.gz'): f = gzip.open(fname) else: f = open(fname) d =...
5,323,237
def site_link_url(request, siteobj): """returns a site urls form already given keys""" return '%s://%s%s/site/%s' % ( presettings.DYNAMIC_LINK_SCHEMA_PROTO, request.META.get('HTTP_HOST'), presettings.DYNAMIC_LINK_URL, siteobj.link_key )
5,323,238
def create_directories(params): """ Creates directories """ Logger.info("Creating directories") Directory(params.dirs, create_parents=True, mode=0755, owner=params.airflow_user, group=params.airflow_group )
5,323,239
def get_arguments(): """ All cli arguments. """ p = ap.ArgumentParser() p.add_argument('mode', type=str, choices=['train', 'predict']) # files p.add_argument('--train-file', type=str) p.add_argument('--dev-file', type=str) p.add_argument('--test-file', type=str) p.add_argument('--model-...
5,323,240
def config_cmd_argparser(cmd_argparser: ArgumentParser): """ Configure the ArgumentParser instance for this MixCli command. :param cmd_argparser: the ArgumentParser instance corresponding to this command :return: None """ cmd_argparser.add_argument('-t', '--tsv', action='store_true', ...
5,323,241
def get_headers(path='.credentials/key.conf'): """Get the authentication key header for all requests""" config = configparser.ConfigParser() config.read(path) headers = { 'Ocp-Apim-Subscription-Key': config['default']['primary'] } return headers
5,323,242
def Sdif(M0, dM0M1, alpha): """ :math:`S(\\alpha)`, as defined in the paper, computed using `M0`, `M0 - M1`, and `alpha`. Parameters ---------- M0 : ndarray or matrix A symmetric indefinite matrix to be shrunk. dM0M1 : ndarray or matrix M0 - M1, where M1 is a positive defini...
5,323,243
def env_world_size(): """World size for distributed training. Is set in torch.distributed.launch as args.nproc_per_node * args.nnodes. For example, when running on 1 node with 4 GPUs per node, the world size is 4. see: https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py""" i...
5,323,244
def musicnet_iterator(musicnet_file): """An iterator over the MusicNet archive that yields audio and NoteSequences. The MusicNet archive (in .npz format) can be downloaded from: https://homes.cs.washington.edu/~thickstn/media/musicnet.npz Args: musicnet_file: The path to the MusicNet NumPy archive (.npz) ...
5,323,245
def test_api_exception_invalid_json(): """Test API response Exception""" with pytest.raises(APIException): with requests_mock.mock() as m: not_json_str = "<html><body>Error</body></html>" m.get('https://api.binance.com/api/v1/time', text=not_json_str, status_code=400) ...
5,323,246
def add_entry(entries, folders, collections, session): """Add vault entry Args: entries - list of dicts folders - dict of folder objects collections - dict of collections objects session - bytes Returns: None or entry (Item) """ folder = select_folder(folders) col...
5,323,247
def test_export_pipeline_empty(): """Assert that an error is raised when the pipeline is empty.""" atom = ATOMClassifier(X_bin, y_bin, random_state=1) pytest.raises(ValueError, atom.export_pipeline)
5,323,248
def make_wsgi_app(services_conf=None, debug=False, ignore_config_warnings=True, reloader=False): """ Create a MapProxyApp with the given services conf. :param services_conf: the file name of the mapproxy.yaml configuration :param reloader: reload mapproxy.yaml when it changed """ if sys.versio...
5,323,249
def _get_node_by_name(graph_def: rewrite.GraphDef, node_name: str) -> rewrite.NodeDef: """Return a node from a graph that matches the provided name""" matches = [node for node in graph_def.node if node.name == node_name] return matches[0] if len(matches) > 0 else None
5,323,250
def evaluate(evaluation_data, step): """Evaluating the test set.""" eval_loss_helper = ReconLossHelper(hp, eval_recon_loss=True) start_time = time.time() for data in evaluation_data: outputs = model(data, training=False, run_synth_coder_only=hp.run_synth_coder_only) loss_dict = eval...
5,323,251
def shorten_link(url: str) -> tuple: """ Method to shorten a given url using the shrtco.de API @Parameters url:str url to be shortened @Returns (errorcode:int,result:str) errorcode: int indicating whether operation succeeded or failed ...
5,323,252
def get_sanitized_bot_name(dict: Dict[str, int], name: str) -> str: """ Cut off at 31 characters and handle duplicates. :param dict: Holds the list of names for duplicates :param name: The name that is being sanitized :return: A sanitized version of the name """ # This doesn't work someimte...
5,323,253
def eval_nmt_bleu(model,dataset,vectorizer,args): """ Evaluates the trained model on the test set using the bleu_score method from NLTK. Parameters ---------- model : NMTModel Trained NMT model. dataset : Dataset Dataset with Source/Target sentences. vectorize...
5,323,254
def load_up_the_tests(folder): """reads the files from the samples directory and parametrizes the test""" tests = [] for i in folder: if not i.path.endswith('.yml'): continue with open(i, 'r') as f: out = yaml.load(f.read(), Loader=yaml.BaseLoader) # The ...
5,323,255
def test_gpx_two_points() -> None: """Read a valid GPX file with two trackpoints in it.""" content = Path("tests/testdata/osmand_1seg_2pt.gpx").read_text() trackpoints, waypoints = conv.extract_gpx(content) assert len(trackpoints) == 2 assert trackpoints[0][0] == dt.datetime(2020, 5, 1, 0, 0, 0, tzi...
5,323,256
def satisfiable(expr, algorithm='dpll2', all_models=False): """ Check satisfiability of a propositional sentence. Returns a model when it succeeds. Returns {true: true} for trivially true expressions. On setting all_models to True, if given expr is satisfiable then returns a generator of models...
5,323,257
def send_test_result_metrics(stdout): """ Send custom metrics about test results to cloudwatch. :param stdout: <int> 0/1. 0 indicates no error during test execution, 1 indicates errors occurred """ cloudwatch_client = boto3.client("cloudwatch") use_scheduler = os.getenv("USE_SCHEDULER", "False")...
5,323,258
def dist_create_samples(net_file, K=Inf, nproc=None, U=0.0, S=0.0, V=0.0, max_iter=Inf, T=Inf, discard=False, variance=False, input_vars=DEFAULT_INPUTS, output_vars=DEFAULT_OUTPUTS, dual_vars=DEFAULT_DUALS, sampler='sample_polytope_cprnd', sampler_...
5,323,259
async def channel_leave(event: Event[uita.message.ChannelLeaveMessage]) -> None: """Disconnect the bot from the voice channel of the active server.""" assert event.active_server is not None voice = uita.state.voice_connections[event.active_server.id] await voice.disconnect()
5,323,260
def test_create_ingredient_successful(authenticated_user): """Test creating a new ingredient""" user, client = authenticated_user payload = {"name": "bread"} client.post(INGREDIENTS_URL, payload) exists = Ingredient.objects.filter(user=user, name=payload["name"]).exists() assert exists
5,323,261
def get_valid_filename(s): """ Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; slashes and colons are converted to dashes; and anything that is not a unicode alphan...
5,323,262
def test_player_handles_mark() -> None: """It handles get and set for marks.""" for player in ( engine.HumanPlayer(1, PLAYER_A_NAME), engine.AIPlayer(1, PLAYER_B_NAME), ): assert player.get_mark() == 1 player.set_mark(-1) assert player.get_mark() == -1 player....
5,323,263
def test_gcre_1(): """ Test the GCRE against known values for the uniform distribution. """ dists = [ uniform(-n//2, n//2) for n in range(2, 23, 2) ] results = [0.5, 1.31127812, 2.06831826, 2.80927657, 3.54316518, 4.27328199, 5.00113503, 5.72751654, 6.45288453, 7.17752308, 7.90161817]...
5,323,264
def clean_text(text, remove_stopwords = True): """ remove artifacts, unneccessary words etc """ ## regex method - remove '\n' cleantext = re.sub(r"\\n", " ", text) ## remove '\BA' cleantext = re.sub(r"\\BA", " ", cleantext) ## remove '\' c...
5,323,265
def initialise_empty_cells(): """Initialise empty dictionary of cells for the grid.""" cells = {(x, y): False for x in range(CELL_WIDTH) for y in range(CELL_HEIGHT)} return cells
5,323,266
def test_exec_cmd_combine_outputs( mock_exec_cmd: MagicMock, caplog: LogCaptureFixture ): """Should execute the command and one output with stdout and stderr.""" mock_exec_cmd.return_value.returncode = 0 mock_exec_cmd.return_value.stdout = 'fake stdout message and fake stderr message' cmd = ['nx...
5,323,267
def wait_for_idle(m: Maestral, cycles: int = 4) -> None: """Blocks until Maestral instance is idle for at least ``cycles`` sync cycles.""" count = 0 while count < cycles: if m.sync.busy(): # Wait until we can acquire the sync lock => we are idle. m.sync.sync_lock.acquire() ...
5,323,268
def test_wild003_wild003_v1_xml(mode, save_output, output_format): """ Basic test of xs:anyAttribute with notNamespace = ##local Allows any attribute so long as it's in a namespace """ assert_bindings( schema="saxonData/Wild/wild003.xsd", instance="saxonData/Wild/wild003.v1.xml", ...
5,323,269
def query_left(tree, index): """Returns sum of values between 1-index inclusive. Args: tree: BIT index: Last index to include to the sum Returns: Sum of values up to given index """ res = 0 while index: res += tree[index] index -= (index & -index) ...
5,323,270
def deleteCategory(category_name): """ This endpoint will show category delete confirmation by GET request and will delet the category by POST request.""" session = DBSession() category = session.query(Category).filter_by(name=category_name).one() if request.method == 'POST' and login_session[...
5,323,271
def figure_defaults(): """Generates default figure arguments. Returns: dict: A dictionary of the style { "argument":"value"} """ plot_arguments={ "fig_width":"6.0",\ "fig_height":"6.0",\ "xcols":[],\ "xvals":"",\ "xvals_colors_list":[],\ "xvals_co...
5,323,272
def CacheMiss(Exception): """Exception raised when a cache miss occurs.""" pass
5,323,273
def apply_box_deltas_graph(boxes, deltas, Size=24): """Applies the given deltas to the given boxes. boxes: [N, (z1, y1, x1, z2, y2, x2)] boxes to update deltas: [N, (dz, dy, dx)] refinements to apply """ # center_z, center_y, center_x are the (normalized) coordinates of the centers center_z...
5,323,274
def calculate_number_of_peaks_gottschalk_80_rule(peak_to_measure, spread): """ Calculate number of peaks optimal for SOBP optimization on given spread using Gottschalk 80% rule. """ width = peak_to_measure.width_at(val=0.80) n_of_optimal_peaks = int(np.ceil(spread // width)) return n_of_opti...
5,323,275
def maxsum(sequence): """Return maximum sum.""" maxsofar, maxendinghere = 0, 0 for x in sequence: # invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]`` maxendinghere = max(maxendinghere + x, 0) maxsofar = max(maxsofar, maxendinghere) return maxsofar
5,323,276
def github_archive(name, org, repo, ref, sha256): """Declare an http_archive from github """ if name not in native.existing_rules(): http_archive( name = name, strip_prefix = repo + "-" + ref, urls = [ "https://mirror.bazel.build/github.com/%s/%s/...
5,323,277
def matrix_from_angles(rot): """ Create a rotation matrix from a triplet of rotation angles. Args: rot: a tf.Tensor of shape [..., 3], where the last dimension is the rotation angles, along x, y, and z. Returns: A tf.tensor of shape [..., 3, 3], where the last two dimensions are t...
5,323,278
def textbox(msg="", title=" ", text="", codebox=0, get_updated_text=None): """ Display some text in a proportional font with line wrapping at word breaks. This function is suitable for displaying general written text. The text parameter should be a string, or a list or tuple of lines to be displaye...
5,323,279
def get_fov_stats(mrcnn, low_confidence, discordant, extreme, artifacts, roi_mask= None, keep_thresh = 0.5, fov_dims= (256,256), shift_step= 128): """ Gets potential FOVs along with their associated statistics. Args: * mrcnn [m, n, 4] - pos...
5,323,280
def negative_sampling_loss(pos_dot, neg_dot, size_average=True, reduce=True): """ :param pos_dot: The first tensor of SKipGram's output: (#mini_batches) :param neg_dot: The second tensor of SKipGram's output: (#mini_batches, #negatives) :param size_average: :param reduce: :return: a tensor has a...
5,323,281
def _has_externally_shared_axis(ax1: "matplotlib.axes", compare_axis: "str") -> bool: """ Return whether an axis is externally shared. Parameters ---------- ax1 : matplotlib.axes Axis to query. compare_axis : str `"x"` or `"y"` according to whether the X-axis or Y-axis is being ...
5,323,282
def network_size(graph, n1, degrees_of_separation=None): """ Determines the nodes within the range given by a degree of separation :param graph: Graph :param n1: start node :param degrees_of_separation: integer :return: set of nodes within given range """ if not isinstance(graph, (BasicG...
5,323,283
def test_middleware_handled_view_exception_success(client, test_spans): """ When an exception is raised in a view and then handled Only the culprit span contains error properties """ with modify_settings( **( dict(MIDDLEWARE={"append": "tests.contrib.django.middleware.HandleE...
5,323,284
def get_conserved_sequences(cur): """docstring for get_conserved_sequences""" cur.execute("SELECT sureselect_probe_counts.'sureselect.seq', \ sureselect_probe_counts.cnt, \ sureselect_probe_counts.data_source, \ cons.cons \ FROM sureselect_probe_counts, cons \ WHERE sures...
5,323,285
def delete_empty_keys(data: Any): """Build dictionary copy sans empty fields""" # Remove empty field from dict # https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary#5844700 dic = data.dict() # if isinstance(data, BaseModel): # dic = **data.dict() return { i:di...
5,323,286
def scan_for_images(tmos_image_dir): """Scan for TMOS disk images""" return_image_files = [] for image_file in os.listdir(tmos_image_dir): filepath = "%s/%s" % (tmos_image_dir, image_file) if os.path.isfile(filepath): extract_dir = "%s/%s" % (tmos_image_dir, ...
5,323,287
def test_init_default(): """initialize my hazard -- smoke""" g, deadline, d_list = get_param() assert deadline == 10 assert g["name"] == 'G9V_grid' hazard = MyHazard(g, deadline) # test pre defined parameters assert hazard.levels == [1, 2, 3, 4, 5] assert hazard.level_label == ['Low'...
5,323,288
def test_spend_unvault_tx_trader_second_trader(bitcoind): """ This tests the unvault transaction spending with the signatures of the second trader and the stakeholder. """ # The stakeholders, the first two are the traders. stk_privkeys = [os.urandom(32) for i in range(4)] stk_pubkeys = [CKey...
5,323,289
def find_language(article_content): """Given an article's xml content as string, returns the article's language""" if article_content.Language is None: return None return article_content.Language.string
5,323,290
def loadDictFromFile(f): """ Load a DotDict from the JSON-format file *f*. """ return dotDict.convertToDotDictRecurse(json.load(f))
5,323,291
def create_problem_from_type_base(problem): """ Creates OptProblem from type-base problem. Parameters ---------- problem : Object """ p = OptProblem() # Init attributes p.phi = problem.phi p.gphi = problem.gphi p.Hphi = problem.Hphi p.A = problem.A p.b = problem.b ...
5,323,292
def test_overlay(): """ make a crude CSF mask, to test the overlay function """ b = np.load('T1_recovery_lowres_4D.npz')['T1vols'] mask1 = b[..., 0] > 0.05 * b[..., 0].max() mask2 = b[..., 7] < 0.3 * b[..., 7].max() csf_mask = mask1 & mask2 volshow(b[..., 7], mode='m', transpose=True) masked...
5,323,293
def geturls(str1): """returns the URIs in a string""" URLPAT = 'https?:[\w/\.:;+\-~\%#\$?=&,()]+|www\.[\w/\.:;+\-~\%#\$?=&,()]+|' +\ 'ftp:[\w/\.:;+\-~\%#?=&,]+' return re.findall(URLPAT, str1)
5,323,294
def get_list(imid: str) -> requests.Response: """ Return the requests.Response containing the list of images for a given image-net.org collection ID. """ imlist = requests.get(LIST_URL.format(imid=imid)) return imlist
5,323,295
def minimum(x1, x2): """Element-wise minimum of input variables. Args: x1 (~chainer.Variable): Input variables to be compared. x2 (~chainer.Variable): Input variables to be compared. Returns: ~chainer.Variable: Output variable. """ return Minimum().apply((x1, x2))[0]
5,323,296
def retype_file(src, pyi_dir, targets, *, quiet=False, hg=False): """Retype `src`, finding types in `pyi_dir`. Save in `targets`. The file should remain formatted exactly as it was before, save for: - annotations - additional imports needed to satisfy annotations - additional module-level names nee...
5,323,297
def clean_source(cfg: Dict[str, str]) -> NoReturn: """ The guts of the "clean-source" command, this function deletes the source notebooks for current course from the remote Databricks instance. :param cfg: The config. COURSE_NAME, COURSE_REMOTE_SOURCE, and DB_PROFILE are assumed to be s...
5,323,298
def train(train_dataset : dict, validation_dataset : dict, batch_size : int = 16, num_epochs : int = 5000, allow_cuda : bool = True, use_shuffle : bool = True, save_criterion : callable = None, stop_criterion : callable = None, save_on_finish : bool = True) -> dict: """ Perfor...
5,323,299