content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
import os def get_post(_activePost): """ functions to get the input scrapping post url :return: a list """ _link = [] if _activePost == "postLink1": _scrapping_link = request.form.get("singlePost") _processed_link = _scrapping_link.replace("www", "m") _link.append(_proc...
3b49a1fd8fca95218784e84aa1014ad01ef3bb05
18,511
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
import os def get_saved_model_list(ckpt_dir): """Return a list of HDF5 models found in ckpt_dir """ filenames_list = [] for (root, directories, filenames) in os.walk(ckpt_dir): filenames_list += filenames # Break to only keep the top directory break ckpt_list = [] for f...
5b557c98beb404d5b6f9fa89b4aba404674ec5bd
18,522
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 check_url_alive(url, accept_codes=[401]): """Validate github repo exist or not.""" try: logger.info("checking url is alive", extra={"url": url}) response = request.urlopen(url) status_code = response.getcode() if status_code in accept_codes or status_code // 100 in (2, 3): ...
5e136604b8e4a16923d2f6db19a1b324ed0a95c1
18,531
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
import os def is_source_path(path): """Check if path is source code path. Parameters ---------- path : str A possible path Returns ------- valid : bool Whether path is a possible source path """ if os.path.exists(path): return True if path.find("\n") !...
f932049eb70275ad8e394ec21af8bbf9ef2c3880
18,544
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 jaccard_index(box_a, box_b, indices=[]): """ Compute the Jaccard Index (Intersection over Union) of 2 boxes. Each box is (x1, y1, x2, y2). :param box_a: :param box_b: :param indices: The indices of box_a and box_b as [box_a_idx, box_b_idx]. Helps in debugging DivideByZero err...
006c58f9f0574da1f8db7c432fa4a16f397eab61
18,552
import types from typing import Optional def ComputePerSliceMetrics( # pylint: disable=invalid-name slice_result: beam.pvalue.PCollection, eval_shared_model: types.EvalSharedModel, desired_batch_size: Optional[int] = None, compute_with_sampling: Optional[bool] = False, random_seed_for_testing: Op...
c47b06776f197726bab1c29d1e186517c7aabcfc
18,553
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 os def get_full_file_path(filepath_parts, path, merge_point=None): """"Typical path formats in json files are like: "parent": "block/cube", "textures": { "top": "block/top" } This checks in filepath_parts of the blender file, matches the base path...
c0d44fb96ead9a9eb544746f1f0037e24220d484
18,558
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
import os from pathlib import Path import subprocess import shlex def run( desc_file, results_dir, start_date, walltime, n_days=1, no_submit=False, quiet=False ): """Create and populate a temporary run directory, and a run script, and submit the run to the queue manager. The run script is stored in :...
4bfef7b1afd9a1960962bff0b822e9a9569559de
18,563
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
import sys def ResolveOrganizationSecurityPolicyId(org_security_policy, display_name, organization_id): """Returns the security policy id that matches the display_name in the org. Args: org_security_policy: the organization security policy. display_name: the displa...
3e78e1013bd55cd7b5671d42e27a2f9d230d71b4
18,566
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
import os def main(args): """ Main function operates the following steps: 1. Get fits and aperature datafile 2. Get or guess the passband from filename 3. Get ra and dec from fits 4. Match image and reference with SkyCoord using ra's and dec's 5. Calculate zeropoint 5. Apply zeropoint...
d6dab808d11415a2f3a1a1face9bac1a2476165e
18,582
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 build_model(images, num_classes): """Build the model :param images: Input image placeholder :param num_classes: Nbr of final output classes :return: Output of final fc-layer """ #####Insert your code here for subtask 1e##### # It might be useful to define helper functions which add a lay...
69614723e72b73988268d6230dee619d571cfe2e
18,594
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