content
stringlengths
22
815k
id
int64
0
4.91M
def predict_breed_transfer(img_path): """load the image and return the predicted breed""" #Transform as per model_transfer transformed = transforms.Compose([ transforms.Resize((224,224)), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) image = transformed...
76,000
def get_mapvars(mapfile): """Read the sugar .map file and return a dictionary where the key is the variable name and the value is the (start,r0,r1) where r0 is the first ordinal and r1 is the last. Sugar uses uniary encoding.""" mapvars = {} with open(mapfile,"r") as f: for line in f: ...
76,001
def split_data(features, objectives, train_ratio): """Split data into a fitting and training set""" assert len(features) == len(objectives) total_envs = len(features) training_index = int(train_ratio * total_envs) X = np.copy(features[:training_index]) Y = np.copy(objectives[:training_index]) ...
76,002
def get_connection_args(dbms_config: Dict) -> Dict: """Fill "_var"-suffixed configuration items from environment variables""" if "options" not in dbms_config: return {} new_options = {} key: str for key, value in dbms_config["options"].items(): if key.endswith("_var"): ne...
76,003
def _windows_31j(codec_name): """ Windows-31J用の検索関数。 一番近いと思われるShift_JISにマッピングする。 :param codec_name: コーデック名 :type codec_name: str :return: Windows-31Jが指定された場合はShift_JIS、それ以外の場合はNone :rtype: codecs.CodecInfo """ # Windows-31JをShift_JISにマッピングする if codec_name.lower() == 'windows-31j...
76,004
def delete(server_id, **kwargs): """Delete server.""" url = '/servers/{server_id}'.format(server_id=server_id) return url, {}
76,005
def clean_tracklisting(string): """Clean tracklisting in track name: 'A1.', 'A2.', etc """ result = re.search(r'^([ABCD]{1}[1234]{0,1}\.\s?).*$', string, re.IGNORECASE) if result is not None: tracklisting = result.groups()[0] string = string.replace(tracklisting, '') return string
76,006
def T2_limit(conf_level: float = 0.95, n_components: int = 0, n_rows: int = 0) -> float: """Returns the Hotelling's T2 value at the given level of confidence. Parameters ---------- conf_level : float, optional Fractional confidence limit, less that 1.00; by default 0.95 Returns -------...
76,007
def names_limit( names: list[str], min: int, max: int = __input_files_max__ ) -> tuple[list[str], ErrMsg]: """清除 names 里的空字符串,并且限定其上下限。""" temp = map(lambda name: name.strip(), names) names = list(filter(lambda name: name != "", temp)) expected = "" size = len(names) if min == max and size ...
76,008
def return_plot_and_view_data(view_dict: dict, *args, **kwargs) -> tuple: """ This function will take in a dict with 2 keys 'master' and 'primary_keys' from 'multiple_result_view' and do the following: 1) clean up the data for unavailable and duplicate keys 2) create and returns the plot 3) calc...
76,009
def num_to_emoji(x: int) -> str: """Convet int to emoji.""" if x <= 20: return { -1: "💣", 0: "🟦", 1: "1️⃣", 2: "2️⃣", 3: "3️⃣", 4: "4️⃣", 5: "5️⃣", 6: "6️⃣", 7: "7️⃣", 8: "8️⃣", ...
76,010
def __generate_permissions_dataframe(_permissions_dict_list): """This function converts a list of dictionaries containing space permissions into a pandas dataframe. .. deprecated:: 2.0.0 The :py:func:`khorosjx.places.spaces.__generate_permissions_dataframe` function should be used. :param _permissi...
76,011
def is_in_period(month, period): """Return which months fall within a specified group of calendar months. Parameters ---------- month : int or iterable of ints One or a series of calendar month numbers [1..12]. period : tuple of ints Group of calendar month numbers to match against....
76,012
def get_stock_quarterly_features_func(d_interval,d_offset): """ Generates a function that returns quarterly features for a stock Args: d_interval: The data interval as a datetime.timedelta (e.g., 6*TIMEDELTA_QUARTER for 6 quarters of data) d_offset: The offset of d_interval relative...
76,013
def show_policy(data): """Show policy."""
76,014
def write_cif(filename: str, CIF: str, outfolder: os.PathLike) -> None: """ Auxilia function for writing a CIF string into a folder Parameters ---------- filename : Filename to save CIF : A CIF string or byte-like CIF string outfolder : Folder to save Returns ------- Nothing. Wr...
76,015
def once(f): """Decorator. Defer to f once and only once, caching the result forever. Users with a functional background may recognize the concept of a `thunk`. """ unset = val = object() def _helper(*args, **kwargs): nonlocal val if val is unset: val = f(*args, **kwa...
76,016
def get_simulation_results(project_list, enhanced_dataframe, test_size, max_iterations, parallel, priority_queue, disable_ignore): """ Applies the simulation and validation procedures to a project list. :param priority_queue: True if the development team uses a Priority Queue, fal...
76,017
def fetch_daily_tickets( schema_name: str, table_name: str, account: str, **kwargs, ): """ Download zendesk json data and reformat it for ingestion into table """ today = kwargs["execution_date"] yesterday = (today - timedelta(days=1)).strftime("%Y%m%d") logger.info(f"Fetching data from sou...
76,018
def load_configuration(configuration_file_path, parameters_file_path, bundles): """Combines the configuration and parameters and build the configuration object""" mappings = {} for bundle in bundles: if hasattr(bundle, "config_mapping"): mappings.update(bundle.config_mapping) loader ...
76,019
def main(path=None, num=35, top=0.6, middle=0.2, bottom=0.2): """Select users to survey.""" if not path: data = download_content() else: with open(os.path.expanduser(path)) as fp: data = fp.read() users = sorted(load_content(data)) for user in find_users(users, num, top, ...
76,020
def jupy2pdf(src): """ """ try: import subprocess des = src.replace(".ipynb",".pdf").replace("Xblog", "Xblog/docs").replace("notebooks", "pdfs") ccc.note("converting " + str(src) + " to pdf") if os.system("bash ./convert.sh {} {} Xblog/ref.bib Xblog/template.tplx".format(src,...
76,021
def delete(): """ Delete a user --- /api/users/delete/me: delete: summary: Return your user data. security: - APIKeyHeader: [] tags: - User responses: '200': description: An Access Token API to be used in Boleto Viewer """ user = UserModel.get_on...
76,022
def get_cached_dirlist(sample_method, path): """ get the list of Samples that have already run from a sample_method (illumina or nanopore) and path (prefix/shard) """ return list(dirlist.find({"sample_method": sample_method, "path": path}, {"samples": 1}))
76,023
def pairwise_align( slice1: AnnData, slice2: AnnData, spatial_key: str = "spatial", alpha: float = 0.1, numItermax: int = 200, numItermaxEmd: int = 100000, device: str = "cpu", ) -> np.ndarray: """Calculates and returns optimal alignment of two slices. Args: slice1: An AnnDa...
76,024
def app(request): """ flask test application :param request: :return: """ # initialize flask application app = create_app('test_app', config.TestConfig) # initialize database with app.app_context(): metadata = MetaData(db.engine) metadata.reflect() # drop da...
76,025
def normalize_number(text): """数字1文字を0に置き換える(桁数は変わらない)""" return re.sub(r"\d", "0", text)
76,026
def dict_g2go(file_g2go): """Creates a dictionary of type {gene1:[(GO_ID, Evidence, GO_name, category), (GO_ID, Evidence, GO_name, category), ...], } :param file_g2go: file with relations gene to GO :return: dict of type {gene1:[(GO_ID, Evidence, GO_name, category), (GO_ID, Evidence, GO_na...
76,027
def build_get_dictionary_request(**kwargs: Any) -> HttpRequest: """Get External Resource as a Dictionary. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to...
76,028
def gen_anchor(featuresize,scale): """ gen base anchor from feature map [HXW][9][4] reshape [HXW][9][4] to [HXWX9][4] """ heights=[11, 16, 23, 33, 48, 68, 97, 139, 198, 283] widths=[16,16,16,16,16,16,16,16,16,16] #gen k=9 anchor size (h,w) heights = np.array(heights).reshape(len(...
76,029
def shib_ds_context(context): """ Creates a dictionary with information: * ServiceProvider login handler * IdPs from cookie """ shib_ds = get_context(context.request) return shib_ds
76,030
def __getattr__(name): # noqa: N807 """Get attribute.""" deprecated = __deprecated__.get(name) if deprecated: warnings.warn( "'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]), category=DeprecationWarning, stacklevel=(3 if PY37 else 4) )...
76,031
async def hub_pod(kube_client, kube_ns): """Create and return a pod running jupyterhub""" return await create_hub_pod(kube_client, kube_ns)
76,032
def iterate(data, path): """Generator that returns values in data matching the given JsonPath.""" if not data: return parsed_path = _PARSED_PATH_CACHE.get(path) if not parsed_path: parsed_path = jsonpath_ng.parse(path) _PARSED_PATH_CACHE[path] = parsed_path for item in parsed_path.find(data): ...
76,033
def parseLayoutFeatures(font): """Parse OpenType layout features in the UFO and return a feaLib.ast.FeatureFile instance. """ featxt = font.features.text or "" if not featxt: return ast.FeatureFile() buf = StringIO(featxt) ufoPath = font.path includeDir = None if ufoPath is n...
76,034
def _hash_file(fpath, chunk_size=65535): """ Calculates the md5 hash of a file :param fpath: path to the file being validated :param chunk_size: Bytes to read at a time (leave unless large files) :return: The file hash """ hasher = hashlib.md5() with open(fpath, 'rb') as fpath_file: ...
76,035
def vac(): """ closes the Helium valve and opens the vacuum valve""" set_he_valve('closed') time.sleep(0.1) set_vak_valve('open')
76,036
def run(): """Runs evaluation in a loop, and logs summaries to TensorBoard.""" # Create the evaluation directory if it doesn't exist. eval_dir = FLAGS.eval_dir if not tf.gfile.IsDirectory(eval_dir): tf.logging.info("Creating eval directory: %s", eval_dir) tf.gfile.MakeDirs(eval_dir) # Create ...
76,037
def broadcast_object_list(object_list, src=0, group=None): """ Broadcasts picklable objects in ``object_list`` to the whole group. Similar to :func:`broadcast`, but Python objects can be passed in. Note that all objects in ``object_list`` must be picklable in order to be broadcasted. Args: ...
76,038
def GetIcon(name, module=None): """ wx.Icon GetIcon(iconName, module=None) Get an icon from a file, possibly prepending the module's path """ name=modPath(name, module) return wx.Icon(name + ".ico")
76,039
def test_timestampMsValidator_correct_values(value): """Check the parsing and validating timestamps with milliseconds part.""" # exception is not expected timestampValidatorMs(value)
76,040
def midpoint(start, end): """Find the mid-point between two points.""" x0, y0 = start x1, y1 = end return (x0+x1)/2, (y0+y1)/2
76,041
def scatterplot(custom_x, custom_y, xlabel=None, ylabel=None, **kwargs): """ Custom x-y plotting using VESIcal's built-in plot() function, built on Matplotlib's plot and scatter functions. Parameters ---------- custom_x: list List of groups of x-values to plot as points or lines custom_y: list List of group...
76,042
def test_init_sort_nodes(): """ Tests initialization with sorting of nodes. This tests that the nodes are ordered correctly when sorted on the "node_order" key. """ G = make_graph_for_grouping() # noqa b = BasePlot(graph=G, node_order='year') assert b.nodes == [n for n, d in ...
76,043
def push(env): """ Set current execution environment for whatever parallel mechanism is used. """ with _lock: ident = identifier() _current_envs.setdefault(ident, []) if _current_envs[ident]: current = _current_envs[ident][-1] current.deactivate() _curre...
76,044
def presale_crowdsale_miletstoned(chain, presale_fund_collector, uncapped_flatprice, presale_milestone_pricing, team_multisig): """ICO associated with the presale where funds will be moved to a presale. We set a special milestone pricing that allows us to control the pricing for the presale participants. "...
76,045
def main(): """Make magic happen.""" parser = argparse.ArgumentParser(description='''Creating public/private PGP keys''') parser.add_argument('password', help='PGP user name') args = parser.parse_args() password_hash = hash_pass(args.password) print(password_hash)
76,046
def dict_populate_loop(pattern): """ Args: pattern: array of tokens that represents the tokens. Returns: updated_dic: a dictionary that contains all the keywords from docstrings. """ updated_dic = {} for token in pattern: if isinstance(token, docopt_util.Branch): ...
76,047
def visualize_farm( plane, nr_points, size_x, size_y, title="", ax=None, vmax=False): """ Function to plot flow-field around a wind farm. Args: plane (2d numpy array): Flow field of wind farm nr_points (list or np array): List of nr of points in x and y size_x (int...
76,048
def oov_rate( targets: jnp.ndarray, oov_values: Tuple[int, ...], mask_values: Tuple[int, ...] = ()) -> MeanMetric: """Computes proportion of non masked tokens that are out of vocabulary. Args: targets: Target values of shape [batch_size, sequence_length, ...]. oov_values: Target values denoting...
76,049
def validation_simple(value, obj=None): """ Validates that at least one character has been entered. Not change is made to the value. """ # TODO: Translate if value is None or len(value) == 0: return False, value, u'El valor digitado debe tener uno o más caracteres' return True, valu...
76,050
def multiprocess_filter_reads(in_dir, alignment_file, readdb, trim=False, quality_threshold=7, worker_count=1, debug=False): """Multiprocess for filtering reads but dont move the files :param in_dir: input directory with subdirectories assumed to have fast5s in them :param alig...
76,051
def hash_to_path(kind: str, rep: str) -> pathlib.Path: """Derive path from content rep hash and create any folder required.""" if kind not in KINDS.values(): raise ValueError(f'unknown {kind=} for {rep=}') folder = DB_OUT_ROOT / kind / rep[:2] folder.mkdir(parents=True, exist_ok=True) return...
76,052
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file1', metavar='FILE', type=argparse.FileType('rt'...
76,053
def test_run_net_distributed_save_all_test_timeline(set_up_smprofiler_config_path, out_dir): """ This test checks if any of the timestamps recorded are negative """ trial = _run_net_distributed(out_dir, include_workers="all", test_timeline=True) assert len(trial.workers()) == 2, f"trial.workers() = ...
76,054
def create_message_with_attachment(sender, to, subject, message_text, file): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. file...
76,055
def part_1(data): """Part 1""" pattern = parse.compile('{} {:d}') loc = Location() for line in data: print(line) command, value = pattern.parse(line) loc.move(command, value) print(loc)
76,056
def mirror_edges(img, psf=3): """Given a 2D image, boundaries are padded by mirroring so that the dimensions of the image are multiples for the width of the point spread function. Args: img (np.array): Image to mirror edges. psf (int): Size of point spread function in pixels. Retur...
76,057
def _srg_rhs_old(s, potential, kinetic, potential_weight, weights, flow, verbose): """Old implementation of SRG flow equation. New implementation is more efficient and reflects actual form better. Keeping this for documentation and as reference for analytic evaluation of flow equation ...
76,058
def compute_taproot_address(pubkey, scripts): """Compute the address for a taproot output with given inner key and scripts.""" tap = taproot_construct(pubkey, scripts) assert tap.scriptPubKey[0] == 0x51 assert tap.scriptPubKey[1] == 0x20 return encode_segwit_address("bcrt", 1, tap.scriptPubKey[2:])
76,059
def part1(): """ find 3x3 grid segment with the highest power level """ fc = FuelCell(load_input()) high_pow = 0 high_coords = [] for x in range(fc.width-2): for y in range(fc.height-2): power = fc.power_of_grid((x,y)) if power > high_pow: hi...
76,060
def perplexity_w_prior(probabilites, smi, d_prior, remove_end=True): """ Compute the perplexity of a SMILES given a list of probabilities. probabilites: (list) of probabilities smi: (str) a SMILES d_prior: (dict) with keys: SMILES characters, and value the prior probability to sample the...
76,061
def RegisterExportConverters(): """Registers all ExportConverters.""" # keep-sorted start export_converters_registry.Register( buffer_reference.BufferReferenceToExportedMatchConverter) export_converters_registry.Register(check_result.CheckResultConverter) export_converters_registry.Register( clien...
76,062
def plot_model_timing(title, data_sizes, fit_scores, predict_scores, ylim=None): """ Generate a simple plot of the given model timing data Parameters ---------- title : string Title for the chart. ylim : tuple, shape (ymin, ymax), optional Defines minimum and maximum yvalues pl...
76,063
def _get_int64(data, position, dummy0, dummy1, dummy2): """Decode a BSON int64 to bson.int64.Int64.""" end = position + 8 return Int64(_UNPACK_LONG(data[position:end])[0]), end
76,064
def set_pin(ctx, pin, new_pin, u2f): """ Set or change the PIN code. The FIDO2 PIN must be at least 4 characters long, and supports any type of alphanumeric characters. On YubiKey FIPS, a PIN can be set for FIDO U2F. That PIN must be at least 6 characters long. """ controller = ctx.ob...
76,065
def test_wgs_cnv_calling_workflow(wgs_cnv_calling_workflow): """Test simple functionality of the workflow""" # Perform the tests # # Check created sub steps expected = ["cnvetti", "erds", "erds_sv2", "link_out", "write_pedigree"] assert list(sorted(wgs_cnv_calling_workflow.sub_steps.keys())) == ...
76,066
def verify_proof(db_contract, proof, received): """This queries the DB to retrieve the heartbeat, state and challenge for the contract id, and then checks the given proof. Returns true if the proof is valid. Can also return false if the contract is expired or if an ip address change has been rejected ...
76,067
def log_data(): """Log the data dir info""" logger.debug("Working dir: {}".format(_dir)) logger.debug("Data file location: {}".format(_datafile))
76,068
def generate_os_release(distro, os_release_file): """ Generates an /etc/os-release like file with information about the package distribution. VERSION and VERSION_ID are left unset if the package source is from an unknown debian release. """ os_release = collections.OrderedDict([ ("PRETTY_N...
76,069
def low_pass_butter4(freqs, tod, fc): """4th-order low-pass filter with f3db at fc (Hz). """ b, a = signal.butter(4, 2*np.pi*fc, 'lowpass', analog=True) return np.abs(signal.freqs(b, a, 2*np.pi*freqs)[1])
76,070
def get_functions(funcset=None): """ Return a dict of variables """ c0 = funcset in _DFUNC.keys() if c0 is not True: lstr = [ "\t- '{}': {}".format(k0, sorted(v0.keys())) for k0, v0 in _DFUNC.items() ] msg = ( "Arg varset must be a valid key to an ...
76,071
def description_to_entityset(description, **kwargs): """Deserialize entityset from data description. Args: description (dict) : Description of an :class:`.EntitySet`. Likely generated using :meth:`.serialize.entityset_to_description` kwargs (keywords): Additional keyword arguments to pass as ke...
76,072
def replace_pair(pair, content): """ Uses regex to locate a pair. First element of the tuple is the original error token. Second element of the tuple is the replacement token. """ return re.sub(pair[0], ' {} '.format(pair[1]), content)
76,073
def cli_create(ctx, model): """Create a migration based on an existing model.""" if not ctx.obj.data['manager'].create(model): sys.exit(1)
76,074
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, hvd=None, manual_fp16=False, use_fp16=False, num_accumulation_steps=1, optimizer_type="adam", allreduce_post_accumulation=False): """Creates an optimizer training op.""" global_step = tf.train.get_or_create_global_step() ...
76,075
def build(paths, dbname, table): """ Load markdown files into a SQLite database Based on https://github.com/simonw/markdown-to-sqlite, modified to use markdown extensions. """ db = Database(dbname) md = markdown.Markdown( extensions=["fenced_code", "codehilite"], extension_c...
76,076
def main(options): """ The main function. """ logger.info("Comparative Analyzer started") print("Log file -> logs/CA.log") ls_files = os.popen("ls -l " + FAAS_ROOT + "/data_archive/*.pkl") archive_files = [] for line in ls_files: archive_files.append([line[line.index('data_archi...
76,077
def load_positions_from_timepoints_file(path): """Load a text file of timepoint pseudo-paths into a list of Positions. The file is expected to be lines of pseudo-paths of the form: /path/to/experiment_root/position_name/timepoint_name where: /path/to/experiment_root/position_name is a valid pat...
76,078
def main(): """Parse command line args and download the requested videos.""" args = _init_argparse() archive_path = pathlib.Path(args.archive_path) output_path = pathlib.Path(args.output_path) archive_path = extract_archvie(archive_path) archive_videos = discover_videos(archive_path) if "...
76,079
def aioresponse(): """ Creates an mock async API response. This comes from a mock library specific to the aiohttp package: https://github.com/pnuckowski/aioresponses """ with aioresponses() as async_response: yield async_response
76,080
def vis_network( nodes, edges, physics="", height=400, node_size=25, font_size=14, filename="", config={}, template_file="vis.html", app=False, ): """Render a network with vis.js in an IFrame for use in a jupyter notebook or website. This function will render a template...
76,081
def _run_ares(): """Run ARES""" os.system('ARES > /dev/null') for tmp in ['tmp', 'tmp2', 'tmp3']: if os.path.isfile(tmp): os.remove(tmp)
76,082
def trace_condition_function(condition: ConditionCheckerType) -> ConditionCheckerType: """Wrap a condition function to enable basic tracing.""" @ft.wraps(condition) def wrapper(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Trace condition.""" with trace_condition(vari...
76,083
def Base_switch(self, param): """ - name: switch window switch: window: win1 - name: switch frame switch: frame: frm1 - name: switch to default window switch: default """ if param in ("default", None, {}, True): self.driver.switch_to_default_content() ...
76,084
def log_me_in(base_url, username=None): """ :param username: :returns cookies :param base_url: :return: """ add_url = "/geo/init" if username is None: user_data = {"userName": "python " + str(datetime.now())} else: user_data = {"userName": username + str(datetime.now(...
76,085
def init_anat_reports_wf(*, freesurfer, output_dir, sloppy, name="anat_reports_wf"): """ Patched workflow for reports to allow no resolution for templates Set up a battery of datasinks to store reports in the right location. Parameters ---------- freesurfer : :obj:`bool` FreeSurfer was e...
76,086
def extract_sitename_date(directory_path, sitename_location, datetime_location): """Extract sitename and datetime from directory path name. Parameters ----------- directory_path : string A path to the directory name sitename_location : ind...
76,087
def make_blanks(spans: List[Span], length: Optional[int] = None, fill: str = TokenFunction.OUTSIDE) -> List[str]: """Create a list of outside tags that we can populate with tags generated from spans. Args: spans: The list of spans that will eventually be used to populate the tags. length: A pre...
76,088
def get_flags(): """ Argument parser for the script :return: Object containing flags. :rtype: Dict """ parser = argparse.ArgumentParser() parser.add_argument( "--stats", dest="stats", action="store_true", help="Run stats, need to have labels in test folder", ...
76,089
def month_holidays(year, month): """ その月の祝日日、祝日名を返します。 """ date = datetime.date(year, month, 1) output = [] while date.month == month: name = is_holiday_name(date) if name is not None: output.append((date, name)) date = date + datetime.timedelta(days=1) ...
76,090
def collection_test(in_dim1, in_dim2, channels, out_dim): """ Return a small collection of models and their names """ names = [] for a in range(1, 3): for b in range(3): n1 = a * 8 n2 = b * 8 m_str = str(n1) ...
76,091
def favourites_add(request): """ Function to add recipe to favourites. This function is used via AJAX. """ user = request.user title = request.POST.get('title') recipe_id = request.POST.get('recipe_id') image_url = request.POST.get('image_url') favourite, created = Recipe.objects.get...
76,092
def read_chain_header(line): """ Convenience wrapper to parse chain header information :param line: :return: """ _, score, tName, tSize, tStrand, tStart, tEnd, qName, qSize, qStrand, qStart, qEnd, chainid = line.strip().split() return Chain(tName, int(tSize), tStrand, int(tStart), int(tEnd),...
76,093
async def get_host_by_slug(host_slug: constr(strip_whitespace=True)): """Retrieve a Host object, based on Host slug string, containing: Host ID, name, slug string, and gender.""" try: host = Host(database_connection=_database_connection) host_info = host.retrieve_by_slug(host_slug) i...
76,094
def python_minifiy(file): """Outputs a minified version of the given Python file. Runs pyminifier on the given file. The minified filename has '.min' added before the '.py' extension. This function is used to help code fit under the 4k limit when uploading lambda functions, directly, as opposed t...
76,095
def cleanup_text(line: str) -> str: """ Args: line: text line of the opinion Returns: text line where not alphabetical characters removed """ corrections = {"&quot": "", "&amp": ""} line_lower = line.lower() for wrong, cor in corrections.items(): line_lower = lin...
76,096
def partial_threshold_tanimoto_search_symmetric(results, arena, threshold=0.7, query_start=0, query_end=None, target_start=0, target_end=None): """Compute a portion of the symmetric Tanimoto search results For most ...
76,097
def send_mail(to_mail, mail_subject, mail_body): """ Function to send a mail using Sendgrid API Parameters: arg1 (string): The recipient's email address. arg2 (string): The subject of the mail. arg3 (string): The body of the mail. """ message = Mail( from_email=current_app.con...
76,098
def get_client_rate(client_id): """ End point for getting rate for a client_id. :param client_id: str :return: http response """ # How to get the actual rate from client_id? # all_clients = get_client_rates() # if client_id in all_clients: # return str(all_clients[client_id]['ra...
76,099