content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_publishers(): """ Fetch and return all registered publishers.""" url = current_app.config['DATABASE'] with psycopg2.connect(url) as conn: with conn.cursor() as cur: cur.execute("SELECT * FROM userrole WHERE is_publisher = %s ORDER BY reg_date DESC;", ('true',)) res = ...
ed6f95ea576e97f6c38074803d447de4db9b8d40
3,652,300
import curses def acs_map(): """call after curses.initscr""" # can this mapping be obtained from curses? return { ord(b'l'): curses.ACS_ULCORNER, ord(b'm'): curses.ACS_LLCORNER, ord(b'k'): curses.ACS_URCORNER, ord(b'j'): curses.ACS_LRCORNER, ord(b't'): curses.ACS_LT...
2121ab5dd650019ae7462d2ab34cf436966cffe9
3,652,301
def get_polymorphic_ancestors_models(ChildModel): """ ENG: Inheritance chain that inherited from the PolymorphicModel include self model. RUS: Наследуется от PolymorphicModel, включая self. """ ancestors = [] for Model in ChildModel.mro(): if isinstance(Model, PolymorphicModelBase): ...
aa7129dd81009e72d9fe86787a2d4516dcca3b29
3,652,302
def plot_load_vs_fractional_freq_shift(all_data,ax=None): """ Plot fractional frequency shift as a function of load temperature for all resonators """ if ax is None: fig,ax = plt.subplots(figsize=(8,8)) for name, group in all_data.groupby('resonator_index'): ax.plot(group.sweep_prima...
24f5bdbee5a904fb72d27986634244f380202a34
3,652,303
def encode_dist_anchor_free_np(gt_ctr, gt_offset, anchor_ctr, anchor_offset=None): """ 3DSSD anchor-free encoder :param: gt_ctr: [bs, points_num, 3] gt_offset: [bs, points_num, 3] anchor_ctr: [bs, points_num, 3] anchor_offset: [bs, points_num, 3] :return: encoded_...
96f3fa686a4b89dac35a4a4725831f550a62107b
3,652,304
def BCrand(h, hu, t, side, mean_h, amplitude, period, phase): """ Conditions aux limites du modele direct, avec plus de paramètres""" if side == 'L': h[0] = mean_h + amplitude * np.sin((t * (2 * np.pi) / period) + phase) hu[0] = 0.0 elif side == 'R': h[-1] = h[-2] hu[-1] = hu...
7113fd81a375bbabc2ac8e1bf4e5c6706d3198c6
3,652,305
from bs4 import BeautifulSoup from matplotlib import pyplot as mpl_pyplot def pyplot( figure=None, scale: float = 0.8, clear: bool = True, aspect_ratio: typing.Union[list, tuple] = None ) -> str: """ :param figure: :param scale: :param clear: :param aspect_ratio: ...
04375ad36cefc83a332c3d183b3a97b5f149518a
3,652,306
import itertools def simplify(graph): """ helper that simplifies the xy to mere node ids.""" d = {} cnt = itertools.count(1) c2 = [] for s, e, dst in graph.edges(): if s not in d: d[s] = next(cnt) if e not in d: d[e] = next(cnt) c2.append((d[s], d[e]...
3ec7950922c5e49bad68f19666eb0381247d8f8f
3,652,307
from typing import Collection def _get_class_for(type): """Returns a :type:`class` corresponding to :param:`type`. Used for getting a class from object type in JSON response. Usually, to instantiate the Python object from response, this function is called in the form of ``_get_class_for(data['object'...
d122fe4dabd8a0486b0ed441b064f5c3d08c6b9b
3,652,308
import requests def _query_jupyterhub_api(method, api_path, post_data=None): """Query Jupyterhub api Detects Jupyterhub environment variables and makes a call to the Hub API Parameters ---------- method : string HTTP method, e.g. GET or POST api_path : string relative path, f...
22ba33ae53908aabae44bf591f9f3f1efcd97219
3,652,309
def PoolingOutputShape(input_shape, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: compute the output shape for the pooling layer.""" dims = (1,) + pool_size + (1,) # NHWC spatial_strides = strides or (1,) * len(pool_size) strides = (1,) + spatial_strides + (1,) pads = co...
185b97b308b8c15aa7fab2701ad40e1ee8241248
3,652,310
from pathlib import Path from typing import List import json import this import jsonschema def parse_config_file(config_file_path: Path) -> List[TabEntry]: """ Parse the json config file, validate and convert to object structure """ app_config = None Logger().info(f"Loading file '{config_file_path}'...") ...
8ce41d517eed17539b19f6caddb6dc8b2ce50cee
3,652,311
def create_app(): """ 工厂函数 """ app = Flask(__name__) register_blueprint(app) # register_plugin(app) register_filter(app) register_logger() return app
06ad3e8c07fd823b0f8ec5f4a18d49a0a430fa93
3,652,312
def passwordbox(**kwargs): """ This wrapper is for making a dialog for changing your password. It will return the old password, the new password, and a confirmation. The remaining keywords are passed on to the autobox class. """ additional_fields = kwargs.get("additional_fields") and kwar...
ff38d854a8d7303bbf58654e220c0b24b3ede105
3,652,313
def unravel_hpx_index(idx, npix): """Convert flattened global map index to an index tuple. Parameters ---------- idx : `~numpy.ndarray` Flat index. npix : `~numpy.ndarray` Number of pixels in each band. Returns ------- idx : tuple of `~numpy.ndarray` Index array...
c7fa097ffeae3219d59526ed76d62383277d317b
3,652,314
import os import sqlite3 import csv def map2sqldb(map_path, column_names, sep='\t'): """Determine the mean and 2std of the length distribution of a group """ table_name = os.path.basename(map_path).rsplit('.', 1)[0] sqldb_name = table_name + '.sqlite3db' sqldb_path = os.path.join(os.path.dirname(m...
656db3aa8797231ba09f6ddd08d00c0308be9285
3,652,315
def parse_revdep(value): """Value should be an atom, packages with deps intersecting that match.""" try: targetatom = atom.atom(value) except atom.MalformedAtom as e: raise argparser.error(e) val_restrict = values.FlatteningRestriction( atom.atom, values.AnyMatch(values.F...
eb2118af7644fac15fa4ebedba6684d20ab18d47
3,652,316
def is_context_word(model, word_a, word_b): """Calculates probability that both words appear in context with each other by executing forward pass of model. Args: model (Mode): keras model word_a (int): index of first word word_b (int): index of second word """ # define ...
a7b0642cfc97b21e53f8b42eaddbed69689a0f1d
3,652,317
import pathlib def map_and_save_gene_ids(hit_genes_location, all_detectable_genes_location=''): """ Maps gene names/identifiers into internal database identifiers (neo4j ids) and saves them :param hit_genes_location: genes in the set we would like to analyse :param all_detectable_genes_location: gen...
db29322d61b12cf7a3d266b831b553305327bed3
3,652,318
def next_method(): """next, for: Get one item of an iterators.""" class _Iterator: def __init__(self): self._stop = False def __next__(self): if self._stop: raise StopIteration() self._stop = True return "drums" return next(_...
85cdd08a65ae66c2869ba2067db81ff37f40d0b8
3,652,319
import json def get_ingress_deployment( serve_dag_root_node: DAGNode, pipeline_input_node: PipelineInputNode ) -> Deployment: """Return an Ingress deployment to handle user HTTP inputs. Args: serve_dag_root_node (DAGNode): Transformed as serve DAG's root. User inputs are translated t...
33f7ca9218e59af168fccdd8e0d0392964febaf2
3,652,320
def get_project_settings(project): """Gets project's settings. Return value example: [{ "attribute" : "Brightness", "value" : 10, ...},...] :param project: project name or metadata :type project: str or dict :return: project settings :rtype: list of dicts """ if not isinstance(project...
298d00eedff7c70ae8745e47f2eff48642988c7b
3,652,321
def guard(M, test): """Monadic guard. What it does:: return M.pure(Unit) if test else M.empty() https://en.wikibooks.org/wiki/Haskell/Alternative_and_MonadPlus#guard """ return M.pure(Unit) if test else M.empty()
9184310fcebec10ca1cc7cdb25e36831b327cbb0
3,652,322
def get_git_hash() -> str: """Get the git hash.""" rv = _run("git", "rev-parse", "HEAD") if rv is None: return "UNHASHED" return rv
978eca015aeb534e500dbbc5e9ab7aad5b487865
3,652,323
def primary_style(): """ a blue green style """ return color_mapping( 'bg:#449adf #ffffff', 'bg:#002685 #ffffff', '#cd1e10', '#007e3a', '#fe79d1', '#4cde77', '#763931', '#64d13e', '#7e77d2', 'bg:#000000 #ffffff', )
aecbe4cccb18763cf961ba08d6d9c04188080989
3,652,324
def decrypt_files(rsa_key): """ Decrypt all encrypted files on host machine `Required` :param str rsa_key: RSA private key in PEM format """ try: if not isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey): rsa_key = Crypto.PublicKey.RSA.importKey(rsa_key) if not rsa...
ccc5d253b5ab7a7851195751a798ba4e18fef983
3,652,325
def _bivariate_uc_uc( lhs,rhs, z, dz_dl, # (dz_re_dl_re, dz_re_dl_im, dz_im_dl_re, dz_im_dl_im) dz_dr # (dz_re_dr_re, dz_re_dr_im, dz_im_dr_re, dz_im_dr_im) ): """ Create an uncertain complex number as a bivariate function This is a utility method for implementing mathematical function...
f3b2c778cd1152910c951e893861f0c900978a4e
3,652,326
def smoothing_filter(time_in, val_in, time_out=None, relabel=None, params=None): """ @brief Smoothing filter with relabeling and resampling features. @details It supports evenly sampled multidimensional input signal. Relabeling can be used to infer the value of samples at ...
7af0f6925d255c0445c7b5dfdfb330f4058f8afc
3,652,327
def get_selector_qty(*args): """get_selector_qty() -> int""" return _idaapi.get_selector_qty(*args)
82ea62d3220893456358c42b0ec931e5c2cf9053
3,652,328
from typing import Optional from typing import Dict from typing import Any import requests def get( host: str, path: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, authenticated: bool = True, stream: bool = False, ) -> requests.Response: """ Sen...
7f0188ad2d678c0edef5d4fce623a5faee5c13db
3,652,329
def inner_xml(xml_text): """ Get the inner xml of an element. >>> inner_xml('<div>This is some <i><b>really</b> silly</i> text!</div>') u'This is some <i><b>really</b> silly</i> text!' """ return unicode(INNER_XML_RE.match(xml_text).groupdict()['body'])
dcba13de5a75d4b9956c2a27f02a289212d9789e
3,652,330
def store_tags(): """Routing: Stores the (updated) tag data for the image.""" data = { "id": request.form.get("id"), "tag": request.form.get('tags'), "SHOWN": 0 } loader.store(data) next_image = loader.next_data() if next_image is None: return redirect("/finished...
ec433586e7ad60d2b85ac8ff2ccc209f4c00a110
3,652,331
def getAssets(public_key: str) -> list: """ Get all the balances an account has. """ balances = server.accounts().account_id(public_key).call()['balances'] balances_to_return = [ {"asset_code": elem.get("asset_code"), "issuer": elem.get("asset_issuer"), "balance": elem.get("balance")} for elem in ba...
71c1b89edd79f0dc4092b909c2d7f505b35d5391
3,652,332
def parse_pattern(format_string, env, wrapper=lambda x, y: y): """ Parse the format_string and return prepared data according to the env. Pick each field found in the format_string from the env(ironment), apply the wrapper on each data and return a mapping between field-to-replace and values for each. ...
fdd5057929ed06f5ee984019e967df45d683fb75
3,652,333
def u1_series_summation(xarg, a, kmax): """ 5.3.2 ROUTINE - U1 Series Summation PLATE 5-10 (p32) :param xarg: :param a: :param kmax: :return: u1 """ du1 = 0.25*xarg u1 = du1 f7 = -a*du1**2 k = 3 while k < kmax: du1 = f7*du1 / (k*(k-1)) u1old = u1 ...
e54cb5f68dd5ecba5dd7f540ac645ff8d70ae0e3
3,652,334
def mask_iou(masks_a, masks_b, iscrowd=False): """ Computes the pariwise mask IoU between two sets of masks of size [a, h, w] and [b, h, w]. The output is of size [a, b]. Wait I thought this was "box_utils", why am I putting this in here? """ masks_a = masks_a.view(masks_a.size(0), -1) mas...
585bb48b3b8460660739acd102d8a0f5e1716078
3,652,335
import torch def normalized_grid_coords(height, width, aspect=True, device="cuda"): """Return the normalized [-1, 1] grid coordinates given height and width. Args: height (int) : height of the grid. width (int) : width of the grid. aspect (bool) : if True, use the aspect ratio to scal...
7ddd1c5eda2e28116e40fa99f6cd794d9dfd48cc
3,652,336
from typing import Optional from pathlib import Path from typing import Iterable from typing import List from typing import Any import ray import traceback def ray_map(task: Task, *item_lists: Iterable[List[Any]], log_dir: Optional[Path] = None) -> List[Any]: """ Initialize ray, align item lists and map each ...
a033bb1f2d84b7a37bffd4db4643ed5c2291b3ba
3,652,337
def consensus_kmeans(data=None, k=0, linkage='average', nensemble=100, kmin=None, kmax=None): """Perform clustering based on an ensemble of k-means partitions. Parameters ---------- data : array ...
25ee74ac24883a4981db98c730c9010d13866840
3,652,338
def to_cftime(date, calendar="gregorian"): """Convert datetime object to cftime object. Parameters ---------- date : datetime object Datetime object. calendar : str Calendar of the cftime object. Returns ------- cftime : cftime object Cftime ojbect. """ ...
cfd968e1fd74f105ef7b44ce6700d646d4470910
3,652,339
def poly_to_mask(mask_shape, vertices): """Converts a polygon to a boolean mask with `True` for points lying inside the shape. Uses the bounding box of the vertices to reduce computation time. Parameters ---------- mask_shape : np.ndarray | tuple 1x2 array of shape of mask to be generat...
13dec3d1057cff4823fa989e268f5103756bc263
3,652,340
def get_nn_edges( basis_vectors, extent, site_offsets, pbc, distance_atol, order, ): """For :code:`order == k`, generates all edges between up to :math:`k`-nearest neighbor sites (measured by their Euclidean distance). Edges are colored by length with colors between 0 and `order - 1`...
dfc55a3696c18769bbe3d4b15f068afbc763b6bf
3,652,341
from datetime import datetime import pytz import dateutil def expand(vevent, default_tz, href=''): """ :param vevent: vevent to be expanded :type vevent: icalendar.cal.Event :param default_tz: the default timezone used when we (icalendar) don't understand the embedded timezone ...
4d158051b95befed575f1243fd905d545c0cdabb
3,652,342
def setup_transition_list(): """ Creates and returns a list of Transition() objects to represent state transitions for a biased random walk, in which the rate of downward motion is greater than the rate in the other three directions. Parameters ---------- (none) Returns ---...
d820502beefc6065f1d5624dc0c0749fc65a0ae9
3,652,343
import math def unit_vector(data, axis=None, out=None): """Return ndarray normalized by length, i.e. eucledian norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) >>> v1 = uni...
eb29e86d33ff576f290ea11aa6e2e6180a04d56e
3,652,344
import torch def negative_f1_score(probs, labels): """ Computes the f1 score between output and labels for k classes. args: probs (tensor) (size, k) labels (tensor) (size, 1) """ probs = torch.nn.functional.softmax(probs, dim=1) probs = probs.numpy() labels = l...
bd308d70934ed5ada0868f454b07c0f554384f32
3,652,345
import requests def search_usb_devices_facets(): """Facet USB Devices""" data = {"terms": {"fields": ["status"]}} usb_url = USB_DEVICES_FACETS.format(HOSTNAME, ORG_KEY) return requests.post(usb_url, json=data, headers=HEADERS)
d4f09b8374fe2461ac5e7c121822287bf8e80494
3,652,346
import struct def pack4(v): """ Takes a 32 bit integer and returns a 4 byte string representing the number in little endian. """ assert 0 <= v <= 0xffffffff # The < is for little endian, the I is for a 4 byte unsigned int. # See https://docs.python.org/2/library/struct.html for more info. ...
bbaeb0026624a7ec30ec379466ef11398f93d573
3,652,347
def index(): """ """ category = Category.get_categories() pitch = Pitch.get_all_pitches() title = "Welcome to Pitch Hub" return render_template('index.html', title = title, category = category, pitch =pitch)
6758964bf9a304d62d9048e9b9248cee39d04742
3,652,348
def maximum_sum_increasing_subsequence(numbers, size): """ Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order. """ results = [numbers[i] for i in range(size...
a684ead4dcd9acbf8c796f5d24a3bf826fb5ad9d
3,652,349
def lstsqb(a, b): """ Return least-squares solution to a = bx. Similar to MATLAB / operator for rectangular matrices. If b is invertible then the solution is la.solve(a, b).T """ return la.lstsq(b.T, a.T, rcond=None)[0].T
4b046896ce29b79e9edcb434b1a01c652654867c
3,652,350
def multivariateGaussian(X, mu, sigma2): """ 多元高斯分布 :param X: :param mu: :param sigma2: :return: """ k = len(mu) if sigma2.shape[0] > 1: sigma2 = np.diag(sigma2) X = X - mu argu = (2 * np.pi) ** (-k / 2) * np.linalg.det(sigma2) ** (-0.5) p = argu * np.exp(-0.5 * n...
67a466318c473eef2749bf23e26d45de1149c5dc
3,652,351
from datetime import datetime def get_day(input): """ Convert input to a datetime object and extract the Day part """ if isinstance(input, str): input = parse_iso(input) if isinstance(input, (datetime.date, datetime.datetime)): return input.day return None
8a18e1832b85faf0612667ce3431176301502523
3,652,352
def read_ds(tier, pos_source=None): """ Like read_pt above, given a DS tier, return the DepTree object :param tier: :type tier: RGTier """ # First, assert that the type we're looking at is correct. assert tier.type == DS_TIER_TYPE # --1) Root the tree. root = DepTree.root() #...
797503380a3ff697440da8cd5d409b5c89384f4f
3,652,353
def get_local_ontology_from_file(ontology_file): """ return ontology class from a local OWL file """ return ow.get_ontology("file://" + ontology_file).load()
c022aac464c4afdbc088455a5edf8a4d91bc5586
3,652,354
import urllib def get_wolframalpha_imagetag(searchterm): """ Used to get the first image tag from the Wolfram Alpha API. The return value is a dictionary with keys that can go directly into html. Takes in: searchterm: the term to search with in the Wolfram Alpha API """ base_url = 'htt...
958e09d6498b1f1d98de72fe9089e45e48988f20
3,652,355
def get_synset_definitions(word): """Return all possible definitions for synsets in a word synset ring. :param word (str): The word to lookup. :rtype definitions (list): The synset definitions list. """ definitions = [] synsets = get_word_synsets(word) for _synset in synsets: defini...
70d522777cd413902157df6c0d96bdf378d7cf69
3,652,356
import json def getResourceDefUsingSession(url, session, resourceName, sensitiveOptions=False): """ get the resource definition - given a resource name (and catalog url) catalog url should stop at port (e.g. not have ldmadmin, ldmcatalog etc... or have v2 anywhere since we are using v1 api's ...
883a393018b068b8f15a8c0ea5ac6969c1a386b6
3,652,357
def _merge_sse(sum1, sum2): """Merge the partial SSE.""" sum_count = sum1 + sum2 return sum_count
0aae96262cfb56c6052fdbe5bbd92437d37b1f76
3,652,358
def earliest_deadline_first(evs, iface): """ Sort EVs by departure time in increasing order. Args: evs (List[EV]): List of EVs to be sorted. iface (Interface): Interface object. (not used in this case) Returns: List[EV]: List of EVs sorted by departure time in increasing order. ...
f1a57586b9993d890ddda6c309dafbea4ae16554
3,652,359
import re def auto_load(filename): """Load any supported raw battery cycler file to the correct Datapath automatically. Matches raw file patterns to the correct datapath and returns the datapath object. Example: auto_load("2017-05-09_test-TC-contact_CH33.csv") >>> <ArbinDatapath object>...
6b3ccf40296f62c15ea005cfe5e87e397d8e9f88
3,652,360
def print_param_list(param_list, result, decimal_place=2, unit=''): """ Return a result string with parameter data appended. The input `param_list` is a list of a tuple (param_value, param_name), where `param_value` is a float and `param_name` is a string. If `param_value` is None, it writes 'N/A'. ...
f92fd926eaf312e625058c394c42e9909cac7a43
3,652,361
def get_veh_id(gb_data): """ Mapping function for vehicle id """ veh_ref = gb_data['Vehicle_Reference'] acc_id = get_acc_id_from_data(gb_data) veh_id = common.get_gb_veh_id(acc_id, int(veh_ref)) return veh_id
de3a8f99a099737cedb00534ad21bc7dd1a900c5
3,652,362
def linreg_qr_gramschmidt_unencrypted(clientMap, coordinator, encryLv=3, colTrunc=False): """ Compute vertical federated linear regression using QR. QR decomposition is computed by means of Numpy/Scipy builtin algorithm and Gram-Schmidt method. Parameters ---------- clientMap : List The...
59fee17cff911a22c4e6cfc6daf13ce7559d32a7
3,652,363
def has_soa_perm(user_level, obj, ctnr, action): """ Permissions for SOAs SOAs are global, related to domains and reverse domains """ return { 'cyder_admin': True, #? 'ctnr_admin': action == 'view', 'user': action == 'view', 'guest': action == 'view', }.get(user_l...
6b32c9f3411d9341d9692c46e84a7506d649f36d
3,652,364
import os def parse_test(project, path): """Compares the dynamic graph to the parsed one.""" inputs, outputs, built_by, graph = parse_graph(project.graph) fuzzed = sorted([f for f in inputs - outputs if project.filter_in(f)]) count = len(fuzzed) root = project.buildPath G = defaultdict(list) with op...
0f55d8123c1984faccef9b41e9807cc82d17492b
3,652,365
from typing import Any from typing import Dict import os import base64 def upload_artifact(args: Any, file_path: str, org_id: Any = None) -> Dict[str, Any]: """ Upload artifact using Pyxis API Args: args (Any): CLI arguments file_path (str): Path to a artifact file org_id (Any): o...
c6f2dfc94581028ccff0d2d3a86008a18b3816aa
3,652,366
def check_skyscrapers(input_path: str) -> bool: """ Main function to check the status of skyscraper game board. Return True if the board status is compliant with the rules, False otherwise. """ board = read_input(input_path) return check_not_finished_board(board) and check_uniqueness_in_rows...
a4a2c77049bad429e548c749ef3e34ef27081de4
3,652,367
from typing import Optional async def get_station(station: avwx.Station, token: Optional[Token]) -> dict: """Log and returns station data as dict""" await app.station.add(station.lookup_code, "station") return await station_data_for(station, token=token) or {}
659bf56ff274ccd460dfdf240d6f4776fb7586a6
3,652,368
def add_check_numerics_ops(): """Connect a `check_numerics` to every floating point tensor. `check_numerics` operations themselves are added for each `half`, `float`, or `double` tensor in the graph. For all ops in the graph, the `check_numerics` op for all of its (`half`, `float`, or `double`) inputs is gua...
8a5026ff07a0cfce7f0acac58641996cef76fb2e
3,652,369
def get_text(part): """Gmailの本文をdecode""" if not part['filename'] and \ part['body']['size'] > 0 and \ 'data' in part['body'].keys(): content_type = header(part['headers'], 'Content-Type') encode_type = header(part['headers'], 'Content-Transfer-Encoding') data = decod...
2d32b30539c39dc89cb3680e2d21e14eb9ce24c4
3,652,370
import dataclasses def run(ex: "interactivity.Execution"): """Specify the target function(s) and/or layer(s) to target.""" selection: "definitions.Selection" = ex.shell.selection is_exact = ex.args.get("exact", False) functions = ex.args.get("functions", False) layers = ex.args.get("layers", False...
9389ada1c657b1f2794650e9b2b2d9a40039b64f
3,652,371
def get_mixture_mse_accuracy(output_dim, num_mixes): """Construct an MSE accuracy function for the MDN layer that takes one sample and compares to the true value.""" # Construct a loss function with the right number of mixtures and outputs def mse_func(y_true, y_pred): # Reshape inputs in case t...
ac37233f14afb7aa13b8afc74e04d3d8adc89ff5
3,652,372
def ByName(breakdown_metric_name): """Return a BreakdownMetric class by name.""" breakdown_mapping = { 'distance': ByDistance, 'num_points': ByNumPoints, 'rotation': ByRotation, 'difficulty': ByDifficulty } if breakdown_metric_name not in breakdown_mapping: raise ValueError('Invalid ...
06a1a44f8453375cfc83729339062948829d950c
3,652,373
def deserialize_structure(serialized_structure, dtype=np.int32): """Converts a string to a structure. Args: serialized_structure: A structure produced by `serialize_structure`. dtype: The data type of the output numpy array. Returns: A numpy array with `dtype`. """ return np.asarray( [toke...
ec8f3d096f3eedea4343576f7b204da15ae73ca6
3,652,374
from typing import List def get_all_text_elements(dataset_name: str) -> List[TextElement]: """ get all the text elements of the given dataset :param dataset_name: """ return data_access.get_all_text_elements(dataset_name=dataset_name)
fa4c2e0bff9818f1026095b5b6b774b09652b989
3,652,375
def form_x(form_file,*args): """ same as above, except assumes all tags in the form are number, and uses the additional arguments in *args to fill out those tag values. :param form_file: file which we use for replacements :param *args: optional arguments which contain the form entries for the file in question, by n...
e2d45e71ff18ce626a89d9a097389fc27b34fa82
3,652,376
import click def init(): """Manage IAM users.""" formatter = cli.make_formatter('aws_user') @click.group() def user(): """Manage IAM users.""" pass @user.command() @click.option('--create', is_flag=True, default=False, he...
b237e6ba7c10aafa1a499944f1553eaceed0fb2a
3,652,377
def fix_units(dims): """Fill in missing units.""" default = [d.get("units") for d in dims][-1] for dim in dims: dim["units"] = dim.get("units", default) return dims
d3a47ad84e1b4e44bedebb1e5739778df975a6fe
3,652,378
def annotate_movement(raw, pos, rotation_velocity_limit=None, translation_velocity_limit=None, mean_distance_limit=None, use_dev_head_trans='average'): """Detect segments with movement. Detects segments periods further from rotation_velocity_limit, translation_ve...
f89e48281cb70da6aa27b7dde737a8a587024f08
3,652,379
from typing import Any def run_in_executor( func: F, executor: ThreadPoolExecutor = None, args: Any = (), kwargs: Any = MappingProxyType({}), ) -> Future: """将耗时函数加入到线程池 .""" loop = get_event_loop() # noinspection PyTypeChecker return loop.run_in_executor( # type: ignore execu...
dfa40f30e359d785e3582f48910d3936659bd2fa
3,652,380
def find_entry_with_minimal_scale_at_prime(self, p): """ Finds the entry of the quadratic form with minimal scale at the prime p, preferring diagonal entries in case of a tie. (I.e. If we write the quadratic form as a symmetric matrix M, then this entry M[i,j] has the minimal valuation at the prim...
737a6dd1c3a1f416f4e22b79440b7731a5048fe0
3,652,381
import awkward._v2._connect.pyarrow def from_arrow(array, highlevel=True, behavior=None): """ Args: array (`pyarrow.Array`, `pyarrow.ChunkedArray`, `pyarrow.RecordBatch`, or `pyarrow.Table`): Apache Arrow array to convert into an Awkward Array. highlevel (bool): If True...
a3c0cea2f2f3763f8997978e2963654cc08ed4e1
3,652,382
def _basis_search(equiv_lib, source_basis, target_basis, heuristic): """Search for a set of transformations from source_basis to target_basis. Args: equiv_lib (EquivalenceLibrary): Source of valid translations source_basis (Set[Tuple[gate_name: str, gate_num_qubits: int]]): Starting basis. ...
2911b93f4ea36875c6d5e675028aedcd8caf3929
3,652,383
def Get_EstimatedRedshifts( scenario={} ): """ obtain estimated source redshifts written to npy file """ return np.genfromtxt( FilenameEstimatedRedshift( scenario ), dtype=None, delimiter=',', names=True, encoding='UTF-8')
0696cfee6783c093b8cf4b7c9703fec18e9799a4
3,652,384
def get_national_museums(db_connection, export_to_csv, export_path): """ Get national museum data from DB """ df = pd.read_sql('select * from optourism.state_national_museum_visits', con=db_connection) if export_to_csv: df.to_csv(f"{export_path}_nationalmuseums_raw.csv", index=False) ...
d34b9ff8f7f95025f932078e8d6e8b179bcff27e
3,652,385
from re import A def hrm_configure_pr_group_membership(): """ Configures the labels and CRUD Strings of pr_group_membership """ T = current.T s3db = current.s3db settings = current.deployment_settings request = current.request function = request.function table = s3db.pr_group...
f5ec66e00063bf8101505de8b1b8a767227b6bbd
3,652,386
import torch def inverse_sphere_distances(batch, dist, labels, anchor_label): """ Function to utilise the distances of batch samples to compute their probability of occurence, and using the inverse to sample actual negatives to the resp. anchor. Args: batch: torch.T...
9bcb7f56f08fd850f6a9fa70175e1f83df603705
3,652,387
def get_recording(sleeps=False): """Get list of recorded steps. :param sleeps: set False to exclude recording sleeps """ # TODO. atm will always use CLICK # TODO. Add examples global recording # pylint: disable=W0602 output = [] top = None action_name = "Click" for item in reco...
11ea9e01fc6af731d444b743ea7e56deefff02d4
3,652,388
from functools import reduce def wrap_onspace(text, width): """ A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are posix newlines (\n). """ return reduce(lambda line, word, width=width: '%s%s%s' % (line,...
13387fa67dcff2b0329463dfe1ab7d6721255afc
3,652,389
def xsd_simple_type_factory(elem, schema, parent): """ Factory function for XSD simple types. Parses the xs:simpleType element and its child component, that can be a restriction, a list or an union. Annotations are linked to simple type instance, omitting the inner annotation if both are given. """ ...
27ab47787923fadef6364828e2cc7604b006d76d
3,652,390
def amen_solve(A, f, x0, eps, kickrank=4, nswp=20, local_prec='n', local_iters=2, local_restart=40, trunc_norm=1, max_full_size=50, verb=1): """ Approximate linear system solution in the tensor-train (TT) format using Alternating minimal energy (AMEN approach) :References: Sergey Dolgov,...
15b35bedd6e07f867ae1bae54992f8988b1b56cb
3,652,391
def get_vss(ts, tau_p): """ Compute candidates of VS for specified task tau_p """ if tau_p == None: return [] C, T, D = extract(ts) R = rta(C, T) _VS = _get_vs(C, T, R, task_name_to_index(ts, tau_p)) _VS.sort() VS = [] vs = Server(0, 0, None) # ignore duplicates for s i...
a6b0abc26d32d8e62e4026ee59a6491a02dd6a32
3,652,392
from typing import Iterable from typing import Dict from typing import Hashable from typing import List def groupby( entities: Iterable["DXFEntity"], dxfattrib: str = "", key: "KeyFunc" = None ) -> Dict[Hashable, List["DXFEntity"]]: """ Groups a sequence of DXF entities by a DXF attribute like ``'layer'``...
0eecfc2263c1f5716615cb4add6bc092edbb2b8b
3,652,393
def train_test_split(data_filepath, num_train=10, num_test=10): """Split a dataset into training and test sets.""" df = pd.read_csv(data_filepath, sep=',', header=None) data = df.values train = data[:2*num_train, :] test = data[2*num_train:2*(num_train+num_test), :] ind = np.argsort(train[:,-1...
650979e62667ade3f88d89f2058bedf8675a5ae5
3,652,394
import requests def get_filings(app: Flask = None): """Get a filing with filing_id.""" r = requests.get(f'{app.config["LEGAL_URL"]}/internal/filings') if not r or r.status_code != 200: app.logger.error(f'Failed to collect filings from legal-api. {r} {r.json()} {r.status_code}') raise Excep...
4b2ba1a3d15918fe5d7b706a20006d0c85818176
3,652,395
def _uno_struct__setattr__(self, name, value): """Sets attribute on UNO struct. Referenced from the pyuno shared library. """ return setattr(self.__dict__["value"], name, value)
6b66213e33bb8b882407ff33bcca177701fb98cd
3,652,396
import io import warnings import os def load_imgs_from_tree(data_dir, img_sub_folder=None, fovs=None, channels=None, dtype="int16", variable_sizes=False): """Takes a set of imgs from a directory structure and loads them into an xarray. Args: data_dir (str): directo...
d92aad79e78ad2ce1c1fdd944d8e2c4049ddca4d
3,652,397
from datetime import datetime def register(): """Registers the user.""" if g.user: return redirect(url_for('user_home')) error = None if request.method == 'POST': if not request.form['username']: error = 'You have to enter a username' elif not request.form['email'...
572ee30c9f4981f6d526f115178ba8988e2b93c1
3,652,398
def test_single_while_2(): """ Feature: JIT Fallback Description: Test fallback with control flow. Expectation: No exception. """ @ms_function def control_flow_while(): x = Tensor(7).astype("int32") y = Tensor(0).astype("int32") while x >= y: y += x ...
8334819ee7d4ea24085e2a2f1ab3d18fb732c8cc
3,652,399