content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def check_playlist_url(playlist_url): """Check if a playlist URL is well-formated. Parameters ---------- playlist_url : str URL to a YouTube playlist. Returns ------- str If the URL is well-formated, return the playlist ID. Else return `None`. """ match...
b14808e3dc25fcb7f91e9b66ec5f31ae869c6ae5
16,500
import multiprocessing import asyncio def test_PipeJsonRpcSendAsync_2(method, params, result, notification): """ Test of basic functionality. Here we don't test for timeout case (it raises an exception). """ value_nonlocal = None def method_handler1(): nonlocal value_nonlocal valu...
3311c1be5013eae986b5c8e358ef08eafff6420c
16,501
def f(t, T): """ returns -1, 0, or 1 based on relationship between t and T throws IndexError """ if(t > 0 and t < float(T/2)): return 1 elif(t == float(T/2)): return 0 elif(t > float(T/2) and t < T): return -1 raise IndexError("Out of function domain")
f2365094d41d2a151322ad640dcf4b290dd1de79
16,502
import http import json def auth0_token(): """ Token for Auth0 API """ auth = settings["auth0"] conn = http.client.HTTPSConnection(auth['domain']) payload = '{' + f"\"client_id\":\"{auth['client']}\"," \ f"\"client_secret\":\"{auth['client-secret']}\"," \ ...
ba27798d4af79999f1c37d5b356a54cd427a0681
16,503
def get_ami(region, instance_type): """Returns the appropriate AMI to use for a given region + instance type HVM is always used except for instance types which cannot use it. Based on matrix here: http://aws.amazon.com/amazon-linux-ami/instance-type-matrix/ .. note:: :func:`populate_ami_...
7ea60dbda0dabb05d9f7509ddb4c567560d681eb
16,504
def convert_config(cfg): """ Convert some configuration values to different values Args: cfg (dict): dict of sub-dicts, each sub-dict containing configuration keys and values pertinent to a process or algorithm Returns: dict: configuration dict with some items converted to diff...
f84ae8f5b90f364eb378b48071c7ea4a99370076
16,505
def _signals_exist(names): """ Return true if all of the given signals exist in this version of flask. """ return all(getattr(signals, n, False) for n in names)
3f62e5a6309d792843947c3aa6f5ad687b6debf5
16,506
def login(): """Route for logging the user in.""" try: if request.method == 'POST': return do_the_login() if session.get('logged_in'): return redirect(url_for('home')) return render_template('login.html') except Exception as e: abort(500, {'message': s...
1f610bcfd450de5de576eef797ed9d26f726ec72
16,507
import os def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for...
3dc0418a4b1674b7db34fe1893f66e55d44ea5bc
16,508
from typing import List def __screen_info_to_dict(): """ 筛查 :return: """ screen_dict: {str: List[GitLogObject]} = {} for info in git.get_all_commit_info(): if not authors.__contains__(info.name): continue if not info.check_today_time(): continue ...
6fb5519ab746b8918f18ec0c0a1769b5dca3558c
16,509
from typing import Type from typing import Optional def bind_prop_arr( prop_name: str, elem_type: Type[Variable], doc: Optional[str] = None, doc_add_type=True, ) -> property: """Convenience wrapper around bind_prop for array properties :meta private: """ if doc is None: doc = ...
f8e610011f096013c3976ee22f43eb58472c0513
16,510
from typing import Dict from typing import Any import json def generate_profile_yaml_file(destination_type: DestinationType, test_root_dir: str) -> Dict[str, Any]: """ Each destination requires different settings to connect to. This step generates the adequate profiles.yml as described here: https://docs....
f66b8df469b00d8aa11e6aba7d6efb5c2af4e21f
16,511
def get_foreign_trips(db_connection): """ Gets the time series data for all Foreign visitors from the database Args: db_connection (Psycopg.connection): The database connection Returns: Pandas.DataFrame: The time series data for each unique Foreign visitor. It...
bd5f0d308681286c615d60b0bf2fcb88bfd2a806
16,512
from typing import List def get_diagonal_sums(square: Square) -> List[int]: """ Returns a list of the sum of each diagonal. """ topleft = 0 bottomleft = 0 # Seems like this could be more compact i = 0 for row in square.rows: topleft += row[i] i += 1 i = 0 for col in square.columns: bottoml...
37a5e167b3170feece19b963c21eae1359df14ec
16,513
import base64 def int_to_base64(i: int) -> str: """ Returns a 12 char length representation of i in base64 """ return base64.b64encode(i.to_bytes(8, 'big'))
5bd7bb032926a8f429d766632c2ef2af9ee01edc
16,514
def payment_provider(provider_base_config): """When it doesn't matter if request is contained within provider the fixture can still be used""" return TurkuPaymentProviderV3(config=provider_base_config)
d6439a5ef097350682a2e17ccc41aeba1310a78a
16,515
import re def gradle_extract_data(build_gradle): """ Extract the project name and dependencies from a build.gradle file. :param Path build_gradle: The path of the build.gradle file :rtype: dict """ # Content for dependencies content_build_gradle = extract_content(build_gradle) match =...
dd802b8fedb682493a1978ae6cd60be9706580ff
16,516
from typing import Sequence import torch def stack_batch_img( img_tensors: Sequence[torch.Tensor], divisible: int = 0, pad_value: float = 0 ) -> torch.Tensor: """ Args :param img_tensors (Sequence[torch.Tensor]): :param divisible (int): :param pad_value (float): value to pad :return: ...
9952965a89688d742a3342804062cb8051f47f54
16,517
from evo.core import lie_algebra as lie def convert_rel_traj_to_abs_traj(traj): """ Converts a relative pose trajectory to an absolute-pose trajectory. The incoming trajectory is processed elemente-wise. Poses at each timestamp are appended to the absolute pose from the previous timestamp. ...
57e4972f5bc4ea67bf62b88ea87fc5df8dda0d7c
16,518
def remove(handle): """The remove action allows users to remove a roommate.""" user_id = session['user'] roommate = model.roommate.get_roommate(user_id, handle) # Check if roommate exists if not roommate: return abort(404) if request.method == 'POST': model.roommate.delete_roo...
b1a279989d3cb463d54c8559352f2ae67f198b40
16,519
def maxsubarray(list): """ Find a maximum subarray following this idea: Knowing a maximum subarray of list[0..j] find a maximum subarray of list[0..j+1] which is either (I) the maximum subarray of list[0..j] (II) or is a maximum subarray list[i..j+1] for some 0 <= i <= j ...
a991ca09c0594b0d47eb4dd8be44d093d593cd36
16,520
def get_merged_threadlocal(bound_logger: BindableLogger) -> Context: """ Return a copy of the current thread-local context merged with the context from *bound_logger*. .. versionadded:: 21.2.0 """ ctx = _get_context().copy() ctx.update(structlog.get_context(bound_logger)) return ctx
03c2689fd71542c7c007512fb4c2bf76a841a7bc
16,521
def sort_cipher_suites(cipher_suites, ordering): """Sorts the given list of CipherSuite instances in a specific order.""" if ordering == 'asc': return cipher_suites.order_by('name') elif ordering == 'desc': return cipher_suites.order_by('-name') else: return cipher_suites
5a554ba1e2e4d82f53f29c5a1c2f4d311f538889
16,522
def make_1D_distributions(lims, n_points, all_shifts, all_errs, norm=None, max_shifts=None, seed=None): """ Generate 1D distributions of chemical shifts from arrays of shifts and errors of each distribution Inputs: - lims Limits of the distributions - n_points Number o...
87c48b80dc395b4423b88fcbb3307dd53655333e
16,523
def fill_column_values(df, icol=0): """ Fills empty values in the targeted column with the value above it. Parameters ---------- df: pandas.DataFrame icol: int Returns ------- pandas.DataFrame """ v = df.iloc[:,icol].fillna('').values.tolist() vnew = fill_gaps(v) d...
158939f6436a4c9b5a13a18567ee6061e71df51c
16,524
import torch def reward(static, tour_indices): """ Euclidean distance between all cities / nodes given by tour_indices """ # Convert the indices back into a tour idx = tour_indices.unsqueeze(1).expand(-1, static.size(1), -1) tour = torch.gather(static.data, 2, idx).permute(0, 2, 1) # Ens...
f7197bcfb3699cafa4df3c1430b4f9ee1bf53242
16,525
def valid_review_queue_name(request): """ Given a name for a queue, validates the correctness for our review system :param request: :return: """ queue = request.matchdict.get('queue') if queue in all_queues: request.validated['queue'] = queue return True else: _t...
fc6ef2fb728b18ce84669736f0e4ec1f020ea2bf
16,526
import subprocess def is_valid_cluster_dir(path): """Checks whether a given path is a valid postgres cluster Args: pg_ctl_exe - str, path to pg_ctl executable path - str, path to directory Returns: bool, whether or not a directory is a valid postgres cluster """ pg_contro...
f34a9569af6a8e83d3f1f7b37e0c266f24c86cca
16,527
def get_best_straight(possible_straights, hand): """ get list of indices of hands that make the strongest straight if no one makes a straight, return empty list :param possible_straights: ({tuple(str): int}) map tuple of connecting cards --> best straight value they make :param hand: (set(s...
f2a470ef3033cac27cb406702daead42d59683aa
16,528
from django.shortcuts import render_to_response, RequestContext def stats(request): """ Display statistics for the web site """ views = list(View.objects.all().only('internal_url', 'browser')) urls = {} mob_vs_desk = { 'desktop': 0, 'mobile': 0 } for view in views: if is_mobi...
3b63250e6ce3c9ddd09ec8d19c9961b22bfab62a
16,529
def build_argparser(): """ Builds argument parser. :return argparse.ArgumentParser """ banner = "%(prog)s - generate a static file representation of a PEP data repository." additional_description = "\n..." parser = _VersionInHelpParser( description=banner, epilog=a...
f33679c82a1499db83caf3473b0e5403ebfa52fe
16,530
def abc19(): """Solution to exercise C-1.19. Demonstrate how to use Python’s list comprehension syntax to produce the list [ a , b , c , ..., z ], but without having to type all 26 such characters literally. """ a_idx = 97 return [chr(a_idx + x) for x in range(26)]
c9bb948ad57ddbc138dfbc0c481fabb45de620ba
16,531
import os def setForceFieldVersion(version): """ Set the forcefield parameters using a version number (string) and return a handle to the object holding them current version are: '4.2': emulating AutoDock4.2 'default': future AutoDock5 Parameters <- setForceFieldVersion(version) ...
a5349bda04f919c6858c4653400f98fe57092a9e
16,532
def filter_words(data: TD_Data_Dictionary): """This function removes all instances of Key.ctrl from the list of keys and any repeats because of Press and Realese events""" # NOTE: We may just want to remove all instances of Key.ctrl from the list and anything that follows that keys = data.get_letters() ...
fb34e1758c83af0e30b5ae807a3f852ab7e3be29
16,533
from typing import Dict def check_url_secure( docker_ip: str, public_port: int, *, auth_header: Dict[str, str], ssl_context: SSLContext, ) -> bool: """ Secure form of lovey/pytest/docker/compose.py::check_url() that checks when the secure docker registry service is operational. Ar...
ebdc8f4d175f3be70000022424382f71d9fd73b5
16,534
def ResNet101(pretrained=False, use_ssld=False, **kwargs): """ ResNet101 Args: pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. If str, means the path of the pretrained model. use_ssld: bool=False. Whether using distillation pretrain...
0277c59f9b60d5c6127fb1021eb71b10691bd0f8
16,535
def LineTextInCurrentBuffer( line_number ): """ Returns the text on the 1-indexed line (NOT 0-indexed) """ return vim.current.buffer[ line_number - 1 ]
8c3b51a48e25e8955a00d89619da9e191612861a
16,536
def imported_instrumentor(library): """ Convert a library name to that of the correlated auto-instrumentor in the libraries package. """ instrumentor_lib = "signalfx_tracing.libraries.{}_".format(library) return get_module(instrumentor_lib)
db26277b23f989d8d5323c7c6bde0905b1e2f5ef
16,537
import time import calendar def parse_cache_entry_into_seconds(isoTime): """ Returns the number of seconds from the UNIX epoch. See :py:attribute:`synapseclient.utils.ISO_FORMAT` for the parameter's expected format. """ # Note: The `strptime() method is not thread-safe (http://bugs.python.org...
7492b828b331d54f3bf90056d9010e2dbbd86d06
16,538
from datetime import datetime def parse_runtime(log_file): """ Parse the job run-time from a log-file """ with open(log_file, 'r') as f: for line in f: l0 = line.rstrip("\n") break l1 = tail(log_file, 1)[0].rstrip("\n") l0 = l0.split()[:2] l1 = l1.split()[:2] ...
75a5a80409918779173eb1e80d6b3f95abf242cb
16,539
def calculateEMA(coin_pair, period, unit): """ Returns the Exponential Moving Average for a coin pair """ closing_prices = getClosingPrices(coin_pair, period, unit) previous_EMA = calculateSMA(coin_pair, period, unit) constant = (2 / (period + 1)) current_EMA = (closing_prices[-1] * (2 / (1...
ec884f89c2e8e64ada4384767251d6722c7b63c8
16,540
def euler_method(r0, N): """ euler_method function description: This method computes the vector r(t)'s using Euler's method. Args: r0 - the initial r-value N - the number of steps in each period """ delta_t = (2*np.pi)/N # delta t r = np.zeros((5*N, 2)) # 5Nx...
6ac3deae5cdb5ce84fa19433b55de80bf04ddf47
16,541
def main_menu(found_exists): """prints main menu and asks for user input returns task that is chosen by user input""" show_main_menu(found_exists) inp = input(">> ") if inp == "1": return "update" elif inp == "2": return "show_all" elif inp == "3": return "s...
61d0bda6a1ddf8bf70a79ff6e7488601d781c5fc
16,542
def fromPsl(psl, qCdsRange=None, inclUnaln=False, projectCds=False, contained=False): """generate a PairAlign from a PSL. cdsRange is None or a tuple. In inclUnaln is True, then include Block objects for unaligned regions""" qCds = _getCds(qCdsRange, psl.qStrand, psl.qSize) qSeq = _mkPslSeq(psl.qName, p...
f1da225d53f36abf5d10589077de934f13c1ca2a
16,543
def drawMatrix(ax, mat, **kwargs): """Draw a view to a matrix into the axe." TODO ---- * pg.core.BlockMatrix Parameters ---------- ax : mpl axis instance, optional Axis instance where the matrix will be plotted. mat: obj obj can be so far: * pg.core.*Matrix...
3ad4988b90909d803c5e730a50c0e09bd9c554ce
16,544
from typing import Optional def get_graph(identifier: str, *, rows: Optional[int] = None) -> pybel.BELGraph: """Get the graph surrounding a given GO term and its descendants.""" graph = pybel.BELGraph() enrich_graph(graph, identifier, rows=rows) return graph
fc004ebd3cdfa70edd01b611987dfd48306ceb80
16,545
import logging def parse_custom_variant(self, cfg): """Parse custom variant definition from a users input returning a variant dict an example of user defined variant configuration 1) integrated: cpu=2 ram=4 max_nics=6 chassis=sr-1 slot=A card=cpm-1 slot=1 mda/1=me6-100gb-qsfp28 2) distributed: cp: cp...
f79874b6512a3874f2c88f7473c34dcf40b5fc65
16,546
def cube_recenter_via_speckles(cube_sci, cube_ref=None, alignment_iter=5, gammaval=1, min_spat_freq=0.5, max_spat_freq=3, fwhm=4, debug=False, recenter_median=False, fit_type='gaus', negative=True, crop=True, ...
aaf113bc0c701993c492fbfeb855aeb4c0b73c8d
16,547
def root_histogram_shape(root_hist, use_matrix_indexing=True): """ Return a tuple corresponding to the shape of the histogram. If use_matrix_indexing is true, the tuple is in 'reversed' zyx order. Matrix-order is the layout used in the internal buffer of the root histogram - keep True if reshaping t...
8df83a84f0a3b12bab248949042cd2df5df6f53e
16,548
import io import json import sys def json_file_to_dict(fname): """ Read a JSON file and return its Python representation, transforming all the strings from Unicode to ASCII. The order of keys in the JSON file is preserved. Positional arguments: fname - the name of the file to parse """ tr...
c2542597d0785ed495ae217f1300df941156763a
16,549
from typing import Union def get_weather_sensor_by( weather_sensor_type_name: str, latitude: float = 0, longitude: float = 0 ) -> Union[WeatherSensor, ResponseTuple]: """ Search a weather sensor by type and location. Can create a weather sensor if needed (depends on API mode) and then inform the r...
b4feb0a75709d1bf27378df6d90420c74e36646c
16,550
import six def _npy_loads(data): """ Deserializes npy-formatted bytes into a numpy array """ logger.info("Inside _npy_loads fn") stream = six.BytesIO(data) return np.load(stream,allow_pickle=True)
5e9ee0a0d41403af0a8e1ed41f6d15a677d82c44
16,551
import dateutil def parse_string(string): """Parse the string to a datetime object. :param str string: The string to parse :rtype: `datetime.datetime` :raises: :exc:`InvalidDateFormat` when date format is invalid """ try: # Try to parse string as a date value = dateutil.parser...
6db2edad31f1febced496c92bfb2d7d76761850a
16,552
def get_elfs_oriented(atoms, density, basis, mode, view = serial_view()): """ Outdated, use get_elfs() with "mode='elf'/'nn'" instead. Like get_elfs, but returns real, oriented elfs mode = {'elf': Use the ElF algorithm to orient fingerprint, 'nn': Use nearest neighbor algorithm} """ ...
36b5abe66e9054ab49a25eca753d4a61148a1b1c
16,553
import os import json def _get_corpora_json_contents(corpora_file): """ Get the contents of corpora.json, or an empty dict """ exists = os.path.isfile(corpora_file) if not exists: print("Corpora file not found at {}!".format(corpora_file)) return dict() with open(corpora_file, ...
d2a0dcf8bbbca573121237190b96c8d372d027b4
16,554
def error_logger(param=None): """ Function to get an error logger, object of Logger class. @param param : Custom parameter that can be passed to the logger. @return: custom logger """ logger = Logger('ERROR_LOGGER', param) return logger.get_logger()
ca6449c2e63ebdccbd7bd3993dc1d11375e66e29
16,555
import multiprocessing import os def _run_make_examples(pipeline_args): """Runs the make_examples job.""" def get_region_paths(regions): return filter(_is_valid_gcs_path, regions or []) def get_region_literals(regions): return [ region for region in regions or [] if not _is_valid_gcs_path(regi...
f4481ba095242c3b6ef2b465c96a32082bf5b912
16,556
def get_iou(mask, label): """ :param mask: predicted mask with 0 for background and 1 for object :param label: label :return: iou """ # mask = mask.numpy() # label = labels.numpy() size = mask.shape mask = mask.flatten() label = label.flatten() m = mask + label i = len(np...
9322d0184a3e28bdd1d5bf3214b7fbe8936d6a21
16,557
from typing import List from typing import Set from typing import Any def mean_jaccard_distance(sets: List[Set[Any]]) -> float: """ Compute the mean Jaccard distance for sets A_1, \dots A_n: d = \frac{1}{n} \sum_{i=1}^{n-1} \sum_{j=i+1}^n (1 - J(A_i, A_j)) where J(A, B) is the Jaccard index betwee...
efbfce8092e2e3a9b5b076c46a636dfa17e2d266
16,558
def nx_find_connected(graph, start_set, end_set, cutoff=np.inf): """Return the nodes in end_set connected to start_set.""" reachable = [] for end in end_set: if nx_is_reachable(graph, end, start_set): reachable.append(end) if len(reachable) >= cutoff: break ...
a3feb8a172bb610fa4416c6f4a4c0558540d2190
16,559
def svn_client_proplist(*args): """ svn_client_proplist(char target, svn_opt_revision_t revision, svn_boolean_t recurse, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return _client.svn_client_proplist(*args)
1cc82161292df7b9ba284397a0dcd55da9d0d7c1
16,560
def dev_transform(signal, input_path='../data/', is_denoised=True): """ normalization function that transforms each fature based on the scaling of the trainning set. This transformation should be done on test set(developmental set), or any new input for a trained neural network. Due to existence of ...
ce6dfe780bb724ae8036502d2b1d1828fce675dc
16,561
def moveTo(self, parent): """Move this element to new parent, as last child""" self.getParent().removeChild(self) parent.addChild(self) return self
40caa9681346db9a6cfb5c95fdb761a9f98e607a
16,562
from datetime import datetime def coerce_to_end_of_day_datetime(value): """ gets the end of day datetime equivalent of given date object. if the value is not a date, it returns the same input. :param date value: value to be coerced. :rtype: datetime | object """ if not isinstance(value...
374e7decf543e5fb40fb7714d4472cf4cfa48cb1
16,563
def greybody(nu, temperature, beta, A=1.0, logscale=0.0, units='cgs', frequency_units='Hz', kappa0=4.0, nu0=3000e9, normalize=max): """ Same as modified blackbody... not sure why I have it at all, though the normalization constants are different. """ h,k,c = unitdict[units]...
89cca39acf5659e8ab7b403c5747b19c119d0e51
16,564
import copy def GCLarsen_v0(WF, WS, WD, TI, pars=[0.435449861, 0.797853685, -0.124807893, 0.136821858, 15.6298, 1.0]): """Computes the WindFarm flow and Power using GCLarsen [Larsen, 2009, A simple Stationary...] Inputs ---------- WF: WindFarm Windfarm instance WS: list Ro...
a075074b0cee9b36fdf3411804ff4eff2f5fe63b
16,565
def guess_table_address(*args): """ guess_table_address(insn) -> ea_t Guess the jump table address (ibm pc specific) @param insn (C++: const insn_t &) """ return _ida_ua.guess_table_address(*args)
073773e33b5cf4c59f3a3c892d5a53320c2c1f4b
16,566
import logging import os def xmind_to_excel_file(xmind_file): """Convert XMind file to a excel csv file""" xmind_file = get_absolute_path(xmind_file) logging.info('Start converting XMind file(%s) to excel file...', xmind_file) testcases = get_xmind_testcase_list(xmind_file) fileheader = ["所属模块", ...
779f540b56043ee60ea0ef28a89cea49d7cda51c
16,567
def get_elbs(account, region): """ Get elastic load balancers """ elb_data = [] aws_accounts = AwsAccounts() if not account: session = boto3.session.Session(region_name=region) for account_rec in aws_accounts.all(): elb_data.extend( query_elbs_for_account(acc...
32b059c7929b0adae3df7b8393fd062f5a281cc3
16,568
import io import os def nyul_normalize(img_dir, mask_dir=None, output_dir=None, standard_hist=None, write_to_disk=True): """ Use Nyul and Udupa method ([1,2]) to normalize the intensities of a set of MR images Args: img_dir (str): directory containing MR images mask_dir (str): directory c...
9774725919ed43735060047855ad67e55e227936
16,569
def likelihood_params(ll_mode, mode, behav_tuple, num_induc, inner_dims, inv_link, tbin, jitter, J, cutoff, neurons, mapping_net, C): """ Create the likelihood object. """ if mode is not None: kernel_tuples_, ind_list = kernel_used(mode, behav_tuple, num_induc, inner_dims)...
2e817c4fdfdd9a65d138f61166ef8fbb3154460b
16,570
def is_num_idx(k): """This key corresponds to """ return k.endswith("_x") and (k.startswith("tap_x") or k.startswith("sig"))
bd4ed2c9c4a24ae423ec6c738d99b31ace6ec267
16,571
def convert_to_boolarr(int_arr, cluster_id): """ :param int_arr: array of integers which relate to no, one or multiple clusters cluster_id: 0=Pleiades, 1=Meingast 1, 2=Hyades, 3=Alpha Per, 4=Coma Ber """ return np.array((np.floor(int_arr/2**cluster_id) % 2), dtype=bool)
c769ca07ea32a9e0ab0d230cd3574e5b71434de4
16,572
def serialize(root): # """Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Des...
a2bec43b384302d5218e8c62c83bc069be3bcbd3
16,573
def ensure_daemon(f): """A decorator for running an integration test with and without the daemon enabled.""" def wrapper(self, *args, **kwargs): for enable_daemon in [False, True]: enable_daemon_str = str(enable_daemon) env = { "HERMETIC_ENV": "PANTS_PANTSD,PANTS...
d9005c48d489b8b5da1f9687b78d1f455aaf3d62
16,574
from adaptivefiltering.pdal import execute_pdal_pipeline from adaptivefiltering.pdal import PDALInMemoryDataSet import json def reproject_dataset(dataset, out_srs, in_srs=None): """Standalone function to reproject a given dataset with the option of forcing an input reference system :param out_srs: Th...
0380442a837f89bbf06d0d1b5e9917e7309876ad
16,575
def conditional(condition, decorator): """ Decorator for a conditionally applied decorator. Example: @conditional(get_config('use_cache'), ormcache) def fn(): pass """ if condition: return decorator else: return lambda fn: fn
7c17ad3aaacffd0008ec1cf66871ea6755f7869a
16,576
import statistics def variance(data, mu=None): """Compute variance over a list.""" if mu is None: mu = statistics.mean(data) return sum([(x - mu) ** 2 for x in data]) / len(data)
92f89d35c2ae5abf742b10ba838a381d6f74e92c
16,577
def make_note(outfile, headers, paragraphs, **kw): """Builds a pdf file named outfile based on headers and paragraphs, formatted according to parameters in kw. :param outfile: outfile name :param headers: <OrderedDict> of headers :param paragraphs: <OrderedDict> of paragraphs :param kw: keyword...
d9bc331167649210cf18e76bcff4099817c28458
16,578
import stat def output_file_exists(filename): """Check if a file exists and its size is > 0""" if not file_exists(filename): return False st = stat(filename) if st[stat_module.ST_SIZE] == 0: return False return True
ad2f3a7451feefd32fe98da7fc3bfca9852b080c
16,579
def IMF_N(m,a=.241367,b=.241367,c=.497056): """ returns number of stars with mass m """ # a,b,c = (.241367,.241367,.497056) # a=b=c=1/3.6631098624 if .1 <= m <= .3: res = c*( m**(-1.2) ) elif .3 < m <= 1.: res = b*( m**(-1.8) ) elif 1. < m <= 100.: # res = a*( m*...
4d120af2840a793468335cddd867f6d29940d415
16,580
def features_disable(partial_name, partial_name_field, force, **kwargs): """Disable a feature""" mode = "disable" params = {"mode": "force"} if force else None feature = _okta_get("features", partial_name, selector=_selector_field_find(partial_name_field, partial_name)) featu...
5477a43ad2f849669a6a209abfc835f0f4ee453a
16,581
def _get_images(): """Get the official AWS public AMIs created by Flambe that have tag 'Creator: flambe@asapp.com' ATTENTION: why not just search the tags? We need to make sure the AMIs we pick were created by the Flambe team. Because of tags values not being unique, anyone can create a public AMI ...
975596ff9eb1c9c0864cadb41edc2b1a4d009790
16,582
def ar_coefficient(x, param): """ This feature calculator fits the unconditional maximum likelihood of an autoregressive AR(k) process. The k parameter is the maximum lag of the process .. math:: X_{t}=\\varphi_0 +\\sum _{{i=1}}^{k}\\varphi_{i}X_{{t-i}}+\\varepsilon_{t} For the config...
a7a7171a44055d23457fd622d7e893f839f17bcf
16,583
import matplotlib.pyplot as plt import warnings def measure_ir( sweep_length=1.0, sweep_type="exponential", fs=48000, f_lo=0.0, f_hi=None, volume=0.9, pre_delay=0.0, post_delay=0.1, fade_in_out=0.0, dev_in=None, dev_out=None, channels_input_mapping=None, channels_ou...
33873a6c373daf0351db25872f02613dfaf635d4
16,584
from faker import Faker import random def address_factory(sqla): """Create a fake address.""" fake = Faker() # Use a generic one; others may not have all methods. addresslines = fake.address().splitlines() areas = sqla.query(Area).all() if not areas: create_multiple_areas(sqla, random.ran...
91f4558887025841d99ab6e65795111bbc804238
16,585
from pm4py.util import constants from pm4py.algo.discovery.dfg.adapters.pandas.df_statistics import get_dfg_graph from pm4py.statistics.start_activities.pandas import get as start_activities_module from pm4py.statistics.end_activities.pandas import get as end_activities_module from pm4py.algo.discovery.dfg.variants imp...
df8d9669c7e2a4cd3170cb1c5a1ecc7e7811649e
16,586
import warnings def mifs(data, target_variable, prev_variables_index, candidate_variable_index, **kwargs): """ This estimator computes the Mutual Information Feature Selection criterion. Parameters ---------- data : np.array matrix Matrix of data set. Columns are variables, rows are obser...
058ebdbb831d7fb52c4b5f053ba7bb8a1ce7f144
16,587
def input_thing(): """输入物品信息""" name_str, price_str, weight_str = input('请输入物品信息(名称 价格 重量):').split() return name_str, int(price_str), int(weight_str)
2a986e9479e8e4262cfab89f258af3536c5fefe3
16,588
def extract_features_mask(img, mask): """Computes law texture features for masked area of image.""" preprocessed_img = laws_texture.preprocess_image(img, size=15) law_images = laws_texture.filter_image(preprocessed_img, LAW_MASKS) law_energy = laws_texture.compute_energy(law_images, 10) energy_feat...
e184695fb2879cf9fd418e7110498717585b4878
16,589
def construct_grid_with_k_connectivity(n1,n2,k,figu = False): """Constructs directed grid graph with side lengths n1 and n2 and neighborhood connectivity k""" """For plotting the adjacency matrix give fig = true""" def feuclidhorz(u , v): return np.sqrt((u[0] - (v[0]-n2))**2+(u[1] - v[...
46b690f02c4f025719424582acecff43580543da
16,590
import os import urllib import tarfile def get_tar_file(tar_url, dump_dir=os.getcwd()): """ Downloads and unpacks compressed folder Parameters ---------- tar_url : string url of world wide web location dump_dir : string path to place the content Returns ------- tar_na...
2d07940dc107510436155a0ce5ff55299bf2f45e
16,591
import array def _optimal_shift(pos, r_pad, log): """ Find the shift for the periodic unit cube that would minimise the padding. """ npts, ndim = pos.shape # +1 whenever a region starts, -1 when it finishes start_end = empty(npts*2, dtype=np.int32) start_end[:npts] = 1 start_end[...
cac3c56307ea3d240ebe838ea4d26bb38c62dc3c
16,592
def ShowActStack(cmd_args=None): """ Routine to print out the stack of a specific thread. usage: showactstack <activation> """ if cmd_args == None or len(cmd_args) < 1: print "No arguments passed" print ShowAct.__doc__.strip() return False threadval = kern.GetValueFromA...
43b0eca326465fe9dc7b0207ba448d75da7e9889
16,593
import os from datetime import datetime import time def upload(dbx, fullname, dbx_folder, subfolder, name, overwrite=False): """Upload a file. Return the request response, or None in case of error. """ path = '/%s/%s/%s' % (dbx_folder, subfolder.replace(os.path.sep, '/'), name) while '//' in path:...
67271753093f8ccf15943301bcd37253e71a63c5
16,594
import json def load_request(possible_keys): """Given list of possible keys, return any matching post data""" pdata = request.json if pdata is None: pdata = json.loads(request.body.getvalue().decode('utf-8')) for k in possible_keys: if k not in pdata: pdata[k] = None # ...
b21c503fac56398be6745a10fb95889128c6e2b2
16,595
import random def get_random_tcp_start_pos(): """ reachability area: x = [-0.2; 0.4] y = [-0.28; -0.1] """ z_up = 0.6 tcp_x = round(random.uniform(-0.2, 0.4), 4) tcp_y = round(random.uniform(-0.28, -0.1), 4) start_tcp_pos = (tcp_x, tcp_y, z_up) # start_tcp_pos = (-0.2, -0.28, ...
adf87dec45bf5a81c321f94c93d45a67f0aeff0d
16,596
def CalculateChiv3p(mol): """ ################################################################# Calculation of valence molecular connectivity chi index for path order 3 ---->Chiv3 Usage: result=CalculateChiv3p(mol) Input: mol is a molecule object...
27405fce52540a0de9c4c1c2d5a35454681554fa
16,597
from typing import Tuple from typing import Optional def coerce(version: str) -> Tuple[Version, Optional[str]]: """ Convert an incomplete version string into a semver-compatible Version object * Tries to detect a "basic" version string (``major.minor.patch``). * If not enough components can be fou...
e712533aa05444ad47403fc10e7f2ec29b8132ec
16,598
def choose_wyckoff(wyckoffs, number): """ choose the wyckoff sites based on the current number of atoms rules 1, the newly added sites is equal/less than the required number. 2, prefer the sites with large multiplicity """ for wyckoff in wyckoffs: if len(wyckoff[0]) <= number: ...
14b276d8aa50e84f47d77f6796e193cc96ddd0a9
16,599