content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def buildstamp(p5_connection=None): """ Syntax: srvinfo buildstamp Description: Returns the build time-stamp of the P5 release Return Values: -On Success: The build time-stamp """ method_name = "buildstamp" return exec_nsdchat([module_name, method_name], p5_connection)
8d8c7a8ee6821fea618af2caafc765c0efca1a5d
38,419
def changeoOb(attrname, G, A, i): """change statistic for binary exogenous attribute oOb (outcome attribute related to binary attribute on same node) [*] """ return 0 if G.binattr[attrname][i] == NA_VALUE else G.binattr[attrname][i]
6b97269fe2f1490bff632868c10e03160caaf421
38,420
def is_cli_command(ctx: Context) -> bool: """ Check if command is run from CLI Args: ctx: Click context object Returns: True if run as CLI command, False otherwise """ return ctx.parent.info_name == "model-navigator"
c6121dd742e2c2a3a0c3b4b5863d73d8d0fde658
38,421
import random def is_prime_mr(n): """ Miller-Rabin primality test. A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. Source: http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python >>> is_prime_mr(2) True >>> is_pri...
48a9ea5f8708b56199cdf36dc0affe5d84c113a9
38,423
def lat_lon2point(df): """Create shapely point object of latitude and longitude.""" return Point(df['Wikipedia', 'longitude'], df['Wikipedia', 'latitude'])
f430d9532c52eb11ec05f6a2cbddd2d5600c9413
38,425
from typing import OrderedDict def _get_exp_uri(): """Return expected basic result for OpenUri action.""" return OrderedDict( ( ("@type", "OpenUri"), ("name", "Open URL"), ( "targets", [OrderedDict((("os", "default"), ("uri", "http://...
a3e527a52769083fd7adb8cf04a27ebcfc272922
38,426
def save_json(node): """Load tvm object as json string. Parameters ---------- node : Node A TVM Node object to be saved. Returns ------- json_str : str Saved json string. """ return _api_internal._save_json(node)
0c9a2b18d18bf2357a2a539f2941972dd4e810ce
38,427
import re import string def normalize_text(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r"\b(a|an|the)\b", " ", text) def white_space_fix(text): return " ".join(text.split()) def remove_punc(text): exclude = set(string.punc...
d619ed0c963997e90dc57a8fad951a4555b5c304
38,428
def computeBits(image, start, end, newName): """ Compute the bits of an image :param start: start bit :type start: int :param end: end bit :type end: int :param newName: new name for the band :type newName: str :return: A function which single argument is the image and returns a single ...
5a741e4cc8f14fa914b914bb9a237ee2768b1d76
38,429
import getpass def get_html_connector_kwargs_options_from_args(args): """Take a parsed ArgumentParser and return a dict of argument.""" if not args.password: args.password = getpass.getpass( "Please enter the password for {} with login {}:\n".format(args.url, args.login) ) retu...
d96f070363c6db33632974028b6363cbad739537
38,430
def benchmark(problems, algorithms, stop_criterion, runs=10, seeds=None): """A function to perform multiple algorithms on multiple soltions. Note that the problems, algorithms and the stop criterion all need to have the method reset method properly implemented for this function to work properly. The lo...
5ed084bf1e3fb2ba55a579e1ed5a3314721d1559
38,431
def list_huisnummers_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Huisnummer` to json. """ return { 'id': obj.id, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie ...
bcc48d753e5c51581b34d7f5f695ae1f1ae744c1
38,432
def fetch_production(zone_key, session=None, target_datetime=None, logger=None): """ Requests the last known production mix (in MW) of a given country Arguments: zone_key (optional) -- used in case a parser is able to fetch multiple countries session (optional) -- request session passed in orde...
e23234553a0da497415488e3c15e2e62b00cc779
38,433
def generate_vocab_from_token_count(token_count, max_vocab_size=1000000, min_count=0, unk_tk=UNK_TK, start_tk=START_TK, decode_tk=DECODE_TK,...
11b7fb52db85302353ffb5128ee04a2cd6958d1e
38,434
from typing import Optional from typing import Dict def timesketch_list_saved_searches( data: Optional[Text] = '') -> Dict[str, api_search.Search]: """List up all available saved searches. Args: data (str): Not used. Returns: A dict with a list of available saved searches. """ connect() stat...
c575d1c6ef6b66a371c1b3370b9f954fb2688bb5
38,435
def get_coords(gals): """ Takes list of galaxies and looks up their coordinates by name. If no name found: warn, skip, remove galaxy from list Returns: gals: list of galaxies minus those that weren't found start_coord: list of coordinates corresponding to center of g...
904405f70611b4fcc38f2f963f36b9d63dd98e6f
38,437
def yesnoquery(message): """ Displays `message` and waits for user Y/N input. Returns Boolean where true means Y. """ useryn = None while useryn is None: if not isinstance(message, str): raise ValueError("Must pass a valid string to query") useryn =...
87ec3cb01e4a2e52ce1cd900e5446cbab9a05373
38,438
def material(): """ Factory associated with PowerLaw3D. """ return PowerLaw3D()
5340bdd546d9c804a12ac0a9bbf446a4859ce2bb
38,439
def formatExtendedTraceback(exc): """Format a traceback for the given exception as a string. The traceback will include the source line of each frame, as usual, but also the values of local variables in the frames. """ return ''.join(listExtendedTraceback(exc)).rstrip('\n')
567274bd8cfef86e8070c659d470edbc5e793ade
38,440
def _normalize_ad_ts_sid(df, ndays=0, nhours=8, target_tz='utc'): """规范`asof_date`、`timestamp`、`sid` 操作: 股票代码 -> sid(int64) date(date) -> asof_date(timestamp) date(date) + ndays -> timestamp(timestamp) 确保timestamp >= asof_date """ if AD_FIELD_NAME in df.columns: ...
19fa72d33128ba4684c388db6fb1e63062c85c26
38,441
def lnLikelihoodGaussian(parameters, values, errors, weights=None): """ Calculates the total log-likelihood of an ensemble of values, with uncertainties, for a Gaussian distribution. INPUTS parameters : model parameters (see below) values : data values errors : data unc...
17d1cdf00a841fae15f9f77616bc4b6c5fdb39ce
38,443
def g(r, r_i, r_c, a, gamma): """ Non-orthogonalized radial functions """ def g_(r, r_i, r_c, a): return (r-r_i)**(2)*(r_c-r)**(a+2)*np.exp(-gamma*(r/r_c)**(1/4)) # return (r-r_i)**(5)*(r_c-r)**(a+2) r_grid = np.arange(r_i, r_c, (r_c-r_i)/1e3) N = np.sqrt(np.sum(g_(r_grid,r_i,r_...
fbfcf68470f0b8198f4697bf1079bd4009c3259d
38,444
def formatProccessingTime(ss, verbose: int = 1, estimate: bool = True, keep_seconds=False): """ Format processing time to string Args: ss: Time in seconds or a string """ if isinstance(ss, (str, bytes)): res = ss else: if ss < 0: res = '-1' elif ss < 60: ...
a2bea60365530169013322f8a767c9da3cc44c31
38,445
def lorenz(xyz, t, sigma, beta, rho): """The most famous of the strange attractors.""" x, y, z = xyz dx = sigma * (y - x) # dt dy = x * (rho - z) - y # dt dz = x * y - beta * z # dt return dx, dy, dz
4241c36b8d4b924289edaa522a49855949208327
38,446
def seq_to_array(seq, k=1, overlap=True): """Converts a DNA sequence into a Numpy vector. If :math:`k>1`, then it creates a vector of the :math:`k`-mers. Args: seq (~skbio.sequence.DNA or str): The sequence to convert. k (int, optional): The :math:`k` value to use. Defaults to 1. ov...
8a236536f85c49c8da217e8fd6b50f5f6051e64c
38,447
import copy def add_classes_to_geojson(geojson, class_map): """Add missing class_names and class_ids from label GeoJSON.""" geojson = copy.deepcopy(geojson) features = geojson['features'] for feature in features: properties = feature.get('properties', {}) if 'class_id' not in properti...
9aadf15fbe64995e7e52b2f6182e76ab722f06b5
38,448
import math def calNewGeoLocationNE(initialPOINT, yNORTH, xEAST): """ This function is used to calculate new GEO Point which is 'y' meters north and 'x' meters east of a Reference point. Knowing the lat/long of reference point and y and x distance , it returns a POINT class object with new location lat/long value...
3116856f253984dc89a6fb10889a1ac24d955072
38,449
from typing import Set from typing import Tuple def cfpq_matrix( graph: MultiDiGraph, cfg: CFG, start_nodes: Set[int] = None, final_nodes: Set[int] = None, start_var: Variable = Variable("S"), ) -> Set[Tuple[int, int]]: """ Context-Free Path Querying based on Matrix Multiplication Par...
647d7110c2bed1403e36cc0208f62849e809cbbb
38,452
from typing import Optional def filter_reg(reg: IRParam) -> Optional[Register]: """Filters a possible register object. returns None if not a register.""" if isinstance(reg, Dereference) and isinstance(reg.to, Register): return reg.to if isinstance(reg, Register): return reg return None
f39e10d08ba5265496663dd64e849562f9918a09
38,455
def get_init_data(file_name): """ Args: file_name: Returns: camera starting position, imu starting position """ init_file = INIT_PATH + file_name + '.json' init_data = read_json_file(init_file) return init_data['cam_start'], init_data['imu_start']
52e2d7afd3b0667a122c857205db86a29ad048b6
38,456
import re def get_aspect_ratio (video_source_filename): """This returns the aspect ratio of the original video. This is usualy 1.78:1(16/9) or 1.33:1(4/3). This function is very lenient. It basically guesses 16/9 whenever it cannot figure out the aspect ratio. """ cmd = "mplayer '%s' -vo png -...
a71b642f64464f0675a9d3c20b610ccfb55df426
38,457
from typing import Dict from typing import Any from typing import Callable def ot3_remote_everything_commit_id( ot3_default: Dict[str, Any], robot_set_source_type_params: Callable ) -> RuntimeComposeFileModel: """Get OT3 configured for local source and local robot source.""" return robot_set_source_type_p...
9b4511e83d31b2e58c046447ed87569e9721ffba
38,458
from typing import Union import random def pick_typo(next_letter: str) -> Union[str, None]: """Picks a typo according to the next letter to type. This function uses `is_typo()` to determine wether or not there will be a typo. Plausible typos are defined in the `PLAUSIBLE_TYPOS` global variable. ...
a0f310f04d57e97d85afbdcaa6074a71eed324ff
38,459
def _get_tag_by_name(tag_name: str, auth_id: int, db: Session): """ Returns tag data by passing the tag name Args: tag_name (str): Tag Name auth_id (int): User Id db (Session): sqlAlchemy connection object Returns: sql_object : Tag data """ return db.query(TagDB).fi...
47ea0ec8572fdeec0005ffb0e8d132855db09336
38,460
def sshconnect_ex1(ssh: SSH): """ SSH example using :class:`ssh2.SSHConnect` with SSH configuration file (:code:`~/.ssh/config`). """ return ssh.execute("ls -l")
4ee656143e5d8fde85dd4bff264775a09c7f0f56
38,461
def list_org_inner_pub_repos(org_id, username, start=None, limit=None): """ List org inner pub repos, which can be access by all org members. """ try: shared_repos = seafserv_threaded_rpc.list_org_inner_pub_repos(org_id) except SearpcError: shared_repos = [] for repo in shared_r...
df00f7dd9a7c7b05246ad6663eae4697aede4b53
38,462
import sqlite3 def select_special_student(sql_special): """ 特殊sql语句的查询 并将其结果封装为Student类型的列表 :param sql_special: 特殊的sql条件 :return: list(Student) """ if sql_special is None: return None connection = sqlite3.connect(r'sqlite/student_system.db') cursor = connection.cursor() # ...
bacec7fe8628c78d3911bdf20a18c5f2bd7759ef
38,463
def gauss(x, a, b, c): """ generate a Gaussian function Parameters ---------- x : array like x coordinates. a : float amplitude (centeral height). b : float center. c : float sigma. Returns ------- y y = Gaussian(x | a, b, c). ""...
99d14f51d17488dcb216c92754c97303c2b64295
38,464
import re def replace_urls(text, filler='<url>'): """Replaces URLs in text with `f' {filler}'`. Potentially induces duplicate whitespaces. Includes punctuation in websites (which is not really a problem, because URLs on Twitter are rendered as https://t.co/randomnum). The regex doesn't account...
0556120c0b8ab8a888acad550cb4cad24c5961ae
38,465
from typing import Dict from datetime import datetime import urllib import hmac import hashlib import base64 def create_signature_v2( api_key, method, host, path, secret_key, get_params=None ) -> Dict[str, str]: """ 创建签名 :param get_params: dict 使用GET方法时附带的额外参数(urlparams) :retur...
6ff58204372f07085fae99fcce418638b1e8b30c
38,466
def solution(X, A): """Find the earliest time that a frog can jump to position X. In order to reach X, a leaf must be present at every position from 1 to X. Args: X (int): The position that the frog must reach. A (list): A list of integers from 1 to X, where A[k] represents a leaf ...
d1fec5a3ec4c6dc06cd0feab295c90cb4c920ced
38,467
import math def moments_get_orientation(m): """Returns the orientation in radians from moments. Theta is the angle of the principal axis nearest to the X axis and is in the range -pi/4 <= theta <= pi/4. [1] 1. Simon Xinmeng Liao. Image analysis by moments. (1993). """ theta = 0.5 * math.atan...
0b75e86e324dccd5fe2c4332dfeb15d63a417b9b
38,469
def load_sklearn_bc_dataset(): """ Helper to load sklearn dataset into a pandas dataframe Returns: pd.DataFrame: X and y combined """ dataset = load_breast_cancer() df = pd.DataFrame(data=pd.np.c_[dataset['data'], dataset['target']], columns=(dataset['feature_names...
39ac7c63099971fce732f18d6051c0ac3f250a36
38,470
def get_select_form_layout(id, options, label, description): """Creates a select (dropdown) form with provides details Parameters ----------- id: str id of the form options: list options to show label: str label of the select dropdown bar description: str lon...
d019943048679ec0dfb15150d5df26ddd1c2ff21
38,471
def visualise_sampling_grid(X_sampled, gridsize=3): """Show how herding algorithm samples the datapoints Using X_sampled, which is the original design matrix with rows permuted such that X_sampled[i] is the i'th row chosen by the sampling algorithm. This enables calculating X_sampled by arbitrary algor...
efed02bf1f58b1d01d5fe087eb3f1838b606952b
38,472
def serialize_ip_block(block): """ Serialize an IP block to protobuf string. Args: block (ipaddress.ip_network): object to serialize Returns: serialized (bytes): serialized object """ proto = IPBlock( version=_ip_version_int_to_proto(block.version), net_address=b...
9344c35f51d6ecaa7803f9198b8e0451bb78caaf
38,473
def DeWeWriteCAN(nBoardNo, CanFrameList): """Dewe write CAN""" if f_dewe_write_can is not None: n_real_frame_count = c_int() n_frame_count = len(CanFrameList) p_can_frames = (BOARD_CAN_FRAME * n_frame_count)() i = 0 for CanFrame in CanFrameList: p_can_frames[...
bb3eb6ddc28cd43ed9c9a70457626e92496d6a77
38,475
def get_article_case(article, word): """Determines the correct article casing based on the word casing""" return article.capitalize() if word[0].istitle() else article
603810cb60c3719c102afe024cdc0ce474d37bfa
38,476
def calc_DM(seg): """ Computes NON-SIGNED Distance Map of input ground truth image or volume using scipy function. In case seg is 3D volume, it separately computes 2D DM fo each single slice. Args: seg: 2D or 3D binary array to compute the distance map Returns: res: distance map ...
f707db2ca620a62f994f04360c96450fa855d0e3
38,477
def get_valid0(cfg: Config): """ Simple network with all inputs and all outputs used. Configuration: 0 1 / | 2 \ / \ | -1 -2 -3 """ # Create a dummy genome genome = Genome( key=0, num_outputs=cfg.genome.num_outputs, ...
c52c72285ee8b364ecafed330d9348de79a38198
38,478
from typing import List def get_dependents_auto(tensor: tf.Tensor, candidates: List[tf.Tensor]) -> List[tf.Tensor]: """Return the nodes in `candidates` that `tensor` depends on. Args: tensor (): candidates (): """ try: dependent_ops = all_parents(tensor.op) except RuntimeE...
2b1a5143a3c2faf54a7e5bb42093e7fde41d512c
38,479
def gram_matrix(input_tensor): """ Computes the outer-product of the input tensor x. Input: - x: input tensor of shape [H,W,C]. We reshape it to [C (H, W)] Returns: Tensor of shape [C,C] corresponding to the Gram matrix Your code goes here """ channels = int(input_tensor.shape[...
e7db0bcae972331146958b02eac3e0e23fae87cc
38,480
def false_positive_rate(context, positive_class, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a multiclass false positive rate. The result of this function repres...
ece9d7d9f40d6b52af1efc1f168186698c3ec94f
38,481
from typing import List import re from pathlib import Path def check_missing_pictures(document: Document, args: Args) -> List[Issue]: """Check that all pictures files linked in the document exist.""" issues = [] markdown_picture_re = re.compile(r"\s*\!\[.*\]\((.*)\)") for number, line in enumerate(do...
92d45dc4895dfcb143ec44a7eda3a8189b1f3155
38,484
def _load_mesh(path: str): """Loads mesh data from numpy file. Args: path (str): Path to data file Returns: data (np.ndarray): Scaled data (NHWC) """ with open(path, "rb") as f: mesh = np.einsum("abcde->deabc", sio.loadmat(f)["im"]) flattened_mesh = mesh.reshape((-1,) +...
ae46ff174a4efaf8e3accc601ba1ee6d5bfbb989
38,485
def configure(filename="tuf.interposition.json", parent_repository_directory=None, parent_ssl_certificates_directory=None): """The optional parent_repository_directory parameter is used to specify the containing parent directory of the "repository_directory" specified in a configurati...
3aca6e4b3fb6bdbd8e909b4b686c7871bf7a9115
38,486
import xdg def get_script_folder_name(): """Returns the folder where Enso commands are found. This function is responsible for ensuring that this folder exists: it must not return a path that is not present! It is expected to place this folder in some platform-specific logical location.""" return x...
78ff0b66e4198c15f8f0aa9cfa9428415f57db9f
38,487
def CDLHOMINGPIGEON(equity, start=None, end=None): """Homing Pigeon :return: """ opn = np.array(equity.hp.loc[start:end, 'open'], dtype='f8') high = np.array(equity.hp.loc[start:end, 'high'], dtype='f8') low = np.array(equity.hp.loc[start:end, 'low'], dtype='f8') close = np.array(equity.hp....
26a95084abe3cc418a35db13fd191d8fd544cd04
38,488
import collections def deep_convert_to_plain_dict(an_odict): """ Recursively convert `an_odict` and any of its dictionary subelements from `collections.OrderedDict`:py:class: to plain `dict`:py:class: .. note:: This is naive, in that it will not properly handle dictionaries with recursive obj...
0a463981909153d4beee64fbbf5fad489adf78ac
38,489
def mie(r, eps, sig, m=12, n=6): """Mie pair potential. """ prefactor = (m / (m - n)) * (m / n)**(n / (m - n)) return prefactor * eps * ((sig / r) ** m - (sig / r) ** n)
97e96c73c55c9db61f9efe404b26b368090df0bc
38,490
def dpn_conv1x1(in_channels, out_channels, stride=1): """ 1x1 version of the DPN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple...
65e2d408a330050fb45d0b63cced003b443c18e0
38,491
def _conv2d_legalize(attrs, inputs, arg_types): """Legalizes Conv2D op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output ...
912b8f144a0c00ba5fa4985fbfadcc8d13d334a9
38,492
def smooth_good_regions_repeatedly(blob_id, repeated_smoothings=5, spine_order=SPINE_ORDER, spine_window=SPINE_WINDOW, time_order=TIME_ORDER, time_window=TIME_WINDOW, ...
ed16652137854607b3afa224975c3b80c9965fcc
38,493
def mean_filter(dem, kernel_radius): """Applies mean filter (low pass filter) on DEM. Kernel radius is in pixels. Kernel size is 2 * kernel_radius + 1. It uses matrix shifting (roll) instead of convolutional approach (works faster). It returns mean filtered dem as numpy.ndarray (2D numpy array).""" radi...
1bbac4841ab35a38045083cdabd70a5371e97f87
38,494
def _members_geom_lists(relation_val, footprints): """ Add relation members' geoms to lists. Parameters ---------- relation_val : dict members and tags of the relation footprints : dict dictionary of all footprints (including open and closed ways) Returns ------- tu...
a0ccf10ef75c381b5839cf8e17ba304a7488ecda
38,495
import numpy as np def hits_numpy(G,normalized=True): """Return HITS hubs and authorities values for nodes. The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. Parameters ...
b202749cad4550f094f7a5908c4d0e835920acd1
38,496
def InputFunc(): """ InputFunc [This Function is used to take declare input.] Returns: [int]: [windowSize] [int]: [dataBits] [int]: [Timeout] """ dataStr = '1010010011' dataStr = " ".join(dataStr) windowSize = 4 # Makes the input string to a list dataBits = [...
ec9426e20774d093459e752c128a103886b7b514
38,497
def httpResponse(graph, uri): """HTTP response: FAIR metadata in RDF and JSON-LD formats""" accept_header = request.headers.get('Accept') fmt = 'turtle' # default RDF serialization mime_types = { 'text/turtle': 'turtle', 'application/rdf+xml': 'xml', 'application/ld+json': 'json...
b3f9d07d3c7a610a3b09a601e4a988e95488e4c5
38,498
def reaction( func=None, # type: Optional[Callable[[_BO, Action, Phase], None]] priority=None, # type: Optional[int] ): # type: (...) -> Union[CustomReaction, ReactionDecorator] """ Decorates an object's method into a custom reaction. Reaction methods are called automatically when an action pr...
1dab9c52aa3d381e7ad418851b5d75aa5c96af8e
38,499
def delete_report(repo, username=None, namespace=None): """Delete a report from a project.""" repo = flask.g.repo form = pagure.forms.ConfirmationForm() if form.validate_on_submit(): report = flask.request.form.get("report") reports = repo.reports if report not in reports: ...
d3cee0f0702b3a48559782b01b426bb0f4975de7
38,500
import math def fuzzifier_determ(D: int, N: int) -> float: """The function to determ the fuzzifier paramter of fuzzy c-means """ return 1 + (1418 / N + 22.05) * D**(-2) + (12.33 / N + 0.243) * D**(-0.0406 * math.log(N) - 0.1134)
3bf0f85a74400c19fae74349ea651eba8b600697
38,502
from typing import List def _is_paired(ordered_list: List[int]) -> bool: """Check whether values are paired in ordered_list.""" consecutive_comparison = [ t == s for s, t in zip(ordered_list, ordered_list[1:]) ] return (all(consecutive_comparison[0::2]) & (not any(consecutive_comparison[1::2])...
ba7052de513bcc7bf274e38005c459715e9f60b8
38,503
def rgb_to_gray(image, three_channels=False): """Converts a 3 channel RGB image to a 1 channel grayscale image. Args: image: Rank 3 float32 tensor containing 1 image -> [height, width, 3] with pixel values varying between [0, 1]. Returns: image: A single channel grayscale image -> [image, hei...
89b3bf7dab7b94ff21be046e72895e2326819abe
38,504
def get_largest_partition_size(ns, device): """ Returns size of the largest free region (in blocks), which can accommodate a partition on given device. There must be partition table present on this device. :type device: LMIInstance/CIM_StorageExtent or string :param device: Device which should...
104c1bd8626236fbd0983f6280213c0a15785f41
38,505
def steps(number): """ Count steps needed to get to 1 from provided number. :param number int - the number provided. :return int - the number of steps taken to reach 1. """ if number < 1: raise ValueError("Provided number is less than 1.") steps = 0 while number != 1: s...
8681691946b5ba2d261a1ae753d2a04c46ac1719
38,507
def labs(**kwargs): """ Change plot title, axis labels and legend titles. Parameters ---------- kwargs : dict A list of new name-value pairs where name should be an aesthetic, e.g. title='Plot title' or aesthetic='Scale label'. Returns ------- `FeatureSpec` or `FeatureS...
45c0038e694b730a92d35c407ddb4a4cb639647b
38,508
def nested_dict_values(d): """ Extracts all values from a nested dictionary """ listvals = list(nested_dict_gen(d)) listvals_unwrapped = [] for l in listvals: if type(l) == list or type(l) == np.ndarray: for ll in l: listvals_unwrapped.append(ll) else:...
cfeb0a5fb782240e622b3dd21a47ce10143af569
38,509
import numpy def _get_sr_pod_grid(success_ratio_spacing=0.01, pod_spacing=0.01): """Creates grid in SR-POD space SR = success ratio POD = probability of detection M = number of rows (unique POD values) in grid N = number of columns (unique success ratios) in grid :param success_ratio_spacin...
6349afbecc8994c1078f2fa019a5a721862b0d15
38,511
from typing import Optional from typing import Set async def all_upcoming_broadcasts( seconds: Optional[int] = None, ) -> Set[TextChannel]: """All upcoming broadcast channels that have yet to be announced. If minutes are given, then it will only mention the events comming up in the given number of minutes...
bdb52910824a284b89676d3b2b2bc7a296353b50
38,512
def jd2iso(jd): """Convert a Julian date into an ISO 8601 date string representation""" return astropy.time.Time(jd, format='jd', scale=time_scale, precision=0).iso
6c8111d78adff702a22347c2cf1855ceddcc8d55
38,513
def MakeOnnxInputsOutputs(name, elem_type, shape, **kwargs): """Wrapper for creating onnx graph inputs or outputs name, # type: Text elem_type, # type: TensorProto.DataType shape, # type: Optional[Sequence[int]] """ if elem_type is None: elem_type = onnx_pb.TensorProto.UNDEFI...
e9fc478ff715584752e5ed69ec2c9c826ce76a9d
38,514
def geom_lst_to_gdf(lst): """Convert geometry or geometry list to gdf. Args: lst (geometry|list(geometry)): The geometry or geometries. Returns: gpd.GeoDataFrame: The geodataframe. """ if not isinstance(lst, list): lst = [lst] return gpd.GeoDataFrame( {'ge...
5189e77a5c4d1701aaee6feea5b4f1b80a86c0e4
38,515
def build_get_enum_valid_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get enum array value ['foo1', 'foo2', 'foo3']. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azure.core...
654c0de7e0efc219406e42f6395ed214aa92aeb5
38,516
import scipy def ks_2samp(data1, data2): """ Computes the Kolmogorov-Smirnov statistic on 2 samples. This is a two-sided test for the null hypothesis that 2 independent samples are drawn from the same continuous distribution. Parameters ---------- a, b : sequence of 1-D ndarrays tw...
58854c49fe6adbbc747579f5c38c00673430d21d
38,517
def list_shows(): """ return all the shows """ shows = ShowRun.query.all() ret = [] for show in shows: ret.append({'show_id': show.id, 'show_date': show.created_date, 'show_status': show.status.name}) return jsonify({'date': ret})
2008646c0c911de0012a5cfc4e6187c2e0406c2f
38,518
from typing import Dict import re def _replace_spec_toks(mthd: str, spec_toks: Dict[str, str]) -> str: """ Performs the replacement of special tokens by the original ones """ spec_toks = spec_toks.copy() # Add special tokenizer tokens -> deleted for code analysis spec_toks['<bos>'] = "" sp...
0c1b9ec96880c2c488952f238dd146719398cbcd
38,519
def redirect_to_user_chat(markup: ReplyKeyboardMarkup): """ Clean the bot commands from the group chat and send the message to a user. Args: markup: ReplyKeyboardMarkup Returns: None or Calls decorated function if in the user's chat. """ def decorator(func): ...
c8feae1ed2e3f3b5e44309b17f04dc54ba7c6e30
38,520
def run_intcode(memory, input_list): """Run an Intcode program from memory and return the result""" instr_ptr = 0 input_ptr = 0 output = None while instr_ptr < len(memory): instruction = memory[instr_ptr] digits = list_digits(instruction) # extract opcode opcode_pair...
0941d13400ca170714d41476d6cf72a4942e9c97
38,521
from typing import Union from typing import Optional def get_kubeflow_value( tfx_value: Union[int, float, str, Text]) -> Optional[pipeline_pb2.Value]: """Converts TFX/MLMD values into Kubeflow pipeline Value proto message.""" if tfx_value is None: return None result = pipeline_pb2.Value() if isinstan...
5f579f5b34261dad2f753d73dd5fe4c36cf34d8f
38,522
def read_parquet( path, engine: str = "auto", columns=None, storage_options: StorageOptions = None, use_nullable_dtypes: bool = False, **kwargs, ): """ Load a parquet object from the file path, returning a DataFrame. Parameters ---------- path : str, path object or file-like...
ea8264bbda6293a07059a7a0ebd85c15a844bdf1
38,523
import torch def calculate_cis_nominal(genotypes_t, phenotype_t, residualizer=None, return_af=True): """ Calculate nominal associations genotypes_t: genotypes x samples phenotype_t: single phenotype residualizer: Residualizer object (see core.py) """ p = phenotype_t.reshape(1,-1) r_no...
ad73cdcb962f7108761833a83e847e1dcaf9b249
38,524
def get_ver(): """Read out the version number of the radio""" return radio_get_ver_fn()
03b20e4c4e60807327f593f36605fa651350a1af
38,525
def get_entities_list(token, aiid): """Returns a list of all entities for an AI""" return fetch_api('/entities/{aiid}', token=token, aiid=aiid)
d660e56c9e94e1ae587b037571e9120df5acf8bd
38,526
def read_P23_from_sequence(file): """ read P2 and P3 from a sequence file calib_cam_to_cam.txt """ P2 = None P3 = None with open(file, 'r') as f: for line in f.readlines(): if line.startswith("P_rect_02"): data = line.split(" ") P2 = np.array([floa...
eb4e334a8dfac11c86d837640b47f3a48880af90
38,527
def openConnection(): """ Method that starts a connection with the database :return: the driver for the connection """ connection = nj.GraphDatabase.driver( uri=URI, auth=nj.basic_auth(USER, PASSWORD)) return connection
35db801d44e143007c0972747380e942fbbdee0f
38,528
from .views import item_methods def resource_view_attrs(raml_resource, singular=False): """ Generate view method names needed for `raml_resource` view. Collects HTTP method names from resource siblings and dynamic children if exist. Collected methods are then translated to `nefertari.view.BaseView` ...
63f2687b0e0fdde3d3749dade2a706818ac9acce
38,529
def total(inarray, axis, type='meanclip'): """ Collapse 2-D array in one dimension. .. note:: MYTOTAL routine from ACS library. Examples -------- >>> collapsed_array = total(inarray, 1, type='median') Parameters ---------- inarray : array_like Input 2-D array. axis : ...
f3083d53eea18303594d21fff53073c79a84e9dc
38,530
def check_rack_shape_match(source_shape, target_shape, row_count, col_count, translation_behaviour=None): """ Checks whether two rack shape match the given rack transfer or translation behaviour. :Note: One-to-one translations can not be discovered ...
273691fca54b93ab8725b4c5f2e89e00cec03d4b
38,531
def deny_request( request_id ): """Denies a given request for slots No request params. """ try: req = SlotRequest.get( SlotRequest.id == request_id ).select().join( User ).first() print(req) g.user.deny_request( request_id ) rs = RadioStation.get() send_mail( '{}...
022485b485172f7501ea021fec9d712c7d6862c0
38,532
def make_env(rank, seed=0): """ Utility function for multiprocessed env. :param env_id: (str) the environment ID :param num_env: (int) the number of environments you wish to have in subprocesses :param seed: (int) the inital seed for RNG :param rank: (int) index of the subprocess """ de...
00732e1373bd2ca4536f9612ba4ad268b606307b
38,533