content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def delete_partitions(rt_info, partitions): """ 删除指定分区 :param rt_info: rt的字段和配置信息 :param partitions: 分区值集合 :return: 执行结果 """ params = construct_connect_config(rt_info) params[DELETE_PARTITION] = partitions rsp = DataHubApi.iceberg_delete_partitions.create(params) if not rsp.is_s...
91c827f9b3e45fcc6bba3c9a17253283aefdee2c
71,900
def jucesp_simple_driver(): """ # Fazendo DEFIS # Driver que armazena perfil e recebi caminho para download :return: o driver. """ # __padrao = profile_path # o try já tá dentro de replace chrome_options = Options() # chrome_options.add_argument("--headless") chrome_options.a...
77160587e1821b5a4db73cadf689e82f293df892
71,901
def generate_uncrypted_record(timestamp, input_template_text, key): """Generates formatted individual record and returns the iv and the record as a tuple. Keyword arguments: timestamp -- the timestamp for the record input_template_text -- the input template text key -- the key for the id plaint...
98cc6afebc732045078e2bae461e29b9016c6cf6
71,902
import os def main(): """Script entry point.""" stop_at = 80 * 1000 * 1000 prefix = 'simple' # noinspection PyUnusedLocal experiments_very_sparse = [ Experiment('doom_curious_vs_vanilla/doom_maze_very_sparse/doom_maze_very_sparse_pre_0.0', 'A2C (no curiosity)'), Experiment('doom_s...
6e5a3f0332ae0fe059469bc5d94a487c53ed6557
71,903
def kelvin_to_fahrenheit(kelvintemp): """ Converts a numeric temperature from Kelvin degrees to Fahrenheit degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Fahrenheit temperature :raises: *TypeError* when bad argument types are provided ...
20b26915c9e32a52dad04704937e685b068bd081
71,904
import requests def _post_request(url, params, headers): """ Utilizes requests module to formulate HTTP POST request over the network :param url: String representing base URL of request :param params: String or Dictionary containing parameters :param headers: Dictionary containing headers ...
a429defc62199b3783b73d237ac7923dde78145a
71,905
import os def get_image_list(path): """ Get list of image files in given directory :param path: path of image directory :type path: str :return: list of image files :rtype: list[str] """ return sorted([f for f in os.listdir(path) if os.path.splitext(f)[1] in setting.IMAGE_...
5ee38bd2545e555fe6f6f12a3b05fbd73cc0f1a3
71,906
from typing import OrderedDict import os def _read_config(fname, arg): """Simple parser to read configuration files. """ data = OrderedDict() sec = None line_num = 0 with open(fname, 'r') as fhandle: for line in fhandle: line_num += 1 if line[0] == '[': ...
c2b4f3a5452e7f4d3a3dac55b56fbea768504751
71,907
def delete_parameter_group(name, region=None, key=None, keyid=None, profile=None): """ Delete an RDS parameter group. CLI Example: .. code-block:: bash salt myminion boto_rds.delete_parameter_group my-param-group \ region=us-east-1 """ try: conn = _get_conn(reg...
94c49786d10c2f2eee3fd5d77d040f89166f87b2
71,908
def Start(): """ Renders the Home Page """ return render_template('Start.html')
a4bb3c7f16d89afaf701a9601fe80c163d77ce6c
71,909
import random def get_fast_smallworld_graph(N, k_over_2, beta, verbose=False): """ Loop over all possibler short-range edges and add each with probability :math:`p_S`. Sample :math:`m_L` from a binomial distribution :math:`\mathcal B(N(N-1-k)/2, p_L`. For each edge m with :math:`0\leq m\leq m...
8fe43e228ec3e7ab88667e14c73c5932e4cb00bd
71,910
def derive_ionmode(spectrum_in: SpectrumType) -> SpectrumType: """Derive missing ionmode based on adduct. Some input formates (e.g. MGF files) do not always provide a correct ionmode. This function reads the adduct from the metadata and uses this to fill in the correct ionmode where missing. Param...
12e7d98bc2b9e35df67ccccc955e545c96f9b597
71,911
def channel_type(info, idx): """Get channel type Parameters ---------- info : dict Measurement info idx : int Index of channel Returns ------- type : 'grad' | 'mag' | 'eeg' | 'stim' | 'eog' | 'emg' | 'ecg' Type of channel """ kind = info['chs'][idx]['ki...
37cd3ee91e09d0c183c472ca81c8e0e703268a4c
71,912
from re import T def init_weights__(l): """ source: https://github.com/Xingyu-Lin/mbpo_pytorch/blob/main/model.py#L64 """ def truncated_normal_(w, mean=0.0, std=1.0): nn.init.normal_(w, mean=mean, std=std) while True: i = T.logical_or(w < mean - 2*std, w > mean + 2*std) ...
b3a452150010343609a73a2bd254789355adb77a
71,913
def calc_box(box,x_gap,y_gap,rotate_angle,center): """ calculate the size of the required surrounding environment for doorway segmentation box: four corners' coordinates of doorway x_gap: remained space in the vertical way y_gap: remained space in the horizontal way """ door_box = np.array([...
2265f83dd70f9a1ae08843dc66dc0b5a8df557a6
71,914
def get_dummy_img_point(contour, principal_point=None, offset=-7): """ Return an estimated position of the dummy from its contour if principal point is provided. """ M = cv.moments(contour) centroid = np.array([ M['m10']/M['m00'], M['m01']/M['m00'] ]) if principal_poi...
91bcfd4a8e7d8d658c344545228700a1c872ce1f
71,915
import os def docker_compose_files(in_docker_compose, pytestconfig): """ This fixture provides support for `cloudbuild`. By passing the command line argument `--in-docker-compose=cloudbuild`, uses `docker-compose.cloudbuild.yml`. """ dc_type = f".{in_docker_compose}" if in_docker_compose else ...
22aec9c7953955febc6ea52c5fec450b36a1d144
71,916
from typing import Callable from typing import Tuple def compute_pairwise_distances( charge: int, n_spectra: int, mz_splits: np.ndarray, process_spectrum: Callable, vectorize: Callable, precursor_tol_mass: float, precursor_tol_mode: str, n_neighbors: int, n_neighbors_ann: int, batch_si...
d6923d6e898f13ca91b432f811026abb8525ae5b
71,917
def jensen_shannon(vec1, vec2, num_features=None): """Calculate Jensen-Shannon distance between two probability distributions using `scipy.stats.entropy`. Parameters ---------- vec1 : {scipy.sparse, numpy.ndarray, list of (int, float)} Distribution vector. vec2 : {scipy.sparse, numpy.ndarra...
721c1ca1218ca5aa201af1d4e8d131424cd5d8bf
71,918
from joblib import load as joblib_load def load_extractor(extractor: str) -> BaseEstimator: """loads a custom feature extractor""" return joblib_load(f"msvc/src/features/feature_extractors/{extractor}.joblib")
1e20fad04b38eadb6874c38aca940a5fa255de99
71,919
def conv2d(x, W,strides=[1, 1, 1, 1],dilations=[1,1,1,1],padding='SAME'): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x, W, strides=strides,padding=padding)
f0919e14c948185d390eaa152a3bdce27e9f53ba
71,920
def infer_keypoint_left_right_type(left_right_types, indices): """Infers keypoint left/right type. The inferred left/right type is decided as follows: 1. If either type is UNKNOWN, returns UNKNOWN. 2. If both types are the same, returns this type. 3. If one type is CENTRAL, and the other type is LEFT or RIGH...
d0895036a088c20bbe4f88fb3af098a03922dcca
71,921
def get_length(vector): """ calculate the lengt of a 3d vector @type vector: tuple(float) | list(float) @value vector: the given 3d vector @rtype: float @return: the length of a vector is the square root of the dot product of the vector with itself """ return sqrt(get_dot_product(ve...
be3d779e9cdd8164ac4808d155702615e98d0704
71,922
from typing import Mapping def normalize_and_encode( charset: Mapping[str, bytes], value: str, field_name=None ) -> bytes: """ unicode normalize value and translate it into the datanorm charset :param charset: A mapping from string to bytes :param value: A unicode string to be translated. :pa...
a42af498157c0df5f52e4927a5ed98b02f2e192b
71,923
from typing import Optional def sqlupload_start( request: HttpRequest, pk: int, workflow: Optional[Workflow] = None, ) -> HttpResponse: """Load a data frame using a SQL connection. The four step process will populate the following dictionary with name upload_data (divided by steps in which th...
6713e6bd486fe0369e57ea0942e41ffdb3ed6b3e
71,924
def evaluate_hist_x_multi_y(x, row, bins, vals): """ Evaluate a set of values from histograms Parameters ---------- x : array_like (n) X values to interpolate at row : array_like (n) Which rows to interpolate at bins : array_like (N) X-values used for the interpolati...
93e9623e2a8eb5f106efbd0054c26dc4f2079314
71,925
def bg_trim(im): """ Function to programmatically crop card to edge. `im` is a PIL Image Object. """ # This initial crop is hacky and stupid (should just be able to set device # options) but scanner isn't 'hearing' those settings. # w,h = im.size im = im.crop((443, 0, 1242, 1200)) # ...
b5b59059aa9823cd2be385ead5cc21b135a4e24b
71,926
import torch def datasets_fn(num_features: int): """ Docs. """ X = torch.rand(int(1e4), num_features) y = torch.rand(X.shape[0]) dataset = TensorDataset(X, y) return {"train": dataset, "valid": dataset}
0b812c29928f62a7e9d431376138f337572e6af9
71,927
def handle_tags(text, keeptags, tags, filetype, previewing=False): """ Handles tags that are found in the text. Useless tags (header tags) are deleted and depending on the specifications chosen by the user, words between meaninful tags (corr, foreign) are either kept or deleted. Args: text:...
00ecd330ae86aee576301a8cb8c90e199f54a021
71,928
import csv def lastMonthsRetun(fileName): """Function taking the formatter data array and then converting it to dataFrame, with aim to find returns data we are interested in Args: fileName (String): File we want to have the data from Returns: Float : Returns sum devided by 5 """ ...
a24d5ce7704a4751f93c4b6404a42d772360d80f
71,929
import importlib import pkgutil def get_indexes(package_name): """ Gets a sorted list of migrations in a package """ package = importlib.import_module(package_name) indexes = [] for (loader, name, ispkg) in pkgutil.iter_modules(package.__path__): try: insort(indexes, int(na...
d820c910add680a625a483b20a6c21aded630aba
71,930
def get_filtered_query(must_list=None, must_not_list=None): """Get the correct query string for a boolean filter. Accept must and must_not lists. Use MatchList for generating the appropriate lists. """ bool_filter = {} if must_list: bool_filter['must'] = must_list if must_not_list: ...
2190456ad7e91239bb623f7ec3d2c460e521e36f
71,931
def _mask_tissue(image, kernel_size=(7, 7), gray_threshold=220): """Masks tissue in image. Uses gray-scaled image, as well as dilation kernels and 'gap filling' """ # Define elliptic kernel kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernel_size) # Convert rgb to gray scale for easier ...
7f901a0625efd0e7e7fa7cd3ebcf8c77e362b761
71,932
def stack2designs(old_X, new_X, old_contrasts={}, new_contrasts={}): """ Add some columns to a design matrix that has contrasts matrices already specified, adding some possibly new contrasts as well. This basically performs an np.hstack of old_X, new_X and makes sure the contrast matrices are dealt...
55a11a02c09bdbbd685a0e7e88f665945e28621f
71,933
import os import shutil def prepare_ta_directory_tree(src, dest, logger, envs): """ If dest doesn't exist, then generate a new TA directory tree. If dest exists, then merge with the new one """ output_dir = dest if not output_dir: # if not output, then all content will be print to scr...
860f44797b59caf2a2c1c838877ffd6c13353f16
71,934
def duplicate_event_files(event): """Get list of event files that have equivalent deferred events. :param event: Event to compare :type event: ServiceEvent :returns: List of event files :rtype: List[str] """ duplicates = [] for event_file, existing_event in deferred_events(): if...
76d59e96d71da34d7a596f99ac170adbafecb83e
71,935
def cluster_input(prosumer, emissions, load, PV, k, hours): """ Clustering of hourly input data into representative time periods using k-means clustering algorithm Keyword arguments: prosumer ... list of prosumer names emissions ... marginal emissions (pandas.DataFrame(index=time_steps...
32cf73f7175a140fbc08ce800deb66a028c377ef
71,936
def handle_array_input(args): """ Format any command argument that is supposed to be an array from a string to a list. parameter: (dict) args The command arguments dictionary returns: The arguments dict with field values transformed from strings to lists where necessary """ arr...
f072412936e16425d1217423c01689d8c32e3f2e
71,937
def parse_source(source): """Parse a source in the format <region>:<db-identifier> Args: source (str): The source string Returns: :class:`Source`: A Source namedtuple. """ try: region, _id = source.split(":", 1) except ValueError: raise ValueError( "...
a799392e353dedc6e34d2242143ae3212923cae0
71,938
def mat_load(path, m_dict=None): """ Load mat files. :param path: :return: """ if m_dict is None: data = sio.loadmat(path) else: data = sio.loadmat(path, m_dict) return data
ebab6c377c0d7d2fc544d5f94b4f002021454677
71,939
def internal_redirect(url, default_path): """ Redirect to the specified URL after checking that host is in the allowed hosts list :param url: URL to redirect to :param default_path: Default path to redirect to if url is unsafe """ if not is_safe_url(url, settings.ALLOWED_HOSTS): retu...
5ee3e46e46ed9a28e46ae3e741a9ffa255ec3a7d
71,940
def convert_to_letter(grade): """Convert a decimal number to letter grade""" grade = round(grade, 1) if grade >= 82.5: return 'A' elif grade >= 65: return 'B' elif grade >= 55: return 'C' elif grade >= 50: return 'D' else: return 'F'
13ce25275750e7a27e0699078a15ba551674a941
71,941
import numpy def _reorient_4d(image): """ Reorganize the data for a 4d nifti """ # print 'converting 4d image' # Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size # of the array in each direction is the same with the corresponding dire...
9159e75daef5bc65dab9a7d8c6ff0cfa35fae96c
71,942
def mask_sequence(aln, rstart, rend): """Masks quality according to changed softclips in cigarstring Args: aln (pysam.AlignedSegment): aligned read rstart (int): start of non-primer sequence rend (int): end of non-primer sequence Returns: aln (pysam.AlignedSegment): aligned...
ba351335136411e4c0dd1c55a800c9990fe3f217
71,943
import base64 def get_encid(decid): """ Generate an encrypted ID from a decrypted ID :param decid: Decrypted ID, type int :return: Encrypted ID, type str """ try: int(decid) except: raise InvalidIDException('Decrypted ID must be int-castable') # Slashes are not URL-fr...
9fd425bc8f09ade997b12d533386ef2be7c6eaa8
71,944
import os import matplotlib import matplotlib.cm as cm from mpl_toolkits.axes_grid1 import ImageGrid from mpl_toolkits.axes_grid import ImageGrid import matplotlib.pyplot as plt import nibabel as nb import numpy as np from CPAC.qc.utils import determine_start_and_end, get_spacing def make_montage_axial(overlay, under...
8d4d4d53cbda192df8691fb95df87c0013b57aea
71,945
def time_coord(cube): """ Return the variable attached to time axis. Examples -------- >>> import iris >>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/' ... 'fmrc/us_east/US_East_Forecast_Model_Run_Collection_best.ncd') >>> cube = iris.load_cube(url, 'sea_water_potent...
12a706f956846e8471d0d7f044367c77210c4486
71,946
def filter_lowpass(trace: Trace, sampling_frequency: int, cutoff: int) -> Trace: """ Apply a lowpass digital filter (Butterworth) to `trace`, given `sampling_frequency` and `cutoff` frequency. :param trace: :param sampling_frequency: :param cutoff: :return: """ return _filter_any(trace,...
47dc83a5a53f97af562eba45289b9bf52bcfbc9b
71,947
import multiprocessing def _valid_general_args(cfg, logger): """ Validates the "general" parameters of a json configuration file used for inference. :param cfg: EasyDict, json configuration file imported as dictionary :param logger: logger instance :return: EasyDict, dictionary compos...
0f78e2b905a15289730ed4252d3c7e6568d1b5fb
71,948
import re def oneliner(s) -> str: """Collapse any whitespace in stringified `s` into a single space. """ return re.sub(r"[\n ]+", " ", str(s).strip())
ed1d419b4fab8cb2deccdbc2944996ef7be28cc5
71,949
def _get_nominal_integer_dict(nominal_vals): """Convert nominal values in integers, starting at 0. Parameters: nominal_vals (pd.Series): A series. Returns: d (dict): An dictionary with numeric values. """ d = {} for val in nominal_vals: if val not in d: curre...
1005c00ea5d7033368b589d4954934e85b0e1d6e
71,950
import cgi def xml_escape(input): """Replace special characters "&", "<" and ">" to HTML-safe sequences. """ return cgi.escape(input)
87f60cdf680372761da23e64c2880ad649d5b0a6
71,951
from typing import Counter def diff_counts(values : list[int]) -> dict[int, int]: """Count the gaps between ordered elements in a list, by size.""" ordered = [0] + sorted(values) + [max(values) + 3] return Counter(j - i for i, j in zip(ordered, ordered[1:]))
897cb7fdfed85b37bd8bd7031290e34199c57574
71,952
def plot_visibility(snnames, obs_windows, dark_time, priorities=None, labeltype='index', figsize=None): """Function for plotting visibility of targets as previously determined in ztfcosmology_visibility.ipynb """ if priorities is None: priorities = np.zeros(len(snnames), dtype=int) ...
2f396fb45cc3c9526cb74e5824aca5acbce10c07
71,953
import re def find_autoxc_code_skeleton(lines,subr_lines): """ Assuming that the subroutine is of the autoxc code skeleton type find all the if-branches and return a list of all the (start,end) tuples. """ (lineno_start,lineno_end) = subr_lines ifbranches = [] line = lineno_start ifstart = -1 ...
122e5e082929451019d1689eed9f182085593daa
71,954
def get_one_prior_probability(state, segment_df, total_positions): """ Returns the number of genomics positions that are of the state """ state_df = segment_df[segment_df[3] == state] num_pos_this_state = float(sum(state_df['num_occ'])) return num_pos_this_state / float(total_positions)
157666f84d9ba6b7d236bb0f10e331e9315d9efa
71,955
def ticket_details(): """ Upon request, generate a TicketDetails object for the user's session if it does not exist, fetch the details of the requested ticket as well as its associated users by the given ticket URL using the TicketDetails get_ticket() method. Render the pop-up modal HTML with the ti...
2276f2a5b9d57667433c75bec35d1320c6a7cca9
71,956
from typing import Callable def stochastic_policy( fun: Callable[[FloatLike], FloatLike], fun_params0: randvars.RandomVariable, rng: np.random.Generator, ) -> float: """Policy returning a random action. Parameters ---------- fun : One-dimensional objective function. fun_params...
57524f09045a21b47eafe553b869e5ad98838a29
71,957
def load_whoop_data(sleep_file) -> pd.DataFrame: """ Load a Whoop daily summary CSV file and return a pandas DataFrame version of the file. Only read in a subset of columns defined by the expected_cols parameter. Args: sleep_file: file to be converted to a DataFrame. Returns: pandas DataFra...
3e124434c0694c611753136abcee399c93acc94b
71,958
import torch def conv1x1(in_planes, out_planes, stride=1, num_experts=1, binary=False, activation=torch.sigmoid, use_se=False): """1x1 convolution""" if num_experts > 1: return EBConv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False, num_experts=num...
8461c4e8be1438aeaf383b0804e4aebfa9720298
71,959
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = "Welcome to the UCSC Bus Bot. " \ "Please state the bus stop id or location to get starte...
deed05421cf8d19b88f1c1703f3bab15cf6354a2
71,960
def parse_request_query(request) -> QueryModel: """ Like atoolbox.utils.parse_request_query but simplified and with a more human readable error response. """ data = {} for k in QueryModel.__fields__.keys(): v = request.query.get(k) if v is not None: data[k] = v try: ...
62c59422610d6080d97a465b159e881746abcbec
71,961
def convert_netdict_to_pydict(dict_in): """Convert a net dictionary to a Python dictionary. Parameters ---------- dict_in : dict Net dictionary to convert. Returns ------- dict Dictionary converted to Python. """ pydict = {} for key in dict_in.Keys: pyd...
6aa9bb5ac00ff92d23ff5a449d096caad0d01c9c
71,962
def sigmoid (x, parameters): """Sigmoid function POI = A2 + (A1 - A2) / (1. + exp((x - x0) / dx)) Parameters ---------- x: float or array of floats variable parameters: dict dictionary containing 'sigmoid_A1','sigmoid_A2','sigmoid_x0', and 'sigmoid_dx' R...
bcf77e2e508800f6c4c37ec4c8c79c4bda2a6934
71,963
def heatmap_chart(df, title=""): """Plot custom confusion matrix chart.""" source = df.copy() source = source.reset_index() source = pd.melt(source, id_vars="index", value_vars=df.columns) source.columns = ["m1", "m2", "value"] base = alt.Chart(source).encode( alt.X('m1:O', title="New M...
6e6405afcbffff7159446c96ad1c87757708ac09
71,964
def server(request): """Return the server based upon the server class in the request.""" if 'production' == request.param: return ReviewBoardServer('https', 'reviews.reviewboard.org') if 'demonstration' == request.param: return DemonstrationServer() raise ValueError("invalid internal tes...
d4a485706258a032e6a069ce9cdad4671f13c141
71,965
def poolformer_s24(pretrained=False, **kwargs): """ PoolFormer-S24 model, Params: 21M """ model = _create_poolformer('poolformer_s24', pretrained=pretrained, layers=(4, 4, 12, 4), **kwargs) return model
84f255eff21b158e4826830e74e3cb8dcdfe4ae0
71,966
def laptop_history(request, id): """ View a history of password retrievals and rotations for a given laptop :param id: Primary key of laptop """ laptop = get_object_or_404(Laptop, retired=False, pk=id) password_retrievals = laptop.password_retrievals.all() password_rotations = laptop.passwo...
20908500aa5946e3e4dce7004ef57ae15efae753
71,967
import logging def make_restore_checkpoint_fn(checkpoint_path, prefix='', skip_regex=None): """Returns scaffold function to restore parameters from v1 checkpoint. Args: checkpoint_path: path of the checkpoint folder or file. Example 1: '/path/to/model_dir/' Example 2: '/path/to/model.ckpt-22500' ...
3af8013b460cd9e7f3ef0396c144723600943a73
71,968
from typing import List def binary_search(input_array: List[int], target: int): """ Given a sorted input array of integers, the function looks for a target or returns None Returns: Target index or None """ if not input_array or not target: return None left_pointer = 0 ri...
b9f389d1b31e5b95bb885bd638549f7775db207e
71,969
from datetime import datetime def _sort_by_date(time_coord): """ Private sorting function used by _file _sort_by_earliest_date() and sort_by_earl iest_date(). Args: time_coord: Cube time coordinate for each cube to be sorted by. Returns: time_origin: The time origin t...
89c52c40dd8dfa03cbe431a4db6f107b42b22e81
71,970
def preprocess_img(img): """ Preprocesses screenshot of AH for OCR. Removes details which would be needed for image matching. """ # grayscale newimg = get_grayscale(img) #cv2.imwrite("screenshots/img_9g.png",newimg) # crop newimg = newimg[175:660, 0:1920] # cv2.imwrite("screensh...
ff3348580e84e2d01069c25b46c327dd98177817
71,971
from typing import Callable import functools def aws_provider(api: str = None, name="default", should_load: Callable[[], bool] = None): """ Decorator for marking methods that create a Service instance as a ServicePlugin. Methods marked with this decorator are discoverable as a PluginSpec within the namesp...
8db109647f82fbf2fe44ccd1f4140e704f1247b6
71,972
import galsim def rotate(image, rot_center, interpolate=False, force_interpolate=False): """ Rotate an image about a point. Defaults to using numpy array operations, which means that the rotation center is rounded to the nearest half-pixel grid point. Optionally, use GalSim to rotate about arbitrary pos...
86bc0e6a651ac997cd044daac07597cc5896c066
71,973
def _parse_labels_map(labels_path): """Loads a labels map via the `label_map_util` from the TF-Models library. Args: labels_path: path to a labels map in `.pbtxt` format Returns: (category_index, class_labels), where `category_index` is a dict mapping IDs to names, and `class_l...
d737831d57f27c983ff54bb7154c26136f3f6a24
71,974
def is_superuser(view): """Allow access to the view if the requesting user is a superuser.""" return view.request.user.is_superuser
5a15433200634ca326c36bdc17acbc1ada4e6426
71,975
import os def read_mat(name): """ read .mat file :param name: dataset name :return: a dict containing adjacency matrix, nx.Graph() and its node labels """ result = dict() PATH = os.path.join('data', '{}.mat'.format(name)) matfile = sio.loadmat(PATH) result['adjacency'] = matfile['n...
f173c275ca652a85fe2c5f2a7cea24406571ce97
71,976
def _restrict_asap(func=None, backend=None, issuers=None, required=True, subject_should_match_issuer=None): """Decorator to allow endpoint-specific ASAP authorization, assuming ASAP authentication has already occurred. """ def restrict_asap_decorator(func): @wraps(func) ...
6e9496d41a5aab3c0e3aef0662c8eb3e91019a2f
71,977
import os def meta(file_dir, file_name=None, deep=1): """ 返回文件的基本信息 :param file_dir: 路径 :param file_name: 文件名称 :param deep: 深度 :return:文件信息 """ return { 'dir': file_dir, 'name': file_name, 'path': file_dir if file_name is None else os.path.join(file_dir, file_na...
d68002a864e255151fe5176bfa20c01a2f554c78
71,978
def tag_row(tag): """Format a tag table row""" return [tag.get('id'), tag.get('name'), tag.get('referenceCount', 0)]
4cd1d0991eae996a52288c6d1d9bb3bd1a368ea6
71,979
import types import numpy import pandas def hpat_pandas_series_sort_values(self, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.sort_values Limit...
31b0f49f2a8e75b0cec27a33b5969893924c96e7
71,980
def get_owner_apikey_id(): """ Get owner api key id from the config file. """ config_key = 'owner_api_key_id' try: owner_apikey_id = CONFIG.get(AUTH_SECTION, config_key) if not validators.uuid(owner_apikey_id): print_config_error_and_exit(AUTH_SECTION, 'Owner API key ID(...
9c7cac14a60b38788ef49d2103e6dd331673ef1b
71,981
import math import time def parse_cookies(target_cookie): """Deserializes single Target cookie into several individual cookies""" if not target_cookie: return {} raw_internal_cookies = get_internal_cookies(target_cookie) now_in_seconds = math.ceil(time.time()) valid_cookies = [deserialize...
33591141624a06bf37f1bc879521b5ac45e8692e
71,982
from typing import Any def get_state_from_observation(observation: Any) -> State: """ Function which given an observation returns a state :param observation: :return: """ return State( robots_data=list(observation[:len(observation) // 2]), time=observation[len(observation) // ...
95e33e884df25a6c4f00ee91dd764d886eafe05e
71,983
from typing import Iterable import ctypes def vaddg(v1: Iterable[float], v2: Iterable[float], ndim: int) -> ndarray: """ Add two n-dimensional vectors https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vaddg_c.html :param v1: First vector to be added. :param v2: Second vector to be added. :...
d87c7171e0296587d02d66e04522ff3f1c5d02e7
71,984
from typing import Any import torch import numbers def python_scalar_to_tensor(data: Any, device: torch.device = torch.device("cpu")) -> Any: """ Converts a Python scalar number to a torch tensor and places it on the given device. """ if isinstance(data, numbers.Number): data = torch.tensor([data], de...
83e4ac093a40225f9c5fe121d9b67424f258e039
71,985
def allpath(path): """ return paths """ paths = path.strip("/").split("/") for i in range(1,len(paths)): paths[i] = paths[i-1] + "/" + paths[i] return paths
8b76f70dbae41a1ae46462d0755dbb5c5c0eb4c1
71,986
def setup(hass, config): """Set up the NZBGet sensors.""" host = config[DOMAIN][CONF_HOST] port = config[DOMAIN][CONF_PORT] ssl = "s" if config[DOMAIN][CONF_SSL] else "" name = config[DOMAIN][CONF_NAME] username = config[DOMAIN].get(CONF_USERNAME) password = config[DOMAIN].get(CONF_PASSWORD...
9a1d9867ff95e724a84a3e5a9843a3a9c216f5a8
71,987
def globus_callback_authorize(request): """ TODO: This logic 'lets the auth token escape' May need to refactor this... """ code = request.GET.get('code') user_token = globus_validate_code(request) if not user_token: # Redirect out of the OAuth loop return HttpResponseRedirect...
17fdce6c846d2771d0d0b69aa44d7e1aa0eb1a74
71,988
def zoom(input, zoom, mode="nearest", blocks=(16, 16, 4), **kwargs): """scale array with nearest neighbors or linear interpolation If a float, `zoom` is the same for each axis. If a sequence, `zoom` should contain one value for each axis. """ if isinstance(zoom, (int, float)): zoom = tuple(...
299689876f03776d121f9d36256ba90adf6f404c
71,989
def calculate_null_kl(experimental_condition_list=None, filename=None): """ Calculates the smoothed null KL distribution. One of the two parameters must be non-null :param experimental_condition_list: [list] The list of treatment condition from which the null kl is to be calculated. :param filename: If ...
55ff2d73827e2a5b0140a0460ea9a4e1a9c97efe
71,990
def read_tsv(file_path): """ General method for converting a tsv into a dictionary of lists, assuming each key has an associated time series :param file_path: :return: """ headers = None header_indexes = None # Each data type will have a list data = defaultdict(list) static_data...
28f2c53c9302269fc3d3e9d34867e6845fa3c13d
71,991
def validate_actions(data): """ Validate an Action configuration dictionary, as imported from actions.yml, for example. The method returns a validated and sanitized configuration dictionary. :arg data: The configuration dictionary :rtype: dict """ # data is the ENTIRE schema... cle...
9e027ccf74d9ec2c610e237fd0b9dca9f7ac9e8b
71,992
def LIGHTNING(conf): """Get Lightning Color code from config""" return conf.get_color("colors", "color_lghtn")
08781e469c7262228904e883594e475be634816b
71,993
from re import A def ecef2lla(xyz): # TODO # [ ] make it vectorizable ? """ Function: ecef2lla(xyz) --------------------- Converts ECEF X, Y, Z coordinates to WGS-84 latitude, longitude, altitude Inputs: ------- xyz : 1x3 vector containing [X, Y, Z] coordinate O...
1b9c004c0fd0d3ffa1075e710be955c18fb33d69
71,994
from django.contrib.auth.models import User import os import sys def _get_user_workspace(app_class, user_or_request): """ Get the file workspace (directory) for the given User. Args: app_class(TethysApp): tethys app user_or_request(User or HttpRequest): User or request object. Returns: ...
1d70f36c11a606afb148aa4d53684f5fb7142c24
71,995
def process_ordinal(X): """ordinal numeric value preprocessing.""" # missing value imputation X = median_impute(X, strategy='median') # remove any low info columns (high variance) X = remove_low_info(X) # remove low variance variables X = remove_low_variance(X) # scaling X = scale...
9e144dc6e1e2e145feda80a94ac493acdf44522a
71,996
def devname_from_index(if_index): """Return Windows adapter name for given Windows interface index""" return ifaces.devname_from_index(if_index)
69b5ef2a33451ca755a8388fad5de3fcac0e60d2
71,997
import io import locale def purchase_order_pdf(request, pk): """ Función para imprimir la orden de ventas """ response = HttpResponse(content_type='application/pdf') pdf_name = _("purchase_order.pdf") response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name # Los productos de la...
6d5be05cfbc32aecb904c724fa406371e822e5c2
71,998
def chrxor(st1, st2, strf1, ar1, strf2, ar2, fun1, fun2): """Takes two strings and applies a function to each charater in the string. Function is some function that takes characters and turns them into integers. This could be something to turn them into ascii order, or simply map them to another range of integers....
d463e21e55bf41ce9dee612d77810c2000210477
71,999