content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def auto_read(filename): """Automatically determine the format of filename and open accordingly""" #XXX: this won't work correctly on pipes #would be better to use file magic f = open(filename, 'r') firstchar = f.read(1) f.close() if firstchar == '#': return gnucap_read(filename) else: return sp...
0485626e6305aa43ece6b6cf36a924f7526af26c
3,644,356
import time def WaitForOperation(client, messages, operation_name, operation_description=None, project=None, timeout=180): """Wait for an operation to complete. Polls the operation requested approximately every second, showing a progress indicator. Returns when the ope...
e63b3951dd98762d28050ebff753f78e88cd0231
3,644,357
def get_unstaged_files(gitobj): """ ref: http://gitpython.readthedocs.io/en/stable/tutorial.html#obtaining-diff-information """ diff = [] diff.extend(gitobj.index.diff(gitobj.head.commit)) diff.extend(gitobj.index.diff(None)) return {"changed": diff, "untracked": gitobj.untracked_files}
623a2706bb0d2c428df0f44fe10a473e7d740938
3,644,358
from typing import Optional from typing import Union from typing import Tuple def conv2d( inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None, stride: Union[int, Tuple[int, int]] = 1, padding: Union[int, Tuple[int, int]] = 0, dilation: Union[int, Tuple[int, int]] = 1, groups: int = ...
fff9e2430c21757e3a5a4e1146ead63ad2fb5918
3,644,359
import encodings def find_tex_directives(texfile, ignore_root_loops=False): """Build a dictionary of %!TEX directives. The main ones we are concerned with are: root Specifies a root file to run tex on for this subsidiary TS-program Tells us which latex program to run ...
df639f11f1609ee5c8a6bca0add8c154a42c481a
3,644,360
def projects(): """ Handles the GET & POST request to '/projects'. GET: requests to render page POST: request to edit project with sent data :return: render projects page / Json containing authorisation error / manage(data) function call """ if request.method == "GET": return render_...
7a8a1d9c4d50623ad557d9dcaf419c5a3e83f521
3,644,361
def evolve_fqe_givens_sector(wfn: Wavefunction, u: np.ndarray, sector='alpha') -> Wavefunction: """Evolve a wavefunction by u generated from a 1-body Hamiltonian. Args: wfn: FQE Wavefunction on n-orbitals u: (n x n) unitary matrix. sector: Optional either 'a...
7f8334d64a1965424c5a1faf166bbf8741c0e1ae
3,644,362
from typing import Iterable def epoch_folding_search(times, frequencies, nbin=128, segment_size=5000, expocorr=False, gti=None, weights=1, fdots=0): """Performs epoch folding at trial frequencies in photon data. If no exposure correction is needed and numba is installed, it uses a fa...
7eaa1d038a883babcf55f239acf519f5c059b0b2
3,644,364
def boxbin(x,y,xedge,yedge,c=None,figsize=(5,5),cmap='viridis',mincnt=10,vmin=None,vmax=None,edgecolor=None,powernorm=False, ax=None,normed=False,method='mean',quantile=None,alpha=1.0,cbar=True,unconditional=False,master_count=np.array([])): """ This function will grid data for you and provide the c...
b80a9fdf25d16ecd5e73addae325d1a2348ef900
3,644,367
def _get_elastic_document( tasks: list[dict], symprec: float, fitting_method: str, ) -> ElasticDocument: """ Turn a list of deformation tasks into an elastic document. Parameters ---------- tasks : list of dict A list of deformation tasks. symprec : float Symmetry pr...
f01ea537fbd73c6a2da529a4da15e358033ed2a9
3,644,368
from typing import Union from pathlib import Path from typing import Counter def first(filename: Union[str, Path]) -> int: """ Sort the input, prepend with 0 and append with 3 + the max. Return: (# of successive differences == 1) * (# of successive differences == 3) """ with open(filename...
18ffe3e97d7256ea61fcf6e436d36bb360d0a285
3,644,369
def charge_is_valid(charge_profile, capacity=6, max_charge_rate=2.5, time_unit=0.5): """ Function determining if a charge profile is valid (and fully charges the battery) """ if np.all(np.isclose(capacity/time_unit, charge_profile.groupby(charge_profile.index.date).sum())) is False: return False...
489717fc834b9492ab3add1ddfaa5c55e2f4d8e9
3,644,370
def create_slice_obj(start, end, step): """Create slice object""" return slice(start, end, step)
88a5c5a9e0d3b714b4316d8744fcdd1a34f347a7
3,644,371
def binary_cross_entropy_error(y, t): """バイナリー交差エントロピー誤差""" #y.shape (N,C,H,W) delta = 1e-7 return -np.mean(t*np.log(y + delta) + (1-t)*np.log(1-y + delta))
a0090d4d5e6695ab0c4d988b8f0efbdfcd44984c
3,644,372
def get_abc(): """ :return: list all the abcs as a list """ # ok return list(abcs.find({}, {'_id': False}))
aa2c39bdc8ec1f31f43ea02701b5022f612b286b
3,644,373
from typing import Optional from typing import List def matching_system_code(concept: CodeableConcept, system: str) -> Optional[str]: """ Returns a code from a specified *system* contained within a given *concept*. If no code is found for the given *system*, returns None. Raises an :class:`Assertion...
cd9005ebcfd9ab15e5d27f7f30b8b4ea4b4db7b0
3,644,374
def get_pybullet(env_name): """ Returns pybullet dataset and envrironment. The dataset is provided through d4rl-pybullet. See more details including available dataset from its GitHub page. .. code-block:: python from d3rlpy.datasets import get_pybullet dataset, env = get_pybullet('ho...
79d3e408698ea7454398490a98fd7d653625cbd4
3,644,375
from typing import Iterable from typing import Any def reverse(d: Iterable) -> Any: """Reverses the provided iterable, but also RETURNS it""" d.reverse() return d
5eff6b170afe6424f113ec4b15f985ee8d306e83
3,644,376
def scalar(typename): """ Returns scalar type from ROS message data type, like "uint8" from "uint8[100]". Returns type unchanged if already a scalar. """ return typename[:typename.index("[")] if "[" in typename else typename
729fb68bced11e190b3d32d03bbadd921f191bee
3,644,377
def subject(mock_messenger: AsyncMock) -> initiator.FirmwareUpdateInitiator: """The test subject.""" return initiator.FirmwareUpdateInitiator(mock_messenger)
cfab4395d5ffc3de6a33d3eeb2d7ce373f719b06
3,644,378
def onetangent(ri, rf, ta_transb, k=0, use_alts=True, center='earth'): """Orbit transfer with one tangential burn and one nontangential burn. Must be circular or coaxially elliptic. Currently only for circular orbits. :param ri: altitude (or radius) of initial circular orbit (km) :param rf: altitu...
12eae51bc3833df94b063597e2444df851a7960c
3,644,379
def display_matplot(images, title = None, gray=None): """[Standard display fuction used throughout testing to see the output of thhe various transforms. Displays multilpe plots at once for comparison, always in a square format.] Arguments: images {[Array]} -- [the array that contains all of the ...
635b6c977d1d71a9d7479e064978c3695115d757
3,644,380
def get_version(): """ It returns the pmml version . Returns ------- version : String Returns the version of the pmml. """ version = '4.4' return version
162f6e0ffb4c4741fafe2aa16d6fceed16bae99a
3,644,381
import torch def customsoftmax(inp, multihotmask): """ Custom Softmax """ soft = F.softmax(inp, dim=1) # This takes the mask * softmax ( sums it up hence summing up the classes in border # then takes of summed up version vs no summed version return torch.log( torch.max(soft, (multi...
a0db0926aa9ed804bfab54cfaaf7c4a031809aae
3,644,382
import scipy def mandoline( D_src: np.ndarray, D_tgt: np.ndarray, edge_list: np.ndarray, sigma: float=None, ): """ Mandoline solver. Args: D_src: (n_src x d) matrix of (example, slices) for the source distribution. D_tgt: (n_tgt x d) matrix of (example, slices) for the sou...
5b7817e1ff252724f61572ac6f103ec963c257dd
3,644,383
def service_transformer_info_get(service): # noqa: E501 """Retrieve transformer info Provides information about the transformer. # noqa: E501 :param service: Inxight_Drugs service :rtype: TransformerInfo """ return transformer[service].info
a12d4d19efe7bf8a3c185213790366339aad8c9f
3,644,384
def create_app(config=None, app_name=None): """Create a Flask app.""" if app_name is None: app_name = DefaultConfig.PROJECT app = Flask(app_name, instance_path=INSTANCE_FOLDER_PATH, instance_relative_config=True) configure_app(app, config) configure_hook(app) configure_blueprints(app) ...
95f5191fc64f5656156fc69bd9565b0a754e014c
3,644,385
def read_translocations_tumors(gene_A, gene_B,\ tumor_barcodes,\ data_location=default_location): """ For a given set of tumor barcode and a gene, finds with a lookup the mutation for this particular gene on the TCGA dataset. INPUT: - gene_A (str): fi...
7ae16c2898272676ab1ab2bccde4ca3958fbb4a0
3,644,386
import numbers def simplify_if_constant(symbol, keep_domains=False): """ Utility function to simplify an expression tree if it evalutes to a constant scalar, vector or matrix """ if keep_domains is True: domain = symbol.domain auxiliary_domains = symbol.auxiliary_domains else: ...
c696ec4a7c81251448c97afe92c32f275284f71e
3,644,387
def is_visible(window): """ Check whether the window is visible or not. """ return lib.is_visible(window)
23f146625dcaa3f473ddec1684b9f222496bae48
3,644,388
from typing import Optional import copy def fix_mol( mol: Chem.rdchem.Mol, n_iter: int = 1, remove_singleton: bool = False, largest_only: bool = False, inplace: bool = False, ) -> Optional[Chem.rdchem.Mol]: """Fix error in molecule using a greedy approach. Args: mol: input molecul...
6d745d9ec308e577b73243850e6f46c93c5ff24f
3,644,389
from typing import Iterable from typing import List def permutation_circuit(swaps: Iterable[List[Swap[_V]]]) -> PermutationCircuit: """Produce a circuit description of a list of swaps. With a given permutation and permuter you can compute the swaps using the permuter function then feed it into thi...
c45d5fea5974c3bfb7e695ddc366d4948203e1d1
3,644,390
def Add(a, b): """ Adds two numbers, throws on overflow. """ c = a + b Require(c >= a) return c
cf6c04ed1f5f2f6782e6b91aea739c7e54c1dfe6
3,644,391
from typing import Dict from typing import Type def remap_shared_output_descriptions(output_descriptions: Dict[str, str], outputs: Dict[str, Type]) -> Dict[str, str]: """ Deals with mixed styles of return value descriptions used in docstrings. If the docstring contains a single entry of return value descripti...
06d589016a747230f88aa3507bd751fd30095222
3,644,392
def dist_matrix(): """Fix dist_matrix for the next two tests.""" dist_matrix = np.array([[0, 4, 5, 6], [4, 0, 7, 8], [5, 7, 0, 9], [6, 8, 9, 0]]) return dist_matrix
5bc3e5da5a6c76fd91858a697e2db183c74eb03f
3,644,393
def fitarg_rename(fitarg, ren): """Rename variable names in ``fitarg`` with rename function. :: #simple renaming fitarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1}, lambda pname: 'y' if pname=='x' else pname) #{'y':1, 'limit_y':1, 'fix_y':1, 'error_y':1}, #...
151233d0f18eaea564afbc6d600d576407504b35
3,644,394
def flatten(tensor): """Flattens a given tensor such that the channel axis is first. The shapes are transformed as follows: (N, C, D, H, W) -> (C, N * D * H * W) """ C = tensor.size(1) # new axis order axis_order = (1, 0) + tuple(range(2, tensor.dim())) # Transpose: (N, C, D, H, W) ->...
e7586da0abfdea639b3bb760fe31fca1cc849d1d
3,644,395
def node_to_edge(edges, directed=True): """ From list of edges, record per node, incoming and outgoing edges """ outgoing = defaultdict(set) incoming = defaultdict(set) if directed else outgoing nodes = set() for i, edge in enumerate(edges): a, b, = edge[:2] outgoing[a].add(i...
7e3f7bf93bbf19355b3329762a3531504bbc53a4
3,644,397
from typing import Counter def grouping_cumulative(df, col_index, col_column): """ compute histogram statistic over selected column and in addition group this histograms :param DataFrame df: rich table :param str col_index: column which will be used s index in resulting table :param str col_column: c...
f99b1c2cc4e7bc4e3a3af02414ba82bd057607e9
3,644,398
def _get_matching_stream(smap, itag): """ Return the url and signature for a stream matching itag in smap. """ for x in smap: if x['itag'] == itag and x.get("s"): return x['url'], x['s'] raise IOError("Sorry this video is not currently supported by pafy")
dc83fd3207d5ab4e1c85eb719f5f7d023131565e
3,644,399
import functools def Debounce(threshold=100): """ Simple debouncing decorator for apigpio callbacks. Example: `@Debouncer() def my_cb(gpio, level, tick) print('gpio cb: {} {} {}'.format(gpio, level, tick)) ` The threshold can be given to the decorator as an argument (in millis...
156b128ffaa579ead371bff3c4b4f20a2a05646b
3,644,400
def int_to_uuid(number): """ convert a positive integer to a UUID : a string of characters from `symbols` that is at least 3 letters long""" assert isinstance(number,int) and number >= 0 if number == 0: return '000' symbol_string = '' while number > 0: remainder = number % base ...
49ce7bfeb4e11c90b2589b8b4003c3135ba78f53
3,644,403
def count_digit(n, digit): """Return how many times digit appears in n. >>> count_digit(55055, 5) 4 """ if n == 0: return 0 else: if n%10 == digit: return count_digit(n//10, digit) + 1 else: return count_digit(n//10, digit)
29cf3db8cca85e14b3b537f96246803d8176441d
3,644,405
def cal_chisquare(data, f, pepoch, bin_profile, F1, F2, F3, F4, parallel=False): """ calculate the chisquare distribution for frequency search on the pepoch time. """ chi_square = np.zeros(len(f), dtype=np.float64) t0 = pepoch if parallel: for i in prange(len(f)): phi = (da...
13dfc33cd975758a3f6c64ff2da4f91409cfdae4
3,644,406
def rng() -> np.random.Generator: """Random number generator.""" return np.random.default_rng(42)
2c2f88eed71c9429edc25a06890266f5b7e8fc22
3,644,408
def add_values_in_dict(sample_dict, key, list_of_values): """Append multiple values to a key in the given dictionary""" if key not in sample_dict: sample_dict[key] = list() sample_dict[key].extend(list_of_values) temp_list = sample_dict[key] temp_list = list(set(temp_list)) # remove duplica...
8c30b50256fd16eb1b9eefae5cc6ab5be58fe85f
3,644,409
def parse_length(line, p) -> int: """ parse length specifer for note or rest """ n_len = voices[ivc].meter.dlen # start with default length try: if n_len <= 0: SyntaxError(f"got len<=0 from current voice {line[p]}") if line[p].isdigit(): # multiply note length ...
cee6c83eecbea455a53c3d4ac9a778d7351b66e0
3,644,410
def get_dual_shapes_and_types(bounds_elided): """Get shapes and types of dual vars.""" dual_shapes = [] dual_types = [] layer_sizes = utils.layer_sizes_from_bounds(bounds_elided) for it in range(len(layer_sizes)): m = layer_sizes[it] m = [m] if isinstance(m, int) else list(m) if it < len(layer_siz...
297a305d8ef71d614eae21c3fc5c52ef08b271a3
3,644,411
def linear_search(alist, key): """ Return index of key in alist . Return -1 if key not present.""" for i in range(len(alist)): if alist[i] == key: return i return -1
ab4c0517f9103a43509b0ba511c75fe03ea6e043
3,644,412
def overlap_integral(xi, yi, zi, nxi, nyi, nzi, beta_i, xj, yj, zj, nxj, nyj, nzj, beta_j): """ overlap <i|j> between unnormalized Cartesian GTOs by numerical integration on a multicenter Becke grid Parameters ---------- xi,yi,zi : floats Cartesian posit...
500da2037d5e9f880f239788156cc717163b6b0c
3,644,413
def save_project_id(config: Config, project_id: int): """Save the project ID in the project data""" data_dir = config.project.data_dir filename = data_dir / DEFAULT_PROJECTID_FILENAME with open(filename, "w") as f: return f.write(str(project_id))
9769067d222c8430764a2abd4def67a9ce45e49a
3,644,414
async def session_start(): """ session_start: Creates a new database session for external functions and returns it - Keep in mind that this is only for external functions that require multiple transactions - Such as adding songs :return: A new database session ...
cb84d30a8a89bdf58c63114fa84558d7567396bd
3,644,415
from pm4py.objects.bpmn.obj import BPMN from pm4py.objects.bpmn.util.sorting import get_sorted_nodes_edges from typing import Optional from typing import Dict from typing import Any import tempfile def apply(bpmn_graph: BPMN, parameters: Optional[Dict[Any, Any]] = None) -> graphviz.Digraph: """ Visualize a BP...
ca1e25dfe758712125327717e01cba36788b8b38
3,644,416
def _predict_exp(data, paulistring): """Compute expectation values of paulistring given bitstring data.""" expectation_value = 0 for a in data: val = 1 for i, pauli in enumerate(paulistring): idx = a[i] if pauli == "I": continue elif pauli ...
32737920e750780655ba85ae9e57d6e3cd0f194c
3,644,417
import math def AGI(ymod1, c02500, c02900, XTOT, MARS, sep, DSI, exact, nu18, taxable_ubi, II_em, II_em_ps, II_prt, II_no_em_nu18, c00100, pre_c04600, c04600): """ Computes Adjusted Gross Income (AGI), c00100, and compute personal exemption amount, c04600. """ # calculate AGI assum...
aed1c311bc6b46b46bfea3e9756cd73933c37ca9
3,644,418
def tokenize(headline_list): """ Takes list of headlines as input and returns a list of lists of tokens. """ tokenized = [] for headline in headline_list: tokens = word_tokenize(headline) tokenized.append(tokens) return tokenized
e5cf957a72d6d08d95787bf0f2222e525727c54a
3,644,419
def create_en_sentiment_component(nlp: Language, name: str, force: bool) -> Language: """ Allows the English sentiment to be added to a spaCy pipe using nlp.add_pipe("asent_en_v1"). """ LEXICON.update(E_LEXICON) return Asent( nlp, name=name, lexicon=LEXICON, intensif...
f66ab4d86da2d42adb7c8da95cfdff9517dcc34f
3,644,420
import json def lambda_handler(event, context): """ 店舗一覧情報を返す Parameters ---------- event : dict フロントより渡されたパラメータ context : dict コンテキスト内容。 Returns ------- shop_list : dict 店舗一覧情報 """ # パラメータログ logger.info(event) try: shop_list = get_sh...
48eebf18d34e50a98d00bd589b9d8a0712b9f985
3,644,421
import warnings def mask_land_ocean(data, land_mask, ocean=False): """Mask land or ocean values using a land binary mask. Parameters ---------- data: xarray.DataArray This input array can only have one of 2, 3 or 4 dimensions. All spatial dimensions should coincide with those ...
97d32c2720db12e47738a58d2152d7052af095ed
3,644,422
def create_project_type(project_type_params): """ :param project_type_params: The parameters for creating an ProjectType instance -- the dict should include the 'type' key, which specifies the ProjectType subclass name, and key/value pairs matching constructor arguments for that ProjectType subc...
446961674985a2f5a64417d6f1f9bc6b39f7fbe4
3,644,423
def env_str(env_name: str, default: str) -> str: """ Get the environment variable's value convert into string """ return getenv(env_name, default)
529adfcfe770a39a5997d92792fdd2c857b32a41
3,644,424
def extract_sigma_var_names(filename_nam): """ Parses a 'sigma.nam' file containing the variable names, and outputs a list of these names. Some vector components contain a semicolon in their name; if so, break the name at the semicolon and keep just the 1st part. """ var_names = [] wit...
930e855d47c4303cac28e9973982392489fb577d
3,644,426
def vectors_to_arrays(vectors): """ Convert 1d vectors (lists, arrays or pandas.Series) to C contiguous 1d arrays. Arrays must be in C contiguous order for us to pass their memory pointers to GMT. If any are not, convert them to C order (which requires copying the memory). This usually happens ...
c9a3878f2d1099ffd985525931f05df1b8631c46
3,644,427
import random import string def random_name_gen(size=6): """Generate a random python attribute name.""" return ''.join( [random.choice(string.ascii_uppercase)] + [random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)] ) if size > 0 else ''
67ade3cde47fffc126cbdb11f01ffda2672d021c
3,644,428
def is_identity(u, tol=1e-15): """Test if a matrix is identity. Args: u: np.ndarray Matrix to be checked. tol: float Threshold below which two matrix elements are considered equal. """ dims = np.array(u).shape if dims[0] != dims[1]: raise Exception("...
160f33651b9d79448167423542cd1e2ad0bd3110
3,644,430
def get_metrics(): """ Collects various system metrics and returns a list of objects. """ metrics = {} metrics.update(get_memory_metrics()) metrics.update(get_cpu_metrics()) metrics.update(get_disk_metrics()) return metrics
d4055e0eb23d9babb9882bc3c089af293c638def
3,644,431
import inspect def create_fun(name: str, obj, options: dict): """ Generate a dictionnary that contains the information about a function **Parameters** > **name:** `str` -- name of the function as returned by `inspect.getmembers` > **obj:** `object` -- object of the function as returned by `inspec...
f95e6fab1ed0cf6a10574b790e81933c40b924c4
3,644,433
def serial_ss(file_read, forward_rate, file_rateconstant, file_energy, matrix, species_list, factor, initial_y, t_final, third_body=None, chemkin_data=None, smiles=None, chemkin=True): """ Iteratively solves the system of ODEs for different rate constants generated ...
f23693826c3507d9a2327b4b492f20469fca963f
3,644,434
def contains_left_button(buttons) -> bool: """ Test if the buttons contains the left mouse button. The "buttons" should be values returned by get_click() or get_mouse() :param buttons: the buttons to be tested :return: if the buttons contains the left mouse button """ return (buttons & QtC...
a5cde64ce1d1fa5fd1fe57988f8b60db03fc2dcf
3,644,435
def is_bst(t: BST) -> bool: """Returns true if t is a valid BST object, false otherwise. Invariant: for each node n in t, if n.left exists, then n.left <= n, and if n.right exists, then n.right >= n.""" if not isinstance(t, BST): return False if t._root and t._root.parent is not None: ...
5180d01f8306f79b6ed4551e7d2bd4046a088ac2
3,644,438
def are_embedding_layer_positions_ok_for_testing(model): """ Test data can only be generated if all embeddings layers are positioned directly behind the input nodes """ def count_embedding_layers(model): layers = model.layers result = 0 for layer in layers: if is...
4317cdc11e0b0acf84fda0c2633400851075e124
3,644,439
from typing import Any def all_tasks_stopped(tasks_state: Any) -> bool: """ Checks if all tasks are stopped or if any are still running. Parameters --------- tasks_state: Any Task state dictionary object Returns -------- response: bool True if all tasks are stopped. ...
98edffe71052cc114a7dda37a17b3a346ef59ef8
3,644,440
import PIL def enhance_color(image, factor): """Change the strength of colors in an image. This function has identical outputs to ``PIL.ImageEnhance.Color``. Added in 0.4.0. **Supported dtypes**: * ``uint8``: yes; fully tested * ``uint16``: no * ``uint32``: no *...
f6654fc0b4dfebecf221e4a34ec0c894e1c72d1f
3,644,441
def random_deceleration(most_comfortable_deceleration, lane_pos): """ Return a deceleration based on given attribute of the vehicle :param most_comfortable_deceleration: the given attribute of the vehicle :param lane_pos: y :return: the deceleration adopted by human driver """ if lane_pos: ...
c5e4f9ca16285c020b9b7f2376e0b43f198d5173
3,644,442
def dataclass_fields(dc): """Returns a dataclass's fields dictionary.""" return {name: getattr(dc, name) for name in dc.__dataclass_fields__}
4b82af3bfbc02f7bbfcf1aecb6f6501ef10d86e1
3,644,443
from mabel import DictSet, Reader from ...internals.group_by import GroupBy def SqlReader(sql_statement: str, **kwargs): """ Use basic SQL queries to filter Reader. Parameters: sql_statement: string kwargs: parameters to pass to the Reader Note: `select` is taken from SQL SEL...
0354dd8b4d8cc6913cc1887b96aba6a06613ffe5
3,644,447
def _handle_consent_confirmation(user, is_confirmed): """ Return server response given user consent. Args: user (fence.models.User): authN'd user is_confirmed (str): confirmation param """ if is_confirmed == "yes": # user has already given consent, continue flow resp...
c4f61ed8465616a4fad912d02e81840eb9d34604
3,644,448
import math def local_coherence(img, window_s=WSIZ): """ Calculate the coherence according to methdology described in: Bazen, Asker M., and Sabih H. Gerez. "Segmentation of fingerprint images." ProRISC 2001 Workshop on Circuits, Systems and Signal Processing. Veldhoven, The Netherlands, 2001. """ ...
d360b388d743a3ada1004be8367ed2d105f7857a
3,644,449
def storeIDToWebID(key, storeid): """ Takes a key (int) and storeid (int) and produces a webid (a 16-character str suitable for including in URLs) """ i = key ^ storeid l = list('%0.16x' % (i,)) for nybbleid in range(0, 8): a, b = _swapat(key, nybbleid) _swap(l, a, b) ret...
38d9bffaa98c2191e818edd969d51873bb077094
3,644,450
def _jupyter_server_extension_paths(): """ Set up the server extension for collecting metrics """ return [{"module": "jupyter_resource_usage"}]
f59c343dd8bcdb4755c725107b3c83f12978e9ef
3,644,451
import collections def _make_ordered_node_map( pipeline: p_pb2.Pipeline ) -> 'collections.OrderedDict[str, p_pb2.PipelineNode]': """Helper function to prepare the Pipeline proto for DAG traversal. Args: pipeline: The input Pipeline proto. Since we expect this to come from the compiler, we assume th...
c0f7af61adf114a3b2211d82de050bf5e1f4e681
3,644,452
from typing import Optional from typing import Tuple def fmin_b_bfgs(func, x0, args=(), options=None): """ The BFGS algorithm from Algorithm 6.1 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 136-143 with bounded parameters, using the active set approach from, Byrd, R. H., L...
0f8ce3e1873b9a5a955b95489ea454e3c9813524
3,644,454
def find_broken_in_text(text, ignore_substrings=None): """Find broken links """ links = _find(text, ignore_substrings=ignore_substrings) responses = [_check_if_broken(link) for link in links] return [res.url for res in responses if res.broken]
43075b6abb1ba8e7fc6f163e1afd1d6f305d99ab
3,644,455
def home(): """ route for the index page""" return jsonify({"message" : "welcome to fast_Food_Fast online restaurant"})
cad54560f01361ff6d9fed1d117f8b50eff59b50
3,644,457
def singlediode_voc(effective_irradiance, temp_cell, module_parameters): """ Calculate voc using the singlediode model. Parameters ---------- effective_irradiance temp_cell module_parameters Returns ------- """ photocurrent, saturation_current, resistance_series, resistan...
b47cff93f7ad51ce026fd1e28c6427bcaca0a639
3,644,458
from apysc._file import file_util from typing import Optional from typing import List def _exec_document_lint_and_script( limit_count: Optional[int] = None) -> List[str]: """ Execute each runnable scripts in the documents and check with each lint. Parameters ---------- limit_count : i...
a9406dfc5180c5b0f820740ae99522d8141af22d
3,644,459
from typing import Dict from typing import Union def _apply_result_filters(key_gender_token_counters: Dict[Union[str, int], GenderTokenCounters], diff: bool, sort: bool, limit: int, remove_swords: bool) -> KeyGende...
120bb37936293810796ad6e62cee6b3c0bccabe4
3,644,462
def blog_delete(request): """Delete blog entry by id.""" blog_id = int(request.params.get('id')) entry = BlogRecordService.by_id(blog_id, request) if not entry: return HTTPNotFound() request.dbsession.delete(entry) return HTTPFound(location=request.route_url('home'))
4e1b9a19cd3a33743479de69ee1fbc4ffc9f9a42
3,644,463
import aiohttp async def get_ios_cfw(): """Gets all apps on ios.cfw.guide Returns ------- dict "ios, jailbreaks, devices" """ async with aiohttp.ClientSession() as session: async with session.get("https://api.appledb.dev/main.json") as resp: if resp.status == 200:...
dfb0dfafef2ef8e27940bc7a154cd4a35f863017
3,644,464
def server_error(errorMsg): """ Shorthand for returning error message. """ resp = HttpResponse(status=502) resp.write("<h3>502 BAD GATEWAY: </h3>") resp.write("<p>ERROR: {}</p>".format(errorMsg)) return resp
cadadfc0a8c0098832ca08080e3602bdaf01ffc4
3,644,465
import re def protein_variant(variant): """ Return an HGVS_ variant string containing only the protein changes in a coding HGVS_ variant string. If all variants are synonymous, returns the synonymous variant code. If the variant is wild type, returns the wild type variant. :param str variant:...
ed9d11759ed5d09f76daa757b9e75d00bfd0f029
3,644,466
import scipy from functools import reduce def calc_predictability_trace_of_avg_cov(x, k, p, ndim=False): """ The main evaluation criterion of GPFA, i.e., equation (2) from the paper. :param x: data array :param k: number of neighbors for estimate :param p: number of past time steps to consider ...
a803847ce8f8791edf44d3ba102137e69836f410
3,644,469
from typing import Dict from typing import Sequence def nx_to_loreleai(graph: nx.Graph, relation_map: Dict[str, Predicate] = None) -> Sequence[Atom]: """ Converts a NetworkX graph into Loreleai representation To indicate the type of relations and nodes, the functions looks for a 'type' attribute Arg...
f847c26d0831bf6bbaf16eabe5a32d27118550da
3,644,470
def _kohn_sham_iteration( density, external_potential, grids, num_electrons, xc_energy_density_fn, interaction_fn, enforce_reflection_symmetry): """One iteration of Kohn-Sham calculation.""" # NOTE(leeley): Since num_electrons in KohnShamState need to specify as # static argument in ji...
81ecffb04d0bc76b31187708c3502acead8653ab
3,644,471
def get_sync_func_driver(physical_mesh): """Get the sync function on the driver.""" def sync_func_driver(): assert isinstance(physical_mesh, LocalPhysicalDeviceMesh) physical_mesh.devices[0].synchronize_all_activity() return sync_func_driver
13dee330aa22524c52272c1969f3acba23f4378f
3,644,472
def get_nc_BGrid_GFDL(grdfile): """ Bgrd = get_nc_BGrid_GFDL(grdfile) Load B-Grid grid object for GFDL CM2.1 from netCDF grid file """ nc = pyroms.io.Dataset(grdfile) lon_t = nc.variables['geolon_t'][:] lat_t = nc.variables['geolat_t'][:] lon_uv = nc.variables['geolon_c'][:] lat_u...
0b6f844676da7f357334640eafdb3039127df912
3,644,473
def _getTimeDistORSlocal(fromLocs, toLocs, travelMode, port, speedMPS): """ Generate two dictionaries, one for time, another for distance, using ORS-local Parameters ---------- fromLocs: list, Required The start node coordinates in format of [[lat, lon], [lat, lon], ... ] toLocs: list, Required The End node ...
67feca093769c4cef4f4383cb6eaca4e0f584019
3,644,474
def sequence_plus_one(x_init, iter, dtype=int): """ Mathematical sequence: x_n = x_0 + n :param x_init: initial values of the sequence :param iter: iteration until the sequence should be evaluated :param dtype: data type to cast to (either int of float) :return: element at the given iteration a...
ec84cdb2f98147d2d1d967f7a071d3124ccdf54a
3,644,475
def _is_test_product_type(product_type): """Returns whether the given product type is for tests purposes or not.""" return product_type in ( apple_product_type.ui_test_bundle, apple_product_type.unit_test_bundle, )
41847ab87e4a8a0dfc2b2758b70b5f7b5d7b952b
3,644,476
def _synced(method, self, args, kwargs): """Underlying synchronized wrapper.""" with self._lock: return method(*args, **kwargs)
54ca3cf69742550bd34ff3d2299a2d84f78577a3
3,644,477