content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def pollutants_from_summary(summary): """ Get the list of unique pollutants from the summary. :param list[dict] summary: The E1a summary. :return dict: The available pollutants, with name ("pl") as key and pollutant number ("shortpl") as value. """ return {d["pl"]: d["shortpl"] for d in summary}
d880a1f693139786a3ee799594ed1bd664d4b93e
30,015
def _dest_path(path): """Returns the path, stripped of parent directories of .dSYM.""" components = path.split("/") res_components = [] found = False for c in components: # Find .dSYM directory and make it be at the root path if c.endswith(".dSYM"): found = True if found: res_components.append(c) return "/".join(res_components)
869efc4265e09c182a948f6580075846a6af7c9f
30,016
def get_max(num_list): """Recursively returns the largest number from the list""" if len(num_list) == 1: return num_list[0] else: return max(num_list[0], get_max(num_list[1:]))
a1ba81d12e1a9f7aa7cfa1c9846a790a5789485d
30,019
import json def get_device(token): """ Read the device configuration from device.json file. :return: dict - the device configuration """ try: with open("/tmp/{}/device.json".format(token), "r") as f: return json.load(f) except: pass
5675113a87ee2d4abf8ce630cd167113c25e3626
30,020
def unique(valuelist): """Return all values found from a list, but each once only and sorted.""" return sorted(list(set(valuelist)))
1218bb7c353a898b2815c5cd95b8ef71e386b91f
30,023
from typing import List from typing import Any def get_list_elements_containing(l_elements: List[Any], s_search_string: str) -> List[str]: """get list elements of type str which contain the searchstring >>> get_list_elements_containing([], 'bc') [] >>> get_list_elements_containing(['abcd', 'def', 1, None], 'bc') ['abcd'] """ if (not l_elements) or (not s_search_string): return l_elements ls_results = [] for s_element in l_elements: if isinstance(s_element, str): if s_search_string in s_element: ls_results.append(s_element) else: continue return ls_results
7a9ea19fcf94ca0493487c3a343f49cd45e85d08
30,024
def floatformatter(*args, sig: int=6, **kwargs) -> str: """ Returns a formatter, which essantially a string temapate ready to be formatted. Parameters ---------- sig : int, Optional Number of significant digits. Default is 6. Returns ------- string The string to be formatted. Examples -------- >>> from dewloosh.core import Library >>> data = Library() >>> data['a']['b']['c']['e'] = 1 >>> data['a']['b']['d'] = 2 >>> data.containers() """ return "{" + "0:.{}g".format(sig) + "}"
aead01fd8a2b1f97d20091af4326a7f248ea43a7
30,026
def comp_active_surface(self): """Compute the active surface of the conductor Parameters ---------- self : CondType11 A CondType11 object Returns ------- Sact: float Surface without insulation [m**2] """ Sact = self.Hwire * self.Wwire * self.Nwppc_tan * self.Nwppc_rad return Sact
302bb23c4ed94084603c02437c67ef4ea8046b4b
30,028
import hashlib def get_checksum(address_bytes: bytes) -> bytes: """ Calculate double sha256 of address and gets first 4 bytes :param address_bytes: address before checksum :param address_bytes: bytes :return: checksum of the address :rtype: bytes """ return hashlib.sha256(hashlib.sha256(address_bytes).digest()).digest()[:4]
40e515603223ec68ce2b07208de47f63905dafd2
30,029
def isHeteroplasmy(variant, depth_min = 40, depth_strand = 0, depth_ratio_min = 0.0, freq_min = 0.01): """ determine whether a variant is a heteroplasmy according to the filers specified Attributes ---------- variant: MTVariant depth_min: the minimum depth depth_strand: the minimum depth on either the forward and the reverse strand depth_ratio_min: the minimum ratio of reads passing QC freq_min: the minimum minor allele frequency Returns ---------- True: is a heteroplasmy False: not a heteroplasmy None: does not pass QC """ if (variant.depth_qc >= depth_min and variant.depth_fwd >= depth_strand and variant.depth_rev >= depth_strand and variant.depth_ratio >= depth_ratio_min): if (variant.alt_freq >= freq_min): return True else: return False else: return None
0f36082b2d545a3f4ceec9474f3dfd63feda36d0
30,045
import hashlib def hash_ecfp(ecfp, size): """ Returns an int < size representing given ECFP fragment. Input must be a string. This utility function is used for various ECFP based fingerprints. Parameters ---------- ecfp: str String to hash. Usually an ECFP fragment. size: int, optional (default 1024) Hash to an int in range [0, size) """ ecfp = ecfp.encode('utf-8') md5 = hashlib.md5() md5.update(ecfp) digest = md5.hexdigest() ecfp_hash = int(digest, 16) % (size) return (ecfp_hash)
4850ee88735ae172216a5ae5cbd08505d8a2f42e
30,050
def dict_union(a, b): """ Return the union of two dictionaries without editing either. If a key exists in both dictionaries, the second value is used. """ if not a: return b if b else {} if not b: return a ret = a.copy() ret.update(b) return ret
5f228221a4a0fc5f322c29b8500add4ac4523e04
30,055
def gef_pybytes(x: str) -> bytes: """Returns an immutable bytes list from the string given as input.""" return bytes(str(x), encoding="utf-8")
aa349940a72129329b850363e8cb807566d8d4b8
30,058
def parse_STATS_header(header): """ Extract the header from a binary STATS data file. This extracts the STATS binary file header information into variables with meaningful names. It also converts year and day_of_year to seconds at midnight since the epoch used by UNIX systems. @param header : string of binary data @return: tuple (spcid, vsrid, chanid, bps, srate, errflg, year, doy, sec, freq, orate,nsubchan) """ (spcid, # 1) station id - 10, 40, 60, 21 vsrid, # 2) vsr1a, vsr1b ... chanid, # 3) subchannel id 0,1,2,3 bps, # 4) number of bits per sample - 1, 2, 4, 8, or 16 srate, # 5) number of samples per second in samples per second errflg, # 6) hardware error flag, dma error or num_samples # error, 0 ==> no errors year, # 7) time tag - year doy, # 8) time tag - day of year sec, # 9) time tag - second of day freq, # 10) frequency in Hz orate, # 11) number of statistics samples per second nsubchan # 12) number of output sub chans ) = header return spcid, vsrid, chanid, bps, srate, errflg, year, doy, sec, freq, \ orate,nsubchan
87ee5bd8971f62304c7e48f7b573a1a89c604c65
30,061
import decimal def recall(qtd_true_positives, list_of_true_positive_documents, ref=0): """ TP / (TP + FN) TP - True Positive FN - False Negative - a document is positive but was classified as negative """ fn = 0 for d in list_of_true_positive_documents: if d.predicted_polarity < ref: fn = fn + 1 qtd_true_positives = decimal.Decimal(qtd_true_positives) fn = decimal.Decimal(fn) return (qtd_true_positives / (qtd_true_positives + fn))
7656a565a9ef42d06d8d7deeb3f14966e1fcf138
30,066
from datetime import datetime def fromisoformat(isoformat): """ Return a datetime from a string in ISO 8601 date time format >>> fromisoformat("2019-12-31 23:59:59") datetime.datetime(2019, 12, 31, 23, 59, 59) """ try: return datetime.fromisoformat(isoformat) # Python >= 3.7 except AttributeError: return datetime.strptime(isoformat, "%Y-%m-%d %H:%M:%S")
bcb7e277e907a5c05ca74fd3fbd7d6922c0d7a36
30,073
def _generator_to_list(subnets_generator): """Returns list of string representations of each yielded item from the generator. """ subnets = [] for subnet in subnets_generator: subnets.append(str(subnet)) return subnets
f72c1f735d692a820d20eb14cd13e88abe21b2bb
30,076
def is_selected_branch(branch: str) -> bool: """Determine whether a branch is the current branch.""" return branch.startswith("* ")
f7569964a3aee08a7995f66332a890ec03cee096
30,080
def getFile(file): """ Read out a file and return a list of string representing each line """ with open (file, "r") as out: return out.readlines()
b869a7252fc45fdc6877f22975ee5281650877b9
30,083
def format_chores(chores): """ Formats the chores to properly utilize the Oxford comma :param list chores: list of chores """ if len(chores) == 1: return f'{chores[0]}' elif len(chores) == 2: return f'{chores[0]} and {chores[1]}' else: chores[-1] = 'and ' + chores[-1] return f"{', '.join(chores)}"
38b7115520867e2545f7be7364e6147ca12dc8e1
30,085
import math def get_line_size(l): """ Return the size of the given line """ return math.sqrt( math.pow(l[0] - l[2], 2) + math.pow(l[1] - l[3], 2))
07a1d92e19e2b6104bf8d63459e588449d45912e
30,086
def centercrop(pic, size): """ Center-crops a picture in a square shape of given size. """ x = pic.shape[1]/2 - size/2 y = pic.shape[0]/2 - size/2 return pic[int(y):int(y+size), int(x):int(x+size)]
fa89253af6be414ef242ee0ba4b626ab676980a0
30,091
def early_stopping(val_bleus, patience=3): """Check if the validation Bleu-4 scores no longer improve for 3 (or a specified number of) consecutive epochs.""" # The number of epochs should be at least patience before checking # for convergence if patience > len(val_bleus): return False latest_bleus = val_bleus[-patience:] # If all the latest Bleu scores are the same, return True if len(set(latest_bleus)) == 1: return True max_bleu = max(val_bleus) if max_bleu in latest_bleus: # If one of recent Bleu scores improves, not yet converged if max_bleu not in val_bleus[:len(val_bleus) - patience]: return False else: return True # If none of recent Bleu scores is greater than max_bleu, it has converged return True
dafc48f674673736e5a129aab8ce4c40fdbcbbeb
30,096
def indent_code(input_string): """ Split code by newline character, and prepend 4 spaces to each line. """ lines = input_string.strip().split("\n") output_string = "" for line in lines: output_string += " {}\n".format(line) ## one last newline for luck output_string += "\n" return output_string
5b110ed9bb1a4bbf471c5c4126c7460b6eb6ba1c
30,097
import torch def set_devices(model, loss, evaluator, device): """ :param: model, loss, evaluation_loss : torch.nn.Module objects :param: device: torch.device,compatible string, or tuple/list of devices. If tuple, wrap the model using torch.nn.DataParallel and use the first specified device as the 'primary' one. :return: None Sets the model and loss the the specified device. Evaluation loss is performed on CPU. """ print("Using device: ", device) if isinstance(device, (tuple, list)): model = torch.nn.DataParallel(model, device_ids=device) print("Using multi GPU compute on devices:", device) device = torch.device(device[0]) device = torch.device(device) # Will throw a more explicit error if the device specification is invalid model.to(device) loss.to(device) evaluator.loss.cpu() evaluator.model_device = device evaluator.model = model return model, evaluator
d15de114b4e5099c9c33edf5e82d95d2babed3cd
30,100
def btod(binary): """ Converts a binary string to a decimal integer. """ return int(binary, 2)
202ce460bf9fa5675e195ca2714d8f5f0576020c
30,107
def set_progress_percentage(iteration, total): """ Counts the progress percentage. :param iteration: Order number of browser or version :param total: Total number of browsers or versions :return: Percentage number """ return float((iteration + 1) / total * 100)
1881cd84e2af051379dc293b0e71067fc7be92a0
30,111
def has_loop(page_list): """ Check if a list of page hits contains an adjacent page loop (A >> A >> B) == True. :param page_list: list of page hits derived from BQ user journey :return: True if there is a loop """ return any(i == j for i, j in zip(page_list, page_list[1:]))
461691e62a900e84f779ed96bdf480ce8a5367af
30,117
def linear(a, b, x, min_x, max_x): """ b ___________ /| / | a _______/ | | | min_x max_x """ return a + min(max((x - min_x) / (max_x - min_x), 0), 1) * (b - a)
d6bbac95a0a53663395cd4d25beeadbaa5f9f497
30,118
def form_message(sublines, message_divider): """Form the message portion of speech bubble. Param: sublines(list): a list of the chars to go on each line in message Return: bubble(str): formaatted to fit inside of a bubble """ bubble = "" bubble += message_divider bubble += "".join(sublines) bubble += message_divider return bubble
c3ca1c2a684d25b439a594cfc5ade187f272a2c1
30,123
from typing import BinaryIO from typing import Optional from io import StringIO def decode_object( handle: BinaryIO, num_lines: Optional[float] = None, ) -> StringIO: """ Converts a binary file-like object into a String one. Files transferred over http arrive as binary objects. If I want to check the first few lines I need to decode it. """ # If we don't specify a number of lines, just use infinity if num_lines is None: num_lines = float("inf") lines = [l.decode() for i, l in enumerate(handle) if i < num_lines] # Create an in memory file like object out = StringIO() # Write the lines to the file like object. out.writelines(lines) # Rewind the files to the start so that we can read them out.seek(0) handle.seek(0) return out
5c08438727290ea797ee93261ccd6f03763b7f36
30,125
import torch def get_grad_norm_from_optimizer(optimizer, norm_type=2): """ Get the gradient norm for some parameters contained in an optimizer. Arguments: optimizer (torch.optim.Optimizer) norm_type (int): Type of norm. Default value is 2. Returns: norm (float) """ total_norm = 0 if optimizer is not None: for param_group in optimizer.param_groups: for p in param_group['params']: if p.grad is not None: with torch.no_grad(): param_norm = p.grad.data.norm(norm_type) total_norm += param_norm ** norm_type total_norm = total_norm ** (1. / norm_type) return total_norm.item()
c8987953f23d6023d3b4f3abf894b98d720662fb
30,128
def count_days_between(dt1, dt2): """Function will return an integer of day numbers between two dates.""" dt1 = dt1.replace(hour=0, minute=0, second=0, microsecond=0) dt2 = dt2.replace(hour=0, minute=0, second=0, microsecond=0) return (dt2 - dt1).days
94fb2cf51af9007ab0c47229d485524af1f18656
30,132
import string import random def generate_random_alphanumeric_string(str_length=12): """ Generates a random string of length: str_length :param str_length: Character count of the output string :return: Randomly generated string :rtype: str """ letters_and_digits = string.ascii_letters + string.digits return ''.join((random.choice(letters_and_digits) for i in range(str_length)))
5f0cbd817e3d9dcb5a0b5e785a634bfa2e166968
30,135
def _buffer_list_equal(a, b): """Compare two lists of buffers for equality. Used to decide whether two sequences of buffers (memoryviews, bytearrays, or python 3 bytes) differ, such that a sync is needed. Returns True if equal, False if unequal """ if len(a) != len(b): return False if a == b: return True for ia, ib in zip(a, b): # Check byte equality, since bytes are what is actually synced # NOTE: Simple ia != ib does not always work as intended, as # e.g. memoryview(np.frombuffer(ia, dtype='float32')) != # memoryview(np.frombuffer(b)), since the format info differs. # Compare without copying. if memoryview(ia).cast('B') != memoryview(ib).cast('B'): return False return True
c88d9d87684d27007a73c196f5aaa12e963a8656
30,136
def delete_line_breaks(text, joiner): """ Deletes line breaks and joins split strings in one line :param text: string :param joiner: string used to join items [" " for abs or "" for title] :return: joined text """ text = text.split('\n') text = joiner.join(text) return text
b05a701d4828d57060af55389ec785a64e094392
30,142
def get_adm_fields(adm_level, field_name="name"): """Get list of adm-fields from `adm_level` up to the adm1 level""" return [f"adm{i}_" + field_name for i in range(1, adm_level + 1)]
75a216ab7448f53417c5b8f5e951a5c96312b1e3
30,145
def prepare_actions(actions, enabled_analyzers): """ Set the analyzer type for each buildaction. Multiple actions if multiple source analyzers are set. """ res = [] for ea in enabled_analyzers: for action in actions: res.append(action.with_attr('analyzer_type', ea)) return res
a8a8624c5921f9addaef9c9e532f333726e35618
30,149
import click def style_bold(txt, fg): """Style text with a bold color.""" return click.style(txt, fg=fg, bold=True)
adecdf207ecb27d202f298a56f8de54576e72ecd
30,150
from typing import Optional from typing import Tuple import re def find_github_owner_repo(url: Optional[str]) -> Tuple[Optional[str], Optional[str]]: """Find the owner's name and repository name from the URL representing the GitHub repository. Parameters ---------- url : Optional[str] Any string (expect it to be a URL). Returns ------- owner : str or None Owner's name, or None if not found. repo : str or None Repository name, or None if not found. Examples -------- >>> owner, repo = find_github_owner_repo("https://github.com/poyo46/lilili.git#foo") >>> assert owner == "poyo46" >>> assert repo == "lilili" >>> owner, repo = find_github_owner_repo("https://www.example.com") >>> assert owner is None >>> assert repo is None """ if url is None: return None, None m = re.match(r"[^:/]+://github.com/(?P<owner>[^/]+)/(?P<repo>[^/#]+)", url) if m is None: return None, None repo = m.group("repo") if repo.endswith(".git"): repo = repo[:-4] return m.group("owner"), repo
81ba5533546efde91a7c6ef5f48e65d1cdd2c6c4
30,151
from typing import Union def celsius_to_kelvin(temperature_in_celsius: Union[int, float]) -> float: """ >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(1) 274.15 >>> celsius_to_kelvin(-1) 272.15 >>> celsius_to_kelvin(-273.15) 0.0 >>> celsius_to_kelvin(-274.15) Traceback (most recent call last): ... ValueError: Argument must be greater than -273.15 >>> celsius_to_kelvin([-1, 0, 1]) Traceback (most recent call last): ... ValueError: Argument must be int or float >>> celsius_to_kelvin('one') Traceback (most recent call last): ... ValueError: Argument must be int or float """ if not isinstance(temperature_in_celsius, (float, int)): raise ValueError('Argument must be int or float') if temperature_in_celsius < -273.15: raise ValueError('Argument must be greater than -273.15') return float(temperature_in_celsius + 273.15)
1aa5b214e20c0d47a3ab50388132f174cd33dbde
30,152
def union(x, y=None): """ Return the union of x and y, as a list. The resulting list need not be sorted and can change from call to call. INPUT: - ``x`` - iterable - ``y`` - iterable (may optionally omitted) OUTPUT: list EXAMPLES:: sage: answer = union([1,2,3,4], [5,6]); answer [1, 2, 3, 4, 5, 6] sage: union([1,2,3,4,5,6], [5,6]) == answer True sage: union((1,2,3,4,5,6), [5,6]) == answer True sage: union((1,2,3,4,5,6), set([5,6])) == answer True """ if y is None: return list(set(x)) return list(set(x).union(y))
67b20db26081c05a8c706d5529897bc753726f6a
30,153
from typing import List def define_frontal_base_direction(robot: str) -> List: """Define the robot-specific frontal base direction in the base frame.""" if robot != "iCubV2_5": raise Exception("Frontal base direction only defined for iCubV2_5.") # For iCubV2_5, the reversed x axis of the base frame is pointing forward frontal_base_direction = [-1, 0, 0] return frontal_base_direction
eac7536aca5e8cd1ba06160a4dd4f5f6332fb5ed
30,158
from typing import List from typing import Dict from pathlib import Path def collect_file_pathes_by_ext( target_dir: str, ext_list: List[str] ) -> Dict[str, List[Path]]: """Return the list of Path objects of the files in the target_dir that have the specified extensions. Args: target_dir (str): Directory to search for files. ext_list (List[srt]): List of file extensions to search for. Returns: List[List[Path]]: List of lists of Path objects. The first list contains the files having the first extension in the ext_list. The second list contains the files having the second extension in the ext_list and so on. """ target = Path(target_dir) rtn = {} for ext in ext_list: if ext[0] == ".": ext = ext.strip(".") rtn[ext] = list(target.glob(f"**/*.{ext}")) return rtn
18b6287d12a301b7cff98e37a4122474ae3a7958
30,162
def node_is_empty(node): """Handle different ways the regulation represents no content""" return node.text.strip() == ''
64c80be5ad40ab388664e6f391fb729b6fc9ebb6
30,165
def find_dict_in_list_from_key_val(dicts, key, value): """ lookup within a list of dicts. Look for the dict within the list which has the correct key, value pair Parameters ---------- dicts: (list) list of dictionnaries key: (str) specific key to look for in each dict value: value to match Returns ------- dict: if found otherwose returns None """ for dict in dicts: if key in dict: if dict[key] == value: return dict return None
02c98b64086266a21c2effdb72d1b681f77cbc26
30,167
from typing import List from typing import Any def get_combinations(*args: List[Any]) -> List[List]: """Takes K lists as arguments and returns Cartesian product of them. Cartesian product means all possible lists of K items where the first element is from the first list, the second is from the second and so one. Returns: All possible combinations of items from function's arguments. """ result: List[List] = [[]] for list_n in args: result = [old_item + [new_item] for old_item in result for new_item in list_n] return result
db3d2f48e650e647cec79d7bab0b6e555238cb3a
30,169
def unique_from_list_field(records, list_field=None): """ Return a list of unique values contained within a list of dicts containing a list. """ values = [] for record in records: if record.get(list_field): values = values + record[list_field] return list(set(values))
9b30a2afb80e95479aba9bbf4c44ecdc0afaed34
30,170
def human_size(qbytes, qunit=2, units=None): """ Returns a human readable string reprentation of bytes""" if units is None: units = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'][qunit:] return str(qbytes) + units[0] if qbytes < 1024 else human_size(qbytes >> 10, 1, units[1:])
2d573c61ae5241383054936e99adcc38260fc9ae
30,175
def flesch(df): """ Calculates the Flesch formula for each text. The formula and its interpretation is given in this wiki page: https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests Needed features: Avg_words_per_sentence Avg_syllables_per_word Adds column: Flesch - Flesch formula score for the text """ # Flesch formula df["Flesch"] = 206.835 - 1.015 * df["Avg_words_per_sentence"] - 84.6 * df["Avg_syllables_per_word"] return df
8bf6efa9e9c2ddd8795688ed0d11b687c20a4c36
30,178
def state_size_dataset(sz): """Get dataset key part for state size. Parameters ---------- sz : `int` State size. Returns ------- `str` Dataset key part. """ return '_ss%d' % sz
2ab9b2247309b3441437baddd9f258f1772cd5ae
30,179
def trunc(number, n_digits=None, *, is_round=False): """ Function to truncate float numbers >>> from snakypy import helpers >>> helpers.calcs.trunc(1.9989, 2) 1.99 >>> helpers.calcs.trunc(1.9989, 2, is_round=True) 2.0 Args: number (float): Must receive a float number n_digits (int): An integer must be passed to define the number of places after the comma. is_round (bool): If the value is TRue, round the number. Returns: Returns a float number """ if is_round: return round(number, n_digits) if n_digits and not is_round: return int(number * 10 ** n_digits) / 10 ** n_digits return number
41f1e84271795fb0972e17a9c3a9208d1db8b816
30,182
import re def comment_modules(modules, content): """ Disable modules in file content by commenting them. """ for module in modules: content = re.sub( r'^([ \t]*[^#\s]+.*{0}\.so.*)$'.format(module), r'#\1', content, flags=re.MULTILINE ) return content
ba1c1a6a9e5fd9a655e7c6c00975843196b4c1db
30,183
import logging def get_logger(logger_name): """ Get the dev or prod logger (avoids having to import 'logging' in calling code). Parameters: logger_name - 'dev' or 'prod' Returns: Logger to use for logging statements. """ valid_logger_names = ['dev','prod'] if logger_name in valid_logger_names: return logging.getLogger(logger_name) else: raise ValueError("Invalid logger name: allowed values are "+",".join(valid_logger_names)) return None
2e4c41ef0eb226e11d9627090d80bcbbf9bfc475
30,186
def get_out_path(config): """ Returns path where summary output is copied after d-blink finishes running :param config: ConfigTree :return: path if it exists, otherwise None """ steps = config.get_list('dblink.steps') copy_steps = [a for a in steps if a.get_string('name') == 'copy-files'] # filter out 'copy-files' steps if len(copy_steps) == 0: return None if len(copy_steps) == 1: return copy_steps[0].get_string('parameters.destinationPath') else: raise NotImplementedError('Too many copy-files steps')
330e32fe84f473b5e46a3d033fe94653ed33e551
30,187
def _clean(item): """Return a stripped, uppercase string.""" return str(item).upper().strip()
92e3319345149b5b645b21250389ddf3ce04e636
30,191
def validation_email_context(notification): """Email context to verify a user email.""" return { 'protocol': 'https', 'token': notification.user.generate_validation_token(), 'site': notification.site, }
0475223827d57f93aba25f49080f02cf164628d6
30,194
def parse_path(path): """Parse a path of /hash/action/my/path returning a tuple of ('hash', 'action', '/my/path') or None values if a shorter path is given. :param path: :py:class:`string`: the path :rtype: :py:func:`tuple` """ if path == '/': return None, None, None paths = path[1:].split('/', 1) #Filter Empty strings paths = [p for p in paths if p != ''] if len(paths) == 1: return paths[0], None, None else: file_hash, rest = paths paths = rest.split('/', 1) #Filter Empty strings paths = [p for p in paths if p != ''] if len(paths) == 1: return file_hash, paths[0], None else: action, rest = paths return file_hash, action, rest
d6b9ea79104503888c862e8c42c8815e91a885fb
30,196
import six def _contains(values, splitter): """Check presence of marker in values. Parameters ---------- values: str, iterable Either a single value or a list of values. splitter: str The target to be searched for. Return ------ boolean """ if isinstance(values, six.string_types): values = (values,) try: if any([splitter in x for x in values]): return True return False except TypeError: return False
1f41e366309e7160d66a54115e1f20d4c3fe5f52
30,197
def get_top_namespace(node): """Return the top namespace of the given node If the node has not namespace (only root), ":" is returned. Else the top namespace (after root) is returned :param node: the node to query :type node: str :returns: The top level namespace. :rtype: str :raises: None """ name = node.rsplit("|", 1)[-1] # get the node name, in case we get a dagpath name = name.lstrip(":") # strip the root namespace if ":" not in name: # if there is no namespace return root return ":" else: # get the top namespace return name.partition(":")[0]
c7314b4b2dea934da4ab5710ee8cd1c1e7c87035
30,200
def football_points(win: int, draw: int, loss:int): """Calculate the number of points for a football team.""" return (win * 3 + draw)
692d115e3955847e2a2e9ede2995fedbc752a00c
30,201
def perc_diff(bigger, smaller): """ Calculates the percentual difference between two int or float numbers :param bigger: greater value :param smaller: smaller value :return: dif_perc """ dif_perc = round(((bigger - smaller) / smaller * 100), 2) return dif_perc
3e4a19e907afed549c598cd03d78454c2e140db1
30,202
def uploads_to_list(environment, uploads_list): """ return list of upload url """ return [upload.get("url") for upload in uploads_list]
7771dfb0190b76ad3de55168720640170e72f26c
30,203
def _element_fill_join(elements, width): """Create a multiline string with a maximum width from a list of strings, without breaking lines within the elements""" s = '' if(elements): L = 0 for i in range(len(elements) - 1): s += str(elements[i]) + ', ' L += len(elements[i]) + 2 if(L + len(elements[i+1]) >= width - 2): s += '\n' L = 0 s += elements[-1] return(s)
2cb08a9be5dfc5a6af99f9fbd95487fbaebf11ca
30,204
def hmsToHour(s, h, m, sec): """Convert signed RA/HA hours, minutes, seconds to floating point hours.""" return s * (h + m/60.0 + sec/3600.0)
900f6a942d126eb9af0f4f0ccfc57daac73e0e53
30,205
def convert_to_indices(vert_list): """ Convert given flattened components list to vertices index list :param vert_list: list<str>, list of flattened vertices to convert # NOTE: Vertices list must follow Maya vertices list convention: ['{object_name}.v[0]', '{object_name}.v[1]' ...] :return: list<str>, [0, 1, 2, 3 ...] """ indices = list() for i in vert_list: index = int(i.split('[')[-1].split(']')[0]) indices.append(index) return indices
b98f79fc8e6c5f8126698ef0ce0b1fb77e29250d
30,206
def guess_feature_group(feature): """Given a feature name, returns a best-guess group name.""" prefix_list = ( ('Sha', 'Shadow'), ('miRNA', 'miRNA'), ('chr', 'mRNA'), ('Fir', 'Firmicutes'), ('Act', 'Actinobacteria'), ('Bac', 'Bacterodetes'), ('Pro', 'Proteobacteria'), ('Ami', 'Amino Acid'), ('Pep', 'Peptide'), ('Car', 'Carbohydrate'), ('Ene', 'Energy'), ('Lip', 'Lipid'), ('Nuc', 'Nucleotide'), ('Cof', 'Cofactor or Vitamin'), ('Xen', 'Xenobiotics'), ('Gen', 'Genus OTU'), ('MET', 'Metabolite'), ('OTU', 'OTU'), ('V.K', 'Vaginal Functional'), ('F.K', 'Fecal Functional'), ('V.G', 'Vaginal Gene'), ('F.G', 'Fecal Gene'), ('V.', 'Vaginal OTU'), ('F.', 'Fecal OTU') ) for prefix, group in prefix_list: if feature.startswith(prefix): return group return 'NA'
f25d5c368cf832b48f8f154d525c96999fae39fb
30,209
def add_lane_lines(img, lane_line_img): """ Colors lane lines in an image """ ret_img = img.copy() ret_img[(lane_line_img[:, :, 0] > 0)] = (255, 0, 0) ret_img[(lane_line_img[:, :, 2] > 0)] = (0, 0, 255) return ret_img
2cab2fe7615f9072d998afc3c28a31ff82a7e8fd
30,212
import re def parse(instruction): """ Take an instruction as a string and return a tuple (output wire, input specification). Example input specifications: * ("ID", "6") for constant input * ("ID", "a") for direct wire input "a" * ("NOT", "ab") for negated wire "ab" * ("AND", "76", "xy") for bitwise-AND between constant and wire "ab" Keyword arguments: instruction --- an instruction formatted according to the challenge rules """ match = re.search("^(.*) -> ([a-z]+)$", instruction) if match: (input_expression, output_wire) = match.groups() if " " not in input_expression: input_command = ("ID", input_expression) elif "NOT" in input_expression: submatch = re.search(r"^NOT (\w+)$", input_expression) if submatch: input_command = ("NOT", submatch.group(1)) else: raise ValueError("Illegal instruction:", instruction) else: submatch = re.search(r"^(\w+) ([A-Z]+) (\w+)$", input_expression) if submatch: input_command = (submatch.group(2), submatch.group(1), submatch.group(3)) else: raise ValueError("Illegal instruction:", instruction) return (output_wire, input_command) else: raise ValueError("Illegal instruction:", instruction)
8a17605b4a4a93a2ca01e32bee083ece6d75627b
30,213
import math def _ms_to_us(time_ms, interval_us=1e3, nearest_up=True): """Convert [ms] into the (not smaller/greater) nearest [us] Translate a time expressed in [ms] to the nearest time in [us] which is a integer multiple of the specified interval_us and it is not smaller than the original time_s. Example: :: _ms_to_us(1.0) => 1000 [us] _ms_to_us(1.0, 1024) => 1024 [us] _ms_to_us(1.1) => 2000 [us] _ms_to_us(1.1, 1024) => 2048 [us] :param time_ms: time in milliseconds :type time_ms: float :param interval_us: the result will be an integer multiple o this value (default = 1e3) :type time_ms: int :param nearest_up: convert to not smaller nearest if True, to not greater otherwise (default = True) :type nearest_up: bool """ if nearest_up: return interval_us * int(math.ceil((1e3 * time_ms) / interval_us)) return interval_us * int(math.floor((1e3 * time_ms) / interval_us))
fcc6c03ba55451dccfce42b30579298d963ef696
30,215
def generate_dmenu_options(optlist: list) -> str: """ Generates a string from list seperated by newlines. """ return "\n".join(optlist)
6bcb1e601973d12d66c1d28f86a8eb4743408a4d
30,216
import time def _is_active(log_stream: dict, cut_off: int) -> bool: """ Determine if the given stream is still active and worth tailing. :param log_stream: A dictionary returned by `describe_log_streams` describing the log_stream under consideration. :param cut_off: The number of seconds to wait before calling a log_stream inactive. If the stream does not have a `lastIngestionTime` more recent than `cut_off` seconds ago it will be considered not active. :return: Whether the given log stream is active. """ last_ingest = log_stream["lastIngestionTime"] / 1000 return time.time() - last_ingest < cut_off
210dcd5a965dcf2535e55af694e11f17918666e6
30,217
import re def mountpoint_dataset(mountpoint: str): """ Check if dataset is a 'zfs' mount. return dataset, or None if not found """ target = re.compile(r'^.*\s+' + mountpoint + r'\s+zfs\b') with open("/proc/mounts") as f: mount = next((ds for ds in f.read().splitlines() if target.search(ds)), None) return None if mount is None else mount.split()[0]
b549a94915b0089fcb3267b6273bde6f3243bd65
30,223
def _add_necessary_columns(args, custom_columns): """ Convenience function to tack on columns that are necessary for the functionality of the tool but yet have not been specifically requested by the user. """ # we need to add the variant's chrom, start and gene if # not already there. if custom_columns.find("gene") < 0: custom_columns += ", gene" if custom_columns.find("start") < 0: custom_columns += ", start" if custom_columns.find("alt") < 0: custom_columns += ", alt" return custom_columns
931b7ed9b181462220e665e6fb895bb7a1a835dc
30,224
def get_part_of_speech(s): """ Detect part-of-speech encoding from an entity string, if present. :param s: Entity string :return: part-of-speech encoding """ tokens = s.split("/") if len(tokens) <= 4: return "" pos_enc = tokens[4] if pos_enc == "n" or pos_enc == "a" or pos_enc == "v" or pos_enc == "r": return pos_enc return ""
8498e4ff112bad0946b1f66b466007d9049b5e2f
30,228
def get_pam_and_tool_from_filename(score_filename): """Extracts pam/tool info from a score filename Args: score_filename: specific score file name (including .txt) Returns: list of pam, pam_tool Example: Example score file: 'aggt_Chimera.txt' output: ['aggt', 'Chimera'] """ pam, pam_tool_txt = score_filename.split('_') pam_tool = pam_tool_txt.split('.')[0] return pam, pam_tool
319c211d98591ab1702689e08d15cb5025ca7a6c
30,229
from typing import Dict from typing import Union def parse_websocket_action(data: Dict[str, str]) -> Union[str, None]: """ Returns the websocket action from a given decoded websocket message or None if the action doesn't exist or isn't a valid string. """ if isinstance(data, Dict): websocket_action = data.get('action', None) if websocket_action and isinstance(websocket_action, str): return websocket_action return None
7a7a2136c0f5809e51641ba10839070152b2df98
30,230
def get_object(conn, key, error='object not found', version_id=None): """ Gets an object from s3 """ def helper(): try: if version_id is None: return conn['client'].get_object(Bucket=conn['bucket'], Key=key) else: return conn['client'].get_object(Bucket=conn['bucket'], Key=key, VersionId=version_id) except conn['client'].exceptions.NoSuchKey: raise ValueError(error) k = helper() return {'key' : key, 'version_id' : k['VersionId'], 'body' : k['Body'], 'content_length' : k['ContentLength'], 'content_type' : k['ContentType'], 'metadata' : k['Metadata'], 'last_modified' : k['LastModified']}
506dfdf11c98d9cd6cf6d7d6938c71b4b6d4ae5c
30,231
import fnmatch def filter_repos(config, repo_dir=None, vcs_url=None, name=None): """Return a :py:obj:`list` list of repos from (expanded) config file. repo_dir, vcs_url and name all support fnmatch. Parameters ---------- config : dist the expanded repo config in :py:class:`dict` format. repo_dir : str, Optional directory of checkout location, fnmatch pattern supported vcs_url : str, Optional url of vcs remote, fn match pattern supported name : str, Optional project name, fnmatch pattern supported Returns ------- list : Repos """ repo_list = [] if repo_dir: repo_list.extend( [r for r in config if fnmatch.fnmatch(r['parent_dir'], repo_dir)] ) if vcs_url: repo_list.extend( r for r in config if fnmatch.fnmatch(r.get('url', r.get('repo')), vcs_url) ) if name: repo_list.extend([r for r in config if fnmatch.fnmatch(r.get('name'), name)]) return repo_list
587d81e0292f785fd8a4a4511487752a1d5ebfe7
30,234
def extend_smallest_list(a, b, extension_val=None): """Extend the smallest list to match the length of the longest list. If extension_val is None, the extension is done by repeating the last element of the list. Otherwise, use extension_val. Arg(s): a - A list. b - A list. extension_val - Extension value. Returns: The input lists with the smallest list extended to match the size of the longest list. """ gap = abs(len(a) - len(b)) if len(a) > len(b): extension_val = extension_val if extension_val is not None else b[-1] b += [extension_val] * gap else: extension_val = extension_val if extension_val is not None else a[-1] a += [extension_val] * gap return a, b
2d80690073cbf258ac918b1677b6cd0b7313d17d
30,235
def to_celsius(temp): """Convert temperature measured on the Fahrenheit scale to Celsius. Parameters: temp (int): temperature value to convert Returns float: temperature value converted to Celsius """ return round((int(temp) - 32) * .5556, 3)
da86d46794ef1e8d4d34ae2b23a48488b75643a0
30,240
def readable_bool(b): """Takes a boolean variable and returns "yes" for true and "no" for false as a string object. :param b: boolean variable to use """ if b: return "yes" else: return "no"
dc30a0dda31943538283b1f18dd6351ca0613614
30,243
import re def is_url(_str): """return true if the str input is a URL.""" ur = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', _str) return len(ur) > 0
7a298424c2f39f62a9d4197a7f822806e68e424f
30,244
from typing import Union from typing import List def common_missing_fills(variable_type: str) -> Union[List[int], List[str]]: """Return a list of common missing stand-ins. Returns ------- List[int] Parameters ---------- variable_type : str What type of variable to return the missing stand-ins for, either "numeric" or "string". Returns ------- list list of strings if variable_type is "string" and of ints if variable_type is "numeric". """ if variable_type == "numeric": common_missing_fill_vals_numeric = [-1] # repetitions of "9"s mc_cains = [int("9" * i) for i in range(2, 5)] mc_cains = mc_cains + [-i for i in mc_cains] common_missing_fill_vals_numeric = common_missing_fill_vals_numeric + mc_cains return common_missing_fill_vals_numeric elif variable_type == "string": common_missing_fill_vals_str = ["NA", "missing", "N/A", "NaN"] return common_missing_fill_vals_str else: raise NotImplementedError
1e3e189c7d2fd2895028ca5be59e3ada3a90a688
30,246
def obtain_ECG(tensec_data): """ obtain ECG values of ten second data :param tensec_data: 10 seconds worth of heart rate data points :return ECGData: ECG unmultiplexed data """ ECGData = tensec_data[1::2] return ECGData
ce63b58435b67b6995d19e04a64bcc24d9687cd5
30,252
import ast def str2dict(d_s): """Convert string to dictionary :d_s: Dictionary string :returns: Evaluated dictionary """ return ast.literal_eval(d_s)
959da3c3197b5f8338cc33a7d9998303c50dd424
30,260
def project_08_largest_product(count): """ Problem 8: Find the largest product of n numbers in a hardcoded series.. Args: count (int): The number of adjacent numbers to determine product for. """ def product(sequence): if 0 in sequence: return 0 else: product = 1 for term in sequence: product = int(int(product) * int(term)) return product series = '73167176531330624919225119674426574742355349194934' \ '96983520312774506326239578318016984801869478851843' \ '85861560789112949495459501737958331952853208805511' \ '12540698747158523863050715693290963295227443043557' \ '66896648950445244523161731856403098711121722383113' \ '62229893423380308135336276614282806444486645238749' \ '30358907296290491560440772390713810515859307960866' \ '70172427121883998797908792274921901699720888093776' \ '65727333001053367881220235421809751254540594752243' \ '52584907711670556013604839586446706324415722155397' \ '53697817977846174064955149290862569321978468622482' \ '83972241375657056057490261407972968652414535100474' \ '82166370484403199890008895243450658541227588666881' \ '16427171479924442928230863465674813919123162824586' \ '17866458359124566529476545682848912883142607690042' \ '24219022671055626321111109370544217506941658960408' \ '07198403850962455444362981230987879927244284909188' \ '84580156166097919133875499200524063689912560717606' \ '05886116467109405077541002256983155200055935729725' \ '71636269561882670428252483600823257530420752963450' max_terms = list(map(int, series[0:count])) max_product = product(max_terms) for start_index in range(1, len(series)-count-1, 1): terms = list(map(int, series[start_index:start_index+count])) term_product = product(terms) if term_product > max_product: max_terms = terms max_product = term_product return max_product
49d7e5d5d2b90bc22b07d9af7863b8367d16501d
30,262
def load_input_segs(cand_segs, ref_segs, src_segs=None): """ Load input files specified in the CL arguments into memory. Returns a list of 5-tuples: (segment_id, origin, src_segment, candidate_segment, reference_segment) "origin" is always None (present for compatibility with other modules handling sdlxliff files). "src_segment" is None if the source file was not passed on the CL. """ # src file is optional src_segs = src_segs or [None] * len(cand_segs) assert len(src_segs) == len(cand_segs) == len(ref_segs) return [(i, None, src.strip() if src else src, cand.strip(), ref.strip()) for i, (src, cand, ref) in enumerate(zip(src_segs, cand_segs, ref_segs), 1)]
e6d8f6b92d00603dc7c06ca1484bf86ebea84273
30,263
from typing import Union def fibonacci_k_n_term(n: int, k: int) -> Union[int, NotImplementedError]: """ Returns the nth fibonacci_k number. Where F_{k,n+1} = k*F_{k,n} + F_{k,n−1} for n ≥ 1 """ if n < 0: return NotImplementedError('negative n is not implemented') if n in [0, 1]: return n root = (k+(k**2 + 4)**0.5) / 2 return round((root**n - (-root)**(-n)) / (root + 1/root))
135e130f63e0ab9317eb145f21e55268412973da
30,264
from typing import Sequence def chg_modelqa(models: Sequence, ordinal: int, **kwargs) -> int: """ Information on the quality of the curve fit the intercept the ordinal date. Args: models: sorted sequence of CCDC namedtuples that represent the pixel history ordinal: standard python ordinal starting on day 1 of year 1 Returns: curve_qa or 0 """ if ordinal <= 0 or not models: return 0 for m in models: if m.start_day <= ordinal <= m.end_day: return m.curve_qa return 0
9d370dcecccd67204d2c88edf5d8d426f72ef2dd
30,265
import yaml def yaml_read(path): """ Reads yaml from disk """ with open(path, "r") as fp: return yaml.load(fp, Loader=yaml.FullLoader)
838b286792dfa0a38a385fe38aafdef92945e263
30,278
def chunks(obj, size, start=0): """Convert `obj` container to list of chunks of `size`.""" return [obj[i : i + size] for i in range(start, len(obj), size)]
c523a346906b85c121bf67a56a806d51f639eeb3
30,282
def http_verb(dirty: str) -> str: """ Given a 'dirty' HTTP verb (uppercased, with trailing whitespaces), strips it and returns it lowercased. """ return dirty.strip().lower()
74601bb0d5e22f632612fbf63924e27777ce8bf3
30,283
import copy def trim_audio(A, start, stop): """Trim copy of MultiSignal audio to start and stop in seconds.""" B = copy.deepcopy(A) assert start < len(B) / B.fs, 'Trim start exceeds signal.' for c in range(B.channel_count): B.channel[c].signal = B.channel[c].signal[ int(start * B.fs): int(stop * B.fs)] return B
722a6b40bed4b6e441cddc5e0a0c5ca75207f701
30,288
def all_values_unique(d): """Return whether no value appears more than once across all value sets of multi-valued mapping `d`.""" seen = set() for multivalue in d.values(): if any(v in seen for v in multivalue): return False seen.update(multivalue) return True
a4663130a72e88b77dc47878165149fc35b50cec
30,295
def calculate_future_value(present_value, interest_rate, compounding_periods, years): """ Calculates the future value of money given the present_value, interest rate, compounding period, and number of years. Args: present_value (float): The present value interest_rate (float): The interest rate periods (int): The compounding period years (int): The number of years Returns: The future value of money. """ future_value = present_value * ((1 + (interest_rate / compounding_periods))**(compounding_periods * years)) future_value_formatted = round(future_value, 2) return future_value_formatted
80578a52a7339e647846b342ff44e0593351a204
30,296
def align(value, m): """ Increase value to a multiple of m """ while ((value % m) != 0): value = value + 1 return value
9171b62c71ae21b51b2f6cffe9e9e2a6d4778446
30,300
def get_ip(request): """ Attempts to extract the IP number from the HTTP request headers. """ key = "REMOTE_ADDR" meta = request.META # Lowercase keys simple_meta = {k.lower(): v for k, v in request.META.items()} ip = meta.get(key, simple_meta.get(key, "0.0.0.0")) return ip
2ccb542312257a955b0e2a34c2f63693c818955d
30,303
import re def sanitize_title(title): """Generate a usable anchor from a title string""" return re.sub("[\W+]","-",title.lower())
bb6b1cf9a5e0e9b9e896d35e6c7b77beb631ac64
30,305
def IsGoodTag(prefixes, tag): """Decide if a string is a tag @param prefixes: set of prefixes that would indicate the tag being suitable @param tag: the tag in question """ for prefix in prefixes: if tag.startswith(prefix): return True return False
7c772b24c0b17257654fca0fb1e5d6c41ffbf9a9
30,311