content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def main(): """Send test metric to AWS CloudWatch""" logging.basicConfig(level=logging.DEBUG) cloud_watch = create_cloud_watch( 'Test Namespace', asynchronous=False, buffered=False, dummy=False, dimensions={'By intent': 'Test'}, ) cloud_watch....
3b0e4b01a544b9e4edd7b3ffe32418651ea6a7e1
46,200
def pdf(X, m, S): """ Calculates the probability density function of a Gaussian distribution: X is a numpy.ndarray of shape (n, d) containing the data points whose PDF should be evaluated m is a numpy.ndarray of shape (d,) containing the mean of the distribution S is a numpy.ndarray of shape (d...
56d53f34c3d58e359f0f19279f8db125aebe2e3f
46,201
def find_correct_weight(program_weights, program, correction): """Return new weight for node.""" return program_weights[program] + correction
994c25efef10fa37971372f444a879e816708830
46,202
from typing import Optional def segment_mask(segment_ids: JTensor, source_segment_ids: Optional[JTensor] = None, dtype: jnp.dtype = jnp.float32) -> JTensor: """Computes (non-causal) segment mask. Args: segment_ids: a JTensor of shape [B, T], the segment that each token belon...
3ea357746326b6a88c5017e1fe6d4b0141b69519
46,203
def handle_keys(): """ This version use keypad (hence KP?). Not tested. """ global fov_recompute global mouse_coord keypress = False for event in tdl.event.get(): if event.type == 'KEYDOWN': user_input = event keypress = True if event.type == 'MOU...
04be0066018da8d5ac52ceeeb83c357734bccbf1
46,204
def test_for(item, min_version=None, callback=extract_version): """Test to see if item is importable, and optionally check against a minimum version. If min_version is given, the default behavior is to check against the `__version__` attribute of the item, but specifying `callback` allows you to ex...
3c6b8ffbff46914bc348494ab77295a6debd6d41
46,205
import ctypes def errcheck_object(result, func, args): """Checks the return value of NormFileEnqueue and NormDataEnqueue""" if result == ctypes.c_void_p.in_dll(libnorm, "NORM_OBJECT_INVALID"): raise NormError( "Error creating object from function '%s'" % func.__name__) return resul...
5d654f34937ae0784470ba6264afc9a5bfc8774b
46,206
import argparse def parseArgs(): """ CLI inputs """ log.info('Parsing command-line arguments...') parser = argparse.ArgumentParser(description='Explore enzyme-screening variability historically') subparsers = parser.add_subparsers(help='Choose mode of operation') plot_parser = subparsers.a...
3d15a104adceed9543c97fac4ee0a42237b4f993
46,207
def encode(delta_str, n_vertices, base, m=False): """Encodes delta string as a big integer. Args: delta_str: A string with delta coordinates in reference to min_x and min_y, min_x and min_y also included n_vertices: Number of vertices in the polygon base Returns: A dict map...
35353910c61610add5df138934caa2ad94c63daf
46,208
def get_most_common_elements(iterator): """Returns a generator containing a descending list of most common elements.""" if not isinstance(iterator, list): raise TypeError("iterator must be a list.") grouped = [(key, len(list(group))) for key, group in groupby(sorted(iterator))] return sorted(gr...
c259560a3ca8e8c2e8b0666a67f866a2a8c736c0
46,209
import starlette def build_starlette_request(scope, serialized_body: bytes): """Build and return a Starlette Request from ASGI payload. This function is intended to be used immediately before task invocation happens. """ # Simulates receiving HTTP body from TCP socket. In reality, the body has ...
76e7ed35ab1ecb8375696bcb474deeaec75a03dc
46,210
from typing import Mapping import os def expand_environment_variables(config): """Expand environment variables in a nested config dictionary This function will recursively search through any nested dictionaries and/or lists. Parameters ---------- config : dict, iterable, or str Input...
6990c5092ece4436e41e619f3c8f68dee066dbcd
46,211
import yaml def create_namespace_with_name_from_yaml(v1: CoreV1Api, name, yaml_manifest) -> str: """ Create a namespace with a specific name based on a yaml manifest. :param v1: CoreV1Api :param name: name :param yaml_manifest: an absolute path to file :return: str """ print(f"Create ...
11f06eabefdf3b8ba9c4354345896fed076b98a8
46,212
def sd_generate_state(model, n_steps, n_targets, init_state, birth, death, noise=True): """Generate synthetic data on target states Provide with a model, number of steps to generate, number of targets, initial state of each of the targets and the time of the birth and death of eac...
4b26ad19a565f5a105ca827f71aec22235a167b6
46,213
def value_of_ace(card_one, card_two): """Calculate the most advantageous value for the ace card. :param card_one, card_two: str - card dealt. See below for values. :return: int - either 1 or 11 value of the upcoming ace card. 1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10 2. 'A' (ace...
90ff26e76c116fd1cb803b56362d28aec1d642e4
46,214
from typing import Dict def autoapi_skip_member(app: Sphinx, what: str, name: str, obj: PythonPythonMapper, would_skip: bool, options: Dict): """Project specific skip function for AutoAPI.""" if '__init__' in name: return False return would_skip
9ec70eeec97c3713ac10f2beb27a63b96ecadb3f
46,215
async def post_settings(update: AdvancedSettingRequest) -> AdvancedSettingsResponse: """Update advanced setting (feature flag)""" try: await advanced_settings.set_adv_setting(update.id, update.value) except ValueError as e: raise LegacyErrorResponse(message=str(e)).as_error(status.HTTP_400_B...
ff558558089ccbdd9e5c94d0a2be5558fbcfe672
46,216
def safe_log10(data): """ A safe function for LOG10 in cases of too small values (close or equal to 0 ) """ prob_tmp = np.where(data > 1.0e-10, data, 1.0e-10) result = np.where(data > 1.0e-10, np.log10(prob_tmp), -10) return result
861030069dad485188d3b23750e6395b11ff4ff2
46,217
def offset(point, direction, distance=1): """Offsets a point in a given direction some distance, E.g. (0, 0) offset 'R' by 2 => (2, 0) Args: point (Point): the point to use for the offset point direction (str): a valid direction ('U', 'R', 'D' or 'L') distance (Optional[int]): the d...
3998cbb0bf2f4af3930677fd991967404a1c173d
46,218
def property_entropy(col, sim_matrix, bg_distr, seq_weights, gap_penalty=1): """Calculate the entropy of a column col relative to a partition of the amino acids. Similar to Mirny '99. sim_matrix and bg_distr are ignored, but could be used to define the sets. """ # Mirny and Shakn. '99 property_pa...
af8e4ded39ec68f7d9c282b327d8ed3245d70bb8
46,219
from re import T def set_p_to_zero(pvect, i): """ Provided utility function: given a symbolic vector of probabilities and an index 'i', set the probability of the i-th element to 0 and renormalize the probabilities so they sum to 1. """ new_pvect = T.set_subtensor(pvect[i], 0.) new_pvect =...
da7287606ed7e62c1c30adc165b74c6794da7c2b
46,220
import requests def get_cards(session: requests.sessions.Session, dni: str) -> list: """Returns cards list and details using the session provided.""" endpoint = GET_CARDS_ENDPOINT data = { "dni": dni, } json_response = session_post(session, endpoint, data) card_list = json_response["re...
f96d24149c481228e4edb39c6dbf633828adea8c
46,221
def define_systems(cube, verbose=True, MinNSpax=0, return_first=False, return_second=False): """ Args: cube: verbose: MinNSpax: Returns: """ #!..make sure that undefined variance pixels that are defined in the datacube have a dummy high value #WHER...
41c4f99ae7b5ceba95f9eabf8fa9bc7e2190ee72
46,222
def configure_i18n(app): """ ๅ›ฝ้™…ๅŒ–ๆ”ฏๆŒ. """ babel = Babel(app) @babel.localeselector def get_locale(): if has_request_context() and request: # Request a locale and save to session rl = request.args.get('_locale', None) if rl: accept_languages = ap...
a3fadcb4ef107e56bfd630ef0182115b7f9348b1
46,223
from datetime import datetime def process_articles_results(articles_results_list): """ Function that process the list of article from the request. """ articles_results = [] for individual_article in articles_results_list: title = individual_article.get('title') description = indivi...
0af29222fd77e742a1f59049877f2892fb57c6c0
46,224
import networkx import itertools import random def _compute_diagram_component(Primes, Update, Subspaces, EdgeData, Silent): """ Also computes the commitment diagram but without removing out-DAGs or considering connected components separately. Not meant for general use. Use compute_diagram(..) instead. ...
1d6a5c979bc40bfc8363e8dfc3d69df575fbd1a8
46,225
def translate_english_to_chinese(target_str): """ translate English to Chinese Args: target_str (str): target string """ translator = Translator(to_lang="chinese") result = translator.translate(target_str) return result
c6d78feff9d6c18b8966160775bb8ff4f2900ad2
46,226
def div(a,b): """Elementwise division with another vector, or with a scalar.""" if hasattr(b,'__iter__'): if len(a)!=len(b): raise RuntimeError('Vector dimensions not equal') return [ai/bi for ai,bi in zip(a,b)] else: return [ai/b for ai in a]
c12511e47a4366efc8d248b7abfac2eea02644c5
46,227
def part2(grid): """ A basin is all locations that eventually flow downward to a single low point. Therefore, every low point has a basin Locations of height 9 do not count as being in any basin All other locations will always be part of exactly one basin. The size of a basin is the number of lo...
7876ab48d5290654919f396b04b5146310d53b37
46,228
import re def normalize_twitter_hashtag(text): """hashtagใ‚’ๅ…ฑ้€šใฎๆ–‡ๅญ—ๅˆ—ใซ็ฝฎใๆ›ใˆใ‚‹๏ผˆๅซใ‚“ใงใ„ใ‚‹ใ“ใจใ‚’่กจใ—ใŸใ„๏ผ‰""" return re.sub(r"#\w+", "#hashtag", text)
bccff4f413732b5d401e5dd362b299998f707f1c
46,229
def get_market_price_change_by_ticker(fromdate: str, todate: str, market: str="KOSPI", adjusted: bool=True) -> DataFrame: """์ž…๋ ฅ๋œ ๊ธฐ๊ฐ„๋™์•ˆ์˜ ์ „ ์ข…๋ชฉ ์ˆ˜์ต๋ฅ  ๋ฐ˜ํ™˜ Args: fromdate (str ): ์กฐํšŒ ์‹œ์ž‘ ์ผ์ž (YYYYMMDD) todate (str ): ์กฐํšŒ ์ข…๋ฃŒ ์ผ์ž (YYYYMMDD) market (str , optional): ์กฐํšŒ ์‹œ์žฅ (KOSPI/...
0bb2775baef9436c19a8edbbd6f72aea212ca7a1
46,230
from typing import Optional def deserialize_environment_from_cluster(cluster: Cluster, path: Optional[ str] = None) -> Environment: # noqa, pylint: disable=line-too-long,bad-whitespace """Loads the environment from remote file....
6bc133c4ab5761320fbabd5c01b1aa4fe6a8e408
46,231
import scipy.signal as sig def filter(data, low=300, high=6000, rate=30000): """ Filter the data with a 3-pole Butterworth bandpass filter. This is used to remove LFP from the signal. Also reduces noise due to the decreased bandwidth. You will typically filter the raw data, then extract...
59801cbd04878a6a5049262c283e4d18b042a53d
46,232
def load_config(filepath: str) -> ConfigFile: """Load configuration Arguments: filepath {str} Returns: {ConfigFile} -- query parameters """ config = ConfigFile.from_filename(filepath) validate(config.content, config.version) return config
328907c370308369436e7ff55cd0a11ee5c55572
46,233
def szudzik_pair(pairs: np.ndarray) -> np.ndarray: """ Numpy implementation of a pairing function by Matthew Szudzik Args: pairs (np.ndarray): n x 2 integer array of pairs. Returns: hash_list (np.ndarray): n x 1 integer array of hashes. """ xy = np.array(pairs) x = xy[..., ...
5eaa4f9c8fd62f0409bf7e01e2609220c6f336cf
46,234
def relu(x): """ Compute the relu of x Arguments: x -- A scalar or numpy array of any size. Return: s -- relu(x) """ s = np.maximum(0,x) return s
9531d5cc64e4721d25482e0f5f3257d2255e2a5b
46,235
import os def SearchForExecutableOnPath(executable, path=None): """Tries to find all 'executable' in the directories listed in the PATH. This is mostly copied from distutils.spawn.find_executable() but with a few differences. It does not check the current directory for the executable. We only want to find ...
a21e97d3f1d90e11a594f5d712a236cf362e5aa8
46,236
import re import requests def get_enumeration_sparql(rq, v, endpoint, auth=None): """ Returns a list of enumerated values for variable 'v' in query 'rq' """ glogger.info('Retrieving enumeration for variable {}'.format(v)) vcodes = [] # tpattern_matcher = re.compile(".*(FROM\s+)?(?P<gnames>.*)\...
bfe59b7131ab74cf230e92ce6f2f609d7c0a76cd
46,237
def get_instance_id(finding): """ Given a finding, go find and return the corresponding AWS Instance ID :param finding: :return: """ for kv in finding['attributes']: if kv['key'] == 'INSTANCE_ID': return kv['value'] return None
f4f6826dc02664b95ca8fdc91d89a6429192b871
46,238
from typing import Optional def get_winning(process_id: int) -> Optional[list[Version]]: """Get a dict of the winning process versions per customer category. Format of dict: [{ 'customer_category': str, 'winning_version': Version.A or Version.B }] :param process_id: specify proces...
322299b7e28ca5429695d5b310b269853279f09e
46,239
def BackwardFoldScaleAxis(): """Backward fold axis scaling into weights of conv2d/dense. Returns ------- ret : tvm.relay.Pass The registered pass to backward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis as b...
dc9bb99fa02920a643c8fa59d4e08c29e4a3826f
46,240
def refresh(request): """Endpoint that'll use the database information to update running process""" ips_from_database = [x.ip for x in Machine.objects.all()] database_machines_found = LocalNetworkScanner().refresh(ips_from_database, PORTS) # if machine in database found on netowkr ips_from_fou...
ed0c28a1c02525c7396ee04cb9d92e7a10f1a349
46,241
def triple(subject, relation, obj): """Builds a simple triple in PyParsing that has a ``subject relation object`` format""" return And([Group(subject)(SUBJECT), relation(RELATION), Group(obj)(OBJECT)])
b4c3a1bf4192fbf7a5c0c155551633cd7eb34678
46,242
def get_article_sentiment(article): """ Extracts sentiment analysis for article. @param article: article dictionary (retrieved from the Data Lake) @returns: (article_level_polarity, article_level_subjectivity) """ if language_dict[article['media']] == 'DE': blob = TextBlobDE(article['tex...
d07fba0a706571d6e3f22793e99f3ae5890c995c
46,243
def frame_to_yaml_safe(frame): """ Convert a pandas DataFrame to a dictionary that will survive YAML serialization and re-conversion back to a DataFrame. Parameters ---------- frame : pandas.DataFrame Returns ------- safe : dict """ return {col: series_to_yaml_safe(series)...
f33f0ca3b0c4fe689639a99b2f4bf44fc06e9973
46,244
import sys def hgcmd(): """Return the command used to execute current hg This is different from hgexecutable() because on Windows we want to avoid things opening new shell windows like batch files, so we get either the python call or current executable. """ if mainfrozen(): if getattr...
a3a4a5356f85467156975e9b74d0805ab83cb8fb
46,245
def coach_or_competitor(username): """converts a string to bytes Args: username: the user whose should be checked Returns: renders the competiotr template if user is comeptitor or the coach one if coach """ if is_coach(username): print "This user is a coach" return...
98750b1cb80ee59c2481672350867b429e660746
46,246
def taint_name(rawtxt): """check the interface arguments""" tainted_input = str(rawtxt).lower() for test_username in get_user_list(): if tainted_input in test_username: return test_username return None
4407508960ddfcdd267ab427227db0d009183221
46,247
def cdlsticksandwich(opn, high, low, close): """Stick Sandwich๏ผš A stick sandwich is a technical trading pattern in which three candlesticks form what appears to resemble a sandwich on a trader's screen. Stick sandwiches will have the middle candlestick oppositely colored of the candlesticks on either s...
192f85c1de98f4095fad9a5d3a1cbc2d7df53e49
46,248
def sample_bounded_multicoal_tree(stree, n, T, leaf_counts=None, namefunc=None, sroot=None, sleaves=None, stimes=None, gene_counts=None): """ Returns a gene tree from a bounded multi-species coalescence process stree -- species tree ...
b5cc1bd53d86ef588ab36ebe0ffc54ed7e7e5e2b
46,249
def collect_inventory_license_expression(location, scancode=False): """ Read the inventory file at location and return a list of ABOUT objects without validation. The purpose of this is to speed up the process for `gen_license` command. """ abouts = [] if scancode: inventory = gen.load_...
cb2020b2e89aa2294d46fe890d846548e1f88b32
46,250
def node_hist_fig( node_color_distribution, title="Graph Node Distribution", width=400, height=300, top=60, left=25, bottom=60, right=25, bgcolor="rgb(240,240,240)", y_gridcolor="white", ): """Define the plotly plot representing the node histogram Parameters --------...
35ad64446612a98db6df49d364679d0a890eca1e
46,251
def analytic_solution_modes(dx, p, nx, ny, x, y, c, t, n): """ Analytic solution for acoustic modes in 2D rectangular domains. :param dx spatial step after discretization, scalar (m). :param p numerical acoustic pressure used for the sizes, 2D-array (Pa). :param nx mode number (...
b2b69cb4bb8b4a827cbb8818750a9f86e0c33773
46,252
from typing import Dict def encode_images(format_dict: Dict) -> Dict[str, str]: """b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ...
c1dd645767d272a257cdd257d9854c2abad82353
46,253
import os def initialise_fleet_data(fleet_file_path=None, reset=False): """ Uses the provided file path to load the fleet file csv file. If no fleet file is found we return false. Reset=True Remove all records and replace with this file. Reset=False Add these fleet entries to the fleet table. ...
9c961014ff8a25bc5d9e5c3f9fbd9b8244b179b2
46,254
def read_catl(path_to_file): """ Reads survey catalog from file Parameters ---------- path_to_file: `string` Path to survey catalog file survey: `string` Name of survey Returns --------- catl: `pandas.DataFrame` Survey catalog with grpcz, abs rmag and stell...
6013689b4d6f8558dba11cac5ece8d41bd38da8c
46,255
def deconv(in_planes, out_planes, upscale_factor=2): """2d deconv""" kernel_size, stride, opad = get_deconv_params(upscale_factor) # print("DECONV", kernel_size, stride, opad) return nn.ConvTranspose2d(in_planes, out_planes, kernel_size=kernel_size, ...
7b1f32915aee14b64564c92e20cb372935b3c759
46,256
import types def OR(r1, r2): """Or/Union Equates to union (both relations have same heading) """ if r1.heading() != r2.heading(): raise RelationInvalidOperationException(r1, "OR can only handle same reltypes so far: %s" % str(r2._heading)) #assert r1._heading == r2._heading, "OR can onl...
2a430a721904382ea313609916199a3d63f5fdf2
46,257
from cntk.cntk_py import bernoulli_random_like def bernoulli_like(x, mean=0.5, seed=auto_select, name=''): """bernoulli_like(x, mean=0.5, seed=auto_select, name='') Generates samples from the Bernoulli distribution with success probability `mean`. Args: x: cntk variable (input, output, parameter,...
943804bcb7725533242fa674c7357b9b56cc0655
46,258
def dVdc_calc(Vdc,Ppv,S,C): """Calculate derivative of Vdc""" dVdc = (Ppv - S.real)/(Vdc*C) return dVdc
59d2708726e078efb74efce0bac2e397ba846d89
46,259
def percentile_spectrogram(spg, f_axis, rank_freqs=(8., 12.), pct=(0, 25, 50, 75), sum_log_power=True, show=True): """ Compute percentile power spectra using the spectrogram, ranked by power within a specific band. Essentially a different way of visualizing correlation between freqs. Parameters -------...
44154d001479b82b14d4b9e794b56f49500ec4bf
46,260
import math def _get_cold_progression(age, rng, carefulness, preexisting_conditions, really_sick, extremely_sick): """ [summary] Args: age ([type]): [description] rng ([type]): [description] carefulness ([type]): [description] preexisting_conditions ([type]): [description]...
6fad1e52bddba28ca4045ed79e8838441ec32483
46,261
def project_to_image_space(anchors, stereo_calib_p2, image_shape): """ Projects 3D anchors into image space Args: anchors: list of anchors in anchor format N x [x, y, z, dim_x, dim_y, dim_z] stereo_calib_p2: stereo camera calibration p2 matrix image_shape: dimensions of ...
927267f0c4a75a5fdf5f0f52456c7e7ac48931f7
46,262
def define_model(quant_features, qual_features): """Define model Args: quant_features (list of str): corresponding to column names of training data qual_features (list of str): corresponding to column names of training data Returns: model (sklearn obj) """ # transf...
6cb132f0c7d58655afd8f3779712e62e8842bdef
46,263
def check_order(df, topcol, basecol, raise_error=True): """ Check that all rows are either depth ordered or elevation_ordered. Returns 'elevation' or 'depth'. """ assert basecol in df.columns, f'`basecol` {basecol} not present in {df.columns}' if (df[topcol] > df[basecol]).all(): return...
9b4e7b9938bb2fe14ab99d5c111883a0f6d73337
46,264
import os def environment(request): """ A JavaScript snippet that initializes the environment """ # Capture all REACT_APP_ variables into a dictionary for context environment = { k: v for k, v in os.environ.items() if k.startswith('REACT_APP_') } # Add Environment ...
39969dfc161f5009c081aa200665f57c6e68a4fa
46,265
import os import pickle def search(results_path, network_type, num_layers, num_neurons, batch_size, num_epochs, training_method, regularization): """Search relevant files. based on input arguments and return a list of filename Parameters ---------- results_path : string ...
db6f7d79fb9e4b8998f5eb6e39e82cd2db2222a9
46,266
async def list_keys(hub, ctx, name, resource_group, **kwargs): """ .. versionadded:: 2.0.0 Retrieve a Redis cache's access keys. This operation requires write permission to the cache resource. :param name: The name of the Redis cache. :param resource_group: The name of the resource group. CL...
410ee854ae90de02f1b41dc32eaccd74d202462e
46,267
from typing import Tuple def new_simple_controller_config( config: dict = None, options: dict = None, config_from_file=False, serial_number="1111", devices: Tuple[pv.VeraDevice, ...] = (), scenes: Tuple[pv.VeraScene, ...] = (), setup_callback: SetupCallback = None, ) -> ControllerConfig: ...
8353cc001d7527afeb475e7b293812df7adf26e9
46,268
import torch def online_mean_and_std(loader): """Compute the mean and sd in an online fashion Var[x] = E[X^2] - E^2[X] """ cnt = 0 fst_moment = torch.empty(3) snd_moment = torch.empty(3) for x, y in loader: b, c, h, w = x.shape nb_pixels = b * h * w sum_ = to...
25479de7b88385d0714e3bf26ce6cbb151bf04f1
46,269
def GetDevice(serial=None): """Returns and ADBDevice given its serial. The first connected device is returned if serial is None. """ devices = [d for d in ListDevices() if not serial or serial == d.serial] return devices[0] if devices else None
ccf6451aa48b98efba03be4fa4438920b0fc5374
46,270
def api_demo_data_project(): # noqa: F401 """Get info on the article""" subset = request.args.get('subset', None) if subset == "plugin": result_datasets = get_dataset_metadata(exclude="builtin") elif subset == "test": result_datasets = get_dataset_metadata(include="builtin") else:...
ca63c2803d9e0720cde7142eef8074bbef3eec40
46,271
import argparse def parse_args(): """set and check parameters.""" parser = argparse.ArgumentParser() parser.add_argument("--result_path", type=str, default="", help="root path of predicted images") args_opt = parser.parse_args() return args_opt
9d417966f4ec71f9e25f16c88a8178dc519686b8
46,272
def nonmax_supression(x): """Nonmaximum suppression finds crests of a signal. All other non-maxima found from thresholding are suppressed. Args: x (1D numpy array): a signal which has been thresholded to only contain maximum peaks. Returns: 1D numpy array: an array indexes ...
cee150df2fb53dc8ad2fd1a0949dcf2e81608588
46,273
def pyth_backward_induction(num_periods, max_states_period, periods_draws_emax, num_draws_emax, states_number_period, periods_payoffs_systematic, edu_max, edu_start, mapping_state_idx, states_all, delta, is_debug, is_interpolated, num_points_interp, shocks_cholesky): """ Backward induction p...
1ce52bb3059dfa61e2a6b04bb84716ccdecf1c07
46,274
def ipv4_subnet_details(addr, mask): """ Function that prints the subnet related details- Network, Broadcast, Host IP range and number of host addresses :param addr: IP address :param mask: subnet mask :return: result dictionary containing the details """ network_address = [] broadcast_a...
7d872a63b9a0968eabbe9af7ccfbfda311346bc8
46,275
def _get_sdk_name(platform): """Returns the SDK name for the provided platform. Args: platform: The `apple_platform` value describing the target platform. Returns: A `string` value representing the SDK name. """ return platform.name_in_plist.lower()
0bc7f446472f44e52ea0b11cda7397e48848f0ef
46,276
def myplus(a, b=0): """ Parameters ---------- a : float the first number b : float the second number defaults to zero Returns ------- a + b """ return a + b
c9efbff1babaae75c51401f56d830e8b7a543286
46,277
def read_data_from_fp_numpy(fp): """ Read the data from a single Silixa xml file. Using a simple approach Parameters ---------- fp : file, str, or pathlib.Path File path Returns ------- data : ndarray The data of the file as numpy array of shape (nx, ncols) Notes ...
5b06e049df52abd262add9e1f449a1317df2d67e
46,278
import tqdm def schedule_jobs( fns, concurrency=DEFAULT_THREADS, progress=None, total=None, green=False ): """ Given a list of functions, execute them concurrently until all complete. fns: iterable of functions concurrency: number of threads progress: Falsey (no progress), String: Progress + ...
b4ae40ba37709f7f323b9dcf6bfa7ffce174fa9e
46,279
def Hamming_bit_decoder(N,kind='bit',read=True,name='decoder'): """Hamming Gate resistant to bit-fips""" circ=HammingCircuit(N, ancillas=N) if kind=='phase': circ.h([*range(2**N)]) circ.append(syndrome(N),[*range(2**N+N)]) circ.append(apply_syndrome(N),[*range(2**N+N)]) if read==True: ci...
9b9e44d1708c57b7c218fe4b5f1e66928942ab30
46,280
import re def _does_string_pass_simple_jndi_regex(input_string: str) -> bool: """Returns True/False if string contains at least one JNDI match, based on a simple regex""" result = re.search(SIMPLE_JNDI_REGEX_PATTERN, input_string) if result: logger.debug(f"String passes simple JNDI regex: `{input_...
35749a404027fb8aca9006956a8421646f4f4f66
46,281
def KeycodeToDIK(keycode): """ Convert a (Tkinter) keycode to a DirectInput Key code If not in table, return keycode as hex """ _res = f'0x{keycode:02x}' for dik, entry in DirectInputKeyCodeTable.items(): if entry[1] == keycode: _res = dik break return _res
608931cae3f47b80b9048aa5532d0b6fb95a8719
46,282
import logging def tts_request(announcement="Text to speech example announcement!") ->str: """Test function to check that the text to speech is working appropriately""" engine = pyttsx3.init() engine.say(announcement) engine.runAndWait() logging.info('tts test run') return "Hello text-to-speec...
24e6b9680dc8e6d3160995d690b9b16defbe52a0
46,283
from typing import List import random def roll_relationships(relationship_points: int, min_icons: int) -> List[IconRelationship]: """ :param relationship_points: How many points are spent to relationship. :param min_icons: Minimum number of different icons to have a relationship to. :...
d951fa6676c8db9bbf3213379aa824d83fd96a12
46,284
import re def ALMAUVFITSTab(inUV, filename, outDisk, err, \ exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \ include=[], logfile=""): """ Write Tables on UV data as FITS file Write Tables from a UV data set (but no data) as a FITAB format file His...
54ffa1a38b8ae37949b2e2ae9b92eea7ba9f7316
46,285
def create_children(input_node, node_holder, max_frag=0, smiles=None, log_file=None, recurse=True): """ Create a series of edges from an input molecule. Iteratively :param input_node: :param max_frag: Max initial fragments (or no limit if 0) :param smiles: A SMILES string, for log/diagnostics only. ...
fe36b1b81fc7668498f8da318a9864b31a272a70
46,286
import re def typify(node): """Convert the input into the appropriate type of ExpressionBase-derived Node. Will apply pattern matching to determine if a passed string looks like a numerical constant or if the input is a numerical constant, return the appropriate node type. Parameters ...
4024effbe9176acc10cdf25ce398b6cb2826b8ba
46,287
import pathlib def file_exists(file_path): """ Returns true if file exists, false if it doesnt """ file = pathlib.Path(file_path) return file.is_file()
d8219f71cf891d2d4e9c95670bd90b957becfdc5
46,288
import hashlib import json def hasher(obj): """Returns non-cryptographic hash of a JSON-serializable object.""" h = hashlib.md5(json.dumps(obj).encode()) return h.hexdigest()
967ba4a1513bbe4a191900458dfce7a1001a8125
46,289
def long_word_pct(df): """ Get percentage of long words. Long words are defined as having more than 8 chars. Needs features: Words Adds features: Long_word_percent: percentage of long words :param: the dataframe with the dataset :returns: the dataframe with the added f...
2d80ea6e93f70ac2d5d68d472a75c0a1b13d6dee
46,290
def check_answer(question_id, answers_list): """ Check answers for question. Convert answers to boolean values for comparing with correct answers. Answer wil get point if correct, not empty and all correct choices was chosen. @param question_id: Question object id --> int @param answers_list: ...
a092646d38e608f88b3191368dcf23c5770323e6
46,291
def _to_float(expr): """Converts a sympy expression to a Python float The given expression must be a sympy ``Number`` isinstance, or ValueError will be raised. """ res = expr.evalf() if isinstance(res, Number): return float(res) else: raise ValueError( 'Expressi...
cb0a0fbca7410d4d32c003e29f86b946a84d69e6
46,292
def atom_count(gra, dummy=False, with_implicit=True): """ count the number of atoms in this molecule by default, this includes implicit hydrogens and excludes dummy atoms """ if not dummy: gra = without_dummy_atoms(gra) natms = len(atoms(gra)) if with_implicit: atm_imp_hyd_vlc_d...
66ff22f6ff7785200ecca8f20bc1247120bb565a
46,293
import numpy def isstarboard(ctx, scene, node1, node2): """ Returns True if node1 is on the right of node2 based on a view matrix calculated from the 'face' of node 2. For node1 to be on the right of node2: - node2 to must be considered to have a front face. - the view transformed...
f4d545ce98ae032d3116b814e3470b5fc514659e
46,294
import glob def get_tls_path(opts, id_type, namespace, release): """Get path to the directory containing TLS materials for a node Args: opts (dict): Nephos options dict. id_type (str): Type of ID we use. namespace (str): Name of namespace. release (str): Nam...
cf4c35163e5852109deed7aa7aa611b41b7a9e54
46,295
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except TypeError: try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: ...
267f6242b5e0c901c30ebaa01b2c39472d3ae07e
46,296
def _root_sort_key(root): """ Allow root comparison when sorting. Args: root (str or re.Pattern): Root. Returns: str: Comparable root string. """ try: return root.pattern except AttributeError: return root
51a7e51b58cbdf8c3277844903950282a5368815
46,297
from medis.Telescope.coronagraph import apodization def optics_propagate(empty_lamda, grid_size, PASSVALUE): """ #TODO pass complex datacube for photon phases propagates instantaneous complex E-field through the optical system in loop over wavelength range this function is called as a 'prescription'...
0f286ceff8027564b553851412c79ee056841507
46,298
def get_layer(keras_tensor): """ Returns the corresponding layer to a keras tensor. """ layer = keras_tensor._keras_history[0] return layer
6b3c950d9bf9c81895c4e7d4d436cd48359143bd
46,299