content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def countries_reaction(t, react_time, top_countries): """ Computes how long a country takes to react once the deceased limit is exceeded. Parameters ---------- t : int Simulation instant. react_time : int Parameter of the exponential distribution. top_countries : list ...
b75402686250de48f5bafd8f0f4c5ca6a1251708
3,629,875
import struct import numpy as np def binaryread_struct(file, vartype, shape=(1), charlen=16): """ Read text, a scalar value, or an array of values from a binary file. file is an open file object vartype is the return variable type: str, numpy.int32, numpy.float32, or numpy.float64 ...
c9e718e929598560206f2ee73a2b92f9347be5d6
3,629,876
def flatten_and_structure_dimensions(op, parameters, number_of_dimensions=None): """ Unrolls nested lists into one flat lists, applies the operation and rolls the resulting flat list back into nested lists. ---------- op : Operation to apply to the tuple of flat lists, resulting in one flat list. parame...
0e52c8f19204a064bf73b15276fde8820263135f
3,629,877
from typing import Any def create_result_scalar(name: str, item_type: str, value: Any) -> dict: """ Create a scalar result for posting to EMPAIA App API. :param name: Name of the result :param item_type: Type of result :param value: Value of the result """ result = {"name": name, "type": ...
3fb16c540cc8c76cfc42e4a906e4be280346b802
3,629,878
def create_edge(source_id, target_id, relationship_type, vitrage_is_deleted=False, update_timestamp=None, metadata=None): """A builder to create an edge :param update_timestamp: :param source_id: :type source_id: str :p...
e6a367ec0d05fbbe92a1f763d3039c2e02bf8b9d
3,629,879
def hg_ui_with_checkers(hg_ui, checkers): """Get test mercurial ui with checkers config set up.""" for key, value in checkers.items(): hg_ui.setconfig('hg_commit_sanity', key, value) hg_commit_sanity.reposetup(hg_ui, hg_repo) return hg_ui
c818ac9b77505cc6bee54a06db4b8b1556a96ba7
3,629,880
def get_inbox_status(): """Return current inbox status""" emails = get_inbox_emails(EMAIL) new = get_new_emails(emails) (direct, cced) = get_direct_emails(emails, MY_EMAILS) nb_total = len(emails) nb_direct = len(direct) nb_cced = len(cced) nb_total_new = get_nb_new(new) nb_direct...
444772b165b9cd9d868e7599b6eea5d71226ea52
3,629,881
def fill_correlation_matrix(c_vec): """ Create a Theano tensor object representing a correlation matrix of a multivariate normal distribution. :param c_vec: PyMC3 model variable corresponding to the `LKJCorr` prior on elements of the correlation matrix :return: correlation matrix...
e32037b7ce573c1a9faefab5b57f771ea7cd90a2
3,629,882
def find_isomorphism(G1, G2): """Search for isomorphism between two graphs Args: G1 (networkx.Graph) G2 (networkx.Graph) Returns: If no isomorphism is found, returns None. Otherwise, returns dict with keys as nodes from graph 1 and values as corresponding nodes fro...
b1688167e805f454150284ba557bd731aef37500
3,629,883
def list_bancos(request): """ Lista Bancos""" usuario = request.user dados = {} try: funcionario = Funcionario.objects.get(usuario_fun=usuario) except Exception: raise Http404() if funcionario: #id pesquisa termo_pesquisa = request.GET.get('pesquisa', None) ...
2a56d07314d08cae1516a9db8514688a5b5b413f
3,629,884
def encode_jwt_token(data, api_secret_code=None): """ Encode Python dictionary as JWT token. :param data: Dictionary with payload. :param api_secret_code: optional string, application secret key is used by default. :return: JWT token string with encoded and signed data. """ if api_secret_cod...
a934b94687c7767bff9e5f8403f14c1ca9dae5ae
3,629,885
from typing import Union from typing import Sequence from typing import Hashable from typing import Callable from typing import Iterable import PIL def handwrite( text: str, template: Union[Template, Sequence[Template]], seed: Hashable = None, mapper: Callable[[Callable, Iterable], Ite...
27552d307f964f274e4c6080f183c3e99be0c3c0
3,629,887
def printMathExp(btree: BinaryTree) -> str: """Print the whole math expression""" s = '' if btree is not None: if btree.left is not None: s += '(' s += printMathExp(btree.left) s += str(btree.key) s += printMathExp(btree.right) if btree.right is not None: ...
e7499d99ec55785f1a2e8744b90ddd3f1d0acdf5
3,629,888
import logging def create_presigned_url(bucket_name, bucket_key, expiration=3600, signature_version=s3_signature['v4']): """Generate a presigned URL for the S3 object :param bucket_name: string :param bucket_key: string :param expiration: Time in seconds for the presigned URL to remain valid :para...
2d3198cd7db5f09ab08a8a1e0abcaa1d85adf288
3,629,890
def softmax_op(node, ctx=None): """ This function computes its softmax along an axis. Parameters: ---- node : Node Input variable. Returns: ---- A new Node instance created by Op. """ return SoftmaxOp(node, ctx=ctx)
5cca012944bb41364cc41b3311d9b6a9ce386d55
3,629,892
def circle_fit(coords): """ Find the least squares circle fitting a set of 2D points ``(x,y)``. Parameters ---------- coords : (N, 2) ndarray Set of ``x`` and ``y`` coordinates. Returns ------- centre_i : (2,) The 2D coordinates of the centre of the circle. r_i : do...
cac5275b1b3d59040c0acc94c12e492d78dfd647
3,629,893
def LayerSet_toLayers(ifc_file): """ Returns a dictionary where keys are the Id of the IfcMaterialLayerSet and where the values are a list (ListOfLayers) with an element per material layer. The material layer information is stored at the same time within a list containing Id (number), material and t...
eaac63c2ee264e32dcf885036671a97bdffd50ba
3,629,895
def conv2d_annotate_fn(expr): # pylint: disable=unused-variable """Check if nn.conv2d is supported by TensorRT.""" attrs, args = expr.attrs, expr.args if not is_supported_trt_dtype(args): return False if not isinstance(args[1], Constant): logger.info("nn.conv2d: kernel argument must be...
b5567d4369e9f9eeaabbacb34e9b6ae7554a4d41
3,629,896
from google.cloud import bigquery from typing import List from datetime import datetime def create_bq_view_of_joined_features_and_entities( source: BigQuerySource, entity_source: BigQuerySource, entity_names: List[str] ) -> BigQuerySource: """ Creates BQ view that joins tables from `source` and `entity_so...
358d8f3b6d3ba98ed1b431c6c201ffdc7d3e30da
3,629,897
import sqlite3 def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again. """ if "db" not in g: g.db = sqlite3.connect( current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLT...
95bcd9e7338b402c040307e02d5dbbe4893453f8
3,629,898
import functools def _map_windows( df, time, method="between", periodvar="Shift Date", byvars=["PERMNO", "Date"] ): """ Returns the dataframe with an additional column __map_window__ containing the index of the window in which the observation resides. For example, if the windows are [[1],[2,3]], a...
31b4780ba7f67dde12dcc75af9abbcf88a1b269a
3,629,900
def unpack_context(msg): """Unpack context from msg.""" context_dict = {} for key in list(msg.keys()): key = str(key) if key.startswith('_context_'): value = msg.pop(key) context_dict[key[9:]] = value context_dict['msg_id'] = msg.pop('_msg_id', None) context_d...
03c42f2e137e219dd15591588d28cf3be897e2fa
3,629,901
def concat_cols(*args): """ takes some col vectors and aggregetes them to a matrix """ col_list = [] for a in args: if isinstance(a, list): # convenience: interpret a list as a column Matrix: a = sp.Matrix(a) if not a.is_Matrix: # convenience: al...
ca0731bdd35909ec544e76b80dce73ef96863a7a
3,629,902
def gen_connected_locations(shape, count, separation, margin=0): """ Generates `count` number of positions within `shape` that are touching. If a `margin` is given, positions will be inside this margin. Margin may be tuple-valued. """ margin = validate_tuple(margin, len(shape)) center_pos = margin ...
9432d4df6e6b1bc5ff2fe762e240f051c07ae81e
3,629,904
import warnings def transp(): """ Instantiates the Transp() class, and shows the widget. Runs only in Jupyter notebook or JupyterLab. Requires bqplot. """ warnings.simplefilter(action='ignore', category=FutureWarning) return Transp().widget
f8f86eab3e428ebdee2be5a2fc83fe3bd3d61702
3,629,905
def oidc_supported(transfer_hop: DirectTransferDefinition) -> bool: """ checking OIDC AuthN/Z support per destination and source RSEs; for oidc_support to be activated, all sources and the destination must explicitly support it """ # assumes use of boolean 'oidc_support' RSE attribute if not tr...
5bb49689b75e1329e2dda5a813ecbd11a346541e
3,629,906
import sympy def replace_heaviside(formula): """Set Heaviside(0) = 0 Differentiating sympy Min and Max is giving Heaviside: Heaviside(x) = 0 if x < 0 and 1 if x > 0, but Heaviside(0) needs to be defined by user. We set Heaviside(0) to 0 because in general there is no sensitivity. This done ...
d1aff5e4a2dd68ba53ced487b665e485dab4b54d
3,629,908
import click import time def check_enrolled_factors(ctx, users): """Check for users that have no MFA factors enrolled""" users_without_mfa = [] msg = ( f"Checking enrolled MFA factors for {len(users)} users. This may take a while to avoid exceeding API " f"rate limits" ) LOGGER.i...
6ab747684d4b39622149b2ead072b1fd1ac2fc6a
3,629,909
def entry_cmp(sqlite_file1, sqlite_file2): """ Compare two sqlite file entries in zookeeper to know the ordering """ seq_id1 = _get_journal_seqid(sqlite_file1) seq_id2 = _get_journal_seqid(sqlite_file2) return sequence_cmp(seq_id1, seq_id2)
d6ff9ee5e3aad62c096ed17106fb56d10b9d7de8
3,629,910
import functools def fill_cn(bcm, n_metal2, max_search=50, low_first=True, return_n=None, verbose=False): """ NOTE: Most likely broken - still need to extend to polymetallic cases Algorithm to fill the lowest (or highest) coordination sites with 'metal2' Args: bcm (atomgraph.AtomGrap...
8b4ac05e0abbadc34f154e4917959627600dcf0d
3,629,911
import functools def _clear_caches_after_call(func): """ Clear caches just before returning a value. """ @functools.wraps(func) def wrapper(*args, **kwds): result = func(*args, **kwds) _clear_caches() return result return wrapper
cdc0342230d09d86021aafb23e4ae883dd30fee0
3,629,912
import random import _bisect def choices(population, weights=None, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ n = len(populatio...
1161b6c43fb54b32e54bf3c45d81abfa1c7261d8
3,629,914
def summarize(text: str) -> str: """Summarizes the text (local mode). :param text: The text to summarize. :type text: str :return: The summarized text. :rtype: str """ if _summarizer is None: load_summarizer() assert _summarizer is not None tokenizer = get_summarizer_tok...
cc3fbee1ef27332733915d27758cdcaf045cd2c8
3,629,915
def linreg(array, dim=None, coord=None): """ Compute a linear regression using a least-square method Parameters ---------- x : xarray.DataArray The array on which the linear regression is computed dim : str, optional The dimension along which the data will be fitted. If not precised, the first dimension wi...
27ff54eccf92b3e1924316d022aeaac5abdb0bb3
3,629,916
import pkg_resources def _gte(version): """ Return ``True`` if ``pymongo.version`` is greater than or equal to `version`. :param str version: Version string """ return (pkg_resources.parse_version(pymongo.version) >= pkg_resources.parse_version(version))
f92d062d2d2ff37184bd7bd5740c8c586bf3e521
3,629,917
def read_data(path, format="turtle"): """ Read an RDFLib graph from the given path Arguments: path (str): path to a graph file Keyword Arguments: format (str): RDFLib format string (default="turtle") Returns: rdflib.Graph: a parsed rdflib.Graph """ g = rdflib.Grap...
31965e0ccc43d873ce06e248ab9e771227b54aba
3,629,918
def exact_change_recursive(amount,coins): """ Return the number of different ways a change of 'amount' can be given using denominations given in the list of 'coins' >>> exact_change_recursive(10,[50,20,10,5,2,1]) 11 >>> exact_change_recursive(100,[100,50,20,10,5,2,1]) 4563 ...
f18cd10802ba8e384315d43814fcb1dcd6472d78
3,629,919
from numpy import diff, where, array def detectGap(date, gapThres): """ Detects gap in a date vector based on the user defined threshold. Parameters ---------- date: list Dates in UTCDateTime format to detect gaps within. gapThres: float Threshold in seconds over which to ...
5cdbeb42d4110469b1a619118e014a0984bdc6c6
3,629,920
def enum(*sequential, **named): """ Enum implementation that supports automatic generation and also supports converting the values of the enum back to names >>> nums = enum('ZERO', 'ONE', THREE='three') >>> nums.ZERO # 0 >>> nums.reverse_mapping['three'] # 'THREE' """ enums = di...
804801e5b94f0e559283deecdc808aea0446fb63
3,629,921
import warnings import warnings from dolo.algos.steady_state import find_steady_state from dolo.numeric.extern.lmmcp import lmmcp from dolo.numeric.optimize.newton import newton def deterministic_solve( model, exogenous=None, s0=None, m0=None, T=100, ignore_constraints=False, maxit=100, ...
d12b50a53e4c03cba4d1e1980c9b0eac41412311
3,629,922
def find_check_string_output( # type: ignore ctx, class_name, method_name, as_python=True, fuzzy_match=False, pbcopy=True ): """ Find output of `check_string()` in the test running class_name::method_name. E.g., for `TestResultBundle::test_from_config1` return the content of the file `./co...
33b8c0d8ebd7399ef63a870f88ddfdfca671b686
3,629,923
from re import T def index(): """ Dashboard """ if session.error: return dict() mode = session.s3.hrm.mode if mode is not None: redirect(URL(f="person")) # Load Models s3mgr.load("hrm_skill") tablename = "hrm_human_resource" table = db.hrm_human_resource if ADM...
a19e62b3c3541b05bb066b54f91b46e9a1566c91
3,629,924
def Vfun(X, deriv = 0, out = None, var = None): """ expected order : r1, r2, R, a1, a2, tau """ x = n2.dfun.X2adf(X, deriv, var) r1 = x[0] r2 = x[1] R = x[2] a1 = x[3] a2 = x[4] tau = x[5] # Define reference values Re = 1.45539378 # Angstroms re = 0.9625247...
4b8b666c60900355a8a215728ae53feb37dd8313
3,629,926
def all_events(number=-1, etag=None): """Iterate over public events. .. deprecated:: 1.2.0 Use :meth:`github3.github.GitHub.all_events` instead. :param int number: (optional), number of events to return. Default: -1 returns all available events :param str etag: (optional), ETag from a...
0b620e00ceffe93b7a6bdf579f031942222d3f10
3,629,927
def mock_datetime(monkeypatch: MonkeyPatch) -> FakeDatetime: """Mocks dt.datetime Returns: FakeDatetime(2021, 3, 20) """ fake_datetime = FakeDatetime(2021, 3, 20) fake_datetime.set_fake_now(dt.datetime(2021, 3, 20)) monkeypatch.setattr(dt, "datetime", FakeDatetime) return fake_dateti...
2b0bbc1b62f80636ea1622fcf4cfa6abfbda929b
3,629,928
def Normalize(v): """ Normalizes vectors so length of vector is 1. Parameters ---------- v : 2D numpy array, floats Returns ------- 2D numpy array, floats Normalized v. """ norm = np.zeros(v.shape[0]) for i, vector in enumerate(v): norm[i] = np.linalg.norm(v...
f68bf8bfd2999b8755c3ace00154377fa19fe04c
3,629,929
import requests def get_instance_details(instance_id): """ Returns json detail of specific instance on slate :return: json object of slate instance details """ query = {"token": slate_api_token, "detailed": "true"} instance_detail = requests.get( slate_api_endpoint + "/v1alpha3/instanc...
77476be1de353079fdbca2b041b49b604e59929b
3,629,930
def admin_lexers(request): """Form to configure lexers for file extensions.""" formset = AdminLexersFormSet.for_config() if request.method == 'POST': formset = AdminLexersFormSet.for_config(request.POST) if formset.is_valid(): formset.save() messages.success(request...
ef56353c0d25ebb4b5eb59dd1dad356a443b5a70
3,629,931
def ignore_module_import_frame(file_name, name, line_number, line): """ Ignores the frame, where the test file was imported. Parameters ---------- file_name : `str` The frame's respective file's name. name : `str` The frame's respective function's name. line_number : `in...
048283ec4a6aa0b1e51aadc033c0438ff125b102
3,629,932
def knapsack(val,wt,W,n): """ Consider W=5,n=4 wt = [5, 3, 4, 2] val = [60, 50, 70, 30] So, for any value we'll consider between maximum of taking wt[i] and not taking it at all. taking 0 to W in column 'line 1' taking wt in rows 'line 2' two cases -> * cur_wt<=total wt in that c...
d030a57e8c7040cbd1f7a3556f21d599ac049428
3,629,934
def CNN_model_basic(img_height, img_width,OPTIMIZER): """ This is a customized function for generating a Keras model built-in Keras module with pre-defined parameters and model architecture. Parameters ----------------- img_height,img_width = input image dimensions OPTIMIZER = keras o...
f1123f2dfd07915d91eb68895a35a67d8f65e99b
3,629,935
def get_filter_df(df, filter_col, targets, greater_than=True): """ Filter dataframe based on target column Returns dataframe """ if filter_col in ["transactions", "category"]: df_filter = get_filter_indicator_df(df, filter_col, targets) elif filter_col == "rating": if greater_th...
6e8ad5c9efe65142dcb8d8f842e0b81a2946251b
3,629,936
def filter_graph(graph, n_epochs): """ Filters graph, so that no entry is too low to yield at least one sample during optimization. :param graph: sparse matrix holding the high-dimensional similarities :param n_epochs: int Number of optimization epochs :return: """ graph = graph.copy() g...
04af2804e208b8ce582440b2d0306fe651a583b0
3,629,937
def create_file_with_maximum_util(folder_file): """ from a folder with multiple .xls-files, this function creates a file with maximum values for each traffic counter based on all .xls-files (ASFINAG format) :param folder_file: String :return: pandas.DataFrame """ # collect all .xls files as ...
67a41549d00f4230b24fe0c45a5b4184912fe3ff
3,629,938
def join_detectionlimit_to_value(df, **kwargs): """Put sign and numeric value together. For example: "<" + "100" = "<100").""" df['Value'] = np.where(df['Value_sign'].isnull(), df['Value_num'], df['Value_sign'] + df['Value_num'].astype(str)) return df
d8b83ff4412408379e3c37a94b5c8b98eb8e129e
3,629,939
def read_data(datapath, metadatapath, label_key='Schizophrenia'): """read_data :param datapath: path to data file (gene) :param metadatapath: path to meta data file of patients :output x: data of shape n_patient * n_features :output y: label of shape n_patients, label[i] == 1 means that the pat...
5c0d72f6d4f0ae75befe6bb760ee6a1034cc85a3
3,629,940
def show(tournament, match_id): """Retrieve a single match record for a tournament.""" return api.fetch_and_parse( "GET", "tournaments/%s/matches/%s" % (tournament, match_id))
ef168fd4c7ab06e0091bb9797ef953e1ec720a45
3,629,941
import json def get_Frequency(ids): """ Restituisce la frequenze presente sul DB con un ID specifico """ db = Database() db_session = db.session data = db_session.query(db.frequency).filter(db.frequency.id == ids).all() data_dumped = json.dumps(data, cls=AlchemyEncoder) db_session.c...
0f07c926626f0c5eb6fb6cdf14c81469fff6a108
3,629,942
import torch def ycbcr_to_rgb_jpeg(image): """ Converts YCbCr image to RGB JPEG Input: image(tensor): batch x height x width x 3 Outpput: result(tensor): batch x 3 x height x width """ matrix = np.array( [[1., 0., 1.402], [1, -0.344136, -0.714136], [1, 1.772, 0]], d...
3dcd8aaa32d7d558e8aa27a5f7f65ee85a105941
3,629,943
def get_global_step(hparams): """Returns the global optimization step.""" step = tf.to_float(tf.train.get_or_create_global_step()) multiplier = hparams.optimizer_multistep_accumulate_steps if not multiplier: return step return step / tf.to_float(multiplier)
82440d93ecae202ced3fbbc98e7d0033e9fc0af4
3,629,945
def rev_find(revs, attr, val): """Search from a list of TestedRev""" for i, rev in enumerate(revs): if getattr(rev, attr) == val: return i raise ValueError("Unable to find '{}' value '{}'".format(attr, val))
6b9488023d38df208013f51ed3311a28dd77d9b8
3,629,948
def untempering(p): """ see https://occasionallycogent.com/inverting_the_mersenne_temper/index.html >>> mt = MersenneTwister(0) >>> mt.tempering(42) 168040107 >>> untempering(168040107) 42 """ e = p ^ (p >> 18) e ^= (e << 15) & 0xEFC6_0000 e ^= (e << 7) & 0x0000_1680 e ^...
4118b55fd24008f9e96a74db937f6b41375484c3
3,629,949
def single_run(var='dt', val=1e-1, k=5, serial=True): """ A simple test program to do PFASST runs for the heat equation """ # initialize level parameters level_params = dict() level_params[var] = val # initialize sweeper parameters sweeper_params = dict() sweeper_params['collocatio...
eba87530288fd600aec0ea349794d2b123c33ba4
3,629,950
def tofloat(img): """ Convert a uint8 image to float image :param img: numpy image, uint8 :return: float image """ return img.astype(np.float) / 255
8e51259e478d30c8cfa01fb397ba022ca071c018
3,629,951
def get_session() -> requests_cache.CachedSession: """Convenience function that returns request-cache session singleton.""" if not hasattr(get_session, "session"): get_session.session = requests_cache.CachedSession( cache_name=str(CACHE_PATH), expire_after=518_400 # 6 days ) ...
d2b5f1be76c4a35adbede1a1bb280bf9ad43b06e
3,629,952
def parse_html(html): """ Take a string that contains HTML and turn it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored. """ parser = Parser() parser.fe...
923cec59495b9e5e80c00e8af532040ec49a95fe
3,629,953
from typing import List def get_atomic_num_one_hot(atom: RDKitAtom, allowable_set: List[int], include_unknown_set: bool = True) -> List[float]: """Get a one-hot feature about atomic number of the given atom. Parameters --------- atom: rdkit.Chem.rdchem.At...
e323aa738321970ff49f555a41dea66d5280c328
3,629,954
from datetime import datetime def ds_to_1Darr(varname,ds,srate='reg',dataw='notrend'): """ var is a string, varibale name from the ds # choose how much data wrangling to do : remove mean or remove mean and trend dataw = 'nomean' or 'notrend' # choose the sampling rate: raw/unchanged or regular 1...
4d5faa04a7c1a0bc0fdf29c3be0fe8a534953615
3,629,955
import inspect def fs_check(**arguments): """Abstracts common checks over your file system related functions. To reduce the boilerplate of expanding paths, checking for existence or ensuring non empty values. Checks are defined for each argument separately in a form of a set e.g @fs_check...
655e9eacc5557e1d71e301f9672ea8013450dca3
3,629,956
def old_pgp_edition(editions): """output footnote and source information in a format similar to old pgp metadata editor/editions.""" if editions: # label as translation if edition also supplies translation; # include url if any edition_list = [ "%s%s%s" % ( ...
633fd75c82d02893e82bebb1d1d8fe3ba1d19c72
3,629,957
def ConstructApiDef(api_name, api_version, is_default, base_pkg='googlecloudsdk.third_party.apis'): """Creates and returns the APIDef specified by the given arguments. Args: api_name: str, The API name (or the command surface name, if different). ...
b7b73e386d97d9195c64f6d3de9d642c0708fb9c
3,629,958
def L2struct_array(L,dtype={'names':('score','col','S_init','tree'),'formats':('f4','S10000','S10000','S10000')}): """ Convert list output from extract_elite to structured Numpy array. Contracts initial conditions string with tree string. Converts column string to int (after removing brackets). Inputs: L: li...
b53982b190ae392db4187073247ebe5a94c7a19f
3,629,959
def build_model(x_train_text, x_train_numeric, **kwargs): """Build TF model.""" max_features = 5000 sequence_length = 100 encoder = preprocessing.TextVectorization(max_tokens=max_features, output_sequence_length=sequence_length) encoder.adapt(x_train_text.values) ...
2ddc501d1a73527b57da20cb90ce8d47d82f1996
3,629,960
def find_group(name): """Make a special case of finding a group. NB This uses ambiguous name resolution so only use it for a casual match """ return root().find_group(name)
d69646dba11c9b7925ac403453100b13ea874a98
3,629,961
def multiplicar(a, b): """ MULTIPLICAR realiza la multiplicacion de dos numeros Parameters ---------- a : float Valor numerico `a`. b : float Segundo valor numerico `b`. Returns ------- float Retorna la suma de `a` + `b` """ return a*b
2d1a56924e02f05dcf20d3e070b17e4e602aecf6
3,629,962
import pkg_resources def email_vertices(): """Return the email_vertices dataframe Contains the following fields: # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 1005 non-null int64 1 dept 1005 non-null int64 ...
5ccba798717b69c367befb4bf3ab92d9d2fab37a
3,629,963
def pascal_row(n): """returns the pascal triangle row of the given integer n""" def triangle(n, lst): if lst ==[]: lst = [[1]] if n == 1: return lst else: oldRow = lst[-1] def helpRows(lst1, lst2): if lst1 == [] or lst2 == [...
030fe3e574f4261c862a882e7fdeee836a1dffb7
3,629,964
def _apply_homography(H: np.ndarray, vdata: np.ndarray) -> tuple : """ Apply a homography, H, to pixel data where only v of (u,v,1) is needed. Apply a homography to pixel data where only v of the (u,v,1) vector is given. It is assumed that the u coordinate begins at 0. The resulting vector (x,y,z) is normali...
3f83dc9da32d03da8c35aabbdee8603264b31918
3,629,965
import re def is_matching_layer(layer): """Returns true if the name of the given layer meets the criteria for processing.""" return ( re.match(LAYER_PREFIX_TO_MATCH, layer.name()) and re.match(f'.*{LAYER_SUBSTRING_TO_MATCH}.*', layer.name()) and re.search(SUFFIX_CLEANABLE, layer.na...
e07c271f99db60ce06bff5d39ee91478937d272e
3,629,967
def parse_call_no(field: Field, library: str) -> namedtuple: """ Parses call number data per each system rules Args: field: call number field, instance of pymarc.Field library: library system Returns: """ if library == "bpl": callNo_data...
f5c787acfaa360315a4f49bf825410762d812e51
3,629,968
from re import A def ni(num,tem): """ num: density cm^-3 """ b = zeros( Aij.shape[0] + 2 , dtype='float64') b[-1] = 10 # this line is REALLY STUPID, but for some pointless reason linalg experiences # precision errors and thinks that A is singular when it is obviously not. if tem > 30: ...
83e5d918752c1241ce5e6917824526f5726edad2
3,629,969
def _parse_example_configuration(config, regexps): """ Parse configuration lines against a set of comment regexps Args: config(_io.TextIOWrapper): Example configuration file to parse regexps(dict[str, list[tuple[re.__Regex, str]]]): Yields: str: Parsed configuration lines "...
86ff5db080f12dc624feb4ce20dcf659dcc2cb49
3,629,970
def readCosmicRayInformation(lengths, totals): """ Reads in the cosmic ray track information from two input files. Stores the information to a dictionary and returns it. :param lengths: name of the file containing information about the lengths of cosmic rays :type lengths: str :param totals: na...
3d20f9e4763050169008875eb12195ec135030f4
3,629,971
import re def get_package_version(): """get version from top-level package init""" version_file = read('pyshadoz/__init__.py') version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) ...
35d16c607ccbf9b0102e47cccf77e532269aea38
3,629,972
def setup_default_abundances(filename=None): """ Read default abundance values into global variable. By default, data is read from the following file: https://hesperia.gsfc.nasa.gov/ssw/packages/xray/dbase/chianti/xray_abun_file.genx To load data from a different file, see Notes section. Param...
b024fa2517b5578f8ee077eecd00fecf6583819d
3,629,973
def load_dataset(datapath): """ Load dataset at given datapath. Datapath is expected to be a list of directories to follow. """ inFN = abspath(join(dirname(__file__), datapath)) return rs.read_mtz(inFN)
02ab263a13b9118d3943031e5165c943cc0c529f
3,629,975
def displace_vertices(vertices, directions, length=1., mask=True): """ Displaces vertices by given length along directions where mask is True Parameters ---------- vertices: (n, d) float Mesh vertices directions: (n, d) float Directions of displacement (e.g. the mesh normals...
a3481b8ac7366279207dee36b0ce7723276aec56
3,629,976
def point_in_poly(x,y,poly): """" Ray Casting Method: Drawing a line from the point in question and stop drawing it when the line leaves the polygon bounding box. Along the way you count the number of times you crossed the polygon's boundary. If the count is an odd number the point must be inside. ...
a13be4c712a4705829780dbfc847467d45897552
3,629,977
def can_comment(request, entry): """Check if current user is allowed to comment on that entry.""" return entry.allow_comments and \ (entry.allow_anonymous_comments or request.user.is_authenticated())
04bcd019af083cff0367e236e720f4f7b00f7a65
3,629,978
def tianqin_psd(f, L=np.sqrt(3) * 1e5 * u.km, t_obs=None, approximate_R=None, confusion_noise=None): """Calculates the effective TianQin power spectral density sensitivity curve Using Eq. 13 from Huang+20, calculate the effective TianQin PSD for the sensitivity curve Note that this function includes an ex...
ac211b96aff1d1bf2eeb8685944274820217d295
3,629,979
def __get_request_body(file: BytesIO, file_path: str, repo_url: str) -> dict[str, str]: """Creates request body for GitHub API. Parameters: file_path: path where file is to be uploaded (e.g. /folder1/folder2/file.html) file: File-like object repo_url: url of SuttaCentral editions repo ...
270ddaccde3f78c25849eccf3b5060d558f17d59
3,629,980
from typing import Union import struct def _write_header(buf: Union[memoryview, bytearray], dtype: np.dtype, shape: tuple): """ Write the header data into the shared memory :param buf: Shared memory buffer :type buf: bytes :param dtype: Data format :type dt...
4719f145e8e189d1c2b285b3ec33bfa5b4a8865f
3,629,981
def _padright(width, s): """Flush left. >>> _padright(6, u'\u044f\u0439\u0446\u0430') == u'\u044f\u0439\u0446\u0430 ' True """ fmt = u"{0:<%ds}" % width return fmt.format(s)
d9333650a76fb8861f576f5e5f17c1929392c210
3,629,982
def single(mjd, hist=[], **kwargs): """cadence requirements for single-epoch Request: single epoch mjd: float or int should be ok hist: list, list of previous MJDs """ # return len(hist) == 0 sn = kwargs.get("sn", 0) return sn <= 1600
8734916221f0976d73386ac662f6551c25accfc3
3,629,983
def accuracies(diffs, FN, FP, TN, TP): """INPUT: - np.array (diffs), label - fault probability - int (FN, FP, TN, TP) foor keeping track of false positives, false negatives, true positives and true negatives""" for value in diffs: if value < 0: if value < -0.5: FP+=1 ...
001cebd169589f9f1494d9833c1fc49d8ba9964b
3,629,984
def compress(s): """param s: string to compress count the runs in s switching from counting runs of zeros to counting runs of ones return compressed string""" #the largest number of bits the compress algorithm can use #to encode a 64-bit string or image is 320 bits #I tested the penguin and ...
7a937503d27a240b1cc867b72e6db458e7626355
3,629,986
def data_scaling(Y): """Scaling of the data to have pourcent of baseline change columnwise Parameters ---------- Y: array of shape(n_time_points, n_voxels) the input data Returns ------- Y: array of shape(n_time_points, n_voxels), the data after mean-scaling, de-meaning a...
94b550386b8411a96b9ccd3f5e93098560c327e1
3,629,987
def _process_normalizations(model_dict, dimensions, labels): """Process the normalizations of intercepts and factor loadings. Args: model_dict (dict): The model specification. See: :ref:`model_specs` dimensions (dict): Dimensional information like n_states, n_periods, n_controls, n_...
852eec42ec9813bf642cafa89fc2460c1af1a010
3,629,988
def versioned_static(path): """ Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version """ return versioned_static_func(path)
5eace52819755f01300a90007a0853766c57e1b1
3,629,989
def calculate_estimated_energy_consumption(motor_torques, motor_velocities, sim_time_step, num_action_repeat): """Calculates energy consumption based on the args listed. Args: motor_torques: Torques of all the motors motor_velocities: Velocities of all the motors....
00fbfd10e21de3fd7ce4b66dd369228951f77f62
3,629,990