content
stringlengths
22
815k
id
int64
0
4.91M
def dcgan32(): """Commands related to DCGAN32"""
5,298,600
def entropy(values): """A slow way to calculate the entropy of the input values""" values = values.flatten() #calculate the probablility of a value in a vector vUni = sp.unique(values) vlen = len(vUni) lenval = float(len(values)) FreqData = sp.zeros_like(vUni) for i in range(le...
5,298,601
def remove_brackets(s: pd.Series) -> pd.Series: """ Remove content within brackets and the brackets itself. Remove content from any kind of brackets, (), [], {}, <>. Examples -------- >>> import texthero as hero >>> import pandas as pd >>> s = pd.Series("Texthero (round) [square] [curl...
5,298,602
def create_transit(transit, venue, event_sku, geo=None): """Add keys for transit search unit""" p.sadd(create_key_name("transit", transit, "events"), event_sku) if geo is not None: p.geoadd(create_key_name("geo", "transits", transit), geo['long'], geo['lat'], venue)
5,298,603
def test_executor_error_override( batch_submit_mock, iter_batch_job_status_mock, parse_task_logs_mock, get_aws_user_mock ) -> None: """ Some AWS Batch errors should be overridden. """ @task() def task1(x): return x + 10 @task(script=True) def task_script1(x): return "ls...
5,298,604
def blur(img): """ :param img: SimpleImage, the image to be blurred :return: SimpleImage, the blurred image """ # Create a blank frame for blurred pixels. blur_img = SimpleImage.blank(img.width, img.height) # Loop the original image. for x in range(img.width): for y in range(img....
5,298,605
def convert_grayscale(img_path: str): """ Convert the image in img_path to grayscale. It overwrites existing image :param img_path: :return: """ img = Image.open(img_path).convert('L') os.remove(img_path) img.save(img_path, quality=100)
5,298,606
def not_a_seq_complex(request: Any) -> Any: """Provide random values that are not sequences of complexs.""" return request.param[1]
5,298,607
def printenergy(a=atoms): """Function to print the potential, kinetic and total energy.""" epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), ...
5,298,608
def ignore_stderr(): """ A context manager to ignore stderr. We use it to avoid PyAudio pulluting the console output. Credits to: https://stackoverflow.com/questions/36956083/how-can-the-terminal-output-of-executables-run-by-python-functions-be-silenced-i/36966379#36966379 """ devnull = os.o...
5,298,609
def test_parameter_values( loader: AWSParameterStore, ) -> None: """compare parameters from mocked loader to what we put in there""" # loading succeeded assert loader.load_values(aws_sstore_name=TEST_PATH, aws_region_name=TEST_REGION) # both our parameters exist and have the expected value asse...
5,298,610
def generate_markov_models(user_names): """ Builds a dictionary of user_name :: Markov text models from the text corpus of each user. :param user_names: A list of the users' names to build. Assumes there is a corresponding "user.txt" corpus available :return: text_models - a dictionary of users and thei...
5,298,611
def planckian_table(uv, cmfs, start, end, count): """ Returns a planckian table from given *CIE UCS* colourspace *uv* chromaticity coordinates, colour matching functions and temperature range using *Yoshi Ohno (2013)* method. Parameters ---------- uv : array_like *uv* chromaticity c...
5,298,612
def vault_subscribe(): """ Subscribe to a remote vault service on the specific hive node, where would create a new vault service if no such vault existed against the DID used. A user can subscribe to only one vault service on the specific hive node with a given DID, then should declare that service end...
5,298,613
def atrim(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#atrim""" return filter(stream, atrim.__name__, *args, **kwargs)
5,298,614
def cut_transcript_seq(seq: str, tag: str): """ Some of the sequences contain length % 3 != 0, because they have ambiguous start and/or end. If this is the case, they should be cut until length % 3 == 0 There are sequences which have both ambiguous start and end => no solution yet :param seq: dna se...
5,298,615
def kama(df, price, kama, n, fast_ema=2, slow_ema=30): """ Kaufman's Adaptive Moving Average (KAMA) is a moving average designed to account for market noise or volatility. KAMA will closely follow prices when the price swings are relatively small and the noise is low. KAMA will adjust when the price...
5,298,616
def NumpyDecoder(dct): """ Decodes a previously encoded numpy ndarray with proper shape and dtype :param dct: (dict) json encoded ndarray :return: (ndarray) if input was an encoded ndarray """ if isinstance(dct, dict) and '__ndarray__' in dct: if 'dtype' in dct: data = b...
5,298,617
def get_silverkite_uncertainty_dict( uncertainty, simple_freq=SimpleTimeFrequencyEnum.DAY.name, coverage=None): """Returns an uncertainty_dict for `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` input parameter: uncertainty_dict. The logic is...
5,298,618
def get_xclarity_client(): """Generates an instance of the XClarity client. Generates an instance of the XClarity client using the imported xclarity_client library. :returns: an instance of the XClarity client :raises: XClarityError if can't get to the XClarity client """ try: xcla...
5,298,619
def create_vgg_model_2d(input_image_size, number_of_classification_labels=1000, layers=(1, 2, 3, 4, 4), lowest_resolution=64, convolution_kernel_size=(3, 3), pool_size=(2, 2), ...
5,298,620
def add_args_to_parser(parser, args): """ Traverse a tuple of argments to add to a parser :param parser: Instance of a parser, subparser, or argument group :type sys_args: argparse.ArgumentParser :param args: Tuple of tuples, format ((arg1, arg2), {'kwarg1':'val1'},) :type sys_args: tuple ...
5,298,621
def write_header(fh, size): """ Write the <head> including css """ side_margin = 10 square_size = 40 fh.write("""<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> div.clear { clear: both; } div.clear_left { clear: left; } div.side { margin: %dpx; float: left; } """...
5,298,622
def _transition_down_block(x, nb_filter, bn_momentum, weight_decay=1e-4, transition_pooling='max', block_prefix='TransitionDown', data_format='channels_last'): """ Adds a pointwise convolution layer (with batch normalization and relu), and a pooling layer. The bloc...
5,298,623
def collect_mentioned( obj: Union[RawFactor, List[Union[RawFactor, str]]], mentioned: Optional[Mentioned] = None, ignore: Sequence[str] = ( "predicate", "anchors", "factor_anchors", "enactment_anchors", "enactments", ), ) -> Tuple[RawFactor, Mentioned]: """ ...
5,298,624
def test_maxfilter_get_rank(n_proj, fname, rank_orig, meg): """Test maxfilter rank lookup.""" raw = read_raw_fif(fname).crop(0, 5).load_data().pick_types() assert raw.info['projs'] == [] mf = raw.info['proc_history'][0]['max_info'] assert mf['sss_info']['nfree'] == rank_orig assert _get_rank_sss...
5,298,625
def run_property_test(module, test, dirname=None): """This function runs a single robustness test.""" mod = importlib.import_module('trempy.tests.' + module.replace('.py', '')) test_fun = getattr(mod, test) # We do not switch directories if we are investigating a failed test case. if dirname is not...
5,298,626
def add(x, y): """相加""" return x + y
5,298,627
def save_in_cpu_load_in_cpu(): """ cpu 下训练 save cpu load :return: """ seed = 90 epoch_num = 1 BATCH_SIZE = 64 # np.set_printoptions(precision=3, suppress=True) diff_var_save = {} diff_var_load = {} with fluid.dygraph.guard(fluid.CPUPlace()): fluid.default_startup_pr...
5,298,628
def calculate_mmc(y_true, y_pred): """Using sklearn to compute the Matthews correlation coefficient (MCC). Arguments: y_true {numpy.array} -- the true labels corresponding to each input y_pred {numpy.array} -- the model's predictions Returns: mmc {float} -- the calcu...
5,298,629
def find_deepest_user_frame(tb): """ Find the deepest stack frame that is not part of SCons. Input is a "pre-processed" stack trace in the form returned by traceback.extract_tb() or traceback.extract_stack() """ tb.reverse() # find the deepest traceback frame that is not part # of SCo...
5,298,630
def test_put_vector_wrong_column(): """ Check that it fails with an exception when giving an invalid column. """ with clib.Session() as lib: dataset = lib.create_data( family="GMT_IS_DATASET|GMT_VIA_VECTOR", geometry="GMT_IS_POINT", mode="GMT_CONTAINER_ONLY", ...
5,298,631
def _get_element_imports(*elements: Element) -> str: """Get the import string for the elements in use.""" prefix = "from statham.schema.elements import " max_length = 80 import_names = [ elem_type.__name__ for elem_type in set.union( *(_get_single_element_imports(element) for...
5,298,632
async def test_start_fail_restarting(): """ Start a process that fails & make sure it restarts """ proc = simpervisor.SupervisedProcess( inspect.currentframe().f_code.co_name, *sleep(1), always_restart=True ) await proc.start() assert proc.running first_pid = proc.pid await a...
5,298,633
def getSpawnProcPIDs(): """Fetch all running DummyMP system process IDs. Looking through all of the DummyMP processes, determine if any are running, and if any, retrieve their system process IDs. Args: None Returns: list: An list with the system process IDs of current ...
5,298,634
def posdef(m): """Map a matrix to a positive definite matrix, where all eigenvalues are >= 1e-5.""" mlambda, mvec = jnp.linalg.eigh(m) mlambda = jnp.maximum(mlambda, 1e-5) return (mvec * jnp.expand_dims(mlambda, -2)) @ jnp.swapaxes(mvec, -2, -1)
5,298,635
def error_500_view(request): """ Renders the 500 error page. """ return render(request, 'climate/500.html')
5,298,636
def stop(): """Stop blocking. (requires admin priviledges)""" logging.info("Action Trigger: Stop") global status if status is Status.OPEN: return removeDomainsFromHosts() status = Status.OPEN
5,298,637
def get_congratulation_template(elapsed_time: int) -> str: """ Получение шаблона при победе, в зависимости от окончания числа секунд игры. """ if 11 <= elapsed_time <= 19 or elapsed_time % 10 in (0, 5, 6, 7, 8, 9): template = "Поздравляем, вы прошли игру за {elapsed_time} секунд!" elif e...
5,298,638
def _get_column(column): """ Helper to get a ``Column`` object if the given argument is a string """ if isinstance(column, six.text_type): column = col(column) if not isinstance(column, Column): raise ValueError('A Column or a column name (as a string) is expected. Got {!r}'.format(c...
5,298,639
def smooth(path, weight_data=0.1, weight_smooth=0.2, tolerance=0.000001): """ Creates a smooth path for a n-dimensional series of coordinates. Arguments: path: List containing coordinates of a path weight_data: Float, how much weight to update the data (alpha) weight_smooth: Float, h...
5,298,640
def tx2g(ctx, input,abstraction): """This command loads DiVA database transactions into a graph""" if ctx.obj["verbose"]: click.echo("Verbose mode: ON") class_transaction_loader = ClassTransactionLoader() method_transaction_loader = MethodTransactionLoader() if abstraction.lower() == "ful...
5,298,641
def CDLDOJI(barDs, count): """Doji""" return call_talib_with_ohlc(barDs, count, talib.CDLDOJI)
5,298,642
def google_auth_installed( secret_file: str, token_file: str, scopes: List[str] ) -> Credentials: """Authenticate installed applications with Google""" try: with open(token_file, "rt") as token_file: token_data = json.load(token_file) credentials = Credentials( None, ...
5,298,643
def get_ceda_file( # type: ignore filepath=None, site=None, instrument=None, height=None, write_yaml=False, date_range=None, ): """Creates a JSON (with a yaml extension for CEDA reasons) object for export for a CEDA upload Args: filepath (str or Path, default=None): Path fo...
5,298,644
def test_cof_context_key_groups_required(): """A CoF requires context_key groups in context.""" with pytest.raises(KeyNotInContextError) as err: cof_func('blah', None, Context({'key': {'a': 'b'}}), 'key') assert str(err.value) == ("key needs a child key 'groups', which should " ...
5,298,645
def _find_notebook(fullname, path=None): """ Find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: path ...
5,298,646
def make_wheel(num_colors): """ Same as default, but just loops around the same num_colors colors in a circle. """ colors = list(default(num_colors)) i = 0 while True: if i >= len(colors): i = 0 yield color[i] i += 1 return
5,298,647
def plot_heatmap(camera_image, grasps, grasp_qualities, kernel_size=11): """Plot the final grasp. Args: camera_image: The whole image captured from the camera. grasps: The chosen Grasp2D instance. grasp_qualities: The predicted grasp qu...
5,298,648
def parallel(): """ Starts a number of threads that search through the key space """ p = Pool(CPU_COUNT) p.map(worker, gen(), chunksize=2) p.close() p.join()
5,298,649
def parse_variable_name(packed_bytes): """ Unpack a 6-bit packed variable name """ variable_name = "" this_char = 0 read_bits = 0 for byte in packed_bytes: # Read six bits at a time for bit in range(0, 8): bit_value = 1 & (byte >> (7 - bit)) this_char = this_...
5,298,650
def _edge_matcher(digraph, nxpattern, node_pred, edge_pred): """ Match individual edges. """ pedge = next(iter(nxpattern.edges)) pu = nxpattern.nodes[pedge[0]] pv = nxpattern.nodes[pedge[1]] if edge_pred is None: for u, v in digraph.edges: if (node_pred(digraph.nodes[u], pu) ...
5,298,651
def divide(self, other, op_cols, **kwargs): """ Divide values (self / other) Parameters ---------- other : :class:`ScmRun <scmdata.run.ScmRun>` :class:`ScmRun <scmdata.run.ScmRun>` containing data to divide op_cols : dict of str: str Dictionary containing the columns to drop be...
5,298,652
def tokenize_code(blob, language='java'): """ :param blob: :param language: :return: """ if language == 'python': parsed_code = astor.to_source(ast.parse(blob)) tokenized_code = [x for x in RegexpTokenizer(r'\w+').tokenize(parsed_code) if not is_numeric(x)] return tokeni...
5,298,653
def create_love_relationship(user, posts): """Creates a love relationship between a profile/user and a post Args: user -- user who is a fan of the post post -- a list of posts Returns: a list of loves """ loves = [] for post in posts: loves.append(LoveFactory(fan=...
5,298,654
def safe_allocate_random_udp_socket(host: str = "127.0.0.1", is_reused: bool = False) -> socket: """ @is_reused<bool> -- enable socket reuse. """ udp_socket = unsafe_allocate_random_udp_socket(host=host, is_reused=is_reused) try: yield udp_socket finally: try: udp_socket.close() ...
5,298,655
def task_run_black(): """ calls black code formatter """ task = { 'actions': ['black textwalker'], 'verbosity': 2 } return task
5,298,656
def to_weld_vec(weld_type, ndim): """Convert multi-dimensional data to WeldVec types. Parameters ---------- weld_type : WeldType WeldType of data. ndim : int Number of dimensions. Returns ------- WeldVec WeldVec of 1 or more dimensions. """ for i in ran...
5,298,657
def imq_kernel(x, y, score_x, score_y, g=1, beta=0.5, return_kernel=False): """Compute the IMQ Stein kernel between x and y Parameters ---------- x : torch.tensor, shape (n, p) Input particles y : torch.tensor, shape (n, p) Input particles score_x : torch.tensor, shape (n, p) ...
5,298,658
def get_target_config_dict(target_obj): """Gets target config as a dict from object :param target_obj: target object :type target_obj: :return: Target config :rtype: `dict` """ target_config = dict(TARGET_CONFIG) if target_obj: for key in list(TARGET_CONFIG.keys()): ...
5,298,659
def blend(m): """Blend colors.""" base = m.group('base') color = m.group('color') blend_type = m.group('type') percent = m.group('percent') if percent.endswith('%'): percent = float(percent.strip('%')) else: percent = int(alpha_dec_normalize(percent), 16) * (100.0 / 255.0) ...
5,298,660
def get_solution(program: Program, monomial: Poly): """ For a given monomial returns its expected value by first checking if it already has been computed and stored """ log(f"Start get solution, { monomial.as_expr() }", LOG_VERBOSE) global solution_store if monomial_is_constant(monomial): ...
5,298,661
def point_cloud_label_to_volume_batch(point_clouds, labels, weights, vsize=12, radius=1.1, flatten=True): """ Input is BxNx3 batch of point cloud Output is Bx(vsize^3) """ vol_list = [] label_list = [] weight_list = [] for b in range(point_clouds.shape[0]): vol, label, weight = p...
5,298,662
def theaterChase(strips, color, wait_ms=50, iterations=10): """Movie theater light style chaser animation.""" astrip = strips[0] for j in range(iterations): for q in range(3): for strip in strips: for i in range(0, strip.numPixels(), 3): strip.set(i+q, color) ...
5,298,663
def box_to_center_scale(box, model_image_width, model_image_height): """convert a box to center,scale information required for pose transformation Parameters ---------- box : list of tuple list of length 2 with two tuples of floats representing bottom left and top right corner of a...
5,298,664
def build_rgb_and_opacity(s): """ Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. EXAMPLE:: >>> build_rgb_and_opacity('ee001122') ('#221100', 0.93) """ # Set defaults color = '000000' opacity = 1 ...
5,298,665
def design_sosmat_band_passes(order, band_edges, sample_rate, edge_correction_percent=0.0): """Return matrix containig sos coeffs of bandpasses. Parameters ---------- order : int Order of the band pass filters. band_edges : ndarray Band edge frequencies...
5,298,666
async def shorten(long_url: str, api_base: str, api_key: str): """ Creates a short url if valid. """ params = { 'url': long_url, 'key': api_key, 'response_type': 'json' } async with aiohttp.ClientSession() as sess: async with sess.get(api_base + '/api/v2/action/sh...
5,298,667
def policy_iteration(problem_data, problem_data_known, K0, L0, sim_options=None, num_iterations=100, print_iterates=True): """Policy iteration""" problem_data_keys = ['A', 'B', 'C', 'Ai', 'Bj', 'Ck', 'varAi', 'varBj', 'varCk', 'Q', 'R', 'S'] A, B, C, Ai, Bj, Ck, varAi, varBj, varCk, Q, ...
5,298,668
def maintainers(path): """Return maintainers of a package at the given path.""" pkg = catkin_pkg.package.parse_package(path) for m in pkg.maintainers: yield m.name, m.email
5,298,669
def add_lldp_filter_by_host(query, hostid): """Adds a lldp-specific ihost filter to a query. Filters results by host id if supplied value is an integer, otherwise attempts to filter results by host uuid. :param query: Initial query to add filter to. :param hostid: host id or uuid to filter results...
5,298,670
def add_new_balance(event_id, balance_amount, account_number): """Add updated balance to database parms: event object amount accountnumber """ c.execute(""" INSERT INTO balances (event_id, balance, account_number) VALUES ({ei}, {ba}, {an});""".format(ei=e...
5,298,671
def usage_demo(): """ Demonstrates some ways to use the functions in this module. This demonstration reads the lines from this Python file and sends the lines in batches of 10 as messages to a queue. It then receives the messages in batches until the queue is empty. It reassembles the lines of the ...
5,298,672
def delta(f, s, d=None): """ Create a delta for the file `f` using the signature read from `s`. The delta will be written to `d`. If `d` is omitted, a temporary file will be used. This function returns the delta file `d`. All parameters must be file-like objects. """ if d is None: d ...
5,298,673
def wrap(func): """ Return a wrapped function object. If arg is already a wrapped function object, return that. Parameters ---------- func : function or OMwrappedFunc A plain or already wrapped function object. Returns ------- OMwrappedFunc The wrapped function obj...
5,298,674
def delete_channel(medialive, event, context): """ Delete a MediaLive channel Return success/failure """ channel_id = event["PhysicalResourceId"] try: # stop the channel medialive.stop_channel(ChannelId=channel_id) # wait untl the channel is idle, otherwise the lambda w...
5,298,675
def relevant_files(root_dir, include_regex='', exclude="*****"): """Return list of files with inclusion regex and exclusion regex. inputs: "root_dir" is the root directory "include_regex" is the string that is searched for within filenames "exclude_regex" is the string that will exclude files if fo...
5,298,676
def edges_and_nodes_csv_to_graph(fpath_nodes, fpath_edges, u_tag = 'stnode', v_tag = 'endnode', geometry_tag = 'Wkt', largest_G = False): """ Function for generating a G object from a saved .csv of edges :param fpath_nodes: path to a .csv containing nodes :param fpath_edges: path to a .c...
5,298,677
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2]) * (rec1[3] ) S_rec2 = (rec2[2] ) * ...
5,298,678
def fn_minimum_argcount(callable): """Returns the minimum number of arguments that must be provided for the call to succeed.""" fn = get_fn(callable) available_argcount = fn_available_argcount(callable) try: return available_argcount - len(fn.__defaults__) except TypeError: return av...
5,298,679
async def get_by_id(id: str): """ ### Recurso que tem por objetivo buscar uma pessoa. #### Usa como parametro de busca o seu identificador: - id [str(ObjectId)] = "605dcc895dbd779d5e66bd90" """ try: manage_legal_person = ManageLegalPerson() legal_person = await ma...
5,298,680
def fill_template(req_sig, responses): """ Fills the template and returns filled request signature else returns None if template is not fillable due to dependencies. """ req_sig_str = json.dumps(req_sig) matches = re.findall(r"{([a-zA-Z0-9\.]+)}", req_sig_str) for match in matches: path = match.split(".") pa...
5,298,681
def get_shader(material_name): """ Convenience function for obtaining the shader that the specified material (as an argument) is attached to. :param material_name: Takes the material name as an argument to get associated shader object :return: """ connections = mc.listConnections(material_n...
5,298,682
def _expr(lex): """Return an expression.""" return _ite(lex)
5,298,683
def GQSignal_fetch_position_singal_day(start, end, frequence='day', market_type=QA.MARKET_TYPE.STOCK_CN, portfolio='myportfolio', ...
5,298,684
def return_diagram_as_base64(activities_count, dfg, format="svg", measure="frequency", maxNoOfEdgesInDiagram=75): """ Return process model in Base64 format Parameters ----------- activities_count Count of attributes in the log (may include attributes that are not in the DFG graph dfg ...
5,298,685
def write_model_table(table, basename, batch_name, path): """ Writes MODELS.txt file for lampe_analyser input """ # -------------------------------------------------------------------------- # Input Parameters # -------------------------------------------------------------------------- # run...
5,298,686
def url_add_api_key(url_dict: dict, api_key: str) -> str: """Attaches the api key to a given url Args: url_dict: Dict with the request url and it's relevant metadata. api_key: User's API key provided by US Census. Returns: URL with attached API key infor...
5,298,687
def validate(schema, data, name=None): """ Validate data against a schema """ try: return schema(data) except Invalid as exn: raise loudml.errors.Invalid( exn.error_message, name=name, path=exn.path, )
5,298,688
def config_file_path(token_file: str) -> Path: """Provide Path to config file""" if token_file is None: return Path.joinpath(Path.home(), ".rmapi") else: return Path(token_file)
5,298,689
def test_not_in(): """Should generate a does not contain condition""" assert NotIn(Q.foo, [1, 2, 3]).to_dict() == {'foo': {'$nin': [1, 2, 3]}}
5,298,690
def _read_ctb(stream: BinaryIO) -> ColorDependentPlotStyles: """ Read a CTB-file from from binary `stream`. """ content = _decompress(stream) content = content.decode() styles = ColorDependentPlotStyles() styles.parse(content) return styles
5,298,691
def _compute_fans(shape): """Computes the fan-in and fan-out for a depthwise convolution's kernel.""" if len(shape) != 4: raise ValueError( 'DepthwiseVarianceScaling() is only supported for the rank-4 kernels ' 'of 2D depthwise convolutions. Bad kernel shape: {}' .format(str(shape))) ...
5,298,692
def cc_proto_builder_library( name, cc_proto_library_deps = [], proto = ["*+"], srcs = None, hdrs = None, ifcs = None, make_interface = False, tpl_value_header = None, deps = [], testonly = None, visibility = None, **kwargs)...
5,298,693
def _topological_sort( graph: Mapping[str, List[str]] ) -> Tuple[Optional[List[str]], Optional[str]]: """ Figure out the dependency graph using the topological sort. Return None if there is a cycle. """ # See https://en.wikipedia.org/wiki/Topological_sorting#Depth-first%20search trace = [] ...
5,298,694
def get_model(pretrained_model_file, latent_dim, n_init_retrain_epochs, n_retrain_epochs, retrain_from_scratch, ite, save_dir, data_enc, data_scores, data_weighter): """ load or train the model """ if ite == 1: print_flush("Loading pre-trained model...") new_weights_dir = pretrained_model_file ...
5,298,695
def get_relation_param_dict(relation: str, filename: str) -> RelationParams: """'Get the relation line parameters. Given a relation string with with the format ID\tREL_TYPE E1_TYPE:E1_ID E2_TYPE:E2_ID' Create a dictionary with the following entity properties: * fname: str * id...
5,298,696
def visualize_weibull_outlier_probabilities(data_outlier_probs, other_data_outlier_probs_dict, data_name, save_path, tailsize): """ Visualization of Weibull CDF outlier probabilites. Parameters: data_outlier_probs (np.array): Outlier probabilities for eac...
5,298,697
def get_analog_unit(itf, sig_name, log=False): """ Return the unit of an analog channel. Parameters ---------- itf : win32com.client.CDispatch COM object of the C3Dserver. sig_name : str Analog channel name. log : bool, optional Whether to write logs or not. The defa...
5,298,698
def truncated_mean(data, n): """Compute a truncated mean, n is truncation size""" return mean(truncated_list(data, n))
5,298,699