content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def doc_factory(global_config, **local_conf): """Return a developer portal instance configured for production.""" return make_app(blueprints.developer_portal, settings.ProductionConfig)
b747b0e5c848955b71b35f203282ca6b5487ab9b
3,604,308
import ast def make_grp_list_func(expr_str, field_names_dict, global_names_dict=None, filename=None): """ >>> func = make_grp_list_func('sum(a)/cnt()', {'a': 0}) >>> func([(1,), (2,), (3,)]) 2 >>> func = make_grp_list_func('1+sum(a)+sum(b**2)', {'a':0, 'b':1}) >>> func([(10, 1), (20, 2)]) ...
7ce4fecd041db76f1ad8e4e3703a1f0e54b2a1cd
3,604,309
from typing import Union from datetime import datetime def plot_cpi_timeseries( start_date: Union[datetime, str, None] = None, end_date: Union[datetime, str, None] = None, **kwargs, ) -> plotly.graph_objects.Figure: """ Plots the Australian CPI vs time Args: start_date (Union[datetime...
1b75b777fbb142c70f1ce16209a10d3f9e319962
3,604,310
from typing import List import re def find_economic_exprs(headline: str) -> List[str]: """ >>> find_economic_exprs('ユーロ高が原因で米株安') ['米株 安', 'ユーロ 高'] """ indices = ['円', '米株', '外株', '欧州株', '米国株', '中国株', '上海株',...
bd9541774400139fbcf5b6d0c807ca6e3eb1ef39
3,604,311
import PIL def scaleImage(image, width=None, height=None, mode="contain", quality=88, result=None, direction=None): """Scale the given image data to another size and return the result as a string or optionally write in to the file-like `result` object. The `image` parameter can either be the raw image dat...
faa1247192c8252dbcf3857172f184aa2b4cc20c
3,604,312
def split_tokens(s,keywordDict): """ Returns list of syntax elements with quotes and spaces stripped. """ result = [] result_append = result.append s_len = len(s) i = 0 while i<s_len: start = i while i<s_len and s[i]!="'": if s[i]=="(" or s[i]==")": if i>start: result_a...
9476337ea8db742e2a71f3caa04571db498d0064
3,604,313
def quat_distance(q1, q2, qsym): """ qsym coming from hexrd.crystallogray.PlaneData.getQSym() is C-contiguous """ q1 = np.ascontiguousarray(q1.flatten()) q2 = np.ascontiguousarray(q2.flatten()) return _transforms_CAPI.quat_distance(q1, q2, qsym)
d0dd769211289a68fb5bd438fb0fb21ebb804ad0
3,604,314
import numpy def _merge_ascending(labels, parents, valid): """Remove the non-valid items by including them in their parents when it exists. Parameters ---------- labels: labels of basins of watershed parents: parent local according to local maximum valid: measured ...
7c0e0983067a774c95f0d0389fc4e1d1ba8b301b
3,604,315
def get( project: str, changed_files: str, threshold: Decimal = Decimal(0), evg_api: EvergreenApi = Depends(get_evg), db: MongoWrapper = Depends(get_db), ) -> TestMappingsResponse: """ Get a list of correlated test mappings for an input list of changed source files. :param evg_api: The ...
d1bd657dff26bddc80568a50901ccd349c02e211
3,604,316
def admin_rated_contests(): """ 获取rated比赛列表 [ { "ratedTime":"rated应用时间", "contestID":"比赛ID", "contestName":"比赛名", "contestantCount":"参赛人数" } ] """ user: User = User.by_id(session.get("uid")) query = db.session.query(Contest.id...
7d6ea07e070955b303b7190098bda230a1ea8e9f
3,604,318
import ctypes def createWaitableTimer(securityAttributes=None, manualReset=False, name=None): """Wrapper to the kernel32 CreateWaitableTimer function. Consult https://msdn.microsoft.com/en-us/library/windows/desktop/ms682492.aspx for Microsoft's documentation. In contrast with the original function, this wrapper a...
de38f3b6202ef8347bb5d3b54326fe1bc0481e00
3,604,319
def name(): """ Returns the name of the token """ return NAME
08a7c7e271c342f6ea7650ab6698b21c55f6521c
3,604,320
def props_intersection(var_list, new_props_var, carry_vars=None): """Perform the intersection of the properties of a list of nodes/edges.""" if carry_vars is None: carry_vars = set(var_list) else: carry_vars.update(var_list) query = "\n//Perform the intersection of the properties of " ...
0262cc395f58361d245b5e52778f57e8dc312c69
3,604,321
def process_links(hyperlinks, file_extensions=None): """ This function processes a list of hyperlinks retrieved from the webpage and returns the list of links which refer to an image resource. The links are filtered by matching the file extensions of basename in that link. :param hyperlinks: List of...
8c4b0de775be32beec782911b96fe0024f878ba2
3,604,322
def get_last_roulette() -> Roulette: """ Returns either the last Roulette (by matching date) or None if there aren't any. """ return Roulette.objects.exclude(matchings_found_on=None).order_by("-matchings_found_on").first()
356cb43f2eebe80b8d16dc3fcfd6a301e192c7f3
3,604,323
def _parse_workflow(wf): """Define tasks for a workflow in the config """ print(f"Defining Device Listeners for Workflow [{wf['workflow_name']}]") schedule = [] for dlistener in wf["device_listeners"]: _handle_device_listener(dlistener) print(f"Defining Periodic Tasks for Workflow [{wf[...
107a0808f9e72cf4e03eed48b50e80539600953a
3,604,324
def available_comb_players_cards(arr_pl_one, arr_pl_two): """Removing intersections of player cards Args: arr_pl_one (np.array): an array of cards first player arr_pl_two (np.array): an array of cards second player Returns: np.array: an array of players cards Raises: V...
b79fdd8ebc3633070cb8b19bf9e59b48a1de2f2a
3,604,325
def oval_operator_or(result): """ The OR operator produces a true result if one or more arguments is true. If every argument is false, the result of the OR is false. If one or more of the arguments are unknown and if none of arguments are true, then the OR operator produces a result of unkno...
796e51f5e9764cf2a9eb42ac11b5f299fddfb91f
3,604,326
def interpolate_plane(ub, lb, location, ubpoints, lbpoints): """Interpolates a plane between two bounding planes at the given location.""" # If the number of points in the upper bound is higher, use it as the starting bound # otherwise switch the upper and lower bounds # if not (len(ubpoints) >= len(lb...
3d4f0e3bd5b1ca4582518a854da718ebbaa23090
3,604,327
def _processor(args): """ Process a single feature. Parameters ---------- args : dict feat : dict A GeoJSON feature to process. src_crs : str or dict The geometry's CRS. buf_crs : str or dict Apply buffer after reprojecting to this CRS. ...
804398c5b7572607172c6bf6901328bc810cb768
3,604,328
def lines_to_config(ctx_keys, line, delete): """ Return the command as it would appear in frr.conf """ cmd = [] if line: for (i, ctx_key) in enumerate(ctx_keys): cmd.append(" " * i + ctx_key) line = line.lstrip() indent = len(ctx_keys) * " " # There are...
ae9fcff2272a167790f2ea9554b3649f91c497af
3,604,329
import torch def masked_loss(lossfunc, logits, y, lens): """ Computes the loss of the first `lens` items in the batches """ mask = torch.zeros_like(logits, dtype=torch.bool) for i, l in enumerate(lens): mask[i, :l, :] = 1 logits_masked = torch.masked_select(logits, mask) y_masked = torch.m...
235f5e51a643eac803c28c2ab62b74e730c3c14d
3,604,330
import json def create_alert_alarm(): """ Create an alert or an alarm; invoked when processing alerts and alarms from uframe. Note: offset from start of unix epoch (jan 1, 1900 at midnight 00:00) to 00:00 1 Jan 1970 GMT, in secs = 2208988800 """ try: # Process request.data; verify required fie...
bd91dbb2dbd92470607252b2a773fd524dd2b5c3
3,604,332
def predict(data_path): """ Generate predictions of the model for new data sored in `data_path`. Print the predictions as an output. :param data_path: Path of the new data as csv. :return: None """ # Load data. X, y = load_data(data_path) # Load model print('Loading model from: {}'....
0f395d2e4173bc0501f854d49880dc43b06c24ef
3,604,335
def match_pair(tilea, tileb): """ Check whether two tiles have match edges """ match_edges = [[0, 2], [2, 0], [1, 3], [3, 1]] for variant in find_variants(tileb["tile"]): if any([tilea["tile"][m[0]] == variant[m[1]] for m in match_edges]): return True return False
c1b7435cf07d3b2c251ecb658e9964fbc63061af
3,604,336
def strings2remove_from_units(features2remove=default_features, other_strings2remove=['eenh', 'nvt']): """Generate a list of unwantes strings that are somtimes combined with the units. The function generates a list of strings that needs to be removed from the original units before performing named entity re...
d928ed528cc8071c7c46af403eea094270da7c30
3,604,337
def int_or_none(x): """ A helper to allow filtering by an integer value or None. """ if x.lower() in ("null", "none", ""): return None return int(x)
f7a99fd637b5f5e2f4519034b36d03128279726c
3,604,338
def calculate() -> str: """this executes the equation""" global equation, syntax_flag syntax_flag = 0 if not equation: return "0" #when input is empty, it equals to zero try: if syntax_flag: return "Syntax error" else: return str(eval(equation)) ...
101fc72a47dc412ce299cb6e2be792c7b979b20b
3,604,339
def build_fn_regs_custom_model_reg(X, n_outputs_, hidden_layer_sizes=None): """Build regressor with subclassed Model registered as serializable.""" if hidden_layer_sizes is None: hidden_layer_sizes = [] x = Input(shape=X.shape[1]) z = Dense(X.shape[1], activation="relu")(x) for size in hidde...
e87a8771e0f132f02b49e8f06d86608a3fa28ebc
3,604,340
def getHouseMsg(): """ 获取今日房价信息 :return: """ current_house_msg = getLastDayHouseMsg() week_house_msg = getWeekHouseMsg() current_house_date = current_house_msg[0] current_house_price = current_house_msg[1] current_house_num = current_house_msg[2] new_house_price = week_house_msg[0] new_house_num = week_hous...
e4d032e7f7d2182feedd46b44402aca60c980af7
3,604,341
def get_report_fnames(p, subj): """Get filenames of report files.""" fnames = [op.join(p.work_dir, subj, '%s_fil%d_report.html' % (subj, p.lp_cut))] return fnames
0f48132a4e5f59a2c8ab7289d0b73e46462d222c
3,604,342
def cnn_2d(x, weight_shape, strides, name, padding="VALID"): """ A 2d Convolutional layer :param x: Tensor, input tensor :param weight_shape: Tensor, [filter_size, filter_size, n_input_features, n_output_features] :param strides: Tensor, [1, stride_x, stride_y, 1] :param name: String, Name of th...
b29e5f98db695887fd74d726b9d5bc0cb9a3af44
3,604,343
def collatz(n): """Cuenta las veces que se itera hasta llegar a 1. Pre: n debe ser un numero entero. Post: Devuelve un numero natural de las repeticiones. """ res = 1 while n!=1: if n % 2 == 0: n = n//2 else: n = 3 * n + 1 res += 1 return res
4e1b5d227dfe18eddad1832352c3280995c672e5
3,604,344
def pl_powerlawsi(S,S_e,freq= [150, 1420], kind=None): """ plot powerlaw of spectralindex *Inputs* :S: Total flux of TGSS and NVSS resp (list) :S_e: error on Total flux of TGSS and NVSS resp (list) :freq: frequency of TGSS and NVSS resp (list) (default = [150, 1420] ) *Example* .. code-block:: p...
d9bd903210cffc1ab9b8d9b7fcd411484c2480a5
3,604,345
from typing import Optional async def update_player(identifier: Optional[str] = None, nickname: Optional[str] = None, username: Optional[str] = None, player: UpdatePlayerModel = Body(...), current_user: AdminModel = Depends(get_current_user)): """ Get an item by...
c84141dc09857608fdeefaa9777db12117e68b49
3,604,346
def get_datasets(expand=None, filters=None, queries=None, as_dataframe=None): """Return all available datasets in active project. Args: expand (bool, Optional, Default=None): include dataset details and format as dict filters(dict, Optional, Default=None): filter datase...
2a371f83660373646176a92b39644fa1273ed740
3,604,347
def count_viewable(row, col, m, flipped_m): """Before coming in, should pad with a border of 2 This allows np.diagonal() to work. m = np.pad(m, pad_width=2, mode='constant', constant_values=0) row, col = row+2, col+2 """ val = m[row, col] n_rows, n_cols = m.shape up = m[:row, c...
f596a0b052b8da8fcc58f2bf7bc4698b95377735
3,604,348
from typing import List from typing import Tuple def combine_user_data(files: List[Tuple[str, str]]) -> str: """Make a multipart/* message from a file content. Args: files: Paths to a file, a content of which will be used as 'UserData'. Returns: A multipart/* message attached a file cont...
73509154545d0a210250055caec59d6fe6fc33b0
3,604,350
import typing def lookahead_intersect( a: typing.Optional[LookaheadRule], b: typing.Optional[LookaheadRule] ) -> typing.Optional[LookaheadRule]: """Returns a single rule enforcing both `a` and `b`, allowing only terminals that pass both.""" if a is None: return b elif b is None: ...
32d3d80933a707d7e2557be06a72067ca3a97a09
3,604,352
import re def format_error(log: str, pkg_version): """ Execute some replacement transformations on the log, to make it more compressible """ # remove store hashes log = re.subn(r"(.*/nix/store/)[\d\w]+(-.*)", r"\1#hash#\2", log)[0] # reduce multiple white spaces to a single space log...
7bae545c480eeeabf57aac9ca5603e34e9368aee
3,604,353
import platform def supports_posix() -> bool: """Check if the current machine supports basic posix. Returns: bool: True if the current machine is MacOSX or Linux. """ return platform.system().lower() in ( "darwin", "linux", )
527bb8570e0493deec01aadafdf929e7315b27c0
3,604,354
def create_version(uid, ver_uid): """ Create a resource version. :param string uid: Resource UID. :param string ver_uid: Version UID to be appended to the resource URI. NOTE: this is a "slug", i.e. the version URI is not guaranteed to be the one indicated. :rtype: str :return: Vers...
9acdb8150cf02b776d6875e15f5426706d70c26a
3,604,355
import torch def compute_reconstruction_error(vae, data_loader, **kwargs): """ Computes log p(x/z), which is the reconstruction error. Differs from the marginal log likelihood, but still gives good insights on the modeling of the data, and is fast to compute. """ # Iterate once over the data ...
ee4fa35002e0f43d6482ae7f9ccfc7b7b1282db7
3,604,356
import torch def shannon_entropy(w: 'Tensor[N, N]') -> 'Tensor[1]': """ Compute the Shannon entropy of w. Function has a runtime of O(N^3) """ n = w.size(0) Z = matrix_tree_theorem(w) logw = w.clone() logw[logw == 0] = 1 logw = torch.log(Z) / n - torch.log(logw) return first_or...
9824f59c6c38c212cb2b5527d8d9e687b96ad680
3,604,357
def get_file_filter(): """get file filter""" composite_filter = CompositeFileFilter([FilterFileExist()]) return composite_filter
0a5fd00eaa76be37c5c963735104a52af685c200
3,604,358
def sporocila_get(): """Vrne sporočila uporabnika in možnosti za prejemnike novega sporočila """ (username, ime, emso) = get_user() c = baza.cursor() c.execute( """SELECT DISTINCT cas, prejemnik, posiljatelj, sporocilo FROM sporocila WHERE (prejemnik = %s OR posiljatelj = %...
b80672767f683c9baeae7d5e6e0fb359f3a1b358
3,604,359
def add_bgp_neighbors(): """POST BGP configuration from form data""" prefix_lists = GetPolicies.fetch_prefix_list(netconf_session) route_maps = GetPolicies.fetch_route_maps(netconf_session) if local_as is None: return render_template('add_bgp_neighbor.html', local_as="No_AS", prefixes=prefix_...
cdf639b71030e28bc86f7b413c13322a4c3fd331
3,604,360
def _whbtms(anchor): """Return width, height, x bottom, and y bottom for an anchor (window).""" w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_btm = anchor[0] + 0.5 * (w - 1) y_btm = anchor[1] + 1.0 * (h - 1) return w, h, x_btm, y_btm
0b4d65ad8a9dca2753ee703ad47764a1cb88f50e
3,604,361
import warnings def gumbel_recurrence(q, recurrence): """Deprecated! Use dist_recurrence(..., dist='gumbel_r').""" warnings.warn(gumbel_recurrence.__doc__, DeprecationWarning) return dist_recurrence(q, recurrence, dist='gumbel_r')
4d20fe8aab249e6fef9ca724f433e36adf4773a2
3,604,363
from datetime import datetime import pytz def get_trade( trade_id: int = 3132964, product: Pair = Pair.ETH_BTC, side: Side = Side.SELL, created_at: datetime = datetime(2018, 1, 2, 1, 18, 26, 406, pytz.UTC), size: Decimal = Decimal("0.00768977"), price: Decimal = Decimal("0.0575"), fee: Dec...
bf921f4c8a1d41efe851bb803fe3f6dc2197fbec
3,604,364
def hi(): """ """ return "Welcome to the IRIS Prediction Model!"
b2d5ff70eedebe5c628ff6676b03e30badf31666
3,604,365
def svn_opt_subcommand_help3(*args): """svn_opt_subcommand_help3(char const * subcommand, svn_opt_subcommand_desc2_t table, apr_getopt_option_t const * options_table, apr_pool_t pool)""" return _core.svn_opt_subcommand_help3(*args)
774aca3c9fdd35284fdbcb24b0bb95679adf5541
3,604,366
def get_total_per_month(month, board_list): """Sums all the values in a month board. :param month: The month to calculate total for :param board_list: The entire Trello Board :return: The sum for the month not rounded """ month = month.lower() total = sum( float(crd.name.split('-')[1...
793db7a2d24c15137b99eb84e51ac4d9cf3e1b7e
3,604,367
def humanize_delta( delta: relativedelta, precision: str = "seconds", max_units: int = 6 ) -> str: """ Returns a human-readable version of the relativedelta. precision specifies the smallest unit of time to include (e.g. "seconds", "minutes"). max_units specifies the maximum number of units of time...
1391604a6190579680cb1546438c175b8999b508
3,604,369
def create_json_structure(header_csv, delimiter): """ Create json structure :param header_csv: header_csv that contains the futur json's fields :param delimiter: delimiter of the nested json :return: json structure created """ # Sort header of csv to find the...
9abc7173951cf8da305828650e84bcb224b24b50
3,604,370
def nested_unstack(x): """Unstacks a pytree of numpy arrays. Inverse of nested_unstack. Example: nested_unstack((np.array([1, 3]), np.array([2, 4]))) == [(1, 2), (3, 4)] """ def unstack(arr): (*slices,) = arr return slices return nested_unzip(nested_map(unstack, x))
ce868f2cab42762e2424277a3f3000f74fe75ff9
3,604,372
def substract(x, y): """SUB NUMBERS TO GETHER""" return y - x
9be83227021ae8c37d4e2c2c9497346f96e878d0
3,604,373
def deleteNone(_dict): """Delete None values recursively from all of the dictionaries, tuples, lists, sets""" if isinstance(_dict, dict): for key, value in list(_dict.items()): if isinstance(value, (list, dict, tuple, set)): _dict[key] = deleteNone(value) elif val...
ac570fc3493277c3e39d87c0db006d18ac797abc
3,604,374
def _compute_land_only_mask(ds, lsm_min=0.8): """Computes a mask for cells that are considered to be over the land. The lsm fraction is above lsm_min. Here, lsm is the land-sea mask as a fraction (0 is all water, 1 is all land).""" da_mask = ds.lsm > lsm_min da_mask.attrs[ "long_name" ] ...
23b682a216031abac3e90989d130f7b3de9abf7c
3,604,375
def check_datasets(datasets): """Check that datasets is a list of (X,y) pairs or a dictionary of dataset-name:(X,y) pairs.""" try: datasets_names = [dataset_name for dataset_name, _ in datasets] are_all_strings = all([isinstance(dataset_name, str) for dataset_name in datasets_names]) are...
e02771dd7d2df3d9e716141ba2ada92408a2b14e
3,604,376
from typing import Any import re def make_exp(ltr_cnt: int = 3, inc_num: bool = False, inc_apos: bool = True) -> Any: """Make compiled regular expression.""" return re.compile(make_token_pattern(ltr_cnt, inc_num, inc_apos))
f31d51da4dda06cd57d9b4fd250d87d1d527ec5d
3,604,378
def plant_partial_rectangle(trajectories, r, p, q, eps): """ This plants a region containing r fraction of the total arc length of all trajectories. q fraction of the trajectories crossing this region are assigned to be anomalous and p fraction of trajectories not crossing this region are assigned to be...
c169457627eda273237e6be9cddb0e77b48ca41b
3,604,379
def chebadd(c1, c2): """ Add one Chebyshev series to another. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- ...
a2a5f976288c121b1c393fdff316c03bc3868842
3,604,380
def move_dtindex(dataframe, shift, freq): """ 数据框的时间索引漂移,只改变索引,数据并不发生漂移 :param dataframe: 数据框 :param shift: 漂移步长 :param freq: 漂移频率 :return: new_frame """ is_ser = False if isinstance(dataframe, pd.Series): dataframe = dataframe.to_frame() is_ser = True if isi...
74d76b230c85b0cefe718350c73d1d8cfc4271bd
3,604,381
from re import X def calc_area(points): """Calculate the area of a polygon :return: Area of polygon """ #ref: http://en.wikipedia.org/wiki/Polygon if len(points) < 3: return 0 p1 = points[0] a = 0 for p2 in points[1:] + [points[0]]: a += p1[X] * p2[Y] - p2[X] * p1[Y] ...
1939a6831a9cb8d140e8d372ce879fca43efffb6
3,604,382
import logging def compare_spatial_geneexp(adata_ge, adata_sp, adata_sc=None, genes=None): """ Compares generated spatial data with the true spatial data Args: adata_ge (AnnData): generated spatial data returned by `project_genes` adata_sp (AnnData): gene spatial data adata_sc (AnnDat...
4ee9083ff753fa77f792c6241daee95435063e6d
3,604,383
def get_symbol(symbol_vector, name): """ Find a casadi symbol by its name in a vertcat (vertical concatenation) vector of symbols. This method can also find vector-shaped symbols that span across a part of the full symbol vector. """ idx = get_symbol_idx(symbol_vector, name) if idx is No...
827bddfb3a423270178aecedee2f15dd664450da
3,604,384
def _make_iterable(x): """Transforms non-iterables into a tuple, but keeps iterables unchanged.""" try: iter(x) except TypeError: return x, else: return x
584802736d9c731401ef5d2447ffbb4195c4920a
3,604,385
def is_inside_except(node): """Returns true if node is inside the name of an except handler.""" current = node while current and not isinstance(current.parent, astroid.ExceptHandler): current = current.parent return current and current is current.parent.name
7e12a8b531f49bd7d6a3f2ca570adac0e64d03b8
3,604,386
def extract_geometries(shape_data, project=True): """ Enhances the shape data by adding a 'shape_obj' field with the shapely object, and splits data into points and polygons. """ points = [] linestrings = [] polygons = [] for sd in shape_data: add_shape = _add_shape(sd) #...
7d169cc840eb12a8b950f3ca7cdf94ad4f82fedd
3,604,387
def authenticate_with_certificate_chain(reactor, base_url, client_chain, client_key, ca_cert): """ Create an ``IAgent`` which can issue authenticated requests to a particular Kubernetes server using a client certificate. :param reactor: The reactor with which to configure the resulting agent. :par...
3606e3d987cfc212a6d2a1352d2c2440d3c38cbc
3,604,388
import requests import json def get_card_updated_data(scryfall_id) -> str: """Gets updated data from scryfall Args: scryfall_id ([type]): [description] Returns: json: result from scryfalls card api ref: https://scryfall.com/docs/api/cards/id ex scryfall_id="e9d5aee0-5963-41db-a2...
2a0f1a9c65cbe7e173543e8a3d4b03fd364e2ae6
3,604,389
def publish_submit(request): """Publish - Marketplace submission page.""" return jingo.render(request, 'ecosystem/publish_submit.html', {'page': 'publish_submit', 'category': 'publish'})
a126b5e175db9b05f777aeccc64efebdaea3fbdd
3,604,390
import random def sample_next_sequence(vocab, probs, seq_length, scheme): """Sample a full sequence of random tokens using uniform or multinomials.""" if scheme.endswith("_uniform"): return [random.choice(vocab) for _ in range(seq_length)] elif scheme.endswith("_freq"): bow_sent = np.random.multinomial...
72c78699e9df29d1ad2207506f223561b49ab4f8
3,604,391
def decompose(data: pd.DataFrame) -> tuple: """ STL时间序列分解 """ decomposition = seasonal_decompose(data) trend = decomposition.trend seasonal = decomposition.seasonal residual = decomposition.resid return trend, seasonal, residual
215d70906f85df6d83ccd0cc359e1e856bb85a68
3,604,392
def input_fn(data_dir, subset, num_shards, batch_size, use_distortion_for_training=True): """Create input graph for model. Args: data_dir: Directory where TFRecords representing the dataset are located. subset: one of 'train', 'validate' and 'eval'. n...
948195ce6ed035271952b086d3413dfe0dfd87c5
3,604,393
import torch def basis(A): """Return orthogonal basis of A columns. """ if A.is_cuda: # torch.orgqr is not available in CUDA Q, _ = torch.qr(A, some=True) else: Q = torch.orgqr(*torch.geqrf(A)) return Q
ad5de52748b4bfca35c2607af623457b4e0362c3
3,604,394
import torch def get_thresholded_graph(meta_data_tensor, threshold_list): """Get the thresholded graph given meta information and a list of thresholds. Args: meta_data_tensor: threshold_list: Returns: """ adj_list = [] for k, v in enumerate(threshold_list): meta_...
a09b27dfea06519b06ef5ed25793da67b01f4bfe
3,604,395
def get_candidate_file_name( monotonous: bool, agg_point: bool, both: bool = False, ) -> str: """Get canonical filename for candidate set sizes.""" if both: return f"candidate_sizes{'_mono' if monotonous else ''}_k_point" else: return f"candidate_sizes{'_mono' if monotonous else ...
85b27f7767fd495a46459553b96160691a3dbeda
3,604,396
def test_magic_factory(): """Test basic magic_factory behavior.""" @magic_factory(call_button=True) def factory(x: int = 1): return x assert isinstance(factory, MagicFactory) # factories make widgets that are FunctionGui instances widget1 = factory() assert isinstance(widget1, Fun...
5f468809432ff40521ead18fa1cbafd7df70ae09
3,604,397
def _matrix_exp_pade5(matrix): """5th-order Pade approximant for matrix exponential.""" b = [30240.0, 15120.0, 3360.0, 420.0, 30.0] b = [constant_op.constant(x, matrix.dtype) for x in b] ident = linalg_ops.eye(array_ops.shape(matrix)[-2], batch_shape=array_ops.shape(matrix)[:-2], ...
806fe9bf2c1d9bcd34cf9a2c9ec68eb1f04c7a44
3,604,398
import transformers def num_tokens(s: str): """Compute the number of tokens according to GPT""" global _tokenizer, _tokenizer_old_version if _tokenizer is None: _tokenizer = transformers.GPT2TokenizerFast.from_pretrained("gpt2") _tokenizer_old_version = (len(_tokenizer.tokenize("\n\nx")) =...
376912ec778b9b2c83c56df2110fac622771049a
3,604,399
def logs(request, tplname="core/logs.html"): """Return a list of log entries. This view is only called the first time the page is displayed. """ page = get_logs_page(request, 1) return render_to_json_response({ "callback": "logs", "content": render_to_string(tplname, {"logs": page....
a43b52533a0dc67a65b6ab3753a79754f97da26e
3,604,400
def log_out(): """Log user out""" # Remove user from session del session['user'] return redirect("/")
cf8dece3e216d96df3678d63bcd7a2a9dc84dbe9
3,604,401
def square_of_sum(limit): """ Returns the square of the sum of all integers in the range 1 up to and including limit. """ return sum([i for i in range(limit + 1)]) ** 2
503048c7b175d10dce20ff9d2f9435be4fbe1c35
3,604,402
def expand_unique_results(y, idx): """Inverse of unique_bitstrings_with_counts. Args: y: Values to pick according to `idx`. idx: The index at which to place each value of `y` in the output. Returns: expanded: `tf.Tensor` such that `expanded[i] == y[idx[i]]`. """ expanded = tf.gather(y, idx, axis...
4d8df1d42b1b437c722ad84cc967679860752c6b
3,604,403
def create_news_abc(schedule_model): """Abstract base news model factory. :param schedule_model: Schedule model to use as news's schedule. :type schedule_model: Any concrete schedule model of abc models from :func:`~create_abc_schedule` factory function. :returns: A abstract base news model. ...
c2572992175f990f557cc02db5010fb62d83c5ca
3,604,404
def ResNet18(include_top=True, weights=None, input_tensor=None, input_shape=None, pooling=None, classes=1000, use_bias=False, block_fn=vanilla_block, **kwargs): """Instantiates the ResNet18 architecture.""" ...
240127eb117366849de2cdc5d7d6b95d26d96c2a
3,604,405
def sigmoid2(temperature, b, c): """The two parameter sigmoid function from Chuine 2000 The full equation is f(x) = 1 / (1 + exp(b*(temp -c))) The scipy.special.expit function = 1/(1+(-x)) Using float32 increases speed significantly over the default float64 Parameters ---------- tem...
44f8af88df2363e4cbe34f5388e5765bbb61de48
3,604,406
def empty(): """ This matcher matches any collection-like object that responds to the __len__ method, and has a length of 0. """ return IsEmpty()
ead89734a3768f8cbdd1c0345fb2e3ada2ee5e0d
3,604,407
def calc_VCC(mdot_kgpers, T_sup_K, T_re_K, q_nom_chw_W, number_of_VCC_chillers): """ For th e operation of a Vapor-compressor chiller between a district cooling network and a condenser with fresh water to a cooling tower following [D.J. Swider, 2003]_. The physically based fundamental thermodynamic mode...
204f723ef1034a7183c2b3951b6e26d89badb9c4
3,604,408
def version_to_str(version): # type: (t.Tuple[int, ...]) -> str """Return a version string from a version tuple.""" return '.'.join(str(n) for n in version)
6f0ebb96c944645b228fec6f05aeb65d9d6d3374
3,604,409
from typing import Optional from typing import Any import logging def get_logger(name: Optional[str] = None, **kwargs: Any) -> Logger: """Return a logger with the specified name. :param name: Logging channel name, defaults to None. :returns: Logger instance. .. seealso:: :py:func:`logging.g...
c300b87d622f3a0d01a0a6fa24e0f9e6000d32ce
3,604,411
def has_duplicate(sampled_clumper): """Checks for a duplicate""" for i in range(len(sampled_clumper)): source_clump = sampled_clumper[i] for j in range(len(sampled_clumper)): if i != j: if sampled_clumper[j] == source_clump: return True return ...
d34dc7de8d84b1dc9e1b65e0a83b9cefcbed8055
3,604,412
def _resolve_expressions(expression_chain): """ Given a chain of intermittend expressions and operators, resolve it into single expression by taking priority rules into account. """ chain = expression_chain.copy() for ops in TOKEN_PRECEDENCE: i = 0 while i < len(chain): i...
2975b3aa51d8451ed9c7f3a916f93b9eb9d28f18
3,604,413
def subtract_noise_from_squared_rir(data, noise_level='auto'): """ Subtracts the noise energy level from the squared RIR. Note, that the RIR has to be squared before. Parameters ---------- data : ndarray, double The squared room impulse response with dimension [..., n_samples] Retu...
0ea7ae47b0d05a4b10a788a47eae43e7165e35af
3,604,414
def compute_spherical_volume(radius): """ Given radius, return volume of corresponding sphere. Args: radius (float): radius of sphere Returns: (float): volume of sphere """ volume = 4.0/3.0 * np.pi * radius**3 return volume
4536a386274e617ac23fba12d50aed6b38a46079
3,604,416
import re def is_valid_regex(regex): """Helper function to determine whether the provided regex is valid. Args: regex (str): The user provided regex. Returns: bool: Indicates whether the provided regex was valid or not. """ try: re.compile(regex) return True ...
4c544168f2b1894e7cc7c7804342f923287022b5
3,604,417
from typing import Iterable from re import T from typing import Iterator def take_last(iterable: Iterable[T], n: int) -> Iterator[T]: """ take only the last n elements of the iterable. >>> list(take_last(range(1000), 3)) [997, 998, 999] """ return deque(iterable, maxlen=n)
c6fab277038ff512683c38d9ce5986788c19d152
3,604,418
def make_rigidgroups_data(prot): """ ziyao: this function generates all rigid-groups-related keys including: [ 'rigidgroups_gt_frames', 'rigidgroups_gt_exists', 'rigidgroups_group_exists', 'rigidgroups_group_is_ambiguous', 'rigidgroups_alt_gt_frames' ] """ # ziyao: this function assumes ...
782364d866a37cf0d4730dc7c950ad69abbb1ae9
3,604,419