content
stringlengths
22
815k
id
int64
0
4.91M
def ensure_rng(rng=None): """Simple version of the ``kwarray.ensure_rng`` Args: rng (int | numpy.random.RandomState | None): if None, then defaults to the global rng. Otherwise this can be an integer or a RandomState class Returns: (numpy.random.RandomState) : rng - ...
5,314,600
def generate_ranked_data(): """ This function read raw data then generates two lists of neighbourhood groups ranked by price and rating, then transform it into approriate formate used in neighbourhood_view.html It generates 2 files under html.js 1. ranked_price_data_by_group.js 2. ranked_r...
5,314,601
def start(ctx, system=True): """ Start both Nginx and Gunicorn under Circus supervision (#TODO!). """ # os.execlp('circusd', '--daemon', '/etc/circus.ini') #os.spawnlp(os.P_NOWAIT, 'nginx', '-p', '/var/www', '-c', '/etc/nginx/nginx.conf') wsgi = os.environ.get('WSGI_APPLICATION', 'app') if ...
5,314,602
def def_grad_surf(surf, u, v): """" Compute deformation gradient via a NURBS surface interpolation of control point displacement at u, v parametric coordinates :param surf: NURBS surface interpolating control point displacements :type surf: NURBS surface object :param u: u parametric location ...
5,314,603
def _load_sql_containers(neo4j_session: neo4j.Session, containers: List[Dict], update_tag: int) -> None: """ Ingest SQL Container details into neo4j. """ ingest_containers = """ UNWIND {sql_containers_list} AS container MERGE (c:AzureCosmosDBSqlContainer{id: container.id}) ON CREATE SET c.fi...
5,314,604
def assign(tensor, val): """ Compatibility assignment operation Args: tensor: Tensor, to be assigned value of T2. val: Tensor or python value, which will be assigned to T1. Returns: Assigned Tensor """ if _VERSION == 1: tf.assign(tensor, val) else: ...
5,314,605
async def add_to_send(pool, client_id, message, date=None): """ Write to db messages to send like: {user_id} as hash {date: message}. I know you are cool, but don't think that it will be several messages for 1 milisecond. I can make it like {some_hash} - {user_id: str({date: message})} if u wan...
5,314,606
def get_v3_users_from_v2_user_ids(v2_user_ids): """ Get v3 users with last_login==null and has a matching v2 user id """ from django.contrib.auth import get_user_model return get_user_model().objects\ .filter(last_login__isnull=True)\ .filter(id__in=v2_user_ids)
5,314,607
def filter_intersection(data, hoax_pages, print_results=False): """returns the dataset filtered with only the users who liked at least one post belonging to a hoax page and one post belonging to a non-hoax page print_results: if True, prints the filtering effect output: sparse like_matrix and page/hoax ...
5,314,608
def test_lock_release(long_lock): """A lock should get released""" # Releasing a lock before it's acquired should do nothing long_lock.release() assert long_lock.acquired is False assert long_lock.is_still_locked() is False assert long_lock.acquire() is True assert long_lock.acquired is Tru...
5,314,609
def get_path_up_down(path_source, path_target): """paths for up/down NOTE: both lists always show the LOWER level element even for the so for path up, it shows the source, for path down the target! Args: path_source(list) path_target(list) """ # find common part of pat...
5,314,610
def destroy_method_test_environment(case): """ Clean up a TestCase where create_method_test_environment has been called. """ clean_up_all_files() shutil.rmtree(case.scratch_dir) CodeResource.objects.all().delete()
5,314,611
def hsitogramEqualize(imgOrig: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray): """ Equalizes the histogram of an image :param imgOrig: Original Histogram :return """ num_of_pixels = imgOrig.shape[0] * imgOrig.shape[1] if len(imgOrig.shape) == 2: norm_255 = normalize_image(imgOri...
5,314,612
def more(fs: FileSystem, name: str): """ 展示文件 :param fs: :param name: :return: """ if name and name == '-h': print(""" 显示文本内容 more file_name 不可跨目录层级调用 完全显示文本内容 """) return pwd_cat = fs.load_pwd_obj() # 当前目录 flag =...
5,314,613
def topic_arn(): """ Get the SNS topic ARN from environment variable :return: The SNS topic ARN """ return os.environ["SNS_TOPIC_ARN"]
5,314,614
def findCentroid(points): """ Compute the centroid for the vectors of a group of Active Site instance Input: n ActiveSite instances Output: the centroid vector """ centroid = [0.0,0.0,0.0] for item in points: centroid = [centroid[0]+item.vector[0],centroid[1]+item.vector[1],centroid[...
5,314,615
def _transform_id(conn_str, model_version, site, target_schema, target_table, id_name, force=False): """Run transformations. TODO: Check whether exception handling is consistent e.g. DatabaseError. :param str conn_str: pq connection string :param str model_version: pedsnet model version :param str...
5,314,616
def setup_view(f): """Decorator for setup views.""" def new_function(*args, **kwargs): request = args[0] if not settings.DEBUG: raise Http404("Site is not in DEBUG mode.") if request.kbsite and request.kbsite.is_setup: raise Http404("Site is already setup, wizard...
5,314,617
def weth_instance(web3_eth): # pylint: disable=redefined-outer-name """Get an instance of the WrapperEther contract.""" return web3_eth.contract( address=to_checksum_address( NETWORK_TO_ADDRESSES[NetworkId.GANACHE].ether_token ), abi=abi_by_name("WETH9"), )
5,314,618
def get_editops_stats(alignment, gap_char): """Get stats for character level edit operations that need to be done to transform the source string to the target string. Inputs must not be empty and must be the result of calling the runing the align function. Args: alignment (tuple(str, str)): the...
5,314,619
def test_address__DeletePostalAddressForm__2(person_data, browser): """`DeletePostalAddressForm` can be canceled.""" browser.login('editor') browser.open(browser.PERSON_DELETE_ENTRY_URL) browser.getControl('RST-Software').click() browser.getControl('Delete entry').click() browser.getControl('No,...
5,314,620
def conv(inputs, out_filters, ksize=(3, 3), strides=(1, 1), dilation=(1, 1), use_bias=True): """ Convolution layer Parameters ---------- inputs: Input tensor out_filters: Number of output filters ksize: Kernel size. One integer of tuple of two integers strides: Strides for movi...
5,314,621
def is_active(host, port): """Check if server is active. Send HTTP GET for a fake /style.css which server will respond to if it's alive. Args: host: server ip address port: server port Returns: Boolean for server state. """ try: url = 'http://{}:{}/style.c...
5,314,622
def norm_lrelu_conv(feat_in, feat_out): """InstanceNorm3D + LeakyReLU + Conv3D block""" return nn.Sequential( nn.InstanceNorm3d(feat_in), nn.LeakyReLU(), nn.Conv3d(feat_in, feat_out, kernel_size=3, stride=1, padding=1, bias=False) )
5,314,623
def test_field_zip(sdc_builder, sdc_executor): """Test field zip processor. The pipeline would look like: dev_raw_data_source >> field_zip >> trash With given config, /basics and /additional will zip to /all path. For e.g., /all will have be a list of 2 zipped maps of {id: 23, inventory:80}, {colo...
5,314,624
def dataframe_divisions( request: Request, reader=Depends(reader), format: Optional[str] = None, serialization_registry=Depends(get_serialization_registry), ): """ Fetch the Apache Arrow serialization of the index values at the partition edges. """ request.state.endpoint = "data" if ...
5,314,625
def get_key_volumes( svm_name: str, volume_name: str, cluster: str, headers_inc: str): """ get volume keys""" print() url = "https://{}/api/storage/volumes?name={}&svm.name={}".format( cluster, volume_name, svm_name) try: response = requests.get(url, heade...
5,314,626
def get_integer_array(obj,name): """ Retrieves the value of a resource that uses a one-dimensional integer array. iarr = Ngl.get_integer_array(plotid, resource_name) plotid -- The identifier returned from Ngl.open_wks, or any PyNGL function that returns a PlotId. resource_name -- The name of the resource...
5,314,627
def assert_allclose(actual: numpy.ndarray, desired: int, atol: float): """ usage.scipy: 68 usage.skimage: 15 usage.sklearn: 2 usage.statsmodels: 12 """ ...
5,314,628
def generate_series(Model, size, epsi, densRange, stepWidth, init, alpha, it_step, chp, saveSpec=None, consecutive=False): """ A series of canonical (fixed average density) systems is generated in a rage of densities. They are created, iterated and saved consecutively. Parameters ----------...
5,314,629
def test(model, dataloader, use_cuda, criterion, full_return=False, log_path=None): """ Computes the balanced accuracy of the model :param model: the network (subclass of nn.Module) :param dataloader: a DataLoader wrapping a dataset :param use_cuda: if True a gpu is used :param full_return: if ...
5,314,630
def EvalCode(code_str, parse_ctx, comp_lookup=None, mem=None, aliases=None): """ Unit tests can evaluate code strings and then use the resulting CommandEvaluator. """ arena = parse_ctx.arena comp_lookup = comp_lookup or completion.Lookup() mem = mem or state.Mem('', [], arena, []) parse_opts, exec_opts...
5,314,631
def read_forces(fname): """Read .forces file format from Cortex MAC. The .forces file in ASCII contains force plate data. The data is saved based on the forcepla.cal file of the trial and converts the raw force plate data into calibrated forces. The units used are Newtons and Newton-meters an...
5,314,632
def mpw_plot_points(slope, years, values): """ Calculate start and end points for line describing MPW best fit :param float slope: line slope :param float array years: x-coordinates :param float array values: y-coordinates :returns: [[x1,x2], [y1,y1]] """ mu_x = np.ma.mean(years) ...
5,314,633
def set_max_perms(user, max_group_list, service_account_flag=False): """ Convert the user group lists present on MAX into a list of UserAffiliations and/or website_admin status. Permissions are encoded as a comma-separated list of: {parent-group}-CGAC_{cgac-code}-PERM_{one-of-R-W-S-F} {pare...
5,314,634
def get_target(module, array): """Return Pod or None""" try: return array.get_pod(module.params['target']) except Exception: return None
5,314,635
def mkdir_p(path): """same as mkdir -p command""" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
5,314,636
def print_stats(unique_emoji, counts): """ Prints the top 3 unique and often used emojis per user. Parameters: ----------- unique_emoji : dictionary of Counters Indicating which emojis are unique to which user counts : dictionary of Counters Indicating which emojis are ofte...
5,314,637
def int_kinenergy(basis): """Calculates the kinenergy matrix for a given basis. Parameters ---------- basis : BasisSet Returns ------- kinenergy : np.ndarray Kinetic energy matrix with shape M x M, where `M = len(basis)`. """ M = len(basis) kinenergy = np.zeros((M, M)) ...
5,314,638
def test_waders(): """Test module waders.py by downloading waders.csv and testing shape of extracted data has 15 rows and 19 columns """ test_path = tempfile.mkdtemp() x_train, metadata = waders(test_path) try: assert x_train.shape == (15, 19) except: shutil.rmtree(test_path) raise()
5,314,639
def test_ospfv3_redistribution_tc6_p0(request): """Test OSPF inter area route calculations.""" tc_name = request.node.name write_test_header(tc_name) tgen = get_topogen() # Don't run this test if we have any failure. if tgen.routers_have_failure(): pytest.skip(tgen.errors) global t...
5,314,640
def bumpversion(ctx, version): """Bump the version. If no version is specified, show the current version.""" version = version.lstrip("v") # Check that we're not missing any libraries for x in ("setuptools", "twine"): try: importlib.import_module(x) except ImportError: ...
5,314,641
def test_commit_in_last_year_yes(monkeypatch): """ 11. Has there been a commit in the last year? """ headers = {} def mock_get(*args, **kwargs): return MockResponseCommitsYes() today = datetime.now() test_date = datetime.strptime(GOOD_DATE_Z, "%Y-%m-%dT%H:%M:%SZ") days = (today...
5,314,642
def all_columns_functional(use_cache = True, update_cache = True): """ Returns all functional categories identified in the data set. """ return get_columns('pathabundance_columns.pickle', 'pathabundance_relab', use_cache, update_cache)
5,314,643
def json_replace(json_obj, **values): """ Search for elements of `{"{{REPLACE_PARAM}}": "some_key"}` and replace with the result of `values["some_key"]`. """ if type(json_obj) is list: return [json_replace(x, **values) for x in json_obj] elif type(json_obj) is dict: new = {} ...
5,314,644
def slit_scan_area_comp(slits, yag, x_width=1.0,y_width=1.0,samples=1): """Find the ratio of real space/pixel in the PIM 1. Send slits to specified position 2. Measure pixel dimensions of passed light. The idea is that the width, height values will be pulled from the PIMPulnixDetector inst...
5,314,645
def diff(f, *x, allowed_nonsmoothness="discontinuous"): """ A differentiator which computes :math:`\\partial f / \\partial x` and understands :class:`Field`\\ s. If ``x`` is one of ``t``, ``x``, ``y``, or ``z`` and ``f`` is a :class:`DynamicField`, the corresponding derivative :class:`Field` is retu...
5,314,646
def append_store_prices(ticker_list, loc, start = '01/01/1990'): """ Given an existing store located at ``loc``, check to make sure the tickers in ``ticker_list`` are not already in the data set, and then insert the tickers into the store. :ARGS: ticker_list: :class:`list` of tickers to ad...
5,314,647
def in_filepath_list(class_paths): """ Print in Filepath list format. """ source, not_founds = genuuml.in_filepath_list(class_paths) _print_not_founds(not_founds) click.echo(source)
5,314,648
def trace_for_kbps(kbps: int) -> List[int]: """ Returns Mahimahi trace lines whose average kbps approximates the passed in value """ # - convert kbps to a Fraction representing # packets per line of a Mahimahi trace file # - Fraction will also simplify the ratio, giving us exactly how many lines we need and...
5,314,649
def barotropic_input_qref_to_compute_lwa(ylat,qref,vort,area,dmu,planet_radius = 6.378e+6): # used to be Eqlat_LWA """ This function computes LWA based on a *prescribed* Qref instead of Qref obtained from the vorticity field on a barotropic sphere. Parameters ---------- ylat : sequence or array_lik...
5,314,650
def merge_models(old, new): """docstring for merge_model""" if old.rowCount() == 0: return new if new.rowCount() == 0: return old old_crcs = [(old.item(row, COLUMN_CRC).text(), row) for row in xrange(old.rowCount())] new_crcs = [(new.item(row, COLUMN_CRC).text(), row) f...
5,314,651
def get_operator_norm(*ops): """ Computes the l2-operator norm of a product of linear operators. """ if all([hasattr(op, "get_matrix") for op in ops]): mat = ops[-1].get_matrix() for op in ops[:-1][::-1]: mat = torch.matmul(op.get_matrix(), mat) return np.linalg.norm(mat.cpu(...
5,314,652
def add_deqatn(se, deqatn): """Add a DEQATN entry to the SE and the optmodel Parameters ---------- deqatn : :class:`DEQATN` The equation to be added. """ se.deqatns.append(deqatn) se.model.optmodel.deqatns[deqatn.id] = deqatn
5,314,653
def fileexistspolicy( overwrite_if_exists: bool, skip_if_file_exists: bool ) -> FileExistsPolicy: """Return the policy for overwriting existing files.""" return ( FileExistsPolicy.RAISE if not overwrite_if_exists else FileExistsPolicy.SKIP if skip_if_file_exists else ...
5,314,654
def createDummy(name, type): """ Create a dummy entry to the SSRQ Person db. :param name: :param type: :return link_id (string): """ try: print("Requesting dummy id for " + name) if type == "person": r = requests.get("https://www.ssrq-sds-fds.ch/persons-db-api/?cr...
5,314,655
def generate(fin, fout): """ Search first author last name, year, and first meaningful word in title. Assemble Google-Scholar-style keys (lastname+year+titlefirstword). Replace original keys ``RN+number" with new keys. Also adds letter suffixes to repeated keys (e.g. peter1998researcha, peter1...
5,314,656
def get_pattern_x( slot: int, pat_num: int, ) -> int: """ get pattern information x - time (line number) """
5,314,657
def connect_routes(dispatcher): """This function takes the dispatcher and attaches the routes. :param dispatcher: The CherryPy dispatcher. """ # controller instances map controllers = { 'root': Root(), 'calculations': Calculations(), 'datasets': Datasets(), 'version'...
5,314,658
def fbeta_score( outputs: torch.Tensor, targets: torch.Tensor, beta: float = 1.0, eps: float = 1e-7, argmax_dim: int = -1, num_classes: Optional[int] = None, ) -> Union[float, torch.Tensor]: """ Counts fbeta score for given ``outputs`` and ``targets``. Args: outputs: A list ...
5,314,659
def set_bot_next_process_time(bot_id, new_time): """Set the next processing time for the specified bot.""" logger.debug( f"Next processing for bot {bot_id} not before " f"{unix_timestamp_to_string(new_time, '%Y-%m-%d %H:%M:%S')}." ) db.execute( f"REPLACE INTO bots (botid, next_...
5,314,660
def test_Image_from_landsat_c1_toa_et_fraction(): """Test if ETf can be built for a Landsat SR image""" image_id = 'LANDSAT/LC08/C01/T1_TOA/LC08_044033_20170716' output = utils.getinfo(ssebop.Image.from_landsat_c1_toa( image_id).et_fraction) assert output['properties']['system:index'] == image_i...
5,314,661
def gc_blocks(seq,block_size): """ Divide sequence into non-overlapping blocks and compute GC content of each block.""" blocks = [] for i in range(0, len(seq) - (len(seq) % block_size), block_size): blocks.append(gc_content(seq[i:i+block_size])) return tuple(blocks)
5,314,662
def copystat(src, dst): """Copy stat bits from src to dst This should be used when shutil.copystat would be used on directories on win32 because win32 does not support utime() for directories. According to the official docs written by Microsoft, it returns ENOACCES if the supplied filename is a di...
5,314,663
def test_from_file_fail_file_not_found(): """ Test the TabularFile.from_file() for nonexistant files. """ with pytest.raises(FileNotFoundError): thresh.TabularFile.from_file("c75fc775d1439c3f3d9212d5c813b594.txt")
5,314,664
def test_user_fps(): """ Test User specified fps """ q_vid = QVideo(frames_per=30) assert q_vid.fps == 30 q_vid.fps = 24 assert q_vid.fps == 24
5,314,665
def is_android(filename): """ check if the files is an apk file or not """ with open(filename, "rb") as f: # AndroidManifest.xml if b"AndroidManifest.xml" in f.read(4096): return True return False
5,314,666
def enrich(alert, rules): """Determine if an alert meets an enrichment rule :param alert: The alert to test :param rules: An array of enrichment rules to test against :returns: Alert - The enriched Alert object """ for enrichment in rules: updates = enrichment(alert) if not upda...
5,314,667
def set_stencil_op(sfail='keep', dpfail='keep', dppass='keep', face='front_and_back'): """Set front or back stencil test actions Parameters ---------- sfail : str Action to take when the stencil fails. Must be one of 'keep', 'zero', 'replace', 'incr', 'incr_wrap', ...
5,314,668
def test_filters(site, client): """Test hostname/attribute filters for Devices.""" # URIs attr_uri = site.list_uri('attribute') dev_uri = site.list_uri('device') # Pre-load the Attributes client.post(attr_uri, data=load('attributes.json')) # Populate the Device objects dev_resp = clien...
5,314,669
def max_ea(): """ Return the highest mapped address of the IDB. Wrapper on :meth:`BipIdb.max_ea`. """ return BipIdb.max_ea()
5,314,670
def desikan_killiany_tourville_labeling(t1, do_preprocessing=True, antsxnet_cache_directory=None, verbose=False): """ Cortical and deep gray matter labeling using Desikan-Killiany-Tourville ...
5,314,671
def empty(document, selection, selectmode=''): """Reduce the selection to a single uppermost empty interval.""" beg = selection[0][0] return Selection(Interval(beg, beg))
5,314,672
def re(rm,rf,beta): """Returns cost of equity using CAPM formula.""" return rf + beta*(rm-rf)
5,314,673
def find_path(matrix, start_x, start_y, end_x, end_y, tile_size, map_height): """ Creates a path from a matrix of barriers, a start position, a desired end position, the size of tiles used in a map, and the map's height (in tiles). """ # TODO: Get map height from matrix instead of it being a pa...
5,314,674
def test_rpm_build_environment(): """Sanity checks of the RPM test environment.""" assert int(os.environ['PYMAJORVERSION']) == sys.version_info[0]
5,314,675
def _kwargs_to_bond_parameters(bond_type: Array, kwargs: Dict[str, Array]) -> Dict[str, Array]: """Extract parameters from keyword arguments.""" # NOTE(schsam): We could pull out the species case from the generic case. for k, v in kwargs.items(): if bond_type is not None: ...
5,314,676
def wait_for_result(func, *args, matcher=simple_matcher(True), attempts=20, interval=5, decode=decode_wrapper): """Runs `func` with `args` until `matcher(out)` returns true or timesout Returns the matching result, or raises an exception. """ for i in range(attempts): out = ...
5,314,677
def host_is_trusted(hostname: str, trusted_list: t.Iterable[str]) -> bool: """Check if a host matches a list of trusted names. :param hostname: The name to check. :param trusted_list: A list of valid names to match. If a name starts with a dot it will match all subdomains. .. versionadded:: 0....
5,314,678
def average_data(flow_fields: Sequence[GmxFlow]) -> GmxFlow: """Average a given list of flow fields. The flow fields must be of identical shape and be regular. It is further assumed that they have the same origin and bin spacing, and that the bins have the same index ordering. If the input list is...
5,314,679
def identify_background_video_folder(parent_folder: typing.Union[str, bytes, os.PathLike], fname: str, fname_format: str, optional_settings: dict = {}) -> typing.Tuple[bool,str]: """ Identifies a background folder that matches a given experimental fname. Identifies a background folder tagged with appropria...
5,314,680
def user_dashboard_request_view(request, **kwargs): """User dashboard request details view.""" avatar = current_user_resources.users_service.links_item_tpl.expand( current_user )["avatar"] request_type = request["type"] is_draft_submission = request_type == CommunitySubmission.type_id ...
5,314,681
def _load_discrim_net(path: str, venv: VecEnv) -> common.RewardFn: """Load test reward output from discriminator.""" del venv # Unused. discriminator = th.load(path) # TODO(gleave): expose train reward as well? (hard due to action probs?) return discriminator.predict_reward_test
5,314,682
def handle_workshop(data: List[Dict[str, str]]): """ Iterates over all provided poster items and checks the http.StatusOK for every valid url item. :param data: list containing workshop dictionary items. """ print("Processing workshop item links ...") fails = "" for idx, item in enumerat...
5,314,683
def _is_generator_like(data): """Checks if data is a generator, Sequence, or Iterator.""" return (hasattr(data, 'next') or hasattr(data, '__next__') or isinstance( data, (Sequence, iterator_ops.Iterator, iterator_ops.IteratorV2)))
5,314,684
def check_tcp_port(host, port, timeout=3): """ Try connecting to a given TCP port. :param host: Host to connect to :param port: TCP port to connect to :param timeout: Connection timeout, in seconds :return: True if the port is open, False otherwise. """ s = socket.socket() try: ...
5,314,685
def create_logger(logger=None, loglevel=DEFAULT_LOGLEVEL): """ Attaches or creates a new logger and creates console handlers if not present """ logger = logger or logging.getLogger('{0}.SSHTunnelForwarder'. \ format(__name__)) if not logger.handlers: # if n...
5,314,686
def dump(fpath, *adj_lists, mode="w"): """Convert Hobgoblin elements to GraphSON""" with open(fpath, mode) as f: for adj_list in adj_lists: dumped = dumps(adj_list) f.write(dumped + '\n')
5,314,687
def psi_from(grid, axis_ratio, core_radius): """ Returns the $\Psi$ term in expressions for the calculation of the deflection of an elliptical isothermal mass distribution. This is used in the `Isothermal` and `Chameleon` `MassProfile`'s. The expression for Psi is: $\Psi = \sqrt(q^2(s^2 + x...
5,314,688
def plot_history(H, epochs): """ Utility function for plotting model history using matplotlib H: model history epochs: number of epochs for which the model was trained """ plt.style.use("fivethirtyeight") plt.figure() plt.plot(np.arange(0, epochs), H.history["loss"], label="train_l...
5,314,689
def create_station_dataframe(): """Creates a pandas dataframe from the csv list of all stations downloaded from the uhrqds. """ files = get_station_files() combinedlst = "" for item in files: for line in item.read().decode().splitlines(): try: #Try to convert ...
5,314,690
def _get_value_from_value_pb(value_pb): """Given a protobuf for a Value, get the correct value. The Cloud Datastore Protobuf API returns a Property Protobuf which has one value set and the rest blank. This function retrieves the the one value provided. Some work is done to coerce the return value...
5,314,691
def load_audio(path): """Load audio data, mp3 or wav format Parameters ---------- path : str audio file path. Returns: ------- data : array-like Audio data. fs : int Sampling frequency in Hz. """ if path[-4:] == ".w...
5,314,692
def export_rule_data(variables, actions): """ export_rule_data is used to export all information about the variables, actions, and operators to the client. This will return a dictionary with three keys: - variables: a list of all available variables along with their label, type and options - actions...
5,314,693
def produce_nm_phase_locked_sig(sig, phase_lag, n, m, wn_base, sfreq, nonsin_mode=2, kappa=None): """ :param sig: :param phase_lag: :param n: :param m: :param wn_base: :param sfreq: :param kappa: if None, the signals are completely locked to each other :return: "...
5,314,694
def test_default(): """ Test if it returns or sets the currently defined default python. """ mock_opt = MagicMock(return_value="salt stack") mock_cmd = MagicMock(return_value=True) mock_all = MagicMock( return_value={"retcode": True, "stdout": "salt", "stderr": "error"} ) with pa...
5,314,695
def patch_schedule_and_run(): """ Patches ``luigi.interface._schedule_and_run`` to invoke all callbacks registered via :py:func:`before_run` right before luigi starts running scheduled tasks. This is achieved by patching ``luigi.worker.Worker.run`` within the scope of ``luigi.interface._schedule_and_run...
5,314,696
def randonness_test(ts, lag=None): """ 样本的随机性检验; :param ts: :return: """ # The Run Test """ H0: the sequence was produced in a random manner """ ts = ts.dropna() statistic, pval = runstest_1samp(ts, correction=False) print(" The Run Test Result \n" "=======...
5,314,697
def test_mp_config_file_validate(): """Test validate.""" mpc_file = MpConfigFile() mpc_file.validate_settings() check.is_in(mpc_file.txt_viewer, mpc_file.viewer.children) check.is_true(len(mpc_file.txt_viewer.value) > 0)
5,314,698
def main(argv=None): """Apply FixMergePyi to a source file without using the 2to3 main program. This is necessary so we can have our own options. Args: argv: Flags and files to process. """ if argv is None: argv = sys.argv args = parse_args(argv) # Log levels range from 10 (DEBUG) to 50 (CRITI...
5,314,699