content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Callable def char_pred(pred: Callable[[int], bool]) -> Parser: """Parses a single character passing a given predicate.""" def f(x): if pred(x): return value(x) else: raise Failure(f"Character '{chr(x)}' fails predicate" " `{p...
2b7be4f740e7f7afad1ef66c0d544208d679fc5c
18,489
def convert_bound(bound, coord_max, coord_var): """ This function will return a converted bound which which matches the range of the given input file. Parameters ---------- bound : np.array 1-dimensional 2-element numpy array which represent the lower and upper bounding box on t...
5784167af65b2f406bfa5c428f1421a8915359f3
18,490
def tk_window_focus(): """Return true if focus maintenance under TkAgg on win32 is on. This currently works only for python.exe and IPython.exe. Both IDLE and Pythonwin.exe fail badly when tk_window_focus is on.""" if rcParams['backend'] != 'TkAgg': return False return rcParams['tk.window_...
757963dce9d9dc00be54ffbcbf694656f2f770e9
18,491
from functools import reduce def cc_filter_set_variables(operator, bk_biz_id, bk_obj_id, bk_obj_value): """ 通过集群ID、过滤属性ID、过滤属性值,过滤集群 :param operator: 操作者 :param bk_biz_id: 业务ID :param bk_obj_id: 过滤属性ID :param bk_obj_value: 过滤属性值 :return: """ client = get_client_by_user(operator) ...
3e1f849c59d3e3553f1c8b6f725a36921cae9451
18,492
def distance(mags, spt, spt_unc): """ mags is a dictionary of bright and faint mags set a bias """ res={} f110w=mags['F110W'] f140w=mags['F140W'] f160w=mags['F160W'] relations=POLYNOMIAL_RELATIONS['abs_mags'] nsample=1000 for k in mags.keys(): #take the stand...
cece86e80c03ce8d9753fe864bd746e68500fca3
18,493
import math def foo(X): """The function to evaluate""" ret = [] for x in X: r = 2*math.sqrt(sum([n*n for n in x])); if r == 0: ret.append(0) else: ret.append(math.sin(r) / r); return ret
7b241cf45757cdf9a5a28ee56c59ee41099ccb1e
18,495
def measure_curv(left_fit, right_fit, plot_points, ym_per_pix, xm_per_pix): """ calculates the curvature using a given polynom Args: left_fit ([type]): [description] right_fit ([type]): [description] plot_points ([type]): [description] """ #get the max y value (start of the...
7ae6d1e390906c3011349716aad0d0640a4c3a65
18,496
import logging from datetime import datetime def get_external_dns(result): """ Function to validate the ip address. Used to extract EXTERNAL_DNS server information Args: result(dict): Input result dictionary with all network parameters and boolean flags Returns: result(dict): The updat...
14531bcd17dbc036f417ec7eca6d24e9c7931e6f
18,497
def __process_agent(agent_param): """Get the agent id and namespace from an input param.""" if not agent_param.endswith('TEXT'): param_parts = agent_param.split('@') if len(param_parts) == 2: ag, ns = param_parts elif len(param_parts) == 1: ag = agent_param ...
49ebaa4c435422066c0e2345e4cf056caebbdc9e
18,498
def inference(predictions_op, true_labels_op, display, sess): """ Perform inference per batch on pre-trained model. This function performs inference and computes the CER per utterance. Args: predictions_op: Prediction op true_labels_op: True Labels op display: print sample prediction...
5e58ab3fff91a2fb5450b37f0bf41b2681d297d9
18,499
from typing import Optional from typing import Any def callback_with_answer_and_close_window( on_change: Optional[OnQuestionChangeCallback], window: Window ) -> OnQuestionChangeCallback: """Create a callback that calls both the on_change and window.close methods.""" def inner(answer: Any) -> None: ...
70ac59a8fcb3634f49b49d2ffa150fa20072b485
18,500
import json import requests def nlu_tuling(question, loc="上海"): """图灵 API """ url = 'http://www.tuling123.com/openapi/api' data = { 'key': "fd2a2710a7e01001f97dc3a663603fa1", 'info': question, "loc": loc, 'userid': mac_address } try: r = json.loads(requ...
6d4ffd7675d27f3316635e72e6f3c02d13e243a6
18,501
import typing from typing import Any from typing import Dict def Lines( apply_clip: bool = True, close_path: bool = False, color: ndarray = None, colors: list = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], curves_subset: list = [],...
8456f09c6d0088d299123eea5545247a8df56ac8
18,502
import logging def parse_currencies(row): """Clean up and convert currency fields to floats.""" date_columns = ( 'Datum van laatste bijwerking', 'Einddatum', 'Begindatum' ) for key in date_columns: try: row[key] = arrow.get(row[key], 'DD.MM.YYYY HH:mm') ...
f0ae86dfc755d5ec4e79bb11ba297a463307ade1
18,503
import sympy def as_tuple(item, type=None, length=None): """ Force item to a tuple. Partly extracted from: https://github.com/OP2/PyOP2/. """ # Empty list if we get passed None if item is None: t = () elif isinstance(item, (str, sympy.Function)): t = (item,) else: ...
9ede0fb0abc43829e4ca53dbb2e5aaeb96479a3c
18,504
def messages(request): """ Return a lazy 'messages' context variable as well as 'DEFAULT_MESSAGE_LEVELS'. """ return { "messages": get_messages(request=request), "DEFAULT_MESSAGE_LEVELS": DEFAULT_LEVELS, }
7c151df9ce2515e34f01886e4100a44a0fa50f36
18,505
def hash_graph(graph): """ A hash value of the tupelized version of graph. Args: graph (NetworkX graph): A graph Returns: int: A hash value of a graph. Example: >>> g = dlib.sample(5) >>> g.nodes NodeView((0, 1, 2, 3, 4)) >>> g.edges EdgeView([(...
94039a1c067a2456345b49609f0f18267607e6f8
18,506
def deserialize(rank: str, suit: str) -> Card.Name: """ Convert a serialized card string to a `Card.Name`. Parameters ---------- rank : str A, 2, 3, ..., 10, J, Q, K suit : str C, D, H, S """ suit_map = { 'C': Suit.CLUBS, 'D': Suit.DIAMONDS, 'H': ...
cd4b8c09a2e0bddf3f8ba2079cd16f1cc3dbff9b
18,507
from contextlib import suppress import inspect def enforce_types(target): """Class decorator adding type checks to all member functions """ def check_types(spec, *args, **kwargs): parameters = dict(zip(spec.args, args)) parameters.update(kwargs) for name, value in parameters.items(...
b8aac44b70290e9277935a52c49cce8da93511d0
18,508
def get_article(URL): """ Get an article from one our trusted sources. Args: URL: URL string to parse, e.g., http://www.hello.com/world Returns Article object if URL was success requested and parsed. None if it fails to parse or the URL is from a source not in the trust...
4fe61fac2cc584819250198ca18c6ad4a640a245
18,509
def crop_central_whiten_images(images=None, height=24, width=24): """Crop the central of image, and normailize it for test data. They are cropped to central of height * width pixels. Whiten (Normalize) the images. Parameters ---------- images : 4D Tensor The tensor or placeholder of i...
d89a5daa8c40f5e56ff635351fd3ca2f09475dd7
18,510
def start(event): """ Whether or not return was pressed """ return event.type == KEYDOWN and event.key == system["ENTER"]
03c54ac79897fa1d84ffb3fd5cbd335486e81c46
18,512
def cost(theta, X, y): """cost fn is -1(theta) for you to minimize""" return np.mean(-y * np.log(sigmoid(X @ theta)) - (1 - y) * np.log(1 - sigmoid(X @ theta)))
476da6562a7083b573037359a8785d2fd99fd785
18,513
def enrich_nodes(nodes, vindplaatsen, articles): """ Add some attributes to the nodes. :param nodes: :param vindplaatsen: :return: """ nodes = add_year(nodes) nodes = add_articles(nodes, articles) nodes = add_versions(nodes, vindplaatsen) return nodes
de708d6a0ac5a79431ec142f91d01c9711115df4
18,514
def has_string(match): """Matches if ``str(item)`` satisfies a given matcher. :param match: The matcher to satisfy, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher invokes the :py:func:`str` function on the evaluated object to get its length, pas...
01f9ef9c5b2acd3b54901300e6c6ed80e656a0b0
18,515
import numpy def get_land_sea_mask(gridded_geo_box, \ ancillary_path='/g/data/v10/eoancillarydata/Land_Sea_Rasters'): """ Return a land/sea 2D numpy boolean array in which Land = True, Sea = False for the supplied GriddedGeoBox and using the UTM projected data in the supplied ancillary_path. ...
54bec48a78f969cd9297872c2965d0ca8a62e39a
18,516
import copy import itertools def qEI_brute(gp_, true_function, X_=np.linspace(0, 1, 200), q=3, niterations=10, nsim=1000): """ q steps EI performed with brute force: Brute search on vector X_ """ gp = copy.copy(gp_) i = 0 nn = X_.shape[0] rshape = q * [nn] qEI_to_evaluate...
a89afb5dc2e569d28642492cbacd7183814ca9dc
18,517
def potential_energy_diff(e_in, e_out): """Returns difference in potential energy. arguments: e_in - dictionary of energy groups from input file e_out - dictionary of energy groups from output file returns: potential energy difference in units of the input """ energy_type ...
11a2f25d5f034c7d824abd45369ed5a5711ad6ab
18,518
def CA_potential_profile(pot_init: float, pot_step: float, pot_rest: float, pot_init_time: float, pot_step_time: float, pot_rest_time: float, buffer_size: int = 1200, samp_rate: int = 3600) -> tuple: """ :param pot_init: Initial potential in V :param pot_ste...
b7a4ac226cb5f3f239125d7227013508df51404f
18,519
def generate_model_class(grid_dir, data_dir, Nlon=936, Nlat=1062, Nz=90): """ Wrapper function for generating the LLCRegion object describing the model region. The wrapper automatically reads the grid information. Default values for grid size are for the Samoan Passage box (Box 12 in Dimitris' notat...
442ea60d4c790dc4da65f65648657d8e49dfd6b7
18,520
from scipy.integrate import dblquad def discretize_integrate_2D(model, x_range, y_range): """ Discretize model by integrating the model over the pixel. """ # Set up grid x = np.arange(x_range[0] - 0.5, x_range[1] + 0.5) y = np.arange(y_range[0] - 0.5, y_range[1] + 0.5) values = np.empty((y...
e70046afb8c26711045d0ce5c7c00ea482ca972a
18,521
def detail(request, question_id): """ HelloWorld 내용 출력 """ question = get_object_or_404(Question, pk=question_id) context = {'question': question} return render(request, 'HelloWorld/question_detail.html', context)
61fe5664baa2a33282ec77aa020332038fc3b040
18,523
def TDataStd_BooleanArray_GetID(*args): """ * Static methods ============== Returns an ID for array. :rtype: Standard_GUID """ return _TDataStd.TDataStd_BooleanArray_GetID(*args)
f5faa03336a07dc366a9c5d9133dac46e6d378db
18,524
def get_axis_order(): """Get the axis_order set by any containing axis_order_scope. Returns: List of strings giving an order to use for axis names, or None, if no axis order is set. """ # By storing axis_order in the graph, we can ensure that axis_order_scope is # thread-safe. axis_order_list = ops...
6a8ed5661822a40cf99762b098eeb0c3600caf3a
18,525
def check_jax_usage(enabled: bool = True) -> bool: """Ensures JAX APIs (e.g. :func:`jax.vmap`) are used correctly with Haiku. JAX transforms (like :func:`jax.vmap`) and control flow (e.g. :func:`jax.lax.cond`) expect pure functions to be passed in. Some functions in Haiku (for example :func:`~haiku.get_paramet...
30d22d616189c6af986373a39d4410d105c222a2
18,526
def score_numeric_deg_ssetype(omega_a, omega_b): """ Return the tableau matching score between two Omega matrix entries omega_a and omega_b, as per Kamat et al (2008), with effiectvely negative infinty score for SSE type mismatch Parameters: omega_a - angle in (-pi, pi] omega_b - an...
5347492aadf50eaa1b32726b4f7eace433d47d7c
18,527
def top_menu(context, calling_page=None): """ Checks to see if we're in the Play section in order to return pages with show_in_play_menu set to True, otherwise retrieves the top menu items - the immediate children of the site root. Also detects 404s in the Play section. """ if (calling_page ...
0479a2f7834f740142330436d04282c19fe6ac20
18,528
def DefineJacobian(J, DN, x): """ This method defines a Jacobian Keyword arguments: J -- The Jacobian matrix DN -- The shape function derivatives x -- The variable to compute the gradient """ [nnodes, dim] = x.shape localdim = dim - 1 if (dim == 2): if (nnodes == 2): ...
e13c092e44db7771a942840083c1628e0f418cb2
18,529
import struct def build_reg_text_tree(text, part): """Build up the whole tree from the plain text of a single regulation. This only builds the regulation text part, and does not include appendices or the supplement. """ title, body = utils.title_body(text) label = [str(part)] subparts_list = ...
a9d1068ee061e1a68f47b5bcdcf7ddde9383f330
18,530
def solve(banks): """Calculate number of steps needed to exit the maze :banks: list of blocks in each bank :return: number of redistribtion cycles to loop >>> solve([0, 2, 7, 0]) 4 """ seen = set() loops = 0 mark = 0 for cycle in count(1): # find value and the index o...
304f4c9294de690a38e517a2fd4455a355db3cb9
18,532
def evaluate_python_expression(body): """Evaluate the given python expression, returning its result. This is useful if the front end application needs to do real-time processing on task data. If for instance there is a hide expression that is based on a previous value in the same form. The response inc...
917490e73d5cd52493128f97d135adb44872a376
18,533
import collections def DictFilter(alist, bits): """Translate bits from EDID into a list of strings. Args: alist: A list of tuples, with the first being a number and second a string. bits: The bits from EDID that indicate whether each string is supported by this EDID or not. Returns: A dict...
33d236d649d75ae60ab354c7dc6588e75c855463
18,534
def mentions(request): """Mentions view.""" return render(request, "mentions.html", {"site_title": "Mentions legales"})
6bb3dcff6e098127e744d21d67384011595f67c7
18,535
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """activity assistant form a config entry is only called once the whole magic has to happen here """ #_LOGGER.warning(str(entry.version)) #_LOGGER.warning(str(entry.entry_id)) #_LOGGER.warning(str(entry.title)) #_LOGGER....
4389f1438a9a9e363f63eae3fe11ec40438569e3
18,536
def delete(id): """ Used by the product page to delete a product. Doesn't actually delete it, just sets the quantity to 0. """ db = get_db() b_id = session.get("user_id") query = "UPDATE product SET quantity = 0 WHERE product_id = ? AND for_business = ?" db.execute(query, (id, b_id,)) db.commit...
25ea594a8d4db6b6040f81033cbd804751d86fce
18,537
def from_meshmaker(filename_or_dict, material="dfalt"): """ Generate a mesh from a block MESHM. Parameters ---------- filename_or_dict: str or dict Input file name or parameters dict with key "meshmaker". material : str, optional, default 'dfalt' Default material name. """ ...
233d2e5059ebfcd819b526e43bb241e136fbc409
18,538
def compute_qtys_new_halos_pk(mvir, rvir, redshift, age_yr): """ Creates a new galaxy along with the new halo. Integrates since the start of the Universe. Updates the initiated quantities with the values of interest. :param mvir: list of mvir [Msun], length = n. :param rvir: list of rvir [kpc] , length = n. ...
8d68a82c08b38596a3ba6defa4633d1c156955b8
18,539
def rank(): """A function which returns the Horovod rank of the calling process. Returns: An integer scalar with the Horovod rank of the calling process. """ rank = MPI_LIB_CTYPES.horovod_tensorflow_rank() if rank == -1: raise ValueError( 'Horovod has not been initialized;...
5ce5b0c4ffc644f6c2cb3fc397ea2eb2e68e7c86
18,540
def getRAMSizeOSX() -> CmdOutput: """Returns the RAM size in bytes. Returns: CmdOutput: The output of the command, as a `CmdOutput` instance containing `stdout` and `stderr` as attributes. """ return runCommand(exe_args=ExeArgs("sysctl", ["-n", "hw.memsize"]))
519d6bb5afff6722bdced29df793b36ae6ee734a
18,541
def load_data(filepath, columns=['title','abstract']): """Loads specified columns of csv/excel data. Arguments --------- filepath: str Path to file (e.g. 'data.csv') columns: list List of strings specifying the column names in the data to load. Returns ------- pandas.Da...
2c1be3075950ac4ab82cdc7fa0b18cbdb7bf80b2
18,542
def pre_process(image): """ Invert pixel intensity of 'images' (to compensate the conversion into image with imwrite). """ return 1 - image * 255
7e7227930567c31874d966ce18aeeffa9b73e646
18,543
from typing import Sequence from typing import List def get_examples_to_execute( predictions: Sequence[inference.Prediction], inference_config: inference.Config ) -> List[official_evaluation.ExecutionInstructions]: """ Converts predictions from a model into sqlite execution instructions. If abstract SQL w...
9e5ef9ec7fa07433e3f8f14c0164e9858d271461
18,545
def verify_query(ctx): """ Verify a LQL query. """ label_widget = ctx.get_state(state="query_builder", key="query_label") lql_query = ctx.get("lql_query") evaluator_id = ctx.get("lql_evaluator") try: _ = ctx.client.queries.validate( lql_query, evaluator_id=evaluator_id) ...
93affbaf7a6049c162850199e5b3f1b55a4f95a9
18,546
import calendar def data_feature_engineering(data): """ Add features to the data for later use state_code, weekday, month, year """ data['state_code'] = data['state'].map(us_state_abbrev) data['weekday'] = pd.to_datetime(data['date']).dt.weekday data['weekday'] = data['weekday'].map(week...
92c78a6c976191167d6de39d25762e2307689674
18,547
import numpy def train_ei_oc(emotion, model, algorithm, evaluation, finetune, baseline, preprocessor=None): """ 2. Task EI-oc: Detecting Emotion Intensity (ordinal classification) Given: a tweet an emotion E (anger, fear, joy, or sadness) Task: classify the tweet into one of four ordinal cl...
9843d9100039b082efb62f293d77552c50032b02
18,548
import random def cross(genom1, genom2, mutation_rate, widths, bounds): """ Generates a child_genom by breeding 2 parent_genoms with a mutation chance = mutation rate = [0, 1]. """ child_genom = [] for i in range(len(genom1)): if widths[i] == 0: child_genom.append...
0f973ffeefeec7b346a27ca3fda84210daff7d74
18,549
def version_0_2(path_in, path_out_base, skip_if_exists = True): """ * name is based on start time (not launch time) :param path_in: :param path_out_base: :param skip_if_exists: :return: """ version = 'v0.2' content = raw.read_file(path_in) name_new = generate_name(content) p...
add6fadabce12011fc1e5b136a1f3b042092d577
18,550
def value_or_dash(value): """Converts the given value to a unicode dash if the value does not exist and does not equal 0.""" if not value and value != 0: return u'\u2013'.encode('utf-8') return value
8cadbfd8dcfad9dfeb4112cb8537f0e0d5de49ba
18,551
def null() -> ColumnExpr: """Equivalent to ``lit(None)``, the ``NULL`` value :return: ``lit(None)`` .. admonition:: New Since :class: hint **0.6.0** """ return lit(None)
d51d861ac165bb5c40e372435bfa6698542a3e30
18,554
def uCSIsThaana(code): """Check whether the character is part of Thaana UCS Block """ ret = libxml2mod.xmlUCSIsThaana(code) return ret
3d6c4e712f997648f40ed9647c6b696126cdc99a
18,555
def geomprojlib_Curve2d(*args): """ * gives the 2d-curve of a 3d-curve lying on a surface ( uses GeomProjLib_ProjectedCurve ) The 3dCurve is taken between the parametrization range [First, Last] <Tolerance> is used as input if the projection needs an approximation. In this case, the reached tolerance is set in <T...
07a48fcad95aabcbbb31dc8563e3a57f51399b5c
18,556
def histogram(ds, x, z=None, **plot_opts): """Dataset histogram. Parameters ---------- ds : xarray.Dataset The dataset to plot. x : str, sequence of str The variable(s) to plot the probability density of. If sequence, plot a histogram of each instead of using a ``z`` coordin...
90e884734d7811258e148df8f8bba5a9dd29ac96
18,557
import pkg_resources def get_resource(name): """Convenience method for retrieving a package resource.""" return pkg_resources.resource_stream(__name__, name)
63aada8f6e99956b770bd9ea7f737d90432c3f90
18,559
def get_team(args): """Return authenticated team token data.""" return Team.query.get(args['team_id'])
160a5aa27a246a740811aec764d7bc52eaa91098
18,560
def config_sanity_check(config: dict) -> dict: """ Check if the given config satisfies the requirements. :param config: entire config. """ # back compatibility support config = parse_v011(config) # check model if config["train"]["method"] == "conditional": if config["dataset"]...
6933dc0687da4fe4d1e3e9cea3f7cbb5caefb69b
18,561
import yaml def parse_yaml() -> Dataset: """Test that 'after' parameters are properly read""" d = yaml.safe_load(f) dataset = d.get("dataset")[0] d: FidesopsDataset = FidesopsDataset.parse_obj(dataset) return convert_dataset_to_graph(d, "ignore")
437fb7d9a495b59c21c88962d2f5d5543c041729
18,562
def race_data_cleaning(race_ethnicity_path): """Clean and relabel birth data based on race/ ethnicity.""" # Read in CSV. race_df = pd.read_csv(race_ethnicity_path, na_values='*', engine='python') # Fill na values with 0. race_df.fillna(value=0, inplace=True) # Drop default sort column. rac...
1a7f8e540c14cdb42ff25b270916ef3af45e7790
18,564
import json def validate_resource_policy(policy_document): """validate policy_document. Between 1 to 5120""" if not isinstance(policy_document, policytypes): raise ValueError("PolicyDocument must be a valid policy document") if isinstance(policy_document, str) and not json_checker(policy_documen...
b6b0a18a7e252cf5402aed6e17e7b184aa3b432f
18,565
def upsample_filt(size): """ Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size. """ factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] return (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1] - center) / fact...
7f19552a5e55a7dbcc5fd99992b9522377628c65
18,567
def _MAC_hash(mac_str): """ Returns MAC hash value in uppercase hexadecimal form and truncated to 32 characters. """ return MD5.new(mac_str).hexdigest().upper()[:32]
c60785fe3b41355ada19d08595f71ff0c02ff3ce
18,568
def divide_rows(matrix, column, in_place=False): """Divide each row of `matrix` by the corresponding element in `column`. The result is as follows: out[i, j] = matrix[i, j] / column[i] Parameters ---------- matrix : np.ndarray, scipy.sparse.csc_matrix or csr_matrix, shape (M, N) The input ...
ae69f91f999cd4f5ea78c30de2ff7c089fe54efd
18,569
def multiSMC(nruns=10, nprocs=0, out_func=None, collect=None, **args): """Run SMC algorithms in parallel, for different combinations of parameters. `multiSMC` relies on the `multiplexer` utility, and obeys the same logic. A basic usage is:: results = multiSMC(fk=my_fk_model, N=100, nruns=20, nproc...
fe7aeb4464a207d6d6764c1d9efc9a199b9100cf
18,570
def colon_event_second(colon_word, words, start): """The second <something> <something> can be: * <day-name> -- the second day of that name in a month """ if len(words) != 1: raise GiveUp('Expected a day name, in {}'.format( colon_what(colon_word, words))) elif words[0]...
d438eb5a2f7f07e9c5cc4ae7e3b95f102bc909d6
18,571
import csv def outfalls_to_dfs(model, model_id): """ Read a .CSV into a Pandas DataFrame until a blank line is found, then stop. """ global RELEVANT_NODES RELEVANT_NODES = get_nodes_from_links(model, model_id) start = build_groups_dicts(model)['nodes_outfalls']['start'] skip_rows = build_grou...
cbbbeb52faebd1ebc57de7e13b555f9d664639d9
18,572
def get_count(path, **kwargs): """ Return the number of items in an dictionary or array :param path: Path to the dictionary or array to count This operation is only valid in :cb_bmeth:`lookup_in` .. versionadded:: 2.2.5 """ return _gen_3spec(_P.SDCMD_GET_COUNT, path, **kwargs)
7a8fe5a288cfba28dfcbac523ea4579cd4d8d165
18,573
def error_message() -> str: """Error message for invalid input""" return 'Invalid input. Use !help for a list of commands.'
2ffea48dd495d464264bc657ca62cfe6043a1084
18,574
def has_substring(string): """ Validate that the given substring is part of the given string. >>> f = has_substring('foobarhamjam') >>> f('arham') True >>> f('barham') True >>> f('FOO') False >>> f('JAMHAM') False :param str string: Main string to compare against. :...
33b7d5b52c6be4185dfdf96bad9a6d33f284ba52
18,575
def repos(): """Display And Add Repos""" page = Repos(ReposTable, dynamodb_table) return page.display()
8c5ec3e44caa7e88cb9ed7be4039309ae9e5cfe5
18,576
def lambda_handler(event, _context): """ Main Handler. """ microservice_name = event.get('MicroserviceName') environment_name = event.get('EnvironmentName') new_vn_sha = event.get('Sha') failure_threshold_value = event.get('FailureThresholdValue') if not failure_threshold_value: failure...
c14fa2ce93d526b1ef5dd0a79a4d7392d1951c5f
18,577
def masked_crc32c(data): """Copied from https://github.com/TeamHG-Memex/tensorboard_logger/blob/master/tensorboard_logger/tensorboard_logger.py""" x = u32(crc32c(data)) # pylint: disable=invalid-name return u32(((x >> 15) | u32(x << 17)) + 0xa282ead8)
24c076033a6c9252b411604a3935d4ba09b5aa16
18,578
def yaml_dictionary(gra, one_indexed=True): """ generate a YAML dictionary representing a given graph """ if one_indexed: # shift to one-indexing when we print atm_key_dct = {atm_key: atm_key+1 for atm_key in atom_keys(gra)} gra = relabel(gra, atm_key_dct) yaml_atm_dct = atoms(g...
b2efa54c188035971f174c14ce6b3543c9234cde
18,579
def CreateCloudsWeights( weights = None, names = None, n_clusters = None, save = 1, dirCreate = 1, filename = 'WC', dirName = 'WCC', number = 50 ): """SAME AS CreateClouds but now it takes as inputs a list of each class ...
9cfb7a94cb27f4587c24ad35b423af2246c68440
18,580
def sigmoid(x, deri=False): """ Sigmoid activation function: Parameters: x (array) : A numpy array deri (boolean): If set to True function calulates the derivative of sigmoid Returns: x (array) : Numpy array after applying the approprite function ...
d523a3ec7df31b71ae60609f63314475784e6b38
18,581
from typing import Counter def palindrome_permutation(string): """ All palindromes follow the same rule, they have at most one letter whose count is odd, this letter being the "pivot" of the palindrome. The letters with an even count can always be permuted to match each other across the pivot. ...
a1e5721d73e9773d802b423747277dd43ee5983f
18,583
import ctypes def generate_pfm_v2(pfm_header_instance, toc_header_instance, toc_element_list, toc_elements_hash_list, platform_id_header_instance, flash_device_instance, allowable_fw_list, fw_id_list, hash_type): """ Create a PFM V2 object from all the different PFM components :param pfm_header_insta...
2b1dfe4150cc18c588c3b8711e7ea94afcfbfbdc
18,584
def symmetrise_AP(AP): """ No checks on this since this is a deep-inside-module helper routine. AP must be a batch of matrices (n, 1, N, N). """ return AP + AP.transpose(2, 3)
4a993f42e576656ec5f450c95af969722f10a58d
18,585
def index(): """新闻首页""" #----------------------1.查询用户基本信息展示---------------------- # 需求:发现查询用户基本信息代码在多个地方都需要实现, # 为了达到代码复用的目的,将这些重复代码封装到装饰器中 # # 1.根据session获取用户user_id # user_id = session.get("user_id") # # user = None # # 先定义,再使用 否则:local variable 'user_dict' referenced before ass...
63965ca1caef0efafe859c10ffd4d72724e16504
18,586
def formatter_message(message, use_color = True): """ Method to format the pattern in which the log messages will be displayed. @param message: message log to be displayed @param use_color: Flag to indicates the use of colors or not @type message: str @type use_color: boolean @return: the...
f171638a60e6a031fde7b249a7e40839da25addc
18,587
def find_offsets(head_mapping): """Find the time offsets that align the series in head_mapping Finds the set of time offsets that minimize the sum of squared differences in times at which each series crosses a particular head. Input is a mapping of head id (a hashable value corresponding to a head...
93864ec2c9902e28e98eeb6e225e918ffc21dbaa
18,588
def get_argument(value, arg): """Get argument by variable""" return value.get(arg, None)
0abd48a3a241ab1076c3ca19241df5b7b4346224
18,589
def tokenize(docs, word_tokenize_flag=1): """ :param docs: :param word_tokenize_flag: :return: """ sent_tokenized = [] for d_ in docs: sent_tokenized += sent_tokenize(d_) if word_tokenize_flag==1: word_tokenized = [] for sent in sent_tokenized: word_t...
b9484010c3e98aa32d96450122510f46dc0d8d72
18,590
def is_literal(expr): """ Returns True if expr is a literal, else False. Examples ======== >>> is_literal(a) True >>> is_literal(~a) True >>> is_literal(a + b) True >>> is_literal(Or(a, b)) False """ if isinstance(expr, Not): return not isinstance(expr....
7ec6b4a00aea544a05686f228be73fa71e70df6f
18,591
def get_target_proportions_of_current_trial(individuals, target): """Get the proportion waiting times within the target for a given trial of a threshold Parameters ---------- individuals : object A ciw object that contains all individuals records Returns ------- int all...
95f3781677f3ca7bb620488778b52502783c6eb9
18,592
def how_many(aDict): """ aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. """ return sum(len(value) for value in aDict.values())
ed1729b55411f29626dfe61c6853bc19813ceedc
18,593
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols): """Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ x, y, a, s = keypoint x1, y1, x2, y2 = crop_coords cropped_...
5a2365a611275fea4d0f5d031127426c88c43905
18,595
def get_tcoeff(epd_model, dF): """ Tranmission coefficients beta, gamma and delta can be directly computed from the time series data. Here we do not need reference to any compartmental model. """ df = dF.copy() dfc = pd.DataFrame(columns=['date','beta','gamma','delta']) df['infected'] = df...
22d6290f15efcdeb2e75b421c8d5d0fa17ff57f3
18,596
from typing import Any def rx_filter(observable: Observable, predicate: PredicateOperator) -> Observable: """Create an observable which event are filtered by a predicate function. Args: observable (Observable): observable source predicate (Operator): predicate function which take on argument ...
1d43435d04660b1a05eb906b16f031d270122585
18,597
from typing import Optional def map_time_program(raw_time_program, key: Optional[str] = None) \ -> TimeProgram: """Map *time program*.""" result = {} if raw_time_program: result["monday"] = map_time_program_day( raw_time_program.get("monday"), key) result["tuesday"] = m...
4a1d97d61e195184f0c3c40e4664a9904d591837
18,598
def _find_tols(equipment_id, start, end): """Returns existing TransportOrderLines matching with given arguments. Matches only if load_in is matching between start and end.""" #logger.error('Trying to find TOL') #logger.error(equipment_id) #logger.error(start_time) #logger.error(end_time) ...
5ebec8857d56382e377bd9d98ce2bb7aa74a44b2
18,599
def MC1(N,g1,x): """ Calculating the numerical solution to the integral of the agents value by Monte Carlo of policy 1 Args: N (int): Number of iterations/draws g1 (float): Agents value of policy 1 x (float): Drawn from a beta distribution (X) ...
f3a25656f60788e0ec50d75be6d20ff3e497f500
18,600