content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def email_data(): """fields every email needs""" site = models.SiteSettings.objects.get() return { "site_name": site.name, "logo": site.logo_small_url, "domain": DOMAIN, "user": None, }
ebc177c30bb5b5ac3e88cbffe56b33ca91bc2dc3
64,400
def home(sort_type='hot'): """ If not trending we order by creation date """ atom_url = url_for('subreddits.atom_feed', subreddit_name='frontpage', _external=True) trending = True if request.path.endswith('trending') else False page_title = "Trending" if trending else "Frontpage" thread_pagi...
e28f72b0c6d29b94b578833a7282ee6345f6fadc
64,401
def get_path_loss(range_m, freq_hz, tx_ht_m, rx_ht_m, include_atm_loss=True, atmosphere=None): """ Computes the propagation loss according to a piece-wise model where free space is used at close range, and two-ray is used at long range. The cross-over range between the two is the Fresnel Zone. Ported ...
d75be948be368140c0e81cdd969c9dd34125c821
64,402
import socket def connected(host: str = "8.8.8.8", port: int = 53, timeout: float = 10.0) -> bool: """ Return the status of network connection via built-in sockets. It is a non-threaded implementation for checking the network. Args: host: Host IP address or Hostname of a webse...
f4218b13b9c7858b03f15e098dbdfea202cad3c2
64,403
def get_patch_dims(im, patch_size, patch_position): """ Returns the dimensions of an image patch of size `patch_size`, with its center at `patch_position` expressed as a ratio of the image's H and W * im: np.ndarray of size H x W x C * patch_size: 2-tuple of patch H x W * pa...
a078747b1978f33aed608e2867f9b18f0fd3f811
64,404
def fluent_comments_list(parser, token): """ A tag to select the proper template for the current comments app. """ return FluentCommentsList()
c5d611a772891ada2244953f5589e640dd458fa8
64,405
def getMRotFromNodeOutput(node_mob, rotOrder = om2.MEulerRotation.kXYZ): """ finds the angular output of the argument node and returns it as a Euler rotation where that angle is the X element :param node_mob: [MObject] the node to get the output port from :param rotOrder: [int] the factory constant...
e2f911b760e0a287919cd9967eaf41c7eae26785
64,406
import json def getAll(filepath): """ Get all config value """ with open(filepath, "r", encoding="utf-8") as target: return json.load(target)
450597deb942c9fdbde33ec37c8feee9d2edd1ec
64,407
from typing import Union def filter_vset_by_metric(metric_dict: dict, vset: Vset, *vsets: Vset, n_keep: int = 1, bigger_is_better: bool = True, filter_on=None, group: bool = False) -> Union[Vset, list]: """Returns a new Vset by filtering `vset.modules` based on ...
9b70c1bd1a50df7b164b64a4ad0f473ae256657a
64,408
import matplotlib.pyplot as plt def plot_series( s, cmap=None, color=None, ax=None, figsize=None, aspect="auto", **style_kwds ): """ Plot a GeoSeries. Generate a plot of a GeoSeries geometry with matplotlib. Parameters ---------- s : Series The GeoSeries to be plotted. Currently ...
b3795b3a5b6927beb9ef0b47beeaa9d85ff9866f
64,409
def safe_div(x: int, y: int): """ Computes x / y and fails if x is not divisible by y. """ assert isinstance(x, int) and isinstance(y, int) assert y != 0 assert x % y == 0, f'{x} is not divisible by {y}.' return x // y
250678a7d6b3b5564ee734a852b17d1cea7ac536
64,410
import time def Timer(): """Returns a Single representing the number of seconds elapsed since midnight""" ltime = time.localtime() h, m, s = ltime[3:6] return h*3600.0 + m*60.0 + s
9e93ac420a439574aaed07520bbd457577dfe3f9
64,411
def format_entry(e): """ Format an entry from the data in the original database to something that uses html """ txt = e.midashigo1 strlen = len(txt) acclen = len(e.ac) accent = "0"*(strlen-acclen) + e.ac # Get the nasal positions nasal = [] if e.nasalsoundpos: positions = e.nasa...
17cbc7270a70cb8bb88ec7faa2295f1f42b041af
64,412
def resnet_model_fn(inputs, training): """Our model_fn for ResNet to be used with our Estimator.""" network = resnet_model.imagenet_resnet_v2( resnet_size=18, num_classes=class_num, mode='se', data_format=None) inputs= network(inputs=inputs, is_training=training) feat = tf.nn.l2_normalize(input...
be238ae34089d39db6f50b7771abf5588e5370ee
64,413
from typing import Union import os def get_bool_env(key: str, default: bool = False) -> bool: """ Return boolean value from environment variable. :param str key: name of environment variable :param bool default: default value if environment variable not exists or empty :return: boolean value from...
17b32dc64e84e6197634e6bba28f0ef39be11210
64,414
from pathlib import Path import sys def cblaster( query_file=None, query_ids=None, query_profiles=None, mode=None, database=None, database_pfam=None, gap=20000, unique=3, min_hits=3, min_identity=30, min_coverage=50, max_evalue=0.01, entrez_query=None, output=No...
22c5078ec4c97b91ba5ccff8a586e246881be71a
64,415
def update_categorygraph_without_scc(categorypages, categorygraph): """Update categorygraph for containing all reachable content without scc. Args: categorypages (Hash[String, Set[String]]): category to page name list dictionary. categorygraph (Hash[String, Set[String]]): category to category l...
bebb98d4992d0db9f652b7b7d80c8499292850c2
64,416
from datetime import datetime def to_datetime(dt_str, format="%Y-%m-%d %H:%M:%S", utc=False): """ utc: False 按当前时区解析,True 按UTC解析 """ try: dt = datetime.strptime(dt_str, format) return _utc_tz.localize(dt) if utc else _local_tz.localize(dt) except Exception: return None
dbdc62b8fce82f12f2a1e6fde32f74da6b7e7f0a
64,417
def dropna_except(df, except_subset, inplace=False): """drop rows containing nans from a Pandas dataframe, but allow nans in the specified subset of columns, in place""" subset = set(df.columns) for ec in except_subset: subset.remove(ec) df = df.dropna(inplace=inplace, subset=subset) ...
708bd3e9cab520f9453cd82d6f36aa8ec8183fc0
64,418
def rf_array_to_tile(array_col: Column_type, num_cols: int, num_rows: int) -> Column: """Convert array in `array_col` into a Tile of dimensions `num_cols` and `num_rows'""" jfcn = RFContext.active().lookup('rf_array_to_tile') return Column(jfcn(_to_java_column(array_col), num_cols, num_rows))
dc879f164567172344206869df3f6a4149e6eb6f
64,419
import six def with_metaclass(meta, *bases, **with_metaclass_kwargs): """Extends the behavior of six.with_metaclass. The normal usage (expanded to include temporaries, to make the illustration easier) is: .. code-block:: python temporary_class = six.with_metaclass(meta, *bases) temp...
80a33fa94d8efa8d770d561ccccab06bfd3fdbf2
64,420
def _timeSlice__compare(self,other): """Compare two time slices, returning tuple (<return code>, <slice>, <comment>), with the larger slice if succesful. If return code is negative, no solution is found. If return code is 2, the slices are disjoint and both returned.""" assert self._h.label == 'timeSlic...
d03b9a4f68c08e232753ae64c52225d8643380d5
64,421
import urllib3 import logging def _SendFileToServer(pool, fullpath, subpath, basename, rebalance): """Sends a specific data store file to the server.""" fp = FileCopyWrapper(rebalance, subpath, basename, fullpath) try: # Content-Length is 0 since we do not know the size of the compressed data. # We wri...
1b5d7be84be6cfac8463e6d62d9491f5084d5e00
64,422
def get_entities_set(domain='gaming', selected=True): """[summary] Keyword Arguments: domain {str} -- [description] (default: {'gaming'}) """ entities = [ 'Badges', 'Comments', 'PostHistory', 'PostLinks', 'Posts', 'Tags', 'Users', 'Votes'] meta_path_template = 'raw\\{0}\\m...
114bef412767f228a11066c90b63d971fb604a3d
64,423
def amp2db(amp, ref=1): """Conversion of an amplitude value into dB Parameters: ----------- amp: np.array amplitude values to be converted ref: float reference value """ if ref == 0: raise ValueError("Reference must be different from 0") elif ref != 0: d...
d54b8fcd8840f22c80600e86e3de2504f72f5847
64,424
def promote_dtypes(dt1, dt2): """ >>> from datashape.coretypes import int32, int64, float32 >>> promote_dtypes(int32, int64) ctype("int64") >>> promote_dtypes(int64, float32) ctype("float64") """ if dt1 == dt2: return dt1 elif isinstance(dt1, CType) and isinstance(dt2, CTyp...
63fde49f279bf628daec6115ac6d0fe26db79c1b
64,425
import sys def build_format_args(cfg, repo_info, next_custom=None): """ Builds the formatting arguments by processing the specified repository information and returns them. If a tag defines pre-release metadata, this will have the precedence over any existing user-defined string. """ in_n...
d6e6e1a04b05e10f0db3d581a0b45ad9960fa75e
64,426
def convert_s3_url_to_http_url(s3_url): """Convert s3 url to http url. Converts the S3 URL s3://bucket-name/object to HTTP URL https://s3.amazonaws.com/bucket-name/object. Args: s3_url Returns: http url Raises: """ u = urlparse(s3_url) s3bucket = u.netloc s3ke...
c4ea7e64eb1e7e05ee6373e6f013c88c58955014
64,427
import argparse def parse_arguments() -> argparse.Namespace: """Parse the arguments.""" parser = argparse.ArgumentParser(description="coco to scalabel") parser.add_argument( "--input", "-i", help="path to the input coco label file", ) parser.add_argument( "--output"...
ccc65221156bda279fee28d25c990d6bdb30da3f
64,428
def GaussianKernel(shape=(3, 3), sigma=0.5): """ 2D gaussian kernel which is equal to MATLAB's fspecial('gaussian',[shape],[sigma]) """ radius_x, radius_y = [(radius-1.)/2. for radius in shape] y_range, x_range = np.ogrid[-radius_y:radius_y+1, -radius_x:radius_x+1] h = np.exp(- (x_range*x_range ...
e39d0f0d446318075b1d7769327fda19ddb9f443
64,429
def quiz_models(directory, test, labels, visualize=False, capsnet=False, eval_model=None, train_df=None): """Loads models from directory and runs the quiz on them. If capsnet, eval_model must be passed in.""" model_directory = './models' + directory[1:] print('\nquizzing best accuracy model...\n') i...
90a1cdbba7a68114eaa24a0ef6b5d3ac102fabbf
64,430
from datetime import datetime import math def pretty_date(iso_datetime): """ Takes an ISO time and returns a string representing how long ago the date represents. Ported from PrettyDate by John Resig """ if not iso_datetime: return '' if isinstance(iso_datetime, basestring): iso_datetime = datetime.strp...
2af9917f001b3400fe479ad8b80edb4f86b4a89a
64,431
from typing import Dict from typing import cast def _double_cross_over_cz( op: ops.Operation, held_w_phases: Dict[ops.Qid, value.TParamVal] ) -> 'cirq.OP_TREE': """Crosses two W flips over a partial CZ. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ──...
9df193afd7329cb760926edf2770049d723b91ca
64,432
def inference_rnn(representations, query_poses, target_frames, params, scope="GQN_RNN"): """ Creates the computational graph for the DRAW module in inference mode. This is the training time setup where the posterior can be inferred from the target image. """ dim_r = representations.get_sh...
757ca4ef35e2657008705638e7b3d3b2ec22171c
64,433
def fj_load_df_from_csv(dir, file): """ Load dataframe from csv file Input: dir: directory for csv file file: csv file Returns: Pandas dataframe corresponding to processed and saved csv file """ df = pd.read_csv(dir + file) print(df.describe()) print ('NAs in data') print(df.isna().sum()) return...
a8849aa47c309ebbade587a17c5867dfc3acb192
64,434
def band_element_orbital_spin_polarized( folder, element_orbital_dict, output='band_element_orbital_sp.png', display_order=None, scale_factor=5, color_list=None, legend=True, linewidth=0.75, band_color='black', unprojected_band_color='gray', unprojected_linewidth=0.6, fon...
2bb2c6a8049da26718004ed667643bf6cfc0194f
64,435
def func_c(c,d_h,d_w,st_h,st_w,par): """ utility function for couples""" # high skilled hs_h = transitions.state_translate(st_h,'high_skilled',par) hs_w = transitions.state_translate(st_w,'high_skilled',par) # initialize to both working (then overwrite if not) alpha_h = 0.0 phi...
be6b2fe346bc6e7de7ae013f11d3b098925fba56
64,436
def assign_submit(): """Finalize assignment of assignments to a session with a due date""" if request.method == 'POST': # Get all the necessary form data date = request.form['date'] assign_id = request.form['assign_id'] session_id = request.form['session_id'] # Validate ...
ec6287f8dec81259db74d4f039165f64e8f427c7
64,437
def loadGiftiVertexData(filename): """Loads vertex data from the given GIFTI file. See :func:`prepareGiftiVertexData`. Returns a tuple containing: - The loaded ``nibabel.gifti.GiftiImage`` object - A ``(M, N)`` numpy array containing ``N`` data points for ``M`` vertices """ g...
4368e394a1bacaf8709f5b294ef39ec5d9359fd0
64,438
import requests def ehld_stids(): """ Retrieves a list of high-level hierarchy pathway with Enhanced High Level Diagrams (EHLD) https://reactome.org/icon-info/ehld-specs-guideline :return: list of pathway stIds """ url = "https://reactome.org/download/current/ehld/svgsummary.txt" try: ...
4bd4af4f7ed78c47b1b4431f958e7d790da0f068
64,439
def _split_lobster_filename(filename): """ splits the LOBSTER-type filename into Ticker, Date, Time Start, Time End, File Type, Number of Levels """ filename2,_ = filename.split(".") ticker_str, date_str, time_start_str, time_end_str, file_type_str, num_levels = filename2.split("_") return ticker_str,...
ae4e11cc653b345c780b33902b740f6b7cb707f6
64,440
def image(x, y, path, width=None, height=None): """ Draws and returns an :py:class:`~jygsaw.image.Image`. :param x: x-coordinate of upper-left corner. :type x: int :param y: y-coordinate of upper-left corner. :type y: int :param path: Internet URL or local file path to the image. :type ...
68cc93e7571c587bb7f21e135d844974150cd681
64,441
def project(points, camera_params): """Convert 3-D points to 2-D by projecting onto images.""" assert camera_params.shape[1] == 14 points_proj = rotate(points, camera_params[:, :3]) points_proj += camera_params[:, 3:6] points_proj = points_proj[:, :2] / points_proj[:, 2, np.newaxis] fx = came...
469ba74c735077f0410c9b1a1159a965900d4499
64,442
def ordinal_filter(num): """ Format a number as an ordinal. """ num = int(num) if 10 <= num % 100 <= 20: suffix = 'th' else: suffix = ORDINAL_SUFFIXES.get(num % 10, 'th') return unicode(num) + suffix
e139f9f7b8d8802550ef64dc3e5a06544f4a5568
64,443
from tqdm import tqdm_notebook as tqdm from tqdm import tqdm def main(): """ Performs training, validation and testing. """ args = setup_train_args() if args.notebook: else: # if config is provided, then load it if args.config is not None: with open(args.config, 'r') as fh: ...
19bb3592f00f710c4e4ad34d44c77d5e3ee03398
64,444
def tab_delimited(list_to_write): """Format list of elements in to a tab-delimited line""" list_to_write = [str(x) for x in list_to_write] return '\t'.join(list_to_write) + '\n'
921a3316f01aecaba1efb43c524b1ad5cca89546
64,445
import time def six_hump_camel_simple(x, persis_info, sim_specs, _): """ Evaluates the six hump camel function for a single point ``x``. :See: ``/libensemble/libensemble/tests/regression_tests/test_fast_alloc.py`` """ O = np.zeros(1,dtype=sim_specs['out']) O['f'] = six_hump_camel_fu...
0341d5b7c8977acb171c75cf053c70bd6f097677
64,446
import json def get_activities(token=None, user_id=None, transaction_id=None): """ Fetches all of available activity summaries Makes one call to the API, fetching a list of all available daily summaries then calls get_activity_summary() to effectively download the data. :param token: OAuth2 access t...
b70949ecb3c1999df1ade7373651518a855a724f
64,447
from typing import Optional def argwhere_op(x, dtype: Optional[flow.dtype] = None): """This operator finds the indices of input Tensor `x` elements that are non-zero. It returns a list in which each element is a coordinate that points to a non-zero element in the condition. Args: x (oneflow.Ten...
20dd69bdc71243f94bd50316c843d9e8db63727e
64,448
from gdsfactory.pdk import get_layer def strip( wg_width: float = 0.5, layer: LayerSpec = "WG", layer_cladding: LayerSpec = "WGCLAD", radius: float = 10.0, cladding_offset: float = 3.0, euler_bend: bool = True, wg_type: str = "strip", ) -> WaveguideTemplate: """ wg_type: strip, slo...
3633ce54efb11c0c039d84db44c8ea2682a49e4d
64,449
def ImageScaler(max_scale_power=1): """ Возвращает keras.layer преобразующий батч входных изображений в [images, images // 2, images // 4, ..., images // 2**max_scale_power] список изображений в разных масштабах ("//" выше обозначает перемасштабирование а не деление) :param max_scale_power: сколько ...
03a9e78d3e26c73455416db4e77d21e25a9f66e9
64,450
import six def render_path(path_to_item): """Returns a string representation of a path""" result = "" for pth in path_to_item: if isinstance(pth, six.integer_types): result += "[{0}]".format(pth) else: result += "['{0}']".format(pth) return result
bf9c9b40d8c6357813cb329c1dcb611aba45eacc
64,451
from sys import path def read_selection(name, fname=None, info=None, verbose=None): """Read channel selection from file By default, the selections used in ``mne_browse_raw`` are supported. Additional selections can be added by specifying a selection file (e.g. produced using ``mne_browse_raw``) using...
f35b7313369a4ecf6d4a9656cb1147fd8368d1c1
64,452
import multiprocessing def clusterpolate(points, values, targets, radius=1, kernel_factory=bump, neighbors=None, num_jobs=None): """ Clusterpolate data. ``points`` (array-like) are the data points and ``values`` (array-like) are the associated values. ``targets`` (array-like) are ...
689f7273e9aa2c9dd4c5c957018f8c990d565d16
64,453
def letter_frequency_dict(text, alphabet = None, # {{{1 precision = FREQ_PRECISION): """Calculates letter frequencies.""" if alphabet is None: alphabet = ALPHAS freqs = dict(izip(alphabet, [0]*len(alphabet))); n = float(len(text)) if not text: return freqs for c in tex...
604d1b47897b4c82ab8aa2a7f231a9f3c5b6c2d5
64,454
def discounts(num_steps: int, discount: float) -> np.ndarray: """Return the discounts array $[1., \\gamma, \\gamma^2, \\ldots]$. :param num_steps: size of the output array :param discount: discount factor :rtype: (N,) np.ndarray of discounts """ checkraise(num_steps > 0, ValueError, 'invalid ...
75b862e599ba4719550de8087ebd02e34c2bbd72
64,455
def compute_lognorm_cdf(hist, bins='', params=False, plot=False, ax=None): """ Returns a fitted CDF of a lognormal distribution, from a given histogram of distances If params=True, returns the parameters of the fitted lognorm """ if bins == '': bins = [i*2 for i in range(len(hist)+1)] db = b...
0b81145a2154ee7f31e404d17f7396c718aa188a
64,456
def random_prime(num_digits, is_prime = miller_rabin): """ Returns a random prime with num_digits digits. Input: num_digits -- a positive integer is_prime -- (optional argment) a function of one argument n that returns either True if n is (probably) ...
05a6dbd0da078dca2be40c0133f0f39bcc8a0e04
64,457
def remove_outliers_mad( *, data, threshold=2.5, fill_value='interpolate', rolling=False, window='1H', dist_const=1.4826 ): """ Outlier removal by robust median estimator. Remove outliers of a DataFrame or Series based on the (rolling) median of the difference of the data to...
302ffcd5b37a5b6a8f3144fd514f43dbee65c904
64,458
def diff_to_wfp(diff, md5, src_path): """ This function converts a parsed diff data structure into WFP Parameters ---------- diff : dict A dictionary containing as keys the filenames contained in the diff and as values its contents stored as a list of strings. md5 : str src_path : str Path t...
bcd31fca4bd5cbdd3fb12270b232245797b90107
64,459
def az_to_polar(x, y): """Convert azimuthal x,y to polar co-ordinates""" lat = -np.sqrt((x**2)+(y**2)) * np.pi + np.pi/2 lon = np.arctan2(-y,x) return lon, lat
3524ec9c3f38eccc96622060dde943b5fb4364ed
64,460
def get_node_continuous_info(node_name): """ 根据node_name 返回一段时间内的连续信息 :param node_name: :return: """ continuous_info = r.lindex(node_name, 0) continuous_dict = ast.literal_eval(continuous_info) return_data = {} return_data["data"] = continuous_dict return_data["status"] = 100 ...
4376c23d102160526229b27d17755aad00a91182
64,461
def parse_datetime(dt, ignoretz=True, **kwargs): """ :param dt: string datetime to convert into datetime object. :return: datetime object if the string can be parsed into a datetime. Otherwise, return None. :see: http://labix.org/python-dateutil Examples: >>> parse_datetime('2011-12-3...
d45cc5ae7c33533111498511e13be362579d3126
64,462
def route_remove_group_member(): """Remove a group member""" group = _lookup_group_from_request() member = request.json.get('member') user = get_user(username=member) remove_group_member(group, user) return make_json_response(removed=user.get_public_dict())
ef146e12da3bcb47ed8203ab943bedf6fbafe0fe
64,463
def get_watermark_for_topic( kafka_client, topic, ): """This method: * refreshes metadata for the kafka client * fetches watermarks :param kafka_client: KafkaToolClient instance :param topic: the topic :returns: dict <topic>: [ConsumerPartitionOffsets] """ # Refresh clie...
83e10f30bd2f97af0646651854663bcbd879114c
64,464
def render_placeholder_info(context, **kwargs): """Render the list of available placeholders. :param context: the context where the placeholders are used :param kwargs: arguments specific to the context """ placeholders = sorted(list(get_placeholders(context, **kwargs).values()), key=attrgetter('na...
75f47fa5781acd9c601dec67d8232e1278ee3045
64,465
def transform_data(data, verbose=False): """Transform the input data to be used by prediction. Args: data (list or dataframe): Input data in a list or dataframe with column name `sequence`. verbose (bool, optional): Whether to print out statistics of input protein sequen...
16858ac496c3c29e33c9cd990cfbd48349379b50
64,466
def _unadvertise(name): """Remove the advert for a name This is intended for internal use only at the moment. When a process exits it can remove adverts for its services from the beacon running on that machine. (Of course, if the beacon thread is part of of the same service, all its adverts will ce...
9ad38ba689637ac128af12bda9f7f50696331565
64,467
def PrintIOConversions(*args): """ PrintIOConversions(os=std::cout) PrintIOConversions() """ return _Ravl.PrintIOConversions(*args)
fe30aa3bf0694db33b363087aa22f131ec690f1a
64,468
def create_mask(mask_type, h, w): """ create mask according to shape """ mask = np.zeros((h, w, 3)) coords = shape_coords(h, w, mask_type) for i in range(h): for j in range(w): if in_polygon(i, j, coords): mask[i, j, :] = 1 return mask
39f34e2cb1a8c46c94ed1c2f05277302d7367f99
64,469
def load_sktime_ts_file(path, normalize=True): """ Load a dataset from .ts files Parameters ---------- path : string Path to the folder containing the .ts file. Dataset name should be specified at the end of path to find files as "dataset_TRAIN.ts" and "dataset_TEST.ts" ...
7b1a56ac15ce6f145e88e706dbb76d9ce85b725f
64,470
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ reprompt_text = "" session_attributes = {} card_title = "Welcome" speech_output = "This skill grabs temperature data from your raspberry pi. " should_end_session = "...
a4a773a39ca3015442716f4003ffb6e834945549
64,471
def parse_bql_string_pos_1(string): """Return ``(phrase, pos)`` for the first BQL phrase in `string`. May not report parse errors afterward. """ for phrase, pos in parse_bql_string_pos(string): return (phrase, pos) return None
c444a0a7cd827b3be07bccb83689f6a8ab6b4153
64,472
def keyjar_init(instance, key_conf, kid_template=""): """ Initialize KeyJar. Configuration of the type: keys = [ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"]}, {"type": "EC", "crv": "P-256", "use": ["enc"]} ]...
c134c97d8b09fc8506a551425732c417463952a5
64,473
def mnist_model(input_shape): """Creates a MNIST model.""" model = tf.keras.models.Sequential() model.add( tf.keras.layers.Conv2D( 32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu')) model.add(tf.keras.layers.Max...
26c42d1b24ec6cdb7b17c57e073fc41e2bf8e050
64,474
def index(): """Display the single page app""" images = [] uploads_ref = firestore_client.collection(u'uploads') uploads = uploads_ref.stream() for upload in uploads: images.append(upload.to_dict()) return render_template('index.html', images=images, qotd=getquote())
0c32203ae5b428eefb99286b17aee2f9f25db44e
64,475
def get_pos_trans_misc_minimal(observation): """ No toes_l, talus_l and pros_foot_r """ observation_array = [] body_keys = ["body_pos"] for body_key in body_keys: for body_part in ["pelvis", "head", "torso", "tibia_l", "pros_tibia_r", "femur_l", "femur_r", "calcn_l...
ccb9768798114ebd70924ebdb11d19fa9955694e
64,476
def _read_split(ext): """ Reads the train/test/val splits :param ext: string for "train", "val", or "test" :return: """ with open('{}/{}.txt'.format(SPLITS, ext), 'r') as f: return [_fix_fn(fn) for fn in f.read().splitlines()]
ae79aceec73dbad223a757c091580425268a7e92
64,477
def _get_available_extension_urls(): """ Get download urls for all the CLI extensions compatible with the installed development CLI. :return: list of 3-tuples in the form of '(extension_name, extension_file_name, extensions_download_url)' """ all_pub_extensions = list_available_extensions(show_details=...
e658b415c8c618d73ee32625d243663c99807f6c
64,478
def poly_relation(a, b): """Describe 2 polygons relation""" rels = { 'a contains b': a.contains(b), 'a crosses b': a.crosses(b), 'a disjoint b': a.disjoint(b), 'a intersects b': a.intersects(b), 'a touches b': a.touches(b), 'a within b': a.within(b), 'a co...
ae008f812f0bf31e2f4ad2384a3390ad381730ad
64,479
def pass_community_schema(f): """Decorator retrieving a community schema.""" @wraps(f) def inner(self, community_id, schema_version_nb, *args, **kwargs): try: if schema_version_nb.isdigit(): version_nb = int(schema_version_nb) community_schema = Community...
8774b59b3ef858670e6c806e19140b599a5938da
64,480
def top_sentences(query, sentences, idfs, n): """ Given a `query` (a set of words), `sentences` (a dictionary mapping sentences to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the `n` top sentences that match the query, ranked according to idf...
3c0481bbeef4ef47307ee259b835d8d91dcf47e7
64,481
def get_alias_movie_by_aliasof(sapo_id): """Gets the alias of movie given its alias id""" return db.movie_aliases.find({'alias_of': sapo_id})
ff6718d523b019de4ba1fa37f6b783d26e068ae6
64,482
from unittest.mock import patch def property_mock(request, cls, prop_name, **kwargs): """ Return a mock for property *prop_name* on class *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, prop_name, new_callable=PropertyMock, **kwargs) request.addfinalizer(...
3b2348143d4fea998254fd3623ae6c91332d5a91
64,483
def NVI(prices): """ :param prices: :return: """ # TODO:性能稍差与其他程序,很难向量化,jit优化更耗时 assert prices is not None _assert_greater_or_equal(len(prices), 1) # df_price = prices.copy() df_price = prices.sort_index(ascending=True) close, volume = df_price[['close', 'volume']].T.values ...
4cc76b915736e9c754547f213bbbc4f691c38b83
64,484
from typing import Union def __compute_lnIMi_IMj_Rup_params( mu_lnIMi_Rup: Union[pd.Series, pd.DataFrame], sigma_lnIMi_Rup: Union[pd.Series, pd.DataFrame], corr_coeff: Union[float, pd.Series], im_j: float, ): """Helper function, computes mu and sigma for the conditional (univariate) lnIMi|IMj,...
bc34abf86d982600c57f7fa68283d594338febc9
64,485
def generator_address_code(address=None): """ 生成地址码 :param address: :return: """ address_code = '' if address is not None: for key, val in data.get_address_code().items(): if val == address: address_code = key break if address_code != ...
189a9c3621020ccb4c13e36bf7d194086d5a03f8
64,486
import urllib def construct_url(query, pageSize, cursorMark): """ This function constructs a url that searches through the europepmc website and returns the results in json format. """ query_string = urllib.parse.quote(query) url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query="...
8ba97c665a259427bfc2a5c500418784855da888
64,487
def validate_sample_pgx_attributes_for_sampleSet(queryDict): """ validate the sample PGx attribuets for sample set item creation/update return a boolean isValid and a text string for error message, None if input passes validation Note: Input length will not be validated since maxLength has been specifie...
1543aeb221a4d1558718a12c5b76be742a0d662b
64,488
from itertools import chain def make_inverse_connectivity(conns, n_nod, ret_offsets=True): """ For each mesh node referenced in the connectivity conns, make a list of elements it belongs to. """ iconn = [[] for ii in xrange( n_nod )] n_els = [0] * n_nod for ig, conn in enumerate( conns ):...
baf319dc2b2516ea82e8a38f1892c9c514842214
64,489
def assign_targets_to_anchors(anchors, annotations, positive_overlap=0.5, background_threshold=0.4): """ Assign ground truth boxes to default boxes. Args: anchors: Default boxes. annotations: Ground truth boxes representing an object in the image. positive_...
6e3d889c7421120866e6668db4012f53c432c113
64,490
def ts_to_date(date_string): """Convert a datetime string (UTC) into a pretty date string""" date_rep = date_string try: date = parse(date_string) date_rep = date.strftime('%b %d %H:%M:%S %Y') except ValueError: pass return date_rep
5d99d1c9caa895984e2f57f6ddaf371d89766b86
64,491
from typing import OrderedDict from typing import List def iet_insert_C_decls(iet, func_table): """ Given an Iteration/Expression tree ``iet``, build a new tree with the necessary symbol declarations. Declarations are placed as close as possible to the first symbol use. :param iet: The input Iter...
fb27ab33e2b807c0ec7c8f4a7b15d42db1b12679
64,492
def load_dfs(f_list, par_list, lh5_group='', idx_list=None, verbose=True): """ Build a pandas dataframe from lh5 data Given a list of files (can use wildcards), a list of lh5 columns, and optionally the group path, return a pandas DataFrame with all values for each parameter. Parameters ------...
f687ba2725aeb1b727ac6c660776342cddbc0d2e
64,493
def get_pmpjpe_metric( shapes_specs): """Returns vectorized PMPJPE metric.""" x_spec = shapes_specs[0] def pmpjpe(gt_x, cur_x): # gt_x: (17, 3), cur_x: (x_shape,) cur_x_pose = unpack_and_unparam(cur_x, x_spec)[0] return single_pmpjpe(gt_x, cur_x_pose) pmpjpe_batch = vmap.vmap(pmpjpe, ['gt_x',...
cde55fcfe2bc88b24ad391bfcd5942fc94c0d281
64,494
def get_peak_points(heatmaps): """ :param heatmaps: numpy array (N,15,96,96) :return:numpy array (N,15,2) """ N, C, H, W = heatmaps.shape # print("N") # print("C") all_peak_points = [] for i in range(N): peak_points = [] for j in range(C): yy, xx = np.whe...
3b5ad0184d490d1fc556eeb7deaedcba6052e039
64,495
def get_format_from_width(width, unsigned = True): """ Returns a PortAudio format constant for the specified `width`. :param `width`: The desired sample width in bytes (1, 2, 3, or 4) :param `unsigned`: For 1 byte width, specifies signed or unsigned format. :raises ValueError...
bf8d9249c463c94e64c036b9665ea827d49ab60d
64,496
def get_dollar_amount(x): """Changes string into the equivalent float in U.S. dollars and returns it.""" x = x.strip(' ') x = x.replace(',', '') x = x.replace('+', '') x = x.replace('est.', '') #Case: Empty String if x == '': return float(0) #Corner Case: Contains the s...
71d3f11ab843940e14731f4b400aea86c1a75beb
64,497
def get_sigmas(dist_X, target_perplexity): """ Finds the sigma for each row of the distance matrix based on the target perplexity. :param dist_X: the pairwise distance matrix :param target_perplexity: the specified perplexity value :return: a vector of sigma values corresponding to each row of the d...
a7e625f4f96941b3d5fac4c81df4ae4caa0964a8
64,498
def get_hardware_info(**output_dict): """ Get the serial number/service tag of the node Does not directly output anything on its own, used in merge_dictionary function """ hw_dict = {} response_json = output_dict['GetHardwareInfo'] for node in response_json['result']['nodes']: ...
15969315bbf0d41d5d0066ca1c0dfe51c7fcbf19
64,499