content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def find_rising_edge(x, y, *, threshold=None, interp=False): """Find the first `x` where `y` exceeds `threshold` (along the last axis). `x` and `y` must have the same shape. If `threshold` is None, it will be inferred as half the rise from min(y) to max(y). If `interp` is True, linearly interpolate b...
69c8601987cac8e44dc89d52499d907f58dc225c
36,800
def normalize_os_name(os_name): """ :API: public """ if os_name not in OS_ALIASES: for proper_name, aliases in OS_ALIASES.items(): if os_name in aliases: return proper_name logger.warning('Unknown operating system name: {bad}, known names are: {known}' .format(bad=os_nam...
ca7e921580ae72d77d4d16158f45edefac2cd8b6
36,801
def make_prediction(*, path_to_images) -> float: """Make a prediction using the saved model pipeline.""" # Load data # create a dataframe with columns = ['image', 'target'] # column "image" contains path to image # columns target can contain all zeros, it doesn't matter dataframe = path_to_ima...
80d30707ecbacdae50c0f986bb3c66a504cc3740
36,802
def vmanage_login(host: str, username: str, password: str): """ """ return Authentication( host=host, user=username, password=password ).login()
f127072880035b30e652d87f4af1b8bcd5110ffd
36,803
def load_image(): """Load image from file, then scale and rotate. Returns CV2 object.""" if display_histogram == 1: image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) else: image = cv2.imread(filename, cv2.IMREAD_COLOR) image_resized = cv2.resize(image, None, fx=scale, fy=scale,...
edaea5b59d6e87c8315bbc556d460b7cbefa2737
36,804
def handle_odd_pad_bwd(dx, odd_padding): """ handle odd padding mode backward Args: dx, the backward tensor odd_padding, the odd_padding Returns: tensor, the output """ # (axis, left padding if True else right padding) flags = [(2, True), (2, False), (3, True), (3, F...
fbf75299db943be3930db77abd21b0dd59c263bf
36,805
import logging def gwas_snp_to_precluster(gwas_snp, populations): """ Extract neighbourhood of GWAS snp Args: * [ GWAS_SNP ] * [ string ] (populations) Returntype: GWAS_Cluster """ mapped_ld_snps = postgap.LD.calculate_window(gwas_snp.snp) logging.info("Found ...
aaa3ac23e0797cfda134f7a105c0e0c33ff8c7a6
36,806
import argparse def parse_args(): """Parse command-line arguments.""" def _bool(val): return bool(strtobool(val)) parser = argparse.ArgumentParser(description='Deploy MargiPose jobs to Kubernetes', formatter_class=argparse.ArgumentDefaultsHelpFormatter) p...
4097bf81811dd2696d0d86b1050b608cb851109f
36,807
def block_shuffle(indices, block_size, one_based=ONE_BASED): # TODO(allie): Handle zero-indexing here too (currently assuming first frame index = 1) """ Shuffles indices according to 'blocks' of size block_size. All 'blocks' start with index 1. inputs: indices (array-like, shape (N,)): integers...
f7d6d590d92d1147c7255aebb86ab13b270e591c
36,808
def cleanup_ud(ds): """More cleaning and calculation of derived variables.""" # remove spikes in temperature for v in ["t1", "t2"]: ds[v] = despike(ds[v], ds.attrs["spike_thresh_t"]) # despike T, C ibefore = 1 iafter = 1 for v in ["c1", "c2", "t1", "t2"]: ds[v].data = helpe...
ff97f13667f07fd79aa3400ffea65d4b958d3163
36,809
import collections def ParseIoStatsLine(line): """Parses a line of io stats into a IoStats named tuple.""" # Field definitions: http://www.kernel.org/doc/Documentation/iostats.txt IoStats = collections.namedtuple('IoStats', ['device', 'num_r...
2764dc96f0720359f906f1b27763738331f63e19
36,810
from sqlalchemy import create_engine from sqlalchemy.pool import NullPool def sql_readaspd(db_dets, query): """ Pull a SQL query output and read it into a Pandas DataFrame Parameters ---------- db_dets: str URL of a postgreSQL database that will be connected to. query: str ...
73d936aa8a9658a35efdb8e4ac451aca9c68abea
36,811
def grid2spec(gfield): """Transform a field on physical grid to spectral space Args: gfield: numpy array with shape (time(optional), y, x, z(optional)) """ if _is_single_layer(gfield): y_loc = -2 else: y_loc = -3 ny, nx = gfield.shape[y_loc], gfield.shape[y_loc+1] ...
224d3e5e739b5b08dc380a161f9bba14e6915771
36,812
def parse_bits_transmission( bits: list[str], pos: int = 0, indent: int = 0 ) -> tuple[int, int]: """Parse a message accoring to the Buoyancy Interchange Transmission System (BITS) Args: bits (list[str]): message in binary representation pos (int): current position in the bit stream ...
30c05c10b3529b70db61dde81b11f44eeec43e4c
36,813
def get_pixel_neighbors(height, width): """ Estimate the 4 neighbors of every pixel in an image :param height: image height :param width: image width :return: pixel index - neighbor index lists """ pix_id = [] neighbor_id = [] for i in range(height): for j in range(width): ...
3e49081fdc59ff2b0df54b84e0cf8c5983ec7b2c
36,814
def parse_copy_running_config_startup_config(raw_result): """ Parse the 'copy running-config startup-config' command raw output. :param str raw_result: copy running-config startup-config raw result string. :rtype: dict :return: The parsed result of the copy running-config startup-config: ...
01bba91527d64e32dc4eabe08de791e45b1c2040
36,815
def make_bson(obj): """Given a Python (JSON compatible) dictionary, returns a BSON string. (This hijacks the Python -> BSON conversion code from pymongo, which is needed for converting queries. Perhaps this dependency can be removed in a later version.) :param obj: object to be encoded as BS...
1b8e862280b3287377fe1cc95d7e28f618fc90a9
36,816
from typing import Optional from typing import Union import json def plot_hail_file_metadata( t_path: str, ) -> Optional[Union[Grid, Tabs, bokeh.plotting.Figure]]: """ Takes path to hail Table or MatrixTable (gs://bucket/path/hail.mt), outputs Grid or Tabs, respectively. Or if an unordered Table is pr...
e3158b525a9f632efa2c592ec4ae802c075bad52
36,817
import os def load_values_from_environment(prefix="", overrides=None): """Reads values from the environment. If ``prefix`` is a non-empty string, only environment variables with the given prefix will be returned. The prefix, if given, will be stripped from any returned keys. If ``overrides`` is ...
95e8b0714cb52faeb0e380222e6a539b33a8cdc7
36,818
def get_user_details(request): """ DataHub account registration form for social accounts. Gives new users a chance to choose a DataHub username and set their email address. Called by the Python Social Auth pipeline's get_user_details step. For more details, look for pipeline.py and the SOCIAL_...
297fa9a15bd9671c827261157118f5fc6d722a96
36,819
import logging import os from datetime import datetime import platform import errno def build_results_dir(params): """ function to create the final result directory for a job/test. Intent is to make backwards compatible with Gazebo. """ logger = logging.getLogger('pav.runjob.build_results_dir') ...
ec61c9dbb4e2f2183485cf4b5c353fa2b418c9e6
36,820
from typing import Optional def _cqv( data: NumArrayLike, ndigits: Optional[int] = 4, interpolation: Optional[str] = "linear", multiplier: Optional[int] = 1, ) -> float: """Internal function to calculate cqv.""" # ------------------- convert data to pandas.core.series.Series ------------------...
179b9060152851c9a898aa70ce4d8a68f13b11a2
36,821
def GetCulpritsForFailures(failures): """Gets culprits for the requested failures. Args: failures (list of AtomicFailures) Returns: (list of findit_result.Culprit) """ culprit_keys = set([ failure.culprit_commit_key for failure in failures if failure and failure.culprit_commit_key ...
7fc5270c687a0056f6a61d5fea09efdc529ef2d5
36,822
from typing import Optional from typing import Dict def get_object_perms(obj: models.Model, user: Optional[User] = None) -> Dict: """Return permissions for given object in Resolwe specific format. Function returns permissions for given object ``obj`` in following format:: { "type": "gr...
3aca9eacb250086dc449fad41d570f958ad71655
36,823
def fixed_from_old_hindu_lunar(l_date): """Return fixed date corresponding to Old Hindu lunar date l_date.""" year = old_hindu_lunar_year(l_date) month = old_hindu_lunar_month(l_date) leap = old_hindu_lunar_leap(l_date) day = old_hindu_lunar_day(l_date) mina = ((12 * year) - 1) * ARYA_SOLAR...
b9dc05384d1e92ba55bec1b6b4e373122bf76fcc
36,824
def get_zrand_mask(zrand, percentile=95): """ Calculates stable regions of `zrand` based on `percentile` Parameters ---------- zrand : (C, K, M) array_like Local similarity of clustering solutions in SNF parameter space percentile : [0, 100] float, optional Percentile of `zrand`...
6e41367c27d4159497d57089c1feee01b45b20ca
36,825
def remove_small_areas(img, min_area): """ Segmenta uma imagem em várias regiões com propriedades em comum e gera uma imagem resultado, deixando de fora todas as regiões que possuam areas menores do que o limiar passado. Esse processo é realizado para remover áreas pequenas (no geral...
4cc7d7120e35317e6b077c4500c1eb3580887b6d
36,826
def show_pages(parser, token): """ Show page links. Usage:: {% show_pages %} It is only a shortcut for:: {% get_pages %} {{ pages }} You can set *ENDLESS_PAGINATION_PAGE_LIST_CALLABLE* in your settings.py as a callable used to customize the pages that are displayed. ...
b412602108544c4560b757807317f043c36619e7
36,827
from image import is_b64 import logging def check_file(file, direction): """ Validate a user input This function ensures that the user enters a valid file list where the list contains a non-empty filename, b64 image, and a valid processing steps array. Args: direction (str): either "uplo...
a22ded240f771a98efc0d613b851dcc84bd95c03
36,828
from typing import Counter def check_valid_solution(solution, graph): """Check that the solution is valid: every path is visited exactly once.""" expected = Counter( i for (i, _) in graph.iter_starts_with_index() if i < graph.get_disjoint(i) ) actual = Counter( min(i, graph.get...
ec22134973153605b3a9b7a2ac7f180ffe55f97e
36,829
import copy def filter_props(props): """Filter props from the Component arguments to exclude: - Those without a "type" or a "flowType" field - Those with arg.type.name in {'func', 'symbol', 'instanceOf'} Parameters ---------- props: dict Dictionary with {propName: propMetadata}...
df2dad9d174702e40d2410fba2cc2b21b05ddfd3
36,830
import numpy def sqr_ts(timeseries, nodata=-9999): """sqr - Interquaritle range (IQR) It computes the interquaritle range of the time series. :param timeseries: Your time series. :type timeseries: numpy.ndarray :param nodata: nodata of the time series. Default is -9999. :type nodata: int ...
21e98734dfa95036cc6194ac253c1cb2eb275d25
36,831
import argparse def parse_args(cloud_args=None): """parameters""" parser = argparse.ArgumentParser('mindspore classification training') parser.add_argument('--platform', type=str, default='Ascend', choices=('Ascend', 'GPU'), help='run platform') # dataset related parser.add_argument('--data_dir',...
02336100602fb4dd21d6e33760d5fca2afe699e5
36,832
from typing import Union from typing import Collection def to_shape(data: Union[Collection, Tensor], add_batch=False, exact_shape=True) -> Union[Collection, Tensor]: """Compute the shape of tensors within a collection of `data`recursively. This method can be used with Numpy data: ```python data = {"x...
00693cd854252805dcbef7ee9ba85c804a896166
36,833
def Color(colorname): """pygame.color.Color(colorname) -> RGBA Get RGB values from common color names The color name can be the name of a common english color, or a "web" style color in the form of 0xFF00FF. The english color names are defined by the standard 'rgb' colors for X11. ...
ef553c482014d9e2275d5ae64016cbb27e34272b
36,834
from typing import List from typing import Union def _create_output(sdfg: SDFG, inputs: List[UfuncInput], outputs: List[UfuncOutput], output_shape: Shape, output_dtype: Union[dtypes.typeclass, List[dtype...
1435886ecf87896e2d82d9a1425c24034d769b25
36,835
import multiprocessing def from_image_files( images_dir: str, extensions: str | tuple[str, ...] = '.jpg', selection: set[str] = set(), ) -> Statistics: """From a directory path with images, will generate the stats of all images. The statistics generated are: mean, std, max, and min. Parameter...
bc2e07891646c7bf5e49c22f7022a2f44df215e5
36,836
def _memoized_fibonacci_aux(n: int, memo: dict) -> int: """Auxiliary function of memoized_fibonacci.""" if n == 0 or n == 1: return n if n not in memo: memo[n] = _memoized_fibonacci_aux(n - 1, memo) + \ _memoized_fibonacci_aux(n - 2, memo) return memo[n]
9a6d8646139d6ae9f6f63d2e990545fd088407eb
36,837
import logging def make_app(table_size, update_size, update_rate): """Create a Tornado application for the webserver.""" MANAGER.host_table("table", TABLE) MANAGER.host_view("view", VIEW) if table_size is not None and TABLE.size() < table_size: current_size = TABLE.size() while curre...
f4670831d6a8dfc8afa232b6198988a2babad2e3
36,838
import nibabel as nib def get_scan_info(in_file): """ Get useful scan-parameters. Function to extract some useful scan-parameters. Parameters ---------- in_file : str Path to (functional!) nifti-image Returns ------- TR : float Time-to-repetition of file """ ...
dde7b2bfcbeee7bccddef8678f717b2f40b5c4df
36,839
def merge_sort(array_of_numbers): """ This should split the array into single numbers and then recombine the list into a single sorted list in a recursive way. :param array_of_numbers: :return: """ length = len(array_of_numbers) split = int(length/2) if length <= 1: return ...
4fb90843689bb213b5dfa0460e99126c9aa16778
36,840
import socket def select_random_ports(n): """Selects and return n random ports that are available.""" ports = [] for i in xrange(n): sock = socket.socket() sock.bind(('', 0)) while sock.getsockname()[1] in _random_ports: sock.close() sock = socket.socket() ...
93145b58e6ecce60da9ae96527ca8e61c794f7ed
36,841
import argparse import ast def parse_args(): """init.""" # yapf: disable parser = argparse.ArgumentParser() model_g = ArgumentGroup(parser, "model", "model configuration and paths.") model_g.add_arg("bert_config_path", str, "data/cased_L-24_H-1024_A-16/bert_config.json", "Path...
c25345de4e8a2a4f11243ecc76eb2900dfb3436e
36,842
def choose_targets(label_dic_set, m, label_dic, source_label): """ This differs from random.sample which can return repeated elements if seq holds repeated elements. """ #global count1 #global count2 targets = set() if len(label_dic_set[source_label]) > m: #print(1) whil...
e350ab8c504d59f3a1db8a9977924c4ad3ba96af
36,843
def sinkhorn(C, log_w_p, log_w_q, key, alpha=0.01): """Uses sinkhorn iterations to solve an optimal transport problem. Computes the optimal cost and transport plan for moving mass from an atomic measure p to another atomic measure q. Args: C: The cost matrix, C_ij contains the cost of moving mass from the...
f1796ce1c2fe347cf24e81bf121a0ad4d9e6193d
36,844
def string_count_words(string: str) -> dict: """Count occurrences of individual words in a given string This function counts occurrences of each separate words. It returns a dictionary, in wich keys correspond to words and values to the number of occurrences. Args: string (str): String for the countin...
cd51101a33fb4fd4c8488718549362fa25ebb360
36,845
import torch def compute_class_freqs(labels): """ https://www.kaggle.com/eugennekhai/chest-x-ray-pytorch-lightning-densnet121 Compute positive and negative frequences for each class. Args: labels (np.array): matrix of labels, size (num_examples, num_classes) Returns: positive_freq...
94915525c138038c20093e3f5c6499383e293369
36,846
def cayley_menger_analysis(vertices, d = 2): """ Determines volume and circumradius for a tetrahedron given the vertices https://westy31.home.xs4all.nl/Circumsphere/ncircumsphere.htm#Coxeter """ if d == 3: cm_matrix = np.array([[0, 1, 1, 1, 1], [1, 0, distance.sqeuclidean(vertices[0], vertic...
794d387adf8bafdba0e4b81aa9635069335da62a
36,847
from pathlib import Path import os def module_dir_path(request): """Assure a directory exists in this module. The directory name is given by the environment variable combining the module name and "_DIR". For example, module test_foo.py will use the environment variable named TEST_FOO_DIR. Return...
f1debd9ee663c1be2165e229e76aa360e9dd03dc
36,848
async def async_setup_entry(hass, entry): """Set up a bridge for a config entry.""" await async_setup_bridge(hass, entry.data['host'], username=entry.data['username']) return True
de649b60ec38c85807860c9e64c46c6f9019d25f
36,849
import os def find_test_pack_root(): """Walks upward from the current directory until it finds a directory containing .stbt.conf """ root = os.getcwd() # This gets the toplevel in a cross-platform manner "/" on UNIX and # (typically) "c:\" on Windows: toplevel = os.path.abspath(os.sep) ...
456e46db25b888395e4f2e4b9b5146594d9a9a97
36,850
def make_non_parallel_copy(model): """Make a non-data-parallel copy of the provided model. torch.nn.DataParallel instances are removed. """ def replace_data_parallel(container): for name, module in container.named_children(): if isinstance(module, nn.DataParallel): ...
2a82494a6b6ef3ac8ca08bd210d3ae2c95a9b9e4
36,851
from re import T from typing import Callable def from_dependent_matroid(matroid: tuple[set[T], list[set[T]]]) -> Callable[[set[T]], int]: """Construct a nulity function from a matroid defined by dependent sets. Args: matroid (tuple[set[T], list[set[T]]]): A matroid defined by dependent sets. Ret...
b449d8d260fe4ec3dd684266c8f990cdc9872309
36,852
def convolve(image, psf, return_Fourier=False): """ Convolves given image by psf. Args: image: a JAX array of size [nx, ny], either in real or Fourier space. psf: a JAX array, must have same shape as image. return_Fourier: whether to return the real or Fourier image. Returns: The resampled kimage...
02010e1f0a39a412ac11ff62c5990218334a93ec
36,853
def read_csv(file: PATH_TYPE) -> pd.DataFrame: """A wrapper for ``pd.read_csv`` which tries to handle errors gracefully. Args: file: The CSV file to read. Returns: A ``DataFrame`` containing the contents of the file. """ try: return pd.read_csv(file, encoding="utf-8") e...
0cb4a2840d0f1718759356705149aa0025db6baa
36,854
def tfm_shear(x_angle=0.0, y_angle=0.0, shape=(0, 0)): """ Generate a shear transformation matrix. :param x_angle: The angle to shear the image in horizontal direction :param y_angle: The angle to shear the image in vertical direction :param shape: The shape of the image to be transformed :retu...
28614a617791142a9955495827a76f957b08ff46
36,855
import subprocess import tempfile import os import pathlib def run_pytype(code: str, check: bool) -> subprocess.CompletedProcess: # pylint: disable=g-doc-args """Runs pytype on the specified code. Raises: subprocess.CalledProcessError if check=True and pytype return is non-zero Returns: A subprocess....
70a9ffe16ae2d205f58046ffbb4fcaba74bfaf26
36,856
def _load(handler_obj): """ Load an :class:`.IHandler` handler object. The handler_obj.load_type() defines whether :func:`._load_module_function` or :func:`._load_module_class` is to be used. """ if handler_obj.load_type() == "function": return _load_module_function(handler_obj) ...
57b207125c7be45b979f0c9a84722382b8078782
36,857
def comp_ac_fft_middlepad(data): """Compute auto-correlations from binned data (without normalization). Uses FFT after zero-padding the time-series in the middle. Parameters ----------- data : nd array time-series from binned data (numTrials * numBin). Returns ------- a...
6bef88dd15e24e9d74654b8c407888066dd7efe5
36,858
import os import json def get_sagemaker_resource_config(): """ Returns JSON for config if training job is running on SageMaker else None """ cluster_config = None sm_config_path = '/opt/ml/input/config/resourceconfig.json' if os.path.exists(sm_config_path): with open(sm_config_path) as...
5faf1d0ca27c0fe0fe6bbdfdbf731c68cede7e06
36,859
def get_mod_for_key(keycode): """ Finds the modifier that is mapped to the given keycode. This may be useful when analyzing key press events. :type keycode: int :return: A modifier identifier. :rtype: xcb.xproto.ModMask """ return __keysmods.get(keycode, 0)
b65e81d2ace36547b799b680e7756f61fcc3118c
36,860
from typing import List from typing import Dict from typing import Any def remove_delay_fault(virtual_service_name: str, routes: List[Dict[str, str]], ns: str = "default", version: str = "networking.istio.io/v1alpha3", configu...
da0a10d6b2316cb1c2aa2fa777e87f3dc592cb8a
36,861
def set_lm_labels(dataset, vocab, stm_lex, stm_win=3): """ set labels of bi-directional language modeling and sentiment-aware language modeling :param dataset: dataset :param vocab: vocabulary :param stm_lex: sentiment lexicon :param stm_win: window size (i.e., length) of sentiment context :...
ec87003f9f427c5de5ea969f7040f7f10d49c3ea
36,862
def pad_sequences(sequences, pad_func, maxlen = None): """ Similar to keras.preprocessing.sequence.pad_sequence but using Sample as higher level abstraction. pad_func is a pad class generator. """ ret = [] # Determine the maxlen max_value = max(map(len, sequences)) if maxlen is None...
5879ab8f8df7477b9d73c87b6c8065fcc43a66df
36,863
def update(event, context): """ Runs on Stack Update """ physical_resource_id = event['PhysicalResourceId'] if event.get('ResourceType') == 'Custom::CWEventPermissions': cwe = CWEventPermissions(event, logger) logger.info("Updating CW Event Bus Policy - CR Router") response =...
afca288f444ebd7acd2442d0178496b144528c8f
36,864
def measure_arbitrary_sequence(qubits, sequence=None, sequence_function=None, sequence_args=None, drive='timedomain', label=None, detector_function=None, df_kwargs=None, sweep_function=awg_swf.SegmentHardSweep, ...
b03a12875c070dbfb16e987307cf89444b57ea19
36,865
def LoadAnnotation( seg_path, prefix=None, label_map=None, reduce_zero_label=False, imdecode_backend='pillow', file_client: FileClient = FileClient(backend='disk'), ): """Load annotations for semantic segmentation. **Args**: - reduce_zero_label (bool): Wh...
7dffe11c98a60ab10e7786cdb1be36e3b830b0d8
36,866
def random_translate(img, streering_angle, range_x, range_y): """ Randomly shift the image virtially and horizontally (translation). """ trans_x = range_x * (np.random.rand() - 0.5) trans_y = range_y * (np.random.rand() - 0.5) streering_angle += trans_x * 0.002 trans_m = np.float32([[1, 0, ...
1ca533617da950657e4d8b1dbd6c681e381d2e1a
36,867
def read_input_data(filename, arguments): """ Reads single input data :param filename: relative path to file :param arguments: image resize :return: left image, right image """ cv_image = cv2.imread(filename) if cv_image is None: raise RuntimeError(f"Unable to open {filename}"...
4857314f6b5ad682ef09a09aa5b567987d2d1aec
36,868
import uuid def get_uuid4(): """ make a random UUID """ s = uuid.uuid4() return str(s)
9643fb712c2181fbba4fabc36b61eecfa42a3dfd
36,869
from typing import Union def black76_vega(F: float, K: Union[float, np.ndarray], vol: Union[float, np.ndarray], disc: float, T: float) -> Union[float, np.ndarray]: """ Vega(s) for strike(s) :param F: float, forward price :param K: flo...
61d10ce1adcdd8478ea789e1e7e2291d900fafba
36,870
def replace_greek_uni(s): """Replace Greek spelled out letters with their unicode character.""" for greek_uni, greek_spelled_out in greek_alphabet.items(): s = s.replace(greek_spelled_out, greek_uni) return s
998d97421d3503de890cdccf60e32ae5e3ddba92
36,871
import torch def load_GG2_images(images): """ Normalizes images and upscales them """ images = [fits.open(file, memmap=False)[0].data for file in images] images = [torch.from_numpy(x.byteswap().newbyteorder()) for x in images] #Normailze normalize = [3.5239e+10, 1.5327e+09, 1.8903e+09, ...
eb50450c64748afcb043d7e0a779b5be03f9c4d4
36,872
def index(): """Main page""" return render_template('landing.html')
de60270e90eea3f42435a9c16ff0326545964b83
36,873
def has_computed_fields(context, obj): """ Return a boolean value indicating if an object's content type has associated computed fields. """ content_type = ContentType.objects.get_for_model(obj) return ComputedField.objects.filter(content_type=content_type).exists()
a820f164ba021a3b61fdb200c941cfbb1cb9aa42
36,874
from typing import Optional from typing import List from typing import Tuple def _prepare_dataframes( forecast_df: DataFrame, truth_df: DataFrame, percentiles: Optional[List[float]] = None, experiment: Optional[str] = None, ) -> Tuple[DataFrame, DataFrame]: """Prepare dataframes for conversion to ...
56b9c024e9b87f22be31d33ba0151545534e4901
36,875
def contour_and_point_distance(point): """ A reusable function that preloads a point and then calculates the distance to a given contour. :param point: an (x,y) tuple point :return: """ return partial(geometry.distance_between_points, point)
da821b2c704e5aeb65719fce95a77e890c8e7f07
36,876
def replace_codepoints(text: str) -> str: """ Replaces Unicode codepoints in a string with the corresponding glyphs. Multiple codepoints can be specified in the same string. Characters which are not part of codepoint annotation are kept. @param text: The text with codepoint annotations to be repla...
d55a608153e8873ef472403110d6534d919e6853
36,877
def grid2grid1D(f1, boxsize, ngridout, origin=0., originout=0., boxsizeout=None): """Remaps a dataset defined on 2D cartesian grid onto a new 2D cartesian grid. Parameters ---------- f1 : array The values of the 2D grid pixels. boxsize : float Box size. ngridout : int Gr...
51ba20f50f689703043d1eb05761c1b6d07de95e
36,878
def get_all_user_feedback(request): """ Returns a list of all the feedbacks for a given user :param request: :return: 200 successful """ feedbacks = Feedback.objects.filter(user=request.user).order_by('-created') serializer = FeedbackSerializer(feedbacks, many=True) return Response(seria...
853dd1a29ade3b0874815be9074471aadda6c86f
36,879
from re import T def atom(env, args): """Atom has the value of 't' or 'f' according to whether its argument is an atomic symbol. Thus: (atom t) = t (atom (quote (t f))) = f """ arg = args.car().eval(env) if isinstance(arg, Symbol) or arg == F: return T return F
671ff8c71ac17bfd443523205b95e4e9f5de8694
36,880
def ad_get_user_dn_by_mail(user_mail_addr): """ 通过mail查询某个用户的完整DN :param user_mail_addr: :return: DN """ conn = __ad_connect() conn.search(BASE_DN, '(&(objectclass=person)(mail=' + user_mail_addr + '))', attributes=['distinguishedName']) user_dn = conn.entries[0]['disting...
a826929a8f3106a823279462ec1f8a2b30693b00
36,881
from typing import Union import io from typing import IO from typing import Any import yaml import sys def safe_load_yaml_with_exceptions(yaml_file: Union[io.FileIO, IO[Any]]) -> Any: """Attempts to use ruamel.yaml.safe_load on the specified file. If successful, returns the output. If not, formats a ruamel.ya...
a8449931fe521e3569fa3224963f7d71b4972c43
36,882
import collections def get_interface_config_ipv6(ip_address, ip_subnet, ip_gateway): """ Return the interface configuration parameters for all IPv6 static addressing. """ parameters = collections.OrderedDict() parameters['IPV6INIT'] = 'yes' parameters['IPV6ADDR'] = netaddr.IPNetwork('%s/%u...
deb75b75e5e806965db30717dda902efa4d07263
36,883
def show_json(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ r=show(i) if r['return']>0: return r return...
7b95ae3ab51a347d83a9038f8a1954d68290f6b7
36,884
from typing import List from typing import Dict import transformers import torch import tqdm def tokenize_jiant_dataset( tokenizer, texts: List[str], span1s: List[List[int]], span2s: List[List[int]], labels: List[str], labels_to_ids: Dict[str, int], max_seq_leng...
824473158a9dbcba3889b5467c53cd0ec3553c5d
36,885
from typing import Dict def splitLR(geom: geo.base.BaseGeometry, splitter: String_or_Ring) -> SplitGeometry: """Split a geometry into a 'left' and 'right' side using the shapely API""" left,right = [],[] split_geom = ops.split(geom, splitter) if len(split_geom)==1: raise GeometryError("splitte...
141c29677cf223dd5a2e2746685a7f850740bf5d
36,886
def view(): """Returns the ProteinViewer app view""" viewer = ProteinViewer() return viewer.view()
9d3e890c9885a0796d8bba283e5fcc7529c3f26f
36,887
def schaffer(X, Y): """constraints=100, minimum f(0,0)=0""" numer = np.square(np.sin(X**2 - Y**2)) - 0.5 denom = np.square(1.0 + (0.001*(X**2 + Y**2))) return 0.5 + (numer*(1.0/denom))
dbdd3d35476013500762df9346b24e8a5b46eef8
36,888
from pathlib import Path import os import sys import subprocess def job_install(info): """install the package defined in info""" sentinel_file = Path( "/anysnake/bioconductor/%s/%s.sentinel" % (info["name"], info["name"]) ) def do(): R_cmd = ["/anysnake/R/bin/R", "--no-save"] ...
b8f725fbd058764f45fb862f473c74c7ec844f59
36,889
def get_producer(): # pragma: no cover """Create a Kafka producer.""" producer = Producer({"bootstrap.servers": Config.INSIGHTS_KAFKA_ADDRESS, "message.timeout.ms": 1000}) return producer
6d357d2de307936cdaba38cd0e8ef805225f68ca
36,890
def infer_capture_method(tx, rx): """ Infers the capture method from the indices of transmitters and receivers. Returns: 'hmc', 'fmc', 'unsupported' Parameters ---------- tx : list One per timetrace rx : list One per timetrace Returns ------- capture_method : s...
d41f2cf3a6adf191ba092828d45eae265a8c5a81
36,891
import logging def check_function(symbol, forward=None, backward=None, grad_input_vars=None, shape=None, dtype=None, in_range=None, values=None, exclude_targets=None, only_targets=None, additional_params=None, numerical_grads=None, numerical_...
a86ab09764e91c97d289e3726d2ca169b942faa1
36,892
def SieveFilter(*args, **kwargs): """ SieveFilter(Band srcBand, Band maskBand, Band dstBand, int threshold, int connectedness=4, char ** options=None, GDALProgressFunc callback=0, void * callback_data=None) -> int """ return _gdal.SieveFilter(*args, **kwargs)
2f36ad6f6a88e57aadea2fe38b8925d66603ce49
36,893
from sys import path def rounded_corner_path(start_x, end_x, min_y, max_y): """creates a U shaped path between the start and end points.""" if start_x > end_x: return rounded_corner_path(end_x, start_x, min_y, max_y).reversed() radius = min(max_y - min_y, (end_x - start_x)/2) paths = [] #f...
119ed6d02496d5afd90079f5bded82e1a2f9042a
36,894
def desc(col): """Sort by `col` descending.""" return Descending(col)
0979d5628be8647ca8f1414f78150b42992542a2
36,895
def compare_names(tag, name, tagname=None): """Compare a tag against a filename and return if they're the same Common substitutions will be tried. Dates will only require the minimum provided data to match """ if tagname in DATE_TAGS: return Date.parse(tag) == Date.parse(name) is not None ...
a61e1c98d0098ed71a31b2a48f046c934f15f284
36,896
import re def clean_text(text: str, remove_punctuation=False) -> str: """Cleans the inputted text based on the rules given in the comments. Code taken from: https://github.com/kk7nc/Text_Classification/ Args: text (str): the text to be cleaned remove_punctuation (bool): whether to remove ...
0f666041724315696924808c335c0110b7ffc158
36,897
def doc(obj=None, itm=None, docs=None, prefix=None): """Python IVI documentation generator""" st = "" # add a dot to prefix when needed if prefix is None or len(prefix) == 0: prefix = '' elif not prefix[-1] == '.': prefix += '.' # if something passed in docs, iterate ov...
aa5652169f5864fdcecc12a53b964c8e0488186b
36,898
def buscaNumQueries(): """ Pela leitura do arquivo de configuração config.ini, retorna o número de queries configuradas. :return número de consultas cadastradas no arquivo de configuração """ # Cria um set com as queries registradas no arquivo de configuração queries = set() contador...
0b2da81aa7eb8490e3556598982f601802bcf8d4
36,899