content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def load_metadata_for_docs(conn_meta, query, split_metadata=False): """ loads the metadata for documents @param conn_meta: connection to the database which includes PubMed metadata @param query: the query to contain metadata (must project pmid and metadata) @param split_metadata: if true the metadat...
5895b4a30d072ec1782c0b8713e436555e145e63
677,356
import getpass def password(name, default=None): """ Grabs hidden (password) input from command line. :param name: prompt text :param default: default value if no input provided. """ prompt = name + (default and ' [%s]' % default or '') prompt += name.endswith('?') and ' ' or ': ' wh...
e1b7953e6a713e1cb31598f266e6cead09de2e45
677,364
def getPatternPercentage(df, column, pattern): """This function counts the number of df[column] which have the given pattern and returns the percentage based on the total number of rows.""" found = df.apply(lambda x: True if(isinstance(x[column], str) and x[column].startswith(pattern)) else False, axis=1).sum() r...
40ad129624e0291088af6471afcb9ea4a5648467
677,365
import tempfile,gzip def gunzip_string(string): """ Gunzip string contents. :param string: a gzipped string :return: a string """ with tempfile.NamedTemporaryFile() as f: f.write(string) f.flush() g = gzip.open(f.name,'rb') return g.read()
b761a2269e8b291681f6abcd7e8c132c72b224f9
677,369
def truncate_latitudes(ds, dp=10, lat_dim="lat"): """ Return provided array with latitudes truncated to specified dp. This is necessary due to precision differences from running forecasts on different systems Parameters ---------- ds : xarray Dataset A dataset with a latitude dimen...
9bdd698f598eb9de0b709d3a33cfc8668fe5baa0
677,370
def RenamePredicate(e, old_name, new_name): """Renames predicate in a syntax tree.""" renames_count = 0 if isinstance(e, dict): if 'predicate_name' in e and e['predicate_name'] == old_name: e['predicate_name'] = new_name renames_count += 1 # Field names are treated as predicate names for funct...
b01cdcb142f098faa079d2ae80952d34f8f86bcb
677,374
import pipes def get_command_quoted(command): """Return shell quoted command string.""" return ' '.join(pipes.quote(part) for part in command)
b689fb927d5c0ed253c9530edad90e860856bde4
677,375
def divide_into_chunks(array, chunk_size): """Divide a given iterable into pieces of a given size Args: array (list or str or tuple): Subscriptable datatypes (containers) chunk_size (int): Size of each piece (except possibly the last one) Returns: list or str or tuple: ...
ed48ebcba3833e5d2923b6dcc6ff572c316873af
677,380
def remove_italics(to_parse: str) -> str: """ A utility function for removing the italic HTML tags. Parameters ---------- to_parse: str The string to be cleaned. Returns ------- str The cleaned string. """ return to_parse.replace("<i>", "").replace("</i>", "")
eca504b9dfa7b1dcf8892f99610c5b39ef78a1ca
677,382
def km_to_meters(kilometers): """ >>> km_to_meters(1) 1000.0 >>> km_to_meters(0) 0.0 >>> km_to_meters(-1) Traceback (most recent call last): ValueError: Argument must be not negative >>> km_to_meters([1, 2]) Traceback (most recent call last): TypeError: Invalid argument type ...
12ac3cc3587b581f207bb3a27c7e55245d3469fc
677,388
def find_index(to_search, target): """Find the index of a value in a sequence""" for index, value in enumerate(to_search): if value == target: return index return -1
cdb57c9a4e1a7973b4c90e4245b939beff1d4e17
677,390
def get_available_difficulties(metadata_record): """Gets the difficulty levels that are present for a song in a metadata record.""" levels = [] for key, value in metadata_record['metadata']['difficulties'].items(): if value == True or value == 'True': levels.append(key) return levels
419203c0b04d2c1f58391ebdb757cb40f2a74f89
677,393
import math def _map_tile_count(map_size: int, lod: int) -> int: """Return the number of map tiles for the given map. Args: map_size (int): The base map size in map units lod (int): The LOD level for which to calculate the tile count Returns: int: The number of tiles in the given...
8ced1676043098a3cfddc106b0aaab0e2745e5b2
677,397
from pathlib import Path def delta_path(input_base_path: Path, item_path: Path, output_base_path: Path) -> Path: """ Removes a base path from an item, and appends result to an output path. Parameters ---------- input_base_path : Path The sub Path to be removed from item_path. item_pat...
b4a4e2eae6ec9cfceb7412c5ab976e002eef72aa
677,398
def mean_hr_bpm(num_beats, duration): """Average heart rate calculation This is a simple function that converts seconds to minutes and divides the total number of beats found by the total minutes in the strip. :param num_beats: a single integer of the number of total beats in a strip :param durati...
83eb5433cec77f9294e1310410e3e06ed1b1eda9
677,402
def is_pdb(datastr): """Detect if `datastr` if a PDB format v3 file.""" assert isinstance(datastr, str), \ f'`datastr` is not str: {type(datastr)} instead' return bool(datastr.count('\nATOM ') > 0)
fbcd58d55563f8fc04604fcf8f6c7c7aa000523f
677,403
def findall(sub, string): """ >>> text = "Allowed Hello Hollow" >>> tuple(findall('ll', text)) (1, 10, 16) """ index = 0 - len(sub) o = [] if not sub in string: return [] while True: try: index = string.index(sub, index + len(sub)) except: ...
8b13279626243b84f9df3793b1475c6e3c405fc9
677,406
def similar_exact(a, b): """Exact comparison between `a` and `b` strings.""" return a == b
04a580df90bb743626859dd4f71a5c5ec3df114e
677,408
def make_wget(urls): """Download multiple URLs with `wget` Parameters ---------- urls : list A list of URLs to download from """ return 'wget -c {}'.format(' '.join(urls))
6531986f5ca3fe98406bfe0d5b8f202df96e8273
677,412
def text2hex(text): """ Takes in a string text, returns the encoded text in hex.""" hex_string = " ".join(format(ord(x), "x") for x in text) return hex_string
9171308f5c58ff306e1437a63027da9a197ec9de
677,417
def isascii(c): """Check if character c is a printable character, TAB, LF, or CR""" try: c = ord(c) # convert string character to decimal representation except TypeError: # it's already an int? (Py3) pass return 32 <= c <= 127 or c in [9, 10, 13]
2af9b721cab40fbcd6b65fff65b743c001ed3e5d
677,418
def _format_syslog_config(cmd_ret): """ Helper function to format the stdout from the get_syslog_config function. cmd_ret The return dictionary that comes from a cmd.run_all call. """ ret_dict = {"success": cmd_ret["retcode"] == 0} if cmd_ret["retcode"] != 0: ret_dict["message"...
815bb929cf85fae604bec5286932011b882514fe
677,421
def get_versions(cfmclient): """ Function takes input cfmclient type object to authenticate against CFM API and queries versions API to return the version number of the system represented by the CFCMclient object Current supported params are :param cfmclient: object of type CFMClient :return: l...
b38301bafe6f6f1cf1150def0dd3c504602b41d1
677,422
import re def matching_segment_range(segments, regexp, invert=False): """Returns a range object that yields the indices of those segments that match 'regexp' from all segments that are returned by function 'segment_data'. Args: segments (list): List of segments as returned by function ...
1c66a62909c998a8a7b9e2970d1ed4d1c98c0366
677,423
def _is_equal_mne_montage(montage_a, montage_b, verbose="info"): """ compare two mne montages for identity""" # fall through for msgs when verbose=True attrs_a = sorted(montage_a.__dict__.keys()) attrs_b = sorted(montage_b.__dict__.keys()) if not attrs_a == attrs_b: if verbose: ...
a21ed93aae832e7c1dcae9d1c9ab321675023cff
677,424
def get_std_color(client, color_type): """Get one of Creo's standard colors. Args: client (obj): creopyson Client. color_type (str): Color type. Valid values: letter, highlight, drawing, background, half_tone, edge_highlight, dimmed, error, warnin...
37d8aa074639bc78c87ce87af8dde861fe5e5d6b
677,426
import torch def bth2bht(t: torch.Tensor) -> torch.Tensor: """Transpose the 2nd and 3rd dim of a tensor""" return t.transpose(1, 2).contiguous()
5e7a448425a2d45a648eca43a260517ba78b4753
677,428
def epoch_span_overlap(span1, span2): """Find the overlap between two epoch spans. Args: span1 (tuple of Time): Range of epochs in increasing order. span2 (tuple of Time): Range of epochs in increasing order. Returns: overlap_range (tuple of Time or None): Overlapping epoch range o...
bb1cd7edf7d58bd189c84dd7e0e1376cc3ca686b
677,437
def _flatten(obj_to_vars): """ Object section is prefixed to variable names except the `general` section [general] warning = red >> translates to: warning = red [panel] title = white >> translates to: panel_title = white """ all_vars = dict() for obj, vars_ in obj_t...
ec5dcb1d626b545d3b1bdae13a750e0632ed3318
677,440
from typing import Dict from typing import Any def marker_smoothing_exceptions(all_exceptions: Dict[str, Any], trial_name: str, marker_name: str) -> Dict[str, Any]: """Given all exceptions (all_exceptions) return just the ones for the specified marker (marker_name) and trial (trial_name).""" trial_excepti...
d6f33bd4f038f88de1e91e0446f4ee206549fbda
677,446
def clip_point(xmin, ymin, xmax, ymax, x, y): """Clips the point (i.e., determines if the point is in the clip rectangle). Parameters ---------- xmin, ymin, xmax, ymax, x, y : float Returns ------- bool `True`, if the point is inside the clip rectangle; otherwise, `Fals...
382f2354ffeba0dcc0e437f91ae9d4ff511d6f4b
677,450
def get_fixed_hyperparams(parser): """ Hyperparameters that remain fixed across all experiments """ parser.add_argument('--pred_logvar_domain', type=bool, default=True) parser.add_argument('--use_l2_sigma_reg', type=bool, default=True) parser.add_argument('--dataset', type=str, default='imagenet_bboxes'...
0cb5f67508a3bf2aa88c9af917ee850e6c8c6625
677,451
from typing import List def get_lower_from_list(upper_array_items: List[str]) -> List[str]: """ Convert a list/tuple objects to lower case character and return it. """ return list(map(lambda x: x.lower(), upper_array_items))
fc9e7ec214454226433cc948bb8e455716b87226
677,453
def format_date(date): """Converts date to string in d. m. Y format.""" return date.strftime('%d. %m. %Y').lower()
c2eb9e0b2c80b64e8931a7f187a7afbefac82e1d
677,454
def epsg_string_to_epsg(epsg_string: str) -> int: """From a string of the form 'EPSG:${code}' return the epsg code as a integer Raise a ValueError if the epsg_string cannot be decoded """ epsg_string = epsg_string.lower() epsg_string = epsg_string.strip() epsg_string = epsg_string.replac...
ea556b4c3eca389d523c4c2473a730bdeaeabd8a
677,456
def sl(c, s, l): """ This accountancy function computes straight line depreciation for an asset purchase for cash with a known life span and salvage value. c = historical cost or price paid (1000) s = the expected salvage proceeds at disposal l = expected useful life of the fixed asset Ex...
84577ac8d1ddb1a84794a2f786ebd0e91e1cc5f8
677,458
import re def natural_sort(iterable): """Sort an iterable by https://en.wikipedia.org/wiki/Natural_sort_order.""" def _convert(text): return int(text) if text.isdigit() else text.lower() def _alphanum_key(key): return [_convert(c) for c in re.split("([0-9]+)", key)] return sorted(it...
a3f3b52f1e84188d4859ad938a6c52292144fbab
677,462
def std_ver_major_uninst_valid_known(request): """Return a value that is a correctly formatted representation of a known major version number.""" return request.param
ad8c13807accd2836c19b325284caa7521f504dd
677,467
def minimumDeletions(s: str) -> int: """Return minimum number of deletions to make 's' balanced, i.e. no 'b' comes before 'a' in string consisting of just 'a's and 'b's.""" deletions = 0 countOfBs = 0 for c in s: if c == 'a' and countOfBs > 0: # Only need to delete 'b' if it co...
1429cc444c0e5b0223d887fc1d2baf05e943e0d2
677,468
import copy def dc(o): """ Some of the testing methods modify the datastructure you pass into them. We want to deepcopy each structure so one test doesn't break another. """ return copy.deepcopy(o)
d0299776280e537855b8100f3f9f9761d9461212
677,473
import re def cleantext(text): """ Custom function to clean enriched text :param text(str): Enriched ytext from Ekstep Content. :returns: Cleaned text. """ replace_char = [ "[", "]", "u'", "None", "Thank you", "-", "(", ")", ...
7728ab5f2d2c4603789c8d2ad1a4a2c76a48b427
677,474
def get_after(end_cursor): """ Get the "after" portion of the pagination query """ return 'after: "{}", '.format(end_cursor) if end_cursor else ""
bac11ec8b3faefed5fb29e041f825db49e3cc36c
677,477
def _and(queries): """ Returns a query item matching the "and" of all query items. Args: queries (List[str]): A list of query terms to and. Returns: The query string. """ if len(queries) == 1: return queries[0] return f"({' '.join(queries)})"
4a2ba5f3812055b76a75b71ccad06c1fbc492618
677,478
def proto_check(proto): """Checks if protocol is TCP or UDP Parameters ---------- proto: int The protocol number in the FCN/CN message Returns ------- The protocol name if TCP/UDP else returns nothing """ # Check for TCP if proto == 6: return 'tcp' # Ch...
118f37249bdfa405ca09846b66c315e8866005ba
677,481
def common_replacements(setting, item): """Maps keys to values from setting and item for replacing string templates. """ return {"$name": setting.lower(), "$setting": setting, "$prettyname": item.py_name, "$doc_str": item.doc_str}
618e0f9f90822455cebdf48c5cfafd913f193214
677,483
def loadStopWords(filename) : """ loads a Set of stopwords from a standard file input : file path containing stop words (format expected is one word per line) return : lines : a set of words """ lines = [] with open(filename,"r") as fileHandle: for line in fileHandle.readlines() : line...
8323557ee2be73017bdc3c853c3cf6e5ccad2055
677,484
import pkg_resources def get_resource_bytes(path): """ Helper method to get the unicode contents of a resource in this repo. Args: path (str): The path of the resource Returns: unicode: The unicode contents of the resource at the given path """ resource_contents = pkg_resourc...
e3ccfa4e2e5d040cc06bad3e042093456e923c58
677,486
def first_match(predicate, list): """ returns the first value of predicate applied to list, which does not return None >>> >>> def return_if_even(x): ... if x % 2 is 0: ... return x ... return None >>> >>> first_match(return_if_even, [1, 3, 4, 7]) 4 ...
859ac7fde416c94cb2cddaf815b76eb59da9654f
677,489
def split_data(msg, expected_fields): """ Helper method. gets a string and number of expected fields in it. Splits the string using protocol's data field delimiter (|#) and validates that there are correct number of fields. Returns: list of fields if all ok. If some error occured, returns None """ count=0 List=...
3f81c7aa6eb2ec210a64c56be325b41f5f8c51ec
677,493
def load_synapses_tsv_data(tsv_path): """Load synapse data from tsv. Args: tsv_path (str): path to the tsv synapses data file Returns: list of dicts containing each data for one synapse """ synapses = [] with open(tsv_path, "r", encoding="utf-8") as f: # first line is d...
097c6f591b6e68e3bd99f53a41a22b89d565e612
677,494
import torch def softplus(x): """Alias for torch.nn.functional.softplus""" return torch.nn.functional.softplus(x)
24d431b5a8965dc382dda846b474c91422b9b48c
677,495
def _index_name(self, name): """ Generate the name of the object in which to store index records :param name: The name of the table :type name: str :return: A string representation of the full table name :rtype: str """ return '_{}_{}'.format(self._name, name)
261fb302a10a56e60a58a4a1d6749d8502e45d6c
677,497
from typing import OrderedDict import torch def transfer_data_to_numpy(data_map: dict) -> dict: """ Transfer tensors in data_map to numpy type. Will recursively walk through inner list, tuple and dict values. Args: data_map (dict): a dictionary which contains tensors to be transferred Return...
772310153c8e4b84c3c5b3884dcb2d2d2ebc5666
677,498
from typing import Dict from typing import Any def time_crop_or_pad_intensity_helper(metadata: Dict[str, Any]) -> float: """ Computes intensity of a transform that consists of temporal cropping or padding. For these types of transforms the intensity is defined as the percentage of video time that has ...
4eb0f07699f8199959bf870757fe769915f0d4ae
677,503
import pickle def load_pickle(filepath_to_load): """Load pickle file""" with open(filepath_to_load, "rb") as inp: return pickle.load(inp)
3635b9d58919f9a43bd53bb0145e297baa831ed1
677,506
def _flattenText(elem): """ Returns the text in an element and all child elements, with the tags removed. """ text = "" if elem.text is not None: text = elem.text for ch in elem: text += _flattenText(ch) if ch.tail is not None: text += ch.tail return t...
aa47128b2f447c8471919abff0f07b6d3c06201b
677,509
import math def distance(x1, y1, x2, y2, x0, y0): """Calculate distance from a point x0, y0 to a line defined by x1, y1 and x2, y2""" num = (y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1 den = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2) return float(num) / float(den)
a692033b29350d666eb251f6f7d0447bc9a94d26
677,510
def parse_copy_availability(line): """Parses 'Status-'line for availability. :param line: Line string. :type line: str :return: Availability. :rtype: bool """ if 'Entliehen' in line: return False elif 'Verfügbar' in line: return True else: return False
c027bc6ee9f3a33c18f4eece47fa9e409354ba8d
677,511
def _get_location_extension_feeds(client, customer_id): """Gets the location extension feeds. Args: client: The Google Ads API client. customer_id: The Google Ads customer ID. Returns: The list of location extension feeds. """ googleads_service = client.get_service("GoogleAd...
437b1aa086f5fbac532dfb1d9efb3d3593c772b0
677,513
def get_fastq_stats(fastq_filehandle): """Return some basic statistics for a fastq file.""" read_count, gc_count, total_base_count = 0, 0, 0 for i, line in enumerate(fastq_filehandle): if i != 1: # only process the reads from the fastq continue read_count += 1 for base i...
b4fc34668d7d2842617e035a059798888d3d8640
677,517
def filter_rule_ids(all_keys, queries): """ From a set of queries (a comma separated list of queries, where a query is either a rule id or a substring thereof), return the set of matching keys from all_keys. When queries is the literal string "all", return all of the keys. """ if not queries: ...
daf5a40754c34342d0707c2334be2ad9de0444e0
677,518
def is_quoted_retweet(text): """ Determines if the text begins with a quoted retweet :param text: The text to analyze (str) :return: true | false """ return int(text[:2] == '"@')
0b1f73f35cf31b369147ff8995a72214702aaefe
677,521
import re def lower_intradocument_links(rst): """Lowercase intra-document links Reference names are converted to lowercase when HTML is rendered from reST (https://bit.ly/2yXRPzL). Intra-document links must be lowercased in order to preserve linkage. `The Link <#Target-No.1>`__ -> `The Link <#ta...
c58e785a07b8adb4a2793f8d061146f001a690b8
677,522
def mean_average(list_of_numbers): """Return the mean average of a list of numbers.""" return sum(list_of_numbers) / len(list_of_numbers)
92b587cac365cdc9c34ca9a03e28d5d0a7adf4e2
677,523
import pathlib import json def read_lipids_topH(filenames): """Generate a list of lipid hydrogen topologies. This function read a list of json files containing the topology of a united-atom lipid for reconstructing the missing hydrogens. The list topologies is stored as dictionary were the key i...
26d7214730dc8b1164af1f2bcafcb3e94104683a
677,527
def stringify_steamids(list_of_steamids): """ Args: list_of_steamids: list of steamids Returns: Single string with steamids separated by comma """ return ','.join(list(map(str, list_of_steamids)))
280866a64db270cbec82db1301fc579dc5be631c
677,530
from typing import OrderedDict def create_epoch_dict(epochs): """ Creates an ordered dictionary of epoch keys and a list of lists, where the first list is the average flux of the bin, and second list the CTE loss slope. Parameters: epochs : list of ints/floats Returns: ...
7492f5b2a1a9f0752106424c837a6e363563e944
677,534
def load_list_room_items(data, room_names): """ Loading each room respective list of items. Parameters: data(dict): Nested dictionaries containing all information of the game. room_names(list): List containg room names. Returns: items_list(list): Returns list of roo...
728c5903945cc992ed06505c60554557875aed8f
677,536
def convert_to_nvc(vertices, faces): """Convert into format expected by CUDA kernel. Nb of triangles x 3 (vertices) x 3 (xyz-coordinate/vertex) WARNING: Will destroy any resemblance of UVs Args: vertices (torch.Tensor): tensor of all vertices faces (torch.Tensor): tensor of all tri...
090f894259f680cf4d4f277c097896b71d677b5a
677,539
def update_docstring_references(obj, ref="ref"): """ Updates docstring reference names to strings including the function name. Decorator will return the same function with a modified docstring. Sphinx likes unique names - specifically for citations, not so much for footnotes. Parameters -------...
78a109838573d5dc42027da8a8998ff107b8ed2a
677,540
def is_dataclass_type(cls): """Returns whether cls is a dataclass.""" return isinstance(cls, type) and hasattr(cls, "__dataclass_fields__")
7a354b54198e8873cbafd184c1611f99958e69c4
677,541
import torch def get_p_star(samples, y, beta): """Get the values for the p_star distribution Parameters: samples: tensor of dim (batch_size x num_samples) with the samples indexes y: tensor of dim (batch_size) with the true label for each example beta: the strength of the feedback Returns: ...
e48bd9fdc8369122880ed428c4fafd0fa5429238
677,545
import pickle def _encode(o): """Encodes an object with cPickle""" return pickle.dumps(o, pickle.HIGHEST_PROTOCOL)
895a273bccd0a0aaa8715679462d958ad9238268
677,546
def get_signal_frame(l4e_data_frame, model_name): """ Converts a dataframe from an L4E style to a Seeq signal style PARAMS ====== l4e_data_frame: pandas.DataFrame (Required) A dataframe returned from lookout_equipment_utils.get_predictions_data_frame() model_nam...
8ee4137832886b61d2dfc71839bb4a35fdc93f11
677,550
from typing import Iterable from typing import List from typing import Optional def sorted_dedup(iterable: Iterable) -> List[Optional[int]]: """Sorted deduplication without removing the possibly duplicated `None` values.""" dedup: List[Optional[int]] = [] visited = set() for item in iterable: ...
b7b5424157bccb764c3db03fadf4ca88e6c50b02
677,551
def xor(a, b): """Return the XOR of two byte sequences. The length of the result is the length of the shortest.""" return bytes(x ^ y for (x, y) in zip(a, b))
a4d41e4d871244a588246f554515b9115ad60b11
677,553
import uuid def create_api_release( client, resource_group_name, service_name, api_id, api_revision, release_id=None, if_match=None, notes=None): """Creates a new Release for the API.""" if release_id is None: release_id = uuid.uuid4().hex api_id1 = "/apis/" + api_id + ";rev=" + api_revi...
a9b2490ca857712b2b8e4be36e76cc7dba9fbc99
677,554
def cli_parse(parser): """Add method specific options to CLI parser. Parameters ---------- parser : argparse object Returns ---------- Updated argparse object """ parser.add_argument('-M', '--M', type=int, required=False, default=4, h...
bbc02f2031e71b2bdf06f6c4f29994b1f9fd6c6a
677,557
def readme_contents_section_exists(path: str) -> bool: """ Given a README.md path, checks to see if there is a Contents section """ try: with open(path, 'r') as f: return '## Contents' in f.read() except FileNotFoundError: return False
7353613b5e74f3343c8214073b00919a32a692b0
677,558
import math def is_power_of_n(num:int,n :int) ->bool: """ Check whether a number is a power of n. Parameters: num: the number to be checked n: the number those power num is checked Returns: True if number is a power of n, otherwise False """ if num <= 0: ra...
da60f68e1f211df052e5df2b7ee60adb61d66c5c
677,559
def hours_to_days(hours): """ Convert the given amount of hours to a 2-tuple `(days, hours)`. """ days = int(hours // 8) hours_left = hours % 8 return days, hours_left
849961d6fc1ce68c72d300885cddb05aebba0941
677,560
def get_primes(start, stop): """Return a list of prime numbers in ``range(start, stop)``.""" if start >= stop: return [] primes = [2] for n in range(3, stop + 1, 2): for p in primes: if n % p == 0: break else: primes.append(n) while primes and primes[0] < start: del primes[0] return primes
21991dd24a2f92b3c91bd2d69ec8c462bde58537
677,561
def format_number(number): """Format numbers for display. if < 1, return 2 decimal places if <10, return 1 decimal places otherwise, return comma formatted number with no decimal places Parameters ---------- number : float Returns ------- string """ if number == 0: ...
254251f9d0b847c6bb020d19953a2c7deb801b7c
677,564
def filter_channels_by_server(channels, server): """Remove channels that are on the designated server""" chans = [] for channel in channels: sv, chan = channel.split(".", 1) if sv == server: chans.append(chan) return chans
358bd83bd2cc6b6fabaced3cac99b0c56741ad06
677,565
def isFloat(string): """ is the given string a float? """ try: float(string) except ValueError: return 0 else: return 1
4605d2975523dab25ec598ee7ed0324c0c200b05
677,567
def transform(m, b, n): """ Given vector 'b', Calculate vector 'a' such that: 2*a-n*one == M * (2*b-n*one), where 'one' = (1, 1) --> a = M*b + (I-M)*one*n/2 M is the transformation matrix, the coordinates of 'a' and 'b' range from 0 to n-1. """ bb = [] for j in range(...
53909072ee9471fb26b89687d7d026638d57463b
677,571
from typing import Optional from typing import IO def openfile(spec: Optional[str]) -> Optional[IO[str]]: """Open file helper. Args: spec: file/mode spec; for example: * ``file`` uses mode ``w`` * ``file+`` uses mode ``a`` * ``file+r`` uses mode ``r`` Return...
435547e3fa359a787f1f14b378a6eed9a0c3ee53
677,572
from pathlib import Path def _get_file_dict(fp,fname): """ Find an image matching fname in the collection This function searches files in a FilePattern object to find the image dictionary that matches the file name, fname. Inputs: fp - A FilePattern object fname - The name of the...
ba4e744a644c6f6f75fde47aa6b30790dbb70c38
677,574
def index_fasta( f ): """ Makes a simple index for a FastA file :param f: an opened fasta file :return: a dict with the chromosomes as keys and the tell positions as values """ lpos = f.tell() rval = {} # for each line in the fasta l = f.readline() while l != "" : # re...
67dc0b00bfb6cf4bd057250e34d9626eb18813f7
677,578
from typing import Tuple def _get_output_pad(plain: bool) -> Tuple[int, int, int, int]: """Return the padding for outputs. Args: plain (bool): Only show plain style. No decorations such as boxes or execution counts. Returns: Tuple[int, int, int, int]: The padding for outputs....
5fdc2b645238028cfe17f8773c1f1a343da692ec
677,581
def height(root): """Function to return the height of a binary tree Args: root (Node): The root node of the binary tree Returns: (int): The height of the binary tree """ left = 0 right = 0 if root.left: left = 1 + height(root.left) if root.right: right =...
5b351705fe9f25f2eda7716d4e80b6630508a318
677,583
def _to_iloc(data): """Get indexible attribute of array, so we can perform axis wise operations.""" return getattr(data, 'iloc', data)
137dc760dc1e33e319017a0b8356a5e12add6b61
677,584
import re def parse_show_ip_bgp_summary(raw_result): """ Parse the 'show ip bgp summary' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show ip bgp summary command in a \ dictionary of the form: :: { ...
0b4f7e2f18a3430647ddf99cfad0c6f64d369b3f
677,588
def build_part_check(part, build_parts): """ check if only specific parts were specified to be build when parsing if the list build_parts is empty, then all parts will be parsed """ if not build_parts: return True return bool(part in build_parts)
9b9923b45e794bff3df03a63cbbed3280a25d211
677,591
import base64 def generate_aws_checksum(image_checksum: str) -> str: """ Takes an MD5 checksum provided by SciHub and generates a base64-encoded 128-bit version, which S3 will use to validate our file upload See https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Clie...
00a7eed956e581fd27db7d6bd65f7e56c4e79211
677,595
def get_model_chain_ids(structure): """ Extracts model and chain ids from structure object. Parameters ---------- structure: Bio.PDB.Structure.Structure Returns ------- struct_id: tuple tuple of (modelid, chainid) """ modelnum = [] chainid = [] for model in str...
2e4c84f6387397d35db71df5365deaeb21bb39c3
677,596
def stats_path(values): """ Return the stats path for the given Values object. """ # The filter() call here will remove any None values, so when we join() # these to get our stat path, only valid components will be joined. return '.'.join(filter(None, [ # plugin name values.plugi...
41fe636a7f0e2152f3fccb75731eed66b7223a07
677,597
def dedupe_n_flatten_list_of_lists(mega_list): """Flatten a list of lists and remove duplicates.""" return list(set([item for sublist in mega_list for item in sublist]))
552bc12b971741a0616da553ae548e8165ad6e5f
677,600
def load_std_type(net, name, element): """ Loads standard type data from the data base. Issues a warning if stdtype is unknown. INPUT: **net** - The pandapipes network **name** - name of the standard type as string **element** - "pipe" OUTPUT: **typedata** - dicti...
4ab28db65e25bed3fb2f2231f8061b8e82261f67
677,604
def selection_sort(lst): """Implement selection sorting algorithm.""" if len(lst) < 2: return lst def smallest_index(lst): smallest = lst[0] sm_index = 0 for i in range(len(lst)): if lst[i] < smallest: smallest = lst[i] sm_index = ...
16be2b90bb297caea10f1093005d7056f641c2d2
677,606