content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def colored_div(*spans, color=''): """Produce an HTML div box with color.""" spans = '<br>'.join(str(item) for item in spans) div = ( f'<div style="background:{color}; display:inline-block">' + spans + '</div>' ) return div
2ccd4ccb4cde9802b910b3d011fdf2660df408b3
587,783
def is_integer(s): """ Simply check whether or not a given input is a string or an integer Args: s (str): A string. Returns: (bool): True if the string can be cast as an int. False if the string can not be cast as an int (it is actually not an int). """ try: int...
7bea33e05bc442b1deb558127c3255b34e969120
587,785
def color_stats(lab_image, mask=None): """Get color stats of a L*a*b* image (mean, std-dev)""" if mask is None: # Image is always in 1 dimension to make it simpler lab_image = lab_image.reshape(-1, lab_image.shape[-1]) else: lab_image = lab_image[mask.nonzero()] return lab_image....
6feecec73e6f16c630bf7a492e37e676734df9eb
587,786
def calendar_date(jd_integer): """Convert Julian Day `jd_integer` into a Gregorian (year, month, day).""" k = jd_integer + 68569 n = 4 * k // 146097 k = k - (146097 * n + 3) // 4 m = 4000 * (k + 1) // 1461001 k = k - 1461 * m // 4 + 31 month = 80 * k // 2447 day = k - 2447 * month // 8...
7993d94244cd064ff62b6880068383218e5883f3
587,787
from functools import reduce def mreplace(content, replacements): """Performs multiple string replacements on content Args: content (str): the content to perform replacements on replacements (Iter[tuple(str)]): An iterable of `old`, `new` pairs Returns: (str): the replaced conten...
49a069dbfdb48fc24d1744c87642f6e7be6774d7
587,789
def justify_center(content: str, width: int, symbol: str): """Centers string in symbol - width chars wide. :param content (str) : String to be centered. :param width (int) : Column width to center within. :param symbol (str) : Symbol to fill the space. :return (str) : Content, centered. """...
1d51367290e5159f569df55374fa02822074f8d3
587,790
def calculate_p0(pressure: float, elevation: float) -> float: """ Calculate P0 from pressure and desired elevation Args: pressure: The pressure at this elevation elevation: The desired elevation Returns: The calibrated P0 """ p0: float = pressure / ((1 - elevation / 0.3048 / ...
cb3bd3266aa0a291e8ef87bb560b44efa9c672b4
587,792
def readline_clean(fp): """ reads a line, striping off the comments and whitespace """ return fp.readline().strip().split('//')[0].strip()
5d168bae0b28ae71aa55fe7b57196848749c710b
587,795
import string def remove_punctuation( text ): """ removes punctuation from a string """ return text.translate(str.maketrans({key: None for key in string.punctuation}))
b576d0b89e9c6a264275978922e61a11d4effa3d
587,796
def get_ivar(data, s): """Return a copy of the inverse variance array with jitter included. This is safe for zero'd out inverse variances. Parameters ---------- data : `~thejoker.data.RVData` s : numeric Jitter in the same units as the RV data. """ return data.ivar.value / (1 ...
49578e649578f266c651cc7879ea3f6ba128f07e
587,801
from io import StringIO def safe_format(format, dictionary, types={int, str, float}, adapt=None, raise_on_missing=False): """ Takes a user-supplied string with format blocks and returns a string where those blocks are replaced by values in a dictionary. For example:: >>> safe_for...
c7ff3288e5c2222311001668663b6bddb89a574f
587,805
def get_user_identity(event: dict) -> str: """ Get user identity from CloudTrail event. """ if 'arn' not in event['userIdentity'].keys(): return "Unknown" return event['userIdentity']['arn'].split(':')[-1]
b9418ddb4616b5062bf0dd2c3df75906e478e55b
587,810
def get_tool_shed_repository_by_id(app, repository_id): """Return a tool shed repository database record defined by the id.""" # This method is used only in Galaxy, not the tool shed. return app.install_model.context.query(app.install_model.ToolShedRepository) \ .filter(a...
30c51fac012300532f890d5d7827a8282a8e12bf
587,819
from typing import Tuple from typing import List import csv def get_dataset_entries(path_to_dataset_csv: str) -> Tuple[List, List]: """Parse and return the header and rows of the dataset csv.""" with open(path_to_dataset_csv, 'r') as file: content = file.read() csv_data = csv.reader(content.sp...
5e7c9b3196b5588dc7387305c5e637ba6fb3b8e3
587,822
from typing import List import re def format_corpus_sents(sentence: List[str]) -> List[str]: """ Reformats spaces in contracted words. Contracted words in <class 'nltk.corpus.reader.bnc.BNCSentence'> are formatted "it 's" and "ca n't". Removes all punctuation except apostrophies, and removes the empt...
0426f82602b701e6942843d06328bbdfcf3af89a
587,824
def is_it_5(chromosome): """A very simple case test function - If the chromosomes gene value is a 5 add one to the chromosomes overall fitness value.""" # Overall fitness value fitness = 0 # For each gene in the chromosome for gene in chromosome.gene_list: # ...
c3aed24b85cb31c834e3d4d722da44e970ea659b
587,826
def get_pbf_url(region, subregion): """Returns the URL to the PBF for the region / subregion. Parameters ---------------------- region : str subregion : str Returns ---------------------- pbf_url : str """ base_url = 'https://download.geofabrik.de' if subregion is None: ...
8f65290efc0fc36eea732d2865b14c63fdfac503
587,828
from pathlib import Path import pkgutil def all_modules(modules_to_ignore=None): """Get a list of all modules from toy_pkg.""" if modules_to_ignore is None: modules_to_ignore = { "tests", } all_modules = [] root = str(Path(__file__).parent.parent) for importer, modname,...
d7800645a7df9e4a58138c405825c00722f555a0
587,829
def update_results(results, add): """Given a map of results for all ontologies and a map of results to add, append the results to the lists in the map.""" results["error"] = results["error"] + add["error"] results["warn"] = results["warn"] + add["warn"] results["info"] = results["info"] + add["info"...
0e303ca71f83838cd6e7384cbb38190db99dfc0b
587,830
def getCase(grid, x, y): """Retourne la case de la grille aux coordonnées (x, y)""" return grid[y][x]
a23f93e4ee31905f6b92af1b74d0ed6a6ca612ef
587,833
def function_to_vector(function, model): """Assigns a vector to a function. Args: function (str): the function name. model (dict): A mapping that words as follows: model[function] == vector Returns: vector: A numpy array, or None if the function was not found in the ...
a3e8377edf2ba463ad8759f73ca3be94900b7f3e
587,836
def scale(x, space): """ Scale some input to be between the range [-1;1] from the range of the space it belongs to """ return 2.0 * (x - space.low) / (space.high - space.low) - 1.0
98d588e3adf927317e3f7984ef1a84dad45a6884
587,838
def roi_pad(roi, pad, shape): """ Pad ROI on each side, with clamping. Returned ROI is guarnteed to be within ``(0,..) -> shape``. """ def pad_slice(s, n): return slice(max(0, s.start - pad), min(n, s.stop + pad)) if isinstance(roi, slice): return pad_slice(roi, shape) re...
4f6852cbc2aa00d17dba219890c58e64b6d7fba2
587,840
def convertb2access(ui): """function to convert user information returned by b2access service returns this format: e.g.:{'name':'John Smith','id': '12345', 'email': 'js@example.com','provider':'b2access'} """ myui = {'name':ui['name'],'id':ui['sub'],'email':ui['email'],'provider':'b2access'} re...
7ba6b35ebf6a448f24aceaf8bfcf2080381f62f1
587,843
import json def is_json(json_str: str) -> bool: """ Check whether the input string is a valid JSON """ try: json.loads(json_str) except ValueError: return False return True
a681ab33c1d6c4146add00dbce90cb140e5ec30a
587,850
def _update_other_results(results, best): """Update the positions and provisional input_sets of ``results`` based on performing the contraction result ``best``. Remove any involving the tensors contracted. Parameters ---------- results : List of contraction results produced by ``_parse_...
d6beeae8734d886e817668abb51b776333ebf2d2
587,852
import re def regex(x): """ Returns x as a compiled regular expression """ if isinstance(x, str): return re.compile(x) return x
ac06a5b9f302917b27862c8db35f3f158c45cf01
587,857
def bin_to_gray(bin_list): """ Convert from binary coding to gray coding. We assume big endian encoding. Examples ======== >>> bin_to_gray('111') '100' See Also ======== gray_to_bin """ b = [bin_list[0]] for i in range(len(bin_list) - 1): b += str(int(bin...
7ad89f7f58db25ac44420b8d8e9539cce2752ef9
587,858
def my_triangle(my_a, my_b): """Calculates the area of a right triangle given the length of the two shorter sides of the triangle. Keyword arguments: my_a (float) -- Length of side a. my_b (float) -- Length of side b. Returns: Float -- Area of the triangle. """ return ...
fe60d9f1b6f7d19ca7562948172c54b32b48b31d
587,866
def format_bi(op): """Format an op dictionary into a .BI line for troff""" line = '.BI ' if op['short_op'] is not None: line += '-' + op['short_op'] + '/' line += '--' + op['long_op'] if op['has_arg'] != 'NULL': if op['has_arg'] == 'no_argument': markers = ['', ''] ...
cca7e665be0aed24f9fc5b96b0c50f18989a0f1a
587,867
def mult(arg1, arg2): """ Function for multiplying two variables """ return arg1 * arg2
5e51462e1df6e70a4711fa422ea43091fcb2a629
587,870
def get_attribute_name(node_and_attribute): """ For a string node.attribute, return the attribute portion """ split = node_and_attribute.split('.') attribute = '' if split and len(split) > 1: attribute = '.'.join(split[1:]) return attribute
a23e515c63e1c3e2d6843b8efe8088092bd783d0
587,877
def clean_strains_with_bad_dates(ird_df): """ Removes strains that have bad dates (i.e. only MM-YYYY or YYYY). """ ird_df['date_length'] = ird_df['Collection Date'].str.split('/').str.len() ird_df = ird_df[ird_df['date_length'] == 3] return ird_df
9cda8c0d50cff313614170035f8fdf2c88cd7ce9
587,879
def deal_hands(deck): """Deal the cards in the deck into four hands""" return (deck[0::4], deck[1::4], deck[2::4], deck[3::4])
f3933c5e43b674d9667fe84c4f86803257f44f2c
587,881
import itertools import collections def groupby(objects, key, reducegroup=list): """ :param objects: a sequence of objects with a key value :param key: the key function to extract the key value :param reducegroup: the function to apply to each group :returns: an OrderedDict {key value: map(reduceg...
916091c87bd7afb5f4f173bc911ec9515ac138cf
587,882
def remove_fields(a, names): """ `a` must be a numpy structured array. `names` is the collection of field names to remove. Returns a view of the array `a` (not a copy). """ dt = a.dtype keep_names = [name for name in dt.names if name not in names] return a[keep_names]
e44fe4c3802b75d8c253390774b5ec5c824e937c
587,887
def get_tables_in_schema(public_mode=True): """ List of organization tables that need to be processed. public_mode: Boolean field. If true, it returns tables that contain generic information from `public` schema. If false, it returns tenant specific tables from tenant schema. """ if public_mode: ...
84a9281e38e83ffd584912114c77a564375a6151
587,889
def auth_token(load_auth, auth_creds): """ Mint and return a valid token for auth_creds """ return load_auth.mk_token(auth_creds)
002f3b39e36647ab499382bcbd9c697f008d9e08
587,894
def sanitizeStructTime(struct): """ Convert struct_time tuples with possibly invalid values to valid ones by substituting the closest valid value. """ maxValues = (9999, 12, 31, 23, 59, 59) minValues = (1, 1, 1, 0, 0, 0) newstruct = [] for value, maxValue, minValue in zip(struct[:6], max...
a3bfd23b134ee47e262134efde04a48f71e65fc6
587,896
def dict_factory(colnames, rows): """ Returns each row as a dict. Example:: >>> from cassandra.query import dict_factory >>> session = cluster.connect('mykeyspace') >>> session.row_factory = dict_factory >>> rows = session.execute("SELECT name, age FROM users LIMIT 1") ...
4470b353f5b6f24ce34b317a471b0b3d561bef57
587,899
import re def _extract_by_pattern(pattern, line): """ Simply matches pattern and search by regex in given line. :param pattern: regex pattern to match. :param line: line for matching. :return: matched values. """ try: res = ''.join(re.findall(pattern, line)).strip() except At...
968b6291dd0ec5ac2ed7608aaf6f0383e9e76425
587,900
import six def hex2color(s): """ Take a hex string *s* and return the corresponding rgb 3-tuple Example: #efefef -> (0.93725, 0.93725, 0.93725) """ if not isinstance(s, six.string_types): return s return tuple([int(n, 16) / 255.0 for n in (s[1:3], s[3:5], s[5:7])])
06317a4baede508007dbd4bfcee51caa5e95887b
587,901
import random def sample_cards(size: int) -> list[int]: """Sample random cards with size.""" return random.sample(range(52), k=size)
fa04ab1735d72c57caa6631aa3f2fd5ac13f9e8b
587,904
def find_parentheses(s): """ Find and return the location of the matching parentheses pairs in s. Given a string, s, return a dictionary of start: end pairs giving the indexes of the matching parentheses in s. Suitable exceptions are raised if s contains unbalanced parentheses. """ # The index...
66567de4764758ce9ced5b8225c3f1ddf854ca58
587,905
def stationlist2filelist(slo): """ Input a stationlist object (slo). From this extract the station codes and create a list of file names that represent long period data files """ site_list = slo.getStationList() files = [] for sta in site_list: fname = "%s" % (sta.scode) file...
10a290ad52dab7fb561ce0c1b87dec9fe5fbd0cf
587,907
def series_to_json_obj(ts): """ Returns a dictionary of values in DeepAR, JSON format. :param ts: A single time series. :return: A dictionary of values with "start" and "target" keys. """ # get start time and target from the time series, ts json_obj = {"start": str(ts.index[0]), "...
4e9adaf243ef36b995afe0d8f8df15602118d912
587,913
def make_data_column_long(data_in, var_name): """ Takes a specfic variable from the raw oTree data and takes the subset of this data for each participant round and super game. """ data_out = data_in.loc[data_in['variable'] == var_name][['participant.code', 'round', 'super_game', 'value']].c...
9a41823746b3efaca8c1179d04103efee8b1043e
587,919
def find_file_name(zipfile): """ Finds file from the zip archive ending with issn-to-issn-l.txt. """ files = zipfile.namelist() select_file = [f for f in files if f.lower().endswith("issn-to-issn-l.txt")] file = select_file[0] if select_file else None return file
09a2c2e0484f72d394888396660ab616d4b57ced
587,923
def parse_works(works_data: list) -> list: """Extract information about works.""" works = [] for work in works_data: works.append({ 'work_id': work.get('workId'), 'title': work.get('title'), 'author': work.get('author'), 'onsale': work.get('onsale'), ...
ce71bcf0d037f2cd599e7e297b40ec5153ef44eb
587,924
def count_params(model): """ Count the number of parameters. :param model: model :return: number of parameters of the model """ return sum(p.numel() for p in model.parameters() if p.requires_grad)
ee9a12fe32ff2e25df93eba32b744e567f9ffa29
587,927
def get_dict_leaves(dictionary): """Get the set of all leaves of a dictionary. Parameters ---------- dictionary : dict A dictionary or nested dictionary. Returns ------- vals : set Set of leaf values. """ vals = [] for k in dictionary: if isinstance(dic...
d013e3395dc35fcfe5a5cf5bcc4ef93e1a7efe91
587,928
def center(string: str, width: int) -> str: """Center the string""" return f"{string:^{width}}"
dc1d3879e9b1f0795470881710622cafb19e795c
587,929
def process_sat_image(sat_image, transform): """ Prepare satellite image to be fed to model. :param sat_image: (np.array) in the format (H, W, C) :param transform: (torchvisions.transform) :return: image (torch.tensor) """ # Images are (H, W, C) as expected by Torch # Normalize image (v...
3d347bf9712bd9b3d109b76bc159f29110d451ec
587,933
def vs_metadata(config): """Load the VS metadata. Implicitly tests that it exists. """ return config["_visual_studio"]
aba2362a981b18a97fd014b9df2ea873940435ec
587,934
def date_index(start_year, date): """Returns the number of months that have passed since January of start_year""" return (date.year - start_year) * 12 + (date.month - 1)
1dafa11fff2e696e0bd293e880df2f02cca38460
587,935
def ensure_directory(file_path): """Checks the given file path for a directory, and creates one if not already present. Args: file_path: a pathlib.Path returns the err message if permission issue, else is None """ if not file_path.exists(): try: file_path.mkdir() except Excep...
384f6f40b3af97b3b00cc5e9957badc24c4396b3
587,936
def build_url(*args): """Build URL by provided parts of url. Also this method strip all right slashes. :param args: Parts of url. :rtype: str """ return "/".join([part.rstrip('/') for part in args])
dbd2df8cc34b34b80563ae9308d1bc24f2c9e78d
587,939
def unquote(str): """Remove quotes from a string.""" if len(str) > 1: if str.startswith('"') and str.endswith('"'): return str[1:-1].replace('\\\\', '\\').replace('\\"', '"') if str.startswith('<') and str.endswith('>'): return str[1:-1] return str
d4242f22d841a83bfdebed75aeff08770156281d
587,943
def slice_adjust_margin(x, maximum, MARGIN): """Return a slice defined by x-MARGIN and x+MARGIN. If x is below 0, it uses 0 instead of x-MARGIN. If x is above maximum, it uses maximum instead of x-MARGIN. Examples: >>> slice_adjust_margin(20, 50, 30) slice(0, 50, None) """ x = ...
bde710b842dffca0b0f387fc9ba28f72e72a80d8
587,951
def method_call_if_def(obj, attr_name, m_name, default, *args, **kwargs): """Calls the provided method if it is defined. Returns default if not defined. """ try: attr = getattr(obj, attr_name) except AttributeError: return default else: return getattr(attr, m_name)(*args...
65131a2333e7b17b6a918ff7433003e91e01d7c8
587,952
import re def fix_columns(dataframe): """ Takes a dataframe and fixes the column names by (1) making all lowercase, (2) removing non-alphanumeric characters, and (3) replacing spaces with an underscore. """ cols = dataframe.columns cols = [col.lower() for col in cols] cols = [re.sub(r'...
3459b31a4541a2cbfbef17a7d38985363a26a60e
587,954
import struct import socket def ipv4_to_network_int(address: str) -> int: """Function to conver an IPv4 address string into network byte order integer Args: address (str): the addess to be converted Returns: int: the big endian representation of the address """ return struct.unpa...
a33319dd5fdc3eadffcf8661a71776264be4ba0f
587,956
def fetch_image_url(item, key="images"): """Fetch image url.""" try: return item.get(key, [])[0].get("url") except IndexError: return None
3d22d4b61bd494ecb6fbdaf868f516749cdacd89
587,958
import re def parse_docstring(docstring, key_symbol="<**>", description_symbol="<++>"): """ Extract from the docstring the keys and description, return it as a dict Parameters ---------- docstring : str key_symbol : str identifies the key of an argument/option description_symbol :...
7b688493442e3e8518cbcc5f4fe1aace3b2be947
587,960
import uuid def gen_cfduid() -> str: """Spoof a Cloudflare uuid""" return str(uuid.uuid4().hex) + str(uuid.uuid4().hex)[0:43]
f9ea76b4a281694cd6a39f1693d9f1cd9d9528f4
587,961
import requests def get_event(id): """Return an event's name, start and end date based on the ID provided.""" event = requests.get('http://api.snooker.org/', params={'e': id}) event = event.json()[0] # the data consists of a single dictionary in a list (same as player's json response) event = { ...
63ef74c29905e2ef593fbbf438b754153ddf8ddc
587,962
def code_mcq(df,col): """ Turns survey response strings into numbers. 'Not sure' or 'Don't know' become 0, 'Yes' becomes 1, and 'No' becomes 2. Arguments: df - chosen dataframe col - name of column in which responses are to be converted Returns: Dataframe with columns in which resp...
ecb70bdaa10ac13f4dca108aa73b5d6a87504cc7
587,967
def terms_from_search_string(search_string): """ Returns a ``(include_terms, exclude_terms)`` tuple, where ``include_terms`` and ``exclude_terms`` are sets of strings. Currently extremely naive; doesn't handle quoted terms. """ terms = set(search_string.split()) exclude_terms = set((term fo...
142d7a1b459c09511f33b9f951831c52b79f8699
587,968
def get_layer_length(layer_index): """ Asks for a given layers length until the input is valid. Preconditions: layer_index: int >= 0 Parameters: layer_index: The index of the given layer whose length we will be obtaining. Postconditions: returns length: The valid inputted layer length. ...
a1895e21224f933e603ae1725a3fc211929081b5
587,969
from typing import List def read_wordlist(fn: str) -> List[str]: """Read a file containing one word per line. Return all words as a list.""" words = list() with open(fn, "r") as file: file_contents = file.read() lines = file_contents.split("\n") for line in lines: ...
09d3a3278c08e8c7fece9daa9f96d65f8421c5be
587,970
def head_file(filename, n=5): """Return the first `n` lines of a file """ with open(filename, 'r') as fd: lines = [] for i, line in enumerate(fd): if i > n: break lines.append(line) return "".join(lines)
4a45aae157fbd5fa2311d78e83793c3085013b94
587,971
def handle_user_event(message, socket): """ Get message about user event `message` to be sent to `socket`. Inspects the embedded user event and decides whether or not the passed socket should receive notification of the event. Returns None if the socket should not receive any message about this us...
0cc2cdb5749c160b349d8723a21837a23fa25296
587,973
def get_maximum_order_with_pairwise(per_layer_orders_and_multiplicities): """ determine what spherical harmonics we need to pre-compute. for pairwise interactions, this will just be twice the maximum order the spherical harmonics function depends on J (irrep order) purely, which is defined by order...
ba3fefd9575903f05772f105e055af6072dd6a52
587,974
import getpass def ask_password(options): """Get the password from stdin.""" password_text = "Password for {} on {}: ".format(options.user, options.server) password = getpass.getpass(password_text) return password
33ca3beb9b5ae672737d456f43ccc5e5ca7c8434
587,975
def position_converter(position): """Converts a player's `element_type` to their actual position.""" position_map = { 1: "Goalkeeper", 2: "Defender", 3: "Midfielder", 4: "Forward" } return position_map[position]
ae731ad483beaf57bbe896fb598474d5f2e7013c
587,980
def produce_output(board): """Creates the output format from the board""" output = "" for i in range(len(board)): for j in range(len(board[0])): if board[i][j] is "?": return "?" output += board[i][j] + " " if j < len(board[0]) - 1 else board[i][j] output += "\n" if i...
893c31c583a45bab9680f932e1ed794bbecc6ad3
587,981
def GetSingleListItem(list, default=None): """Return the first item in the list, or "default" if the list is None or empty. Assert that the list contains at most one item. """ if list: assert len(list) == 1, list return list[0] return default
9b70ffaaeddfe149614314128b0e72b447f38a45
587,985
def split_fragment(uri): """ Given a URI or URI reference, returns a tuple consisting of (base, fragment), where base is the portion before the '#' that precedes the fragment component. """ # The only '#' in a legit URI will be the fragment separator, # but in the wild, people get sloppy. As...
4f2d088f5029852c1c1c6df861379ed8a0c3378e
587,992
def only_once(func): """Simple caching decorator for a no-argument function to only be called once.""" def decorator(): if not hasattr(func, "only_once_return"): ret = func() func.only_once_return = ret return func.only_once_return return decorator
edae232dbf96a4c33b8142675718913a50a82e5a
587,993
def write_gaussian_cube_text( vol, axes, elem=(1,), qs=(0,), pos=((0, 0, 0),), origin=(0, 0, 0), two_line_comment='cube\nfile\n'): """Write Gaussian cube file using volumetric data Args: vol (np.array): volumetric data, shape (nx, ny, nz) axes (np.array): grid basis, e.g. np.diag((dx, dy, dz)) el...
567642fdb3a07e93f3b4d49ec9be4283bb545d5e
587,996
import random def splitDataSets(IDs, trainSize=0.7, seed=2019): """Split a list of ids, can be uid or cid :param IDs: list of ids. It can be list of uids (ordered course id pairs), or a list of course ids :type IDs: list :param trainSize: train set ratio, defaults to 0.7 :type trainSize: floa...
5e6252f6d30c11db1181eb4b47c1b0f641e8a90b
587,997
import re def author(bullet): """Given a Markdown bullet, return the last name of the first author. """ authors = bullet.split('\n')[1] authors, _ = authors.split('(', 1) names = [n.strip() for n in re.split(', and |, | and ', authors)] return names[0].split()[-1]
05b7fea4f9b035a12ede2f55ed820a833a146df1
588,000
import re def get_devices(std_log_data): """Retrieve dictionary of components with their device(s).""" comp_re = re.compile(r"The following components were found:(.*)\n") device_re = re.compile(r" (.*?) with device\(s\) (.*?)\.") # Take first match as we only expect one. match = re.findall(comp_re...
4ca6abde700a3920a52277f3570041ba3818b4aa
588,002
def get_motif_factors(motif, indirect=True): """Return all TFs that are associated with a motif.""" motif_factors = [] for factor_type, factors in motif.factors.items(): if factor_type == "direct" or indirect: motif_factors += factors return motif_factors
7ce99b99dc3922a83fd6ce1d678d1bf369bc5aab
588,008
def no_data_transformation(data): """ :param data: transcripts x cells data matrix :return: identical data """ # print('SC3 log2 data transformation.') return data
feae96dee37d619284dae7b6a61b88b802f16d89
588,009
from typing import Iterable from typing import Tuple import math def seqminmax(sequence: Iterable[int]) -> Tuple[int, int]: """ Returns a tuple containing the minimum and maximum element of the ``sequence``. """ min_, max_ = math.inf, -math.inf for x in sequence: min_ = min(min_, x) ...
2135367c420dc89d28de68d7551779502f615f2f
588,011
def extract_ids(records): """ Given a list of records from a remote server, return a list of ids contained therein. """ ids = [] for record in records: ids.append(record['id']) return ids
28b63c521d499e02a5b78466e5fc4845bed0ed2a
588,012
def _set_label_positions(location, rotation): """Get rotation, horizontal alignment, and vertical alignment, respectively, based on orientation and rotation """ if location in ['top', 'bottom']: rotation = 'horizontal' if rotation is None else rotation return rotation, 'right', 'center'...
6ba50b2dc934324ae62711e35a610e07d6f7ff5c
588,014
def split_len(s, length): """split string *s* into list of strings no longer than *length*""" return [s[i:i+length] for i in range(0, len(s), length)]
ab94cc20515480a8a64c11bc9867428300853ea7
588,017
def user_can_post_document(user, **kwargs): """ Return True iff the given user can upload new files to the catalouge """ return user.is_staff or user.has_perm('document_catalogue.add_document')
f0006345c27548f7cdff65e61a576661fd0e6440
588,019
def assign_multilevel_column(df, val_or_fxn, *collevels): """ Dataframe-pipeable function to assign new multi-level columns Parameters ---------- df : pandas.DataFrame Dataframe with a multilevel index along the column axis. val_or_fxn : scalar, array-like or callable If scalar arra...
141fad6a3a01e644c5ba37a9e5e1150142d7ffea
588,021
def strip_leading_v(version_str: str): """Strip leading v of a version which is not SemVer compatible.""" return version_str[1:] if version_str.startswith("v") else version_str
55027b3706841b4b1640d508200edf43abfdd9be
588,023
def easy_unpack(elements): """ returns a tuple with 3 elements - first, third and second to the last """ return (elements[0], elements[2], elements[-2])
e8859a349c2eaff9fc5e9be984f90eda2ad252cd
588,026
def isValidSubset(subset, background): """ Checks if the gene subset of interest contains genes not present in the background set. If there are additional genes they are removed. Parameters ---------- subset : set of str A subset of Uniprot ACs of interest. background : set of str ...
b5028d643b65d405471e58502069163f3ba878ee
588,028
def filter(words, mask): """Return list of elements from the `words` list that satisfy `mask`""" return [w for w in words if mask.valid(w)]
50ee853869454dcaa51ecf8c8a9dfca2dcf713ac
588,031
from datetime import datetime def _datetime_to_timestamp(dt): """ Converts a Python datetime object to a UNIX timestamp Args: dt (datetime): A python datetime object Returns: int: A UNIX timestamp """ return int((dt - datetime(1970, 1, 1)).total_seconds())
9ac0ae7c1f327524ecada82204772e476188f43a
588,032
def _is_cluster_bootstrapping(cluster_summary): """Return ``True`` if *cluster_summary* is currently bootstrapping.""" return (cluster_summary['Status']['State'] != 'STARTING' and not cluster_summary['Status']['Timeline'].get('ReadyDateTime'))
ff7243e099d278dc0343779a7bdb67ee2ddce4b3
588,034
def checkbox_property(question): """ Convert a checkbox question into JSON Schema. """ return {question['id']: { "type": "array", "uniqueItems": True, "minItems": 0 if question.get('optional') else 1, "maxItems": question.get('number_of_items', len(question['options'])), ...
82ec3810c52e9012a454d13641f970f83612e239
588,035
def coding_problem_39(cells): """ Conway's Game of Life takes place on an infinite two-dimensional board of square cells. Each cell is either dead or alive, and at each tick, the following rules apply: Any live cell with less than two live neighbours dies. Any live cell with two or three li...
58fd4753709e76795052dde00363e38b91a088f3
588,037
def compute_school_holiday_lag(df, shift=1): """Compute lagged indicator for school_holiday.""" school_holiday_lag = df.groupby("store")["school_holiday"].shift(shift) return school_holiday_lag.fillna(0).astype("double")
7f04d0511c687ff277e86e1f33b8552d7617e672
588,038