content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def plot_rolling_beta(returns, factor_returns, legend_loc='best', ax=None, **kwargs): """ Plots the rolling 6-month and 12-month beta versus date. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in...
a8f027c0b54260fed4109e20f7a8d0bc8641bf38
57,200
def is_s3(url: str) -> bool: """Predicate to determine if a url is an S3 endpoint.""" return url is not None and url.lower().startswith('s3')
f1e36654ae86057fb4ae73a90648095119f1b5af
57,201
def C2K(degC): """degC -> degK""" return degC+273.15
877f52078bd0da13cd21a8665a6c89cc0fa90848
57,202
def check_binary_covariates(execution_context, covariate_ids): """Check the dichotomous value from shared.covariate to check if the covariate is binary. If it is, make sure the assigned value is only 0 or 1. """ is_binary = dict() for covariate_id in covariate_ids: result_df = ezfuncs.query(...
d2f3fa8b00769283c3409c94bea1be04ab343082
57,203
import os def load_gifs(): """Return list of `Gif` objects.""" gifs = [] for fn in os.listdir(GIF_DIR): if fn.lower().endswith('.gif'): name = os.path.splitext(fn)[0] path = os.path.join(GIF_DIR, fn) icon = thumbs.thumbnail(path) url = os.path.join(G...
592f1cfbc85b0ad6a5b4cb6fa8b2b93b18b8ff28
57,204
def validate_params(parameters): """Takes a list of parameters from a HTTP request and validates them Returns a string of errors (or empty string) and a list of params """ # Initialize error and params error_response = '' params = {} # City if (parameters.get('address') and ...
fc3ea41010b3eb213cce4dc18ab8f108eb51cda7
57,205
def get_dict_2d_result(macro_strategy_sec_id_list_map, macro_strategy_dict): """ 整合数据到规定的结构 Usage: >>> macro_strategy_sec_id_list_map = [{'record_type': 'win_rates', 'a_share': 'att_00000115'}, >>> {'record_type': 'assessment', 'a_share': 'att_00000116'}, >>> {'record_type': 'depl...
eb1ecf27547f16721490cf617bdc5d140bbfd5d9
57,206
def generate_module_selector_keyboard(language: str) -> ReplyKeyboardMarkup: """Create an return an instance of `module_selector_keyboard` **Keyword arguments:** - language (str) -- The desired language to generate labels **Returns:** ReplyKeyboardMarkup instance """ return ( Re...
8440d4984533a525261a9ad3798234082a67bb75
57,207
def menu(layout: Layout) -> dict: """ Layout menu This method takes a Layout class object as an argument and presents the user with a suite of options in a command line interface (CLI). The options include the generation technical documentation for the layout, or validation of a csv file, with ...
b66dfc37c152f052b0a4f463990d6d17084c9bdf
57,208
def parseargs(p): """ Add arguments and `func` to `p`. :param p: ArgumentParser :return: ArgumentParser """ p.set_defaults(func=func) p.description = "Create the DIRECTORY(ies), if they do not already " + "exist." p.add_argument("directory", nargs="+") p.add_argument( "-p",...
a95766b51c743de467bc7bba2de0f7b536a7c9bb
57,209
import sys import os def find_exe(name): """Finds an executable first in the virtualenv if available, otherwise falls back to the global name. """ if hasattr(sys, 'real_prefix'): path = os.path.join(sys.prefix, 'bin', name) if os.path.isfile(path): return path return na...
57837a0dd5a329441b5f7ab717c94a998d3fe9a7
57,210
def cfn_context(): """ Context object, blank for now """ return ""
a71bffc39ce00e00236667040feb156bb9a4f9a2
57,211
import argparse def parse_rows(rows, select_user=None): """Parse spreadsheet user/project data into User and Project classes Expects 'rows' to include all rows, with row 0 being the header row Returns a dictionary of projects keyed by project name, and a list of rows that were not blank but faile...
8463818aa01eacdc7bababfbce10bd0769ab0d8c
57,212
import re def parse_to_query_term_list(str_query): """ Take a string and parse the field names and field data clauses to q list of SolrQueryTerms NOTE: this is only used by testSearchSyntax to produce term_lists! >>> str = "dreams_xml:mother AND father AND authors:David Tuckett A...
84d7e15afa9f04621f3f47d8ca84c202e59468f3
57,213
def ws_message_event_fixture(ws_message_event_data): """Define a fixture to represent an event response.""" return { "data": ws_message_event_data, "datacontenttype": "application/json", "id": "id:16803409109", "source": "messagequeue", "specversion": "1.0", "time...
a99b4987712c4aac350c7b712642cf5c690261dd
57,214
def hello_world(): """Just an empty route with a string.""" return "Hello there. This route doesn't do anything."
f6dcaa52d51aab51234f51b4f7a46e6e55aeb524
57,215
def load_data_and_labels(one_data_file, two_data_file, three_data_file, five_data_file, eight_data_file, thirteen_data_file, twentyone_data_file): """ Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. """ # Load data from files ...
d3976424229344cf751fdaaa730e5546de1aa09c
57,216
def dict2tsv(condDict): """Convert a dict into TSV format.""" string = str() for i in condDict: string += i + "\t" + "{%f, %f}" % condDict[i] + "\n" return string
c73f8e3158ade699cc4589d541f05397f559d190
57,217
def choose_by_idc(dest_idc, local_idc, ips): """ net.choose_by_idc(dest_idc, my_idc, ip_list) :param dest_idc: is a string representing an IDC where the ips in `ip_list` is. :param local_idc: is a string representing the IDC where the function is running. :param ips: is a list of ip in the `dest_idc...
0878ce74f45f03f5a89b903a76a259c65194eb9a
57,218
import os def _load_data(filenames): """ Load data from all HDF5 file and combine them into arrays. Parameters ---------- filenames : list List of names of the files that are to be combined. Returns ------- X : ndarray Features of the spectra. y : ndarray ...
4552487165dff19b0dd64504c032377426d05e22
57,219
def statuses_retweeters_ids(auth, **params): """ Returns a collection of up to 100 user IDs belonging to users who have retweeted the tweet specified by the id parameter. """ maxitems = params.pop("maxitems", 0) if maxitems > 0: return cursor_iter(statuses_retweeters_ids, maxitems, auth...
eac656d1927725c3055a9f789109e9b7e452ff3d
57,220
def _get_s3_arn_given_smb_file_share(smb_file_share_arn: str) -> str: """ Return S3 ARN associated with a named SMB file share ARN """ s3_arn = '' client = boto3.client('storagegateway') for file_share in client.describe_smb_file_shares(FileShareARNList=[smb_file_share_arn])['SMBFileShareInfoList']: ...
39b57ca85d47b7a5ca95488940c0aea2b72c9923
57,221
import os def createSegmentSpecificPath(path, gpPrefix, segment): """ Create a segment specific path for the given gpPrefix and segment @param gpPrefix a string used to prefix directory names @param segment a GpDB value """ return os.path.join(path, '%s%d' % (gpPrefix, segment.getSegmentConte...
999ce16e3ce4d3923bd22d871a27655bd64d91af
57,222
def rescale_score_by_abs(score, max_score, min_score): """ Normalize the relevance value (=score), accordingly to the extremal relevance values (max_score and min_score), for visualization with a diverging colormap. i.e. rescale positive relevance to the range [0.5, 1.0], and negative relevance to the ...
fe1df85166bb6ab34f6f30d06003d7946a92138e
57,223
def calculate_percentile_rank(array, score): """Get a school score's percentile rank from an array of cohort scores.""" true_false_array = [value <= score for value in array] if len(true_false_array) == 0: return raw_rank = float(sum(true_false_array)) / len(true_false_array) return int(roun...
bfdc64168c10d00c33294bf05851982e0712e230
57,224
def create_histogram(samples): """Returns a pair of arrays (values,counts), where size(values)=size(counts), corresponding to the (sorted) unique values seen in the sample along with the number of times they appear.""" samples.sort() values=[] counts=[] counter=None prev=None for sam...
5e559bf4e83bffd379828e1fc78df20505143e49
57,225
def string_interleave(s1, s2): """Interleave a character from a small string to a big string Args: s1 (str): input string s2 (str): input string Returns: (str): the string that already interleave Raises: TypeError: if s1 or s2 is not a string Examples: >>> str...
be0765a3822c657999e3223ae5adcddaa0bb4ed6
57,226
def season_acquire(month: str) -> str: """ Chose the season that correspond with the month :param month: The month when the animation starts to broadcast :return: Corresponding season """ if month in ('1', '2', '3', '01', '02', '03'): season = '01-Winter' if month in ('4', '5', '6', '04...
65c45726037f9bfb8ca17d4cc81e5eda8b6f4e5c
57,227
def add_default_processor(xml_tree, processor_name): """ Add processor to lqn-model tree. :param xml_tree: lqn-model tree :param processor_name: string :return: Created processor """ processor = add_processor_element(xml_tree, processor_name=processor_name) task = add_task_to_processor(p...
ab9f8cd81602bea1bb4f781ee5a91f49f04a1a33
57,228
def set_window(pixel_array, window_level, window_width): """Sets the window level and width for the image""" scale_img = np.array(pixel_array) # Getting low and high values low = window_level - window_width/2 high = window_level + window_width/2 def bin_function(i, window_level, window_width, high, low): ...
295bddb3317990034f8d194889eaf736346f8276
57,229
import gc import os def get_fold_data(folder, validation_as_test=False, train_only=False, store_pickle_after_read=True, read_from_pickle=True): """ Returns data from a fold folder (letor format) """ # clear any previous datasets gc.collect() train_read = False test_read ...
c7932cf06aeed8d87c348de655af260f0ce07b1b
57,230
def find_conjugated_systems(atoms, res_names): """Finds conjugated systems within a BioPython residue object, and returns them as individual customized BioPython Residue objects. Parameters --------- atoms: array-like List of atoms in the residue res_names: arary-like List of al...
5fe37c498866bdf7fbb0b033a1f18d68bfa9a9a5
57,231
import os def model_fn_builder(config: NeatConfig): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging....
5e79d1c6b1f9e6113a2b5c6802aac74ebf3116d8
57,232
def sym_reflection(Rp, semi_a, phase, Ab): """Symmetric reflection component of the phase curve. Args: Rp (float): radius of the planet in m a (float): semi major axis of the planet in m phase (array): phase angles of the planet in radians Ag (float): geometric albedo of the planet Returns: array, normal...
50ee27c6b49f63fe24a23d3ba2cc8a42763c22ac
57,233
import os async def get_file_from_s3(s3_client, es_client: ElasticsearchConnector, file_name): """ Gets a file from a Cortx S3 bucket and uploads it to slack Parameters ---------- s3_client : botocore.client.S3 A low-level client representing Cortx Simple Storage Service (S3) es_client :...
55cbf98c0b42e74026b21372eb23d82ef7e6359d
57,234
import ctypes def getHistogram(values, bins): """ Build an histogram counting the occurences of `values' in the `len(bins) - 1' intervals of values in `bins'. Parameters ---------- values : float array-like Values to count. bins : float array-like Limits of the bins. ...
2fba87b7f4b2697e8d75e977ae6cc165cfd23e7c
57,235
from typing import Callable import torch def mc_dropout_max_entropy(classifier: BaseEstimator, X: modALinput, n_instances: int = 1, random_tie_break: bool = False, dropout_layer_indexes: list = [], num_cycles: int = 50, sample_per_forward_pass: int = 1000, ...
a3768021b9c3b0c9e513e3b276467057e2e0170c
57,236
def plot_map( ds, hist=True, label=None, coarsen=0, extent=[-180 + 1e-3, 180 - 1e-3, - 60 + 1e-3, 90 - 1e-3], histogram_placement=[0.04, 0.15, 0.23, 0.3], ax=None, figsize=(14, 7), subplot_kw={}, cbar_kw={}, hist_kw={}, **kw...
9f4e077036b56cc8b8bb3f7a40a5d289e0c43d13
57,237
def make_plots(data, env, run='run_name', condition='param_run'): """ Make plots by second, timestep, and episode """ figure, axes = plt.subplots(ncols=3, nrows=1, figsize=(3 * 6, 6)) # plot episodes plot1 = plot_data( data, 'Smoothed_total_reward', 'Iteration', run, condition,...
d31f41b1be8526042045bcfd14f13a454e6833c6
57,238
def incident_priority_select_block( db_session: Session, initial_option: IncidentPriority = None, project_id: int = None ): """Builds the incident priority select block.""" incident_priority_options = [] for incident_priority in incident_priority_service.get_all_enabled( db_session=db_session, p...
3b1a72c705575058c30fa3fa8bb9f9855011b603
57,239
def gen_fm_track(N, f0, df): """ Generate a Frequency-Modulated sinusoid in the presence of noise, to test instantaneous-frequency tracking code Parameters ---------- N : int Number of samples to generate f0 : float Center frequency of sinusoid to generate (in normal...
392414388fb480d5a119a565407ab8edf57990bb
57,240
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificty). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positive ...
b161c4593da7e850b3344925b97ca37e6319b6d1
57,241
def add_time_to_time(time1, time2, result_format='number', exclude_millis=False): """Adds time to another time and returns the resulting time. Arguments: - ``time1:`` First time in one of the supported `time formats`. - ``time2:`` Second time in one of the support...
b736c49eea1ae941f7d195f5ab88e9c5548fbea1
57,242
def mase(y, y_hat, y_train, seasonality=1): """ Calculates the M4 Mean Absolute Scaled Error. MASE measures the relative prediction accuracy of a forecasting method by comparinng the mean absolute errors of the prediction and the true value against the mean absolute errors of the seasonal naiv...
13eb9ef5a63f19f3bdd0ff6d702985de80975a38
57,243
def get_first_value(param, param_pools, on_missing=None, error=True): """ Get the value for a particular parameter from the first pool in the provided priority list of parameter pools. :param str param: Name of parameter for which to determine/fetch value. :param Sequence[Mapping[str, object]] para...
a863b6edb06f127337f2bc22676aee7b03ca1d85
57,244
def deep_sort(data): """ In-place sort of any lists in a nested dict/list datastructure. """ if isinstance(data, list): data.sort() for item in data: deep_sort(item) elif isinstance(data, dict): for item in data.itervalues(): deep_sort(item) return None
2d97b4d83ae444b20047c8f4b0eccfb3996e4ae9
57,245
def fidelity_est(testSignals): """ Estimate the optimal fidelity by estimating the probability distributions. """ rangeMin = np.min(testSignals) rangeMax = np.max(testSignals) groundProb = np.histogram(testSignals[::2], bins=100, range=(rangeMin, rangeMax), density=True)[0] excitedProb, binEdges = np.histogram(...
39e7f4e38ab627610c9db5781d05deccd199009e
57,246
from ..forward.phonon import computeSQESet, kelvin2mev def sqe2dos(sqe, T, Ecutoff, elastic_E_cutoff, M, initdos=None, update_weights=None): """ Given a single-phonon SQE, compute DOS The basic procedure is * construct an initial guess of DOS * use this DOS to compute 1-phonon SQE * for bo...
bcbcb8e1be76c14729633f20a4c6b772ee647c73
57,247
def _one_recursive_step( list_pair, size_task, current_doubled_size_task): """ """ i = 0 j = 0 a_list = list_pair[:size_task] b_list = list_pair[size_task:] c_list = [] for k in range(current_doubled_size_task): #print 'i',i, 'j', j, 'size_task', size_task ...
ae0fe3440b8af38730de80fde4762f3c7fa94623
57,248
import os import pandas as pd def concatenate_tables_vertically(tables, output_csv_file=None): """ Vertically concatenate multiple table files or pandas DataFrames with the same column names and store as a csv table. Parameters ---------- tables : list of table files or pandas DataFrames ...
34359acfed85f1d7aea4de9bc2fe47de7fed36f9
57,249
def getTotalCountFilteredSubreddit(keyword): """ docstring """ try: connection = postgresqlConnection.createConnectionToDatabase() cursor = connection.cursor() create_table_query = f'''select count(*) from subreddits where topicTitle like '%{keyword}%' ''' cursor.execut...
0a144f2aa2ec0d0e376c0a120de69634ac6d94dd
57,250
def list_histogram(data: list, color="b", title="Histogram of element frequency.", x_label="", y_label="Frequency", fig_name="hist.png", mute=False): """ :param data: the origin list :param color: color of the histogram bars :param title: bottom title of the histogram :param x_label: label of x axis...
b63bb54a70c96276a3cb5ebfd9a18c99cab67d4b
57,251
def make_delay(delay): """ Create a delay event with a given delay. See also Sequence.addBlock """ if (not np.isfinite(delay)) or (delay <= 0): raise ValueError('Delay (' + str(delay*1e3) + 'ms) is invalid.') return Delay('delay', delay)
45cc382c64ce430181049dd90b0c56b361cec7b4
57,252
def get_rules(rulesdir, ignore_rules): """Get rules""" rules = RulesCollection(ignore_rules) rules_dirs = [DEFAULT_RULESDIR] + rulesdir try: for rules_dir in rules_dirs: rules.extend( RulesCollection.create_from_directory(rules_dir)) except OSError as e: L...
302ca9272c0b8e9a9bf231e6619dd3156eaf0d78
57,253
def detector_model_specialised(p, parameters): """ Detector model, specialised for use with emcee """ (varying_parameters, Y0, variable_parameters, radon_concentration_timeseries) = unpack_parameters(p, parameters) parameters.update(varying_parameters) # link recoil probability to screen...
59ee008d9ddde43d0265901b3af294cac734285c
57,254
def _get_edges(data, pad_length, mode='extrapolate', extrapolate_window=None, **pad_kwargs): """ Provides the left and right edges for padding data. Parameters ---------- data : array-like The array of the data. pad_length : int The number of points to add to the left and right ...
03c45a0ff4321370610643eb39e4e15ef8037048
57,255
async def async_handle_message(hass, config, request, context=None): """Handle incoming API messages.""" assert request[API_DIRECTIVE][API_HEADER]['payloadVersion'] == '3' if context is None: context = ha.Context() # Read head data request = request[API_DIRECTIVE] namespace = request[A...
fff43a12ec0b1ca2bb42a061de259a351da6e023
57,256
import numpy def hermitian_conjugated(operator): """Return Hermitian conjugate of operator.""" # Handle FermionOperator if isinstance(operator, FermionOperator): conjugate_operator = FermionOperator() for term, coefficient in operator.terms.items(): conjugate_term = tuple([(ten...
a5b89beff70ef03c8cd1615f61194634b1ef4d78
57,257
def tria_compute_rotated_f(tria, vfunc): """ Compute function whose level sets are orthgonal to the ones of vfunc. Inputs: v vertices t triangles vfunc scalar function at triangles Outputs: vfunc rotated function This is done by r...
fbdaaa319244b4cdf95161b8607f49245840c91d
57,258
def preproc_eyetribe_data(sam, msg, blink_gap=6, blink_interp=BLINK_INTERP): """ Preprocess EyeTribe gaze and pupil data from a single participant dataset """ BLINK_THRESH = 0.00001 # Drop blinks (set to NaN) # Note that blink gap is specified in #samples, not ms! blinks = (sam.pa < BLINK_T...
8c4407cd347ae01f2122ee9760b95338f3e8b7fa
57,259
import numpy def ndarray_to_imagedatadict(nparr): """ Convert the numpy array nparr into a suitable ImageList entry dictionary. Returns a dictionary with the appropriate Data, DataType, PixelDepth to be inserted into a dm3 tag dictionary and written to a file. """ ret = {} dm_type = None ...
1d4e1fd30d36811798872f385d2ebc23ebc53626
57,260
def view_color_histogram(image): """ Args: View the histogram of a color image image: Float array of the image Returns: Hist and its bin array """ hist_all = [] for i in range(image.shape[2]): hist, bins = np.histogram(image[:, :, i].ravel(), 256, [0, 256]) # Convert to ...
97249a8f67ad11d963c67118054773dcef516232
57,261
def load_sample_image(image_name): """Load the numpy array of a single sample image. Read more in the :ref:`User Guide <sample_images>`. Parameters ---------- image_name : {`china.jpg`, `flower.jpg`} The name of the sample image loaded Returns ------- img : 3D array Th...
5e95cd808ada569e2741292ee93f2bf0d42b5d98
57,262
from typing import Dict def angry_expression(misty: Misty) -> Dict: """Misty expresses anger. Args: misty (Misty): The Misty to perform the expression. Returns: Dict: The dictionary with `"overall_success"` key (bool) and keys for every action performed (dictionarised Misty2pyResponse). ...
238a5c9c9e5e0422f2685b3aa0f5145cfda43c19
57,263
import sys import os import json def convert_to_tfrecord(logger, config, data_set, cmvn, is_debug=False): """ :param is_debug: :param cmvn: :param config: :param data_set: :param logger: raw_files: $raw_files.adc: speech list, $raw_files.tra: transcription list tag: String that will be added onto the...
21245ff91923743dc98f0b8cf449a97ef54b5ac4
57,264
def getListParameters(request, list_index): """Retrieves, converts and validates values for one list Args: list_index, int: which list to get the values for. (there may be multiple lists on one page, which are multiplexed by an integer.) Returns: a dictionary of str -> str. field name -> f...
31bab6aed6ab2d39690df064804a9409edf6a268
57,265
def _integral_luk_leq_M(model, l, u, k): """Compute :math:`I(l,u,k)` for :math:`0<k<M+1`. Assumes that :math:`a<l,u<b`.""" ag = model.alpha - model.gamma om = 2 * B.pi * k / (model.b - model.a) return (1 / (ag ** 2 + om ** 2)) * ( (ag * B.cos(om * (u - model.a)) + om * B.sin(om * (u - model.a)))...
3fa6ace016c393ca89b3c587137fbdb6c3bd22e2
57,266
from persistent_settings.models import Variable def variable_factory(db): """ Returns a Variable instance. """ def factory(value, name="FOO"): return Variable.objects.create(name=name, value=value) return factory
5723a22ea6f673524f23c11e16b7e6f0b1d39e9b
57,267
def gain_com(exp, num, value): """Change the pmt gain in a job. Return a list with parts for the cam command. """ return [ ("cmd", "adjust"), ("tar", "pmt"), ("num", str(num)), ("exp", str(exp)), ("prop", "gain"), ("value", str(value)), ]
d0bd65b62c4ef0f9f002cef9b929ec37a725389c
57,268
def get_taxon_from_scientific_name(scientific_name): """ Function retrieves a taxon object from a colon delimited item_scientific_name string :param scientific_name: colon delimited item_scientific_name string, e.g. 'Rodentia:Muridae:Golunda gurai' :return: returns a taxon object. """ clean_name...
a37cc559281f8fbb8957d4425dcbb9626f3eac72
57,269
import argparse def get_arguments(): """Gets arguments from the command line. Returns: A parser with the input arguments. """ # Creates the ArgumentParser parser = argparse.ArgumentParser( usage='Loads features, targets .npy files and fits a SVM.') parser.add_argument( ...
7156f836beb4f80b6ee15a81445b2dc9802ba42a
57,270
def get_data(methylation_files, names, window, smoothen=5): """ Import methylation data from all files in the list methylation_files Data can be either frequency or raw. data is extracted within the window args.window Frequencies are smoothened using a sliding window """ return [read_meth(...
6dc3ebb000a9b6b665cc6e56ed8088671c76f512
57,271
from .treemodels import ObjectTreeStore def wrap_treenode_property_to_treemodel(model, prop): """ Convenience function that (sparsely) wraps a TreeNode property to an ObjectTreeStore. If the property is a Gtk.TreeModel instance, it returns it without wrapping. """ return wrap_prope...
283be5fc2b75ae19d8f548e9625f3e2135d24694
57,272
def gaussian(size, rin=0.8, rout=1.0): """Return a complex gaussian probe distribution. Illumination probe represented on a 2D regular grid. A finite-extent circular shaped probe is represented as a complex wave. The intensity of the probe is maximum at the center and damps to zero at the borders ...
d6e8b73206c6ae628ce8f9ac7e5a0e6b088b23f3
57,273
async def get_scorekeepers(): """Retrieve an array of Scorekeepers objects, each containing: Scorekeepers ID, name, slug string, and gender. Results are stored by scorekeeper name.""" try: scorekeeper = Scorekeeper(database_connection=_database_connection) scorekeepers = scorekeeper.ret...
96b94cff265d65e0ffe023ccedfe8f8d3fac001a
57,274
def _phi(x, m, r): """Computes the number of template vector pairs having a smaller distance than tolerance. Required for sample entropy estimation. """ N = len(x) x_ = [[x[j] for j in range(i, i + m - 1 + 1)] for i in range( N - m + 1)] C = [len([1 for j in range(len(x_)) if i != j and ...
04a5af5bb179813dcc771002aecdbb08b5d6aa9a
57,275
def make_divisible(v, divisible_by, min_value=None): """ This function is taken from the original tf repo. https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ if min_value is None: min_value = divisible_by new_v = max(min_value, int(v + divisibl...
3327381e8e79d45223635832ddfca80de629fc12
57,276
def find_corners(img): """ Find chessboard corners """ # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Find the chessboard corners return cv2.findChessboardCorners(gray, (NUM_CHESSBRD_CORNERS_X, NUM_CHESSBRD_CORNERS_Y), None)
989992c3658006483a05b923fed1dad08e0512d8
57,277
import os import json def load_tree(base_dir, data_loader): """Create a one-dimensional dictionary given a tree directory structure. The keys are generated with a separator per folder depth. :param base_dir: a valid directory or path :type base_dir: str :param data_loader: a function specificyin...
30c239c7079901212f5cb11ec1dd4443af6408e9
57,278
def RF_features_select(rdd_feature_vd, n=10, m=7, s = 50): """ Implements random forest classifier to the opcodes counts in each document Returns the importance of each opcodes >> Input (hash, label, features), Output (features, importance) """ data_feature = rdd_feature_vd.map(lambda x: (x[1], ...
fa37f1bb1d38961ec4b271010e8e1b384040979c
57,279
from typing import List async def get_all_users_in_database( db: DatabaseManager = Depends(get_database), ) -> List[User]: """Get all users from users mongodb collection""" users = await db.user_get_all() if users: return JSONResponse(status_code=status.HTTP_200_OK, content=users) raise HT...
6abf9c39d6a9a51c0fb0f417e5bf11ce898d21a8
57,280
def F1(yp, yt): """F1 score. Args: yp (array): predictions yt (array): targets Returns: float: F1 score """ tp = true_positive(yp, yt) fp = false_positive(yp, yt) fn = false_negative(yp, yt) f1 = 2 * tp / (2 * tp + fp + fn) return f1
c02b7b16fe85eb7aff0a9015011e3b96954ad5ea
57,281
import matplotlib.pyplot as plt import os import collections import random def train_policy_gradients(game_spec, create_network, network_file_path, save_network_file_path=None, opponent_func=None, ...
115541798f8359a243e1742162600b45e9f0de49
57,282
def get_line_buffer(): # real signature unknown; restored from __doc__ """ get_line_buffer() -> string return the current contents of the line buffer. """ return ""
9242593c8f39a3175c17ea3f5ce07d8024d1ad03
57,283
from typing import List from typing import Dict from typing import Any def global_metrics_fn(all_confusion_mats: List[jnp.ndarray], dataset_metadata: Dict[str, Any]) -> Dict[str, float]: """Returns a dict with global (whole-dataset) metrics.""" # Compute mIoU from list of confusion matrices:...
ced566bad90d407f279cffac98a44993de12b38e
57,284
def get_lib_dpath_list(root_dir): """ input <root_dir>: deepest directory to look for a library (dll, so, dylib) returns <libnames>: list of plausible directories to look. """ 'returns possible lib locations' get_lib_dpath_list = [ root_dir, join(root_dir, 'lib'), join(ro...
b608336a76ac2e52e6668af26571f8697365ed67
57,285
def authenticate(): """Function for handling Twitter Authentication. Please note that this script assumes you have a file called credentials.py which stores the 4 required authentication tokens: 1. CONSUMER_API_KEY 2. CONSUMER_API_SECRET 3. ACCESS_TOKEN 4. ACCESS_TOKEN_SEC...
9a9010d9329217bf03704c024da359785e48d905
57,286
def get_rhs(lhs): """ Return the possible RHS of a given LHS. :param lhs: token or list of tokens :return: list of tuples """ return _ppdb_dict.get_rhs(lhs)
9d522cdb7725ad70c9786a20a1c05599592067c9
57,287
def root(): """Returns hola perro.""" return 'Welcome'
c83c0d159cbabdb82905595b01058d531a03ddd1
57,288
import os import json import yaml def _load_json_or_yaml(data_path, template_vars): """ attempts to load the data at path as JSON, if that fails tries as YAML """ if not os.path.exists(data_path): _log.error('Unable to load data from path: %s', data_path) return None if len(template_vars)...
200c55d1acbec62c9ed5ecdab2fb55b46cb8b8f4
57,289
def avgpool2d(expr, type_map): """Rewrite a avgpool op""" arg = expr.args[0] t = type_map[arg] arg = relay.op.cast(arg, "int32") out = relay.op.nn.avg_pool2d(arg, **expr.attrs) out = relay.op.cast(out, t.dtype) return [out, t.scale, t.zero_point, t.dtype]
00384ae01594b326188fe7eebced6c86437b4e53
57,290
from typing import Optional def get_export_configuration(export_id: Optional[str] = None, resource_group_name: Optional[str] = None, resource_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetE...
d0efe9cf0a41944b66fdd87650649dc50f76f31e
57,291
import argparse def default_arg_parser(): """ :rtype: argparse.ArgumentParser :return: Default argument parser. """ arg_parser = argparse.ArgumentParser(description="cui main.") arg_parser.add_argument("-a", "--host", type=str, default="0.0.0.0", help="acceptable ho...
b4deda0be168552a67c9d1244e1a26ddda88bb51
57,292
def decrypt(key, ciphertext): """ Decrypts `plaintext` with `key` using AES-128, an HMAC to verify integrity, and PBKDF2 to stretch the given key. The exact algorithm is specified in the module docstring. """ # if(len(ciphertext)%16 != 0): # ciphertext = pad(ciphertext) # assert len(cip...
7220c018db4f05aa56aa490499ed266cf810bfad
57,293
def view_showcases(request): """ Shows the project showcase page """ showcase_settings = ShowcaseSiteSettings.objects.first() if not showcase_settings: return render(request, 'showcase.html', { 'top_results': None, 'all_showcases': None, }) showcase_hackathons = ...
fb3954c132ee620bc74220edcca2c538edbcb837
57,294
import torch def get_models(flags: GetModelsProto, modality: str): """ Get the wanted classifier for specific modality """ # argument feature_extractor_img is only used for mimic_main. # Need to make sure it is unset when training classifiers flags.feature_extractor_img = '' assert modalit...
9a13fa6a323bf0812f3c1e8a1da7bc03dfadd24b
57,295
from datetime import datetime def cite(headline, source, link, HTMLclass, author=""): """ Return a MLA-ish citation for a given headline in HTML. Adds citation along with headline info to firestore. Delets old headline from that source. """ dateAccessed = datetime.now() citation = "" if a...
4dea2923745cd66fec40a261cbd72929c2793bf6
57,296
import argparse import os import time import torch def get_args(): """parse and preprocess cmd line args""" parser = argparse.ArgumentParser() parser.add_argument("-ctx_mode", type=str, default="video_sub", choices=["video", "sub", "video_sub"]) # model config parser.add_argument("-hidden_size", ...
419500fcb55237abf44f788acdfd39f94ec1467e
57,297
def add_label(w, t, n, s='http://portainer:9000/api', e='1'): """Deploy swarm stack. Deploy a swarm stack with the Portainer api. Args: w: Swarm id t: Authorization token n: Stack name d: Path to docker-compose y: Deployment type 1 (Swarm) 2 (Compose) s: Por...
8059f672fd3f54467153b63b760dc133c551472c
57,298
def leaky_relu_backward(dA, cache, alpha=0.01): """ Implements the backward propagation for a single leaky_RELU unit. Arguments: dA -- post-activation gradient, of any shape cache -- 'Z' where we store for computing backward propagation efficiently Returns: dZ -- Gradient of the cost with ...
212926e6e71ebf4edfc51f99f2957643d3e6a7e5
57,299