content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import math def Vabrms_calc(va,vb): """Inverter terminal voltage - line to line RMS""" return abs(va-vb)/math.sqrt(2)
aeb9b30990513f88d4a671c7de035d0a5cd64296
10,048
import re def get_value(text, regex, value_type=float): """Dump a value from a file based on a regex passed in.""" pattern = re.compile(regex, re.MULTILINE) results = pattern.search(text) if results: return value_type(results.group(1)) else: print("Could not find the value {}, in the text provided".format(regex)) return value_type(0.0)
6c4b9990dab2d8fe9f55c7a8f8c97011d3857b01
10,050
def numberofdupes(string, idx): """return the number of times in a row the letter at index idx is duplicated""" # "abccdefgh", 2 returns 1 initial_idx = idx last = string[idx] while idx+1 < len(string) and string[idx+1] == last: idx += 1 return idx-initial_idx
e5b9aa310c821683632dbec1ce3ab9a8bf8a08b7
10,051
def _decline(di, t, qoi, b): """Arp's equation for general decline in a well - qoi: initial rate of production - di: initial decline rate - b: curvature (b=0 exponential) """ return qoi / ((1 + b * di * t) ** (1 / b))
86368cef4d7d24bff738d5fe4acde2a1a9fb8922
10,057
import hashlib def gen_robohash(s, size=200): """Return URL for robohash pic for sha1 hash of string ``s``""" h = hashlib.sha1(s).hexdigest() return ('http://robohash.org/{0}.png?size={1}x{1}&bgset=bg2&set=set1' .format(h, size))
f4ac71b54801a3b86e3ec4e0cf60f25a9cae5990
10,058
from typing import Any import attr def validated() -> Any: """Decorate an entity to handle validation. This will let ``attrs`` manage the class, using slots for fields, and forcing attributes to be passed as named arguments (this allows to not have to defined all required fields first, then optional ones, and resolves problems with inheritance where we can't handle the order) Returns ------- type The decorated class. Examples -------- >>> from isshub.domain.utils.entity import required_field, validated, BaseEntity >>> >>> @validated() ... class MyEntity(BaseEntity): ... my_field: str = required_field(str) >>> >>> MyEntity.__slots__ ('my_field',) >>> >>> instance = MyEntity() Traceback (most recent call last): ... TypeError: __init__() missing 1 required keyword-only argument: 'my_field' >>> instance = MyEntity(my_field='foo') >>> instance.my_field 'foo' >>> instance.validate() >>> instance.my_field = None >>> instance.validate() Traceback (most recent call last): ... TypeError: ("'my_field' must be <class 'str'> (got None that is a <class 'NoneType'>)... """ return attr.s(slots=True, kw_only=True, eq=False)
6903d654e74b6bd6fc2d062755823043125c922a
10,065
def keep_type(value): """ Keep hook returned value type :param value: Value to be returned :return: Any """ return value
f5048e2863aca6eced8c3be76a3623fd5f3a808e
10,071
def find_nodes(graph, query, data=False): """ Iterator over all nodes matching the data query. """ return ((v, graph.nodes[v]) if data else v for v in graph if query(graph.nodes[v]))
e8f2e25f843133446c32ca7f012ac2aa1b80d2b9
10,076
def _SigninUIState(oobe): """Returns the signin ui state of the oobe. HIDDEN: 0, GAIA_SIGNIN: 1, ACCOUNT_PICKER: 2, WRONG_HWID_WARNING: 3, MANAGED_USER_CREATION_FLOW: 4. These values are in chrome/browser/resources/chromeos/login/display_manager.js """ return oobe.EvaluateJavaScript(''' loginHeader = document.getElementById('login-header-bar') if (loginHeader) { loginHeader.signinUIState_; } ''')
355b7ebbaf0010165109c27162ca70f5168abe05
10,077
import hmac import hashlib def generate_dendrite_mac(shared_secret: str, username: str, password: str, admin: bool) -> str: """ Generate a MAC for using in registering users with Dendrite. """ # From: https://github.com/matrix-org/dendrite/blob/master/clientapi/routing/register.go mac = hmac.new( key=shared_secret.encode('utf8'), digestmod=hashlib.sha1, ) mac.update(username.encode('utf8')) mac.update(b"\x00") mac.update(password.encode('utf8')) mac.update(b"\x00") mac.update(b"admin" if admin else b"notadmin") return mac.hexdigest()
bed29168d88db0d9b2bd0bf95f493a9d4b5e7a3f
10,080
def _cmpPair2(a, b): """Auxiliary comparision for sorting lists of pairs. Sorting on the second member of the pair.""" (x, y), (z, w) = a, b if y < w: return -1 elif y > w: return 1 elif x < z: return -1 elif x > z: return 1 else: return 0
5567ddc006756e224dde545503c427a3524c3c90
10,084
def toExport8F8(op): """Converts number to exportable 8.8 signed fixed point number.""" return int(round(op * 256.0))
3364703913e1c87223ffb11bdaf3b622db7eef1c
10,085
import math def LogRegressNomalize(value): """Uses log regress to normalize (-inf, inf) to [0, 1].""" value_exp = math.exp(value) return value_exp / (value_exp + 1)
a5d30077df70b3795754d62c6534781e61482f13
10,086
def to_dict(conf): """Converts a Config object to a dictionary. Args: conf (Config): A Config object Returns: dict: A multi-level dictionary containing a representation ogf the configuration. """ return conf._xpipe_to_dict()
6c709e04f1ffb88b5b5563defc2a03fabfafbb1e
10,096
def valid_hex(value): """Check if the string is a valid hex number representation.""" try: int(value, 16) except Exception: return False return True
4037b9103cd3308253f929d0a4cbbe3f37c1c219
10,099
def get_mapvars(mapfile): """Read the sugar .map file and return a dictionary where the key is the variable name and the value is the (start,r0,r1) where r0 is the first ordinal and r1 is the last. Sugar uses uniary encoding.""" mapvars = {} with open(mapfile,"r") as f: for line in f: (var,name,start,_) = line.strip().split(" ") if var=="int": if ".." in _: (r0,r1) = _.split("..") else: (r0,r1) = int(_),int(_) else: raise RuntimeError("Only variables of type {} are supported".format(var)) start = int(start) r0 = int(r0) r1 = int(r1) mapvars[name] = (start,r0,r1) return mapvars
c149270a4f1a86707b7ee5e2ed437b5736a2a986
10,100
def is_in_period(month, period): """Return which months fall within a specified group of calendar months. Parameters ---------- month : int or iterable of ints One or a series of calendar month numbers [1..12]. period : tuple of ints Group of calendar month numbers to match against. These are usually consecutive, e.g., [3, 4, 5] for MAM, but they don't have to be. Returns ------- return : bool or iterable of bools True for month numbers that are in the group. """ try: return [m in period for m in month] except TypeError: return month in period
e973f1ec11ea4dc6b87834c75d6374bbbb152635
10,105
def once(f): """Decorator. Defer to f once and only once, caching the result forever. Users with a functional background may recognize the concept of a `thunk`. """ unset = val = object() def _helper(*args, **kwargs): nonlocal val if val is unset: val = f(*args, **kwargs) return val return _helper
39e900779a6665155fe83770964e509ff88a12c4
10,106
import hashlib def _hash_file(fpath, chunk_size=65535): """ Calculates the md5 hash of a file :param fpath: path to the file being validated :param chunk_size: Bytes to read at a time (leave unless large files) :return: The file hash """ hasher = hashlib.md5() with open(fpath, 'rb') as fpath_file: for chunk in iter(lambda: fpath_file.read(chunk_size), b''): hasher.update(chunk) return hasher.hexdigest()
9f17f13f487f95620ad705a6f2b23d57407e640e
10,109
def midpoint(start, end): """Find the mid-point between two points.""" x0, y0 = start x1, y1 = end return (x0+x1)/2, (y0+y1)/2
dab5a66b8af759998a295d64ba3711b6e99e4c27
10,110
import re def replace_pair(pair, content): """ Uses regex to locate a pair. First element of the tuple is the original error token. Second element of the tuple is the replacement token. """ return re.sub(pair[0], ' {} '.format(pair[1]), content)
022633d417393959a94629117a1e664709770571
10,113
from datetime import datetime def extract_sitename_date(directory_path, sitename_location, datetime_location): """Extract sitename and datetime from directory path name. Parameters ----------- directory_path : string A path to the directory name sitename_location : index list Index of sitename location in directory path name datetime_location : index list Index of datetime location in directory path name Returns ----------- list : list of site names and datetime information """ # Create an empty list to append sitename and date information site_name_date_list = [] # Assign datetime location to an object date_location = directory_path[datetime_location[0]: datetime_location[1]] # Specify datetime format format = "%Y%m%d" # Use datetime and format to create date varibale date = datetime.strptime(date_location, format) # Assign sitename information to a variable site = directory_path[sitename_location[0]: sitename_location[1]] # Append site variable to list site_name_date_list.append(site) # Append date variable to list site_name_date_list.append(date) return site_name_date_list
86a2085ba68b234585ef9855da64fa1fdd5459ce
10,115
def multi_dict_unpacking(lst): """ Receive a list of dictionaries, join them into one big dictionary """ result = {} for d in lst: for key, val in d.items(): result[key] = val return result
530947224d682cffb809e83f308a97a108002080
10,118
import math def dist(a: list, b: list) -> float: """Calculate the distancie between 2 points Args: a (list): point a b (list): point b Returns: float: Distance between a and b """ return math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2)
7ad6d2f36c0bccee106c7b54a4abebd246c4a3fa
10,119
def get_middle_opt(string: str) -> str: """Get middle value of a string (efficient). Examples: >>> assert get_middle_opt('middle') == 'dd' """ return ( string[int(len(string) // 2) - 1 : int(len(string) // 2) + 1] if not len(string) % 2 else string[int(len(string) // 2)] )
1636f39e22bacc4f571de876dd71add690e940e6
10,121
def duration(duration): """Filter that converts a duration in seconds to something like 01:54:01 """ if duration is None: return '' duration = int(duration) seconds = duration % 60 minutes = (duration // 60) % 60 hours = (duration // 60) // 60 s = '%02d' % (seconds) m = '%02d' % (minutes) h = '%02d' % (hours) output = [] if hours > 0: output.append(h) output.append(m) output.append(s) return ':'.join(output)
7cd89654a84c2e3e41d96cb1b13688833ee54387
10,122
import types def name(function): """ Retrieve a pretty name for the function :param function: function to get name from :return: pretty name """ if isinstance(function, types.FunctionType): return function.__name__ else: return str(function)
4002d7a945c3b3e3e4d957c0b10ff202f2cf0246
10,123
import requests def get_response_json(url: str): """ Function get response json dictionary from url. :param url: url address to get response json :type url: str :return: dictionary data :rtype: json :usage: function calling .. code:: python get_response_json(url) """ response = requests.get(url) response.raise_for_status() return response.json()
dd209b1dba7f4320cd91addb1e49fa98bab0ae2b
10,124
import pickle def dumps_content(content): """ pickle 序列化响应对象 :param content: 响应对象 :return: 序列化内容 """ return pickle.dumps(content)
f88159b9d016a6e39744e7af09a76705c9f4e76f
10,125
def split_data(data, ratio, shuffle=1): """Split dataset according to ratio, larger split is first return""" n_exs = len(data[0]) split_pt = int(n_exs * ratio) splits = [[], []] for col in data: splits[0].append(col[:split_pt]) splits[1].append(col[split_pt:]) return tuple(splits[0]), tuple(splits[1])
fc837dd9f721950dde18cee9ec33eab5e3e96f77
10,133
def delBlank(strs): """ Delete all blanks in the str. """ ans = "" for e in strs: if e != " ": ans += e return ans
a6155af200918819055533057f63b4b44c8dd508
10,139
import re def splitn(s, n): """split string s into chunks no more than n characters long""" parts = re.split("(.{%d,%d})" % (n, n), s) map(parts.remove, [""] * parts.count("")) return parts
3f0f697f54515e26f98bc08b53cb4d39952ed128
10,140
import csv def LoadMOS(mos_csv): """Load a csv file withMOS scores. Args: mos_csv: Path to a csv file that has degraded and MOS. Returns: Dictionary with filename keys and MOS values """ mos_dict = {} with open(mos_csv, 'r') as csvfile: mos_reader = csv.reader(csvfile) for row in mos_reader: # Skip header if row[1] == 'MOS': continue mos_dict[row[0]] = row[1] return mos_dict
e98cbf93e3bc889a31a98ff32a9f9189a850a55f
10,142
import unicodedata def url_is_invalid_unicode(url_string): """ Check for unicode control characters in URL """ for x in str(url_string): if unicodedata.category(x)[0] == "C": return True return False
d1a3974b24023c46a337c7e17718e00aa5916c7d
10,143
import string def escape_bytes(bytes_): """ Convert a bytes object to an escaped string. Convert bytes to an ASCII string. Non-printable characters and a single quote (') are escaped. This allows to format bytes in messages as f"b'{utils.escape_bytes(bytes)}'". """ res = "" for byte in bytes_: char = chr(byte) if char == '\\': res += "\\\\" elif char == '\'': res += "\\'" elif char in (string.digits + string.ascii_letters + string.punctuation + ' '): res += char else: res += "\\x%0.2x" % byte return res
c1a6c2875824d8576e7d9c349f19548e2c3313e8
10,147
def shrink_dimensions(width, height, max_dimension): """ Resize dimensions so max dimension is max_dimension. If dimensions are too small no resizing is done Args: width (int): The width height (int): The height max_dimension (int): The maximum size of a dimension Returns: tuple of (small_width, small_height): A resized set of dimensions, as integers """ max_width_height = max(width, height) if max_width_height < max_dimension: return width, height ratio = max_width_height / max_dimension return int(width / ratio), int(height / ratio)
60d4a6ec9b310f7c22f341f1309b4677c3617fd2
10,148
import json def get_id_set(id_set_path: str) -> dict: """ Parses the content of id_set_path and returns its content. Args: id_set_path: The path of the id_set file Returns: The parsed content of id_set """ with open(id_set_path, 'r') as id_set_file: id_set = json.load(id_set_file) return id_set
244495603bf423324ef4b3ffe4b1fdc3ca7fdf74
10,152
def format_label_value(*values): """ Construct a label value. If multiple value components are provided, they are joined by underscores. """ return '_'.join(values)
46bb4e968577c95d5dd0df8b9687efbfdcc0568e
10,154
def _get_timeout(value): """ Turn an input str or int into a float timeout value. :param value: the input str or int :type value: str or int :raises ValueError: :returns: float """ maximum_dbus_timeout_ms = 1073741823 # Ensure the input str is not a float if isinstance(value, float): raise ValueError( "The timeout value provided is a float; it should be an integer." ) try: timeout_int = int(value) except ValueError: raise ValueError("The timeout value provided is not an integer.") # Ensure the integer is not too large if timeout_int > maximum_dbus_timeout_ms: raise ValueError( "The timeout value provided exceeds the largest acceptable value, %s." % maximum_dbus_timeout_ms ) # Convert from milliseconds to seconds return timeout_int / 1000
b8205cb34b90b856b4dda2a028f801b4cd70d7b4
10,158
def getAnswer(x,input_string): """Iegūst mainīgajam x vērtību 1 vai 2, parādot tekstu input_string. Ja ievadīta nepareiza vērtība, tad tiek paradīta kļūdas ziņa.""" while True: try: x = int(input(input_string)) if x < 1: raise ValueError elif x > 2: raise ValueError break except: print("Lūdzu ievadiet 1 vai 2.\n") return x
66f8b1cccef5fb710713f1c6498248dd0f3517ea
10,160
from typing import Optional from typing import Union import struct def encode_key( key: str, value: Optional[Union[int, float, str]] = None, value_type: str = "str" ) -> bytes: """Encode given header key to a bytes string. Parameters ---------- key : str header key value : Optional[Union[int, float, str]], optional value of the header key, by default None value_type : str, optional type of the header key, by default "str" Returns ------- bytes bytes encoded string """ if value is None: return struct.pack("I", len(key)) + key.encode() if value_type == "str" and isinstance(value, str): return ( struct.pack("I", len(key)) + key.encode() + struct.pack("I", len(value)) + value.encode() ) return struct.pack("I", len(key)) + key.encode() + struct.pack(value_type, value)
b38e04fdbd761bd121f0e08a9eee9dfb692f616c
10,161
import json def get_numeric_project_id(gcloud, project_id): """Get the numeric project ID.""" project_info = json.loads( gcloud.run('projects', 'describe', project_id, '--format=json')) return project_info['projectNumber']
f9e3086ed1436d4ce075960c191ff4f64a76582b
10,165
from functools import reduce from operator import add def fitness(individual,target): """ individual : the individual to evaluate (a list) target : the target sum the individuals are aiming for """ sum = reduce(add,individual,0) return abs(target-sum)
bcfb4d857be926df249149e224babbc98d358780
10,167
def create_schema(name: str) -> str: """Function for generating create schema statements :param str name: The name of the schema :return: Create statement :rtype: str """ statement = f"CREATE SCHEMA {name}" return statement
a82d392ec411e2c412ef3f1959ff7ab229130532
10,168
def courant(dx, dt, v_max, **kwargs): """ Calculate the Courant's number describing stability of the numerical scheme. Parameters ---------- dx : float Size of the spatial grid cell [m]. dt : float Time step [s]. v_max : float Max. velocity of the model. Returns ------- C : float Courant's number used later in CFL criterion C < C_max where C_max is scheme-specific. Notes ----- The smaller the more stable. If C > 1 the fastest wave in the model will be covering more than 1 grid cell per time step. """ # GRID VELOCITY (1 GRID-CELL PER TIME-STEP) IN PHYSICAL UNITS v_grid = dx / float(dt) # RATIO OF MAX AND GRID VELOCITY C = v_max / float(v_grid) return C
58b09b545c4679b845c3e2702af8bffe4262c599
10,169
import math def standard_deviation(series): """ implements the sample standard deviation of a series from scratch you may need a for loop and your average function also the function math.sqrt you should get the same result as calling .std() on your data https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.std.html See numpy documenation for implementation details: https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html """ pass avgnum = sum(series) / len(series) sumsq = 0 for each in series: t = each - avgnum sumsq = sumsq + pow(t,2) stdnum = math.sqrt(sumsq/(len(series)-1)) return stdnum
01a488f4bc8168a92d4a0590daa88bad08032fed
10,172
def unify_projection(dic): """Unifies names of projections. Some projections are referred using different names like 'Universal Transverse Mercator' and 'Universe Transverse Mercator'. This function replaces synonyms by a unified name. Example of common typo in UTM replaced by correct spelling:: >>> unify_projection({'name': ['Universe Transverse Mercator']}) {'name': ['Universal Transverse Mercator']} :param dic: The dictionary containing information about projection :return: The dictionary with the new values if needed or a copy of old one """ # the lookup variable is a list of list, each list contains all the # possible name for a projection system lookup = [['Universal Transverse Mercator', 'Universe Transverse Mercator']] dic = dict(dic) for l in lookup: for n in range(len(dic['name'])): if dic['name'][n] in l: dic['name'][n] = l[0] return dic
a3cdf4bb2a26ee0391281e8f8b0d3e7ea5c8a962
10,173
import requests def api_request(url, api_key=None): """ This function takes a url and returns the parsed json object. If necessary, it submits the auth header """ if api_key: return requests.get(url, headers={'Authorization': 'Token ' + api_key}).json() else: return requests.get(url).json()
ea8572d761dffb952b970ab14e73307a02f67ee8
10,184
def getbitlen(bint): """ Returns the number of bits encoding an integer """ return bint.bit_length()
f6ae3253e767382959d372eb5e4612fb85c89ffc
10,195
def calc_max_cpu(records): """ Returns the CPU usage at the max temperature, ever :param records: a list of records of min, max temp and associated CPU avg load :return: a record with the highest recorded temperature, and the associated list of CPU loads """ max_temp = 0 cpu_loads = [] for record in records: if record['max'] > max_temp: max_temp = record['max'] cpu_loads = [100 * record['cpu']] elif record['max'] == max_temp: cpu_loads.append(100 * record['cpu']) return max_temp, cpu_loads
bee21fadb3fcf9cdbbce79f6281f48350b3ffceb
10,198
from typing import List def longest_substring_using_nested_for_loop(s: str) -> int: """ Given a string s, find the length of the longest substring without repeating characters. https://leetcode.com/problems/longest-substring-without-repeating-characters/ 3946 ms 14.2 MB >>> longest_substring_using_nested_for_loop("abcabcbb") 3 >>> longest_substring_using_nested_for_loop("bbbbb") 1 >>> longest_substring_using_nested_for_loop("pwwkew") 3 """ total = 0 for idx, _ in enumerate(s): vals: List[str] = [] for c2 in s[idx:]: if c2 not in vals: vals += [c2] total = max((total, len(vals))) else: total = max((total, len(vals))) break return total
996ce5fcb956012cb75fef35c6bec8be6ecad461
10,202
import re def isSane(filename): """Check whether a file name is sane, in the sense that it does not contain any "funny" characters""" if filename == '': return False funnyCharRe = re.compile('[\t/ ;,$#]') m = funnyCharRe.search(filename) if m is not None: return False if filename[0] == '-': return False return True
d9e8bac7ebad1fd2af024f8880e255fcb40db68c
10,203
import csv import itertools def csv_read_row(filename, n): """ Read and return nth row of a csv file, counting from 1. """ with open(filename, 'r') as f: reader = csv.reader(f) return next(itertools.islice(reader, n-1, n))
a95cf8ed35b61acff418a02bfa5f8285f589e6d6
10,205
def load_proto(fpath, proto_type): """Load the protobuf Args: fpath: The filepath for the protobuf Returns: protobuf: A protobuf of the model """ with open(fpath, "rb") as f: return proto_type().FromString(f.read())
7b6bcf6d2e56f2ca4087a9ec769b16a986511c55
10,206
from typing import Union from pathlib import Path def _filename(path: Union[str, Path]) -> str: """Get filename and extension from the full path.""" if isinstance(path, str): return Path(path).name return path.name
552655ff66ec6cd42b57ada6080df9dc34db1bd0
10,211
import time def log_str(proc_str, start): """Create a preamble string for stdout.""" former = "[{:>4}".format(proc_str) latter = "] {:.2f}".format(round(time.time() - start, 3)) return former + latter
5f4f82e758cf87ff643a20928e5c0f7368ef537f
10,218
def linear_kernel(X, Y=None): """Compute linear Gram matrix between X and Y (or X) Parameters ---------- X: torch.Tensor of shape (n_samples_1, n_features) First input on which Gram matrix is computed Y: torch.Tensor of shape (n_samples_2, n_features), default None Second input on which Gram matrix is computed. X is reused if None Returns ------- K: torch.Tensor of shape (n_samples_1, n_samples_2) Gram matrix on X/Y """ if Y is None: Y = X K = X @ Y.T return K
b1389059e755fa19bb26c88cf8c9f6ab39d51aec
10,219
def split_date(dates): """ Split datetime64 dates into year, month, day components. """ y = dates.astype("<M8[Y]").astype(int) + 1970 m = dates.astype("<M8[M]").astype(int) % 12 + 1 d = (dates - dates.astype("<M8[M]")).astype("<m8[D]").astype(int) + 1 return y, m, d
7152dbdd1f839ef3c401de06631fb0a249c36642
10,220
def process_failed(returncode, stdout): """Return True if the process failed.""" if returncode != 0: return True if 'badly_formatted' in stdout: return True return False
2d3c84872acf3bf6592316aa95c39e41a6da849e
10,224
def evaluate_quadratic(J, g, s, diag=None): """Compute values of a quadratic function arising in least squares. The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s. """ if s.dim() == 1: Js = J.mv(s) q = Js.dot(Js) if diag is not None: q += s.dot(s * diag) else: Js = J.matmul(s.T) q = Js.square().sum(0) if diag is not None: q += (diag * s.square()).sum(1) l = s.matmul(g) return 0.5 * q + l
cde6067f22ef3a146b80fb5324c0c1a8ce2e65a4
10,225
def vdowham(eta, vel_entrain, e_eff, r_eff): """ Calculate the velocity parameter of the contact problem according to Dowson-Hamrock. Parameters ---------- eta: ndarray, scalar The dynamic viscosity of the lubricant. vel_entrain: ndarray, scalar The entrainment velocity of the contact problem. e_eff: ndarray, scalar The effective modulus of the contact problem. r_eff: ndarray, scalar The effective radius of the contact problem. Returns ------- param_velocity: ndarray, scalar The velocity parameter of the contact problem. """ param_velocity = eta * vel_entrain / (e_eff * r_eff) return param_velocity
e8abfcc3d312ffce0c192a3b890fe8f3a6785e76
10,234
def compute_convergence(output, output_prev): """ Compute the convergence by comparing with the output from the previous iteration. The convergence is measured as the mean of a XOR operation on two vectors. Parameters ---------- output, output_prev : np.ndarray Current and previous iteration binary outputs. Returns ------- float The model convergence between 0 (fully converged) and 1 (fully chaotic) """ if output is None or output_prev is None: return None return (output ^ output_prev).mean()
7ea1e931598ed8dcf8466fb4df327391943187c1
10,235
import json def get_profile_name(host, network): """ Get the profile name from Docker A profile is created in Docker for each Network object. The profile name is a randomly generated string. :param host: DockerHost object :param network: Network object :return: String: profile name """ info_raw = host.execute("docker network inspect %s" % network.name) info = json.loads(info_raw) # Network inspect returns a list of dicts for each network being inspected. # We are only inspecting 1, so use the first entry. return info[0]["Id"]
37128df21074c75e53e9567c51301c76578947f2
10,237
def _absolute_path(repo_root, path): """Converts path relative to the repo root into an absolute file path.""" return repo_root + "/" + path
bae7013db933e58343f0d6b3f90dfa100de74b7e
10,240
def aic(L, k): """ Akaike information criterion. :param L: maximized value of the negative log likelihood function :param k: number of free parameters :return: AIC """ return 2*(k + L)
159a02cc19d2b4eab30dd13c1cd2b802777277ad
10,242
def prepare_update_sql(list_columns, list_values, data_code=100): """ Creates a string for the update query :param list_columns: columns that are in need of an update :param list_values: values where the columns should be updated with :param data_code: data code to add to the columns :return: string with the columns and update values """ string = '' for i in enumerate(list_columns): if list_values[i[0]] is not None: if len(i[1]) >= 50: new_label = i[1][:50] + '_' + str(data_code) string = string + '`' + new_label + '`' + '= ' + '\'' + str(list_values[i[0]]) + '\'' + ', ' else: string = string + '`' + i[1] \ + '_' + str(data_code) + '`' + '= ' + '\'' + str(list_values[i[0]]) + '\'' + ', ' string = string.replace("None", "Null") return string[:-2]
cc3f3c548623bdeb4d2e4e12cc3205baf0a9e9ba
10,245
def onBoard(top, left=0): """Simplifies a lot of logic to tell if the coords are within the board""" return 0 <= top <= 9 and 0 <= left <= 9
2b2007ae2e3acdbb9c04c3df1397cffce97c6717
10,247
def name( path ): """Extracts the resource name.""" return path[1+path.rfind('/'):]
7e8448e5b1c62c30e7ae28c80580731aa9f6f9fb
10,250
def report_dfa(q_0, dfa, g): """ Give a complete description of the DFA as a string """ output = "" output += "----------- DFA ----------- " + "Goal: " + g + " ----------- \n" transitions = [(i,dfa[(i,sigma)],sigma) for i,sigma in dfa] transitions.sort() for i,j,sigma in transitions: output += (f"delta({i},{sigma}) = {j}\n") output += f"q_0 = {q_0}\n" return output
99d86557b9e1aede93f46e1ef78ecb1fe6cdbf30
10,251
def shutting_down(globals=globals): """ Whether the interpreter is currently shutting down. For use in finalizers, __del__ methods, and similar; it is advised to early bind this function rather than look it up when calling it, since at shutdown module globals may be cleared. """ # At shutdown, the attribute may have been cleared or set to None. v = globals().get('_shutting_down') return v is True or v is None
01f601b989611b06a438a3be3e15937eff389038
10,255
def add_xls_tag(file_name): """ Check the file_name to ensure it has ".xlsx" extension, if not add it """ if file_name[:-5] != ".xlsx": return file_name + ".xlsx" else: return file_name
e053d9f7dad8e638122e93d05e49c5a06de3e664
10,258
def pedestal_ids_file(base_test_dir): """Mock pedestal ids file for testing.""" pedestal_ids_dir = base_test_dir / "auxiliary/PedestalFinder/20200117" pedestal_ids_dir.mkdir(parents=True, exist_ok=True) file = pedestal_ids_dir / "pedestal_ids_Run01808.0000.h5" file.touch() return file
edda4c192e577774e0cc4a38aaa7d838127e7dcd
10,263
def get_fa_icon_class(app_config): """Return Font Awesome icon class to use for app.""" if hasattr(app_config, "fa_icon_class"): return app_config.fa_icon_class else: return 'fa-circle'
3766abb1f80b7ccea9e09a5edf011f1586e9b49e
10,264
from typing import Any def get_valid_ref(ref: Any) -> str: """Checks flow reference input for validity :param ref: Flow reference to be checked :return: Valid flow reference, either 't' or 's' """ if ref is None: ref = 't' else: if not isinstance(ref, str): raise TypeError("Error setting flow reference: Input is not a string") if ref not in ['s', 't']: raise ValueError("Error setting flow reference: Input is not 's' or 't', but {}".format(ref)) return ref
16c66dc9e0568bcd33e1cc9956ed31b5ae47595e
10,267
def cut_rod2(p, n, r={}): """Cut rod. Same functionality as the original but implemented as a top-down with memoization. """ q = r.get(n, None) if q: return q else: if n == 0: return 0 else: q = 0 for i in range(n): q = max(q, p[i] + cut_rod2(p, n - (i + 1), r)) r[n] = q return q
2fa1433dffb9099709e466025645c4981f289692
10,270
def monthly_file_name(var, model, rcp): """Function for creating file connections for different variables scenarios and models. Preasently, ensemble member r1i1p1 is assumed, as well as 200601-210012 dime span for the monthly data.""" # e.g. hfls_Amon_CNRM-CM5_rcp85_r1i1p1_200601-210012.nc f = var + "_" + "Amon_" + model + "_rcp" + rcp + "_r1i1p1_200601-210012.nc" return f
7aeea6d3724c470e076645ddb96877e9fa15843f
10,276
def subset(part, whole): """Test whether `part` is a subset of `whole`. Both must be iterable. Note consumable iterables will be consumed by the test! This is a convenience function. Examples:: assert subset([1, 2, 3], [1, 2, 3, 4, 5]) assert subset({"cat"}, {"cat", "lynx"}) """ return all(elt in whole for elt in part)
4200ea95e0c9ff03d0b7589812d0313c5d13cfac
10,279
from pathlib import Path def stem(fname, include_suffix=False): """/blah/my_file.json.gz --> my_file""" path = Path(fname) stem = path.stem # If a filename has multiple suffixes, take them all off. stem = stem[: stem.index(".")] if "." in stem else stem if include_suffix: stem = stem + "".join(path.suffixes) return stem
9e4c557dff8583f9129215f91f8e123f062ccf52
10,280
def atol(s, base=None): # real signature unknown; restored from __doc__ """ atol(s [,base]) -> long Return the long integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted. A trailing L or l is not accepted, unless base is 0. """ return 0
f39aa403cbad98c448a35305c97c595bc3a77c02
10,283
def tokens_to_sovatoms(tokens: float) -> int: """Convert tokens to sovatoms.""" return int(tokens * 100000000)
23f4bc3a1afc4520b5e2416332702d0a594c5039
10,284
def flow_cell_mode(info_reads): """Return flow cell sequencing mode.""" res = '' if info_reads: read_lens = [ a['num_cycles'] for a in info_reads if not a['is_indexed_read']] if len(read_lens) == 1: res = '1x{}'.format(read_lens[0]) elif len(set(read_lens)) == 1: res = '2x{}'.format(read_lens[0]) else: res = ' + '.join(map(str, read_lens)) index_lens = [ a['num_cycles'] for a in info_reads if a['is_indexed_read']] if index_lens: res += '/' if len(set(index_lens)) == 1: res += '{}x{}'.format(len(index_lens), index_lens[0]) else: res += '+'.join(map(str, index_lens)) return res or '?x?'
0563d0c163c2bd42b05d07fb30940669a8ef3513
10,289
def sortKey(e): """ This sorts the chores based on their start time. e[0] is the start time for all the chores in my array of chores. """ return int(e[0])
00d37751d23fe6210b406485cbd76906075b2578
10,290
def merge_into_dict(original, secondary): """Merge two dictionaries into the first and return it. This is simply a conveinence wrapper around the dictionary update method. In addition to the update it returns the original dict to allow for chaining. Args: original: The dict which will be updated. secondary: The dict which will be copied. Returns: The updated original dictionary. """ original.update(secondary) return original
899d40396885f0775f2cbaa865702ed0e5706dba
10,291
def normalize_obs(obs_dict, obs_normalization_stats): """ Normalize observations using the provided "mean" and "std" entries for each observation key. The observation dictionary will be modified in-place. Args: obs_dict (dict): dictionary mapping observation key to np.array or torch.Tensor. Leading batch dimensions are optional. obs_normalization_stats (dict): this should map observation keys to dicts with a "mean" and "std" of shape (1, ...) where ... is the default shape for the observation. Returns: obs_dict (dict): obs dict with normalized observation arrays """ # ensure we have statistics for each modality key in the observation assert set(obs_dict.keys()).issubset(obs_normalization_stats) for m in obs_dict: mean = obs_normalization_stats[m]["mean"] std = obs_normalization_stats[m]["std"] # check shape consistency shape_len_diff = len(mean.shape) - len(obs_dict[m].shape) assert shape_len_diff in [0, 1], "shape length mismatch in @normalize_obs" assert mean.shape[shape_len_diff:] == obs_dict[m].shape, "shape mismatch in @normalize obs" # handle case where obs dict is not batched by removing stats batch dimension if shape_len_diff == 1: mean = mean[0] std = std[0] obs_dict[m] = (obs_dict[m] - mean) / std return obs_dict
c866b6d18df13b9e6903b7d96024d48cde99d2ff
10,292
def get_bprop_l2_loss(self): """Grad definition for `L2Loss` operation.""" def bprop(x, out, dout): dx = x * dout return (dx,) return bprop
6f52c07d9133939f5a7dc6d12a2416169f32147e
10,297
def extract_tracklist_begin_num(content): """Return list of track names extracted from messy web content. The name of a track is defined as a line which begins with a number (excluding whitespace). """ tracklist = [] for line in content.splitlines(): # Empty line if not line: continue # Strip leading and trailing whitespace line.lstrip() line.rstrip() if line[0].isdigit(): tracklist.append(line) return tracklist
7d860fb0ea444ae0d9bd536a4644fa6b1c11a826
10,299
def net_solar_radiation(rs, albedo=0.23): """ Calculate the fraction of the solar radiation that is not reflected from the surface (Allen et al. 1998). Parameters ---------- rs : float Solar radiation (MJ m-2 day-1). albedo : float, optional Albedo (-), default is 0.23 (value for a hypothetical grass reference crop. Returns ------- float Net solar radiation (MJ m-2 day-1). """ return (1 - albedo) * rs
41a8930966db4a658d1c3ec31e754987bc9ed387
10,300
def text_color(message='{}', color_code='\033[0;37m'): """Set text to a color, default color is White""" no_color = '\033[0m' return f'{color_code}{message}{no_color}'
bede08b771b33ce26bbb0ee4fd42f3712d224cc1
10,301
def register_new_user(access, username, password): """ Register a new user & handle duplicate detection """ if access.user_data(username) is not None: raise ValueError("User '%s' already exists!" % username) if username in access.pending_users(): raise ValueError("User '%s' has already registered!" % username) access.register(username, password) if access.need_admin(): access.approve_user(username) access.set_user_admin(username, True) return True return False
25b98c4def9da81d71176aed196f61b2e71d64c5
10,306
def get_not_constant_species(model): """ get species of the model that are not constant @param model: libsbml.model @type model: libsbml.model @return: list of species @rtype: list[libsbml.species] """ def not_const(s): return not( s.getConstant() or s.getBoundaryCondition() ) return filter(not_const, model.getListOfSpecies())
abb376899405fa1623ec5ca646d0399e067fd5cc
10,307
from math import floor from typing import Tuple from typing import Union def conv_output_shape( h_w: Tuple[int, int], kernel_size: Union[int, Tuple[int, int]] = 1, stride: int = 1, padding: int = 0, dilation: int = 1, ) -> Tuple[int, int]: """ Calculates the output shape (height and width) of the output of a convolution layer. kernel_size, stride, padding and dilation correspond to the inputs of the torch.nn.Conv2d layer (https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) :param h_w: The height and width of the input. :param kernel_size: The size of the kernel of the convolution (can be an int or a tuple [width, height]) :param stride: The stride of the convolution :param padding: The padding of the convolution :param dilation: The dilation of the convolution """ if not isinstance(kernel_size, tuple): kernel_size = (int(kernel_size), int(kernel_size)) h = floor( ((h_w[0] + (2 * padding) - (dilation * (kernel_size[0] - 1)) - 1) / stride) + 1 ) w = floor( ((h_w[1] + (2 * padding) - (dilation * (kernel_size[1] - 1)) - 1) / stride) + 1 ) return h, w
ea757a413a3b38ea024b85dd6987beda8a3b9aeb
10,310
def _path(from_object, to_object): """ Calculates the 'path' of objects starting from 'from_object' to 'to_object', along with the index of the first common ancestor in the tree. Returns (index, list) tuple. """ if from_object._root != to_object._root: raise ValueError('No connecting path found between ' + str(from_object) + ' and ' + str(to_object)) other_path = [] obj = to_object while obj._parent is not None: other_path.append(obj) obj = obj._parent other_path.append(obj) object_set = set(other_path) from_path = [] obj = from_object while obj not in object_set: from_path.append(obj) obj = obj._parent index = len(from_path) i = other_path.index(obj) while i >= 0: from_path.append(other_path[i]) i -= 1 return index, from_path
0ccfe54d36832b8dce3c55168f02abb3c79261ef
10,312
def PtknsToStr(path_tokens): """ There are three ways to store paths: As a single string: '/Protein/Phe/Ca' <- the format entered by the user As a list of tokens ['Protein', 'Phe', 'Ca'] <- split into tokens As a list of nodes in a tree (pointers to nodes in a tree hierarchy) This function converts between the first two formats. """ text = '' if len(path_tokens) > 0: text = path_tokens[0] for i in range(1, len(path_tokens)): text += '/' + path_tokens[i] else: text = '' return text
8dd64e6213f8a49f5b20619261a4b3d8daa8d95d
10,321
def traverse_grid(start_cell, direction, num_steps): """ Helper function that iterates over the cells in a grid in a linear direction and returns a list of their indices. """ indices = list() for step in range(num_steps): row = start_cell[0] + step * direction[0] col = start_cell[1] + step * direction[1] indices.append((row, col)) return indices
0ce6f91759c36a63b103ebff2cddd8dd50ca837b
10,322
import requests def open_recipe_file(file, recipes_path=None, github_repo='bioconda/bioconda-recipes'): """ Open a file at a particular location and return contents as string """ if recipes_path: return open(f'{recipes_path}/{file}').read() else: # if no clone of the repo is available locally, download from GitHub r = requests.get(f'https://raw.githubusercontent.com/{github_repo}/master/{file}') if r.status_code == 404: raise OSError else: return r.content
ce5fc3c054bc937203966459e9981a5befdae40b
10,329
def confidence_interval(data, column_name, confidence_level): """ get a 95% confidence interval from a bootstrap dataframe column Parameters ---------- data : pandas dataframe the bootstrap dataframe generated by :py:func:`.bootstrapLE` column_name : string the statistic that you want the interval for, specified by the name of the column containing it confidence_level : float a real number between 0 and 1 that represents the desired confidence level. eg. 0.95 for 95%. Returns ---------- list a two-element list with the lower bound and upper bound. """ results = data[column_name].tolist() results.sort() lower_bound = int((1 - confidence_level) / 2 * len(results)) - 1 upper_bound = int((confidence_level + 1) / 2 * len(results)) - 1 if lower_bound < 0: lower_bound = 0 return [round(float(results[lower_bound]), 1), round(float(results[upper_bound]), 1)]
69668a88030c0a2d6d90dbc1b834cbab76d0ec17
10,330
def pig_latin(wrd): """Returns the Pig Latin version of a word. For words that begin with a consonant, take the consonant/consonant cluster and move it to the end of the word, adding the suffix 'ay' to the end of the word. For words that begin with a vowel, leave the word as is and add the suffix 'way' to the end of the word. >>> pig_latin('dog') 'ogday' >>> pig_latin('brush') 'ushbray' >>> pig_latin('elephant') 'elephantway' >>> pig_latin('awesome') 'awesomeway' >>> pig_latin('rhythm') 'rhythmay' """ idx = next((i for i, v in enumerate(wrd) if v in 'aeiou'), len(wrd)) return wrd[idx:] + (wrd[:idx] or 'w') + 'ay'
2eba5f4aaff1391e60f4097e526539d5b486c9bd
10,334
def parse_units(units_str): """ Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) >>> parse_units('Month [0,?]') ('Month', [-10, None]) >>> parse_units('Widgets [0,100]') ('Widgets', (0, 100)) >>> parse_units('Widgets') ('Widgets', (None, None)) >>> parse_units('[0, 100]') ('', (0, 100)) """ if not len(units_str): return units_str, (None, None) if units_str[-1] == "]": units, lims = units_str.rsplit("[") # types: str, str else: units = units_str lims = "?, ?]" lims = tuple( [float(x) if x.strip() != "?" else None for x in lims.strip("]").split( ",")] ) return units.strip(), lims
18f35a06aedfc9d026cfa70a1217b0b5b0420ca5
10,335
def seg_pixel_accuracy_nd(label_imask, pred_imask, vague_idx=-1, use_vague=False, macro_average=True, empty_result=0.0): """ The segmentation pixel accuracy (for MXNet nd-arrays). Parameters ---------- label_imask : mx.nd.array Ground truth index mask (maybe batch of). pred_imask : mx.nd.array Predicted index mask (maybe batch of). vague_idx : int, default -1 Index of masked pixels. use_vague : bool, default False Whether to use pixel masking. macro_average : bool, default True Whether to use micro or macro averaging. empty_result : float, default 0.0 Result value for an image without any classes. Returns ------- float or tuple of two floats PA metric value. """ assert (label_imask.shape == pred_imask.shape) if use_vague: mask = (label_imask != vague_idx) sum_u_ij = mask.sum().asscalar() if sum_u_ij == 0: if macro_average: return empty_result else: return 0, 0 sum_u_ii = ((label_imask == pred_imask) * mask).sum().asscalar() else: sum_u_ii = (label_imask == pred_imask).sum().asscalar() sum_u_ij = pred_imask.size if macro_average: return float(sum_u_ii) / sum_u_ij else: return sum_u_ii, sum_u_ij
7da093ef624dee07fd335021ae2317d53583e612
10,336
def extract_seed(path, key): """ Scrape the 5-character seed from the path and return it as an integer. :param path: path to the tsv file containing results :param key: substring preceding the seed, "batch-train" for splits, seed-" for shuffles """ try: i = path.find(key) + len(key) return int(path[i:i + 5]) except ValueError: return 0
c5073ad43e8a966aba5382894490aa6cbc871271
10,338