content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def list_files(dir_path): """List all sub-files in given dir_path.""" return [ os.path.join(root, f) for root, _, files in os.walk(dir_path) for f in files ]
9e9e86ce8f2665e09c2b8719cd9a0fa7ce8ee40d
691,731
import zipfile def extract_requirements_from_zip(sdist_filename): """Extract a file named **/*.egg-info/requires.txt in a .zip sdist. Returns bytes or None. """ with zipfile.ZipFile(sdist_filename, 'r') as f: for name in f.namelist(): if name.endswith('.egg-info/requires.txt'): ...
f8d9f3d8ba4fca8fa904022a6713c36038bfca86
691,732
def root(): """Root Route""" return 'Recipes Analyzer'
434b5e5f683efb57c6ac2e70f329463d84918e09
691,733
def _find_gaps_split(datagap_times: list, existing_gap_times: list): """ helper for compare_and_find_gaps. A function to use in a loop to continue splitting gaps until they no longer include any existing gaps datagap_times = [[0,5], [30,40], [70, 82], [90,100]] existing_gap_times = [[10,15], [35,...
af1aaafa27725a033f9d34ff6f10c4288c9f96d9
691,734
def MRR(predictions, target): """ Compute mean reciprocal rank. :param predictions: 2d list [batch_size x num_candidate_paragraphs] :param target: 2d list [batch_size x num_candidate_paragraphs] :return: mean reciprocal rank [a float value] """ assert predictions.shape == target.shape as...
34b156fc3a38f23b6ad3ffae589c9afc773ec1ab
691,736
def isIn(obj, objs): """ Checks if the object is in the list of objects safely. """ for o in objs: if o is obj: return True try: if o == obj: return True except Exception: pass return False
0b19e6ac4d2ac2b290b0fe62bfd862c870708eac
691,737
def sem_of_rule(rule): """ Given a grammatical rule, this function returns the semantic part of it. """ return rule[1][1]
9746ad4c83e681f55c1497ea514637c293074b27
691,740
def htk_to_ms(htk_time): """ Convert time in HTK (100 ns) units to 5 ms """ if type(htk_time)==type("string"): htk_time = float(htk_time) return htk_time / 50000.0
5e177e8e5644e4171296826bc62b71f9803889a3
691,741
def find_diff_of_numbers(stat1, stat2): """ Finds the difference between two stats. If there is no difference, returns "unchanged". For ints/floats, returns stat1 - stat2. :param stat1: the first statistical input :type stat1: Union[int, float] :param stat2: the second statistical input :ty...
b316c702e2a5d63a6dad4beac1dd59939a544aca
691,742
def set_column_constant_lists(): """ Return column lists so they only need to be calculated once """ feature_bases = ["goals", "shots", "shotsOnTarget", "corners", "fouls", "yellowCards", "redCards"] home_columns = [] away_columns = [] for for_against in ["for", "against"]: ...
17a386e62648ebbcc05c39c8055f39858e84f1e9
691,743
import struct import array import functools import operator import numpy def parse_idx(fd): """Parse an IDX file, and return it as a numpy array. https://github.com/datapythonista/mnist/blob/master/mnist/__init__.py Creadit: @datapythonista, Marc Garcia Parameters ---------- fd : file ...
f1f3e4805c495c72a443b76e4f983898be420522
691,744
def pylong_join(count, digits_ptr='digits', join_type='unsigned long'): """ Generate an unrolled shift-then-or loop over the first 'count' digits. Assumes that they fit into 'join_type'. (((d[2] << n) | d[1]) << n) | d[0] """ return ('(' * (count * 2) + "(%s)" % join_type + ' | '.join( ...
b3cda375fc2fbc922fcb7ecb7a4faa7bc581f7d8
691,745
def wc(iterable): """ wc(iter: iterable) return size of "iter" args: iter = [[1,2], [2,3], [3,4]] iter = {} return: 3 0 """ i = 0 for x in iterable: i += 1 return i
165a95a2ea693e5902a4a4e5651228a86f24b17b
691,746
import argparse def parse_args(): """Parse command line arguments. """ a_p = argparse.ArgumentParser() a_p.add_argument('--ca_etcd', default="/EII/Certificates/rootca/cacert.pem", help='ca Certificate') a_p.add_argument('--etcd_root_cert', ...
d2cc9cedc9ed0d007c79ee515a7e0a6216c7c874
691,747
def two_sum2(nums, target): """通过hash,把遍历过的数据存在字典中,对比时从字典取值 :param nums 被查找的列表 :type nums: list [int] :param target 要找到的目标数字 :type target: int :rtype: List[int] :return 两个数字的下标列表 """ hash_data = {} for val in nums: interval = target - val index = nums.index(val...
0b11c34f20ab498c186f333c32701abe72810a78
691,749
import hashlib def hexdigest(s): """ Returns the sha256 hexdigest of a string after encoding. """ return hashlib.sha256(s.encode("utf-8")).hexdigest()
b4ded415c5e7bdf970d51c5973ea9b658ef70fe0
691,750
def factor_first_event(match_info, event_list, team_key): """ Creates factor for an event in event_list Arguments: event_list: list of 'Event' objects team_key: string of the event type in the 'Team' object, e.g. 'firstTower' Returns: -1 if no event did not happen yet 0 if red ...
0691915ddc4fd81775068fa6a1fcda341cbedc3d
691,753
def get_env_vars_snippet(env_vars): """Generates a Lambda CloudFormation snippet for the environment variables.""" snippet = "" if env_vars: snippet = \ """ Environment: Variables: """ for key, value in env_vars.iteritems(): snippet += '{}{}: "{}"\n'.format(" " * 1...
0a9d86a99e672926b19b9c2284df2b8e8ef1c177
691,754
def find_closest_pair(points): """Returns a list of Point objects that are closest together in the input list of Point objects.""" min_dist = -1 pair = [] for i in range(len(points)): for j in range(i+1, len(points)): p1 = points[i] p2 = points[j] ...
fbb254fa12b0067bfc87a4abf64cf9be67de4c4a
691,755
import re def str2num(s, tfunc=None): """Extracts numbers in a string. Parameters ---------- s : str The string. tfunc : None, optional formating function. Returns ------- list The number list. """ numstr = re.findall(r'-?\d+\.?\d*e*E?-?\d*', s) if...
aa735e99251ee681fd4eb94d160a5eaac13648e1
691,756
def escape_like(string, escape_char="\\"): """ Escape the string paremeter used in SQL LIKE expressions. :: from sqlalchemy_utils import escape_like query = session.query(User).filter( User.name.ilike(escape_like('John')) ) :param string: a string to escape ...
df8f805e50c5569910ad32b909db9a7db4b25b53
691,757
def create_bus(net, level, name, zone=None): """ Create a bus on a given network :param net: the given network :param level: nominal pressure level of the bus :param name: name of the bus :param zone: zone of the bus (default: None) :return: name of the bus """ try: assert l...
920aab5009c387b53c92dbd8af64a8122abe18b3
691,758
def u2q(u1, u2, warnings=True): """ Convert the linear and quadratic terms of the quadratic limb-darkening parameterization -- called `u_1` and `u_2` in Kipping 2013 or `a` and `b` in Claret et al. 2013 -- and convert them to `q_1` and `q_2` as described in Kipping 2013: http://adsabs.harvard.e...
baa934c792be8e0b72a9ede9a1431f356f9496fa
691,759
def lm1b(): """Sets up diffusion to run with LM1B.""" return { 'run_experiment.dataset_name': 'lm1b', 'datasets.load.max_length': 128, 'datasets.load.pack': True, 'discrete_diffusion_loss_fn.mask_padding': False, 'discrete_diffusion_loss_fn.normalize_without_padding': False, 'dis...
8295280d4d67caec2cb23859c648a6036b8abbd2
691,760
def fixture_region(): """ Load the grid data from the sample earth_relief file. """ return [-52, -48, -22, -18]
00bbd32e6841c7f3fc7f991f83852619cb4b2ccb
691,761
from typing import OrderedDict def gen_trialList(*args): """Converts arbitrary number of lists into trialList datatype. trialList datatype is used to create TrialHandler. Args: (2-tuple): First value should be a list of objects (any type) used in trial. Second argument should be a string...
ca4e4716b9688aa2513cc0d32162f013eb898f2f
691,762
def find_room_type(room_id, graph, namespace): """ returns the roomType of a edge in AgraphML """ for room in graph.findall(namespace + 'node'): if room_id == room.get('id'): data = room.findall(namespace + 'data') for d in data: if d.get('key') == 'roomTy...
d0c11eb674957d0671c7b8ebdea7b845e2594062
691,763
def divide(x, y): """Divide 2 numbers""" return (x / y)
a46d9906da6f9c028ea3f3cb1db67c64775d0d07
691,765
import os def get_hip_file_path(filepath, hipify_caffe2): """ Returns the new name of the hipified file """ if not hipify_caffe2: return filepath dirpath, filename = os.path.split(filepath) filename_without_ext, ext = os.path.splitext(filename) if 'gpu' in filename_without_ext: f...
cdd3748a688338d668ab934823dedd6e8eb76a2c
691,766
def get_indexed_attestation_participants(spec, indexed_att): """ Wrapper around index-attestation to return the list of participant indices, regardless of spec phase. """ return list(indexed_att.attesting_indices)
5b37fe2628ec906879905da2ff9e433ac4bc16d3
691,768
def nths(x, n): """ Given a list of sequences, returns a list of all the Nth elements of all the contained sequences """ return [l[n] for l in x]
d37cf578d9fa7d1bdbabe951574b30ea2bb608eb
691,769
def fix_queryselector(elems): """Workaround for web components breaking querySelector.""" selectors = '").shadowRoot.querySelector("'.join(elems) return 'return document.querySelector("' + selectors + '")'
a742afcff9f8dc7e972ede32bb3b712b020a9ed7
691,770
def if_index(ifname): """ Return the interface index for *ifname* is present in the system :param str ifname: name of the network interface :returns: index of the interface, or None if not present """ try: with open("/sys/class/net/" + ifname + "/ifindex") as f: index = f.re...
824c8cdf01422c0b4c209833107fdad4b7fd2fc3
691,771
def build_keys_json_object(keys, blob_name, anchor_key, ground_truth_value, extracted_value, confidence, issuer_name, actual_accuracy, extracted_page_number): """ This function build the json object for the auto-labelling :param keys: The json object ...
d5821d22a13a0c7f55eb9c1b2b438e31e34c8836
691,772
def all_target_and_background_names(experiment_proto): """Determine names of all molecules for which to calculate affinities. Args: experiment_proto: selection_pb2.Experiment describing the experiment. Returns: List of strings giving names of target molecules followed by background molecules. """ ...
90d701e1da0ee26b27e8fa9ac178131199d4c8ea
691,773
def get_cleaned_field_name(field_name): """returns cleared field name for flat database""" ret_val = None for i in range(len(field_name)): if field_name[i].isalpha(): ret_val = field_name[i:] break return ret_val
be1619eb44ad44a7c2409da516d946d3c99eabbd
691,774
import random def generate_name(start, markov_chain, max_words=2): """Generate a new town name, given a start syllable and a Markov chain. This function takes a single start syllable or a list of start syllables, one of which is then chosen randomly, and a corresponding Markov chain to generate a new...
dd40e0ad715bf8957d9bfcfc701997883766f7ca
691,775
def process_wildcard(composition): """ Processes element with a wildcard ``?`` weight fraction and returns composition balanced to 1.0. """ composition2 = composition.copy() wildcard_zs = set() total_wf = 0.0 for z, wf in composition.items(): if wf == "?": wildcard_...
b2ab51b96c24fa80301a401bab5111ecfb77b4d0
691,776
def np_slice(matrix, axes={}): """ Slices a matrix along a specific axes Returns the new matrix """ return matrix[-3:, -3:]
c962db7a18e35056d61bf74c9f6dfc44161fc961
691,777
def sunion_empty(ls): """ return empty set if the list of sets (ls) is empty""" try: return set.union(*ls) except TypeError: return set()
4988820c60c6fa7bdb631bbe09d73f21a79dda9d
691,778
def tidyTermList(terms): """ Does a little bit of extra tidying to a term list Args: terms (list of strings): List of strings of terms Returns: list of augmente strings """ # Lower case everything (if not already done anyway) terms = [ t.lower().strip() for t in terms ] # Remove short terms terms ...
cca3b4eb6d8a85064adeedc9e344dcd027b9dcbc
691,779
import re def find_isomorphs(glycan): """returns a set of isomorphic glycans by swapping branches etc.\n | Arguments: | :- | glycan (string): glycan in IUPAC-condensed format\n | Returns: | :- | Returns list of unique glycan notations (strings) for a glycan in IUPAC-condensed """ out_list = [glycan]...
770fe861318658348fa2607b7dda97847b664e5f
691,780
def clean_invalid_data(df): """Removes those samples in the dataframe where current and next day cases are 0 """ # Removing samples with 0 cases in previous day mask = df["Cases"]!=0 df = df.loc[mask] # Removing samples with 0 cases next day mask = df["NextDay"]!=0 df = df.loc[mask] # Removing ...
3fb005e77569507afa47c5e40088dc9a90e74913
691,781
import re def first_item_grabber(the_str: str, re_separator_ptn=";|\-|&#8211;|,|\|", def_return=None): """ From a string containing more than one item separated by separators, grab the first. >>> first_item_grabber("1987, A1899") '1987' >>> first_item_grabber("1987;A1899") '1987' >>> fi...
1b332b28eed5043d0890e862fad884ab72bdf8c7
691,782
import os def replace_py_ipynb(fname): """Replace .py extension in filename by .ipynb""" fname_prefix, extension = os.path.splitext(fname) allowed_extension='.py' if extension != allowed_extension: raise ValueError( "Unrecognized file extension, expected %s, got %s" % (allowed_ext...
ec53ef420f2dfaa6721ba50fa72707821166e755
691,783
def getid(dev): """ Gets the id of a device. @return: id """ buf = bytes([0x00, 0x00, 0x00, 0x00, 0x00]); id = dev.ctrl_transfer(0xa1, 0x01, 0x0301, 0, buf, 500) if (len(id) == 0): return None ret = '' sep = '' for x in id: ret += sep ret += format(x, '02x') sep = ':' return ret
e3489362c4baf95e7521252b84107fafadcf5287
691,784
def get_word(word_type): """Get a word from a user and return that word.""" if word_type == 'adjetive': is_a_an = 'an' else: is_a_an = 'a' return input("Enter a word that is {0} {1}: ".format(is_a_an, word_type))
a4673bcd84b05a36ef69baecaa12f6eb0979c7a8
691,785
def xlsxExportAdd_tAB(Sheet,Data,rowoffset,coloffset,IName,UName,RName,FName,REName,ALabels,BLabels): """ This function exports a 3D array with aspects time, A, and B to a given excel sheet. Same as ExcelExportAdd_tAB but this function is for xlsx files with openpyxl. The t dimension is exported in one ...
9df8d34ff24c07ceac5ca97d07001b02e6562bf4
691,786
import argparse def parser_params(): """Parse command line parameters including the config path and number of workers. """ parser = argparse.ArgumentParser( description= 'Code to convert single-scale (or a set of multi-scale) meshes to the neuroglancer multi-resolution mesh format' ) ...
860ab112abf3cdca1939ca1a3005accce9001e9a
691,787
def exact_change_dynamic(amount,coins): """ counts[x] counts the number of ways an amount of x can be made in exact change out of a subset of coins given in the list of denominations 'coins'. Initially there are no possibilities, if no coins are allowed >>> exact_change_dynamic(20,[50,20,10,5,2,1]) ...
4a41b270451427a055a54afe346d7df8aa1874c9
691,788
def rubicon_and_project_client_with_experiments(rubicon_and_project_client): """Setup an instance of rubicon configured to log to memory with a default project with experiments and clean it up afterwards. Expose both the rubicon instance and the project. """ rubicon, project = rubicon_and_project_cl...
bb35e31554d019ccf07131078736757c642354ab
691,790
def consoO(R,s,tau,w): """Compute the consumption of the old agents Args: R (float): gross return on saving s (float): savings tau (float): percentage of contribution of the wage of the young agent w (float): wage Returns: (float...
522b6b51b50db29b60a5adc473d6cd9cc04a6a3a
691,791
def to_upper_camelcase(lower_underscore: str): """Convert underscore naming to upper camelcase. Example: rock_type --> RockType """ splits = lower_underscore.split("_") splits = [split.capitalize() for split in splits] return "".join(splits)
a0973c5b2c71e0df622cd6adc516459bf7896ea6
691,792
def normalize(tensor, mean, std): """Normalize a ``torch.tensor`` Args: tensor (torch.tensor): tensor to be normalized. mean: (list): the mean of BGR std: (list): the std of BGR Returns: Tensor: Normalized tensor. """ for t, m, s in zip(tensor, mean, std): ...
2dea96d14fd52898bd967725d8805d1ab10ea7cd
691,793
def _read_band_number(file_path): """ :type file_path: Path :return: >>> _read_band_number(Path('reflectance_brdf_2.tif')) '2' >>> _read_band_number(Path('reflectance_terrain_7.tif')) '7' >>> p = Path('/tmp/something/LS8_OLITIRS_NBAR_P54_GALPGS01-002_112_079_20140126_B4.tif') >>> _re...
e02594f32d87260231951df94bbe8e3d704ddc6b
691,794
def category_sort_key(category): """ Sort key for sorting categories. Parameters ---------- category : ``Category`` A command processor's category. Returns ------- sort_key : `str` The categories are sorted based on their display name. """ return categor...
5fe5c32a0cebc1155edcf8674acb438e9352a5fc
691,795
def min_max(x,axis=None): """ return min_max standalization x = (x-x.min)/(x.max-x.min) min=0 max=1 Parameters ------------------- x : numpy.ndarray(x,y) axis :int 0 #caliculate each col 1 # each row Returns -------------------- result : np.nd...
a7a31bfdda1d6a21a8ee0fbe5148d6cdd53aa60b
691,796
def strength_of_measurement(current, total): """ :param current: int() checked objects for new optimization procedure :param total: int() total objects available in doc (this is approximation) :return: int() """ return (current * 100) / total
a1033f14ea0335df887b657aefd670f32d055ad7
691,798
from pathlib import Path def os_release(): """Return a dict containing a normalized version of /etc/os-release.""" lines = Path('/etc/os-release').read_text().strip().split('\n') os_info = dict([x.split('=', 1) for x in lines]) for k in os_info.keys(): if os_info[k].startswith('"') and os_info...
727fe8df47bc2fb492d51b7dced44760149e62bc
691,799
def calc_fitness(fit_form, sum_energy, coef_energy, sum_rmsd, coef_rmsd): """Calculate the fitness of a pmem. Parameters ---------- fit_form : int Represents the fitness formula to use. The only value currently available is 0, where fitness = CE*SE + Crmsd*Srmsd. sum_energy ...
7ac64e72dbbdf6caacad73f99061408d12f7df5e
691,800
def encode_sentences(sentences, lexicon_dictionary): """ Change words in sentences into their one-hot index. :param sentences: A list of sentences where all words are in lexicon_dictionary :param lexicon_dictionary: A dictionary including all the words in the dataset sentences are being drawn...
69af36f02b2b66198f54803072a340c93aaeb31f
691,802
def trim_method_name(full_name): """ Extract method/function name from its full name, e.g., RpcResponseResolver.resolveResponseObject -> resolveResponseObject Args: full_name (str): Full name Returns: str: Method/Function name """ point_pos = full_name.rfind('.') if po...
4783d19103822d68dfbc2c28a7d59acd041216f6
691,803
def permission_denied_page(error): """Show a personalized error message.""" return "Not Permitted", 403
b7009dc1a45f523f23082f6070bdef0a2bc6a353
691,804
def prepare_df_annoVar(df): """Prepare internal dataframe as input to ANNOVAR. Generates a list of all the column names, adding a repeat of position to give start and end, as required by ANNOVAR input format, then reorders the columns to ensure the first 5 are those required by ANNOVAR (chromosome, s...
21cf6cc2e884f5351b99ed7e5c6f2942dde6ad0d
691,805
def check_length(line, min=0, max=0): """Does a length check on the line Params: line (unicode) min (int) max (int) Returns true if length is ok """ status = True if min and status: status = len(line) >= min if max and status: status = len(lin...
c0e4b79dc1caeaa94c2af7741f6a7113c0384abf
691,806
from typing import Union import pathlib def supplement_file_name(file: Union[str, pathlib.Path], sup: str) -> pathlib.Path: """ Adds a string between the file name in a path and the suffix. **Parameters** - `file` : str File name - `sup` : str String to be added **Returns...
1cba9e55939a9c474d9d1a8fffda1023953a457d
691,807
import re def _translate_trace_all(program): """ Replaces the 'label_atoms' magic comments in the given program for label_atoms rule. @param str program: the program that is intended to be modified @return str: """ for hit in re.findall("(%!trace \{(.*)\} (\-?[_a-z][_a-zA-Z]*(?:\((?:[\-\+a-zA-...
aaba6f875f4424ebba1a0b82355a428949d3bd17
691,808
import traceback def report_error(exception): """ Simple error report function :param exception: :return: """ message = f"ERROR: {exception} {traceback.format_exc()}" error = { "isError": True, "type": "Unhandled Exception", "message": message } return erro...
0a03a4fa0a3c195a6b5f071d44552258a70c098e
691,809
def split_xyz(xyz_file: bytes) -> list[bytes]: """Split an xyz file into individual conformers.""" lines = xyz_file.splitlines() structures = [] while True: if len(lines) == 0: break # removed one deck natoms = lines.pop(0) n = int(natoms.decode()) co...
4857fc838f4490526eb9fee4f71318b8ab7c06fe
691,810
def results_to_dict(results): """convert result arrays into dict used by json files""" # video ids and allocate the dict vidxs = sorted(list(set(results['video-id']))) results_dict = {} for vidx in vidxs: results_dict[vidx] = [] # fill in the dict for vidx, start, end, label, score ...
ab42de303a1d039c5605b7828d624234e549d2c0
691,811
def left_justify(words, width): """Given an iterable of words, return a string consisting of the words left-justified in a line of the given width. >>> left_justify(["hello", "world"], 16) 'hello world ' """ return ' '.join(words).ljust(width)
26a2e9f3df582355966959996ae672f60b5c00cc
691,812
def check_validity(mol): """ If convertation to rdkit.Mol fails, the molecule is not valid. """ try: mol.to_rdkit() return True except: return False
9f9f059fb91e346f7fef5c4b54b92023a6c4d4e0
691,813
def civic_vid65(): """Create a test fixture for CIViC VID65.""" return { "id": "civic.vid:65", "type": "VariationDescriptor", "label": "D816V", "description": "KIT D816V is a mutation observed in acute myeloid leukemia (AML). This variant has been linked to poorer prognosis and w...
e09f1c4068190744c7620b0679c452a8b428913f
691,814
def str_to_bool(value): """Represents value as boolean. :param value: :rtype: bool """ value = str(value).lower() return value in ('1', 'true', 'yes')
ff0f2107c3c7758769af2809d51859e016bdd15a
691,815
def encode_classes(y_symbols): """ Encode the classes as numbers :param y_symbols: :return: the y vector and the lookup dictionaries """ # We extract the chunk names classes = sorted(list(set(y_symbols))) """ Results in: ['B-ADJP', 'B-ADVP', 'B-CONJP', 'B-INTJ', 'B-LST', 'B-NP', ...
298abb185012216b5f3234e6623c75a46bc7f5ac
691,816
import os import zipfile import io import numpy import pandas def read_zip(zipfilename, zname=None, **kwargs): """ Reads a :epkg:`dataframe` from a :epkg:`zip` file. It can be saved by @see fn read_zip. :param zipfilename: a :epkg:`*py:zipfile:ZipFile` or a filename :param zname: a filename in zi...
c32864ce274cbefb7ddcd2b2de113b4a1c4870af
691,817
from typing import Any def is_property(obj: Any) -> bool: """Check the given `obj` is defined with `@property`. Parameters: - `obj`: The python object to check. Returns: - `True` if defined with `@property`, otherwise `False`. """ return isinstance(obj, property)
22c20ea7050756a4274822b961811154c6b85210
691,818
def _is_in_bounds(x: int, y: int, width: int, height: int) -> bool: """ Returns whether or not a certain index is within bounds. Args: x (int): x pos. y (int): y pos. width (int): max x. height (int): max y. """ if x < 0: return False if y < 0: re...
8fc76261972588599b183364b3b8c350389d33c0
691,819
def collect_steps(cls): """Collect steps defined in methods.""" cls.steps = list() for attr_name in dir(cls): attr = getattr(cls, attr_name) if hasattr(attr, '_decor_data'): cls.steps.append(attr._decor_data) cls.steps = sorted(cls.steps, key=lambda s: s.index) return ...
8aa201bf2bf4633281af2cb1d0e7cc89adf5f525
691,820
def data_to_html(title, data): """Turns a list of lists into an HTML table""" # HTML Headers html_content = """ <html> <head> <style> table { width: 25%; font-family: arial, sans-serif; border-collapse: collapse; } tr:nth-child(odd) { background-color: #dddddd; } td, th { border: 1px solid #ddd...
c1eb000fd5947fbaa74e1876a6a4f839f5ffe8cf
691,821
from pathlib import Path def get_file_extension(path): """Gets the dot-prefixed extension from the path to a file. :param path: Path to the file to get the extension from. :type path: str :return: The file's extension. :rtype: str Examples -------- >>> get_file_extension('/home/user/...
8e6e97b0046edf31febbe0c731877ea8ecc5186a
691,823
def is_after(t1, t2): """True if t1 is after t2 t1, t2: Time objects """ return (t1.hour > t2.hour and t1.minute > t2.minute and t1.second > t2.second)
bec06b864152cd7c6857c6c4460f9e47c8e4dde5
691,825
import os def __get_version_from_version_txt(path): # pragma: no cover """ private function, tries to find a file ``version.txt`` which should contains the version number (if svn is not present) @param path folder to look, it will look to the the path of this file, ...
9de5394f8033d3b63029bcd14bd91f08158cc6fc
691,826
def replace_color(img, color_map): """return a new image replacing the image colors which will be mapped to their corresponding colors in `color_map` (df)""" new_img = img.copy() for _, (source, target) in color_map.iterrows(): new_img[(img == source).all(axis=-1)] = target return new_img
f83ff06ae86f697d3a65b2bfedb265248befb7e5
691,827
def get_e_rtd_default(hs_type): """定格効率(規定値) Args: hs_type(str): 温水暖房用熱源機の種類 Returns: float: 定格効率(規定値) """ if hs_type in ['ガス従来型温水暖房機', 'ガス従来型給湯温水暖房機']: return 0.81 elif hs_type in ['ガス潜熱回収型温水暖房機', 'ガス潜熱回収型給湯温水暖房機']: return 0.87 else: raise ValueError(h...
d43516867d3481c8b648402b2556c5f4898e0c41
691,828
def reversed_arguments(func): """ Return a function with reversed argument order. """ def wrapped(*args): return func(*reversed(args)) return wrapped
bfd818c0a87f169c06331f1db4e8e6e31e5546cd
691,829
from typing import Any def _detokenize_doc(doc: Any) -> str: """ Detokenize a spaCy Doc object back into a string, applying our custom replacements as needed. This requires the associated extension to have been registered appropriately. The :class:`WordNet` constructor should handle registering the ex...
eebd953f0496a3715243f7e91b9fccb12031c450
691,830
def get_priority_value_map(all_priorities): """ Maps an index of increasing size to each priority ranging from low -> high e.g. given ['LOW', 'MEDIUM', 'HIGH'] will return {'LOW': 0, 'MEDIUM': 1, 'HIGH': 2} """ return dict((priority_text.upper(), priority_index) for priority_index, p...
5a3b85f7b6bdd20a3c6cf2cbeac19e9bb3882cf5
691,831
import torch def val_epoch(model, val_loader, criterion, device): """Validate the model for 1 epoch Args: model: nn.Module val_loader: val DataLoader criterion: callable loss function device: torch.device Returns ------- Tuple[Float, Float] average val loss...
80576b4181f08a2a35276a78a143bbf59233dd9c
691,832
def compute_error(b, m, coordinates): """ m is the coefficient and b is the constant for prediction The goal is to find a combination of m and b where the error is as small as possible coordinates are the locations """ totalError = 0 for i in range(0, len(coordinates)): x = coordinat...
c300a137e3fe75ee2c9a23265d1523a96907d7f7
691,833
import torch def _bilinear_interpolation_vectorized( image: torch.Tensor, grid: torch.Tensor ) -> torch.Tensor: """ Bi linearly interpolate the image using the uv positions in the flow-field grid (following the naming conventions for torch.nn.functional.grid_sample). This implementation uses the ...
b9e3596f1e3d98bb598e74cf3f1c142b376b79a9
691,834
def get_ds_data(ds, target_attribute='targets'): """ Returns X and y data from pymvpa dataset """ return ds.samples, ds.sa[target_attribute].value
f96a2bf87b18e53961c9abf99e24c2f22730461b
691,835
def create_db_strs(txt_tuple_iter): """ From an iterable containing DB info for records in DB or 'not in DB' when no records were found, return info formatted as string. :param txt_tuple_iter: an iterable of tuples where the 0 element of the tuple is the gene/name and element...
57d80e04bab4cc00cf5fc297ef70d03aa100f5cd
691,836
def check_bram(test_data,layernumber): """ checks the Parameters ---------- test_data : numpy array [B,W*H,Ci] Data to check. Content of BRAM layernumber : integer Number of layer Returns ------- error_count : interger Number of errors. """ BLOCK_S...
29118648ad61642e55bc0b6849470b770c2ce741
691,837
def isfloat(x, num_only=False): """Returns true if the input is a float, false otherwise.""" return type(x) == float
a92681e497574bbcb02907ac94240ed47088973c
691,838
def getFrameLevelDisplacements(nodeFound, start, finish): """ Iterates through the entire time-series data for a given body part to extract the X,Y,Z coordinate data. Args: nodeFound (object): joint object for the targeted body part start (int): starting frame number finish (int): ending fram...
7c05dcc901d8a0525e4983ce2301a4d40ef2a542
691,839
from datetime import datetime def get_datetime_object(datetime_string): """ Interpret the UltraSuite prompt date and time string as a python datetime object :param datetime_string: :return: """ return datetime.strptime(datetime_string, '%d/%m/%Y %H:%M:%S')
35fe2c9056f28d3d8dbe963121cd8ce93e36550f
691,840
def GetDuplicateRefcodes(sDuplicateRefcodeFileName): """Load duplicate refcodes. """ with open(sDuplicateRefcodeFileName,"r") as fDupl: lsDuplRefcodes= fDupl.read().strip().split() dtDuplicateRefcodes={} for sRefcode in lsDuplRefcodes: dtDuplicateRefcodes[sRefcode]=1 return dtDuplicateRefcodes
f1ac1cf95954f4923dcdff43bc43dfe80ff9e6ed
691,841
import operator def get_best_individual_in_population(number_of_individual_to_keep, grades, population): """ -> return the bests individual in populations -> number_of_individual_to_keep is the number of bests candidate to retrieve -> grades is a tuple, generated by grade_population() function -> population is a...
b498e1b0660995e51cd975c0653ab84df7a44642
691,843
def reward_val(upn2, upn1, ufn2, ufn1, jain, param, uav_r, uav_f, list_up, list_uf, list_sum): """ This function calculates the reward function based on the current and previous throughput values from both the primary and the fusion(emergency) networks. :param upn2: The current-state throughput value fo...
f34a3b6d08fc131b9c9197e20c4b0b57a56c5377
691,844