content
stringlengths
22
815k
id
int64
0
4.91M
def szepes_ml(local_d): """maximum likelihood estimator from local FSA estimates (for k=1) :param numpy.ndarray of float local_d: local FSA estimates :return: global ML-FSA estimate """ return hmean(local_d) / np.log(2)
5,322,200
def find_aapt(): """Find the aapt (Android Asset Packaging Tool). Returns: Path to aapt if successful, empty string otherwise. """ # NOTE: This is far from perfect since this will pick up the first instance # of aapt installed and not necessarily the newest version. # Use the path to the "android" SDK ...
5,322,201
def create_low_latency_conv_model(fingerprint_input, model_settings, is_training): """Builds a convolutional model with low compute requirements. This is roughly the network labeled as 'cnn-one-fstride4' in the 'Convolutional Neural Networks for Small-footprint Keyword Spotting'...
5,322,202
def sampling_from_enum_with_dirichlet_lm(enum_pool_dict_all, df_log2prob_by_syl, orig_seg_syl_df, lm_orig_dict, scale_num = 1000): """ get a sample lexicon with a orig language model params: @enum_pool_dict_all: enumerated words of all syllable lengths (filtered to make sure that all words are ...
5,322,203
def action_store(raw_val): """Auto type convert the value, if possible.""" if raw_val not in EMPTY_VALUES: return auto_type_convert(raw_val) else: return raw_val
5,322,204
def test_register_get_no_login(app): """ tests going to register with no login - user should be prompted to register """ rv = app.test_client().get('/register') assert rv.status_code == 200 assert b'Register' in rv.data
5,322,205
def test_grammar_attribute_same_for_none_or_file_grammar(): """Check that the grammar attribute of ChunkParser is the same if using None or FILE_GRAMMAR as the input.""" assert ChunkParser().grammar == ChunkParser(FIlE_GRAMMAR).grammar
5,322,206
def haversine_distance(coordinate: Point) -> float: """ Obtain the haversine distance between two cordinates points in the map :param coordinate: shapely.geometry.point :return: haversine distance in km: """ # MKAD coordinate lat1, lon1 = 55.755826, 37.6173 # address coordi...
5,322,207
def route_home(): """ Renders the default page of the webserver, the leaderboard display""" return render_template("home.html", data=leaderboard_manager.get_sorted_data())
5,322,208
def parseSlackMessage(slack_rtm_output, IDToUser): """ The Slack Real Time Messaging API is an events firehose. this parsing function returns None unless a message is directed at the Bot, based on its ID. """ output_list = slack_rtm_output if output_list and len(output_list) > 0:...
5,322,209
def get_org_details(organization_id): """ Return the details for an organization CLI Example: .. code-block:: bash salt-run digicert.get_org_details 34 Returns a dictionary with the org details, or with 'error' and 'status' keys. """ qdata = salt.utils.http.query( "{}/or...
5,322,210
def updatelimit(): """Update sensorlimits.""" script_root() print(request.form['id']) print(request.form['value']) #limit = SensorLimit.query.filter_by(id=request.form['id']).first() #print(request.form['id']) #print(limit) #limit.value = request.form['value'] #db.session.commit(...
5,322,211
def test_tfrecord_to_mindrecord_with_special_field_name(): """test transform tfrecord to mindrecord.""" if not tf or tf.__version__ < SupportedTensorFlowVersion: # skip the test logger.warning("Module tensorflow is not found or version wrong, \ please use pip install it / reinstall v...
5,322,212
async def test_sign_endorse_recursive(image_config: ImageConfig): """Test interlaced signatures and endorsements.""" # Stack representation of a ternary tree stack = [{"name": "?-Unsigned", "image_config": image_config.clone()}] LOGGER.debug("Unsigned Canonical Digest: %s", image_config.get_digest_cano...
5,322,213
def trip_from_staging(conn, service, id_type = 'NUMERIC'): """Calculates the voronoi polygons for every active station in CitiBike and BayWheels Parameters ---------- conn: psycopg2.extensions.connection The connection to the database service: str The bike station ser...
5,322,214
def acquire_multid(z_range): """ micro-manager data acquisition. Creates acquisition events for z-stack. This example: use multi_d_acquisition because the z-stage is run from micro-manager. Unless hardware triggering is set up in micro-manager, this will be fairly slow: micro-manage...
5,322,215
def destroy_cluster( cluster_id: str, enable_spinner: bool, aws_region: str, ) -> None: """ Destroy a cluster. Args: cluster_id: The ID of the cluster. enable_spinner: Whether to enable the spinner animation. aws_region: The region the cluster is in. """ with Hal...
5,322,216
def six_plot(ts, *plotargs, **plotkwds): """ Output a matplotlib figure with full spectra, absorbance, area and stripchart. Figure should be plotly convertable through py.iplot_mpl(fig) assuming one is signed in to plotly through py.sign_in(user, apikey). Parameters ----------- title : st...
5,322,217
def woodbury_solve(vector, low_rank_mat, woodbury_factor, shift): """ Solves the system of equations: :math:`(sigma*I + VV')x = b` Using the Woodbury formula. Input: - vector (size n) - right hand side vector b to solve with. - woodbury_factor (k x n) - The result of calling woodbury_fa...
5,322,218
def _validator_not_empty(instance, attribute, value): """ Attr validator to validate that a list is not empty: """ if len(value) == 0: raise ValueError("{name} must not be empty".format(name=attribute.name))
5,322,219
def create_callbacks(model, data, ARGS): """At the end of each epoch, determine various callback statistics (e.g. ROC-AUC) :param model: Keras model :type model: :class:`tensorflow.keras.Model` :param data: Validation data - data sequences (codes, visits, numeric values) and classifier. :type data:...
5,322,220
def nxlog_callback(ch, method, properties, body): """ Callback on consumed message :param ch: consuming channel :param method: :param properties: :param body: message from queue :return: """ def nx_formatter(event: dict) -> Dict: """ Форматирование nx'овой обвязки ...
5,322,221
def test_get_trackers_command_main_success(mocker, client): """ When "pt-get-trackers" command executes the get_trackers_command function should be called from main. """ import PassiveTotal_v2 mocker.patch.object(demisto, 'command', return_value='pt-get-trackers') mocker.patch.object(Passiv...
5,322,222
async def async_setup_entry(hass: core.HomeAssistant, config_entry: ConfigEntry, async_add_devices): """Add each light based on the passed data""" controller = hass.data[DOMAIN][config_entry.entry_id][CONTROLLER] options = fixDict(config_entry.options) _LOGGER.critical("Options: " + str(options)) f...
5,322,223
def get_user_by_email(email, create_pending=False): """finds a user based on his email address. :param email: The email address of the user. :param create_pending: If True, this function searches for external users and creates a new pending User in case ...
5,322,224
def test_pad_diff_types(): """Check if Pad can handle the case were a different type is passed to constant_value than the type of the data""" args = { "data": np.zeros((1, 48, 32, 32), dtype=np.float32), "pads": np.array([0, 0, 0, 0, 0, 0, 1, 1], dtype=np.int64), "constant_value": 1.5, ...
5,322,225
def test_PropagateHandler_add_handle(loguru_logger: Logger): """Ensure PropgateHandler add_handle works.""" assert len(PropagateHandler._handler_reference.values()) <= 0 assert PropagateHandler.add_handle(loguru_logger) try: assert len(PropagateHandler._handler_reference.values()) == 1 fin...
5,322,226
def import_subscription_items( ctx: Context, api_key: str, curing_window_days: int = 90 ) -> Iterator[Records[StripeSubscriptionItemRaw]]: """ # TODO: repeated code """ latest_full_import_at = ctx.get_state_value("latest_full_import_at") latest_full_import_at = ensure_datetime(latest_full_import...
5,322,227
def get_offset_from_var(var): """ Helper for get_variable_sizes)_ Use this to calculate var offset. e.g. var_90, __saved_edi --> 144, -1 """ instance = False i=0 # Parse string i = var.rfind(' ')+1 tmp = var[i:-1] # Parse var if tmp[0] == 'v': tmp = tmp[4:]...
5,322,228
def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score): """ Takes as input a set of characters alphabet and three scores diag_score, off_diag_score, and dash_score. The function returns a dictionary of dictionaries whose entries are indexed by pairs of characters in alphabet plus '-'...
5,322,229
def _foldl_jax(fn, elems, initializer=None, parallel_iterations=10, # pylint: disable=unused-argument back_prop=True, swap_memory=False, name=None): # pylint: disable=unused-argument """tf.foldl, in JAX.""" if initializer is None: initializer = nest.map_structure(lambda el: el[0], elems) el...
5,322,230
def MAD(a, c=0.6745, axis=None): """ Median Absolute Deviation along given axis of an array: median(abs(a - median(a))) / c c = 0.6745 is the constant to convert from MAD to std; it is used by default """ a = ma.masked_where(a!=a, a) if a.ndim == 1: d = ma.median(a) m...
5,322,231
def plot_prediction( y_pred: np.ndarray, y_test: np.ndarray, ax: plt.Axes = None, scores: str = None, name: str = None, ) -> None: """Plot prediction vs truth Args: y_pred: Predicted values y_test: Ground truth ax: Axes scores: String with scores to show as p...
5,322,232
def checkout(branch_name, new_branch): """Switch branches. Use -b to create and switch to new branch.""" settings = _load_settings() status = _load_settings(".TDB", check=[]) settings.update(status) client, _ = _connect(settings) if new_branch: client.create_branch(branch_name) all_b...
5,322,233
def save_browser_tree_state(): """Save the browser tree state.""" data = request.form if request.form else request.data.decode('utf-8') old_data = get_setting('browser_tree_state') if old_data and old_data != 'null': if data: data = json.loads(data) old_data = json.loads(ol...
5,322,234
def prompt_yes_no(msg, default=False): """Prints the given message and continually prompts the user until they answer yes or no. Returns true if the answer was yes, false otherwise.""" default_str = "no" if default: default_str = "yes" result = prompt_w_default(msg, default_str, "^(Yes|yes|...
5,322,235
def test_position_short_min_interval(): """测试T0逻辑""" pos_short = PositionShort(symbol="000001.XSHG", T0=False, short_min_interval=3600*72) pos_short.update(dt=pd.to_datetime('2021-01-01'), op=Operate.HO, price=100, bid=0) assert not pos_short.pos_changed and pos_short.pos == 0 pos_short.update(dt=...
5,322,236
def save_pressure_coordinate_field(ds, var, model='NorESM'): """ Saves the pressure coordinate field to standardized file. :param ds: :param var: :param model: :return: """ # path_savePressCoord = default_save_pressure_coordinates): # test for pres...
5,322,237
def persistence_distance( x: np.ndarray, y: np.ndarray, dimension: int=0, persistence_feature: str="persistence_landscape" ) -> float: """Distances are euclidean on persistence features. Args: x: First datset. y: Second dataset. dimension: Dimension for persistence diagr...
5,322,238
def get_user_pysit_path(): """ Returns the full path to the users .pysit directory and creates it if it does not exist.""" path = os.path.join(os.path.expanduser('~'), '.pysit') if not os.path.isdir(path): os.mkdir(path) return path
5,322,239
def plot_pit_qq(pdf_ens, ztrue, qbins=101, title=None, code=None, show_pit=True, show_qq=True, pit_out_rate=None, outdir="", savefig=False) -> str: """Quantile-quantile plot Ancillary function to be used by class Metrics. Parameters ---------- pit: `PIT` object ...
5,322,240
def rel_mole_weight(ion, ion_num, oxy_num): """ Calculating Relative Molecular Weight :param ion: Each cation :param ion_num: Number of cations per cation :param oxy_num: The number of oxygen atoms corresponding to each cation :return: Relative molecular weight """ ion_dict = {'Si':28.0...
5,322,241
def get_admin_token(chat_id): """ Get a administrador chat_id """ session = Session() admin = session.query(Admin).\ filter_by( chat_id=chat_id).first() session.close() if admin: return admin.token else: return None
5,322,242
def _get_vocab(name: str): """Retrieve model configuration. Arguments: ---------- name {str} -- Name of the model. Raises: ------- FileNotFoundError: No vocab file provided with model. ValueError: Bad name or unavailable model. Returns: -------- np.ndarray ...
5,322,243
def game_loop(): """ Loops game alternating players until we reach 10 frames. Result is saved in global state (a side effect). """ players = ['A','B'] choice = choose_player() player_1 = players[choice] player_2 = players[not choice] while state['frame'] < 10: state[playe...
5,322,244
def test_args_template(testapp): """Archive processor has respect 'template' argument.""" stream = archive.process( testapp, [holocron.Item({"title": "The Force", "content": "Obi-Wan"})], template="foobar.txt", ) assert isinstance(stream, collections.abc.Iterable) assert li...
5,322,245
def test_https_flags(monkeypatch): """test getting https flags""" key_loc, cert_loc = utils.get_https_envs() assert key_loc is None and cert_loc is None monkeypatch.setenv("USE_HTTPS", "1") with pytest.raises(exceptions.BadHTTPSEnvs): utils.get_https_envs() cur_dir = os.path.dirname(os...
5,322,246
def filter_directory(directory: str, extension: str = '.py') -> str: """ Delete all files within the given directory with filenames not ending in the given extension """ for root, dirs, files in os.walk(directory): [os.remove(os.path.join(root, fi)) for fi in files if not fi....
5,322,247
def get_batches_for_prefix(gcs_client: storage.Client, prefix_path: str, ignore_subprefix="_config/", ignore_file=SUCCESS_FILENAME) -> List[List[str]]: """ This function creates batches of GCS uris for a given prefix. This pref...
5,322,248
def index_of_coincidence(text): """Index of coincidence of a string. This is low for random text, higher for natural langauge. """ stext = sanitise(text) counts = collections.Counter(stext) denom = len(stext) * (len(text) - 1) / 26 return ( sum(max(counts[l] * counts[l] - 1, 0) for ...
5,322,249
def get_allocations(jm_id:str) -> dict: """ Get Allocations Get project allocations for user currently connected to remote system. Parameters ---------- jm_id : str ID of Job Manager instance. Returns ------ allocations : dictionary Dictionary containing informatio...
5,322,250
def set_real(bytearray_: bytearray, byte_index: int, real) -> bytearray: """Set Real value Notes: Datatype `real` is represented in 4 bytes in the PLC. The packed representation uses the `IEEE 754 binary32`. Args: bytearray_: buffer to write to. byte_index: byte index to st...
5,322,251
def LogNormalAddLoc(builder, loc): """This method is deprecated. Please switch to AddLoc.""" return AddLoc(builder, loc)
5,322,252
def add_to_clusters(cluster, r, start, end, bp_sequence, single_breakpoint): """ Count reads overlapping a cluster. If a read r overlaps a cluster region, but does not show evidence for an insertion it will be counted. Once a read name has been seen it will not be counted again. """ referen...
5,322,253
def newton_raphson(x, y): """ The implementation of the `Newton-Raphson <https://en.wikipedia.org/wiki/Newton%27s_method>`_ optimization procedure. It fits the knee curve :math:`f(x)` to the :math:`y` s of the corresponding :math:`x` s by tweaking the shape parameter :math:`c` from an initial guess....
5,322,254
def _vx_no_BRST_check_massive_pp_zero(nhel, nsvahl): """ Parameters ---------- nhel: tf.Tensor, boson helicity of shape=() nsvahl: tf.Tensor, helicity times particle|anti-particle absolute value of shape=() Returns ------- tf.Tensor, of shape=(None,4) and dty...
5,322,255
def rst2node(data, env): """Converts a reStructuredText into its node""" if not data: return parser = docutils.parsers.rst.Parser() document = docutils.utils.new_document("<>") document.settings = docutils.frontend.OptionParser().get_default_values() document.settings.tab_width = 4 d...
5,322,256
def AddNodeTaintsFlag(parser, for_node_pool=False, hidden=False): """Adds a --node-taints flag to the given parser.""" if for_node_pool: help_text = """\ Applies the given kubernetes taints on all nodes in the new node-pool, which can be used with tolerations for pod scheduling. Example: $ {command} node-poo...
5,322,257
def current_branch(): """ Return the current branch """ return f'{REPO.active_branch}'
5,322,258
def _create_config_txn(pubkey, signing_key, setting_key_value): """Creates an individual sawtooth_config transaction for the given key and value. """ setting_key = setting_key_value[0] setting_value = setting_key_value[1] nonce = str(datetime.datetime.utcnow().timestamp()) proposal = ConfigP...
5,322,259
def round_unit(x, unit): """ 按特定单位量对x取倍率 round_int偏向于工程代码简化,round_unit偏向算法,功能不太一样,所以分组不同 Args: x: 原值 unit: 单位量 Returns: 新值,是unit的整数倍 >>> round_unit(1.2, 0.5) 1.0 >>> round_unit(1.6, 0.5) 1.5 >>> round_unit(7, 5) 5 >>> round_unit(13, 5) 15 """ r...
5,322,260
def test_cancel_friend_request_when_can_cancel_request_cancels_request( client_query, auth_headers, requested_friend, user ): """Should cancel a friend request to the user when a request has been sent by the user.""" variables = {"toFriend": requested_friend.uuid} client_query( CANCEL_FRIEND_RE...
5,322,261
def read(*paths): """Read a text file.""" basedir = os.path.dirname(__file__) full_path = os.path.join(basedir, *paths) contents = io.open(full_path, encoding='utf-8').read().strip() return contents
5,322,262
def centroid_1D(image, xpeak, xhw, debug=False): """ Fine location of the target by calculating the centroid for the region centered on the brightest checkbox. Performs the centroid calculation on the checkbox region calculated using the function checkbox_1D(). Keyword arguments: ...
5,322,263
async def async_get_preference(connection, key: PreferenceKey) -> typing.Union[None, typing.Any]: """ Gets a preference by key. :param key: The preference key, from the `PreferenceKey` enum. :returns: An object with the preferences value, or `None` if unset and no default exists. """ proto = aw...
5,322,264
def switch_def(msg_dict_dict, idx_list, Pin_list): """ :根据客户端发过来的JSON数据,判断IDX值是否包含在字典内,如果包含,根据nvalue的值判断GPIO接口高低。 """ msg_idx = msg_dict_dict["idx"] # 取字典内IDX的值 msg_nvalue = msg_dict_dict["nvalue"] # 取字典内nvalue的值 switch_dict = dict(zip(idx_list, Pin_list)) # 合并IDX与Pin列表为字典 if msg_i...
5,322,265
def index(): """ View function for the index page. """ user: User = current_user return \ "<div>" +\ f"<a href=\"{url_for('auth.logout')}\">Log out</a>" +\ f"<h1>Welcome {str(user)}</h1>" +\ "</div>"
5,322,266
def run(credentials, user, password, task_name): """ Run the algorithm for the given task as participant. :param credentials: json file containing credentials. :type credentials: `str` :param user: user name for authentication as task creator :type user: `str` :param password: password for a...
5,322,267
def wait_for_socket(hostname, port): # TODO: upstream this modified version into flocker (it was copied from # flocker.acceptance.test_api) """ Wait until remote TCP socket is available. :param str hostname: The host where the remote service is running. :return Deferred: Fires when socket is a...
5,322,268
def format_event_pull_request(data: typing.Dict[str, typing.Any]) -> str: """ Format a GitHub pull_request event into a string. """ resp = f"{format_author(data['sender'])} " description = f"{format_issue_or_pr(data['pull_request'])} in {format_repo(data['repository'])}" if data['action'] in ("o...
5,322,269
def project_gdf(gdf, to_crs=None, to_latlong=False): """ lovingly copied from OSMNX <https://github.com/gboeing/osmnx/blob/master/osmnx/projection.py> Project a GeoDataFrame to the UTM zone appropriate for its geometries' centroid. The simple calculation in this function works well for most latitud...
5,322,270
def _HadoopMovePartFile(local_path, file_extension: str): """ Internal function moving the single part file from a hadoop path to the local path Args: local_path: the local path where to export file_extension: the file extension which to search for """ import pathlib import ...
5,322,271
def post_url(url,request_num,log,phase): """ # Desc : Function to send post requests to the server. Type 2 is post requests # also captures the ID that was posted and saves it in a list(employee_idlist) # which is used in the ID list to send requests # Input : Post request URL, Request Numbe...
5,322,272
def test_check_107(): """ METADATA.pb font.style "normal" matches font internals ? """ from fontbakery.constants import MacStyle from fontbakery.specifications.googlefonts import (com_google_fonts_check_107 as check, family_metadata, ...
5,322,273
def submit(file_name, dependencies=None, job=None, args=None, kwds=None): """Submit any file with dependencies. If your batch system does not handle dependencies, then raise a NotImplemented error if dependencies are passed. Parameters ---------- file_name : str Path to an existing fil...
5,322,274
def get_shape(obj): """ Get the shape of a :code:'numpy.ndarray' or of a nested list. Parameters(obj): obj: The object of which to determine the shape. Returns: A tuple describing the shape of the :code:`ndarray` or the nested list or :code:`(1,)`` if obj is not an instance of ...
5,322,275
def help_ui_check_answer(capsys, r_input): """a function to calculate an equation from a combination of four numbers to get 24""" final_result = '' with mock.patch.object(builtins, 'input', lambda _: r_input): g_c.ui_check_answer() out, err = capsys.readouterr() print(e...
5,322,276
def _ExtractSourcePathsAndNormalizeObjectPaths(raw_symbols, source_mapper): """Fills in the |source_path| attribute and normalizes |object_path|.""" if source_mapper: logging.info('Looking up source paths from ninja files') for symbol in raw_symbols: object_path = symbol.object_path if symbol.Is...
5,322,277
def precision_recall(classifier, testfeats): """ computes precision and recall of a classifier """ refsets = collections.defaultdict(set) testsets = collections.defaultdict(set) for i, (feats, label) in enumerate(testfeats): refsets[label].add(i) observed = classifier.classify(feats) ...
5,322,278
def set_power_state_xavier(power_state: XavierPowerState) -> None: """Record the current power state and set power limit using nvpmodel.""" # Set power limit to the specified value if is_xavier_agx(): platform = "xavier_agx" elif is_xavier_nx(): platform = "xavier_nx" else: ...
5,322,279
def as_list(x: Any) -> List[Any]: """Wrap argument into a list if it is not iterable. :param x: a (potential) singleton to wrap in a list. :returns: [x] if x is not iterable and x if it is. """ # don't treat strings as iterables. if isinstance(x, str): return [x] try: _ = it...
5,322,280
def _sort_destinations(destinations): """ Takes a list of destination tuples and returns the same list, sorted in order of the jumps. """ results = [] on_val = 0 for dest in destinations: if len(results) == 0: results.append(dest) else: while on_val <...
5,322,281
def test_create_zone_fails_no_authorization(shared_zone_test_context): """ Test creating a new zone without authorization """ client = shared_zone_test_context.ok_vinyldns_client zone = { "name": str(uuid.uuid4()), "email": "test@test.com", } client.create_zone(zone, sign_re...
5,322,282
def exec(args): """Run a command in one or multiple containers.""" open_log_file(args.workdir) log.debug("Command: exec") topo = Topology.load(args.workdir.joinpath(CONFIG_DATA_FILE)) try: run_in_cntrs(topo, as_selector=args.as_pattern, cmd_template=args.command, user=args.user, ...
5,322,283
def test_all_products_are_shown(client: FlaskClient): """ After all the complicated grouping logic, there should still be one header link for each product. """ html = get_html(client, "/ls7_nbar_scene") # We use a sorted array instead of a Set to detect duplicates too. found_product_names = sor...
5,322,284
def Q8(): """ Return the matroid `Q_8`, represented as circuit closures. The matroid `Q_8` is a 8-element matroid of rank-4. It is a smallest non-representable matroid. See [Oxl2011]_, p. 647. EXAMPLES:: sage: from sage.matroids.advanced import setprint sage: M = matroids.named_ma...
5,322,285
def test_particles_ec032_particles_ec032_v(mode, save_output, output_format): """ TEST :3.9.1 The Particle Schema Component [ check length of element information items ] : The {term} is a model group with minOccurs=2, maxOccurs=4, content=choice (a|b), and the instant XML has (b,a) """ assert_bi...
5,322,286
def remove_url(text): """ Supprime les URLs :param text: texte à transformer :return: texte transformé """ return re.sub(r'http\S+', '', text)
5,322,287
def T_sun(a: float, m2_over_m1: float) -> float: """ T = 2 * pi * sqrt(a^3) / (K * sqrt(1 + m2/m1)) :param a: semi-major axis :type a: float :param m2_over_m1: m2 / m1 :type m2_over_m1: float :return: translation period :rtype: float """ return 2 * np.pi * np.sqrt(a * a * a / m...
5,322,288
def deleteDuplicates(head: ListNode) -> ListNode: """解法:重点已排序""" if not head or not head.next: return head pre, ptr =head, head.next while pre and ptr: if pre.val == ptr.val: pre.next = ptr.next ptr = pre.next else: pre = ptr ptr = ptr.next...
5,322,289
def predict_spectrum(svrs, X_, mask=None, scaler=None): """ predict a single spectrum given a list of svrs & mask Parameters ---------- svrs : list a list of svr objects X_ : ndarray the labels of predicted spectra mask : None | bool array predict the pixels where mask==...
5,322,290
def download(url: str, target_path: str, file_name: str) -> None: """Downloads file to a target folder and a specified filename Args: url (str): URL of the file target_path (str): Target folder for file to be downloaded to file_name (str): Specified filename """ if not os.path.e...
5,322,291
def _type_operand(): """ Parser for argument of a binary type operation. """ return binder_type() | agda_vars()
5,322,292
def kernel(process): """ Get the kernel id from a process """ for arg in process.cmdline(): if arg.endswith('.json') and '/kernel-' in arg: return splitext(basename(arg).replace('kernel-', ''))[0]
5,322,293
def debug_status(status, error) -> str: """Return a debug string for the autoscaler.""" if not status: status = "No cluster status." else: status = status.decode("utf-8") as_dict = json.loads(status) lm_summary = LoadMetricsSummary(**as_dict["load_metrics_report"]) if...
5,322,294
def solve_ciknock( Sigma, tol=1e-5, num_iter=10, ): """ Computes S-matrix used to generate conditional independence knockoffs. Parameters ---------- Sigma : np.ndarray ``(p, p)``-shaped covariance matrix of X tol : float Minimum permissible eigenvalue of 2Sigma - S and S...
5,322,295
def analysis_province_sales(): """ 省份与销量的分布 :return: """ # 引入全局数据 global DF_STANDARD # 1、全国商家数量分布 province_sales = DF_STANDARD['item_loc'].value_counts() province_sales_list = [list(item) for item in province_sales.items()] print(province_sales_list) # 1.1 生成热力图 province...
5,322,296
def make_wave_file(outfile, start=None, end=None, step=None, new_wave=None, ewave=None, air=True): """ Writes RH wave file (in xdr format). All wavelengths should be in nm. Parameters ---------- start: number Starting wavelength. end: number Ending wavelength ...
5,322,297
def main(request): """ Main view. Just shows the status of repos, with open prs, as well as a short list of recent jobs. Input: request: django.http.HttpRequest Return: django.http.HttpResponse based object """ limit = 30 repos, evs_info, default = get_user_repos_info(request...
5,322,298
def is_match(text, full_hashed_value, **options): """ gets a value indicating that given text's hash is identical to given full hashed value. :param str text: text to be hashed. :param str full_hashed_value: full hashed value to compare with. :rtype: bool """ return get_component(HashingP...
5,322,299