content
stringlengths
22
815k
id
int64
0
4.91M
def plot_target_measure(config_list, target_list, measure_list_mm, ax): """ plot target and measure """ test_type = config_list[0] boundary_error_threshold = config_list[4] center_error_threshold = config_list[5] for i in range(len(target_list)): if test_type == "line test": ...
25,200
def process_temp_config(configs, verbose=True): """ Temporarily set the sysctl configs. Given configs must follow format: Key=variable; Value=variable_value when evaluated as a string """ assert isinstance(configs, dict) assert isinstance(verbose, bool) print(f"\nVariables to set:\n...
25,201
def main(): """ Main entry point for module execution :returns: the result form module invocation """ module = AnsibleModule( argument_spec=Bgp_globalArgs.argument_spec, mutually_exclusive=[], required_if=[], supports_check_mode=False, ) result = Bgp_global(...
25,202
def write_curies(filepaths: dict, ontoid: str, prefix_map: dict, pref_prefix_map: dict) -> bool: """ Update node id field in an edgefile and each corresponding subject/object node in the corresponding edges to have a CURIE, where the prefix is the ontology ID and the class is inferred fr...
25,203
def split(time: list, value: list, step, group_hours, region=None, whole_group=False): """ Split and group 'step' number of averaged values 'hours' apart :param time: time per value (hour apart) :param value: values corresponding to time :param step: number of group times set for each index...
25,204
def launch_ebs_affinity_process(instanceid, instance_infos, ebs_configs): """ Manage the ebs affinity process. :param instanceid string The instance id :param instance_infos dict Informations about the instance :param ebs_config dict The EBS parameters :return None """ ...
25,205
def forecast_plot(train, test, fitted_values, forecast_values, new_fig=False, plot_title="Forecast"): """ Plot train data, test data, fitted values of the model and the predicted/forecast values Params: train : the train dataframe test : the test dataframe fitted_values :...
25,206
def get_all(isamAppliance, check_mode=False, force=False): """ Retrieve a list of mapping rules """ return isamAppliance.invoke_get("Retrieve a list of mapping rules", "/iam/access/v8/mapping-rules")
25,207
def neg(program: MipsProgram, rd: str, rs: str): """Negate Reg[rs] and store in Reg[rd].""" program.registers[rd] = ((~program.registers[rs]) & 0xFFFF_FFFF) + 1
25,208
def get_oyente(test_subject=None, mutation=None): """ Run the Oyente test suite on a provided script """ is_request = False if not test_subject: test_subject = request.form.get('data') is_request = True o = Oyente(test_subject) info, errors = o.oyente(test_subject) if len(errors) > 0: errors = [{'lin...
25,209
def search_for_example(search_string: str) -> tuple: """Get the Example for a Particular Function""" function = match_string(search_string) if function: function = function.strip() sql = f"SELECT example, comment FROM example WHERE function='{function}'" data = execute(sql) ...
25,210
def WildZumba(x,c1=20,c2=0.2,c3=2*np.pi) : """ A separable R**n==>R function, assumes a real-valued numpy vector as input """ return -c1 * np.exp(-c2*np.sqrt(np.mean(x**2))) - np.exp(np.mean(np.cos(c3*x))) + c1 + np.exp(1)
25,211
def add_arguments_extended(parser: KGTKArgumentParser, parsed_shared_args: Namespace): """ Parse arguments Args: parser (argparse.ArgumentParser) """ from kgtk.io.kgtkreader import KgtkReader, KgtkReaderOptions from kgtk.utils.argparsehelpers import optional_bool from kgtk.value.kgtk...
25,212
def import_xlsx(filename, skip_variation=False): """Импортирует параметры пиков, хроматограммы и варьируемых параметров, если они указаны. Parameters ---------- filename : str Имя xlsx файла. skip_variation : bool, default = False Пропустить блок Variation даже если он есть. Re...
25,213
def _get_dataset_builder( dataset: Union[str, tfds.core.DatasetBuilder], data_dir: Optional[str] = None) -> tfds.core.DatasetBuilder: """Returns a dataset builder.""" if isinstance(dataset, str): dataset_builder = tfds.builder(dataset, data_dir=data_dir) elif isinstance(dataset, tfds.core.DatasetBuild...
25,214
def build_design(yamlfile, sources_dir=None, part=None): """Generate a complete project :param yamlfile: file describing the top design :param sources_dir: directory to scan to include additional HDL files to core file """ ipc = IPConnect() with open(yamlfile) as f: design = lo...
25,215
def write_bbox(scene_bbox, out_filename): """Export scene bbox to meshes Args: scene_bbox: (N x 6 numpy array): xyz pos of center and 3 lengths out_filename: (string) filename Note: To visualize the boxes in MeshLab. 1. Select the objects (the boxes) 2. Filters -> Po...
25,216
def test_get_sr_no_results(client): """Assert that searching for a sr filing on a coop without one returns a 404.""" rv = client.get('/api/v1/businesses/CP0000000/filings/specialResolution') assert 404 == rv.status_code
25,217
def label_rotate(annot, rotate): """ anti-clockwise rotate the occ order annotation by rotate*90 degrees :param annot: (H, W, 9) ; [-1, 0, 1] :param rotate: value in [0, 1, 2, 3] :return: """ rotate = int(rotate) if rotate == 0: return annot else: annot_rot = np.rot9...
25,218
def allocate_available_excess(region): """ Allocate available excess capital (if any). """ difference = region['total_revenue'] - region['total_cost'] if difference > 0: region['available_cross_subsidy'] = difference region['deficit'] = 0 else: region['available_cross_s...
25,219
def items(dic): """Py 2/3 compatible way of getting the items of a dictionary.""" try: return dic.iteritems() except AttributeError: return iter(dic.items())
25,220
def new_settingsresponse_message(loaded_json, origin): """ takes in a request - executes search for settings and creates a response as bytes :param loaded_json: :param origin: is this a response of drone or groundstation :return: a complete response packet as bytes """ complete_response = {}...
25,221
def validate(config_dir_path: Parameter.REQUIRED, **kwargs): """ Validate an Ambassador configuration. This is an extension of "config" that redirects output to devnull and always exits on error. :param config_dir_path: Configuration directory to scan for Ambassador YAML files """ config(config...
25,222
def list_icmp_block(zone, permanent=True): """ List ICMP blocks on a zone .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewlld.list_icmp_block zone """ cmd = "--zone={0} --list-icmp-blocks".format(zone) if permanent: cmd += " --permanent" ...
25,223
def AddVirtualCurrencyTypes(request, callback, customData = None, extraHeaders = None): """ Adds one or more virtual currencies to the set defined for the title. Virtual Currencies have a maximum value of 2,147,483,647 when granted to a player. Any value over that will be discarded. https://docs.microso...
25,224
def dependencies_found(analysis_id, execution_id): """ Installation data from buildbot. Requires a JSON list of objects with the following keys: * installer: The system used to install the dependency. * spec: The full specification used by the user to request the package. ...
25,225
def dict_merge(dct, merge_dct): """ Taken from https://gist.github.com/angstwad/bf22d1822c38a92ec0a9 Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is m...
25,226
def set_augmentor(): """ Set the augmentor. 1. Select the operations and create the config dictionary 2. Pass it to the Augmentor class with any other information that requires 3. Return the instance of the class. :return: """ config = {'blur': {'values': ('gaussian', 0.7, 1.0), 'prob': ...
25,227
def get_global_event_logger_instance(): """Get an event logger with prefilled fields for the collection. This returns an options configured event logger (proxy) with prefilled fields. This is almost CERTAINLY the event logger that you want to use in zaza test functions. :returns: a configured Log...
25,228
def plot_market_entry(cat_entry_and_exit_df, cat_entry_and_exit_df_2): """ returns a plot with the entry and exit of firms per category """ # get the limits so everything is on the same scale df = pd.concat([cat_entry_and_exit_df, cat_entry_and_exit_df_2]) limits = [-df.exit.max() - 0.3, df.entr...
25,229
def load_surface_file(file_name): """Load a CONVERGE surface data file into Tecplot 360. This will create a new dataset in the active frame or create a new frame if the active frame already has a dataset. """ import os try: print("Loading ASCII file") nodes, verts = get_surf...
25,230
def burt2020_surrogates(name, scale): """ Generates surrogates according to Burt et al., 2020, NeuroImage Parameters ---------- atlas : {'atl-cammoun2012', 'atl-schaefer2018'}, str Name of atlas for which to load data scale : str Scale of atlas to use """ # load data + ...
25,231
def find_elements_by_image(self, filename): """ Locate all the occurence of an image in the webpage. :Args: - filename: The path to the image to search (image shall be in PNG format). :Returns: A list of ImageElement. """ template = cv2.imread(filename, cv2.IMREAD_UNCHANGED) ...
25,232
def compile_tf_signature_def_saved_model( saved_model_dir: str, saved_model_tags: Set[str], module_name: str, exported_name: str, input_names: Sequence[str], output_names: Sequence[str]) -> Modules: """Compiles a SignatureDef SavedModel to each backend that we test. Args: saved_model_dir: Directory...
25,233
def origtime2float(time): """ converts current datetime to float >>> import datetime >>> t = datetime.datetime(2010, 8, 5, 14, 45, 41, 778877) >>> origtime2float(t) 53141.778876999997 """ t3fmt = time.strftime("%H:%M:%S:%f") return time2float(t3fmt)
25,234
def test_commands(cam): """Short hand commands should work as intended.""" # get_information cmd = cam.prefix + [("cmd", "getinfo"), ("dev", "stage")] information = cam.get_information() should_be = tuples_as_dict(cmd) assert information == should_be # start_scan cmd = cam.prefix + [(...
25,235
def set_level(lvl, log_to_syslog): """ Sets the log level :param lvl: Log level as ERR/INFO/DEBUG; default: syslog.LOG_ERR :param log_to_syslog; True - write into syslog. False: skip :return None """ global report_level global write_to_syslog write_to_syslog = log_to_syslog if (...
25,236
def test_setitem_downstream_doesnt_affect_upstream_backprop(): """Test that upstream computational graph is not affected by downstream set-item""" x = Tensor([1.0, 2.0, 3.0, 4.0]) y = Tensor([-1.0, -2.0, -3.0, -4.0]) z = x * y y[:] = 0 z.backward() assert_allclose(np.ones_like(z.data), z....
25,237
def discrete_fourier_transform1(freq, tvec, dvec, log=False): """ Calculate the Discrete Fourier transform (slow scales with N^2) The DFT is normalised to have the mean value of the data at zero frequency :param freq: numpy array, frequency grid calculated from the time vector :param tvec: numpy a...
25,238
def ngram_overlaps(a: List[str], b: List[str], threshold: int = 3) -> List[int]: """ Compute the set over overlapping strings in each set based on n-gram overlap where 'n' is defined by the passed in threshold. """ def get_ngrams(text): """ Get a set of all the ngrams in the text ...
25,239
def update_spec_cache(resources: Resources = None, spec_dir: str = None) -> None: """ Allows users to update specified specs in cache. If nothing specified, all urls in "RESOURCES" are updated in the Tapipy folder. If a folder is specified, all urls specified are updated there. """ if not re...
25,240
def ssq_cwt(x, wavelet='morlet', scales='log', nv=None, fs=None, t=None, ssq_freqs=None, padtype='symmetric', squeezing='sum', difftype='direct', difforder=None, gamma=None): """Calculates the synchrosqueezed Continuous Wavelet Transform of `x`. Implements the algorithm described in Sec....
25,241
def test_board_clear(): """Test if the board resets whenever clear is called""" board = Board(size=(3, 3)) board.add(lf.Blinker(length=3), loc=(0, 1)) board.clear() assert len(np.unique(board.state)) == 1 assert np.unique(board.state)[0].astype(int) == 0
25,242
def request_retry_decorator(fn_to_call, exc_handler): """A generic decorator for retrying cloud API operations with consistent repeatable failure patterns. This can be API rate limiting errors, connection timeouts, transient SSL errors, etc. Args: fn_to_call: the function to call and wrap around ...
25,243
def mass_vulndata(): """ Add a vulndata to a lot of hosts TODO: This! """ host_ids = [] if request.vars.has_key('host_ids'): for z in request.vars.host_ids.split('|'): if z is not '': host_ids.append(z) form=SQLFORM.factory( Field('vulndata', 'ref...
25,244
def lambda_handler(event, context): """ 1. Receive from data from the lambda event. 2. DynamoDB: Stores incomming form data 3. Discord: Posts notification to a channel 4. Mailgun: sends notification args: - event: Event data that has trigged the lambda function - context: "...
25,245
async def establish_async_connection(config: json, logger: AirbyteLogger) -> AsyncConnection: """ Creates an async connection to Firebolt database using the parameters provided. This connection can be used for parallel operations. :param config: Json object containing db credentials. :param logger:...
25,246
def _wrap_with_before(action, responder, resource=None, is_method=False): """Execute the given action function before a responder method. Args: action: A function with a similar signature to a resource responder method, taking (req, resp, resource, params) responder: The responder m...
25,247
def last_day_of_month(d): """ From: https://stackoverflow.com/a/43088/6929343 """ if d.month == 12: return d.replace(day=31) return d.replace(month=d.month+1, day=1) - datetime.timedelta(days=1)
25,248
def plot_landscape(landscape): """ Plot all landscapes for a given (set of) diagrams Inputs: ------- landscape (list): Output of one iteration of persim.to_landscape() Outputs: -------- Plots for each landscape in the list Returns: -------- None """ # ...
25,249
def get_access_token(): """Return access token for use in API request. Raises: requests.exceptions.ConnectionError. """ credentials, _ = google.auth.default(scopes=[ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only' ...
25,250
def _singleInstrumentParametersToJson(instrument: InstrumentBase, get: bool = False, addPrefix: str = '', includeMeta: List[str] = [], excludeParameters: List[str] = []...
25,251
def check_type(value: Optional[object], info: QAPISourceInfo, source: str, allow_array: bool = False, allow_dict: Union[bool, str] = False) -> None: """ Normalize and validate the QAPI type of ``value``. Python types of ``str`` or ``None`` are alw...
25,252
def unknown_action(player: Player, table: dynamodb.Table) -> ActionResponse: """ Do nothing because the action could not be resolved. In the message list, returns a message saying the action was bad. :return: Original inputs matching updated inputs, and a message """ message = ["Action could no...
25,253
def loadThemes(): """ Load default and user themes (if exist) """ def loadThemesFromDir(dname, isBuiltin=False): if not os.path.isdir(dname): return for fname in [fname for fname in os.listdir(dname) if fname.endswith(".theme")]: try: theme = ssdf...
25,254
def dump_garbage(): """ show us what's the garbage about """ # force collection print "\nGARBAGE:" gc.collect() print "\nGARBAGE OBJECTS:" for x in gc.garbage: s = str(x) if len(s) > 80: s = s[:80] print type(x),"\n ", s
25,255
def forecast_marginal_bindglm(mod, n, k, X=None, nsamps=1, mean_only=False): """ Marginal forecast function k steps ahead for a binomial DGLM """ # Plug in the correct F values F = update_F(mod, X, F=mod.F.copy()) # F = np.copy(mod.F) # if mod.nregn > 0: # F[mod.iregn] = X.reshape(mo...
25,256
def _list_redundant(namespace): """Generate a list of configured policies which match defaults. This checks all policies loaded from policy files and checks to see if they match registered policies. If so then it is redundant to have them defined in a policy file and operators should consider removing ...
25,257
def import_file(isamAppliance, id, filename, check_mode=False, force=False): """ Importing a file in the runtime template files directory. """ warnings = [] check_file = _check(isamAppliance, id) if check_file != None and force == False: warnings.append("File {0} exist.".format(id)) ...
25,258
def createOverlayMap(*args, **kwargs): """ Create overlay map """ pass
25,259
def get_func_from_attrdict(func_name : str, attrdict : AttrDict) -> ObjectiveFunction1D: """ Given a string func_name, attempts to find the corresponding entry from attrdict. :param func_name :param attrdict :returns Objective Function """ for key, val in attrdict.items(): if val.n...
25,260
def event_handle(handle_code): """ Performs HTTP request-response procedure :param handle_code: customer's code :type handle_code: fdk.customer_code.Function :return: None """ async def pure_handler(request): from fdk import runner log.log("in pure_handler") headers =...
25,261
def load_precomputed_embeddings(det_df, seq_info_dict, embeddings_dir, use_cuda): """ Given a sequence's detections, it loads from disk embeddings that have already been computed and stored for its detections Args: det_df: pd.DataFrame with detection coordinates seq_info_dict: dict with ...
25,262
def printerr(text, width=80, errtype=None): """ Small utility to print custom errors with proper indentation and text wrapping. The only error types coded are `error` and `warning`. Parameters: text (str): String of text without the preceding error flag that will be formated width (int)...
25,263
def _model_gpt(size=0, dropout_rate=0.0, attention_dropout_rate=0.0): """Configs for a variety of Transformer model sizes.""" num_layers = [1, 3, 6, 12, 24, 36, 48][size] dim = [64, 128, 512, 768, 1024, 1280, 1600][size] num_heads = int(dim / 64) # Always dim 64 per head return _transformer( emb_dim=di...
25,264
def parse_local_alignments(input_stream: Iterable[str]) -> Iterable[dict]: """Parse DALIGNER LAdump local alignments. This function reads from an iterable `input_stream` the available local alignments encoded in DALIGNER LAdump format. In other words, you could pipe the output of LAdump to this functio...
25,265
def create_cxr_test_dataset(path_to_test_dataset: Path, num_encoder_images: int = 200, num_labelled_images: int = 300) -> None: """ Creates fake datasets dataframe and dicom images mimicking the expected structure of the datasets of NIHCXR and RSNAKagg...
25,266
def test_module(client, demisto_args: dict): """ Test the OMWS Client connection by attempting to query a common username """ d = client.query_profile_data("maneenus") if d: return 'ok' else: raise DemistoException("Incorrect or empty API response")
25,267
def docs(open_browser=True): """ Generage Sphinx HTML documentation, including API docs. Args: open_browser: Open browser automatically after building docs """ local('rm -f docs/python_boilerplate.rst') local('rm -f docs/modules.rst') local('rm -f docs/python_boilerplate*') loca...
25,268
def as_string(raw_data): """Converts the given raw bytes to a string (removes NULL)""" return bytearray(raw_data[:-1])
25,269
def init_suffix_tree(tld_file=None): """Call this first to initialize the suffix tree""" if tld_file is None: tld_file = os.path.join(os.path.dirname(__file__), 'public_suffix_list.txt') fp = open(tld_file) suffix_lines = fp.readlines() suffix_rules = _tokenize(suffix_lines) fp.close() ...
25,270
def plot_series_statistics(observed=None, expected=None, total_stdev=None, explained_stdev=None, color_set='Set2', xscale="linear", yscale="linear", ...
25,271
def generate_trapezoid_profile(max_v, time_to_max_v, dt, goal): """Creates a trapezoid profile with the given constraints. Returns: t_rec -- list of timestamps x_rec -- list of positions at each timestep v_rec -- list of velocities at each timestep a_rec -- list of accelerations at each timeste...
25,272
def read_trigger_config(filename): """ filename: the name of a trigger configuration file Returns: a list of trigger objects specified by the trigger configuration file. """ # We give you the code to read in the file and eliminate blank lines and # comments. You don't need to know how it works for no...
25,273
def list_graphs(NextToken=None, MaxResults=None): """ Returns the list of behavior graphs that the calling account is a master of. This operation can only be called by a master account. Because an account can currently only be the master of one behavior graph within a Region, the results always contain a si...
25,274
def main(args): """ Main function of PyGalGen generator Parameters ---------- args : list of command line arguments: Returns ------- Error code """ logging.basicConfig(level=logging.DEBUG) parser = define_default_params() pipeline = PipelineExecutor(parser) logging....
25,275
def query_pypi(spec_pk): """ Query one spec of package on PyPI""" spec = Spec.objects.get(pk=spec_pk) logger.debug('[PYPI] Fetching data for %s' % spec) pkg_data = PyPI().get_info(spec.name, spec.version) if not pkg_data: logger.debug('[PYPI] Errored %s ' % spec) spec.status = 'erro...
25,276
def plot_results(results, time_axis, filename, molecule_name): """ Plots the results of the end-to-end-distance test, lever angle test and twist_amount test, if they exist. Saves pdf plots to the working directory. In: results, a dictionary containing a number of named 1-d arrays created in run_sequ...
25,277
def get_logger(name: str, format_str: str = aps_logger_format, date_format: str = aps_time_format, file: bool = False) -> logging.Logger: """ Get logger instance Args: name: logger name format_str|date_format: to configure logging format f...
25,278
def to_tensor(args, device=None): """Convert an arg or sequence of args to torch Tensors """ singleton = not isinstance(args, (list, tuple)) if singleton: args = [args] tensor_args = [] for arg in args: if isinstance(arg, torch.Tensor): tensor_args.append(arg) ...
25,279
def main(self): """ to run: kosmos 'j.data.bcdb.test(name="meta_test")' """ bcdb, _ = self._load_test_model() assert len(bcdb.get_all()) == 0 assert len(bcdb.meta._data["url"]) == 7 s = list(j.data.schema._url_to_md5.keys()) assert "despiegk.test" in s m = bcdb.model_get(u...
25,280
def test_parse_fails(py_c_token) -> None: """Test various forms of invalid syntax to ensure they indeed fail.""" def t(text): """Test a string to ensure it fails parsing.""" try: result = Property.parse(text) except KeyValError: pass else: pyte...
25,281
def draw_grid(pygame_window: pygame.Surface, grid: List[List[Vertex]], num_rows: int, grid_width: int) -> None: """Draw a complete grid on pygame_window corresponding to the input grid, num_rows and grid_width """ pygame_window.fill(THECOLORS['white']) # fills screen with one color f...
25,282
def test_multiple_inputs(): """ Create a VectorSpacesDataset with two inputs (features0 and features1) and train an MLP which takes both inputs for 1 epoch. """ mlp = MLP( layers=[ FlattenerLayer( CompositeLayer( 'composite', ...
25,283
def snake_head_only(): """ |===========| |···········| |···········| |···········| |···········| |···········| |···········| |·······o···| |···········| |···········| |···········| |···········| |===========| """ return Snake.from_dict( **{ ...
25,284
def test_post_new_org_empty_params(): """ empty new org name and short name parameters is a bad request """ res = requests.post( f'{env.AWG_BASE_URL}{ORG_URL}', headers=utils.BASE_HEADERS, json={ 'name': '', 'short_name': '' } ) assert res.status_c...
25,285
def str_to_bool(s): """Convert a string value to its corresponding boolean value.""" if isinstance(s, bool): return s elif not isinstance(s, six.string_types): raise TypeError('argument must be a string') true_values = ('true', 'on', '1') false_values = ('false', 'off', '0') if...
25,286
def id_feat_pred_mz_rt(cursor, mz, rt, ccs, tol_mz, tol_rt, tol_ccs, esi_mode, norm='l2'): """ id_feat_pred_mz_rt description: identifies a feature on the basis of predicted m/z and retention time parameters: cursor (sqlite3.Cursor) -- cursor for querying lipids.db mz (float) -- m/z ...
25,287
def generate(env): """Add Builders and construction variables to the Environment.""" env["JAL"] = _detect(env) env.SetDefault( # Additional command-line flags JAL_FLAGS=SCons.Util.CLVar("-quiet"), # Suffixes/prefixes JAL_SUFFIX=".jal", JAL_ASMSUFFIX=".asm", J...
25,288
def help(user_display_name, module_file_fullpath, module_name): """Generate help message for all actions can be used in the job""" my_path = os.path.dirname(module_file_fullpath) my_fname = os.path.basename(module_file_fullpath) my_package = module_name.rsplit(u'.')[-2] # ex: sayhello my_package_pa...
25,289
def Arrow_bg(self): """ The function that will create the background for the dropdown arrow button. For internal use only. This function is therefore also not imported by __init__.py """ #Just leave the making of the buttons background to the default function. Not gonna bother re-doing that here (be...
25,290
def _is_debugging(ctx): """Returns `True` if the current compilation mode produces debug info. rules_apple specific implementation of rules_swift's `is_debugging`, which is not currently exported. See: https://github.com/bazelbuild/rules_swift/blob/44146fccd9e56fe1dc650a4e0f21420a503d301c/swift/intern...
25,291
def plot_bars(dgm, order='birth', ax=None, bar_style=None): """ Plot the barcode. adapted from "https://github.com/mrzv/dionysus" Parameters: ---------- dgm: ndarray persistence barcode diagram order (str): How to sort the bars, either 'death' or 'birth' ...
25,292
def trick_them(gm, vm): """ Fourberie de Scapy n°1. """ for pdst, psrc, hwdst in ((victim_ip, gate_ip, vm), (gate_ip, victim_ip, gm)): send( ARP(op=2, pdst=pdst, psrc=psrc, hwdst=hwdst) # Faisons croire à pdst que psrc est à l'adresse MAC hwsrc (qui est la nôtre en fait) en l'env...
25,293
def get_bounds_5km_to_1km( itk_5km, isc_5km ) : """ return the 1km pixel indexes limits in the 5km pixel [ itk_5km, isc_5km ] footprint """ # set the (track,scan) indexes of the 5km pixel in the 5km grid itk_1km = itk_5km_to_1km ( itk_5km ) isc_1km = isc_5km_to_1km ( isc_5km ) # set the 1k...
25,294
def batch_hard_triplet_loss(labels, embeddings, margin, squared=False): """Build the triplet loss over a batch of embeddings. For each anchor, we get the hardest positive and hardest negative to form a triplet. Args: labels: labels of the batch, of size (batch_size,) embeddings: tensor of sh...
25,295
def vrt_scrambled(doc: Document = Document(), out: Export = Export("vrt_scrambled/{doc}.vrt"), chunk: Annotation = Annotation("[cwb.scramble_on]"), chunk_order: Annotation = Annotation("[cwb.scramble_on]:misc.number_random"), token: Annotation = An...
25,296
def categorical_sample_logits(logits): """ Samples (symbolically) from categorical distribution, where logits is a NxK matrix specifying N categorical distributions with K categories specifically, exp(logits) / sum( exp(logits), axis=1 ) is the probabilities of the different classes Cleverly ...
25,297
def test_encode(args): """ Test CLI for encoding using subprocesses. """ tree_path = Path("kissim.tree") annotation_path = Path("kinase_annotation.csv") args = args.split() with enter_temp_directory(): subprocess.run(args, check=True) # Tree file there? assert tre...
25,298
def init_chm_test_session(): """Creates and removes the main directory for the test session.""" tmp_dir = tempfile.gettempdir() # Create the main directory parent_dir_path = create_dir( full_path=os.path.join(tmp_dir, PARENT_DIR), on_conflict="replace" ) yield parent_dir_path # Del...
25,299