content
stringlengths
22
815k
id
int64
0
4.91M
def configure_pbr_route_map(device, route_map_name, acl_name, next_hop_ip, default_next_hop=None): """ Configure route-map Args: device (`obj`): Device object route_map_na...
53,900
def get_work_value(block_hash, work, as_hex=False): """ Get the proof-of-work value. The work value must be equal to or higher than the work difficulty to be considered valid. """ validate_block_hash(block_hash) parse_work(work) reversed_work = bytearray(unhexlify(work)) reversed_wor...
53,901
def total_loss(output, target, loss='mse', only_nodes=False, only_graph=False): """ returns the average of the average losses of each task """ assert not (only_nodes and only_graph) if only_nodes: nodes_loss = get_loss(loss, output[0], target[0]) return nodes_loss elif only_graph: ...
53,902
def main(): """ Handle command-line arguments to print or edit data. """ parser = argparse.ArgumentParser(description="Campaign manager utility.") viewGrp = parser.add_argument_group("View", "Print data to stdout") viewGrp.add_argument( "-a", "--available", action="store...
53,903
def parse_mem_str_to_gbsize(strmem): """ String like 845 MB 677.8 MB to GB size :param strtime: :return: """ strmem = strmem.strip() if strmem.endswith('MB'): memgb = float(strmem[:-2]) / 1024 elif strmem.endswith('GB'): memgb = float(strmem[:-2]) elif strmem.endswit...
53,904
def Emonet_extend(num_classes): """ This model is optional and bigger than the previous one. Practically, this model is less useful than the first one therefore is not called by the application. Use only for experimental purposes """ emonet = Sequential() """ Convolution and Maxpool layers:...
53,905
def generate(provider, context, **kwargs): # pylint: disable=W0613 """Generate an EKS auth_map for worker connection. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean ...
53,906
def isListController(obj): """ Evaluates if the supplied object is a list controller. :type obj: pymxs.runtime.MXSWrapperBase :rtype: bool """ return pymxs.runtime.classOf(obj) in LIST_TYPES
53,907
def genomic_del1(): """Create test fixture containing params for genomic del VD.""" params = { "id": "normalize.variation:NC_000003.12%3Ag.10149811del", "type": "VariationDescriptor", "variation_id": "", "variation": dict(), "molecule_context": "genomic", "structu...
53,908
def fec_plots(df_fec_data: pd.DataFrame, pdf: str, dir_plot: str): """ FEC PLOTS """ xlabel= 'Yearly emissions [MtC02/y]' plot_stacked_bar(df_data=df_fec_data.transpose(), xlabel=xlabel, ylabel='[TWh]', ylim=520, pdf_name=dir_plot + '/fec-details-' + pdf + '.pdf') # FEC detailed by EUD hea...
53,909
def civic_vid258(): """Create a test fixture for CIViC VID258.""" return { "id": "civic.vid:258", "type": "VariationDescriptor", "label": "A222V", "value_id": "ga4gh:VA.V5IUMLhaM8Oo-oAClUZqb-gDPaIzIi-A", "value": { "location": { "interval": { ...
53,910
def test2_no_terms(): """ Tests the length of the latent variable vector for an GASX model with no AR or SC terms, and two predictors, and tests that the values are not nan """ assert(len(model_b_1.latent_variables.z_list) == 6) lvs = np.array([i.value for i in model_b_1.latent_variables.z_...
53,911
def get_continuous_ts(finger, max_nans=30): """ Split TS where n consecutive nans bigger than max_nans. 1D only""" gaps = np.isnan(finger) assert(np.all(gaps[0,:] == gaps[1,:])), "Finger x, y dim not equal. Check!" # Use one axis (x,y) gaps = gaps[0,:] seg, n_seg = label(gaps) for s in ran...
53,912
def find_rising_edge(x, y, *, threshold=None, interp=False): """Find the first `x` where `y` exceeds `threshold` (along the last axis). `x` and `y` must have the same shape. If `threshold` is None, it will be inferred as half the rise from min(y) to max(y). If `interp` is True, linearly interpolate b...
53,913
def normalize_os_name(os_name): """ :API: public """ if os_name not in OS_ALIASES: for proper_name, aliases in OS_ALIASES.items(): if os_name in aliases: return proper_name logger.warning('Unknown operating system name: {bad}, known names are: {known}' .format(bad=os_nam...
53,914
def addSimplifiedOutputVariables(self, verboseMode: bool = True): """ Add simplified Output:Variable objects for accim. Remove all outputs and add only VFR outdoor unit consumption and operative temperature. """ EnvList = ([output for output in self.idf1.idfobjec...
53,915
def test_simple022_simple022_v02_xml(mode, save_output, output_format): """ Enumeration value OK if "equal or identical", so NaN is accepted. See bug 9196 Enumeration value OK if "equal or identical", so NaN is accepted. See bug 9196 """ assert_bindings( schema="saxonData/Simple/simple02...
53,916
def make_prediction(*, path_to_images) -> float: """Make a prediction using the saved model pipeline.""" # Load data # create a dataframe with columns = ['image', 'target'] # column "image" contains path to image # columns target can contain all zeros, it doesn't matter dataframe = path_to_ima...
53,917
def test_main_runtime(): """ If there are three arguments passed into main, then it should pass them onto the flash() function. """ with mock.patch('uflash.flash') as mock_flash: uflash.main(argv=['-r' 'baz.hex', 'foo.py', '/media/foo/bar']) mock_flash.assert_called_once_with( ...
53,918
def vmanage_login(host: str, username: str, password: str): """ """ return Authentication( host=host, user=username, password=password ).login()
53,919
def test_residuals(analyser): """Test that the residuals are correctly calculated. Should all be zero when the mean values are exactly correlated. """ assert_almost_equal(analyser.residuals, np.zeros(analyser.val_obs.shape))
53,920
def validate_non_coinbase_transaction_by_itself(transaction: Transaction) -> None: """Do those Transaction checks that can be done outside of the context a blockchain""" if len(transaction.inputs) == 0: raise ValidateTransactionError("No inputs") if len(transaction.outputs) == 0: raise Val...
53,921
def load_image(): """Load image from file, then scale and rotate. Returns CV2 object.""" if display_histogram == 1: image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) else: image = cv2.imread(filename, cv2.IMREAD_COLOR) image_resized = cv2.resize(image, None, fx=scale, fy=scale,...
53,922
def validate_args(args): """ Method to check valid combination of flags """ if args['default_site'] is not None or args['default_contest'] is not None: return if args['clear_cache']: return if not args['site'] == 'spoj' and args['contest'] is None: print('Please specif...
53,923
def handle_odd_pad_bwd(dx, odd_padding): """ handle odd padding mode backward Args: dx, the backward tensor odd_padding, the odd_padding Returns: tensor, the output """ # (axis, left padding if True else right padding) flags = [(2, True), (2, False), (3, True), (3, F...
53,924
def gwas_snp_to_precluster(gwas_snp, populations): """ Extract neighbourhood of GWAS snp Args: * [ GWAS_SNP ] * [ string ] (populations) Returntype: GWAS_Cluster """ mapped_ld_snps = postgap.LD.calculate_window(gwas_snp.snp) logging.info("Found %i SNPs in the vi...
53,925
def grep(options): """ Main function """ if Grep.evaluate_input(options): grep_obj = Grep(options) grep_obj.process_file(options[1]) if "n" in options[1]: print("Numar de aparitii: {0}".format(grep_obj.counter)) else: config.help_function(NAME, OPTIONS)
53,926
def parse_args(): """Parse command-line arguments.""" def _bool(val): return bool(strtobool(val)) parser = argparse.ArgumentParser(description='Deploy MargiPose jobs to Kubernetes', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument...
53,927
def block_shuffle(indices, block_size, one_based=ONE_BASED): # TODO(allie): Handle zero-indexing here too (currently assuming first frame index = 1) """ Shuffles indices according to 'blocks' of size block_size. All 'blocks' start with index 1. inputs: indices (array-like, shape (N,)): integers...
53,928
def register_coco_instances(name, metadata, json_file, image_root): """ Register a dataset in COCO's json annotation format for instance detection, instance segmentation and keypoint detection. (i.e., Type 1 and 2 in http://cocodataset.org/#format-data. `instances*.json` and `person_keypoints*.json`...
53,929
def add_tag(): """ Function will add tag to given UUID of event or attribute. """ uuid = demisto.args().get('uuid') tag = demisto.args().get('tag') MISP.tag(uuid, tag) event = MISP.search(uuid=uuid) ec = { MISP_PATH: build_context(event) } md = f'Tag {tag} has been succe...
53,930
def cleanup_ud(ds): """More cleaning and calculation of derived variables.""" # remove spikes in temperature for v in ["t1", "t2"]: ds[v] = despike(ds[v], ds.attrs["spike_thresh_t"]) # despike T, C ibefore = 1 iafter = 1 for v in ["c1", "c2", "t1", "t2"]: ds[v].data = helpe...
53,931
def test_from_rectangular(arr): """Test creation from rectangular form.""" s = QuaternionSignal.from_rectangular(arr) assert isinstance(s, QuaternionSignal) expected = [ Quaternion(2.0, 2.0, 8.0, 0.0), Quaternion(4.0, 5.0, 6.0, 5.0), Quaternion(1.0, 9.0, 4.0, 1.0), Quater...
53,932
def input_payload_seq( sender: crcelements.CRCSender, crc_sequence: List[Tuple[bytes, bytes, bytes]] ) -> None: """Add sequence of crc payloads as input to a sender.""" for (_, payload, __) in crc_sequence: sender.input(payload)
53,933
def ParseIoStatsLine(line): """Parses a line of io stats into a IoStats named tuple.""" # Field definitions: http://www.kernel.org/doc/Documentation/iostats.txt IoStats = collections.namedtuple('IoStats', ['device', 'num_reads_issued', ...
53,934
def sql_readaspd(db_dets, query): """ Pull a SQL query output and read it into a Pandas DataFrame Parameters ---------- db_dets: str URL of a postgreSQL database that will be connected to. query: str SQL query Returns ------- Pandas.DataFrame ...
53,935
def test_filter_phases_removes_phases_with_inactive_sublattices(load_database): """Phases that have no active components in any sublattice should be filtered""" dbf = load_database() all_phases = set(dbf.phases.keys()) filtered_phases = set(filter_phases(dbf, unpack_components(dbf, ['AL', 'NI', 'VA'])))...
53,936
def grid2spec(gfield): """Transform a field on physical grid to spectral space Args: gfield: numpy array with shape (time(optional), y, x, z(optional)) """ if _is_single_layer(gfield): y_loc = -2 else: y_loc = -3 ny, nx = gfield.shape[y_loc], gfield.shape[y_loc+1] ...
53,937
def parse_bits_transmission( bits: list[str], pos: int = 0, indent: int = 0 ) -> tuple[int, int]: """Parse a message accoring to the Buoyancy Interchange Transmission System (BITS) Args: bits (list[str]): message in binary representation pos (int): current position in the bit stream ...
53,938
def test_align_optimal_complex(sequences, gap_penalty, seq_indices): """ Test `align_optimal()` function using real world sequences, compared to the output of MUSCLE. """ matrix = align.SubstitutionMatrix.std_protein_matrix() index1, index2 = seq_indices seq1 = sequences[index1] seq2 = s...
53,939
def get_pixel_neighbors(height, width): """ Estimate the 4 neighbors of every pixel in an image :param height: image height :param width: image width :return: pixel index - neighbor index lists """ pix_id = [] neighbor_id = [] for i in range(height): for j in range(width): ...
53,940
def parse_copy_running_config_startup_config(raw_result): """ Parse the 'copy running-config startup-config' command raw output. :param str raw_result: copy running-config startup-config raw result string. :rtype: dict :return: The parsed result of the copy running-config startup-config: ...
53,941
def raiseExpectedGot(expected, for_, got): """Raise an error for an unexpected value. Raise a ValueError with the following message: `Expected `expected` for `for_`, got `got` instead.` """ raise ValueError( 'Expected {} for {}, got {} instead.'.format(expected, for_, got) )
53,942
def make_bson(obj): """Given a Python (JSON compatible) dictionary, returns a BSON string. (This hijacks the Python -> BSON conversion code from pymongo, which is needed for converting queries. Perhaps this dependency can be removed in a later version.) :param obj: object to be encoded as BS...
53,943
def set_tlines_allzeroes(s, sample_list, allevents_spec): """ - day_evs are all events CREATED on the same day (or later - delete for each event all connected events for assigned rv - rvlist gets more and more zeroes - then assign rvlist to sample - rvlist can be copied for all day events and th...
53,944
def plot_hail_file_metadata( t_path: str, ) -> Optional[Union[Grid, Tabs, bokeh.plotting.Figure]]: """ Takes path to hail Table or MatrixTable (gs://bucket/path/hail.mt), outputs Grid or Tabs, respectively. Or if an unordered Table is provided, a Figure with file sizes is output. If metadata file or...
53,945
def calldataload(computation): """ Load call data into memory. """ start_position = computation.stack_pop(type_hint=constants.UINT256) value = computation.msg.data[start_position:start_position + 32] padded_value = value.ljust(32, b'\x00') normalized_value = padded_value.lstrip(b'\x00') ...
53,946
def load_values_from_environment(prefix="", overrides=None): """Reads values from the environment. If ``prefix`` is a non-empty string, only environment variables with the given prefix will be returned. The prefix, if given, will be stripped from any returned keys. If ``overrides`` is a dict-like ...
53,947
def get_user_details(request): """ DataHub account registration form for social accounts. Gives new users a chance to choose a DataHub username and set their email address. Called by the Python Social Auth pipeline's get_user_details step. For more details, look for pipeline.py and the SOCIAL_...
53,948
def build_results_dir(params): """ function to create the final result directory for a job/test. Intent is to make backwards compatible with Gazebo. """ logger = logging.getLogger('pav.runjob.build_results_dir') lh = params['log_handle'] root_result_dir = params['results']['root'] os.e...
53,949
def _cqv( data: NumArrayLike, ndigits: Optional[int] = 4, interpolation: Optional[str] = "linear", multiplier: Optional[int] = 1, ) -> float: """Internal function to calculate cqv.""" # ------------------- convert data to pandas.core.series.Series ------------------- _data: pd.Series = pd.Se...
53,950
def GetCulpritsForFailures(failures): """Gets culprits for the requested failures. Args: failures (list of AtomicFailures) Returns: (list of findit_result.Culprit) """ culprit_keys = set([ failure.culprit_commit_key for failure in failures if failure and failure.culprit_commit_key ...
53,951
def get_object_perms(obj: models.Model, user: Optional[User] = None) -> Dict: """Return permissions for given object in Resolwe specific format. Function returns permissions for given object ``obj`` in following format:: { "type": "group"/"user"/"public", "id": <group_or_user_...
53,952
def _dev_test_ORR_analysis(): """function for testing"""
53,953
def fixed_from_old_hindu_lunar(l_date): """Return fixed date corresponding to Old Hindu lunar date l_date.""" year = old_hindu_lunar_year(l_date) month = old_hindu_lunar_month(l_date) leap = old_hindu_lunar_leap(l_date) day = old_hindu_lunar_day(l_date) mina = ((12 * year) - 1) * ARYA_SOLAR...
53,954
def writeFile(filename, lines): """ Writes a new file """ file = open(filename, 'w') for line in lines: file.write( "%s\n" % (line) ) file.close()
53,955
def get_zrand_mask(zrand, percentile=95): """ Calculates stable regions of `zrand` based on `percentile` Parameters ---------- zrand : (C, K, M) array_like Local similarity of clustering solutions in SNF parameter space percentile : [0, 100] float, optional Percentile of `zrand`...
53,956
def remove_small_areas(img, min_area): """ Segmenta uma imagem em várias regiões com propriedades em comum e gera uma imagem resultado, deixando de fora todas as regiões que possuam areas menores do que o limiar passado. Esse processo é realizado para remover áreas pequenas (no geral...
53,957
def show_pages(parser, token): """ Show page links. Usage:: {% show_pages %} It is only a shortcut for:: {% get_pages %} {{ pages }} You can set *ENDLESS_PAGINATION_PAGE_LIST_CALLABLE* in your settings.py as a callable used to customize the pages that are displayed. ...
53,958
def check_file(file, direction): """ Validate a user input This function ensures that the user enters a valid file list where the list contains a non-empty filename, b64 image, and a valid processing steps array. Args: direction (str): either "upload" or download" file (list): UPLO...
53,959
def check_valid_solution(solution, graph): """Check that the solution is valid: every path is visited exactly once.""" expected = Counter( i for (i, _) in graph.iter_starts_with_index() if i < graph.get_disjoint(i) ) actual = Counter( min(i, graph.get_disjoint(i)) for i i...
53,960
def filter_props(props): """Filter props from the Component arguments to exclude: - Those without a "type" or a "flowType" field - Those with arg.type.name in {'func', 'symbol', 'instanceOf'} Parameters ---------- props: dict Dictionary with {propName: propMetadata} structure ...
53,961
def test_get_branch(): """ test getting branch from environment or default """ # Unset defaults to master os.environ["GITHUB_REF"] = "" os.putenv("GITHUB_REF", "") branch = get_branch() if branch != "master": raise AssertionError # Set both GitHub input variable and ref (ref...
53,962
def test_module(): """ Performs basic get request to get system info """ http_request('GET', 'system/info') demisto.results('ok')
53,963
def backupCollection(mongo, zipFile, collection): """ Extract collection from DB, write it to a file, and add file to the zip file.""" dbCollection = mongo.getMviDatabase()[collection] logging.info(f"Backing up {dbCollection.count()} documents from collection {collection}.") documents = dbCollection.f...
53,964
def throw_error(message, title='Error', parent=None): """ Generic way to throw an error and display the appropriate dialog """ dlg = wx.MessageDialog(parent, message, title, wx.OK | wx.ICON_ERROR) dlg.CenterOnParent() dlg.ShowModal() dlg.Destroy()
53,965
def _yum_fix_repo_host(remote, project): """ Update the hostname to reflect the gitbuilder_host setting. """ # Skip this bit if we're not using gitbuilder #if not isinstance(packaging.get_builder_project(), # packaging.GitbuilderProject): if teuth_config._defaults['use_...
53,966
def sqr_ts(timeseries, nodata=-9999): """sqr - Interquaritle range (IQR) It computes the interquaritle range of the time series. :param timeseries: Your time series. :type timeseries: numpy.ndarray :param nodata: nodata of the time series. Default is -9999. :type nodata: int :returns: The...
53,967
def parse_args(cloud_args=None): """parameters""" parser = argparse.ArgumentParser('mindspore classification training') parser.add_argument('--platform', type=str, default='Ascend', choices=('Ascend', 'GPU'), help='run platform') # dataset related parser.add_argument('--data_dir', type=str, default...
53,968
async def do_something() -> None: """ While waiting for confirmation, you can execute arbitrary code here. """ for _ in range(5): print('Doing something in the meantime...') await asyncio.sleep(2)
53,969
def to_shape(data: Union[Collection, Tensor], add_batch=False, exact_shape=True) -> Union[Collection, Tensor]: """Compute the shape of tensors within a collection of `data`recursively. This method can be used with Numpy data: ```python data = {"x": np.ones((10,15)), "y":[np.ones((4)), np.ones((5, 3))],...
53,970
def Color(colorname): """pygame.color.Color(colorname) -> RGBA Get RGB values from common color names The color name can be the name of a common english color, or a "web" style color in the form of 0xFF00FF. The english color names are defined by the standard 'rgb' colors for X11. ...
53,971
def _create_output(sdfg: SDFG, inputs: List[UfuncInput], outputs: List[UfuncOutput], output_shape: Shape, output_dtype: Union[dtypes.typeclass, List[dtypes.typeclass]], storage: dtypes.S...
53,972
def from_image_files( images_dir: str, extensions: str | tuple[str, ...] = '.jpg', selection: set[str] = set(), ) -> Statistics: """From a directory path with images, will generate the stats of all images. The statistics generated are: mean, std, max, and min. Parameters ---------- imag...
53,973
def _memoized_fibonacci_aux(n: int, memo: dict) -> int: """Auxiliary function of memoized_fibonacci.""" if n == 0 or n == 1: return n if n not in memo: memo[n] = _memoized_fibonacci_aux(n - 1, memo) + \ _memoized_fibonacci_aux(n - 2, memo) return memo[n]
53,974
def make_app(table_size, update_size, update_rate): """Create a Tornado application for the webserver.""" MANAGER.host_table("table", TABLE) MANAGER.host_view("view", VIEW) if table_size is not None and TABLE.size() < table_size: current_size = TABLE.size() while current_size < table_s...
53,975
def get_scan_info(in_file): """ Get useful scan-parameters. Function to extract some useful scan-parameters. Parameters ---------- in_file : str Path to (functional!) nifti-image Returns ------- TR : float Time-to-repetition of file """ import nibabel as nib ...
53,976
def merge_sort(array_of_numbers): """ This should split the array into single numbers and then recombine the list into a single sorted list in a recursive way. :param array_of_numbers: :return: """ length = len(array_of_numbers) split = int(length/2) if length <= 1: return ...
53,977
def select_random_ports(n): """Selects and return n random ports that are available.""" ports = [] for i in xrange(n): sock = socket.socket() sock.bind(('', 0)) while sock.getsockname()[1] in _random_ports: sock.close() sock = socket.socket() sock....
53,978
def update_server_version(sender, data, server, **kwargs): """ Store version of the tracker mod running on the server. """ server.version = data['version'].value server.save(update_fields=['version'])
53,979
def parse_args(): """init.""" # yapf: disable parser = argparse.ArgumentParser() model_g = ArgumentGroup(parser, "model", "model configuration and paths.") model_g.add_arg("bert_config_path", str, "data/cased_L-24_H-1024_A-16/bert_config.json", "Path to the json file for bert mo...
53,980
def choose_targets(label_dic_set, m, label_dic, source_label): """ This differs from random.sample which can return repeated elements if seq holds repeated elements. """ #global count1 #global count2 targets = set() if len(label_dic_set[source_label]) > m: #print(1) whil...
53,981
def sinkhorn(C, log_w_p, log_w_q, key, alpha=0.01): """Uses sinkhorn iterations to solve an optimal transport problem. Computes the optimal cost and transport plan for moving mass from an atomic measure p to another atomic measure q. Args: C: The cost matrix, C_ij contains the cost of moving mass from the...
53,982
def string_count_words(string: str) -> dict: """Count occurrences of individual words in a given string This function counts occurrences of each separate words. It returns a dictionary, in wich keys correspond to words and values to the number of occurrences. Args: string (str): String for the countin...
53,983
def compute_class_freqs(labels): """ https://www.kaggle.com/eugennekhai/chest-x-ray-pytorch-lightning-densnet121 Compute positive and negative frequences for each class. Args: labels (np.array): matrix of labels, size (num_examples, num_classes) Returns: positive_frequencies (np.arr...
53,984
def remove_duplicates(data): """ Removes duplicate elements from given sequence: >>> remove_duplicates('abcdaefbg') ['a', 'b', 'c', 'd', 'e', 'f', 'g'] If mutable argument passed, it should remain unchanged: >>> data = [1, 2, 2, 3, 4, 2, 3, 5] >>> remove_duplicates(data) [1, 2, 3, 4, 5]...
53,985
def cayley_menger_analysis(vertices, d = 2): """ Determines volume and circumradius for a tetrahedron given the vertices https://westy31.home.xs4all.nl/Circumsphere/ncircumsphere.htm#Coxeter """ if d == 3: cm_matrix = np.array([[0, 1, 1, 1, 1], [1, 0, distance.sqeuclidean(vertices[0], vertic...
53,986
def module_dir_path(request): """Assure a directory exists in this module. The directory name is given by the environment variable combining the module name and "_DIR". For example, module test_foo.py will use the environment variable named TEST_FOO_DIR. Return the path to the directory or Non...
53,987
def merge_lists(): """Returns pairs from each list.""" x = ['A', 'B', 'C'] y = ['x', 'y', 'z'] # Your code goes here
53,988
async def async_setup_entry(hass, entry): """Set up a bridge for a config entry.""" await async_setup_bridge(hass, entry.data['host'], username=entry.data['username']) return True
53,989
def find_test_pack_root(): """Walks upward from the current directory until it finds a directory containing .stbt.conf """ root = os.getcwd() # This gets the toplevel in a cross-platform manner "/" on UNIX and # (typically) "c:\" on Windows: toplevel = os.path.abspath(os.sep) while roo...
53,990
def make_non_parallel_copy(model): """Make a non-data-parallel copy of the provided model. torch.nn.DataParallel instances are removed. """ def replace_data_parallel(container): for name, module in container.named_children(): if isinstance(module, nn.DataParallel): ...
53,991
def from_dependent_matroid(matroid: tuple[set[T], list[set[T]]]) -> Callable[[set[T]], int]: """Construct a nulity function from a matroid defined by dependent sets. Args: matroid (tuple[set[T], list[set[T]]]): A matroid defined by dependent sets. Returns: Callable[[set[T]], int]: The nuli...
53,992
def convolve(image, psf, return_Fourier=False): """ Convolves given image by psf. Args: image: a JAX array of size [nx, ny], either in real or Fourier space. psf: a JAX array, must have same shape as image. return_Fourier: whether to return the real or Fourier image. Returns: The resampled kimage...
53,993
def dump_libffm_file(data, label, f='data_ffm.txt', feature_name='auto', categorical_feature='auto'): """Dump the dataset in libffm file format. This format is a text-based format, with one sample per line. It does not store zero valued features hence is suitable f...
53,994
def read_csv(file: PATH_TYPE) -> pd.DataFrame: """A wrapper for ``pd.read_csv`` which tries to handle errors gracefully. Args: file: The CSV file to read. Returns: A ``DataFrame`` containing the contents of the file. """ try: return pd.read_csv(file, encoding="utf-8") e...
53,995
def tfm_shear(x_angle=0.0, y_angle=0.0, shape=(0, 0)): """ Generate a shear transformation matrix. :param x_angle: The angle to shear the image in horizontal direction :param y_angle: The angle to shear the image in vertical direction :param shape: The shape of the image to be transformed :retu...
53,996
def test_6(data_file_path, resolution, *args): """`avg_last_3yr_viols` vs `last_yr_viols` """ data = pd.read_csv(data_file_path) data.fillna(0) feature1 = args[0] feature2 = args[1] label = args[2] x_train = data[[feature1, feature2]].values y_train = data[label].values lr = ...
53,997
def run_pytype(code: str, check: bool) -> subprocess.CompletedProcess: # pylint: disable=g-doc-args """Runs pytype on the specified code. Raises: subprocess.CalledProcessError if check=True and pytype return is non-zero Returns: A subprocess.CompletedProcess instance containing stdout """ with tem...
53,998
def _load(handler_obj): """ Load an :class:`.IHandler` handler object. The handler_obj.load_type() defines whether :func:`._load_module_function` or :func:`._load_module_class` is to be used. """ if handler_obj.load_type() == "function": return _load_module_function(handler_obj) ...
53,999