content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import random def integer(start, end, steps=1): """ Function integer Return a random integer Inputs: - start: minimum allowed value - end: maximum allowed value (inclusive) - steps: the interval from which to select the random integers Output: a string containing a random integer """ if type(steps) == float or steps < 1: steps = 1 return str(int(random.randrange(start, end + 1, steps)))
99333decb006a547229eaf7b950a803cc8a450b0
30,315
import re def cleanlines(lines): """Remove comments and blank lines from splitlines output.""" # Clean comments. matchRE = re.compile('(.*?)(//|%|#)') for i in range(len(lines)): line = lines[i] match = matchRE.match(line) if match is not None: lines[i] = match.group(1) # Clean blank lines. return [x.strip() for x in lines if len(x.strip()) > 0]
2971936b5b7098983aad3af40c82d337f998f5a1
30,317
import torch def apply_trans(x, trans): """Apply spatial transformations to input Attributes: x (torch.Tensor): Input Tensor trans (torch.nn.Module): Spatial Transformer module Returns: torch.Tensor: Output Tensor """ x = x.transpose(2, 1) x = torch.bmm(x, trans) x = x.transpose(2, 1) return x
152210b5f544d524aff94039ca1cb33dfdf1f9f5
30,318
import zlib def _adler32(fname): """Compute the adler32 checksum on a file. :param fname: File path to the file to checksum :type fname: str """ with open(fname, 'rb') as f: checksum = 1 while True: buf = f.read(1024*1024*8) if not buf: break checksum = zlib.adler32(buf, checksum) return checksum
7e7b37d39cdd7dbd1795aa25b48460350e121dae
30,319
def event_is_virtual(event): """ Determine if event is virtual. Produces a boolean.""" return 'location' in event and \ '@type' in event['location'] and \ event['location']['@type'] == "VirtualLocation"
6fb246f65ff87e38fc19a7f619b7f1a521f49060
30,320
def time_str_from_datetime_str(date_string: str) -> str: """ Extracts the time parts of a datetime. Example: 2019-12-03T09:00:00.12345 will be converted to: 09:00:00.12345 :param date_string: :return: """ return date_string.split('T')[1]
cd08fc6cb55854cacf1620aea4b02692b7925cd7
30,322
def create_regcontrol_settings_commands(properties_list, regcontrols_df, creation_action='New'): """This function creates a list of regcontrol commands, based on the properties list and regcontrol dataframe passed Parameters ---------- properties_list regcontrols_df creation_action Returns ------- list """ regcontrol_commands_list = [] if properties_list is None: properties_list = ["vreg", "band"] for index, row in regcontrols_df.iterrows(): command_string = f"{creation_action} RegControl.{row['name']}" for property_name in properties_list: command_string = command_string + f" {property_name}={row[property_name]}" regcontrol_commands_list.append(command_string) return regcontrol_commands_list
5095ad7a3aa5ee1e8ada5f7e9333f5a7008511ca
30,323
def _getProfile(APIConn, screenName=None, userID=None): """ Get data of one profile from the Twitter API, for a specified user. Either screenName string or userID integer must be specified, but not both. :param APIConn: authenticated API connection object. :param screenName: The name of Twitter user to fetch, as a string. :param userID: The ID of the Twitter user to fetch, as an integer. Cannot be set if screenName is also set. :return tweepy.User: instance for requested Twitter user. """ assert ( screenName or userID ), "Expected either screenName (str) or userID (int) to be set." assert not ( screenName and userID ), "Cannot set both screenName ({screenName}) and userID ({userID}).".format( screenName=screenName, userID=userID ) if screenName: print("Fetching user: @{screenName}".format(screenName=screenName)) params = {"screen_name": screenName} else: print("Fetching user ID: {userID}".format(userID=userID)) params = {"user_id": userID} return APIConn.get_user(**params)
d41f48197c741a4a4f69dad47fc50c2f28fc30ee
30,325
def slicer(shp, idxs, var=None): """Obtain a list of slicers to slice the data array according to the selected data Parameters ---------- shp : tuple Data shape idxs : iterable Indexes of the selected data var : int, optional Data to be selected, in case of multidimensional sample, by default None Returns ------- slice Slices of the data """ # It is assumed that the first dimension is the samples slc = [] # Iterate over the datasets for idx in idxs: idx.sort() if not var: slc += [tuple([idx] + [slice(None)] * (len(shp) - 1))] else: slc += [tuple([idx] + [slice(None)] * (len(shp) - 2) + [var])] return tuple(slc)
cbe0d3ab7d376a97206dfe899550fd5345a30df4
30,328
def extract_features_in_order(feature_dict, model_features): """ Returns the model features in the order the model requires them. """ return [feature_dict[feature] for feature in model_features]
adc067d35ae61cdd4b5bf0a4199662a6d94ce6f9
30,330
def _IndentString(source_string, indentation): """Indent string some number of characters.""" lines = [(indentation * ' ') + line for line in source_string.splitlines(True)] return ''.join(lines)
f85c2e18448497edcd764068ae9205ec4bbaec5d
30,335
def create_success_response(return_data): """ Creates a standard success response used by all REST apis. """ count = 1 if isinstance(return_data, list): count = len(return_data) return { 'meta': { 'error': False, 'count': count }, 'data': return_data }
0e1252317ebd838b03d680125b22ce1bf67c2c66
30,338
def GetMissingOwnerErrors(metrics): """Check that all of the metrics have owners. Args: metrics: A list of rappor metric description objects. Returns: A list of errors about metrics missing owners. """ missing_owners = [m for m in metrics if not m['owners']] return ['Rappor metric "%s" is missing an owner.' % metric['name'] for metric in missing_owners]
97deb68f1412b371ca1055e8a71a53408d8915d1
30,342
import torch def generate_batch(batch): """ Since the text entries have different lengths, a custom function generate_batch() is used to generate data batches and offsets, which are compatible with EmbeddingBag. The function is passed to 'collate_fn' in torch.utils.data.DataLoader. The input to 'collate_fn' is a list of tensors with the size of batch_size, and the 'collate_fn' function packs them into a mini-batch. Pay attention here and make sure that 'collate_fn' is declared as a top level def. This ensures that the function is available in each worker. Output: text: the text entries in the data_batch are packed into a list and concatenated as a single tensor for the input of nn.EmbeddingBag. offsets: the offsets is a tensor of delimiters to represent the beginning index of the individual sequence in the text tensor. label: a tensor saving the labels of individual text entries. """ label = torch.tensor([entry[0] for entry in batch]) text = [entry[1] for entry in batch] offsets = [0] + [len(entry) for entry in text] offsets = torch.tensor(offsets[:-1]).cumsum(dim=0) text = torch.cat(text) return text, offsets, label
c33bd4c78f4715ef08fc18c1eb9f78540301138b
30,343
def make_name(image): """Format output filename of the image.""" return image['name'][:-4]
ab51f714052528c7dc16cd68b80c1c9b889adaea
30,351
def is_quoted(str): """ whether or not str is quoted """ return ((len(str) > 2) and ((str[0] == "'" and str[-1] == "'") or (str[0] == '"' and str[-1] == '"')))
b079bd4a7f3ac8814250faf522d9e38718fce986
30,353
from typing import List from typing import Dict def track_path_to_header( book_id: int, book_url: str, book_title: str, gpx_name: str ) -> List[Dict]: """ Format the header breadcrumbs - refer to templates/layout.html. Args: book_id (int): Book ID based on the 'shelf' database table. book_url (str): Book URL based on the 'shelf' database table. book_title (str): Book title based on the 'shelf' database table. gpx_name (str): Name of the GPX file in the /tracks directory WITHOUT file extension. Returns: List of dicts. """ return [ {"title": "Stories", "url": "/stories"}, { "title": book_title, "url": "/stories/" + str(book_id) + "/" + book_url, }, { "title": gpx_name.replace("_", " ") # no URL because it is the current one }, ]
28c478da73d73fdf089c169e3d8bd570cabcf58d
30,358
def calcFallVelocity(rho_s, D_s): """ Calculates fall velocity of sediment. Paramters --------- rho_s : sediment density [kg/m^3] D_s : sediment diameter [m] Returns ------- w - fall velocity of sediment [m/s] Notes ----- Equation used is from Ferguson and Church [2004]. C1 and C2 values correspond to fits for natural grains. """ Sd = (rho_s - 999.97)/999.7 C1 = 18.; C2 = 1.0; w = Sd*9.81*D_s**2 / ( C1*1e-6 + (0.75*C2*Sd*9.81*D_s**3)**0.5 ) return w
74f07f6e3448d36f9adf0feb196605f86d70f1bd
30,363
def total_duration_parser(line): """ Parses lines of the following form: Total duration: 5248.89s :param line: string :return: float containing total duration in seconds """ try: return float(line.rstrip('s')[len('Total duration:'):].strip()) except: return 0.
30cc8da46293654b8d4001dbd708160ba208bacb
30,367
from typing import Callable def newton_step(f: Callable[[float], float], f_prime: Callable[[float], float], x_0: float) -> float: """ Performs a single iteration of Newton's Method Parameters ---------- f The function to determine the root of. f_prime The derivative of the function to determine the root of. x_0 The starting point for determining the root from. """ return x_0 - f(x_0)/f_prime(x_0)
b877d0a70ba8557b79f1ae99ef4e1b815d0778ff
30,369
def lucas(n): """Function that provides the nth term of lucas series.""" x, y = 2, 1 for i in range(n - 1): x, y = y, x + y return x
6d40e67ce8dd682bb26f9bd16d2dd34d3d1bf541
30,381
def gas_constant(R, mu): """ Gas constant of natural gas, J/(kg*K) :param R: (float) Universal gas constant, J/(kmole*K) :param mu: (float) Molar mass of natural gas, kg/kmole :return: (float) Gas constant of natural gas, J/(kg*K) """ return R / mu
05587e637635ea6262541347966ec18e05bf6fba
30,383
def engine_options_from_config(config): """Return engine options derived from config object.""" options = {} def _setdefault(optionkey, configkey): """Set options key if config key is not None.""" if config.get(configkey) is not None: options[optionkey] = config[configkey] _setdefault('echo', 'SQLALCHEMY_ECHO') _setdefault('pool_size', 'SQLALCHEMY_POOL_SIZE') _setdefault('pool_timeout', 'SQLALCHEMY_POOL_TIMEOUT') _setdefault('pool_recycle', 'SQLALCHEMY_POOL_RECYCLE') _setdefault('max_overflow', 'SQLALCHEMY_MAX_OVERFLOW') return options
9ece915beba58b080ad330f75197c466246fdfe2
30,387
def df_variables_info(df): """ This function gives information about the df: number of observations, variables, type and number of variables params: df is a dataframe from which we want the information return: NONE """ # Number of variables print('Number of variables:', df.shape[1]) # Number of observations print('Number of observations:', df.shape[0]) # Summary of the type of variables in the dataframe print('Type of variables in the dataframe: \n', df.dtypes.value_counts(),'\n') return None
b766299931398b4973f4bed2a8280b55397203aa
30,392
def _delete_duplicates(l, keep_last): """Delete duplicates from a sequence, keeping the first or last.""" seen=set() result=[] if keep_last: # reverse in & out, then keep first l.reverse() for i in l: try: if i not in seen: result.append(i) seen.add(i) except TypeError: # probably unhashable. Just keep it. result.append(i) if keep_last: result.reverse() return result
fa3d8bc3ef32899bcfedcff1376e3ecb75b5600d
30,395
def rindex(list, value): """Find the last-occurring index of `value` in `list`.""" for i in range(len(list) - 1, 0, -1): if list[i] == value: return i return -1
f4b91f3d8ae531f610806c68054b1075c73b0dcf
30,399
import math def atan_deg(value): """ returns atan as angle in degrees """ return math.degrees(math.atan(value) )
ad7f79e4ebbfc364bddb5f20afd01b8cf70f9c08
30,400
def _add_extension_assets(client, customer_id, language_code): """Creates new assets for the hotel callout. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. language_code: the language of the hotel callout feed item text. Returns: a list of asset resource names. """ operations = [] # Create a hotel callout asset operation for each of the below texts. for text in ["Activities", "Facilities"]: operation = client.get_type("AssetOperation") asset = operation.create asset.hotel_callout_asset.text = text asset.hotel_callout_asset.language_code = language_code operations.append(operation) asset_service = client.get_service("AssetService") # Issues the create request to create the assets. response = asset_service.mutate_assets( customer_id=customer_id, operations=operations ) resource_names = [result.resource_name for result in response.results] # Prints information about the result. for resource_name in resource_names: print( "Created hotel callout asset with resource name " f"'{resource_name}'." ) return resource_names
bc213f9be915845b9ebb977a8b10ec941a640089
30,402
import math def subtended_angle(size, distance): """ Return the subtended angle angle of a sphere with certain size and distance: https://en.wikipedia.org/wiki/Subtended_angle. Used to determine the size of the bounding box located at a certain position in the image. """ angle = math.fabs(size) / math.fabs(distance) return math.degrees(angle)
46b74d3fa14321e3f7004ec0fdcc6b8875abc50e
30,405
import csv def read(path): """ Returns list of dictionaries. All returned values will be strings. Will assume that first row of file contains column names. """ file = open(path, 'r', encoding = 'utf-8') reader = csv.reader(file, delimiter = '\t', quotechar = '', quoting = csv.QUOTE_NONE) result = [] header = reader.__next__() for values in reader: entry = {} for i in range(len(header)): entry[header[i]] = values[i] result.append(entry) file.close() return result
0506a59d28c9ee750dd6045217319097bfa9c662
30,406
def lab_monthly(dataframe): """ Extract monthly data from a labstat file Parameters: dataframe (dataframe): A dataframe containing labstat data Returns: dataframe """ dataframe['month'] = dataframe['period'].str[1:].copy().astype(int) dataframe['value'] = dataframe['value'].astype(int) dataframe = dataframe.loc[~dataframe['month'].isin([13])] return dataframe
440c8502558c7b3746814706b2c4267b87e9d399
30,410
def find_empty_square(board): """ Return a tuple containing the row and column of the first empty square False if no squares are empty """ for i, row in enumerate(board): for j, square in enumerate(row): if square == 0: return (i, j) return False
98b4b50527a33abec3134a22c5a9cff5a874b171
30,412
def user_can_edit_setting_type(user, model): """ Check if a user has permission to edit this setting type """ return user.has_perm("{}.change_{}".format( model._meta.app_label, model._meta.model_name))
cfc2cde620718635493374ef62966539f25ba362
30,418
def verify_notebook_name(notebook_name: str) -> bool: """Verification based on notebook name :param notebook_name: Notebook name by default keeps convention: [3 digit]-name-with-dashes-with-output.rst, example: 001-hello-world-with-output.rst :type notebook_name: str :returns: Return if notebook meets requirements :rtype: bool """ return notebook_name[:3].isdigit() and notebook_name[-4:] == ".rst"
87a839ddffc32613d74775bf532953c8263093cd
30,421
import json def str_to_json(s): """ Deserialize JSON formatted string 's' to a dict. Args: s: JSON string to be deserialized Examples: >>> str_to_json('{}') {} >>> str_to_json('{"a": 1, "c": {"d": 3}, "b": 2}') == {u'a': 1, u'c': {u'd': 3}, u'b': 2} True >>> str_to_json('a') Traceback (most recent call last): ... ValueError: No JSON object could be decoded """ return json.loads(s.decode())
95feed74f9ddda9f3db8b5e03d52bf19fe1538fe
30,423
import re def valid_mac(mac=None): """Validates Ethernet MAC Address :param: mac address to validate :type: str :return: denotes true if MAC proper format else flase :rtype: bool """ if mac is None or mac.strip() == "": return False mac = mac.strip() return re.match("^([0-9A-Fa-f]{2}[:.-]?){5}([0-9A-Fa-f]{2})$", mac)
356f8ce8e16fb25271aa2f1dea845febd19864cb
30,426
def hasmethod(obj, methodname): """Does ``obj`` have a method named ``methodname``?""" if not hasattr(obj, methodname): return False method = getattr(obj, methodname) return callable(method)
a71dcdac40d97de91bc789068a885cab467a6f48
30,429
def _batch_name(split_name, offset, dataset): """Returns the file name for a given batch. Args: split_name: "train"|"test" offset: batch index (0-indexed) dataset: "cifar10"|"cifar100" """ if dataset == 'cifar10': if split_name == 'train': return 'data_batch_%d' % (offset + 1) # 1-indexed. else: return 'test_batch' else: return split_name
b360268ef38bb5fee5fa02b36b19c7d0ae6a1ab7
30,432
from typing import Dict from typing import List def create_dirs_list(all_confs: Dict[int, Dict[str, list]]) -> List[dict]: """Creates required directories for a project. Uses the information provided by `config_info()` to create directories according to the user's configuration file. Args: all_confs (Dict[str, list]): A `dict` of configuration information. This should be created using the `config_info()` function. Returns: List[dict]: A list of directories to create. Each `item` in the list is a `dict` that contains scene names as `keys` and scene elements as `values`. Scene elements are what `good-bot` will record or create. """ if not isinstance(all_confs, dict): raise TypeError( "create_dirs_list(): This function takes a dictionnary as an input." ) dirs_list: List[dict] = [] for ( scene_number, contents, ) in all_confs.items(): # Keys are scene numbers, values is the content # Those dirs are always created to_create: List[str] = ["asciicasts", "embeds", "gifs", "videos"] for content_type, instructions in contents.items(): if instructions: # There are items in the list. to_create.append(content_type) # Things like the editor are added here. # Read has been added in the previous block if "read" in to_create: to_create.append("audio") # MP3 files dirs_list.append({f"scene_{scene_number}": to_create}) return dirs_list
3ca08e48a5e27bfcb9c3d0d751cf7efc553ea34b
30,435
from datetime import datetime def parse_time(line): """ All logging lines begin with a timestamp, parse it and return the datetime it represents. Example: 2016-04-14 14:50:33,325 :param line: the log line containing time :return: native datetime """ return datetime.strptime(line[:19], '%y-%m-%d %h:%M:%S')
40d0e755693bd93a0d1ecf1969b39a5c001b1cca
30,438
from typing import List from typing import Dict def construct_rows(header: list, rows: list) -> List[Dict]: """Construct a list of csv row dicts.\n Arguments: header {list} -- csv header\n rows {list} -- csv contents\n to warp if there is only a single row, e.g. [row]\n Returns: List[Dict] -- a list of csv rows\n """ row_dicts = [{k: v for k, v in zip(header, row)} for row in rows] return row_dicts
771b2dfde99a8b517331695d160eb9f809e4933c
30,447
import requests import zipfile import io def get_zip_file(url): """ Get zip file from provided URL """ with requests.get(url, stream=True) as f: z = zipfile.ZipFile(io.BytesIO(f.content)) return z
2db522396d4ffde212c858b3544cfaa99b03bba0
30,452
def parse_rule(l, cats): """Parses a sound change rule or category. Given a line l with the format 'a > b / c_d ! e_f', produces a dict of the form { 'from': 'a', 'to': 'b', 'before': 'c', 'after': 'd', 'unbefore': 'e', 'unafter': 'f' }. If l is of the form 'a > b / c_d ! e_f | g > h / i_j ! k_l', the output is a list of the '|' delimited rules. If l is of the form 'a = b c d', the output is a dict of the form { 'cat_name': 'a', 'category': ['b', 'c', 'd'] }. Category names in curly brackets are expanded. Args: l: The line of text to parse. cats: The dict of categories to use in the rule. Returns: A dict representing either a sound change rule or category, or a list of several sound changes. """ word_start = r'(?<=^|\s)' word_end = r'(?=$|\s)' out = {} if len(l.split(' = ')) == 2: # If there is an equals sign, it's a category out['cat_name'] = l.split(' = ')[0].strip() category = l.split(' = ')[1] # expand categories for c in cats: category = category.replace('{' + c + '}', ' '.join(cats[c])) out['category'] = category.split() else: if len(l.split(' | ')) > 1: # It's a list of sound changes return [parse_rule(ll, cats) for ll in l.split(' | ')] # Otherwise, it's a sound change rule try: # Attempt to set 'from' and 'to'. If there isn't a ' > ', it will # raise an IndexError when trying to set 'to', so 'from' will be # set, but 'to' will not. This could be used when parsing a rule to # be used as a search pattern, and not as a sound change. Need to # split on ' / ' and ' ! ' in case it is being used in this way. out['from'] = l.split(' > ')[0].split(' / ')[0].split(' ! ')[0] # Treat '0' like '' if out['from'] == '0': out['from'] = '' out['to'] = l.split(' > ')[1].split(' / ')[0].split(' ! ')[0] # Treat '0' like '' if out['to'] == '0': out['to'] = '' except IndexError: pass try: # Attempt to set 'before' and 'after'. If there isn't a ' / ', it # will raise an IndexError, and neither will be set. If there isn't # a '_', it will raise an IndexError when trying to set 'after', so # 'before' will be set, but 'after' will not. out['before'] = l.split(' / ')[1].split('_')[0].split(' ! ')[0] out['before'] = out['before'].replace('#', word_start) out['after'] = l.split(' / ')[1].split('_')[1].split(' ! ')[0] out['after'] = out['after'].replace('#', word_end) except IndexError: pass try: # Attempt to set 'unbefore' and 'unafter'. Same comments apply as # for 'before' and 'after'. Note that the negative conditions must # come after the positive conditions, if both exist. out['unbefore'] = l.split(' ! ')[1].split('_')[0] out['unbefore'] = out['unbefore'].replace('#', word_start) out['unafter'] = l.split(' ! ')[1].split('_')[1] out['unafter'] = out['unafter'].replace('#', word_start) except IndexError: pass return out
db9239fcf8d13d8884dd57a351e312de4caf2c61
30,455
import re from typing import Counter def get_term_frequencies(series, min_str_len=1, ngram=1): """ Get number of occurence of each term in the given pandas series Parameters ---------- series: pandas series Series to extract the term frequencies from min_str_len: int, optional (default value=1) Minimum string length for a word ngram: int, optional (default value=1) Number of words to get frequency from. Return ------- Python dict ({word:frequency}) """ text = " ".join(series.values.astype(str)) regex = re.compile(r"\w+{}".format(r" \w+"*(ngram-1))) words = re.findall(regex, text.lower()) words = [w for w in words if len(w) >= min_str_len] word_dict = Counter(words) return dict(word_dict)
560247a4fa3a6a1321caf9eadd45ba889eb517cc
30,456
from typing import List from typing import Dict def ids_to_models(model_ids: List[str]) -> Dict[str, List[str]]: """ Convert model IDs (MODEL_NAME-MODEL_VERSION) to a dictionary with its keys being the model names and its values being lists of the associated versions for each given model name. """ models = {} for model_id in model_ids: model_name, model_version = model_id.rsplit("-", maxsplit=1) if model_name not in models: models[model_name] = [model_version] else: models[model_name].append(model_version) return models
5a2b3bdc1361954a78630ca8bac4ebd0aefe8293
30,459
def _flatten(list_of_lists): """ Turns a nested list of lists ([a,[b,c]]) into a flat list ([a,b,c]). """ out = [] if type(list_of_lists) is int: return [list_of_lists] for item in list_of_lists: if type(item) is int: out.append(item) elif type(item) is list: out += _flatten(item) return out
8b2489d18a277e15e6f8c67baad70ff874c6e2bf
30,460
def get_nested(dct, key_pattern): """ Get value(s) from a nested dict Args: dct: dict having str keys and values which may be other `dct`s key_pattern: str giving dotted key Returns the value. Note that if key_pattern does not go to full depth then a dict is returned. """ d = dct patt_parts = key_pattern.split('.') for kp in patt_parts: if kp in d: d = d[kp] else: raise KeyError("No such key '%s'" % key_pattern) return d
4e7de6f56a6bcc62fc41b377f9ba2b144ac5627d
30,462
def sw_update_strategy_db_model_to_dict(sw_update_strategy): """Convert sw update db model to dictionary.""" result = {"id": sw_update_strategy.id, "type": sw_update_strategy.type, "subcloud-apply-type": sw_update_strategy.subcloud_apply_type, "max-parallel-subclouds": sw_update_strategy.max_parallel_subclouds, "stop-on-failure": sw_update_strategy.stop_on_failure, "state": sw_update_strategy.state, "created-at": sw_update_strategy.created_at, "updated-at": sw_update_strategy.updated_at} return result
93e8da29292998a37d031d6087bb0afba73fc995
30,468
def is_decimal_amount(string: str) -> bool: """Checks if string is a decimal amount (e.g. 1/2, 1/4, etc..) Args: string: string to be checked. Returns: True if string is a decimal amount, False otherwise. """ if "/" not in string or len(string.split("/")) != 2: return False string_split = string.split("/") return string_split[0].isnumeric() and string_split[1].isnumeric()
5b820eb8586b0eee94c9b122a20f0a7442111777
30,470
def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default
d0b38f828dec28cd9ae7d251fcb3bb0bbf324264
30,471
def institutions(cur): """Returns prototype and agentids of institutions Parameters ---------- cur: sqlite cursor sqlite cursor Returns ------- sqlite query result (list of tuples) """ return cur.execute('SELECT prototype, agentid FROM agententry ' 'WHERE kind = "Inst"').fetchall()
e02233b997cba0a14f1bdcfcecf720deb9b4a494
30,474
def format_string(indices): """Generate a format string using indices""" format_string = '' for i in indices: format_string += ', %s' % (i) return format_string
5bc61727f74b97648961e7b9ccf8299a9680648b
30,479
def element_wise_product(X, Y): """Return vector as an element-wise product of vectors X and Y""" assert len(X) == len(Y) return [x * y for x, y in zip(X, Y)]
e01ec3720ac6b2fa06cca1186cf1a5a4d8703d38
30,480
def get_schedule_config(config): """Get all the config related to scheduling this includes: - Active Days - Start Time - End Time It will also convert the hours and minute we should start/end in to ints. Args: config (ConfigParser): ConfigParser object used to get the config. Returns: dict: Containing the active days, start and end times. """ active_days_list = [ day.strip() for day in config.get("schedule", "active_days").split(",") ] start_time_hour, start_time_minute = config.get("schedule", "start_time").split(":") end_time_hour, end_time_minute = config.get("schedule", "end_time").split(":") return { "active_days": active_days_list, "start": {"hour": int(start_time_hour), "minute": int(start_time_minute)}, "end": {"hour": int(end_time_hour), "minute": int(end_time_minute)}, }
d362a44e80f5ae8bca5ab5ac7fe164777beae1ed
30,486
def p_empty_or_comment(line, comment='#'): """Predicate matching strings that are not empty and don't start with a comment character. For best results, the line should no longer contain whitespace at the start.""" return len(line) and not line.startswith(comment)
d0eef18237b0cac9f019d866d48d02813b1c2e95
30,489
def rowcol_to_index(row, col, width): """Convert row major coordinates to 1-D index.""" return width * row + col
cc9bce2ba17337025e9982865abdc63f4ad90658
30,490
def accuracy_boolean(data, annotation, method, instance): """ Determine whether method output is correct. Parameters ---------- data: color_image, depth_image annotation: Annotation from blob_annotator method: function[instance, data] -> BoundingBox instance: instance of benchmark Returns ------- found, missed, extra """ ## Prediction bounding_boxes = method(instance, *data) prediction = bool(len(bounding_boxes)) ## Expected expected = bool(len(annotation.findall('object'))) ## Calculate accuracy found = int(prediction == expected) missed = 1 - found extra = 0 return found, missed, extra
c28ef0b521895d4eef2a996e376cf0853b4a809a
30,491
import random def dummy_decision(board): """ make a random dummy move """ legal_moves = list(board.legal_moves) return random.choice(legal_moves)
8c44acf1aff245ed532e48c35e440440b6ddcaef
30,493
def leia_int(txt): """ -> Verifica se o valor digitado é numérico :param txt: mensagem a ser mostrado para o usuário :return: retorna o valor digitado pelo o usuário, caso seja um número """ while True: num = input(txt) if num.isnumeric(): break else: print('\033[31;1mERRO! Digite um número.\033[m') return num
f6a1c7104706e5a181a73aacd43f91a75df3e3f1
30,496
def address_column_split(a): """ Extracts city and state in an address and provides separate columns for each """ asplit = a.split(",") city = asplit[0].split()[-1] state = asplit[1].split()[0] return city, state
539123969beb28f2623466db193077f4351d04cb
30,502
def derivative(f, h): """(function, float) -> function Approximates the derivative of function <f> given an <h> value. The closer <h> is to zero, the better the estimate """ return lambda x: (f(x + h) - f(x)) / h
1dbb4035580f0bbb16339ee38ba863a2af144b63
30,503
def nextDWord(offset): """ Align `offset` to the next 4-byte boundary. """ return ((offset + 3) >> 2) << 2
4c51fdf80b2f684645fee85755549c46208361ae
30,510
import math def dist(p1, p2): """ Returns distance between two any-dimensional points given as tuples """ return math.sqrt(sum([(i - j)**2 for i, j in zip(p1, p2)]))
6c57680ae32ea33aba591ab2fb75aabe41af1df5
30,512
def range_count(start, stop, count): """Generate a list. Use the given start stop and count with linear spacing e.g. range_count(1, 3, 5) = [1., 1.5, 2., 2.5, 3.] """ step = (stop - start) / float(count - 1) return [start + i * step for i in range(count)]
41d4e73e1cf85655a0df06c976d9187c9964dc59
30,524
def dens(gamma, pres, eint): """ Given the pressure and the specific internal energy, return the density Parameters ---------- gamma : float The ratio of specific heats pres : float The pressure eint : float The specific internal energy Returns ------- out : float The density """ return pres/(eint*(gamma - 1.0))
ae37519718d3019546a4775cf65ca6697397cf5f
30,527
def dodrawdown(df): """computes the drawdown of a time series.""" dfsum = df.cumsum() dfmax = dfsum.cummax() drawdown = - min(dfsum-dfmax) return drawdown
e45dbdd19238e04975d5d14beb6348b0a744ada9
30,531
def check_mol_only_has_atoms(mol, accept_atom_list): """Checks if rdkit.Mol only contains atoms from accept_atom_list.""" atom_symbol_list = [atom.GetSymbol() for atom in mol.GetAtoms()] return all(atom in accept_atom_list for atom in atom_symbol_list)
472f0c263df1c5306176a5e40e321513f72e7697
30,535
import re def apply_and_filter_by_regex(pattern, list_of_strings, sort=True): """Apply regex pattern to each string and return result. Non-matches are ignored. If multiple matches, the first is returned. """ res = [] for s in list_of_strings: m = re.match(pattern, s) if m is None: continue else: res.append(m.groups()[0]) if sort: return sorted(res) else: return res
26aa766dbd211ca04ec33ace5d0823b059005690
30,536
def merge_shapes(shape, merged_axis: int, target_axis: int) -> list: """ Merge two axes of a shape into one, removing `merged_axis` and multiplying the size of the `target_axis` by the size of the `merged_axis`. :param shape: The full shape, tuple or tf.TensorShape. :param merged_axis: The index of the axis to remove. :param target_axis: The index of the axis to add to. :return: A list representing the merged shape. """ shape = list(shape) shape[target_axis] *= shape[merged_axis] shape.pop(merged_axis) return shape
d2ca4f91f7a99f9cef232d163c36ccac0e89fa18
30,537
def is_on_border(bbox, im, width_border): """ Checks if object is on the border of the frame. bbox is (min_row, min_col, max_row, max_col). Pixels belonging to the bounding box are in the half-open interval [min_row; max_row) and [min_col; max_col). """ min_col = bbox[1] max_col = bbox[3] width_im = im.shape[1] if (min_col <= width_border) or (max_col >= width_im - width_border): return True else: return False
815dab6682f0c977ec2ad86522d41ec086423971
30,542
from datetime import datetime def get_rate_limit_info(headers): """ Get Rate Limit Information from response headers (A Dictionary) :returns: Dictionary of 'remaining' (int), 'limit' (int), 'reset' (time) """ ret = {} ret['remaining'] = int(headers.get('x-rate-limit-remaining')) ret['limit'] = int(headers.get('x-rate-limit-limit')) ret['reset'] = datetime.fromtimestamp(int(headers.get('x-rate-limit-reset'))) return ret
2478b21d71bff0021d102a78fa6a4149ff4b2d6c
30,545
def mysum(a, b): """ Add two numbers together. Parameters ---------- a, b : Number Numbers to be added together. Returns ------- Number The sum of the two inputs. """ return a + b
a64083ac9524cd20875967adbe2b378604be0187
30,546
def list_usage(progname, description, command_keys, command_helps, command_aliases): """ Constructs program usage for a list of commands with help and aliases. Contructs in the order given in command keys. Newlines can be used for command sections by adding None entries to command_keys list. Only one alias allowed per command. :param command_keys: list of keys or None to print help or empty lines :param command_helps: dict{key: help} :param command_aliases: dict{key: alias} :returns: usage string (multiline) """ dvars = {'prog': progname} dvars.update(vars()) result = [] result.append(description % dvars) for key in command_keys: if key in command_aliases: alias = ' (%s)' % command_aliases[key] else: alias = '' if key is not None: result.append(("%s%s" % (key, alias)).ljust(10) + ' \t' + command_helps[key]) else: result.append('') return '\n'.join(result)
3246c509eaea33e271b1dc3425a1cc49acb943a3
30,547
from typing import List def dromedary_to_pascal_case(text: str) -> str: """Convert from dromedaryCase to PascalCase.""" characters: List[str] = [] letter_seen = False for char in text: if not letter_seen and char.isalpha(): letter_seen = True characters.append(char.upper()) else: characters.append(char) return "".join(characters)
50b735ff1f44c30faa27251f85d902f1d2459ea6
30,551
def get_spaceweather_imagefile(if_path, if_date, if_filename, if_extension, \ verbose): """Returns a complete image filename string tailored to the spaceweather site string by concatenating the input image filename (if) strings that define the path, date, filename root, and the filename extension If verbose is truthy, then print the returned image filename string """ sw_imagefile = if_path + if_date + "_" + if_filename + if_extension if verbose: print("Output image file full path: \n{}\n".format(sw_imagefile)) return sw_imagefile
52fab5c964e28287c8cdd1f30208bc74a3e99d34
30,552
from pathlib import Path def find_lab(directory, utt_id): """Find label for a given utterance. Args: directory (str): directory to search utt_id (str): utterance id Returns: str: path to the label file """ if isinstance(directory, str): directory = Path(directory) ps = sorted(directory.rglob(f"{utt_id}.lab")) assert len(ps) == 1 return ps[0]
c3ca69e436456284b890b7de3aff665da756f044
30,553
from typing import Callable from typing import Iterable def multiply(func: Callable, *args, **kwargs): """ Returns a function that takes an iterable and maps ``func`` over it. Useful when multiple batches require the same function. ``args`` and ``kwargs`` are passed to ``func`` as additional arguments. """ def wrapped(xs: Iterable, *args_, **kwargs_) -> tuple: return tuple(func(x, *args_, *args, **kwargs_, **kwargs) for x in xs) return wrapped
97cab2f739d39ab2e933b11a84814df8ecc811cf
30,562
def upload_file_to_slack(slack_connection, file_name, channel_name, timestamp): """ Upload a file to Slack in a thread under the main message. All channel members will have access to the file. Only works for files <50MB. """ try: file_response = slack_connection.files_upload( file=file_name, filename=file_name, title=file_name, channels=channel_name, thread_ts=timestamp) print(f'{file_name} successfully uploaded.') except Exception as e: print(e) file_response = None print('File failed to upload.') return file_response
1922bf8d357881325fd861bc76827961c7ac4db8
30,566
def bitstr_to_int(a): """ Convert binary string to int """ return int(a, 2)
1188a2ff24b1bf6c70db9a458d39f08f44f006e8
30,567
def average(number1, number2, number3): """ Calculating the average of three given numbers Parameters: number1|2|3 (float): three given numbers Returns: number (float): Returning the statistical average of these three numbers """ return (number1 + number2 + number3) / 3.0
04102ee8646b6e5d2cfa9265771c4f4bdbe45d45
30,570
import ast def _convert_string_to_native(value): """Convert a string to its native python type""" result = None try: result = ast.literal_eval(str(value)) except (SyntaxError, ValueError): # Likely a string result = value.split(',') return result
eaeec2eda520e6342ee6b5f3ac523d44b1c06d53
30,575
def cmp(x, y) -> int: """ Implementation of ``cmp`` for Python 3. Compare the two objects x and y and return an integer according to the outcome. The return value is negative if ``x < y``, zero if ``x == y`` and strictly positive if ``x > y``. """ return int((x > y) - (x < y))
2609f78797ad778e0d0b9c40a568a3f03153dd2c
30,579
def update_taxids(input, updatedTaxids): """ Updates a map of sequenceIDs to taxIDs with information from merged.dmp Some of NCBI's taxonomy IDs might get merged into others. Older sequences can still point to the old taxID. The new taxID must be looked up in the merged.dmp file in order to be able to find the right node in the taxonomy tree. Parameters ---------- input : dict of dicts of sets The keys of the outer dicts are the sequence types, e.g. NC, GeneID or gi. Keys of the inner dict are OTUs or clades. Values of the inner dict are sets of taxIDs. updatedTaxids : dict Content of merged.dmp in form of a dict where key is current taxID and value the new taxID Returns ------- The original map, but some taxIDs might have been updated. """ for seqType in input: for seqID in input[seqType]: cur_taxid = input[seqType][seqID] if cur_taxid in updatedTaxids: input[seqType][seqID] = updatedTaxids[cur_taxid] return input
be6fe1579d83e8915712c8ea79baaf76ce0a8c9d
30,580
def parse_slice(useslice): """Parses the argument string "useslice" as the arguments to the `slice()` constructor and returns a slice object that's been instantiated with those arguments. i.e. input useslice="1,20,2" leads to output `slice(1, 20, 2)`. """ try: l = {} exec("sl = slice(%s)" % useslice, l) return l['sl'] except Exception: msg = ("Expected arguments consumable by 'slice' to follow " "option `-j`, found '%s'" % useslice) raise ValueError(msg)
471b31a6774127a68eca6619d36df8e0bee66f18
30,581
def predict_multiclass(model, x, *extra_xs): """ Predict a class (int in [0...(n classes - 1)]) for each input (first dim of `x`) using the classifier `model`. Args: model: multiclass classifier module that outputs "n classes" logits for every input sequence. x: input tensor. extra_xs: additional inputs of `model`. Returns Integer tensor of shape `(x.size(0),)` that contains the predicted classes. """ preds = model(x, *extra_xs).cpu() pred_classes = preds.argmax(dim=-1) return pred_classes
c351d672d2177cb668a67b6d81ac166fde38daa2
30,586
import torch def convert_2Djoints_to_gaussian_heatmaps_torch(joints2D, img_wh, std=4): """ :param joints2D: (B, N, 2) tensor - batch of 2D joints. :param img_wh: int, dimensions of square heatmaps :param std: standard deviation of gaussian blobs :return heatmaps: (B, N, img_wh, img_wh) - batch of 2D joint heatmaps (channels first). """ device = joints2D.device xx, yy = torch.meshgrid(torch.arange(img_wh, device=device), torch.arange(img_wh, device=device)) xx = xx[None, None, :, :].float() yy = yy[None, None, :, :].float() j2d_u = joints2D[:, :, 0, None, None] # Horizontal coord (columns) j2d_v = joints2D[:, :, 1, None, None] # Vertical coord (rows) heatmap = torch.exp(-(((xx - j2d_v) / std) ** 2) / 2 - (((yy - j2d_u) / std) ** 2) / 2) return heatmap
26607acb1f756b840a8b970ade0ccdf01bf286e9
30,587
import string import random def random_string(length=50): """Return a string of random letters""" chars = string.ascii_letters r_int = random.randint return "".join([chars[r_int(0, len(chars) - 1)] for x in range(length)])
b337045cc724d450f578fc890042dd5e4c849580
30,594
def istamil_alnum( tchar ): """ check if the character is alphanumeric, or tamil. This saves time from running through istamil() check. """ return ( tchar.isalnum( ) or tchar.istamil( ) )
605fc9c82b688e314201ba2be3a3cf9d06fb256d
30,595
def diff_lists(list_a, list_b): """ Return the difference between list_a and list_b. :param list_a: input list a. :param list_b: input list b. :return: difference (list). """ return list(set(list_a) - set(list_b))
3fac6e456827d567900d1c8dd14cb3fe7e4af0b7
30,597
from urllib.parse import urlparse def deluge_is_url( torrent_url ): """ Checks whether an URL is valid, following `this prescription <https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not>`_. :param str torrent_url: candidate URL. :returns: ``True`` if it is a valid URL, ``False`` otherwise. :rtype: bool """ try: result = urlparse( torrent_url ) return all([result.scheme, result.netloc, result.path]) except Exception as e: return False
4a4817dddb89800f8e9db7f80e31f58bff698c5b
30,600
def to_dict(block, keys=['hash', 'start', 'end', 'blockSize', 'version', 'prevHash', 'merkleRootHash', 'time', 'timestamp', 'nBits', 'nonce', 'nTransactions']): """ Return block attributes as dict Similar to block.__dict__ but gets properties not just attributes. """ # Create output dict bd = {} for k in keys: # Add each attribute with attribute name as key bd[k] = getattr(block, k) return bd
aa594edc52500347fb515c81c9abe8308c81ce04
30,604
def popcount(x): """ Count ones in the binary representation of number x Parameters ---------- x: Integer The number to be counted Returns ------- cnt: Integer The number of ones in the binary representation of number x """ cnt = 0 while x: x -= x & -x cnt += 1 return cnt
2198546d57be313268ba5f2700a8f7bb9b13518d
30,606
def origin(current, start, end, cum_extents, screen, moving): """Determine new origin for screen view if necessary. The part of the DataFrame displayed on screen is conceptually a box which has the same dimensions as the screen and hovers over the contents of the DataFrame. The origin of the relative coordinate system of the box is calculated here. >>> origin(0, 0, 0, [0, 4, 8, 12], 7, True) 0 >>> origin(4, 0, 2, [0, 4, 8, 12], 7, True) 5 >>> origin(5, 1, 1, [0, 4, 8, 12], 7, False) 4 :param current: current origin of a given axis :type current: int :param start: leftmost column index or topmost row index selected :type start: int :param end: rightmost column index or bottommost row index selected :type end: int :param cum_extents: cumulative sum of column widths or row heights :type cum_extents: numpy.ndarray :param screen: total extent of a given axis :type screen: int :param moving: flag if current action is advancing :type: bool :returns: new origin :rtype: int """ # Convert indices to coordinates of boundaries start = cum_extents[start] end = cum_extents[end+1] if end > current + screen and moving: return end - screen elif start < current and not moving: return start else: return current
c679db7f9c68b28ce7c89069f267dc7013e8bdf6
30,607
def _swap_on_miss(partition_result): """ Given a partition_dict result, if the partition missed, swap the before and after. """ before, item, after = partition_result return (before, item, after) if item else (after, item, before)
2cbf8ae30bc4b9efb449e0b0f63c78781cd09fd3
30,609
from operator import truediv def distances_from_average(test_list): """Return a list of distances to the average in absolute terms.""" avg = truediv(sum(test_list), len(test_list)) return [round(float((v - avg) * - 1), 2) for v in test_list]
e59e404e824e35d99dbf8fb8f788e38b7a19cc03
30,611
def byte_display(size): """ Returns a size with the correct unit (KB, MB), given the size in bytes. """ if size == 0: return '0 KB' if size <= 1024: return '%s bytes' % size if size > 1048576: return '%0.02f MB' % (size / 1048576.0) return '%0.02f KB' % (size / 1024.0)
35766e6ec839de9d928f8acf965e60de3a66b5cb
30,613
def load_element_single(properties, data): """ Load element data with lists of a single length based on the element's property-definitions. Parameters ------------ properties : dict Property definitions encoded in a dict where the property name is the key and the property data type the value. data : array Data rows for this element. If the data contains list-properties, all lists belonging to one property must have the same length. """ col_ranges = [] start = 0 row0 = data[0] for name, dt in properties.items(): length = 1 if '$LIST' in dt: # the first entry in a list-property is the number of elements in the list length = int(row0[start]) # skip the first entry (the length), when reading the data start += 1 end = start + length col_ranges.append((start, end)) # start next property at the end of this one start = end return {n: data[:, c[0]:c[1]].astype(dt.split('($LIST,)')[-1]) for c, (n, dt) in zip(col_ranges, properties.items())}
cc82704592cd2c5e98864cf59b454d2d7551bba0
30,618
def get_preresolution(file: str) -> int: """ Read pre file and returns number of unknowns :param file: pre file :return: number of unknowns """ with open(file) as f: content = f.readlines() ind = [idx for idx, s in enumerate(content) if '$DofData' in s][0] tmp = content[ind + 5].split()[-1] return int(tmp)
8084c37792246bef5f6fc9da43e30da9f4902cbc
30,623
def is_recovered(alleles_in_probands, alleles_in_pool): """True if all the variants found in the proband(s) are also found in the pool. This tends to result in multi-alleleic sites not getting filtered in many cases. alleles_in_probands, alleles_in_pool: iterable consisting of items that can be compared in a set """ if len(set(alleles_in_probands) - set(alleles_in_pool)) == 0: return True else: return False
68e978f63bcfc899a0a8c278d17d418d6423d674
30,624
from typing import Union import json def load_json_from_file(path: str) -> Union[dict, list, str, int]: """Load JSON from specified path""" with open(path, 'r', encoding='utf-8') as infile: return json.load(infile)
c8ba755c62ea4ab6fe74b4571034967ce610afdf
30,626