content
stringlengths
22
815k
id
int64
0
4.91M
def rand_replace(rep_fun): """ Wrapper of contrastive sample generate functions. """ def gen_neg_subwords(example, tokenizer, cont_ent_idx, auxiliary_json=None, max_seq_len=128): cont_example = copy.deepcopy(example) entities = cont_example.entities if not entities: ...
69,500
def locate_ellipsoid(frame, spacing=1, rad_range=None, maxfit_size=2, spline_order=3, threshold=0.1): """Locates an ellipsoid in a 3D image and returns center coordinates and radii along x, y, z. The function fully analyzes the vesicle. Parameters ---------- image3d: 3D ndarray...
69,501
def _hist_bin_sturges(*input_data): """ Sturges histogram bin estimator. A very simplistic estimator based on the assumption of normality of the data. This estimator has poor performance for non-normal data, which becomes especially obvious for large data sets. The estimate depends only on size ...
69,502
def test_rn_validation_valid_number_is_really_valid(): """Test if a valid number is really valid""" valid_number = '200400401' assert rn.start(valid_number)
69,503
def dialog_response(attributes, endsession): """ create a simple json response with card """ return { 'version': '1.0', 'sessionAttributes': attributes, 'response':{ 'directives': [ { 'type': 'Dialog.Delegate' } ...
69,504
def generate_c(repository): """ Generate a repository with some example data. :param repository: Repository to generate. Must not already exist. """ from splitgraph.core.engine import repository_exists if repository_exists(repository): raise click.ClickException( "Repositor...
69,505
def zero_auth(start, end, delta): """ Ciclo per produrre tutti i secondi della giornata """ current = start while current < end: yield current current += delta
69,506
def infer_optimal_calib(input_files, model_wrappers, image_shape, half): """ Process a single input file to produce and save visualization Parameters ---------- input_file : list (number of cameras) of lists (number of files) of str Image file output_file : str Output file, or f...
69,507
def canpickle(obj): """ Determine if object can be pickled :returns: `bool` """ import os try: from cPickle import UnpickleableError as unpick_error import cPickle as pickle from cPickle import PicklingError as unpick_error_2 except ImportError: import pickl...
69,508
def define_integrals_app(crd: CRDFileProcessor, logy: bool = True) -> None: """Create a PyQt5 app for defining integrals. :param crd: CRD file to calibrate for. :param logy: Should the y axis be logarithmic? Defaults to True. """ app = QtWidgets.QApplication(sys.argv) window = DefineIntegrals(c...
69,509
def create_parser(): """ Read in the cmd line arguments 'data' arg is the data set which shall be used. """ parser = argparse.ArgumentParser() parser.add_argument("data") args = parser.parse_args() return args
69,510
def bring_to_normal(): """ Returns any previous settings for system state and display back to normal. System state may go to idle and display may turn off if no user activity """ if os.name == 'nt': windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
69,511
def getMetadata(path, filename): """ Get the metadata for a specified file. Returns a JSON as follows: { hits: [ {metadata for file} ... ] } This will usually only be one hit. """ token = authenticate() url = "http://{}:{}/query_metadata?project=\"{}\"&source=\"{}\"&Path=\"{}\"&filename=\"{}\"".forma...
69,512
def api_cert_info(): """ Return a JSON with the certificate info """ with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: cert_list = [] for hostinfo in executor.map(lambda x: get_certificate(x[0], int(x[1])), ...
69,513
def mbed_os_support(): """! Function used to determine if host OS is supported by mbed-lstools @return Returns None if host OS is not supported else return OS short name @details This function should be ported for new OS support """ result = None os_info = mbed_lstools_os_info() if (os_inf...
69,514
def sub_field(k, v): """Return a nested dictionary with field keys k and value v.""" res = {} field_d = res fields = k.split('.') for f in fields[:-1]: field_d[f] = {} field_d = field_d[f] field_d[fields[-1]] = v return res
69,515
def mkkekz(u_t, v_t, wap, utt, vtt, p_l, lat, nlat, ntp, nlev): """Compute the zonal mean - eddy KE conversions from u and v. Arguments: - u_t: a 3D zonal velocity field; - v_t: a 3D meridional velocity field; - wap: a 3D vertical velocity field; - utt: a climatological mean 3D zonal velocity f...
69,516
def sieve5(n): """Return a list of the primes below n.""" """from http://codereview.stackexchange.com/questions/42420/sieve-of-eratosthenes-python""" prime = [True] * n result = [2] append = result.append sqrt_n = (int(n ** .5) + 1) | 1 # ensure it's odd for p in range(3, sqrt_n, 2): ...
69,517
def make_chapter_xml((time,name)): """ Creates the xml for the chapter """ chapter = Template(""" <ChapterAtom> <ChapterTimeStart>$time</ChapterTimeStart> <ChapterDisplay> <ChapterString>$name</ChapterString> <ChapterLanguage>eng</ChapterLanguage> </ChapterDisplay> </Ch...
69,518
def dropout(input, rate=.5, noise_shape=None, training=False, name=None): """ Apply dropout on `input`. Args: input (Tensor): The input tensor. rate (float or tf.Tensor): The rate of dropout. noise_shape (tuple[int] or tf.Tensor): Shape of the noise. If not specified, us...
69,519
def refresh_pkce_token( client_id: str, refresh_token: str ) -> RefreshingToken: """ Request a refreshed PKCE user token. Parameters ---------- client_id client ID refresh_token refresh token Returns ------- RefreshingToken automatically refreshing u...
69,520
def convert_physio(ds, dest_dir, physio_stub, verbose=False): """ Purpose ---- Read physio data from a CMRR Multiband generated DICOM file (DICOM spectroscopy format) Current CMRR MB sequence version : VE11C R016a Adapt parsing logic from extractCMRRPhysio.m. Also see adolphslab/mriphysio/dcm2ph...
69,521
def jsonify_new_book(book): """return json object of newly uploaded book""" book_data = {'book_id': book.book_id, 'title': book.title, 'author': book.author, 'image_url': book.image_url, 'genre': book.genre, 'description': book.des...
69,522
def build_smod(builder, a, b, name): """Builds expression for signed int modulo.""" rem = BuildSRem(builder, a, b, "") neg_rem = BuildMul(builder, rem, ConstInt(TypeOf(rem), -1, True), "") return BuildSelect(builder, _mod_scale(builder, a, b), neg_rem, rem, name)
69,523
def upload_indicators_command( client: QRadarClient, ref_name=None, element_type=None, timeout_type=None, query=None, time_to_live=None, limit=1000, page=0, ): """ Finds indicators according to user query and updates QRadar reference set Returns: (string, dict). Huma...
69,524
def test_lsun_zip(): """ Feature: LSUN Description: test basic usage of LSUN Expectation: the dataset is as expected """ logger.info("Test Case zip") # define parameters repeat_count = 2 # apply dataset operations data1 = ds.LSUNDataset(DATA_DIR, num_samples=10) data2 = ds.L...
69,525
def create_stream(context=None): """ create a stream. .. note:: case 1. context is None. Get the context and create a new stream. case 2. context is not None. Create a new stream on existing context. Args: context (int): If context is None, it will get context and then create a stre...
69,526
def get_prediction(model, batch, device): """Get predicted labels for given input batch and model.""" images = torch.tensor(batch, dtype=torch.float).to(device) outputs = model(images) _, predicted = torch.max(outputs.data, 1) return predicted
69,527
def parse_args(input_args, parser, allow_unknown=True): """Parse an argument list using parser generated by create_parser() Parameters ---------- input_args: list A list of arguments Returns ------- args: argparse.Namespace A simple object storing the input arguments un...
69,528
def test_HVAC_Average_watts_for_small_time_frame(typicalHvac: HVAC): """Tests the The average watts per second calculation Arguments: typicalHvac {HVAC} -- the hvac test fixture object """ typicalHvac.TurnCoolingOn() typicalHvac.SimulateOneSecond() typicalHvac.SimulateOneSecond() typicalHvac.SimulateOneSecon...
69,529
def keep_points_outside_shape(xy_iterable, shape, exclusion_buffer): """From an iterable of (x, y) iterables, select points outside a shapely shape, with an exclusion buffer (positive)""" return [ np.array(xy, dtype=np.float32) for xy in xy_iterable if not shape.buffer(exclusion_buffer)....
69,530
def testing_gallery(tmpdir): """Testing gallery with two albums: - testing-album - album-incomplete (without album metadata in album.ini) Both galleryes contain four photos: Photo{1..4}.jpg """ shutil.copy(os.path.join(DATA_PATH, 'gallery.ini'), str(tmpdir)) _create_album(tmpdir, 'testing-al...
69,531
def ControlsAreSame(control1, control2): """return 1 if control1 and control2 are the same control, otherwise return 0""" return _AutomationClient.instance().dll.CompareElements(control1.Element, control2.Element)
69,532
def close(): """ Close all pool connections and shutdown the pool. """ global db_pool db_pool.close() return db_pool
69,533
def check_sorting(previous_chrom, previous_pos, current_chrom, current_pos): """docstring for check_sorting""" pass
69,534
def create_app(test_config=None): """create and configure the app""" app = Flask(__name__, instance_relative_config=True) app.secret_key = os.urandom(12) # Generic key for dev purposes only # ======== Routing ============================= # # -------- Home -------------------------------- # @a...
69,535
def create_dir_structure(directory_path, create_sub_dir): """ Creates required directory structures inside the parent directory figures. Args: directory_path: string Given path that already exists. create_sub_dir: string Sub dir...
69,536
def build_optimizer(network, optimizer:str, learning_rate:float): """Optimizer creation Args: network (torch.model): Network to train optimizer (str): optimizer type one of [sgd,adam,rmsprop] learning_rate (float): float learning rate Returns: [torch.optim.optimizer]: optim...
69,537
def stopApplicationOnCluster(appname,clustername): """Stops the named application on all servers in named cluster""" m = "stopApplicationOnCluster:" sop(m,"Entry. appname=%s clustername=%s" % ( appname, clustername )) server_id_list = listServersInCluster( clustername ) for server_id in server_id_li...
69,538
def test_creating_tables_from_models(): # language=rst """ Creating tables from models --------------------------- Say I have some model: """ class Foo(models.Model): a = models.IntegerField() def __str__(self): return f'Foo: {self.a}' # @test clas...
69,539
def send_msg(app, msg): """ Send an openflow message. """ return app.send_request(event.SendMsgRequest(msg=msg))()
69,540
def _standardize_node_pro_config_entry(hass, config_entry): """Ensure that Node/Pro config entries have appropriate properties.""" entry_updates = {} if CONF_INTEGRATION_TYPE not in config_entry.data: # If the config entry data doesn't contain the integration type, add it: entry_updates["da...
69,541
def _write_bot(botname, botdir, c_key, c_secret, a_token, a_secret): """ Handles creating the bot directory and writing all the components of the bot: configuration, models, and the main driver. """ os.mkdir(botdir) os.chdir(botdir) f = open("./settings.cfg", "w") c = """# Sets the confi...
69,542
def test_from_name(): """Make sure one can construct a Component subclass by name""" subclass = ExampleComponent.from_name("ExampleSubclass1") assert isinstance(subclass, ExampleSubclass1) subclass = ExampleComponent.from_name("ExampleSubclass2") assert isinstance(subclass, ExampleSubclass2)
69,543
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. ...
69,544
async def get_crypto(symbol): """Returns the data of a crypto. symbol: bytes """ data = crypto.get(symbol.encode()) if data: return orjson.loads(data) return None
69,545
def get_monthly_fields(cases, varlist, from_time, to_time, pressure_adjust=True, raw_data_path=get_input_datapath(), model='NorESM'): """ Get monthly fields of files (i.e. not averaged) :param cases: list of cases to load :param varlis...
69,546
def move_blob_file(connect_str: str, source_container: str, target_container: str, source_path: str, target_path: str) -> None: """ Move blob from source to destination container """ logging.info('Move blob from %s/%s to %s/%s', source_container, source_path, target_container...
69,547
def valid_search_inputs_1(): """Basic search input tests for Sra and Ena (single inputs)""" return [ [ 0, 20, ["covid-19"], None, None, None, None, None, None, None, None, ...
69,548
def WriteImageSeries(writer, tag, n_images=1): """Write a few dummy images to writer.""" step = 0 session = tf.Session() p = tf.placeholder("uint8", (1, 4, 4, 3)) s = tf.image_summary(tag, p) for _ in xrange(n_images): im = np.random.random_integers(0, 255, (1, 4, 4, 3)) summ = session.run(s, feed_d...
69,549
def chooseRandPixel(mask): """ Returns [x,y] numpy array of random pixel. NOTE: the returned [x, y] correspond to [row, col] in the mask @param {numpy matrix} mask from which to choose random pixel. E.g., self.level_dims = self.slide.level_dimensions self.zoom = self.le...
69,550
def copytree( dest, select, root_start=None, followlinks=True, handler_cls=None): """Copies files to dest for a FileSelect. root_start is an optional location from which select.root, if relative, starts. Defaults to os.curdir. If followlinks is True (the default...
69,551
def _setup_batch(batch_shape): """Create random time points with batch_shape and a Constant kernel""" num_data = 9 np.random.seed(1234) shape = batch_shape + (num_data,) return ( tf.convert_to_tensor( generate_random_time_points(expected_range=4.0, shape=shape), tf.float64 ...
69,552
def query_build_version(config, log): """Find the build version we're looking for. AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query, only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status...
69,553
async def test_event_forwarding( decoy: Decoy, subject: HardwareEventForwarder, hardware_control_api: HardwareControlAPI, action_dispatcher: ActionDispatcher, ) -> None: """It should forward events that come from a different thread.""" handler_captor = matchers.Captor() unsubscribe_callback ...
69,554
def get_directed_edges( nodes, edges, direction="oneway", from_id_col="u", to_id_col="v", node_id_col="id", force_bidirectional=False, network_type=None, ): """Prepares the edges and nodes for exporting to different graphs.""" allowed_network_types = Conf._possible_network_filter...
69,555
async def cmd_raw_research(ctx: commands.Context, *, research_id: str = None): """ Get raw research design data from the PSS API. Usage: /raw research <id> <format> Parameters: id: An integer. If specified, the command will only return the raw data for the research with the specified i...
69,556
def list_split(l, indices): """Split list at given indices. Closed lists have the same first and last elements. If the list is closed, splitting wraps around if the first or last index is not in the indices to split. Parameters ---------- l : list A list. indices : list ...
69,557
def test_no_words(): """ No words in input """ result = {'lan': 'es', 'tokens': []} mock_response = {'tokens': [], 'language': 'es'} response_obj = munchify(mock_response) with mock.patch('extract.gcloud_syntax_extraction', return_value=response_obj): assert result == get_keywords(...
69,558
def trigger(version, appengine_instance, access_token): """Triggers db migration.""" base_url = 'https://{0}-dot-{1}.appspot.com/maintenance'.format( version, appengine_instance) url = base_url + '/migrate' post_data = {'access_token': access_token} response = requests.post(url, data=post_data) ...
69,559
def test_get_evaluation_concurrency(): """Test getting default evaluation_concurrency property.""" value = c.evaluation_concurrency assert_equal(value, default_evaluation_concurrency)
69,560
def sphinx_quickstart( temp_root: Union[str, Path], requirements: Optional[List[str]] = None ): """ Generate required files for a Sphinx project. sphinx-quickstart is an interactive tool that asks some questions about your project and then generates a complete documentation directory and sample Make...
69,561
def create_filing(token=None, filing_json=None, business_id=None, filing_date=EPOCH_DATETIME, bootstrap_id: str = None): """Return a test filing.""" filing = Filing() if token: filing.payment_token = str(token) filing.filing_date = filing_date if filing_json: filing.filing_json = fi...
69,562
def plot_3D(X, y, z, elev=30, azim=30): """ Plots rotatable 3D scatter plot with scaled z-axis. ----------- Parameters: - X: matrix with (x1, x2) data points - y: vector with color labels for individual points - z: vector with scale levels for individual points - ele...
69,563
def load_notes_midi(midi_path): """ Load all MIDI notes from a MIDI file, keeping track of sustain pedal activity. TODO - make sustain pedal stuff optional? TODO - break this up more? Parameters ---------- midi_path : string Path to MIDI file to read Returns ---------- ba...
69,564
def napari_experimental_provide_dock_widget() -> Union[ AugmentedWidget, List[AugmentedWidget] ]: """Provide QWidget classes to be instantiated and docked on the viewer. This hook specification is marked as experimental as the API or how the returned value is handled may change here more frequently the...
69,565
def get_tracks_as_np_strings(labels: Labels) -> List[np.string_]: """Get list of track names as `np.string_`.""" return [np.string_(track.name) for track in labels.tracks]
69,566
def _model_validation_for_base(opt, base_model, device, tokenizer, with_mask=False): """ validation set 을 이용하여 모델 정확도 계산 """ corpus_list, asp_info = loader.load_validation_data() transform = nlp.data.BERTSentenceTransform( tokenizer, max_seq_length=opt["bert_max_len"], pad=True, pair=Tru...
69,567
def no_op(ctx, node, name, args): """Skip node.""" return None
69,568
def mastQuery(request): """Perform a MAST query. Parameters ---------- request (dictionary): The MAST request json object Returns head,content where head is the response HTTP headers, and content is the returned data """ server='mast.stsci.edu' # Grab Python Version version ...
69,569
def log_likelihood(z:Union[np.ndarray,float,int], x:np.ndarray, P:np.ndarray, H:np.ndarray, R:np.ndarray) -> Union[np.ndarray,float,int]: """ Returns log-likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R """ S = np...
69,570
def recession_index(data, compare=operator.gt): """returns the index of the start of the recession Parameters ---------- data: DataFrame GDP data to search compare: function compare quarters (change to < to find end) Returns ------- int : iloc of start of first recessi...
69,571
def block_iter(fileobj, blocksize=io.DEFAULT_BUFFER_SIZE): """Iterate over fileobj and yield blocks up to size of blocksize. Arguments: fileobj {[type]} -- Any object supporting .read() method. Notes: Iteration will attempt to find EOF position and iterate till EOF. Otherwise, iter...
69,572
def copy_tree(t): """Returns a copy of t. Only for testing purposes. >>> t = tree(5) >>> copy = copy_tree(t) >>> t = tree(6) >>> print_tree(copy) 5 """ return tree(root(t), [copy_tree(b) for b in branches(t)])
69,573
def set_owner(conn, uuid, owner): """Set ON_OWNER by uuid. @param uuid: uuid of the VM @param owner: string representing owner """ # Save owener regardless if VM is working or not # Old logic will write owner info only if VM is working. owners_file = '/etc/opennode/kvmowners' # XXX: tou...
69,574
def wait_for_element_not_visible( driver, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=settings.LARGE_TIMEOUT ): """ Searches for the specified element by the given selector. Raises an exception if the element is still visible after the specified timeout. @Params driver - the webdrive...
69,575
def connect_info_factory(info_type: str, **kwargs): """ Creates a specific ConnectInfo based on the type of connection we are looking for. Any additional kwargs specified are passed on to the appropriate ConnectInfo constructor. :param info_type: the connection info type to make. For example, 'irc'. ...
69,576
def test_post_unknown_field(client): """Do we properly reject a POST with an unknown field?""" response = client.post( '/artist/', data=json.dumps({'foo': 'bar', 'Name': 'Jeff Knupp'}), headers={'Content-type': 'application/json'} ) assert response.status_code == 400 json_res...
69,577
def test_compress_assets_correctly_fetches_static_images(settings, tmpdir): """ Make sure that `compress_assets` correctly fetches static assets such as icons and writes them correctly into our compressed and concatted files. Refs https://github.com/mozilla/addons-server/issues/8760 """ set...
69,578
def entity_similarity(algo, entity1, entity2): """ measure the similarity of the two entities :param algo: the algorithm to measure similarity :param entity1, entity2: two entities to measure analogy :return: [float] in [0. 1) """ if algo == "jaccard": return jaccard_similarity_score...
69,579
def cancel(form): """Callback for dialog cancel""" choice = QMessageBox.question(None, 'Question', 'Are you sure?', QMessageBox.Yes | QMessageBox.No) if choice == QMessageBox.Yes: form.close()
69,580
def uploadFolderCsvToBlob(storage_account, storage_key, container, in_dir, blob_out_dir): """ Uploads csvs in a folder into blob storage """ # Create blob service block_blob_service = BlockBlobService(account_name=storage_account, account_key=storage_key) # Create container if not exists ...
69,581
def hook_compressed_text(filename, mode, encoding='utf8'): """ #lines are byte strings and not text string if we use gzip.open by default. """ ext = os.path.splitext(filename)[1] if ext == '.gz': import gzip return gzip.open(filename, mode + 't', encoding=encoding) #elif ext == ...
69,582
def deprecated(func): """ Decorator to be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. Usage:: @other_decorators_must_be_upper @deprecated def some_old_function(x,y): return x + y class SomeClass: ...
69,583
def test_output_type(value, ff_cls, exp_type): """The FuzzyField always returns the correct type """ ff = ff_cls() res = ff.parse(value) assert res == 1 assert isinstance(res, exp_type)
69,584
def setup_cli(args, cfg): """ Configure command-line arguements """ description =""" Benign_domains outputs a list of preceived benign domains. This is intended to help gather data for ML training sets and generate white lists. The core set of domains are provided by majestic million. Opti...
69,585
def metadata_label_cbor(self, label: str, **kwargs): """ Transaction metadata per label. https://docs.blockfrost.io/#tag/Cardano-Metadata/paths/~1metadata~1txs~1labels~1{label}~1cbor/get :param label: Metadata label :type label: str :param return_type: Optional. "object", "json" or "pandas". D...
69,586
def uses_gpu(*args): """Mark to differentiate tests that use the GPU is some capacity. These tests will be run on CPU-only test nodes and on test nodes with GPUS. To mark a test that must have a GPU present to run, use :py:func:`tvm.testing.requires_gpu`. Parameters ---------- f : function...
69,587
def get_imbalances(regressions): # Deprecated """ Generates a numpy array of the imbalances. For a value *x* where *x* is the beta of a regression: ========= ====== ======================================================= *x* < 0 **-1** The regression had a negative beta value *x* = nan **0** The regression ...
69,588
def iterview(server_url, database_name, view_name, sleep_seconds=10, wrapper=None, **options): """Iterate the rows in a view, fetching rows in batches and yielding one row at a time. Since the view's rows are fetched in batches any rows emitted for documents added, changed or deleted between requests m...
69,589
def compute_walk_paths_java(gtfs_db_path, osm_file, cache_db=None): """ Parameters ---------- gtfs_db_path: str (path to the gtfs database) osm_file: str cache_db: str Returns ------- None """ raise NotImplementedError("This has not been pipelined yet. Please see the Python ...
69,590
def _mock_repo(root, namespace): """Create an empty repository at the specified root Args: root (str): path to the mock repository root namespace (str): mock repo's namespace """ repodir = py.path.local(root) if isinstance(root, str) else root repodir.ensure(spack.repo.packages_dir...
69,591
def get_course_ids(): """ Get a list of course ids that is necessary for the rest of the functions to work. """ global course_ids dump_course_ids = subprocess.Popen(['/edx/bin/python.edxapp', '/edx/app/edxapp/edx-platform/manage.py', ...
69,592
def get_optimizer(learning_rate, config): """Returns the optimizer of choice given the configurations.""" if isinstance(config, experiment.MomentumOptimizer): optimizer = tf.keras.optimizers.SGD( learning_rate=learning_rate, momentum=config.momentum, nesterov=config.nesterov ) ...
69,593
def get_gitlab_project_data(initial_data, headers, resources): """ Get all directories and files of given projects. Parameters ---------- initial_data: list List of all top level projects headers: dict The authorization header that GitLab expects resources: list A li...
69,594
def convert_observations(observations:str)->List[str]: """ Parses a string with observations separated by comas. Args: observations: str -> Obesrvations string, each observation must be separated by a coma. Example "Green, ugly, has errors" Retrun: ...
69,595
def prepare_data(data, nlags): """prepares data for LSTM model, x=last nlags values, y=(nlags+1)'th value""" data_x, data_y = [], [] for i in range(data.shape[0]): for j in range(0, data.shape[1] - nlags): data_x.append(data[i, j : j + nlags]) data_y.append(data[i, j + nlags]...
69,596
def divisors(n: int) -> list[int]: """Get the proper divisors of a number n""" limit = int(math.sqrt(n)) + 1 proper_divisors = {1} for i in range(2, limit): if n % i == 0: proper_divisors.add(n // i) proper_divisors.add(i) return list(proper_divisors)
69,597
def compressImage(image, height): """ Note: Should probably replace this method with one from photutils or PIL.Image. Will probably be faster/more accurate and can handle both increasing and decreasing resolution """ """ Compresses the image to a given size. Given that 3D printing cannot handle fine resolution, a...
69,598
def get_lsb_num(num): """docstring""" cnt = 0 while not (num >> cnt) & 1: cnt += 1 # return cnt + 1
69,599