content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def wait_for_task(task, actionName='job', hideResult=False): """ Waits and provides updates on a vSphere task """ while task.info.state == vim.TaskInfo.State.running: time.sleep(2) if task.info.state == vim.TaskInfo.State.success: if task.info.result is not None and not hideResult:...
c750238117579236b159bf2389e947e08c8af979
28,700
def _get_candidate_names(): """Common setup sequence for all user-callable interfaces.""" global _name_sequence if _name_sequence is None: _once_lock.acquire() try: if _name_sequence is None: _name_sequence = _RandomNameSequence() finally: _on...
bc42c4af0822fcaa419047644e9d4b9d064a42fd
28,701
def relative_difference(x: np.array, y: np.array) -> np.array: """ Returns the relative difference estimator for two Lagrange multipliers. """ maximum = np.max([x, y]) minimum = np.min([x, y]) difference = maximum-minimum return np.abs(difference) / np.max(np.abs([x, y, difference, 1.]))
6b169a3deb3f6ed91958744521aa8028451fb3d8
28,702
def ConvertPngToYuvBarcodes(input_directory='.', output_directory='.'): """Converts PNG barcodes to YUV barcode images. This function reads all the PNG files from the input directory which are in the format frame_xxxx.png, where xxxx is the number of the frame, starting from 0000. The frames should be consecut...
43cc0dd4126b0699212064e445608c82123ad7b9
28,703
from pathlib import Path def _ignore_on_copy(directory, contents): # pylint: disable=unused-argument """Provides list of items to be ignored. Args: directory (Path): The path to the current directory. contents (list): A list of files in the current directory. Returns: list: A li...
3a551f6a252406b88fb19c0dc8180631cd5996ce
28,704
def registDeptUser(request): """ 홈택스 현금영수증 부서사용자 계정을 등록합니다. - https://docs.popbill.com/htcashbill/python/api#RegistDeptUser """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 홈택스 부서사용자 계정아이디 DeptUserID = "deptuserid" # 홈택스 부서사용자 계정비밀번호 DeptUserPW...
e5f923ac4290fd029eafdf6e408d7847be9d0c6b
28,705
import os def generate_repository_path(object_id): """ Generate the path of a cilantro (sub)object in the repository. This is based on the last 4/2 digits of the object_id, which should be a zenon or atom ID. E.g. object_id "JOURNAL-ZID1234567" is stored under "4500/4567/JOURNAL-ZID1234567". ...
05f7eabf865128dc01f50a9aded186f8f613f11d
28,706
import os def write_sysctl(entry, value): """Write value to a sysctl entry. Return this value if successful""" path = SYSCTL_ENDPOINT + '/' + '/'.join(entry.split('.')) if not os.path.exists(path): logger.debug("{} does not exist".format(entry)) return try: with open(path, 'w')...
878a0a1505e43d1ff2ad667b16500c5a57709aa8
28,707
import httpx import asyncio async def get_rank(mode: str, num: int) -> list[dict]: """请求pixiv榜单的函数 Args: mode (str): 日榜daily/周榜weekly/月榜monthly num (int): 数量(1-50) Returns: list[dict]: 一个包含图片标题与id,排名,画师名称与id,原图链接以及tags的列表,请求失败的返回请求失败字符串 """ url = "https://www.pixiv.net/ra...
e32e2c680ff2c2066de5ff207c9ea53e2565e974
28,708
import torch def generate_fake_data_loader(): """" Generate fake-DataLoader with four batches, i.e. a list with sub-lists of samples and labels. It has four batches with three samples each. """ samples1 = torch.tensor([[2., 2., 2., 2.], [2., 2., 0., 0.], [0., 0., 2., 2.]]) samples2 = torch.tensor([[1....
4d86ab464653f5766a44f03e41fd2c26714cabf1
28,709
def get_graph(node, seq): """Get the relaxed pose graph from the map server""" request = GraphRelaxation.Request() request.seq = int(seq) request.update_graph = False # TODO not used? request.project = True # TODO always True? return ros_service_request(node, "relaxed_graph", GraphRelaxation, request)
d618e9f557f83f875fe30343fc53fe31ded634b6
28,710
def get_RV_K( P_days, mp_Mearth, Ms_Msun, ecc=0.0, inc_deg=90.0, nsamples=10000, percs=[50, 16, 84], return_samples=False, plot=False, ): """Compute the RV semiamplitude in m/s via Monte Carlo P_days : tuple median and 1-sigma error mp_Mearth : tuple media...
11cdb7bfeef27d5a05638d74232e105a22fa0222
28,711
def arc(color, start_angle, stop_angle, width, height, x=None, y=None, thickness=1, anchor='center', **kwargs): """ Function to make an arc. :param color: color to draw arc :type color: str or List[str] :param start_angle: angle to start drawing arc at :type start_angle: int :param ...
42c0a53632315ff03b92c53cbc172a0cfd08f5a7
28,712
def calculate_shapley_value(g, prob_vals, maxIter=20000): """ This algorithm is based on page 29 of the following paper: https://arxiv.org/ftp/arxiv/papers/1402/1402.0567.pdf :param g: the graph :param prob_vals: a list. it contains the weight of each node in the graph :param maxIter: maximum ...
41329a17f0914597bcf457ea04e9dc0a7053ae62
28,713
from typing import List from typing import Dict from typing import Any async def complete_multipart_upload(bucket: str, s3_key: str, parts: List, upload_id: str) -> Dict[str, Any]: """Complete multipart upload to s3. Args: bucket (str): s3 bucket s3_key (str): s3 prefix parts (List): ...
01441cbc196f594bead4dd9a9b17fe1a3c8bfa4d
28,714
def build_mask(module='A', pixscale=0.03): """Create coronagraphic mask image Return a truncated image of the full coronagraphic mask layout for a given module. +V3 is up, and +V2 is to the left. """ if module=='A': names = ['MASK210R', 'MASK335R', 'MASK430R', 'MASKSWB', 'MASKLWB'] ...
97e068fe8eef6e8fdd65b1e426428001cf549332
28,715
async def update_login_me( *, password: str = Body(...), new_email: tp.Optional[EmailStr] = Body(None, alias='newEmail'), new_password: tp.Optional[str] = Body(None, alias='newPassword'), current_user: models.User = Depends(common.get_current_user), uow: IUnitOfWork = Depends(common.get_uow), ) ...
ec3f56ee474d19a4fd89c51940f3a198322672a1
28,716
def comp_sharpness(is_stationary, signal, fs, method='din', skip=0): """ Acoustic sharpness calculation according to different methods: Aures, Von Bismarck, DIN 45692, Fastl Parameters: ---------- is_stationary: boolean True if the signal is stationary, false if it is time varying ...
a8ae39740c90e824081e3979d5ff2b5c96a8ad75
28,717
def load_hobbies(path='data', extract=True): """ Downloads the 'hobbies' dataset, saving it to the output path specified and returns the data. """ # name of the dataset name = 'hobbies' data = _load_file_data(name, path, extract) return data
e60e024d0fe1766c599a3b693f51522cb7d7303a
28,718
def is_viable(individual): """ evaluate.evaluate() will set an individual's fitness to NaN and the attributes `is_viable` to False, and will assign any exception triggered during the individuals evaluation to `exception`. This just checks the individual's `is_viable`; if it doesn't have one, this a...
c1e5c839f362e99800dcd1a996be9345cabb4261
28,719
def combine_counts(hits1, hits2, multipliers=None, total_reads=0, unmatched_1="Unknown", unmatched_2="Unknown", ): """ compile counts into nested dicts """ total_counted = 0 counts = {} # ke...
505e91f6538267e40f438926df201cf25cb1a3f9
28,720
def root(): """Serves the website home page""" return render_template("index.html")
676c966da523108bd9802c2247cf320993815124
28,721
import string import random def getCookie(): """ This function will return a randomly generated cookie :return: A cookie """ lettersAndDigits = string.ascii_lowercase + string.digits cookie = 'JSESSIONID=' cookie += ''.join(random.choice(lettersAndDigits) for ch in range(31)) return co...
6fff76d37921174030fdaf9d4cb8a39222c8906c
28,722
def get_authenticated_igramscraper(username: str, password: str): """Gets an authenticated igramscraper Instagram client instance.""" client = Instagram() client.with_credentials(username, password) #client.login(two_step_verificator=True) client.login(two_step_verificator=False) return client
c8f7cf4500aa82f11cf1b27a161d75a7261ee84a
28,723
def read_in_nn_path(path): """ Read in NN from a specified path """ tmp = np.load(path) w_array_0 = tmp["w_array_0"] w_array_1 = tmp["w_array_1"] w_array_2 = tmp["w_array_2"] b_array_0 = tmp["b_array_0"] b_array_1 = tmp["b_array_1"] b_array_2 = tmp["b_array_2"] x_min = tmp["x...
3f2366ab9fd4b4625c8b7d00b1191429678b466b
28,724
def crop_zeros(array, remain=0, return_bound=False): """ Crop the edge zero of the input array. Parameters ---------- array : numpy.ndarray 2D numpy array. remain : int The number of edges of all zeros which you want to remain. return_bound : str or bool Select the m...
13cb5a0a289ef622d3dd663777e6a0d2814b5104
28,725
def go_info_running(data, info_name, arguments): """Returns "1" if go is running, otherwise "0".""" return '1' if 'modifier' in hooks else '0'
8027d0106e379156225c87db1959110fcfac6777
28,726
def letra_mas_comun(cadena: str) -> str: """ Letra Parámetros: cadena (str): La cadena en la que se quiere saber cuál es la letra más común Retorno: str: La letra más común en la cadena que ingresa como parámetro, si son dos es la letra alfabéticamente posterior. """ letras_e...
c36a753717365164ca8c3089b398d9b6e358ef3f
28,727
def dwt2(image, wavelet, mode="symmetric", axes=(-2, -1)): """Computes single level wavelet decomposition for 2D images """ wavelet = ensure_wavelet_(wavelet) image = promote_arg_dtypes(image) dec_lo = wavelet.dec_lo dec_hi = wavelet.dec_hi axes = tuple(axes) if len(axes) != 2: r...
4ee7e1f3c19bb1b0bf8670598f1744b7241b235d
28,728
def recommended_global_tags_v2(release, base_tags, user_tags, metadata): """ Determine the recommended set of global tags for the given conditions. This function is called by b2conditionsdb-recommend and it may be called by conditions configuration callbacks. While it is in principle not limited to...
8396dcc2d54a5e36dfe5485d33ef439059a944c6
28,729
def plot_corelation_matrix(data): """ Plotting the co-relation matrix on the dataset using the numeric columns only. """ corr = data.select_dtypes(include=['float64', 'int64']).iloc[:, 1:].corr() # Generate a mask for the upper triangle mask = np.zeros_like(corr, dtype=np.bool) mask[np....
49e89f3ba844f0bf9676bca4051c72ad1305294f
28,730
import urllib from bs4 import BeautifulSoup def product_by_id(product_id): """ Get Product description by product id :param product_id: Id of the product :return: """ host = "https://cymax.com/" site_data = urllib.urlopen(host + str(product_id) + '--C0.htm').read() soup = BeautifulSou...
2f2f3abfd0dcf5a124ae4a1bd3975734fbac7783
28,731
def overlap(X, window_size, window_step): """ Create an overlapped version of X Parameters ---------- X : ndarray, shape=(n_samples,) Input signal to window and overlap window_size : int Size of windows to take window_step : int Step size between windows Returns ...
4f53be9c87d0ce9800a6e1b1d96ae4786eace78b
28,732
def may_ozerov_depth_3_complexity(n, k, w, mem=inf, hmap=1, memory_access=0): """ Complexity estimate of May-Ozerov algorithm in depth 3 using Indyk-Motwani for NN search [MayOze15] May, A. and Ozerov, I.: On computing nearest neighbors with applications to decoding of binary linear codes. In: Annual I...
b390a515626185912cbc234fbebd492a0e154bbb
28,733
import json import copy def unpack_single_run_meta(storage, meta, molecules): """Transforms a metadata compute packet into an expanded QC Schema for multiple runs. Parameters ---------- db : DBSocket A live connection to the current database. meta : dict A JSON description of ...
3a3237067b4e52a5f7cb7d5ecc314061eaaa2b15
28,734
def getKey(event): """Returns the Key Identifier of the given event. Available Codes: https://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/keyset.html#KeySet-Set """ if hasattr(event, "key"): return event.key elif hasattr(event, "keyIdentifier"): if event.keyIdentifier in ["Es...
0935ad4cb1ba7040565647b2e26f265df5674e1d
28,735
def get_long_season_name(short_name): """convert short season name of format 1718 to long name like 2017-18. Past generations: sorry this doesn't work for 1999 and earlier! Future generations: sorry this doesn't work for the 2100s onwards! """ return '20' + short_name[:2] + '-' + short_name[2:]
314ef85571af349e2e31ab4d08497a04e19d4118
28,736
from typing import List from typing import Any from typing import Dict def make_variables_snapshots(*, variables: List[Any]) -> str: """ Make snapshots of specified variables. Parameters ---------- variables : list Variables to make snapshots. Returns ------- snapshot_name : ...
d6a7bf5be51ebe7f4fb7985b2a440548c502d4ec
28,737
def sext_to(value, n): """Extend `value` to length `n` by replicating the msb (`value[-1]`)""" return sext(value, n - len(value))
683316bd7259d624fddb0d9c947c7a06c5f28c7e
28,738
def parse_matching_pairs(pair_txt): """Get list of image pairs for matching Arg: pair_txt: file contains image pairs and essential matrix with line format image1 image2 sim w p q r x y z ess_vec Return: list of 3d-tuple contains (q=[wpqr], t=[xyz], essential matrix) ...
6697e63a091b23701e0751c59f8dc7fe0e582a97
28,739
import threading from typing import OrderedDict def compile_repo_info(repos, all=False, fetch=False): """Compiles all the information about found repos.""" # global to allow for threading work global git_info git_info = {} max_ = len(repos) threads = [] for i, repo in enumerate(repos): ...
b3cbdcdd53ce2c5274990520756390f396156aaa
28,740
def histogram2d(x, y, bins=10, range=None, weights=None, density=False): # pylint: disable=redefined-builtin """ Computes the multidimensional histogram of some data. Note: Deprecated numpy argument `normed` is not supported. Args: x (Union[list, tuple, Tensor]): An array with shape `(...
8b537168cb7248ccd2959c95ae4fb742b81aa225
28,741
def get_project_arg_details(): """ **get_project_arg_details** obtains project details from arguments and then returns them :return: """ project_id = request.args.get('project_id') names = request.args.get('names') cell = request.args.get('cell') email = request.args.get(...
5efcaebf0efe89a5d8fa5f52d50777041b545177
28,742
def vibronic_ls(x, s, sigma, gamma, e_vib, kt=0, n_max=None, m_max=None): """ Produce a vibronic (Frank-Condom) lineshape. The vibronic transition amplitude computed relative to 0 (ie: relative to the electronic transition energy). Lines are broadened using a voigt profile. Parameter...
428f0c44566cf3a824902fc9f7fb8012089d1b89
28,743
import re import requests def handleFunction(command,func): """ Function to calculate, Translate """ try: # re.search(r"(?i)"+func,' '.join(SET_OF_FUNCTIONS)) if("calculate" == func.lower()): func,command = command.split() try: return eval(command) except: return "Sorry! We are unable to cal...
c5ff05b0b31a7441f7efaf9ce76c496f3f708eea
28,744
import json def auth(): """returns worker_id !!!currently!!! does not have auth logic""" response_body = {} status_code = 200 try: auth_token = request.args.get("auth_token", None) resp = fl_events_auth({"auth_token": auth_token}, None) resp = json.loads(resp)["data"] excep...
bbbeb0dbf7401b11e56399890f43a799f859eb87
28,745
def redo_a_task(): """Allows the user to unfinish a task so they can complete it again""" user = get_user_info() if user['id'] != g.user['id']: abort(403) if request.method == 'POST': redo = request.form['redoTask'] # get the database connection with db.get_db() as ...
78910778a93246bb3a819cb5392400fa8e65de0a
28,746
def get_templates_environment(templates_dir): """Create and return a Jinja environment to deal with the templates.""" env = Environment( loader=PackageLoader('charmcraft', 'templates/{}'.format(templates_dir)), autoescape=False, # no need to escape things here :-) keep_trailin...
9f3571ce4cb8f18f64912e6c259bc2f1022698f2
28,747
import numpy as np def return_U_given_sinusoidal_u1(i,t,X,u1,**kwargs): """ Takes in current step (i), numpy.ndarray of time (t) of shape (N,), state numpy.ndarray (X) of shape (8,), and previous input scalar u1 and returns the input U (shape (2,)) for this time step. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...
b5faba122af139f29f20dbce983b84fe5c0c277c
28,748
def verify(s): """ Check if the cube definition string s represents a solvable cube. @param s is the cube definition string , see {@link Facelet} @return 0: Cube is solvable<br> -1: There is not exactly one facelet of each colour<br> -2: Not all 12 edges exist exactly once<br> ...
d3e765af153a7400d84e59c72d292a9ccd9170f5
28,749
from typing import cast import copy def copy_jsons(o: JSONs) -> MutableJSONs: """ Make a new, mutable copy of a JSON array. >>> a = [{'a': [1, 2]}, {'b': 3}] >>> b = copy_jsons(a) >>> b[0]['a'].append(3) >>> b [{'a': [1, 2, 3]}, {'b': 3}] >>> a [{'a': [1, 2]}, {'b': 3}] """ ...
c9fffefe0dd541e20a7a3bef503e0b1af847909d
28,750
def string_to_dot(typed_value): # type: (TypedValue) -> Tuple[List[str], List[str]] """Serialize a String object to Graphviz format.""" string = f'{typed_value.value}'.replace('"', r'\"') dot = f'_{typed_value.name} [shape="record", color="#A0A0A0", label="{{{{String | {string}}}}}"]' return [dot], ...
287d2c886aca5ca940b323b751af91e33ed54fc4
28,751
def resolve_country_subdivisions(_, info, alpha_2): """ Country resolver :param info: QraphQL request context :param alpha_2: ISO 3166 alpha2 code :param code: ISO 3166-2 code """ return CountrySubdivision.list_for_country(country_code=alpha_2)
56ffa7343f1da686819c85dee54770cd4d1564d3
28,752
from typing import Tuple def bool2bson(val: bool) -> Tuple[bytes, bytes]: """Encode bool as BSON Boolean.""" assert isinstance(val, bool) return BSON_BOOLEAN, ONE if val else ZERO
3d4456f6db88939966997b8a49c3d766b1ef4ba1
28,753
def isbn13_to_isbn10 (isbn_str, cleanse=True): """ Convert an ISBN-13 to an ISBN-10. :Parameters: isbn_str : string The ISBN as a string, e.g. " 0-940016-73-6 ". It should be 13 digits after normalisation. cleanse : boolean If true, formatting will be stripped from the ISBN before conversion. :Re...
b39d6d9f7a850a8b0edbb6b9502f4d6bb73f8848
28,754
import json def import_data(): """Import datasets to internal memory""" with open('data/names.json') as f: data_names = json.load(f) with open('data/issues.json') as f: data_issues = json.load(f) with open('data/disasters.json') as f: data_disasters = json.load(f) with open...
11db10c2c56b6b714ecffa57510c9a79abfa1d86
28,755
def synthesize_ntf_dunn(order=3, osr=64, H_inf=1.5): """ Alias of :func:`ntf_dunn` .. deprecated:: 0.11.0 Function has been moved to the :mod:`NTFdesign` module with name :func:`ntf_dunn`. """ warn("Function superseded by ntf_dunn in " "NTFdesign module", PyDsmDeprecationWarn...
2920ec676ab070ebb5f7c95e245baf078b723fae
28,756
def schedule_notification() -> str: """Randomly select either news or covid stats to add to the notifcation column, if there is already a 'news' item in the notificaitons column then it will update the item with a newer piece of news""" #NEWS news_title, news_content = get_news() notif_exists =...
9aed44251170dc124f71b11bf482ef009ebe973e
28,757
def _parse_hexblob(blob: str) -> bytes: """ Binary conversions from hexstring are handled by bytes(hstr2bin()). :param blob: :return: """ return bytes(hstr2bin(blob))
e49348f7cb15bbba850dbf05c0a3625427d0ac2d
28,758
from typing import List from typing import Dict def _row_to_col_index_dict(headers: List[Cell]) -> Dict[str, int]: """Calculate a mapping of cell contents to column index. Returns: dict[str, int]: {MFP nutrient name: worksheet column index} mapping. int: N """ return {h.value: h.col - ...
11f7a68cd211b216d2a27850be99291cc830d52f
28,759
def preprocess_cat_cols(X_train, y_train, cat_cols=[], X_test=None, one_hot_max_size=1, learning_task=LearningTask.CLASSIFICATION): """Preprocess categorial columns(cat_cols) in X_train and X_test(if specified) with cat-counting(the same as in catboost) or with one-hot-encoding, depends ...
10402fe0fd534eb73598fa99a1202b970202f2c0
28,760
def get_start_time(period, time_zone=None): """Doc.""" today = pd.Timestamp.today(tz=time_zone or 'Europe/Stockholm') if period == 'thisyear': return pd.Timestamp(f'{today.year}0101').strftime('%Y-%m-%d %H:%M:%S') elif period in DAYS_MAPPER: return (today - pd.Timedelta(days=DAYS_MAPPER....
c5e9ab4543f813f7210bc278e83d9c4a554d242b
28,761
def setup_textbox(parent, font="monospace", width=70, height=12): """Setup for the textboxes, including scrollbars and Text widget.""" hsrl = ttk.Scrollbar(parent, orient="horizontal") hsrl.pack(side=tk.BOTTOM, fill=tk.X) vsrl = ttk.Scrollbar(parent) vsrl.pack(sid...
674bc72eefacc16485a4b369535f1253187e5ded
28,762
def generate_mock_statuses(naive_dt=True, datetime_fixtures=None): """ A dict of statuses keyed to their id. Useful for mocking an API response. These are useful in``Timeline`` class testing. May be set to have a utc timezone with a ``False`` value for the ``naive_dt`` argument. """ mock_status...
aca7bd235ef6fd404f8da894b6917636d7895dcb
28,763
import os def get_current_ingest_id(): """Get the uuid of the active ingest :return: the id of the active ingest :rtype: uuid """ return os.getenv('JETA_CURRENT_INGEST_ID')
31299e8422e07fe38bc7a850033cf128a9a27749
28,764
import hashlib def hashlib_mapper(algo): """ :param algo: string :return: hashlib library for specified algorithm algorithms available in python3 but not in python2: sha3_224 sha3_256, sha3_384, blake2b, blake2s, sha3_512, shake_256, shake_128 """ algo = algo.lower() if algo == "...
56830caccd0b3f88982bfe09a8789002af99c1e7
28,765
def partition_cells(config, cells, edges): """ Partition a set of cells - cells -- A DataFrame of cells - edges -- a list of edge times delimiting boundaries between cells Returns a DataFrame of combined cells, with times and widths adjusted to account for missing cells """ # get indices of...
c8532cbf148802b482380f8978dbc8d9d3b1b35f
28,766
from typing import List from typing import Union def timing_stats(results: List[Result]) -> List[str]: """Calculate and format lines with timings across completed results.""" def percentile(data: List[float], percent: int) -> Union[float, str]: if not data: return '-' data_sorted =...
08d671b2866674924dc070dda2e7e85a4c56c064
28,767
import logging def analyse_gamma( snps_object, output_summary_filename, output_logger, SWEEPS, TUNE, CHAINS, CORES, N_1kG, fix_intercept=False, ): """ Bayesian hierarchical regression on the dataset with the gamma model. :param snps_object: snps instance :param ou...
fac6111e4ad87d63d89d2942e5cfc28023950117
28,768
def dpc_variant_to_string(variant: _DV) -> str: """Convert a Basix DPCVariant enum to a string. Args: variant: The DPC variant Returns: The DPC variant as a string. """ return variant.name
2eb7eeff47eb36bea47714b9e233f3d286925d3b
28,769
import secrets from datetime import datetime async def refresh_token(request: web.Request) -> web.Response: """ Refresh Token endpoints """ try: content = await request.json() if "token" not in content: return web.json_response({"error": "Wrong data. Provide token."}, status=400) ...
a8008a33793ccb7b34900724b62fb3add061fa30
28,770
def get_my_choices_projects(): """ Retrieves all projects in the system for the project management page """ proj_list = Project.objects.all() proj_tuple = [] counter = 1 for proj in proj_list: proj_tuple.append((counter, proj)) counter = counter + 1 return proj_tuple
f35563adb12aff32ac1b60152b3085c63dc839f0
28,771
import platform import locale import sys import struct import os def _get_sys_info() -> dict[str, JSONSerializable]: """ Returns system information as a JSON serializable dictionary. """ uname_result = platform.uname() language_code, encoding = locale.getlocale() return { "commit": _ge...
d86e84d90dc93d762f6ea33b776acaa28d1e8869
28,772
import math def normalDistributionBand(collection, band, mean=None, std=None, name='normal_distribution'): """ Compute a normal distribution using a specified band, over an ImageCollection. For more see: https://en.wikipedia.org/wiki/Normal_distribution :param band: the nam...
57b0d6beb590126253c4934e403487bd69c7c094
28,773
import torch def compute_ctrness_targets(reg_targets): """ :param reg_targets: :return: """ if len(reg_targets) == 0: return reg_targets.new_zeros(len(reg_targets)) left_right = reg_targets[:, [0, 2]] top_bottom = reg_targets[:, [1, 3]] ctrness = (left_right.min(dim=-1)[0] / l...
538a63b6adcd73fbd601d6e61eea5f27642746fa
28,774
import hashlib import hmac import base64 def create_hmac_signature(key:bytes, data_to_sign:str, hashmech:hashlib=hashlib.sha256) -> str: """ Creates an HMAC signature for the provided data string @param key: HMAC key as bytes @param data_to_sign: The data that needs to be signed @param hashmech: ...
0c3f5b8bef6e3330e8c24fca62ce2707b0de5286
28,775
def CV_range( bit_depth: Integer = 10, is_legal: Boolean = False, is_int: Boolean = False ) -> NDArray: """ Returns the code value :math:`CV` range for given bit depth, range legality and representation. Parameters ---------- bit_depth Bit depth of the code value :math:`CV` range. ...
e1eb079e4e75cb7b8353d88e13bb7eb82d15428c
28,776
import torch def bw_transform(x): """Transform rgb separated balls to a single color_channel.""" x = x.sum(2) x = torch.clamp(x, 0, 1) x = torch.unsqueeze(x, 2) return x
3ecec3ada4b75486ff96c30890e8a3e173ca7d31
28,777
def fom(A, b, x0=None, maxiter=None, residuals=None, errs=None): """Full orthogonalization method Parameters ---------- A : {array, matrix, sparse matrix, LinearOperator} n x n, linear system to solve b : {array, matrix} right hand side, shape is (n,) or (n,1) x0 : {array, matri...
b95ac8b383150e57ffd599fb2e77608dd7503d9d
28,778
def get_gprMax_materials(fname): """ Returns the soil permittivities. Fname is an .in file. """ materials = {'pec': 1.0, # Not defined, usually taken as 1. 'free_space': 1.000536} for mat in get_lines(fname, 'material'): props = mat.split() materials[props[-1]] = f...
f56e720c5c2209b67ca521b779ce9472665beb6a
28,779
import random def generate_utt_pairs(librispeech_md_file, utt_pairs, n_src): """Generate pairs of utterances for the mixtures.""" # Create a dict of speakers utt_dict = {} # Maps from speaker ID to list of all utterance indices in the metadata file speakers = list(librispeech_md_file["speaker_ID"]...
9079fa35b961de053c86b08527085e8eb84609b8
28,780
def simpson(so, spl: str, attr: str, *, local=True, key_added=None, graph_key='knn', inplace=True) -> None: """Computes the Simpson Index on the observation or the sample level Args: so: SpatialOmics instance spl: Spl for which to compute the metric attr: Categorical feature in SpatialO...
d10fd40305f384d75f8c33d391a87f6b5c8adcd5
28,781
def _rk4(dparam=None, k0=None, y=None, kwdargs=None): """ a traditional RK4 scheme, with: - y = array of all variables - p = parameter dictionnary dt is contained within p """ if 'itself' in dparam[k0]['kargs']: dy1 = dparam[k0]['func'](itself=y, **kwdargs) dy2 = dpar...
a44e177e6925c36fa9355ed9c5ee41d0604d01bd
28,782
def generate_discord_markdown_string(lines): """ Wraps a list of message into a discord markdown block :param [str] lines: :return: The wrapped string :rtype: str """ output = ["```markdown"] + lines + ["```"] return "\n".join(output)
1c0db2f36f4d08e75e28a1c024e6d4c35638d8f5
28,783
from typing import Optional def _sanitize_ndim( result: ArrayLike, data, dtype: Optional[DtypeObj], index: Optional[Index] ) -> ArrayLike: """ Ensure we have a 1-dimensional result array. """ if getattr(result, "ndim", 0) == 0: raise ValueError("result should be arraylike with ndim > 0") ...
6a1e49e07658ea3f7b9e80915c73464548715419
28,784
from typing import Callable from typing import Any from re import T from typing import List from typing import Dict def from_list_dict(f: Callable[[Any], T], x: Any) -> List[Dict[str, T]]: """Parses list of dictionaries, applying `f` to the dictionary values. All items must be dictionaries. """ assert...
2a1316098165367e8657d22717245a6c695cb96e
28,785
def TSTR_eICU(identifier, epoch): """ """ # get "train" data exp_data = np.load('./experiments/tstr/' + identifier + '_' + str(epoch) + '.data.npy').item() X_synth = exp_data['synth_data'] Y_synth = exp_data['synth_labels'] n_synth = X_synth.shape[0] X_synth = X_synth.reshape(n_synth, -1...
8f719e94689b1354e6463935e6dbdc2c5a110779
28,786
def wizard_active(step, current): """ Return the proper classname for the step div in the badge wizard. The current step needs a 'selected' class while the following step needs a 'next-selected' class to color the tip of the arrow properly. """ if current == step: return 'selected' ...
2daad3f7651df7609f3473af698e116ce419c9df
28,787
def set_token(token: OAuth2Token): """Set dynamics client token in a thread, so it can be done in an async context.""" def task(): name = "dynamics-client-token" expires = int(token["expires_in"]) - 60 cache.set(name, token, expires) with ThreadPoolExecutor() as executor: f...
61b4bfa3dbe1ddd03ff608a476f34905ec2440e9
28,788
def pFind_clumps(f_list, n_smooth=32, param=None, arg_string=None, verbose=True): """ A parallel implementation of find_clumps. Since SKID is not parallelized this can be used to run find_clumps on a set of snapshots from one simulation. **ARGUMENTS** f_list : list A list cont...
85e2c80f3fdb95f2c324b8b934550788faa6c5bb
28,789
import math def gamma_dis(x): """fix gamma = 2 https://www.itl.nist.gov/div898/handbook/eda/section3/eda366b.htm """ x = round(x, 14) res = round(x*math.exp(-x) / TAU_2, 14) return res
a3375b7ae16755d0dab47ecd4f54ebc8c40143b9
28,790
import os import pprint import json import sys def generate_schema_dictionary(source_type, csdl_schema_dirs, json_schema_dirs, entity, schema_file_name, oem_entities=None, oem_schema_file_names=None, profile=None, schema_url=None, ...
c550d5c03dc7577e3ede9db9bc469e76bbe68f9b
28,791
import calendar def get_month_number(year): """ Function to get month from the user input. The month should be number from 1-12. :returns: the number of month enterd by user :rtype: int """ year = int(year) while True: val = input("Please, enter the number of month? (1-12)\n") ...
c2d0f5010b8f1de6d1764a216c43eb1901c8093c
28,792
def reconstruct_with_whole_molecules(struct): """ Build smallest molecule representation of struct. """ rstruct = Structure() rstruct.set_lattice_vectors(struct.get_lattice_vectors()) molecule_struct_list = get_molecules(struct) for molecule_struct in molecule_struct_list: geo_arra...
f3595fdd23e22fc0c24b9a7cfa6e000206eda93f
28,793
def _json_serialize_no_param(cls): """ class decorator to support json serialization Register class as a known type so it can be serialized and deserialzied properly """ return _patch(cls, _get_type_key(cls), 0)
3eaf4c7c53694c316898b1a9e4d41dc4b212afed
28,794
def aireTriangle(a,b,c): """ Aire du triangle abc dans l'espace. C'est la moitié de la norme du produit vectoriel ab vect ac """ u,v=b-a,c-a r=u[2]*v[0]-u[0]*v[2] s=u[0]*v[1]-u[1]*v[0] t=u[1]*v[2]-u[2]*v[1] return 0.5*sqrt(r*r+s*s+t*t)
641aa598d36189c787b91af4a98734f2289173e0
28,795
def ez_admin(admin_client, admin_admin, skip_auth): """A Django test client that has been logged in as admin. When EZID endpoints are called via the client, a cookie for an active authenticated session is included automatically. This also sets the admin password to "admin". Note: Because EZID does not ...
0b2ac749a690ad5ac0dc83ca9c8f3905da5a016b
28,796
import textwrap def _template_message(desc, descriptor_registry): # type: (Descriptor, DescriptorRegistry) -> str """ Returns cls_def string, list of fields, list of repeated fields """ desc = SimpleDescriptor(desc) descriptor_registry[desc.identifier] = desc slots = desc.field_names ...
2586ffe0b81ea683a40bc20700ddb970fc385962
28,797
import re def parse_archive(path, objdump): """Parses a list of ObjectFiles from an objdump archive output. Args: path: String path to the archive. objdump: List of strings of lines of objdump output to parse. Returns: List of ObjectFile objects representing the objects ...
1f30804ba1d723bf8656dd26f522c5a369db4b3d
28,798
async def async_validate_trigger_config( hass: HomeAssistant, config: ConfigType ) -> ConfigType: """Validate config.""" config = TRIGGER_SCHEMA(config) device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(config[CONF_DEVICE_ID]) trigger ...
f43e1b58bd37e0cf989da8076505cf34c4386830
28,799