content
stringlengths
22
815k
id
int64
0
4.91M
def cossin(X, p=None, q=None, separate=False, swap_sign=False, compute_u=True, compute_vh=True): """ Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix. X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following where upper left block has the shape of ...
63,800
def getBlankBoard(): """Create a new, blank tic tac toe board.""" board = {} # The board is represented as a Python dictionary. for space in ALL_SPACES: board[space] = BLANK # All spaces start as blank. return board
63,801
def isopycnal_arr(arrin,target_density,pd,interp=None): """ Returns the value of an input array along an isopycnal. """ if target_density < 100: target_density += 1000 if not interp: i0 = isopycnal_mask(target_density,pd) if len(arrin.shape) > 1: i1,i2 = np.indi...
63,802
def forecast(model, predict_data, seq_len=50, forward=10, stride=1): """Step through the out-of-sample data and make predictions. Args: model (keras.Model): Trained model. predict_data (numpy.array): Out-of-sample data. seq_len (int): Sequence length. forward (int): Forward. stride (int): Step size. Retu...
63,803
def _run_on_failure_decorator(method, *args, **kwargs): """ A decorator to run when the tests fail :param method: the method to run :param args: the tuple arguments to pass to the method :param kwargs: the dict arguments to pass to the method :return: runs the method on failure, raises exception...
63,804
def load_blackrock( exp_path, test, electrode, connections=(), downsamp=15, page_size=10, bandpass=(), notches=(), save=True, snip_transient=True, lowpass_ord=12, units='uV', **extra ): """ Load raw data in an HDF5 table stripped from Blackrock NSx format. This data...
63,805
def get_xy_arrs(m_size, ant_rad): """Finds the x/y position of each pixel in the image-space Returns arrays that contain the x-distances and y-distances of every pixel in the model. Parameters ---------- m_size : int The number of pixels along one dimension of the model a...
63,806
def debugindex(orig, ui, repo, file_=None, **opts): """dump the contents of an index file""" if ( opts.get('changelog') or opts.get('manifest') or opts.get('dir') or not shallowutil.isenabled(repo) or not repo.shallowmatch(file_) ): return orig(ui, repo, file_...
63,807
def jot_obj(self, obj, name, comment=''): """ write obj data to the note database, with whatever that should be noted. """ had = self.db.keys('jot/'+name+'*') # if it the same name but a later version, we stupidly add a number to the # so the name doesn't collide. Any better idea? suffix = ...
63,808
def build_data(known_languages): """Build primary objects edge_struct and nodes from graph_base.""" with (SRC_DATA / 'graph_base.json').open() as base_fh: primary_data = json.load(base_fh) edge_struct = {} for relation_type, edges in primary_data['edges'].items(): edge_struct[relation_t...
63,809
def PrepareSipCollection(adornedRuleset): """ Takes adorned ruleset and returns an RDF dataset formed from the sips associated with each adorned rule as named graphs. Also returns a mapping from the head predicates of each rule to the rules that match it - for efficient retrieval later """ ...
63,810
def negate_q(a: ElementModQ) -> ElementModQ: """ Computes (Q - a) mod q. """ return ElementModQ(_Q_gmp - a.elem, make_formula("negate_q", a))
63,811
def test_save_load_confidence_report(): """ Test that a confidence report can be loaded and saved. """ report = ConfidenceReport() num_examples = 2 clean_correctness = np.zeros((num_examples,), dtype=np.bool) clean_confidence = np.zeros((num_examples,), dtype=np.float32) adv_correctness = clean_correctn...
63,812
def candidate_synsets(lemma, pos): """ Used to restrict our attention only to synsets from the entire probability distribution over the output layer :param lemma: :param pos: :return: list(Candidate synsets) or lemma if nothing in Wordnet """ pos_dict = {"ADJ": wn.ADJ, "ADV": wn.ADV, "NOUN":...
63,813
def start_session(username="user", password="password", enterprise="enterprise", api_url="https://vsd:8443", version="3.2", api_prefix="api"): """ Log in and fetch api key """ session = NURESTTestSession(username=username, password=password, enterprise=enterprise, api_url=api_url, version=version, api_prefix=a...
63,814
def test_get_docs_urls(client, jurisdiction, case, reporter): """ Test that every url in docs.html is functional """ settings.API_DOCS_CASE_ID = case.id response = client.get('/') html = response.content.decode() tmp_html = re.sub(";", "", html) possible_lines = tmp_html.split("&#39") ...
63,815
def nodes_or_number(which_args): """PORTED FROM NETWORKX Decorator to allow number of nodes or container of nodes. Parameters ---------- which_args : int or sequence of ints Location of the node arguments in args. Even if the argument is a named positional argument (with a default va...
63,816
def _crosscorr(x, y, **kwargs): """ Returns the crosscorrelation sequence between two ndarrays. This is performed by calling fftconvolve on x, y[::-1] Parameters x: ndarray y: ndarray axis: time axis all_lags: {True/False} whether to return all nonzero lags, or to clip the length ...
63,817
def get_qword(*args): """get_qword(ea_t ea) -> ulonglong""" return _idaapi.get_qword(*args)
63,818
def wine_key(wine_cate=DEFAULT_WINE_CAT): """Constructs a Datastore key for a Wine entity.""" return ndb.Key('WineCategory', wine_cate.lower())
63,819
def run_knn( train_features: torch.Tensor, train_targets: torch.Tensor, test_features: torch.Tensor, test_targets: torch.Tensor, k: int, T: float, distance_fx: str, ) -> Tuple[float]: """Runs offline knn on a train and a test dataset. Args: train_features (torch.Tensor, opti...
63,820
def create_account(create_account_key): """Checks the key. If valid, displays the create account page.""" user_id = auth_utils.check_create_account_key(create_account_key) if user_id is None: flask.current_app.logger.warn( f'Invalid create_account_key: {create_account_key}') flas...
63,821
def determine_inventory_groups(vm_directory): """ Determine the Ansible inventory groups that this VM is a member of. :param vm_directory: directory to issue `vagrant' commands in :return: list of Ansible inventory groups """ group_config = join(vm_directory, 'groups.yml') if exists(gro...
63,822
def mypy(session: Session) -> None: """Type-check using mypy.""" args = session.posargs or ["src", "tests", "docs/conf.py"] session.install(".") session.install("mypy", "pytest") session.run("mypy", *args) if not session.posargs: session.run("mypy", f"--python-executable={sys.executable...
63,823
def data_value(value: str) -> float: """Convert to a float; some trigger values are strings, rather than numbers (ex. indicating the letter); convert these to 1.0.""" if value: try: return float(value) except ValueError: return 1.0 else: # empty string ...
63,824
def _monom(n): """ monomial in `eta` variables from the number `n` encoding it """ v = [] i = 0 while n: if n % 2: v.append(i) n = n >> 1 i += 1 return v
63,825
def _combin(points,n, max_dist): """Summary Args: points (lst): sample points n (integer): number of samples max_dist (float): maximum permissible distance Returns: lst: List of tuples containing the permissible pairs """ dist =[] p = 0 for i in range(0,n): for j in range((i+1),n): ...
63,826
def run_test(): """Run test""" sapi = SampleApi() aapi = AnalysisApi() def _print_samples(): samples = sapi.get_samples( body_get_samples_by_criteria_api_v1_sample_post={ 'project_ids': [PROJ], 'active': True, } ) for s in ...
63,827
def compare_stride_patterns(system, n=5): """ Creates and optimizes networks with several random stride patterns, to explore sensitivity of optimization to stride pattern. :param system: a System (physiological model) for which to create a convnet :param n: number of stride patterns / networks to g...
63,828
def get_buildtime(in_list, start_year, path_list): """ Calculates the buildtime required for reactor deployment in months. Parameters ---------- in_list: list list of reactors start_year: int starting year of simulation path_list: list list of paths to reactor files ...
63,829
def concat(rlist, method="gridded", enhance=False, parallel=False): """ This function takes a list of Radial objects or radial file paths and combines them along the time dimension using xarrays built-in concatenation routines. Args: rlist (list): list of radial files or Radial ...
63,830
def test_success(database): """ Tests that SF 133 amount sum for lines 1160, 1180, 1260, 1280 matches Appropriation budget_authority_appropria_cpe for the specified fiscal year and period """ tas = "".join([_TAS, "_success"]) sf_1 = SF133(line=1160, tas=tas, period=1, fiscal_year=2016, amount=1, a...
63,831
def month_counter(fm, LAST_DAY_OF_TRAIN_PRD=(2015, 10, 31)): """Calculate number of months (i.e. month boundaries) between the first month of train period and the end month of validation period. Parameters: ----------- fm : datetime First day of first month of train period Returns: ...
63,832
def warning(message): """Log helper function for jinja2 tasks""" l.warning(message) return ""
63,833
def demean(X, weights=None, return_mean=False, inplace=False): """Remove weighted mean over rows (samples). Parameters ---------- X : array, shape=(n_samples, n_channels[, n_trials]) Data. weights : array, shape=(n_samples) return_mean : bool If True, also return signal mean (de...
63,834
def l10n_overview_rows(locale, product=None): """Return the iterable of dicts needed to draw the Overview table.""" # The Overview table is a special case: it has only a static number of # rows, so it has no expanded, all-rows view, and thus needs no slug, no # "max" kwarg on rows(), etc. It doesn't fit...
63,835
def tupleize(series_dict, tuple_name="obs"): """Creates an observation list of NamedTuples.""" kwarg_dict = {} keys = [i for i in series_dict.keys()] for i in range(0, len(keys)): kwarg_dict[keys[i]] = list(series_dict[keys[i]]) return create_observation_list(tuple_name, **kwarg_dict)
63,836
def symmetry_specified(self, x, bond_order): """ Specify the symmetry of the bond and then calculate separately, before concatenating them together. TODO: finish implementing """ return tf.cond( lambda: tf.greater( bond_order, tf.constant(1, dtype=tf.float32)), ...
63,837
def get_confusion_matrix_by_activity(num_classes, label, predicted): """Calculate confusion matrix based on activity accuracy Instead of calculating confusion matrix by comparing ground truth and predicted result one by one, it compares if a segment of activity is correctly predicted. It also logs the ...
63,838
def parse(handle,format): """Parses an output file of motif finding programs. Currently supported formats: -AlignAce -MEME you can also use single-motif formats: -pfm -sites """ try: parser=_parsers[format] except KeyError: try: #not a true parser, try ...
63,839
def uv_history_obs_description(kat_adapter, uvf): """ Record MeerKAT observation metadata in AIPS history Parameters ---------- katdal_adapter : :class:`katacomb.KatdalAdapter` Katdal Adapter uvf : :class:`katacomb.UVFacade` UV file """ uvf.append_history("="*70) uv...
63,840
def get_background(background_img=BACKGROUND): """Start with a background image""" _img = Image.open(background_img) # Check the width and height of the image assert _img.size == (400, 300), "Background must be 400x300" # Convert the image to use a white / black / red colour palette # hopefull...
63,841
def start_torrents(host: str, directories: str, port: int = 443, debug: bool = False, start_stopped: bool = False, syslog: bool = False, config: Optional[str] = None) -> None: """Uploads torrent files t...
63,842
def test_process_still_querying_zero(cbcsdk_mock): """Testing Process""" # mock the POST of a search cbcsdk_mock.mock_request("POST", "/api/investigate/v2/orgs/test/processes/search_jobs", POST_PROCESS_SEARCH_JOB_RESP) # mock the search validation cbcsdk_mock.mock_reques...
63,843
def ZonalComputeUrl(project, zone, collection, name): """Generate zone compute URL.""" return ''.join([COMPUTE_URL_BASE, 'projects/', project, '/zones/', zone, '/', collection, '/', name])
63,844
def gendocs(): """Generates the docs""" local('sphinx-build -b singlehtml docs docs/_build') print('Documentation is now available in ./docs/_build.')
63,845
def check_repo(repo_dir = '../../models/all_from_repository', model_suffix = 'xml', invalid_if_warnings = False, compare=True): """ Validate every model in the CellML repository, and return a list of invalid models. If compare is False, writes errors & w...
63,846
def test_safe_file_dump_save_existing(): """Test safe file dump.""" import pickle m = mock_open() data = np.array([1, 2]) with patch('os.path.exists', return_value=True) as mpe,\ patch('builtins.open', m) as mo,\ patch('pickle.dump') as md,\ patch('shutil.move') as msm: ...
63,847
def build_get_long_valid_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an ...
63,848
def fromKML(filename=None, data=None, crs=None, encoding=None): """ Create a list of Features from a KML file. Return a python tuple with ee.Feature inside. This is due to failing when attempting to create a FeatureCollection (Broken Pipe ERROR) out of the list. You can try creating it yourself casting ...
63,849
def run_as_thread(fn): """Run function as thread""" @wraps(fn) def run(*args, **kwargs): t = threading.Thread(target=fn, args=args, kwargs=kwargs) t.daemon = True t.start() return t return run
63,850
def to_unicode(obj): """Convert object to unicode""" if isinstance(obj, bytes): return obj.decode('utf-8', 'ignore') return str(obj)
63,851
def positive_definite_matrix(N, M=None): """return an array of M positive-definite matrices with shape (N, N)""" if M is None: V = np.random.random((N, N)) V = np.dot(V, V.T) else: V = np.random.random((M, N, N)) for i in range(M): V[i] = np.dot(V[i], V[i].T) ...
63,852
def test_wild_occupied(): """ The 1 die can't move onto the wild space, because it's occupied. """ start_state = """\ 1|0 3|1 0|0 3|0 2|0 3|3 --- dice:(3,2)1,(3,1)2,(2,1)3 """ board = BeesBoard.create(start_state, max_pips=3) expected_display = """\ 1|0 3|1 0|0 3|0 2|0 3|3 --- dice:(0,2)1,(3,1)2,(2,...
63,853
def restore_agent(agent_class, learner_config, env_config, session_config, render): """ Restores an agent from a model. """ agent = agent_class( learner_config=learner_config, env_config=env_config, session_config=session_config, agent_id=0, agent_mode='eval_deter...
63,854
def get_pretrained_model_last_layer_change(model_name, n_classes): """ :param model_name: 뢈러올 pre trained λͺ¨λΈ 이름 :param n_classes: λΆ„λ₯˜ν•  클래슀 갯수 :return: 뢈러온 λͺ¨λΈμ˜ λΆ„λ₯˜κΈ° λΆ€λΆ„λ§Œ μˆ˜μ •ν•œ ꡬ쑰λ₯Ό λ¦¬ν„΄ν•œλ‹€. """ if model_name == 'alexnet': model = models.alexnet(pretrained=True) # Freeze early layers ...
63,855
def download_image(ses, url): """ dumps image into memory """ dl = ses.get(url, stream=True) img = StringIO() img.write(dl.content) img.seek(0) # rewind to beginning return img
63,856
def get_masteries(): """ https://developer.riotgames.com/api/methods#!/968/3317 Returns: MasteryList: all the masteries """ request = "{version}/masteries".format(version=cassiopeia.dto.requests.api_versions["staticdata"]) params = {"tags": "all"} if _locale: params["locale...
63,857
def run_gunicorn(): """ Exec gunicorn with our wsgi app. Settings are taken from environment variables as listed in the help text. This is intended to be called as a console_script entry point. """ # this only exists to provide help/usage text parser = ArgumentParser(description=DESCRIPTIO...
63,858
def test_nosend_reject_send(): """Server rejects switch to key2 which is marked nosend, it keeps sending with key1""" context = make_tcp_authopt_socket_pair( server_key_list=[ tcp_authopt_key(send_id=1, recv_id=1, key="111"), tcp_authopt_key(send_id=2, recv_id=2, key="222", nosen...
63,859
def test_solve_4x4(): """Tests if LU factorization works""" matrix = Matrix([ [1, -2, 2, -3], [3, 4, -1, 1], [2, -3, 2, -1], [1, 1, -3, -2] ]) vector = Vector([15, -6, 17, -7]) doolittle = Doolittle(matrix=matrix, matrix_name="A", vector=vect...
63,860
def get_shape(x, unknown_dim_size=1): """ Extract shape from onnxruntime input. Replace unknown dimension by default with 1. Parameters ---------- x: onnxruntime.capi.onnxruntime_pybind11_state.NodeArg unknown_dim_size: int Default: 1 """ shape = x.shape # replace unknow...
63,861
def process_fields(filename, field_occurrences=defaultdict(list)): """ Create a dict of fieldnames and the forms that include them. Args: filename (str): CSV field_occurrences (dict): A dictionary of the sort we'll be returning. Returns: A dictionary of lists, indexed by fieldn...
63,862
def test_read_json(): """ This function tests the read_json_file function to ensure it returns the correct results """ if plat in lin_plat: file = '../data/test/json.json' else: file = r'..\data\test\json.json' dat = read_json_file(file) assert dat['widget']['debug'] == ...
63,863
def test_del(): """Test deletelist command.""" cmd = command.del_com() assert cmd == [("cmd", "deletelist")]
63,864
def sensemap_sim( shape=(64, 64), spacings=(3, 3), ncoil=8, rcoil=100, orbit=360, orbit_start=None, coil_distance=1.5, nring=1, dz_coil=None, scale="default", dtype=np.complex128, xp=np, ): """Simulate sensitivity maps for sensitivity-encoded MRI. Parameters ...
63,865
def _check_typeclass_signature( typeclass_signature: CallableType, instance_signature: CallableType, ctx: MethodContext, ) -> bool: """ Checks that instance signature is compatible with. We use contravariant on arguments and covariant on return type logic here. What does this mean? Let...
63,866
def quaternion_matrix(quaternion): """Return homogeneous rotation matrix from quaternion.""" q = np.array(quaternion, dtype=np.float64, copy=True) n = np.dot(q, q) if n < _EPS: return np.identity(4) q *= np.sqrt(2.0 / n) q = np.outer(q, q) return np.array([ [1.0-q[2, 2]-q[3, ...
63,867
def rhex_str(length: int = 4) -> str: """Returns a random hex string :param length: length of random bytes to turn into hex (defaults to 4) :type length: int :return: random hexadecimal string :rtype: str .. doctest:: python >>> a = rhex_str() >>> isinstance(a, str) Tr...
63,868
def logfile(): """Return path to log file.""" return os.path.join(env.flags["log_dir"], env.flags["log_file"])
63,869
def word_tally(word_list): """ Compiles a dictionary of words. Keys are the word, values are the number of occurrences of this word in the page. :param word_list: list List of words :return: dictionary Dict of words: total """ word_dict = {} for word in word_list: ...
63,870
def _matches( spec: jax.core.Jaxpr, capture_literals: Dict[int, str], graph: jax.core.Jaxpr, eqn_idx: int, ) -> Tuple[ bool, int, Sequence[jax.core.Var], Sequence[jax.core.Var], Dict[str, Any]]: """Determines whether the graph continues with the given reference graph. Args: spec: Reference ...
63,871
def read_file(file_: str, question: str) -> str: """Read file or ask for data to write in text file.""" if not os.path.isfile(f'assets/{file_}.txt'): open(f'assets/{file_}.txt', 'a') with open(f'assets/{file_}.txt', 'r+', encoding='utf-8') as file: text = file.read() if text == '': ...
63,872
def complexity(sequence, N): """ Computes the Shannon Entropy of a given sequence of a biopolymer with `N` possible residues. See (Wooton, 1993) for more. :param sequence: the nucleotide or protein sequence whose Shannon Entropy is to calculated. :param N: the total number of possible re...
63,873
def command(anime_name, new, update_all, _list, quality, remove, download_dir, provider): """ With watch you can keep track of any anime you watch. Available Commands after selection of an anime:\n set : set episodes_done, provider and title. Ex: set episodes_done=3\n...
63,874
def test_check_absence_of_large_intervals( counterpoint_continuation: LineElement, cantus_firmus_elements: List[LineElement], max_n_semitones: int, expected: bool ) -> None: """Test `check_absence_of_large_intervals` function.""" result = check_absence_of_large_intervals( ...
63,875
def overlay_taylor_diagram_lines(axes, cax, option): """ Overlay lines emanating from origin on a Taylor diagram. OVERLAY_TAYLOR_DIAGRAM_CIRCLES(AXES,CAX,OPTION) Plots lines emanating from origin to indicate correlation values (CORs) INPUTS: axes : data structure containing axes information ...
63,876
def test_close_popups_exception(instagram): """ Test the popup closing reraises exception """ with patch.object(instagram, 'app_store_center_popup_close'): with patch.object(instagram, 'app_store_footer_popup_close') as fc_mock: cd_prop = PropertyMock(side_effect=[False, True]) t...
63,877
def magma_sgeqrf3_gpu(m, n, A, ldda, tau, dT): """ QR factorization (gpu interface). """ info = c_int_type() status = _libmagma.magma_sgeqrf3_gpu(m, n, int(A), ldda, int(tau), int(dT), ctypes.byref(info)) m...
63,878
def regex_replace_nb( notebook: NotebookNode, replacements: Tuple[Tuple[str, str, str]] ) -> NotebookNode: """Return a new notebook with string regex replacements applied. :param replacements: list of (path, regex, replacement), path is a string of form '/cells/0/outputs', and can contain * wildcar...
63,879
def setUpModule(): """ Before running module. """ pass
63,880
def test_validate_dup_uuids(sample_component_definition: ComponentDefinition) -> None: """Test validation of comp def with duplicate uuids.""" args = argparse.Namespace(mode=const.VAL_MODE_ALL) validator = validator_factory.get(args) # confirm the comp_def is valid assert validator.model_is_valid(s...
63,881
def Axis( color: str = None, grid_color: str = None, grid_lines: str = "solid", label: str = "", label_color: str = None, label_location: str = "middle", label_offset: str = None, num_ticks: int = None, offset: dict = {}, orientation: str = "horizontal", scale: Element[bqplot...
63,882
def _kuhn_munkres_algorithm(true_lab, pred_lab): """ Private function that implements the Hungarian method. It selects the best label permutation of the classification output that minimizes the misclassification error when compared to the clustering labels. :param true_lab: clustering algorithm lab...
63,883
def single(ARGS): """ main entry point for python Super32 assembler (with single storage) """ Settings.load() cfg = FileIO.read_json('instructionset.json') input_file = FileIO.read_code(ARGS['<input-file>']) preprocessor = Preprocessor() assembler = Assembler(Architectures.SINGLE) ...
63,884
async def load_test_system(dir_name, config: dict = None) -> Gateway: """Create a system state from a packet log (using an optional configuration).""" try: with open(f"{dir_name}/config.json") as f: kwargs = json.load(f) except FileNotFoundError: kwargs = {"config": {}} if ...
63,885
def main(): """Function that obtains the arguments and generates data :return: """ parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='./../data/stanford_indoor3d', help='Data directory path to use [default: ./../data/standford_indoor3d]')...
63,886
def score_segment(previous_segment, current_segment, next_segment): """ Computing scores for current segment based on it's surroundings :param previous_segment: segment tuple for previous segment defined as (start, end, gt_event_index, det_event_index, standard_score) or None :param current_segment: seg...
63,887
def te(s, assignment=None): """Convenience wrapper around the meta-language parser.""" return meta.TypedExpr.factory(s, assignment=assignment)
63,888
def segment_single_image(data_root, image_name, save_folder, gray2color): """Inferences DeepLab model and visualizes result. Args: data_folder: test images folder path image_name: image name save_folde: results save folder path (both for gray ones for mIOU evaluation, and color ones) gra...
63,889
def edit_party(party_id): """Edit a specific party.""" details = request.get_json() party = PartyModels().update_party(party_id, details) if party: n_success = make_response(jsonify({ "status" : 200, "mg": "party updated successfully", "data": party }...
63,890
def get_usage_summary(client: AmberApi, site_id: str, start_date: date, end_date: date) -> \ Dict[Tuple[date, str], UsageSummary]: """ Uses the given client to query the Amber API for all Usage data for the specified Site between the given dates (both inclusive), summarises the returned data by date...
63,891
def _convert_to_fzx(font): """Convert monobit font to FZX properties and glyphs.""" # select glyphs that can be included # only codepoints 32--255 inclusive # on extraction 32--127 will be assumed to be ASCII includable = font.subset(codepoints=set(_FZX_RANGE)) dropped = font.without(codepoints=...
63,892
def validate_dataset(data): """ Validate user given dataset """ if data: if not isinstance(data, DatasetAutoFolds): raise ValidationError( "data", 'Unknown data format. Must be and instance of "DatasetAutoFolds". Got "%s"' % type(data),...
63,893
def assert_process_rules(rules, nodes, hash_nodes, start, stop, required, wait, expected_load, running_strategy): """ Check the process rules. """ assert rules.node_names == nodes assert rules.hash_node_names == hash_nodes assert rules.start_sequence == start assert rules.st...
63,894
def Linear_Regularized( name, alphas=(0.1, 1.0, 10.0), folds=10, ): """ FUNCTION: Used to create a Linear Machine Learning model with built-in regularization and cross validation PARAMS: name: str A name/alias given to the model by the user al...
63,895
def randomString(url, stringLength=30): """Generate a random string of fixed length """ Letters = string.ascii_lowercase + string.ascii_uppercase + string.digits url_split = url.split(".") format_ = url_split[-1] s = ''.join(random.choice(Letters) for i in range(stringLength)) + "." + format_ ...
63,896
def print_colored(message, color): """Prints colored the specified text in the chosen color. Args: message (string): a string containing the message to be printed in color. color (string): a string containing the color to print the message in. """ # using term color to print string in s...
63,897
def attempt_symlink_to(path, to_path): """Try to make a symlink from "path" to "to_path", skipping in case this platform does not support it or we don't have sufficient privileges (common on Windows).""" try: Path(path).symlink_to(Path(to_path)) except OSError: pytest.skip("could not cre...
63,898
def p_codeBlock(t): """ codeBlock : R_DECLARE declarationList R_BEGIN plInstructions R_END | R_DECLARE declarationList list_declaraciones_declere R_BEGIN plInstructions R_END | R_BEGIN plInstructions R_END """ if len(t) == 6: t[0] = CodeBlock(lista_instrucciones=t[4] , lista_declaracione...
63,899