content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def MAX(src_column): """ Builtin maximum aggregator for groupby Example: Get the maximum rating of each user. >>> sf.groupby("user", ... {'rating_max':tc.aggregate.MAX('rating')}) """ return ("__builtin__max__", [src_column])
59d030a07fafb6f254149d264b3a4feb9431ed28
634,434
def base_url(application_settings, base_path): """ Returns the service URL.""" return 'http://localhost:%s%s' % (application_settings['APP_PORT'], base_path)
1976659865ed11ddadcb4b6bfad87e362550c926
182,932
def create_element(type, props=None, *children): """ Convenience function to create a dictionary to represent a virtual DOM node. Intended for use inside ``Widget._render_dom()``. The content of the widget may be given as a series/list of child nodes (virtual or real), and strings. Strings are converted to text nodes. To insert raw HTML, use the ``innerHTML`` prop, but be careful not to include user-defined text, as this may introduce openings for XSS attacks. The returned dictionary has three fields: type, props, children. """ if len(children) == 0: children = None # i.e. don't touch children elif len(children) == 1 and isinstance(children[0], list): children = children[0] return dict(type=type, props=props or {}, children=children, )
4160c04e9c3031879fab3501914f75a61139f55e
119,407
from typing import Dict from typing import Union def od_parse(data: str) -> Dict[str, Union[str, list]]: """Parse od command output without argument, return a dict with the following keys: hex, ascii, list, text Returns: dict: with key hex, ascii, list, text """ text, asc_data, hex_data, list_data = "", "", "", [] for line in data.split("\n"): for d in line.split(" ")[1:]: h = hex(int(d, 8))[2:].zfill(4) a, b = int(h[2:], 16), int(h[:2], 16) text += chr(a) + chr(b) hex_data += "0x%x 0x%x " % (a, b) asc_data += "%s %s " % (a, b) list_data += [a, b] return {"hex": hex_data.strip(), "ascii": asc_data.strip(), "list": list_data, "text": text}
c9eb69a988063009971af373dd88da6101a0dfe8
646,050
def unix_to_windows_path(path_to_convert, drive_letter='C'): """ For a string representing a POSIX compatible path (usually starting with either '~' or '/'), returns a string representing an equivalent Windows compatible path together with a drive letter. Parameters ---------- path_to_convert : string A string representing a POSIX path drive_letter : string (Default : 'C') A single character string representing the desired drive letter Returns ------- string A string representing a Windows compatible path. """ if path_to_convert.startswith('~'): path_to_convert = path_to_convert[1:] if path_to_convert.startswith('/'): path_to_convert = path_to_convert[1:] path_to_convert = '{}{}{}'.format(drive_letter, ':\\', path_to_convert).replace('/', '\\') return path_to_convert
d3c23e2c19be4b81be135ae84760430be852da41
2,603
def is_valid_structure(ext): """ Checks if structure format is compatible with GROMACS """ formats = ['tpr', 'gro', 'g96', 'pdb', 'brk', 'ent'] return ext in formats
1b2af60c2f60df0eb5aa8a43fd8df5494d8b7830
563,474
def versions_match(versions): """Check if the versions are the same""" base = None for name in versions: if base is None: base = versions[name] elif base != versions[name]: return False return True
6d02c9170302a18e14dfac393f1b573d491d3545
653,346
def split(iterable, function): """ Split an iterable into two lists according to test function :param iterable iterable: iterable of values to be split :param function function: decision function ``value => bool`` :returns: tuple( list with values for which function is `True`, list with values for which function is `False`,) Example _______ >>> split([1,2,3,4,5,6], lambda x: x<3) ([1, 2], [3, 4, 5, 6]) """ match = [] unmatch = [] for value in iterable: if function(value): match.append(value) else: unmatch.append(value) return match, unmatch
ede20fcc80bd126410a8417d1e91dee2e530c9af
41,121
def load_text(input_file): """Load text from a text file and return as a string.""" with open(input_file, "r") as file: text = file.read() return text
effaea8e8f19f15d59abadbe4a71b6a3d8828f90
336,998
def binary_string(number: int) -> str: """Number to binary string :param number: some number (an integer) to turn into a binary string :return: Some string which is the binary string :rtype: str .. doctest:: python >>> binary_string(200) '11001000' >>> binary_string(10) '1010' """ return bin(number)[2:]
aa22bcc4ddd5546805db333c9b0be2e7f0e1c703
681,850
def delete_max_length(data_in, data_out=None, max_length=20): """ Delete phrases with more than `max_length` characters. """ idx_to_remove = [count for count, sent in enumerate(data_in) if len(sent) > max_length] print(idx_to_remove) for idx in reversed(idx_to_remove): del data_in[idx] if data_out is not None: del data_out[idx] if data_out is not None: idx_to_remove = [count for count, sent in enumerate(data_out) if len(sent) > max_length] for idx in reversed(idx_to_remove): del data_in[idx] del data_out[idx] return data_in, data_out else: return data_in
0af5e71f6815b5f5e0086c262433a24da9c59695
423,809
import re def find_application_includes(path): """ Build a set that contains the vtk includes found in the file. :param path: The path to the application file. :return: The includes that were found. """ includes = set() include_hdr1 = re.compile(r'((?:vtk|QVTK).*\.h)') include_hdr2 = re.compile(r'(\w+QtQuick\.h)') content = path.read_text() incs = include_hdr1.findall(content) includes.update(incs) incs = include_hdr2.findall(content) includes.update(incs) return includes
96f5e4ae024d691ece9188e66c6b0d795150d513
236,158
def train_network(net, epochs, training_data, validation_data, batch_size, callbacks, verbose=1): """ train a network on data for a fixed number of epochs parameters: net: network to train epochs: number of epochs training_data: training data under the format of numpy arrays (inputs, labels) validation_data: validation data under the format of numpy arrays (inputs, labels) batch_size: size of batch for training callbacks: callbacks wanted for the training verbose: display of training (1:yes, 2: no) """ print('\nStart the training') hist = net.fit(training_data[0], training_data[1], epochs=epochs, batch_size=batch_size, verbose=verbose, shuffle=True, validation_data=(validation_data[0], validation_data[1]), validation_steps=int(len(validation_data[0])/batch_size), callbacks=callbacks) return hist
d89704adc14bf2b609fa7bdb2300d59c4b2b5b1f
648,267
def get_current_valid_edges(current_nodes, all_edges): """ Returns edges that are present in Cytoscape: its source and target nodes are still present in the graph. """ valid_edges = [] node_ids = {n['data']['id'] for n in current_nodes} for e in all_edges: if e['data']['source'] in node_ids and e['data']['target'] in node_ids: valid_edges.append(e) return valid_edges
3f09ac58e7d7beb9bd68a99653bb8ccc6db1909a
297,969
import csv def read_from_csv(fn): """Read in the CSV file and return a list of (email, password) tuples""" users = [] csvfile = csv.reader(open(fn, "r")) for row in csvfile: if row[0] != "": users.append(row) return users
f495330ce4cc8d7d325ff7b16795faa0bafec063
88,481
def scurve(start,end,n,s): """Return an S-Curve with a constant velocity section from start to end with n points. The start and end S-curves each have s points""" ys,ye = start,end s1 = [ (ye-ys)*(x*x-s*s)/(2*s*float(n-1))+ys for x in range(0,s) ] cv = [ (ye-ys)*(x-s)/float(n-1)+ys for x in range(s,s+n) ] s2 = [ (ye-ys)*((s+n)*(s+n)+(4*s+2*n)*(x-s-n)-x*x)/(2*s*float(n-1))+ye for x in range(s+n+1,s+n+s+1) ] return s1+cv+s2
a16ba1143cdeff9a8392a2c993b88918dff82350
646,470
import yaml def read_yaml(file_path): """ Reads YAML file and return a dictionary """ with open(file_path) as f: return yaml.safe_load(f)
e3d29ad6bd2e233f058ba65521e36d9c0564e570
521,217
def extended_gcd(a, b): """ I don't claim any copyright on this. I copied it from the internet somewhere. Extended Greatest Common Divisor Algorithm. Returns: gcd: The greatest common divisor of a and b. s, t: Coefficients such that s*a + t*b = gcd Reference: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode """ old_r, r = a, b old_s, s = 1, 0 old_t, t = 0, 1 while r: quotient, remainder = divmod(old_r, r) old_r, r = r, remainder old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t return old_r, old_s, old_t
93222993bafb69fd96dbd3d963edcd0c243225b4
350,313
def ms_to_cs(ms): """Convert Millisecons to Centiseconds""" return ms / 10
19114824f6495215c4caa77cd458118ca2b17594
389,876
import operator def filter_by_count(df, col, method, value, norm=False): """Filter a dataframe to return a subset of rows determined by their value_counts(). For example, we can return rows with users who appear at least 5 times in the dataframe, or with users who appear less than 10 times, or who appear exactly once. Parameters ----------- col: str Name of dataframe column to filter by. method: str Symbol specifying which operation to use for filtering. One of ('=', '<', '>', '<=', '>='). value: int, float Numeric value that each row in `col` will be compared against. norm: bool If True, filtering will occur on normalized values (so the value should be a float between 0 and 1). Returns -------- pd.DataFrame Examples --------- Return rows containing users who appear at least 5 times: df.filter_by_count('user_id', '>=', 5) Return rows containing users who appear only once: df.filter_by_count('user_id', '=', 1) Return rows containing users who make up less than 20% of rows: df.filter_by_count('user_id', '<', .2, True) """ operation = {'=': operator.eq, '>': operator.gt, '<': operator.lt, '>=': operator.ge, '<=': operator.le } counts = df[col].value_counts(norm).loc[lambda x: operation[method](x, value)] return df[df[col].isin(counts.index)]
fd700dfe3daf641b72e4a29d40061f8d5e4e14f5
326,810
def reorder_minibatch(minibatch_data, minibatch_label): """ Helper method that sorts the minibatch data and labels so that the samples are sorted in order from longest to shortest. This is makes it more efficient to pad different-length samples, according to https://stackoverflow.com/questions/51030782/why-do-we-pack-the-sequences-in-pytorch (Taken from Dr. Laurent's batching example) Returns a tuple of sorted lists: (data, labels) """ temp = sorted(zip(minibatch_data, minibatch_label), key=lambda x: len(x[0]), reverse=True) list1, list2 = map(list, zip(*temp)) return list1, list2
9993250026b5c3bf81c4b3bd91889548684201bc
488,758
def fmt_ms(ms): """Take a time in milliseconds and convert it to mm:ss.ms""" time = int(ms) minutes = int(time / (60 * 1000)) time -= minutes * (60 * 1000) seconds = time / 1000 return str(minutes) + ':' + "{seconds:.3f}".format(seconds=seconds)
c9d256d7f6a59b25748016f024f2fdf44db7d687
377,975
import math def evap_fract_time_fingas(heavy, c1, time, T, c2 = None): """ Return the evaporated fraction [] source : (Fingas, 2015) Parameters ---------- heavy : True if the fuel need to follow a ln, else it will be a sqrt C : fingas constant time : Time from the spill [s] T : Temperature [K] c2 : second fingas constant, can be compute by defaut [] """ if c1 is None: raise Exception("The mix does not have Fingas constant c1 defined") if(time < 60): #else it will cause trouble with the log return 0 b = 0 T = T - 273.15 if heavy: if c2 is None: c2 = 0.045 #b = 15+273.15 return (c1 + c2 * (T - b)) * math.log(time/60) #temperature in [K], time in sec else: if c2 is None: c2 = 0.01 #b = 15+273.15 return (c1 + c2 * (T - b)) * math.sqrt(time/60)
9241a61b15ad8df26be787b657ddad4c6de8e3a1
368,840
from pathlib import Path import json def load_dict(file_path: Path) -> dict: """Loads a json file into a dictionary.""" with file_path.open('r') as infile: return json.load(infile)
c2f8c0806b327d947c982c2ad2facd7b7d9b0417
364,197
def guarded_unpack_sequence(it, spec, _getiter_): """Protect nested sequence unpacking. Protect the unpacking of 'it' by wrapping it with '_getiter_'. Furthermore for each child element, defined by spec, guarded_unpack_sequence is called again. Have a look at transformer.py 'gen_unpack_spec' for a more detailed explanation. """ # Do the guarded unpacking of the sequence. ret = list(_getiter_(it)) # If the sequence is shorter then expected the interpreter will raise # 'ValueError: need more than X value to unpack' anyway # => No childs are unpacked => nothing to protect. if len(ret) < spec['min_len']: return ret # For all child elements do the guarded unpacking again. for (idx, child_spec) in spec['childs']: ret[idx] = guarded_unpack_sequence(ret[idx], child_spec, _getiter_) return ret
8c16e404a238eea45d8286feaafa9f8e78aa1f01
490,238
def no_resize(packing, cell): """Don't do any resizing""" return packing, cell
4d50c6c5219c37bd848905788060cb5c096041d8
128,775
import requests def read_build_cause(job_url, build_id): """Read cause why the e2e job has been started.""" api_query = job_url + "/" + str(build_id) + "/api/json" response = requests.get(api_query) actions = response.json()["actions"] cause = None for action in actions: if "_class" in action and action["_class"] == "hudson.model.CauseAction": cause = action["causes"][0] # None or real build cause return cause
80c3aafc29ae9eed1a7e4165962c4a50281779dd
675,989
def _parse_package_name(name: str) -> str: """ Force lower case and replace underscore with dash to compare environment packages (see https://www.python.org/dev/peps/pep-0426/#name) Args: name: Unformatted package name Returns: Formatted package name """ return name.lower().replace("_", "-")
0257cbae7d8c25b31d089c983a0185c67cff6e2d
678,053
import pickle def load_pickle(file_pkl): """Receives a path of a pickle file and loads it. :param file_pkl: str referencing a .pkl file :returns: the object loaded""" with open(file_pkl,'rb') as open_file: object = pickle.load(open_file) return object
16726cf976821e02c263ec6705203e127f34feb3
142,714
def nice_bytes(number, lang='', speech=True, binary=True, gnu=False): """ turns a number of bytes into a string using appropriate units prefixes - https://en.wikipedia.org/wiki/Binary_prefix spoken binary units - https://en.wikipedia.org/wiki/Kibibyte implementation - http://stackoverflow.com/a/1094933/2444609 :param number: number of bytes (int) :param lang: lang_code, ignored for now (str) :param speech: spoken form (True) or short units (False) :param binary: 1 kilobyte = 1024 bytes (True) or 1 kilobyte = 1000 bytes (False) :param gnu: say only order of magnitude (bool) - 100 Kilo (True) or 100 Kilobytes (False) :return: nice bytes (str) """ if speech and gnu: default_units = ['Bytes', 'Kilo', 'Mega', 'Giga', 'Tera', 'Peta', 'Exa', 'Zetta', 'Yotta'] elif speech and binary: default_units = ['Bytes', 'Kibibytes', 'Mebibytes', 'Gibibytes', 'Tebibytes', 'Pebibytes', 'Exbibytes', 'Zebibytes', 'Yobibytes'] elif speech: default_units = ['Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Terabytes', 'Petabytes', 'Exabytes', 'Zettabytes', 'Yottabytes'] elif gnu: default_units = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] elif binary: default_units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'] else: default_units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] units = default_units if binary: n = 1024 else: n = 1000 for unit in units[:-1]: if abs(number) < n: if number == 1 and speech and not gnu: # strip final "s" unit = unit[:-1] return "%3.1f %s" % (number, unit) number /= n return "%.1f %s" % (number, units[-1])
89680dabf2e71c15769e2d1c33b54f6a10cdec67
586,462
import re def smart_truncate1(text, max_length=100, suffix='...'): """Returns a string of at most `max_length` characters, cutting only at word-boundaries. If the string was truncated, `suffix` will be appended. """ if len(text) > max_length: pattern = r'^(.{0,%d}\S)\s.*' % (max_length-len(suffix)-1) return re.sub(pattern, r'\1' + suffix, text) else: return text
cf957435d6d7d168d819670fed0dcd52d7ff0f67
309,022
def train_val_test_split(time_series, train_start_timestamp, train_end_timestamp, val_end_timestamp): """ Splits a given time series in training data, validation data and test data. Args: time_series (pandas.core.series.Series): input time series. train_start_timestamp (string): initial timestamp of training data train_end_timestamp (string): final timestamp of training data val_end_timestamp (string): final timestamp of validation data Returns: numpy.ndarray: training time series numpy.ndarray: validation time series numpy.ndarray: test time series """ train = time_series[train_start_timestamp:train_end_timestamp].values val = time_series[train_end_timestamp:val_end_timestamp].values test = time_series[val_end_timestamp:].values return train, val, test
eeb18f27b4afda423125787af82d21d5a961d041
278,024
def grid_frames(params: dict): """ Generate frame parameters for individual grid data frames when performed in step mode. :param params: run parameters :return: list of dictionaries representing a frame each """ return ( { 'name': params['name'], 'uuid': params['uuid'], 'saved': False, 'first': i + 1, 'start': params['angle'], 'delta': params['delta'], 'exposure': params['exposure'], 'energy': params['energy'], 'distance': params['distance'], 'two_theta': params.get('two_theta', 0.0), 'attenuation': params.get('attenuation', 0.0), 'directory': params['directory'], 'p0': point, } for i, point in enumerate(params['grid']) )
338bc0a6e4f0d34daa2ca725448c032f1ba99269
137,079
from typing import Any from typing import Union import re def replace_variables( input_string: str, interface: Any, key: Union[int, None] = None ) -> str: """ In a string, attempt to replace all the "$$X" variables with their definitions from the interface. If not found in the interface, it skips the variable, leaving it to the user to replace afterwards Args: input_string (str): String containing $$X variables interface (Any): An interface key (Union[int, None], optional): If the replacement string is a data structure, use this key to index it. Defaults to None. Returns: str: Updated string """ regex_variable = re.compile(r"\$\$[^_|\W]+") for variable in re.findall(regex_variable, input_string): try: new_variable = getattr(interface, variable[2:]) except AttributeError: continue else: if isinstance(new_variable, (list, tuple)): if key is None: raise ValueError new_variable = new_variable[key] input_string = input_string.replace(variable, str(new_variable)) return input_string
6827b9907772fe81b026bd6009fcc4670787d656
431,211
def _BuildCustomMetricUtilizations(args, messages): """Builds custom metric utilization policy list from args. Args: args: command line arguments. messages: module containing message classes. Returns: AutoscalingPolicyCustomMetricUtilization list. """ result = [] if args.custom_metric_utilization: for custom_metric_utilization in args.custom_metric_utilization: result.append( messages.AutoscalingPolicyCustomMetricUtilization( utilizationTarget=custom_metric_utilization[ 'utilization-target'], metric=custom_metric_utilization['metric'], utilizationTargetType=( messages .AutoscalingPolicyCustomMetricUtilization .UtilizationTargetTypeValueValuesEnum( custom_metric_utilization['utilization-target-type'], ) ), ) ) return result
74ba408772546b30a0b9fce1a681a9ef6ea295af
194,421
def gcd(number1: int, number2: int) -> int: """Counts a greatest common divisor of two numbers. :param number1: a first number :param number2: a second number :return: greatest common divisor""" number_pair = (min(abs(number1), abs(number2)), max(abs(number1), abs(number2))) while number_pair[0] > 0: number_pair = (number_pair[1] % number_pair[0], number_pair[0]) return number_pair[1]
9f22c315cc23e2bbf954f06d416a2c44f95ddbb7
705,416
def win_check(board, mark): """ function that takes in a board and checks to see if someone has won. :param board: the board to check :param mark: the last mark in placed in the board :return: True if game is win or False otherwise """ return ((board[7] == mark and board[8] == mark and board[9] == mark) or (board[4] == mark and board[5] == mark and board[6] == mark) or (board[1] == mark and board[2] == mark and board[3] == mark) or (board[7] == mark and board[4] == mark and board[1] == mark) or (board[8] == mark and board[5] == mark and board[2] == mark) or (board[9] == mark and board[6] == mark and board[3] == mark) or (board[7] == mark and board[5] == mark and board[3] == mark) or (board[9] == mark and board[5] == mark and board[1] == mark))
38cad514d38aa42fdb88ebe4cb174f2999a9ae9b
664,866
def normalize_timedelta(timedelta): """ Given a string like "1w" or "-5d", convert it to an integer in milliseconds. Integers without a suffix are interpreted as seconds. Note: not related to the datetime timedelta class. """ try: return int(timedelta) * 1000 except ValueError as e: t, suffix = timedelta[:-1], timedelta[-1:] suffix_multipliers = {'s': 1000, 'm': 1000*60, 'h': 1000*60*60, 'd': 1000*60*60*24, 'w': 1000*60*60*24*7, 'M': 1000*60*60*24*30, 'y': 1000*60*60*24*365} if suffix not in suffix_multipliers: raise ValueError() return int(t) * suffix_multipliers[suffix]
097d519e9b6a41b67d61c4b2af09be6e47fdb91f
487,524
def flatten(a): """recursively flatten n-nested array example: >>> flatten([[1,2],[3,4],[5,6,[7,8],]]) [1, 2, 3, 4, 5, 6, 7, 8] """ if isinstance(a, list): b = list() for a_ in a: if isinstance(a_, list): b.extend(flatten(a_)) else: b.append(a_) return(b) else: return(a)
d58e5f32446c1b750b4da676faff480461646e54
307,298
def chop_end_of_string(str_input, str_remove): """Function that strips the supplied str_remove from the end of the input string Parameters ---------- str_input: `str` A string to be chopped str_remove: `str` The string to be removed from the end of the input Returns ------- str: `str` A string that contains the new string """ if str_input.endswith(str_remove): return str_input[:-len(str_remove)] return str_input
792b95a6ae33faffdd4632f2785c3161ebea9bad
258,672
import random def pick_pivot(l, r): """ Picks a pivot element at random from the 25-75% input percentile. Params: l - left most index to pick as pivot r - right most index to pick as pivot Return: int - a randon number in [l, r] """ return random.randint(l, r)
4638a4df1de7d317276ad64b129165d46141cee4
453,523
def throughput_history(summaries): """Calculates the change in completion for a list of summaries. Args: summaries (List[ProjectSummary]): List of project summaries to analyze Returns: List[int]: The change in number of items complete between each set of two summaries provided. """ history = [] for i in range(len(summaries)-1): throughput = summaries[i+1].complete - summaries[i].complete if throughput < 0: throughput = 0 history.append(throughput) return history
5d1b2d2b4d285d9002ca56586f32ce0916981e55
311,061
from typing import Dict def get_headers(token: str) -> Dict[str, str]: """ Returns authorization header for the data registry with the provided token. :param token: personal access token :return: Authorization headers """ return {"Authorization": f"token {token}"} if token else {}
79b47ed3c81f2162ade773db9fc0d933d9f00942
150,900
def hook_TakeOver(state): """Implements `DeepState_TakeOver`, returning 1 to indicate that it was hooked for symbolic execution.""" return 1
a9bc8000a9873f655cb361b0df4a67dffbb99742
160,465
def _theoretical_logit_grad(x): """Reference implementation for the gradient of the logit function.""" return 1 / (x * (1.0 - x))
6baf81891db30961b5e35d6f2e98a5397bca797f
294,479
def chrtonam(c): """Find unique elements in an iterable and in what order they appear. Return a 3-tuple (uniqelements, eltoindex, map): uniqelements -- elements in order of first appearance eltoindex -- map from elements to their indices in uniqelements; equivalent to dict((el, i) for (i, el) in uniqelements) map -- indices of uniqelements in the order in which they appeared, such that c[i] = uniqelements[map[i]] """ d = {} nam = [] for tile in c: d.setdefault(tile, len(d)) nam.append(d[tile]) chrdata = [None] * len(d) for (tile, tn) in d.items(): chrdata[tn] = tile return chrdata, d, nam
38d901196a81ebdf29441fc4bfde64a76929d4a3
488,055
def get_computers_with_policy_and_relay_list(api, configuration, api_version, api_exception, relay_list_id, policy_id): """ Search for computers that are assigned to a specific policy and relay list. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :param api_version: The version of the API to use. :param api_exception: The Deep Security API exception module. :param relay_list_id: The ID of the relay list. :param policy_id: The ID of the policy. :return: A Computers object that contains matching computers """ # Set search criteria for platform policy_criteria = api.SearchCriteria() policy_criteria.field_name = "policyID" policy_criteria.numeric_test = "equal" policy_criteria.numeric_value = policy_id # Set search criteria for relay relay_criteria = api.SearchCriteria() relay_criteria.field_name = "relayListID" relay_criteria.numeric_test = "equal" relay_criteria.numeric_value = relay_list_id # Create the search filter search_filter = api.SearchFilter(None, [policy_criteria, relay_criteria]) # Include the minimum information in the returned Computer objects expand = api.Expand(api.Expand.none) # Perform the search computers_api = api.ComputersApi(api.ApiClient(configuration)) return computers_api.search_computers(api_version, search_filter=search_filter, expand=expand.list(), overrides=False)
4fd4603cea8c1a2484daa582d74982ef756019f3
136,955
def is_unitless(ds, variable): """ Returns true if the variable is unitless Note units of '1' are considered whole numbers or parts but still represent physical units and not the absence of units. :param netCDF4.Dataset ds: An open netCDF dataset :param str variable: Name of the variable """ units = getattr(ds.variables[variable], "units", None) return units is None or units == ""
8574327f657e67d2165f247a8892c38eab89784f
648,232
def encode(tokenizer, question, context): """encodes the question and context with a given tokenizer""" encoded = tokenizer.encode_plus(question, context) return encoded["input_ids"], encoded["attention_mask"]
b821896a42414d9df617fd9c8a2456d26f23e724
414,117
from typing import Iterable def scheduler_story(keys: set, transition_log: Iterable) -> list: """Creates a story from the scheduler transition log given a set of keys describing tasks or stimuli. Parameters ---------- keys : set A set of task `keys` or `stimulus_id`'s log : iterable The scheduler transition log Returns ------- story : list """ return [t for t in transition_log if t[0] in keys or keys.intersection(t[3])]
7b6a3bb377ff962acdd9bd47855a83e388fc56be
116,993
def splitstring(string, split_character=' ', part=None): """ Split a string based on a character and get the parts as a list string: The string to split split_character: The character to split for the string. The default is ' '. part: Get a specific part of the list. The default is None. """ if part is None: return str(string).split(split_character) return str(string).split(split_character)[part]
9bf12cbb989380ccab8a3dd88bf12490ad1bf0c3
297,260
def parse_data(data, objects_format, separator=" "): """ Takes a list of strings and a list of objects format and returns a list of objects formatted according to the objects format. Example: parse_data(['forward 10', 'left 90', 'right 90'], [{'key': 'command, 'format': str}, {'key': 'value', 'format': int}], " ") => [{'command': 'forward', 'value': 10}, {'command': 'left', 'value': 90}, {'command': 'right', 'value': 90}] """ result = [] for line in data: line_result = {} for i, value in enumerate(line.split(separator)): line_result[objects_format[i]["key"]] = objects_format[i]["format"](value) result.append(line_result) return result
55702626a122957834566073f32ba2612bb4fbb5
537,334
from typing import Dict from typing import Any def _make_pod_envconfig( config: Dict[str, Any], relation_state: Dict[str, Any] ) -> Dict[str, Any]: """Generate pod environment configuration. Args: config (Dict[str, Any]): configuration information. Returns: Dict[str, Any]: pod environment configuration. """ return { # General configuration "ALLOW_ANONYMOUS_LOGIN": "yes", "GIN_MODE": config["gin_mode"], "NRF_HOST": relation_state["nrf_host"], }
3f41f89f9bdf25ab6a75c5206943df5437092d1c
74,376
def ClusterKey(cluster, key_type): """Return a cluster-generated public encryption key if there is one. Args: cluster: Cluster to check for an encryption key. key_type: Dataproc clusters publishes both RSA and ECIES public keys. Returns: The public key for the cluster if there is one, otherwise None """ master_instance_refs = cluster.config.masterConfig.instanceReferences if not master_instance_refs: return None if key_type == 'ECIES': return master_instance_refs[0].publicEciesKey return master_instance_refs[0].publicKey
073ce9fb790b8fcdaabded2c8f9a4ec649f10850
643,752
def best_neighbor_match_check(k_neighbors_labels): """ Returns the value with the most repetitions in `k_neighbors`. """ k_neighbors_labels.sort() longest_repeats = current_repeats = 0 current_value = best_match_value = k_neighbors_labels[0] for value in k_neighbors_labels: if value == current_value: current_repeats += 1 else: current_repeats = 1 current_value = value if longest_repeats < current_repeats: longest_repeats = current_repeats best_match_value = current_value return best_match_value
d56ab1a5683768767da2bc00306e1aaa3665343a
441,227
def file_to_string(sql_path): """Converts a SQL file holding a SQL query to a string. Args: sql_path: String containing a file path Returns: String representation of a file's contents """ with open(sql_path, 'r') as sql_file: return sql_file.read()
f63542f756ac85efdb1ec82ec9ed4f629e548fee
609,970
import torch def compute_distances(x, n_particles, n_dimensions, remove_duplicates=True): """ Computes the all distances for a given particle configuration x. Parameters ---------- x : torch.Tensor Positions of n_particles in n_dimensions. remove_duplicates : boolean Flag indicating whether to remove duplicate distances and distances be. If False the all distance matrix is returned instead. Returns ------- distances : torch.Tensor All-distances between particles in a configuration Tensor of shape `[n_batch, n_particles * (n_particles - 1) // 2]` if remove_duplicates. Otherwise `[n_batch, n_particles , n_particles]` """ x = x.reshape(-1, n_particles, n_dimensions) distances = torch.cdist(x, x) if remove_duplicates: distances = distances[:, torch.triu(torch.ones((n_particles, n_particles)), diagonal=1) == 1] distances = distances.reshape(-1, n_particles * (n_particles - 1) // 2) return distances
e6d39e9855c57f5a926054df032cd70ba58d38e9
87,573
def combine(intervals): """combine overlapping and adjacent intervals. >>> combine([(10,20), (30,40)]) [(10, 20), (30, 40)] >>> combine([(10,20), (20,40)]) [(10, 40)] >>> combine([(10,20), (15,40)]) [(10, 40)] """ if not intervals: return [] new_intervals = [] intervals.sort() first_from, last_to = intervals[0] for this_from, this_to in intervals[1:]: if this_from > last_to: new_intervals.append((first_from, last_to)) first_from, last_to = this_from, this_to continue if last_to < this_to: last_to = this_to new_intervals.append((first_from, last_to)) return new_intervals
e30fc920ab5d1174551412603d2bb95a865438e0
466,301
import math def _atand(v): """Return the arc tangent (measured in in degrees) of x.""" return math.degrees(math.atan(v))
c395efa781f3ea6aa0d6ab6926a09325cd7ea0ea
147,524
def get_key_padding_mask(padded_input, pad_idx): """Creates a binary mask to prevent attention to padded locations. Arguements ---------- padded_input: int Padded input. pad_idx: idx for padding element. Example ------- >>> a = torch.LongTensor([[1,1,0], [2,3,0], [4,5,0]]) >>> get_key_padding_mask(a, pad_idx=0) tensor([[False, False, True], [False, False, True], [False, False, True]]) """ if len(padded_input.shape) == 4: bz, time, ch1, ch2 = padded_input.shape padded_input = padded_input.reshape(bz, time, ch1 * ch2) key_padded_mask = padded_input.eq(pad_idx).to(padded_input.device) # if the input is more than 2d, mask the locations where they are silence # across all channels if len(padded_input.shape) > 2: key_padded_mask = key_padded_mask.float().prod(dim=-1).bool() return key_padded_mask.detach() return key_padded_mask.detach()
234d5f947b7042c5edad68e9b8162e4bbf6963f3
20,113
def rank_features(explanation): """ Given an explanation of type (name, value) provide the ranked list of feature names according to importance Parameters ---------- explanation : list Returns ---------- List contained ranked feature names """ ordered_tuples = sorted(explanation, key=lambda x : abs(x[1]), reverse=True) results = [tup[0] if tup[1] != 0 else ("Nothing shown",0) for tup in ordered_tuples] return results
f1d14296434f800fc03313cb447a44a2c11ea123
661,727
def interval_width(interval): """Returns half the width of an interval, given by a list""" return (interval[1]-interval[0])/2+(interval[1]+interval[0])/2
77147c99368ef5591cd7a3dc97badde9a21d17e9
328,397
def uniqify(seq): # Dave Kirby """ Return only unique items in a sequence, preserving order :param list seq: List of items to uniqify :return list[object]: Original list with duplicates removed """ # Order preserving seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
a1a15b06f2c632c9a95dca7b687177e264e5551e
102,491
from typing import Union def _create_table_row(key: str, value: Union[str, int], highlight: bool = False) -> str: """ Create table row for stats panel """ template_stats_data = """ <tr style="border-bottom: 1px solid;"> <th style="text-align: left">{key}</th> <td style="text-align: left">{value}</td> </tr> """ template_stats_data_red = """ <tr style="color: #f00; border-bottom: 1px solid;"> <th style="text-align: left">{key}</th> <td style="text-align: left">{value}</td>\ </tr> """ return ( template_stats_data_red.format(key=key, value=value) if highlight else template_stats_data.format(key=key, value=value) )
362154b67151f9f6c1d996c1e9ee67cbcf8b7ea3
61,313
def dict_to_list(dictionary, order_list): """ Create a list from dictionary, according to ordering in order_list """ #assert sorted(order_list) == sorted(dictionary.keys()) wc_list = [] for wc_name in order_list: wc_list.append(dictionary[wc_name]) return wc_list
8d61f8fe2729ab6cfec0258771180d7106b372ac
232,041
import requests def make_request(endpoint): """ Make a request to the given URL and return the response. """ return requests.get( f"https://api.audioboom.com{endpoint}", # The API needs version specifying headers={'Accept': 'application/json; version=1'} ).json()["body"]
8811fcf685980e8bc043bd6cfeab9942942a39fa
424,941
from typing import List def list_squares(n: int) -> List[int]: """Generates a list of squares of numbers from 0 to n using list comprehension. doctests: >>> list_squares(2) [0, 1, 4] >>> list_squares(5) [0, 1, 4, 9, 16, 25] """ x = [i ** 2 for i in range(0, n + 1)] return x
e88dc5807fb81a39d48f92bae5d8cb692769861c
114,480
def cell_trap_getter_generator(priv_attr): """ Generates a getter function for the cell_trap property. """ def getter(self): if getattr(self, priv_attr) is None: data =\ ( self.gfpffc_bulb_1 - self.gfpffc_bulb_bg )/self.gfpffc_bulb_bg setattr(self, priv_attr, data) return getattr(self, priv_attr) return getter
15217adbd96ce44b361444867e5d9c6d202440f4
13,951
def set_difference(dependent,independent): """ This function compares two lists, and takes their set-theoretical difference: dependent - independent arguments: dependent, independent """ return list(set(dependent)-set(independent))
bd7e85b53fda26378330f780e57b89c0d05d5d33
562,464
def new_value_part_2(seat: str, visible_count: int) -> str: """ Returns the next state for one seat. """ if seat == "L" and visible_count == 0: return "#" elif seat == "#" and 5 <= visible_count: return "L" else: return seat
6b8dcaecfd5a62fbb8a5c9333dc8ec180cc814ca
654,295
def create_rg_azure(resourceGroup, tag, source): """Create Terraform Module for Azure Resource Group.""" tf_module_rg = { "source": "%s/m-azure-rg" % source, "resourceGroupName": resourceGroup['name'], "resourceGroupRegion": resourceGroup['region'], "tagEnvironment": tag } return tf_module_rg
bbde0748b54063a00004bb1590b22fb2b634b7eb
144,534
def lambda_handler(event, context): """ Expects input of the form: [ [ Input, [ O1 ] ], ... [ Input, [On ] ] ] Returns: [ O1, ... On ] """ return [ e[1][0] for e in event ]
c27ba001018491de387ecdb0b670bf01f8dfd47d
555,920
def create_tlink_attributes(reltype, id1, id2, link_id, origin): """Create a dictionary with tlink attibutes. Arguments: reltype - string id1 - string id2 - string link_id - string of the form l\d+ origin - string Returns a dictionary.""" # NOTE: this method should perhaps be moved elsewhere, possibly to # a Tlink class attrs = {} if id1.startswith('e'): attrs['eventInstanceID'] = id1 else: attrs['timeID'] = id1 if id2.startswith('e'): attrs['relatedToEventInstance'] = id2 else: attrs['relatedToTime'] = id2 attrs['relType'] = reltype attrs['lid'] = link_id attrs['origin'] = origin return attrs
032db530493ce3ace31782c1e8e9db9c045df681
163,636
def prettify_cve_announcement(cve_announcement, api_url): """Format a cve_announcement to be human friendly.""" return ( f"[{cve_announcement.cve_code}] {cve_announcement.content}\n" f"Score: {cve_announcement.score}\n" f"Exploit code maturity: {cve_announcement.exploit_code_maturity}\n" f"Link: {api_url}/cve_announcements/{cve_announcement.cve_code}\n" )
0a8d8890954703e4aaf47aecf7159b9ecdc38822
429,390
def _autoname_plots(plotlist, sequential=False): """ Automatically name any plots that were not given a name by the user. """ namelist = [] count = 0 for plot in plotlist: if plot.get('type') == 'figure': continue name = plot.get('axes') if name is None: if sequential: num = count else: num = 0 name = '_autoname_{:02d}'.format(num) count += 1 plot['axes'] = name namelist.append(name) # Extract the unique names in order. namelist = list(dict.fromkeys(namelist)) return namelist
d34f409e7a8e6bb6e931c2680dd68a785e4082b1
545,218
def maybe_add_slash(path): """Add a final trailing slash if it wasn't there already""" with_trailing_slash = path if path.endswith('/') else path + '/' return with_trailing_slash
117f670b47ad6e6d1df26c54d09ed0c771c2d273
582,437
def expected_error_node_kwargs(node_kwargs): """Return the expected error message depending on node_kwargs.""" if 's' in node_kwargs: return "Please use 'node_size' and not 'node_kwargs'" elif 'c' in node_kwargs: return "Please use 'node_color' and not 'node_kwargs'"
b935445f34542a8257c76194fae55fa188a2e31c
489,283
def del_from_dict(dictionary, srcip, dstip): """Removes an entry from the given dictionary. Assumed is that srcip and dstip exist in the dictionary. :param dictionary: dictionary to remove an entry from :type dictionary: dictionary :param srcip: source ip :type srcip: string :param dstip: destination ip :type dstip: string :return: dictionary """ if len(dictionary[srcip]['targets']) <= 1: del dictionary[srcip] else: del dictionary[srcip]['targets'][dstip] return dictionary
2833371c38ff09cb4f9a7cc7e0af16b41973c3f6
275,205
def create_function_from_source(function_source, imports=None): """Return a function object from a function source Parameters ---------- function_source : unicode string unicode string defining a function imports : list of strings list of import statements in string form that allow the function to be executed in an otherwise empty namespace """ ns = {} import_keys = [] try: if imports is not None: for statement in imports: exec(statement, ns) import_keys = list(ns.keys()) exec(function_source, ns) except Exception as e: msg = "Error executing function\n{}\n".format(function_source) msg += ( "Functions in connection strings have to be standalone. " "They cannot be declared either interactively or inside " "another function or inline in the connect string. Any " "imports should be done inside the function." ) raise RuntimeError(msg) from e ns_funcs = list(set(ns) - set(import_keys + ["__builtins__"])) assert len(ns_funcs) == 1, "Function or inputs are ill-defined" func = ns[ns_funcs[0]] return func
2fa6c5ed6778270a4a2b1c2e02c0203a3d463e10
637,299
def slice_z_center(mesh): """Slice mesh through center in z normal direction, move to z=0.""" slice_mesh = mesh.slice(normal='z') slice_mesh.translate((0, 0, -slice_mesh.center[-1]), inplace=True) return slice_mesh
3278fec43db960698866443bc10e79a260b5eeb2
299,652
import zlib def decompress_data(data): """ Decompresses the data with zlib :param data: :return: """ return zlib.decompress(data)
6dd778eae0331291d979d82a8fe9aad17a92e48a
557,633
def isblankstr(line): """ check for blank string :param line: :return bool: """ return len(line.strip()) == 0
0719369d0d83ca0b36bc8969ccea541b122b9906
382,278
def iterable_response_to_dict(iterator): """ Convert Globus paginated/iterable response object to a dict """ output_dict = {"DATA": []} for item in iterator: dat = item try: dat = item.data except AttributeError: pass output_dict["DATA"].append(dat) return output_dict
9764718a922a310b2892e1896657dd2af24e7a8f
47,912
def _check_size(node, size=0): """Recursive function, visits all nodes and counts number of elements. Return the number of elements.""" if node is None: return size else: size += 1 size = _check_size(node.left_node, size) # Go down the left tree size = _check_size(node.right_node, size) # Go down the right tree return size
d7693cc1caba672a1e6f7f5a527d731ce3dd9690
355,539
def GetUpdatesUrl(project_name, max_results=1000): """Construct the URL to the issues updates for the given project.""" return ('http://code.google.com/feeds/p/%s' '/issueupdates/basic?max-results=%d' % (project_name, max_results))
b0b369420391a8faf2cb99e0a2398475e9c022ed
497,673
from pathlib import Path def _get_data_size_of_dir(path: Path) -> float: """Returns the data volume / size of a directory given at path. Parameters ---------- path : Path Path for which the size should be determined Returns ------- float Value between 0 and the max size of your disk in mega bytes. """ return round(sum(f.stat().st_size for f in path.glob("**/*") if f.is_file()) / 1024**2, 4)
4e37752889f67837584b9b8859d131765238dc51
537,251
from typing import Type from typing import Any from typing import Set def _get_all_subclasses(cls: Type[Any]) -> Set[Type[Any]]: """Returns a list of all classes that inherit directly or indirectly from the given class.""" subclasses = set() def recurse(cl: Type[Any]) -> None: for subclass in cl.__subclasses__(): subclasses.add(subclass) recurse(subclass) recurse(cls) return subclasses
3ae35c1e5f967211ae2865b51c536d4e68a1a92b
443,880
def coco2pascal(box): """Convert bounding box coordinates from Coco format to Pascal VOC. Go from [x, y, width, height] to [x1, y1, x2, y2]. """ x, y, width, height = box return [x, y, x + width, y + height]
484b6a51e68d98df6b13b487cb0d7989c81765e4
213,171
def merge(ll, rl): """Merge given two lists while sorting the items in them together :param ll: List one (left list) :param rl: List two (right list) :returns: Sorted, merged list """ res = [] while len(ll) != 0 and len(rl) != 0: if ll[0] < rl[0]: res.append(ll.pop(0)) else: res.append(rl.pop(0)) if ll: res = res + ll if rl: res = res + rl return res
0b88eea3733d0ac2739faff57b36faf6841d0446
663,103
def filtrar_cortas(texto, chars=0): """Filtra líneas en texto de longitud chars o inferior. Parameters ---------- texto : str Texto que se quiere filtrar. chars : int Mínimo número de caracteres en una línea de texto. Returns ------- str Texto filtrado. """ filtrado = "" for linea in texto.splitlines(): if len(linea) > chars: filtrado += linea + "\n" return filtrado
3a1568f94e31965f962a0a969271154555bf24ec
471,601
def get_numeric_columns(df): """ # Returns a list of numeric columns of the dataframe df # Parameters: # df (Pandas dataframe): The dataframe from which extract the columns # Returns: # A list of columns names (strings) corresponding to numeric columns """ numeric_columns = list(df._get_numeric_data().columns) return numeric_columns
6ec1cb8d1a8dd9c4cb49f17257b137e9ec0d4210
654,222
def dotp(a, b): """Dot product of two equal-dimensioned vectors""" return sum(aterm * bterm for aterm,bterm in zip(a, b))
502fba46bf2284a1b7d48572c38cef1d1a188c11
576,307
def line_plot(ax, x, ys, labels=None, styles=None, param_dict=None): """ A helper function to make a line graph Parameters ---------- ax : Axes The axes to draw to x : array The x data ys : array The y data labels : list The ys labels param_dict : dict Dictionary of kwargs to pass to ax.plot Returns ------- out : list list of artists added """ for i, y in enumerate(ys): if labels is not None: if styles is not None: ax.plot(x, y, label=labels[i], linestyle=styles[i]) else: ax.plot(x, y, label=labels[i]) else: ax.plot(x, y) if param_dict is not None: ax.set_xlabel(param_dict['xlabel']) # Add an x-label to the axes. ax.set_ylabel(param_dict['ylabel']) # Add a y-label to the axes. ax.set_title(param_dict['title']) # Add a title to the axes. ax.legend() # Add a legend return ax
837867df9029f9a1c78cf448079e19e3ba9a17b3
627,669
def reconstruction_loss(reconstruction, orig): """ Computes the reconstruction loss :param reconstruction: batch x im_size :param orig: batch x im_ht x im_wd :return rloss: The reconstruction loss """ rloss = ((reconstruction - orig.view(orig.size(0), orig.size(1), -1)) ** 2).mean(-1) rloss = rloss.mean() return rloss
24e25a08f35ff9724ace694f08d8c2f7ce597d01
309,124
def generate_uniform_prior(params, indent=4): """ Generates the JAGS prior declarations for a list of parameters. The strings are generated using a specifiable number of indentation whitespaces. """ prior_strings = [] for p in params: prior_strings.append( "{}{} ~ dunif(0, 1)".format("".join([" "] * indent), p)) return prior_strings
a1e3d670466643f7f18e25296d974218c874218e
159,498
def aggregate_values_from_key(host_state, key_name): """Returns a set of values based on a metadata key for a specific host.""" aggrlist = host_state.aggregates aggregate_vals = set() for aggr in aggrlist: if key_name in aggr.metadata: aggregate_vals.add(aggr.metadata[key_name]) return aggregate_vals
e720c5aec3af230edfd0f3180357be9c858f9ba9
500,513
def compute_frequencies(words): """ Args: words: list of words (or n-grams), all are made of lowercase characters Returns: dictionary that maps string:int where each string is a word (or n-gram) in words and the corresponding int is the frequency of the word (or n-gram) in words """ Bdict = {} #Bdict is a dictionary that maps each string with its frequency for i in words: if i in Bdict.keys(): Bdict[i] += 1 else: Bdict[i] = 1 return Bdict
47f6c1f717a080277ea13fd1255def1bb444b2ea
174,983
def is_int(s : str) -> bool: """ Check if string is an int. """ try: float(s) except Exception as e: return False return float(s).is_integer()
f83b1c7c683807397880f685cf6913d2270f5252
100,808
def url_from_id(id): """Returns URL of article with given ID""" return "https://www.ncbi.nlm.nih.gov/pubmed/" + id
3dff22b1c8f20f3379de682af01d768ef75412ca
225,632
def get_environment(certificate): """Return environment associated with certificate. """ STAGING_ENV = "Fake LE Intermediate X1" for component in certificate.get_issuer().get_components(): if component[0] == 'CN': if component[1] == STAGING_ENV: return 'staging' else: return 'production' return None
e83379a87b30b15cbe58e6909850ad33a556b63a
396,102