content
stringlengths
22
815k
id
int64
0
4.91M
def add_users_to_groups_based_on_users_permissions(apps, schema_editor): """Add every user to group with "user_permissions" if exists, else create new one. For each user, if the group with the exact scope of permissions exists, add the user to it, else create a new group with this scope of permissions ...
19,900
def enforce(*types): """ decorator function enforcing, and converting, argument data types """ def decorator(fn): def new_function(*args, **kwargs): # convert args into something mutable, list in this case newargs = [] for original_argument, type_to_convert in...
19,901
def modify_repr(_cls: Type[Any]) -> None: """Improved dataclass repr function. Only show non-default non-internal values, and summarize containers. """ # let classes still create their own if _cls.__repr__ is not object.__repr__: return def new_repr(self: Any) -> str: name = se...
19,902
def _is_binary(path): """Checks if the file at |path| is an ELF executable. This is done by inspecting its FourCC header. """ with open(path, 'rb') as f: file_tag = f.read(4) return file_tag == '\x7fELF'
19,903
def test_cwd(): """Test the generator cwd.""" with cwd(".") as dir: # nothing is yielded assert dir is None
19,904
def rotationNcropping(folder_in,folder_out): """ Function to rotate a set of 3D images such a a way the struts of the scaffold the scaffols are alligned with x and y directions """ for filename in os.listdir(folder_in): imp =IJ.openImage(os.path.join(folder_in,filename)) IJ.run(imp, "TransformJ Rotate", "z-...
19,905
def update_item(*, table: str, hash_key: str, sort_key: Optional[str] = None, update_expression: Optional[str], expression_attribute_values: typing.Dict, return_values: str = 'ALL_NEW'): """ Update an item from a dynamoDB table. Will determine the type of db this is being called on by the nu...
19,906
def get_configuration(configuration_path=DEFAULT_CONFIGURATION_FILE): """ Return a dict containing configuration values. :param str configuration_path: path to parse yaml from. :return: dict """ global _configuration if _configuration is None: LOGGER.debug('Loading configuration: %s...
19,907
def scrap_docs_pages(): """ Scrape the documentation pages one-by-one while filling the clipboard every 10k characters for a grammar check-up. """ url = "https://help.close.com/docs/welcome" response = requests.get(url) document = BeautifulSoup(response.text, 'html.parser') all_text = '' #...
19,908
def load_and_process(event_id, stations, st, min_magnitude=7, event_client="USGS", event_et=3600, stat_client="IRIS", inv=None, save_raw=True, save_processed=True, process_d=True, sampling_rate=40.0, gen_plot=True, gen_audio=True, folder_name="default_folde...
19,909
def test_save_load_replay_buffer(tmp_path, recwarn, online_sampling, truncate_last_trajectory): """ Test if 'save_replay_buffer' and 'load_replay_buffer' works correctly """ # remove gym warnings warnings.filterwarnings(action="ignore", category=DeprecationWarning) warnings.filterwarnings(action...
19,910
def test_get_method_edit_customer_view(client, authenticated_user, create_customer): """test the get method for the edit customer view""" customer = Customer.objects.all() response = client.get( reverse("customer_update", kwargs={"customerid": customer[0].id}) ) assert response.status_code =...
19,911
def google_login_required(fn): """Return 403 unless the user is logged in from a @google.com domain.""" def wrapper(self, *args, **kwargs): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return email_match = re.match('^(.*)@(.*)$', user.e...
19,912
def init_res_fig(n_subplots, max_sess=None, modif=False): """ init_res_fig(n_subplots) Initializes a figure in which to plot summary results. Required args: - n_subplots (int): number of subplots Optional args: - max_sess (int): maximum number of sessions plotted ...
19,913
def setup() -> None: """ Call all 'setup_*' methods. """ setup_colorblind() setup_latex_fonts()
19,914
def change_personal_data_settings(request): """ Creates a question with summarized data to be changed :param request: POST request from "Change personal data settings" Dialogflow intent :return: JSON with summarized data to be changed """ language = request.data['queryResult']['languageCode'] ...
19,915
def test_filter_invalid_items(): """ filters the item which is not valid. it should return a list equal to input list. """ schema = ResultSchema(depth=5) results = [{1, 2, 3}, {4, 5, 6}, {7, 8, 9}] filtered = schema.filter(results) assert len(filtered) == len(results) assert filtered =...
19,916
def get_selected_cells(mesh, startpos, endpos): """ Return a list of cells contained in the startpos-endpos rectangle """ xstart, ystart = startpos xend, yend = endpos selected_cells = set() vertex_coords = mesh.coordinates() for cell in dolfin.cells(mesh): cell_vertices = cell....
19,917
def flip_axis(array, axis): """ Flip the given axis of an array. Note that the ordering follows the numpy convention and may be unintuitive; that is, the first axis flips the axis horizontally, and the second axis flips the axis vertically. :param array: The array to be flipped. :type array: `n...
19,918
def fizz_buzz_tree(input_tree): """ traverses a tree and performs fizz buzz on each element, agumenting the val """ input_tree.in_order_trav(lambda x: fizzbuzz(x)) return input_tree
19,919
def scan_to_headerword(serial_input, maximum_bytes=9999, header_magic=HeaderWord.MAGIC_MASK): """ Consume bytes until header magic is found in a word :param header_magic: :param maximum_bytes: :param serial_input: :rtype : MTS.Header.Header """ headerword = 0x0000 bytecount = 0 ...
19,920
def _c2_set_instrument_driver_parameters(reference_designator, data): """ Set one or more instrument driver parameters, return status. Accepts the following urlencoded parameters: resource: JSON-encoded dictionary of parameter:value pairs timeout: in milliseconds, default value is 60000 Sample:...
19,921
def generate_key(keysize=KEY_SIZE): """Generate a RSA key pair Keyword Arguments: keysize {int} -- Key (default: {KEY_SIZE}) Returns: bytes -- Secret key bytes -- Public key """ key = RSA.generate(keysize) public_key = key.publickey().exportKey() secret_key = key.ex...
19,922
def main(): """Test the linear actuator protocol for two actuators.""" parser = argparse.ArgumentParser( description='Test the linear actuator protocol for two actuators.' ) add_argparser_transport_selector(parser) args = parser.parse_args() transport_loop = parse_argparser_transport_sel...
19,923
def get_api_endpoint(func): """Register a GET endpoint.""" @json_api.route(f"/{func.__name__}", methods=["GET"]) @functools.wraps(func) def _wrapper(*args, **kwargs): return jsonify({"success": True, "data": func(*args, **kwargs)}) return _wrapper
19,924
def scrape_radio_koeln(): """ Fetch the currently playing song for Radio Köln. :return: A Song, if scraping went without error. Return None otherwise. """ url = 'http://www.radiokoeln.de/' tag = get_tag(url, '//div[@id="playlist_title"]')[0] artist = tag.xpath('.//div/b/text()') title =...
19,925
def get_mt4(alias=DEFAULT_MT4_NAME): """ Notes: return mt4 object which is initialized. Args: alias(string): mt4 object alias name. default value is DEFAULT_MT4_NAME Returns: mt4 object(metatrader.backtest.MT4): instantiated mt4 object """ global _mt4s if alias ...
19,926
def get_log_probability_function(model=None): """ Builds a theano function from a PyMC3 model which takes a numpy array of shape ``(n_parameters)`` as an input and returns returns the total log probability of the model. This function takes the **transformed** random variables defined withing the mo...
19,927
def get_health(check_celery=True): """ Gets the health of the all the external services. :return: dictionary with key: service name like etcd, celery, elasticsearch value: dictionary of health status :rtype: dict """ health_status = { 'etcd': _check_etcd(), 'sto...
19,928
def add_quotation_items(quotation_items_data): """ 添加信息 :param quotation_items_data: :return: None/Value of user.id :except: """ return db_instance.add(QuotationItems, quotation_items_data)
19,929
def load_cifar10_human_readable(path: str, img_nums: list) -> np.array: """ Loads the Cifar10 images in human readable format. Args: path: The path to the to the folder with mnist images. img_nums: A list with the numbers of the images we want to load. Returns: ...
19,930
def identity(target_ftrs, identity_ftrs, output_name=None, output_folder=None, cluster_tolerance="", problem_fields={}, full_out_path=""): """ perform identity analysis on target feature class with identity feature class """ try: output_location = IN_MEMORY out_ftrs = ...
19,931
def get_project_linked_to_object(object_id: int) -> typing.Optional[Project]: """ Return the project linked to a given object, or None. :param object_id: the ID of an existing object :return: the linked project or None :raise errors.ObjectDoesNotExistError: if no object with the given ID ex...
19,932
def main(): """ Input 'images/poppy.png' and assign it to 'original', then show it. Make 'shrink()' function to scale image and redistribute color values, then show it. """ original = SimpleImage("images/poppy.png") original.show() after_shrink = shrink(original) # scale image and re...
19,933
def country_all_year (select_year, country_id): """ Prints a list of UK countries population for selected year, in descending order. :param select_year: (str) input year within dataset to analyse. :param country_id: (str) column containing countries unique ID :return: Returns a list of countries total...
19,934
def processor(template: Union[str, Path] = None, format_name: str = None) -> Union[None, RecordProcessor]: """ Configures the record level processor for either the template or for the format_name Args: template: path to template or template as string format_name: one of the valid registered...
19,935
def calc_distances_for_everyon_in_frame(everyone_in_frame, people_graph, too_far_distance, minimum_distance_change): """ :param everyone_in_frame: [PersonPath] :type everyone_in_frame: list :param people_graph: :type people_graph: Graph :param too_far_distance: :param minimum_distance_...
19,936
def conv2d(input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor = None, stride=1, padding=0, dilation=1, groups=1, mode=None): """Standard conv2d. Returns the input if weight=None.""" if weight is None: return input ...
19,937
def infer(model, loader_test): """ Returns the prediction of a model in a dataset. Parameters ---------- model: PyTorch model loader_test: PyTorch DataLoader. Returns ------- tuple y_true and y_pred """ model.eval() ys, ys_hat = [], [] for ids, ma...
19,938
def validate_project(project_name): """ Check the defined project name against keywords, builtins and existing modules to avoid name clashing """ if not project_name_rx.search(project_name): return None if keyword.iskeyword(project_name): return None if project_name in dir(__...
19,939
def test_port_range_scan(): """should return result of 'masscan -p1-80 54.250.0.0/16 --rate=500 -oG output.txt'""" config = ReadConfig.get_all_settings() output_file_name = "masscan-test_port_range_scan.txt" try: thread_holder(config["MASSCAN_TIMEOUT_SECONDS"], config["LOGGER"]) # Design...
19,940
def test_backends_database_es_database_instantiation_with_forbidden_op_type(es): """Tests the ES backend instantiation with an op_type that is not allowed.""" # pylint: disable=invalid-name,unused-argument,protected-access with pytest.raises(BackendParameterException): ESDatabase(hosts=ES_TEST_HOST...
19,941
def _print_available_filters(supported_filters): """Prints information on available filters and their thresholds.""" widths = (20, 40, 20) data = [("Filter", "Description", "Threshold Values"), ("------", "-----------", "----------------")] # this is stupid for f, (d, t, c) in supported_...
19,942
def _get_dates(i, *args, **kwargs): """ Get dates from arguments """ try: start_date = kwargs['start_date'] except: try: start_date = args[i] except: start_date = None try: end_date = kwargs['end_date'] except: try: ...
19,943
def _execute(filepath=""): """ load pmd file to context. """ # load pmd bl.progress_set('load %s' % filepath, 0.0) model=reader.read_from_file(filepath) if not model: bl.message("fail to load %s" % filepath) return bl.progress_set('loaded', 0.1) # create root objec...
19,944
def home_page(): """Shows home page""" html = """ <html> <body> <h1>Home Page</h1> <p>Welcome to my simple app!</p> <a href='/hello'>Go to hello page</a> </body> </html> """ return html
19,945
def test_foca_api(): """Ensure foca() returns a Connexion app instance; valid api field""" temp_file = create_temporary_copy( API_CONF, PATH_SPECS_2_YAML_ORIGINAL, ) app = foca(temp_file) assert isinstance(app, App) os.remove(temp_file)
19,946
def GetPDFHexString(s, i, iend): """Convert and return pdf hex string starting at s[i], ending at s[iend-1].""" j = i + 1 v = [] c = '' jend = iend - 1 while j < jend: p = _re_pswhitespaceandcomments.match(s, j) if p: j = p.end() d = chr(ordat(s, j)) ...
19,947
def infer() -> None: """Perform inference on an input image.""" # Get the command line arguments, and config from the config.yaml file. # This config file is also used for training and contains all the relevant # information regarding the data, model, train and inference details. args = get_args() ...
19,948
def get_edge_syslog_info(edge_id): """Get syslog information for specific edge id""" nsxv = get_nsxv_client() syslog_info = nsxv.get_edge_syslog(edge_id)[1] if not syslog_info['enabled']: return 'Disabled' output = "" if 'protocol' in syslog_info: output += syslog_info['protoco...
19,949
def _get_rec_suffix(operations:List[str]) -> str: """ finished, checked, Parameters ---------- operations: list of str, names of operations to perform (or has performed), Returns ------- suffix: str, suffix of the filename of the preprocessed ecg signal """ suffix =...
19,950
def get_A_text(params, func_type=None): """ Get text associated with the fit of A(s) """ line1 = r'$A(s|r)$ is assumed to take the form:' line2 = (r'$A(s|r) = s^{-1}\bigg{(}\frac{s}{\Sigma(r)}\bigg{)}^a ' r'exp\bigg{(}{-\bigg{(}\frac{s}{\Sigma(r)}\bigg{)}^b}\bigg{)}$') a, b = params...
19,951
def test_cifar10_basic(): """ Validate CIFAR10 """ logger.info("Test Cifar10Dataset Op") # case 0: test loading the whole dataset data0 = ds.Cifar10Dataset(DATA_DIR_10) num_iter0 = 0 for _ in data0.create_dict_iterator(num_epochs=1): num_iter0 += 1 assert num_iter0 == 10000 ...
19,952
def transform_to_dict(closest_list: list) -> dict: """ Returns dict {(latitude, longitude): {film1, film2, ...}, ...} from closest_list [[film1, (latitude, longitude)], ...], where film1, film2 are titles of films, (latitude, longitude) is a coordinates of a place where those films were shoot. ...
19,953
def _enrich_errors( errors: Iterable[ErrorDetails], tag: Tag, loc: Any = NO_ERROR_PATH ) -> Iterable[ErrorDetails]: """ Enrich the stream of errors with tag and location information. Tags are useful for determining which specs were evaluated to produce the error. Location information can help calle...
19,954
def fixed_params(control_file): """ Adds fixed parameters to the control file for the second chromEvol run :param control_file: file handler of control file :return: NA """ control_file.write("_logFile log.txt\n") control_file.write("_maxChrNum -10\n") control_file.write("_minChrNum -1\n...
19,955
def test_count_rows_in_2d_arrays_with_nans(): """Test that nan-containinr rows in 2d arrays are counted correctly.""" data_1_row = np.array([[1, 2, 3]]) data_2_rows = np.array([[1, 2, 3], [1, 2, 3], [np.nan, 2, 3], [1, np.nan, 3]]) data_3_rows = np.array( [[1, 2, 3], [np.nan, 2, 3], [1, np.nan...
19,956
def ECGDataQuality(datastream: DataStream, windowsize: float = 5.0, bufferLength: int = 3, acceptableOutlierPercent: int = 50, outlierThresholdHigh: int = 4500, outlierThresholdLow: int = 20, badSegmentThre...
19,957
def deprecation_mark(deprecation_note: str) -> None: """ Function used to mark something deprecated in this package :param deprecation_note: What and when was deprecated message, that will be collected by loggers """ warn(deprecation_note, DeprecationWarning)
19,958
def plot_class_activation_map_widget(model, time_series, labels, fs): """ Launch interactive plotting widget. Parameters ---------- model : object Active model with live session time_series : np.array([m, length]) image array labels : np.array([m,]) a 1D array of le...
19,959
def get_numpy_val_from_form_input(input_name): """Get a NumPy-compatible numerical value from the request object""" return get_numpy_val(input_name, request.form[input_name])
19,960
def load_model(model, path): """Load a the model parameters from a file and set them. Parameters ---------- model : a :class:`Layer` instance The model with unset parameters. path : string The file with the model parameters. Returns ------- a :class:`Layer` instance ...
19,961
def transform_table(path, df_mean, df_stabw, properties): """ This function creates a DataFrame with mean values and errors including the units for every feauer and calls the plot function for them. Args: path (string): path to store the plots df_mean (pandas.DataFrame): DataFrame ...
19,962
def node_id_at_cells(shape): """Node ID at each cell. Parameters ---------- shape : tuple of int Shape of grid of nodes. Returns ------- ndarray : ID of node associated with each cell. Examples -------- >>> from landlab.grid.structured_quad.cells import node_id...
19,963
def search_media(search_queries, media, ignore_likes=True): """Return a list of media matching a queary that searches for a match in the comments, likes, and tags in a list of media""" # Initialize update message update_message = print_update_message(len(media)) update_message.send(None) # Init...
19,964
def ensure_experiment_lock(obj: Union[Experiment, Scan], user: User) -> None: """ Raise an exception if the given user does not possess the experiment lock. This should be called by all REST `create` methods that correspond to an object within a Experiment, as new object creation policies are not handl...
19,965
def emu_getuid(mu: Uc, emu_env: EmulatorEnv): """ Emulates getuid syscall functionality. """ uid = os.getuid() mu.reg_write(UC_X86_REG_RAX, uid)
19,966
def validation_plot_thesis(show_plot=True, results_2010=None, results_2011=None, model_run="cosumnes_michigan_bar"): """ Hardcoded items because they're for my thesis, not meant for more general use. :return: """ if results_2010 is None: results_2010 = validate_flow_methods("{}_2010".format(model_run), show_plo...
19,967
def get_produced_messages(func): """Returns a list of message fqn and channel pairs. Args: func (Function): function object Returns: list """ result = [] for msg, channel in func.produces: result.append((_build_msg_fqn(msg), channel)) return result
19,968
def find_coverage_files(src_path: Path) -> Sequence: """ Find the coverage files within the specified src_path. Parameters: src_path (Path): The path in which to look for the .coverage files. Returns: (Sequence) The set of .coverage files within the specified folder. """ re...
19,969
def checkrunsh(filename): """ write a temporary (run.sh) file and than checks it againts the run.sh file already there This is used to double check that the pipeline is not being called with different options """ tempdir = tempfile.mkdtemp() tmprunsh = os.path.join(tempdir,os.path.basename(filen...
19,970
def get_exploration_summary_from_model(exp_summary_model): """Returns an ExplorationSummary domain object. Args: exp_summary_model: ExplorationSummary. An ExplorationSummary model instance. Returns: ExplorationSummary. The summary domain object correspoding to the given...
19,971
def get_service(api_name, api_version, scope, key_file_location, service_account_email): """Get a service that communicates to a Google API. Args: api_name: The name of the api to connect to. api_version: The api version to connect to. scope: A list auth scopes to authorize for t...
19,972
def model_map(lon, lat, alt, comp, binsize = 0.1, nmax = 134, a = 3393.5): """ Calculates a map of one component of the crustal magnetic field field model, for a given altitude. Parameters: lon: array The longitude range, in degrees. Ex.: [20., 50.]. lat: array ...
19,973
def parse_command(incoming_text): """ incoming_text: A text string to parse for docker commands returns: a fully validated docker command """ docker_action = '' parse1 = re.compile(r"(?<=\bdocker\s)(\w+)") match_obj = parse1.search(incoming_text) if match_obj: docker_ac...
19,974
def deploy_heroku_ui(ctx, token, app="striker-vn-ui"): """ Deploy UI docker image on heroku """ ctx.run(docker("login", f"--username=_", f"--password={token}", "registry.heroku.com")) with ctx.cd(get_ui_directory()): ctx.run(heroku("co...
19,975
def crt_fill_parameters(config_path, overwrite_flag=False, debug_flag=False): """Calculate GSFLOW CRT Fill Parameters Args: config_file (str): Project config file path ovewrite_flag (bool): if True, overwrite existing files debug_flag (bool): if True, enable debug level logging ...
19,976
def get_entities_from_tags(query, tags): """From a set of joint IOB tags, parse the app and system entities. This performs the reverse operation of get_tags_from_entities. Args: query (Query): Any query instance. tags (list of str): Joint app and system tags, like those created...
19,977
async def test_3(pc): """setting direction should change transceiver.direction independent of transceiver.currentDirection""" init = webrtc.RtpTransceiverInit(direction=webrtc.TransceiverDirection.recvonly) transceiver = pc.add_transceiver(webrtc.MediaType.audio, init) assert transceiver.direction == w...
19,978
def angle_connectivity(ibonds): """Given the bonds, get the indices of the atoms defining all the bond angles A 'bond angle' is defined as any set of 3 atoms, `i`, `j`, `k` such that atom `i` is bonded to `j` and `j` is bonded to `k` Parameters ---------- ibonds : np.ndarray, shape=[n_bond...
19,979
def BOPDS_PassKeyMapHasher_IsEqual(*args): """ :param aPKey1: :type aPKey1: BOPDS_PassKey & :param aPKey2: :type aPKey2: BOPDS_PassKey & :rtype: bool """ return _BOPDS.BOPDS_PassKeyMapHasher_IsEqual(*args)
19,980
def replaceToSantizeURL(url_str): """ Take arbitrary string and search for urls with user and password and replace it with sanitized url. """ def _repUrl(matchObj): return matchObj.group(1) + matchObj.group(4) # TODO: won't catch every case (But is it good enough (trade off to performa...
19,981
def dms2dd(s): """convert lat and long to decimal degrees""" direction = s[-1] degrees = s[0:4] dd = float(degrees) if direction in ('S','W'): dd*= -1 return dd
19,982
def setna(self, value, na=np.nan, inplace=False): """ set a value as missing Parameters ---------- value : the values to set to na na : the replacement value (default np.nan) Examples -------- >>> from dimarray import DimArray >>> a = DimArray([1,2,-99]) >>> a.setna(-99) di...
19,983
def hbox(*items, **config): """ Create a DeferredConstraints object composed of horizontal abutments for a given sequence of items. """ return LinearBoxHelper('horizontal', *items, **config)
19,984
def find_columns(clause): """locate Column objects within the given expression.""" cols = util.column_set() visitors.traverse(clause, {}, {'column':cols.add}) return cols
19,985
def _preprocess_data(smiles, labels, batchsize = 100): """ prepares all input batches to train/test the GDNN fingerprints implementation """ N = len(smiles) batches = [] num_bond_features = 6 for i in range(int(np.ceil(N*1./batchsize))): array_rep = utils.array_rep_from_smi...
19,986
def test_makedep_error(cc): """Check missing header error.""" src = make_source('foo.c', '#include "foo.h"') with capture_output() as (out, err), pytest.raises(CallError): check_makedep(cc, src, 1) stdout = out.getvalue() stderr = err.getvalue() print(stdout) print(stderr)
19,987
def linear_activation_forward(A_prev, W, b, activation, keep_prob=1): """ Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (...
19,988
def get_version(file, name="__version__"): """Get the version of the package from the given file by executing it and extracting the given `name`. """ path = os.path.realpath(file) version_ns = {} with io.open(path, encoding="utf8") as f: exec(f.read(), {}, version_ns) return version_...
19,989
def load_image(image_path, size): """ Load an image as a Numpy array. :param image_path: Path of the image :param size: Target size :return Image array, normalized between 0 and 1 """ image = img_to_array(load_img(image_path, target_size=size)) / 255. return image
19,990
def species__filesystem(argt): """ fill in species guess geometries """ call_task( argt, task.species.filesystem, specs=( specifier( al.SPECIES_CSV, inp=True, ), specifier( al.SPECIES_CSV, out=True, opt_char=SPC_CSV_...
19,991
def _signal_exit_code(signum: signal.Signals) -> int: """ Return the exit code corresponding to a received signal. Conventionally, when a program exits due to a signal its exit code is 128 plus the signal number. """ return 128 + int(signum)
19,992
def make_template_matrix(msigdb_file, blacklist, checkblacklist=True): """ Retrieve all genes and pathways from given msigdb .gmt file Output: sorted gene by pathways pandas dataframe. Entries indicate membership """ all_db_pathways = [] all_db_genes = [] # Get a set of all genes a...
19,993
def test_deep_segmentation_spinalcord(params): """High level segmentation API""" fname_im = sct_test_path('t2', 't2.nii.gz') fname_centerline_manual = sct_test_path('t2', 't2_centerline-manual.nii.gz') # Call segmentation function im_seg, _, _ = sct.deepseg_sc.core.deep_segmentation_spinalcord( ...
19,994
def unwrap_key( security_control: SecurityControlField, wrapping_key: bytes, wrapped_key: bytes ): """ Simple function to unwrap a key received. """ validate_key(security_control.security_suite, wrapping_key) validate_key(security_control.security_suite, wrapped_key) unwrapped_key = aes_key_...
19,995
def checkOwnership(obj, login_session): """ This function helps to check if the current logged in user is the creator of the given category or a given item. This function return True if the current user owns the category, otherwise, it will return False. """ # the user has logged in at ...
19,996
def move() -> str: """Move a file.""" if not g.ledger.options["documents"]: raise FavaAPIException("You need to set a documents folder.") account = request.args.get("account") new_name = request.args.get("newName") filename = request.args.get("filename") if not account: raise F...
19,997
def transform_file_name(original_file_name): """ Now, this is just whatever I felt like. Whee. So in this function I could have just used 0 and 1 as my indices directly when I look at the different parts of the file name, but it's generally better to name these sorts of things, so people know *why* the...
19,998
def remove_overlapping_cells(graph): """ Takes in a graph in which each node is a cell and edges connect cells that overlap eachother in space. Removes overlapping cells, preferentially eliminating the cell that overlaps the most cells (i.e. if cell A overlaps cells B, C, and D, whereas cell B only ...
19,999