content
stringlengths
22
815k
id
int64
0
4.91M
def build_prediction(tracefile_lines, src, dst): """ Provided tracefile data in nstrace format, predict if dst node will fall out of range from src. """ tcp_packet_size = 1000 prediction = {} throughput_history = [] avg_throughput_history = 0 events = trace.get_prediction_events(tracef...
59,100
def self(stack: List[object], stash: List[object]) -> None: """$method -- $method$.__self__""" stack.append(cast(types.MethodType, stack.pop()).__self__)
59,101
def unitSpacing2MM(unit): """ Converts KLE unit spacing into wxPoint spacing. Used in placing KiCAD components """ unitSpacing = 19.050000 wxConversionFactor = 1000000 return unit*unitSpacing
59,102
def test_conformer(species, conf, natom, atom, mult, charge, ts = 0, ring = 0): """ Test whether a conformer has the same bond matrix as the original structure. Returns the conformer object and -1 if not yet finished, 0 if same, and 1 if not. """ r = '' if ring: r = 'r' if ts: j...
59,103
def make_legend_isophotes(ax, lw=2, suffix='', fontsize=18): """ add legend of isophotes """ ax.plot(-1, -1, color='white', lw=lw, label='Isophote'+suffix) # ax.plot(-1, -1, color='red', lw=lw, label='Galaxy mask') lg = ax.legend(loc='lower right', prop={'size':fontsize-4}) frame = lg.get_frame() ...
59,104
def generate_sentence(data): """Generate new Markov chains sentence. This data generates new sentence based on Markov chains algorithm **Note!** Current implementation is buggy and will be changed in future Args: data (list): List of data to work with Returns: chain (list...
59,105
def delete(config: Config, keys: List[str]) -> None: """Delete the listed keys""" while keys: # Can delete up to 1000 keys in a single request. sub_keys = keys[0:1000] del keys[0:1000] debug('Attempting to delete keys {keys}', keys=sub_keys) try: get_s3_client...
59,106
def update_repo_in_cache(repo_name: str, repo_dir: str, app_dir: str) -> None: """ Updates a single repo_details dict in the imported_repos cached list :param repo_name: name of the repo to update :param repo_dir: dir of the repo to update :param app_dir: current application :return: None ""...
59,107
def read_event(io, metadata): """Reads the event that the stream points to. :param io: the stream. :param metadata: metadata of the PML file. :return: Event object. """ process_idx, tid, event_class_val, operation_val, _, _, duration, date, result, stacktrace_depth, _, \ details_size, e...
59,108
def Mean(xs): """Computes mean. xs: sequence of values returns: float mean """ return np.mean(xs)
59,109
def start_upload_listener(event): """ Display info when an upload starts :param StartUploadEvent event: event """ msg = "Upload {rank}/{total}: uploading {filepath}..." print(msg.format(rank=event.upload_file_rank, total=event.files_to_upload, filepath=event.filepath), end='') sys.stdout.f...
59,110
def split_negative_slide(slide: Slide, level, otsu_threshold, poi_threshold=0.01, tile_size=128, overlap=5, verbose: bool = False): """Create tiles from a negative slide. Iterator over the slide in `tile_size`×`tile_size` Tiles. For every tile an otsu mask ...
59,111
def tcp_shasum_calc(src: bytes, dst: bytes, proto: int, payload: bytes) -> bytes: """ Calculate SHA256 sum of a TCP header :param src: source IP address :param dst: destination IP address :param proto: TCP protocol :param payload: TCP payload :return: SHA256 sum """ _sum = struct.pack(">...
59,112
def make_env(unique_name, queue_child=None, mpQueue_parent=None, thQueue_parent=None, seed=123): """This is either given a MP queue or a threading queue in which case it's writing to the queues. Or it's given the handles for BOTH queues in which case it's the main thread, reading from the queues, and displa...
59,113
def call_ellipse_virgofilaments(onegal, galaxy, galaxydir, pixscale=0.262, nproc=1, verbose=False, debug=False, logfile=None, input_ellipse=None, zcolumn=None, sdss=False, sdss_pixscale=0.396, unwise=False, unwise_pixscale=2.75, ...
59,114
def generate_exmat(T_mat, center, tracking): """ Generate the extrinsic matrix for the camera. Develop the extrinsic matrix for the camera, which is used for transforming the object in the world coordinate system into the homogeneous camera coordinate system. Note that the intermediate variable H_...
59,115
def NumStabilityChk(nproc): """...""" import os from modules import InpGen as ig with open("numMethod.inp") as f1: lines1 = f1.readlines() sol_flag = int(lines1[1].rstrip()) if sol_flag >= 50: print(f" >> ERROR: This stability check works only if the last run meth...
59,116
def wiki(searchterm): """return the top wiki search result for the term""" searchterm = quote(searchterm) url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json" url = url.format(searchterm) result = requests.get(url).json() pages = result["query"]["search...
59,117
def bce_loss(prediction, target): """ prediction and target should have the same size. :param prediction: :param target: :return: """ return F.binary_cross_entropy_with_logits(prediction, target)
59,118
def test_EfficientVoiceLeading(): """Test EfficientVoiceLeading module class.""" D_minor_scale = MinorScale('D') D_minor_scale = Chord(D_minor_scale.getPitches('D4', 'C5')) E_major_scale = MajorScale('E') E_major_scale = Chord(E_major_scale.getPitches('E4', 'D#5')) scale = ChromaticScale('C') ...
59,119
def func(*args, **kwargs): """ Summary This function splits an Iterable into the given size of multiple chunks. The items of An iterable should be the same type. Parameters ---------- iterable: Iterable An Iterable to split. how: {'equal', 'remaining'} The method to sp...
59,120
def get_or_create_aa_group(conn: OSConnection, name: str) -> int: """create anti-affinity server group, if doesn't exists yet parameters: conn: OSConnection name: str - group name returns: str - group id """ try: return conn.nova.server_groups.find(name=name).id except ...
59,121
def isMonthly(s): """ This function test if the data are monthly data from the time axis. :param s: A cdms2 TransientVariable :type s: cdms2.tvariable.TransientVariable :returns: An integer flag indicating whether s has monthly data (1), or does not (0). :rtype: int """ tim = s.getTime...
59,122
def get_files(ctx, workflow, _filter, output_format, access_token): """List workflow workspace files.""" logging.debug('command: {}'.format(ctx.command_path.replace(" ", "."))) for p in ctx.params: logging.debug('{param}: {value}'.format(param=p, value=ctx.params[p])) try: ...
59,123
def pressure(v, t, n=6.022e23): """Compute the pressure in pascals of an ideal gas. v -- volume of gas, in cubic meters t -- absolute temperature in degrees kelvin n -- particles of gas (default: one mole) """ return n * k_b * t / v
59,124
def instance_type_destroy(context, name): """ Marks specific instance_type as deleted""" session = get_session() instance_type_ref = session.query(models.InstanceTypes).\ filter_by(name=name) records = instance_type_ref.update(dict(deleted=True)) if records == 0...
59,125
def activate(connection, args): """Activates the given interface. """ iface = sap.adt.Interface(connection, args.name) iface.activate()
59,126
def geneconvLTRs(g='/g0', I=6, clustering_method='WickerFam', WickerParams={'pId':80,'percAln':80,'minLen':80}): """Assesses intra-element gene conversion between LTRs g can be one of /g0, /g1, or /g2 g is proportional to the tolerance for mismatches in ...
59,127
def do_express_payment(token, payer_id, cart, settings): """Call DoExpressCheckoutPayment for each lineitem.""" params = {"METHOD": "DoExpressCheckoutPayment", "TOKEN": token, "PAYERID": payer_id, "PAYMENTREQUEST_0_CURRENCYCODE": "USD", # TODO: Make setting ...
59,128
def get_crs_from_raster(raster_address): """Function reads raster data and gets its coordinate reference system""" with rio.open(raster_address) as f: band_crs = f.crs return band_crs
59,129
def merge(msg_to_ref, ref_msg_pairs): """ Merge ref_msg_pairs into msg_to_ref """ for (ref, msg) in ref_msg_pairs: msg_to_ref.setdefault(msg, set()).add(ref)
59,130
def _build_entrez_map(hgnc_manager: bio2bel_hgnc.Manager) -> Mapping[str, HumanGene]: """Build a mapping from entrez gene identifiers to their database models from :py:mod:`bio2bel_hgnc.models`.""" logger.info('getting entrez mapping') t = time.time() emap = { model.entrez: model for mo...
59,131
def build_conformer_block( block: Dict[str, Any], self_attn_class: str, pw_layer_type: str, pw_activation_type: str, conv_mod_activation_type: str, ) -> ConformerEncoderLayer: """Build function for conformer block. Args: block: Conformer block parameters. self_attn_type: Sel...
59,132
def _stringify_query_build_rows(qb_rows: [], order_by_desc: str = None) -> str: """ 'Stringify' supplied rows by concatenating them, removing the final, dangling 'UNION ALL' keyword, and optionally appending an 'ORDER BY' clause. Intended for use with output rows of query builder algorithms. :param ...
59,133
def tessellation(order, face_centers=False, face_areas=False): """ Constructs a tessellation from a subdivision of an icosahedron. Parameters ---------- order : int The order of the recursive tessellation. compute_face_centers : bool, optional compute_face_areas : bool, optiona...
59,134
def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs): """Runs the given function and arguments in a modified environment.""" try: original_env = environ.copy() environ.update(extra_env) return function(*args, **kwargs) finally: environ.clear() environ.update(original_env)
59,135
def dihedral(bits, f, i): """Apply an element of the dihedral group to a bit board or bit pattern. Args: bits: An integer whose bits represent a pattern on a Yavalath board, or a tuple of integers f: An integer indicating the number of flips about the horizontal axis to...
59,136
def mute(func): """ Decorator Make stdout silent """ def _f(*args, **kwargs): sys.stdout = open(os.devnull, 'w') res = func(*args, **kwargs) sys.stdout.close() sys.stdout = sys.__stdout__ return res return _f
59,137
def automatic_alignment(id_series, id_ep, refsT, hypsT): """Aligns IMDB character's names with transcripts characters names. Parameters ---------- id_series : `str` Id of the series. id_ep : `str` Id of the episode. refsT : `dict` Dictionnary of character's names from tr...
59,138
def add_attribs_reserveds_list(attrib_list): """Add attributes that follow a reserved name to reserveds list.""" if len(attrib_list) > 1: # A single item does not change is_reserved = False reserved_set = set() for name in attrib_list: if not is_reserved: try...
59,139
def type_detect_frame( df: pd.DataFrame, typeset: VisionsTypeset ) -> Dict[str, Type[VisionsBaseType]]: """Detect the type in the base graph Args: df: the DataFrame to detect types on typeset: the Typeset that provides the type context Returns: A dictionary with a mapping from ...
59,140
def cleanup_data(df: pd.DataFrame) -> pd.DataFrame: """Clean up some empty/null values""" df = df.replace(r"^\s+$", nan, regex=True) df = df.replace("", nan, regex=True) return df
59,141
def sigmoid(z): """The sigmoid function """ return 1. / (1. + np.exp(-z))
59,142
def pyccel(): """ pyccel console command. """ class MyParser(argparse.ArgumentParser): """ Custom argument parser for printing help message in case of an error. See http://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without...
59,143
def entrypoint(label): """ If a class if going to be registered with setuptools as an entrypoint it must have the label it will be registered under associated with it via this decorator. This decorator sets the ENTRY_POINT_ORIG_LABEL and ENTRY_POINT_LABEL class proprieties to the same value, la...
59,144
def check_semver(): """Get output from pyang tool with option '--check-update-from' for all the modules between and filter. I. If module compilation failed it will give you only link to get diff in between two yang modules. II. If check-update-from has an output it will provide tree diff and output of the p...
59,145
def main(): """PointViz visualizer examples.""" parser = argparse.ArgumentParser( description=main.__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('pcap_path', nargs='?', metavar='PCAP', hel...
59,146
def plot_concept_activation(sentence, activations, concepts_delim,nb_concepts, output_function = None, savefig=False, sub_ttl_fig='', ylims=(-0.4, 1.4)): """ Plots activation through time of the different concepts while hearing the sentence. If output_function is not None, it is applied to the re...
59,147
def dictionary_and_embeddings_to_indices(word_frequencies, embeddings): """ Sort words by frequency (descending), adds offset (3 items), maps word indices to embeddings and generate random embeddings for padding, start of sequence, and OOV :param word_frequencies: dict (word: frequency) :param embed...
59,148
def check_already_unfollowed(self, user_id): """ controls if user was already unfollowed before """ if ( self.follows_db_c.execute( "SELECT EXISTS(SELECT 1 FROM usernames WHERE username_id='" + user_id + "' AND unfollow_count > 0 LIMIT 1)" ).fetchone()[0] ...
59,149
def base_seir_model_OLD(param, dict): """ # S=susceptable, E=exposed, I=infected, R=Removed (with icfrac with a delay of idelayD) # Added: Recovered, Hospitalized, Dead :param param: :param dict: :return: """ n, r0, sigma, gamma, alpha, delay_hos, delay_rec, delay_hosrec, delay_hosd, ho...
59,150
def get_view_edge(state: SDFGState, view: nd.AccessNode) -> gr.MultiConnectorEdge[mm.Memlet]: """ Given a view access node, returns the incoming/outgoing edge which points to the viewed access node. See the ruleset in the documentation of ``dace.data.View``. :param state: The state in which the vie...
59,151
def service(service, private_base_url): """Add upstream policy""" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig("upstream", { "rules": [{"url": private_base_url("echo_api"), "regex": "/httpbin"}]})) return service
59,152
def edit_pb_txt(old_args, export_dir): """ Edit file path argument in pbtxt file. :param old_args: Old file paths need to be copied and edited. :param export_dir: Directory of the saved model. """ assets_extra_dir = os.path.join(export_dir, "./assets.extra") if not os.path.exists(assets_extra_dir): os...
59,153
def sanity_check_inputs(unet_patch_side, unet_batch_size, unet_threshold, overlapping, new_spacing, conv_filters, cv_folds, anatomically_informed_sliding_window, test_time_augmentation, reduce_fp, max_fp, reduce_fp_with_volume, min_aneurysm_volume, remove_dark_fp, bids_dir, training_outputs_path...
59,154
def reduce_mem_usage(df, columns=None, verbose=True, debug=False): """ Reduce memory usage of provided DataFrame using best dtype for each column """ from tqdm import tqdm_notebook if columns == None: columns = df.columns elif len(columns) == 0: return df if verbose: print...
59,155
def metadata(): """ Provides the metadata for the Real plug-in. This gives human-readable information on the plug-in, dependency resolution information, and tells the plug-in system what this plug-in can do. :return: Dictionary of metadata. """ return { "name": "Real", "description": "Defines real numbers t...
59,156
def update_home_tab(): """ Schedules an update to the home tab, to occur in the next asyncio update """ global should_update_home_tab home_tab_lock.acquire() should_update_home_tab = True home_tab_lock.release()
59,157
def hide_empty(value, prefix=', '): """Return a string with optional prefix if value is non-empty""" value = str(value) return prefix + value if value else ''
59,158
def merge_layers_on_edges(mask): """ First merges layers left halves to right halves, then top to bottom. """ lr_center = mask.shape[1] // 2 left_half_idx = np.argwhere(mask[:, lr_center - 1, :].sum(axis=0) > 0).flatten() right_half_idx = np.argwhere(mask[:, lr_center, :].sum(axis=0) > 0).flatte...
59,159
def move_snake(keys, snake): """Move snake if only one key is being pressed.""" count = 0 key_pressed = '' for key, pressed in keys.items(): if pressed: key_pressed = key count += 1 if count == 1: snake.set_direction(key_pressed)
59,160
def scrollTo(driver, element, *args, **kwargs): """ This function use continuousScroll to scroll to an element The page is centered to the element You can give smartScroll parameters in *args, **kwargs """ y = element.location["y"] (scrollTop, scrollBottom, windowHeight, document...
59,161
def kvlds_length_and_bytes(data): """ Make some bytes storing the length and data in the kvlds format. """ # Sanity check if not isinstance(data, bytes): raise NotBinaryData() if len(data) > 255: raise KivalooTooMuchData() # Return form expected by kivaloo return struct.pack('>B...
59,162
def answer(sentence): """ This is the main function of all the project, it recibes a sentence: p:sentence And using other functions in our project, implements the bag of words algorithm to answer it. """ # check if the user wants to exit the chat if sentence == 'STOP': # break the program print('BOG retu...
59,163
def pluginunload(bot, event, *args): """unloads a previously unloaded plugin, requires plugins. prefix""" if args: module_path = args[0] try: yield from plugins.unload(bot, module_path) message = "<b><pre>{}</pre>: unloaded</b>".format(module_path) except (Runt...
59,164
def asset_key(assets: List[str]) -> str: """Convert multiple version specs into a URL-friendly key.""" return make_name( '-'.join(assets) .replace('==', '-eq-') .replace('>=', '-gte-') .replace('<=', '-lte-') .replace('>', '-gt-') .replace('<', '-lt-'), ma...
59,165
def request_clone_or_create(request, rid, title, submit_url, TRequestCreateCloneForm, TRequestCreateCloneConfirmation, form_prefill, default_step_values = {'nEventsPerJob':'1000','priority':'880'}): """ Fill form for creating request. Create request->slice->steps for POST View cr...
59,166
def LF_DG_BICLUSTER_OVEREXPRESSION(c): """ This label function uses the bicluster data located in the A global network of biomedical relationships """ sen_pos = c.get_parent().position pubmed_id = int(c.get_parent().document.name) if (pubmed_id, sen_pos) in overexpression_base: retur...
59,167
def check_table_and_warn_if_dmg_freq_is_low(folder): """Returns true if the damage frequencies are too low to allow Bayesian estimation of DNA damages, i.e < 1% at first position. """ logger = logging.getLogger(__name__) filename = "misincorporation.txt" mismatches = { "5p": {"C": 0, "C>...
59,168
def preauction_filters(participants, task, indivisible_tasks=False): """Apply some preauction filters to the participants list in order to remove any invalid candidates. Args: participants (list): A list of participating nodes and their info. indivisible_tasks (bool): Only allow nodes that offe...
59,169
def test_delete_gif_by_id_admin(client: FlaskClient, db_session) -> None: """Assert when DELETE /gifs/<gif_id> is requested, that admin users are allowed to make the request, and that the gif is deleted from the database. Args: client (:obj:`~flask.testing.FlaskClient`): The Client fixture. ...
59,170
def test_api_accessing_hidden_users(): """Hidden users should not be visible to normal users, only to admins""" app = create_ctfd() with app.app_context(): register_user(app, name="visible_user", email="visible_user@ctfd.io") register_user(app, name="hidden_user", email="hidden_user@ctfd.io"...
59,171
def mk_fitfunc(fname, pnames, globname, extraargs=[]): """ Dynamically make a fit function for the given param names, to be passed to Minuit. Return a string definition of the function, to be exec'd, and the list of generated internal arg names corresponding to pnames. """ fargs = ["A%03i" % i ...
59,172
def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Faster R-CNN demo') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--cpu', dest='cpu_mode', ...
59,173
def setTOURL(url:str) -> bool: """ Sets the :data:`TO_USE_SSL`, :data:`TO_PORT` and :data:`TO_HOST` global variables and verifies, them. :param url: A full URL (including schema - and port when necessary) specifying the location of a running Traffic Ops server :returns: whether or not the URL could be set succe...
59,174
def test_two_span( test_data: data.DataLoader, model: transformers.PreTrainedModel, loss_func: nn.modules.loss._Loss, ids: List[int], dev=None ) -> Tuple[float, float, float]: """Test a two span edge probing model. Args: test_data: test dataset. m...
59,175
def set_env_solver_nodes(lattice, perveance, max_sep=0.01, min_sep=1e-6): """Place a set of envelope solver nodes into the lattice. The method will place the set into the lattice as child nodes of the first level accelerator nodes. The nodes will be inserted at the beginning of a particular part of...
59,176
def compile_file(dir): """ Compile a py file """ try: import compileall compileall.compile_dir(dir=dir, ddir=dir, force=0, quiet=report_problem) except Exception: return sys.exc_info()[1] return None
59,177
def child(): """获取子程序的pid""" print("Hello from child, ", os.getpid()) os._exit(0)
59,178
def render_question_type_049(workspace, module, node, question, answer): """ Dependency: - QID: 77 | I will offer the the following incentives to get customers to try my products or services - QID: 78 | I will use the following physical marketing materials as ways to communicate my product or service to...
59,179
def default_on_failure(request, message, **kwargs): """ default failure action on signin """ return render('openid_failure.html', { 'message': message })
59,180
def insert_vendor(vendor_name): """ insert a new vendor into the vendors table """ sql = """INSERT INTO vendors(vendor_name) VALUES(%s) RETURNING vendor_id;""" conn = None vendor_id = None try: # read database configuration params = config() # connect to the Post...
59,181
def isSymmetric(root): """ :type root: TreeNode :rtype: bool """ if not root: return True leftPart=[root.left] rightPart=[root.right] while leftPart and rightPart: leftNode=leftPart.pop() rightNode=rightPart.pop() if leftNode and rightNode: if ...
59,182
def test_decoder_cache_shrink_threadsafe(monkeypatch, tmp_path): """Tests that shrink handles files deleted by other processes.""" cache_dir = str(tmp_path) solver_mock = SolverMock() with DecoderCache(cache_dir=cache_dir) as cache: cache.wrap_solver(solver_mock)(**get_solver_test_args()) ...
59,183
def convert_request_to(target): """ convert different kinds of request to needed input. there are 4 needed inputs: - GraphNode - GraphRelation - RawString - ExtractorInput """ def _convert_request_to(func): @wraps(func) def wrapper(self, request, context): ...
59,184
def set_context(data, key="custom"): """ Attach contextual data to the current transaction and errors that happen during the current transaction. If the transaction is not sampled, this function becomes a no-op. :param data: a dictionary, or a callable that returns a dictionary :param key: the nam...
59,185
def test_consumer_register(pyoslc): """ GIVEN the PyOSLC API WHEN requesting the creation of a consumer THEN validating the status code of the response parsing the response content into json validating the key content in the response """ response = pyoslc.create_consumer...
59,186
def plot_env(env, run_id: int = -1, colors=('b', 'r'), draw_start_goal=True, draw_start_goal_thetas=False, show_start_goal_labels=True, set_title=True, show_distances=False, custom_min_x=None, custom_min_y=None, custom_max_x=None, custom_max_y=None, ...
59,187
def json_serial(obj): """ JSON serializer for datetime objects """ if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError ("Type %s not serializable" % type(obj))
59,188
def thick_plane_points(plane: Plane, thickness, plane_point=None): """ Convert plane point to two thick plane points. Given a Plane and a thickness, return two points along the normal that are `thickness` apart. Optionally specify a specific point in the plane. """ if plane_point is None: ...
59,189
def get_timestamp_string( date_array ): """ Convenience function returning the datetime timestamp based on the given input Args: date_array: array Array of integers corresponding to [year, month, day, hour, minute, second]. Any integers not provided will be padded ac...
59,190
def Tracker(switch=1,targetName="Landmark", targetParam=0.1): """Turn tracker on or off. Or get status = 2""" ##Target Parameters Comment ##RedBall diameter of ball (meter) Used to compute the distance between robot and ball. ##Face width of face (meter) Used to compute the distance ...
59,191
def from_file(file, gpu=None): """Preprocess pitch from file""" return from_audio(cargan.load.audio(file), cargan.SAMPLE_RATE, gpu)
59,192
def mod(t1, t2): """ Element-wise division remainder of values of operand t1 by values of operand t2 (i.e. t1 % t2), not commutative. Takes the two operands (scalar or tensor) whose elements are to be divided (operand 1 by operand 2) as arguments. Currently t1 and t2 are just passed to remainder. ...
59,193
def check_date(birth_date): """If false it has a validation message with it""" if birth_date != None: birth_date = birth_date.strip() if birth_date == '': return (False, "Please Enter Your Birth Date") try: time.strptime(birth_date, '%m/%d/%Y') birth_...
59,194
def gdb_run_silent_cmd(cmd: CommandType, before: CommandType = (), after: CommandType = (), target: Path = DEFAULT_TARGET, strip_ansi: bool = STRIP_ANSI_DEFAULT) -> str: """Disable the output and run entirely the `target` binary.""" before = [*before, "gef config co...
59,195
def get_instance_data(instance_id): """Fetch instance details and return type and subnet.""" try: result = ec2_client.describe_instances(InstanceIds=[instance_id]) vpc_subnet_id = result['Reservations'][0]['Instances'][0]['SubnetId'] instance_type = result['Reservations'][0]['Instances'...
59,196
def can_finetune( last_fingerprint: Fingerprint, new_fingerprint: Fingerprint, core: bool = False, nlu: bool = False, ) -> bool: """Checks if components of a model can be finetuned with incremental training. Args: last_fingerprint: The fingerprint of the old model to potentially be fine...
59,197
def test_variable_interpolation_stage_parameters_funny(ys1): """This test won't work and I'm not sure why: 1. Maybe parsing the yaml file won't get the same unicode code? 2. Regex won't capture it""" with patch("builtins.open", mock_open(read_data=ys1)) as mock_file: ctx = build_context( ...
59,198
def test_generate_classical_meta_knowledge_graph(): """ Test generate meta knowledge graph operation. """ input_args = { "filename": [ os.path.join(RESOURCE_DIR, "graph_nodes.tsv"), os.path.join(RESOURCE_DIR, "graph_edges.tsv"), ], "format": "tsv", } ...
59,199