content
stringlengths
22
815k
id
int64
0
4.91M
def parsePDB(filename, **kwargs): """Read PDB file. If there exists a beta file read it also. If the file is a `.tar.gz` or `.tar.bz2` file, the file will be treated as PDB bundle file. Any non-PDB file will be read as the chain mapper. If no chain mapper then only 1 PDB file allowed in the tar fil...
5,298,300
def make_fuser(fusion_method: str, feature_size: int, n_modalities: int, **kwargs): """Helper function to instantiate a fuser given a string fusion_method parameter Args: fusion_method (str): One of the supported fusion methods [cat|add|bilinear|attention] feature_size (int): The input modality...
5,298,301
def get_dir_file_listing(data_socket): """ Get file listing of cwd of other host via data socket from host on other end Keyword arguments: data_socket -- socket opened on client-side at data port (socket obj) """ filenames = (data_socket.recv(NUM_CHARS_MSG)).decode('utf-8') should_continue = True # while filen...
5,298,302
def qa_to_qaconf_slow(qa_data): """ Transforms MODIS QA into a confidence score. confidence comes from the vi_usefulness bits """ # https://lpdaac.usgs.gov/dataset_discovery/modis/modis_products_table/mod13q1 # 0-1 MODLAND_QA # 00 VI produced, good quality # 01 VI produced, bu...
5,298,303
def create_token_from_id(id): """ Create a token that can be used to verify a email address. Expires in 1 hour. """ to_encode = { "id": id, } expire = datetime.utcnow() + timedelta(minutes=EMAIL_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) encoded_jwt = jwt.en...
5,298,304
def erode_labels_in_dir(labels_dir, result_dir, labels_to_erode, erosion_factors=1., gpu=False, recompute=True): """Erode a given set of label values for all label maps in a folder. :param labels_dir: path of directory with input label maps :param result_dir: path of directory where cropped label maps will ...
5,298,305
def good_turing(corpus, words): """ :param corpus: :param words: :return: """ for w in words: if w in corpus: raise ValueError('未登录词有误!') r_dict = {} for w in corpus: if r_dict.get(w) is None: r_dict[w] = 1 else: r_dict[w] += ...
5,298,306
def get_server(): """Return the server info.""" return dict(version=QUALITY_TIME_VERSION)
5,298,307
def to_file(file_out, g): """This function permit to print value of the a generator to a file Args: file_out (string): Path of the file where we will store values """ check_and_rename(file_out) try: f = open(file_out, 'a') # looping over generator, this not increase time co...
5,298,308
def extract_main_tree(treedata, idx=None): """ Returns a single branch/trunk of tree following only the main progenitors. Works whether the treedata is alltrees or atree. Search until no progenitor is found. Doesn't matter how long the given tree is. """ if idx == None: prin...
5,298,309
def decode_smiles(model_outputs:torch.tensor = None) -> List[str]: """ Function to decode smiles from their generated indexes. Parameters : ------------- model_outputs : torch.tensor, a tensor of tensors that containes indices of each generated smile character. Returns : -...
5,298,310
def to_ansi(*codes): """Convert a set of ANSI codes into a valid ANSI escape sequence.""" if not codes: return '' return colorise.nix.cluts._COLOR_ESCAPE_CODE +\ '{0}m'.format(';'.join(str(c) for c in codes))
5,298,311
def _compile(schema_path, import_paths, output_path): """Compile the schema.""" cmd = ['capnp', 'compile', '-o-'] for import_path in import_paths: cmd.append('--import-path=%s' % Path(import_path).absolute()) cmd.append(str(schema_path)) log.info('execute: %s > %s', ' '.join(cmd), output_pat...
5,298,312
def critical_cases_20(): """ Real Name: b'Critical Cases 20' Original Eqn: b'INTEG ( infected critical case rate 20-critical cases recovery rate 20-death rate 20+isolated critical case rate 20\\\\ , init Critical Cases 20)' Units: b'person' Limits: (None, None) Type: component b'' """ ...
5,298,313
def datatype_percent(times, series): """ returns series converted to datatype percent ever value is calculated as percentage of max value in series parameters: series <tuple> of <float> returns: <tuple> of <float> percent between 0.0 and 1.0 """ max_value = max(series) try: ...
5,298,314
def lame(E=None, v=None, u=None, K=None, Vp=None, Vs=None, rho=None): """ Compute the first Lame's parameter of a material given other moduli. :param: E: Young's modulus (combine with v, u, or K) :param v: Poisson's ratio (combine with E, u, or K) :param u: shear modulus (combine with E, v, or K) ...
5,298,315
def encrypt_factory(cypher = None,Seed = None): """ creates an encryptor and a decryptor function from a cypher, or a seed, or randomly """ if not cypher: cypher = make_cypher(Seed) trans = mt(alphabet,cypher) untrans = mt(cypher,alphabet) def encryptor(message): return message....
5,298,316
def create_expcube(start, stop): """ Create exposure cube Parameters ---------- start : integer Start year stop : integer Stop year """ # Set observation definition filename inobs = 'gps_obs' + get_filename(start, stop) + '.xml' expcube = 'gps_expcube' + ge...
5,298,317
def simulate(ti_controls, sampling_times, model_parameters): """ ensuring pyomo returns state values at given sampling times """ model, simulator = create_model(sampling_times) """ fixing the control variables """ # time-invariant model.theta_0.fix(model_parameters[0]) model.theta_1.fix(model_p...
5,298,318
def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. """ #defining a blank mask to start with mask = np.zeros_like(img) #defining a 3 channel ...
5,298,319
def initialize_vocabulary(vocabulary_path): """ initialize vocabulary from file. assume the vocabulary is stored one-item-per-line """ characters_class = 9999 if os.path.exists(vocabulary_path): with codecs.open(vocabulary_path, 'r', encoding='utf-8') as voc_file: rev_vocab ...
5,298,320
def _make_decorator(measuring_func): """morass of closures for making decorators/descriptors""" def _decorator(name = None, metric = call_default): def wrapper(func): name_ = name if name is not None else func.__module__ + '.' +func.__name__ class instrument_decorator(object): #...
5,298,321
def runSome(): """ Unittest runner """ tests = [] names = ['testBlending', ] tests.extend(map(BasicTestCase, names)) suite = unittest.TestSuite(tests) unittest.TextTestRunner(verbosity=2).run(suite)
5,298,322
def remove_device_routines(filename, filepath): """ f2py/crackfortran.py gets confused by device subroutines/functions, so we're going to remove all of those """ txt = "" outtxt = "" with open(os.path.join(filepath, filename)) as infile: txt = infile.read() # finds start of...
5,298,323
def close_window(): """Close current tab and switch context to another window handle. If you need to change to specific tab, use switch window keyword. Examples -------- .. code-block:: robotframework CloseWindow """ driver = browser.get_current_browser() window_handles = win...
5,298,324
def _generate_librispeech_examples(directory): """Generate examples from a Librispeech directory.""" transcripts_glob = os.path.join(directory, "LibriSpeech", "*/*/*/*.txt") for transcript_file in tf.io.gfile.glob(transcripts_glob): path = os.path.dirname(transcript_file) with tf.io.gfile.GF...
5,298,325
def _unimport_class(old, ignores): """Remove traces of a class""" __internal_swaprefs_ignore__ = "unimport_class" oldItems = _safevars(old).items() ignores += (id(oldItems),) for name, value in oldItems: if name in ("__dict__", "__doc__", "__weakref__"): continue if ins...
5,298,326
def webtest(url, webtimeout): """ This tests connectivity to a webservice running at a given URL. :param url: Application URL to be tested. :type url: basestring :param webtimeout: application web timeout to be used for the test. :type webtimeout: int :return: Raises an exception or returns ...
5,298,327
def result(obj, key, default=None): """Return the value of property `key` on `obj`. If `key` value is a function it will be invoked and its result returned, else the property value is returned. If `obj` is falsey then `default` is returned. Args: obj (list|dict): Object to retrieve result from....
5,298,328
def config_adpd_stream(samp_freq_hz=50, agc_state=0, led='G', skip_load_cfg=False): """ :param samp_freq_hz: :param agc_state: :param led: :param skip_load_cfg: :return: """ cfg_dict = {'G': {'adpd_cfg': '1', 'clk_calib': adpd_clk_calib, 'sub': '6', 'agc_ctrl_id': '1'}, ...
5,298,329
def load_accuracy_data( files: List[Tuple[str, str, str]], folder: str ) -> List[Tuple[ndarray, ndarray, str, int, float]]: """This function loads the accuracy data that the user has elected to plot. Args: files: List containing tuples of the parameters of the files that are to be plotted. The ...
5,298,330
def add_options(options): """Decorator to add a list of options.""" def _add_options(func): for option in reversed(options): func = option(func) return func return _add_options
5,298,331
def run_program(): """ Function that runs the process of conversion and loading bar concurrently """ global progress_bar t1 = threading.Thread(target=progress_bar.start) t2 = threading.Thread(target=save_audio_file) t2.start() t1.start()
5,298,332
def exec_rmdir(dirname): """ Create a directory. Parameters ---------- dirname: str The full path of the directory. Returns ------- bool: True on success, raises an exception otherwise. """ _logger.debug('__ Removing directory tree %s.', dirname) try:...
5,298,333
def test_case_from_battin_book(solver): """ Example 7.12 from An Introduction to the Mathematics and Methods of Astrodynamics (Revised Edition), by Richard H. Battin """ # Initial conditions mu_sun = 39.47692641 # [AU ** 3 / year ** 2] r1 = np.array([0.159321004, 0.579266185, 0.052359607]) ...
5,298,334
def _get_s3_creds(client, force=False): """ Retrieves stored s3 creds for the acting user from the config, or generates new creds using the client and stores them if none exist :param client: The client object from the invoking PluginContext :type client: linodecli.CLI :param force: If True, ge...
5,298,335
def build_tracer(name, task, loader=None, hostname=None, store_errors=True, Info=TraceInfo, eager=False, propagate=False, app=None, IGNORE_STATES=IGNORE_STATES): """Return a function that traces task execution; catches all exceptions and updates result backend with the state an...
5,298,336
def create_mvp_sample_similarity(): """Create the most minimal Sample Similarity model possible.""" sample_similarity_result = SampleSimilarityResult(categories=CATEGORIES, tools=TOOLS, data_records=DATA_...
5,298,337
def _validate_freq(in_res: str, out_res: str) -> None: """ Validate the aggregation step See also: `ISO 8601 Durations <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ """ # Validate output frequency as a valid offset string try: dates = pd.date_range('2000-01-01', periods=5, freq=o...
5,298,338
def show_items(location_id): """ Show items for selected location """ locations = SESSION.query(Location).order_by(asc(Location.name)) location = SESSION.query(Location).filter_by(id=location_id).one() items = SESSION.query(Item).join(User).filter(User.location_id == location_id).all() if 'em...
5,298,339
def test_arcus_api_integration_group(): """ test the arcus api integration group cli call """ runner = CliRunner() result = runner.invoke(voithos.cli.service.arcus.integrations.get_integrations_group()) assert result.exit_code == 0
5,298,340
async def treats(ctx): """treatos! Get the bot's response time, aka. let lui search for treatos under your bed""" em = discord.Embed(color=discord.Color.green()) em.title = "Woof!" em.description = f'it took me exactly {bot.latency * 1000} ms \n' \ f'to find the treatos you have bee...
5,298,341
def test_TVD_g_u1(): """This and the following three tests test whether the TVD advection scheme produces the same result as the upwind advection scheme. """ g = ThPa2D.FDgrid(nx, nz, ng) h = ThPa2D.FDgrid(nx, nz, ng) gTVD, hTVD = ThPa2D.adflow(g, h, t, T, u2, k_ad, k_de...
5,298,342
def DiskPatch(tile=(8, 8), device='cuda:0'): """ Creates a disk patch Parameters ---------- tile : (int,int) (optional) the number of divisions of the disk (default is (8,8)) device : str or torch.device (optional) the device the tensors will be stored to (default is 'cuda:0') ...
5,298,343
def fused_mb_conv_block( inputs, input_filters: int, output_filters: int, expand_ratio=1, kernel_size=3, strides=1, se_ratio=0.0, bn_momentum=0.9, activation="swish", survival_probability: float = 0.8, name: str = "", ): """Fused MBConv Block: Fusing the proj conv1x1 and ...
5,298,344
def all(ctx, human, local): """List all events, past and future.""" events = ctx.obj.get("events") print_events(events, human, use_local_time=local)
5,298,345
def test_azure_devops_pull_request_get_command(requests_mock): """ Scenario: Retrieve pull-request information. Given: - User has provided valid credentials. When: - azure-devops-pull-request-get called. Then: - Ensure number of items is correct. - Ensure outputs prefix is correc...
5,298,346
def configure_logging( log_file, log_level=logging.INFO, log_format="%(asctime)s %(name)s %(levelname)s: %(message)s"): """ Configure the logging module :param str,None log_file: target file path. If None use standard error. :param int log_level: min log level to be reported in ...
5,298,347
def output(text, tag_arg=''): """ outputs the text in the specified format if the tag matches the resume_tags. tag is either '' (always matches), a string, or a list of strings of acceptable tags. this method can be edited to output to specific files later """ if tag_arg=='' or check_...
5,298,348
def read_xdr_var(buf, var): """ Reads a single variable/array from a xdrlib.Unpack buffer. Parameters ---------- buf: xdrlib.Unpack object Data buffer. var: tuple with (type[,shape]), where type is 'f', 'd', 'i', 'ui', or 's'. Shape is optional, and if true is shape of ar...
5,298,349
def diffMonths(d1, d2): """ Takes in two datetimes and calculates the difference in months between them. """ return int(diffDays(d1, d2)/30.4)
5,298,350
def validate_specs(specs: Blocklist, match_versions: bool = False) -> None: """ Validates an array of specs. Args: specs (list): Array of specs. match_versions (bool): If True raises SpecsVersionError if the array has conflicting versions or different version_bits. ...
5,298,351
def _fetch_events_for_all_contracts( web3, event, argument_filters: dict, from_block: int, to_block: int) -> Iterable: """Get events using eth_getLogs API. This method is detached from any contract instance. This is a stateless method, as opposed to createFilter. ...
5,298,352
def get_local_status() -> Dict[str, Any]: """ Returns a running status if localhost:4040/api/v1/applications is reachable; othe :return: Dict[str, Any] """ idle_cluster_state = { "url" : "spark://simulated-local-mode-cluster:7077", "workers" : [ ], "aliveworkers" : 0, ...
5,298,353
def test_app_json_modified(): # pragma: no cover """ Pytest test that verifies app.json is up-to-date To use this, you should import this into a test file somewhere in your project: from mitol.common.pytest_utils import test_app_json_modified """ with open("app.json") as app_json_file: ...
5,298,354
def total_points(min_x, max_x, points_per_mz): """ Calculate the number of points for the regular grid based on the full width at half maximum. :param min_x: the lowest m/z value :param max_x: the highest m/z value :param points_per_mz: number of points per fwhm :return: total number of points ...
5,298,355
def get_investor_brokerage_transactions(investor_id, **kwargs): """ Returns a list of brokerage transactions for a given investor. Arguments --------- investor_id: int Investor specified by the investorId returned from the investors endpoint. Keyword Arguments -------------...
5,298,356
def _received_in_time(record, extra_data): """Check if publication is not older than 24h """ api_url = current_app.config.get('CROSSREF_API_URL') api_response = requests.get(api_url + get_first_doi(record)) if api_response.status_code != 200: return True, ('Article is not on crossref.', ), 'Api...
5,298,357
def merge_multiple_edge_attrs(main_graph, merge_graph, key, merge_type="mean"): """merge multiple """ edges = list(main_graph.edges) for edge in edges: try: merge_edge_attrs(main_graph, merge_graph, edge, edge, key, merge_type=merge_type) except KeyError as e: edg...
5,298,358
def core_count(): """ count number of cores in the local machine """ with open("/proc/cpuinfo","r") as procinfo: return reduce(lambda a, b: a + b.startswith("processor"), procinfo, 0)
5,298,359
def AnalyticalSolution(a,b,c,d,e,eps): """ Source: https://en.wikipedia.org/wiki/Quartic_function#General_formula_for_roots Calculates the value of the analytical solution. """ p=(8*a*c-3*b**2)/(8*a**2) q=(b**3-4*a*b*c+8*a**2*d)/(8*a**3) Delta0=c**2-3*b*d+12*a*e Delta1=2*c**3 -9*b*c...
5,298,360
def restart(service): """ Restart service on all nodes :param service: the service name """ print("Restarting nodes.") remote_op = { "action_str": "restart {}".format(service), "service": [{"name": service, "restart": "yes"}], } do_configure_op(remote_op)
5,298,361
def time_text_to_float(time_string): """Convert tramscript time from text to float format.""" hours, minutes, seconds = time_string.split(':') seconds = int(hours) * 3600 + int(minutes) * 60 + float(seconds) return seconds
5,298,362
def calc_adaptive_threshold(frate, pfit, bounds): """ calculates the adaptive threshold, based on the current firing rate, the estimated peak reduction and the initially user set static bounds that are to be adaptively modified. Args: frate (neo.core.AnalogSignal): the firing rate p...
5,298,363
def longest_seq( tr ): """ Given a tree, t, find the length of the longest downward sequence of node labels in the tree that are increasing consecutive integers. The length of the longest downward sequence of nodes in T whose labels are consecutive integers. >>> t = Tree (1 , [ Tree (2) , Tree (1 , [ Tr...
5,298,364
def parse_args(argv): """Parses command line arguments.""" parser = argparse_flags.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) # High-level options. parser.add_argument( "--num_filters", type=int, default=32, help="Number of filters in each convolutio...
5,298,365
def subset_bcf_regions( file: str, regions: List[str], output: Optional[str] = None, keep: bool = True): """ Args: file: Input BCF file path regions: Each str is a region of the reference genome, e.g. chr1 ...
5,298,366
def test_snap_restore_from_artifacts(bin_cloner_path, bin_vsock_path, test_fc_session_root_path, cpu_template): """ Restore from snapshots obtained with all supported guest kernel versions. The snapshot artifacts have been generated through the `create_snapshot_arti...
5,298,367
def soil_evpa(Pt, EPt, WUt, WLt, WDt, C, WLM): """ 三层蒸散发模型。 Parameters: ----------- Pt: float, t时刻的降水量 EPt: float, t时刻对应的蒸发能力 WUt, WLt, WDt: float, t时刻对应的地表,浅层和深层土壤含水量 C: float, 浅层蒸散发折算系数 WLM: float, 下层土壤水含水容量 Return: -------- EUt, EDt, ELt: float, t时刻对应的地表,浅层和深层蒸发水量 ...
5,298,368
def smiles_from_pdb(ligand_ids: Iterable[str]) -> dict: """ Retrieve SMILES of molecules defined by their PDB chemical identifier. Parameters ---------- ligand_ids: iterable of str PDB chemical identifier. Returns ------- ligands: dict Dictionary with PDB ch...
5,298,369
def fetch_values_from_file(values_dict, file_name): """ Fetches KEYWORD=VALUE settings from the specified file. Everything to the left of the first '=' is the keyword, everything to the right is the value. No stripping of white space, so beware. The file must exist, otherwise you get the Python exception...
5,298,370
def incremental_build(new_content: str, lines: List, metadata: Dict) -> List: """Takes the original lines and updates with new_content. The metadata holds information enough to remove the old unreleased and where to place the new content Args: lines: The lines from the changelog new_co...
5,298,371
def get_template_groups_priorities(self) -> dict: """Get order that template groups will be applied in .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - template - GET - /template/templateGroupPriorities :return: Re...
5,298,372
def read_tides(path: str) -> Tuple[List, List]: """Read a CO-OPS tide data CSV file and return a list of times and elevations.""" data = [line.strip() for line in open(path)] time = [] elevation = [] for line in data[1:]: line = line.replace('"','').split(',') time.append(datetim...
5,298,373
def sigmoid(x): """Sigmoid activation function. For small values (<-5) the sigmoid returns a value close to zero and for larger values (>5) the result of the function gets close to 1. Arguments: x {tensor} -- Input float tensor to perform activation. Returns: tensor -- Output o...
5,298,374
def run_trio(proc, *args): """Call an asynchronous Trio function from asyncio. Returns a Future with the result / exception. Cancelling the future will cancel the Trio task running your function, or prevent it from starting if that is still possible. You need to handle errors yourself. """ ...
5,298,375
def computeVoronoiDefects(lattice, refLattice, vacancies, voronoiOptions): """ Compute Voronoi for system containing defects """ logger = logging.getLogger(__name__) vorotime = time.time() logger.info("Computing Voronoi (defects)") logger.debug(" NAtoms: %d; NVacancies: %d", ...
5,298,376
def mahalnobis(u, v): """ By Robin Hayman gets the mahalanobis distance between two vectors feature arrays u and v a blatant copy of the Mathworks fcn as it doesn't require the covariance matrix to be calculated which is a pain if there are NaNs in the matrix """ u_sz = u.shape v_sz = v...
5,298,377
def is_valid_uri(uri): """Determine if the string is a valid URL. We use it to distringuish links from workflow variables.""" try: result = urllib.parse.urlparse(uri) return result.scheme and result.path except Exception as e: return False
5,298,378
def tier_from_reader(stream): """Return a tier object from a stream of strings and numbers. Parameters ---------- stream : iterator of str, int, and float Iterator that yields strings and numbers in the order that Praat expects to define a tier. Returns ------- IntervalTier...
5,298,379
def get_house_committees(biennium: str) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/committeeservice.asmx?op=GetHouseCommittees""" argdict: Dict[str, Any] = dict(biennium=biennium) keydict: Dict[str, Any] = {} return waleg.call("Committee", "GetHouseCommittees", argdict, keydict)
5,298,380
def _train_dsm(x, t, e, folds, params): """Helper Function to train a deep survival machines model. Args: x: a numpy array of input features (Training Data). t: a numpy vector of event times (Training Data). e: a numpy vector of event indicators (1 if event occured, 0 otherwise) ...
5,298,381
def create_user(context,galaxy,email,public_name,password,only_check, message_template): """ Create new Galaxy user. Creates a new user in GALAXY, using EMAIL for the username. If PUBLIC_NAME is not supplied then it will be generated automatically from the leading part of the email ...
5,298,382
def get_teams_history(**kwargs): """ """
5,298,383
def vote(request): """Ajax call to add an up vote to comment comment_pk.""" comment_pk = request.GET.get('comment_pk') c = Comment.objects.get(pk=int(comment_pk)) c.up_votes += 1 c.save() return JsonResponse({'id': comment_pk, 'count': c.up_votes})
5,298,384
def get_lovelive_info(): """ 从土味情话中获取每日一句 :return: str,土味情话 """ print('获取土味情话...') try: resp = requests.get('https://api.lovelive.tools/api/SweetNothings') if resp.status_code == 200: return resp.text print('土味情话获取失败。') except requests.exceptions.RequestEx...
5,298,385
def set_exploit_name(id_, name, user, **kwargs): """ Set a Exploit name. :param id_: Exploit ObjectId. :type id_: str :param name: The new name. :type name: str :param user: The user updating the name. :type user: str :returns: dict with keys: "success" (boolean), ...
5,298,386
def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press left mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenW...
5,298,387
def readfile(fname: Union[str, Path]) -> Union[str, dict, np.ndarray]: """ Util function for reading a variety of different files """ fname = str(fname) ext = os.path.splitext(fname)[-1] if ext == ".json": with open(fname, "r") as f_in: data = json.load(f_in) elif ext == ...
5,298,388
def test_force_sync_discussion_users_task_api_error(mocker): """ Test that sync_discussion_users logs errors if they occur """ mock_api = mocker.patch('discussions.api.create_or_update_discussion_user', autospec=True) user = UserFactory.create() # don't count the one triggered by signals on Use...
5,298,389
def main(debug: bool = False): """ Cytheron, a C interpretor made with Python """ # Initialize colorama colors formatting init() # Setup debugging logger = logging.getLogger("cytheron") logger.setLevel(logging.CRITICAL) ch = logging.StreamHandler() ch.setLevel(logging.CRITICAL)...
5,298,390
def check_assertisinstance(logical_line, filename): """N331 - Enforce using assertIsInstance.""" if 'neutron/tests/' in filename: if re.search(r"assertTrue\(\s*isinstance\(\s*[^,]*,\s*[^,]*\)\)", logical_line): msg = ("N331: Use assertIsInstance(observed, type) instead "...
5,298,391
def test_predict_multiple_k2_no_verbose(capsys): """Silently predict multiple observation sequences (k=2)""" predictions = clfs['k=2'].predict(X, verbose=False) assert 'Classifying examples' not in capsys.readouterr().err assert len(predictions) == 6
5,298,392
async def async_get_registry(hass) -> DeviceRegistry: """Return device registry instance.""" task = hass.data.get(DATA_REGISTRY) if task is None: async def _load_reg(): registry = DeviceRegistry(hass) await registry.async_load() return registry task = ha...
5,298,393
def read_json_file(filename: str) -> Any: """Read a json file Parameters ---------- filename : str The json file Returns ------- A json object Example ------- >>> import allyoucanuse as aycu >>> content = aycu.read_json_file("tickets.json") """ with ope...
5,298,394
async def api_user_authenticate(request): """ 用户登录验证API函数 :param request: 请求对象 :return: 回响消息, 并且设置COOKIE """ request_data = RequestData(request) if not await request_data.json_load(): return data_error(u'非法数据格式, 请使用JSON格式') email = request_data.email password = re...
5,298,395
def get_best_invocation_for_this_pip() -> str: """Try to figure out the best way to invoke pip in the current environment.""" binary_directory = "Scripts" if WINDOWS else "bin" binary_prefix = os.path.join(sys.prefix, binary_directory) # Try to use pip[X[.Y]] names, if those executables for this enviro...
5,298,396
def test_complex_pattern_equivalence_monomer_pattern_ordering(): """Ensure CP equivalence is insensitive to MP order.""" Monomer('A', ['s1', 's2']) cp0 = A(s1=1, s2=2) % A(s1=2, s2=1) cp1 = A(s1=2, s2=1) % A(s1=1, s2=2) _check_pattern_equivalence((cp0, cp1))
5,298,397
def sendCommand(name, value): """ Sends a command to the LED :name: The name of the command, eg. turn :value: The value of the command, eg. on """ url = "https://developer-api.govee.com/v1/devices/control" headers = {"Govee-API-Key": apikey, "Content-Type": "application/json"} params = {"device": deviceid, "m...
5,298,398
def schedule_push(graph, u, message_func, reduce_func, apply_func, inplace, outframe=None): """Get push schedule Parameters ---------- graph: GraphAdaptor Graph u : utils.Index ...
5,298,399