content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def make_desc_dict(ecfp): """ Format tuple of fingerprint information into dictionary :param ecfp: Tuple of fingerprint features and values :return: dictionary of fingerprint features and values """ ecfp_feat, ecfp_val = zip(*ecfp) return ecfp_feat, ecfp_val
5925cda8d428fad5c9bfd46a7a26276e34256569
34,002
def extract_tags(tags): """ Extract the tag names from tag list""" return [tag['display_name'] for tag in tags]
2c07a66ac3ddf1291fd0dab803fd4310c2e80941
34,004
def get_orders(value): """ Return a list of orders for context tiers. Parameters ---------- value : int or string The maximum context length or a string in the set "bigram" (for context 1, and 2), "trigram" (for context 1, 2, and 3), or "fourgram" (for contexts 1, 2, 3, and 4). """ # Dictionary used for mapping string descriptions of window size to # actual Python ranges; by mapping to `range()` here in advance # (and consuming such range into a list), computations is a bit # faster and, in particular, it is clearer. Note that we always start # from 1, so no zero-length is included in the lists (the zero distance # is the actual alignment site itself). order_map = { "bigram": list(range(1, 2)), "trigram": list(range(1, 3)), "fourgram": list(range(1, 4)), } # get mapping if isinstance(value, int): orders = list(range(1, value + 1)) elif isinstance(value, str): orders = order_map[value] else: orders = [] return orders
7f473e50a9fbb0ec0927016994367150aee7aa70
34,005
def clean_env(env): """Make a copy of env without game.""" new_env = env.copy() del new_env["game"] return new_env
dc7356a271c6f82ba8fe06a600302f6bc1eae963
34,008
def _num_clips( duration_sec: float, fps: float, stride_frames: int, window_size_frames: int, backpad_last: bool = True, ) -> int: """ Utility to calculate the number of clips for a given duration, fps, stride & window_size """ num_frames = round(duration_sec * fps) N = num_frames - window_size_frames if N < 0: return 1 result = N // stride_frames + 1 # handle padded frame if backpad_last and N % stride_frames != 0: result += 1 return result
f13cec1dd9ced5a4a446b24524646a2e6db3479e
34,010
import csv def load_review_data(path_data): """ Returns a list of dict with keys: * sentiment: +1 or -1 if the review was positive or negative, respectively * text: the text of the review """ basic_fields = {'sentiment', 'text'} data = [] with open(path_data) as f_data: for datum in csv.DictReader(f_data, delimiter='\t'): for field in list(datum.keys()): if field not in basic_fields: del datum[field] if datum['sentiment']: datum['sentiment'] = int(datum['sentiment']) data.append(datum) return data
e19e51a37007ad308893c190a3629beef9e57f90
34,011
def days_per_month(leap=False): """Return array with number of days per month.""" ndays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if leap: ndays[1]+= 1 return ndays
e8efeab08bc82344792a3956df91e53767be81c9
34,013
def linear_annuity_mapping_func(underlying, alpha0, alpha1): """linear_annuity_mapping_func calculate linear annuity mapping function. Annuity mapping function is model of $P(t, T) / A(t)$ so that it's value is positive. linear annuity mapping function calculates following formula: .. math:: \\alpha(S) := S \\alpha_{0} + \\alpha_{1}. where :math:`S` is underlying, :math:`\\alpha_{0}` is alpha0, :math:`\\alpha_{1}` is alpha1. :param float underlying: :param float alpha0: :param float alpha1: :return: value of linear annuity mapping function. :rtype: float. """ assert(underlying * alpha0 + alpha1 > 0) return underlying * alpha0 + alpha1
3c4f780c8bc90ac2e6e2b3a1f9b930cbd291c9a7
34,017
def xy_to_wcs(xy, _w): """ Convert pixel coordinates (xy) to astronomical coordinated (RA and DEC) """ _radec = _w.wcs_pix2world(xy, 1) return _radec[:, 0], _radec[:, 1]
0d82fadee33a783ec6f1f202b74f9e6345ff827e
34,021
def format_month_day(dt, month_fmt="%b"): """ Formats the month and day of a datetime Args: dt (datetime.datetime): The datetime to be formatted month_fmt (Optional[str]): The strftime-compatible month format Returns: str: The formatted month and day """ # NOTE: This function is used instead of just 'strftime' because the '%-d' directive, which is used to produce a # formatted day without trailing zeros, is platform-dependent. return "{} {}".format(dt.strftime(month_fmt), dt.day)
19e7862e49d998b48b1c2f404e24af4eaf5bf73c
34,024
def capitalize(text): """capitalizes a word, for use in rendering template Args: text (str): word to capitalize Returns: capitalized (str): capitalized word """ return text[0].upper() + text[1:]
63248f2f0477c56ca1032aaefde69dd3398970fd
34,025
def string_to_maya_value(string): """ Convert a value saved in string to a numerical type understood by maya """ if string.isdigit(): return int(string) if '.' in string or ',' in string: if string.replace(',', '').replace('.', '').isdigit(): return float(string) return string
eeac4948225f496c3ad224f149b7eca2b1572e9e
34,027
def get_arg(*args, index: int): """Get the argument at index.""" if args: return args[index] return None
7f0e3ad04affdceb4ed02cb88a79f1c7b00e6ad2
34,033
import torch def sqrt(x): """Apply sqrt function.""" return torch.sqrt(x)
e6e7421f27ba44dc91d3c2162d6846d2b6427626
34,034
def check_api_key(tmdb) -> bool: """ Checks for the presence of the TMDB API Key. """ return False if not tmdb.api_key or "" else True
8a6c4c59448c761d548de3ba66b089beb814f839
34,040
from datetime import datetime def start_and_end_of_the_month(dt: datetime): """Get first of month and first of next month for a given datetime. """ start = dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0) if start.month == 12: end = start.replace(year=start.year + 1, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) else: end = start.replace(month=start.month + 1) return start, end
9f1001c325d04a4754b666477292788f620596f7
34,047
def has_any_permissions(user, permissions): """ Retuns `True` if the user has any of the permissions """ for perm in permissions: if user.has_perm(perm): return True return False
2de21fcb3f5a4984365185216f45ed2814fd13e4
34,053
def weighing_function(orig_length, cur_length): """ Function to generate the weight value given the predicted text-length and the expected text-length The intuition is that if the predicted text-length is far from the expected text-length then weight should be small to that word-bbox. :param orig_length: Length of the expected word bounding box :param cur_length: Length of the predicted word bounding box :return: """ if orig_length == 0: if cur_length == 0: return 1 return 0 return (orig_length - min(orig_length, abs(orig_length - cur_length)))/orig_length
09afb649952039e0d7f7b776d43cc0b0307329ee
34,054
def _parse_text_with_command(text: str): """ Parse string that is passed when bot command is invoked. """ if after_bot_name_text := text.split('</at>')[-1].rstrip().strip(): return after_bot_name_text.split() else: return '', []
03559b81e696064fee90c8818cb2825a93cbe719
34,057
from typing import Mapping from typing import Optional def _parse_obsolete(obsolete_file_path: str) -> Mapping[str, Optional[str]]: """Parses the data file from PDB that lists which pdb_ids are obsolete.""" with open(obsolete_file_path) as f: result = {} for line in f: line = line.strip() # Format: Date From To # 'OBSLTE 06-NOV-19 6G9Y' - Removed, rare # 'OBSLTE 31-JUL-94 116L 216L' - Replaced, common # 'OBSLTE 26-SEP-06 2H33 2JM5 2OWI' - Replaced by multiple, rare if line.startswith('OBSLTE'): if len(line) > 30: # Replaced by at least one structure. from_id = line[20:24].lower() to_id = line[29:33].lower() result[from_id] = to_id elif len(line) == 24: # Removed. from_id = line[20:24].lower() result[from_id] = None return result
c4e3f3a04d3349d6752d133d079a1bb3aa34e13f
34,060
def compact_date(date): """ Converts an ISO 8601 format date string into a compact date. Parameters ---------- Date: a string date in iso format. Returns ---------- A string date without hyphens. """ return date.replace('-', '')
e377096d2f0ce9404835968627e9b4e3f9d4b252
34,062
import torch def calculate_accuracy(inputs: torch.Tensor, targets: torch.Tensor) -> float: """ A function that calculates accuracy for batch processing. Returns accuracy as a Python float. Args: inputs (torch.Tensor): shape == [N, n_class] targets (torch.Tensor): shape == [N] Returns: accracy (float) """ with torch.no_grad(): total = targets.shape[0] _, predicted = torch.max(inputs, 1) correct = (predicted == targets).cpu().sum().float().item() return correct / total
53eff3901d675370a9ed0f260d1230c2c5badb79
34,064
import hashlib def hash100(s: str): """ Hash a string into 1~100. Useful when you split a dataset into subsets. """ h = hashlib.md5(s.encode()) return int(h.hexdigest(), base=16) % 100 + 1
0686d599e42c104d487462682340f04bd3fe94b4
34,069
def _get_union_type_name(type_names_to_union): """Construct a unique union type name based on the type names being unioned.""" if not type_names_to_union: raise AssertionError( "Expected a non-empty list of type names to union, received: " "{}".format(type_names_to_union) ) return "Union__" + "__".join(sorted(type_names_to_union))
f72f6a5212aa97eba32a3da7249087c97ce471b3
34,071
def is_clinical_in_cases(clinical_obj, cases): """Checks to see if clinical object representation is part of cases to assess Example: >>> clin_obj = xml_to_raw_clinical_patient("Test_Data/nationwidechildrens.org_clinical.TCGA-MH-A562.xml") >>> cases = set(["ad7ba244-67fa-4155-8f13-424bdcbb12e5", "dc39df39-9945-4cb6-a852-d3b42177ac80", "b877d608-e4e0-4b28-9235-01dd65849cf7"]) >>> is_clinical_in_cases(clin_obj, cases) False >>> cases = set(["ad7ba244-67fa-4155-8f13-424bdcbb12e5", "dc39df39-9945-4cb6-a852-d3b42177ac80", "b877d608-e4e0-4b28-9235-01dd65849cf7", "45bdcfd6-1e3f-4be8-b843-ae949e8e43eb"]) >>> is_clinical_in_cases(clin_obj, cases) True """ def get_days_to_birth(): pass def get_days_to_death(): """This returns either the censored value of the""" pass patient_uuid = clinical_obj['kirp:patient']['shared:bcr_patient_uuid']['#text'] patient_uuid = patient_uuid.strip().lower() return patient_uuid in cases
ecff8e7e4697b0b89f5cf5e45de8e6515e2c0ea9
34,072
def get_blanks(nrows, ncols, plot_set): """Return a list of plot locations that should remain blank.""" assert type(plot_set) == set nplots = nrows * ncols plot_numbers = range(1, nplots + 1) return list(set(plot_numbers) - plot_set)
e2049d16b7ff1f3e5d9d3628881f2574febffe16
34,074
def _qualified_names(modname): """Split the names of the given module into subparts For example, _qualified_names('pylint.checkers.ImportsChecker') returns ['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker'] """ names = modname.split(".") return [".".join(names[0 : i + 1]) for i in range(len(names))]
97c614bbcc0997ab95a8535bf02489291d9d1c11
34,075
def find_index(x,y): """ find the index of x in y, if x not in y, return -1 """ for index, item in enumerate(y): if x == item: return index return -1
2e454c97155bd9d52851a1e20a0c795e8a485a46
34,083
def get_user_action(message, options): """ Reads user input and returns value specified in options. In case user specified unknown option, returns default value. If default value is not set, returns None :param message: The message for user. :type message: string :param options: Options mapping. :type options: dict :return: Value according to the user selection. """ r = input(message).lower() return options.get(r, options.get("default"))
207e0a64ff1b5e9e638fc449c6782ae3bf3b8f5f
34,087
def byte_pos(text, line, col): """ Return position index of (line, col) line is line index, col is column index The returning byte position __includes__ all '\n's. Text is unicode. """ if type(text) != list: lines = text.splitlines(True)[:line+1] else: lines = text[:line+1] b = len(''.join(lines[:line])) + len(lines[line][:col]) return b
8bd545b76569861a0c23d6a23cb70fdfcbad0475
34,092
import re import copy def _select_allowed_items(item_dict, allow_patterns, disallow_patterns): """ Creates the dictionary of items selected from `item_dict` such that item names satisfy re patterns in `allow_patterns` and not satisfy patterns in `disallow_patterns`. The function does not modify the dictionary, but creates a new dictionary with selected items, where item values are deep copies of the values of the original dictionary. Parameters ---------- item_dict: dict Dictionary of items. allow_patterns: list(str) Selected item should match at least one of the re patterns. If the value is ``[None]`` then all items are selected. If ``[]``, then no items are selected. disallow_patterns: list(str) Selected item should not match any of the re patterns. If the value is ``[None]`` or ``[]`` then no items are deselected. Returns ------- dict Dictionary of the selected items. """ items_selected = {} for item in item_dict: select_item = False if allow_patterns: if allow_patterns[0] is None: select_item = True else: for pattern in allow_patterns: if re.search(pattern, item): select_item = True break if select_item: if disallow_patterns and (disallow_patterns[0] is not None): for pattern in disallow_patterns: if re.search(pattern, item): select_item = False break if select_item: items_selected[item] = copy.deepcopy(item_dict[item]) return items_selected
c56d9b6bf7db0f7a26da42c6da808de8fb8b7341
34,096
def scale_lr_and_momentum(args, cifar=False, skip=False): """ Scale hyperparameters given the adjusted batch_size from input hyperparameters and batch size Arguements: args: holds the script arguments cifar: boolean if we are training imagenet or cifar skip: boolean skipping the hyperparameter scaling. """ if skip: return args print('=> adjusting learning rate and momentum. ' f'Original lr: {args.lr}, Original momentum: {args.momentum}') std_b_size = 128 if cifar else 256 old_momentum = args.momentum args.momentum = old_momentum ** (args.batch_size / std_b_size) args.lr = args.lr * (args.batch_size / std_b_size * (1 - args.momentum) / (1 - old_momentum)) print(f'lr adjusted to: {args.lr}, momentum adjusted to: {args.momentum}') return args
abe65febe2538218db67470b1c2919ae7dd08cb2
34,097
def _py_lazy_or(cond, b): """Lazy-eval equivalent of "or" in Python.""" return cond or b()
965c831da37e79cc22caaf20bc9edd8677e86be6
34,098
def get_printable_table(class_name: str, class_info: dict) -> str: """ Creates and returns a string displaying the class info in a format that is easily read in a table. :param class_name: The name of a class owning the data. :type class_name: str :param class_info: The data in the class to display. :type class_info: dict{str: variant} :return: The class info in a readable format. :rtype: str """ max_key = max([len(k) for k in class_info.keys()]) max_value = max([len(str(v)) for v in class_info.values()]) header_separator = f"+{'=' * (max_key + max_value + 5)}+" row_separator = header_separator.replace("=", "-") rows = [header_separator, f"| {class_name}" f"{' ' * (max_key + max_value - len(class_name) + 4)}|", header_separator] for key, value in class_info.items(): row = f"| {key}{' ' * (max_key - len(key))} | " \ f"{value}{' ' * (max_value - len(str(value)))} |" rows.append(row) rows.append(row_separator) return "\n".join(rows)
7734537c4f68df0cc755c51661fd63d5ddb46978
34,099
def get_geometry_type(gi): """ Return the geometry type from a __geo_interface__ dictionary """ if gi["type"] == "Feature": return get_geometry_type(gi["geometry"]) elif gi["type"] in ("FeatureCollection", "GeometryCollection"): return get_geometry_type(gi["geometries"][0]) else: return gi["type"]
6e1292863dd45933c59e84cc465d3ade53248c08
34,102
def ListToString(alist, useAssert=False): """Convert a list of strings into a single string alist is the list to be converted into a string if useAssert is True, then the function checks whether all elements of alist are strings before proceeding""" if useAssert: assert all([isinstance(x, str) for x in alist]), "All elements of input list must be strings" return ''.join(alist)
29b4329df4f4e97c571240076f7f3571e91f970e
34,105
def is_number_offset(c_offset): """ Is the offset a number """ return 0x66 <= c_offset <= 0x6f
6606048314047de7f59e77e01f48e438d4113159
34,107
def inbound_degrees(adj_list: dict) -> dict: """Calculate the inbound degree of each node in a graph. Args: adj_list (dict): An adjacency list. Can be from an undirected or directed graph. Returns: dict: A dictionary where the key is a graph node \ and the value is the number of inbound edges. """ indegrees = {node: 0 for node in adj_list} for node in adj_list: for neighbor in adj_list[node]: indegrees[neighbor] += 1 return indegrees
0580e29e4f21dcc33ee6ef74717bda4250dca8c7
34,111
def sizes (im): """ Return the dimensions of an image as a list. Arguments: im the image whose dimensions are to be returned """ return im.shape
3bddd044a103b11a7c2e3eef46efb8b83c7f44d6
34,113
def _range_to_number(bucket_string): """Converts "X-Y" -> "X".""" return int(bucket_string.split('-')[0])
1bc40f88cfabec19d8f9e5e14e7de03cec825f58
34,114
import torch def compute_input_lengths(padded_sequences: torch.Tensor) -> torch.Tensor: """ Parameters ---------- padded_sequences (N, S) tensor where elements that equal 0 correspond to padding Returns ------- torch.Tensor (N,) tensor where each element corresponds to the non-padded length of each sequence Examples -------- >>> X = torch.tensor([[1, 2, 0, 0, 0], [1, 2, 3, 0, 0], [1, 2, 3, 0, 5]]) >>> compute_input_lengths(X) tensor([2, 3, 5]) """ lengths = torch.arange(padded_sequences.shape[1]).type_as(padded_sequences) return ((padded_sequences > 0) * lengths).argmax(1) + 1
44640410704c2118a09b3c0490bc854fde93269a
34,115
def calc_swath_at_nadir_cross(gsd_cross, pixels_cross): """ Calculate the swath at nadir cross track. https://en.wikipedia.org/wiki/Swathe Returns ------- double : meters """ return gsd_cross * pixels_cross
c5cdd2f08ea64884624bae6ae0497f850fe7d815
34,118
def matchAPIProfile(api, profile, elem): """Match a requested API & profile name to a api & profile attributes of an Element""" match = True # Match 'api', if present if ('api' in elem.attrib): if (api == None): raise UserWarning("No API requested, but 'api' attribute is present with value '" + elem.get('api') + "'") elif (api != elem.get('api')): # Requested API doesn't match attribute return False if ('profile' in elem.attrib): if (profile == None): raise UserWarning("No profile requested, but 'profile' attribute is present with value '" + elem.get('profile') + "'") elif (profile != elem.get('profile')): # Requested profile doesn't match attribute return False return True
147e8174d57fb05f43869075f7826c9a0fd4d484
34,121
def _plain_value_to_html(dict_, html=None): """Convert plain JSON-LD value to HTML.""" if html is None: html = [] html.append(dict_['@value']) return html
8579318b1ada26e1259550ff925d400bc5c5fa15
34,123
def angular_velocity(v, r): """ Calculates the angular velocity of an object whose linear velocity is 'v' and radius of the path traced is 'r' Parameters ---------- v : float r : float Returns ------- float """ return v / r
f24c43711044d3a3ed5d10b3590eeb19dcd1820e
34,124
def list_neighbors(cfg): """List neighbors from config. Args: cfg (dict): config from config_load. Returns: list: list of string with neighbor names. Examples: >>> list_neighbors(cfg) ['192.168.0.2', '192.168.0.1'] """ return [neighbor["name"] for neighbor in cfg["neighbors"]]
c341ef5aa63fce5bf1f11ea8e615f70037448410
34,127
from typing import Counter def CalculateSharedAddresses(symbols): """Checks how many symbols share the same memory space. This returns a Counter result where result[address] will tell you how many times address was used by symbols.""" count = Counter() for _, _, _, _, address in symbols: count[address] += 1 return count
ed7872872e9d538edb08957a5268b6ab21948534
34,128
def create_dt_hparams(max_depth=None, min_samples_split=2): """ Creates hparam dict for input into create_DNN_model or other similar functions. Contain Hyperparameter info :return: hparam dict """ names = ['max_depth','min_samples_split'] values = [max_depth, min_samples_split] hparams = dict(zip(names, values)) return hparams
7b0ddc46bdd5ace23402dc8d8f8a338a82c86cf9
34,130
def sizestr(s): """ Parses a CHANNELSxHEIGHTxWIDTH string into a tuple of int. """ return tuple(map(int, s.split('x')))
bc7f21a5340792d5fd85ef9b420562dc39ea2f81
34,132
def calculate_area_per_pixel(resolution): """ Takes a resolution in metres and return the area of that pixel in square kilometres. """ pixel_length = resolution # in metres m_per_km = 1000 # conversion from metres to kilometres area_per_pixel = pixel_length**2 / m_per_km**2 return area_per_pixel
375b376cc9c2104d3298334b718cf51c9bbd23ab
34,137
def exp_transformation(data, orig_col, new_col, power): """ Performs feature transformation by raising the indicated feature column to the given power. Parameters: _________________ data: dataframe containing training data orig_col: (str) column in data to be transformed new_col: (str) header for new transformed column power: (int) number to raise the original column by Returns: _________________ transformed_df: new dataframe with transformed column added as the last col """ transformed_df = data.withColumn(new_col, pow(data[orig_col], power)) print('The transformed DataFrame is:') transformed_df.show() return transformed_df
0fb10d848d3bec1c6a8b2a3a0776a3f0bb501b0d
34,139
import math def tan(degrees) -> float: """Calculate the tangent of the given degrees.""" return math.tan(math.radians(degrees))
90d21f4618eed7ac5eefa6a7868f2bc25322e252
34,140
def transpose(xss): """ Transpose a list of lists. Each element in the input list of lists is considered to be a column. The list of rows is returned. The nested lists are assumed to all be of the same length. If they are not, the shortest list will be used as the number of output rows and other rows wil be lost without raising an error. """ # get the number of rows in the input N = min([len(xs) for xs in xss]) return [[xs[i] for xs in xss] for i in range(N)]
655465216e3190c9ae08900c8790d46b65be0401
34,147
import uuid def generate_uuid_filename(instance, filename): """ Generate a uuid filename keeping the file extension. """ extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension)
b7846db99992d019c63b87cbb680d1d0b941dacf
34,148
def convert_bounding_boxes(bboxes): """Accepts a list of bounding boxes in format (xmin,ymin,xmax,ymax) Returns the list of boxes in coco format (xmin,ymin, width, height) """ coco_boxes = [] all_tokens = [] for b, tokens in bboxes: ymin, ymax, xmin, xmax = b h = ymax - ymin w = xmax - xmin coco_boxes.append([xmin, ymin, w, h]) all_tokens.append(tokens) assert len(coco_boxes) == len(all_tokens) return coco_boxes, all_tokens
873adfe784e39cbb4e0bcbd4eca966abc76221dd
34,149
def defval(val, default=None): """ Returns val if is not None, default instead :param val: :param default: :return: """ return val if val is not None else default
eb945de18a125b3465fb5716df4f87487a5d7205
34,152
def fixup(ocr_text, pattern): """Fix spacing and numerics in ocr text""" cleaned_pattern = pattern.replace("4", "A").replace("1","l").replace(" ","") #print(f"{pattern}\t\t{cleaned_pattern}") #print("{0:<30} {1:<10}".format(pattern, cleaned_pattern)) return ocr_text.replace(pattern, cleaned_pattern)
8aaef7a24a7599a5ddbfc5d3b2af3b6377bbe749
34,153
def true_text(variable): """ Deal with variables that should be True or False even when a string (defaults to False) i.e. returns True if variable = True, 1, "True", "T", "t", "true" etc :param variable: :return: """ # if variable is a True or 1 return True if variable in [True, 1]: return True # if variable is string test string Trues if isinstance(variable, str): if variable.upper() in ['TRUE', 'T', '1']: return True # else in all other cases return False return False
aafd64921aa64d0e2d66e2e429005f91f1e53b9c
34,156
def minimum(evaluator, ast, state): """Evaluates "min(left, right)".""" res = min(evaluator.eval_ast(ast["left"], state), evaluator.eval_ast(ast["right"], state)) return res
c64e9444bff000a2ae73caf6efb717ea6164ad81
34,157
def pad_list(orig_list, pad_length): """ Pads a list with empty items Copied from http://stackoverflow.com/a/3438818/3710392 :param orig_list: the original list :param pad_length: the length of the list :return: the resulting, padded list """ return orig_list + [''] * (pad_length - len(orig_list))
89c2f1d0908fcfaf7fc699bf095e2faff7a7b987
34,160
import ast from typing import Any def json_to_py(json: dict, replace_comma_decimal: bool = True, replace_true_false: bool = True) -> Any: """Take json and eval it from strings. If string to string, if float to float, if object then to dict. When to use? - If sending object as parameter in function. Args: json (dict): JSON with various formats as string. replace_comma_decimal (bool, optional): Some countries use comma as decimal separator (e.g. 12,3). If True, comma replaced with dot (Only if there are no brackets (list, dict...) and if not converted to number string remain untouched) . For example '2,6' convert to 2.6. Defaults to True replace_true_false (bool, optional): If string is 'false' or 'true' (for example from javascript), it will be capitalized first for correct type conversion. Defaults to True Returns: dict: Python dictionary with correct types. Example: >>> json_to_py({'one_two': '1,2'}) {'one_two': 1.2} """ evaluated = json.copy() for i, j in json.items(): replace_condition = isinstance(j, str) and "(" not in j and "[" not in j and "{" not in j if replace_comma_decimal and replace_condition: j = j.replace(",", ".") if replace_true_false and replace_condition: if j == "true": evaluated[i] = True if j == "false": evaluated[i] = False if j == "true" or j == "false": continue try: evaluated[i] = ast.literal_eval(j) except Exception: pass return evaluated
f4929ef26ac3d69ad124180dada8994e5873e842
34,162
def format_quantum_numbers(info: tuple): """Takes an expression like ('S', 1, 0, 2, ('3b', 1), ('y', 2/3)) and returns a string like S(3, 3, 2/3)(3b: 1) """ lorentz, su3_up, su3_down, su2, *charges = info su3_dim = lambda m, n: 0.5 * (m + 1) * (n + 1) * (m + n + 2) # For now just add the bar for more lowered than raised indices, but for # larger reps this will be problematic su3_dim_format = lambda m, n: str(int(su3_dim(m, n))) + ("b" if n > m else "") charges_dict = dict(charges) return f"{lorentz}({su3_dim_format(int(su3_up), int(su3_down))}, {str(int(su2) + 1)}, {charges_dict['y']})({charges_dict['3b']})"
6fa8835fdbf4fe3d3c914dec10e12573070b58ad
34,167
def rename_table_clause(old_table, new_table): """ Create a RENAME table clause string for SQL. Args: old_table: The table to be renamed. new_table: The new table name. Returns: A string with the crafted clause. """ return 'ALTER TABLE {} RENAME TO {}'.format(old_table, new_table)
d984cbce2b6c0b3451c8927a61e40fbdbc330c7c
34,170
from typing import List def median(lst: List[int]) -> float: """Takes an ordered list of numbers, and returns the median of the numbers. If the list has an even number of values, it computes the mean of the two center values. Args: lst - an ordered list of numbers Returns: the median of the passed in list """ lenlst = len(lst) counter = lenlst / 2 counter = int(counter) if lenlst % 2 == 0: return (lst[counter - 1] + lst[counter]) / 2 else: return lst[counter]
830c5122536c73ec154be3e231d1bf54a66d977c
34,172
def get_word_length(word): """ Returns number of letters in the word :param word: word :return: int """ return len(word)
0e9eeca8f3cb35178484575303a4bddae7d08adb
34,173
def split_rowcol(matrix_dim): """ Split the input matrix dimensions into row and columns matrix_dim: String Input concatenated string with row and column return: Tuple Row and column split based on suffix """ k = str(0) * 3 M = str(0) * 6 replace_M = matrix_dim.replace('M', str(M)) replace_k = replace_M.replace('k', str(k)) row, col = replace_k.split('_') return row, col
e5d27349c0cf9db28841f4bdd6e606257ecd9ca5
34,174
from typing import List import glob def get_html_files(src: str) -> List[str]: """Get all the HTML file names in the source directory""" _html_files = glob.glob(f"{src}/*.html") return _html_files
7c8f48166f28eb51dcc6d31ed6bdd9ca25b7218c
34,177
def RGBDimtoRGB(R, G, B, Dim): """ convert RGBDim to RGB color :warning: When Dim is 0, no more color component information encoded :warning: Prefer RGBDimtoHSV function :param R: red value (0;255) :param G: green value (0;255) :param B: blue value (0;255) :param Dim: brightness value (0.0;100) -> can be specified over 100% if needed (beware of saturation) :return: RGB tuple (0;255) """ bright = Dim / 100.0 return tuple(int(i * bright) for i in (R, G, B))
c1996c8c27a445f623ef5566497318bf90cd3c97
34,179
def _format_datetime_for_js(stamp): """Formats time stamp for Javascript.""" if not stamp: return None return stamp.strftime("%Y-%m-%d %H:%M:%S %Z")
a305c9c64f1ec9de0bd99181f14dedebae8cf940
34,182
def constrain(value, min_value, max_value): """ Constrains the `value` to the specified range `[min_value, max_value]` Parameters ---------- `value` : The value to be constrained `min_value` : The lower limit of range (inclusive) `max_value` : The upper limit of range (inclusive) Returns ------- `min_value` : if `value` is less than `min_value` `max_value` : if `value` is greater than `max_value` `value` : otherwise Examples -------- >>> constrain(10, 20, 40) 20 >>> constrain(30, 20, 40) 30 >>> constrain(50, 20, 40) 40 """ return min(max(value, min_value), max_value)
230cb07a564f78c75ebe7978e6c3877722efd34a
34,183
def get_news(soup): """Gets bs object, returns list of bs object representing the articles in the news section of the webpage""" results = soup.find_all("article", class_="clanek col-12 mb-3 mt-3") return results
c6b55f49f468fd3cf93895cac13bd7a8683de2b9
34,185
import pickle def load_ranks_from_file(filename): """ Given a pickled rank file, returns ranks and inverse_ranks. """ with open(filename, 'rb') as f: content = pickle.load(f) return content['ranks'], content['inverse_ranks']
ff6823241c16bcc5f51dc788366291e47a9c1142
34,188
import json def global_extent(tiles): """ Compute the global raster extent from a list of tiles Args: tiles: list of config files loaded from json files Returns: (min_x,max_x,min_y,max_y) tuple """ min_x = None max_x = None min_y = None max_y = None # First loop is to compute global extent for tile in tiles: with open(tile, "r") as file: tile_cfg = json.load(file) size_x = tile_cfg["roi"]["x"] size_y = tile_cfg["roi"]["y"] size_w = tile_cfg["roi"]["w"] size_h = tile_cfg["roi"]["h"] if min_x is None or size_x < min_x: min_x = size_x if min_y is None or size_y < min_y: min_y = size_y if max_x is None or size_x + size_w > max_x: max_x = size_x + size_w if max_y is None or size_y + size_h > max_y: max_y = size_y + size_h return (min_x, max_x, min_y, max_y)
81e16f22fc1fce75b9583c5037a10d19851097ec
34,189
import yaml def read_yaml_data(yaml_file): """ read yaml file. Args: yaml_file: yaml file Returns: dict: yaml content of the yaml file """ with open(yaml_file, 'r', encoding="utf-8") as file: file_data = file.read() data = yaml.safe_load(file_data) return data
225c3caa8a8060eb3eab7af3b2e556dffb4c1a6f
34,190
def get_unique_peptides(peptides:list) -> list: """ Function to return unique elements from list. Args: peptides (list of str): peptide list. Returns: list (of str): list of peptides (unique). """ return list(set(peptides))
15ad1a70c0bf4269ce2f6d08032b384080e7c655
34,191
import logging def get_log_level(ll): """Get the logging level from the logging module. Defaults to ERROR if not found. :param ll: `str` The log level wanted. :returns: `int` The logging level. """ return getattr(logging, ll.upper(), logging.ERROR)
6fbb3ab5cdbef507faa883121a49a12529008441
34,195
def date_parser(dates): """Date Parser - changes dates to date format 'yyyy-mm-dd' Parameters ---------- dates: list of dates and times strings in the format 'yyyy-mm-dd hh:mm:ss' Returns ------- list: A list of only the dates in 'yyyy-mm-dd' format. """ data_format = [] #Empty list. for i in dates: #Iterate over elements of dates. x = i.split(" ")[0] #Split the strings in dates to get rid of the times. data_format.append(x) #append splitted strings to the empty list 'data_format' return data_format #Return the new list 'data_format'.
20a91662129edc38a3bd36ea4f39cd4dcb966ab3
34,196
def intfloat(x): """int . float (for convenience in command-line specification)""" return int(float(x))
9b75d32e209f30415d826ac7ea2e59f7a162cad7
34,198
def create_health_check(lock): """ Return health check function that captures whether the lock is acquired """ def health_check(): d = lock.is_acquired() return d.addCallback(lambda b: (True, {"has_lock": b})) return health_check
fc77f8c42f271fd98051f91771d99ccc8aec7a9e
34,199
def check_batch_state(state, max_len, pad_token): """Check batch of states and left pad or trim if necessary. Args: state (list): list of of L decoder states (B, ?, dec_dim) max_len (int): maximum length authorized pad_token (int): padding token id Returns: final (list): list of L decoder states (B, pred_len, dec_dim) """ final_dims = (len(state), max_len, state[0].size(1)) final = state[0].data.new(*final_dims).fill_(pad_token) for i, s in enumerate(state): curr_len = s.size(0) if curr_len < max_len: final[i, (max_len - curr_len) : max_len, :] = s else: final[i, :, :] = s[(curr_len - max_len) :, :] return final
c4b4f16fe71daa61ac6afba4935ae94b51a3516d
34,200
def get_clicked_pos(pos, rows, width): """ Identify spot which was clicked on. Basically we need to find the position of mouse on the screen in the terms of our grid. :param pos: position of click from pygame :param rows: :param width: :return: """ gap = width // rows y, x = pos row = y // gap col = x // gap return row, col
def409071e95b5a48f287be6d3c7d4e2b7c4adf3
34,201
def target_label_split(label): """ Split a target label into a tuple of it's parts: (fsname, target type, index) """ a = label.rsplit("-", 1) if len(a) == 1: # MGS return (None, a[0][0:3], None) return (a[0], a[1][0:3], int(a[1][3:], 16))
58e7333f555712f3a1afffe3d31e35db4bb8c40b
34,204
def _ResolveMsg(msg_type, msg_map): """Fully resolve a message type to a name.""" if msg_type in msg_map: return msg_map[msg_type] else: return '[Unknown message %d (0x%x)]x' % (msg_type, msg_type)
b8bd2b9aa29bbb88ee6f70038f5f97cf2bea908e
34,205
def round_digits( v: float, num_digits: int = 2, use_thousands_separator: bool = False ) -> str: """ Round digit returning a string representing the formatted number. :param v: value to convert :param num_digits: number of digits to represent v on None is (Default value = 2) :param use_thousands_separator: use "," to separate thousands (Default value = False) :returns: str with formatted value """ if (num_digits is not None) and isinstance(v, float): fmt = "%0." + str(num_digits) + "f" res = float(fmt % v) else: res = v if use_thousands_separator: res = "{0:,}".format(res) # type: ignore res_as_str = str(res) return res_as_str
38873d5dd6d1cee6cf48b9ff2f046e59007822fa
34,206
from typing import Sequence from typing import Hashable def filter_dict(src: dict, keys_to_filter: Sequence[Hashable]) -> dict: """ Filters dictionary by keys_to_filter set. Parameters ---------- src: dict Source dictionary. keys_to_filter: Sequence[Hashable] Set of keys that should be in the final dictionary. Returns ------- dict Filtered source dictionary. """ return {key: value for key, value in src.items() if key in keys_to_filter}
92ee67c92e07b110122a2adb0b0084991e978415
34,208
def oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("12") 10 >>> oct_to_decimal(" 12 ") 10 >>> oct_to_decimal("-45") -37 >>> oct_to_decimal("2-0Fm") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("19") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function """ oct_string = str(oct_string).strip() if not oct_string: raise ValueError("Empty string was passed to the function") is_negative = oct_string[0] == "-" if is_negative: oct_string = oct_string[1:] if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string): raise ValueError("Non-octal value was passed to the function") decimal_number = 0 for char in oct_string: decimal_number = 8 * decimal_number + int(char) if is_negative: decimal_number = -decimal_number return decimal_number
ef933850d533c499b126d024d1cae1f86944248e
34,209
def crop_image_nparts(input_image, n_parts_x, n_parts_y=None): """ Divide an image into n_parts_x*n_parts_y equal smaller sub-images. """ # if n_parts_y not specified, assume we want equal x,y if not n_parts_y: n_parts_y = n_parts_x xsize, ysize = input_image.size x_sub = int(xsize / n_parts_x) y_sub = int(ysize / n_parts_y) sub_images = [] for ix in range(n_parts_x): for iy in range(n_parts_y): box = (ix * x_sub, iy * y_sub, (ix + 1) * x_sub, (iy + 1) * y_sub) region = input_image.crop(box) sub_images.append(region) return sub_images
f12e4f1ee85411f1f2b38042d47894f3d8dafda6
34,210
from typing import Union from typing import Sequence def format_as_iter(vals: Union[int, Sequence[int]], iters_per_epoch: int, time_scale: str): """Format data to be at iteration time scale. If values are negative, they correspond to the opposite time scale. For example if `time_scale="epoch"` and `val=-1`, `val` corresponds to 1 iteration. Args: vals (`int(s)`): Values to format. iters_per_epoch (int): Number of iterations per epoch. time_scale (str): Time scale of current values. Returns: int: Time (positive int) formatted in iteration format """ assert time_scale in ["epoch", "iter"] single_value = not isinstance(vals, Sequence) if single_value: vals = [vals] epoch_convention = (time_scale == "epoch" and all(x >= 0 for x in vals)) or ( time_scale == "iter" and all(x <= 0 for x in vals) ) if epoch_convention: vals = type(vals)([iters_per_epoch * abs(x) for x in vals]) else: vals = type(vals)([abs(x) for x in vals]) if single_value: return vals[0] else: return vals
f9971ad6227b497834e4667f101a56c49b71507e
34,216
import math def deg2rad(degrees): """Degrees to radians """ radians = math.pi * degrees/180.0 return radians
ffb796655e1181310d222297071187c2865b1d24
34,219
def get_value(config, key): """Get value from (possibly nested) configuration dictionary by using a single string key as used for the commandline interface (list of keys delimited by '-' or '_'). """ keys = key.replace('-', '_').split('_') for key in keys[:-1]: config = config[key] return config[keys[-1]]
d0ef4c16cb3fb202956c0ab14d8ade843d68d7cc
34,222
import re def check_domain_valid(submission): """ Check if a submission is a valid domain. :param submission: The submission to be checked :return: True if 'submission' is a valid domain, otherwise False """ return re.match("^([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*(?:\\.[A-Za-z]{2,}))$", submission) is not None
c6f011242cad39d187cbc723f006ae0cb3087dea
34,223
def compute_chi_eff(m1,m2,s1,s2): """ Compute chi effective spin parameter (for a given component) -------- m1 = primary mass component [solar masses] m2 = secondary mass component [solar masses] s1 = primary spin z-component [dimensionless] s2 = secondary spin z-component [dimensionless] """ return (m1*s1+m2*s2)/(m1+m2)
ee7d619c282a2d48a68651b896024c3c2e3b4d72
34,224
def appropriate_partition(distance): """Find appropriate partition of a distance into parts. Parameters ---------- distance : float Traveled distance in meters Returns ------- segment_distance : float Appropriate length of segments in which we split the total distance """ if distance < 5000: return 400 elif distance < 20000: return 1000 elif distance < 40000: return 2000 elif distance < 100000: return 5000 else: return 10000
35d7888166ea416d470e106fbbfc3e07af6671e1
34,227
import itertools def all_subsets(A, strict=True, null=True): """ Return all subsets of A (list/tuple/etc). If strict is False, result includes A, if null is True, includes (). """ n = len(A) min = 0 if null else 1 max = n if strict else n + 1 out = [] for m in range(min, max): out.append(itertools.combinations(A, m)) return itertools.chain(*out)
c26e035d6d1b38c6a6ac153ee883566d8ed513fb
34,228
from typing import Mapping from typing import Tuple def mapping_sort_key(prediction: Mapping[str, str]) -> Tuple[str, ...]: """Return a tuple for sorting mapping dictionaries.""" return ( prediction["source prefix"], prediction["source identifier"], prediction["relation"], prediction["target prefix"], prediction["target identifier"], prediction["type"], prediction["source"], )
ce506f536ea2321f7c67b2703cbf09fde9d13275
34,232
import base64 import hashlib def compute_md5_for_string(string): """Compute MD5 digest over some string payload""" return base64.b64encode(hashlib.md5( string.encode('utf-8')).digest()).decode('utf-8')
6f4af502ec5a14551ba5a22cd7df048ccd7fcc8a
34,233
def fits_identify(origin, *args, **kwargs): """Check whether given filename is FITS.""" return (isinstance(args[0], str) and args[0].lower().split('.')[-1] in ['fits', 'fit'])
10257681795a4f0979caf33775e700b1666e156a
34,236
def copy_column(column, schema): """ Safely create a copy of a column. """ return column.copy(schema=schema)
1842db07939a3d2aee7923e72230819afacd7751
34,238
def _unembed(tree_list): """Unembeds (or deletes) extra spaces at the end of the strings.""" unembedded = [] for line in tree_list: unembedded.append(line.rstrip()) return unembedded
c692f2f440b88a2a079b48f7ee1928f529136a15
34,247
def get_py_type(json_type): """ Given a JSON type return a corresponding Python type. If no type can be determined, return an empty string. """ if json_type in ("enum", "string", "File"): return "str" elif json_type == "boolean": return "bool" elif json_type == "array": return "list" elif json_type == "integer": return "int" elif json_type == "int": return "int" elif json_type == "number": return "float" elif json_type == "void": return "None" return ""
bf738c5257022019ec26ac89a45ba098e129afcd
34,252