content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getPublishersBooksIDs(publisher, base=ALEPH_DEFAULT_BASE): """ Get list of :class:`DocumentID` objects of documents with given `publisher`. Args: publisher (str): Name of publisher which will be used to search Aleph. base (str, optional): base on which will be search performed. Defa...
887e4b608f74e03d1a7eb0c022e39d22f688c4ca
54,610
def czt(x, m=None, w=1.0, a=1, axis=-1): """ Compute the frequency response around a spiral. Parameters: ---------- x: array The set of data to transform. m: int The number of points desired. Default is the length of the input data. a: complex The starting point in the com...
a28e49c58270b8c8019f896593e62c822528a55d
54,611
def gettitle(): """Return title string to be used in the timeline""" return "%s [ %s, %s - %s ]" % ( params['TIMELINE.pretitle'], params['TIMELINE.title'], gettimelinestartdate().toString(), gettimelineenddate().toString())
e7462cffb6e08fe59fb67f0fb3da0dba599e0f7e
54,612
def refresh_token(token) -> dict or None: """ JWT access token refresh method. Args: token: payload containing jwt access token to refresh and refresh token. Returns: refreshed jwt token payload. """ user = token['user'] user_refresh_token = token['refresh_token'] try:...
3604d34b8ee9d76cae2f537c02c84b343f9a1f84
54,613
def resume(): """ Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped. """ t = timer() if f.t.stop...
afdf7969d62427ee0b9d527d756ca4f3e77f4018
54,615
def encode_side(side): """ Return side index by letter :param side: 'n' | 'o' | 's' | 'w' :return: 0 | 1 | 2 | 3 """ if side and isinstance(side, str): side = str.lower(side) else: raise SideValueError side_list = ['n', 'o', 's', 'w'] try: retur...
92d031bff824ff897ba489bc700c71b3bbaee3b0
54,616
def mmr_df_filter(df, years, start_date, end_date): """Return dataframe filtered by given years, start_date and end_date. df is mmr dataframe (mandatory) years is a list of Workout_date years to include in plot (mandatory) e.g. years=[2020, 2021] - if no value is given (years=No...
6fb939b01731f6c3d4153a6fbcbcca7e64af9696
54,617
def loggedReactor(reactor): """ Construct and return a wrapper around the given C{reactor} which provides all of the same interfaces, but which will log all traffic over outgoing TCP connections it establishes. """ bases = [] for iface in providedBy(reactor): if iface is IReactorTCP:...
0948f9f070bab308ad4acc97f762633e48c7efec
54,618
def process_head_element_content(placeholder_storage, markup): """ Process content for elements inside <head>. Processes CMD syntax which does not produce new elements, i.e. escapes, line continuations, and whitespace, and then protects the content with a placeholder. """ markup = process_escapes(pl...
27ac55590fb62ae9194b5a1549268e412c03f701
54,621
def central_derivative(xs, ys): """ central derivative at x[1] """ return (ys[2]-ys[0])/(xs[2]-xs[0])
ef3e397eda004f9f2afbd2a5bd5c8c23b72755c5
54,622
def print_from_tests(pav_cfg, tests, outfile, json=False): """Print the statuses given a list of test objects or a single test object. :param dict pav_cfg: Base pavilion configuration. :param Union(test_run.TestRun,list(test_run.TestRun) tests: Single or list of test objects. :param bool json: ...
4ed044189bf9fa3c9c418956cc80414580294471
54,623
def plot_boxplot(data, ylabel, title, log_scaling=True): """ Args: data: Dict of list of numbers. """ fig, ax = plt.subplots(1, 1, figsize=(8, 6), dpi=300) plt.xticks(rotation=90) ax.boxplot(data.values(), labels=data.keys()) ax.set_ylabel(ylabel) ax.set_title(title) if log...
1e08ac5415edfff41432445189652d135827906b
54,624
def submit_dataframe_operation(comms, coroutine, df_list, extra_args=()): """Submit an operation on a list of Dask dataframe Parameters ---------- coroutine: coroutine The function to run on each worker. df_list: list of Dask.dataframe.Dataframe Input dataframes extra_args: tupl...
33173645ed1b71eb0f6d4cc7d2ceed44dbf76358
54,625
from typing import Union def encode(message: Union[str, bytes]) -> bytes: """Encodes a message (str or bytes) to zbase32.""" if isinstance(message, str): message = message.encode('ASCII') elif not isinstance(message, bytes): raise TypeError("message must be string or bytes") barr = _m...
5c278e16822fc721b4219dda28c0b154eeaf7020
54,626
from typing import Callable def linear_adjoint(fun: Callable, *primals) -> Callable: """Conjugate transpose a function that is promised to be linear. :func:`scico.linear_adjoint` differs from :func:`jax.linear_transpose` for complex inputs in that the conjugate transpose (adjoint) of `fun` is returned. ...
8c3f3d8db725bd107c5236e352c240df010b0f01
54,627
def parse_sra(path_to_config): """ Parses genetorrent config file. Returns list of samples: [ [id1, id1 ], [id2, id2], ... ] Returns duplicate of ids to follow UUID/URL standard. """ samples = [] with open(path_to_config, 'r') as f: for line in f.readlines(): if not line.iss...
59c5ddc2e2efca6cada28db4ea225bc0590f1fb2
54,628
def queryTagHistory( paths, # type: List[String] startDate=None, # type: Optional[Date] endDate=None, # type: Optional[Date] returnSize=-1, # type: Optional[int] aggregationMode="Average", # type: Optional[String] returnFormat="Wide", # type: Optional[String] columnNames=None, # type:...
b9bc9fdda65dcd5e8b5918b75bd38b20e514b0a7
54,629
import torch def hard_sigmoid(tensor: torch.Tensor, inplace: bool = False) -> torch.Tensor: """ Applies HardSigmoid function element-wise. See :class:`torchlayers.activations.HardSigmoid` for more details. Arguments: tensor : Tensor activated element-wise inplace : ...
5f4d87749ddca014076f46e0af6e9b3c4308ddf7
54,630
def define_ns_gnn_encoder(gnn_name): """ return specified model class for GNNs with node-sampling. """ if gnn_name == 'gat': return SamplingGAT elif gnn_name == 'sage': return SAGE elif gnn_name == 'mpnn': return SamplingMPNN else: raise NotImplementedError("n...
2f89a708e8c417b246291cffa0eaee21eb9f56c7
54,631
def egaussian(p, x, y, e=None): """ Compute the deviation between the values y and the gaussian defined by p, x: p is a three- or four-component array, list, or tuple. Returns: y - p3 - p0/(p1*sqrt(2pi)) * exp(-(x-p2)**2 / (2*p1**2)) if an error array, e (typ. one-sigma) is entered, the returned va...
80b155783eb27de52f2553047c505cf9c8e0203e
54,632
from typing import Optional def _get_html_tree(html_content: str) -> Optional[lxml.html.HtmlElement]: """Obtain the HTML parse tree for the given HTML content. Args: html_content: The content to parse. Returns: The corresponding HTML parse tree. """ html_content = html_content.st...
842805b6b364d7cc277633daca6a42999b9d7972
54,635
from typing import Callable def get_int(prompt: str | None = None, min_value: int | None = None, max_value: int | None = None, condition: Callable[[int], bool] | None = None, default: int | None = None) -> int: """Gets an int from the command line. :param promp...
e1c2beada06088804709d572a848f827a3946fb2
54,637
from typing import Tuple def _normalize_array(array_data: Array, normalizer: Tuple[Array, Array]) -> Array: """Helper function for normalize_graph().""" shift, scale = normalizer return (array_data - shift) / scale
2a206eb871dc40cc29d064b64e26b8e89f4979e1
54,638
def linear_gauss_policy_fit_with_prior(train_data, prior_mean, prior_cov, niw_prior_m, niw_prior_n0, cov_reg, action_size, observation_size): """ @brief: pi = p_x.dot(x) + f_c, cov(f) = f_cov """ cov_reg_matrix = np.zeros([action_...
2a00bb1c386212f85c1cf2f14fbefdb1552fa377
54,639
import copy def get_action_dict_junc(observation_builder, obs): """ Takes an agent handle and returns next action for that agent following shortest path: - if agent status == READY_TO_DEPART => agent moves forward; - if agent status == ACTIVE => pick action using shortest_path.py() fun available in pr...
62fefab9f18c300989df8ba1fbf212592c0fe755
54,640
import re def scan(file, blocksize=10000): """Get the number of molecules in an sd file""" pat = re.compile("^[$][$][$][$]", re.MULTILINE) text = file.read(blocksize) count = 0 while text: g = pat.findall(text) count += len(g) if text[-1] == "$" and text[-4]!='$': ...
e3b1af1e65e28146d609a0c2841f195ad783b59e
54,641
from fontTools.ufoLib.filenames import userNameToFileName from robofab.tools.glyphNameSchemes import glyphNameToShortFileName def testGLIFFileName(rangeName, toFile=None): """ test on glif file name """ # support both UFO2 as UFO3 try: # UFO3 ufoLib def nameToFileName(name): ...
c2b6d83e4372baf3895b3647d07404686230418a
54,642
def Checksum(bbytes: bytes, length: int) -> bytes: """Checksum Create checksum of [length] bytes from the 256 bit hash of the byte slice. Returns the lower [length] bytes of the hash Errors if length > 32.""" hash = ComputeHash256Array(bbytes) return hash[len(hash)-length:]
c0993c3252a8794b7762068f27a44dbb3dbcb724
54,643
def peters_g(n, e): """ Compute g(n, e) from Peters and Mathews (1963) Eq.20 ### Parameters: n (`int/array`): Harmonic(s) of interest e (`float/array`): Eccentricity ### Returns: g (`array`): Relative power of gravitational radiation at the nth harmonic """...
f13d2b8222d74a0e3e45a264e84149bd0f37a460
54,644
def normalized_sat_value_difference_index(Blue, Green, Red): """transform red, green, blue arrays to normalized sat-value difference Parameters ---------- Blue : np.array, size=(m,n) blue band of satellite image Green : np.array, size=(m,n) green band of satellite image Red : np...
41ba01231db8252b77defaae62698c042b461a98
54,645
def make_game(environment_data, level): """Initialises the game. Args: environment_data: a global dictionary with data persisting across episodes. level: which game level to play. Returns: A game engine. """ sprites = {SUSHI_CHR: [SushiSprite], AGENT_CHR: [AgentSprite]} upda...
57d1ddaba3ebe4b083506f3bba03dcdaced256de
54,646
import pickle def filter_by_freq(word_list, chained_words, min_freq): """ Replaces words occuring less than min_freq with the unknown tag <unk> and dumps the replaced words to a file (via pickle) """ unk_list = [] print("Filtering words occuring less than %d times..." % min_freq) for word in w...
76186e9cb0dcc494575bc00c6994601e4a891483
54,647
def score_tile( tile_cij, clr, expected_indexed, expected_value_col, clr_weight_name, kernels, max_nans_tolerated, band_to_cover, ): """ The main working function that given a tile of a heatmap, applies kernels to perform convolution to calculate locally-adjusted expected and...
4597a4a929d610c9316b5e40a80696ed46e94c61
54,648
def display_time(seconds, granularity=1): """ Turns seconds into weeks, days, hours, minutes and seconds. Granularity determines how many time units should be returned. EG: # 2 time unites, week and day 1934815, 2 = '3 weeks, 1 day' # 4 time units 1934815, 4 = '3 weeks, 1 day, 9 hours, 26 minute...
d4b94ffafcdbda99526ecc906ed8379d7fc5edab
54,649
import torch def euler2mat(angle): """Convert euler angles to rotation matrix. Reference: https://github.com/pulkitag/pycaffe-utils/blob/master/rot_utils.py#L174 Args: angle: rotation angle along 3 axis (in radians) -- size = [B, 3] Returns: Rotation matrix corresponding to the euler a...
4b503e13948b68c8961796c4aa8cee687740e3b3
54,650
from typing import List from typing import Optional from typing import Any def execute_cli_command(args: List[str], input_data: Optional[str] = None, ret_val: int = 0, output_string: bool = True) -> Any: """Execute a Nessie CLI command.""" if output_string: return _run(args, input_data, ret_val).outpu...
054a3fc9f2b9d1de33b347c94a4ac4b7bd62900f
54,651
def transformer_latent_decoder(x, encoder_output, ed_attention_bias, hparams, name=None): """Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch,...
51e82f5ceea3c6a3a1e473208936f1fdb5f63303
54,653
def errorbar(*args, **kwargs): """ Plot curves with error bars Example:: import numpy as np x = np.linspace(-5, 5, 1000) errorbar(x, -1+x**2/20+.2*np.random.rand(len(x)), x/20) show() """ axe = gca() curve = make.merror(*args, **kwargs) axe.add_p...
09130681d4c205008083b101d152664131ee83ed
54,654
def privkey_to_wif(privkey, netcode="BTC"): """ Get private key from bitcoin wif. Args: privkey (str): Hex encoded private key Return: str: Private key encode in bitcoin wif format. """ prefix = networks.wif_prefix_for_netcode(netcode) secret_exponent = encoding.from_bytes_32(h...
055125ac7e76341366ad5c9ea5289f44427260fd
54,655
def join_values(values): """Return the values as a space-delimited string.""" return " ".join((str(v) for v in values))
60fd4acbafc4619c134ae67d224df408cad12ab0
54,656
def get_cookie_opener( gs_username, gs_token, gs_toolname=None ): """ Create a GenomeSpace cookie opener """ cj = http_cookiejar.CookieJar() for cookie_name, cookie_value in [ ( 'gs-token', gs_token ), ( 'gs-username', gs_username ) ]: # create a super-cookie, valid for all domains cookie = ...
7e9fd52ebccd8fc5065673f727d2cff720f53246
54,657
def translate(im,trans): """translates 3d images""" shape_ = im.shape zmax=shape_[0] xmax=shape_[1] ymax=shape_[2] zmin,xmin,ymin=0,0,0 trans_=np.array(np.round(trans),dtype=int) zmin-=trans_[0] zmax-=trans_[0] xmin-=trans_[1] xmax-=trans_[1] ymin-=trans_[2] ymax-=tra...
b2f438b20ff2d7cca65e7dd410c5826790f7224d
54,658
def add_base32_padding(base32_input_no_padding): """Return a base32 string with the correct padding Parameters: base32_input_no_padding (str): base32 string without padding """ result = base32_input_no_padding while ((len(result) % 8) != 0): result += '=' return result
9f98d4c705b5932171954aee3fb90c34681ea7fc
54,659
import torch def compute_similarities(audio_embeds, query_embeds, audio_lens): """ Compute a batch of audio-text alignment matrices. :param audio_embeds: tensor, (N, T, E). :param query_embeds: tensor, (N, Q, E). :param audio_lens: numpy 1D-array, (N,). :return: tensor, (N, T, Q). """ ...
52d8180a99426408c767f50c78acade3f217a74d
54,660
from re import T def T_inv(e, d, b): """Inverse transform b.""" return T(rotate_right(e, d+1), N-d-2, b)
64da217aac3e63a29aa56b089fedd937c47fc6ca
54,662
def magic(num_lst, n, k): """对 num_lst 使用 k 次魔力""" a = num_lst[:] for j in range(k): b = a[1:] # 又一种“移动”方法 b.append(a[0]) for i in range(n): a[i] = (a[i] + b[i]) % 100 # 无差别对 100 取余 return a
1f8e1e766add89e0f03a6ef778fe6c1100886125
54,663
import asyncio import aiohttp async def test_timeout(aresponses): """Test request timeout from AdGuard Home.""" # Faking a timeout by sleeping async def response_handler(_): """Response handler for this test.""" await asyncio.sleep(2) return aresponses.Response(body="Goodmorning!")...
5e1ddf44797bd23badb180a2fc99897286cfad1d
54,664
def format_number(number): """ Round number to two decimals :param number: input number :return: number rounded to two decimals """ return format(float(number), '.2f')
621e48e46aef43c6ede38b62a3608b8e193d7df7
54,665
def apply_sort(query, sort_spec): """Apply sorting to a :class:`sqlalchemy.orm.Query` instance. :param sort_spec: A list of dictionaries, where each one of them includes the necesary information to order the elements of the query. Example:: sort_spec = [ {'...
26ae50a733b41b78dfe1ddf77ac0f0957ffa38bc
54,666
def _find(searchable_models, tupls): """ # start with the output of the _dice doctest >>> p = [('a', 'b', 'c'), ('a', 'b'), ('b', 'c'), ('a',), ('b',), ('c',)] >>> class MockModel_A(object): ... ... def __repr__(self): ... return "<MM:A>" ... ... @classmethod ......
75b58b4377abe5f42e9611f44140a9034d930d0e
54,667
def tags_index(): """Show a page with info on all tags""" tags = Tag.query.all() return render_template('tags/index.html', tags=tags)
9ee801d9ad80bf4b72825791a6e985536399de04
54,668
def build_estimator(model_dir, model_type): """Build an estimator.""" if model_type == "wide": m = tf.estimator.LinearClassifier( model_dir=model_dir, feature_columns=feature_columns) elif model_type == "deep": m = tf.estimator.DNNClassifier( model_dir=model_dir, feature_columns=fe...
807d092211d7c4a112a4cdfe31b3db853a347f07
54,669
def double_variants(word): """get variants for the variants for a word""" return set(s for w in variants(word) for s in variants(w))
a9cfd85508b2d3f035ae918411725e94faa57860
54,670
def callBigDlFunc(bigdl_type, name, *args): """ Call API in PythonBigDL """ jinstance = JavaCreator.instance(bigdl_type=bigdl_type).value sc = get_spark_context() api = getattr(jinstance, name) return callJavaFunc(sc, api, *args)
0a3ce4b3045f932b6c3452b948c7216d55fe8f26
54,672
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
ee760d69ea9489525f7ad9313bf0f49e92e748f7
54,673
def format_indentation(string): """ Replace indentation (4 spaces) with '\t' Args: string: A string. Returns: string: A string. """ return string.replace(" ", "&nbsp;&nbsp;&nbsp;&nbsp;")
501f8b3a11f03fef295df771d76ac3a63f8209f3
54,674
from typing import Optional def get_sync_group(database_name: Optional[str] = None, resource_group_name: Optional[str] = None, server_name: Optional[str] = None, sync_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = No...
84e7adb466efd34377542361cf0e5bfde7b4320e
54,676
def kneel_down(score_diff, timd, secs_left, dwn): """Return 1 if the offense can definitely kneel out the game, else return 0.""" if score_diff <= 0 or dwn == 4: return 0 if timd == 0 and secs_left <= 120 and dwn == 1: return 1 if timd == 1 and secs_left <= 87 and dwn == 1: ...
2865d32484015f0e4a8f1cd28d68ec1a57847ce4
54,677
from typing import Union from typing import TextIO from typing import Collection from pathlib import Path import logging def create_wrappers_for_header_file(path: Union[str, PathLike[str]], out_dir: str, include_dir: Union[str, PathLike[str]], ...
7610e71cba6bac96ea04123a43c904ed02220715
54,678
def get_top_ngrams(vectorizer, top_n=5): """ Get highest ranking ngrams of a feature matrix :param vectorizer: vectorizer object :param top_n: amount of top n-grams to return :return: top n-grams """ indices = np.argsort(vectorizer.idf_)[::-1] features = vectorizer.get_feature_names() ...
2b391b7aba863ad576e445731d9ca8be4fd0c203
54,679
def variational_kmeans(mesh, vector_field, n_clusters, iters, tol): """ An instance of VariationalKMeans. """ return VariationalKMeans(mesh, vector_field, n_clusters, iters, tol)
8562c39ee35c24514c5526d900df16dd64bd7db5
54,680
def get_contours(image): """ For input image use `cv2.findContours` function to get a list of contour objects. Args: image (numpy.ndarray): Input image. Returns: list of contour objects: List of contour objects extracted from the image. """ # NOQA E501 #...
afa929c6ca9c9c0ab52d18617c7e4d5d1b0552b5
54,685
def encode(n, b=58): """ :param n: 压缩的数字 :param b: 进制 最大58 :return: 对应进制字符串 """ result = '' x = int(n) while True: x, y = divmod(x, b) result = baseList[y] + result if x <= 0: break return result
9f2af45ef63297ed6774c75d382fe1984edf6f84
54,686
import math def quantity_string(quantity, unit, computer_prefix=False): """Return a human-friendly string representing a quantity by adding prefixes and keeping the number of significant figures low. 'computer_prefix' determines whether each prefix step represents 1024 or 1000. Examples: >>> ...
04aa8743e045c2aaf80115984c30f091d695de77
54,689
def populate_context(dbot_scores: list, domain_entries: list, file_entries: list, url_entries: list, email_entries: list = None) -> dict: """ Populate the context object with entries as tuples - the first element contains global objects and the second contains PhishLabs objects :par...
3c72887e7d508a5e449b74da096165ed7d0229c3
54,692
import pytz def round_datetime(dt, period, tzinfo=pytz.UTC, force=False): """ Rounds a datetime to the nearest period. Valid periods are: minute, minute-15, hour, day, week :type dt: datetime :param dt: A naive or aware datetime object. :type period: str :param period: Options are mi...
ec856a37d7e9bb7c4077e753327287ac3048b9b0
54,693
def force_categorical_determination(table): """ Find string columns using 'computationally expensive' approach """ source_shape = table.shape columns_number = source_shape[1] if len(source_shape) > 1 else 1 categorical_ids = [] non_categorical_ids = [] # For every column in table make check for...
012fb261c39e2bd5106df4e88af9703821158146
54,694
def _apply_words(nums): """ Get the corresponding words for a list of 11-bit numbers. Args: nums (int[]): list of 11-bit numbers Returns: str[]: list of words """ return [index_to_word[n] for n in nums]
626fab36ea86b7b22e17b6d924dfa72f4437dbb7
54,695
def FCN_32s(input_shape, n_class, encoder_name, encoder_weights=None, fc_num=4096, weight_decay=1e-4, kernel_initializer="he_normal", bn_epsilon=1e-3, bn_momentum=0.99, dropout=0.5): """ implementation of FCN...
4baac4a8472a7cddb938fa0f69fa5f9f68863999
54,696
import numpy def L2d1(x): """ First derivative of the quadratic lagrange basis function. :param x: points to interpolate :type x: numpy array (npoints) :return: basis weights :rtype: numpy array(npoints, 3) """ L1 = 1-x return numpy.array([ 1.0 - 4.0 * L1, 4.0 ...
d74adfa7c22d9686a1428f21777f1d3bc3cda4d7
54,698
def vector_to_dictionary(vector, layers): """ Convert the parameter vector of a model into a dictionary used by the model Arguments: vector -- one-dimensional vector in orders: "W1", "W2", "WL", "b1", "b2", "bL" layers -- list of (n_uints, activations) pairs that define network structure,...
33f628463546892ae8127cad25bda1e7ae19a78a
54,700
def compute_vanderwaals(traj_frag_molid, frame_idx, index_to_label, sele_id, VDW_EPSILON, VDW_RES_DIFF): """ Compute all vanderwaals interactions in a frame of simulation Parameters ---------- traj_frag_molid: int Identifier to simulation fragment in VMD frame_idx: int Frame num...
05749204946124e87f8413d2bd1845c93cb568b8
54,702
def load_text(filepath): """Loads text from a file and returns it as a string. Args: filepath (str): The path to the file to be loaded. Returns: text (str): The text loaded from the file. Examples -------- >>> load_text('text.txt') """ with open(filepath, encoding='utf...
66a925216a33f8b9e7abab4b7ada6ad2716cefd6
54,703
def f_call_one_optional_kwd(a, /, *, b=2): """ >>> f_call_one_optional_kwd(1) (1, 2) >>> f_call_one_optional_kwd(1, b=3) (1, 3) """ return (a,b)
4bcbc58d90f093775c4f52dcdfce0d0deb5d6686
54,704
import requests import json def send_post_request(url, data: dict = None, **kwargs) -> dict: """ 发起post请求 :param url: 请求目标地址 :param data: 请求参数 :param kwargs: :return: """ try: resp_dict = requests.post(url, data=json.dumps(data), **kwargs).json() except Exception as e: ...
95de52e6005e7f00078a6e682512450a0367ee70
54,705
def _data_type_filter(x, y): """Filter data types into acceptable format.""" if HAS_DASK: x = extract_dask_data(x) if y is not None: y = extract_dask_labels(y) if HAS_PANDAS: x = extract_pandas_data(x) if y is not None: y = extract_pandas_labels(y) return x, y
de9bf7141d82655a4c202d8baed80cecb1ac94aa
54,706
def area(int_pts, num_of_inter): """area""" area_val = 0.0 for i in range(num_of_inter - 2): area_val += abs(trangle_area(int_pts[:2], int_pts[2 * i + 2:2 * i + 4], int_pts[2 * i + 4:2 * i + 6])) return area_val
78519de4802bbd76c376af1e2bec71ed106eca34
54,707
def unique(it): """Return a list of unique elements in the iterable, preserving the order. Usage:: >>> unique([None, "spam", 2, "spam", "A", "spam", "spam", "eggs", "spam"]) [None, 'spam', 2, 'A', 'eggs'] """ seen = set() ret = [] for elm in it: if elm not in seen: ...
8e182467eb8179c2b9168470f8b683710ad37b56
54,708
def _quaternionAdd(quat0, quat1): """ Multiplies 2 lists of quaternions """ # Find the maximum indices to use for clipping purposes max0, max1 = quat0.shape[0]-1, quat1.shape[0]-1 maxsize = max(max0, max1) + 1 quat = np.empty((maxsize,4)) for ii in range(maxsize): index0 = min(ii, ...
f3124f38955d728efbe8e9b467a7164e8024b888
54,709
from numpy import where def image_numbers(logfile,name="",repeat_count=[]): """Select a subset of a dataset based on critria, such a file name and repeat counts logfile: table object, must have attributes "file",Temperature","Delay" name: part of the image filname, e.g. "_offWT" repeat_count: e.g. [["...
e4ed486792eab4091016599ec09cf3a219df14b2
54,710
import scipy def optimize_epsilon(data_train, labels_train, data_test, labels_test, num_markers, method='centers', fixed_parameters={}, bounds=[(0.2 , 10)], x0=[1], max_fun_evaluations=20, n_experiments=5, clf=None, hierarchy=False, verbose=True): """ Finds the optimal value of epsilon using scipy.optimize.du...
d8089bf5059bbcb3b1650ea3adcf24a39365c3e4
54,712
def census_vip_call(*, resp, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param resp: df, response from url call :return: pandas dataframe of original source data """ # Convert response to dataframe df = pd.read_excel(resp.content, ...
c7e63b569b317cc9bdae2eb6064fea437ac03f49
54,713
def model_field_slugify( model_class, instance, string, filter_keys=None, exclude_keys=None, slug_field='slug'): """Slugify string based on another string and saves slug in model""" if str(string).lower() in reserved_slugs: raise ReservedSlugException('Es...
1520deee2a8ba5b2cb78372c5f00ab63306f0e0c
54,714
def create_read_fmt(read_id: str) -> str: """create a bitstruct format for any given read it up to 512 bits""" if len(read_id) > 64: raise ValueError("Read ID is too large") padding = 512 - len(read_id)*8 r_fmt = "t{0}p{1}".format(len(read_id)*8, padding) return r_fmt + ("u3" * 150) + ("u6" ...
f7319ffc62b55859ed8af3e6b7e044d9481f7384
54,715
from typing import Optional import tempfile from pathlib import Path def get_job_log_file(run: Run, index: Optional[int] = None) -> str: """ Reads the job log file (70_driver_log.txt or std_log.txt) of the given job. If an index is provided, get the matching file from a multi-node job. :return: The co...
5675a9e08a499cd99c765e1e76009c0ad3cbdc55
54,718
import warnings from typing import cast def _is_compatible(program: Loop, min_len: int, quantum: int, sample_rate: TimeType) -> _CompatibilityLevel: """ check whether program loop is compatible with awg requirements possible reasons for incompatibility: program shorter than minimum length ...
38cc5f639b54bbfc5602d4f5e3c25909a9a06014
54,719
def get_data_for_tpu(tpu_name, economic_dataframe, marry_dataframe, edu_dataframe, population_dataframe): """ :param tpu_name: the name of the tpu :param economic_dataframe: the dataframe contains median income and employment rate :param marry_dataframe: the dataframe which saves the marrital status ...
fe71fd15fab28684f848b80e68746fe1e3a73f51
54,720
def gridaspoints(*arrs): """Creates an N-dimensional grid form arrs and returns grid points sequence of point coordinate pairs """ # there is a small gotcha here. # with the convention following the 2013-08-30 sprint in Potsdam it was # agreed upon that arrays should have shapes (...,z,y,x) simi...
ba907705965bf9f432d127126c784eb5b1c84873
54,721
def download_powermeter_csv(agent): """ Method to download a CSV list of mains sensor readings for all configured power meters and panels **parameters** :param agent: An agent instance from the device where the pmc data should be downloaded :return: returns the pmc data in csv format **Exampl...
d1c2b10ca89de98fd029388882e91b2264c0d235
54,722
def get_learner(case, *args, **kwargs): """Generator function for test""" data = Data(*args, is_learner=True, **kwargs) p = getattr(data.indexer, 'partitions', 1) X, y = data.get_data((12, 4), 2) (F, wf), (H, wh) = data.ground_truth(X, y, p) data.indexer.fit(X) learner, transformer = Estima...
104317d0a5e7daf0272178b54595c33068fb844c
54,723
def cleaned(cls): """Call individual cleaning methods and collect all of their ValidationErrors Purpose: This decorator allows you to write individual methods that do some validation or cleaning without having to worry about collecting all of their ValidationErrors together into a list ...
d502bfb2070d6a5578a5d7bb502383513f816ee0
54,726
def check_framescene(scene, frame, cameras, quality, check_green_frames, check_empty_frame, min_nbr_people): """ Checks a frame for all cameras in one scene. Returns True if all frame is good. Returns False if any frame was bad. """ for camera in cameras: bad, ids = ...
05843c8b022fae658076232be709d295dd42cd84
54,728
def _get_consecutive_and_overlapping_fronts(onset_fronts, offset_fronts, onset_front_id, offset_front_id): """ Gets an onset_front and an offset_front such that they both occupy at least some of the same frequency channels, then returns the portion of each that overlaps with the other. """ # Get the...
14314dc10d896807a3d10ef57a1a4abaab28de5c
54,729
import statistics def time_formatted(event:str, mode:str, t: float, dnf: bool=False) -> str: """ Reverses parse_time """ if t == statistics.DNF: return "DNF" if dnf else "" if event in ["3x3x3 Fewest Moves", "3x3x3 Multi-Blind"]: if event == "3x3x3 Fewest Moves" and mode == "average": ...
fb39e88e3e790b2338288cc31f4e6b0c7e9b299c
54,731
from re import T import numpy def tsum(x: T.Tensor, axis: int=None, keepdims: bool=False) -> T.FloatingPoint: """ Return the sum of the elements of a tensor along the specified axis. Args: x: A float or tensor. axis (optional): The axis for taking the sum. keepdims (optional): If ...
a8004051ed0258396366e075bd5b4f3cdebcdd5d
54,732
def ask_multi_choices(prompt="Add to choices : ", choices_list=[], to_save="s", to_quit="q"): """Collect multi choices from list Keyword Arguments: prompt {str} -- the question method (default: {"Add to choices : "}) choices_list {list} -- the available options (default: {[]}) to_sa...
0ece08fd561b770445af1e9a778f3dbaf0c1ba6a
54,733
def DtypeToType(dtype): """Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.""" if dtype.char in np.typecodes['AllFloat']: return GetFeatureStatsProtoDef().FLOAT elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or np.issubdtype(dtype, np.datetime64) or np.i...
b448192a2bd50cf1b45a29c3f29e1be53c4cab08
54,734
def register_prelu_func(graph): """Register Prelu op with function def, this is need for importing graph_def with unregistered Prelu op. Args: graph: A tf.Graph object to insert prelu function into. """ # Create a function for Prelu op @function.Defun(tf.float32, tf.float32, func_name='Prelu') def pr...
6884288e62489e8e27f1b9bf7aac911c13f005c4
54,735
def _parseSteps(raw_steps, lang=None): """ :type raw_steps: Iterable[dict] :param lang: (Optional) Descriptor of the language to query the step, without any specification of encoding or modifiers. :type lang: str | None :rtype: Iterable[TutorialStep] """ def getI18nStringForStepKey(...
7a9b2cc7cf3c805d38db6c1ae21ea20062ba7ca4
54,736
def legendre_P(n,x): """ Returns the Legendre polynomial of the first kind for integers `n > -1`. REFERENCE: - AS 22.5.35 page 779. EXAMPLES:: sage: P.<t> = QQ[] sage: legendre_P(2,t) 3/2*t^2 - 1/2 sage: legendre_P(3, 1.1) 1.67750000000000 sage...
45b60b0ad5874a3bf54e83cad6037e72e8f363fd
54,737