content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def parse_picard_file(fpath): """ From MultiQC - Adapted to parse picard outputs so we can display specific metrics in tables """ parsed_data = dict() keys = None commadecimal = None filehandle = open(fpath) for l in filehandle: if "HsMetrics" in l and "## METRICS CLASS" in l: ...
ff2402d763cc1e8eff42a624169042a6fbb01ead
628,301
import os import pickle import torch def load_data(): """You can use this function to load the files you saved using Atari_DeepMind_Grid""" game_name = input("""Enter the name of the game from which you want to load data (without version) : """) model = input("""model (dqn/...
dc4386d64cb5bcc81501f2e284dd9f7bd016f876
628,302
def offset_api_limit(sp, sp_call): """ Get all (non-limited) artists/tracks from a Spotify API call. :param sp: Spotify OAuth :param sp_call: API function all :return: list of artists/tracks """ results = sp_call if 'items' not in results.keys(): results = results['artists'] ...
6dcbcf33e4a47fba5dbd832bcf4fb7cfb5898fa7
628,304
import os def is_file_exist(file: str) -> bool: """ 判断文件名是否存在 :param file: 文件名 :return: bool """ return os.path.exists(file)
050af611748c2b5227a00ebccae4abaaf2b75164
628,307
from datetime import datetime def get_date(): """ Return date as string """ return datetime.now().strftime("%c")
20fe11e45f1304192fe5c4faa8e4587a7ca0e719
628,308
def receber_jogada(): """ Lê uma jogada e confere se ela é válida """ #Lista com as jogadas válidas validas = ["a","s","d","w"] while True: #Conferindo se a jogada faz parte do conjunto #de válidas jogada = input("""\n W \nA S D :""") if jogada.lower() in validas: ...
66a6c311b435a5a253f32c139631e270876ed11b
628,309
from typing import Callable def make_normalization_function(min_value: float, max_value: float, scope=(0, 1)) -> Callable: """ Minimax normalization :param min_value: Min value in data :param max_value: Max value in data :param scope: Normalization range :return: normalization function ""...
2414bb7172cff411e461f4255f7c7d69bf6b8d9e
628,310
import subprocess def get_db2sysc_user(): """ """ return subprocess.Popen( ["ps", "-o", "user", "-C", "db2sysc"], stdout=subprocess.PIPE ).communicate()[0].strip().splitlines()[1].strip()
97753ee5430ef9ed74579be05e2ed9e8cb20a130
628,311
import os import time def build_name(kscfg, release=None, prefix = None, suffix = None): """Construct and return an image name string. This is a utility function to help create sensible name and fslabel strings. The name is constructed using the sans-prefix-and-extension kickstart filename and the su...
c40334dc43bb18fb9134083a3a6c2473ce32cd5b
628,312
import requests def request(url, input_file, token, include_words=False): """ :param input_file: Input object :param url: Endpoint url :param token: X-Inferuser-Token :param include_words: Include Mindee vision words in http_response :return: requests response """ input_file.file_objec...
bed43f7888d0d7f6a06641b02d5984cfe2879107
628,313
import argparse from typing import List def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: """Get a list of subcommands for an ArgumentParser""" sub_cmds = [] # Check if this is parser has subcommands if parser is not None and parser._subparsers is not None: # Find the _SubP...
a06d12fc2d3b64cf72a26aa64f0e1201f8293c1b
628,314
def xml_get_attrs(xml_element, attrs): """Returns the list of necessary attributes Parameters: element: xml element attrs: tuple of attributes Returns: a dictionary of elements """ result = {} for attr in attrs: result[attr] = xml_element.getAttribute(attr) ...
77911646f3624dc089475927a8b1e14abd9caef7
628,315
from typing import Dict def _get_api_headers(token: str) -> Dict: """ Return authorization header with current token. Parameters ---------- token : str Azure auth token. Returns ------- Dict A dictionary of headers to be used in API calls. """ return { ...
c8761da1ba2c36825b1a73bd236196a125d1bdfd
628,316
import subprocess def launch(command): """Launch a program as it would have been launched in terminal""" commands = command.split() subprocess.Popen(commands) return True
8436f2b87aab826cab82aa3fb6aaf0ad2cafb113
628,317
def arg_cond_req_or(args_array, opt_con_req_dict): """Function: arg_cond_req_or Description: Checks a dictionary list array for options that require one or more options to be included in the argument list. Arguments: (input) args_array -> Array of command line options and values. ...
b691b92eeaae063dd25e80f5db7b0ed795ea8519
628,318
def fanout(w): """ Get the number of places a wire is used as an argument. :param w: WireVector to check fanout for :return: integer fanout count """ _, dst_nets = w._block.net_connections() if w not in dst_nets: return 0 all_args = [arg for net in dst_nets[w] for arg in net.args] ...
3ce96c3eab252d0b34c13c346cb9acfbaf34c618
628,319
def get_tree( graph, root, prop, mapper=lambda x: x, sortkey=None, done=None, dir="down" ): """ Return a nested list/tuple structure representing the tree built by the transitive property given, starting from the root given i.e. get_tree(graph, rdflib.URIRef("http://xmlns.com/foaf/0.1/P...
345d5023d1342d58ed9f644d78a1bc7908726bbd
628,320
def get_file_contents(file_path): """ Get expected result from file. """ try: with open(file_path, 'r') as f: # remove string literals (needed in python2) and newlines return f.read().replace('\r', '').strip() except OSError as e: raise e
4debf6b82eed7f4c1ee5e747efb7c4a8ce33fcda
628,321
def endswith_xFFxD9(data): """ Checks whether the given data endswith `b'\xD9\xFF'` ignoring empty bytes at the end of it. Parameters ---------- data : `bytes-like` Returns ------- result : `bool` """ index = len(data) - 1 while index > 1: actual = data[index] ...
9be0913e7226ff64938e083f19990f8521d01873
628,322
import os def _is_executable_file(path): """Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. This function was forked from pexpect originally: Copyright (c) 2013-2014, Pexpect development team Copyrig...
e62d26415621049ef61a58a795df78a34251e067
628,323
def infix(formula: str, arg: int): """ evaluation of infix expression :param formula: bytebeat formula :param arg: time argument :return: int: computation result """ characters = formula.replace("t", str(arg)).replace("/", "//") try: return eval(characters) except...
7bee7c4711b20b91502b934607752cfa7022dd85
628,324
import requests def get_list_nab() -> list: """ Get list of possible time series to retrieve from the Numenta Anomaly Benchmark: https://github.com/numenta/NAB. Returns ------- List with time series names. """ url_labels = 'https://raw.githubusercontent.com/numenta/NAB/master/labels/combi...
2dc0bc54c274f2208a2303826a394401d44e6ffc
628,325
from typing import Dict def first_subset_second(first: Dict, second: Dict) -> bool: """ Return true if first is a subset of second, false otherwise. :param first: first dict :param second: second dict :return: true if all elements in first are in second, and are mapped to same value,...
0f05340b8ba92f088d547837d8fd12c03933ccac
628,326
from typing import Union from typing import Type from typing import Any from typing import Optional import inspect def get_module_source_from_class( class_: Union[Type[Any], str] ) -> Optional[str]: """Takes class input and returns module_source. If class is already string then returns the same. Args...
783b64590da118f0fab0b68588e008f923aa253e
628,327
def take_fragment(umi, fragment_index): """ >>> take_fragment("AGCT-TCGA", 0) 'AGCT' >>> take_fragment("AGCT-TCGA", 1) 'TCGA' >>> take_fragment("AGCT_TCGA", 0) 'AGCT_TCGA' >>> take_fragment("AGCT", 1) Traceback (most recent call last): ... ValueError: ('Fragment index out o...
09b2de506c6643dc8b95fcedbac33b7e053040f8
628,328
def mean(items): """ Calculates arithmetic mean. Returns zero for empty lists. """ return float(sum(items)) / len(items) if items else 0
a01271032bb9b7b2a1f9e305edf95b08da58e810
628,329
from datetime import datetime def _build_date(date, kwargs): """ Builds the date argument for event rules. """ if date is None: if not kwargs: raise ValueError('Must pass a date or kwargs') else: return datetime.date(**kwargs) elif kwargs: raise Val...
b298683842e3e2d24e04d9c6a03d09debee62ac6
628,330
def parse(puzzle_input): """Parse input""" return [int(line) for line in puzzle_input.split()]
e870a59298d44991e5fb82d5de432613e5078ebd
628,332
import os def _filename(f): """Return the filename relative to `common.py`.""" return os.path.join(os.path.dirname(__file__), f)
0d0c6904ce0c4119164793f5b5bba41c43d43b35
628,333
def equalize_strings(x_value, y_value): """ >>> def eq_str(x, y): ... max_len = max(len(x), len(y)) ... return x.zfill(max_len), y.zfill(max_len), max_len >>> >>> all(equalize_strings(x, y) == eq_str(x, y) for x, y ... in (('x' * i, 'y' * (i // 2)) for i in rang...
24917322c53d8c148b95d018aed0e7e345d02afe
628,334
def column_types(tbl): """ table column types """ return tuple(tbl.dtypes)
bdccd8540dd366c1f3102e0b24b1ca2593edd30c
628,335
import subprocess def diff_two_files_identical(file1, file2): """ Check whether two files are identical. Return true if diff reports no differences. >>> file1 = "test_data/file1" >>> file2 = "test_data/file2" >>> diff_two_files_identical(file1, file2) True >>> file1 = "test_data/test1...
7b96b3b726cb04adf3db262a950d81e19104c54b
628,336
import importlib def get_table(table_name): """ Returns an instance of a unit table given the name of the table. @param table_name Name of table to retrieve @return UnitTable instance """ converter_module = importlib.import_module('unitconverter.unit_tables.%s' % table_name) converter_cl...
197ccb88f2821550e1576cbedd142fc89eff0c8f
628,337
def __add_sentiment_column__(dataset): """ Create a new column for multi-class classification :param dataset: the dataset to use :return: the updated dataset """ dataset['Sentiment'] = dataset['Positive'] * 100 + dataset['Negative'] * -100 dataset['Sentiment'] = dataset['Sentiment'].map({10...
6ecb8896aae20e236f18aa240c4ded1aa94aa9ea
628,338
def flatten_filesystem(entry, metadata): """ Converts all nested objects from the provided metadata into non-nested `field->field-value` dicts representing filesystem metadata changes. Raw values (such as memory size, timestamps and durations) are transformed into easy-to-read values. :param entry...
1777c5bfa9dd6337f04eab38b8f7795a67c5ecf5
628,339
def convert2dict(data, train=True): """convert data to dict""" return data.text, data.label
fdb384754206a5252da82cfabc1ca5e934876340
628,340
import six def to_utf8(string): """ Encode a string as a UTF8 bytestring. This function could be passed a bytestring or unicode string so must distinguish between the two. """ if isinstance(string, six.text_type): return string.encode('utf8') return string
393d902e34f11b46317c5ef4d9501cfc725f0cb8
628,341
import gzip def reader(fname): """Returns correct file object handler or reader for gzipped or non-gzipped FastQ files based on the file extension. Assumes gzipped files endwith the '.gz' extension. """ if fname.endswith('.gz'): # Opens up file with gzip handler return gzip.open ...
6d24474fb51b9902888c13d4341cf0b25fcbf104
628,342
import torch def one_hot_encoding(input_tensor, num_labels): """ One-hot encode labels from input """ return torch.eye(num_labels, device=input_tensor.device)[input_tensor]
ce878d1dbc1f5802a4a8059a586d14bc1e9d342a
628,343
def get_e_hs_H_d_t(e_th_H_d_t, e_r_H_d_t): """(7) Args: e_th_H_d_t: 日付dの時刻tにおける暖房時のヒートポンプサイクルの理論効率(-) e_r_H_d_t: 日付dの時刻tにおける暖房時のヒートポンプサイクルの理論効率に対する熱源機の効率の比(-) Returns: 日付dの時刻tにおける暖房時の熱源機の効率(-) """ return e_th_H_d_t * e_r_H_d_t
b80bc588f62312dd9ac1b188d8bec7187d10395d
628,344
def integerize_shape(func): """装饰器,保证input_shape一定是int或None """ def convert(item): if hasattr(item, '__iter__'): return [convert(i) for i in item] elif hasattr(item, 'value'): return item.value else: return item def new_func(self, input_shape)...
f9945cfc71da72755cd9d16a648937e014000ced
628,345
def _adapt_parent_trials(node, parent_trials_node): """Adapt trials from the parent recursively .. note:: To call with node.map(fct, node.parent) to connect with parents """ if parent_trials_node is not None: adapter = node.item['experiment'].refers['adapter'] for parent in pa...
0f35559cfa646d6e8f9d6eb6fbbdf4a3c5bee0ee
628,346
def check_type(lp): """ check the type of the launchpad :param lp: launchpad object :return: name of launchpad type """ if lp.Check(0, "pro"): print("Launchpad Pro") return "Pro" elif lp.Check(0, "mk2"): print("Launchpad Mk2") return "Mk2" else: ...
acf8b349d0bd8858b0445d74b6eb9ea3bca582ce
628,347
def edits0(word): """ Return all strings that are zero edits away from the input word (i.e., the word itself). """ return {word}
7f4a4d1ce4584dc66443eabe8999722351e815e6
628,348
import json def open_json(filepath, default_data): """parse a json file Args: filepath (str): load location default_data (dict): default json data if file is not found Returns: dict: parsed_json """ try: with open(filepath, 'r') as json_file: # open file in appen...
7e68916b896ef8ec58a85da787c3f1bb0276da1c
628,349
def extract_num_options(val): """ convert a categorical to a number of options """ if len(val) == 1: for v in val: if isinstance(v, tuple): # this looks nightmarish... # but i think it should always work # should also check if the tuple...
8994c6149ca1a2bd4c3ed150ac3380ef3ce38296
628,350
def byte_list_to_string(byte_list): """Convert a list to human readable string in HEX :returns: a string representing the list """ hex_str = [hex(x) for x in byte_list] return "[{0}]".format(' '.join(hex_str))
537162b8f03341e3fb025b8bfb5aecc8a247d5fa
628,351
def greet_all(greeting: str, names: list) -> list: """Return a list of strings that consist of the greeting messages for each person in names. The format of each greeting message is '<greeting>, <name>', where greeting is the given greeting and <name> is an element of <names>. The returned list should...
03303a15e5f8ac807f8e630fc3210d611bd7af1d
628,352
def harmonic_mean(arr_of_pos_nr): """ harmonic mean :param arr_of_pos_nr: array of pos real numbers :return: harmonic mean """ if len(arr_of_pos_nr) == 0: raise IndexError('no element in array') # if not any(isinstance(x, (int, float)) and x >= 0 for x in arr_of_pos_nr): # ra...
4e867dee4e37927771b920a23f421f66f69c7977
628,353
def idx_word(idx, nlp): """ Returns the token/word at the specified index of the spaCy model. :param idx: The index to query. :param nlp: The spaCy model. :return: Word at the index in the vocabulary. """ hash_code = nlp.vocab.vectors.find(row=idx) if len(hash_code) == 0: return '<UNK>' return nlp.vocab.stri...
5cc53f5869c247ce8759583e63aae2ea1ef3e216
628,354
def inverse(dictionary): """ {a: {b}} -> {b: {a}} """ result = {} for key, values in dictionary.items(): for value in values: if value not in result: result[value] = set() result[value].add(key) return result
117d33067fef5bd1ceec4c6bdfcc82fc0c9ac79b
628,356
def get_entity_from_bio(tokens, entitys): """ Get {word:entity} from bio labeled sequence,. Only accept BIO schema. inputs: tokens: A B C D E F entitys: B-GPE I-GPE B-PER I-PER O O return: {'AB': 'GPE', 'CD': 'PER'} """ word2entity = {} left = 0 r...
817de1c0d696682cc119cf5e2fe550c103838729
628,357
import os import subprocess def annotate_orfs(fa, seqs, threads, threshold = 1e-6): """ search orfs against pfam # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, {orf: annotations}], ...]] """ db = '%s/pfam/Pfam-A.hmm' % os.environ['database...
6662142a26fb0393cc6d65440b2e33c9a6d4a400
628,358
def _resource_fields(chromo): """ return the resource metadata fields created for resource definition chromo """ return { 'name': chromo['resource_name'], 'description': chromo['title'], 'url_type': u'datastore', }
bf87275abf2453f46630f7059e4388b41b835eda
628,359
import torch def one_hot(tensor, depth, dim=-1, on_value=1.0, dtype=torch.float32): """get the one hot tensor from tensor""" tensor_onehot = torch.zeros(*list(tensor.shape), depth, dtype=dtype, device=tensor.device) tensor_onehot.scatter_(dim, tensor.unsqueeze(dim).long(), on_value) return tensor_oneh...
ec02c2102aedc696b0aa1a6424a268277d10b4cf
628,360
def all_same_suit(card_set): """ Determines whether the cards in the given collection are all of the same suit. """ return all(card.suit == card_set[0].suit for card in card_set[1:])
8069c8809b788fc754f0d2720947b03c513653cb
628,361
def lorenz(in_, t, sigma, b, r): """Evaluates the RHS of the 3 Lorenz attractor differential equations. in_ : initial vector of [x_0, y_0, z_0] t : time vector (not used, but present for odeint() call) sigma : numerical parameter 1 b : numerical parameter 2 r : numerical parameter ...
f4b9758be3a0f956f2b27fbb389dfcb2fb6edbfc
628,362
def _text_preprocessing(text): """ Apostrophes not handled properly by spaCy https://github.com/explosion/spaCy/issues/685 """ return text.replace('’s', '').replace('’m', '').replace('\'s','')
898a8ebc7bdbd49d3c7a96c26576a9360a1005bf
628,364
from typing import Sequence from typing import Dict def get_masks(counterfactuals: Sequence[Sequence[str]], vocab_to_indices: Dict[str, Sequence[int]]): """Returns masks indicating if counterfactual tokens are in original sentence. Args: counterfactuals: The tokens of the input's counterfactual...
504d4f9e3fba844c4d2496c47003e34fd54b8752
628,365
def count_digits(n): """Counts the number of digits in `n` Test cases: - 057 """ if n == 0: return 1 num_digits = 0 while n > 0: num_digits += 1 n /= 10 return num_digits
700cc1e02761ae9c977954c9140c48b28c838d9e
628,366
def merge_fe(dataset): """combine the columns of Fe2O3 and FeO in the formula of 0.8998 * Fe2O3 + FeO :param dataset: data set :return: data set with the transformation of FeO """ print("Combine the columns of 'Fe2O3' and 'FeO' in the formula of (0.8998 * Fe2O3 + FeO)") print("Remove the column...
2af3915890acc20cf99bc3694b2111d821576b9a
628,367
import glob def sourceList(): """ Return list of all python modules except this one in current dir """ liste = [] for s in glob.glob("*.py"): if s == 'runalltests.py': continue s = s.split('.')[0] liste.append(s) return liste
caac0cb89916145816f719dca380a4b5f8611fcd
628,368
def zscore(raw, mean, stddev): """Returns the zscore (standard score) of a value""" zscore = (raw - mean) / stddev return zscore
545e3354105c021dc537dcd80013f074b311f71b
628,369
def get_filter_list(table): """Get the filter list and number of filter in a table.""" filters = set(table['filter']) return filters, len(filters)
347e623dc82a74453bfd82524946ff5be9db28b6
628,371
import numpy def construct_transformation_matrix(args): """Construct the transformation matrix :param args: parsed arguments :return: transform """ # original params lengths = numpy.array(args.lengths, dtype=numpy.float32) indices = numpy.array(args.indices, dtype=numpy.int32) origin ...
bccd6be28fe2db6b0109c63367d22e725d33b4ce
628,373
import json import subprocess def unit_get(attribute): """Get the unit ID for the remote unit""" _args = ['unit-get', '--format=json', attribute] try: return json.loads(subprocess.check_output(_args).decode('UTF-8')) except ValueError: return None
957e3f779195fdcbd36a827081e248b4d2acabf0
628,374
def approximate_index(dataset, findvalue): """ Return index value in dataset, with optimized find procedure. This assumes a `dataset` with continuous, increasing values. Typically, these are timestamps. :param list dataset: a continuous list of values (f.e. timestamps) :param int findvalue: the value,...
98e8720ee3cf7e175ba0df69cf4f3671f4b52ecb
628,375
def gen_k1_graph_in(size: int) -> str: """ Generate K1 graph input :param size: size of graph """ input_graph = f"{size} {size}" for i in range(size // 2): input_graph += f" {i*2} {i*2+1} 1" input_graph += f" {i*2+1} {i*2} 1" return input_graph
1ad21ac1c96bff2da2b0e8fb0c69c8e46893f12c
628,376
def _find_qubit_id(cmd): """Find qubit id in openqasm cmd.""" left = [] right = [] for i, j in enumerate(cmd): if j == '[': left.append(i) elif j == ']': right.append(i) if len(left) != len(right): raise ValueError(f"Parsing failed for cmd {cmd}") ...
78082b69c932d0ad78f491e002d9c5a1665c622c
628,377
def get_upload_path(instance, filename): """ Construct the path to where the uploaded config file is to be stored. """ configtype = instance.config_type.lower() # sanitize the filename here.. path = 'export/config/{0}/{1}'.format(configtype, instance.filename) return path
76c4f0fef08c649cd482c33e2891984d214169a7
628,378
import os def getFilename(session=0,level=0,extension='xml',root='.'): """ @return: the scenario file name for the given session ID and level @rtype: str """ return os.path.join(root,'%s_%d.%s' % (session,level,extension))
1d90f96fd4b55934a17b8f0c535d9e3917bcecbf
628,379
from functools import reduce def compute_product_string(product_string): """Takes `product_string` and returns the product of the factors as string. Arguments: - `product_string`: string containing product ('<factor>*<factor>*...') """ factors = [float(f) for f in product_string.split("*")] ...
ebd2a7e57529dc24960a29b5406634830f30bf83
628,380
def get_battery_energy_full(battery_id): """ Get the maximum energy stored in the battery :param battery_id: Battery ID/Number e.g. BAT0 :return: maximum energy (int) """ with open(f'/sys/class/power_supply/{battery_id}/energy_full') as f: battery_percentage = int(f.read()) return b...
7465c89a91680d746a35d6f5db0dd27c652e9e39
628,381
def _GetTestSubPath(key): """Gets the part of the test path after the suite, for the given test key. For example, for a test with the test path 'MyMaster/bot/my_suite/foo/bar', this should return 'foo/bar'. Args: key: The key of the TestMetadata entity. Returns: Slash-separated test path part after...
c792a606d54b10f67bbb270964be319135500bf5
628,382
import json import re def get_dblp_titles(fp): """ :param fp: Path to DBLP scraper results (JSON) :return: acl_id2title, doi2title, arxiv2title """ title2dblp_hits = json.load(open(fp, 'r')) title2doi = {} doi2title = {} title2arxiv = {} arxiv2title = {} title2acl_id = {} ...
9511eb619bde626769fb3c612031a1bcacf388e3
628,383
import os def _ch_emitter(source, target, **_kw): """generate target list for check header builder""" target = [] for src in source: (base, _ext) = os.path.splitext(src.abspath) target.append(f"{base}_check_header$OBJSUFFIX") return target, source
859643d41229bd390159c2ec52d8232d801825f5
628,384
def get_string_without_quotes(str): """ Helper function to return a string without the quotes :param str: Input String :type str: String :return: String with quotes replaced :rtype: String """ return str.replace('"', '')
56f4dc56d82b0dae01f93fcb0ea405f6b0e3ccac
628,385
def show_tags(skin_name, context): """ 태그 목록 :return: """ # context 에 추가 # context['tags'] = get_tags() context['body_id'] = 'tt-body-tag' context['route_type'] = 'tags' return context
d4044224d6eefe74f541fb8bd505097599c09c10
628,386
def property_type(value): """ Return the type for given value in Neo4j land. """ if isinstance(value, str): return "string" elif isinstance(value, int): return "int" elif isinstance(value, float): # Nb. Python floats are double precision return "double" elif ...
7c037c2ad310b8c0a30823b10eda10a5c3f5f37f
628,388
def check_error(ck_id_list, ck_head_list): """ check if head is not in the id list to remove the sentence which involves this case. :param ck_id_list: :param ck_head_list: :return: """ error_sent = [] for i, (ck_id_sent, ck_head_sent) in enumerate(zip(ck_id_list, ck_head_list), 1): ...
6df718a24bd45e1db442d3c4c8ffb6a52f55dca7
628,389
def pivotCombinedInventories(combinedinventory_df): """Create a pivot table of combined emissions. :param combinedinventory_df: pandas dataframe returned from a 'combineInventories..' function :return: pandas pivot_table """ # Group the results by facility,flow,and compartment combinedi...
71d56bd546b5990c7b2658f0616ebaf8ed6f472f
628,390
def get_epsilon_inc(epsilon, n, i): """ n: total num of epoch i: current epoch num """ return epsilon / ( 1 - i/float(n))
77a318df7592f1aa0e3967232efd80f75fff6670
628,392
def pubapi_dev_tensor_ptr(self): """get a pointer to the corresponding mgb::pubapi::DeviceTensor object :rtype: int :return: the address as an integer """ return self._pubapi_dev_tensor_ptr(1)
7526d7fd6b17cd955fe295cc17e2913a401acf59
628,393
def fahrenheit_to_celsius(temperature): """Covert from Fahrenheit to Celsius :param temperature: degree understood to be in Fahrenheit NOTE: Fahrenheit to Celsius formula: °C = (°F - 32) x 5/9 First subtract 32, then multiply by 5, then divide by 9. """ return (temperature - 32) * 5.0 / 9.0
cc054b90d17c7d9850e2762181b86a6c54719142
628,394
def ranges_overlap(min1, max1, min2, max2): """ :param min1: :param max1: :param min2: :param max2: :return: return True if the 2 ranges overlap (edge inclusive), else False """ if min1 <= max2 and min2 <= max1: return True return False
ec531bf2303e1d7a36d55a6ba9be8fac00fb65e4
628,396
import copy def recursive_postprocessing(filter_, condition, replacement): """Recursively descend into the query, checking each dictionary (contained in a list, or as an entry in another dictionary) for the condition passed. If the condition is true, apply the replacement to the dictionary. Param...
2a639a621100ab7c23222c26a8944ea223b5b6d1
628,397
from typing import Iterable def search_split_pos(text: str, keys: Iterable = "”’】)。!?;~…"): """查找最适合切分的位置""" def rindex(c: str): try: return text.rindex(c) except ValueError: return -1 return max(map(rindex, keys)) + 1
5e7a3200a02736cc96eef8b68b58a3f67a5d648c
628,398
import bisect def find_between(a, low, high): """Finds all elements of a between low and high. Simple binary search algorithm using the bisect module. Searches the array a for all elements between low and high. Useful for finding mergers that occur between time t1 and t2. Arguments: a {...
40596dfbb4d99c7b9988fbf22c787eaf22a94f6a
628,399
def get_attribute(element, attribute, default=0): """ Returns XML element's attribute, or default if none. """ a = element.getAttribute(attribute) if a == "": return default return a
84406553069b9c300d6ea188d970f554cd7ee424
628,400
def _device_in_list( devices: str | frozenset[str], device_type: str, do_wildcard_search: bool ) -> bool: """Return if device is in set.""" if isinstance(devices, str): if do_wildcard_search: return device_type.lower().startswith(devices.lower()) return device_type.lower() == dev...
20c76338aed4ec76fc12d338758aa1eeaea57471
628,401
import zlib import random def find_credit_grade(email): """Returns the credit grade of the person identified by the given email address. The credit grade is generated randomly using the email as the seed to the random number generator. The credit grade can be either A, B, C, D, E, F or G. ""...
254cafd9db80219b4ea4725af76c89365e32c646
628,402
def jul_day(year, month, day): """ Routine to calculate julian day. This is the weird Astronomical thing which counts from 1 Jan 4713 BC. :param year: Year :param month: Month :param day: Day :type year: integer :type month: integer :type day: integer :return: julian day :rt...
5fb27836d36888184ae56f79e837c89628ea6dc8
628,403
def _factor2(n): """Factorise positive integer n as d*2**i, and return (d, i). >>> _factor2(768) (3, 8) >>> _factor2(18432) (9, 11) Private function used internally by the Miller-Rabin primality test. """ assert n > 0 i = 0 d = n while 1: q, r = divmod(d, 2) ...
52c2a627636f07e4b8fe6028b705051cf2565a4a
628,404
def to_lists(scraped_data): """ Translate elements of scraped data (a list) from dicts to lists and return it. Convert 'research_fields' and 'research_objects' lists to ' :: '-delimited strings. """ delimiter = " :: " return [[lab["number"], lab["certdate"], lab["org_name"], lab["org_address"], lab[...
468d991986e4649e7a3c174557616e9590327232
628,405
def _get_bool_attribute(elem, name, default=False): """! @brief Extract an XML attribute with a boolean value. Supports "true"/"false" or "1"/"0" as the attribute values. Leading and trailing whitespace is stripped, and the comparison is case-insensitive. @param elem ElementTree.Element object...
1f99aa8b1c2c52cd9701f1ea4deb68e1fb7a36a7
628,406
def _create_device(): """Create an empty device property dictionary. """ props = dict() props["PETAL"] = -1 props["DEVICE"] = -1 props["PETAL_ID"] = -1 props["DEVICE_ID"] = "NONE" props["DEVICE_TYPE"] = "NONE" props["CABLE"] = -1 props["CONDUIT"] = "NA" props["FWHM"] = 0.0 ...
6f6fac84614074476abfa5a93470d01307c14199
628,407
def ConsensusMotif(sequence_set): """Find the consensus motif for the input sequence set.""" k = len(sequence_set[0]) matrix = [[0] * k for i in range(4)] # Initiate a zero-filled nested list. for col, colbases in enumerate(zip(*sequence_set)): for row, letter in enumerate('ACGT'): ...
4d0dc206ddad3dd3b701e332f9f7bad3fe1975a2
628,408
import logging def cartesian_goals(x, y): """ Use a cartesian coordinate system to calculate goals from given X and Y values. :param x: x cartesian coordinate :param y: y cartesian coordinate :return: cartesian derived base, fibia, and tibia servo goal values """ # Convert 2D X and Y ...
9bb73b628967ab171d654f4d6e50d6055e8b6023
628,409
def has_overlap2(label1,label2): """ Returns TRUE if the two labels overlap Otherwise returns FALSE """ label1,label2 = label1.lower(),label2.lower() labeloverlaps = {"pron-subj":{'pron-obj': '1', 'copula': '2', 'present_marker_deletion': '4', 'lexical': '6', 'dem_pro': '9', 'gender': '14', 'mar...
45e183a8636db73312b6b0c4f94c6f8a478e357c
628,410
import pathlib def _get_artefacts_count_of_bootstrap_nodes(_: pathlib.Path) -> int: """Returns number of network bootstrap nodes. """ return 3
7c03491c47161fc65474bc39a59e3a8b6ecf34f2
628,411