content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import itertools def config_path(*args, **kwargs): """ Join multiple paths from configuration and always use config['path']['base'] as base path. Use as follows: ```python config_path('model.train') ``` :param args: Lists of keys to load. :param kwargs: Keyword arguments. Cur...
c75ffafae583cb2ea9f9d4277c556c9dc4e815d7
3,632,300
def get_one_hot_predictions(tcdcn, x, dim): """ This method gets a model (tcdcn), passes x through it and gets it's prediction, then it gets one_hot matrix representation of the predictions. depending on whether tcdcn is RCN or a structured model, x can be an image (in the former case) and a one...
27bf3ad70f77e726ba8484dec8770211907dfbd5
3,632,301
def run_multi_lsp(x, y, err, fts, fmin=0.1, fmax=150, k_band=1, m_base=1, mode='fast', dt_cut=365, k_term_base=0): """Run all methods of multiband gatspy Lomb-Scargle Periodogram. Input ------ x, y, err, fts: phase, magnitudes/flux, error, filter list fmin, fmax: minimum and maximum...
28d0061499fe809f4cce770b8a23c66d8471f741
3,632,302
def render_tablet_screen(): """ Serves the page for the tablet backend. :return: The tablet html file. """ return app.send_static_file('tablet.html')
d82f1bf75438e05c4745a7eb7e25c2223f8e98cc
3,632,303
def add_content(resp, param, value): """Adds content/body of the response. ecocnt_html: html body, ecocnt_css: css body, ecocnt_js: js body, ecocnt_img: img body, ecocnt_vid: video body, ecocnt_audio: audio body, """ if param == "ecocnt_html": t = loader.get_template("echo/t...
07bc2bc61d9901ab09b0badaef643622eb270754
3,632,304
def intersection_over_union(box1, box2): """Returns the IoU critera for pct of overlap area box = (left, right, bot, top), same as matplotlib `extent` format >>> box1 = (0, 1, 0, 1) >>> box2 = (0, 2, 0, 2) >>> print(intersection_over_union(box1, box2)) 0.25 >>> print(intersection_over_union...
4825de855bd12fcaaebbfa337fc0f6faa9482a74
3,632,305
def fpsol(nu,u): """ reads the vector normal and slip vector returning strike, rake, dip """ dip=np.arccos(-1*nu[2]) if nu[0] ==0. and nu[1] == 0.: str=0. else: str=np.arctan2(-1*nu[0],nu[1]) sstr=np.sin(str) cstr=np.cos(str) sdip=np.sin(dip) cdip=...
735e99dc9b00c1d22c6a6976892ed709840cc007
3,632,306
def create_short_ticket(access_token, expire_seconds=2592000, scene_id=0): """ 创建临时二维码 :param access_token: 微信access_token :param expire_seconds: 二维码过期时间 :param scene_id: 场景值ID :return: """ target_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s' % access_token ...
30dc627d5319d8145854b568ce8b7a8d4e4eba69
3,632,307
import os def gen_compound(name, N=50, nP=10): """ (1) Alkane vs Alcohol N: the #carbon atom in compound, ex: N=50 generates compounds of different length from 1 to 50 carbons P: # of permutation to relabeling the vertex order for each generated compound -----------------------------------...
b5b33b50ea9245669eb98f7f0f3c002dcf79e87e
3,632,308
from datetime import datetime import os def build_youtube_search_request(): """ Building a query based on the following API - https://developers.google.com/youtube/v3/docs/search/list """ video_search_params = { "part": "id,snippet", "type": "video", "maxResults": 50, "...
4e79bcc8154f6384a371b236154d8eba7050c43c
3,632,309
from qtpy.QtWidgets import QDesktopWidget # noqa def get_screen_size(): """Get **available** screen size/resolution.""" if mpl.get_backend().startswith('Qt'): # Inspired by spyder/widgets/shortcutssummary.py widget = QDesktopWidget() sg = widget.availableGeometry(widget.primaryScreen(...
9575fbf1874d6dcf22e0ebb5a771015dfa570847
3,632,310
def potential_bond_keys(mgrph): """ neighboring radical sites of a molecular graph """ ridxs = radical_sites(mgrph) return tuple(frozenset([ridx1, ridx2]) for ridx1, ridx2 in combinations(ridxs, 2) if ridx2 in atom_neighborhood_indices(mgrph, ridx1))
ccbff81075cab38b3bc96b39885f1873c733bd93
3,632,311
def convolve(signal,kernel): """ This applies a kernel to a signal through convolution and returns the result. Some magic is done at the edges so the result doesn't apprach zero: 1. extend the signal's edges with len(kernel)/2 duplicated values 2. perform the convolution ('same' mode) ...
1eb31d9fdf2a6afa6ea08912f8b28f0ae4af64e6
3,632,312
def makemebv(gmat, meff): """Set up family-specific marker effects (GEBV).""" qqq = np.zeros((gmat.shape)) for i in range(gmat.shape[0]): for j in range(gmat.shape[1]): if gmat[i, j] == 2: qqq[i, j] = meff[j]*-1 elif gmat[i, j] == 1: qqq[i, j] ...
44cbcdeadbfee9b7e802e201ad589f9ebdcb11b3
3,632,313
from typing import Tuple from typing import Optional import io import textwrap from re import I def _define_property_shape( prop: intermediate.Property, cls: intermediate.ClassUnion, url_prefix: Stripped, class_to_rdfs_range: rdf_shacl_common.ClassToRdfsRange, constraints_by_property: infer_for_sc...
29483d27548a7fbd208f820e8e0821e0b121132f
3,632,314
def row2string(row, sep=', '): """Converts a one-dimensional numpy.ndarray, list or tuple to string Args: row: one-dimensional list, tuple, numpy.ndarray or similar sep: string separator between elements Returns: string representation of a row """ return sep.join("{0}".form...
f81a2ec54b8c37285715cadca4458918962440b9
3,632,315
from sys import path import time import requests import json def download_profile_picture(user_id, discriminator, avatar_hash=None, cache_dir="cache", default_dir="default", cert_file=None, game_name=None, game_version=None, game_url=None): """ Download a discord user's profile pi...
c68cc069a4666d6f693271971d94829e2bb963ae
3,632,316
def apply_kNNO(Xs, Xt, ys=None, yt=None, scaling=True, k=10, contamination=0.1): """ Apply kNNO. k-distance is the distance of its k-th nearest neighbour in the dataset KNNO ranks all instances in a dataset by their k-distance, with higher distances signifying more anomalous instances Parameter...
6a90757063ff20dba11075508bce7038295920a1
3,632,317
import logging def _tenant_update(name, new_name=None, description=None, default_datastore=None): """ API to update a tenant """ logging.debug("_tenant_update: name=%s, new_name=%s, descrption=%s, default_datastore=%s", name, new_name, description, default_datastore) error_info, tenant =...
87b9586b87868c3693b09a4127edc148c6d36bb0
3,632,318
from typing import Iterable import os def _clone_all(urls: Iterable[str], cwd: str): """Attempts to clone all urls, sequentially. If a repo is already present, it is skipped. If any one clone fails (except for fails because the repo is local), all cloned repos are removed Args: urls: HTTPS u...
5a7c10de2fc8e1c4f77e9a7505315b62a94eb28e
3,632,319
def build_aggregation(facet_name, facet_options, min_doc_count=0): """Specify an elasticsearch aggregation from schema facet configuration. """ exclude = [] if facet_name == 'type': field = 'embedded.@type' exclude = ['Item'] elif facet_name.startswith('audit'): field = facet...
b8c3f337143a229401b9a41a8fde8903027cf67e
3,632,320
def recover_marker_rbt(itf, tgt_mkr_name, cl_mkr_names, log=False): """ Recover the trajectory of a marker by rbt(rigid body transformation) using a group (cluster) markers. The number of cluster marker names is fixed as 3. This function extrapolates the target marker coordinates for the frames whe...
598cd920494dac9e2847e9fdf7a0b1d66715957b
3,632,321
def route_wrap_01_version(request_mapping: str): """ flask 路由映射包裹器 增加API_VERSION :param request_mapping: :return: """ return '{}/{}'.format(API_VERSION, request_mapping)
0a3db2ed132c1f2233817a8154c5c1c87872d6dc
3,632,322
def spawn(pool): """spawn a greenlet it will be automatically killed after the test run """ return pool.spawn
fadea4b814e77f7fb26af27f0cc7bce1189a7dcf
3,632,323
from typing import Any import json def from_json_util(json_str: str) -> Any: """Load an arbitrary datatype from its JSON representation. The Out-of-proc SDK has a special JSON encoding strategy to enable arbitrary datatypes to be serialized. This utility loads a JSON with the assumption that it follo...
5da695fb260b1df35dc91dfb8ef9026b04472d6a
3,632,324
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
7bddc4e58344e519a2bd928187db3a6b65e17118
3,632,325
def inline(text): """ Convert all newline characters to HTML entities: &#10; This can be used to prevent Hypertag from indenting lines of `text` when rendering parent nodes, and to safely insert `text` inside <pre>, <textarea>, or similar elements. """ return text.replace('\n', '&#10;')
658f7e5adbf5747ea069fad8a9599e9bd499a381
3,632,326
def align_pos(xyz, test_crd, ref_crd, ind=None): """Translates a set of atoms such that two positions are coincident. Parameters ---------- xyz : (N, 3) array_like The atomic cartesian coordinates. test_crd : (3,) array_like Cartesian coordinates of the original position. test_c...
ffa6001e20a4e4a1379e6a95139946aa91a5bdd0
3,632,327
from typing import Optional from typing import Sequence def get_orderable_db_instance(availability_zone_group: Optional[str] = None, engine: Optional[str] = None, engine_version: Optional[str] = None, instance_class: Optional[st...
6557de19d6c14d903d9f3058f7428ffe700633d0
3,632,328
def publish_channel_url(): """open_channel_url: returns url to publish channel Args: None Returns: string url to publish channel """ return PUBLISH_CHANNEL_URL.format(domain=DOMAIN)
7ba59e32746b9ffa9c9a46fd073cfbb1c3905e9f
3,632,329
def hist_counts(df_acts=None, lst_acts=None, df_ac=None, y_scale="linear", idle=False, figsize=None, color=None, file_path=None): """ Plot a bar chart displaying how often activities are occurring. Parameters ---------- df_acts : pd.DataFrame, optional recorded activities fr...
4e9820d25bd2f33de8269f413fbce0b1898fd7fa
3,632,330
def random_dense(shape, fortran): """Generate a random qutip Dense matrix of the given shape.""" return qutip.core.data.Dense(random_numpy_dense(shape, fortran))
869c8cd2972b40f82d73403ed5c54d170fe3dcb5
3,632,331
import torch def bo_step(X, y, objective, bounds, GP=None, acquisition=None, q=1, state_dict=None, *GP_args, **GP_kwargs): """ One iteration of Bayesian optimization: 1. Fit GP model using (X, y) 2. Create acquisition function 3. Optimize acquisition function to obtain cand...
e752091e5aaf3b42e3e8f21a21f0368485f60c25
3,632,332
def validate_inputs(input_data): """Check prediction inputs against schema.""" # set many=True to allow passing in a list schema = InsuranceDataRequestSchema(strict=True, many=True) errors = None try: schema.load(input_data) except ValidationError as exc: errors = exc.messages ...
e0faacabb729d191308bdf1d5710525b529d4793
3,632,333
def published_stats_list(request): """ List cumulative stats about projects published. The request may specify the desired resource type """ resource_type = None # Get the desired resource type if specified if 'resource_type' in request.GET and request.GET['resource_type'] in ['0', '1']: ...
308ef79fb6f51d192adb31849dd6bb75a46fe469
3,632,334
def get_entity(name): """Get an entity by the given name. Args: name (str): namespace.entity_name Returns: OntologyEntity: The entity with the given name. """ ns, n = name.split(".") return _namespace_registry._get(ns)._get(n)
bd00058f8d3af4d29b35bcf0cc336f4c567baf8a
3,632,335
def tst(): """members page.""" return render_template('users/testing2.html')
042463af7cc3742e78f744bc66ad09c3060ca877
3,632,336
def get_bq_col_type(col_type): """ Return correct SQL column type representation. :param col_type: The type of column as defined in json schema files. :return: A SQL column type compatible with BigQuery """ lower_col_type = col_type.lower() if lower_col_type == 'integer': return 'I...
86cac08a04d804cc6addbeee86014f1aa6d35735
3,632,337
def _do_boundary_search(search_term): """ Execute full text search against all searchable boundary layers. """ result = [] query = _get_boundary_search_query(search_term) with connection.cursor() as cursor: wildcard_term = '%{}%'.format(search_term) cursor.execute(query, {'term'...
b2cc74b7ba436c0c57bbb7505d964d79354a36f5
3,632,338
def prices(identifier, start_date=None, end_date=None, frequency='daily', sort_order='desc'): """ Get historical stock market prices or indices. Args: identifier: Stock market symbol or index start_date: Start date of prices (default no filter) end_date: Last date (defaul...
145d8ea607a1e374e205ef337345f7b9d6064479
3,632,339
import requests import json def verify_captcha(secret, response, remoteip=None): """ From https://developers.google.com/recaptcha/docs/verify: secret: The shared key between your site and ReCAPTCHA. response: The user response token provided by the reCAPTCHA to the user and provide...
fbfaea5a388f5047322cdb05d0b37d7f445a2b17
3,632,340
def x1y1x2y2_to_xywh(x1y1x2y2): """Convert [x1 y1 x2 y2] box format to [x y w h] format.""" if isinstance(x1y1x2y2, (list, tuple)): # Single box given as a list of coordinates assert len(x1y1x2y2) == 4 ct_x, ct_y = (x1y1x2y2[3] + x1y1x2y2[1]) / 2, (x1y1x2y2[2] + x1y1x2y2[0]) / 2 ...
b5535ace312ca2f790f4dcb66ed9e53223b90649
3,632,341
def col(loc, strg): """ Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more ...
0dfc4387e391c4823939350ad19c60d106211a58
3,632,342
def create_model_fn(model_class, hparams, use_tpu=False): """Wraps model_class as an Estimator or TPUEstimator model_fn. Args: model_class: AstroModel or a subclass. hparams: ConfigDict of configuration parameters for building the model. use_tpu: If True, a TPUEstimator model_fn is returned. Otherwise ...
83be600771b8e64c610db0d3d16fe10ba668fbd0
3,632,343
from typing import Any def boolean(value: Any) -> bool: """Validate and coerce a boolean value.""" if isinstance(value, str): value = value.lower() if value in ("1", "true", "yes", "on", "enable"): return True if value in ("0", "false", "no", "off", "disable"): ...
781dbb2e30448065d8dc65b42ab02914a3338b43
3,632,344
def unmap(data, count, inds, fill=0): """ Unmap a subset of item (data) back to the original set of items (of size count) :param data: input data :param count: the total count of data :param inds: the selected indices of input data :param fill: filled value :return: unmaped data """ ...
3cc361650644275673e6340f8d6a216071b0c3c9
3,632,345
def processbundle(repo, unbundler, transactiongetter=None, op=None, source=b''): """This function process a bundle, apply effect to/from a repo It iterates over each part then searches for and uses the proper handling code to process the part. Parts are processed in order. Unknown Mandatory part will ...
4651bc64da5d48d992379301294c480f9d42cb0f
3,632,346
def recursive_feature(G, f, n): """ G: iGraph graph with annotations func: string containing function name n: int, recursion level Computes the given function recursively on each vertex Current precondition: already have run the computation for G, func, n-1. """ retur...
4516e85cddea50dc9a1f14448a7b950a0620e3f0
3,632,347
import unicodedata def remove_accents(string): """ Removes unicode accents from a string, downgrading to the base character """ nfkd = unicodedata.normalize('NFKD', string) return u"".join([c for c in nfkd if not unicodedata.combining(c)])
41c8e05aa8982c85cf5cf2135276cdb5e26fefec
3,632,348
from typing import Optional def __get_a0( # pylint: disable=invalid-name n: int, a0: Optional[np.ndarray] = None ) -> np.ndarray: """ Returns initial parameters for fitting algorithm. :param n: Number of parameters :param a0: Initial parameters value. Optional :return: nd.array """ i...
80b5d974dd6187746215191cc1f4de1ae135b93e
3,632,349
def convert_yaw_to_old_viewpoint(yaw): """ we initially had viewpoint coordinates inverted Example: >>> import math >>> TAU = 2 * math.pi >>> old_viewpoint_labels = [ >>> ('left' , 0, 0.000 * TAU,), >>> ('frontleft' , 45, 0.125 * TAU,), >>> ...
7659e15bf7f4693ac7c6223b8f4600450bc7f2fe
3,632,350
import os def uploadimages(path_list,client,csv_list): """Uploads images to imgur. Arguments: path_list {list} -- [List of files at directory.] client {ImgurClient} -- [ImgurClient we get from authentication.] csv_list {list} -- [List of uploaded pictures.] """ #we create a da...
cdc798a60e38fea6e07325b7e50e2c11d80ee6aa
3,632,351
def extract_lexical_features_test(nlp, tweet_list): """Provides tokenization, POS and dependency parsing Args: nlp (spaCy model): Language processing pipeline """ result = [] texts = (tweet for tweet in tweet_list) for doc in nlp.pipe(texts, batch_size=10000, n_threads=3): setti...
b0f87996558c4b2e1d77b59068e8ad259524a455
3,632,352
def get_hostname(): """ Return hostname. """ return tg.config.get('workbox.hostname')
367dda60f71d169c6490913a3ee3f8befc83b738
3,632,353
import http def geocode_location(api_key, loc): """Get a geocoded location from gooogle's geocoding api.""" try: parsed_json = http.get_json(GEOCODING_URL, address=loc, key=api_key) except IOError: return None return parsed_json
95c820abc58a13cd57e662e78bfab8fceac5eadf
3,632,354
def degree(f, *gens, **args): """ Return the degree of ``f`` in the given variable. The degree of 0 is negative infinity. Examples ======== >>> degree(x**2 + y*x + 1, gen=x) 2 >>> degree(x**2 + y*x + 1, gen=y) 1 >>> degree(0, x) -inf """ allowed_flags(args, ['gen'...
a6b5e2ba9228ea1477234c0e16477dd603fb9598
3,632,355
from typing import Dict def fit_model_sector(sector_corpus: Dict[DocId, Token]) -> sbmtm: """Fits the model taking the sector corpus data structure as an input Args: sector_corpus: a dict where keys are doc ids and values are the tokenised descriptions Returns: The model ...
d025a0f4faac53b4b21486e159a0310c78dc72b8
3,632,356
def get_simulated_matches(path, met, sample_to_match, pop_var): """Selects initial conditions from cosmic data to match to star sample Parameters ---------- path : `str` path to cosmic data met : `float` metallicity of cosmic data file sample_to_match : `DataFrame` A d...
ecbb46f284f7b6748031b0907813deaad8967eba
3,632,357
def _get_url_ext(url: str): """ >>> _get_url_ext('http://example.com/blog/feed') 'feed' >>> _get_url_ext('http://example.com/blog/feed.xml') 'xml' >>> no_error = _get_url_ext('http://example.com') """ try: url_path = urlparse(url).path.strip('/') except ValueError: re...
61b94bd2c98686192a47ade9bb240bc4c58904c2
3,632,358
def connect_server(): """Connect to azure cosmos DB. Connet to azure cosmos DB. Need to insert ID, DB name, table name, and key. Args: None Returns: clt(str): an instance for connecting to azure cosmos DB server """ clt = client.Client( 'wss://<YOURID>...
1826b4676af381882710a8802392f7f1d4f2253e
3,632,359
def checkCpuTime(sleeptime=0.2): """Check if cpu time works correctly""" if checkCpuTime.passed: return True # First test that sleeping does not consume cputime start1 = process_time() sleep(sleeptime) t1 = process_time() - start1 # secondly check by comparing to cpusleep (where we ...
5b7db840f56b5eafdbfa857c470c316c257c9bac
3,632,360
import logging import os import csv def xmind_to_iwork_csv_file(xmind_file): """Convert XMind file to a iwork csv file""" xmind_file = get_absolute_path(xmind_file) logging.info('Start converting XMind file(%s) to iwork file...', xmind_file) testcases = get_xmind_testcase_list(xmind_file) filehea...
56fd6f7cb6413bf25d7bf2200d6972765477a9c0
3,632,361
def load_ply(path): """ Loads a 3D mesh model from a PLY file. :param path: A path to a PLY file. :return: The loaded model given by a dictionary with items: 'pts' (nx3 ndarray), 'normals' (nx3 ndarray), 'colors' (nx3 ndarray), 'faces' (mx3 ndarray) - the latter three are optional. """ ...
289c0854bc3270dafab5689bc53d2507ff27c67c
3,632,362
def parse_range(rng, dictvars={}): """Parse a string with an integer range and return a list of numbers, replacing special variables in dictvars.""" parts = rng.split('-') if len(parts) not in [1, 2]: raise ValueError("Bad range: '%s'" % (rng,)) parts = [int(i) if i not in dictvars else dictva...
214109a71c84d06241e29cacaa052d9ce00302c5
3,632,363
from typing import Union from typing import Iterable from typing import List from pathlib import Path def relpaths(basepath: _path_t, pattern: Union[str, Iterable[_path_t]]) -> List[str]: """Convert a list of paths to relative paths Parameters ---------- basepath : Union[str, Path] Path to us...
80c9febd541d8fd1ab190b2ef36e8929ee387b08
3,632,364
def binary_backtests_returns( backtests: pd.DataFrame, ) -> pd.DataFrame: """ Converts a Horizon backtest data frame into a binary backtests of directions """ return backtests.diff().apply(np.sign).dropna()
0355cd48620cbdbe54eb4ee48e82f7315f069263
3,632,365
def calculate_students_features_csv(entry_id, xmodule_instance_args): """ Compute student profile information for a course and upload the CSV to an S3 bucket for download. """ # Translators: This is a past-tense verb that is inserted into task progress messages as {action}. action_name = ugettex...
ccf8eae3b9732535c94381ba1909f36bce52556d
3,632,366
def colorMap(value, name="jet", vmin=None, vmax=None): """Map a real value in range [vmin, vmax] to a (r,g,b) color scale. :param value: scalar value to transform into a color :type value: float, list :param name: color map name :type name: str, matplotlib.colors.LinearSegmentedColormap :return:...
8e444db6b3e04229dbf8b46cbe68ce6337032b01
3,632,367
def save_genre(row: dict): """Genre's control and save in data base.""" try: result: Genres = session.query(Genres) \ .filter(Genres.name == row.get('genre_name')) \ .one() return result except MultipleResultsFound: pri...
0c7e26082816a2639cc4561a1e9ee5f2697a4175
3,632,368
def specializations(examples_so_far, h): """Specialize the hypothesis by adding AND operations to the disjunctions""" hypotheses = [] for i, disj in enumerate(h): for e in examples_so_far: for k, v in e.items(): if k in disj or k == 'GOAL': continue ...
5f21edd18477c09d37a03026073c0120b6be41b9
3,632,369
def formulate_contingency(problem: LpProblem, numerical_circuit: OpfTimeCircuit, flow_f, ratings, LODF, monitor, lodf_tolerance): """ :param problem: :param numerical_circuit: :param flow_f: :param LODF: :param monitor: :return: """ nbr, nt = ratings.shape ...
ecc5deb3b689a5802341d48e81382d2d602f1ebc
3,632,370
def max_pooling3d(inputs, pool_size, strides, padding='valid', data_format='channels_last', name=None): """Max pooling layer for 3D inputs (e.g. volumes). Arguments: inputs: The tensor over which to pool. Must have rank 5. pool_size: An integer or tuple...
49756ea26e58549115408fbcb4ce179442a09942
3,632,371
def parareal_engine(x_0, U, num_iter, coarse_model="learned"): """Rolls out a trajectory using Parareal Args: x_0: Initial state U: Control sequence num_iter: Number of Parareal iterations to use for prediction coarse_model: Learned/Analytical coarse model Returns: X: The corresponding state seq...
bd589650711d510fcffb2033dd5f7a501dc4e041
3,632,372
def plot_posterior_op(trace_values, ax, kde_plot, point_estimate, round_to, alpha_level, ref_val, rope, text_size=16, **kwargs): """Artist to draw posterior.""" def format_as_percent(x, round_to=0): return '{0:.{1:d}f}%'.format(100 * x, round_to) def display_ref_val(ref_val): ...
13d7d12dfac13f803fb08b49970471e4f97c7bff
3,632,373
from operator import sub from re import M def change_theme(file: str, theme_name: str, logfile: str) -> bool: """ Change Oh My ZSH Theme """ if get_zsh_theme(file, logfile): current_file = read_file_log(file, logfile) current_theme = get_zsh_theme(file, logfile)[1] new_theme = ...
55438f7d93779417aff4dfa4170997269b200dca
3,632,374
def check_tensor(data): """Ensure that data is a numpy 4D array.""" assert isinstance(data, np.ndarray) if data.ndim == 2: data = data[np.newaxis,np.newaxis,...] elif data.ndim == 3: data = data[np.newaxis,...] elif data.ndim == 4: pass else: raise RuntimeError('...
d641645e9a2c780d52c5e635859bdfcce61f86ab
3,632,375
from typing import Type from typing import Optional def _find_first_ref(ref: Ref, message_type: Type[B]) -> Optional[B]: """ Finds and returns (if exists) the first instance of the specified message type within the specified Ref. """ # Get the body message, if it exists body = _get_ref_body(ref) ...
474ad2a2c874c6ae226475fc1e4b144fdd4f72a1
3,632,376
def verify_activation_token(*, uidb64, token): """ :param uidb64: (str) Base 64 of user PK. :param token: (str) Hash. :return: (bool) True if user verified, False otherwise. """ user_id = force_text(urlsafe_base64_decode(uidb64)) try: user = User.objects.get(pk=user_id) except ...
f184a85852906526434dc54b2e26491ad3dafc51
3,632,377
def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a min...
f91d004eefd6e8c2bd7c151628a7aa809b2c40da
3,632,378
def read_protein_from_file(file_pointer): """The algorithm Defining Secondary Structure of Proteins (DSSP) uses information on e.g. the position of atoms and the hydrogen bonds of the molecule to determine the secondary structure (helices, sheets...). """ dict_ = {} _dssp_dict = {'L': 0, 'H': 1,...
071a7b04b652261f83311e250e92884e95a4e818
3,632,379
def match(string, rule='IRI_reference'): """Convenience function for checking if `string` matches a specific rule. Returns a match object or None:: >>> assert match('%C7X', 'pct_encoded') is None >>> assert match('%C7', 'pct_encoded') >>> assert match('%c7', 'pct_encoded') """ ...
c6c2079786651bfaa1ba819251e1d51a276bf8cd
3,632,380
from typing import List def verify_td3(mrz: List[str]) -> bool: """Verify TD3 MRZ""" if mrz[0][0] != "P": return False # if mrz[0][1]: # At the discretion of the issuing State or organization or "<" # if mrz[0][2:5]: # ISSUING STATE OR ORGANIZATION # if mrz[0][5:44]: # NAME if calculat...
13dca85d0f91cac9bbf759f8a5171e73ddfb4836
3,632,381
def compute_pwcca(acts1, acts2, epsilon=0.): """ Computes projection weighting for weighting CCA coefficients Args: acts1: 2d numpy array, shaped (neurons, num_datapoints) acts2: 2d numpy array, shaped (neurons, num_datapoints) Returns: Original cca coefficient mean and weighted mean ...
17f0b6674cd1c45435eb73bc4e754543640543d6
3,632,382
def read_table(srm_file): """ Reads SRM compositional data from file. For file format information, see: http://latools.readthedocs.io/en/latest/users/configuration/srm-file.html Parameters ---------- file : str Path to SRM file. Returns ------- SRM compositions : panda...
6ec87cab30162af55e3cce659b3ef7a205857595
3,632,383
def walker_method(for_class=object, methods_list=None): """A decorator to add something to the default walker methods, selecting on class """ if methods_list is None: # handle early binding of defaults methods_list = fallback_walker_method_list def wrap(walker): # wrap a walker wi...
b500f04510695e5cfd88590feaa75b27aee3b5b8
3,632,384
import pandas as pd from IPython.display import display def get_data(name_dataset='index', verbose=True, address="../datasets/",): """ This function is to load dataset from the git repository :param name_dataset: name of dataset (str) :param verbose: :param address: url o...
fa518e744d43950ebcf65d00a5aa474d4fb36443
3,632,385
import torch def copy_valid_indices( acts, # type: torch.Tensor target, # type: List[List[int]] act_lens, # type: List[int] valid_indices, # type: List[int] ): # type: (...) -> (torch.Tensor, List[List[int]], List[int]) """Copy the CTC inputs without the erroneous samples""" if len(val...
9eac2b7304ff5157ca13fae9d790af6c2b67d9c7
3,632,386
def is_odd(num: int) -> bool: """Is num odd? :param num: number to check. :type num: int :returns: True if num is odd. :rtype: bool :raises: ``TypeError`` if num is not an int. """ if not isinstance(num, int): raise TypeError("{} is not an int".format(num)) return num % 2 ==...
0e5781596a99909e58583859948332c3afb06fb0
3,632,387
def cross_entropy_loss(y_hat, y): """ Cross entropy loss y_hat: predict y after softmax, shape:(M,d), M is the #of samples y: shape(M,d) """ loss = np.mean(np.sum(- y * np.log(y_hat), axis=-1)) dy = y_hat - y return loss, dy
81f6dc61d0ed9d9e5eac4a41042679b3ea01167d
3,632,388
import string def string_list(resource_name, encoding='utf-8'): """Package resource wrapper for obtaining resource contents as list of strings. The function uses the 'string' method and splits the resulting string in lines. Params: resource_name: Relative path to the resource in the pack...
88e7103056e38020670a74a19bfeee90326e7d38
3,632,389
import os def get_plugin_names(): """ Get the list of names of registered plugins. """ pluginlist = [] # Read if os.path.isfile(regfile): with open(regfile, 'rb') as f: pluginlist = f.read().decode().splitlines() # Clean pluginlist = [line.strip() for line in pluginlist...
b86908b2789598f1bd46249ab31f9d1990a87d68
3,632,390
from typing import Optional def rpc_get_name() -> Optional[str]: """Retrieve the JsonRpc id name.""" global _RpcName return _RpcName
2b7d7e9b37b00281b0791e446e5ad4bacee78c4b
3,632,391
def _epd_platform_from_raw_spec(raw_spec): """ Create an EPDPlatform instance from the metadata info returned by parse_rawspec. if no platform is defined ('platform' and 'osdist' set to None), then None is returned. """ platform = raw_spec[_TAG_PLATFORM] osdist = raw_spec[_TAG_OSDIST] i...
b6757206e6753441478629519531b0ec5adfc83a
3,632,392
def index(request): """The home page for Distance Tracker.""" if request.user.is_authenticated: today = date.today() cur_week = today.isocalendar()[1] cur_month = today.month cur_year = today.year exercises_week = Exercise.objects.filter(owner=request.user, ...
279f6e7c1cb9f2821ebee7b138c7b8b22e60768e
3,632,393
import runpy import imp def mod_from_file(mod_name, path): """Runs the Python code at path, returns a new module with the resulting globals""" attrs = runpy.run_path(path, run_name=mod_name) mod = imp.new_module(mod_name) mod.__dict__.update(attrs) return mod
3ea8109d912582555b76816f55fbb632ba82f189
3,632,394
def interpolation(x0: float, y0: float, x1: float, y1: float, x: float) -> float: """ Performs interpolation. Parameters ---------- x0 : float. The coordinate of the first point on the x axis. y0 : float. The coordinate of the first point on the y axis. x1 : float. T...
f8fc96c6dc6c2eeeeceb22f92b32023f3873fe3e
3,632,395
def do2ptblinding(unblindedfile, cosmfile, inifor2pt, outftag = 'bl', seed='blinded'): """ Given unblinded data file, computes and applies blinding factors. Factors are computed doing [shift cosm 2pt fn]/[ref cosm 2pt fn] where cosm parameters are taken from pregenerated cosmfile, and the shifted c...
64f1cc3d684f18f6cd0443a4333167aba6585054
3,632,396
import collections def product_counter_v3(products): """Get count of products in descending order.""" return collections.Counter(products)
22c57d50dc36d3235e6b8b642a4add95c9266687
3,632,397
def remove_noise(line,minsize=8): """Remove small pixels from an image.""" if minsize==0: return line bin = (line>0.5*np.amax(line)) labels,n = ndimage.label(bin) sums = ndimage.sum(bin,labels,range(n+1)) sums = sums[labels] good = np.minimum(bin,1-(sums>0)*(sums<minsize)) return good
1e19fad38a081db35ac31e3e19d224f4cb8e7d59
3,632,398
import textwrap def _ParseFormatDocString(printer): """Parses the doc string for printer. Args: printer: The doc string will be parsed from this resource format printer. Returns: A (description, attributes) tuple: description - The format description. attributes - A list of (name, descript...
f5aaffb91cbedbc1b6e0da64cdfb3ff4adfa684e
3,632,399