content
stringlengths
22
815k
id
int64
0
4.91M
def get_dep_ids(plan_by_id, package): """ Gather all package ids that need to be built, given a top-level package (usually clash-ghc). Given list is in order, but will probably contain duplicates. """ package_id = package["id"] if not is_preinstalled(package): components = package.ge...
79,800
def _ConvertInteger(value): """Convert an integer. Args: value: A scalar value to convert. Returns: The integer value. Raises: ParseError: If an integer couldn't be consumed. """ if isinstance(value, float) and not value.is_integer(): raise ParseError('Couldn\'t parse integer: {0}.'.forma...
79,801
def create_connection(host_ip, ssh_port, user, password): """ 创建一个ssh连接 :param host_ip:主机ip :param ssh_port: ssh端口 :param user: 登录用户 :param password: 登录密码 :return: 如果创建连接成功返回连接,连接超时返回'TIMEOUT',如果认证失败返回"AUTH_FAIL" """ logger.info("准备创建ssh连接,host_p=%s,ssh_port=%d,user=%s,password=%s" %...
79,802
def to_segments(data, num=32): """ These code is taken from: https://github.com/rajanjitenpatel/C3D_feature_extraction/blob/b5894fa06d43aa62b3b64e85b07feb0853e7011a/extract_C3D_feature.py#L805 :param data: list of features of a certain video :return: list of 32 segments """ data = np.array(d...
79,803
def restore_ttl(): """ restores old ttl from json """ if not os.path.exists('ttl.json'): print("please set a new ttl first") print_help() return try: with open('ttl.json', 'r') as ttl_file: set_ttl(int(json.load(ttl_file)['old_ttl'])) except FileNotFoundError...
79,804
def draw_graph_graphviz(vertices, edges, image=None, engine="dot"): """ Draws a graph using :epkg:`Graphviz`. @param edges see below @param vertices see below @param image output image, None, just returns the output @param engine *dot* or ...
79,805
async def discord_has_token(discord_id: int, db: AsyncSession = Depends(get_db_session)): """Return if a user has a valid token""" profile = await discord_users.get_profile_from_discord_id(discord_id) if not profile: return DestinyHasTokenModel(token=False, value=None) no_token = await discord_...
79,806
def filter_metrics(output): """Filter by metric name.""" for item in output: name = item.get('name', {}).get('name', '') for k, v in COST.items(): if k in name: yield name, item.get('scalar')
79,807
def calc_FID(gen, batchsize=100, stat_file="%s/cifar-10-fid.npz" % os.path.dirname(__file__), dst=None, path=None, n_ims=5000, num_evals=1, training=True): """Frechet Inception Distance proposed by https://arxiv.org/abs/1706.08500""" @chainer.training.make_extension() def evaluation(trainer=No...
79,808
def tokenize_text(text): """ Tokenizes and tags a given text. Args: text (str): Text to process. Returns: List(Tuple[str, str]): List of word-tag pairs. """ nltk.download('punkt') nltk.download('averaged_perceptron_tagger') tokens = nltk.word_tokenize(text) tagged =...
79,809
def kl_loss_diag(mean, logvar): """ KL divergence of normal distributions with diagonal covariance and standard multivariate normal. :param mean1: mean of distribution 1 :param logvar1: logarithm of the covariance diagonal of distribution 1 :return: KL divergence of the given distribution and stand...
79,810
def randomize(df, seed=None): """Develop a randomization function that randomizes all of a dataframe's cells then returns that randomized dataframe. This function also accepts a random seed for reproducible randomization""" df = df.copy() columns = df.columns df = shuffle(df[columns], random_st...
79,811
def censusdp1tract_to_sqlite(pudl_settings=None, year=2010): """ Use GDAL's ogr2ogr utility to convert the Census DP1 GeoDB to an SQLite DB. The Census DP1 GeoDB is read from the datastore, where it is stored as a zipped archive. This archive is unzipped into a temporary directory so that ogr2ogr c...
79,812
def raise_400(instance, msg=None): """Abort the current request with a 400 (Bad Request) response code. If the message is given it's output as an error message in the response body (correctly converted to the requested MIME type). :param instance: Resource instance (used to access the response) :ty...
79,813
def add_class(add, class_): """Add to a CSS class attribute. The string `add` will be added to the classes already in `class_`, with a space if needed. `class_` can be None:: >>> add_class("foo", None) 'foo' >>> add_class("foo", "bar") 'bar foo' Returns the amended cl...
79,814
def get_model(point_cloud, is_training,num_classes,normal = False,bn_decay=None,bn=True, num_keypoints = 192,k = 16,nsample = 32): """ Classification PointNet, input is BxNx3, output BxNUM_CLASSES """ b = point_cloud.get_shape()[0].value n = point_cloud.get_shape()[1].value end_points = ...
79,815
def preview_synthetic_training_data(data, target, backgrounds=None, verbose=True, **kwargs): """ A utility function to visualize the synthetically generated data. ...
79,816
def guessColorName(nameMe): """Return a tuple (distance, guessed human-name of a color).""" return min(colors, key=lambda x: distance(nameMe, x))
79,817
def to_lower_camel_case(str_to_convert): """ This function will convert any string with spaces or underscores to lower camel case string :param str_to_convert: target string :return: converted string """ if type(str_to_convert) is not str: raise TypeError("The method only take str as its...
79,818
def ordinal_suffix(n): """Return the ordinal suffix for a positive integer >>> ordinal_suffix(0) '' >>> ordinal_suffix(1) 'st' >>> ordinal_suffix(2) 'nd' >>> ordinal_suffix(3) 'rd' >>> ordinal_suffix(4) 'th' >>> ordinal_suffix(11) 'th' >>> ordinal_suffix(12) 'th' >>> ordinal_suffix(13) ...
79,819
def sentence_to_token_ids(sentence, vocabulary, max_sequence_length): """Convert a string to a list of integers representing token-ids.""" words = sentence.strip().split() if len(words) > max_sequence_length: words = words[:max_sequence_length] return [vocabulary.get(w, UNK_ID) for w in words]
79,820
def _collect_facts(resource): """Transfrom cluster information to dict.""" facts = { 'identifier' : resource['ClusterIdentifier'], 'create_time' : resource['ClusterCreateTime'], 'status' : resource['ClusterStatus'], 'username' : resource['MasterUs...
79,821
def vendor_requirements_available(vendor_requirements: TypeDict[str, TypeAny]) -> bool: """ Check whether torch or python version is supported Args: vendor_requirements: dictionary containing version of python or torch to be supported Returns: True if system supports all vendor require...
79,822
def _async_create_template_tracking_entities( async_add_entities, hass, definitions: list[dict], unique_id_prefix: str | None ): """Create the template binary sensors.""" sensors = [] for entity_conf in definitions: unique_id = entity_conf.get(CONF_UNIQUE_ID) if unique_id and unique_id...
79,823
def pytest_addoption(parser): """The app ini file to be used for testing (should be specified).""" parser.addoption('--appini', default=APPINI, help='app conf')
79,824
def correlate_distance_matrix_quadrants(distmat, figdir, name): """ Take the lower triangle matrix of each quadrant in the distance matrix, and then correlate all quadrants lower triangle matrices with eachother. Repeat this process, but with permutated values. Find the percentile of the non-permuta...
79,825
def leave_one_in(feature_groups): """For each group, return a copy of just that group Args: feature_groups (list) The feature groups to apply the strategy to Returns: A list of feature dicts """ return feature_groups
79,826
def push(ui, repo, patch=None, **opts): """push the next patch onto the stack By default, abort if the working directory contains uncommitted changes. With --keep-changes, abort only if the uncommitted files overlap with patched files. With -f/--force, backup and patch over uncommitted changes. ...
79,827
def disable() -> dict: """Disables log domain, prevents further log entries from being reported to the client.""" return {"method": "Log.disable", "params": {}}
79,828
def dissolve_unwanted_nodes(pp): """ Modify planar partition by dissolving edges that share a node of degree 2 where this is not needed """ new_edge_id = max(pp.edges.keys()) + 1 dissolve = [] for node_id, node in pp.nodes.items(): star = node.star # for node_id, star in pp.stars....
79,829
def repeat_each_element(element: tf.Tensor, number_of_repeats: int) -> tf.data.Dataset: """ A dataset mappable function which repeats the elements a given number of times. :param element: The element to map to to repeat. :param number_of_repeats: The number of times to repeat the element. :return: ...
79,830
def read_instance(path, shape=(4, 240, 240, 155)): """ Read a 3-d image with corresponding mask """ x = np.empty(shape) for i, channel in enumerate(CHANNELS): channel_path = glob.glob(os.path.join(path, f"*{channel}.nii.gz"))[0] x[i] = nib.load(channel_path).get_fdata() y_path = glob.g...
79,831
def ncc(I, J): """ Code comes from: Unsupervised Learning for Fast Probabilistic Diffeomorphic Registration Adrian V. Dalca, Guha Balakrishnan, John Guttag, Mert R. Sabuncu MICCAI 2018. """ eps = 1e-5 # assumes I, J are sized [batch_size, *vol_shape, nb_feats] ndims = len(I...
79,832
def equivalent_string( seq_x: Sequence[Hashable], seq_y: Sequence[Hashable] ) -> Tuple[str, str]: """ Returns a string equivalent to a sequence, for comparison. As some methods offered by third-party libraries only operate on strings, while `seqsim` is designed to offer all methods of compariso...
79,833
def initial_checks(s3interface, gremlinInterface): """Perform initial checks of services + selftest.""" check_buckets_existence(s3interface)
79,834
def _get_subtopics( corpus, dictionary, num_topics, num_words, depth, passes=10 ): """The recursive function""" ldamodel = models.ldamodel.LdaModel( corpus, num_topics=num_topics, id2word=dictionary, passes=passes ) lda_output = {} topics = ldamodel.ge...
79,835
def normalizeimage(image, depth=256, verbose=False): """Normalize image to chosen bit depth""" if verbose: print 'Normalizing image from [' + str(numpy.min(image)) + ':' + str( numpy.max(image)) + '] to', normalizedimage = ((image - numpy.min(image)) * (depth / (numpy.max( image)...
79,836
def remote_disable(*args, conan_api, parser, subparser): """ Update remote info """ subparser.add_argument("remote", help="Pattern of the remote/s to disable. " "The pattern uses 'fnmatch' style wildcards.") args = parser.parse_args(*args)
79,837
def _strftime(d): """ Format a date the way Atom likes it (RFC3339?) """ return d.strftime('%Y-%m-%dT%H:%M:%SZ%z')
79,838
def cache_signatures(inference_state, context, bracket_leaf, code_lines, user_pos): """This function calculates the cache key.""" line_index = user_pos[0] - 1 before_cursor = code_lines[line_index][:user_pos[1]] other_lines = code_lines[bracket_leaf.start_pos[0]:line_index] whole = ''.join(other_li...
79,839
def append_entrypoint(app: Flask, entrypoint: str, location: str) -> Flask: """Add routes/functions defined in entrypoint.""" mod = pw.import_entrypoint(entrypoint, location) fm = pw.get_func_annotations(mod) if not any([e.endpoint for e in fm]): raise Exception("no endpoints defined") ope...
79,840
def print_results(result, commands, labels, top=3): """Example callback function that prints the passed detections.""" top_results = np.argsort(-result)[:top] for p in range(top): l = labels[top_results[p]] if l in commands.keys(): threshold = commands[labels[top_results[p]]]["conf"] else: ...
79,841
def _extract_process_nodes(cube: Union[dict, DataCube], process_id: str) -> List[dict]: """Extract process node(s) from a data cube or flat graph presentation by process_id""" if isinstance(cube, DataCube): cube = cube.flat_graph() return [d for d in cube.values() if d["process_id"] == process_id]
79,842
def check_if_data_sets_are_downloaded(): """ This function checks if the data sets are downloaded, and returns an error if they are not. """ # If the downloaded data path doesn't exist, raise an error if not os.path.exists(downloaded_data_path): raise FileNotFoundError("The downloaded d...
79,843
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Alpha Vantage sensor.""" data = hass.data[ALPHA_VANTAGE] dev = [] for symbol in discovery_info[CONF_SYMBOLS]: dev.append(AlphaVantageSensor(symbol, data)) for conversion in discovery_info[CONF_FOREIGN_EXCHAN...
79,844
def plot_yproj(histogramme_mcdwin, filename): """ plot the y projection of the mcdwin 2d histogram to eps and pdf :param histogramme_mcdwin: :param filename: :return: None """ c = TCanvas('c', 'Y projection', 200, 10, 700, 500) # create Yprojection of MM6 data y_projection = projecti...
79,845
def eot_splitting_generator(string_iterable, encoder): """ Given strings, splits them internally on <|endoftext|> and yields (generally more) strings """ for doc in string_iterable: for d in doc.split(encoder.eos_token): if len(d) > 0: yield d
79,846
def read_pyc(filename): """ Read the code inside a bytecode compiled file if the MAGIC number is compatible Returns: a code object """ data = read_file(filename, 'rb') if not is_gae and data[:4] != imp.get_magic(): raise SystemError('compiled code is incompatible') retur...
79,847
def evaluate(model, val_file_path, num_classes): """ 评价SegNet网络指标,主要是测试miou :param model: 模型对象 :param val_file_path: 验证集文件路径 :param num_classes: 分类数量 :return: None """ val_dataset = VOCDataset(val_file_path, batch_size=1) val_dataset = val_dataset.tf_dataset() val_dataset = iter(...
79,848
def gravity_and_floor(x, y, floor, g=1, scale=100): """ A hard wall at the bottom of the view and a linear downward potential. Note: y increases in the downward direction. """ v = np.zeros((len(y), len(x))) v += g*np.abs(y[:,None]-floor) v[y>floor] = scale return v
79,849
def action_check(opts, continuation=arch_check): """ Continue analysis only if it compilation or link. """ if opts.pop('action') <= Action.Compile: return continuation(opts) else: logging.debug('skip analysis, not compilation nor link') return None
79,850
def scan(a, dim=0, op=BINARYOP.ADD, inclusive_scan=True): """ Generalized scan of an array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim : optional: int. default: 0 Dimension along which the scan is performed. op : optional: af.BINARYOP. def...
79,851
def get_centor(feature, centors): """ 迭代计算聚类中心 :param node: 待判断数据[r,g,b] :param centors: init[cen1,cen2...] :param classes: [[node of class1],[node of class2],......[node of classk]] :return: cens=[cen1,cen2...] """ k = len(centors) # 建立k个类别数据的空集合 classes = [[] for _ in...
79,852
def calculate_results(file_path): """Calculates precision, recall and the F1 score on the development set """ org_dict = dict() misc_dict = dict() per_dict = dict() loc_dict = dict() with open("development_output.csv") as f: count = 0; for line in f: count+=1 if count is 2: l = line[4:]...
79,853
def food(request): """Show food. """ tracker = init_tracker(request) tracker.track_page_view("http://0.0.0.0:8000/food", "food_page") food = Food.objects.filter(owner=request.user).order_by('date_added') is_empty = True for f in food: if f.quantity > 0: is_empty = False ...
79,854
def fire_cannon(player, cannon_block): """Fires a cannon ball for the player out of the cannon_block.""" cannon_ball = Actor('cannon_ball', pos=cannon_block.pos) sounds.cannon_boom.play() target, end_shot_x = get_target_player_and_x(player, cannon_block) shots_fired.append(cannon_ball) cannon_ba...
79,855
def plot_basis(ax=None, R=None, p=np.zeros(3), s=1.0, ax_s=1, strict_check=True, **kwargs): """Plot basis of a rotation matrix. Parameters ---------- ax : Matplotlib 3d axis, optional (default: None) If the axis is None, a new 3d axis will be created R : array-like, shape (3...
79,856
def slicify(index, length=-1): """ Takes an index as an instance of a list, a tuple, an np.ndarray, an int, or anything else. In the case of a list, a tuple, or a np.ndarray return a slice if possible, else return an np.ndarray. In the case of an int, return slice(int, int+1). In the case of anythin...
79,857
def run_async_asyncio(func, *args, **kwargs): """ Runs an Async Function in a Sync Call using asyncio in sync calls """ if not iscoroutinefunction(func): func = AsyncFunction(func) coro = func(*args, **kwargs) return asyncio_run(coro)
79,858
def get_combined_revision(functions: Iterable[Callable]) -> forge.Revision: """Combine the parameters of all revisions into a single revision""" params = {} for func in functions: params.update(forge.copy(func).signature.parameters) return forge.sign(*params.values())
79,859
def create_layer_for_inference(layer: _TrainingWrapper, algorithm): """Internal API to create layer for inference with weight compression.""" # TODO(tfmot): move these checks to public API for # visibility. if not isinstance(algorithm, object): raise ValueError('`_create_layer_for_inference` requires `algor...
79,860
def merge(d, u): """ Recursively updates a dictionary. Example: merge({"a": {"b": 1, "c": 2}}, {"a": {"b": 3}}) = {"a": {"b": 3, "c": 2}} """ for k, v in u.items(): if isinstance(v, collections.Mapping): r = merge(d.get(k, {}), v) d[k] = r else: d[...
79,861
def _numba_i0(x): """ computes i0 to 15 digits """ if x < 0: x = -x if x <= 8.0: y = x/2.0 - 2.0 return np.exp(x)*_numba_chbevl(y, i0_lt8) else: y = 32.0/x - 2.0 return np.exp(x)*_numba_chbevl(y, i0_gt8)/np.sqrt(x)
79,862
def parse_args(parser): """ Parse commandline arguments. """ parser.add_argument('--waveglow', type=str, required=True, help='Full path to the WaveGlow model checkpoint file') parser.add_argument('-o', '--output', type=str, required=True, help='Directo...
79,863
def track_day_test(year, month, day, hour, lat, lon, elevdlim=-2.5): """ Given date, time, lat and lon calculate if the sun elevation is > elevdlim. If so return daytime is True This is the "day" test used by tracking QC to decide whether an SST measurement is night or day. This is importan...
79,864
def arn_has_slash(arn): """Given an ARN, determine if the ARN has a stash in it. Just useful for the hacky methods for parsing ARN namespaces. See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details on ARN namespacing.""" if arn.count("/") > 0: return True ...
79,865
def execute(env): """Perform pre-stage tasks for running a component. Parameters ---------- env : dict A dict of component parameter values from WMT. """ env['n_steps'] = int(round(float(env['_run_duration']) / float(env['dt']))) env['save_grid_dt'] = float(env['dt']) env['save_p...
79,866
def calculate_gradient(f: Callable, x: List[float]) -> np.array: """Return the gradient of a function at a given point Args: f (Callable): function in consideration x (List[float]): point at which gradient is evaluated Returns: np.array: gradient of f(x) """ dim = length(x)...
79,867
def record_tabular(key, val): """ Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration """ _Logger.CURRENT.record_tabular(key, val)
79,868
def stereographic_proj( normals, intensity, max_angle, savedir, voxel_size, projection_axis, min_distance=10, background_south=-1000, background_north=-1000, save_txt=False, cmap=default_cmap, planes_south=None, planes_north=None, plot_planes=True, scale="line...
79,869
def keccak_224(data: typing.Optional[bytes] = None) -> Keccak: """Returns a 224-bit keccak hash object""" return Keccak(c=448, r=1152, n=224, name='keccak_224', data=data)
79,870
def decr_id(id, id_remove): """Decrement a single id, with the aim of closing the gap at id_remove. The logic used is similar to that incr_id_after. """ k = len(id_remove) if len(id) >= k and id[:k-1] == id_remove[:k-1] and id[k-1] > id_remove[k-1]: return id[:k-1] + (id[k-1] - 1,) + id...
79,871
def get_ctf_json(json: Dict) -> Dict: """ Get ctf in rawsec json. Parameters ---------- json: Dict rawsec json. Returns ------- Dict ctf dict. """ return json["ctf_platforms"] if "ctf_platforms" in json else {}
79,872
def test_chinese_whispers_type_checks(): """ Tests contract (expected errors) in case client provides wrong types """ with raises(TypeError): chinese_whispers() with raises(TypeError): chinese_whispers('foo') with raises(RuntimeError): chinese_whispers(['foo']) with r...
79,873
def _make_extrinsic_corner_plot(samples, latex_labels, **kwargs): """Generate the corner plots for a given approximant Parameters ---------- opts: argparse argument parser object to hold all information from the command line samples: nd list nd list of samples for each parameter for...
79,874
def GetOperationError(error): """Returns a ready-to-print string representation from the operation error. Args: error: operation error object Returns: A ready-to-print string representation of the error. """ error_message = io.StringIO() resource_printer.Print(error, 'yaml', out=error_message) r...
79,875
def help_command(update, context): """Send a message when the command /help is issued.""" update.message.reply_text("/stats - Check Overall Stats\n\ /state - Check cases of States & UT's ")
79,876
def hogbom_clean(dirty, psf, gamma=0.1, threshold="default", niter="default"): """ Performs Hogbom Clean on the ``dirty`` image given the ``psf``. Parameters ---------- dirty : np.ndarray float64 dirty image of shape (ny, nx) psf : np....
79,877
def sql( query: str, index_col: Optional[Union[str, List[str]]] = None, **kwargs: Any, ) -> DataFrame: """ Execute a SQL query and return the result as a pandas-on-Spark DataFrame. This function acts as a standard Python string formatter with understanding the following variable types: ...
79,878
def to_cartisian(r, theta): """ Take two numbers or np arrays and return cartisian representation of the comblex number(s) r*exp(i*theta) Return: tuple (x, y) """ x = r*np.cos(theta) y = r*np.sin(theta) return (x, y)
79,879
def _get_team_(client, jwt, project_id): """Get team and return response.""" headers = ss_client_auth_header(jwt) response = client.get(TEAM_API.replace(':project_id', project_id), headers=headers, content_type='application/json') return response
79,880
def train(model, train_dataset, val_dataset=None, optimizer=None, save_dir='output', iters=10000, batch_size=2, resume_model=None, save_interval=1000, log_iters=10, num_workers=0, use_vdl=False, losse...
79,881
def counted ( f ): """create 'counted' function to know number of function calls Example ------- >>> fun = ... >>> func = counted ( fun ) ## use as function >>> @counted >>> def fun2 ( ... ) : return ... """ def wrapped ( *args, **kwargs ): wrapped.calls += 1 ...
79,882
def get_latex_permutations(rows, cols, tarray, title): """ Creates a latex table as a string. The string can be cut and paste into the dissertation. :param rows: number of rows in the board. :param cols: number of columns in the board. :param tarray: 2D array of the table contents. :para...
79,883
def load(file, collapsed=True, index=None): """Loads Laue diffraction data.""" if file['stacked'] is True: files = loadstack(file) if file['ext'] == 'h5': vals = loadh5files2(files, file['h5']['key'], file['frame']) else: if file['ext'] == 'h5': begin, end, st...
79,884
def test_catalogue_store_2(): """ Check various dataset sizes and resolutions """ cases = [(10000, 0), (1000, 0), (1000, 2), (1, 0)] for n, r in cases: yield check_catalogue_store_batches, n, r
79,885
def non_fabric_wireless(ctx, obj): """DNA Center Non-Fabric Wireless API (version: 1.2.10). Wraps the DNA Center Non-Fabric Wireless API and exposes the API as native Python commands. """ ctx.obj = obj.non_fabric_wireless
79,886
def test_run_app(first_app_config, tmp_path, monkeypatch): """A macOS app can be started.""" command = macOSAppRunCommand(base_path=tmp_path) command.subprocess = mock.MagicMock() log_stream_process = mock.MagicMock() command.subprocess.Popen.return_value = log_stream_process monkeypatch.setatt...
79,887
def format_map_to_vector(feature_lists: list, start: int, end: int): """ Convert map into vector :param feature_lists: list of features, whose elements are maps. :param start: starting element within list :param end: ending element within list :return: vector (list) of selected features """ ...
79,888
def setup(bot: SopelWrapper) -> None: """ Setup for the plugin """ bot.settings.define_section("ctxreminders", config.ContextualRemindersSection) ctx_service.setup(bot)
79,889
def tree_subtract_mean(oks: PyTree) -> PyTree: """ subtract the mean with MPI along axis 0 of every leaf """ return jax.tree_map(partial(subtract_mean, axis=0), oks)
79,890
def patch_expsets_otherprocessedfiles_for_queried_files(connection, **kwargs): """ Update the Higlass Items from Experiment Set Other Processed Files (aka Supplementary Files). Args: connection: The connection to Fourfront. **kwargs, which may include: called_by(opti...
79,891
def running_in_notebook_or_ipython(): """ Returns ``True`` if the module is running in IPython kernel, ``False`` if in IPython shell or other Python shell. """ return "ipykernel" in sys.modules
79,892
def selector(possibilities, names): """ Print a selector of all possibilities, and validate the choice against the "names" list """ # Print all possibilities for i in range(len(possibilities)): print(f'({i +1}) {possibilities[i]}') names.append(str(i + 1)) skip_lines(1) # Ask a user...
79,893
def check_numeric(feature_table: DataFrame) -> None: """ Check if spark DataFrame columns are of NumericType :param feature_table: spark DataFrame """ for column in feature_table.columns: if not isinstance( feature_table.schema[column].dataType, st.NumericType ): ...
79,894
def splinit(fun, data, i, s, smax, par, x0, n0, u, v, x, y, x1, x2, L, l, xmin, fmi, ipar, level, ichild, f, xbest, fbest, stop): """ splits box # par at level s according to the initialization list in the ith coordinate and inserts its children and their parameters in the list """ n...
79,895
def test_sevenchar(elem): """Test that we can consume a seven char code.""" elem.consume_code("QRHRZXA") assert elem.probability == "A"
79,896
def update_volume(VolumeId=None, Name=None, MountPoint=None): """ Updates an Amazon EBS volume's name or mount point. For more information, see Resource Management . See also: AWS API Documentation :example: response = client.update_volume( VolumeId='string', Name='string', ...
79,897
def lightspeed_quiz(driver: webdriver.Firefox): """ Completes the "lightning speed" quiz :param driver: The web driver used to interact with the browser """ # get the number of points quiz = driver.find_element_by_id("QuizContainerWrapper") trivia_overlay = quiz.find_element_by_id("b_TriviaO...
79,898
def check_version(expected, found): """Raises ValueError if `found` is not equal to or found within `expected`. """ if is_sequence(expected): is_good = found in expected else: is_good = (found == expected) if not is_good: error = "Version '{0}' is invalid. Expected {1}....
79,899