content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _(shape: spatial.qhull.ConvexHull, x: float, y: float): """ For convex hulls, convert their exterior first into a Delaunay triangulation and then use the delaunay dispatcher. """ exterior = shape.points[shape.vertices] delaunay = spatial.Delaunay(exterior) return _contains(delaunay, x, y...
3ddbdf88997e97cdf8e8d8278d6dc65d460ad092
79,357
def get_contract(): """Build registry contract object.""" return w3_client().eth.contract(**compile_registry())
c3a8ff8364edc4d910336faba089ec7af97ed517
79,358
import torch def make_audio(data, vocab): """ batch audio data """ nfft = data[0].size(0) t = max([t.size(1) for t in data]) sounds = torch.zeros(len(data), 1, nfft, t) for i, spect in enumerate(data): sounds[i, :, :, 0:spect.size(1)] = spect return sounds
715fa328d76c080bcfca365a276adc678ec50af4
79,359
def consolidate_dataset_modified(dataset, data_column, label_column, offensive_label): """Turns all the datasets into a unified format: data columns - renamed to 'data' label columns - renamed to 'label' all other columns dropped labels: NOT for not offensive posts and OFF for offensive posts ...
2d7e7ea80e490196c0fc61e3eb9421862c938455
79,361
def getnodes(o,attr=None,graph=None): """Get destination nodes from graph bindings of o, limited to the specific attribute or graph if specified""" if attr: if hasattr(o,'__schema__') and attr in o.__schema__: return getattr(o,o.__schema__[attr][2]) # RETURN THE PRODUCT ...
2e852643d2fd53f6078949a40401ca3c2b3388bd
79,362
def checksum(numbers): """Form checksum from list of numbers.""" return numbers[0] * numbers[1]
cdab30f2be037940d4d6f3cf39f15ce4d7efb072
79,363
def ckwrite_sysctl_int(entry, value): """Check wether entry is already equal to value and if not, set it""" val = read_sysctl_int(entry) if val is None or val == value: return val return write_sysctl_int(entry, value)
2e008152453d54cdd9b7e5bf547786a5b0eb2588
79,364
from typing import Optional def dangerously_get_comment(comment_id: str, parent_post: Post) -> Optional[Comment]: """ Get a Comment by its ID without checking permission We don't need to check permission here because this method is only used internally e.g. Not exposed to an API :param commen...
f101357f5824cbfa042d577fc88876d28ef7d9f3
79,365
import pbio.misc.utils as utils def parse_kegg_pathways(row): """ This function parses all of the KEGG pathways out of the "kegg" field of a record. It first checks the "pathway" field, which is assumed to be a dictionary, of the row for a field key called "kegg". It assumes the "kegg" fi...
14bf0678ca2ef922c2b29e551cd637534c060ec5
79,366
def create_score_list_Knn(labels: list, sections: list, delay_lst: list, k: int) -> list: """ create KNeighbors score list of all the prediction by label type, section of microorganism and delay Parameters ---------- labels : list list of labels: SV and SVI sections : list list ...
c174d002da162c7501b2a691313eb040de30bb72
79,367
from datetime import datetime def connect(connection, connection_timeout_seconds=1): """ Attempts to make contact with a given connection object. """ created_at = datetime.utcnow() log_engine = pg_etl_engine # Create test_engine; for now, assume SQLAlchemy test_engine = create_...
b45dba1f768cdd6082ba2ebc2f0669d6094d0d67
79,368
import base64 import hmac import hashlib def sign_policy(policy): """ Sign and return the policy document for a simple upload. http://aws.amazon.com/articles/1434/#signyours3postform """ signed_policy = base64.b64encode(policy) signature = base64.b64encode(hmac.new( app.config.get('AWS_CLIENT_...
5f09d7a84ba688d7c3a56e04ff3d56ca9a89dc58
79,369
import torch def tensorFromSentence(lang, sentence, device): """tensorFromSentence # Arguments: lang: sentence: device: # Return: """ indexes = indexesFromSentence(lang, sentence) indexes.append(EOS_token) return torch.tensor(indexes, dtype=torch.long, device=device...
1b6ec87a78abe98478c109a063c1a6c79dca822d
79,370
def pspect(val_imgs, generator, invtransform, noise_vect_len, channel_axis, fname=None, Xterm=True, multichannel=False): """plots mean and std deviation of power spectrum over validation set + generated samples""" num = val_imgs.shape[0] gen_imgs = generator.predict(np.random.normal(size=(num,1,noise_vect_l...
0fd2f94aea7b5a49aec96e5fe8f3d0c362115ba7
79,371
def failureToString(failure): """ Given a failure instance return a string representing the kind of error that occurred. Args: failure: a :class:twisted.internet.error instance Returns: A string representing the HTTP response error message. """ for failure_type, failure_...
5e17d89b70ce19e2f829348a6828f36c19ca44c5
79,372
def weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False): """ Calculates quantiles (similar to np.percentile), but supports weights. Parameters ---------- values : ndarray Data quantiles : ndarray Which quantiles to calculate sample_...
707a2a649baa5dd3a297e9057f1de21b6697879f
79,373
def Normalize(D): """ Method to normalize feature matrix. Parameters: - - - - - D : array input feature matrix Returns: - - - - D_norm : array normalized feature matrix """ mu = D.mean(0) stdev = D.std(0) zs = (stdev != 0) D_norm = (D[:, zs] - mu[zs...
93ce0760850ef1aeb40685589f843efe35e78384
79,374
def mymad(x,y): """customized log intrinsic function""" return tvm.tir.call_intrin(x.dtype, "tir.mymad", y,x)
b8989d5d6b62f17ab7e2a82e7e75b52b471f99eb
79,375
def collect_docs(module, ctx): """Extract documentation for the supplied module -- module parameter is a pyang Statement object""" # create the top level container for this module modtop = ModuleDoc(module.i_modulename) # create the root StatementDoc object for the module mod = StatementDoc(module.i_modu...
10854c029a0d4b1d789eb54e1722d1832a98605c
79,376
from typing import cast def get_strlist_element(char_ptr_list: CharPtrList, index: int, max_val: int = 1) -> str: """ Get an element of a list of char* """ return (cast(char_ptr_list, P(c_char * max_val)))[index].value.decode()
e7f4ff2744e8c14a0e57b25736e74267ff9a5a3e
79,377
import re def pp_symbols(labels, drop_unvoiced_vowels=True): """Extract phoneme + prosoody symbol sequence from input full-context labels The algorithm is based on [Kurihara 2021] [1]_ with some tweaks. Args: labels (HTSLabelFile): List of labels drop_unvoiced_vowels (bool): Drop unvoice...
659c7a79ade15c96ef8e8964c46a42326a80787f
79,378
def stop_codon(draw, allow_ambiguous=True) -> str: """Generates [stop codons](https://en.wikipedia.org/wiki/Stop_codon). ### Arguments - `allow_ambiguous`: Whether ambiguous bases are permitted. """ return draw(sampled_from(ambiguous_stop_codons if allow_ambiguous else stop_codons))
ffb3fe85889a959d1a2bb7f37aaf0ddcee94a533
79,379
def recursiveGlob(*args, ext=None): """ glob with ability to search in subdirectories @param args: passed to getPath() @type args: arguments @param ext: passed to getPath() @type ext: string @return: list of paths that match desired pattern @rtype: list """ path = getPath(*args...
734154054ce4650970ab47a665b34208b8d40523
79,382
import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular ...
2a2171df2b6fc6789f7a8d4add044b70404f49ed
79,383
def offer_publication_list(): """ A simple exemple of ids used in OfferPublicationList in Offers.xml """ return [1, 16]
9d8e936c8cea8e568f4941dc84eeee4b2bebeca2
79,384
from typing import Dict from typing import Any from typing import Optional import torch def create_loss_function(main_config: Dict[str, Any]) -> \ Optional[torch.nn.Module]: """Create loss function also based on SMP. Args: main_config (Dict[str, Any]): Config with initial data. Returns: ...
725173c8307335e985e036e4c11b41f3f60e73f0
79,385
import warnings def get_gdal_dtype(numpy_dtype): """ Get the appropriate gdal data type from the numpy data type @param numpy_dtype: Numpy dtype @return GDAL data type """ if numpy_dtype == np.float32: gdal_dtype = gdal.GDT_Float32 elif numpy_dtype == np.float64: gdal_dty...
87c50e1961808297a055c7a713ec22b936684455
79,386
from colradpy import colradpy def get_colradpy_pec_prof( ion, cs, rhop, ne_cm3, Te_eV, lam_nm, lam_width_nm, adf04_loc, meta_idxs=[0], pec_threshold=1e-20, pec_units=2, plot=True, ): """Compute radial profile for Photon Emissivity Coefficients (PEC) for lines within...
f131e13f796904fc8653948f056bd086e52930d5
79,387
def put_entity(payload, entity_name, token, aiid): """Updates an entity""" return fetch_api( '/entity/{aiid}?entity_name={entity_name}', token=token, aiid=aiid, json=payload, entity_name=entity_name, method='put' )
d40079234d76957d5095b7fde46ada2b0d6489b2
79,388
import torch def transform_data(df, max_seq_len): """ returns the padded input ids and attention masks according to the DistilBert tokenizer """ tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") def tokenize_fct(turn): return tokenizer.encode(turn, add_special_tok...
9d524f1e9679ea180abd84282ba663136c2ced6e
79,389
import re def parse_length(length): """ Parse ``length``` and return parsed length interval (in seconds) or None if length can't be parsed. >>> parse_length('1m') 60 >>> parse_length('1h1m') 3660 >>> parse_length('1') >>> parse_length('1hX1m') >>> parse_length('1d') 86400 ...
9501962932b0f3a304dae50191db3544e463de4b
79,390
import warnings def is_sent_tokenizer(cls, verbose=False): """Determine if `cls` corresponds to something that resembles an nltk sentence tokenizer. If True, returns the valid (input, output) types. Examples: >>> from sklearn.linear_model import LogisticRegression >>> from nltk.tokenize import P...
56a80fabcc86a452ef481a2a3836b493451b5a8e
79,392
from datetime import datetime import time def search_shodan(thread_name, ips, api_key, start, end, org_uid, org_name, failed): """Search IPs in the Shodan API.""" # Initialize lists to store Shodan results data = [] risk_data = [] vuln_data = [] # Build dictionaries for naming conventions and...
62467842bb1f798ead26aae253bd5c166ef6c7ab
79,393
def smallest_with_symbols(expr, symbols): """ Return the smallest sub-tree in an expression that contains all given symbols. """ assert all(x in expr.free_symbols for x in symbols) if len(expr.args) == 1: return smallest_with_symbols(expr.args[0], symbols) candidates = [ arg for ...
1706c58a53e8a7718969d0194af81964cc673926
79,394
def jsont(t, as_list): """ return all fields in a JSON-serializable way """ if not as_list: return {l: ",".join(getattr(t, l)) if attr_is_list(l) else getattr(t, l) for l in LABELS} else: td = t.__dict__ out = [] for l in LABELS: if attr_is_list(l): out.append(",".join(td[l])) else: out.append(...
4b2c9f9c9420e574ba7619c86a239e61377e08b1
79,395
def get_title_elements(soup): """Get title elements from the homepage""" title_elements = soup.select('span[class*="k-card__title-piece"]') return title_elements
0df3606c78abe5550b2aae959083b670513a9d05
79,396
def fixed_read_text_method(uri): """We need to rewrite the URI to allow for broken logic in the library for parsing local files""" with open(rewrite_uri(uri)) as f: return f.read()
11b4ad51db5cea2690c0ab23e7113c722e579b9f
79,397
def user_exists(username: str): """ Check if username has a match in database. :param username: :return: True if username exists in database :return: False if no match :return: False if an Exception was raised. """ try: db = get_db() cur = db.cursor() user = cur.e...
2391b8dc0553f645ea448eca652fb494b8e392b6
79,398
def querystring(request, **kwargs): """ Append or update the page number in a querystring. """ querydict = request.GET.copy() for k, v in kwargs.items(): if v is not None: querydict[k] = str(v) elif k in querydict: querydict.pop(k) querystring = querydict....
304649c8ef2c335e40bacc5438c0ed0d50691117
79,399
def v_res(v, Td, kb, mass): """Rescale velocities using numba Args: v -- np.array(N,dim) containing velocities Td -- desired temperature kb -- Boltzmann constant mass -- particles' mass Returns: v -- rescaled velocities """ vel_sq = 0 for axis in range(v...
779f81a8ac0b8a9c6c43202dab7f0bc2e0f6db2e
79,401
def _get_ch_type_mapping(fro='mne', to='bids'): """Map between BIDS and MNE nomenclatures for channel types. Parameters ---------- fro : str Mapping from nomenclature of `fro`. Can be 'mne', 'bids' to : str Mapping to nomenclature of `to`. Can be 'mne', 'bids' Returns -----...
b90bd99da3ad0a59fcf3fcd38f04670ba5ed16b0
79,402
def tags_for_docker(cid, cardinality): """ Queries the tagger for a given container id :return: string array, empty if container not found """ return tagger.get_tags('container_id://%s' % cid, cardinality) or []
f4d63e5e5170c61dbd816362a1dd0809416c9356
79,403
def RunMStressMasterTest(opts, hostsList, test): """ Called when run in master mode. Invokes the slave version of the same program on the provided hosts list with the given test name. Args: opts: parsed commandline options. hostsList: list of hosts obtained from plan file. test: string: test name...
908c69c484d6197cf0d45f4b03a09eddaa60c564
79,404
def test_syn_seq_ffffffff(exit_stack: ExitStack, client_isn): """Test SYN with seq=0xffffffff Client is pytest, server is linux. """ con = TCPConnectionFixture() secret_key = b"hello" con.tcp_authopt_key = tcp_authopt_key( alg=TCP_AUTHOPT_ALG.HMAC_SHA_1_96, key=secret_key, )...
49589973175cf8ed5740631b6240fd816382ae21
79,405
def load_species_sf_dict(): """ Load dictionary of scale factors for molecules/cm2/s -> g/m2/yr and particles/cm2/s*6.022e26 -> particles/m2/yr for different emitted species """ species_sf_dict = {'so2': (365*24*60*60)*(100*100)*(32/6.02214e23), # g(S)/m2/yr 'oc': (365*24*60*...
b5d7bad35b5d4b7f928d1602a6e16f9aa51f6498
79,406
import json def create_rihvit_invoice(order_id): """ Create Rihvit Invoice using order details and iCredit Settings :param order_id: Sales Order :return: Invoice Creation Status (String) """ try: order = frappe.get_doc("Sales Order", order_id) rihvit_settings = frappe.get_doc("Rihvit Settings", "Rihvit Sett...
c8e103aa9b0015fec19b82fee08896be28ec8fdd
79,407
def delete_datasource_instance(connection, id, error_msg=None): """Delete a specific database source based on id. Args: connection: MicroStrategy REST API connection object id (string): ID error_msg (string, optional): Custom Error Message for Error Handling Returns: Comple...
5b33aaa02017667e40d3abe87b4f61e973c0e7b9
79,409
def gaussianPulse(time, energy = 1.5, amplitude = 1, width = 100, fwhm = None,t_start = 0, envelope_only = False, THz_pulse = False, change_sign = False, verbose = True): """ Build a Gaussian pulse. Args: time : the value of the time variable (in fs), it can be a single :py:class:`float` ...
0fb595498de8a363e1811b791d25edddf286517a
79,411
def ns(model_name, dat, let): """ First observation time for model_name. """ output_path = rm.make_output_dirs(model_name, dat, let)[0] obs_file = rm.make_file_dir_names(model_name)[13] file_input = open(output_path+'/'+obs_file, 'r') file_input.readline() ns = int(str.split(file_input....
77e5dc9f4ed1b30c592cbff4f4b075ab4c2dfb4b
79,412
import types def cacheable(cache_key_template = None): """ Decorator that makes a function cacheable. The /cache_key_template/ argument needs to be a string containing the same number of string formatting operators (%...) as the number of arguments of the decorated function. Note that keyword argu...
d63dd1feced08d5350c05c1e9867793bd0f6b8ca
79,413
def validation_errors(schema): """ Given a dict, returns any known JSON Schema validation errors. If there are none, implies that the dict is a valid JSON Schema. :param schema: dict :return: [String, ...] """ errors = [] if not isinstance(schema, dict): errors.append('Paramete...
d28e4a6d132e2836da38a8c40b70676c5860b478
79,414
from typing import Optional from typing import Union def plot( x: AnnData, by: Optional[str] = None, gene: Optional[Union[str, int]] = None, show_title: Optional[bool] = False, return_fig: Optional[bool] = False ) -> None: """ Plotting functionality. Parameters __________ x: A...
a4be97b09f360e63727a6bdb05e54860d7ff5e80
79,415
def db_method(func): """Decorator for a database method of a `DataRepository` object. The decorated method's object must have its database session stored in self._dbsession`. """ def wrapped_commit_func(self, *args, **kwargs): # Determine if we'll issue a commit or not. Remove 'commit' ...
5577c4b44af9f701303f7bce2e9f4b4785cece21
79,416
def get_seasonality(days: int) -> np.ndarray: """ Return an array with the weekly seasonality as seen in restaurant sales. The seasonality is generated by sampling the standard normal probability density function. the pattern is repeated every 7 days. The exact shape of the pdf is determined by a ...
dce6c7c6458b979694f8acd53b416073cb28ea37
79,417
def predict(model, message): """Return prediction: float Returns closing stock price for given row """ train_df = read_data(TRAIN_DATA) dataset_test = pd.DataFrame(message, index=[0]) dataset_test.columns = train_df.columns scaler = MinMaxScaler(feature_range=(0,1)) df = train_df.tail(300) # print('--------...
af1c8a743dbc4824fd37117655b55e9603eb5540
79,419
def trail_edge_length_from_plane(pos, direction, plane): """ Calculates the length of a trail edge from a line-plane intersection. Parameters ---------- pos : ``list`` of ``float`` The XYZ coordinates of the starting node of an edge. direction : ``list`` of ``float`` The XYZ coo...
80062ddf3b9ec92de1b6bff2cee534012a6f5624
79,421
def extractPolicy(v, gamma=1.0): """Calculate policy given value-function""" # init random policy (zero values for all states) policy = np.zeros(env.env.nS) for s in range(env.env.nS): # random expected total rewards # for given state and possible actions q_sa = np.zeros(env.en...
f8600a076a9c0731817fcc56cd2df2f3e3a5d348
79,422
def in1d(needles, haystack, invert=False): """ Test whether each element of a 1d array is also present in a second 1d array. :param array needles: (n1,) dtype array :param array haystack: (n2,) dtype array :param bool? invert: if True, the values in the returned array are inverted, ``in1d(a...
863c99932428dc0136692d8deede7e72557d0df4
79,424
def ph_element_op(op, bra, ket): """ phonon operator """ assert op in ph_op_list assert bra >= 0 assert ket >= 0 if op == r"b^\dagger b": if bra == ket: return float(ket) else: return 0.0 elif op == "b": if bra == ket - 1: retu...
293205ac51777edb3d9a92d6aea6ab4e38a1341e
79,425
from typing import Dict from typing import Any def circulating_supply(event: Dict[str, Any], context: 'bootstrap.LambdaContext') -> Dict[str, Any]: """ Return the circulating supply getting data from the status lambda function """ return get_payload('circulating_supply', event)
60cbb1321646a4b1b0875baedda31106491fb78f
79,426
def pool_status(conn_name: str = "main_conn") -> str: """Return pool status used for the conn_name.""" return application.PROJECT.conn_manager.pool_status(conn_name)
9b29d33150256ef0b674245405a078b891c7699d
79,427
def scale_fill_gradient_energinet( low: int = 0, high: int = 2, **kwargs ) -> p9.scale_fill_gradient: """ Create a two-point fill gradient. Parameters: low (int): Index of low color. high (int): Index of high color. """ pal = endktheme.colors.excel() return p9.scale_fill_gra...
af1739de3625ec2464ae7508bfe0b73f4792883c
79,428
from typing import Union from typing import List def orig_infix_to_postfix(equation: Union[str, List[str]], number_token_map: dict, free_symbols: list, join_output: bool = True): """ Read infix equation string and convert it into a postfix string :param Union[str,List[str]] equation: ...
37b12b790fdb4df0784e03d37532fe229e088190
79,429
def first_order_coeff_at_interfaces(f, Vi): """Compute the diffusion coefficient by 1st order finite-difference currents determined at both sides of an interface.""" G, I = f.shape Im1 = I - 1 fb = 2 * f[:, 1:] * f[:, :-1] return fb / (f[:, 1: ] * np.tile(Vi[:-1], G).reshape(G, Im1) + ...
e3910357f3b68d78221acecd9457e723a36514c1
79,430
def CalculateAAComposition(ProteinSequence): """ ######################################################################## Calculate the composition of Amino acids for a given protein sequence. Usage: result=CalculateAAComposition(protein) Input: protein is a pure protein sequence. Output...
5d26da04154326aa2bb601d22556ffc311846e07
79,432
from typing import List def from_path( path: PathLike, steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: List[str] = None, cp_exclusion: List[str] = None, preemptive_behaviour: bool = True, explain: bool = False ) -> CharsetMa...
8b3d3c23540530e3574b450c68a2a54ebf0b1ac6
79,433
def create_db(): """ Create & connect database INPUT : None RETURN : session: establish connection cluster: cassandra cluster """ cluster = Cluster() # To establish connection and begin executing queries, need a session session = cluster.connect() # session.execut...
0367390f66383273bd01c8fd8460ef69e9be3ccd
79,434
def verify_course_exists_and_in_program(view_func): """ Raises: An api error if the course run specified by the `course_id` kwarg in the wrapped function is not part of the curriculum of the program specified by the `program_uuid` kwarg This decorator guarantees existance of the pro...
8c6e92dcfb84b4c12d5d71750d6995452e731966
79,435
from datetime import datetime def fromtimestamp(timestamp: float) -> datetime.datetime: """always returns an aware datetime object with UTC timezone""" return datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc)
359c2345d5fc02d69c63b354de4392f1eddea155
79,436
def run_as(user, command, *args, **kwargs): """ Run a command as a particular user, using ``/etc/environment`` and optionally capturing and returning the output. Raises subprocess.CalledProcessError if command fails. :param str user: Username to run command as :param str command: Command to ru...
91f211659e796dfd1c131bfb32c45cc8241e1e38
79,437
def render_layer(psd_file, layer_id, original_size=True): """Render a layer in a PSD file, into PIL Image. :param psd_file: File path to PSD Image. :type psd_file: str :param layer_id: Layout ID to render. :type layer_id: int :param original_size: Keep original PSD size flag. :type original...
11900b1302ea62b2fa1af0f8fc059c970396aea7
79,438
def get_deid_field_dict(item): """ Return a dictionary with custom fields from the DeID Upload metadata. :param item: the item with data. :returns: a dictionary of key-vlaue pairs. """ deid = item.get('meta', {}).get('deidUpload', {}) if not isinstance(deid, dict): deid = {} res...
4de64e7dc205687c193a70c4e4dcfb6d30d436c3
79,439
from typing import Optional from typing import Union from typing import List def from_location_attribute(geom_type: Optional[str], geom: Optional[Union[str, List[str], dict]])\ -> Optional[SlfGeometry]: """ Instantiates an ``SlfGeometry`` from Simple Location Format data. ...
408e800b5339c9312ac5ac28259f3b1e45a4c8c2
79,440
def check(m,SG): """ This is the function intended for external use. Checks which crystal system the SG is in, then executes that system's check method. """ # Check cache key=SG+','+''.join(map(str,m)) if key in cache: return cache[key] for crystalsystem in crystalsystems: ...
45e6b880fc9f0ad23ca8b93a7ae23874acb4aa11
79,441
def create_roo_variable(var=None, name='x', title='', lwb=None, upb=None, val=None, unit=''): """ Magic function to convert several objects into ROOT.RooRealVar Args: var (list or ROOT.RooAbsReal): Variable from list or ROOT object name (str): Name of the new ROOT.RooRealVar title (str)...
1c8534a8d467f60aa0accdf96b8b61b12a2a9f0e
79,442
import math def ndtri(y): """ Return the argument x for which the area under the Gaussian probability density function (integrated from minus infinity to x) is equal to y. :param y: function input :type y: float :return: ndtri as float """ s2pi = 2.50662827463100050242 code = 1 i...
7aa0419483ea3da550394260adb0421584b44706
79,443
from datetime import datetime def get_seair_curves_for_region( region, disease=covid19, notification_rate=1.0, R0=None, use_deaths=False, CFR_bias=1.0, ) -> pd.DataFrame: """ A cached function that returns SEAIR compartments from cases inferred from region. """ region = mun...
7aaf8b454030f9d61e8d4da8bb3da7d283f58896
79,444
def _make_component_list_from_actions(actions): """ Creates a list of components from the input DataCheckAction list Arguments: actions (list(DataCheckAction)): List of DataCheckAction objects used to create list of components Returns: List of components used to address the input actio...
a90bc4c42b9b1bfd4d20b99d614244e7668efe94
79,445
from typing import Dict from typing import Any def interface_struct(interface: Interface) -> Dict[str, Any]: """Return a dict with information of a interface to be used in th API.""" return { ATTR_INTERFACE: interface.name, ATTR_TYPE: interface.type, ATTR_ENABLED: interface.enabled, ...
46724ccb1e71f1416c2c95ce434f60e0efbd9ca2
79,446
def new_id(method="uuid"): """ Generates a unique identifier to be used with any dataset. The default method will use a random generated uuid based on computer and a random generated uuid. Args: method: "uuid" -> default random uuid generation ???? -> other m...
ff88ea59f7a230ec4b97c0500530c838acad031a
79,447
def _split_constraints(constraints, type_): """Split list of constraints in two list. The first list contains all constraints of type and the second the rest. """ filtered = [c for c in constraints if c["type"] == type_] rest = [c for c in constraints if c["type"] != type_] return filtered, re...
28a54eb323dc61ef69fd57a01eacb26689290385
79,448
from typing import List from typing import Any import requests def fetch_latest_blocks() -> List[Any]: """ Get the latest Taproot block statistics using the API from https://taproot.watch """ r = requests.get(f'{config.TAPROOT_WATCH_URL}/blocks', timeout=5) return r.json()
300144c80b176dd456aa48dd16503baf08e4b1e5
79,449
def display_date(d): """ Render a date/datetime (d) as a date, using the SPECTATOR_DATE_FORMAT setting. Wrap the output in a <time> tag. Time tags: http://www.brucelawson.co.uk/2012/best-of-time/ """ stamp = d.strftime("%Y-%m-%d") visible_date = d.strftime(app_settings.DATE_FORMAT) ret...
52043130a656d1a1921fca1ffddda00ebec47321
79,450
def getNeededUpdates(baseVersion): """ Returns an array of needed updates to upgrade to the current version """ return MIGRATION_ORDER[MIGRATION_ORDER.index(getNormalizedVersion(baseVersion))+1:]
c26b9d68af0b83f934b53c2954ad5e2830105b66
79,451
def validate_email(data): """Validate that the email of the user is not used yet""" email = data['email'] user = User.objects.get(email=email) if (user is not None): raise serializers.ValidationError('A user with the email {0} already exists.'.format(email)) return data
40917ae41857ae0ce33ec1fab01ea37815deffbe
79,452
def batch_norm ( input # in_minibatch x in_channel x <...> , running_mean , running_var , weight=None , bias=None , eps=1E-5 , rigor=False , verbose=False): """ Correspond torch.nn.functional.batch_norm(in...
2c2886d65cf0e7e79cf1a0a8553405b0c70b67b4
79,453
def current(): """Retrieve the current visit record from the cherrypy request.""" return getattr(cherrypy.request, "tg_visit", None)
de77c2604e9d789fad81efcdb44b4fd4d8b4f3f6
79,454
def glorot_initializer(shape, tt_rank=2, dtype=tf.float32, name='t3f_glorot_initializer'): """Constructs a random TT matrix with entrywise variance 2.0 / (n_in + n_out) Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. ...
3d1571ee12d8c540b503361f1422c69d46c7e968
79,455
import bempp.api from bempp.api.operators import OperatorDescriptor from bempp.api.assembly.potential_operator import PotentialOperator from bempp.api.assembly.assembler import PotentialAssembler def single_layer( space, points, wavenumber, parameters=None, assembler="dense", device_interface=...
068bb7888a94786aaf8d69020b4a40af7ff92ff9
79,456
def lookup_ssh_key(): """ Looks up an SSH key by search_key for keyhelper.py """ search_key = flask.request.form["search_key"] username = flask.request.form.get("username") _auth_log.info( "User is trying to access pagure using the ssh key: %s -- " "|user: %s|IP: %s|method: N/A|repo: N/A...
495a22275a260ecb9d4b1b011983f07b80eb6ea1
79,457
def scrub(txt): """Returns sluggified string. e.g. `Sales Order` becomes `sales_order`.""" return txt.replace(' ','_').replace('-', '_').lower()
32546e1fa96337b351ef4dabc020d65659f8f2bd
79,458
def get_projection(utm_zone, south): """ Get a pyproj projection for WGS84 given the utm zone and south :param utm_zone: :param south: :return: """ if not south: south_string = '' else: south_string = '+south' projection = pyproj.Proj("+proj=utm +zone=%s, %s +ellps=WG...
5bbbbf1d595950fad70a89f00d208a95a798463c
79,459
def rle_masks_to_boxes(masks): """Computes the bounding box of each mask in a list of RLE encoded masks.""" if len(masks) == 0: return [] decoded_masks = [ np.array(mask_util.decode(rle), dtype=np.float32) for rle in masks ] def get_bounds(flat_mask): inds = np.where(flat_mask > 0)[0] retu...
4debf3647b12f809c8b3857f192bcb77275bf00f
79,460
def dataset_to_table_schema(ds: xr.Dataset) -> t.List[bigquery.SchemaField]: """Returns a BigQuery table schema able to store the data in 'ds'.""" # Get the columns and data types for all variables in the dataframe columns = [ (str(col), map_dtype_to_sql_type(ds.variables[col].dtype)) for co...
8a46929f3bb735397e0d56002716e832a9b76b72
79,461
import ipaddress def get_ip_interfaces(session, management_ip=None): """Gets interface ips addresses""" interface_info = [] unassigned_interfaces = ['Tunnel', 'Loopback', 'Vlan'] interface_num = [] nuclear_int = None ip_config = get_config(session) for ints in interface_types: cu...
3d84332eb5d59516ce8357bc433c731a12643e4f
79,462
def import_fqname(name): """ Looks up a fully qualified name, importing modules as needed. :param name: A fully-qualified name. """ modname = name qualname = "" while True: try: module = import_module(modname) except ImportError as exc: # Faile...
f075ce0d5b7dfbc1ab273844c03bbacd27aa4898
79,463
def bag42_geocode(address): """ Use the BAG42 service to geocode a given address. """ log.msg('Geocoding address %s' % address, evel=log.INFO) address_fields = ['street', 'zip_code', 'city'] payload = [] for field in address_fields: if field in address and address[field] is not None...
a0693bc5bc1565d56b3b5ec48ad5d1ea5fadd8f9
79,464
def double_dot(A, B): """Return A:B""" A, B = np.asarray(A), np.asarray(B) assert has_valid_shape(A) assert has_valid_shape(B) if A.shape == (6,6) and B.shape == (6,): return np.dot(A, B) if A.shape == (6,) and B.shape == (6,6): return np.dot(A, B) A, B = A.reshape(-1), B.res...
9c2180003062672cf33e7f9d63b920b4ea05f134
79,465
def predict_future_price(ticker, years): """Predicts future one day price of stock, inputs: ticker:str, years: int output: future price: float, accuracy: float""" df = get_data(ticker, years) df_new = df[["adjclose"]] forecast_out = 1 df_new["prediction"] = df_new[["...
1fc27b74877348d1e7caedad65f7a94e12685952
79,466
import torch def _relu(x: Tensor) -> Tensor: """(F.relu(inplace=False)) :param x: shape = (*) :return: shape = x.shape""" return torch.where(x > 0, x, torch.tensor(0., dtype=x.dtype, device=x.device))
2f44d9358cab470920d07ce9b45c77bb3d8768ee
79,467