content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def read_query(name: str): """ Read in a query from a separate SQL file Retrieves a query from a separate SQL file and stores it as a string for later execution. Query files are stored in the utils/sql_queries directory Args: name: Name of the SQL file to retreive Returns: (str): String representation of the full SQL query. """ with open(f"src/phoebe_shelves_clt/sql_backend/sql_queries/{name}.sql") as f: return(f.read())
5b1dc1f9d1aee856cd8b47651aeadf6cd9b5408d
79,962
import torch def FalseTensor(*size, device='cuda:0'): """ Returns a Tensor of type torch.uint8 containing only False values Parameters ---------- *size : int the shape of the tensor device : str the device to store the tensor to Returns ------- Tensor a uint8 precision tensor """ return torch.zeros(*size, dtype=torch.uint8, device=device)
40ea379020283e87edd74fd0a7821ea763838dc9
98,015
def quotewrap(item): """wrap item in double quotes and return it. item is a stringlike object""" return '"' + item + '"'
91acd54664b9408832b105a01b47165b53fdf4f5
59,900
def elide_list(line_list, max_num=10): """Takes a long list and limits it to a smaller number of elements, replacing intervening elements with '...'. For example:: elide_list([1,2,3,4,5,6], 4) gives:: [1, 2, 3, '...', 6] """ if len(line_list) > max_num: return line_list[:max_num - 1] + ['...'] + line_list[-1:] else: return line_list
b40930de03d3463721e3c6a27d90cb7e0dc7f01f
138,046
def msize(m): """ Checks whether the matrix is square and returns its size. Args: m (numpy.ndarray): the matrix to measure; Returns: An integer with the size. """ s = m.shape[0] if m.shape != (s, s): raise ValueError("Do not recognize the shape (must be a square matrix): {}".format(m.shape)) return s
ecd67ade9f5ba1b0297252eb75235f5f9b900e95
559,001
def dec2bin(num, width=0): """ >>> dec2bin(0, 8) '00000000' >>> dec2bin(57, 8) '00111001' >>> dec2bin(3, 10) '0000000011' >>> dec2bin(-23, 8) '11101001' >>> dec2bin(23, 8) '00010111' >>> dec2bin(256) '100000000' """ if num < 0: if not width: raise ValueError('Width must be specified for negative numbers') num += 2 ** width binary = '' while num: if num & 1: binary += '1' else: binary += '0' num >>= 1 if width: no_zeros = width - len(binary) if no_zeros < 0: raise OverflowError('A binary of width %d cannot fit %d' % (width, num)) binary += '0' * no_zeros if not binary: binary = '0' return binary[::-1]
a63cfca8506d23ee69eeb112d489cf9af0542f79
61,928
import torch def collate_train(batch): """ Collate function for preparing the training batch for DCL training. :param batch: The list containing outputs of the __get_item__() function. Length of the list is equal to the required batch size. :return: The batch containing images and labels for DCL training """ imgs = [] # List to store the images target = [] # List to store the targets target_jigsaw = [] # List to store the jigsaw targets patch_labels = [] # List to store the ground truth patch labels # Iterate over each output of the __get_item__() function for sample in batch: imgs.append(sample[0]) # Append the original image imgs.append(sample[1]) # Append the transformed image (after applying RCM) # Append the same labels for original and RCM image for Cls. head target.append(sample[2]) target.append(sample[2]) # Append the different labels for original and RCM image for Adv. head target_jigsaw.append(sample[2]) target_jigsaw.append(sample[3]) # Append the ground truth patch labels patch_labels.append(sample[4]) patch_labels.append(sample[5]) # Stack the images and return the required batch for training return torch.stack(imgs, 0), target, target_jigsaw, patch_labels
18c897fe862a2b75c6aea8e2e239049a1c4929ac
433,812
def occurence_data(pat_df, column): """ Return value counts of given dataframe columns :param pat_df: Dataframe :param column: Column included in Dataframe :return: Series of value occurences """ return pat_df[column].value_counts()
7bec7cec90c0f575aa5e2dfd4855106caf03a31a
90,794
def get_rec_names(study_folder): """ Get list of keys of recordings. Read from the 'names.txt' file in study folder. Parameters ---------- study_folder: str The study folder. Returns ---------- rec_names: list LIst of names. """ with open(study_folder / 'names.txt', mode='r', encoding='utf8') as f: rec_names = f.read()[:-1].split('\n') return rec_names
ab9c7eddc0ce593ddcea129c2122e753a94432bf
648,436
import six import operator def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs): """Expected inclusion_unlimited_args_kwargs __doc__""" # Sort the dictionary by key to guarantee the order for testing. sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0)) return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % ( ', '.join(six.text_type(arg) for arg in [one, two] + list(args)), ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) )}
58c903759bc10a3fb215cf5cdbeca9deef72c0d3
589,318
def md_entry_same(entry_name, s1, s2): """Returns (s1 and s2 have the same value for entry_name?, message).""" s1_val = s1[entry_name] s2_val = s2[entry_name] return (s1_val == s2_val, "(" + entry_name + ") " + repr(s1_val) + ", " + repr(s2_val))
61d1cae8b70a810e9ff85e66a1667f6cb2431f49
321,873
def format_score(logpath, log, markup): """Turn a log file JSON into a pretty string.""" output = [] output.append('\nLog: ' + logpath) if log['unrecognized']: output.append('\nLog is unrecognized: {}'.format(log['unrecognized'])) else: if log['flagged']: output.append('\nLog is flagged: {}'.format(log['flagged'])) output.append('\nDisc name: {}'.format(log['name'])) output.append('\nScore: {}'.format(log['score'])) if log['deductions']: output.append('\nDeductions:') for deduction in log['deductions']: output.append(' >> {}'.format(deduction[0])) if markup: output.append('\n\nStylized Log:\n\n{}'.format(log['contents'])) return '\n'.join(output)
c3ac492375b72d05481a3a2dc2986149f79b405e
664,860
def is_categorical(s, column=None): """Check if a pandas Series or a column in a DataFrame is categorical. s (pandas.Series or pandas.DataFrame): Series to check or dataframe with column to check. column (str): Column name. If a column name is given it is assumed that `s` is a `pandas.DataFrame`. """ if column is not None: # s is not a Series, it is a DataFrame. s = s[column] return s.dtype.name == "category"
21eecc2b6760ffa88194b9cd59c6133ec9c1ba18
552,661
def create_datafile_url(base_url, identifier, is_filepid): """Creates URL of Datafile. Example - File ID: https://data.aussda.at/file.xhtml?persistentId=doi:10.11587/CCESLK/5RH5GK Parameters ---------- base_url : str Base URL of Dataverse instance identifier : str Identifier of the datafile. Can be datafile id or persistent identifier of the datafile (e. g. doi). is_filepid : bool ``True`` to use persistent identifier. ``False``, if not. Returns ------- str URL of the datafile """ assert isinstance(base_url, str) assert isinstance(identifier, str) base_url = base_url.rstrip("/") if is_filepid: url = "{0}/file.xhtml?persistentId={1}".format(base_url, identifier) else: url = "{0}/file.xhtml?fileId={1}".format(base_url, identifier) assert isinstance(url, str) return url
d6deece390b3028f45b27a0f6aa1864688ed97fa
24,053
def project_grad(g): """Project gradient onto tangent space of simplex.""" return g - g.sum() / g.size
41a50bf9d9e8e0efbbe703758385b7da6e2a26ca
404,552
def IsGlobalTargetGrpcProxiesRef(target_grpc_proxy_ref): """Returns True if the target gRPC proxy reference is global.""" return target_grpc_proxy_ref.Collection() == 'compute.targetGrpcProxies'
20ea7d0baf818a2435506a7e0a23f7c1a0921f36
653,677
def interpretStatus(status, default_status="Idle"): """ Transform a integer globus status to either Wait, Idle, Running, Held, Completed or Removed """ if status == 5: return "Completed" elif status == 9: return "Removed" elif status == 1: return "Running" elif status == 12: return "Held" elif status == 0: return "Wait" elif status == 17: return "Idle" else: return default_status
578ace00f98da7f01f42a5ba03cd9a249e08f7ad
365,198
def conv_kwargs_helper(norm: bool, activation: bool): """ Helper to force disable normalization and activation in layers which have those by default Args: norm: en-/disable normalization layer activation: en-/disable activation layer Returns: dict: keyword arguments to pass to conv generator """ kwargs = { "add_norm": norm, "add_act": activation, } return kwargs
56c578511220a19a614255b83ff1c031814ed5ae
427,590
import math def rmsd(V, W): """ Calculate Root-mean-square deviation from two sets of vectors V and W. Parameters ---------- V : array (N,D) matrix, where N is points and D is dimension. W : array (N,D) matrix, where N is points and D is dimension. Returns ------- rmsd : float Root-mean-square deviation between the two vectors """ D = len(V[0]) N = len(V) result = 0.0 for v, w in zip(V, W): result += sum([(v[i] - w[i])**2.0 for i in range(D)]) return math.sqrt(result / N)
36712ed6666c45378ef6959ddcd300a907c121a1
364,746
def med_min_2darray(a): """Takes in a list of lists of integers and returns the minimum value.""" return min(min(inner) for inner in a)
c30a7588a11e2c23829fe73b6d84ffdaee8fb321
32,334
def _cast_to_int(num, param_name): """Casts integer-like objects to int. Args: num: the number to be casted. param_name: the name of the parameter to be displayed in an error message. Returns: num as an int. Raises: TypeError: if num is not integer-like. """ try: # __index__() is the Pythonic way to convert integer-like objects (e.g. # np.int64) to an int return num.__index__() except (TypeError, AttributeError): raise TypeError('%s is not integer-like (found type: %s)' %(param_name, type(num).__name__))
493c9010054c5ff0d80bd7f304de97d3b0e4776c
293,377
def prefix_by_topic(topic_str): """ Return a topic-based prefix to produce distinct output files. `+` in the topic is replaced with `ALL`. The last element, `#` is left out from the prefix. See https://digitransit.fi/en/developers/apis/4-realtime-api/vehicle-positions/#the-topic """ els = topic_str.split('/')[1:] els = [el for el in els[:-1] if el is not None] els = [el.replace('+', 'ALL') for el in els] return '_'.join(els)
fd1288e664a94277985672f6af38314a805de6be
506,089
def split_by_two_strings(line, str1, str2): """Split the input line into three parts separated by two given strings.""" # Start of second part in the input string. i1 = line.index(str1) + len(str1) # End of second part in the input string. i2 = line.index(str2) # Now we know where the second part can be found in input string. It is # therefore easy to figure out where the first part and third part are. return line[:i1], line[i1:i2], line[i2:]
4883075e61185b9bfc0490586cb08c66db603a7a
620,233
def get_variant_prices_from_lines(lines): """Get's price of each individual item within the lines.""" return [ line.variant.get_price() for line in lines for item in range(line.quantity)]
ec6414ec638da574d1665a93c33ccd1b68f58cf9
241,681
async def client_send(ctx, msg, embed=1): """Sends messages to Discord context. Easily makes messages 'embeded' if embed == 1""" try: msg = str(msg) if embed == 1: m = await ctx.send("```" + msg + "```") else: m = await ctx.send(msg) return m except: return 1
6429401c692ff3e09fb8cb066706ef0168230c6f
550,968
from typing import List def split_commits_data( commits_data: str, commits_sep: str = '\x1e', ) -> List[str]: """ Split data into individual commits using a separator. :param commits_data: the full data to be split :param commits_sep: the string which separates individual commits :return: the list of data for each individual commit """ # Remove leading/trailing newlines commits_data = commits_data.strip('\n') # Split in individual commits and remove leading/trailing newlines individual_commits = [ single_output.strip('\n') for single_output in commits_data.split(commits_sep) ] # Filter out empty elements individual_commits = list(filter(None, individual_commits)) return individual_commits
5b698df35b483628b1f6e5216ebf20174359b5fd
166,730
def create_prop_dictionary(properties_list): """ Creates a dictionary of all properties from the properties list :param properties_list: list of property objects :return: dictionary of property objects grouped by unique key (name, unit, condition name, condition unit, method and data type) """ prop_dict = {} for prop in properties_list: identifier = prop.name + '-' if prop.units: identifier += prop.units + '-' else: identifier += '' + '-' if prop.conditions: for cond in prop.conditions: identifier += cond.name + '-' if cond.units: identifier += cond.units else: identifier += '' + '-' if prop.methods: for meth in prop.methods: identifier += meth.name + '-' if prop.data_type: identifier += prop.data_type + '-' if prop.scalars or prop.files: try: prop_dict[identifier].append(prop) except KeyError: prop_dict[identifier] = [prop] return prop_dict
decc20437814386c3499c41c4d6358ea5ab088a7
439,438
def identity_transformation(data): """Default coder is no encoding/decoding""" return data
effec06dcb5627f35224bebcd68e19ba249a8789
161,910
from functools import reduce import operator def _vector_add(*vecs): """For any number of length-n vectors, pairwise add the entries, e.g. for x = (x_0, ..., x_{n-1}), y = (y_0, ..., y_{n-1}), xy = (x_0+y_0, x_1+y_1, ..., x_{n-1}+y{n-1}).""" assert(len(set(map(len, vecs))) == 1) return [reduce(operator.add, a, 0) for a in zip(*vecs)]
d5a8c9a6dc42c65e879b721e75c42abd17d97ef0
97,163
from typing import Tuple def participant_names(redcap_record: dict) -> Tuple[str, ...]: """ Extracts a tuple of names for the participant from the given *redcap_record*. """ if redcap_record['participant_first_name']: return (redcap_record['participant_first_name'], redcap_record['participant_last_name']) else: return (redcap_record['part_name_sp'],)
d0cd8aa80f585b04828bf52ef1ff76ac5274fd3d
504,538
def get_accounts_aws(self, filter=""): """Retrieves AWS account information from Polaris Args: filter (str): Search string to filter results Returns: dict: Details of AWS accounts in Polaris Raises: RequestException: If the query to Polaris returned an error """ try: query_name = "accounts_aws" variables = { "filter": filter } return self._query(query_name, variables) except Exception: raise
87ef43ccb7398afced32afb3aaa4a2e81c5d6f88
530,679
def arg_type_to_string(arg_type) -> str: """ Converts the argument type to a string :param arg_type: :return: String representation of the argument type. Multiple return types are turned into a comma delimited list of type names """ union_params = ( getattr(arg_type, '__union_params__', None) or getattr(arg_type, '__args__', None) ) if union_params and isinstance(union_params, (list, tuple)): return ', '.join([arg_type_to_string(item) for item in union_params]) try: return arg_type.__name__ except AttributeError: return '{}'.format(arg_type)
b55506d9a0f9eec2468a05aa839dbd999ce9b42a
245,040
def combine_biases(*masks): """Combine attention biases. Args: *masks: set of attention bias arguments to combine, some can be None. Returns: Combined mask, reduced by summation, returns None if no masks given. """ masks = [m for m in masks if m is not None] if not masks: return None assert all(map(lambda x: x.ndim == masks[0].ndim, masks)), ( f'masks must have same rank: {tuple(map(lambda x: x.ndim, masks))}') mask, *other_masks = masks for other_mask in other_masks: mask = mask + other_mask return mask
994241493b94139f84ec2e944b5a66fbe0b2349b
262,664
from pathlib import Path def find_source_dir_from_file(filepath: Path): """Find the source directory of the Sphinx project.""" conf_file = Path("conf.py") source_dir = filepath.parent root = Path("/") while source_dir != root: path = source_dir / conf_file if path.exists(): return source_dir source_dir = source_dir.parent return None
a0f1e3e25c588b11379f5e1e0356efce43e070ac
243,786
import socket def localhost_has_free_port(port: int) -> bool: """Checks if the port is free on localhost. Args: port (int): The port which will be checked. Returns: bool: True if port is free, else False. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) is_success = sock.connect_ex(("localhost", port)) return True if is_success else False
f64d1570756462bf9cec37d34b1d942d94a23e75
377,245
import torch def generate_spatial_noise(size, device, *args, **kwargs): """ Generates a noise tensor. Currently uses torch.randn. """ # noise = generate_noise([size[0], *size[2:]], *args, **kwargs) # return noise.expand(size) return torch.randn(size, device=device)
5c9116fdc132d59e4a0ccc6c5674042f70533efe
26,046
def get_first_child(node, type): """Return the first child of |node| that has type |type|.""" index = node.first_child_matching_class(type) return node[index]
090711b92a3a62ad9ee3ed3d2910652c9849d87f
464,729
def add_normalized_column(df, column_name): """ Normalize a column and add it to the DataFrame. Parameters ---------- df: DataFrame Input DataFrame containing the column to normalize. column_name: string Name of the column to normalize. Returns ------- out: DataFrame DataFrame with a normalized column having postfix "_norm". """ df[f"{column_name}_norm"] = (df[column_name] - df[column_name].min()) / ( df[column_name].max() - df[column_name].min() ) return df
0f9d556d12912ee1c659d9ae497f8a6f9b193953
459,853
def make_reverse_dict(in_dict, warn=True): """ Build a reverse dictionary from a cluster dictionary Parameters ---------- in_dict : dict(int:[int,]) A dictionary of clusters. Each cluster is a source index and the list of other source in the cluster. Returns ------- out_dict : dict(int:int) A single valued dictionary pointing from source index to cluster key for each source in a cluster. Note that the key does not point to itself. """ out_dict = {} for k, v in in_dict.items(): for vv in v: if vv in out_dict: if warn: print("Dictionary collision %i" % vv) out_dict[vv] = k return out_dict
7126107779524026f3bf04ec37235413984ea583
680,941
def stations_highest_rel_level(stations, N): """For a list of MonitoringStaton objects (stations), returns a list of the N stations at which the water level, relative to the typical range, is highest""" #Filter list as to not include stations without relative water level new_stations = list(filter(lambda station: station.relative_water_level() is not None, stations)) #Sorts stations in descending order of relative water level new_stations.sort(key=lambda station: station.relative_water_level(), reverse = True) #Return first N stations in lists (N stations with highest water level) return new_stations[:N]
61b9a2282678e13cce238b665009368f4e13043b
85,945
def MeanAveragePrecision(predictions, retrieval_solution, max_predictions=100): """Computes mean average precision for retrieval prediction. Args: predictions: Dict mapping test image ID to a list of strings corresponding to index image IDs. retrieval_solution: Dict mapping test image ID to list of ground-truth image IDs. max_predictions: Maximum number of predictions per query to take into account. For the Google Landmark Retrieval challenge, this should be set to 100. Returns: mean_ap: Mean average precision score (float). Raises: ValueError: If a test image in `predictions` is not included in `retrieval_solutions`. """ # Compute number of test images. num_test_images = len(retrieval_solution.keys()) # Loop over predictions for each query and compute mAP. mean_ap = 0.0 for key, prediction in predictions.items(): if key not in retrieval_solution: raise ValueError('Test image %s is not part of retrieval_solution' % key) # Loop over predicted images, keeping track of those which were already # used (duplicates are skipped). ap = 0.0 already_predicted = set() num_expected_retrieved = min(len(retrieval_solution[key]), max_predictions) num_correct = 0 for i in range(min(len(prediction), max_predictions)): if prediction[i] not in already_predicted: if prediction[i] in retrieval_solution[key]: num_correct += 1 ap += num_correct / (i + 1) already_predicted.add(prediction[i]) ap /= num_expected_retrieved mean_ap += ap mean_ap /= num_test_images return mean_ap
089baa160e4c01032e759d6479eb48dd34032100
539,848
def safe_inserter(string, inserter): """Helper to insert a subject name into a string if %s is present Parameters ---------- string : str String to fill. inserter : str The string to put in ``string`` if ``'%s'`` is present. Returns ------- string : str The modified string. """ if '%s' in string: string = string % inserter return string
91a86856061b8db8645d87d3313130ffe89a8a96
515,088
def undulating(number): """ Returns True if number is undulating """ if number < 100: return False number = str(number) for idx in range(len(number)-2): if number[idx] != number[idx+2]: return False return True
e114bebb260c8c1f895fcd1f9fefb3e14b38f9c6
609,332
def parse_result_line(line): """Take a line consisting of a constituency name and vote count, party id pairs all separated by commas and return the constituency name and a list of results as a pair. The results list consists of vote-count party name pairs. To handle constituencies whose names include a comma, the parse considers count, party pairs *from the right* and stops when it reaches a vote count which is not an integer. """ items = line.strip().split(',') results = [] # If there is more to parse, there should be at least the constituency name, # a vote count and a party id, i.e. more than two values while len(items) > 2: party_id = items.pop() count_str = items.pop() try: count = int(count_str.strip()) except ValueError: items.extend([count_str, party_id]) break results.append((count, party_id.strip())) # The remaining items are assumed to be to be the constituency name. Note we # need to reverse the results in order to preserve the order we were given. return ','.join(items), results[::-1]
8808f09fad8ba37896826e8ccf7ebe68bf9a516f
369,850
def is_ip_per_task(app): """ Return whether the application is using IP-per-task. :param app: The application to check. :return: True if using IP per task, False otherwise. """ return app.get('ipAddress') is not None
7de05a7db5eb886bea2687492585b554f898fc41
669,691
def column(results): """ Get a list of values from a single-column ResultProxy. """ return [x for x, in results]
352a604eb9bb863c8bf71c7c96df6c2cbcd226c8
53,677
def unflatten_dict(d, delimiter = "/"): """Creates a hierarchical dictionary by splitting the keys at delimiter.""" new_dict = {} for path, v in d.items(): current_dict = new_dict keys = path.split(delimiter) for key in keys[:-1]: if key not in current_dict: current_dict[key] = {} current_dict = current_dict[key] current_dict[keys[-1]] = v return new_dict
edede31b6fc22a82f70e085b7fcd3a8ace030212
464,327
def parse_subnets(subnets): """ Parse the Subnets dict, checking it is in correct format. Raises errors if there is a format violation. Arguments: subnets : the subnets dict Returns: parsed_subnets : parsed Subnet dict """ if not isinstance(subnets, dict): raise ValueError("Subnets must be dict with key-value pairs: {}" .format("subnet_id : [subnet_id, ..., subnet_id]")) if len(subnets) < 2: raise ValueError("Not enough subnets specified, need at least two:", "one for attacker and one for target") parsed_subnets = {} avail_subnets = set(subnets.keys()) for subnet_id, connected_list in subnets.items(): if not isinstance(connected_list, list) or len(connected_list) < 1: raise ValueError("Subnet values must be list with at least one entry {} is invalid" .format(connected_list)) if subnet_id in connected_list: raise ValueError("Subnet connected list should not contain parent subnet: {}: {} invalid" .format(subnet_id, connected_list)) for connected_id in connected_list: if connected_id not in avail_subnets: raise ValueError("Subnets can only be connected to subnets with specified in top", "level subnet list: for subnet {} connected subnet {} invalid" .format(subnet_id, connected_id)) if connected_list.count(connected_id) > 1: raise ValueError("Connected subnet lists cannot have duplicates: {}: {} invalid" .format(subnet_id, connected_list)) parsed_subnets[subnet_id] = connected_list return parsed_subnets
72d56b25ce269977e2ddad6531eec8ca7e140e34
312,375
def _get_outside_corners(corners, board): """ Return the four corners of the board as a whole, as (up_left, up_right, down_right, down_left). """ xdim = board.n_cols ydim = board.n_rows if corners.shape[1] * corners.shape[0] != xdim * ydim: raise Exception( "Invalid number of corners! %d corners. X: %d, Y: %d" % (corners.shape[1] * corners.shape[0], xdim, ydim) ) up_left = corners[0, 0] up_right = corners[xdim - 1, 0] down_right = corners[-1, 0] down_left = corners[-xdim, 0] return (up_left, up_right, down_right, down_left)
647a5f42192a312c7a661880d1d2750ebf70e154
651,335
import importlib def import_object(obj): """Import an object from its qualified name.""" if isinstance(obj, str): package, name = obj.rsplit('.', 1) return getattr(importlib.import_module(package), name) return obj
c0e4816c6db6bc2c826ba4d8498e7081daa9be48
555,416
import re def snakeCasetoCamelCase(a_string): """assumes a_string is a string in snake_case returns a new string, representing a_string in camelCase""" pattern = "(\w)(_)(\w)" new_string = re.sub(pattern, r"\1\3", a_string) return new_string
4f8b588cdba4fbc73e997d14c7c0f70e7a2cee57
552,992
from re import findall def to_integer(given_input: str): """ Finds the number in a given input(should be a string with numbers) using regular expression. >>> to_integer('abc') 0 >>> to_integer('1') 1 >>> to_integer('abc123') '123' >>> to_integer('abc123abc') '123' >>> to_integer('abc123abc456') '123,456' Args: given_input (str): any text with numbers in it Returns: Number: returns number in a comma separated form if found else returns 0 """ if isinstance(given_input, str): match = findall('\d+', given_input) if match: return ",".join(match) return 0 # default value return given_input
a65977833883962cf6327caf3873456b907a6133
376,034
def _validate_scp_time(the_sicd): """ Validate the SCPTime. Parameters ---------- the_sicd : sarpy.io.complex.sicd_elements.SICD.SICDType Returns ------- bool """ if the_sicd.SCPCOA is None or the_sicd.SCPCOA.SCPTime is None or \ the_sicd.Grid is None or the_sicd.Grid.TimeCOAPoly is None: return True cond = True val1 = the_sicd.SCPCOA.SCPTime val2 = the_sicd.Grid.TimeCOAPoly[0, 0] if abs(val1 - val2) > 1e-6: the_sicd.log_validity_error( 'SCPTime populated as {},\n' 'and constant term of TimeCOAPoly populated as {}'.format(val1, val2)) cond = False return cond
6d84c1e204e419042c346b668bd50a7bf3e83406
397,577
def directory_tree(tmp_path): """Create a test directory tree.""" # initialize p = tmp_path / "directory_tree" p.mkdir() p.joinpath("file1").write_text("123") p.joinpath("dir1").mkdir() p.joinpath("dir1/file2").write_text("456") p.joinpath("dir1/file3").write_text("789") return p
371dc92f1708bf7de7bd66b19b7a1e1ac4a8e3ff
323,156
def intstrtuple(s): """Get (int, string) tuple from int:str strings.""" parts = [p.strip() for p in s.split(":", 1)] if len(parts) == 2: return int(parts[0]), parts[1] else: return None, parts[0]
eb105081762e5d48584d41c4ace5697fccb8c29e
602,715
def findSmallerInRight(string, start, end): """ Counts the number of caracters that are smaller than string[start] and are at the right of it. :param string: Input string. :param start: Integer corresponding to the index of the starting character. :param end: Integer corresponding to the index of the string. :return: Integer corresponding to the number of chars, on the right, that are smaller. """ countRight = 0 i = start + 1 while i <= end: if string[i] < string[start]: countRight = countRight + 1 i = i + 1 return countRight
b9cc36373706a305565804831415efe6e0b0d424
116,281
def dict_is_song(info_dict): """Determine if a dictionary returned by youtube_dl is from a song (and not an album for example).""" if "full album" in info_dict["title"].lower(): return False if int(info_dict["duration"]) > 7200: return False return True
b4792a850be39d4e9dc48c57d28d8e4f50751a75
677,740
def get_n_last_observations_from_trajectories(trajectories, n, ascending=True): """ Get n extremity observations from trajectories Parameters ---------- trajectories : dataframe a dataframe with a trajectory_id column that identify trajectory observations. (column trajectory_id and jd have to be present) n : integer the number of extremity observations to return. ascending : boolean if set to True, return the most recent extremity observations, return the oldest ones otherwise, default to True. Returns ------- last_trajectories_observations : dataframe the n last observations from the recorded trajectories Examples -------- >>> from pandera import Check, Column, DataFrameSchema >>> test = pd.DataFrame({ ... "candid" : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], ... "jd" : [0.0, 1.0, 2, 3, 4, 5, 6, 7, 8, 9], ... "trajectory_id" : [1, 1, 1, 1, 2, 2, 3, 3, 3, 3] ... }) >>> df_schema = DataFrameSchema({ ... "jd": Column(float), ... "trajectory_id": Column(int) ... }) >>> res = get_n_last_observations_from_trajectories(test, 1, False) >>> res = df_schema.validate(res).reset_index(drop=True) >>> df_expected = pd.DataFrame({ ... "candid" : [6, 4, 0], ... "jd" : [6.0, 4.0, 0.0], ... "trajectory_id" : [3, 2, 1] ... }) >>> assert_frame_equal(res, df_expected) >>> res = get_n_last_observations_from_trajectories(test, 1, True) >>> res = df_schema.validate(res).reset_index(drop=True) >>> df_expected = pd.DataFrame({ ... "candid" : [3, 5, 9], ... "jd" : [3.0, 5.0, 9.0], ... "trajectory_id" : [1, 2, 3] ... }) >>> assert_frame_equal(res, df_expected) >>> res = get_n_last_observations_from_trajectories(test, 2, True) >>> res = df_schema.validate(res).reset_index(drop=True) >>> df_expected = pd.DataFrame({ ... "candid" : [2, 3, 4, 5, 8, 9], ... "jd" : [2.0, 3.0, 4.0, 5.0, 8.0, 9.0], ... "trajectory_id" : [1, 1, 2, 2, 3, 3] ... }) >>> assert_frame_equal(res, df_expected) >>> res = get_n_last_observations_from_trajectories(test, 2, False) >>> res = df_schema.validate(res).reset_index(drop=True) >>> df_expected = pd.DataFrame({ ... "candid" : [7, 6, 5, 4, 1, 0], ... "jd" : [7.0, 6.0, 5.0, 4.0, 1.0, 0.0], ... "trajectory_id" : [3, 3, 2, 2, 1, 1] ... }) >>> assert_frame_equal(res, df_expected) """ return ( trajectories.sort_values(["jd"], ascending=ascending) .groupby(["trajectory_id"]) .tail(n) .sort_values(["jd", "trajectory_id"], ascending=ascending) )
5c01eefb4d2de6da74a8a7f7967a7ee56ea4a78d
129,654
def get_arg_to_class(class_names): """Constructs dictionary from argument to class names. # Arguments class_names: List of strings containing the class names. # Returns Dictionary mapping integer to class name. """ return dict(zip(list(range(len(class_names))), class_names))
ec992707772716b2707ecb881a700c5726293745
510,902
def has_encountered_output_source(context): """Return True if the current context has already encountered an @output_source directive.""" return 'output_source' in context
3b78bcb40e8e4aa6b9ea269b0031d03803cae3b9
192,455
def writeSeg(BCFILE, title, segID, planeNodeIDs): """write face segments to BC input file Args: BCFILE: file IO object title (str): header comment line segID (int): segment ID # planeNodeIDs (int): 2D array Returns: segID (inc +1) """ BCFILE.write('*SET_SEGMENT_TITLE\n') BCFILE.write('%s\n' % title) BCFILE.write('%i\n' % segID) for i in range(0, (len(planeNodeIDs) - 1)): (a, b) = planeNodeIDs.shape for j in range(0, (b - 1)): BCFILE.write("%i,%i,%i,%i\n" % (planeNodeIDs[i, j], planeNodeIDs[i + 1, j], planeNodeIDs[i + 1, j + 1], planeNodeIDs[i, j + 1])) segID = segID + 1 return segID
a82848e3664229ca9d4bcaa78dc8036e731c96a0
83,634
from typing import List def get_requires() -> List[str]: """ Get Requires: Returns a list of required packages. """ return [ 'Click', 'cupy', 'tqdm', 'appdirs' ]
2fa8988e4ce8d2d5fe6cad9d9a995dad899ebb8a
364,258
def github_repository_name(url): """ Get the repository name from a Github URL """ repo = url.rstrip("/") if repo.endswith(".git"): repo = repo[:-4] _, name = repo.rsplit("/", 1) return name
366185873f1a083af8b219359d1c3c30cad7d222
336,574
def github_paginate(session, url): """Combines return from GitHub pagination :param session: requests client instance :param url: start url to get the data from. See https://developer.github.com/v3/#pagination """ result = [] while url: r = session.get(url) result.extend(r.json()) next_url = r.links.get('next') if next_url: url = next_url.get('url') else: url = None return result
6c951f0dadc3d6b8c0bae7ada61bbd46e085d544
643,200
def chunk(arr:list, size:int=1) -> list: """ This function takes a list and divides it into sublists of size equal to size. Args: arr ( list ) : list to split size ( int, optional ) : chunk size. Defaults to 1 Return: list : A new list containing the chunks of the original Examples: >>> chunk([1, 2, 3, 4]) [[1], [2], [3], [4]] >>> chunk([1, 2, 3, 4], 2) [[1, 2], [3, 4]] >>> chunk([1, 2, 3, 4, 5, 6], 3) [[1, 2, 3], [4, 5, 6]] """ _arr = [] for i in range(0, len(arr), size): _arr.append(arr[i : i + size]) return _arr
0aa82c11fdc63f7e31747c95e678fdcac4571547
686,877
def split_rows(array:list, l:int=9) -> list: """ Transforms a 1D list into a list of lists with every list holding l elements. Error is raised if array has a length not divisible by l. """ if len(array) % l != 0: raise ValueError("split_rows(): Rows in list have different lengths") return [array[i:i+l] for i in range(0, len(array), l)]
3f9934f92f6891f95c868e207831634f62e2eaed
90,785
def fixture_other_case() -> str: """Return the case id that differs from base fixture""" return "angrybird"
9c31d9b1a4f24d2859829be84cf8f4f526598dfb
197,614
import re def prune_protected(mailboxes, ns): """ Remove protected folders from a list of mailboxes Exchange has several protected folders that are used for non-mail purposes, but still appear in the list. Therefore, we want to exclude these folders to prevent reading non-mail items. Args: [<str>]: list of mailboxes - Must not include surrounding quotes <str>: namespace for the account Returns: [<str>]: list of mailboxes with protected folders removed """ protected = ['Calendar', 'Contacts', 'Tasks', 'Journal', 'Deleted Items'] flagged = [] for folder in protected: pattern = "(?:{})?{}\\b".format(ns,folder) for mailbox in mailboxes: result = re.match(pattern, mailbox, flags=re.IGNORECASE) if result: flagged.append(mailbox) return [mailbox for mailbox in mailboxes if mailbox not in flagged]
29a709683b40a89c4c1f422860166681dd1f2f7d
513,757
def remove_hetatm(filename_in, file_out, remove_all): """Remove HETATM and related lines. If remove_all is False, remove only element X which happens in many PDB entries but is not accepted by pointless, refmac, phaser, etc """ # we could instead zero occupancy of the atoms and replace X with Y file_in = open(filename_in) removed = set() def is_removed(serial): return serial and not serial.isspace() and int(serial) in removed for line in file_in: record = line[:6] if record == 'HETATM': if remove_all or line[76:78] == ' X': atom_serial_num = int(line[6:11]) removed.add(atom_serial_num) continue elif record in ('HET ', 'HETNAM', 'HETSYN', 'FORMUL'): continue elif line.startswith('ANISOU'): if is_removed(line[6:11]): continue elif line.startswith('CONECT'): if any(is_removed(line[p:p+5]) for p in (6, 11, 16, 21, 26)): continue file_out.write(line) return len(removed)
74278aa9c42334251924856350ce339b62366b44
479,141
def _urpc_test_func_2(buf): """! @brief u-RPC variable length data test function. @param buf A byte string buffer @return The same byte string repeated three times """ return buf*3
f13f7dcf45eaa0706b69eb09c63d29ba2bbd3d60
1,596
import gzip def read_consanguineous_samples(path, cutoff=0.05): """ Read inbreeding coefficients from a TSV file at the specified path. Second column is sample id, 6th column is F coefficient. From PLINK: FID, IID, O(HOM), E(HOM), N(NM), F Additional columns may be present but will be ignored. """ consanguineous_samples = {} myopen = gzip.open if path.endswith('.gz') else open with myopen(path) as inf: _ = inf.readline() for line in inf: cols = line.strip().split() if float(cols[5]) > cutoff: consanguineous_samples[cols[1]] = True return consanguineous_samples
be3515e6704966ae927bfaff2594be9191063889
6,722
def is_reserved_name(name): """Tests if name is reserved Names beginning with 'xml' are reserved for future standardization""" if name: return name[:3].lower() == 'xml' else: return False
29ca0ec73b18259126a61aaf335a7d0946b72eb6
696,787
def prompt(message, values=None): """Prompt a message and return the user input. Set values to None for binary input ('y' or 'n'), to 0 for integer input, or to a list of possible inputs. """ if values is None: message += ' (y/n)' message += ' > ' while 1: ans = input(message) if values is None: if ans.lower() == 'y': return True elif ans.lower() == 'n': return False elif values == 0: try: read = int(ans) except: continue return read elif ans in values: return ans
4d6b87b84ed1dfd95722e0055a8df3b1b34f1e84
16,212
def parse_input(input_file): """ Processes the input with song titles. See above format. Returns a dict of mapping number -> [title1, title2, ...] """ tdb = {} disc_no = -1 with open(input_file) as fin: for line in fin: line = line.strip() if 'disc ' in line.lower() or 'disk ' in line.lower(): disc_no += 1 tdb[disc_no] = [] elif line != '': tdb[disc_no].append(line) return tdb
652334d928df97f1456cedcd6250444e60b8207a
543,389
def is_type(indexed_token, tag_type): """Tests if the given token was tagged with the given tag type.""" return indexed_token.has_key('tag') and (indexed_token['tag'] == tag_type)
48a23454459080d9677bfc5f78529407e54864bc
544,993
import re def get_root_url(the_line): """ Get the root URL from the line :param the_line: the line :return: either the root URL or None """ ret = re.search('https://[^/]*/[^/]*/', the_line) if ret: return ret.group(0) return None
a4a4a283664e8d80088c3ec5e349aae3d3f34dd5
607,668
import six def _get_context(estimator=None): """Get context name for warning messages.""" if estimator is not None: if isinstance(estimator, six.string_types): estimator_name = estimator.lower() else: estimator_name = estimator.__class__.__name__.lower() estimator_name = "[%s] " % estimator_name else: estimator_name = "" return estimator_name
5212bad031a8f953b8f827b8b930da11e60e411c
506,430
def strictly_equal(obj1: object, obj2: object) -> bool: """Checks if the objects are equal and are of the same type.""" return obj1 == obj2 and type(obj1) is type(obj2)
00fcfa2ab3bbbfa40fa03731a553ae9f7224ea57
531,135
def exception_redirect(new_exception_class, old_exception_class=Exception, logger=None): """ Decorator to replace a given exception to another Exception class, with optional exception logging. >>> >>> class MyException(Exception): ... pass >>> >>> @exception_redirect(MyException) ... def test(): ... raise Exception("test") >>> >>> test() Traceback (most recent call last): ... lump.decorators.MyException: test """ def _decorator(func): def catch_and_redirect_exception(*args, **kwargs): try: return func(*args, **kwargs) except old_exception_class as e: if logger is not None: logger.exception(e) raise new_exception_class(e) from None return catch_and_redirect_exception return _decorator
bef002fc5cf15ebc1517fd1ea9ca78fb2b4be3eb
568,146
def yubikey_get_yubikey_id(yubikey_otp): """ Returns the yubikey id based :param yubikey_otp: Yubikey OTP :type yubikey_otp: str :return: Yubikey ID :rtype: str """ yubikey_otp = str(yubikey_otp).strip() return yubikey_otp[:12]
32de713e8d4cf3b6a5ca908976b73f7f9eb69561
276,686
import torch def load_weights_from_path(model, path): """load weights from file Args: model (Net): Model instance path (str): Path to weights file Returns: Net: loaded model """ model.load_state_dict(torch.load(path)) return model
7d684d616bd90eea43e73362f31647692cbb0f8e
202,407
def directory_current_user(request): """ Return the current user directory """ path = request.user.get_home_directory() try: if not request.fs.isdir(path): path = '/' except Exception: pass return path
c73d0d7a50cfb7f7b4942919e79fbf6c7878a269
395,468
def create_dict_playlists_playlistids(p_list, pid_list): """ Create a dictionary of playlists and playlist ids """ playlists_and_playlist_ids = {} for i in range(len(p_list)): playlists_and_playlist_ids[p_list[i]] = pid_list[i] return playlists_and_playlist_ids
173850ed85b3dc774ddea14674e22e701991c807
701,685
import typing import types def is_iterable(obj: typing.Any) -> bool: """ >>> is_iterable([]) True >>> is_iterable(()) True >>> is_iterable([x for x in range(10)]) True >>> is_iterable((1, 2, 3)) True >>> g = (x for x in range(10)) >>> is_iterable(g) True >>> is_iterable('abc') False >>> is_iterable(0) False >>> is_iterable({}) False """ return isinstance(obj, (list, tuple, types.GeneratorType)) or \ (not isinstance(obj, (int, str, dict)) and bool(getattr(obj, 'next', False)))
fcd260fa3dace6d0de7dcbbd5ad5d9899ed6bb7c
489,820
def color565(red, green=0, blue=0): """ Convert red, green and blue values (0-255) into a 16-bit 565 encoding. """ try: red, green, blue = red # see if the first var is a tuple/list except TypeError: pass return (red & 0xf8) << 8 | (green & 0xfc) << 3 | blue >> 3
4c1f2c28313c35f839fa189b45fb15abfa715cd1
643,010
from typing import Mapping def _flatten_dict(d, prefix=''): """ Convert a nested dict: {'a': {'b': 1}} -> {'a--b': 1} """ out = {} for k, v in d.items(): if isinstance(v, Mapping): out = {**out, **_flatten_dict(v, prefix=prefix + k + '--')} else: out[prefix + k] = v return out
fb19771e7aad5b1df832ae95694b2182bcde2725
148,057
def mass(self): """get mass""" return self._mass
522c1acb9c154f707ece2a75ad675c7e9b35a338
331,169
def x_forwarded_ip(request): """ Returns the IP Address contained in the 'HTTP_X_FORWARDED_FOR' header, if present. Otherwise, `None`. Should handle properly configured proxy servers. """ ip_address_list = request.META.get('HTTP_X_FORWARDED_FOR') if ip_address_list: ip_address_list = ip_address_list.split(',') return ip_address_list[0]
3b346c3fe2404cf637cea66a12f89e41ad87aed6
146,110
def float2String(input, ndigits=0): """ Round and converts the input, if int/float or list of, to a string. Parameters ---------- input: int/float or list of int/float ndigits: int number of decimals to round to Returns ------- output: string or list of strings depending on the input """ output = input if not isinstance(input, list): output = [output] output = [round(x, ndigits) for x in output] output = list(map(int, output)) output = list(map(str, output)) if not isinstance(input, list): output = output[0] return output
3c2794e1d9b3b4809eb5878895cbc1b246120c94
526,323
def remove_forbidden_keys(data): """Remove forbidden keys from data Args: data (list): A list of dictionaries, one per transactions Returns: list: A list of dictionariess, one per transaction, with forbidden keys removed """ # There are different forbidden keys based on the report requested forbidden_keys = ["customer id", "space/lpn"] new_data = [] for row in data: new_row = {k: v for k, v in row.items() if k.lower() not in forbidden_keys} new_data.append(new_row) return new_data
c0aea19a433e36ab97a827045d576311761a8506
220,358
def RestoreListType(response, key_triggers=()): """Step (recursively) through a response object and restore list types that were overwritten by SOAPpy. Lists with only one element are converted by SOAPpy into a dictionary. This handler function restores the proper type. Args: response: dict Response data object. Returns: dict Restored data object. """ if not key_triggers: return response if isinstance(response, dict): if not response.keys(): return response dct = {} for key in response.keys(): value = response.get(key) if key in key_triggers and not isinstance(value, list): value = [value] data = RestoreListType(value, key_triggers) dct[str(key)] = data return dct elif isinstance(response, list): lst = [] for item in response: lst.append(RestoreListType(item, key_triggers)) return lst else: return response
414c7eb4c88838ea6d21977b1f50e16e3db80a13
148,418
def get_asset_url(release, quiet=False): """ get the assets url from the release information :return: the assets_url """ return release["assets_url"]
38815dce5158c4980e57a4cf7aa7a386e371e57f
632,206
def hour_of_day(datetime_col): """Returns the hour from a datetime column.""" return datetime_col.dt.hour
18b2f6e16ccbcb488f3863968466fda14f669d8b
706,249
def find_service_by_type(cluster, service_type): """ Finds and returns service of the given type @type cluster: ApiCluster @param cluster: The cluster whose services are checked @type service_type: str @param service_type: the service type to look for @return ApiService or None if not found """ for service in cluster.get_all_services(): if service.type == service_type: return service return None
fd04adce95c71499e17a143d7c94c0cf1aa603c9
28,818
def largest_factor(n): """Return the largest factor of n*n-1 that is smaller than n. >>> largest_factor(4) # n*n-1 is 15; factors are 1, 3, 5, 15 3 >>> largest_factor(9) # n*n-1 is 80; factors are 1, 2, 4, 5, 8, 10, ... 8 """ factor = n - 1 while factor > 0: if (n*n-1) % factor == 0: return factor factor -= 1
deaad22f8a5c11a696c8410b8d179b0dc38c8a93
636,311
def add_required_cargo_fields(toml_3p): """Add required fields for a Cargo.toml to be parsed by `cargo tree`.""" toml_3p["package"] = { "name": "chromium", "version": "1.0.0", } return toml_3p
1c8d061f8b53fe3cd82c5c2130e13aef07a92670
146,192
import math def quat_to_euler(q): """returns yaw, pitch, roll at singularities (north and south pole), assumes roll = 0 """ # See http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/ eps=1e-14 qw = q.w; qx = q.x; qy = q.z; qz = -q.y pitch_y = 2*qx*qy + 2*qz*qw if pitch_y > (1.0-eps): # north pole] yaw = 2*math.atan2( qx, qw) pitch = math.asin(1.0) roll = 0.0 elif pitch_y < -(1.0-eps): # south pole yaw = -2*math.atan2( qx, qw) pitch = math.asin(-1.0) roll = 0.0 else: yaw = math.atan2(2*qy*qw-2*qx*qz , 1 - 2*qy**2 - 2*qz**2) pitch = math.asin(pitch_y) roll = math.atan2(2*qx*qw-2*qy*qz , 1 - 2*qx**2 - 2*qz**2) return yaw, pitch, roll
94c1c36c20abeb0875f16ff83bc5aaa3dadd5ffd
159,596
def describe(df): """Shorthand for df.describe() Args: df (`pandas.DataFrame`): The dataframe to describe Returns: summary: Series/DataFrame of summary statistics """ return df.describe()
25a637bf7df4ca566ed871f91a3d8860e32eee62
411,069
def ternary_expr(printer, ast): """Prints a ternary expression.""" cond_str = printer.ast_to_string(ast["left"]) # printer.ast_to_string(ast["cond"]) then_expr_str = printer.ast_to_string(ast["middle"]) # printer.ast_to_string(ast["thenExpr"]) else_expr_str = printer.ast_to_string(ast["right"]) # printer.ast_to_string(ast["elseExpr"]) return f'{cond_str} ? {then_expr_str} : {else_expr_str}'
f88fc65b684bff7ad61e0bc64d17b65bbe7735e5
28,675
def _combine_paths(path): """ Turn path list into edge list. :param path: List. A list of nodes representing a path. :returns: List. A list of edge tuples. """ edges = [] for i, node in enumerate(path[1:]): edges.append((path[i], node)) return edges
7dae202ad637a9360e5a929840989aab34366ece
268,619