content
stringlengths
22
815k
id
int64
0
4.91M
def orthogonalize(vec1, vec2): """Given two vectors vec1 and vec2, project out the component of vec1 that is along the vec2-direction. @param[in] vec1 The projectee (i.e. output is some modified version of vec1) @param[in] vec2 The projector (component subtracted out from vec1 is parallel to this) ...
27,900
def tokenize(text): """ Function to process text data taking following steps: 1) normalization and punctuation removal: convert to lower case and remove punctuations 2) tokenization: splitting each sentence into sequence of words 3) stop words removal: removal of words which do not add a...
27,901
def extract_text(bucketname, filepath): """Return OCR data associated with filepaths""" textract = boto3.client('textract') response = textract.detect_document_text( Document={ 'S3Object': { 'Bucket': bucketname, 'Name': filepath } }) ...
27,902
def box1_input(input): """uses above to return input to player 1""" return get_input(1, input)
27,903
def test_join_query_string(): """Union de query string""" pass
27,904
def test_force_stop(process_engine, exec_infos, sync_server): """Test forcing the stop of the engine. """ t = ExecThread(process_engine, exec_infos) t.start() sync_server.wait('test1') process_engine.stop(force=True) t.join() assert 'engine' in t.value.errors assert 'terminated' in ...
27,905
def _get_xy_from_geometry(df): """ Return a numpy array with two columns, where the first holds the `x` geometry coordinate and the second column holds the `y` geometry coordinate """ # NEW: use the centroid.x and centroid.y to support Polygon() and Point() geometries x = df.geometry.centroi...
27,906
def create_styled_figure( title, name=None, tooltips=None, plot_width=PLOT_WIDTH, ): """Return a styled, empty figure of predetermined height and width. Args: title (str): Title of the figure. name (str): Name of the plot for later retrieval by bokeh. If not given the ...
27,907
def multiNodeMultDiskStripTest(): """ if you want to work from the monitoring vm: (remote option) on monitoring vm do, to make sure there are keys & ssh-agent is loaded js 'j.do.loadSSHAgent(createkeys=True)' #now logout & back login into that node, this only needs to happen once """ ...
27,908
def render_text(string, padding=5, width=None, height=None, size=12, font="Arial", fgcolor=(0, 0, 0), bgcolor=None): """ Render text to an image and return it Not specifying bgcolor will give a transparent image, but that will take a *lot* more work to build. Specifying a bgcolor, width...
27,909
def pretty_spectrogram(d,log = True, thresh= 5, fft_size = 512, step_size = 64): """ creates a spectrogram log: take the log of the spectrgram thresh: threshold minimum power for log spectrogram """ specgram = np.abs(stft(d, fftsize=fft_size, step=step_size, real=False, compute_onesided=...
27,910
def check_for_win(position, board, player): """ check for wins on 3x3 board on rows,cols,diag,anti-diag args: position (int 1-9, user input) board (np.array 2d) player ("X" or "O") """ #initialize win to False win = False #check win on rows for row in board: ...
27,911
def wrap_http_exception(app: FastAPI): """ https://doc.acrobits.net/api/client/intro.html#web-service-responses """ @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request, exc): return JSONResponse({'message': exc.detail}, exc.status_code)
27,912
def perm_2sample(group1, group2, nrand=10000, tail=0, paired=True): # Take from JW's functions """ non-parametric permutation test (Efron & Tibshirani, 1998) tail = 0 (test A~=B), 1 (test A>B), -1 (test A<B) """ a = group1 b = group2 ntra = len(a) ntrb = len(b) meana = np.mean(...
27,913
def _merge_cols(blocks, out_blocks, blocks_shape, skip): """ Merges the blocks into a single list of blocks where each block has bn as number of rows (the number of cols remains the same per block). """ bn, bm = blocks_shape data = Array._merge_blocks(blocks) for i in range(0, ceil(data.sha...
27,914
def test_reorder_lrt_ltr_var_rpts(): """ This reordering with variable repeats is not supported. In priciple it is possible (TI1_R1, TI2_R1, TI2_R2, TI2_R3) but this seems unlikely and is probably more likely an error """ d = np.zeros([5, 5, 5, 8]) for z in range(8): d[..., z] = z img =...
27,915
def softmax_op(node): """ This function computes its softmax along an axis. Parameters: ---- node : Node Input variable. Returns: ---- A new Node instance created by Op. """ return SoftmaxOp()(node)
27,916
def test_module_attribute() -> None: """Ensure module attributes' signatures.""" assert hasattr(lmp.model, 'BaseModel') assert hasattr(lmp.model, 'ElmanNet') assert hasattr(lmp.model, 'LSTM1997') assert hasattr(lmp.model, 'LSTM2000') assert hasattr(lmp.model, 'LSTM2002') assert hasattr(lmp.model, 'ALL_MOD...
27,917
def test_adls_gen2_file_event_filepath_when_whole_file_mode_disabled(sdc_builder, sdc_executor, azure): """ We want to make sure that the filepath attribute of an event generated by the ADLS gen2 destination contains only a file path and doesn't contain a schema. A misbehaviour normally happened before when...
27,918
def full_chain(): """ :return: Returns entire blockchain in memory (current_chain.blockchain) """ response = { 'chain': current_chain.blockchain, 'length': len(current_chain.blockchain), } return response, 200
27,919
def normalizer(x, mi, ma, eps=1e-20, dtype=np.float32): """ Number expression evaluation for normalization Parameters ---------- x : np array of Image patch mi : minimum input percentile value ma : maximum input percentile value eps: avoid dividing by zero dtype: type of numpy array...
27,920
def do(args): """ Main Entry Point. """ build_worktree = qibuild.parsers.get_build_worktree(args) sourceme = build_worktree.generate_sourceme() print(sourceme) return sourceme
27,921
def policy_action(module, state=None, policy_name=None, policy_arn=None, policy_document=None, path=None, description=None): """ Execute the actions needed to bring the policy into the specified state. ...
27,922
def GET_v1_metrics_location(days=1): """Return some data about the locations users have reported from. """ if days > 7: days = 7 from_time = f'-{days}d' locations = fetch_graphite_sum('*.geoip.*', from_time=from_time) return jsonify(locations=locations)
27,923
def present(*args, **kwargs): """ basically calls show if not embeded. Kwargs: max_rows, row_first, no_tile, monitor_num, percent_w, percent_h, hide_toolbar CommandLine: python -m wbia.plottool.fig_presenter present Example: >>> # DISABLE_DOCTEST >>> from w...
27,924
def add_default_to_usage_help( usage_help: str, default: str or int or float or bool ) -> str: """Adds default value to usage help string. Args: usage_help (str): usage help for click option. default (str or int or float): default value as string for click option. ...
27,925
def describe_deformation(el_disps, bfg): """ Describe deformation of a thin incompressible 2D membrane in 3D space, composed of flat finite element faces. The coordinate system of each element (face), i.e. the membrane mid-surface, should coincide with the `x`, `y` axes of the `x-y` plane. ...
27,926
def remove_emails(text): """Returns A String with the emails removed """ result = re.sub(EMAIL_REGEX, "", text) return result
27,927
def _fit_model_residual_with_radial(lmparams, star, self, interpfunc): """Residual function for fitting individual profile parameters :param lmparams: lmfit Parameters object :param star: A Star instance. :param self: PSF instance :param interpfunc: The interpolation function ...
27,928
def _whoami(): # type: () -> Tuple[str,str] """ Return the current operating system account as (username, fullname) """ username = getuser() fullname = username if GET_PW_NAM: pwnam = getpwnam(username) if pwnam: fullname = pwnam.pw_gecos.split(",", 1)[0] retu...
27,929
def text_set_class( set_class: Sequence, ) -> str: """Converts a set class into a string representing its interval vector. """ id_dict = {0: "one", 1: "two", 2: "three", 3: "four", 4: "five", 5: "six"} result = "" for i, el ...
27,930
def Span_read(stream): """Read a span from an 88.1 protocol stream.""" start = Address_read(stream) width = Offset_read(stream) return Span(start, width)
27,931
def analyze(label): """ Combination of the methods provided by ramanspectrum class. """ spec = ramanspectrum(label + '/data_' + label + '.txt', label = label) spec.SelectSpectrum() spec.SelectBaseline() spec.SelectPeaks() spec.FitSpectrum() spec.SaveFitParams()
27,932
def test_initial_states(): """Check the initial state of all parsers.""" p = TextParser() assert p is not None p = MarkdownParser() assert p is not None p = HtmlParser() assert p is not None p = ReStructuredTextParser() assert p is not None p = AsciidocParser() assert p i...
27,933
def temp_database(tmpdir_factory): """ Initalize the Database """ tmpdb = str(tmpdir_factory.mktemp('temp'))+"/testdb.sqlite" return tmpdb
27,934
def play_smithy(game): """ +3 Cards """ game.player_state.draw_cards(3)
27,935
def walk_with_depth( base_dir:str, depth=1, followlinks=True, ) -> Iterator[Tuple[str, List[str], List[str]]]: """Walk a directory with a max depth. This is similar to os.walk except it has an optional maximum directory depth that it will walk """ base_dir = base_dir.rstrip(os.path.sep) ...
27,936
def get_classes(pyfile_path): """ Obtiene las clases que están dentro de un fichero python :param str pyfile_path: nombre del fichero a inspeccionar :return: devuelve una lista con todas las clases dentro de un fichero python :rtype: list .. code-block:: python >> get_classes('./data....
27,937
def transpose_outer_dimensions(outer_dimensions: ST_Type, diff_dimensions: ST_Type, ports_to_transpose: List) -> Kind: """ Transpose the outer dimensions of a set of ports, move them inside the diff dimensions. The outer dimensions that are sseqs are the same for all elements, so treat as inner dimensions. ...
27,938
def pad_or_clip_nd(tensor, output_shape): """Pad or Clip given tensor to the output shape. Args: tensor: Input tensor to pad or clip. output_shape: A list of integers / scalar tensors (or None for dynamic dim) representing the size to pad or clip each dimension of the input tensor. Ret...
27,939
def _hr_ensemble_plot_end_phase_annotation(ax: plt.Axes, data: pd.DataFrame, phase: str, i: int, **kwargs): """Add End Phase annotations to heart rate ensemble plot. Parameters ---------- ax : :class:`matplotlib.axes.Axes` axes object data : :class:`~pandas.DataFrame` data belonging...
27,940
def dynamic_lstm(x, n_neuron, act_fn=tanh, seq_len=None): """ assert x is batch_major, aka [batch, time, ...] """ cell_class = lstm with tf.variable_scope("fw"): cell_fw = cell_class(n_neuron, activation=act_fn, cell_clip=15.0) o, s = tf.nn.dynamic_rnn( cell_fw, x, seq_len, ...
27,941
def ho2ax_single(ho): """Conversion from a single set of homochoric coordinates to an un-normalized axis-angle pair :cite:`rowenhorst2015consistent`. Parameters ---------- ho : numpy.ndarray 1D array of (x, y, z) as 64-bit floats. Returns ------- ax : numpy.ndarray 1D a...
27,942
def construct(): """Construct file to be used in graph.""" def add(data, br, km, year, events): """Calculate critical level and insert events and in data dict.""" if br not in data: data[br] = {} if km not in data[br]: data[br][km] = {} accidents = events....
27,943
def task_export_commit(request): """提交导出任务""" try: datas = json.loads(request.body.decode()) taskSetting = PlTaskSetting.objects.get(id=datas["params"]["id"]) try: exportJob = PlExportJob.objects.get(task_setting_id=taskSetting.id) except ObjectDoesNotExist: ...
27,944
def getExceptionMessage(exceptionDetails: dict) -> str: """Get exception message from `exceptionDetails` object.""" exception = exceptionDetails.get('exception') if exception: return exception.get('description') message = exceptionDetails.get('text', '') stackTrace = exceptionDetails.get('st...
27,945
def evaluate_by_net(net, input_fn, **kwargs): """encapsulate evaluate """ ret = evaluate( graph=net.graph, sess=net.session, fea_ph=net.features_ph, label_ph=net.labels_ph, outputs=net.outputs, input_fn=input_fn, **kwargs ) return ret
27,946
def flush(): """Try to flush all stdio buffers, both from python and from C.""" try: sys.stdout.flush() sys.stderr.flush() except (AttributeError, ValueError, IOError): pass
27,947
def ordinate(values,maxrange,levels): """Ordinate values given a maximum data range and number of levels Parameters: 1. values: an array of continuous values to ordinate 2. maxrange: the maximum data range. Values larger than this will be saturated. 3. levels: the number of levels at which valu...
27,948
def is_start_state(state): """ Checks if the given state is a start state. """ return (state.g_pos.value == 0) and (state.theta.value == 'N')
27,949
def days_in_month(year, month): """ return number of days in that month in that year """ if not 1 <= month <= 12: return 'Invalid Month' if month == 2 and is_leap(year): return 29 return month_days[month]
27,950
def tmm_normal(fPath, bFilter=True): """ Function to obtain the Voom normal Count Args: fPath string Path with the raw counts outPath string File output bFilter Bool Bool to FIlter low expression genes Returns: tmm dataframe DataFrame with the log2(TMM) counts ...
27,951
def StrainFitness(all_cix_series, all_cntrl_sum, debug_print=False): """ Args: all_cix_series (pandas Series): The current experiment name column of values from all_df_used length = nAllStrainsCentralGoodGenes all_cntrl_sum...
27,952
def np_to_base64(img_np): """ Convert numpy image (RGB) to base64 string """ img = Image.fromarray(img_np.astype("uint8"), "RGB") buffered = BytesIO() img.save(buffered, format="PNG") return "data:image/png;base64," + base64.b64encode( buffered.getvalue()).decode("ascii")
27,953
def sample_unknown_parameters(_params, _n=None): """ AW - sample_unknown_parameters - Sample the parameters we do not fix and hence wish to marginalize over. :param _params: SimpNameSp: dot accessible simple name space of simulation parameters. :return: SimpNameSp: dot accessible simple name spac...
27,954
def vector2Table (hdu, xlabel='wavelength',ylabel='flux') : """ Reads a 1-D vector from a FITS HDU into a Table. If present, the wavelength scale is hopefully in a simple, linear WCS! """ hdr = hdu.header if hdr['NAXIS'] != 1 : logging.error ('vector2Table can only construct 1-D tables!') return None nw = hd...
27,955
def subscribe(symbol: Text, app_name: str = "current_app") -> None: """订阅""" if app_name == "current_app": app = current_app else: app = get_app(app_name) if not app.config.get("MD_FUNC"): raise MarketError(message="行情功能未开启, 无法进行订阅") app.market.subscribe(symbol)
27,956
def get_zarr_size(fn): """Get size of zarr file excluding metadata""" # Open file grp = zarr.open_group(fn) # Collect size total = 0 for var in list(grp.keys()): total += grp[var].nbytes_stored return total
27,957
def rotation_matrix(a, b): """ Calculate rotation matrix M, such that Ma is aligned to b Args: a: Initial vector direction b: Target direction """ # np.allclose might be safer here if np.array_equal(a, b): return np.eye(3) # Allow cases where a,b are not unit vectors, s...
27,958
def bind(filename=None, blockpairs=1): """ Open a connection. If filename is not given or None, a filename is chosen automatically. This function returns blockpairs number of Writer, Reader pairs. """ # Open memory mapped file, deduced file size from number of blocks size = HEAD_SIZE + blockpair...
27,959
def tmp_trestle_dir(tmpdir: pathlib.Path) -> pathlib.Path: """Create and return a new trestle project directory using std tmpdir fixture. Note that this fixture relies on the 'trestle init' command and therefore may misbehave if there are errors in trestle init. """ pytest_cwd = pathlib.Path.cwd() ...
27,960
def saveuserprefs(): """ Fetch the preferences of the current user in JSON form """ user = current_user() j = request.get_json(silent=True) # Return the user preferences in JSON form uf = UserForm() uf.init_from_dict(j) err = uf.validate() if err: return jsonify(ok=False, err=e...
27,961
def process_args(args): """ Process the options got from get_args() """ args.input_dir = args.input_dir.strip() if args.input_dir == '' or not os.path.exists(os.path.join(args.input_dir, 'model.meta')): raise Exception("This scripts expects the input model was exist in '{0}' directory.".format(...
27,962
def make_features(batch, side, data_type='text'): """ Args: batch (Tensor): a batch of source or target data. side (str): for source or for target. data_type (str): type of the source input. Options are [text|img|audio]. Returns: A sequence of src/tgt tensors with...
27,963
def page_dirs_to_file_name(page_dirs): """ [カテゴリ1,カテゴリ2,ページ]というディレクトリの配列状態になっているページパスを 「カテゴリ1_._カテゴリ2_._ページ」というファイル名形式に変換する。 :param page_dirs: :return: """ file_name = "" for page_dir in page_dirs: if page_dir: file_name = file_name + page_dir.strip() + '_._' fil...
27,964
def has_field(feature_class, field_name): """Returns true if the feature class has a field named field_name.""" for field in arcpy.ListFields(feature_class): if field.name.lower() == field_name.lower(): return True return False
27,965
def test_connection_dialog_remembers_input_with_ssh_passphrase( qtbot, connection_dialog_factory): """ Test that the dialog remembers the user's kernel connection settings and ssh key passphrase when the user checks the save checkbox. """ dlg = connection_dialog_factory.submit_filled_di...
27,966
def avg_speed_over_time(file_path): """[Graphs average speed over time] """ # reads in activities df df = pd.read_csv(file_path) #Create new dataframe with only columns I care about cols = ['name', 'upload_id', 'type', 'distance', 'moving_time', 'average_speed', 'max_speed','to...
27,967
def process_settings(settings: AttrDict, params: T.Optional[T.Set[str]] = None, ignore: T.Iterable[str]=()) -> AttrDict: """ Process an dict-like input parameters, according to the rules specified in the `Input parameter documentation <https://sqsgenerator.readthedocs.io/en/latest/input_parameters.html>`_....
27,968
def serialize_block(block: dict) -> Block: """Serialize raw block from dict to structured and filtered custom Block object Parameters ---------- block : dict Raw KV block data from gRPC response Returns ------- Block Structured, custom defined Block object for more controll...
27,969
def add_f08_to_env(env) -> None: """Add Builders and construction variables for f08 dialect.""" try: F08Suffixes = env['F08FILESUFFIXES'] except KeyError: F08Suffixes = ['.f08'] try: F08PPSuffixes = env['F08PPFILESUFFIXES'] except KeyError: F08PPSuffixes = [] Di...
27,970
def repr_pandas_Series(series, _): """ This function can be configured by setting the `max_rows` attributes. """ from pandas import get_option return series.to_string( max_rows=repr_pandas_Series.max_rows, name=series.name, dtype=series.dtype, length=get_option("disp...
27,971
def convert_fmt(fmt): """rs.format to pyglet format string""" return { rs.format.rgb8: 'RGB', rs.format.bgr8: 'BGR', rs.format.rgba8: 'RGBA', rs.format.bgra8: 'BGRA', rs.format.y8: 'L', }[fmt]
27,972
def train_ALS(train_data, validation_data, num_iters, reg_param, ranks): """ Grid Search Function to select the best model based on RMSE of hold-out data """ # initial min_error = float('inf') best_rank = -1 best_regularization = 0 best_model = None for rank in ranks: for reg...
27,973
def coral_command_bootstrap(tsinghua_mirror=False): """ Bootstrap the command by installing the dependencies. """ # pylint: disable=unused-variable local_host = ssh_host.get_local_host(ssh=False) log = clog.get_log(console_format=clog.FMT_NORMAL) distro = local_host.sh_distro(log) if dis...
27,974
def parse_input_vspec (opts): """Parses input from vspec and returns excitation energies in the form [energy, f], in eV and atomic units units, respectively.""" lines = sys.stdin.readlines () inside_data = False roots = [] for l in lines: if "<START>" in l: try...
27,975
def is_yaml_file(filename): """Return true if 'filename' ends in .yml or .yaml, and false otherwise.""" return os.path.splitext(filename)[1] in (".yaml", ".yml")
27,976
def response_ack(**kwargs): """ Policy-based provisioning of ACK value. """ try: tlv, code, policy, post_c2c = kwargs["tlv"], kwargs["code"], kwargs["policy"], kwargs["post_c2c"] new_tlv = copy.deepcopy(tlv) if post_c2c is not True: ret = policy.get_available_policy(...
27,977
def is_file(path, use_sudo=False): """ Check if a path exists, and is a file. """ func = use_sudo and sudo or run with settings(hide('running', 'warnings'), warn_only=True): return func('[ -f "%(path)s" ]' % locals()).succeeded
27,978
def test_p6(): """ Test some joint and conditional perplexities """ d = D(['00', '11'], [1/2]*2) assert P(d) == pytest.approx(2) assert P(d, [0], [1]) == pytest.approx(1) assert P(d, [1], [0]) == pytest.approx(1)
27,979
def component(project_dir, *args, **kwargs): """CLI for generate MLOps archetypes.""" try: cwd = Path().cwd() / project_dir Interface().component(cwd, *args, **kwargs) except Exception as error: logger.exception(error) sys.exit(0)
27,980
def bounded_random_walk(minval, maxval, delta_min, delta_max, T, dtype=tf.float32, dim=1): """ Simulates a random walk with boundary conditions. Used for data augmentation along entire tube. Based on: https://stackoverflow.com/questions/48777345/vectorized-random- ...
27,981
def validate_photo_url(photo_url, required=False): """Parses and validates the given URL string.""" if photo_url is None and not required: return None if not isinstance(photo_url, str) or not photo_url: raise ValueError( 'Invalid photo URL: "{0}". Photo URL must be a non-empty ' ...
27,982
def to_flp(stipples, dpi=300, x_mm=0, y_mm=0, laser_pwr=35000, ticks=500, base=100): """" Converts a set of stipples into a list of FLP packets dpi is the image's DPI x_mm and y_mm are the corner location of the image (default 0,0) (where 0,0 is the center of the b...
27,983
def GetSchema(component): """convience function for finding the parent XMLSchema instance. """ parent = component while not isinstance(parent, XMLSchema): parent = parent._parent() return parent
27,984
def save_status(filename: str, status: StatusList) -> None: """ ファイルにステータスを追記する -------- :type status: StatusList :param filename: 書き込むファイル名 :param status: 書き込むデータ :return: None """ result = status.out_tuple() with open(filename, mode='a', encoding="utf-8")as f: writer ...
27,985
def ranked_bots_query(alias="ranked_bots"): """ Builds a query that ranks all bots. This is a function in case you need this as a subquery multiple times. """ return sqlalchemy.sql.select([ bots.c.user_id, bots.c.id.label("bot_id"), bots.c.mu, bots.c.sigma, b...
27,986
def marathon_deployments_check(service): """Checks for consistency between deploy.yaml and the marathon yamls""" the_return = True pipeline_deployments = get_pipeline_config(service) pipeline_steps = [step['instancename'] for step in pipeline_deployments] pipeline_steps = [step for step in pipeline_...
27,987
def get_book_info(book_id, books): """Obtain meta data of certain books. :param book_id: Books to look up :type: int or list of ints :param books: Dataframe containing the meta data :type: pandas dataframe :return: Meta data for the book ids :rtype: List[str], List[str], List[str] "...
27,988
def save_error_message(func): """ This function will work only if transition_entity is defined in kwargs and transition_entity is instance of ErrorMessageMixin """ @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except Exception ...
27,989
def EMV(data,n=20,m=23): """ """ def emv(high,low,vol,n=14): MID = np.zeros(len(high)) MID[1:] = (np.array(high[1:])+np.array(low[1:])-np.array(high[:-1])-np.array(low[:-1]))/2. BRO = np.array(vol)/(100000000.*(np.array(high)-np.array(low))) EM = MID/BRO return ta.S...
27,990
def desired_directions(state: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Given the current state and destination, compute desired direction.""" destination_vectors = state[:, 4:6] - state[:, 0:2] directions, dist = normalize(destination_vectors) return directions, dist
27,991
def binary_repr(number, max_length = 1025): """ Return the binary representation of the input *number* as a string. This is more efficient than using :func:`base_repr` with base 2. Increase the value of max_length for very large numbers. Note that on 32-bit machines, 2**1023 is the largest int...
27,992
def df_fc_overlap_9(): """Scenario case with 3 sets of 2 overlapping fragments, bound to a common combination of 2 redundant fragments.""" mol = Chem.MolFromSmiles('NC1C(O)C(CCCC2CC2CCC2CC2)C1CCC1CC(C(N)C1O)C1CCC(O)C(N)C1') return DataFrame([ ['mol_fc_overlap_9', 'XXX', 'O1', 0, 'O1:0', ...
27,993
def check_cal(es_url, es_index, id): """Query for calibration file with specified input ID.""" query = { "query":{ "bool":{ "must": [ { "term": { "_id": id } }, ] } }, "fields": [], } if es_url.endswith...
27,994
def mountpoint_create(name, size): """Service Layer to create mountpoint""" mountpoint = MountPoint(name, size) return mountpoint
27,995
def test_torch_transform(ctx): """try using torch.Transform in combination with bgflow.Flow""" torch.manual_seed(10) x = torch.torch.randn(10, 3, **ctx) flow = SequentialFlow([ TorchTransform(IndependentTransform(SigmoidTransform(), 1)), TorchTransform( AffineTransform( ...
27,996
def test_get_desired_value(): """Test that sensor returns correct desired value in different states.""" const = get_const("1.4") sensor_id = 1 child_id = 0 value_type = const.SetReq.V_LIGHT_LEVEL wrong_child_id = 100 wrong_value_type = 9999 sensor = Sensor(sensor_id) sensor.add_chil...
27,997
def test_halo_update_timer( zeros_quantity_list, communicator_list, n_points_update, n_points, numpy, subtests, boundary_dict, ranks_per_tile, ): """ test that halo update produces nonzero timings for all expected labels """ halo_updater_list = [] for communicator, qu...
27,998
def install(user=False, symlink=False, overwrite=False, **kwargs): """Install the bqplot nbextension. Parameters ---------- user: bool Install for current user instead of system-wide. symlink: bool Symlink instead of copy (for development). overwrite: bool Overwrite pre...
27,999