content
stringlengths
22
815k
id
int64
0
4.91M
def guided_wavelength(freq, line_width, line_gap, substrate_thickness, film_thickness, dielectric_constant=11.45): """A simple calculator to determine the guided wavelength of a planar CPW transmission ...
5,299,600
def template_to_file(template, model_name): """ Write a template to a file :param template: Template string to write :param model_name: Name of file to write """ with open(TEST_MODELS_ROOT / f"{model_name}.sql", "w") as f: f.write(template.strip())
5,299,601
def get_build_hash(fallback: Optional[str] = None) -> str: """Get build hash""" build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "") if build_hash == "" and fallback: return fallback return build_hash
5,299,602
def get_name(number: int) -> str: """Get material name Args: number (int): element ID Returns: str: material name """
5,299,603
def segment_mean(data: jnp.ndarray, segment_ids: jnp.ndarray, num_segments: Optional[int] = None, indices_are_sorted: bool = False, unique_indices: bool = False): """Returns mean for each segment. Args: data: the values which are averaged segm...
5,299,604
def compute_rq_type(oslevel, empty_list): """Compute rq_type. return: Latest when oslevel is blank or latest (not case sensitive) Latest when oslevel is a TL (6 digits) and target list is empty TL when oslevel is xxxx-xx(-00-0000) SP when oslevel is xxxx-xx-xx(-xxxx) ...
5,299,605
def custom_repr(repr_text): """Function decorator to allow setting a custom repr for a class method. References: https://stackoverflow.com/a/32215277 """ # the decorator itself def method_decorator(method): # Wrap the method in our own descriptor. class CustomReprDescripto...
5,299,606
def translate(request, locale, slug, part=None, template='translate.html'): """Translate view.""" log.debug("Translate view.") invalid_locale = invalid_project = False # Validate locale try: l = Locale.objects.get(code__iexact=locale) except Locale.DoesNotExist: invalid_locale ...
5,299,607
def color_map_cyclic(color_normalized: float) -> (float, float, float): """ Maps normalized value to color, cyclic. Note: For JIT to work, this must be declared at the top level. @param color_normalized: Normalized color value @return: R, G, B """ hue = (color_normalized + 1 / 6) % 1 x...
5,299,608
def check_connection(server="lbry.io", port=80, timeout=2): """Attempts to open a socket to server:port and returns True if successful.""" log.debug('Checking connection to %s:%s', server, port) try: server = socket.gethostbyname(server) socket.create_connection((server, port), timeout) ...
5,299,609
def get_model_names(): """ Returns all available model names as a list of strings. """ model_names = [] for key, value in default_models.items(): model_names.append(key) return model_names
5,299,610
def cli(): """ Manually check whether names are available on PyPI. Runs an infinite loop in the command line, where a name can be input and the avilability status of that name on PyPI is printed. Notes ----- Please note that the input name is presently un """ while (True): # UI Lo...
5,299,611
def test_tagged_arp_pkt(ptfadapter, vlan_ports_list, duthosts, rand_one_dut_hostname, toggle_all_simulator_ports_to_rand_selected_tor): """ Send tagged GARP packets from each port. Verify packets egress without tag from ports whose PVID same with ingress port. Verify packets egress with tag from ports w...
5,299,612
def imageDataDisplay(data, title=None, saveAs=None): """ Given a 2D image delta dataset (where value 0 represents no change), create a plot where negative/positive is blue/red and save or show it. """ # the axis limits (blue and red) are a function of standard deviation LMT = np.std(data)*5 ...
5,299,613
def itransduce(xform, rf, init, coll=_Undefined): """ itransduce(xform, rf, init, coll) -> reduction result *itransduce(xform, rf, coll) -> reduction result* Returns the result of reducing an iterable with a transformation. Reduces `coll` using a transformed reducing function equal to ``xform(...
5,299,614
def lseek_syscall(fd, offset, whence): """ http://linux.die.net/man/2/lseek """ # check the fd if fd not in filedescriptortable: raise SyscallError("lseek_syscall","EBADF","Invalid file descriptor.") # if we are any of the odd handles(stderr, sockets), we cant seek, so just report we are at 0 if ...
5,299,615
def convert_to_embedded( compressed_messages: Sequence[ndarray], message_shape: Sequence[int], tail_capacity: int, ) -> Tuple[ndarray, ndarray]: """ Embed a truncated list of byte arrays into equal-size arrays. Args: compressed_messages: Packed message to embed into a standard-length. ...
5,299,616
def add_skill_data( tx: Transaction, node_mapping_dict: dict ): """Add skill category connection to AMR KG.""" skill_df = pd.read_csv( os.path.join(DATA_DIR, "AMR", "skill.csv"), usecols=["skill", "category"], encoding=ENCODING, engine=ENGINE ) skill_df["categor...
5,299,617
def lambda_handler(event, context): """ Manages Let's Encrypt certificates in ACM. """ cert = find_latest_cert() if not cert or get_days_remaining(cert) <= 30: cert_data = provision_cert() cert = import_cert(cert_data) return { 'Certificate': cert.Certificate, ...
5,299,618
def get_full_contentsection_list(course, filter_children=True): """Return a list of ContentSections with material and a list of all material for this course.""" level2_items = {} # level2_items gets filled lazily groups_with_children = set([]) # ContentGroups that h...
5,299,619
def vaecf(users_number: int, items_number: int): """ :param users_number: :param items_number: :return: """ input_layer = tf.keras.layers.Input(shape=(items_number,), name='UserScore') enc = tf.keras.layers.Dense(512, activation='selu', name='EncLayer1')(input_layer) lat_space = tf.ke...
5,299,620
def mode(series): """Computes the mode.""" if series.isnull().all(): return np.nan return series.mode()[0]
5,299,621
def lbeta(x, y, name=None): """Returns log(Beta(x, y)). This is semantically equal to lgamma(x) + lgamma(y) - lgamma(x + y) but the method is more accurate for arguments above 8. The reason for accuracy loss in the naive computation is catastrophic cancellation between the lgammas. This method avoids t...
5,299,622
def _xor_guess_key_size(ct, top_results=5, max_key_size=64): """Returns a list of the most likely key sizes for a ciphertext xored with a repeating key. """ distances = [] for ksize in range(2, max_key_size+1): chunks = chunked(ct, ksize) hammings = [hamming_bin(chunks[i], chunks[i+...
5,299,623
def filter_even_devices(nr): """ Filter the hosts inventory, using a filter function to find devices which match what is considered an even number host. :param nr: An initialised Nornir inventory, used for processing. :return target_hosts: The targeted nornir hosts after being processed throug...
5,299,624
def customUIAction(info, userData): """ Hook called when a custom action is triggered in the menu :param info: A dictionary containing information about the custom action with the keys - name: Name of the action being triggered - selection: Tuple of wiretap ids :param...
5,299,625
def updateRedis(rs, status, url): """ What --- Updates redis sets active or inactive with url Returns: --- nothing """ if status == 1: rs.sadd('active', url) else: rs.sadd('inactive', url) rs.hmset(url, {"name": url, "status_code": status})
5,299,626
def convert_input_paths(argo_json): """ argo aggregation is not valid json as properties are not enclosed in quotes: flow/step/[{task-id:flow-step-3119439657},{task-id:flow-step-195521861},{task-id:flow-step-3020891073}] Parameters ---------- argo_json Returns ------- list of task-...
5,299,627
def _constant_i32(value: int): """Emits a constant i32 value.""" return d.ConstantOp( d.IntegerType.get_explicit(32), ir.IntegerAttr.get(ir.IntegerType.get_signless(32), value)).result
5,299,628
def replace_var(content, variables_mapping): """将 url 中带有参数的变量替换为真实的值 :param content: url 地址,如 https://mubu.com/list?code=$code :param variables_mapping: 要替换的真实的值 :return: """ matched = variable_regex_compile.match(content) if not matched: return content var_name_code = matched[1...
5,299,629
def get_ur(df): """ Method of getting user-rating pairs Parameters ---------- df : pd.DataFrame, rating dataframe Returns ------- ur : dict, dictionary stored user-items interactions """ ur = defaultdict(set) for _, row in df.iterrows(): ur[int(row['user'])].add(int(...
5,299,630
def field_popularity(data): """ Computes the number of different fields that each paper is about by taking the number of fields in 'fields_of_study' Input: - df['fields_of_study']: dataframe (dataset); 'fields_of_study' column [pandas dataframe] Output: - Field varie...
5,299,631
def pubmed_local10k(): """Hparams for Meena local attention model.""" hparams = sparse_transformer_local() hparams.max_length = 10240 hparams.batch_size = 10240 hparams.max_target_length = 512 hparams.hidden_size = 256 hparams.embedding_dims = 256 hparams.num_encoder_layers = 4 hparams.num_decoder_lay...
5,299,632
def update_dict(d, u): """Return updated dict. http://stackoverflow.com/a/3233356 :param d: dict :type d: dict :param u: updated dict. :type u: dict :rtype: dict """ for k, v in u.items(): if isinstance(v, Mapping): r = update_dict(d.get(k, {}), v) ...
5,299,633
def individual_run(individual: Network) -> Network: """ An individual run """ random.seed(datetime.now()) mario = SuperMario() player = Joypad(JoypadSpace(mario, MOVEMENT)) while mario.ram[0x0009] < INITIAL_THRESHOLD: player.press((Button.START,), delay=INITIAL_THRESHOLD) frame...
5,299,634
def h5create_dset(): """dummy function for C h5_create_dset""" return
5,299,635
def parseBamReadcountIndel(row): """Parsing indels only""" # first split ref data ref_split = row[row['REF']].split(':') ref_split = ref_split[:1] + [float(x) for x in ref_split[1:]] # now arrgegate information for alt allels possib_alt = ['INDEL', 'INDEL1', 'INDEL2', 'INDEL3'] num_allels = ...
5,299,636
def draw( solver, show_delta_pressures=False, show_streamlines=False, show_wake_vortices=False, ): """Draw the geometry of the airplanes in a solver object. Citation: Adapted from: vlm3.draw in AeroSandbox Author: Peter Sharpe Date of Retrieval: ...
5,299,637
def loadDataFrame(filename, logger): """ Loads the file into a pandas dataframe Args: filename - Path to file """ dataframe = pd.read_excel(io=filename, header=0, na_values=['[]', '', 'NaN']) logger.info("Finished Loading File: {} ".format(filename.split('\\')[-1])) return dataframe
5,299,638
def get_ui_search_gene_project_donor_counts(url): """ if we look at the implementation of this endpoint, there are no filters http://bit.ly/2hfku5a So, redact the response strip off all projects not in white list """ # if no whitelist_projects, abort whitelist_projects = _whitelist_projects(...
5,299,639
def ocvh_smemo(for_each_device=False): """ Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes the results for each device. Otherwise, it memo...
5,299,640
def apply_exif_orientation(image): """ Reads an image Exif data for orientation information. Applies the appropriate rotation with PIL transposition. Use before performing a PIL .resize() in order to retain correct image rotation. (.resize() discards Exif tags.) Accepts a PIL image and returns ...
5,299,641
def normalize_v4_address(source): """ IPv4 アドレスを整形する。 :param source: IPv4 アドレスと思われる文字列 :type source: str :return: 整形した IPv4 アドレス :rtype: str """ try: v4 = IPv4Address(source) except AddressValueError as _: return None return str(v4)
5,299,642
def _jacobian(params, pose0, fixed_pt3d, n_cams, n_pts, cam_idxs, pt3d_idxs, pts2d, K, px_err_sd): """ cost function jacobian, from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6891346/ """ params = np.hstack((pose0, params)) poses, pts3d = _unpack(params, n_cams, n_pts if len(fixed_pt3d) == ...
5,299,643
def _cursor(host, dictCur = False): """Cursor Returns a cursor for the given host Args: host (str): The name of the host dictCur (bool): If true, cursor will use dicts Return: Cursor """ # Get a connection to the host oCon = _connection(host) # Try to get a cursor on the connection try: if dictCur...
5,299,644
def test_eigenvalues_dimensions(mca, k): """Check the eigenvalues is a vector of length `k`.""" assert len(mca.eigenvalues) == k
5,299,645
def get_solar_charge_state() -> str: """ Gets the current state of the charging system Returns: The charge state object as a json string """ current_state = Path('current_state.json').read_text() return current_state
5,299,646
def get_lambda_execs_in_last_min(): """ Use CloudWatch to see how many lambdas are currently running (take the average over the last minute). Returns: (int): Average number of currently running lambdas. """ utc_zone = timezone(timedelta(hours=0)) now = datetime.now() delta = ti...
5,299,647
def get_fixture_value(request, fixture_name): """ Returns the value associated with fixture named `fixture_name`, in provided `request` context. This is just an easy way to use `getfixturevalue` or `getfuncargvalue` according to whichever is available in current `pytest` version. :param request: ...
5,299,648
def train_test_split(source_dir_path, destination_dir_path, class_names, val_ratio, test_ratio, same_file_number=False, no_files_in_folder=1345): """ Categorizes your folder containing the image files into test, train and validation sets depending on the arguments, provide to the functi...
5,299,649
def ParametricCrossCap(**kwargs): """Generate a cross-cap. ParametricCrossCap generates a cross-cap which is a non-orientable self-intersecting single-sided surface. This is one possible image of a projective plane in three-space. Return ------ surf : pyvista.PolyData ParametricCr...
5,299,650
def random_member_id(): """ Return a zero-padded string from 00000000 to 99999999 that's not in use by any Member. """ def random_id(): return str("{0:08d}").format(random.randint(0, 99_999_999)) member_id = random_id() while Member.objects.filter(member_id=member_id).count() > 0:...
5,299,651
def has_role(package_path, role, identity): """True if |identity| has |role| in some |package_path|.""" assert impl.is_valid_package_path(package_path), package_path assert is_valid_role(role), role if auth.is_admin(identity): return True for acl in get_package_acls(package_path, role): if identity in...
5,299,652
def _add_o_makedup_bam_parser_options(p): """Add a bam as output of `pbsv1 markduplicates`""" return __add_makedup_bam_parser_options(p, str)
5,299,653
def image_to_vec(image_rgb: np.ndarray) -> np.ndarray: """Construct a RGB color vector from a 2D RGB image. Args: image_data (np.ndarray): image data as a ndarray or ndarray-like image_data.shape = (num_x_pixels, num_y_pixels, num_channels) Returns: np.ndarray: one row for each...
5,299,654
def pod_throughput(num_pods, image, timings, node_selector): """Measure pod startup/cleanup throughput.""" node_selector = dict([kv.split("=") for kv in node_selector]) logger.info("Launching {} pods with image {} and node selector {}", num_pods, image, node_selector) v1 = client.CoreV...
5,299,655
def animate(gens, interval=200): """Animate a set of 1d CA generations.""" # we'll need these num_cols = len(gens[0]) num_rows = len(gens) # set up figure fig, ax = plt.subplots(figsize=(num_cols*0.3, num_rows*0.3)) plt.close() ax.set_xlim([-1, num_cols]) ax.set_xticks(np.a...
5,299,656
def load_user(user_id): """Check if user is logged-in on every page load.""" """Check if user is logged-in on every page load.""" if user_id is not None: query = 'match (n:User) where ID(n)={userid} return n' user = db.graph.run(query, parameters={'userid': user_id}).evaluate() user2...
5,299,657
def main(file_in, file_out, add_labels=False): """ Reads clean data from `file_in` and outputs some features in `file_out`. Adds labels from train_labels.csv if add_labels is True. :param file_in: Path to cleaned data :param file_out: Path to output file :param add_labels: If `True`, adds colu...
5,299,658
def create_recurrent_merge_branch_model( vocab_size: int, embedding_size: int = 96, num_lstm_layers: int = 1, lstm_size: int = 670, shared_embedding: bool = False) -> tf.keras.Model: """Constructs a recurrent model with an initial embeding layer. The output is the average of the two branches,...
5,299,659
def test_remove_legacy_cache_dir(): """ Check that legacy cache dir is removed at import time. """ os.mkdir(os.path.expanduser("~/.pip-tools")) status, output = invoke([sys.executable, "-m", "piptools"]) output = output.decode("utf-8") assert output.startswith("Removing old cache dir") ...
5,299,660
def _convert_to_initializer(initializer): """Returns a TensorFlow initializer. * Corresponding TensorFlow initializer when the argument is a string (e.g. "zeros" -> `tf.zeros_initializer`). * `tf.constant_initializer` when the argument is a `numpy` `array`. * Identity when the argument is a TensorFlow initia...
5,299,661
def parseInpatientClaimData(obj, elem): """ Parse InpatientClaim data from xml element. Parameters: - obj : the claim data object - elem : the xml element containing claim data Return the claim data object """ parseData(obj, elem, inpatientClaimDataInstance, InPatientClaimMappi...
5,299,662
def set_log_level(level): """ Select which minimal logging level should be displayed. Parameters ---------- level: int or str Possible values by increasing level: 0 or "notset" 1 or "all" 10 or "debug" 20 or "info" 30 or "warning" 40 or "error"...
5,299,663
def _unicode(ctx, text): """ Returns a numeric code for the first character in a text string """ text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
5,299,664
def parse_config(config): """ Parse config file so that it is in the correct form for the environment class """ parsed_config = {} subnets = config["subnets"] subnets.insert(0, 1) parsed_config["subnets"] = subnets parsed_config["num_services"] = config["num_services"] parsed_config[...
5,299,665
def main(config): """ This is the main part of the logic. 1. Checks if we have enabled disk check (if used disk is above a limit set in configuration, then it will compress and archive the files in a folder in current directory 2. Reads the folders from configuration, and collects files that...
5,299,666
def loadFeatures(inpath, maxFeatures=-1, noMix=False, discardDerivs=False): """ Given the filepath of an input CSV feature file, this function reads all features from the file and stores them in a Numpy matrix suitable for use with SciKit classifiers. It returns the feature matrix and the list of labels for...
5,299,667
def test_crp(S): """ Make sure that equity of a portfolio [1,0,...,0] with NaN values is the same as asset itself. """ b = [1.] + [0.] * (len(S.columns) - 1) result = algos.CRP(b).run(S) assert abs(result.total_wealth - S[S.columns[0]].iloc[-1]) < EPS
5,299,668
def SBFIZ(cpu_context: ProcessorContext, instruction: Instruction): """Signed bitfield insert in zero""" logger.debug("%s instruction not currently implemented.", instruction.mnem)
5,299,669
def files(token, project_id): """List project files""" resp = cloud_request("GET", f"files/{project_id}", token=token) payload = resp.json() print(f"Project files for project {project_id}:") print(json.dumps(payload, indent=2, sort_keys=True))
5,299,670
def test_receive_payment_meets_travel_rule_threshold_sender_kyc_data_is_soft_match_then_accepted_after_reviewing_additional_kyc_data( currency: str, travel_rule_threshold: int, target_client: RestClient, stub_client: RestClient, ) -> None: """ Test Plan: 1. Create sender account with kyc da...
5,299,671
def read(*parts): """ Assume UTF-8 encoding and return the contents of the file located at the absolute path from the REPOSITORY joined with *parts. """ with codecs.open(os.path.join(PROJECT, *parts), "rb", "utf-8") as f: return f.read()
5,299,672
def quote_ident(column: str): """ --------------------------------------------------------------------------- Returns the specified string argument in the format that is required in order to use that string as an identifier in an SQL statement. Parameters ---------- column: str Colu...
5,299,673
def adjust_learning_rate(optimizer, lr): """ adjust learning to the the new value. Parameters ---------- optimizer : required. pytorch optimizer. float : ``float``, required. the target learning rate. """ for param_group in optimizer.param_groups: param_group['l...
5,299,674
def find_opt_end(options): """ Find the end of an option (;) handling escapes. """ offset = 0 while True: i = options[offset:].find(";") if options[offset + i - 1] == "\\": offset += 2 else: return offset + i
5,299,675
def gas_fvf(z, temp, pressure): """ Calculate Gas FVF For range: this is not a correlation, so valid for infinite intervals """ temp = temp + 459.67 Bg = 0.0282793 * z * temp / pressure return(Bg)
5,299,676
def test_no_forwarding_loops(): """Confirm no-forwarding-loops assert passes and fails as expected when specifying a session.""" bf = Session(load_questions=False) with patch.object(bf.q, "detectLoops", create=True) as detectLoops: # Test success detectLoops.return_value = MockQuestion() ...
5,299,677
def index(): """Return index page. The index page presents: - a header with the title of the website and a button that takes you to the login page. If you are logged in it logs you out. - a categories menu that displays all available categories. - a column with the latest items added. """ ...
5,299,678
def configure_logging(): """Configure logging for Chaospy.""" logpath = os.environ.get("CHAOSPY_LOGPATH", os.devnull) logging.basicConfig(level=logging.DEBUG, filename=logpath, filemode="w") streamer = logging.StreamHandler() loglevel = logging.DEBUG if os.environ.get("CHAOSPY_DEBUG", "") == "1" els...
5,299,679
def build_auxiliary_edge_connectivity(G): """Auxiliary digraph for computing flow based edge connectivity If the input graph is undirected, we replace each edge (`u`,`v`) with two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute 'capacity' for each arc to 1. If the input graph is...
5,299,680
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: # model.load_state_dict(model_zoo.load_url(model_urls['resnet18']...
5,299,681
def save_draw_bbox(image, bboxes_,score_,label_, xml_path, iname, classes=classes, show_label=False): """ bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates. """ k = 0 num_classes = len(classes) image_h, image_w, _ = image.shape hsv_tuples = [(1.0 * x / num_...
5,299,682
def partition(A, p, r): """procedura partition Parametri: A (int): lista di numeri interi p (int): indice di inzio dell'array(o sottoarray) r(int): indice di fine dell'array(o sottoarray) Valore di Ritorno: int: indice del pivot """ x = A[r] ...
5,299,683
def printSchoolYear(year1): """Return a print version of the given school year. """ if year1: return "%d–%d" % (year1 - 1, year1)
5,299,684
def check_print(assert_in: str = "", length: int = -1): """Captures output of print function and checks if the function contains a given string""" def checker(func): @functools.wraps(func) def wrapper(*args, **kwargs): capturedOutput = io.StringIO() sys.stdout = captured...
5,299,685
def get_rightsizing_recommendation(Filter=None, Configuration=None, Service=None, PageSize=None, NextPageToken=None): """ Creates recommendations that helps you save cost by identifying idle and underutilized Amazon EC2 instances. Recommendations are generated to either downsize or terminate instances, alon...
5,299,686
def insertMenuInfo(mDB): """ Insert the initial information of Menu. Arg: mDB: the data of Menu in the form of json. """ for mInfo in mDB: rOpt = restaurantOperator() rOpt.manageRestaurantTable(restaurantName="TINYHIPPO", password="123456") restaurantID = selectUniqueItem...
5,299,687
def main(): """Read input and print output""" while True: try: facts, denominator = [int(i) for i in input().split()] except EOFError: break if denominator: divisible = (denominator == 1 or facts >= denominator) if not divisible: ...
5,299,688
def dahua_brightness_to_hass_brightness(bri_str: str) -> int: """ Converts a dahua brightness (which is 0 to 100 inclusive) and converts it to what HASS expects, which is 0 to 255 inclusive """ bri = 100 if not bri_str: bri = int(bri_str) current = bri / 100 return int(current *...
5,299,689
def create_experiment(): """In this sample usage we will create of the default configurations configured in the package. """ # experiment = '1q_X' # experiment = '1q_X_N1Z' # experiment = '1q_X_N2Z' # experiment = '1q_X_N3Z' # experiment = '1q_X_N4Z' # experiment = '1q_XY', # exp...
5,299,690
def pytest_bug_item_mark(item, config): # pragma: no cover """ Called after set mark :param item: pytest item :param config: Base pytest config """
5,299,691
def info(): """Display information on available transplant installs.""" click.echo(htmap.transplant_info())
5,299,692
def connected_to_db(): """ Queries the database to check if the connection is live :return: Boolean """ try: session = Session() session.execute(text('SELECT 1')) session.close() return True except: return False
5,299,693
def PrintVmInfo(vm, depth=1): """ Print information for a particular virtual machine or recurse into a folder or vApp with depth protection """ maxdepth = 10 # if this is a group it will have children. if it does, recurse into them # and then return if hasattr(vm, 'childEntity'): if depth...
5,299,694
def setup_xprahtml5(): """ Setup commands and and return a dictionary compatible with jupyter-server-proxy. """ from pathlib import Path from tempfile import gettempdir, mkstemp # from random import choice # from string import ascii_letters, digits global _xprahtml5_passwd, _xprahtml5...
5,299,695
def color_segmentation(segmentation): """ Converts a segmentation map to a color image. Args: segmentation: a 3-dim numpy array represents a RGB image Returns: colored segmentation map """ color_map = [ [0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0,...
5,299,696
def read(rel_path): """Read a file so python does not have to import it. Inspired by (taken from) pip's `setup.py`. """ here = os.path.abspath(os.path.dirname(__file__)) # intentionally *not* adding an encoding option to open, See: # https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690 ...
5,299,697
def global_scaling(gt_boxes, points, scale_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading] points: (M, 3 + C), scale_range: [min, max] Returns: """ if scale_range[1] - scale_range[0] < 1e-3: return gt_boxes, points noise_scale = np.ran...
5,299,698
async def parse_annotation(param: inspect.Parameter, default, arg: str, index: int, message: discord.Message): """ Parse annotations and return the command to use. index is basically the arg's index in shelx.split(message.content) """ if default is param.empty: default = None if param.annotati...
5,299,699