content
stringlengths
22
815k
id
int64
0
4.91M
def compute_kld(confidences: torch.Tensor, reduction="mean") -> torch.Tensor: """ Args: confidences (Tensor): a tensor of shape [N, M, K] of predicted confidences from ensembles. reduction (str): specifies the reduction to apply to the output. - none: no reduction will be applied, ...
11,500
def create_mappings(index_name, payload_file_path): """ create mapping in es """ try: url = '{}/{}'.format(config['es_url'], index_name) resp = requests.get(url) if resp.status_code // 100 == 4: # if no such index there with codecs.open(payload_file_path, 'r') as f: ...
11,501
def get_crypto_quote(symbol, info=None): """Gets information about a crypto including low price, high price, and open price :param symbol: The crypto ticker. :type symbol: str :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Opt...
11,502
def test_register_task_decl_duplicate1(collector, task_decl): """Test handling duplicate : in collector. """ collector.contributions['exopy.Task'] = None tb = {} task_decl.task = 'exopy.tasks:Task' task_decl.register(collector, tb) assert 'exopy.Task_duplicate1' in tb
11,503
def plot_contours_2D(clf, xx, yy, **params): """Plot the decision boundaries for a classifier. Parameters ---------- ax: matplotlib axes object clf: a classifier xx: meshgrid ndarray yy: meshgrid ndarray params: dictionary of params to pass to contourf, optional """ Z = clf.pred...
11,504
def fix(item, missing_atoms=True, missing_residues=True, nonstandard_residues=True, missing_terminals=True, missing_loops=False, missing_hydrogens=True, pH=7.4, to_form=None, engine_fix='PDBFixer', engine_hydrogens='PDBFixer', engine_loops='Modeller', verbose=False): """fix_pdb_structure(it...
11,505
def data_split(*args, **kwargs): """A function to split a dataset into train, test, and optionally validation datasets. **Arguments** - ***args** : arbitrary _numpy.ndarray_ datasets - An arbitrary number of datasets, each required to have the same number of elements, as numpy arrays....
11,506
def compare(isamAppliance1, isamAppliance2): """ Compare Policy Sets between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) for obj in ret_obj1['data']: del obj['id'] del obj['userlastmodified'] del obj['lastmodified'] de...
11,507
def hardwareRenderPanel(*args, **kwargs): """ This command creates, edit and queries hardware render panels which contain only a hardware render editor. Returns: `string` Panel name """ pass
11,508
def capacity(quantity, channel, gamma, dim, basis, eps, **kwargs): """ Runs the Blahut-Arimoto algorithm to compute the capacity given by 'quantity' (which can be 'h', 'tc', 'coh' or 'qmi' taking the channel, gamma, dim, basis and tolerance (eps) as inputs). With the optional keyword arguments ...
11,509
def test_get_raw_features_and_labels_examples_in_same_order() -> None: """Tests that the raw features and raw labels have examples in the same order. For example, say X_train[0] is the raw Bulbasaur image; then y_train[0] must be the labels for Bulbasaur.""" # pylint: disable=invalid-name processor ...
11,510
def get_Teq_from_L(L: ArrayLike, d: ArrayLike, A: ArrayLike) -> np.ndarray: """Calculates the equilibrium temperature of a planet given the stellar luminosity L, planetary semi-major axis d and surface albedo A: Args: L (ArrayLike): Stellar luminosity in erg/s. d (ArrayLike): Planetary ...
11,511
def lookup_container_plugin_by_type(container: IContainer, plugin_type: Type[ContainerResolutionPlugin]): """ Given a container, finds the first plugin that is an instance of the specified type. :param container: The container to perform the lookup on. :param plugin_type: The type of the plugin to find...
11,512
def restore_flag_values(saved_flag_values, flag_values=FLAGS): """Restores flag values based on the dictionary of flag values. Args: saved_flag_values: {'flag_name': value_dict, ...} flag_values: FlagValues, the FlagValues instance from which the flag will be restored. This should almost never need...
11,513
async def test_repo_cloner_clone_local_repo(local_repo: Repo): """ checks that the cloner can handle a local repo url """ repo: Repo = local_repo root: str = repo.working_tree_dir target_path: str = Path(root).parent / "target" result = await RepoCloner( repo_url=root, clon...
11,514
def shift_map_longitude(mapdata, lonshift, spline_order=1): """ Simple shift of the map by wrapping it around the edges Internally uses scipy's ndimage.shift with spline interpolation order as requested for interpolation Parameters ---------- mapdata : 2D Numpy array A map with the...
11,515
def aalogoheights(aahistObj, N=20): """For a objhist of AA frequencies, compute the heights of each AA for a logo plot""" aahistObj = deepcopy(aahistObj) keys = list(aahistObj.keys()) for aa in BADAA: if aa in keys: dummy = aahistObj.pop(aa) keys = [aa for aa in aahistObj.sor...
11,516
def upgrade(): """Upgrade database schema and/or data, creating a new revision.""" connection = op.get_bind() # Get tuples (newer-id, older-id) of mirrored relationships created # by external user. It's not safe to remove relationships created by # regular GGRC users, because these relationship might be ref...
11,517
def cmdline_opts( request ): """PyMTL options parsed from pytest commandline options.""" opts = _parse_opts_from_request( request ) # If a fixture is used by a test class, this seems to be the only # way to retrieve the fixture value. # https://stackoverflow.com/a/37761165/13190001 if request.cls is not No...
11,518
def replace(index, ndim, axes, rindices): """Replace indexing for a specified dimension Args: index(index): object used in slicing ndim(num): number of dimensions axes(list): dimension to be replaced rindex(list): new indexing for this dimensions Returns: index "...
11,519
def _closed(sock): """Return True if we know socket has been closed, False otherwise. """ try: rd, _, _ = select([sock], [], [], 0) # Any exception here is equally bad (select.error, ValueError, etc.). except: return True return len(rd) > 0
11,520
def get_forest_connection(device_name: str, seed=None): """Get a connection to a forest backend Args: device_name: the device to connect to Returns: A connection to either a pyquil simulator or a QPU """ if device_name == "wavefunction-simulator": return WavefunctionSimulat...
11,521
def get_slack_colour(level): """Return Slack colour value based on log level.""" level = level.upper() colours = { "CRITICAL": "ff0000", "ERROR": "ff9933", "WARNING": "ffcc00", "INFO": "33ccff", "DEBUG": "good" } return colours.get(level, "good")
11,522
async def async_setup_platform( hass, config, async_add_entities, discovery_info=None ): """Initialise Hue Bridge connection.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = HueSensorData(hass) await hass.data[DOMAIN].async_add_platform_entities( HueBinarySensor, BINARY_SENSO...
11,523
def add_suffix(path, suffix=""): """Adds a suffix to a filename *path*""" return join(dirname(path), basename(path, ext=False) + suffix + extname(path))
11,524
def MdAE_np(preds, labels): """ Median Absolute Error :param preds: :param labels: :return: """ preds = np.reshape(preds, [-1]) labels = np.reshape(labels, [-1]) return np.median(np.abs(preds - labels))
11,525
async def s3_fetch_object(url, s3, range=None, **kw): """ returns object with On success: .url = url .data = bytes .last_modified -- last modified timestamp .range = None | (in,out) .error = None On failure: .url = url .data = None .last_mod...
11,526
def _create_topic(committer_id, topic, commit_message, commit_cmds): """Creates a new topic, and ensures that rights for a new topic are saved first. Args: committer_id: str. ID of the committer. topic: Topic. Topic domain object. commit_message: str. A description of changes made t...
11,527
def mss(**kwargs): # type: (Any) -> MSSMixin """ Factory returning a proper MSS class instance. It detects the plateform we are running on and choose the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ ...
11,528
def reshape_fps(X): """Reshape 4D fingerprint data to 2D If X is already 2D, do nothing. Returns: reshaped X """ if len(X.shape) == 4: num_factors = X.shape[3] num_fps = np.prod(X.shape[:3]) X.shape = (num_fps,num_factors) else: num_factors = X.shape[1] ...
11,529
def experiment(config, loss_select, opt_select): """Run optimizers with all configurations from config""" losses = config["loss"] optimizers = config["optimizer"] for loss in losses: for opt in optimizers: loss_config = {**config["loss"][loss]} opt_params = config["optimi...
11,530
def df_fc_overlap_2(): """Scenario case with 2 fragments overlapping, bound to a common fragment.""" mol = Chem.MolFromSmiles('NC1CC(CCC1O)C1CCC1') return DataFrame([ ['mol_fc_overlap_2', 'XXX', 'O1', 0, 'O1:0', 'O2', 0, 'O2:0', 'ffo', 'fusion', 'false_positive', 'overlap', (7, 6, 5, 4...
11,531
def show_toolbar(request): """Determines whether debug toolbar should be shown for the request. Requires settings.DEBUG=True, 'debug_toolbar' GET param present, and request ip in settings.INTERNAL_IPS. Args: request: HttpRequest object. Returns: Boolean. """ if ('debug_too...
11,532
def strfnow(fmt=HUMAN_DATETIME): """ Returns a string representation of the current timestamp """ return datetime.now(tzlocal()).strftime(fmt)
11,533
def tag_to_dict(node): """Assume tag has one layer of children, each of which is text, e.g. <medalline> <rank>1</rank> <organization>USA</organization> <gold>13</gold> <silver>10</silver> <bronze>9</bronze> <total>32</total> </medalline> """ d =...
11,534
def test_id_rot(): """Test equivalence of constants that represent no rotation.""" assert_array_almost_equal(R_id, matrix_from_axis_angle(a_id)) assert_array_almost_equal(R_id, matrix_from_quaternion(q_id)) assert_array_almost_equal(R_id, matrix_from_euler_xyz(e_xyz_id)) assert_array_almost_equal(R_...
11,535
def compute_contact_centroid(molecular_complex: Any, cutoff: float = 4.5) -> np.ndarray: """Computes the (x,y,z) centroid of the contact regions of this molecular complex. For a molecular complex, it's necessary for various featurizations that compute voxel grids to find a reasonable...
11,536
def general_operator_gamma_norm(matrix, gamma, max_j, max_q): """ Returns the gamma operator norm of matrix, summing up to max_j and considering the sup up to max_q. Assumed that matrix is a function accepting two arguments i,j and not an array () for efficiency. """ max_j_sum = -1 q = ...
11,537
def crop_image_single(img, device): """ Implementation of the MTCNN network to crop single image to only show the face as shown in the facenet_pytorch doc: https://github.com/timesler/facenet-pytorch/blob/master/examples/infer.ipynb :param device: pytorch device :param img: s...
11,538
def tf2zpk(b, a): """Return zero, pole, gain (z,p,k) representation from a numerator, denominator representation of a linear filter. Parameters ---------- b : ndarray Numerator polynomial. a : ndarray Denominator polynomial. Returns ------- z : ndarray Zeros...
11,539
def gpiod_line_is_free(line: gpiod_line) -> bool: """ @brief Check if the calling user has neither requested ownership of this line nor configured any event notifications. @param line: GPIO line object. @return True if given line is free, false otherwise. """ return line.state == _L...
11,540
def aseta_nappain_kasittelija(kasittelija): """ Asettaa funktion, jota käytetään näppäimistöpainallusten käsittelyyn. Tarvitaan vain jos haluat pelisi käyttävän näppäimistöä johonkin. Käsittelijäfunktiolla tulee olla kaksi parametria: symboli ja muokkausnapit. Symboli on vakio, joka on asetettu p...
11,541
def test_content(google_translator): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string assert google_translator.translate(payload='좋은') == "good"
11,542
def train_step(optimizer, inputs, learning_rate_fn, dropout_rng=None): """Perform a single training step.""" weights = jnp.where(inputs > 0, 1, 0) # We handle PRNG splitting inside the top pmap, rather # than handling it outside in the training loop - doing the # latter can add some stalls to the devices. ...
11,543
def doublet_line_polar_u(rcp,zcp,dmz_dz, bSelfInd=False): """ Velocity field induced by a semi-infinite doublet line (on the z axis) of intensity `dmz_dz` Control points defined by polar coordinates `rcp` and `zcp`. \int 1/(r^2 + (z-x)^2 )^(3/2) dx \int 1/(r^2 + (z-x)^2 )^(5/2) dx """ i...
11,544
def paginate(text: str): """Simple generator that paginates text.""" last = 0 pages = [] for curr in range(0, len(text)): if curr % 1980 == 0: pages.append(text[last:curr]) last = curr appd_index = curr if appd_index != len(text) - 1: pages.append(...
11,545
def check_estimator(Estimator): """Check if estimator adheres to scikit-learn conventions. This estimator will run an extensive test-suite for input validation, shapes, etc. Additional tests for classifiers, regressors, clustering or transformers will be run if the Estimator class inherits from the ...
11,546
def get(): """ Get the current version number. Reads from the pyproject.toml file. """ print(get_toml_version())
11,547
def get_batch_copy(vocab_size, batch_size, seq_len): """Generates random data for copying.""" batch = np.random.choice( vocab_size - 1, size=[batch_size, seq_len // 2 - 1]) + 1 batch = np.concatenate([np.zeros([batch_size, 1], dtype=int), batch], axis=1) batch = np.concatenate([batch] * 2, axis=1) batc...
11,548
def buildCompareDFs(strTodayFileName): """read in and return today's CSV as DF, determine appropriate old CSV as DF, and the old file name for use later""" # get today's file dfTodaysCards = pandas.read_csv( DATA_DIR_NAME + strTodayFileName, dtype={'Card Number': object}) dfTodaysCards = cleanC...
11,549
def _vj_stat(v = None, j = None, freq_type = 'vj_occur_freq', ts = None): """ Return estimate of a single v-gene, j-gene, or vj-gene-pairings frequency specified < v > and <j> argumens , given a tcrsamper instance < ts > Parameters ---------- v : str j : str e.g., freq_type :...
11,550
def __cvx_eda(y, delta, tau0=2., tau1=0.7, delta_knot=10., alpha=8e-4, gamma=1e-2, solver=None, options={'reltol': 1e-9, 'show_progress': False}): """ CVXEDA Convex optimization approach to electrodermal activity processing This function implements the cvxEDA algorithm described in "cvxEDA: a ...
11,551
def pulsar_from_opencv_projection( R: torch.Tensor, tvec: torch.Tensor, camera_matrix: torch.Tensor, image_size: torch.Tensor, znear: float = 0.1, ) -> torch.Tensor: """ Convert OpenCV style camera parameters to Pulsar style camera parameters. Note: * Pulsar does NOT ...
11,552
def identity(gender:str = None) -> dict: """ Generates a pseudo-random identity. Optional args gender: 'm' for traditionally male, 'f' for traditionally female. Returns a dict with the following keys: name -> full name given -> given name / first name family -> family name ...
11,553
def matthews_corrcoef(y_true, y_pred): """Returns matthew's correlation coefficient for binary classes The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary (two-class) classifications. It takes into account true and false positives and negatives and is ...
11,554
def convert_image_link(image): """Convert an image link specification into a Markdown image link Args: image (Match): A Match object corresponding to an image link Returns: str: Markdown formatted link to the image """ image_name = str(image.group(1)) file_ext = 'jpg' i...
11,555
def yaml_dump(dict_to_dump: Dict[str, Any]) -> str: """Dump the dictionary as a YAML document.""" return yaml.safe_dump(dict_to_dump, default_flow_style=False)
11,556
def test_delete_files_success_nofile(s3_mock, paths, bucket): """delete_files should run successfully even when files not found.""" # Arrange s3_mock.create_bucket( Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": "eu-west1"} ) # Act & Assert assert delete_files(paths) is...
11,557
def completeness(importance_matrix): """"Compute completeness of the representation.""" per_factor = completeness_per_code(importance_matrix) if importance_matrix.sum() == 0.: importance_matrix = np.ones_like(importance_matrix) factor_importance = importance_matrix.sum(axis=0) / importance_matrix.sum() re...
11,558
def image_stat(image_id): """ Return the statistics ofd an image as a pd dataframe :param image_id: :return: """ counts, total_area, mean_area, std_area = {}, {}, {}, {} img_area = get_image_area(image_id) for cl in CLASSES: polygon_list = get_polygon_list(image_id, cl) ...
11,559
def delete_original(): """ Decorator that deletes the original Discord message upon command execution. :return: boolean """ async def predicate(ctx): if ctx.invoked_with != "help": # Don't try to delete if help command if isinstance(ctx.message.channel, discord.TextChannel...
11,560
def resize_stanford_dataset(inp_dir, out_dir): """ The function resizes all the images in stanford dataset to 224x224 """ print_after_iter = 1000 files = [f for f in os.listdir(inp_dir) if os.path.isfile(os.path.join(inp_dir, f))] for i in range(len(files)): if i % print_after_iter == 0:...
11,561
def test_stream_targets_info(): """ Tests an API call to get stream targets """ response = stream_targets_instance.info() assert isinstance(response, dict) assert 'stream_targets' in response
11,562
def test_cli_stdio_hub(runner, echo, app): """ Ensures tcp starts a server. """ with runner.isolated_filesystem(): with open('my.hub', 'w') as f: f.write('Hello World!') e = runner.invoke(Cli.main, ['--hub=my.hub', 'stdio']) assert e.exit_code == 0 App.__init_...
11,563
def list_template_dirs(): """List names of directories containnig parallel programming templates.""" dirs = [] for templates_dir in settings.TEMPLATE_DIRS: for template_dir in os.listdir(templates_dir): path = os.path.join(templates_dir,template_dir) if os.path.isdir(path): ...
11,564
def fcd2dri(inpFCD, outSTRM, ignored): """ Reformats the contents of the given fcd-output file into a .dri file, readable by PHEM. The fcd-output "fcd" must be a valid file name of an fcd-output. The following may be a matter of changes: - the engine torque is not given """ # print >> outST...
11,565
def get_H_OS(): """屋根又は天井の温度差係数 (-) Args: Returns: float: 屋根又は天井の温度差係数 (-) """ adjacent_type = '外気' return get_H(adjacent_type)
11,566
def forward_softmax(x): """ Compute softmax function for a single example. The shape of the input is of size # num classes. Important Note: You must be careful to avoid overflow for this function. Functions like softmax have a tendency to overflow when very large numbers like e^10000 are computed. ...
11,567
def applySpectralClusters(kmeansObj, img, imgNullVal): """ Use the given KMeans object to predict spectral clusters on a whole image array. The kmeansObj is an instance of sklearn.cluster.KMeans, as returned by fitSpectralClusters(). The img array is a numpy array of the image to p...
11,568
def _singleton_new(cls, *args, **kwargs): """ An invalid new for singleton objects. """ raise TypeError( "'{0}' cannot be instantiated because it is a singleton".format( cls.__name__, ), )
11,569
def get_config_and_project_dir(config_file: str): """Guess config file name and project dir""" if config_file is not None: config_file = path.abspath(config_file) project_dir = path.dirname(config_file) else: project_dir = find_project_dir() config_file = '{}/stakkr.yml'.form...
11,570
def get_config() -> ConfigParser: """ Parse the config file. :return: config """ cfg = ConfigParser() cfg.read(CONFIG_PATH) return cfg
11,571
def run_experiments(map: Map): """Run a series of experiments. Generate Random, Linear, and Curiosity agents for each starting position. Test a series of brain configurations for the Curiosity agent so we can see if there is an optimal configuration. """ # Some high-level parameters num_starting_po...
11,572
def setver(_, ver=""): """Sets the Turtle Canon version""" match = re.fullmatch( ( r"v?(?P<version>[0-9]+(\.[0-9]+){2}" # Major.Minor.Patch r"(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?" # pre-release r"(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?)" # build metadata ), ...
11,573
def greetings(queue, id_): """Send a dummy message""" payload = {"type": "server:notice", "notice": "subed to {}:{!s}".format(queue.value, id_)} coro = MSG.send_message(queue, id_, payload) asyncio.get_event_loop().call_later(0.2, asyncio.ensure_future, coro)
11,574
def drop_table(table_name, db_engine): """ Drops a table from the database :param table_name: Name of the table that needs to be dropped :param db_engine: Specifies the connection to the database :return: None """ if has_table(table_name, db_engine): logger.debug("Deleting old (pre-e...
11,575
def test_array_to_image_valid_options(): """Creates image buffer with driver options.""" arr = np.random.randint(0, 255, size=(3, 512, 512), dtype=np.uint8) mask = np.zeros((512, 512), dtype=np.uint8) + 255 assert utils.array_to_image(arr, mask=mask, img_format="png", ZLEVEL=9)
11,576
async def test_missing_optional_config(hass): """Test: missing optional template is ok.""" with assert_setup_component(1, "template"): assert await setup.async_setup_component( hass, "template", { "template": { "number": { ...
11,577
def iso_register(iso_code): """ Registers Calendar class as country or region in IsoRegistry. Registered country must set class variables ``iso`` using this decorator. >>> from calendra.core import Calendar >>> from calendra.registry import registry >>> from calendra.registry_tools import iso_...
11,578
def dict_check_defaults(dd, **defaults): """Check that a dictionary has some default values Parameters ---------- dd: dict Dictionary to check **defs: dict Dictionary of default values Example ------- .. ipython:: python @suppress from xoa.misc import d...
11,579
def construct_search_params(): """Iterates through user-defined Entrez Search settings to assemble the search parameters. Envars hold the most recent user-defined Entrez settings, such as rettype, retmax, database, etc. These settings are iterated through, and their values are returned and appended to the ...
11,580
def get_invested_and_worth(account): """Gets the money invested and the actual worth of an account""" data = query_indexa(f"accounts/{account}/performance") invested = data["return"]["investment"] worth = data["return"]["total_amount"] return {"invested": round(invested, 2), "worth": round(worth,...
11,581
def make_album(singer, name, number = ''): """Return singers' names and album""" album = {'singer': singer, 'name': name} if number: album['number'] = number return album
11,582
def test_true(*_): """Creating new profile true path""" profile_name = "existing_profile.yaml" destination = "/output/directory/my_new_profile.yaml" expected_source_file = os.path.join(fake_profiles_path(), profile_name) expected_target_file = destination expected_target_dir = os.path.dirname(de...
11,583
def executeCustomQueries(when, _keys=None, _timeit=True): """Run custom queries as specified on the command line.""" if _keys is None: _keys = {} for query in CUSTOM_QUERIES.get(when, []): print('EXECUTING "%s:%s"...' % (when, query)) sys.stdout.flush() if query.startswith('F...
11,584
def test_index_page(): """ Check index page and click to Login """ # driver = webdriver.Firefox(executable_path=GeckoDriverManager().install()) # driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get("http://127.0.0.1:5000/") assert "AAA Home" in driver.title driver...
11,585
def fit_ctmp_meas_mitigator(cal_data: Dict[int, Dict[int, int]], num_qubits: int, generators: List[Generator] = None) -> CTMPExpvalMeasMitigator: """Return FullMeasureErrorMitigator from result data. Args: cal_data: calibration dataset. nu...
11,586
def discounted_item(data): """ DOCSTRING: Classifies item purchases as 'Promoted' or 'Not Promoted' based on 'Item Discount' column. Also 'COD Collectibles' column gets restructured by eliminating undesired default values, like 'Online'. INPUT: > data : Only accepts Pandas DataFrame or TextParser, t...
11,587
def NamespacedKubernetesSyncer(namespace, use_rsync=False): """Wrapper to return a ``KubernetesSyncer`` for a Kubernetes namespace. Args: namespace (str): Kubernetes namespace. use_rsync (bool): Use ``rsync`` if True or ``kubectl cp`` if False. If True, ``rsync`` will need to be ...
11,588
def _cons8_88(m8, L88, d_gap, k, Cp, h_gap): """dz constrant for edge gap sc touching 2 edge gap sc""" term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts term2 = 2 * k * d_gap / m8 / Cp / L88 # cond to adj bypass edge return 1 / (term1 + term2)
11,589
def cache_key(path): """Return cache key for `path`.""" return 'folder-{}'.format(hashlib.md5(path.encode('utf-8')).hexdigest())
11,590
def ref_731(n): """Reference number calculator. Returns reference number calculated using 7-3-1 algorithm used in Estonian banks. :param string n: base number (client id, etc) :rtype: string """ return "%s%d" % (n,((10 - (sum(map(\ lambda l: int(n[-l])*(7,3,1)[(l-1) % 3], \ ...
11,591
async def exception_as_response(e: Exception): """ Wraps an exception into a JSON Response. """ data = { "message": str(e), "traceback": "".join(traceback.TracebackException.from_exception(e).format()) } return web.json_response(data, status=500)
11,592
def canvas_merge_union(layers, full=True, blend=canvas_compose_over): """Blend multiple `layers` into single large enough image""" if not layers: raise ValueError("can not blend zero layers") elif len(layers) == 1: return layers[0] min_x, min_y, max_x, max_y = None, None, None, None ...
11,593
def exception_response(request, code=400, exception=None): """ Create a response for an exception :param request: request instance :param code: exception code :param exception: exception instance :return: exception formatted response """ code = code if code in [400, 403, 404, 500] else 4...
11,594
def get_jira_issues(jira, exclude_stories, epics_only, all_status, filename, user): """ Query Jira and then creates a status update file (either temporary or named) containing all information found from the JQL query. """ issue_types = ["Epic"] if not epics_only: issu...
11,595
def entropy(series): """Normalized Shannon Index""" # a series in which all the entries are equal should result in normalized entropy of 1.0 # eliminate 0s series1 = series[series!=0] # if len(series) < 2 (i.e., 0 or 1) then return 0 if len(series1) > 1: # calculate the maximu...
11,596
def spatially_whiten(X:np.ndarray, *args, **kwargs): """spatially whiten the nd-array X Args: X (np.ndarray): the data to be whitened, with channels/space in the *last* axis Returns: X (np.ndarray): the whitened X W (np.ndarray): the whitening matrix used to whiten X """ ...
11,597
def get_settings(basename: str="settings.yml", path: Path=PROJECT_ROOT / "conf") -> dict: """ Loads settings file Args: basename (str, optional): Basename of settings file. Defaults to "settings.yml". path (Path, optional): Path of seetings file. Defaults to PROJECT_ROOT/"conf". Raises...
11,598
def quaternion2rotationPT( q ): """ Convert unit quaternion to rotation matrix Args: q(torch.tensor): unit quaternion (N,4) Returns: torch.tensor: rotation matrix (N,3,3) """ r11 = (q[:,0]**2+q[:,1]**2-q[:,2]**2-q[:,3]**2).unsqueeze(0).T r12 = (2.0*(q[:,1]*q[:,2]-q[:,0]*q[:,...
11,599