content
stringlengths
22
815k
id
int64
0
4.91M
def transform_url(url, qparams=None, **kwargs): """ Modify url :param url: url to transform (can be relative) :param qparams: additional query params to add to end of url :param kwargs: pieces of URL to modify - e.g. netloc=localhost:8000 :return: Modified URL .. versionadded:: 3.2.0 """ ...
49,500
def stop_slash2_socks(tsuite, sock_name, sl2objects, ctl_type, daemon_type): """ Terminates all slash2 socks and screen socks on a generic host. Args: tsuite: tsuite runtime. sock_name: name of sl2 sock. sl2objects: list of objects to be launched. ctl_type: key to ctl path in src_dirs daemon_typ...
49,501
def coords_in_bbox(pose, bbox): """ Return coords normalized to interval's bbox as dict of np arrays. origin at box center, (.5, .5) """ x1, x2, y1, y2 = bbox width = x2 - x1 height = y2 - y1 origin = np.array([x1, y1]) scale = np.array([width, height]) normalized_pose = {} for j...
49,502
def display_instances(image, boxes, masks, ids, names, scores): """ take the image and results and apply the mask, box, and Label """ n_instances = boxes.shape[0] colors = random_colors(n_instances) if not n_instances: print('NO INSTANCES TO DISPLAY') else: assert boxes....
49,503
def scrape_page(url): """ Given a URL, it adds in the database all the links contained in that web page. :param url: A string containing the URL of the web page to analyse. :return: None. """ print(f"{get_time()} [SELENIUM] Page rendering started.") browser = webdriver.Firefox(executable_pat...
49,504
def _find_xy(ll, T, M, maxiter, atol, rtol, low_path): """Computes all x, y for given number of revolutions.""" # For abs(ll) == 1 the derivative is not continuous assert abs(ll) < 1 M_max = np.floor(T / pi) T_00 = np.arccos(ll) + ll * np.sqrt(1 - ll ** 2) # T_xM # Refine maximum numb...
49,505
def ligne_vivante(ligne, x_1, x_2): """ Retourne un booléen indiquant si la ligne spécifiée contient au moins une cellule vivante """ for colonne in range(x_1, x_2 + 1): if plateau[ligne][colonne] != CELLULE_MORTE: return True return False
49,506
def changeMatchingReciprocity(G, i, j): """ change statistic for categorical matching reciprocity """ return G.catattr[i] == G.catattr[j] and G.isArc(j, i)
49,507
def compare_letters(letter1, letter2, table=ambiguity_code_to_nt_set): """Compare two extended nucleotide letters and return True if they match""" set1 = table[letter1] set2 = table[letter2] if set1 & set2 != set(): is_match = True else: is_match = False return is_match
49,508
def get_swarm_yspans(coll, round_result=False, decimals=12): """ Given a matplotlib Collection, will obtain the y spans for the collection. Will return None if this fails. Modified from `get_swarm_spans` in plot_tools.py. """ import numpy as np _, y = np.array(coll.get_offsets()).T try: ...
49,509
def secondes(heure): """Prend une heure au format `H:M:S` et renvoie le nombre de secondes correspondantes (entier). On suppose que l'heure est bien formattée. On aura toujours un nombre d'heures valide, un nombre de minutes valide et un nombre de secondes valide. """ H, M, S = heure.split(":")...
49,510
def central_crop(image, crop_height, crop_width, channels=3): """Performs central crops of the given image list. Args: image: a 3-D image tensor crop_height: the height of the image following the crop. crop_width: the width of the image following the crop. Returns: 3-D tensor with ...
49,511
def mapper_or_checker(container): """Callable to map the function parameter values. Parameters ---------- container : dict-like object Raises ------ TypeError If the unit argument cannot be interpreted. Example ------- >>> conv = mapper_or_checker({True: 42}) >>> c...
49,512
def cmd_konesyntees(bot, update, args): """Use superior estonian technology to express your feelings like you've never before!""" chatid = update.message.chat_id text = '' for x in args: text += f'{x} ' try: tts = gTTS(text=text, lang='et') tts.save('bot/konesyntees/konesynt...
49,513
def test_bool2int(): """ Converts a boolean array to an unsigned integer """ #assert fandango.functional.bool2int
49,514
def download_file(filename_with_path, url, use_curl=False, overwrite=False): """ downloads a file from any URL :param filename_with_path: filename with path to download file to :type filename_with_path: ``str`` :param url: URL to download map from :type url: ``str`` :param...
49,515
def numeric_check(param, name): """ Ensures that a given parameter is a numerical value Parameters ========== param :: object The parameter itself to type-check name :: str The name of the parameter as VICE sees it Raises ====== TypeError :: :: param is not a real number """ if not isin...
49,516
def run_stylelint(options): """ Runs stylelint on Sass files. If limit option is passed, fails build if more violations than the limit are found. """ violations_limit = int(getattr(options, 'limit', -1)) num_violations = _get_stylelint_violations() # Record the metric _write_metric(num_...
49,517
def tinynet_a(pretrained=False, **kwargs): """ TinyNet """ r, c, d = TINYNET_CFG['a'] default_cfg = default_cfgs['tinynet_a'] assert default_cfg['input_size'] == (3, 224, 224) channel, height, width = default_cfg['input_size'] height = int(r * height) width = int(r * width) default_cfg[...
49,518
def test_article_admin_modelchoice_change_labels(db, admin_client): """ Admin change form should have language names in model choices fields. """ # Create new objects CategoryFactory(title="garlic", language="en") CategoryFactory(title="ail", language="fr") ArticleFactory(title="egg", langu...
49,519
def srwl_uti_write_data_cols(_file_path, _cols, _str_sep, _str_head=None, _i_col_start=0, _i_col_end=-1): """ Auxiliary function to write tabulated data (columns, i.e 2D table) to ASCII file :param _file_path: full path (including file name) to the file to be (over-)written :param _cols: array of data c...
49,520
def reserve_offer_request(offer_id: int, adult_count: int, children_count: int): """ Request order offer """ # call to API Gateway for getting offers response = requests.post( ORDER_RESERVE_REQUEST_ENDPOINT, data={ "offer_id": offer_id, "customer_email": sessi...
49,521
def evaluate_nccl(baseline: dict, results: dict, failures: int, tolerance: int) -> int: """ Evaluate the NCCL test results against the baseline. Determine if the NCCL test results meet the expected threshold and display the outcome with appropriate units. Parameters ---------...
49,522
def calculate_AUC(x_axis, y_axis): """ Calculates the Area Under Curve (AUC) for the supplied x/y values. It is assumed that the x axis data is either monotonoically increasing or decreasing Input: x_axis: List/numpy array of values y_axis: list/numpy array of values Output: ...
49,523
def bisec_method(func, tol=0.01, lo=None, up=None, debug=False, flex_up=False, increasing=None): # TODO-doc TODO-PW """ Execute the bisection method to find a root of func. Parameters ---------- func: function-handle the function tol: float or tuple the erro...
49,524
def next_nibble(term, nibble, head, worm): """ Provide the next nibble. continuously generate a random new nibble so long as the current nibble hits any location of the worm. Otherwise, return a nibble of the same location and value as provided. """ loc, val = nibble.location, nibble.value ...
49,525
def test_bubble_sort(): """Test bubble sort with random list.""" unsorted = [randint(0, 1000000) for i in range(1000)] assert bubble_sort(unsorted) == sorted(unsorted)
49,526
def line_pattern_matrix(wl, wlc, depth, weight, vels): """ Function to calculate the line pattern matrix M given in Eq (4) of paper Donati et al. (1997), MNRAS 291, 658-682 :param wl: numpy array (1D), input wavelength data (size n = spectrum size) :param wlc: numpy array (1D), central wavelengths ...
49,527
def pandas_join_string_list(row, field, sep=";"): """ This function checks if the value for field in the row is a list. If so, it is replaced by a string in which each value is separated by the given separator. Args: row (pd.Series or similar): the row to check field...
49,528
def OpenClipboardCautious(nToTry=4, waiting_time=0.1): """sometimes, wait a little before you can open the clipboard... """ for i in range(nToTry): try: win32clipboard.OpenClipboard() except: time.sleep(waiting_time) continue else: ...
49,529
def data_change_url_to_name(subject_data: tuple, column_name: str) -> tuple: """ Changes names instead of urls in cell data (later displayed on the buttons). """ return tuple(dh.change_url_to_name(list(subject_data), column_name))
49,530
def get_run_ids(release_id, request_url, auth_token): """ Get the test run IDs for the given release ID - each feature will have a unique run ID :param release_id: the release ID from Azure DevOps :param request_url: the URL for the Microsoft API :param auth_token: the ID number of the release from ...
49,531
def register_received_package(files_storage, pkg_path, _id, annotation=None): """ Raises ------ ReceivedPackageRegistrationError """ zip_path = None basename = os.path.basename(pkg_path) if files.is_zipfile(pkg_path): zip_path = pkg_path zip_name = basename ...
49,532
def setdefault(context, key, value): """If a key is not set in the current task context, map it to a value. If the key is already set, its associated value is unchanged. """ context.setdefault(key, value)
49,533
def operGet(fn): """ this is Decoration method get opearte """ def _new(self, *args, **kws): try: obj = args[0] #print obj.id if hasattr(obj, "id") or hasattr(obj, "_id"): key = operKey(obj, self.name) args = args[1:] k...
49,534
def latent_iterative_pca(layer, batch, conv_method: str = 'median'): """Get NxN matrix of principal components sorted in descending order from `layer_history` Args: layer_history : list, layer outputs during training Returns: eig_vals : numpy.ndarray of absolute value of eigenvalues, s...
49,535
def test_symlinks(): """Checks if relative symbolic links are handled correctly.""" config_file = './study/profit_symlink.yaml' config = Config.from_file(config_file) base_file = './study/run_000/mockup.in' link_file = './study/run_000/some_subdir/symlink_link.txt' try: run(f"profit run...
49,536
def _Generate1xNLoadMultiplyAggregate(emitter, registers, kernel_n, aggregators, lhs, rhs, count): """Emit inner loop for 1 row x M cols multiplication.""" assert kernel_n in [5, 6, 7, 8] emitter.EmitNewline() emitter.EmitComment('General 1xM lanes loop.') emitter.EmitNum...
49,537
def filter_max(data,s=(1,1),m="wrap",c=0.0): """ Apply maximum filter to data (real and imaginary seperately) Parameters: * data Array of spectral data. * s tuple defining shape or size taken for each step of the filter. * m Defines how edges are determinded ('reflect','constant','nea...
49,538
def update_alarms(_): """ Entry point for the CloudWatch scheduled task to discover and cache services. """ return periodic_handlers.update_alarms()
49,539
def price_to_sales(asset: Asset, period: str, period_direction: FundamentalMetricPeriodDirection, *, source: str = None, real_time: bool = False) -> Series: """ Price to Sales of the single stock or the asset-weighted average value of a composite's underliers. 1y forward: time-weighted a...
49,540
def create_mapping(alphabet): """ Change list of chars to list of ints, taking sequencial natural numbers :param alphabet: list of char :return: dictionary with keys that are letters from alphabet and ints as values """ mapping = {} for (letter, i) in zip(alphabet, range(len(alphabet))): ...
49,541
def check_config(content): """checks if config contains valid service names - runs systemctl --all --type service and saves it to an array \\ also appends .service if it's missing""" valid_process_names = [] command = "systemctl --all --type service" try: output = subproces...
49,542
async def async_setup_entry(hass, config_entry, async_add_devices): """Set up the Alexa alarm control panel platform by config_entry.""" return await async_setup_platform( hass, config_entry.data, async_add_devices, discovery_info=None )
49,543
def analyze(clf, data): """ Analyze how well a classifier performs on data. Parameters ---------- clf : classifier object data : dict """ # Get confusion matrix from sklearn import metrics predicted = clf.predict(data['test']['X']) print("predicted is", predicted, data['test...
49,544
def mirror_tensor(*, target: "Tensor", source: "Tensor"): """*Dev use only* Creates a shallow copy of attribute dictionary of ``self`` and assigns it to``tensor``, so that ``tensor`` has the same state as ``self`` and points to the same array data. This is used to facilitate "in-place" operations....
49,545
def admin_get_all_requests(current_user): """Gets all requests""" requests = admin_get_all(current_user['id']) return jsonify(requests),200
49,546
def git_drv_info(url, version): """ Retrieve the necessary git info to create a nix expression using `fetchgit`. """ rev = [] if version != "master": rev = ["--rev", version] ret = run_cmd( ["nix-prefetch-git", "--no-deepClone", "--quiet", "--url", url,] + rev ) return...
49,547
def draw_bbox(image, bboxes, classes): """ [[[original function from Yun-Yuan: bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.]]] bboxes: [cls_id, probability, x_min, y_min, x_max, y_max] format coordinates.] """ num_classes = len(classes) image_h, image_w, _ = ima...
49,548
def testDBSQLite_CreateTable(tmpConf, tmpDir, caplog): """Check that the table create functions can handle exceptions.""" dbFile = os.path.join(tmpDir, "index.db") tmpConf.dbProvider = "sqlite" tmpConf.sqlitePath = tmpDir # Check that the db was created theDB = SQLiteDB() assert theDB.conf...
49,549
def is_admin(user): """ Test if a user has the admin group. This function is meant to be used by the user_passes_test decorator to control access to views. It uses the is_member function with a predefined list of groups. Parameters ---------- user : django.contrib.auth.models.User The ...
49,550
def testJSON(): """ Compressing structured text dictionaries is a test case where we expect compression to have a big impact. This requires a 'sample.json' file which is not included in the distribution. I recommend the following tool for generating sample JSON data: h...
49,551
def run_cli(context, run_args=None): """Run the process using pexpect.""" run_args = run_args or [] if context.conf.get('host', None): run_args.extend(('-h', context.conf['host'])) if context.conf.get('user', None): run_args.extend(('-u', context.conf['user'])) if context.conf.get('p...
49,552
def Grid(gridtype, *args, **kwargs): """Return an instance of the GridBase child class based on type. Parameters ---------- gridtype : string Type of grid; choices: ['cell-centered', 'x-face', 'y-face']. var_names : list of strings List of names for the variables to crea...
49,553
def read_tess_lightcurve(filename, flux_column="pdcsap_flux", quality_bitmask="default"): """Returns a `TessLightCurve`. Parameters ---------- filename : str Local path or remote url of a Kepler light curve FITS file. flux_column : 'pdcsap_f...
49,554
async def fix_issue(number: int, *, reason: str=None) -> dict: """Synchronously labels the specified issue as fixed, or closed. :param number: The issue number on GitHub to fix or consider, if a suggestion :param reason: The reason the issue was not considered. Note: this parameter only applies to ...
49,555
async def enter_option_value(message: types.Message, state: FSMContext): """Accepts and updates the value of SSH configuration option corresponding to the passed state.""" current_state = await state.get_state() option = current_state.split(':')[1] await update_option_value(option, message, state)
49,556
def _parse_schema(s: str) -> Schema: """Instantiate schema dict from a string.""" tables: List[Tuple[str, Fields]] = [] seen: Set[str] = set() current_table = '' current_fields: List[Field] = [] lines = list(reversed(s.splitlines())) # to pop() in right order while lines: line = lin...
49,557
def mom2(data, axis=0): """ Intensity-weighted coordinate dispersion (function version). Pixel units. """ shp = list(data.shape) n = shp.pop(axis) x = np.zeros(shp) x2 = np.zeros(shp) w = np.zeros(shp) # build up slice-by-slice, to avoid big temporary cubes for loc in range(n)...
49,558
def get_rdf_bin_labels(bin_distances, cutoff): """ Common function for getting bin labels given the distances at which each bin begins and the ending cutoff. Args: bin_distances (np.ndarray): The distances at which each bin begins. cutoff (float): The final cutoff value. Returns: ...
49,559
def tangent_point(circle, circle_radius, point, angle_sign=1): """Circle tangent passing through point, angle sign + if clockwise else - """ circle2d, point2d = a2(circle), a2(point) circle_distance = dist2d(circle2d, point2d) + 1e-9 relative_angle = math.acos(Range(circle_radius / circle_distance, 1...
49,560
def range_projection(current_vertex, fov_up=3.0, fov_down=-25.0, proj_H=64, proj_W=900, max_range=50): """ Project a pointcloud into a spherical projection, range image. Args: current_vertex: raw point clouds Returns: proj_range: projected range image with depth, each pixel contains...
49,561
def _get_blobs(im, rois, mask=False): """Convert an image and RoIs within that image into network inputs.""" blobs = {'data' : None, 'rois' : None} blobs['data'], im_scale_factors = _get_image_blob(im) if not cfg.TEST.HAS_RPN or mask: blobs['rois'] = _get_rois_blob(rois, im_scale_factors) re...
49,562
def urls() -> List[str]: """ Returns all URLs contained in the pasteboard as strings. """ urls = general_pasteboard().URLs str_urls = [] if urls is not None: for url in urls: str_urls.append(str(url.absoluteString)) return str_urls
49,563
def eager_no_dists(cls, *args): """ This interpretation is like eager, except it skips special distribution patterns. This is necessary because we want to convert distribution expressions to normal form in some tests, but do not want to trigger eager patterns that rewrite some distributions (e.g. N...
49,564
def _ParseException(log): """Searches a log for a stack trace and returns the exception string. This function supports both default Python-style stacks and Telemetry-style stacks. It returns the first stack trace found in the log - sometimes a bug leads to a cascade of failures, so the first one is usually the...
49,565
def euclid_dist( arr1, arr2, unsigned=True): """ Calculate the element-wise correlation euclidean distance. This is the distance D between the identity line and the point of coordinates given by intensity: \\[D = abs(A2 - A1) / sqrt(2)\\] Args: arr1 (ndarray...
49,566
def compute_redshift_path_per_line(Wobs, wa, fl,er,sl=3.,R=20000,FWHM=10,wa0=1215.67,fl_th=0,zmin=None,zmax=None): """Compute the total redshift path for a given line with Wobs (could be a np.array), in a given spectrum fl (with error er).""" #define N, number of lines try: N = len(Wobs) ...
49,567
def guard(clusters): """ Split Clusters containing conditional expressions into separate Clusters. """ processed = [] for c in clusters: free = [] for e in c.exprs: if e.conditionals: # Expressions that need no guarding are kept in a separate Cluster ...
49,568
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Hello World from a config entry.""" # Store an instance of the "connecting" class that does the work of speaking # with your actual devices. hass.data.setdefault(DOMAIN, {})[entry.entry_id] = hub.Hub(hass, entry.data...
49,569
def shut_down(sock, how=socket.SHUT_RDWR): """Shut down the given socket.""" sock.shutdown(how)
49,570
def display_energies(energies, x0, x): """ Display the bilinear and Dirichlet energies. Inputs: energies - an Energies object for the coefficents of the quadratic energies. x0 - original vector x - solution vector """ # LSQ = QuadEnergy(2 * energies.LSQ.Q, energi...
49,571
def make_viewnames(pathnames, tfm_unique_only=False, order_func=default_viewname_order): """ Make all view names from the paths given as arguments. Parameters ---------- pathnames : list[str] tfm_unique_only : bool Default: False. If True, returns only the views that give *different* im...
49,572
def installed_packages(): """Returns a list of all installed packages Returns: :obj:`list` of :obj:`str`: List of all the currently installed packages """ _check_for_old_versions() return [x["name"] for x, _ in _iter_packages()]
49,573
def get_hponeview_client(args): """Generate an instance of the HPE OneView client. :returns: an instance of the HPE OneView client. :raises: OneViewConnectionError if try a secure connection without a CA certificate file path in Ironic OneView CLI configuration file. """ ssl_certificat...
49,574
def random_binary_tree(depth, p=.8): """ Constructs a random binary tree with given maximal depth and probability p of bifurcating. Parameters: depth: The maximum depth the tree can have (might not be reached due to probabilistic nature of algorithm) p: Probability that any node bi...
49,575
def test_smartspim_stitching_twochannels_works(test_client, smartspim_multichannel_stitched_request): """ Test that stitching task runs and db is updated """ with test_client.session_transaction() as sess: sess['user'] = 'lightserv-test' # Make sure lightsheet table now has both of our channels stitching_conten...
49,576
def make_uid_setter(**kwargs): """ Erzeuge eine Funktion, die die UID einer bekannten Ressource setzt; es wird nichts neu erzeugt """ if 'catalog' not in kwargs: context = kwargs.pop('context') catalog = getToolByName(context, 'portal_catalog') else: catalog = kwargs.pop(...
49,577
def build_action_group(obj, name=None): """ Build actions and a Gtk.ActionGroup for each Action instance found in obj() (that's why Action is a class ;) ). This function requires GTK+. >>> class A: ... @action(name='bar') ... def bar(self): print('Say bar') ... @toggle_action(na...
49,578
def afftdn(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#afftdn""" return filter(stream, afftdn.__name__, *args, **kwargs)
49,579
def sh2vap(q, p): """Specific Humidity to Water vapor pressure formula derived from ratio of humid air vs. total air Parameters ---------- q specific humidity [kg/kg] p total air pressure [Pa] Returns ------- water vapor pressure [Pa] """ c = eps() # Rd / Rv = ...
49,580
def triplets(a, b, c): """ Time: O(n) Space: O(n lg n), for sorting - n = a_len + b_len + c_len """ a = list(sorted(set(a))) b = list(sorted(set(b))) c = list(sorted(set(c))) ai = bi = ci = 0 a_len, c_len = len(a), len(c) answer = 0 while bi < len(b): while ...
49,581
def flatten_dict(d, parent_key='', joinchar='.'): """ Returns a flat dictionary from nested dictionaries the flatten structure will be identified by longer keys coding the tree. A value will be identified by the joined list of node names e.g.: {'a': {'b': 0, 'c': {'r': 10, ...
49,582
def face_vertices(vertices, faces): """ :param vertices: [batch size, number of vertices, 3] :param faces: [batch size, number of faces, 3] :return: [batch size, number of faces, 3, 3] """ assert (vertices.ndimension() == 3) assert (faces.ndimension() == 3) assert (vertices.shape[0] == ...
49,583
def test_markdown_page(client: Client) -> None: """Test markdown rendering.""" response = client.get(reverse("resources")) assert response.status_code == 200 assert "<h2>For Organisers</h2>" in response.content.decode()
49,584
def get_results(tickers=None): """ Given a list of stock tickers, this print formatted results to the terminal. """ if tickers == ['']: return stocks = QuarterlyReport.get_stocks(tickers) if verbose: string_header = '{:<10}'.format('Ticker') + '{:<17}'.format('Earnings Date') ...
49,585
def reverse_mapper_or_checker(container): """Callable to REVERSE map the function parameter values. Parameters ---------- container : dict-like object Raises ------ TypeError If the unit argument cannot be interpreted. Example ------- >>> conv = reverse_mapper_or_check...
49,586
def export_detected_regions( image_path, image, regions, output_dir: str = "output/", rectify: bool = False ): """ Arguments: image_path: path to original image image: full/original image regions: list of bboxes or polys output_dir: folder to be exported rectify: rect...
49,587
def smallest_boundary_value(fun, discretization): """Determine the smallest value of a function on its boundary. Parameters ---------- fun : callable A tensorflow function that we want to evaluate. discretization : instance of `GridWorld` The discretization. If None, then the functi...
49,588
def test_http_error_exception_handling(): """Test the basic behaviour of HTTPError class.""" try: raise HTTPError(404, "Not found") except HTTPError as e: print(e)
49,589
def BufferAnthroFeatures(filename, Parameter_Values): """ Buffer line and point type anthropogenic features :param filename: the anthro feature to be buffered :param Parameter_Values: the Parameter Values table :return: None """ # Join Buffer field from Parameter_Values table based on Subtyp...
49,590
def read_ids(idtype, idfile): """Read ids from idfile of type idtype.""" print "Using %s file: %s" % (idtype, idfile) ids = read_dot_name(idfile) print "%d %s read in." % (len(ids), idtype) return ids
49,591
def unconfigure_bgp_neighbor_remote_as( device, bgp_as, neighbor_as, neighbor_address, address_family=None, vrf=None ): """ unonfigure destination in vrf Args: device ('obj'): Device object bgp_as ('str'): Router bgp neighbor_as ('str'): Destination neighb...
49,592
def get_pseudo_class_checker(psuedo_class): """ Takes a psuedo_class, like "first-child" or "last-child" and returns a function that will check if the element satisfies that psuedo class """ return { 'first-child': lambda el: is_first_content_node(getattr(el, 'previousSibling', None)), ...
49,593
def gammaincinv(y, s): """ Calculates the inverse of the regularized lower incomplete gamma function, i.e.:: \gamma(x; s) = 1/\Gamma(s)\int_0^x t^{s-1}e^{-t} \mathrm{d}t NOTE: Inspired by: https://github.com/minrk/scipy-1/blob/master/scipy/special/c_misc/gammaincinv.c Parameters ...
49,594
def multiprocess_tracking(func, iter, args=(), kwargs={}, tqdm_kwargs={}, single_process=False, max_workers=None, expand_args=False): """Using ProcessPoolExecutor to run *func* on multiple processes Arguments: func {function} -- Function to be executed iter {iterable} -- Call function on ea...
49,595
def testpathmv_relpathinputs(): """ Verify that when relative paths are inputted into pathmv, it performs correctly """ testpathmv_setup() pathmv_main([os.path.relpath(str(__projectdir__ / Path('testpathmv/file1.txt'))), os.path.relpath(str(__projectdir__ / Path('testpathmv/file2.txt')))], [os....
49,596
def run_lightgbm_experiment(X_train, y_train, X_test, y_test): """Run training evaluation and save lightgbm model""" mlflow.lightgbm.autolog() model = lgb.LGBMClassifier(objective='binary', tree_learner='data', verbosity=-1, ...
49,597
def divide_with_zero_divisor(dividend, divisor): """Returns 0 when divisor is zero. Args: dividend: Numpy array or scalar. divisor: Numpy array or scalar. Returns: Scalar if both inputs are scalar, numpy array otherwise. """ # NOTE(leeley): The out argument should have the broadcasting shape of ...
49,598
def str_strip(x): """ Apply .strip() string method to a value. """ if isnull(x): return x else: return str(x).strip()
49,599