content
stringlengths
22
815k
id
int64
0
4.91M
async def get_category(category): """ Retrieves the data for the provided category. The data is cached for 1 hour. :returns: The data for category. :rtype: dict """ # Adhere to category naming standard. category = category.lower() # URL to request data from. url = BASE_URL + "time...
31,700
def __round(x): """ rounds to the nearest 0.25 :param x: <float> number. :return: <float> rounded number. """ print(round(x*4)/4)
31,701
def func_simple_sca_batch_scanner(root_directory): """ 使用SCA逐一扫描目录下所有的文件夹,比如:repos/app1 repos/app2 repos/app3 :param root_directory: 指定目录 :return: """ root_directory = Path(root_directory) repos = [_ for _ in os.listdir(root_directory) if os.path.isdir(os.path.join(root_directory, _))] f...
31,702
def plot_data(): """Plots the selected data""" if X_SELECT.get() != "" and Y_SELECT.get() != "": x_data = DATA_DICT[X_SELECT.get()] y_data = DATA_DICT[Y_SELECT.get()] # print(x_data, y_data) plot_name = Y_SELECT.get() + ' vs ' + X_SELECT.get() plt.figure(num=plot_name) #...
31,703
def discover_modules(mnodule_name): """ Recursively import a module and all sub-modules in the module :param mnodule_name: module name :return: modules from the package """ module = import_module(mnodule_name) yield module if getattr(module, '__path__', None): for _, name, _ i...
31,704
def plot_ellipses_area( params, depth="None", imin=0, imax=398, jmin=0, jmax=898, figsize=(10, 10) ): """Plot ellipses on a map in the Salish Sea. :arg params: a array containing the parameters (possibly at different depths and or locations). :type param: np.array :arg depth: The depth at w...
31,705
def get_repo_owner_from_url(url: str) -> str: """Get git repository owner from git remote url. Args: url: (str) git remote url. Can be "git@" or "https://". Returns: str: git repository owner (user or organization). """ last_slash_index = url.rfind('/') # IF HTTPS: https://git...
31,706
def radec2lb(ra, dec, radian=False, FK5=False): """ Convert (ra, dec) into Galactic coordinate (l, b). Parameters ---------- ra : float or list or array RA Coordinates in degree dec : float or list or array DEC Coordinates in degree Returns ------- l : float or list...
31,707
def populate_workflow_request_body(manifest_data: Dict): """ Populate workflow request body with the passed data according API specification :param data: item data from manifest files :return: populated request :rtype: dict """ request = { "runId": "", "execu...
31,708
def openImage(filename, videoFrameTime=None, isMask=False, preserveSnapshot=False): """ Open and return an image from the file. If the file is a video, find the first non-uniform frame. videoFrameTime, integer time in milliseconds, is provided, then find the frame after that point in time preserveSnapsh...
31,709
def is_leap_year(year): """ Is the current year a leap year? Args: y (int): The year you wish to check. Returns: bool: Whether the year is a leap year (True) or not (False). """ if year % 4 == 0 and (year % 100 > 0 or year % 400 == 0): return True return False
31,710
def delta2bbox(src_bbox, delta): """ src_bbox: (N_bbox, 4) delta: (N_bbox, 4) """ #---------- debug assert src_bbox.shape == delta.shape assert isinstance(src_bbox, np.ndarray) assert isinstance(delta, np.ndarray) #---------- src_bbox_h = src_bbox[:,2] - src_bbox[:,0] src...
31,711
def blank_dog(): """Set up (16, 3) array of dog with initial joint positions""" length = 0.5 width = 0.2 ankle_length = 0.1 ankle_to_knee = 0.2 knee_to_shoulder = 0.05 O = Vector(0,0,0) # origin out = [] for lengthwise in [-1, +1]: for widthwise in [+1, -1]: foot = O + length * Vector(lengthwise/2,0,0) ...
31,712
def pandoc_command(event, verbose=True): #@+<< pandoc command docstring >> #@+node:ekr.20191006153547.1: *4* << pandoc command docstring >> """ The pandoc command writes all @pandoc nodes in the selected tree to the files given in each @pandoc node. If no @pandoc nodes are found, the command loo...
31,713
def _update_testcase_list(options: dict): """ Use provided config options to find the final list of test cases to use for running the workflows. The following implementation assumes options `--testcases` and `--testcase-file` are mutually exclusive. """ if options.get("testcases"): retur...
31,714
def stop_worker(config, *, worker_ids=None): """ Stop a worker process. Args: config (Config): Reference to the configuration object from which the settings for the worker are retrieved. worker_ids (list): An optional list of ids for the worker that should be stopped. """ if...
31,715
def random_majority_link_clf(): """ for link classification we do not select labels from a fixed distribution but instead we set labels to the number of possible segments in a sample. I.e. we only predict a random link out of all the possible link paths in a sample. """ def clf(labels, k:int...
31,716
def configure_logger(logger_args): """Configures the global Python logger object.""" logger_val = ArgumentsValidator(logger_args, "Logger arguments") with logger_val: show_debug_logs = logger_val.get("show_debug_logs", ATYPE_BOOL, False, default=False) show_date = logger_val.get("show_date", ATYPE_BOOL...
31,717
def do_snapshot_force_delete(cs, args): """Attempt force-delete of snapshot, regardless of state.""" snapshot = _find_share_snapshot(cs, args.snapshot) snapshot.force_delete()
31,718
def db_to_df(db_table): """Reads in a table from the board games database as pandas DataFrame""" query = f"SELECT * FROM {db_table};" pd_table = pd.read_sql(query, DB) return pd_table
31,719
def server(ip, port, channel, token, single, config, tmux): """Runs the discord bot server.""" if single: validate_single = {"channel": channel, "token": token} for key, arg in validate_single.items(): assert ( len(arg[0]) > 0 ), f"{key} is empty. Please a...
31,720
def kill_master_if_running(identifier="lunchrc", directory=None): """ Given a lunch master identifier and a PID file directory, kills the master. """ pid_file = gen_pid_file_path(identifier, directory) deferred = defer.Deferred() send_sigkill_at = time.time() + 20.0 # wait 20 seconds before to u...
31,721
def player_input_choice() -> int: """Function that takes the player input as the position for his|her marker""" marker_position = 0 while marker_position not in range(1, 10) or not tic_tac_toe.check_the_cell(marker_position): marker_position = int(input("Choose the position for your marker from 1 to...
31,722
def write_all_summaries(ID, stats_pdframe, output_folder): """ Docstring Args: ID: str, stats_pdframe is pd dataframe (summary stats) output_path should be the folder path where you want to save the output Return: write out as csv files named by user ID """ if os.path.exists(output_fol...
31,723
def increment_datetime_by_string(mydate, increment, mult=1): """Return a new datetime object incremented with the provided relative dates specified as string. Additional a multiplier can be specified to multiply the increment before adding to the provided datetime object. Usage: ...
31,724
def get_regularization_loss(scope=None, name="total_regularization_loss"): """Gets the total regularization loss. Args: scope: An optional scope name for filtering the losses to return. name: The name of the returned tensor. Returns: A scalar regularization loss. """ losses = get_regularization_...
31,725
def Make_Sequential(sents, **kwargs): """ Make sequential parses (each word simply linked to the next one), to use as baseline """ output_path = kwargs.get("output_path", os.environ["PWD"]) sequential_parses = [] for sent in sents: parse = [["0", "###LEFT-WALL###", "1", sen...
31,726
def test_handle_set_handle_set_characteristics_unencrypted(driver): """Verify an unencrypted set_characteristics.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 service = acc.driver.loader.get_service("GarageDoorOpener") acc.add_service(service) driver.add_accessory(acc) h...
31,727
def test_keypoint_nn(model): """Wrapper for KeypointModelTest""" KeypointModelTest(model)()
31,728
def storage_backend_get_all(context, inactive=False, filters=None): """Get all storage backends""" return IMPL.storage_backend_get_all(context, inactive, filters)
31,729
def get_date_opm_status_response(intent, session): """ Gets the current status of opm for the day """ card_title = "OPM Status Result" session_attributes = {} speech_output = "I'm not sure which o. p. m. status you requested. " \ "Please try again." reprompt_text = "I'm not s...
31,730
def oauth_api_request(method, url, **kwargs): """ when network error, fallback to use rss proxy """ options = _proxy_helper.get_proxy_options() client = RSSProxyClient(**options, proxy_strategy=_proxy_strategy) return client.request(method, url, **kwargs)
31,731
def validate_cached(cached_calcs): """ Check that the calculations with created with caching are indeed cached. """ valid = True for calc in cached_calcs: if not calc.is_finished_ok: print('Cached calculation<{}> not finished ok: process_state<{}> exit_status<{}>' ...
31,732
def SplitRecursively(x, num_splits, axis=-1): """Splits Tensors in 'x' recursively. Args: x: a Tensor, or a list or NestMap containing Tensors to split. num_splits: number of splits per Tensor. axis: the split axis. Returns: A list of split values of length 'num_splits'. - If 'x' is a Tenso...
31,733
def calc_global_rwr(events, tslsi_anom, tas_anom, weights, regrid_model, ndays_dry=_NDAYS_DRY, ndays_ante=_NDAYS_ANTE, rwr_beg=_RWR_BEG, rwr_end=_RWR_END, modis_out=False, file_out_rwr=None, file_out_modis=None): """ Calculate RWR f...
31,734
def generate_entry(request, properties, data, mtime=None): """ Takes a properties dict and a data string and generates a generic entry using the data you provided. :param request: the Request object :param properties: the dict of properties for the entry :param data: the data content for the ...
31,735
def info(): """Refresh teh client session using the refresh token""" global client client = client.refresh_session(app_id, app_secret) return "Refreshed"
31,736
def weight_point_in_circle( point: tuple, center: tuple, radius: int, corner_threshold: float = 1.5 ): """ Function to decide whether a certain grid coordinate should be a full, half or empty tile. Arguments: point (tuple): x, y of the point to be tested ...
31,737
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
31,738
def esmf_interp_points(ds_in, locs_lon, locs_lat, lon_field_name='lon', lat_field_name='lat'): """Use ESMF toolbox to interpolate grid at points.""" # generate grid object grid = esmf_create_grid(ds_in[lon_field_name].values.astype(np.float), ds_in[lat_field_name...
31,739
def update_loan_record(id_: int, loan_record: LoanRecord) -> bool: """Update a loan record from the database Args: id_: loan record id which wants to be modified. loan_record: new information for updating.""" updated_data = {key: value for key, value in loan_record.items() if value is not None} # ...
31,740
def check_results(results): """Examines a list of individual check results and returns an overall result for all checks combined. """ if CheckResults.SCALE_UP in results: return CheckResults.SCALE_UP if all(r == CheckResults.SCALE_DOWN for r in results): return CheckResults.SCALE_DOW...
31,741
def disk_usage(path): """returns disk usage for a path""" total = os.path.getsize(path) if os.path.isdir(path): for filename in os.listdir(path): child_path = os.path.join(path, filename) total += disk_usage(child_path) print(f"{total:<10} {path}") return total
31,742
def mark_sent(email_id, db): """Mark an email as sent in the database.""" query_string = "UPDATE emails SET sent=NOW() WHERE id = {};".format(email_id) db.execute(query_string)
31,743
def edit_route(link_id): """edit link""" link = dynamo.tables[TABLE_NAME].get_item(Key={'id': link_id})['Item'] form = LinkForm(link=link['link'], tags=','.join(link['tags'])) if form.validate_on_submit(): link, tags = form.parsed_data() dynamo.tables[TABLE_NAME].update_item( ...
31,744
def build_empty_pq(): """Build empty pq.""" return PriorityQ()
31,745
def add_flags(flags): """Add KZC flags""" def f(test, way): test.args += flags return f
31,746
def extract_stackstring(f, bb): """ check basic block for stackstring indicators """ if _bb_has_stackstring(f, bb): yield Characteristic("stack string"), bb.va
31,747
async def goto(ctx, channel: discord.TextChannel): """Tell Amy to go to another channel""" change_channel(channel) await ctx.send('*Walks to ' + channel.mention + '.*')
31,748
def RunProcess(cmd, stdinput=None, env=None, cwd=None, sudo=False, sudo_password=None): """Executes cmd using suprocess. Args: cmd: An array of strings as the command to run stdinput: An optional sting as stdin env: An optional dictionary as the environment cwd: An optional string as...
31,749
def general_output(string): """prints string on cmd""" string = ownfunctions.replace_signs(string) print(string)
31,750
def public_jsonp_service(view): """ More explicitly named to call attention to the extra little p """ return _json_service_wrapper(JSONPResponse, view)
31,751
def make_submission(predictions, index2playlist, index2trackid, outfile=None, topk=500): """ Writes the predictions as submission file to disk """ print("Sorting top {} items for each playlist".format(topk)) __, topk_iy = argtop...
31,752
def test_convert_wrong_path(mock_app): """test the command with missing args""" runner = mock_app.test_cli_runner() # Provide a non-valid path to a panel file result = runner.invoke(cli, ["convert", "wrong/path/to/file"]) assert result.exit_code != 0 assert "Could not open file: wrong/path/to/f...
31,753
def chunks(iterable, size): """Generator which chunks data into chunks of given size.""" it = iter(iterable) while True: chunk = tuple(islice(it, size)) if not chunk: return yield chunk
31,754
def load_network(): """ Load the network. After calling this function, facebook.network points to a networkx object for the facebook data. """ load_features() load_nodes() load_edges()
31,755
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the FiveM sensor platform.""" coordinator = hass.data[DOMAIN][entry.entry_id] # Add sensor entities. async_add_entities( [FiveMSensorEntity(coordinator...
31,756
def manage_data(xls_file: str) -> list: """ 转换xls手动标注的数据为待处理的格式 :param xls_file: 目标文件路径 :return: 转换后的字典列表 """ f = pd.read_excel(xls_file, index=False) cnt = 0 result = [] while cnt < len(f) - 1: if f.text[cnt] == f.text[cnt + 1]: temp_dic = {'text': f.text[cnt], '...
31,757
def get_arrival_times(inter_times): """Convert interevent times to arrival times.""" return inter_times.cumsum()
31,758
def generate_custom_background(size, background_color, nb_blobs=3000, kernel_boundaries=(50, 100)): """ Generate a customized background to fill the shapes Parameters: background_color: average color of the background image nb_blobs: number of circles to draw ker...
31,759
def rotate_z(domain, nrot=4): """take BoxCollection and return equivalent CylinderCollection by rotating about the second axis. thus, transform coordinates of points like (x, z) --> (x, 0, z).""" return rotate(domain, d=1, nrot=nrot)
31,760
def test_unsaved_filing_lock(session): """Assert that an unsaved filing, even with an invoice, is not locked.""" # not locked filing = Filing() filing.payment_token = 'payment_token' assert not filing.locked
31,761
def fetch_rib(config): """ Fetch the Internet routing table, as observed by BGP collectors. """ cleanup_files(config) download_ribs(config) convert_ribs(config)
31,762
def filter_roi(roi_data, nb_nonzero_thr): """Filter slices from dataset using ROI data. This function filters slices (roi_data) where the number of non-zero voxels within the ROI slice (e.g. centerline, SC segmentation) is inferior or equal to a given threshold (nb_nonzero_thr). Args: roi_data...
31,763
def mdadm_status(): """ Check the status of mdadm managed disks. Example Output: Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10] md0 : active raid1 sdc1[1] sdb1[0] 9766302720 blocks super 1.2 [2/2] [UU] bitmap: 0/73 pages [0KB], 65536KB chun...
31,764
def postprocess_relative_symlinks(logger, artifact_dir, filename): """ Turns absolute symlinks that points inside the artifact_dir into relative symlinks, and gives an error on symlinks that point out of the artifact """ if os.path.islink(filename): target = os.readlink(filename) if ...
31,765
def from_numpy(shape, dt): """ Upcast a (shape, dtype) tuple if possible. >>> from_numpy((5,5), dtype('int32')) dshape('5, 5, int32') """ dtype = np.dtype(dt) if dtype.kind == 'S': measure = String(dtype.itemsize, 'A') elif dtype.kind == 'U': measure = String(dtype.item...
31,766
def ParseArgs(): """Parse the command line options.""" option_parser = optparse.OptionParser() option_parser.add_option( '--from', dest='sender', metavar='EMAIL', help='The sender\'s email address') option_parser.add_option( '--to', action='append', metavar='EMAIL', dest='recipients', default=...
31,767
def set_conf(key, value, conf=None): """ Set configuration key. """ if conf is None: conf = global_config *base, name = key.split('.') data = conf for k in base: data = data.setdefault(k, {}) data[name] = value conf.save()
31,768
def train_perception(base_dir, save_path, batch_size=32, random_state=0, lr=0.01, optim='Adam', epochs=100): """Trains the Perception network Sample command: python train_perception.py /kaggle/input/simulation/perception_data/ /kaggle/working/ \ --batch-size 64\ --random-...
31,769
def define_components(mod): """ Adds components to a Pyomo abstract model object to force discrete builds for generation technologies that have g_unit_size specified. Unless otherwise stated, all power capacity is specified in units of MW and all sets and parameters are mandatory. NEW_PROJ_BUI...
31,770
def pyramidnet110_a84_cifar100(classes=100, **kwargs): """ PyramidNet-110 (a=84) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default ...
31,771
def contains_vendored_imports(python_path): """ Returns True if ``python_path`` seems to contain vendored imports from botocore. """ # We're using a very rough heuristic here: if the source code contains # strings that look like a vendored import, we'll flag. # # Because Python is dynamic, t...
31,772
def filter_uniq(item): """Web app, feed template, creates unique item id""" detail = item['item'] args = (item['code'], item['path'], str(detail['from']), str(detail['to'])) return ':'.join(args)
31,773
def load_pickle(filename, verbose=2, use_joblib=False): """ Note: joblib can be potentially VERY slow. """ with open(filename, 'rb') as file: if verbose >= 2: start = time.time() logging.info(f'Loading PICKLE from {filename}...') if use_joblib: war...
31,774
def test_cards(fabdb): """ Test the cards function """ cards = fabdb.cards() assert isinstance(cards, dict) assert len(cards['data']) > 0
31,775
async def make_match(*args, register=False, **kwargs) -> Match: """Create a Match object. There should be no need to call this directly; use matchutil.make_match instead, since this needs to interact with the database. Parameters ---------- racer_1_id: int The DB user ID of the first racer...
31,776
def is_anonymous(context: TreeContext) -> bool: """Returns ``True`` if the current node is anonymous.""" # return context[-1].anonymous tn = context[-1].tag_name return not tn or tn[0] == ':'
31,777
def expand_to_beam_size(tensor, beam_size): """Tiles a given tensor by beam_size.""" tensor = tf.expand_dims(tensor, axis=1) tile_dims = [1] * tensor.shape.ndims tile_dims[1] = beam_size return tf.tile(tensor, tile_dims)
31,778
def saveLayer_PDN(fileName: str, layeredImage: LayeredImage) -> None: """Save a layered image as .pdn.""" del fileName, layeredImage Logger(FHFormatter()).logPrint("Saving PDNs is not implemented in pypdn", LogType.ERROR) raise NotImplementedError
31,779
def get_vignettes( h5_file, bed_file, tmp_dir=".", importance_filter=True, rsid_to_genes=None, ensembl_to_hgnc=None): """get the example indices at the locations of interest """ # prefix (scanmotifs) dirname = h5_file.split("/")[-2] print dirname ...
31,780
def delete_cluster(access_token, project_id, cluster_id): """删除集群""" url = f"{BCS_CC_API_PRE_URL}/projects/{project_id}/clusters/{cluster_id}/" params = {"access_token": access_token} return http_delete(url, params=params)
31,781
def test_hello(): """Should call hello end point""" client = flask_basic_restx_app.app.test_client() result = client.get("/hello") assert result.json == {"hello": "world"}
31,782
def modifMail(depute, mail = MAIL): """ modifMail renvoit une chaine de caractères d'un mail personnélisé pour chaque députés des comissions choisies Prend en entrée : infoDeput : un tableau de tableau avec les données des députés. mail : l'adresse d'un fichier txt remp...
31,783
def atoi(s, base=None): # real signature unknown; restored from __doc__ """ atoi(s [,base]) -> int Return the integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chos...
31,784
def add_to_command_lookup(command, entity): """Add discovered command to lookup """ commands = COMMAND_LOOKUP if command in commands: commands[command].append(entity) else: commands[command] = [entity]
31,785
def gzip_requested(accept_encoding_header): """ Check to see if the client can accept gzipped output, and whether or not it is even the preferred method. If `identity` is higher, then no gzipping should occur. """ encodings = parse_encoding_header(accept_encoding_header) # Do the actual co...
31,786
def test_vwprocess(model_class): """ Test whether results are same as using vw command directly: run 'vw -q :: -p /dev/stdout --quiet' command: 0 1.0 |u u1 |i i1 1 1.0 |u u1 |i i2 1 1.0 |u u1 |i i3 1 1.0 |u u2 |i i1 1 1.0 |u u2 |i i2 0 1.0 |u u2 |i i3 |u u1 |i i1 |u u1 |i i2 |u u1 |i i3 |u u2 |i i1 |u ...
31,787
async def load(ctx, extension): """Load specified cog""" extension = extension.lower() bot.load_extension(f'cogs.{extension}') await ctx.send('{} has been loaded.'.format(extension.capitalize()))
31,788
def create_logger(name="dummy", level=logging.DEBUG, record_format=None): """Create a logger according to the given settings""" if record_format is None: record_format = "%(asctime)s\t%(levelname)s\t%(message)s" logger = logging.getLogger("modbus_tk") logger.setLevel(level) formatter = logg...
31,789
def precip_units(units): """ Return a standardized name for precip units. """ kgm2s = ['kg/m2/s', '(kg/m^2)/s', 'kg/m^2/s', 'kg m^-2 s^-1', 'kg/(m^2 s)', 'kg m-2 s-1'] mmday = ['mm/day', 'mm day^-1'] if units.lower() in kgm2s: return 'kg m^-2 s^-1' elif units.lower() in...
31,790
def validate_cfg(cfg): """Validate config content.""" _validate_agent_cfg(cfg)
31,791
def exportSiteProperties(context): """ Export site properties as an XML file. """ site = context.getSite() logger = context.getLogger('properties') exporter = queryMultiAdapter((site, context), IBody) if exporter is None: logger.warning('Export adapter missing.') return con...
31,792
def enumerate_quantities( df: pd.DataFrame, cols: Union[List[str], None] = None, qty_col: str = "quantity" ) -> pd.DataFrame: """Creates new dataframe to convert x,count to x*count.""" if not cols: raise ValueError("parameter cols must be an iterable of strings") new_cols: List = [ sum(...
31,793
def calcul_acc(labels, preds): """ a private function for calculating accuracy Args: labels (Object): actual labels preds (Object): predict labels Returns: None """ return sum(1 for x, y in zip(labels, preds) if x == y) / len(lab...
31,794
def makeMolFromAtomsAndBonds(atoms, bonds, spin=None): """ Create a new Molecule object from a sequence of atoms and bonds. """ mol = Molecule(pybel.ob.OBMol()) OBMol = mol.OBMol for atomicnum in atoms: a = pybel.ob.OBAtom() a.SetAtomicNum(atomicnum) OBMol.AddAtom(a) ...
31,795
def alpha_040(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: ((-1\* rank(stddev(high, 10)))\* correlation(high, volume, 10)) """ enddate = to_date_str(enddate) func_name...
31,796
def get_preprocessor(examples, tokenize_fn, pad_ids): """ Input: examples: [List[str]] input texts tokenize_fn: [function] encodes text into IDs Output: tf input features """ def generator(): for example in examples: tokens = tokenize_fn(example) yield pad...
31,797
def is_propositional_effect(eff: BaseEffect): """ An effect is propositional if it is either an add or a delete effect. """ return isinstance(eff, (AddEffect, DelEffect))
31,798
def read_user(msg): """Read user input. :param msg: A message to prompt :type msg: ``str`` :return: ``True`` if user gives 'y' otherwhise False. :rtype: ``bool`` """ user_input = input("{msg} y/n?: ".format(msg=msg)) return user_input == 'y'
31,799