content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def normalize_md(txt): """Replace newlines *inside paragraphs* with spaces. Consecutive lines of text are considered part of the same paragraph in Markdown. So this function joins those into a single line to make the test robust to changes in text wrapping. NOTE: This function doesn't attempt to b...
3d3383607c7b5957ce75888266326f03f7dc7be2
20,417
import re def tsv_string_to_list(s, func=lambda x : x, sep='|^|'): """Convert a TSV string from the sentences_input table to a list, optionally applying a fn to each element""" if s.strip() == "": return [] # Auto-detect separator if re.search(r'^\{|\}$', s): split = re.split(r'\s*,\s*', re.sub(...
3bc223b7d685a0245d4dad98eeac81c39a315a77
20,422
def replicate_config(cfg, num_times=1): """Replicate a config dictionary some number of times Args: cfg (dict): Base config dictionary num_times (int): Number of repeats Returns: (list): List of duplicated config dictionaries, with an added 'replicate' field. """ # ...
8b4d43002c22d20c6d2238c2309086a21d560c5c
20,425
def create_table_sql(tablename, fields, geom_type, geom_srid): """ Create a SQL statement for creating a table. Based on a geoJSON representation. For simplicity all fields are declared VARCHAR 255 (not good, I know, patches welcome) """ cols = [] for field in fields: cols.append("%s...
1df5ff0472a0333f6dcc872030e3f253e4aeb940
20,436
import click def _validate_count(value): """ Validate that count is 4 or 5, because EFF lists only work for these number of dice. :param value: value to validate :return: value after it's validated """ # Use `set` ({x, y, z}) here for quickest result if value not in {4, 5}: r...
79f17c061af41e71f0f2f82d4a6a21fe2e09abfa
20,443
import torch def compute_content_loss(a_C, a_G): """ Compute the content cost Arguments: a_C -- tensor of dimension (1, n_C, n_H, n_W) a_G -- tensor of dimension (1, n_C, n_H, n_W) Returns: J_content -- scalar that you compute using equation 1 above """ m, n_C, n_H, n_W = a_G.sha...
51894aedd2a7cfce5db3be3b43f8689ecdf78bf6
20,449
def filter_table_from_column(table,column,value): """ Return a view into the 'table' DataFrame, selecting only the rows where 'column' equals 'value' """ return table[table[column] == value]
2b0642d8a2a7959614ef99f1fdc12148ddd294f7
20,451
def strip_specific_magics(source, magic): """ Given the source of a cell, filter out specific cell and line magics. """ filtered=[] for line in source.splitlines(): if line.startswith(f'%{magic}'): filtered.append(line.lstrip(f'%{magic}').strip(' ')) if line.startswith(f'...
3c2722b86b6fc8e40c8dd51edd06d7edb28e2945
20,452
def pagination_for(context, current_page, page_var="page", exclude_vars=""): """ Include the pagination template and data for persisting querystring in pagination links. Can also contain a comma separated string of var names in the current querystring to exclude from the pagination links, via the ``...
77996effe11d35cff3b7e279533f331e1b2d05e0
20,459
import hmac def compute_signature(payload: bytes, secret: bytes, algo: str = 'sha256') -> str: """ Computes the HMAC signature of *payload* given the specified *secret* and the given hashing *algo*. # Parmeters payload: The payload for which the signature should be computed. secret: The secret string that ...
0f62326eaadddb569c661a59a60284062c348b2e
20,467
from typing import Any import jinja2 def _render_jinja2(filename: str, **kwargs: Any) -> str: """Returns a rendered template. Args: filename: Template filename. **kwargs: Template environment. """ with open(filename, 'r') as fh: template = jinja2.Template(fh.read(), autoescape=False) return tem...
1a48edc8fb829e9a12bfd678756c995afaf5c9bd
20,478
def min_value_node(node): """ Binary Search Tree min value node Complexity: O(HEIGHT) Find the node with the minimum value in a binary search tree. """ while node.left is not None: node = node.left return node
4d423183f0da3fd5d0bc66c84f26353543f8e406
20,479
def parse_option_list_string(option_list, delimiter=None): """Convert the given string to a dictionary of options. Each pair must be of the form 'k=v', the delimiter seperates the pairs from each other not the key from the value. :param option_list: A string representation of key value pairs. :typ...
fe6a440e004552b418d151ac6f3de9a08fe3e787
20,481
def _read_exact(read, size): """ Read exactly size bytes with `read`, except on EOF :Parameters: - `read`: The reading function - `size`: expected number of bytes :Types: - `read`: ``callable`` - `size`: ``int`` :return: The read bytes :rtype: ``str`` """ if size <...
4520c977812bd77365dd1b5a445697b3435d1d19
20,483
import re def char_length(character, letter_spacing=0): """Return the max width of a character by looking at its longest line. :param character: The character array from the font face :param letter_spacing: The user defined letter spacing :returns: The length of a longest line in a character """ ...
32650f0d21e597810225dad25513b0107d6551e1
20,488
from typing import List from typing import Dict def aggregate_action_stats(action_stats: List[Dict[str, int]]) -> Dict[str, int]: """Aggregate statistics by returning largest value observed for each of the tweet reactions (reply, retweet, favorite).""" action_stat = {} for key in action_stats[0].keys(): ...
2e43e186c6f6ba58ce7ba0ff883bdb61783c896b
20,490
import re import logging def append_to_csl_item_note(csl_item, text='', dictionary={}): """ Add information to the note field of a CSL Item. In addition to accepting arbitrary text, the note field can be used to encode additional values not defined by the CSL JSON schema, as per https://github.com...
b3f43adacba1dca3749e048fe94b5cf0b2c15e3b
20,491
def GetTitle( text ): """Given a bit of text which has a form like this: '\n\n Film Title\n \n (OmU)\n ' return just the film title. """ pp = text.splitlines() pp2 = [p.strip() for p in pp if len(p.strip()) >= 1] return pp2[0]
d152282610072fa88c7a45a3aca2991b6fedb79c
20,493
def get_time_in_seconds(timeval, unit): """ Convert a time from 'unit' to seconds """ if 'nyear' in unit: dmult = 365 * 24 * 3600 elif 'nmonth' in unit: dmult = 30 * 24 * 3600 elif 'nday' in unit: dmult = 24 * 3600 elif 'nhour' in unit: dmult = 3600 elif '...
4fbcbf16e7a51e046e267a0cafad090049357cae
20,494
def get_columns(document): """ Return a list of tuples, each tuple containing column name and type """ # tags = document.tags.to_dict() tags = document.tags names = list(tags.keys()) types = list(tags.values()) columns = [] for field, value in zip(names, types): try: ...
c227815fcf1d2b3815b951c90397a7e89c43cc1c
20,496
def drawPins(input_data, xpins, ypins, map): """ Draw pins on input_data Inputs: - input_data: np.array of size (C, H, W) (all zeros to start with) - xpins & ypins: np.array of x-coordinates and y-coordinates for all pins e.g., [x1, x2 ... xm] and [y1, y2, ... ym] for ...
1d5796cc2a009e8e5993cbc374525c46b08a1a61
20,497
import re def slugify(input: str) -> str: """Converts Foo Bar into foo-bar, for use wih anchor links.""" input = re.sub(r"([() ]+)", "-", input.lower()) return re.sub(r"-$", "", input)
c08acb689783e382ce58ca886f2971aa4f42c763
20,500
def check_input_stream_count(expected_number_of_streams): """ Decorator for Tool._execute that checks the number of input streams :param expected_number_of_streams: The expected number of streams :return: the decorator """ def stream_count_decorator(func): def func_wrapper(*args, **kwa...
96dfdc8f85d70dee1ac44f01f95dd07eb3725261
20,508
import math def calculate_base_day_duration(game): """Calculate the base day length.""" base_day_length = math.sqrt(2 * game.nb_alive_players) base_day_length = math.ceil(base_day_length) + 1 base_day_length = base_day_length * 60 return base_day_length
00f49a75f7b9772bed5358fe05f7ddf9b35d2f93
20,510
def contains_tokens(pattern): """Test if pattern is a list of subpatterns.""" return type(pattern) is list and len(pattern) > 0
10436114b1eb1b9e3f5c85bf30ec0813d999d101
20,513
def solve(equation, answer): """ Solve equation and check if user is correct or incorrect """ splitted = equation.split('=') left = splitted[0].strip().replace('?', str(answer)).replace('x', '*') right = splitted[1].strip().replace('?', str(answer)).replace('x', '*') try: if right.isdigit(...
78f0eced818e681ed8d8c5e0e4667a101a7ffd4e
20,522
def load_model_configurations(model): """ Arguments: model: A SSD model with PriorBox layers that indicate the parameters of the prior boxes to be created. Returns: model_configurations: A dictionary of the model parameters. """ model_configurations = [] for layer in mod...
34c6efbca820bd5461b2e5aeb2c7b30184afa250
20,540
def user_case(mocker, user, case, org): """Fake UserCase instance.""" instance = mocker.Mock() instance.user = user instance.case = case instance.organisation = org return instance
5d6de334a8ac690156204e81a6c2db53a71ea1d6
20,543
import re def camel_to_snake(text): """ Will convert CamelCaseStrings to snake_case_strings. Examples: >>> camel_to_snake('CamelCase') 'camel_case' >>> camel_to_snake('CamelCamelCase') 'camel_camel_case' >>> camel_to_snake('Camel2Camel2Case') 'camel2_camel2_case' >>> camel_to_snak...
d7216ab1a35c189abf67bfb475486ce05dcba560
20,544
def get_hex(binary_str): """ Returns the hexadecimal string literal for the given binary string literal input :param str binary_str: Binary string to be converted to hex """ return "{0:#0{1}x}".format(int(binary_str, base=2), 4)
fe2784e58d61e577bcc66ed1bd3d2c02c1e7fda0
20,545
import glob def is_file_exists(file_name: str) -> bool: """ Checks if a file exists. :param file_name: file name to check :return: True, if the file exists, False otherwise """ return len(glob.glob(file_name)) == 1
7e8da1f544d40d53f9329e4453e198022330f01c
20,551
def fix_lon(lon): """ Fixes negative longitude values. Parameters ---------- lon: ndarray like or value Input longitude array or single value """ if lon < 0: lon += 360. return lon
ab11dca9279399179242537c86cf0af85eedb60e
20,552
def is_unique_chars_v3(str): """ If not allowed to use additional data structures, we can compare every character of the string to every other character of the string. This will take 0(n ** 2) time and 0(1) space """ for char1 in str: occurrence = 0 for char2 in str: ...
5c524ffa29b7cdc9d43619da7b299ae0f90d443c
20,554
def split_canonical(canonical): """ Split a canonical into prefix and suffix based on value sign # :param canonical: the canonical to split :return: prefix and suffix """ if '#' not in canonical: return canonical, '' if canonical.startswith('#'): return '', canonical[1:].str...
1a3f7e17cfcc9fa88d63d72fced5435c92f2ea10
20,555
def _format_yaml_load(data): """ Reinsert '\n's that have been removed fom comments to make file more readable :param data: string to format :return: formatted string """ # ptr = 0 # cptr = data[ptr:].find('comment: ') data = data.replace("\n", "\n\n") return data
499cd37a75d9badb4ba3bc853a6152036bc2e66b
20,564
def TransformName(r, undefined=''): """Returns a resorce name from an URI. Args: r: JSON-serializable object. undefined: Returns this value if the resource cannot be formatted. Returns: A project name for selfLink from r. """ if r: try: return r.split('/')[-1] except AttributeError...
6dafaa2b3f0e187fc9bc9238e3a7a06a895675fd
20,565
def get_username(request): """Returns the username from request.""" # Retrieve the username either from a cookie (when logging out) or # the authenticated user. username = "not-login" if hasattr(request, "user"): username = request.user.username if request.session.get('staff', False)...
cdd19d9715c20a4bc7f20be9b53926b87be671da
20,566
def west_valley(parcels): """ Dummy for presence in West Valley. """ in_wv = parcels['mpa'].isin([ 'AV', 'BU', 'EL', 'GB', 'GL', 'GO', 'LP', 'PE', 'SU', 'TO', 'WI', 'YO' ]) return (parcels['is_MC'] & in_wv).astype(int)
fec326f82b21acb0cab670904b76096f84445e4d
20,569
from typing import Dict def _run_compatibility_patches(json_data: Dict) -> Dict: """Patch the incoming JSON to make it compatible. Over time the structure of the JSON information used to dump a workflow has changed. These patches are to guarantee that an old workflow is compliant with the new structu...
e00776cfb89499fbac71cf867830fc00631ac600
20,575
def unsplit_to_tensors(tuples): """Get original tensor list from list of tensor tuples. Args: tuples: list of tensor tuples. Returns: original tensor list. """ return [t for tup in tuples for t in tup]
b5df94421ade286ef5ff9bb4c422c5201babe36f
20,577
def getLivenessPoints(liveness): """ histogram points for the liveness plot. It will be used for a plot like: ^ | * | * * * | ** *** | ********* +--------------> schedule index. For example, if the livenesses are [3,5], the points will be, [[0,3],[1,3]...
84dac2f0b29c957727354dd06863820c2e56a866
20,578
from urllib.parse import urlencode def oauth_url(client_id, permissions=None, server=None, redirect_uri=None): """A helper function that returns the OAuth2 URL for inviting the bot into servers. Parameters ----------- client_id : str The client ID for your bot. permissions : :class:`P...
bf7ca1957153ff938334927744804891010c0c26
20,579
def get_menu_item(menu): """ Asks user to choose a menu item from one of the menu dictionaries defined above Args: (dictionary) menu - dict of menu items Returns: (str) selection - key of menu item chosen """ while True: print('------------') print('Menu Optio...
603ed07bdd7b51d9539cb0251f42e0affc1001cf
20,584
def _sharded_checkpoint_pattern(process_index, process_count): """Returns the sharded checkpoint prefix.""" return f"shard-{process_index:05d}-of-{process_count:05d}_checkpoint_"
67e0b91b8b3ac9d5c69ec662f6c7931c90a79225
20,587
def parse_arg(arg): """ Parses arguments for convenience. Argument can be a csv list ('a,b,c'), a string, a list, a tuple. Returns a list. """ # handle string input if type(arg) == str: arg = arg.strip() # parse csv as tickers and create children if ',' in arg: ...
45154fbdd9b6ecfafebbee0ec47a6185799a773a
20,589
from typing import Dict def tags_string(tags: Dict[str, str]) -> str: """ tags_string generates datadog format tags from dict. """ s = '' for k in tags: s += f'{k}:{tags[k]},' return s.rstrip(',')
203243c2960bb4fb75a832bc014484aa5b9dec9c
20,590
def if_elif_else(value, condition_function_pair): """ Apply logic if condition is True. Parameters ---------- value : anything The initial value condition_function_pair : tuple First element is the assertion function, second element is the logic function to execute if a...
ff2e5315e3bf7ad3e8fa23941e17d7052d6e3ebc
20,593
from typing import List def nest_list(inp: list, col_cnt: int) -> List[list]: """Make a list of list give the column count.""" nested = [] if len(inp) % col_cnt != 0: raise ValueError("Missing value in matrix data") for i in range(0, len(inp), col_cnt): sub_list = [] for n in r...
6d3ca2e2d4cb61d68279ffad773831a7ba203eae
20,595
def get_koji_build_info(build_id, session, config): """ Returns build information from koji based on build id. :param dict build_id: build id of a build in koji. :param koji.ClientSession session: koji connection session object :return: build information. :rtype: dict """ print("Retrie...
4ffc925ca3ec6ede46d55f7a98f129683d2b4980
20,599
def dict_from_list(keyfunc, l): """ Generate a dictionary from a list where the keys for each element are generated based off of keyfunc. """ result = dict() for item in l: result[keyfunc(item)] = item return result
a676eb6cefaf99cbb6dd8d0aa61f05c31f2a2382
20,604
import re def add_item_offset(token, sentence): """Get the start and end offset of a token in a sentence""" s_pattern = re.compile(re.escape(token), re.I) token_offset_list = [] for m in s_pattern.finditer(sentence): token_offset_list.append((m.group(), m.start(), m.end())) return token_of...
45c387674c84cb6ba7559acc98b69e6789040f50
20,606
import torch def get_lastlayers_model_weights(mdl, is_mask_class_specific = False, is_fc_lastlayer = False): """ Returns the weights at the head of the ROI predictor -> classification and bounding box regressor weights + bias :returns cls_weights, bbox_pred_weights, bbox_pred_bias :rtype: tuple ""...
fe662b448dc514113a8692cfb06417c99ab77244
20,607
def custom_rounder(input_number, p): """ Return round of the input number respected to the digit. :param input_number: number that should be round :type input_number: float :param p: 10 powered by number of digits that wanted to be rounded to :type p: int :return: rounded number in float ...
01cc63849c180024f83bb530aa0dfd69cbfc1495
20,610
def get_type(string_: str): """ Find type into which provided string should be casted. :param string_: str -- single string to reformat :return: float, int, bool or str """ if "." in string_ and string_.replace(".", "").isdigit(): return float elif string_.replace("-", "").isdigit()...
1ca3de231a973488a77489b938eeaddb9531de1e
20,612
import torch import math def elastic_deformation(img: torch.Tensor, sample_mode: str = "bilinear", alpha: int = 50, sigma: int = 12) -> torch.Tensor: """ Performs random elastic deformation to the given Tensor image :param img: (torch.Tensor) Input image :param sample_mode: (st...
ce8e884780a8dd54851d375f058fb836dfca0a0a
20,617
def as_list(value): """\ Cast anything to a list (just copy a list or a tuple, or put an atomic item to as a single element to a list). """ if isinstance(value, (list, tuple)): return list(value) return [value]
02f8aa7194a594e0fd4bbddde77995382e011ac2
20,618
def user_register(request): """ 用户注册页面路由函数 :param request: 请求对象 :return: 用户注册页面 """ return { '__template__': 'user_register.html' }
72813591d14a63a5788c2c9056d1482e8d07a31b
20,620
from pathlib import Path def dbt_artifacts_directory() -> Path: """ Get the path to the dbt artifacts directory. Returns ------- out : Path The dbt artifacts directory """ artifactis_directory = Path(__file__).parent / "dbt/data/" return artifactis_directory
94b44a3418c4d307f2bed977325015ca2e78ed00
20,624
from datetime import datetime def get_data_for_daily_statistics_table(df): """ Return data which is ready to be inserted to the daily_statistics table in the database. Parameters ---------- df : pandas.core.frame.DataFrame Pandas Dataframe containing data received from the API. ...
faf7cfb76e88838d049e79bcabfbeef2238dc304
20,625
def number_of_authors(publications: list[dict]) -> int: """Computes the number of different authors. Authors are differentiated by their ID. :param: a list of publications. :return: the number of authors. """ authors = set() for publication in publications: authors.update(x['id'] ...
7d4c610bb2f9a8003ae440e1408998ee28733bbc
20,629
def get_slope(r, sy, sx): """ Get the slope for a regression line having given parameters. Parameters ---------- > `r`: regrwssion coefficient of the line > `sy` sample standard deviation of y distribution > `sx`: sample standard deviation of x distribution Returns ------- The slope of the given regression ...
ada3f2b105634635a41d973a629aa32b64f8bbaf
20,632
def clean_translation(translation): """Clean the translation string from unwanted substrings.""" illegal_substrings = ['; french.languagedaily.com', ';\u00a0french.languagedaily.com', ' french.languagedaily.co'] for iss in illegal_substrings: trans...
9e20b739ebb47900555309d3a91f58f9ef0e8f7c
20,634
def get_ids_from_nodes(node_prefix, nodes): """ Take a list of nodes from G and returns a list of the ids of only the nodes with the given prefix. param node_prefix: prefix for the nodes to keep. type node_prefix: str. param nodes: list of nodes from G. type nodes: [(str, int)]. """ re...
08c53235c0164dee66b63f7d672550763bb7e26d
20,636
def parse_cachecontrol(header): """Parse Cache-Control header https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 >>> parse_cachecontrol(b'public, max-age=3600') == {b'public': None, ... b'max-age': b'3600'} True >>> parse_cachecontro...
8ebcd161f1361c59b82dd6eda42d429dc3bf1e4b
20,637
def get_prefix0_format_string(item_num): """Get the prefix 0 format string from item_num. For example, 3 items would result in {:01d} """ max_digit_num = len(str(item_num)) output_pattern = '{:0' + str(max_digit_num) + 'd}' return output_pattern
9b5e5597763d16577aacc2f884cc391edea4dcd4
20,639
from typing import Iterable def join_comma_or(items: Iterable[str]) -> str: """Join strings with commas and 'or'.""" if not items: raise ValueError("No items to join") *rest, last = items if not rest: return last return f"{', '.join(rest)} or {last}"
08126eb0db002943c7613f140ad8ee279a1a8515
20,642
def generate_cursor(collection, parameters): """Query collection and return a cursor to be used for data retrieval.""" # We set no_cursor_timeout so that long retrievals do not cause generated # cursors to expire on the MongoDB server. This allows us to generate all cursors # up front and then pull resu...
7b50cff3bad2cc0907f262008ff4e2c91b794d35
20,644
def is_prod_of_two_3_digit_num(n): """Determine whether n is the product of 3-digit numbers.""" result = False for i in range(100, 1000): if n % i == 0 and n // i in range(100, 1000): result = True break return result
db0cb1b3ae1ecb8b15d01582f8c0599ce00ce766
20,647
def split_authority(authority): """ Basic authority parser that splits authority into component parts >>> split_authority("user:password@host:port") ('user', 'password', 'host', 'port') """ if '@' in authority: userinfo, hostport = authority.split('@', 1) else: use...
bb6663646cec725ecb809cccfd75e7ee48a1684e
20,648
def finite_fault_factor(magnitude, model="BT15"): """ Finite fault factor for converting Rrup to an equivalent point source distance. Args: magnitude (float): Earthquake moment magnitude. model (str): Which model to use; currently only suppport "BT15". Retur...
55d74563cdfd367e7866ebc5285d6abed9c649df
20,650
def addattr(**kwargs): """ Decorator to add attributes to a function The shortcut is most useful for admin representations of methods or attributes. Example: Instead of writing >>> def is_valid(self): >>> return self.name != "foo" >>> is_valid.short_description = "The name fo...
bbf9ed404cc90413e6e186967621ed5d8ef858ad
20,652
def outputCoords(x:int,y:int) -> str: """ Converts 2D list indexes into Human-Readable chess-board coordinates x and y correspond to the indexes such that it looks like this: `dataList[x][y]` """ columnCheck = ["A","B","C"] column = columnCheck[y] row = str(x+1) return column+row
37412d503f792822f2264ac59eb22aee334182e8
20,653
def replace_ch(string: str, characters: list, replacement: str) -> str: """Replaces all intances of characters in a given string with a given replacement character. """ n_string = string for ch in characters: n_string = n_string.replace(ch, replacement) return n_string
30939885554638d4b1cf844211e687a1447cd72b
20,654
def isfloat(element): """ This function check if a string is convertable to float """ try: float(element) return True except ValueError: return False
0a2c209b998a8aeea696a35f2cb3b587373739a5
20,657
def extract_topic_data(msg, t): """ Reads all data in a message This is a recursive function. Given a message, extract all of the data in the message to a dictionary. The keys of the dictionary are the field names within the message, and the values are the values of the fields in the messag...
2a80771b70aa012bd626da7fbe8d5509c444481b
20,658
def atm2Btu_ft3(x): """atm -> Btu/ft^3""" return 2.719*x
e9717d6990e18a50c644bd5c942b965fabff861b
20,661
def calc_angle(per, line): """ Calculate angle between two vector. Take into consideration a quarter circle :param per: first vector :type per: DB.XYZ :param line: second vector :type line: DB.XYZ :return: Angle between [-pi, pi] :rtype: float """ return (1 if per.Y >= 0 els...
81290fd40dfd4d714f56478a2c41b33156ca8157
20,665
from pathlib import Path def check_dir(dir, mkdir=False): """check directory ディレクトリの存在を確認する。 Args: dir (str): 対象ディレクトリのパス(文字列) mkdir (bool, optional): 存在しない場合にディレクトリを作成するかを指定するフラグ. Defaults to False. Raises: FileNotFoundError: mkdir=Falseの場合に、デ...
1ada67ae07bdfe05c25474f3028cf4b5808d541b
20,667
def extract_column_from_array(array, col_number): """ Extracts a specific column from an array and copies it to a list :param array: The NumPy array with the data :param col_number: The number of the column that should be extracted :return: The list with the extracted values """ extracted_c...
b390ee58aab8802302996488925855de4d428f1a
20,671
def spreadsheet_col_num_to_name(num): """Convert a column index to spreadsheet letters. Adapted from http://asyoulook.com/computers%20&%20internet/python-convert-spreadsheet-number-to-column-letter/659618 """ letters = '' num += 1 while num: mod = num % 26 letters += chr(mod + 64...
c39a96ed5794f582ce790a025ddecfe2cff39bf0
20,673
def _get_states(rev, act): """Determines the initial state and the final state based on boolean inputs Parameters ---------- rev : bool True if the reaction is in the reverse direction. act : bool True if the transition state is the final state. Returns -----...
4303b193a40515b4b7c52c4e2b5286dc6a9f4cd1
20,679
from typing import Any def compare_any_with_str(other: Any, str_value: str) -> bool: """Compare any value with a string value in its str() form. :param other: the other value to be compared with a string. :param str_value: the string value to be compared. :return: True if the str() of the other value...
be88d4e15a609468d3d65eb99417a4e76582ac9a
20,682
def get_temp_column_name(df) -> str: """Small helper to get a new column name that does not already exist""" temp_column_name = '__tmp__' while temp_column_name in df.columns: temp_column_name += '_' return temp_column_name
a4dba2fb09166b2797f8c4c6dd93f46aaebb408e
20,683
def enable() -> dict: """Enables tracking security state changes.""" return {"method": "Security.enable", "params": {}}
a9c341edf37ec5ebbc0b372b4e56a81e98aff903
20,685
def _sanitize_for_filename(text): """ Sanitize the given text for use in a filename. (particularly log and lock files under Unix. So we lowercase them.) :type text: str :rtype: str >>> _sanitize_for_filename('some one') 'some-one' >>> _sanitize_for_filename('s@me One') 's-me-one' ...
7edda0859a6527c9a4cb0a464afb82c16d6df6dc
20,691
def estimate_parms(W, X, Y, n): """Compute estimates of q_mod and q_con parameters.""" q_mod_hat = 1 - X / Y q_con_hat = W / (n - 1) return (q_mod_hat, q_con_hat)
b1f47de984482dee9d99f8ffa33ccb570079ba93
20,702
def _is_empty(value): """Returns true if value is none or empty string""" return value is None or value is ""
8afbcbc71ab47097520c7a7e646406967d1086f6
20,704
from html.entities import name2codepoint import re def extract_text(html, start, end, decode_entities=True, strip_tags=True): """Given *html*, a string of HTML content, and two substrings (*start* and *end*) present in this string, return all text between the substrings, optionally decoding any HTML entities and ...
1770ad49ec992df949725c9595f48e93188dc0e8
20,705
def serializer_is_dirty(preference_serializer): """ Return True if saving the supplied (Raw)UserPreferenceSerializer would change the database. """ return ( preference_serializer.instance is None or preference_serializer.instance.value != preference_serializer.validated_data['value'] ...
19ce15215a13e96020e0503c28930525d6243330
20,711
import json import requests def adjust_led(state_irgb): """ Sends a request to the arduino to adjust the leds. """ state = state_irgb.split()[0] irgb = state_irgb.split()[1].upper() url = f"http://192.168.1.188/led?state={state};irgb={irgb};" return json.loads(requests.get(url).text)
8330842295b0bb3dcfb99085fb9d27e18b12c8a0
20,713
import re def isfloat(word): """Matches ANY number; it can be a decimal, scientific notation, integer, or what have you""" return re.match('^[-+]?[0-9]*\.?[0-9]*([eEdD][-+]?[0-9]+)?$',word)
8df3be23d1e39590c88fb0e8de275571b0ec4c57
20,715
def safestart(text: str, piece: str, lc: bool = False) -> bool: """ Checks if text starts with another, safely :param text: the string to check :param piece: the start string :return: true if text starts with piece """ check = text if lc else text.lower() return len(text) >= len(piece) ...
9bdefe01f97be4660b11ed4ce36b08da410680e3
20,723
def onecase(case): """Check if the binary string is all ones""" if case == "1" * len(case): return True else: return False
d21bbf34960abcf3eafe6f0b4271ea9054d3e77f
20,725
def get_chosen_df(processed_cycler_run, diag_pos): """ This function narrows your data down to a dataframe that contains only the diagnostic cycle number you are interested in. Args: processed_cycler_run (beep.structure.ProcessedCyclerRun) diag_pos (int): diagnostic cycle occurence for ...
b09abfdc3a9b1fa7836f548d6c40ca7845321418
20,729
def hms_to_sec(hms): """ Converts a given half-min-sec iterable to a unique second value. Parameters ---------- hms : Iterable (tuple, list, array, ...) A pack of half-min-sec values. This may be a tuple (10, 5, 2), list [10, 5, 2], ndarray, and so on Returns ------- ou...
9da83a9487bfe855890d5ffd4429914439f4b28b
20,733
def easeInOutQuad(t, b, c, d): """Robert Penner easing function examples at: http://gizma.com/easing/ t = current time in frames or whatever unit b = beginning/start value c = change in value d = duration """ t /= d/2 if t < 1: return c/2*t*t + b t-=1 return -c/2 * (t*(t...
a4ae2cc0b2c03a499bee456a08bdada023570361
20,736
def higlight_row(string): """ When hovering hover label, highlight corresponding row in table, using label column. """ index = string["points"][0]["customdata"] return [ { "if": {"filter_query": "{label} eq %d" % index}, "backgroundColor": "#3D9970", "...
c4473cf2d41b4ef7df6d08048dd6f9fe8f5d4099
20,742
def get_dict_value(key, data): """Return data[key] with improved KeyError.""" try: return data[key] except (KeyError, TypeError): raise KeyError("No key [%s] in [%s]" % (key, data))
166656c226bb7a846c7c63f6d8d07ab7ee1a81f9
20,744
def list_to_string(s, separator='-'): """ Convert a list of numeric types to a string with the same information. Arguments --------- s : list of integers separator : a placeholder between strings Returns ------- string Example ------- >>> list_to_string( [0,1], "-" ) ...
bf926cbc87895fe820d5de8c206f499f9558eefd
20,746
import functools def cached_method(cache_size=100): """ Decorator to cache the output of class method by its positional arguments Up tp 'cache_size' values are cached per method and entries are remvoed in a FIFO order """ def decorator(fn): @functools.wraps(fn) def wrapper(self, *...
3e580dc984373d3a19fd37a7c195ee3c4842d8b3
20,748