content
stringlengths
22
815k
id
int64
0
4.91M
def subspace(P, k, precision, mode): """ Computes isometries `V1` and `V2` respectively mapping into the column and null space of a rank-`k` projection matrix `P`. Args: P: The input matrix, expected to be a projector as described in the docstring. k: The rank of `P`. precision: The matmul p...
5,290,000
def combine_results(partitions, destination_dict): """ Combines partitioned results into single csv file :param partitions: list containing aws partition addresses :param destination_dict: folder where results are saved """ df = pd.DataFrame() for part_id in partitions: partial_df = ...
5,290,001
def dev_tree65432(runid, config, dir, dir2, dir3, dir4, dir5, dir6): """ recursive list the file structure of the working directory """ wd = os.path.abspath(get_wd(runid)) dir = os.path.abspath(_join(wd, dir, dir2, dir3, dir4, dir5, dir6)) assert dir.startswith(wd) return browse_response(dir...
5,290,002
def get_modis(tiles, save_path, months='', years=''): """The following script automatically retrieves monthly MODIS16 hdf file from the ntsg website. :param tiles: Tile number in format h##v##; based on grid from https://modis-land.gsfc.nasa.gov/MODLAND_grid.html :param save_path: name of output file name ...
5,290,003
def make_prediction(*, input_data: t.Union[pd.DataFrame, dict],) -> dict: """Make prediction using a saved model pipeline.""" # load trained model from local storage pipeline_file_name = f'{config.PIPELINE_SAVE_FILE}{_version}.pkl' _price_pipe = load_pipeline(file_name=pipeline_file_name) # valida...
5,290,004
def getdaydate(Occurrence: str = 'Second', DayOfWeek: str = 'Tuesday', Month: int = date.today().month, Year: int = date.today().year): """ Overivew: return the date for occurrence of a day of the week Description: function returns the date for a giving day of the week and occurrence of givi...
5,290,005
def equalsOp(template, rule, propertyList): """ Process EQUALS operators """ matches = [] for prop in propertyList: actualValue = getProperty(prop, rule) if actualValue.strip() != str(rule.value).strip(): path = prop['Path'] path = path + rule.prop.split('.') ...
5,290,006
def scaling_factor(context, ruler, rulerWidth): """ :type context: HackedContext """ rulerElement = context.driver.simple_find(ruler) rulerPixels = rulerElement.size['width'] scaleFactor = float(rulerPixels) / float(rulerWidth) return scaleFactor
5,290,007
def parse_args(args): """Parse command line parameters""" parser = argparse.ArgumentParser( description="Test utility for the command line", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "-v", "--version", action="version", ...
5,290,008
def to_bytes(string, encoding="utf-8"): """ Converts the given object to binary object, bytes (Py3) or str (Py2). :param string: The string like object to convert to bytes :type string: ``object`` :param encoding: The encoding to encode the string with. :type encoding: ``str`` :returns: The...
5,290,009
def makeVBClass(cls, init=None): """Returns the text of a VB class file wrapping the specified class If provided, then the init parameter is used as the initializer for the class so that you can link to the real Python object """ vb = [] # Build up as list and then .join it later # # Get t...
5,290,010
def new_compile_assets(data, compile_all=False): """ Process list of asset dictionaries from uframe; transform into (ooi-ui-services) list of asset dictionaries. """ info = False # Log missing vocab items when unable to create display name(s), etc. (default is True) new_data = [] ...
5,290,011
def quat_delta(dalpha): """ Form quaternion from small angle rotation vector dalpha """ half_norm = 0.5 * norm(dalpha) scalar = cos(half_norm) vector = sinc(half_norm) * 0.5 * dalpha dqw = scalar dqx, dqy, dqz = vector dq = np.array([dqw, dqx, dqy, dqz]) return dq
5,290,012
def sample_rate_limiter_client(): """Sample code to show how to implement rate limiter""" my_user_id = "your-user-id" quota_limit = 3 # 1. Create a rate limiter, and configure a quota limit for a user rate_limiter = RateLimiter() rate_limiter.configure_limit(user_id=my_user_id, rps=quota_limit)...
5,290,013
def cluster_main_stats(sparkdf, src="src", dst="dst", cluster_id_colname="cluster_id"): """calculate diameter / transitivity(GCC) / triangle clustering coefficient LCC / square clustering coeff Args: sparkdf: imput edgelist Spark DataFrame src: src column name dst: dst c...
5,290,014
def markers( image: Image, *, kernel_length: int = 5, blur_kernel_size: int = 9, threshold_value: float = 150, num_iterations: int = 4, debug: bool = False ) -> tp.List[np.ndarray]: """Return the contours of the black square markers.""" from .plots import plot # cv2.imwrite("foo...
5,290,015
def test_resources_exist_when_missing_bucket(mock_event): """ tests resources_exist function returns false when bucket is None """ instance_id = "i-12345678" bucket = None assert resources_exist(instance_id, bucket) is False
5,290,016
def clone_remote_db(conn): """ Copy remote data (JSON dump), download it locally and recreate a local SQLite database with those data. """ local = Context() db_name = settings.DATABASES['default']['NAME'] is_sqlite = 'sqlite' in settings.DATABASES['default']['ENGINE'] def exist_local_db...
5,290,017
def build_keras_model_front_v2(path_to_keras_model, idx_to_target_w = -1): """ idx_to_target_w = to which layer (default = -1 (the last one)) - 1 """ from tensorflow.keras.models import load_model, Model idx = 0 loaded_model = load_model(path_to_keras_model) front_layers = loaded_model.layers[:idx_to_target_w]...
5,290,018
def center_margin_bb(bb, img_bounds, margin=0.25): """create new bounding box with input margin""" bb_size = ([bb[0, 2] - bb[0, 0], bb[0, 3] - bb[0, 1]]) margins = (np.max(bb_size) * (1 + margin) - bb_size) / 2 bb_new = np.zeros_like(bb) bb_new[0, 0] = np.maximum(bb[0, 0] - margins[0], 0) bb_ne...
5,290,019
def multi_fidelity_optimize( vocs, evaluate_f, budget=1, processes=1, base_cost=1.0, **kwargs ): """ Multi-fidelity optimization using Bayesian optimization This optimization algorithm attempts to reduce the computational cost of optimizing a scalar function through the use of many low-cost approxi...
5,290,020
async def save(proxies, filename): """Save proxies to a file.""" with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break f.write('smtp://%s:%d\n' % (proxy.host, proxy.port))
5,290,021
def downloadDatabase(database_name, alignment_choice, output_dir, reference_dir = "."): """ Automatically downloads a peptide database for use with EUKulele and stores the name of the resulting FASTA file and taxonomy table. """ print("Automatically downloading database " + database_name, ...
5,290,022
def exchange_delegate_token(token, repository_id): """ Exchange a token for a delegated token :param token: a JWT granting the onboarding service access to write on the client's behalf :param repository_id: the target repsitory's ID :returns: a new JWT authorized to write to the repository ...
5,290,023
async def test_get_deck_labware_fixtures_short_trash( short_trash_deck_def: DeckDefinitionV2, short_fixed_trash_def: LabwareDefinition, mock_labware_data: AsyncMock, deck_data: DeckDataProvider, ) -> None: """It should be able to get a list of prepopulated labware on the deck.""" mock_labware_da...
5,290,024
def finalize_columns(points): """Finalize column names and contents.""" # Calculate how many people each point represents. count_by_zip_crid = points.groupby('ZIP_CRID').count()['TOT_CNT'] points['max_points_by_zip_crid'] = points['ZIP_CRID'].apply( lambda x: count_by_zip_crid.loc[x] ) ...
5,290,025
def confluence_2_and_3_into_1(sleep_speed): """ Lights up arms 2 and 3, then arm 1 """ LOGGER.debug("Confluence 2 and 3 into 1...") # Arm 2 and 3, Red PYGLOW.led(7, 120) PYGLOW.led(13, 120) sleep(sleep_speed) # Arm 2 and 3, Orange PYGLOW.led(8, 120) PYGLOW.led(14, 120) sl...
5,290,026
def unique_filename(filename, upload_id): """Replace filename with upload_id, preserving file extension if any. Args: filename (str): Original filename upload_id (str): Unique upload ID Returns: str: An upload_id based filename """ if "." in filename: return "."...
5,290,027
def sync_deft_jedi_task(task_id): """ Sync task between JEDI and DEFT DB. :param task_id: task id for sync :return: """ deft_task = ProductionTask.objects.get(id=task_id) if deft_task.request_id != 300: t_task = TTask.objects.filter(id=task_id).values('status','total_done_jobs','s...
5,290,028
def parse_object(*args): """ 将查询到的结果转换为需要的结构 :param args: :return: """ results = [] for cond in args: result = {'OPEN_ID': cond.OPEN_ID, 'OBJECT_ID': cond.OBJECT_ID, 'OBJECT_NAME': cond.OBJECT_NAME, 'OBJECT_CLASS': cond.OBJECT_CLA...
5,290,029
def filter_ec2(tagName, ec2Name, env): """Filter EC2 Instances by Tag""" ec2_list = [] ec2 = boto3.client('ec2', region_name=env.get('region')) instances = ec2.describe_instances( Filters=[ { 'Name': tagName, 'Values': [ec2Name] } ]...
5,290,030
def pqm_outgoing_message_thread(thread_name, router_socket_port, action_queue, notification_queue): """ This thread is responsible for sending messages to PQMs. An outside thread commands this thread via the action queue (send message, shut down, etc). Results and notifi...
5,290,031
def test_linked_list_search_returns_node_if_exists(): """Test_linked_list_search_returns_node_if_exists.""" ll = LinkedList() ll.push(1) ll.push(2) assert ll.search(1) == ll.head.next_node
5,290,032
def do_roll(u): """ Actually do a 'roll' and updating global (secret) z """ global z z = [update(val) for val in z] r = [(((z[i] - 1) * x_coe[i] + u[i]) % 14) + 1 for i in range(NUM_CARDS)] return r
5,290,033
def pseudo_nm_tmatrix(markovian_tmatrix, stateA, stateB): """Obtain a pseudo non-Markovian transition matrix from a Markovian transiton matrix The pseudo Markovian matrix has a shape of (2 n_states, 2 n_states) """ check_tmatrix(markovian_tmatrix) n_states = len(markovian_tmatrix) # pseudo no...
5,290,034
def translate(img, x, y): """ Translates the given image. :param x: distance to translate in the positive x-direction :param y: distance to translate in the positive y-direction :returns: the translated image as an numpy array """ M = np.float32([[1, 0, x], [0, 1, y]]) return cv2.warpAffine(img.reshape(28,28),...
5,290,035
def get_parent(graph, loc=None, exp=None, attr=None): """ Query syntax at start of expression: .. Selects the parent of the current node :param graph: (sub)graph instance to search :param loc: path location identifier :type loc: :py:str :param exp: expression to query for in...
5,290,036
def took(func): """ A decorator that will print how long a function was running to the debug output. This is useful for measuring performance in production. """ @wraps(func) def func_wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) spent...
5,290,037
def htmlstriptags(*args): """ .. function:: htmlstriptags(str, default_tag_conversion) Strips the html tags of input. It also converts "<br>" tags to new lines. If a default_tag_conversion is provided then tags that would have been erased are converted to *default_tag_conversion*. Examples: >...
5,290,038
def Assemble_Figure(data_plots, posterior_plots, heatmaps, annotation_plot, output, horizontal): """Assemble everything together and return svg and pdf of final figure""" DPI = 300 size_prob_plot = 215 size_stat_plot = 225 size_annotation_plot = 30 size_heatmap = 225 if heatmaps == None: ...
5,290,039
def rtc_runner(rtc): """ :type rtc: pbcommand.models.ResolvedToolContract :return: """ return gather_run_main(chunk_json=rtc.task.input_files[0], chunk_key=Constants.CHUNK_KEY, gathered_fn=rtc.task.output_files[0], ln_n...
5,290,040
def public_modules(path): """Yield all the paths to public modules in a given directory.""" for entry in path.iterdir(): if entry.name.startswith('_'): continue if entry.is_dir() or entry.is_file() and entry.suffix == '.py': yield entry
5,290,041
def check_and_prepare_sources(source): """ Check source type and return source(s) as a list :param source: single source or list of sources :return: list of sources based on provided source(s) """ source_ok = True if isinstance(source, Iterable): if not all([isinstan...
5,290,042
def write_epoch(parent_dir, accuracy, epoch): """Write the results of the current iteration to a file. Args: parent_dir: The directory to save the new file to. accuracy: The accuracy for this epoch on the test data. epoch: The current epoch number. """ iteration_file = open(os.path.join(parent_dir,...
5,290,043
def streamBurst(handle, numAddresses, aScanList, scanRate, numScans): """Initializes a stream burst and collects data. This function combines eStreamStart, eStreamRead, and eStreamStop, as well as some other device initialization. Args: handle: A valid handle to an open device. n...
5,290,044
def _recursive_update(my_dict: dict, update_dict: dict, delete: bool = False) -> None: """Update nested dicts deeply via recursion.""" for key, value in update_dict.items(): if value == TO_DELETE and delete and key in my_dict.keys(): del my_dict[key] elif isinstance(value, dict) and ...
5,290,045
def get_server_logs(hostname, instance_id): """ Get server logs for specified host and instance. """ host = get_host_by_hostname(hostname) if not host: return None if host['uri']: try: r = requests.get("%s/servers/%s/logs" % (host['uri'], instance_id), ...
5,290,046
def test_masked(image, measurements, module, objects, workspace): """Make sure we can process a completely masked image Regression test of IMG-971 """ image.pixel_data = numpy.zeros((10, 10, N_CHANNELS)) image.mask = numpy.zeros((10, 10), bool) objects.segmented = numpy.ones((10, 10), int) ...
5,290,047
def __to_pplot(p): """ Change Particle to pplot so that crossing 0-degree line can be plotted. Parameters ---------- p: Particle A given Lagrangian particle. Returns ------- re: tuple of particle and cross0 Particle after LON being modified and whether it crosses 0-degr...
5,290,048
def ror (endv, iv): """ This capital budgeting function computes the rate of return on an investment for one period only. iv = initial investment value endv = total value at the end of the period Example: ror(100000, 129,500) """ return (endv - iv)/iv
5,290,049
def cov(x): """ https://en.wikipedia.org/wiki/Covariance_matrix """ E_x = x.mean(dim=1) x = x - E_x[:, None] return torch.mm(x, x.T) / (x.size(1) - 1)
5,290,050
def assert_st_vector(vect: _np.ndarray): """Raise if `vect` is not a valid one-dimensional stochastic vector. Args: vect (np.ndarray) Object to test. Raises: ValueError """ if vect.ndim != 1: raise ValueError('Vector must be one-dimensional.') if not _np.isclose...
5,290,051
def ParseOptions(argv, docstring, extra_opts="", extra_long_opts=(), extra_option_handler=None): """Parse the options in argv and return any arguments that aren't flags. docstring is the calling module's docstring, to be displayed for errors and -h. extra_opts ...
5,290,052
def get_exportlog(site, save_dir=os.getcwd(), only_if_newer=False, country_code='GRC'): """ Download the latest available M3G igs log file for a given station. The input 'site' parameter should be the site's 9-char-id (aka the site's long name). If it is only the 4-char-id, then also the site's cou...
5,290,053
def compare_prime_type(sku, winner): """Easier to compare listings of different types.""" compare = zip(sku, winner) # x = [prime_sku, prime_price], y = [nonprime_sku, nonprime_price] # there are 3 common cases, same listingtyp than winner # different listingtype than winner, no listing at all. ...
5,290,054
def load_housing_data(housing_path=HOUSING_PATH): """ 使用pandas加载数据 """ csv_path = os.path.join(housing_path,"housing.csv") return pd.read_csv(csv_path)
5,290,055
def one_configuration_row(): """ ConfigurationRow """ return [ ConfigurationRow( id=100, name="Product 1: Feature 1", product="testproduct1", features='{"feature1": 1}', license_servers=["flexlm:127.0.0.1:2345"], license_ser...
5,290,056
def atan(x, f=None): """ Computes trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = arctan(y). :param x: Input array. :type x: array :param f: Machine learning framework. Inferred from inputs if None. :type f: ml_framework, optional :return:...
5,290,057
def _recurse_cli( cli_element: Union[click.Command, click.Group, click.CommandCollection], ctx: click.Context, io_dict: Dict[str, Any], get_help: bool = False, ) -> None: """ Code copied over from kedro.tools.cli to maintain backwards compatibility with previous versions of kedro (<0.17.5). ...
5,290,058
def butter(cutoff, fs, btype="low", order=4): """Return Butterworth filter coefficients. See scipy.signal.butter for a more thorough documentation. Parameters ---------- cutoff : array Cutoff frequency, e.g. roughly speaking, the frequency at which the filter acts. Units should be s...
5,290,059
def is_dimensionless(quantity_or_unit: QuantityOrUnit) -> bool: """ Check wheter a quantity or unit is dimensionless. Parameters ---------- quantity_or_unit : QuantityOrUnit A quantity or a unit Returns ------- bool Whether the quanti...
5,290,060
def count_lines(filename): """Returns the number of lines of the file :obj:`filename`.""" with tf.io.gfile.GFile(filename, mode="rb") as f: i = 0 for i, _ in enumerate(f): pass return i + 1
5,290,061
def raise_if_duplicate(response, sid): """Check response and raise if there is already an event""" event_count = int(response.get('height', 0)) if event_count > 0: raise DuplicateEventImportError()
5,290,062
def _build_transformer(gin_function): """ Makes a session and a default graph, loads the simple graph into it, and then calls gin_function(session) to build the :py:obj:`TFInputGraph` object. Return the :py:obj:`TFTransformer` created from it. """ graph = tf.Graph() with tf.Session(graph=gra...
5,290,063
def forecast_starter(seq, past, dim_in): """prepares the staring vector for RNN forecast :param seq: the sequence from which the beggining is used as the forcast starter :param past: the number of considered steps in the past :param dim_in: the dimensionality of the data fed to the network :returns: starter inpu...
5,290,064
def _get_single_osc(centers, powers, bws, osc_low, osc_high): """ Searches for an oscillations of specified frequency band. Returns a single oscillation in that band. Helper function for osc_per_vertex in MegSubj. Parameters ---------- centers : 1d array Vector of oscillation centers. ...
5,290,065
def ngram_jurisdiction(jurisdiction_id, replace_existing=False, max_n=3): """ For given jurisdiction, extract all ngrams up to max_n. Write ngrams to ngram_storage with paths like "jurisdiction_year/mass_2018-1.tsv.xz" Each file is an xzipped tsv with the columns "gram", "instances", and "do...
5,290,066
def list_property_flags(flags): """Return list of PROPERTY_FLAG strings from flag number.""" return [k for k, v in Lucam.PROP_FLAG.items() if v & flags]
5,290,067
def add_github(githubfolder): """ Create a script that auto appends to the path all repos in your github folder on startup. Only needs to be called once. """ import site sitepackdir = site.getsitepackages()[-1] # make a .py script for adding all github paths path = os.path.join(sit...
5,290,068
def union_func_name(prefix: str, union_args: List[Type]) -> str: """ Generate a function name that contains all union types * `prefix` prefix to distinguish between serializing and deserializing * `union_args`: type arguments of a Union >>> from ipaddress import IPv4Address >>> from typing imp...
5,290,069
def create_line(data): """ Convenience function to create a new line chart with the right args """ return Line(data, x='year', y=countries, legend=True, width=1400, height=300, ylabel='Energy use per capita', palette=['purple', 'green', 'blue', 'pink'])
5,290,070
def slow_subtractor(a, b): """Return a minus b.""" time.sleep(5) return a - b
5,290,071
def _convert_image(data, mask=None): """ Convert the input data to a float64 (double) `numpy.ndarray`, required for input to `skimage.measure.moments` and `skimage.measure.moments_central`. The input ``data`` is copied unless it already has that `numpy.dtype`. If ``mask`` is input, then ma...
5,290,072
def concatenate_list_of_dict(list_of_dict) -> dict: """ Concatenate dictionary with the same set of keys Args: list_of_dict: list of dictionary to concatenate Returns: output_dict: the concatenated dictionary """ # check that all dictionaries have the same set of keys for i...
5,290,073
def sample_plot_beta(): """ Plot the data from the C++ script against the scipy pdf, for the beta distribution """ print(' beta') raw_output = sample_exes_and_outputs['rand_beta'] output_file = os.path.join(output_sample_dir, raw_output) graph_name = os.path.join(output_sample_dir, '{}.svg...
5,290,074
def get_task(request): """ 取出所有任务类型信息 :param request: :return: """ try: res = Task.objects.get_task(1) # 调用search_host接口 return res # 返回json数据 except Exception as e: return_dic = { "result": F...
5,290,075
def degrees(input): """Convertir a grados Función para convertir una entrada en radianes a grados. Args: input(Number): valor real Returns: Number """ return (180*input)/math.pi
5,290,076
def _announce_new_object(request, obj, route, topic, data): """Enqueue a message about new object being created.""" if request and hasattr(request, '_messagings'): msg = { 'url': reverse(route, args=[obj.pk], request=request), 'new_value': data, } request._messagi...
5,290,077
def plot_3d_clustering(x, y, z, idx, elev=45, azim=-45, x_label=None, y_label=None, z_label=None, color_map='viridis', alphas=None, first_cluster_index_zero=True, s=None, markerscale=None, legend=True, figure_size=(7,7), title=None, save_filename=None): """ Plots a three-dimensional manifold divided into cluste...
5,290,078
async def getrolenamed(role: str, guild: discord.Guild, create: bool = False, exact: bool = True): """ Returns a role inside a Guild based on a given name. :param role: The role to be gathered. -> str :param guild: The guild to retrieve the role from. -> discord.Guild :param create: If set to True, ...
5,290,079
def get_head_commit(current_branch=None): """Gets the commit hash of HEAD in the given branch. Args: current_branch: String; containing the name of a branch. Defaults to None and in this case is replaced by a call to get_current_branch. Returns: 40 hexadecimal characters contai...
5,290,080
def _collect_format_strings(zones_map: ZonesMap) -> IndexMap: """Collect the 'formats' field and return a map of indexes.""" short_formats: Set[str] = set() for zone_name, eras in zones_map.items(): for era in eras: format = era['format'] short_format = format.replace('%s', '...
5,290,081
def lognormal(a, f): """ A lognormal distribution Parameters ---------- a : ndarray(3) * a[0] : the natural logarithm of the Gaussian amplitude * a[1] : the natural logarithm of the center of the Gaussian * a[2] : the width of the Gaussian in units of natural logarithm o...
5,290,082
def run_testing(global_step, d3_parts, c12_parts): """Testing func""" # Tell TensorFlow that the model will be built into the default Graph. with tf.Graph().as_default(): image = Image.open("img.bmp") # Открываем изображение. image = image.convert('YCbCr') width = image.size[0] # Определяем ширину....
5,290,083
def init_pose(pred_Rs, init_pose, weights=None): """ Should stay close to initial weights pred_Rs is N x 24 x 3 x 3 init_pose is 72D, need to conver to Rodrigues """ init_Rs = batch_rodrigues(tf.reshape(init_pose, [-1, 3])) init_Rs = tf.reshape(init_Rs, [-1, 24, 3, 3]) RRt = tf.matmul(in...
5,290,084
def get_volume_breakdown(model: BDF, property_ids=None, stop_if_no_volume=True): """ Gets a breakdown of the volume by property region. Parameters ---------- property_ids : List[int] / int list of property ID stop_if_no_volume : bool; default=True prevents crashing if there are ...
5,290,085
def convert_file(file_info): """Convert MATLAB *.mat file to Pandas HDF5 format.""" # If the file exists, load and convert print('Converting: {}'.format(file_info['file_name'])) # If running in dry-run mode, do not attempt to convert if file_info['dry_run']: return # Load data, convert...
5,290,086
def test_tty_start_stage(capsys): """Verify the start_stage() method works correctly.""" output = Tty() output.log(OutputMethod.STAGE_START) captured = capsys.readouterr() assert captured.out == 'Starting Stage 1\n' output.log(OutputMethod.STAGE_START, name='test-stage') captured = capsys.r...
5,290,087
def test_generate_base_venvs_with_pattern(cli: click.testing.CliRunner): """Generatening generate with pattern passes in that pattern""" with mock.patch("riot.cli.Session.generate_base_venvs") as generate_base_venvs: with with_riotfile(cli, "empty_riotfile.py"): result = cli.invoke(riot.cli....
5,290,088
def send_activation_email(profile): """ Send acivation e-mail for unactivated users """ instance = profile if instance.user.is_staff or instance.user.is_superuser or instance.user.is_active: instance.email_sent = True instance.user.is_active = True else: if instance.email...
5,290,089
def clone_case(casedir, template_dir, copy_polymesh=True, copy_zero=True, copy_scripts=True, extra_patterns=None): """Clone a Caelus case directory. Args: casedir (path): Absolute path to new case directory. template_dir...
5,290,090
def get_manifest_list(manifests_dir: str) -> List[str]: """Get a list of manifest files from the manifest directory.""" yml_endings = ["yml", "yaml"] manifest_list = [] for yml_ending in yml_endings: manifest_list += glob.glob(f"{manifests_dir}/**/*.{yml_ending}", recursive=True) return ma...
5,290,091
def run_in_background(coroutine: Callable[[concurrent.futures.Future[T]], Coroutine[Any, Any, None]], *, name: Optional[str] = None, debug: bool = False, _policy_lock: threading.Lock = threading.Lock()) -> T: """ Runs ``coroutine(future)`` in a new event loop on a background thread. Blocks on *future* and ...
5,290,092
def render(root: MdastNode) -> str: """Convert MDAST to CommonMark compliant HTML.""" return MdastToHtmlTransform()(root)
5,290,093
def interpolateNDMinTimeLinear(x0, x1, vmax, amax): """interpolateNDMinTimeLinear(doubleVector x0, doubleVector x1, doubleVector vmax, doubleVector amax)""" return _motionplanning.interpolateNDMinTimeLinear(x0, x1, vmax, amax)
5,290,094
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up config entry.""" def get_sensor_description(type_string: str): if (description := SENSOR_TYPES_DICT.get(type_string)) is None: return Binary...
5,290,095
def slack_channel_lookup_error(err): """'None' or 'Multiple' results were found during a ``one()`` query for :class:`jackalope.database.models.SlackChannel``. """ current_app.logger.exception(err) return err.message, 404
5,290,096
def actor_lookup_email(api_user, email): """ Lookup an actor based on an email address, useful for determining if an email address is available PARAMETERS: email - email alias RETURNS: actor_ref """ query = Relation.gql("WHERE target = :1 AND relation = 'email'", email) for rel_...
5,290,097
def progressbar(current, total, text=None, width=30, end=False): """Progress bar Args: current (float): current value of the bar total (float): total of the bar text (string): additional text to show width (int, optional): number of spaces of the bar end (bool, optio...
5,290,098
def load_user(user_id): """ Loads current user data --- """ return User.query.filter_by(id=user_id).first()
5,290,099