content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_org_staff(org_id, user): """ Check whether user is staff of a org. """ try: ret = ccnet_threaded_rpc.is_org_staff(org_id, user) except SearpcError: ret = -1 return True if ret == 1 else False
3531c11c60b6ee240eaaa3bd21483be391a6e643
76,910
from typing import List def _check_columns_subset( *, input_list: List, reference_list: List, raise_error: bool = True ) -> bool: """ Checks if `input_list` is a subset of `reference_list`. Returns a bool, or if `raise_error` is True, raises a ValueError on a failed check. Args: input_lis...
13671c05fe9c7c5ea075e8a3ee9900d7b9054f82
76,911
def add_fits_keywords(log_message): """Process log `message` and annotate data model keywords/paths with their FITS translations if possible like: <data_models_keyword> '[' <fits_keyword> ']' """ try: return _add_fits_keywords(log_message) except Exception: # if annotation fails, just...
9f73f176c333a5232774c1e7b7ce57c1bf9c8331
76,912
def create_tree_digraph(booster, tree_index=0, show_info=None, precision=3, orientation='horizontal', **kwargs): """Create a digraph representation of specified tree. Each node in the graph represents a node in the tree. Non-leaf nodes have labels like ``Column_10 <= 875.9``, which...
e0ee3c7f63af5ba41694857656435e3e987fdf11
76,913
def linalgFit(x, y): """ Function to fit a straight line to data and estimate slope and intercept of the line and corresponding errors using linear algebra. Parameters ---------- x : ndarray X-axis data y : ndarray Y-axis data Returns ------- n...
618fc42354de37c6f5ecbe18d4788fc2922f3911
76,915
def test_backend_authentication_creates_a_user_with_id_attribute(monkeypatch, django_user_model, settings): """ If CAS_CREATE_USER_WITH_ID is True and 'id' is in the attributes, use this field to get_or_create a User. """ factory = RequestFactory() request = factory.get('/login/') request.se...
e79e9e4a7fc6a055a49f8cebe838edfd860ca228
76,916
from typing import List from typing import Mapping def _parse_array( value_expr: str, target_expr: str, ref_parts: List[str], a_type: mapry.Array, registry_exprs: Mapping[mapry.Class, str], auto_id: _AutoID, cpp: mapry.Cpp) -> str: """ Generate the code to parse an array. The code...
698d90152b6ae7fae903a15430ef4b4a9767750e
76,917
def nearest_neighbors(qreq_, Kpad_list, verbose=VERB_PIPELINE): """ Plain Nearest Neighbors Tries to load nearest neighbors from a cache instead of recomputing them. CommandLine: python -m ibeis.algo.hots.pipeline --test-nearest_neighbors python -m ibeis.algo.hots.pipeline --test-neares...
b5ae33dfc747a09801640819c23f65f46c843aa3
76,918
from typing import Union def create_extended_dataframe(original_data: Union[pd.DataFrame, str], save_path: str = None) -> pd.DataFrame: """ Creates an extended dataframe containing extra - derived - data, e.g. speeds and other pedestrians' positions :param original_data: original data as a pandas datafram...
5dcf9643ad9d4c117f6fa2f5414fe4a686f489cf
76,919
def index_error_exception_handler(e): """ Handle the index error when it occurs. For example, call list[3] when len(list) == 3. :param e: the error event :return: json containing error info """ print('index error ') return jsonify({'message': "Index Error"})
417a32a1001eac6deeef0db4806750038a760d5e
76,920
def flip_2d(arr): """ Flip a board layout (nxm becomes mxn) @param {Array} arr Rectangle layout @return {Array} Rectangle layout flipped along diagonal """ return tuple(zip(*arr[::]))
7204265236d367ef03b858560b1f2fe31f14388c
76,921
def validate_image_add_source(analysis_request_dict, api_schema): """ Validates the normalized ImageAnalysisRequest Schema (swagger.yaml) with semantic checks Raises exceptions on validation errors: BadRequest exceptions if the request has properties that don't make sense in combination or violate form...
a5e6c95090bdc8dfe3f5b9277991f687ccbd1ab0
76,922
def add_roll_joints(start_jnt, end_jnt, n=2, source_axis="X", target_axis="X"): """ Add n number of roll joints between start and end joints, that gain some proportion of the twist of the end_joint, and are parented to start_jnt .. note:: This solution will flip when driver goes past 180, ...
eeaa78dd2c3934d3ca014a320990a008af7b1ec0
76,925
from typing import List def listup_operators(graph: Graph) -> List[Operator]: """listup_nodes(graph, ignore_internal_input_bound, ignore_internal_output_bound) List up all operators in graph in order of forward computation. Args: graph (:class:`~webdnn.graph.graph.Graph`) : computation graph ...
f8615f19d353bc3dc267473af6f41c178429e642
76,926
from typing import Callable def make_data(filter_: FilterType, value: ValueType = None, *, json_serializer: Callable[[NonSerializedDataType], str] = _serialize_data) -> str: """ Make a string for callback_data field in InlineKeyboardButton. :param filter_: value to filter the callback. ...
70c554b75d343c7502d80b359191552995b6560d
76,927
def make_save_string(file_name): """ Returns a complete save string for saving a model. ====================================== Input: file_name (string) - Filename used in save string. Output: save_string (string) - Save string for specified model. """ # Filepath for s...
fb00690f4c5a4d7063220918709a8a45daa0a538
76,928
def get_graph_mark(graph): """Get the marks of a graph. Parameters ---------- graph : Graph Returns ------- map from operation to mark """ ret = _ffi_api.get_graph_mark(graph) return {x:y.value for x, y in ret.items()}
f145af6be41e900e40f07132185d7d240d626838
76,929
def sum_calculation(images, label, val=None, save=False, folder=None, default_value=None): """ Calculate sum volumes """ if not folder: folder = TEMP_FOLDER_PATH path_n = folder + 'total_' + label + '.nii' path_n = path_n.replace('label', 'tumor') if not val: val = [1]*len(images) ...
476e2860f667572075a5df70d12d418ce28ae7f3
76,930
def sync_synchronize(repository_id, user_id=None): """ Run all tasks for a repository, to be called from scheduler """ auth.s3_impersonate(user_id) s3mgr.load("sync_repository") rtable = db.sync_repository query = (rtable.deleted != True) & \ (rtable.id == repository_id) ...
f6a400b5b53c3fa662a298e86ae0bc556e2bde3f
76,931
def visualize_hexagons(hexagons, color="red", folium_map=None, weight=8, fix=True): """ hexagons is a list of hexcluster. Each hexcluster is a list of hexagons. eg. [[hex1, hex2], [hex3, hex4]] """ polylines = [] lat = [] lng = [] for hex in hexagons: polygons = h3.h3_set_to_mult...
746b5061fbfaaff300ae2055bd6dda376d830db4
76,932
def test_non_ascii(tree, rulename, from_attrib, to): # Rules containing non-printable characters. """Rule contains non-printable character in 'to' pattern.""" for t in to: for c in t: if c not in printable_characters: return False return True
af8a3955d355b79bb45c79dddd28d66f73af65b7
76,933
import collections def safe_predict_list(vis_list, model, predict=predict_2d, **kwargs): """ Predicts a list of visibilities to obtain a list of visibilities Can be used in bag.map() :param vis_list: :param model: :param predict: :param kwargs: :return: List of visibilities "...
521f0aacfb58345994021d76fd041ca6c21bdbc7
76,934
from typing import Union def load_character(name: str) -> Union[Character, None]: """Loads a previously saved character object. Args: name (str): Name of the character to load Returns: Character: The loaded Character None: A Character with `name` couldn not be found. """ ...
74079afb6cd700f25094823d272a7fbcdecdca68
76,935
import collections def normalize(arg, targettype, targetmap): """Coerce arg to targettype, optionally using targetmap to provide a conversion functions for source types.""" argtype = type(arg) if targettype is not None and argtype is not targettype: if isinstance(targettype, tuple) and \ ...
b80546d2e08cd776c31196c40a0e9c857fbeb0c2
76,936
import numpy def _kl_divergence(xs, p1, p2): """Calculate Kullback-Leibler divergence of p1 and p2, which are assumed to values of two different density functions at the given positions xs. Return divergence in nats.""" with numpy.errstate(divide='ignore', invalid='ignore'): kl = p1 * (numpy.l...
433c10350bac2f92b9aafeb61d9fe7823f763073
76,937
def randomwalk(n_steps, dim=3): """Generate a random walk in n-dimensional space by making steps of fixed size (unit length) and uniformly chosen direction. Parameters ---------- n_steps : Length of random walk, i.e. number of steps dim: positive integer Dimension of embedding ...
6b7bf5ebc0ae839c60b95219ad16f7d852488bcd
76,938
def pq_to_transform(p, q): """ convert position, quaternion to geometry_msgs/Transform Args: p (np.array): position array of [x, y, z] q (np.array): quaternion array of [x, y, z, w] Returns: transform (geometry_msgs/Transform): ROS transform of given p and q """ transform = T...
4cb28aa725b55da2858691ed03a407fa4d3c1930
76,939
def read_more(body, absolute_url, truncate_limit=120): """ This one was taken from: https://djangosnippets.org/snippets/841/ """ if '<!--more-->' in body: return body[:body.find('<!--more-->')]+'<a href="'+str(absolute_url)+'">Czytaj dalej</a>' else: return truncatewords(body, trunca...
161367b652b0f0d1cfffc0577dcc41d57d4c9944
76,940
def fraction_str(*numbers): """normalized numbers list by sum and return as str Parameters ---------- - numbers: numbers to print fractions of """ total = sum(numbers) fractions = [number / float(total) for number in numbers] return '(' + ', '.join('{:0.03f}'.format(item) for item in fr...
150a35b6cfcbf623ee91d6b9db416ec359c850d0
76,941
def _get_buildlogger_handler_info(logger_info): """ Returns the buildlogger handler information if it exists, and None otherwise. """ for handler_info in logger_info["handlers"]: handler_info = handler_info.copy() if handler_info.pop("class") == "buildlogger": return han...
9d8ef79ca2bf8fd2f7d71ac0aa5cfa8cfb7f9351
76,942
def v7_multimax(iterable): """Return a list of all maximum values. Or we could make a new list out of the given iterable and then find the max and loop over it again just as we did before """ iterable = list(iterable) max_item = max(iterable, default=None) return [ item for ...
6997aa3c7ec0cd549e25c4016d64ce32c6fa0f61
76,943
def _get_job_dir(jenkins_directory, job_name): """ Returns the directory for a job configuration file relative to the jenkins home directory. """ return jenkins_directory + '/jobs/' + job_name
b77a56efa394b4d43209b7f47da96a4f5f0ca96b
76,944
import math def make_bins(**kwargs): """ 'make_bins` computes the upper and lower bounds and midpoints of all the bins given either * `boundaries` * `boundaries_left` and `boundaries_right` * or `lb`, `ub`, and `midpoints` (`channels_per_decade` optional). :param boundaries: A list co...
f340505c9c6c316acca04a3d42094e200add66f7
76,945
def load_report(filepath='D:/mdcr.xlsx'): """ Load report from whiteRabbit to Dataframe, separate table for each sheet to acts like with a real tables :param - path to whiteRabbit report """ list = [] xls = pd.ExcelFile(filepath) sheets = xls.sheet_names for sheet in sheets: ...
4618b661a55553810d5b5d295e3129f33630ae5c
76,946
def getValuePixel(imx, pt): """ Return interpolated pixel value in an image Args: imx (numpy array): input image pt (numpy array): list of points Returns: vv (numpy array): interpolated value """ ptf = np.array(pt).flatten() if len(imx.shape) == 2: vv = cv2.getR...
7ca2d70f9fdb6d4be65da9cefae6ea25771c49c0
76,947
def get_new_position(position, move_command): """Get new position from position after move_command.""" return tuple( [value + change for value, change in zip(position, COMMAND_TO_MOVE[move_command])])
352f2a471d95eed80f2e98a3dd469cdb4a482483
76,948
import http def GetDockerDigestFromPrefix(digest): """Gets a full digest string given a potential prefix. Args: digest: The digest prefix Returns: The full digest, or the same prefix if no full digest is found. Raises: InvalidImageNameError: if the prefix supplied isn't unique. """ reposito...
36d3665265742ce711231f17d826334cb4160d0c
76,949
def check_n_levels(parsed, n): """Make sure there are n levels in parsed""" if len(parsed) == n: return True else: return False
f4040e4cf53730e61e5c06fed5dbe8f271020c6a
76,951
import re import glob def find_files(input_path, framerange=None): """ Discovers files on the filesystem. :param input_path: Path to the file sequence :param framerange: optional framerange :return: array of single file paths """ files = [] if '%' not in input_path: return [inp...
8f2818b6c8b72f344c70adee0e79ac52c2313902
76,952
def first_image_number(): """The number of the first image that has not been collected already. If all image are collected, return Nimages+1. return value: 1-based index""" filenames = all_image_filenames() exist = exist_files(filenames) & logfile_has_entries(filenames) if not all(exist): first_...
6222ac299cad57b0896a895b45357ed9a76bfabf
76,953
def add_frame(): """ 增加Web框架 :return: Json """ if request.method == "POST": frame_name = request.form.get("frame_name", None) description = request.form.get("description", None) if frame_name is None or frame_name == "": return jsonify(tag="danger", message="Fram...
64ecef3a30919ddf7d88cc2b28e63403d64c83f9
76,954
from typing import Tuple def sort_data(predictors: np.ndarray, targets: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ Sort the data - predictors and targets. :param predictors: :param targets: :return: Sorted tuple of (predictors, targets). """ assert predictors.shape[0] == targets.sha...
818a627cfad92f57226fb918c265e6c6c00aa3b3
76,955
import pathlib def _parse_requirements(path: pathlib.Path): """Read and strip comments from a requirements.txt-like file. """ lines = [line.strip() for line in path.read_text().splitlines() if line] return [line for line in lines if not line.startswith('#')]
af010076d79cca83bfbc6590b833e1bf5f68ddcd
76,956
def emulation_smart_covmat(x1, x2, gammav, returndir=False): """Return the covariance between x1 and x2 given parameter gammav.""" x1 = 1*x1.reshape(1, gammav.shape[0]-1) if x1.ndim < 1.5 else x1 x2 = 1*x2.reshape(1, gammav.shape[0]-1) if x2.ndim < 1.5 else x2 V = np.zeros([x1.shape[0], x2.shape[0]]) ...
f0a317c49e1abdde5173eccf89d58efa264875bb
76,957
def get_pod(): """Get pod record. Throws an error if you're not running in a cluster. """ config.load_incluster_config() api = client.CoreV1Api() namespace = "default" with open( "/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r" ) as f: namespace = f.readlines()...
ba931c0b4b00e3cf84ae2f64922a85d12a3333f0
76,958
def find_and_get_analytics( advertisers, analytics_object, ads_entities, get_args, level ): """ Recursive function that prints out one level of advertising entity and then calls itself to print entities at lower levels. """ entity = ads_entities[level] kind = entity["kind"] entity_list =...
65a4d253a8058b4ca32d09d1af7869151ed477bb
76,959
import json def time_series_asset_for_point(): """ .. :quickref: TimeSeries For predefined asset; Get the timeseries for a predefined EE asset, date range and a point **Example request**: .. code-block:: javascript { point: [0.0, 0.0], dateFromTimeSeries: "YYYY-MM-D...
33e8cf2d2750fdd12d5940c76ee4da9d82648c28
76,960
def get_task_assignment_details(task_assignment): """ Return various information about the specified task assignment. Args: task_assignment (orchestra.models.TaskAssignment): The specified task assignment. Returns: task_assignment_details (dict): Information abo...
45969cc528359f8f699eef5489c7d64341d26f42
76,961
def GET(request): """Get this Simulation.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'simulationId': 'int' } ) except exceptions.ParameterError as e: return Response(400, e.message) #...
5b6896f1b973a60992fdb2f21f2b298840cc1e64
76,962
def dejudder(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#dejudder""" return filter(stream, dejudder.__name__, *args, **kwargs)
484c954959436e7d3a83f6bf659caacf60ea2045
76,963
def _get_value(value): """Interpret null values and return ``None``. Return a list if the value contains a comma. """ if not value or value in ['', '.', 'NA']: return None if ',' in value: return value.split(',') return value
93fb82c586fa2db8d3130fdb6759ac0a559b89b4
76,964
def TSRindices(weights, evals): """Ns array containing participation index of mode i to TSR""" n = len(weights) Index = np.zeros((n)) norm = np.sum([weights[i] * np.abs(evals[i]) for i in range(n)]) for i in range(n): Index[i] = weights[i] * np.abs(evals[i]) Index[i] = Index[i]/norm ...
7e25b201edbc41ea0e8e0365bb511de4b4597ada
76,965
def get_possible_levels( pc, source=characters.PC_CLASSES ): """ Return a list of levels the PC qualifies for.""" pl = [] for l in source: if l.can_take_level( pc ): pl.append( l ) return pl
ca9bd101d7509774024875ae5a40448b12b09d7a
76,966
import io import uuid def generate_ids(nodes, asset_id=None): """Returns new unique ids for the given nodes. Note: This does not assign the new ids, it only generates the values. To assign new ids using this method: >>> nodes = ["a", "b", "c"] >>> for node, id in generate_ids(nodes): >>> ...
e5e763ee8dda1e53af8b149073cff050f04956c1
76,967
def _extract_generated_sources(target): """Returns (source_metadatas, includes) generated by the given target.""" transitive_depsets = [] objc_provider = _get_opt_provider(target, ObjcInfo) if hasattr(objc_provider, "source"): transitive_depsets.append(objc_provider.source) cc_info = _get_op...
e9363ad7754e62dbebcfe4d0e80e77683b74b9c2
76,968
def label_colormap(): """ colormap for visualizing bones """ return np.asarray( [[155, 122, 157], [ 45, 245, 50], [ 71, 25, 64], [231, 176, 35], [125, 249, 245], [ 32, 75, 253], [241, 31, 111], [218, 71, 252], [248, 220, 197], [ 34, 194, 198], [108, 178, 96], [ 33, 101, 119], [125, 100, ...
b259e74ad64fb29a01c798a401966df2cc9f4164
76,969
import numpy def generateRHS_gpu(field_array, surf_array, param, kernel, timing, ind0, electric_field=0): """ It generate the right hand side (RHS) for the GMRES suitable for the GPU. Arguments ---------- field_array: array, contains the Field classes of each region on the surface. surf_array...
c2619e7b0bf9829eb8bbe1e7c40a67ed795bfd5e
76,970
def MultivariateGaussianKernel(x, y, h, c=0): """ This function implements the multivariate gaussian kernel. $K(x,y|h) = \frac{1}{|h|^{1/2}(2\pi)^{d/2}}\exp{-0.5*(x-y)^T h^{-1} (x-y)}$ x,y are D dimensional random vectors. x is the sample vector the kernel is built around. ...
6d9018b019275f34bb8708105874a921c1f18185
76,971
def spatial_preprocessing(datasets, min_cells=1, min_genes=1, n_top_genes=2000, lognorm=True, hvg=True): """\ Preprocess and merge two visium datasets from different batches Parameters ---------- datasets: list, optional (default: None) The list of anndata objects from different batches min_cells: int, optio...
a3be61941d65b0470152c188ee52966817106c29
76,972
import configparser from typing import Optional def input_with_default(label: str, defaults: configparser.ConfigParser, fallback: str = "", key: Optional[str] = None) -> str: """Return the string if non empty otherwise use the default.""" key = label.replace(" ", "_") if key is None else key default = def...
1e900f2164c5ef975b16d74d39c7e587b0444fe3
76,973
def polyval(fit, points, der=0): """Evaluate polynomial generated by :func:`polyfit` on `points`. Parameters ---------- fit, points : see :func:`polyfit` der : int, optional Derivative order. Only for 1D, uses np.polyder(). Notes ----- For 1D we provide "analytic" derivatives u...
b40193914335e2f583b2f0847bc30beb46e75ab0
76,974
import torch import numpy as np def one_hot(labels, dim): """Convert label indices to one-hot vector""" batch_size = labels.size(0) out = torch.zeros(batch_size, dim) out[np.arange(batch_size), labels.long()] = 1 return out
ba7cefef066229bd578fb7cdec4f4033f353cd73
76,975
from typing import Iterable def detokenize(tokens: Iterable[str], with_treebank: bool = True) -> str: """ Given a list of tokens, join them together into a string. with_treebank = True is typically used when rendering utterances, so we don't need to deal with things like "andrew's" with_treebank =...
d6a90c5181a18fe45118b83bdf605c534ceeeac8
76,976
def pair(k1, k2): """ Cantor pairing function """ z = int(0.5 * (k1 + k2) * (k1 + k2 + 1) + k2) return z
83de1d237049ac8f76ec09f7b23037ab581792d5
76,977
from typing import Callable def make_pipeline(*funcs: Callable[[str], str]) -> Callable[[str], str]: """ Make a callable pipeline that takes a text as input, passes it through one or more functions in sequential order, then outputs a single (preprocessed) text string. This function is intended as a l...
e0e3eb8be09ebd701144a30821cbeabc10ddab9a
76,978
def set_ball_speed(dataset): """ Function to get ball speed based on the difference of horizontal and vertical positions in subsequent frames. """ #Since we don't know the previous position of the first sample, we will have one less datapoint #Velocity(T) = Position(T) - Position(T-1) speed...
0fac0023da7f933baf72d56d002f0a304120b83c
76,979
def batch_extract_embeddings(x): """Convert an audio signal to a logmel spectrogram and then into an embedding vector.""" with tf.device("GPU"): signals, rates = x["signal"], x["sample_rate"] S = audio.spectrograms(signals, rates[0]) S = audio.linear_to_mel(S, rates[0]) S = t...
bef10db40f3eff9c1f2016db9765ed48f691ac87
76,980
def _annotate_categories_with_selection(lot_slug, category_filters, cleaned_request_args, url_args_for_lot, content_manifest, framework, aggregations, keys_to_remove, search_link_builder, parent_category=None): """ Recursive setting...
6ed863726907f03473d15f4d905fc83a5aea2d9b
76,981
from datetime import datetime def get_random_date(start, end): """Generate a random datetime between `start` and `end`""" return start + datetime.timedelta( # Get a random amount of seconds between `start` and `end` seconds=randint(0, int((end - start).total_seconds())), )
bfadbd917f55f7da541617a830aab71c5b272cbe
76,982
def SSD(input_shape, num_classes): """SSD512 architecture. # Arguments input_shape: Shape of the input image, expected to be either (512, 512, 3) or (3, 512, 512)(not tested). num_classes: Number of classes including background. # References https://arxiv.org/abs/1512.02...
56513eaead6050077b95006eb0e28a65aa3f1aab
76,983
def lorenz96(t0=0.0, tmax=30.0, y0=None, num_variables=10, forcing=8.0): """Lorenz 96 system in JAX implementation.""" y0 = y0 or _lorenz96_chaotic_y0(forcing, num_variables) @jax.jit def f_lorenz96(_, y, c=forcing): A = jnp.roll(y, shift=-1) B = jnp.roll(y, shift=2) C = jnp.ro...
7167bf721eab9ddad3536e68ee9ba0092298653b
76,985
import glob def prepare_mhcii_netmhcpan(mhc_select, MS=False, with_MHC_seq=False, data_dir="./", netmhc_data_version="3.2"): """ Prepare training data of NetMHCIIpan3.2/NetMHCIIpan4.0 with test data from Prachar, M., Justesen, S., Steen-Jensen, D.B. et al. Identification and validation of 174 COVID-...
3b5ebb9961526054dff4923c73eddb0f394d9a65
76,986
import json import requests def strotimer(): """Render home page.""" try: facility_types = repo.get_facility_types() return render_flod_template( 'strotimer.html', facility_types=json.dumps(facility_types) ) except requests.exceptions.ConnectionError: ...
22aacfdea6441cac0047ce4e61830b6761f5065f
76,987
import time def greedy(g, k, p=0.1, mc=1000): """ input g: the graph you input k: number of nodes in influence maximization set p: Activation limits mc: Number of cycles of Monte Carlo output influence maximization set spread of each node time cost """ S, spread, timel...
a28de3e3d02cc0aeb835ffb43d8e6065c580aabd
76,988
def env_step(action): """ Arguments --------- action : int the action taken by the agent in the current state Returns ------- result : dict dictionary with keys {reward, state, isTerminal} containing the results of the action taken """ global windy_world, cur...
6ea4b598121a4933293e40b803230d71aa7c9644
76,989
import json def rpc_error(message = 'Invalid Request'): """ Generates an rpc error message """ return json.dumps({"result":None, 'error':{'message':message}, 'id':1})
4aa061e25be938b882cac71cb935f2153ad958cf
76,990
def homo_coordinate(g): """Transform a numpy 3D meshgrid to 3D data points in homogeneous coordinates""" axes = np.vstack(list(map(np.ravel, g))) data_points = axes.T return np.insert(data_points, 3, 1, axis=1)
476d5230d02c64dce41b416ba60327306848cc36
76,993
def gen_input_config(): """ Generates an input configuration for providing to a vault client in tests """ def _gen_input_config( vault_secrets={"acme.user": "secret/acme/server/user", "acme.pwd": "secret/acme/server/user"} ): input_config = { "acme": {"host": "https://ac...
2d238e91de03641889c0aac9a41d2284294af15d
76,995
def is_ph5_array_csv(fh): """ :type file_handle :param fh: :return: Boolean """ fh.seek(0, 0) line1 = False line2 = False length = kefx.file_len(fh) if length < 2: fh.seek(0, 0) return False head = [next(fh) for x in range(2)] for line in head: if ...
4967723e4f9f711b127c384b45cf6686a2d5a7d3
76,996
def image_to_data(image): """Generator function to convert a PIL image to 16-bit 565 RGB bytes.""" # NumPy is much faster at doing this. NumPy code provided by: # Keith (https://www.blogger.com/profile/02555547344016007163) pb = np.array(image.convert('RGB')).astype('uint16') color = ((pb[:,:,0] & 0...
880577d588b02a6910f6b04588e7cbfc788782c7
76,997
async def link( request: Request, # api_key = Depends(security), similarity_threshold: float = 0.65, body: LinkingRequest = Body(..., example=example_request), ): """Link batch of Spans to their canonical KnowledgeBase Id.""" try: nlp = request.state.nlp # app_api_key = reque...
4a1443173821bde39ceb1086efd4872e431cf84c
76,998
def pol_to_cart(r, theta, r_err=0, theta_err=0, cx=0, cy=0, astro_convention=False): """ Returns cartesian coordinates for input polar coordinates, with error propagation. Parameters ---------- r, theta : float or numpy ndarray radii and position angles to be converted t...
ff91e801031e585d0d9a52aaf362a99d82508adb
76,999
import random def d6(): """Roll a 6-sided die.""" return random.randint(1, 6)
83278951d22f8517965d6cb3ea585285ddfa160b
77,000
def save_matches_to_file(number: str, matches: dict) -> str: """Save matches for given unsig to text file and return path""" path = f"{ROOT_DIR}/data/matches_{str(number).zfill(5)}.txt" with open(path, 'w') as f: f.write(f"Matches for unsig{str(number).zfill(5)}\n") for side, assets i...
fc631b95c58536665fb6d1f4f7b430bec5786e1e
77,001
import time def scraptime(hashtags, target, total_tweets, attempts): """ Retrieve Tweets from twitter using the hashtags, target date, total tweets and attempts. Parameters ---------- hashtags : string target : string total_tweets : int attempts : int Returns ------- pd.DataF...
1fabb3082d1d1f5cc78bf84479ca334e8a3475db
77,002
import time def bigppr(digits=100): """ Randomly generate a probable prime with a given number of decimal digits """ start = time.clock() print("Working...") candidate = int(bigdec(digits)) # or use bighex if candidate & 1==0: candidate += 1 prob = 0 while True: ...
48e2510a13ba53e0ef3c1c8f3f3e827c24ea896d
77,003
def calculate_cos_solar_zenith_angle(h, lat, lon, y, m, d): """ calculate solar zenith angle :param lat: (float array) latitude [degrees] :param lon: (float array) longitude [degrees] :param y: year [int] :param m: month [int] :param d: day [int] :param h: hour [int] https://agupubs...
c5d297ba30bd8d654bffbc40369354b261302041
77,004
def _tooSoon(timestamp): """ Check if the previous transaction was too soon to start another one The delay is based on conf.TIME_INTERVAL. """ last_tx = getLastTx() if last_tx > 0 \ and timestamp - last_tx < du.secToNano(3 * conf.TIME_INTERVAL * 60): if LEDGERS[conf.QUOTE].verbo...
41fd29849d001708209718e0fbd3950e967a6f03
77,005
def both_roles_allowed(function): """ this allows both the attendant and admin to have access""" @wraps(function) @jwt_required def wrapper(*args, **kwargs): """wrapper for the function""" return function(*args, **kwargs) return wrapper
4c1cd7bb53d59e9dddc8c347515b7a190ff3c0a8
77,006
def celsius_to_fahrenheit(bot, trigger): """ Convert Celsius to Fahrenheit """ try: celsius = float(trigger.group(2)) except ValueError: bot.reply( "Could not understand input. Please input the temperature in Celsius, e.g. !fa 100" ) return False if celsius...
04cfa7b0e7b5a2b2b784dc7b1d158efe1f3dfbb2
77,007
def create_init_weights_fn(initialization_fn): """Returns a function that wraps :func:`initialization_function` and applies it to modules that have the :attr:`weight` attribute. Args: initialization_fn (callable): A function that takes in a tensor and initializes it. Returns: ...
9b8344bf86ff02181228f2bf6412d1c5e867c876
77,008
import urllib import html def list_book_info(save=False): """ Lists title, author, year author, genre and filename of each book in the Gutenberg top 100 downloaded. Parameters: save (boolean): If true, saves books .txt webpage to a .txt file locally. returns pandas dataframe with t...
3d3325730b94529231011ad89e0932257748f135
77,009
def json_schema_type(cls=None, /, *, schema=None): """Decorator to add user-defined schema definition to a class.""" def wrap(cls): return register_schema(cls, schema) # see if decorator is used as @json_schema_type or @json_schema_type() if cls is None: # called with parentheses ...
c8376646400758197d56e3c7c250eb9e200e86b4
77,011
from typing import List from typing import Tuple def _partial_trace( tensor: Tensor, labels: List, backend_obj: AbstractBackend) -> Tuple[Tensor, List, List]: """ Perform the partial trace of `tensor`. All labels appearing twice in `labels` are traced out. Args: tensor: A tensor. labels: The n...
ef08f98f73a13ac0988ff1faaa35c5db624702f4
77,012
def int64_feature_list(value): """Returns an int64_list from a bool / enum / int / uint.""" v = tf.train.Int64List(value=value) return tf.train.Feature(int64_list=v)
6f74664b34a7629771233f4f187cb5504f5f27d5
77,013
def list_insert_2(): """ insertion """ mylist = ['dog', 'lion', 'snake', 'elephant', 'cow', 'donkey', 'goat', 'duck'] mylist.insert(3, 'rabbit') return mylist
2ac2d9e0bd4ad618a53c1fece3720162aeb33933
77,014
def set_change_handler_regex(module_re, property_re, func, args = None, on_enable=False): """ Sets up a change handler on the given modules' property/ies :param module_re: Regular expression matching the module(s) on which to look for properties :type module_re: str :param property_re: Regular expre...
f26088d3a7676c630339e08d6b76f1828b9ebb62
77,015
def extract_bits(n, n_bits, offset_from_lsb): """Extract a number of bits from an integer. Example: >>> bin(extract_bits(0b1101011001111010, n_bits=5, offset_from_lsb=7)) '0b1100' 0b1101011001111010 -> 0b01100 ^^^^^<- 7 -> The bits marked with ^ will be extracted. The offset...
08a92d319975915b3b0f453144cc73cba620c5b1
77,016
from typing import Union def __jpointer_get_next_thing(next_part) -> Union[dict, list]: """ Looking at next part of pointer creates a proper object - dict or list to insert into a doc, that is being `jsonpointer.walk`ed. """ # `next_part` looks like array index like"[0]" or "-" (RFC 6901) if n...
f8b1d253dd2d82c1bc8f449083083a7e2a3fb760
77,017
import requests def get_model(name, username=None, password=None, cookies_file=None): """Get model data from Nuance Mix Website""" # Get model ID model_id = get_model_id(name, username, password, cookies_file) url = "https://developer.nuance.com/mix/nlu/api/v1/projects/{}".format(model_id) result...
1c30d1319bd0d207af03102f8602d646bf65412d
77,018