content
stringlengths
22
815k
id
int64
0
4.91M
def test_empty_x_field(): """ Expect the same response is if x-fields header is not used """ r = _get_with_additional_headers({X_FIELDS: ''}) assert r['total']['value'] == NUMBER_OF_ADS assert len(r) == 7 assert len(r['hits']) == 10 assert len(r['hits'][0]) == 35
26,300
def test_md025_bad_front_matter_title_top_level_atx(): """ Test to make sure we get the expected behavior after scanning a good file from the test/resources/rules/md004 directory that has consistent asterisk usage on a single level list. """ # Arrange scanner = MarkdownScanner() supplie...
26,301
def main(): """Go Main Go""" for i in range(1, 15): runner(i)
26,302
def getCaffemodelFromSolverstate(solverstate): """ Parse the filename of the caffemodel file from the solverstate file. """ from backend.caffe.path_loader import PathLoader proto = PathLoader().importProto() try: state = proto.SolverState() with open(solverstate, 'rb') as f: ...
26,303
def get_L_from_D(line): """ Assume line contains one or more <Dn> Return list of all n """ a = [] for m in re.finditer(r'<D([0-9]+)>',line): a.append(m.group(1)) return a
26,304
def test_base_url_error(): """Test the base URL setting on init.""" url = utils.random_lower_string() with pytest.raises(ValidationError): _ = DriPostal(url)
26,305
def per_pixel_mean_stddev(dataset, image_size): """ Compute the mean of each pixel over the entire dataset. """ #NOTE: Replace "3" by the number of channels initial_state = tf.constant(0., dtype=tf.float32, shape=[image_size, image_size, 3]) dataset = dataset.map(lambda x: resize(x, image_si...
26,306
def get_indexes_from_list(lst, find, exact=True): """ Helper function that search for element in a list and returns a list of indexes for element match E.g. get_indexes_from_list([1,2,3,1,5,1], 1) returns [0,3,5] get_indexes_from_list(['apple','banana','orange','lemon'], 'orange') -> returns [2]...
26,307
def simplify_polygon(polygon, tolerance=0.01): """Remove doubles coords from a polygon.""" assert isinstance(polygon, Polygon) or isinstance(polygon, MultiPolygon) # Get the coordinates coords = [] if isinstance(polygon, Polygon): coords = polygon.exterior.coords elif isinstance(polygon,...
26,308
def plot_wordcloud(text): """ Draw wordcloud with matplotlib :param text: :return: """ wordcloud = WordCloud(max_font_size=50, max_words=100, background_color="white", relative_scaling=1.0, stopwords=stop_words_es).gen...
26,309
def test_get_all_namespace_when_no_descriptors(): """test_get_all_namespace_when_no_descriptors.""" descriptors = dict() res = get_all_namespaces(descriptors) assert len(res) == 0
26,310
def candplot(canddatalist, snrs=None, outname=''): """ Takes output of search_thresh (CandData objects) to make candidate plots. Expects pipeline state, candidate location, image, and phased, dedispersed data (cut out in time, dual-pol). snrs is array for an (optional) SNR histogram plot. Writte...
26,311
def looks_like_PEM(text): """ Guess whether text looks like a PEM encoding. """ i = text.find("-----BEGIN ") return i >= 0 and text.find("\n-----END ", i) > i
26,312
def find_duplicates(list_to_check): """ This finds duplicates in a list of values of any type and then returns the values that are duplicates. Given Counter only works with hashable types, ie it can't work with lists, create a tuple of the lists and then count if the list_to_check contains un-hashable i...
26,313
def test_failure(database): """ Test failure for PrimaryPlaceofPerformanceZIP+4 should not be provided for any format of PrimaryPlaceOfPerformanceCode other than XX#####. """ det_award_1 = DetachedAwardFinancialAssistanceFactory(place_of_performance_code="00FORGN", ...
26,314
def none_to_default(field: Any, default: Any) -> Any: """Convert None values into default values. :param field: the original value that may be None. :param default: the new, default, value. :return: field; the new value if field is None, the old value otherwise. :rtype: any """ retu...
26,315
def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, cache, show_progress, output_dir): """Build a zipline data bun...
26,316
def _maybe_disable_mpi(mpi_disabled): """A context that can temporarily remove the mpi4py import. Useful for testing whether non-MPI algorithms work as intended when mpi4py isn't installed. Args: disable_mpi (bool): If True, then this context temporarily removes the mpi4py import f...
26,317
def test_ap_wps_authenticator_mismatch_m5(dev, apdev): """WPS and Authenticator attribute mismatch in M5""" addr,bssid,hapd = wps_start_ext(apdev[0], dev[0]) wps_ext_eap_identity_req(dev[0], hapd, bssid) wps_ext_eap_identity_resp(hapd, dev[0], addr) wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Star...
26,318
def search(): """Search downloaded pages."""
26,319
def test_convert_new_line_tags(): """Tests converting HTML links into JSON.""" json = html_to_draftjs("<br><br/>", strict=True) assert json == { "entityMap": {}, "blocks": [ { "key": "", "text": "\n\n", "type": "unstyled", ...
26,320
def fetch_pauli2018(data_dir=None, url=None, resume=True, verbose=1): """ Downloads files for Pauli et al., 2018 subcortical parcellation Parameters ---------- data_dir : str, optional Path to use as data directory. If not specified, will check for environmental variable 'NNT_DATA';...
26,321
def test_list_installed_packages(): """ Test the main function of ggd list """ ## Normal Run args = Namespace(command='list', pattern=None, prefix=None, reset=False) temp_stdout = StringIO() with redirect_stdout(temp_stdout): list_installed_pkgs.list_installed_packages((), args) ...
26,322
def filled_in_kinefold_form(filename, list_of_sub_objects): """ Creates a kinefold submission for for simulating and processing devices on hyak. :param filename: The name of the csv filename. :type filename: str :param list_of_sub_objects: List of submission objects to be created :type list_...
26,323
def lambda_to_ent(la): """ entanglement from a schmidt coeff lambda ent = - [la * log(la) + (1 - la) * log(1 - la)] where la (lambda) is the Schmidt coefficient """ return - np.nan_to_num((1-la)*np.log(1-la) + la*np.log(la))
26,324
def parse_states( value_field: str, selected_values: selected_values_type, selected_fields: selected_fields_type, *, field_cleaners: Dict[str, Callable[[pd.DataFrame, str], pd.DataFrame]] = None, ) -> parsed_data_type: """ Outputs CSVs of state data after parsing a large CSV of U.S. county-l...
26,325
def check_updates(): """ invoke --upgrade-dist return output lines as array """ # check that permissions are sufficent if not os.access(os.path.join(CONFIG["rpmdir"], 'Packages'), os.R_OK): die("ERROR", "rpm Packages accessible: %s" % os.path.join(CONFIG["rpmdir"], 'Packages')) if ...
26,326
def resp(): """ Requests response fixture""" resp = Response() resp.status_code = 409 yield resp
26,327
def get_reference_models(content_model): """Yields (model, lookups) tuples, where model is a model that can contain references to content_model. """ extension = get_extension() yield from _get_reference_models(content_model, extension.reference_models)
26,328
def is_diagonal_segment(vector_start, vector_end): """Diagonal as defined by a slope of 1 or -1""" return slope(vector_start, vector_end) in (1, -1)
26,329
def evaluate_statistic_methods_on_file(f, xc, mas, classifier_obj, tagger): """ :type xc: RGCorpus :type mas: MultAlignScorer """ xc.heur_align() # Start by adding the manual alignments... mas.add_corpus('gold', INTENT_ALN_MANUAL, f, xc) EVAL_LOG.info("") xc.giza_align_t_g(aligner...
26,330
def properties_table(segment_props, columns=None, exclude_columns=None): """ Construct a `~astropy.table.Table` of properties from a list of `SegmentProperties` objects. If ``columns`` or ``exclude_columns`` are not input, then the `~astropy.table.Table` will include all scalar-valued properties. ...
26,331
def create_mutation(model, app): """Create Class-Mutation.""" app_name_lower = app.name.lower() type_name = f"{ app_name_lower }{ app.model.name }Type" mutation_name = f"{ app_name_lower }{ app.model.name }Mutation" form_name = f"{ app_name_lower }{ app.model.name }Form" api_uri = f"{ app_name_l...
26,332
def read_players_info(): """Get players info - [player 1 name, player 1 sign]""" first_player_name = input("Player one name: ") second_player_name = input("Player two name: ") first_player_sign = read_first_player_sign(first_player_name) second_player_sign = "O" if first_player_sign == "X" else "X" ...
26,333
def z_gate_circuits_deterministic(final_measure=True): """Z-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Z alone circuit = QuantumCircuit(*regs...
26,334
def symbol_sum(variables): """ ``` python a = symbols('a0:100') %timeit Add(*a) # >>> 10000 loops, best of 3: 34.1 µs per loop b = symbols('b0:1000') %timeit Add(*b) # >>> 1000 loops, best of 3: 343 µs per loop c = symbols('c0:3000') %timeit Add(*c) ...
26,335
def before_request(): """Make sure we are connected to the database each request and look up the current user so that we know he's there. """ g.db = connect_db() g.user = None if 'user_id' in session: g.user = query_db('select * from user where user_id = ?', [se...
26,336
def any_specified_encoding(sequence: bytes, search_zone: int = 4096) -> Optional[str]: """ Extract using ASCII-only decoder any specified encoding in the first n-bytes. """ if not isinstance(sequence, bytes): raise TypeError seq_len = len(sequence) # type: int results = findall( ...
26,337
def maf(genotypes): """Computes the MAF and returns a boolean indicating if the minor allele is currently the coded allele. """ warnings.warn("deprecated: use 'Genotypes.maf'", DeprecationWarning) g = genotypes.genotypes maf = np.nansum(g) / (2 * np.sum(~np.isnan(g))) if maf > 0.5: ...
26,338
def test_extract_media_extracts_file() -> None: """Ensure extract_media extracts a FileDescription and sets attachment correctly.""" extracted_media, extracted_file = extract_media(InputMediaPhoto(Path('test.jpg'))) assert isinstance(extracted_media.media, str) assert extracted_media.media.startswith('...
26,339
def lower_bound_jensen_shannon(logu, joint_sample_mask=None, validate_args=False, name=None): """Lower bound on Jensen-Shannon (JS) divergence. This lower bound on JS divergence is proposed in [Goodfellow et al. (2014)][1] and [Nowozin et al. (2016)][2]. When estimating lower bou...
26,340
def start_data_package_loader(): """ Adds the data package loader to the module loaders. """ sys.meta_path.append(DataPackageFinder())
26,341
def random_splits(sets: List, out_path: str, out_size: int, num: int, cat: str=None): """Make `num` random splits of the datasets in `sets` containing `out_size` images each.""" for n in range(num): concat_sets(sets, out_path + '_' + str(out_size) + id_string(n) + '.json', out_size, cat=cat)
26,342
def competition_ranking(data, dtype="int32"): """ Ranks the given data in increasing order and resolving duplicates using the lowest common rank and skipping as many ranks as there are duplicates, i.e., [0.5, 1.2, 3.4, 1.2, 1.2] -> [1, 2, 5, 2, 2]. Parameters ---------- data: numpy.arr...
26,343
def fmt_dashes(name: str) -> str: """ Converts name to words separated by dashes. Words are identified by capitalization, dashes, and underscores. """ return '-'.join([word.lower() for word in split_words(name)])
26,344
def stringify_dict_key(_dict): """ 保证_dict中所有key为str类型 :param _dict: :return: """ for key, value in _dict.copy().items(): if isinstance(value, dict): value = stringify_dict_key(value) if not isinstance(key, str): del _dict[key] _dict[str(key)] ...
26,345
def bestIndividual(hof, X, y): """ Get the best individual """ maxAccurcy = 0.0 for individual in hof: if(individual.fitness.values > maxAccurcy): maxAccurcy = individual.fitness.values _individual = individual _individualHeader = [list(X)[i] for i in range( ...
26,346
def output_with_grid_search(kalman_filter, key, grid_params, annotations): """パラメータをグリッドサーチして, xiごとに1つの図に出力. Args: kalman_filter (KalmanFilterSteadyState): kalman filterクラス. key (str): グリッドサーチ対象の(kalman_filterクラスの)メンバ変数. grid_params (list): グリッドサーチに使う値リスト. annotations (list): gr...
26,347
def rename_fasta(file: str, out: str, new_locus_tag_prefix: str, old_locus_tag_prefix: str = None, validate: bool = False): """ Change the locus tags in a protein/nucleotide FASTA file :param file: input file :param out: output file :param new_locus_tag_prefix: desired locus tag :param old_locu...
26,348
def make_new_paste(devkey, paste_text, user_key=None, paste_title=None, paste_format=None, paste_type=None, paste_expiry: int=None): """This function creates a new paste on pastebin with the given arguments.""" data = {'api_dev_key': devkey, 'api_option': 'paste', 'api_paste_code': paste_text, 'api_paste_e...
26,349
def not_none(value): """ This function ensures that passed value is not None: >>> schema = Schema(not_none) >>> assert 1 == schema(1) >>> try: ... schema(None) ... assert False, "an exception should've been raised" ... except MultipleInvalid: ... pass """ if val...
26,350
def before_request(): """ before request """ if 'is_admin' in session: g.is_admin = 1 else: g.is_admin = None
26,351
def j1c_dblprime(amplitudes): """Calculate j''1c angular observable""" [_, _, _, _, a_0_l, a_0_r, a_00_l, a_00_r] = amplitudes return (2 / tf.sqrt(3.0)) * ( tf.math.real(a_00_l * tf.math.conj(a_0_l) * bw_k700_k892) + tf.math.real(a_00_r * tf.math.conj(a_0_r) * bw_k700_k892) )
26,352
def preprocess(img): """Changes RGB [0,1] valued image to BGR [0,255] with mean subtracted.""" mean_bgr = load_mean_bgr() print 'mean blue', np.mean(mean_bgr[:, :, 0]) print 'mean green', np.mean(mean_bgr[:, :, 1]) print 'mean red', np.mean(mean_bgr[:, :, 2]) out = np.copy(img) * 255.0 out =...
26,353
def test_get_breach(requests_mock): """Tests darktrace-get-breach command function. Configures requests_mock instance to generate the appropriate get_alerts API response, loaded from a local JSON file. Checks the output of the command function with the expected output. """ from Darktrace import...
26,354
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the WorldTidesInfo Custom sensor.""" # Get data from configuration.yaml name = config.get(CONF_NAME) lat = config.get(CONF_LATITUDE, hass.config.latitude) lon = config.get(CONF_LONGITUDE, hass.config.longitude) if N...
26,355
def get_modules(folder): """Find (and import) all valid modules in the given submodule of this file. @return: all loaded valid modules @rtype: iterator of module """ mod = importlib.import_module(".." + folder, __name__) prefix = mod.__name__ + "." modules = [m[1] for m in pkgutil.iter_modul...
26,356
def profile_detail(request, username, template_name='userena/profile_detail.html', extra_context=None, **kwargs): """ Detailed view of an user. :param username: String of the username of which the profile should be viewed. :param template_name: String representing the template name tha...
26,357
def prepare_ternary(figsize, scale): """Help function to ternary plot""" fig, ax = plt.subplots(figsize=figsize) tax = ternary.TernaryAxesSubplot(ax=ax, scale=scale) ax.axis('off') gm = 0.1 * scale blw = 1 tlw = 1 # Draw Boundary and Gridlines tax.boundary(linewidth=blw) tax.grid...
26,358
def parse_spreadsheet(hca_spreadsheet: Workbook, entity_dictionary: Dict): """ Parse the spreadsheet and fill the metadata with accessions. :param hca_spreadsheet: Workbook object of the spreadsheet :param entity_dictionary: Dictionary mapping by entity UUID to the proper archiveEntity :return: Acc...
26,359
def test_a_extra_tokens(): """Test a theoretical A format with extra tokens in first section.""" msg = ".AR SHPP1 20210925 Z DH06 DC202109210148/DUE/DQG/QIIFE 151000.0" res = process_message_a(msg) assert res[0].qualifier == "G"
26,360
def test__rules__std_L016_L036_long_line_fix2(): """Verify that a long line that causes a clash between L016 and L036 does not add multiple newlines (see #1424).""" sql = "SELECT\n 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n" result = sqlfluff.fi...
26,361
def decode(data): """Decode JSON serialized string, with possible embedded Python objects. """ return _decoder.decode(data)
26,362
def p_correction(p_values): """ Corrects p_values for multiple testing. :param p_values: Dictionary storing p_values with corresponding feature names as keys. :return: DataFrame which shows the results of the analysis; p-value, corrected p-value and boolean indicating \ significance. """ p...
26,363
def GetFlippedPoints3(paths, array): """same as first version, but doesnt flip locations: just sets to -1 used for random walks with self intersections - err type 6""" # this may not work for double ups? for i in paths: for j in i: # for the rest of the steps... array[j[0]][j[1]][j[...
26,364
def reset(context): """ Recreates database. """ import django from django.conf import settings django.setup() if not settings.DEBUG: print("DEBUG is False!") Exit() return user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PAS...
26,365
async def _silent_except(f: Callable, *args, **kwargs): """ Helper Function that calls a function or coroutine and returns its result excepting all errors """ try: called = f(*args, **kwargs) except: return if isawaitable(called): try: result = await called ...
26,366
def get_concat_h(im1, im2): """Concatenate two images horizontally.""" dst = Image.new("RGB", (im1.width + im2.width, im1.height)) dst.paste(im1, (0, 0)) dst.paste(im2, (im1.width, 0)) return dst
26,367
def visualize_one_channel_dataset(images_original, images_transformed, labels): """ Helper function to visualize one channel grayscale images """ num_samples = len(images_original) for i in range(num_samples): plt.subplot(2, num_samples, i + 1) # Note: Use squeeze() to convert (H, W,...
26,368
def get_taxname(taxid): """Return scientific name for NCBI Taxonomy ID.""" if get_taxname.id_name_map is None: get_taxname.id_name_map = load_taxid_name_map('data/taxnames.tsv') if get_taxname.id_name_map is None: # assume fail, fallback get_taxname.id_name_map = TAXID_NAME_MAP ...
26,369
def _get_movies(dir): """Gets the movies from the specified directory""" movieList = [] directories = os.listdir(dir) for d in directories: # We need to skip past directories without instruction sets if '__' not in d: continue files = os.listdir("{root}/{subdir}".for...
26,370
def lrfn(epoch): """ lrfn(epoch) This function creates a custom piecewise linear-exponential learning rate function for a custom learning rate scheduler. It is linear to a max, then exponentially decays * INPUTS: current `epoch` number * OPTIONAL INPUTS: None * GLOBAL INPUTS:`START_LR`, `MIN_LR...
26,371
def get_balances(): """ Get the balances of the configured validator (if possible) """ balances = account.get_balance_on_all_shards(validator_config['validator-addr'], endpoint=node_config['endpoint']) for bal in balances: bal['balance'] = float(numbers.convert_atto_to_one(bal['balance'])) ...
26,372
def test_duplicate(): """verify duplicate table detection""" with pytest.raises(ValueError) as ex: A.query.join(C).join(C) assert ex.value.args[0] == "duplicate table 'c'" A.query.join(C).join(C, alias='CC')
26,373
def _make_ordered_node_map( pipeline: pipeline_pb2.Pipeline ) -> 'collections.OrderedDict[str, pipeline_pb2.PipelineNode]': """Prepares the Pipeline proto for DAG traversal. Args: pipeline: The input Pipeline proto, which must already be topologically sorted. Returns: An OrderedDict that maps ...
26,374
def energy(_x, _params): """Kinetic and Potential Energy of point mass pendulum. _x is an array/list in the following order: q1: Angle of first pendulum link relative to vertical (0 downwards) u1: A[1] measure number of the inertial angular velocity of the first link. _params is an array...
26,375
def gelu(input_tensor): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied. """ # math.sqrt nee...
26,376
def cli(): """Query threat report from APIs, or submit for analysis."""
26,377
def KPConv_ops(query_points, support_points, neighbors_indices, features, K_points, K_values, KP_extent, KP_influence, aggregation_mode): """ This function creates a graph of operations to def...
26,378
def listen_keyboard(): """ This function will listen the keyboard and save the event. :return: None """ data_path = 'Data/Train_Data/Keyboard' if not os.path.exists(data_path): os.makedirs(data_path) def on_press(key): save_event_keyboard(data_path, 1, key) def on_relea...
26,379
async def invert(message: discord.Message, image_arg: image): """ Invert the colors of an image. """ image_arg.modify(ImageOps.invert, convert="RGB") await send_image(message, image_arg, quality=100)
26,380
def kerneleval(X_test, X_train, kernel): """ This function computes the pariwise distances between each row in X_test and X_train using the kernel specified in 'kernel' X_test, X_train: 2d np.arrays kernel: kernel parameters """ if kernel is None: return X_train fn = kernel...
26,381
def aks_show_snapshot_table_format(result): """Format a snapshot as summary results for display with "-o table".""" return [_aks_snapshot_table_format(result)]
26,382
def get_all_monitors() -> List[Dict[str, Any]]: """ :return: all monitors array list sorted from left to right. i.e: [ {'hr': 1366, 'vr': 768, 'ho': 0, 'vo': 914, 'name': 'eDP-1-1'}, {'hr': 2560, 'vr': 1440, 'ho': 1366, 'vo': 0, 'name': 'HDMI-1-1'}, ] hr: Horizontal resolution ...
26,383
def poly_prem(f, g, *symbols): """Returns polynomial pseudo-remainder. """ return poly_pdiv(f, g, *symbols)[1]
26,384
def reset_accumulators(): """ Simply reset all accumulators for scalars. """ _accumulators.clear()
26,385
def gen_input_code(question, id): """ Returns the html code for rendering the appropriate input field for the given question. Each question is identified by name=id """ qtype = question['type'] if qtype == 'text': return """<input type="text" class="ui text" name="{0}" ...
26,386
def orbit_position(data, body='sun'): """calculate orbit position of sun or moon for instrument position at each time in 'data' using :class:`ephem` Args: data: :class:`xarray.Dataset`, commonly Measurement.data body (optional): name of astronomical body to calculate orbit from ('sun' or 'moon'...
26,387
def test_by_type_failing(db): """ Ensure that when incorrect brewery type is requested, correct error response returned. """ # GIVEN FastAPI GET request to breweries endpoint # WHEN GET response to invalid brewery type `by_type` query parameter response = client.get("/breweries", params={"b...
26,388
def stop(): """Stop any currently playing presets and return to the prior state.""" for bulb in BULBS: bulb.stop_flow()
26,389
def list_inventory (inventory): """ :param inventory: dict - an inventory dictionary. :return: list of tuples - list of key, value pairs from the inventory dictionary. """ result = [] for element, quantity in inventory.items(): if quantity > 0: result.append ((element, qua...
26,390
def mcf_classical_atom(modal_context, fml, clausal_form_dict, id_mc): """ Takes classical literal (fml), and adds to relevant disjunction. """ assert not u.is_complex(fml) create_mc(modal_context, id_mc, clausal_form_dict, fml)
26,391
def wsd_is_duplicated_msg(msg_id): """ Check for a duplicated message. Implements SOAP-over-UDP Appendix II Item 2 """ if msg_id in wsd_known_messages: return True wsd_known_messages.append(msg_id) if len(wsd_known_messages) > WSD_MAX_KNOWN_MESSAGES: wsd_known_messages.popl...
26,392
def match_diagnostic_plot(V1, V2, pair_ix, tf=None, new_figure=False): """ Show the results of the pair matching from `match_catalog_quads`. """ import matplotlib.pyplot as plt if new_figure: fig = plt.figure(figsize=[4,4]) ax = fig.add_subplot(111) else: ax = plt.gc...
26,393
def sliding_tile_state(): """ Return the current state of the puzzle :return: JSON object representing the state of the maze puzzle """ json_state = {'sliding_tile': sliding_tile.array(), 'solver': sliding_tile_str_solver, 'steps': sliding_tile_steps, 'search_steps': sliding_tile_s...
26,394
def test_plot_raw_filtered(): """Test filtering of raw plots.""" raw = _get_raw() assert_raises(ValueError, raw.plot, lowpass=raw.info['sfreq'] / 2.) assert_raises(ValueError, raw.plot, highpass=0) assert_raises(ValueError, raw.plot, lowpass=1, highpass=1) assert_raises(ValueError, raw.plot, low...
26,395
def _json_to_numpy(string_like, dtype=None): # type: (str) -> np.array """Convert a JSON object to a numpy array. Args: string_like (str): JSON string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the ...
26,396
def connect(**kwargs): """ A strategy to connect a bot. :param kwargs: strategy, listener, and orders_queue :return: the input strategy with a report """ strategy = kwargs['strategy'] listener = kwargs['listener'] orders_queue = kwargs['orders_queue'] assets = kwargs['assets'] ...
26,397
def create_env(env, render=False, shared=False, maddpg=False, evaluate=False): """Return, and potentially create, the environment. Parameters ---------- env : str or gym.Env the environment, or the name of a registered environment. render : bool whether to render the environment ...
26,398
def measure_approximate_cost(structure): """ Various bits estimate the size of the structures they return. This makes that consistent. """ if isinstance(structure, (list, tuple)): return 1 + sum(map(measure_approximate_cost, structure)) elif isinstance(structure, dict): return len(structure) + sum(map(measure_approx...
26,399