content
stringlengths
22
815k
id
int64
0
4.91M
def is_in_cell(point:list, corners:list) -> bool: """ Checks if a point is within a cell. :param point: Tuple of lat/Y,lon/X-coordinates :param corners: List of corner coordinates :returns: Boolean whether point is within cell :Example: """ y1, y2, x1, x2 = corners[2][0], corn...
32,600
def test_input_para_validator(): """Test running a calculation note this does only a dry run to check if the calculation plugin works""" # put an invalid type in params and check if the validator captures it for key, val in { 'llg_n_iterations': 17.2, 'mc_n_iterations': [1, 2, 3...
32,601
def json_response(function): """ This decorator can be used to catch :class:`~django.http.Http404` exceptions and convert them to a :class:`~django.http.JsonResponse`. Without this decorator, the exceptions would be converted to :class:`~django.http.HttpResponse`. :param function: The view function whi...
32,602
def plot_saliency(image, model): """Gets a saliency map for image, plots it next to image. """ saliency = get_saliency(image, model) plt.ion() fig, (ax1, ax2) = plt.subplots(2) ax1.imshow(np.squeeze(saliency), cmap="viridis") hide_ticks(ax1) ax2.imshow(np.squeeze(image), cmap="gray") hid...
32,603
def generate_junit_report_from_cfn_guard(report): """Generate Test Case from cloudformation guard report""" test_cases = [] count_id = 0 for file_findings in report: finding = file_findings["message"] # extract resource id from finsind line resource_regex = re.search("^\[([^]]*)...
32,604
def new_custom_alias(): """ Create a new custom alias Input: alias_prefix, for ex "www_groupon_com" alias_suffix, either .random_letters@simplelogin.co or @my-domain.com optional "hostname" in args Output: 201 if success 409 if the alias already exists """ ...
32,605
def setup_pen_kw(penkw={}, **kw): """ Builds a pyqtgraph pen (object containing color, linestyle, etc. information) from Matplotlib keywords. Please dealias first. :param penkw: dict Dictionary of pre-translated pyqtgraph keywords to pass to pen :param kw: dict Dictionary of Matplo...
32,606
def seq(seq_aps): """Sequence of parsers `seq_aps`.""" if not seq_aps: return succeed(list()) else: ap = seq_aps[0] aps = seq_aps[1:] return ap << cons >> seq(aps)
32,607
def test_bad_multiplication(): """Tests that a multiplication fails.""" x = UniPoly(1, 'x', 1) p = x + 1 q = x - 1 assert p * q == x * x + 1
32,608
def Growth_factor_Heath(omega_m, z): """ Computes the unnormalised growth factor at redshift z given the present day value of omega_m. Uses the expression from Heath1977 Assumes Flat LCDM cosmology, which is fine given this is also assumed in CambGenerator. Possible improvement could be to tabulate...
32,609
def freq2bark(freq_axis): """ Frequency conversion from Hertz to Bark See E. Zwicker, H. Fastl: Psychoacoustics. Springer,Berlin, Heidelberg, 1990. The coefficients are linearly interpolated from the values given in table 6.1. Parameter --------- freq_axis : numpy.array ...
32,610
def main(argv): """Run tests, return number of failures (integer).""" # insert our paths in sys.path: # ../build/lib.* # .. # Q. Why this order? # A. To find the C modules (which are in ../build/lib.*/Bio) # Q. Then, why ".."? # A. Because Martel may not be in ../build/lib.* test_pat...
32,611
def close_connection(conn: Connection): """ Closes current connection. :param conn Connection: Connection to close. """ if conn: conn.close() return True return False
32,612
def tile_memory_free(y, shape): """ XXX Will be deprecated Tile vector along multiple dimension without allocating new memory. Parameters ---------- y : np.array, shape (n,) data shape : np.array, shape (m), Returns ------- Y : np.array, shape (n, *shape) """ im...
32,613
def load_ref_system(): """ Returns d-talose as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C -0.6934 -0.4440 -0.1550 C -2.0590 0.1297 0.3312 C -3.1553 -0.9249 0.167...
32,614
def PVLPrint (VLTable, image, streamname, err): """ Print the contents of a VL (survey catalog) table * VLTable = VL table to print * image = Image to to which VL table is attached * streamname = Name of stream to use, "stdout", or "stderr" * err = Python Obit Error/message stac...
32,615
def format_user_id(user_id): """ Format user id so Slack tags it Args: user_id (str): A slack user id Returns: str: A user id in a Slack tag """ return f"<@{user_id}>"
32,616
def test_module(params: dict): """ Returning 'ok' indicates that the integration works like it is supposed to. This test works by running the listening server to see if it will run. Args: params (dict): The integration parameters Returns: 'ok' if test passed, anything else will fail...
32,617
def class_loss_regr(num_classes, num_cam): """Loss function for rpn regression Args: num_anchors: number of anchors (9 in here) num_cam : number of cam (3 in here) Returns: Smooth L1 loss function 0.5*x*x (if x_abs < 1) x_abx - 0...
32,618
def smtplib_connector(hostname, port, username=None, password=None, use_ssl=False): """ A utility class that generates an SMTP connection factory. :param str hostname: The SMTP server's hostname :param int port: The SMTP server's connection port :param str username: The SMTP server username :param ...
32,619
def _to_one_hot_sequence(indexed_sequence_tensors): """Convert ints in sequence to one-hots. Turns indices (in the sequence) into one-hot vectors. Args: indexed_sequence_tensors: dict containing SEQUENCE_KEY field. For example: { 'sequence': '[1, 3, 3, 4, 12, 6]' # This is the amino acid ...
32,620
def kaiser_smooth(x,beta): """ kaiser window smoothing """ window_len=41 #Needs to be odd for proper response # extending the data at beginning and at the end # to apply the window at the borders s = np.r_[x[window_len-1:0:-1],x,x[-1...
32,621
def get_indel_dicts(bamfile, target): """Get all insertion in alignments within target. Return dict.""" samfile = pysam.AlignmentFile(bamfile, "rb") indel_coverage = defaultdict(int) indel_length = defaultdict(list) indel_length_coverage = dict() for c, s, e in parse_bed(target): s = i...
32,622
def _ComputeRelativeAlphaBeta(omega_b, position_b, apparent_wind_b): """Computes the relative alpha and beta values, in degrees, from kinematics. Args: omega_b: Array of size (n, 3). Body rates of the kite [rad/s]. position_b: Array of size (1, 3). Position of the surface to compute local a...
32,623
def make_chord(midi_nums, duration, sig_cons=CosSignal, framerate=11025): """Make a chord with the given duration. midi_nums: sequence of int MIDI note numbers duration: float seconds sig_cons: Signal constructor function framerate: int frames per second returns: Wave """ freqs = [midi...
32,624
def calculate_percent(partial, total): """Calculate percent value.""" if total: percent = round(partial / total * 100, 2) else: percent = 0 return f'{percent}%'
32,625
def test_item_not_available(app): """Test item not available.""" item_pid = "1" transition = "checkout" msg = ( "The item requested with pid '{0}' is not available. " "Transition to '{1}' has failed.".format(item_pid, transition) ) with pytest.raises(ItemNotAvailableError) as ex:...
32,626
def test_resolve_variable_no_type() -> None: """Test resolve_variable.""" with pytest.raises(VariableTypeRequired): resolve_variable("name", {}, None, "test")
32,627
def okgets(urls): """Multi-threaded requests.get, only returning valid response objects :param urls: A container of str URLs :returns: A tuple of requests.Response objects """ return nest( ripper(requests.get), filt(statusok), tuple )(urls)
32,628
def check_content_type(content_type): """ Checks that the media type is correct """ if request.headers['Content-Type'] == content_type: return app.logger.error('Invalid Content-Type: %s', request.headers['Content-Type']) abort(415, 'Content-Type must be {}'.format(content_ty...
32,629
def worker(args): """ This function does the work of returning a URL for the NDSE view """ # Step 1. Create the NDSE view request object # Set the url where you want the recipient to go once they are done # with the NDSE. It is usually the case that the # user will never "finish" with the N...
32,630
def plot_horiz_xsection_quiver_map(Grids, ax=None, background_field='reflectivity', level=1, cmap='pyart_LangRainbow12', vmin=None, vmax=None, u_vel_contours=None, ...
32,631
def register(registered_collection, reg_key): """Register decorated function or class to collection. Register decorated function or class into registered_collection, in a hierarchical order. For example, when reg_key="my_model/my_exp/my_config_0" the decorated function or class is stored under registered_col...
32,632
def form_hhaa_records(df, team_locn='h', records='h', feature='ftGoals'): """ Accept a league table of matches with a feature """ team_records = [] for _, team_df in df.groupby(by=team_locn): lags = range(0, len(team_df)) ...
32,633
def test_invalid_metric(aggregator): """ Invalid metrics raise a Warning and a critical service check """ instance = common.generate_instance_config(common.INVALID_METRICS) check = common.create_check(instance) check.check(instance) # Test service check aggregator.assert_service_check("...
32,634
def plot_adjust(): """ Adjust the plot """ plt.xlabel('Site occupation density $\\rho$') plt.ylabel('Normalized flux $j$') plt.legend(loc='upper left', labelspacing=0.2, frameon=False, borderaxespad=0) plt.tight_layout() return
32,635
def test_io_mapping(): """Test if ``inputs`` and ``outputs`` are translated to output/input names.""" good_io = {'inputs': ['input', 'second_input'], 'outputs': ['output', 'sum']} model = SimpleModel(dataset=None, log_dir='', **good_io) assert model.input_names == good_io['inputs'] assert model.outp...
32,636
async def test_entity_device_info_update(hass, mqtt_mock): """Test device registry update.""" registry = dr.async_get(hass) config = { "topic": "test-topic", "device": { "identifiers": ["helloworld"], "connections": [["mac", "02:5b:26:a8:dc:12"]], "manufa...
32,637
def terminate_process_by_name(procname): """Terminate process by process name.""" for proc in psutil.process_iter(): if proc.name() == procname: proc.kill()
32,638
def process_dataset(material: str, frequency: float, plot=False, pr=False) -> float: """ Take a set of data, fit curve and find thermal diffustivity. Parameters ---------- material : str Gives material of this dataset. 'Cu' or 'Al'. frequency : float Frequenc...
32,639
def migrate(db_pass, image=image_tag): """ Performs migrations on database. :param db_pass: Password for database. :param image: Name of seventweets image. """ run(f'docker run ' f'--rm ' f'--net {network_name} ' f'-e ST_DB_USER={db_user} -e ST_DB_PASS={db_pass} ' ...
32,640
def search(obj, terms, oper, packages): """ Search PyPI for packages or releases thereof. Search terms may be specified as either ``field:value`` (e.g., ``summary:Django``) or just ``value`` to search long descriptions. """ spec = {} for t in terms: key, colon, value = t.partition("...
32,641
def load_shuttle(main_data_path, folder='shuttle', df=None): """ ____ _ _ _ _ ___ ___ _ ____ [__ |__| | | | | | |___ ___] | | |__| | | |___ |___ From UCI https://archive.ics.uci.edu/ml/datasets/Shuttle+Landing+Control """ # Encoder ...
32,642
def cuda_reset() -> None: """Calls `cudaDeviceReset` Destroy all allocations and reset all state on the current device in the current process. """
32,643
def hxlrename(): """Console script for hxlrename.""" run_script(hxlrename_main)
32,644
def show_drizzle_HDU(hdu): """Make a figure from the multiple extensions in the drizzled grism file. Parameters ---------- hdu : `~astropy.io.fits.HDUList` HDU list output by `drizzle_grisms_and_PAs`. Returns ------- fig : `~matplotlib.figure.Figure` The figure....
32,645
def test_get_tenant_shares_for_period_one_billing( django_db_setup, lease_factory, contact_factory, tenant_factory, tenant_contact_factory, assert_count_equal, ): """Lease with two tenants. Tenant2's billing contact is contact1""" lease = lease_factory( type_id=1, municipality_id...
32,646
def make_ln_func(variable): """Take an qs and computed the natural log of a variable""" def safe_ln_queryset(qs): """Takes the natural log of a queryset's values and handles zeros""" vals = qs.values_list(variable, flat=True) ret = np.log(vals) ret[ret == -np.inf] = 0 ret...
32,647
def test_dice(): """ Tests for catalyst.metrics.dice metric. """ size = 4 half_size = size // 2 shape = (1, 1, size, size) # check 0: one empty empty = torch.zeros(shape) full = torch.ones(shape) assert dice(empty, full, class_dim=1, mode="per-class").item() == 0 # check 0:...
32,648
def calc_all_energies(n, k, states, params): """Calculate all the energies for the states given. Can be used for Potts. Parameters ---------- n : int Number of spins. k : int Ising or Potts3 model. states : ndarray Number of distinct states. params : ndarray ...
32,649
def create_heroku_connect_schema(using=DEFAULT_DB_ALIAS): """ Create Heroku Connect schema. Note: This function is only meant to be used for local development. In a production environment the schema will be created by Heroku Connect. Args: using (str): Alias for databas...
32,650
def extract_sentences(modifier, split_text): """ Extracts the sentences that contain the modifier references. """ extracted_text = [] for sentence in split_text: if re.search(r"\b(?=\w)%s\b(?!\w)" % re.escape(modifier), sentence, re.IGNORECASE): extracted_tex...
32,651
def get_1_neighbours(graph, i): """ This function gets all the 1-neighborhoods including i itself. """ nbhd_nodes = graph.get_out_neighbours(i) nbhd_nodes = np.concatenate((nbhd_nodes,np.array([i]))) return nbhd_nodes
32,652
def window_slice(frame, center, window): """ Get the index ranges for a window with size `window` at `center`, clipped to the boundaries of `frame` Parameters ---------- frame : ArrayLike image frame for bound-checking center : Tuple (y, x) coordinate of the window window : ...
32,653
def each_30_sec(exercises): """ Do one minute of each exercise with no break """ one_by_one(exercises, sec_on=30, sec_off=0)
32,654
def revnum_to_revref(rev, old_marks): """Convert an hg revnum to a git-fast-import rev reference (an SHA1 or a mark)""" return old_marks.get(rev) or b':%d' % (rev+1)
32,655
def onset_precision_recall_f1(ref_intervals, est_intervals, onset_tolerance=0.05, strict=False, beta=1.0): """Compute the Precision, Recall and F-measure of note onsets: an estimated onset is considered correct if it is within +-50ms of a reference onset. Note that this metric ...
32,656
def parse_acs_metadata(acs_metadata, groups): """Returns a map of variable ids to metadata for that variable, filtered to specified groups. acs_metadata: The ACS metadata as json. groups: The list of group ids to include.""" output_vars = {} for variable_id, metadata in acs_metadata["variabl...
32,657
def split_series_using_lytaf(timearray, data, lytaf): """ Proba-2 analysis code for splitting up LYRA timeseries around locations where LARs (and other data events) are observed. Parameters ---------- timearray : `numpy.ndarray` of times understood by `sunpy.time.parse_time` function. ...
32,658
def establish_file_structure(project_dir): """Create output data directory and empty spin system master if required for MADByTE Args: output_dir (str or Path): desired output directory project_dir (str or Path): project directory """ project_dir = Path(project_dir) master = pr...
32,659
def getrqdata(request): """Return the request data. Unlike the now defunct `REQUEST <https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.REQUEST>`_ attribute, this inspects the request's `method` in order to decide what to return. """ if request.method in (...
32,660
def generate_per_level_fractions(highest_level_ratio: int, num_levels: int = NUM_LEVELS) -> List[float]: """ Generates the per-level fractions to reach the target sum (i.e. the highest level ratio). Args: highest_level_ratio: The 1:highest_level_ratio ratio for the highest level; i.e. t...
32,661
def choose_transformations(name): """Prompts user with different data transformation options""" transformations_prompt=[ { 'type':'confirm', 'message':'Would you like to apply some transformations to the file? (Default is no)', 'name':'confirm_transformations', ...
32,662
def update_list_item_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]: """Updates a list item. return outputs in Demisto's format Args: client: Client object with request args: Usually demisto.args() Returns: Outputs """ list_id = int(args.get('list_id')) # ty...
32,663
def fft(input, inverse=False): """Interface with torch FFT routines for 3D signals. fft of a 3d signal Example ------- x = torch.randn(128, 32, 32, 32, 2) x_fft = fft(x) x_ifft = fft(x, inverse=True) Parameters ---------- x : tensor ...
32,664
def dbdescs(data, dbname): """ return the entire set of information for a specific server/database """ # pylint: disable=bad-continuation return { 'admin': onedesc(data, dbname, 'admin', 'rw'), 'user': onedesc(data, dbname, 'user', 'rw'), 'viewer': onedesc(data, dbname, 'viewer', 'ro') }
32,665
def format_date(date): """Format date to readable format.""" try: if date != 'N/A': date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').strftime('%d %b %Y') except ValueError: logger.error("Unexpected ValueError while trying to format date -> {}".format(date)) pa...
32,666
def favor_attention(query, key, value, kernel_transformation, causal, projection_matrix=None): """Computes FAVOR normalized attention. Args: query: query tensor. key: key tensor. value: value tensor. ...
32,667
def estimate_perfomance_plan(sims, ntra, stateinit, destination, plan=list(), plot=False, verbose=True): """ Estimates the performances of two plans and compares them on two scenarios. :param list() sims: List of :class:`simulatorTLKT.Simulator` :param int ntra: Number of trajectories used to estimate ...
32,668
def xls_dslx_ir_impl(ctx, src, dep_src_list): """The implementation of the 'xls_dslx_ir' rule. Converts a DSLX source file to an IR file. Args: ctx: The current rule's context object. src: The source file. dep_src_list: A list of source file dependencies. Returns: DslxModuleIn...
32,669
def IterElementsWithTag(root, tag, depth=-1): """Iterates over DOM tree and yields elements matching tag name. It's meant to be replacement for `getElementsByTagName`, (which does recursive search) but without recursive search (nested tags are not supported in histograms files). Note: This generator stops g...
32,670
def pendu_version1(nb_erreur_max: int, new_stat=nouvel_etat): """Procédure affichant le jeu du pendu version 1 Le paramètre new_stat contient la fonction nouvel_etat, pour éviter de recopier tout le code quand on passe à nouvel_etat_version2 """ # Init mot = choice(lire_mots("littre.txt")) ...
32,671
def split_data(images, labels): """ Split data into training (80%), validation (10%), and testing (10%) datasets Returns (images_train, images_validate, images_test, labels_train, labels_validate, labels_test) Assumes that num_covid_points <= num_normal_points and num_virus_points """ ...
32,672
def randomlyInfectRegions(network, regions, age_groups, infected): """Randomly infect regions to initialize the random simulation :param network: object representing the network of populations :type network: A NetworkOfPopulation object :param regions: The number of regions to expose. :type regions...
32,673
def assert_equal( actual: Tuple[int, int], desired: Tuple[int, int], err_msg: Literal[""], verbose: bool, ): """ usage.statsmodels: 1 """ ...
32,674
def timestamp_to_uint64(timestamp): """Convert timestamp to milliseconds since epoch.""" return int(timestamp.timestamp() * 1e3)
32,675
async def test_response_handler_no_return_route_raises_error( alice_gen, bob, send, dispatcher, message, response ): """Test response handler works.""" alice = alice_gen(partial(send.return_response, bob.pack(response)), dispatcher) with pytest.raises(RuntimeError): await alice.send_async(messag...
32,676
def main(): """Receives the number of levels (N) of the pyramid to print.""" if len(sys.argv) < 2: print('Usage: pyramid_of_numbers_kata.py <number_of_levels>.') sys.exit(1) if not sys.argv[1].isnumeric(): print('Usage: pyramid_of_numbers_kata.py <number_of_levels>,' ...
32,677
def test_pd_types_correct_function_call( mocker, test_function_call, expected_value, pd_testing_function ): """Test that the correct 'sub' assert function is called if expected for the given input type - and none of the other functions are called. """ # test_function_call is the function to check h...
32,678
def extensible(x): """ Enables a function to be extended by some other function. The function will get an attribute (extensible) which will return True. The function will also get a function (extendedby) which will return a list of all the functions that extend it. """ extensible_functions.a...
32,679
def main(): """ An example of usage... """ pb = SimpleProgressBar(total=200) for i in range(201): pb.update(i) time.sleep(0.05)
32,680
def _validate_user_deploy_steps(task, user_steps, error_prefix=None): """Validate the user-specified deploy steps. :param task: A TaskManager object :param user_steps: a list of deploy steps. A deploy step is a dictionary with required keys 'interface', 'step', 'args', and 'priority':: ...
32,681
def is_period_arraylike(arr): """ return if we are period arraylike / PeriodIndex """ if isinstance(arr, pd.PeriodIndex): return True elif isinstance(arr, (np.ndarray, gt.ABCSeries)): return arr.dtype == object and lib.infer_dtype(arr) == 'period' return getattr(arr, 'inferred_type', Non...
32,682
def _udld_B74(linLD, wavel=0.8): """ linLD ~ 0.5 for R band, Teff=5500K, logg=1 (van Hamme 1993) """ B = np.linspace(20,30) # NPOI, Armstrong+ 2001 p = {'diam':1.5, 'wavel':0.8, 'linLD':linLD} # delta cep # plt.figure(1) # plt.clf() # plt.subplot(211) # plt.plot(B, V2ld_B74(B, p)) ...
32,683
def reset_password_step_2(token): """Processing the second step of changing the password (password change)""" email = confirm_token_reset_password(token) if not email: return redirect(url_for('web_pages.reset_password_step_1')) form = EditPassword() if form.validate_on_submit(): pass...
32,684
def FStarTypeRole(typ, rawtext, text, lineno, inliner, options={}, content=[]): """An inline role to highlight F* types.""" #pylint: disable=dangerous-default-value, unused-argument return nodes.literal(typ, rawtext, text, lineno, inliner, options=options, content=content)
32,685
def matobj2dict(matobj): """A recursive function which converts nested mat object to a nested python dictionaries Arguments: matobj {sio.matlab.mio5_params.mat_struct} -- nested mat object Returns: dict -- a nested dictionary """ ndict = {} for fieldname in matobj._fieldnam...
32,686
def download_from_vt(client: vt.Client, file_hash: str) -> bytes: """ Download file from VT. :param vt.Client client: the VT client :param str file_hash: the file hash :rtype: bytes :return: the downloaded data :raises ValueError: in case of any error """ try: buffer = io.Byt...
32,687
def divide_and_conquer(x, k, mul): """ Divide and conquer method for polynomial expansion x is a 2d tensor of size (n_classes, n_roots) The objective is to obtain the k first coefficients of the expanded polynomial """ to_merge = [] while x[0].dim() > 1 and x[0].size(0) > 1: si...
32,688
def calculate_operating_pressure(feed_state_block=None, over_pressure=0.15, water_recovery=0.5, NaCl_passage=0.01, solver=None): """ estimate operating pressure for RO unit model given the following arguments: feed_state_block: the state block of the RO feed that has t...
32,689
def parse_pypi_index(text): """Parses the text and returns all the packages Parameters ---------- text : str the html of the website (https://pypi.org/simple/) Returns ------- List[str] the list of packages """ soup = BeautifulSoup(text, "lxml") return [i.get_te...
32,690
def fetch(data_dir, dest="wmt14"): """ Fetches most data from the WMT14 shared task. Creates the `dest` if it doesn't exist. Args: data_dir (str): absolute path to the dir where datasets are stored dest (str): name for dir where WMT14 datasets will be extracted Returns: fi...
32,691
def _get_score_measure(func, alphabeta, color, board, alpha, beta, depth, pid): """_get_score_measure """ measure(pid) return _get_score(func, alphabeta, color, board, alpha, beta, depth, pid)
32,692
def mousePressed(): """ Return True if the mouse has been left-clicked since the last time mousePressed was called, and False otherwise. """ global _mousePressed if _mousePressed: _mousePressed = False return True return False
32,693
def __make_responsive_for_list(root: object, parent: list) -> None: """Modify recursive object to be responsive. Args: root (object): the main object that should be responsive parent (object): the current parent in the hierachy """ for index, value in enumerate(parent): current_...
32,694
def set_logging_config(logging_config: Dict) -> None: """Update logger configurations. Warning: This function modifies the configuration of the standard logging system for all loggers, and might interfere with custom logger configurations. """ dictConfig(logging_config)
32,695
def variable_on_cpu(name, shape, initializer): """ Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory. """ # Use the /cpu:0 device for scoped operations with tf.devic...
32,696
def adaptive_generate_association_rules(patterns, confidence_threshold): """ Given a set of frequent itemsets, return a dictof association rules in the form {(left): (right)} It has a check with 2048 thus will only retain multimodal rules. """ missed = 0 rules = defaultdict(set) ...
32,697
def cli(): """ Rebuild the docker container :return: Subprocess call result """ cmd = "docker-compose down && docker-compose build" return subprocess.call(cmd, shell=True)
32,698
def test_api_challenge_patch_admin(): """Can a user patch /api/v1/challenges/<challenge_id> if admin""" app = create_ctfd() with app.app_context(): gen_challenge(app.db) with login_as_user(app, "admin") as client: r = client.patch( "/api/v1/challenges/1", json={"n...
32,699