content
stringlengths
22
815k
id
int64
0
4.91M
def get_response_rows(response, template): """ Take in a list of responses and covert them to SSE.Rows based on the column type specified in template The template should be a list of the form: ["str", "num", "dual", ...] For string values use: "str" For numeric values use: "num" For dual values:...
18,000
def stations_within_radius(stations, centre, r): """function that returns a list of all stations (type MonitoringStation) within radius r of a geographic coordinate x.""" close_stations = [] for station in stations: if haversine(station.coord, centre) < float(r): close_stations.appe...
18,001
def get_pack_display_name(pack_id: str) -> str: """ Gets the display name of the pack from the pack ID. :param pack_id: ID of the pack. :return: Name found in the pack metadata, otherwise an empty string. """ metadata_path = os.path.join(PACKS_FULL_PATH, pack_id, PACK_METADATA_FILE) if pack...
18,002
async def test_delete_requires_admin(opp, opp_ws_client, opp_read_only_access_token): """Test delete requires admin.""" client = await opp_ws_client(opp, opp_read_only_access_token) await client.send_json( {"id": 5, "type": auth_ha.WS_TYPE_DELETE, "username": "test-user"} ) result = await ...
18,003
def test_command_base(run_cli_process_launch_command, fixture_code, generate_calc_job_node): """Test invoking the calculation launch command with only required inputs.""" code = fixture_code('quantumespresso.pw2wannier90').store() calculation = generate_calc_job_node('quantumespresso.pw', test_name='default...
18,004
def tflite_conversion(model, tflite_path, conversion_type="fp32"): """Performs tflite conversion (fp32, int8).""" # Prepare model for inference model = prepare_model_for_inference(model) create_directories([os.path.dirname(tflite_path)]) converter = tf.lite.TFLiteConverter.from_keras_model(model) ...
18,005
def jacobian(model, x, output_class): """ Compute the output_class'th row of a Jacobian matrix. In other words, compute the gradient wrt to the output_class. :param model: forward pass function. :param x: input tensor. :param output_class: the output_fz class we want to compute the gradients. ...
18,006
def get_ctf(bot, trigger): """See the CTF Login Information Params: uname email passwd teamid """ section = 'ctf' # Get section and option from first argument. arg1 = trigger.group(3).split('.') if len(arg1) == 1: section_name, option = "ctf", arg1[0]...
18,007
def render_face_orthographic(mesh, background=None): """ mesh location should be normalized :param mesh: :param background: :return: """ mesh.visual.face_colors = np.array([0.05, 0.1, 0.2, 1]) mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False) # mesh = pyrender.Mesh.from_trimesh(...
18,008
def do_servicegroup_show(cc, args): """Show a Service Group.""" try: servicegroup = cc.smc_servicegroup.get(args.servicegroup) except exc.HTTPNotFound: raise exc.CommandError('Service Group not found: %s' % args.servicegroup) except exc.Forbidden: raise exc.CommandError("Not auth...
18,009
def check_and_join(phrase, symbols=None, filter=None): """ Joins characters of ``phrase`` and if ``symbols`` is given, raises an error if any character in ``phrase`` is not in ``symbols``. Parameters ========== phrase String or list of strings to be returned as a string. symbols ...
18,010
def rigs_from_file(filepath: str, sensor_ids: Optional[Set[str]] = None) -> kapture.Rigs: """ Reads rigs from CSV file. :param filepath: input file path :param sensor_ids: input set of valid sensor ids. If a rig id collides one of them, raise error. If a ...
18,011
def drawLaneOnImage(img): """ Find and draw the lane lines on the image `img`. """ left_fit, right_fit, left_fit_m, right_fit_m, _, _, _, _, _ = findLines(img) output = drawLine(img, left_fit, right_fit) return cv2.cvtColor( output, cv2.COLOR_BGR2RGB )
18,012
def enthalpy_diff(SA, CT, p_shallow, p_deep): """ Calculates the difference of the specific enthalpy of seawater between two different pressures, p_deep (the deeper pressure) and p_shallow (the shallower pressure), at the same values of SA and CT. This function uses the computationally-efficient 48...
18,013
def zipdir(path, zippath): """ walkfiles = os.walk(path) zippath = zipfile.ZipFile(zippath, 'w') for root, dirs, files in walkfiles: for filename in files: zippath.write(os.path.join(root, filename)) """ execStr = ['zip', '-r',zippath, path] print(' '.join(execStr)) proc = subpro...
18,014
def ss(a, axis=0): ### taken from SciPy """Squares each value in the passed array, adds these squares, and returns the result. Parameters ---------- a : array axis : int or None Returns ------- The sum along the given axis for (a*a). """ a, axis = _chk_asarray(a, axis) return numpy.sum(a*a, axis)
18,015
def main(): """main""" args = get_args() tsv_files = args.tsv_file dbname = args.dbname if not os.path.isfile(dbname): print('Bad --dbname "{}"'.format(dbname)) sys.exit(1) db = sqlite3.connect(dbname) for fnum, tsv_file in enumerate(tsv_files): if not os.path.isfi...
18,016
def Journaling_TypeInfo(): """Journaling_TypeInfo() -> RTTI""" return _DataModel.Journaling_TypeInfo()
18,017
def _maven_artifact( group, artifact, version, ownership_tag = None, packaging = None, classifier = None, exclusions = None, neverlink = None, testonly = None, tags = None, flatten_transitive_deps = None, aliases = None): ...
18,018
def docmdnf(cmd): """Execute a command.""" if flag_echo: sys.stderr.write("executing: " + cmd + "\n") if flag_dryrun: return 0 return u.docmdnf(cmd)
18,019
def get_anchors(n): """Get a list of NumPy arrays, each of them is an anchor node set""" m = int(np.log2(n)) anchor_set_id = [] for i in range(m): anchor_size = int(n / np.exp2(i + 1)) for _ in range(m): anchor_set_id.append(np.random.choice(n, size=anchor_size, replace=False...
18,020
def diag_gaussian_log_likelihood(z, mu=0.0, logvar=0.0): """Log-likelihood under a Gaussian distribution with diagonal covariance. Returns the log-likelihood for each dimension. One should sum the results for the log-likelihood under the full multidimensional model. Args: z: The value to compute the l...
18,021
def _filter_option_to_config_setting(flt, setting): """ Encapsulates the logic for associating a filter database option with the filter setting from relay_config :param flt: the filter :param setting: the option deserialized from the database :return: the option as viewed from relay_config """ ...
18,022
def write_config(conf, output_file): """Write documentation to yaml file.""" with open(output_file, 'w') as ofh: yaml.dump(conf, ofh, default_flow_style=False)
18,023
def get_svg(accession, **kwargs): """ Returns a HMM sequence logo in SVG format. Parameters ---------- accession : str Pfam accession for desired HMM. **kwargs : Additional arguments are passed to :class:`LogoPlot`. """ logoplot = plot.LogoPlot(accession, **kwargs) ...
18,024
def wl_to_en( l ): """ Converts a wavelength, given in nm, to an energy in eV. :param l: The wavelength to convert, in nm. :returns: The corresponding energy in eV. """ a = phys.physical_constants[ 'electron volt-joule relationship' ][ 0 ] # J return phys.Planck* phys.c/( a* l* 1e-9 )
18,025
def get_local_address_reaching(dest_ip: IPv4Address) -> Optional[IPv4Address]: """Get address of a local interface within same subnet as provided address.""" for iface in netifaces.interfaces(): for addr in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []): iface = IPv4Interface(addr["...
18,026
def atSendCmdTest(cmd_name: 'str', params: 'list'): """ 发送测试命令,方便调试 ATCore """ func_name = 'atSendCmdTest' atserial.ATraderCmdTest_send(cmd_name, params) res = recv_serial(func_name) atReturnChecker(func_name, res.result) return res.listResult
18,027
def action_pool_nodes_del( batch_client, config, all_start_task_failed, all_starting, all_unusable, nodeid): # type: (batchsc.BatchServiceClient, dict, bool, bool, bool, list) -> None """Action: Pool Nodes Del :param azure.batch.batch_service_client.BatchServiceClient batch_client: b...
18,028
def unlabeled_balls_in_unlabeled_boxes(balls, box_sizes): """ OVERVIEW This function returns a generator that produces all distinct distributions of indistinguishable balls among indistinguishable boxes, with specified box sizes (capacities). This is a generalization of the most common formulation o...
18,029
def find_notebooks(path): """Yield all the notebooks in a directory Yields the path relative to the given directory """ for parent, dirs, files in os.walk(path): if ".ipynb_checkpoints" in parent.split(os.path.sep): # skip accidentally committed checkpoints continue ...
18,030
def get_version(): """Extract current version from __init__.py.""" with open("morphocell/__init__.py", encoding="utf-8") as fid: for line in fid: if line.startswith("__version__"): VERSION = line.strip().split()[-1][1:-1] break return VERSION
18,031
def sessions_speakers(transaction): """ GET /sessions/1/speakers :param transaction: :return: """ with stash['app'].app_context(): speaker = SpeakerFactory() db.session.add(speaker) db.session.commit()
18,032
def run(length, width, height, fps, level, observation_spec): """Spins up an environment and runs the random agent.""" env = deepmind_lab.Lab( level, [observation_spec], config={ 'fps': str(fps), 'width': str(width), 'height': str(height) }) env.reset() agent = ...
18,033
def get_neighbor_v4_by_id(obj_id): """Return an NeighborV4 by id. Args: obj_id: Id of NeighborV4 """ try: obj = NeighborV4.get_by_pk(id=obj_id) except NeighborV4NotFoundError as e: raise NeighborV4DoesNotExistException(str(e)) return obj
18,034
def get_resources_json_obj(resource_name: str) -> Dict: """ Get a JSON object of a specified resource. :param resource_name: The name of the resource. :returns: The JSON object (in the form of a dictionary). :raises Exception: An exception is raised if the specified resources does not exist. ...
18,035
def skip_if(predicate, reason=None): """Skip a test if predicate is true.""" reason = reason or predicate.__name__ def decorate(fn): fn_name = fn.__name__ def maybe(*args, **kw): if predicate(): msg = "'%s' skipped: %s" % (fn_name, reason) raise ...
18,036
def synthesized_uvw(ants, time, phase_dir, auto_correlations): """ Synthesizes new UVW coordinates based on time according to NRAO CASA convention (same as in fixvis) User should check these UVW coordinates carefully: if time centroid was used to compute original uvw coordinates the centroids ...
18,037
def execute_pso_strategy(df, options, topology, retrain_params, commission, data_name, s_test, e_test, iters=100, normalization='exponential'): """ Execute particle swarm optimization strategy on data history contained in df :param df: dataframe with historical data :param options: dict with the followi...
18,038
def human_turn(c_choice, h_choice): """ The Human plays choosing a valid move. :param c_choice: computer's choice X or O :param h_choice: human's choice X or O :return: """ depth = len(empty_cells(board)) if depth == 0 or game_over(board): return # Dictionary of valid moves ...
18,039
def env_get(d, key, default, decoders=decoders, required=None): """ Look up ``key`` in ``d`` and decode it, or return ``default``. """ if required is None: required = isinstance(default, type) try: value = d[key] except KeyError: if required: raise re...
18,040
def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \ tUnion[TMP_RES, tTuple[int, int]]: """ With no = 1, computes ceiling(expr) With no = -1, computes floor(expr) Note: this function either gives the exact result or signals failure. """ from sympy.funct...
18,041
def validate_tree(tree): """Checks the validty of the tree. Parameters ---------- tree : bp.BP The tree to validate """ # this is currently untested since we can't actually parse a tree of this # nature: https://github.com/wasade/improved-octo-waddle/issues/29 if len(tree) <= 1...
18,042
def doPrimaryClick(releaseDelay: Optional[float] = None): """ Performs a primary mouse click at the current mouse pointer location. The primary button is the one that usually activates or selects an item. This function honors the Windows user setting for which button (left or right) is classed as the primary ...
18,043
def inv_last_roundf(ns): """ ns -> States of nibbles Predict the states of nibbles after passing through the inverse last round of SomeCipher. Refer to `last_roundf()` for more details. """ return inv_shift_row(ns)
18,044
def get_screen(name, layer=None): """ :doc: screens Returns the ScreenDisplayable with the given `name` on layer. `name` is first interpreted as a tag name, and then a screen name. If the screen is not showing, returns None. This can also take a list of names, in which case the first screen ...
18,045
def generate_address_full(chance=None, variation=False, format=1): """ Function to generate the full address of the profile. Args: chance: Integer between 1-100 used for realistic variation. (not required) variation: Boolean value indicating whether variation is requested. (optional) format: String value use...
18,046
def add_book(book, order, size, _age = 10): """ Add a new order and size to a book, and age the rest of the book. """ yield order, size, _age for o, s, age in book: if age > 0: yield o, s, age - 1
18,047
def binder_url(repo, branch="master", filepath=None): """ Build a binder url. If filepath is provided, the url will be for the specific file. Parameters ---------- repo: str The repository in the form "username/reponame" branch: str, optional The branch, default "master" ...
18,048
async def on_message_execute(message): """ The on_message function specifically handles messages that are sent to the bot. It checks if the message is a command, and then executes it if it is. :param self: Used to access the class' attributes and methods. :param message: Used to store information a...
18,049
def _create_group_hub_without_avatar(_khoros_object, _api_url, _payload): """This function creates a group hub with only a JSON payload and no avatar image. .. versionadded:: 2.6.0 :param _khoros_object: The core :py:class:`khoros.Khoros` object :type _khoros_object: class[khoros.Khoros] :param _a...
18,050
def ReplaceDirName(rootDir,startNumber=0): """Modify the folder name under the rootDir path. This function just change your Dir name in one loop. rootDir : The dir in your computer. startNumber: The DirName you want start( we set file name into number sequnce.) .If none, default = 0 # Returns...
18,051
def ulstrip(text): """ Strip Unicode extended whitespace from the left side of a string """ return text.lstrip(unicode_extended_whitespace)
18,052
def deploy(verbosity='noisy'): """ Full server deploy. Updates the repository (server-side), synchronizes the database, collects static files and then restarts the web service. """ if verbosity == 'noisy': hide_args = [] else: hide_args = ['running', 'stdout'] with hide(*...
18,053
def clone_dcm_meta(dcm): """ Copy an existing pydicom Dataset as a basis for saving another image :param dcm: the pydicom dataset to be copied :return: """ newdcm = pydi.Dataset() for k, v in dcm.items(): newdcm[k] = v newdcm.file_meta = mk_file_meta() newdcm.is_little_en...
18,054
def test_ingredients_limited_to_user(authenticated_user): """Test that ingredients returned are for authenticated user""" user, client = authenticated_user user2 = get_user_model().objects.create_user("other@test.com", "testpass") Ingredient.objects.create(user=user2, name="banana") ingredient = Ing...
18,055
def run_yosys_with_abc(): """ Execute yosys with ABC and optional blackbox support """ ys_params = create_yosys_params() yosys_template = args.yosys_tmpl if args.yosys_tmpl else os.path.join( cad_tools["misc_dir"], "ys_tmpl_yosys_vpr_flow.ys") tmpl = Template(open(yosys_template, encodin...
18,056
def load_plate(toml_path): """\ Parse a TOML-formatted configuration file defining how each well in a particular plate should be interpreted. Below is a list of the keys that are understood in the configuration file: 'xlsx_path' [string] The path to the XLSX file containing the plate ...
18,057
def reduce_entropy(X, axis=-1): """ calculate the entropy over axis and reduce that axis :param X: :param axis: :return: """ return -1 * np.sum(X * np.log(X+1E-12), axis=axis)
18,058
def compile_pbt(lr: float = 5e-3, value_weight: float = 0.5): """ my default: 5e-3 # SAI: 1e-4 # KataGo: per-sample learning rate of 6e-5, except 2e-5 for the first 5mm samples """ input_shape = (N, N, dual_net.get_features_planes()) model = dual_net.build_model(input_shape) opt = keras....
18,059
def _hostnames() -> List[str]: """Returns all host names from the ansible inventory.""" return sorted(_ANSIBLE_RUNNER.get_hosts())
18,060
def memory(kdump_memory): """Set memory allocated for kdump capture kernel""" config_db = ConfigDBConnector() if config_db is not None: config_db.connect() config_db.mod_entry("KDUMP", "config", {"memory": kdump_memory})
18,061
def seabass_to_pandas(path): """SeaBASS to Pandas DataFrame converter Parameters ---------- path : str path to an FCHECKed SeaBASS file Returns ------- pandas.DataFrame """ sb = readSB(path) dataframe = pd.DataFrame.from_dict(sb.data) return dataframe
18,062
def countVisits(item, value=None): """This function takes a pandas.Series of item tags, and an optional string for a specific tag and returns a numpy.ndarray of the same size as the input, which contains either 1) a running count of unique transitions of item, if no target tag is given, or 2) a running ...
18,063
def test_atomic_unsigned_short_min_exclusive_4_nistxml_sv_iv_atomic_unsigned_short_min_exclusive_5_1(mode, save_output, output_format): """ Type atomic/unsignedShort is restricted by facet minExclusive with value 65534. """ assert_bindings( schema="nistData/atomic/unsignedShort/Schema+Instan...
18,064
def test_run_inference(ml_runner_with_container: MLRunner, tmp_path: Path) -> None: """ Test that run_inference gets called as expected. """ def _expected_files_exist() -> bool: output_dir = ml_runner_with_container.container.outputs_folder if not output_dir.is_dir(): return ...
18,065
def gen_accel_table(table_def): """generate an acceleration table""" table = [] for i in range(1001): table.append(0) for limit_def in table_def: range_start, range_end, limit = limit_def for i in range(range_start, range_end + 1): table[i] = limit return table
18,066
def dataset_constructor( config: ml_collections.ConfigDict, ) -> Tuple[ torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset ]: """ Create datasets loaders for the chosen datasets :return: Tuple (training_set, validation_set, test_set) """ dataset = { "AddProb...
18,067
def ensemble_log_params(m, params, hess=None, steps=scipy.inf, max_run_hours=scipy.inf, temperature=1.0, step_scale=1.0, sing_val_cutoff=0, seeds=None, recalc_hess_alg = False, recalc_func=None, save...
18,068
def process(actapi, country_list): """Fetch ISO-3166 list, process and print generic_uploader data to stdout""" facts_added = {} for c_map in country_list: for location_type, location in c_map.items(): if not location: continue # Skip locations with empty values ...
18,069
def read_from_url(url): """Read from a URL transparently decompressing if compressed.""" yield smart_open.open(url)
18,070
def issue_config_exists(repo_path): """ returns True if the issue template config.yml file exists in the repo_path """ path_to_config = repo_path + "/.github/ISSUE_TEMPLATE/config.yml" return os.path.exists(path_to_config)
18,071
def test_safe_fn(): """ Shows how the safe_fn guards against all exceptions. :return: """ assert celldb._safe_fn(pow, 2, "a") is None
18,072
def _read(fd): """Default read function.""" return os.read(fd, 1024)
18,073
def get_metrics(actual_classes, pred_classes): """ Function to calculate performance metrics for the classifier For each class, the following is calculated TP: True positives = samples that were correctly put into the class TN: True negatives = samples that were correctly not put into the class...
18,074
def load_modules(): """Imports all modules from the modules directory.""" for module in os.listdir('modules/'): if not module.startswith('_') and module.endswith('.py'): __import__('modules.{}'.format(module.split('.')[0]))
18,075
def extract_tika_meta(meta): """Extracts and normalizes metadata from Apache Tika. Returns a dict with the following keys set: - content-type - author - date-created - date-modified - original-tika-meta The dates are encoded in the ISO format.""" def _get_flat(di...
18,076
def update_table(key_id,guess,correct): """ Updates the d- if wrong: adds guess if right: adds +1 for right guesses """ try: client = MongoClient('localhost') # get our client db = client.quickdraw # get our database if(correct==False): db.qd.update_one({'key...
18,077
def __gen_pause_flow(testbed_config, src_port_id, flow_name, pause_prio_list, flow_dur_sec): """ Generate the configuration for a PFC pause storm Args: testbed_config (obj): L2/L3 config of a T0 testbed src_...
18,078
def plot_spectra(obs, model): """Plot two spectra.""" plt.plot(obs.xaxis, obs.flux, label="obs") plt.plot(model.xaxis, model.flux, label="model") plt.legend() plt.show()
18,079
def move_calculator(): """ A function that will calculate the best moves for the cuurent position.\n This works by: - Will check all the moves in the current position """
18,080
def parse_str_to_bio(str, dia_act): """ parse str to BIO format """ intent = parse_intent(dia_act) w_arr, bio_arr = parse_slots(str, dia_act) bio_arr[-1] = intent return ' '.join(w_arr), ' '.join(bio_arr), intent
18,081
def train_early_stop( update_fn, validation_fn, optimizer, state, max_epochs=1e4, **early_stop_args ): """Run update_fn until given validation metric validation_fn increases. """ logger = Logger() check_early_stop = mask_scheduler(**early_stop_args) for epoch in jnp.arange(max_epochs): (...
18,082
def get_povm_object_names() -> List[str]: """Return the list of valid povm-related object names. Returns ------- List[str] the list of valid povm-related object names. """ names = ["pure_state_vectors", "matrices", "vectors", "povm"] return names
18,083
def choose(a,b): """ n Choose r function """ a = op.abs(round(a)) b = op.abs(round(b)) if(b > a): a, b = b, a return factorial(a) / (factorial(b) * factorial(a-b))
18,084
def pad_and_stack_list_of_tensors(lst_embeddings: List[torch.Tensor], max_sequence_length: Optional[int] = None, return_sequence_length: bool = False): """ it takes the list of embeddings as the input, then applies zero-padding and stacking to transform it as @param lst_em...
18,085
def bq_solid_for_queries(sql_queries): """ Executes BigQuery SQL queries. Expects a BQ client to be provisioned in resources as context.resources.bigquery. """ sql_queries = check.list_param(sql_queries, 'sql queries', of_type=str) @solid( input_defs=[InputDefinition(_START, Nothing)]...
18,086
def RestartNetwork(): """Restarts networking daemon.""" logging.warning('Restart networking.') try: subprocess.check_output(['/etc/init.d/networking', 'restart']) if HasIp(): logging.info('Network is back') except subprocess.CalledProcessError as e: # This is expected in some network environme...
18,087
def mock_accession_unreplicated( mocker: MockerFixture, mock_accession_gc_backend, mock_metadata, lab: str, award: str, ) -> Accession: """ Mocked accession instance with dummy __init__ that doesn't do anything and pre-baked assembly property. @properties must be patched before instantia...
18,088
def get_prepared_statement(statement_name: Optional[str] = None, work_group: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPreparedStatementResult: """ Resource schema for AWS::Athena::PreparedStatement :param str st...
18,089
def set_initial_current_workspace(db_workspace): """ :param workspace: :return: """ sql_create_current_workspace = ''' INSERT OR IGNORE INTO current_workspace(current_db) VALUES(?) ''' CUR.execute(sql_create_current_workspace,db_workspace) CONNECTION.commit()
18,090
def handle_col(element, box, _get_image_from_uri, _base_url): """Handle the ``span`` attribute.""" if isinstance(box, boxes.TableColumnBox): integer_attribute(element, box, 'span') if box.span > 1: # Generate multiple boxes # http://lists.w3.org/Archives/Public/www-style/...
18,091
def get_dotted_field(input_dict: dict, accessor_string: str) -> dict: """Gets data from a dictionary using a dotted accessor-string. Parameters ---------- input_dict : dict A nested dictionary. accessor_string : str The value in the nested dict. Returns ------- dict ...
18,092
def separa_frases(sentenca): """[A funcao recebe uma sentenca e devolve uma lista das frases dentro da sentenca] Arguments: sentenca {[str]} -- [recebe uma frase] Returns: [lista] -- [lista das frases contidas na sentença] """ return re.split(r'[,:;]+', sentenca)
18,093
def read_datasets(path=None, filename="datasets.json"): """Read the serialized (JSON) dataset list """ if path is None: path = _MODULE_DIR else: path = pathlib.Path(path) with open(path / filename, 'r') as fr: ds = json.load(fr) # make the functions callable for _, ...
18,094
def get_solvents(reaction): """Return solvents involved in the specified reaction.""" for df in reaction.data_fields: if SOLVENT_RE.match(df): n = SOLVENT_RE.search(df).group('N') name_field = 'RXN:VARIATION:STEPNO:SOLVENT(' + n + '):MOL:SYMBOL' if name_field in...
18,095
def test_negative_format_postcode2(formatting_negative_value_special_char): """Function to test format_postcode method for negative cases(Special chars) arguments: formatting_positive_value -- list of post codes with special char """ postcode = Postcode() print(postcode.format_p...
18,096
def as_actor(input, actor) : """Takes input and actor, and returns [as <$actor>]$input[endas].""" if " " in actor : repla = "<%s>"%actor else : repla = actor return "[as %s]%s[endas]" % (repla, input)
18,097
def error_403(request): """View rendered when encountering a 403 error.""" return error_view(request, 403, _("Forbidden"), _("You are not allowed to acces to the resource %(res)s.") % {"res": request.path})
18,098
def restarts(**bindings): """Provide restarts. Known as `RESTART-CASE` in Common Lisp. Roughly, restarts can be thought of as canned error recovery strategies. That's the most common use case, although not the only possible one. You can use restarts whenever you'd like to define a set of actions to han...
18,099