content
stringlengths
22
815k
id
int64
0
4.91M
def admin_role_required(f): """ Grant access if user is in Administrator role """ @wraps(f) def decorated_function(*args, **kwargs): if g.user.role.name != 'Administrator': return redirect(url_for('error', code=401)) return f(*args, **kwargs) return decorated_function
51,500
def AddNetworkArgs(parser): """Set arguments for choosing the network/subnetwork.""" netparser = parser.add_mutually_exclusive_group() network = netparser.add_argument( '--network', default=constants.DEFAULT_NETWORK, help='Specifies the network that the instances will be part of.') network.d...
51,501
def reload_app(data=None): """IPC callback to reload a DIAL app""" # When an add-on will be updated is needed reload the DIAL app, or will remains in memory the old script code if data and data.get('skip_version_check'): execute_reload = True else: # Todo: execute reload only if the add-...
51,502
def format_location_detail_tract(data): """Reformat the list of data to Location Detail format for tract Args: data (list): A list of FSF object Returns: A pandas formatted DataFrame """ df = pd.DataFrame([vars(o) for o in data]) df.rename(columns={'fsid': 'fsid_placeholder'}, i...
51,503
def pgcdDesDistancesEntreRepetitions(crypted: List[int], i: int) -> int: """ Returns pgcd{ } """ assert 0 <= i < len(crypted) - 2, "i must be in [0, len(crypted)-2)" search_for = crypted[i:i+2+1] current_pattern: List[int] = [] distances: List[int] = [] for i, c in enumerate(crypted[i+3...
51,504
def preprocess(simulation, field): """ Store DOF and geometry info that will not change unless the mesh is updated (which is not handled in any way) """ mesh = simulation.data['mesh'] dofmap = field.function_space().dofmap() conFC = simulation.data['connectivity_FC'] # Data to compute ...
51,505
def drop_probable_entities(X): """ :param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> drop_empty_lists(drop_arabic_numeric(drop_probable_entities([['Catullus'], ['C.', 'VALERIVS', 'CATVLLVS'],['1','2', '2b', '3' ],['I.', 'ad', 'Cornelium'],['Cui...
51,506
def wrong_obj_msg(*objs, allow="sources"): """return error message for wrong object type provided""" assert len(objs) <= 1, "only max one obj allowed" allowed = allow.split("+") prefix = "No" if len(allowed) == 1 else "Bad" msg = f"{prefix} {'/'.join(allowed)} provided" if "sources" in allowed: ...
51,507
def list(): """List out information in a configuration DB."""
51,508
def text2haiku(text, keep_chance=0.75, iterations=2000): """ Given a string of text, try to make a haiku returns a haiku as a string or None if it fails """ word_list = text_to_word_list(text) haiku = bagging_haiku_maker(word_list, keep_chance=keep_chance, iterations=iterations) return haiku
51,509
def test_ppl_sentence(): """测试句子粒度的ppl得分""" sentence_char_split1 = ' '.join('先救挨饿的人,然后治疗病人。') sentence_char_split2 = ' '.join('先就挨饿的人,然后治疗病人。') n = model.perplexity(sentence_char_split1) print('1', n) n = model.perplexity(sentence_char_split2) print(n) part_char_split1 = ' '.join('先救挨饿的...
51,510
def test_bust_cache_reevaluates_function(redis_mock): """:type redis_mock: mock.MagicMock""" from cache_requests import Memoize # LOCAL TEST HELPER # ------------------------------------------------------------------------ def call_count(): try: return redis_mock.get.call_count...
51,511
def control_trezor_keepkey_libs(connecting_to_hw): """ Check if trying to switch between Trezor and Keepkey on Linux. It's not allowed because Trezor/Keepkey's client libraries use objects with the same names (protobuf), which causes errors when switching between them. :param connecting_to_hw: type of t...
51,512
def load_housing_data(housing_path=HOUSING_PATH): """ Load housing data from csv into pandas dataframe housing_path: path to the dataset return: pandas.DataFrame """ # file path csv_path = os.path.join(housing_path, "housing.csv") #return the dataf...
51,513
def read_ccs(fname): """ Read a CCS matrix from file into a scipy csc matrix. This routine uses the CCS matrix files that CheSS generates. Args: fname (str): name of the file. Result: scipy.sparse.csc_matrix: the matrix in the file. """ from scipy.sparse import csc_matrix ...
51,514
def postprocess_hyperparams(args, config): """Postprocess a given hyperparameter configuration.""" #if config['--seq-beam'].current_value <= 8: # config['--max-tokens'].current_value = 400 #else: # config['--max-tokens'].current_value = 300 # decoder_embed_dim = config['--decoder_embed_dim...
51,515
def test_pickle(): """Test that a fit search can be pickled""" clf = MockClassifier() grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, refit=True) grid_search.fit(X, y) pickle.dumps(grid_search) # smoke test random_search = RandomizedSearchCV(clf, {'foo_param': [1, 2, 3]}, ...
51,516
def test_send_queued_messages( # pylint: disable=unused-argument raiden_network, deposit, token_addresses, network_wait, skip_if_not_matrix ): """Test re-sending of undelivered messages on node restart""" raise_on_failure( raiden_network, run_test_send_queued_messages, raiden_networ...
51,517
def demo__google_result_open_in_new_tab(raw_text, content_mime): """Force google search's result to open in new tab. to avoid iframe problem 在新标签页中打开google搜索结果 """ def hexlify_to_json(ascii_str): _buff = '' for char in ascii_str: if char in '\'\"<>&=': _buff ...
51,518
def to_location_via_telescope_name(self): """Calculate the observatory location via the telescope name. Returns ------- loc : `astropy.coordinates.EarthLocation` Location of the observatory. """ return EarthLocation.of_site(self.to_telescope())
51,519
def mailmangle_linked(email): """ Weakly obfuscates an email address using JavaScript and displays it with a mailto link. If JS not present (i.e. what's in ``<noscript>``), displays a link to a reCAPTCHA. """ encoded = _encoder( '<a href="mailto:{0}" class="email">' '{0}' ...
51,520
def hamiltonian(ncomp, freq, controls): """Assemble hf for one spin, given a detuning freq, the control amplitudes controls, and ncomp components of the control pulse.""" nc = 2 * ncomp + 1 # number of components in hf hf = np.zeros((nc, 2, 2), dtype=np.complex128) for k in range(ncomp): # ...
51,521
def delete_database_cluster(rds_client, db_identifier): """Function to delete RDS instance. Args: rds_client (Client): AWS RDS Client object. db_instance_identifier (str): RDS instance to delete Returns: bool: True if instance was deleted successfully or does not exist, ...
51,522
def get_nbow_vecotr(word_string, label_dict): """ Calc nBOW vector :param word_string: :param label_dict: :return: """ n_bow = label_dict.transform([word_string]) # nBOW vector n_bow = n_bow.toarray().ravel() n_bow = n_bow.astype(np.double) n_bow /= n_bow.sum() re...
51,523
def configMSOD(): """Setup a default configuration for the server so you can log into it as admin""" sudo('PYTHONPATH=/opt/SpectrumBrowser/services/common:/usr/local/lib/python2.7/site-packages /usr/local/bin/python2.7 ' + getSbHome() + '/setup-config.py -host ' + os.environ.get('MSOD_WEB_HOST') + ' -f ' +...
51,524
def google_audio_settings_to_mod9(google_audio_settings): """ Map from Google-style audio input to Mod9 TCP server-style audio input. Args: google_audio_settings (dict): Google-style audio. Returns: Union[str, Iterable[bytes]]: Mod9-style audio to pass to Mo...
51,525
def get_sequence_lengths(sequence_batch: Array, eos_id: int) -> Array: """Returns the length of each one-hot sequence, including the EOS token.""" # sequence_batch.shape = (batch_size, seq_length, vocab_size) eos_row = sequence_batch[:, :, eos_id] eos_idx = jnp.argmax(eos_row, axis=-1) # returns first occurren...
51,526
def create_status(): """Post a new status. The status should be posted as JSON using 'application/json' as the content type. The posted JSON needs to have 3 required fields: * user (the username) * content * api_key An example of the JSON:: { "user": "r1cky", ...
51,527
def unzipped_multi_fasta_test(): """Load unzipped multi-fasta.""" ref = mio.Fasta(multi_fasta=os.path.join(mitty.tests.example_data_dir, 'chimera.fa')) assert len(ref) == 4 assert len(ref[4]['seq']) == 702 assert ref[1]['seq'] == 'CATCATCAATAATATACCGCACACTTTTATTGCCCCTTTTGTGGCGTGGTGATTGGCGGAGAGGGTTGGGGGCGGCGGG...
51,528
def Shift(parent, shift, da_mode="nearest", constant=0.0, name=""): """\ Shift the input image. :param parent: parent layer :param shift: list of maximum absolute fraction for the horizontal and vertical translations :param da_mode: one of "nearest", "constant" :param constant: fill value...
51,529
def iterations_for_terms(terms): """ Parameters ---------- terms : int Number of terms in the singular value expansion. Returns ------- Int The number of iterations of the power method needed to produce reasonably good image qualit for the given number of terms in th...
51,530
def explained_variance(y_pred, y): """ Returns 1 - Var[y - y_pred] / Var[y] """ assert y.ndim == 1 and y_pred.ndim == 1 variance = np.var(y) return np.nan if variance == 0 else 1 - np.var(y - y_pred) / variance
51,531
def drop_bad_genera(cxn): """Remove taxonomy records with a bad genus. A bad genus name is completely useless for any further analysis. """ cxn.execute("""DELETE FROM taxonomy WHERE genus LIKE '%.%';""") cxn.commit()
51,532
def get_3d_points_from_multiple_observation(candidate_sets, camera_matrixs, fundamental_matrixs, threshold_sv = 15.0): """ param candidate_sets : [[np.array{2}, ...], ...] list of candidate sets(list) in cameras param camera_matrixs : np.array{ v x 3 x 4 } return : [np.array{3}, ...] the corresponding p...
51,533
def get_macro(macro_name): """ Get the configured macro :param macro_name: The name of the macro to add :return: The macro itself in string form """ return MACROS[macro_name]
51,534
def plot_locomotion_2D(locomotion: Locomotion, ax: plt.Axes): """ Draws a 2D trace with the locomotion trajectory of each bodypart """ ax.axis("equal") # plot com ax.plot( locomotion.com.x, locomotion.com.y, color="k", lw=1, alpha=1, zorder=2 ) # plot longitudinal and norm...
51,535
def part_1(input_data: str) -> int: """What do you get if you multiply your final horizontal position by your final depth? Returns: int: [final horizontal position * final depth] """ h_pos, depth = 0, 0 # Your horizontal position and depth both start at 0. commands = parse_input(input_data)...
51,536
def initializePlugin(obj): """ """ plugin = OpenMayaMPx.MFnPlugin(obj, "Erkan Ozgur Yilmaz", "0.1.0", "Any") try: plugin.registerNode( node_type_name, plugin_id, nodeCreator, nodeInitializer, OpenMayaMPx.MPxNode.kDeformerNode ) ...
51,537
def preprocess_image(img, cam_values): """ Function to prepare image for lane extraction: 1. undistort image 2. crop a region of interest 3. convert image to hsv 4. Get binary gradient image using sobel 5. transfer binary image using the roi Args: img ([type]): [description] ...
51,538
def add_handler(name, handler): """Register a `handler` function to be called on event `name`. Handler signatures are:: def before_event_handler(event_name, obj, args): # called just before `obj.method(**args)` executes def after_event_handler(event_name, obj, args, return_value):...
51,539
def init_compress_eigerdata( images, mask, md, filename, bad_pixel_threshold=1e15, hot_pixel_threshold=2 ** 30, bad_pixel_low_threshold=0, nobytes=4, bins=1, with_pickle=True, reverse=True, rot90=False, direct_load_data=False, data_path=None, images_per_file=1...
51,540
def _generate(ctx): """ Generates the source files. """ if not ctx.files.srcs: fail("No grammars provided, either add the srcs attribute or check your filespec", attr="srcs") args = ctx.actions.args() if ctx.attr.atn: args.add("-atn") if ctx.attr.depend: args.add("-depend...
51,541
def cli(quiet, logfile): """Python implementation of the Two-Way Active Measurement Protocol (TWAMP and TWAMP light) as defined in RFC5357.""" loglevel = logger.level if quiet: logger.setLevel(logging.NOTSET) if loglevel >= logging.DEBUG and logfile: file_handler = TimedRotating...
51,542
def parseTomEval(inFile, strand): """parse the tomtotm.txt file and return a dict of e-values between motifs """ #dict between query and target Ids matchDict = {} #read the tomtom.txt file and see if any known are found with open(inFile, 'rb') as handler: for line in handler: line = line.strip() if...
51,543
def prepare_peoples_speech( corpus_dir: Pathlike, output_dir: Pathlike, ) -> Dict[str, Union[RecordingSet, SupervisionSet]]: """ Prepare :class:`~lhotse.RecordingSet` and :class:`~lhotse.SupervisionSet` manifests for The People's Speech. The metadata is read lazily and written to manifests in a...
51,544
def test_session_with_context(webserver, port_number): """ If a X-MDK-CONTEXT header is sent to the webserver it reads it and uses the encoded session. """ context = create_context() returned_context = requests.get(get_url(port_number, "/context"), headers={"X...
51,545
def process_edit_distances(mx, reference_counter, reference_values, search_values): """Extract search values that has minimum edit distance from reference values. Multiple hits are enabled.""" min_distances = mx.min(axis=1) matches = [] for i in range(mx.shape[0]): min_dist = min_distances[i] ...
51,546
def maven_new_manifest_stack_analysis(context, manifest, version=3, token="without"): """Send the Maven package manifest file to the stack analysis.""" endpoint = stack_analysis_endpoint(context, version) use_token = parse_token_clause(token) send_manifest_to_stack_analysis(context, manifest, 'dependenc...
51,547
def test_deprecation(spec_fixture, workspace_manager_fixture, # noqa test_workspace, tmpdir): """Verify execution runs with deprecated option """ my_temp_dir = tmpdir.mkdir("tmp") deprecated_output = my_temp_dir.join("deprecated_output.yml") deprecated_input_string = \ ...
51,548
def get_jobs(): """Get a list of jobs""" query = "SELECT * FROM urls" result = db.execute(query) return jsonify(result)
51,549
def get_leaf_nodes(struct): """ Get the list of leaf nodes. """ leaf_list = [] for idx, node in enumerate(struct): if node['is_leaf']: leaf_list.append(idx) return leaf_list
51,550
def pytest_configure(config: Config) -> None: """Pytest `configure hook`_ to perform initial configuration. .. _configure hook: https://docs.pytest.org/en/stable/reference.html#pytest.hookspec.pytest_configure We're registering our custom marker so that it passes ``--strict-markers``. """ con...
51,551
def plot_mri_tmap( sample_id: Union[int, str], tmap_cache: TensorMapCache, tmap: TensorMap, plot_type: PlotType, instance: int, color_range: Tuple[int, int], transpose: bool, flip: bool, fig_width: int, ) -> None: """Visualize the applicable MRI series within this HD5 file. Args: sample_id: The local o...
51,552
def cg_build_w_env(A, B, i): """ Build the environment for constructing the ith HOTRG isometry for A and B. """ A_indices1 = [1,2,3,4,5,-11] A_indices2 = [1,2,3,4,5,-12] A_indices1[i] = -1 A_indices2[i] = -2 A2 = ncon((A, A.conjugate()), (A_indices1, A_indices2)) B_indices1 = [1,2,3...
51,553
def get_node_edge(docs, w2d_score, d2d_score): """ :param docs: :param w2d_score: :param d2d_score: :return: """ wid2wnid = {} w_id, d_idx = [], [] w_d_wnid, w_d_dnid = [], [] w_d_feat = {"score": [], 'dtype': []} d_d_dnid1, d_d_dnid2 = [], [] d_d_feat = {"score": [], '...
51,554
def get_elixier_org_by_id_local(id_local): """ ..liefert den zu id_local passenden Datensatz """ items = DmsElixierOrg.objects.filter(id_local=id_local) if len(items) > 0: return items[0] else: return None
51,555
def nearest_approach_to_any_vehicle(traj, vehicles): """ Calculates the closest distance to any vehicle during a trajectory. """ closest = 999999 for v in vehicles.values(): d = nearest_approach(traj, v) if d < closest: closest = d return closest
51,556
def iter_fill(iterable, n, fillvalue=None): """Iterate over iterable and append fillvalue until n values have been yielded.""" for x in iterable: yield x n -= 1 yield from (fillvalue,) * n # for _ in range(n): # yield fillvalue
51,557
def getAllQuery(): """ This will get all the records in the userQuery table """ rows = [] with engine.begin() as conn: sel = userQuery.select() rows = conn.execute(sel).fetchall() return rows
51,558
def testingParameters(cal_file = None): """ Create a Spliner parameters object. """ params = parameters.ParametersSpliner() params.setAttr("max_frame", "int", -1) params.setAttr("start_frame", "int", -1) params.setAttr("background_sigma", "float", 8.0) if cal_file is not None:...
51,559
def fetch_labels(k, kmeans_history, offset=-1): """This fetches the original edges of a hierarchical mean. """ labels = kmeans_history[1] passes = labels.shape[0] indices = np.array([k]) for i in range(offset, -(passes + 1), -1): try: indices = np.array([np.nonzero(labels[i]...
51,560
def _reshape(t: 'Tensor', shape) -> 'Tensor': """ Also see --------- :param t: :param shape: :return: """ data = t.data.reshape(shape) requires_grad = t.requires_grad if requires_grad: def grad_f(grad: 'np.ndarray') -> 'np.ndarray': return grad.reshape(t.s...
51,561
def get_target_month(month_count, utc_now=None): """ Return datetime object for number of *full* months older than `month_count` from now, or `utc_now`, if provided. :arg month_count: Number of *full* months :arg utc_now: Used for testing. Overrides current time with specified time. :rtype: Da...
51,562
def mark_notifications_read(db: orm.Session = Depends(get_db)): """Mark all the notifications as read Returns: List of schema.Notification: A list of all the notifications updated to read """ notifications = db.query(model.Notification).all() for notification in notifications: ...
51,563
def created_task(result, status=202, mimetype='application/vnd.task-v1+json', headers={}): """ Created response for celery result by creating a task representation and adding a link header. :param result: :type result: AsyncResult :param status: Http status code. Defaults to 20...
51,564
def _get_dir_list(names): """This function obtains a list of all "named"-directory [name1-yes_name2-no, name1-no_name2-yes, etc] The list's building occurs dynamically, depending on your list of names (and its order) in config.yaml. The entire algorithm is described in "img" in the root directory and in th...
51,565
def _write_bed(chromosome, protein_list, filename, append): """Write bedfile with only DB peaks.""" if(append): bedfile = open(filename, "a") else: bedfile = open(filename, "w") for prot in protein_list: bedfile.write("%s\t%s\t%s\n" %(chromosome.name, prot.start, prot.stop))
51,566
def test_more_expected_than_printed_fails(): """Show pytest fails when more lines are printed than expected.""" command = "phmdoctest tests/extra_line_in_output.md --outfile discarded.py" simulator_status = phmdoctest.simulator.run_and_pytest( well_formed_command=command, pytest_options=["--doctest-...
51,567
def mapCardToImagePath(card): """ Given a card, return the relative path to its image """ if card == "01c": return 'src/imgs/2C.png' if card == "02c": return 'src/imgs/3C.png' if card == "03c": return 'src/imgs/4C.png' if card == "04c": return 'src/imgs/5C.png...
51,568
def verify_html(s): """Raise an error if s does not end with </html>""" assert s.strip().lower()[-7:] == '</html>'
51,569
def update_partition(chain_parent_in: list, job_id: str, partition_name: str) -> Optional[dict]: """ NOTE: This task is part of a chain(). At very first, it is evaluated if the previous tasks contain any errors. :param chain_parent_in: Output of parent task. :param job_id: :param partition_name: ...
51,570
def get_config(): """Read config file and return Python dictionary""" config_file = os.environ.get(config_environ) or default_path with open(config_file) as f: config = yaml.load(f) return config
51,571
def powerOff(currentBookTitle,fractional): """ stops player, updates meta file for next time you turn on player. cleans up GPIO board """ global player player.stop() updateMetaFile(currentBookTitle,fractional,True) GPIO.cleanup()
51,572
def consolidate_gauge(df): """ takes in gauge columns and normalizes them all to stiches per inch """ try: df['gauge_per_inch'] = df.loc[:,'gauge']/df.loc[:,'gauge_divisor'] except: print("Error occured when consolidating gauge") return df
51,573
def test_lump_init(ctx_factory): """ Simple test to check that Lump initializer creates the expected solution field. """ cl_ctx = ctx_factory() queue = cl.CommandQueue(cl_ctx) actx = PyOpenCLArrayContext(queue) dim = 2 nel_1d = 4 from meshmode.mesh.generation import generate_reg...
51,574
def upload_model_to_s3(bucket: str, prefix: str, model: str): """ Upload model file to s3, model file should end with .tar.gz :param bucket: Bucket name in s3 :param prefix: Prefix name :param model: Path to model file """ assert model.endswith(".tar.gz"), "Model path should point to a tar.g...
51,575
def parse_data(driver): """Return a float of the current price given the driver open to the TMX page of the specific symbol.""" # The driver needs time to load the page before it can be parsed. time.sleep(5) content_obj = driver.find_element(by="id", value="root") content_text = content_obj.text ...
51,576
def gather_bag(data_file, relation2id, tmp_bag_file): """ Gather instances into bags bag_id: (en1_id, en2_id, relation), Hence a bag only contains one relation total: total number of sentences, not bags Args: data_file: train.txt or test.txt relation2id: dictionary tmp_bag_f...
51,577
def print_entropy(band_name, img): """ plot the entropy of image with each band name """ bits = image_entropy(img) #per_pixel = bits / img.size print(f"{band_name:3s} entropy = {bits:7.2f} bits")
51,578
def _check_job_status( client, customer_id, offline_user_data_job_resource_name, user_list_resource_name, ): """Retrieves, checks, and prints the status of the offline user data job. Args: client: The Google Ads client. customer_id: The customer ID for which to add the user list...
51,579
def grab_images_and_videos(adir): """Grabs image and video files Args: adir: directory with images Returns: files: image and video files """ return grab_images(adir) + grab_videos(adir)
51,580
def get_docstring( node: AST, strict: bool = False, ) -> tuple[str | None, int | None, int | None]: """Extract a docstring. Parameters: node: The node to extract the docstring from. strict: Whether to skip searching the body (functions). Returns: A tuple with the value and ...
51,581
def main(): """ Initializes and trains a BNN network. Path to config file are read from command line arguments. """ # Initialize argument parser to pull neccesary paths parser = argparse.ArgumentParser() parser.add_argument('config',help='json config file containing BNN type ' + 'and data/model paths') args =...
51,582
def _get_default_siaf(instrument, aper_name): """ Create instance of pysiaf for the input instrument and aperture to be used later to pull SIAF values like distortion polynomial coefficients and rotation. Parameters ---------- instrument : str The name of the instrument aper_nam...
51,583
def add_shift_steps_unbalanced( im_label_list_all, shift_step=0): """ Appends a fixed shift step to each large image (ROI) Args: im_label_list_all - list of tuples of [(impath, lblpath),] Returns: im_label_list_all but with an added element to each tuple (shift step) """ ...
51,584
def gitlab(cve, output): """Extract CVEs assigned by the GitLab CNA""" cves = [] for cve_number in cve: year = re.match("CVE-([0-9]*)-[0-9]*", cve_number).group(1) api_endpoint = ( f"https://gitlab.com/gitlab-org/cves/-/raw/master/{year}/{cve_number}.json" ) requ...
51,585
def load_img_embeddings(source_file): """ Load image embeddings saved as pickle file :param source_file: The pickle file where the embeddings are stored :return: a list of image embeddings """ img_embeddings = load_pickle_file(source_file) img_embed = list(img_embeddings.values()) img_embed...
51,586
def test_get_unknown_mappers(row_type): """Tests get_row_mapper for unknown mappings.""" assert get_row_mapper(row_type) is None
51,587
def test_expint(): """ Test various exponential integrals. """ from sympy import (expint, unpolarify, Symbol, Ci, Si, Shi, Chi, sin, cos, sinh, cosh, Ei) assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo), meijerg=True, conds='none' ).rewri...
51,588
def are_aabb_colliding(a, b): """ Return True if given AABB are colliding. :param AABBCollider a: AABB a :param AABBCollider b: AABB b :return: True if AABB are colliding :rtype bool: """ a_min = [a.center[i] - a.size3[i] / 2 for i in range(3)] a_max = [a.center[i] + a.size3[i] / 2 for i in range(3)] b_min ...
51,589
def edit_distance(str1, str2): """ Given two sequences, return the edit distance normalized by the max length. """ matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)] for i in range(1, len(str1) + 1): for j in range(1, len(str2) + 1): if (str1[i - 1] ==...
51,590
def scoped_logger(module_name: str, config_name: str = "maestral") -> logging.Logger: """ Returns a logger for the module ``module_name``, scoped to the given config. :param module_name: Module name. :param config_name: Config name. :returns: Logger instances scoped to the config. """ retu...
51,591
def parse (line): """Parse line into an array of numbers (`EMPTY`, `OCCUPIED`, or `FLOOR`) for each spot in the seatring area. """ return [ CharToInt[c] for c in line.strip() ]
51,592
def create_tables(engine=ENGINE): """ Create all tables in the sql database """ LOG.debug('Creating tables in sql') BASE.metadata.create_all(engine)
51,593
def aic(X, k, likelihood_func): """Akaike information criterion. Args: X (np.ndarray): Data to fit on. k (int): Free parameters. likelihood_func (function): Log likelihood function that takes X as input. """ return 2 * k - 2 * likelihood_func(X)
51,594
def lazy_formatter_gettext( string: str, lazy_formatter: Callable[[str], str], **variables: Any ) -> LazyString: """Formats a lazy_gettext string with a custom function Example:: def custom_formatter(string: str) -> str: if current_app.config["CONDITIONAL_KEY"]: string ...
51,595
def render_color_palette(color: tuple) -> Image.Image: """ Assembles the entire color palette preview from all the render pieces. :param color: the color to lookup :return: the preview image """ pixel, ratio = get_cast_color_info(color) reticle_preview = render_reticle(CAST_COLOR_IMAGE, pix...
51,596
def set_synchronous_mode(world, value, delta=None): """ Sets the synchronous mode on the world to the given value. Args: world: The world to set the synchronous mode on. value: The value to set the synchronous mode to. delta: The delta at which to run the simulator if synchronous mode ...
51,597
def simplify(x): """ Simplify raw string. Combine successive same sign value, drop zeros, drop leading negative """ value = 0 for i in x: if i == 0: continue elif value == 0: if i > 0: value = i else: pass # le...
51,598
def heightmap_get_interpolated_value(hm: np.ndarray, x: float, y: float) -> float: """Return the interpolated height at non integer coordinates. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. x (float): A floating point x coordi...
51,599