content
stringlengths
22
815k
id
int64
0
4.91M
def getListProjectsInGroup(config, grp): """ Get list of issue in group """ print("Retrieve project of group: %s " % grp.name) data = None __prjLst = gitlabProjectList(grp) if (DUMMY_DATA): testFile = getFullFilePath(ISSUES_GRP_TEST_FILE) with open (testFile, 'rt') as f: ...
16,400
def group_naptan_datatypes(gdf, naptan_column='LocalityName'): """[summary] groups together naptan datasets into subsets that are grouped by the given naptan column. Args: gdf ([type]): [description] naptan_column (str, optional): [description]. Defaults to 'LocalityName'. Returns: ...
16,401
def test_dataview_delitem(): """Test that table.data can be indexed like a numpy array.""" input = _TABLE_DATA["dict"] table = Table(value=input) row_keys = table.keys("row") # also demoing keys views col_keys = table.keys("column") # also demoing keys views assert list(row_keys) == ["r1", "r2...
16,402
def plot_paper(altitudes, S_hat, world_shape, fileName=""): """ Plots for NIPS paper Parameters ---------- altitudes: np.array True value of the altitudes of the map S_hat: np.array Safe and ergodic set world_shape: tuple Size of the grid world (rows, columns) fil...
16,403
def get_facts_by_name_and_value(api_url=None, fact_name=None, fact_value=None, verify=False, cert=list()): """ Returns facts by name and value :param api_url: Base PuppetDB API url :param fact_name: Name of fact :param fact_value: Value of fact """ return utils._make_api_request(api_url, '...
16,404
def produce_phase(pipeline_run): """Produce result with Produce phase data.""" scores = pipeline_run['run']['results']['scores'] if len(scores) > 1: raise ValueError('This run has more than one score!') scores = scores[0] return { 'metric': scores['metric']['metric'], 'con...
16,405
async def init_integration(hass: HomeAssistant, use_nickname=True) -> MockConfigEntry: """Set up the Mazda Connected Services integration in Home Assistant.""" get_vehicles_fixture = json.loads(load_fixture("mazda/get_vehicles.json")) if not use_nickname: get_vehicles_fixture[0].pop("nickname") ...
16,406
def get_app_domain(): """ Returns the full URL to the domain. The output from this function gets generally appended with a path string. """ url = settings.INCOMEPROPERTYEVALUATOR_APP_HTTP_PROTOCOL url += settings.INCOMEPROPERTYEVALUATOR_APP_HTTP_DOMAIN return url
16,407
def deprecated(removal_version, hint_message=None, subject=None, ensure_stderr=False): """Marks a function or method as deprecated. A removal version must be supplied and it must be greater than the current 'pantsbuild.pants' version. When choosing a removal version there is a natural tension between the code...
16,408
def prepare_comparator(comparator_path): """ Processes the comparator path from the benchmark specification. Imports the object dynamically. Parameters ---------- comparator_path : str Path to the python script file containing the comparator definition. Returns ------- ccobra.C...
16,409
def get_genes(path): """Returns a list of genes from a DE results table""" with open(path) as gene_list: gene_list = csv.reader(gene_list) gene_list = [row[0] for row in gene_list if row[0].startswith('P')] return gene_list
16,410
def process(path, ignore=[]): """calculate SET1 directory stats for given path, skipping directories mentioned in ignore (e.g. '.hg', '.svn', ...) """ if not PY3K: # unicode is critical to for non-English local names on Windows path = unicode(path) s = copy.copy(SET1) s['totalsize'] = 0 for r...
16,411
def getNoncaptureMovesForRegularPiece(theGame, pieceLocation): """ This returns a GameNode for every legal move of a regular piece """ moveList = [] xBoard = pieceLocation.get_x_board() yBoard = pieceLocation.get_y_board() pieceDestinationLeft = None pieceDestinationRight = None if theGame....
16,412
def _top_level_package_filenames(tarball_paths): """Transform the iterable of npm tarball paths to the top-level files contained within the package.""" paths = [] for path in tarball_paths: parts = pathlib.PurePath(path).parts if parts[0] == "package" and len(parts) == 2: paths.a...
16,413
def scale(X_train, X_test, type='MinMaxScaler', tuning_mode= True): """ This function apply Min Max or Standard scaling to a divided set of features divided as train and test data Args: The two dataframes: X_train: a pandas dataframe with features of the training window X_test: a pandas da...
16,414
def calc_positions(pl, pr, region1, region3, w, xi, t, gamma, dustFrac=0.): """ :return: tuple of positions in the following order -> Head of Rarefaction: xhd, Foot of Rarefaction: xft, Contact Discontinuity: xcd, Shock: xsh """ p1, rho1 = region1[:2] # don't need velocity ...
16,415
def spectrum_correlation_fft(tlist, y): """ Calculate the power spectrum corresponding to a two-time correlation function using FFT. Parameters ---------- tlist : *list* / *array* list/array of times :math:`t` which the correlation function is given. y : *list* / *array* l...
16,416
def accuracy(targets, predictions, weights=None): """Computes the categorical accuracy. Given a set of ground truth values and a set of predicted labels as tensors of the same shape, it returns a tensor of the same shape with 1.0 in those position where the ground truth value and the predicted one are ...
16,417
def restart_parent_process() -> None: """After enabling or disabling a plugin we must gracefully restart our server process.""" logger.info("Restarting requested from %s", os.getpid()) # Don't restart if we're running under the develop server if sys.argv[1] != "runserver": os.kill(os.getppid(), ...
16,418
def jp_author_name_normalized(name): """Construct the author name as P. Szekely.""" clean = name.replace('.',' ').replace(',',' ').replace(';', ' ') clean = asciiChars(clean, '') names = re.sub(r'\s+', ' ', clean.strip()).split(' '); last_word = names[-1] if len(last_word) == 1: # The last word is an initial...
16,419
def test_randint(): """ test randint Returns: None """ with fluid.dygraph.guard(fluid.CPUPlace()): x = paddle.tensor.randint(low=1, high=5, shape=[3, 3], seed=33) if platform.system() == "Darwin": expect = [[3, 4, 1], [2, 4, 1], [1, 2, 3]] elif platform.sy...
16,420
def plot_training_results(train_loss_list, valid_loss_list, valid_accuracy_list, epoch_num): """ This function plots the results of training the network. Inputs: train_loss_list: list of loss value on the entire training dataset. valid_loss_list: list of loss value on the entire valid...
16,421
def _write_vocabulary_to_file(model_prefix: str, voc_fname: str): """write processed vocabulary to file""" snt_vocab = _read_sentencepiece_vocab("{}.vocab".format(model_prefix)) bert_vocab = list(map(_parse_sentencepiece_token, snt_vocab)) ctrl_symbols = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"] ...
16,422
def run5(): """传入客户号,客户类型,只生成交易""" busi = ',2,2,20200222' main4()
16,423
def palette(tensor, shape, name=None, time=0.0, speed=1.0): """ Another approach to image coloration https://iquilezles.org/www/articles/palettes/palettes.htm """ if not name: return tensor channel_shape = [shape[0], shape[1], 3] p = palettes[name] offset = p["offset"] * tf.o...
16,424
def _generate_frame(drive_date, drive_number, frame, attack_type, verbose=Verbose.NORMAL): """ generates a log file corresponding to the attack frame saves it in the raw folder with the same structure as the original data, under attack/log folder Usage:: >>> generate_frame('2011_09_26', 1, 0) :param ...
16,425
def binarize_categorical_columns( input_train_df, input_test_df, categorical_columns): """Function to converting categorical features to one-hot encodings.""" # Binarize categorical columns. binarized_train_df = pd.get_dummies( input_train_df, columns=categorical_columns) binarized_test_df = pd.get_d...
16,426
def testAgentBuildCLI_whenCommandIsValidAndImageAlreadyExists_ShowsMessageAndExists(image_cleanup): """Test ostorlab agent build CLI command : Case where the command is valid. The agent container should be built. """ del image_cleanup dummy_def_yaml_file_path = Path(__file__).parent / 'assets/dummy...
16,427
def smallest_sval(X, solver='lobpcg', **kws): """ Computes the smallest singular value of a matrix using scipy.sparse.linalg.svds Parameters ---------- X: array-like solver: str Which solver to use. Must be one of ['lobpcg', 'arpack'] **kws Kws for svds Output ...
16,428
def test_load_schemes() -> None: """Test that loading schemes works""" for scheme_file in os.listdir(SCHEMES_PATH): scheme_path = os.path.join(SCHEMES_PATH, scheme_file) _ = xcodeproj.Scheme.from_file(scheme_path)
16,429
def mean_ndcg_score(u_scores, u_labels, wtype="max"): """Mean Normalize Discounted cumulative gain (NDCG) for all users. Parameters ---------- u_score : array of arrays, shape = [num_users] Each array is the predicted scores, shape = [n_samples[u]] u_label : array of arrays, shape = [num_us...
16,430
def load_genbank_features( genbank_record: SeqRecord.SeqRecord, terminus: Union[SeqFeature.FeatureLocation] = None ) -> List[GENBANK_FEATURE]: """ Parses a GenBank record and generates Bitome knowledgebase objects based on the features within the record Currently set up to cr...
16,431
def average_precision(predictions: List, targets: List, iou_threshold: float = 0.5) -> torch.Tensor: """Calculates average precision for given inputs Args: predictions (List): [Ni,5 dimensional as xmin,ymin,xmax,ymax,conf] targets (List): [Mi,4 dimensional as xmin,ymin,xmax,ymax] ...
16,432
def new_post(update: Update, context: CallbackContext) -> int: """Start the conversation, display any stored data and ask user for input.""" # init empty list to store dicts w/ info about each uploaded photo context.user_data['photos'] = [] reply_text = "Initiate conversation: new post " # if conte...
16,433
def format_residual_axis(ax, xlim=None, ylim=None, num_ticks=5, line_kws=None): """Creates a clean axis for the residual plots This method is primarily designed to make neatly formatted axes for residual axes in a plot. Parameters ---------- ax : Axis The axis to be formatted xlim,...
16,434
def _get_geometry_type_from_list( features: List, allowed_features: List[Union[Tuple, Sequence]] ) -> Tuple[str]: """ Gets the Geometry type from a List, otherwise it raises an exception. :param features: input feature as a list :return: tuple with extracted geometry types """ geometry_type...
16,435
def test_web_config(): """Test whether filabel posts a label""" filabel.web.load_config(config_path="../test/fixtures/labels.abc.cfg") assert filabel.config.config['labels'] is not None
16,436
def _create_mock_event(datastore, event_id, quantity, time_diffs=None, source_attrs=None): """ Loads in the datastore mock events that based on the given arguments. Args: datastore: An instance of MockDataStore. event_id: Desired ID for the first Event (to then be inc...
16,437
def test_binarytree_instantiate_null(): """ Can we instantiate with no intial values """ b = BinaryTree() assert isinstance(b, BinaryTree)
16,438
def save_network_to_path(interactions, path): """Save dataframe to a tab-separated file at path.""" return interactions.to_csv(path, sep='\t', index=False, na_rep=str(None))
16,439
def apply_sql( query: str, output_name: Optional[str], found: Dict[str, beam.PCollection], run: bool = True) -> Tuple[str, Union[PValue, SqlNode], SqlChain]: """Applies a SqlTransform with the given sql and queried PCollections. Args: query: The SQL query executed in the magic. output_name:...
16,440
def test_list_nmtoken_white_space_nistxml_sv_iv_list_nmtoken_white_space_1_5(mode, save_output, output_format): """ Type list/NMTOKEN is restricted by facet whiteSpace with value collapse. """ assert_bindings( schema="nistData/list/NMTOKEN/Schema+Instance/NISTSchema-SV-IV-list-NMTOKEN-whiteS...
16,441
def loadRepository(connection, sessionUrl, rxf_file_path): """ Load test repository. In case of remote IxLoadGatware, copy the repository to the remote machine first. todo: copy adjacent files to remote machine. :param connection: connection object that manages the HTTP data transfers between the client a...
16,442
def check_course_time_conflict(current_course: Course, user: NaturalPerson) -> Tuple[bool, str]: """ 检查当前选择课程的时间和已选课程是否冲突 """ selected_courses = Course.objects.activated().filter( participant_set__person=user, participant_set__status__in=[ Cours...
16,443
def update_linear_nodes(graph:Graph, qc: QuantizationConfig, fw_info: FrameworkInfo, first_op2d_node: BaseNode, second_op2d_node: BaseNode, scale_factor: np.ndarray): """ Scale the weights of ...
16,444
def or_func(a, b): """Creates a new list out of the two supplied by applying the function to each equally-positioned pair in the lists. The returned list is truncated to the length of the shorter of the two input lists""" return a or b
16,445
def json_loads( value: typing.Union[bytes, bytearray, str] ) -> typing.Union[ typing.List[typing.Dict[str, typing.Any]], typing.Dict[str, typing.Any] ]: """Practical json dumps helper function, bytes, bytearray, and str input are accepted. supports for ``orjson``, ``simplejson`. In case of orjson, ...
16,446
def execute_create_payment(client, create_payment_request): """ Create a payment. Automatically creates an NR for use. :param client: :param create_payment_request: :return: """ headers = get_test_headers() draft_nr = setup_draft_nr(client) nr_id = draft_nr.get('id') payment_ac...
16,447
def collect_contrib_features( project: 'ballet.project.Project' ) -> List[Feature]: """Collect contributed features for a project at project_root For a project ``foo``, walks modules within the ``foo.features.contrib`` subpackage. A single object that is an instance of ``ballet.Feature`` is importe...
16,448
def callwebservice(omdb_api_key, dvd_title, year=""): """ Queries OMDbapi.org for title information and parses if it's a movie or a tv series """ logging.debug("***Calling webservice with Title: " + dvd_title + " and Year: " + year) try: strurl = "http://www.omdbapi.com/?t={1}&y={2}&plot=sh...
16,449
def rect_bevel_2d(width, height, bevel) -> Verts2D: """get a rib, parameterized by the height and width of the opening""" # TODO: there's a generic bevel somewhere in here width_half = width * 0.5 height_half = height * 0.5 return np.array([ (width_half - bevel, -height_half), (wi...
16,450
def verify_token(token): """ Basic auth method """ curr_user = User.check_token(token) if token else None return curr_user is not None
16,451
def print_error(msg): """ Wrapper function to prints the msg into stderr and log-file. """ msg = 'SEUC:: [' + time.ctime() + ']' + str(msg) + '::SEUC' print(msg) log.error(msg)
16,452
def generate_test_cases(n_tests: int, min_len: int, max_len: int, min_dim: int, max_dim: int) \ -> Sequence[Sequence[int]]: """ :param n_tests: number of test to generate :param min_len: minimum number of matrices for each test case :param max_len: maximum number of matrices for each test case ...
16,453
def calc_neighbours( adata: AnnData, distance: float = None, index: bool = True, verbose: bool = True, ) -> List: """Calculate the proportion of known ligand-receptor co-expression among the neighbouring spots or within spots Parameters ---------- adata: AnnData The data object ...
16,454
def _build_tree_string( root: Optional[Node], curr_index: int, include_index: bool = False, delimiter: str = "-", ) -> Tuple[List[str], int, int, int]: """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing t...
16,455
def growth(xs, ys , x): """ growth function pre: xs,ys are arrays of known x and y values. x is a scaler or np.array of values to calculate new y values for post: return new y values """ xs = np.array(xs) ys = np.log(np.array(ys)) xy_bar = np.average(xs*ys) x_b...
16,456
def diarization_experiment(model_args, training_args, inference_args): """Experiment pipeline. Load data --> train model --> test model --> output result Args: model_args: model configurations training_args: training configurations inference_args: inference configurations """ predicted_labels =...
16,457
def remove_short_transition(transition_sites,thresh=11): """ removes transitions that are too close from others. """ if len(transition_sites) < 4: return transition_sites for i in range(len(transition_sites) - 1): forward_difference = transition_sites[i+1] - transition_sites[i] ...
16,458
def load_image(file_path): """ Load data from an image. Parameters ---------- file_path : str Path to the file. Returns ------- float 2D array. """ if "\\" in file_path: raise ValueError( "Please use a file path following the ...
16,459
def _kubectl_port_forward( service: str, namespace: str, target_port: int, local_port: Optional[int] = None ) -> Generator[int, None, None]: """Context manager which creates a kubectl port-forward process targeting a K8s service. Terminates the port-forwarding process upon exit. Args: serv...
16,460
def get_city_data(message): """ Send the data for a city to the requesting player. """ position = message["position"] city = CITIES.get(Coordinate.load(position)) LOGGER.debug(f"{current_user} loading city {city}") if city: emit("update_city", city)
16,461
def absolute_dispersion(drifters,starttime,time): """ Calculates absolute dispersion A^2, given desired current and initial time. Parameters ---------- drifters : GladDrifter instance, list, ndarray A list or numpy array of GladDrifter instances. starttime : datetime instance ...
16,462
def add_xgis_url(df: gpd.geodataframe.GeoDataFrame) -> gpd.geodataframe.GeoDataFrame: """ Adding x-gis URL which will let the user check the result :param df: gdf to use """ # Generaring url from string df.reset_index(inplace=True) # resetting index xy_tog = df[c.X].astype(str) + "," + df[c.Y]...
16,463
def get_compute_capacity_reservation_instance_shapes(availability_domain: Optional[str] = None, compartment_id: Optional[str] = None, display_name: Optional[str] = None, ...
16,464
def is_branch_or_version(string): """Tries to figure out if passed argument is branch or version. Returns 'branch', 'version', or False if deduction failed. Branch is either 'master' or something like 3.12.x; version is something like 3.12.5, optionally followed by letter (3.12.5b) for aplha/beta/ga...
16,465
def eval_regressors(regressor_factories, gen_one_data, batch_size=1, names=None): """Evaluates an iterable of regressors on some test data of size :batch_size: generated from :gen_one_data:. """ X, y = dg.BatchData.batch(gen_one_data, batch_size) return _eval_regressors(regressor_factories, X, y, na...
16,466
def beautify(): """Set reasonable defaults matplotlib. This method replaces matplotlib's default rgb/cmyk colors with the colarized colors. It also does: * re-orders the default color cycle * sets the default linewidth * replaces the defaault 'RdBu' cmap * sets the default cmap to 'RdBu' ...
16,467
def filter_xr_by_month(data: xr.DataArray, month: str) -> xr.DataArray: """ filtering xr.DataArray by input string of season :param data: :param month: such as 'JJA', 'DJF', et 'NDJF' :return: """ if isinstance(data, xr.DataArray): month = value_month_from_str(month) mask =...
16,468
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 9...
16,469
def ordered_load(stream, loader=yaml.SafeLoader, object_pairs_hook=OrderedDict): """Load YAML, preserving the ordering of all data.""" class OrderedLoader(loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return object_pairs_hook(loader.construct_pairs(...
16,470
def user_unions_clear(*args): """ user_unions_clear(map) Clear user_unions_t. @param map (C++: user_unions_t *) """ return _ida_hexrays.user_unions_clear(*args)
16,471
def heur_best_from_now(state): """ This heuristics computes the cost based in put all weight in the launch with the lowest variable cost. @param state: state to compute the cost. @return: cost """ try: return min([launch.compute_variable_cost(state.left_weight()) for launch in state.laun...
16,472
def test_get_task_status_description(task_status_code, language): """Test task status description.""" result = utils.get_task_status_description(task_status_code, language) if task_status_code == "0": assert result == "Waiting" elif task_status_code == "5": assert result == "渲染中" els...
16,473
def test_top_level_availability(make_napari_viewer): """Current viewer should be available at napari.current_viewer.""" viewer = make_napari_viewer() assert viewer == napari.current_viewer()
16,474
def get_ngram(text, ns=[1]): """ 获取文本的ngram等特征 :param text: str :return: list """ if type(ns) != list: raise RuntimeError("ns of function get_ngram() must be list!") for n in ns: if n < 1: raise RuntimeError("enum of ns must '>1'!") len_text = len(text) ...
16,475
def entropy(df): """Return Shannon Entropy for purchases of each user.""" from scipy.stats import entropy mask = df.credit_debit.eq('debit') df = df[mask] num_cats = df.auto_tag.nunique() def calc_entropy(user, num_cats): total_purchases = len(user) cat_purchases = user.groupby(...
16,476
def splitter(h): """ Splits dictionary numbers by the decimal point.""" if type(h) is dict: for k, i in h.items(): h[k] = str(i).split('.'); if type(h) is list: for n in range(0, len(h)): h[n] = splitter(h[n]) return h
16,477
def apprise_notify(apprise_cfg, title, body): """APPRISE NOTIFICATIONS :argument apprise_cfg - The full path to the apprise.yaml file title - the message title body - the main body of the message :returns nothing """ yaml_file = apprise_cfg with open(yaml_file, "r") as f: ...
16,478
def listall_comments(): """Lists rule-based labels Returns: list: A list of FileTypeComments """ return listall('comment')
16,479
def batch_iterable(iterable, n: int): """Return an iterable of batches with size n""" it = iter(iterable) for first in it: yield list(chain([first], islice(it, n-1)))
16,480
def test_empty_query(app): """Test building an empty query.""" with app.app_context(): q = RecordsSearch() assert q.to_dict()['query'] == {'match_all': {}} q = RecordsSearch.faceted_search('') assert q._s.to_dict()['query'] == {'match_all': {}} q = RecordsSearch()[10] ...
16,481
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit v...
16,482
def make_html_doc(body, root, resource_dir=None, title=None, meta=None): """Generate HTML document Parameters ---------- body : fmtxt-object FMTXT object which should be formatted into an HTML document. root : str Path to the directory in which the HTML file is going to be located. ...
16,483
def blur(img): """ :param img: :return: """ blank_img = SimpleImage.blank(img.width, img.height) for x in range(1, img.width-1): for y in range(1, img.height-1): left1_pixel = img.get_pixel(x-1, y-1) left2_pixel = img.get_pixel(x-1, y) left3_pixel = im...
16,484
def generalized_euler_solver(descr, coefs, rho0, v0, t, x, bc="periodic", num_integrator_steps=1, fix_vvx_term=True): """Solver for Euler hydro system. Builds RHS of the Euler equation Dv_t = f(...) from symbolic description. """ t_pde = np.linspace(t[0], t[-1], len(t)*num_integrator_steps) # Create...
16,485
def generate_rnr_features(in_query_stream, outfile, collection_id, cluster_id, num_rows=30, config=load_config()): """ Iterates over a labelled query stream and generates a feature file with the columns: <query_num>,<answer_id>,<fea_0>,<fea_1>,...,<fea_n>,<relevance_label> :param rnr_debug_helpers.q...
16,486
def get_theme_settings(theme): """ docutils writer will load css file. """ stylesheet = {} search_paths = [ os.path.abspath(os.path.dirname(os.path.dirname(html5_polyglot.__file__))), ] docutils_theme_path = '' for path in search_paths: if os.path.exists(os.path.join(path...
16,487
def pick_unassigned_variable(board, strategy, unassigned_heap): """ :returns: (row_index, col_index) """ if strategy == Strategies.FIRST_FOUND: return __pick_unassigned_variable_first_found(board) elif strategy == Strategies.MIN_ROW: return __pick_unassigned_variable_min_row(board) ...
16,488
def CONTAINS_INTS_FILTER(arg_value): """Only keeps int sequences or int tensors.""" return arg_value.elem_type is int or arg_value.has_int_dtypes()
16,489
def pad_renderable(renderable, offset): """ Pad a renderable, subject to a particular truncation offset. """ if offset < 0: raise Exception("invalid offset!") if offset == 0: return RenderGroup(_RULE, Padding(renderable, 1)) if offset == 1: return Padding(renderable, 1) ...
16,490
def hull_test(self): """ Perform a test run of Ilustrado with dummy DFT, on all cores of current machine. """ from matador.hull import QueryConvexHull from ilustrado.ilustrado import ArtificialSelector res_files = glob.glob(REAL_PATH + "/data/hull-KP-KSnP_pub/*.res") cursor = [res2dict(_fil...
16,491
def draw_annotation_names(frame_bgr, names): """ Writes the trackers names on the screen. """ global colors if len(names) > 0: num_names = len(names) cv2.rectangle(frame_bgr, (10, frame_bgr.shape[0] - 15 - 30 * num_names), (150, frame_bgr.shape[0] - 10), ...
16,492
def reload_doc(module, dt=None, dn=None, force=False, reset_permissions=False): """Reload Document from model (`[module]/[doctype]/[name]/[name].json`) files. :param module: Module name. :param dt: DocType name. :param dn: Document name. :param force: Reload even if `modified` timestamp matches. """ import fra...
16,493
def transform_box_coord_pseudo(H, W, box_vertices, dataset_name): """ Transform box_vertices to match the coordinate system of the attributions :param H: Desired height of image :param W: Desired width of image :param box_vertices: :param dataset_name: :param high_rez: :param scaling_fac...
16,494
def plot_a_bar(x, y, plot_cmd=plt.loglog, rec_width=0.1, # box ("rectangle") width, log scale rec_taille_fac=0.3, # notch width parameter styles={'color': 'b'}, linewidth=1, fill_color=None, # None means no fill f...
16,495
def create_api_app(global_conf, **local_conf): """Creates MainAPI application""" controllers = {} api_version = global_conf.get('api_version') if api_version == 'v2.0': controllers.update({ '/log/single': v2_logs.Logs() }) elif api_version == 'v3.0': controllers...
16,496
def gauss_4deg(x,b, ampl,cent,sigm): """ Simple 3 parameter Gaussian Args: x b (float): Floor ampl (float): Amplitude cent (float): Centroid sigm (float): sigma Returns: float or ndarray: Evaluated Gausssian """ return b + ampl*np.exp(-1.*(cent-x)**...
16,497
def get_spreads(pair, since): """Returns last recent spreads""" api_command = API_LINK + f'Spreads?pair={pair}&since={since}' resp = requests.get(api_command).json() if not resp['error']: # empty return resp return resp['error']
16,498
def _ValidateMutexOnConfigIdAndOrganization(args): """Validates that only a full resource name or split arguments are provided.""" if "/" in args.notificationConfigId: if args.organization is not None: raise InvalidNotificationConfigError( "Only provide a full resouce name " "(organiza...
16,499