content
stringlengths
22
815k
id
int64
0
4.91M
def fetch_events_sciencehistory(base_url='https://www.sciencehistory.org'): """ Fetch events from Science History Institute, https://www.sciencehistory.org/events """ events = [] page_soup = BeautifulSoup(requests.get( urljoin(base_url, '/events')).content, 'html.parser') all_events = p...
48,900
def generate_url(endpoint, token): """Generate a url for an endpoint with a token. E.g. a confirmation url for a user to verify their account. Args: endpoint: An endpoint referencing a method in the backend token: A token that has been serialized with relevant data (e.g. a user's e...
48,901
def _create_buffer(size): """Create a ctypes buffer of a given size.""" buftype = (CHAR * size) return buftype()
48,902
def collect_files(config: Config, files: Optional[List[str]] = None, method: Optional[str] = None) -> DFs: """Read a filtered memory map from a set of files.""" filenames = files if files else config.get('args.inputs', []) if method is None: method = config.get('c...
48,903
def ModelInfoAddShader(builder, shader): """This method is deprecated. Please switch to AddShader.""" return AddShader(builder, shader)
48,904
def list_by_title(library): """ Input tags title or part of it and find all books that have that title part :param library: the book library list """ pass
48,905
def configuration(request): """Various things stored in settings.py""" return {"version": VERSION, "current_url": request.get_full_path(), "project_long_name": settings.project_long_name, "project_short_name": settings.project_short_name, "project_description": se...
48,906
def percentile(event_collection, target_property, percentile, timeframe=None, timezone=None, interval=None, filters=None, group_by=None, max_age=None): """ Performs a percentile query Finds the percentile of a target property for events that meet the given criteria. :param event_collection:...
48,907
def plot_cell_positions(table_path, savename, imgshape, vx_size): """ plot detected cell positions, and saves it as a image (NIFTI format) Inputs: table_path: path to cell table (csv) savename: Output file name. should end with .nii.gz imgshape: shape of the input image, order should...
48,908
def load_stats_from_csv(csv_path): """Load statistics from a CSV file at csv_path and return them as a list of Stats.""" logger.debug(f"Loading {csv_path.name}...") stats = [] with csv_path.open("r", encoding="utf-8") as csv_file: reader = csv.DictReader(csv_file) for r in reader: ...
48,909
def MolAsMolWithQueryAtoms( mol: rdChem.Mol, strict: bool = False, includeIsotopes: bool = True ) -> rdChem.Mol: """If Mol contains Chem.Atoms, convert to Mol with Chem.QueryAtoms If Mol already is composed of QueryAtoms, returns the same object """ if all(isinstance(atom, rdChem.QueryAtom) for ato...
48,910
def find_images( directory: pathlib.Path, specs: specsmod.Specs) -> Tuple[List[pathlib.Path], List[str]]: """ Find all the sample images beneath the directory. :param directory: where to search :param specs: specification of the problem :return: list of image paths, list of class la...
48,911
def login(): """ Log in user --- tags: - Auth requestBody: content: application/x-www-form-urlencoded: schema: type: object properties: pin: description: Redirects to next page if login successful typ...
48,912
def T_asy(x, beta): """Symmetry breaking transformation. .. math:: T_{asy}^{\\beta} (x_i) = \\begin{cases}x_i^{ 1 + \\beta \\frac{i-1}{D-1}\sqrt{x_i}} & \\text{if } x_i > 0\\\\ x_i & \\text{otherwise} \\end{cases} Parameters ---------- ...
48,913
def init(repo): """ Initializes new repository in the --repo directory. Initializes new repository in the current working directory if --repo argument is not provided: - Creates .aim directory & runs upgrades for structured DB """ repo_path = clean_repo_path(repo) or os.getcwd() re_init = F...
48,914
def commonChecks(L0: float, Rtot: np.ndarray, KxStar: float, Kav: np.ndarray, Ctheta: np.ndarray): """ Check that the inputs are sane. """ Kav = jnp.array(Kav, dtype=float) Rtot = jnp.array(Rtot, dtype=float) Ctheta = jnp.array(Ctheta, dtype=float) assert Rtot.ndim <= 1 assert Rtot.size == Kav.s...
48,915
def com_google_fonts_check_varfont_generate_static(ttFont): """Check a static ttf can be generated from a variable font.""" import tempfile from fontTools.varLib import mutator try: loc = {k.axisTag: float((k.maxValue + k.minValue) / 2) for k in ttFont['fvar'].axes} with ...
48,916
def _threed_extract(step, var, walls=False): """Return suitable slices and coords for 3D fields.""" is_vector = not valid_field_var(var) hwalls = is_vector or walls i_x = conf.field.ix i_y = conf.field.iy i_z = conf.field.iz if i_x is not None or i_y is not None: i_z = None if i_...
48,917
def calc_temps(session,start_date, end_date): """TMIN, TAVG, and TMAX for a list of dates. Args: start_date (string): A date string in the format %Y-%m-%d end_date (string): A date string in the format %Y-%m-%d Returns: TMIN, TAVE, and TMAX """ return sessi...
48,918
def test_merge_multiple(simple_canvas): """Test multiple line merge. """ simple_canvas.line.handles()[1].pos = (20, 16) segment = Segment(simple_canvas.line, simple_canvas.view) segment.split_segment(0, count=3) # Start with 4 handles and 3 ports, merge 3 segments assert len(simple_canvas....
48,919
def get_react_score(reactions: List[dict]) -> float: """ Returns score of the post according to reactions weights. :reactions: list of dictionaries containing post info """ react_score = 0 for react in reactions: react_score += reactions_dict[react.get("name", "")] * react.get("count"...
48,920
def _get_collections_abc_obj_id(node: ast.expr | None) -> str | None: """ If the node represents a subscripted object from collections.abc or typing, return the name of the object. Else, return None. >>> _get_collections_abc_obj_id(_ast_node_for('AsyncIterator[str]')) 'AsyncIterator' >>> _g...
48,921
def show_index(): """ main site, generating sections """ title = "Homepage" sql_query = 'SELECT categoryId, title FROM category' output = myDB.execute_sql(sql_query) sections = dict(output) return render_template("index.html", title=title,sections = sections)
48,922
def main(): """ This script takes the events table from the new database. This contains all of the events that can trigger a tsunami for chile, so we can delete all the events in the existing database that are just chile events. The new events must be inserted into the existing database, ...
48,923
def create_hyperlink(url, text): """ Creates a VTE hyperlink clickable in a terminal window """ if True: # TODO: Check for capability or config return f"\033]8;;{url}\033\\{text}\033]8;;\033\\" else: return text
48,924
def generate_packed_decoder(wrapped_decoder): """Generate an decoder for a packer type from a base type decoder""" def length_wrapper(buf, pos): """Decode repeat values prefixed with the length""" length, pos = varint.decode_varint(buf, pos) end = pos+length output = [] w...
48,925
def test_to_smirnoff_missing_dependency(monkeypatch): """Test that the correct custom exception is raised when the OpenFF toolkit cannot be imported.""" monkeypatch.setitem(sys.modules, "openff.toolkit", None) with pytest.raises(MissingOptionalDependency): original_am1bcc_corrections().to_smir...
48,926
def create_ik_handle(name, start_joint, end_joint, solver_type=None, curve=None, **kwargs): """ Creates a new IK handle :param name: str :param start_joint: str :param end_joint: str :param solver_type: str :param curve: str :param kwargs: :return: str """ if solver_type is ...
48,927
def FinalFitness4(intermediate_outputs): """ Function: FinalFitness3 ======================== Compute global fitness of an individual. Intended when wanting to refine the fitness score. @param intermediate_outputs: the fitnesses of the tree over several sets of ...
48,928
def create_with_deletion_protection(ledger_name): """ Create a new ledger with the specified name and with deletion protection enabled. :type ledger_name: str :param ledger_name: Name for the ledger to be created. :rtype: dict :return: Result from the request. """ logger.info("Let's cr...
48,929
def run(command): """Execute command as user:<command>""" with hide('everything'), settings(warn_only=True): result = api.run(command) print("["+env.host+"] " + command) if result != '': print(result) return result
48,930
def dummy_request(): """Fixture to return a single dummy request.""" return testing.DummyRequest()
48,931
def refill(pop): """Get rid of duplicates.""" for lst in pop: lst[9] = sgn(lst[9]) lst[-1] = abs(lst[-1]) pop.sort() newpop = [0] * Npop i = 0 last = None for lst in pop: if lst != last: newpop[i] = lst i += 1 last = lst for j in ...
48,932
def parse_code(body): """ Parse the code from the body """ # Regex to match code block reddit comment regex = ur"^((?:(?:(?:[ ]{4}).*|)(?:[\r\n]+|$))+)" matches = re.findall(regex, body, re.MULTILINE) # remove all empty lines matches = [match for match in matches if match != "\n"] ...
48,933
def displacement_numbers(mat): """ Desplaza todos los numeros a la izquierda de la matriz """ new = new_game(c.GRID_LEN) # crea una matrix de 0 de AxA (donde A es la c.GRID_LEN) done = False for i in range(c.GRID_LEN): # Inspecciona una fila count = 0 for j in range(c.GRI...
48,934
def test_ap_track_sta_no_auth(dev, apdev): """Dualband AP rejecting authentication from dualband STA on 2.4 GHz""" try: _test_ap_track_sta_no_auth(dev, apdev) finally: subprocess.call(['iw', 'reg', 'set', '00'])
48,935
def get_or_create_transaction_destination_account( transaction: Transaction, ) -> Tuple[Optional[Account], bool, bool]: """ Returns: Tuple[Optional[Account]: The account(s) found or created for the Transaction bool: boolean, True if created, False otherwise. bool: boolean, True if tr...
48,936
def test_loading(tmpdir): """ Load an object. """ class A(FSObject): _config_file = 'a.json' def __init__(self,**kwargs): super().__init__(**kwargs) @property def state(self) -> dict: return {} @classmethod def load(cls, base_path: ...
48,937
def random_date(start=None, end=None): """Get a random date between two dates""" if start is None and end is None: end = datetime.datetime.now() start = end - datetime.timedelta(days=365) stime = date_to_timestamp(start) etime = date_to_timestamp(end) ptime = stime + random.random...
48,938
def browse_windows10spotlight(url): """ Connects to the given URL then parse the HTML source code to retrieve, in the HTML tags <a></a>, the HTTP link of the spotlight image to download. :param url: The URL of the current page (e.g. https://windows10spotlight.com/page/123) """ if not args.no_dow...
48,939
def test_domain_reputation_command_not_specify_domain_arguments_values(client): """ When no value enter for command argument then should raise error with proper message """ from PassiveTotal_v2 import domain_reputation_command # Configure args = { 'domain': '' } # Execute ...
48,940
def _chg_float(something): """ floatに変換できたらfloatに変換する """ try: f = float(something) return f except ValueError: pass return something
48,941
def get_seeding_programs(): """Returns the list of seeding program names""" try: seed_catalogs = read_plist(SEED_CATALOGS_PLIST) return list(seed_catalogs.keys()) except (OSError, IOError, ExpatError, AttributeError, KeyError) as err: log.warn(err) return ""
48,942
def query_ols(iri): """ Gets the name field of measurementTechnique, infectiousAgent, infectiousDisease, and species in our nde schema ols api doc here: https://www.ebi.ac.uk/ols/docs/api Returns the formatted dictionary {name: ####, url: ####} if an url was given or {name: ####} """ url =...
48,943
def cylinder( **named ): """Create a cylinder, adding to current scene""" return _newNode( geometry.VPCylinder, named )
48,944
def check_dup_configs(ctx): """Checks for duplicate configs in Trino config files (jvm.config and config.properties). This is a safety check for modules that may improperly modify these files. Duplicates will only be registered for JVM config if the configs are identical. For config.properties, dup...
48,945
def handle_audio_end(_): """Request unmute, if more sources have requested the mic to be muted it will remain muted. """ if config.get("listener").get("mute_during_output"): loop.unmute()
48,946
def mrr_finesse(a, r): """ description: Calculate the finesse of the MRR, i.e., finesse=FSR/FWHM=pi*sqrt(ra)/(1-ra) (Bogaerts et al., Silicon microring resonators, Laser and Photonics Review 2011, Eq.(21))\\ a {float} Attention coefficient\\ r {float} Self-coupling coefficient\\ return finesse {floa...
48,947
def config_I(event): """This function is executed every time there is a size change in the window of the interface. It scales and adjusts the sizes and positions of the main frames according to window size.""" current_width, current_height = event.width, event.height x = current_width*0.05 ## padding on horizontal...
48,948
def is_numeric(value): """ Check whether *value* is a numeric value (i.e. capable of being represented as a floating point value without loss of information). :param value: The value to check. This value is a native Python type. :return: Whether or not the value is numeric. :rtype: bool """ if not isinstance(v...
48,949
def example_6_nested_spans() -> None: """Print and log simple message.""" msg = "Hello World! I'm about to call another spanned function w/ the same tracer name/id" print(msg) logging.info(msg) try: example_4_with_an_uncaught_error() except FileNotFoundError: pass
48,950
def configure_repo(name, token, create, org): """ Configures a repository to conform to standards. """ g = Github(token) o = g.get_organization(org) click.echo(f"Successfully logged into organization {o.name} ({o.login}).") try: r = o.get_repo(name) except UnknownObjectExcepti...
48,951
def _position_to_features(sam_reader, allele_counter, region, position, exclude_contig): """Extracts the AlleleCount data from a given position.""" # We build the AlleleCount at the position. reads = sam_reader.query(region) for read in reads: allele_counter.add(read) counts = al...
48,952
def p_name(username): """ 根据用户名获取昵称 :param username: 用户名 :return: """ friend = itchat.search_friends(userName=username) if not friend: return '' return friend.get('RemarkName') or friend.get('NickName')
48,953
def user_profile(self): """Return this user's UserProfile, or None if one doesn't exist.""" try: return self.userprofile except UserProfile.DoesNotExist: return None
48,954
def get_policy_list(cluster_name): """ 获取存储策略列表 :param cluster_name: :return: """ data = [] status = '' message = '' resp = {"status": status, "data": data, "message": message} pm = PolicyManager(cluster_name) try: sfo_policys = pm.policys() for policy in sfo_...
48,955
def package_air_ticket(request): """ view air ticket package for customer """ air_tickets = AirTicket.objects.all()[::-1] package_air_tickets = PackageAirTicket.objects.all()[::-1] context = { 'air_tickets': air_tickets, 'package_air_tickets': package_air_tickets, 'user_inf...
48,956
def CheckNodeJSPackage(package): """ Check whether a node.js package is installed """ cmd = "node -e \"var d3=require('%s');\"" % package x = RunCommand(cmd) return x == 0
48,957
def toggle_extreme_values(curr_doc: CurrentDoc, plot, vals_active=True): """ Toggles the visualisation of the extreme values in a chosen plot :param plot: plot to visualise the extreme values in :param vals_active: Boolean to define if values shell be plotted or not :return: """ # toggle ext...
48,958
def compilable(tex): """Return tex-math content wrapped so that it can be compiled using tex.""" # remove "\usepackage{pmc}". It's not clear what the contents # of this package are (I have not been able to find it), but # compilation more often succeeds without it than with it. tex = tex.replace('\...
48,959
def filter_matches(matches, threshold=0.75): """Returns filterd copy of matches grater than given threshold Arguments: matches {list(tuple(cv2.DMatch))} -- List of tupe of cv2.DMatch objects Keyword Arguments: threshold {float} -- Filter Threshold (default: {0.75}) Returns: li...
48,960
def upgrade(): """ Upgrade Semantic Description: ENTER DESCRIPTION HERE """ # ### commands auto generated by Alembic - please adjust! ### op.create_table('name', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column('v...
48,961
def V_PT(P, T, substance, eos = IDEAL_GAS): """Returns specific volume.""" mw = get_parameter(substance, 'molecular-weight') Vmol = eos.Vmol_PT(P, T, substance) return Vmol / mw
48,962
def test_riomucho_simple_dataset_object(tmpdir, test_1_tif): """We can pass an open dataset for output""" with rasterio.open(str(test_1_tif)) as src: options = src.profile with rasterio.open(str(tmpdir.join("output.tif")), "w", **options) as dst: with riomucho.RioMucho([str(test_1_tif)], ds...
48,963
def checks(poly_fit_left, poly_fit_right, poly_fitx_left, poly_fitx_right, poly_fity): """Check if found lanes make sense.""" # check curvature y_eval = np.max(poly_fity) curvature_left = (((1 + (2*poly_fit_left[0]*y_eval + poly_fit_left[1])**2)**1.5) /...
48,964
def show_phase(adata, genes, mode='labeling', vkey='velocity', basis='umap', group=None): """Draw the phase portrait, velocity, expression values on the low dimensional embedding. Parameters ---------- adata: :class:`~anndata.AnnData` an Annodata object genes: `list` A list of gene ...
48,965
def run( dataset_file: str = Path.joinpath(DATA_DIR, "processed", "winequality_clean.csv"), params_file: str = Path.joinpath(MODELS_DIR, "params.json").read_text(), ): """ Run the training process """ dataset = load_dataset(dataset_file) train_test = split_dataset(dataset) params = load_...
48,966
def _UpdateMetadataValue(metadata, key, value): """Updates a single key-value pair in a metadata object. Args: metadata: metadata object, i.e. a dict containing containing 'items' - a list of key-value pairs. key: name of the key. value: new value for the key, or None if it should be removed. "...
48,967
def test_gateway_bad_protocol(): """Test initializing gateway with a bad protocol_version.""" gateway = get_gateway(protocol_version=None) assert gateway.protocol_version == '1.4'
48,968
async def test_availability_when_connection_lost( hass, mqtt_client_mock, mqtt_mock, setup_tasmota ): """Test availability after MQTT disconnection.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 2 config["lt_st"] = 1 # 1 channel light (Dimmer) await help_test_availability_when_con...
48,969
def createRandomStrings(l,n,chars=None,upper=False): """create list of l random strings, each of length n""" names = [] if chars == None: chars = string.ascii_lowercase #for x in random.sample(alphabet,random.randint(min,max)): if upper == True: chars = [i.upper() f...
48,970
def create_gene_table(connection): """ Create a gene table in the SQLite database """ statement = """ CREATE TABLE GENE ( GENE_ID INTEGER PRIMARY KEY NOT NULL, GENE_SYMBOL TEXT, HGNC_ID TEXT, ENTREZ_GENE_ID INTEGER, ENSEMBL_G...
48,971
def create_model(reader_input, base_model=None, is_training=True, args=None): """ given the base model, reader_input return the output tensors """ labels = reader_input[-1] cls_feats = base_model.final_sentence_representation cls_feats = fluid.layers.dropout( x=cls_feats, ...
48,972
def shot_mix(df1): """ Calculates the average of the poisson models for shots and shots on target """ df1["H_att_Poi_mix"] = (3*df1["H_att_PoiS"] + 3*df1["H_att_PoiST"] + 2*df1["H_att_PoiG"]) / 8 df1["A_att_Poi_mix"] = (3*df1["A_att_PoiS"] + 3*df1["A_att_PoiST"] + 2*df1["A_att_PoiG"]) / 8 df1["H...
48,973
def test_config(test_app): """tests config command""" out = test_app.app_cmd("config") assert isinstance(out, CommandResult) assert str(out.stdout).strip() == 'Database path: None' assert out.data is None
48,974
def web(twitterwall, debug): """Run the web app""" app.config['twitterwall'] = twitterwall app.run(debug=debug)
48,975
def configure_logging(count=0): """Configure logging using the provided verbosity count.""" if count == -1: level = settings.QUIET_LOGGING_LEVEL default_format = settings.DEFAULT_LOGGING_FORMAT verbose_format = settings.LEVELED_LOGGING_FORMAT elif count == 0: level = settings...
48,976
def find_devices(name=None, serial_number=None, vid_pid=None, device_id=None, hid_enumeration=None, chip_name=None): """ Returns a list of keyplus keyboards that are currently connected to the computer. The arguments can be used to filter result. Args: name: filter list by the ...
48,977
def jobs(): """ lista de jobs """ rows = db(db.job).select(orderby=db.job.created_on) return locals()
48,978
async def reserve_subdomain(request: Request, req: t.Optional[ReservationRequest] = None): """ Reserve a subdomain for use with an application. If no subdomain is given, a random subdomain is reserved and returned. If a set of SSH public keys is given, they are associated with the subdomain and the ...
48,979
def get_previous_quarter(today): """There are four quarters, 01-03, 04-06, 07-09, 10-12. If today is in the last month of a quarter, assume it's the current quarter that is requested. """ end_year = today.year end_month = today.month - (today.month % 3) + 1 if end_month <= 0: end_year -= 1 end_mo...
48,980
def example_log_file(temporary_log_directory) -> Dict[str, Union[logging.Logger, logging.RootLogger, str]]: """Create a temporary log file for testing purposes.""" # Create a temporary directory to store the log file, and define a file path to a log file temporary_log_file = temporary_log_directory.join("t...
48,981
def main() -> None: """tldextract CLI main command.""" logging.basicConfig() parser = argparse.ArgumentParser( prog="tldextract", description="Parse hostname from a url or fqdn" ) parser.add_argument( "--version", action="version", version="%(prog)s " + __version__ ) parser...
48,982
def test_context_propagate(log_capture): """ check if extra variables propagate properly in variouls local() levels """ logger = logger_mod.getLogger("foo.bar2", extra={"evar1": "initial"}) logger.info("this is message from first logger") assert log_capture.records[-1].evar1 == "initial" loclo...
48,983
def extract_metadata(document): """Return the dict containing document metadata. :param document: :type document: :class:`docutils.nodes.document` :returns: docinfo data from document :rtype: dict From: https://github.com/adieu/mezzanine-cli @ mezzanine_cli/parser.py License: BSD (https://...
48,984
def get_bottleneck_features(model=None, source='path', container_path=None, tensor=None, classes=None, save=False, filename=None, ...
48,985
def load_model(data, labels, filename, params, num_samples = 16): """ Loads a checkpoint from disk with the corresponding parameters set. Then it runs the model on a some collection of randome samples. Args: data (nparray) : dataset labels (nparray) : labels filename (str) : filename of tf checkpoint file ...
48,986
def ibp_loglik(Z, alpha): """Probability of an assignment matrix drawn from an IBP prior, where each customer chooses new dishes consecutively from the end, but otherwise the columns are unordered.""" N, K = Z.shape total = K * np.log(alpha) new_dish_counts = np.bincount(first_customer(Z)) total...
48,987
def test_union(): """unit test for wrapper around trimesh union""" # all of this works with trimesh 3.2.2 # no redundant points mesh = components.cylinder(4.0, 1.0, 8) mesh_2 = util.translate_mesh(mesh, vec3(0.5, 0, 0)) # concat / union meshes together mesh_c = util.concat([mesh, mesh_2])...
48,988
def neighbours(geohash): """ Returns all 8 adjacent cells to specified geohash:: | nw | n | ne | | w | * | e | | sw | s | se | :param geohash: string, geohash neighbours are required of :returns: neighbours as namedtuple of geohashes with properties n,ne,e,se,s,sw,w,nw ...
48,989
def get_payload(address): """ According to an Address object, return a valid payload required by create/update address api routes. """ return { "address": address.address, "city": address.city, "country": str(address.country), "first_name": address.first_name, ...
48,990
def new_alphabet(shift): """ :param shift: int, The magic number that user input to produce shifted. :return: str, a new_alphabet will be returned. """ first_half = ALPHABET[shift:] second_half = ALPHABET[:shift] # first_half = ALPHABET[(26 - shift):] # second_half = ALPHABET[0:(26 - shi...
48,991
def _tensor_equal_tensor(x, y): """ Determine if two tensors are equal. Args: x (Tensor): first input tensor. y (Tensor): second input tensor. Returns: bool, if x == y return true, x != y return false. """ return F.equal(x, y)
48,992
def CleanUnicodeString(s, separator=None): """Return list of words after lowering case and may be removing punctuations. Args: s: a unicode string. separator: default is None which implies separator of whitespaces and punctuation is removed. Returns: Lowered case string after removing runs of ...
48,993
def compute_cumulants(G, mus, R=None, return_R=False): """ Compute the cumulants of a Hawkes process given the integrated kernel matrix `G` and the baseline rate vector `mus` Arguments --------- G : np.ndarray The integrated kernel matrix of shape shape dim x dim mus : np.ndarray ...
48,994
def interp_2d_to_3d(gs, grid, gt): """Interpolate 2D vector to a 3D grid using a georeferenced grid. Parameters ---------- gs : geopandas.GeoSeries Input geopandas GeoSeries grid : array_like 2D array of values, e.g. DEM gt : tuple GDAL-style geotransform coefficients fo...
48,995
def split_log_line(i): """Splits a line at either a period or a colon, depending on which appears first in the line. """ if index_default(i, "apple") < index_default(i, "banana"): a = i.split('apple')[1] # print(a) b = 'apple' + a s.append(b) elif index_default(i, "b...
48,996
async def run_config(config_path: Path) -> None: """Parse a YAML config file, returning the validated ILLIXR system config.""" YamlIncludeConstructor.add_to_loader_class( loader_class=yaml.FullLoader, base_dir=config_path.parent, ) with config_path.open() as f: config = yaml.full_load(f...
48,997
def norecurse(f): """Decorator that keeps a function from recursively calling itself. Parameters ---------- f: function """ def func(*args, **kwargs): # If a function's name is on the stack twice (once for the current call # and a second time for the previous call), then return...
48,998
def test_sudo_path_without_grant(container): """Container should include /opt/conda/bin in the sudo secure_path.""" c = container.run( tty=True, user="root", command=["start.sh", "which", "jupyter"], ) rv = c.wait(timeout=10) assert rv == 0 or rv["StatusCode"] == 0 logs =...
48,999