content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def compute_heat_transfer_area(LMTD, U, Q, ft): """ Return required heat transfer area by LMTD correction factor method. Parameters ---------- LMTD : float Log mean temperature difference U : float Heat transfer coefficient Q : float Duty """ return Q/(U*LMTD*ft)
fa55587d7a65cb59ca7a6bce0afb9e338d68095f
121,752
def leavesToString(leaves): """Return the leaves as concatenated string with whitespace separation.""" retstr = "" for e in leaves: retstr = retstr + e[0] + " " return retstr
a43fdfebbd000e4948c38557276b1fbba2aced57
121,757
import json def jsonLoad(filename): """ Import a .json file into a Python dictionary INPUT: filename.json file OUTPUT: json object """ with open(filename, 'r') as f: return json.load(f)
461344f0977b2ad83520061a3972ce70423ba19b
121,764
def get_option_or_default(options, option_name, default_value=None): """ Gets the first option's value from options or returns the default value :param options: the parsed options :param option_name: the name of the option for which get the value :param default_value the value to return if the parameter is not present :return: the obtained value or the default value if the parameter if the argument is not present """ return options.get(option_name) or default_value
a36724011a3b183f15f4a91b25d887d3f64facd3
121,766
import json def render_json(value): """ Render a dictionary as formatted JSON. This filter is invoked as "json": {{ data_dict|json }} """ return json.dumps(value, ensure_ascii=False, indent=4, sort_keys=True)
f07d31f90c015e40f766378878ba9a56901ce49d
121,767
def _adjust_component(value: int) -> int: """ Returns the midpoint value of the quadrant a component lies. By Maitreyi Patel 101120534 >>>_adjust_component(43) 31 >>>_adjust_component(115) 95 >>>_adjust_component(154) 159 >>>_adjust_component(210) 223 """ midpt = 0 if 255 >= value >=192: midpt = 223 if 191 >= value >=128: midpt = 159 if 127 >= value >=64: midpt = 95 if 63 >= value >=0: midpt = 31 return midpt
f37ec9782ba2c1edd6b9e0be9a92c9964de5707a
121,771
def get_node_id(ip): """A consul's node id is derived from the last two octets of its ip. Args: ip (string): Instance's ip address. Returns: (string): Node id as known to Consul cluster. """ octets = ip.split('.') return octets[2] + octets[3]
3d66f99a804222f5be55b388660b3d05c1f24b64
121,773
def format_agg_rois(rois): """ Helper function to format MultiImageMaths command. Parameters ---------- rois : `list` of `str`s List of files Returns ------- first_image op_files op_string """ return rois[0], rois[1:], ("-add %s " * (len(rois) - 1)).strip()
a5551bb0a4a3fcb3769e8f0cf20e1de6b34dccbe
121,776
def load_column_names(filename): """ Read the first line of the file and extract column names from it. Returns a dictionary with two elements: colnames A list of column names indices A dictionary of column indices, indexed by name """ f = open(filename, "r") line = f.readline() f.close() names = line.replace("#", "").replace(" ", "").replace("\n", "")\ .split(",") indices = {} for i in range(0, len(names)): indices[names[i]] = i return {"colnames": names, "indices": indices}
e834da74ceb0c338a26531ede656e88998cd69d8
121,780
import re import uuid def _renewUUIDs(jsonString): """Renew uuids in given text, by doing complete string replacements with newly generated uuids. Return the resulting text. """ RE_UUID = r"(?P<uuid>\w{8}-\w{4}-\w{4}-\w{4}-\w{12})" matches = re.findall(RE_UUID, jsonString) uuids = list(set(matches)) for original in uuids: replacement = str(uuid.uuid4()) jsonString = jsonString.replace(original, replacement) return jsonString
5123f0c2cd8a0ed099fe4d70fb06f93f5756def1
121,786
def autocomplete_getarg(line): """ autocomplete passes in a line like: get_memory arg1, arg2 the arg2 is what is being autocompleted on so return that """ # find last argument or first one is seperated by a space from the command before_arg = line.rfind(',') if(before_arg == -1): before_arg = line.find(' ') assert before_arg >= 0 # assign the arg. it skips the deliminator and any excess whitespace return line[before_arg+1:].lstrip()
91f4773de94259a1026e09ac32d2cb798b6ac5b4
121,788
import codecs def encode_punycode(string: str): """Encodes the string using Punycode. Example: >>> encode_punycode('hello')\n b'hello-' >>> decode_punycode(b'hello-')\n 'hello' """ if isinstance(string, str): temp_obj = string result = codecs.encode(temp_obj, "punycode") return result
ca1fea712198c93295f5d6dff5a5efe276987edf
121,789
import json def _write_json(file, contents): """Write a dict to a JSON file.""" with open(file, 'w') as f: return json.dump(contents, f, indent=2, sort_keys=True)
86f0809cb46d833135ac3941eef9916b23001d4e
121,790
def hamming_distance(seq1, seq2): """Calculate the Hamming difference between 'seq1' and 'seq2'.""" return sum(0 if a == b else 1 for (a, b) in zip(seq1, seq2))
357583d24221716db1cb1c297866242976b13fed
121,794
from typing import Tuple from typing import Dict import gzip def get_items_from_gzip(binary: bytes) -> Tuple[str, Dict[str, bytes]]: """ Return decompressed gzip contents. Parameters ---------- binary : bytes byte array of gz file Returns ------- Tuple[str, bytes] File type + decompressed file """ archive_file = gzip.decompress(binary) return "gz", {"gzip_file": archive_file}
82e4f704fddb0e8e671562f936067ce99d5e9da2
121,796
def process_all_dictionary_keys(dictionary, function): """ Function that applies a function or a list of functions to every single key in a dictionary """ _dictionary = {} for k, v in dictionary.items(): if isinstance(function, list): for f in function: _dictionary[f(k)] = v else: _dictionary[function(k)] = v return _dictionary
8754fd63ae70a534526847b79806918a03476ea5
121,798
def _RemainingDataSize(input_buffer): """Computes how much data is remaining in the buffer. It leaves the buffer in its initial state. Args: input_buffer: a file-like object with seek and tell methods. Returns: integer representing how much data is remaining in the buffer. """ current_position = input_buffer.tell() input_buffer.seek(0, 2) remaining_data_size = input_buffer.tell() - current_position input_buffer.seek(current_position) return remaining_data_size
ecf18b99b3c68001a6cb6fad63bd7b886111e25d
121,801
def mcastIp2McastMac(ip): """ Convert a dot-notated IPv4 multicast address string into an multicast MAC address""" digits = [int(d) for d in ip.split('.')] return '01:00:5e:%02x:%02x:%02x' % (digits[1] & 0x7f, digits[2] & 0xff, digits[3] & 0xff)
4713507e933e35b07fa917e04da431d71fe2b38f
121,805
def form_page_ranges(current_page, last_page): """Leave only the first 2, the last 2 pages, and selected page with 4 its neighbours. The method assumes that less than 10 pages shouldn't be separated. Example outputs: * if 6 is selected, 11 pages total: [[1, 2], [4, 5, 6, 7, 8], [10, 11]] * if 4 is selected, 11 pages total: [[1, 2, 3, 4, 5, 6], [10, 11]] * if 11 is selected, 11 pages total: [[1, 2], [9, 10, 11]] """ if last_page <= 10: return [list(range(1, last_page + 1))] leftmost_neighbour = current_page - 2 rightmost_neighbour = current_page + 3 displayed_ranges = [] current_range = [1, 2] # the first 2 pages if leftmost_neighbour > 3: # apart from the first 2 pages displayed_ranges.append(current_range) current_range = [] if rightmost_neighbour < last_page - 1: # apart from the last 2 pages displayed_ranges.append(list(range(leftmost_neighbour, rightmost_neighbour))) else: # merge with the last 2 pages current_range += list(range(leftmost_neighbour, last_page - 1)) else: # merge with the first 2 pages current_range += list(range(3, rightmost_neighbour)) displayed_ranges.append(current_range) current_range = [] current_range += [last_page - 1, last_page] # the last 2 pages displayed_ranges.append(current_range) return displayed_ranges
36240a97e6d48f8c0f566515c030812f857382f4
121,817
def pad_line(line): """Pad line to 80 characters in case it is shorter.""" size_of_line = len(line) if size_of_line < 80: padding = 80 - size_of_line + 1 line = line.strip('\n') + ' ' * padding + '\n' return line[:81]
36953bce9e8414b60f707500496dbd8b640ab046
121,818
def add_ss(user, player_id, ss): """Add a ss by a player Parameters: user: a user dictionary (dict) player_id: the player id of the batter (int) ss: the number of ss (int) Returns: user: the update user """ for __ in range(0, ss): user['game']['ss'].append(player_id) return user
382bb323e64d7eac0658e5cb3d975a1bce9aec61
121,820
import math def round_number(number, significant_digits): """ Rounds a number to the specified number of significant digits :param number: number to be rounded :param significant_digits: number of significant digits :return: """ if number != 0: return round(number, significant_digits - int(math.floor(math.log10(abs(number)))) - 1) else: return 0
59d4254d324e0b22bb3e4bbcbc37a73754290d77
121,821
def parse_readelf_line(x): """Return the version from a readelf line that looks like: 0x00ec: Rev: 1 Flags: none Index: 8 Cnt: 2 Name: GLIBCXX_3.4.6 """ return x.split(':')[-1].split('_')[-1].strip()
b92b473fd6d0591312c9a163aee94b55706df8c8
121,824
def Join(*parts): """Join (AFF4) paths without normalizing. A quick join method that can be used to express the precondition that the parts are already normalized. Args: *parts: The parts to join Returns: The joined path. """ return "/".join(parts)
6849d4c987f7601b272629e7a0ae12f77f73c74b
121,825
def intdivceil(x, y): """ Returns the exact value of ceil(x // y). No floating point calculations are used. Requires positive integer types. The result is undefined if at least one of the inputs is floating point. """ result = x // y if (x % y): result += 1 return result
bf5ee4b9b9436c698dfcb0fffb60e8034a273ce3
121,828
def make_inv_cts(cts): """ cts is e.g. {"Germany" : "DEU"}. inv_cts is the inverse: {"DEU" : "Germany"} """ inv_ct = {} for old_k, old_v in cts.items(): if old_v not in inv_ct.keys(): inv_ct.update({old_v : old_k}) return inv_ct
001f459fcdde2ec169723a7a67197f1f19b1cc74
121,831
from bs4 import BeautifulSoup def strip_html(text): """ Removes html tags from text :param text: text from which tags should be removed :return: text without html tags """ soup = BeautifulSoup(text, "html.parser") return soup.get_text()
22d283c7c941530ebd5944bfb17c659659ef9eb2
121,839
def strOrNone(x): """ Converts numeric values to strings, but leaves None as None. """ if x is None: return None if type(x) == int: return str(x) else: return x
aeb2879007d7b5634592c98c04da04dfa7612ad9
121,844
import time def test_function(*args, **kwargs): """Simple test function to wait a short time and return its arguments.""" time.sleep(0.01) return [args, kwargs]
a4665a99b2a2ec7f437d494ed92e33fd0e98b86f
121,845
def ele_bounds(eles): """ Get the min, max s postion of a list of eles. Only considers elements with 'zedge' in them. """ if not isinstance(eles, list): eles = [eles] mins = [] maxs = [] for ele in eles: if 'zedge' not in ele: continue zedge = ele['zedge'] L = ele['L'] mins.append(zedge) maxs.append(zedge+L) return min(mins), max(maxs)
dc6d11252eea129ea4767e50816cc8fa9b0eab86
121,847
def format_str(s, delimiter=None): """ Format a python str as a c++ string literal. """ if not delimiter: return '"{0}"'.format(s) return 'R"{delim}({s}){delim}"'.format(s=s, delim=delimiter)
d14dada5b86af5ce1d3b979d052ae5eb6f2ec8ad
121,856
def range_data_nomerge(main_data, added_data): """ Take main data and then update clusters with the added data only if they do not already exist. Return only the valid clusters (not full set) """ ret_data = {} for cluster in added_data: if main_data.get(cluster) is None: ret_data[cluster] = added_data[cluster] return ret_data
336b0a54524962bb00c8b82f4ebfae42da013698
121,859
import inspect def parse_user_args(method, *args, **kwargs): """ Parse user arguments in a function. Args: method (method): a callable function. args: user passed args. kwargs: user passed kwargs. Returns: user_filled_args (list): values of what the user passed in for the arguments. ba.arguments (Ordered Dict): ordered dict of parameter and argument for what the user has passed. """ sig = inspect.signature(method) if 'self' in sig.parameters or 'cls' in sig.parameters: ba = sig.bind(method, *args, **kwargs) ba.apply_defaults() params = list(sig.parameters.keys())[1:] else: ba = sig.bind(*args, **kwargs) ba.apply_defaults() params = list(sig.parameters.keys()) user_filled_args = [ba.arguments.get(arg_value) for arg_value in params] return user_filled_args, ba.arguments
28aca620bb85c088f5d3b1ee431b7c05cf0036ac
121,864
def get_chess_square(size, x, y): """ Returns the coordinates of the square block given mouse position `x` and `y` """ return (x // (size // 8), y // (size // 8))
d51ef89ceb5f88a1b189b01e9f0b0034ebfcd8c4
121,878
import math def snap_to_grid(xmin, ymin, xmax, ymax, resolution): """ Given a roi as xmin, ymin, xmax, ymax, snap values to entire step of resolution :param xmin: xmin of the roi :type xmin: float :param ymin: ymin of the roi :type ymin: float :param xmax: xmax of the roi :type xmax: float :param ymax: ymax of the roi :type ymax: float :param resolution: size of cells for snapping :type resolution: float :returns: xmin, ymin, xmax, ymax snapped tuple :type: list of four float """ xmin = math.floor(xmin / resolution) * resolution xmax = math.ceil(xmax / resolution) * resolution ymin = math.floor(ymin / resolution) * resolution ymax = math.ceil(ymax / resolution) * resolution return xmin, ymin, xmax, ymax
ceb42a0c50363cd7189df260881f5f72de3f4cc9
121,879
def get_branch_name(ref_name): """Returns the branch name corresponding to the specified ref name.""" branch_ref_prefix = 'refs/heads/' if ref_name.startswith(branch_ref_prefix): return ref_name[len(branch_ref_prefix):]
cfd0dd289df8a48e83abacaab61743d0d4ddcd1c
121,880
def kt_distance(scores, e_scores): """ Kendall Tau distance Z pairs exist where for a pair i, j is true score of i < true score of j, for such i, j sum count of estimated score of i > estimated score of j then divide by Z """ N = len(scores) num = 0 denum = 0 for i in range(N): for j in range(N): if scores[i] < scores[j]: denum += 1 if e_scores[i] > e_scores[j]: num += 1 return num/denum
cad9e995aea8e501e3c22ddf2378b0fdf6c125cb
121,881
def likes(list_of_names: list) -> str: """ >>> likes([]) 'no one likes this' >>> likes(["Python"]) 'Python likes this' >>> likes(["Python", "JavaScript", "SQL"]) 'Python, JavaScript and SQL like this' >>> likes(["Python", "JavaScript", "SQL", "JAVA", "PHP", "Ruby"]) 'Python, JavaScript and 4 others like this' """ if len(list_of_names) == 0: return "no one likes this" if len(list_of_names) == 1: return f"{list_of_names[0]} likes this" if len(list_of_names) == 2: return f"{list_of_names[0]} and {list_of_names[1]} like this" if len(list_of_names) == 3: return ( f"{list_of_names[0]}, {list_of_names[1]} and {list_of_names[2]} like this" ) else: return f"{list_of_names[0]}, {list_of_names[1]} and {len(list_of_names) - 2} others like this"
20d46cfcd319b7bef3733a86aa6e57769381d67b
121,882
def coups_legaux(grille): """Renvoie la liste des colonnes dans lesquelles il est possible de jouer un jeton """ coups = [] for i in range(0, 6): if grille[i][0] == 0: coups += [str(i + 1)] return coups
6d1b765f43f891f926fa7d1b5ae8927db68317a1
121,885
def _deindent(line, indent): """Deindent 'line' by 'indent' spaces.""" line = line.expandtabs() if len(line) <= indent: return line return line[indent:]
6fba2ed9a8387901bd8d100d0cb98d808db44310
121,888
def sort_lists(*lists): """Sort a list of lists based on the first list""" out = [[] for _ in range(len(lists))] for vals in sorted(zip(*lists)): for i, val in enumerate(vals): out[i].append(val) return tuple(out)
7611702b1c71b6d4230cdc03b3d05e967a873dcd
121,889
def pretty_exception(err: Exception, message: str = ""): """Return a pretty error message with the full path of the Exception.""" return f"{message} ({err.__module__}.{err.__class__.__name__}: {str(err)})"
b5fdce86753ff70dd8b247b56e0e21ecf8d0f7d1
121,896
def _find_all_meta_group_vars(ncvars, meta_group_name): """ Return a list of all variables which are in a given meta_group. """ return [k for k, v in ncvars.items() if 'meta_group' in v.ncattrs() and v.meta_group == meta_group_name]
ee49bcd48de17778268bc0c5fc4298327c66cb6f
121,899
import six import textwrap import tokenize def _can_tokenize(source_lines): """ Check if a list of lines of source can successfully be tokenized """ # tokenize.generate_tokens requires a file-like object, so we need to # convert source_lines to a StringIO to give it that interface filelike = six.StringIO(textwrap.dedent(''.join(source_lines))) try: for tokty, tok, start, end, tok_lineno in ( tokenize.generate_tokens(filelike.readline)): pass except tokenize.TokenError: return False return True
58207e7fe24e7bafb8124603b2ff500418348062
121,900
import base64 def file_to_base64(path): """ Read file data, encode it into base64. Return utf-8 string of base64 encode data """ return base64.b64encode(open(path, 'rb').read()).decode("utf-8")
21723572d3e62139b3d5118906a056f6a3d2e586
121,901
def std(vals): """Computes the standard deviation from a list of values.""" n = len(vals) if n == 0: return 0.0 mu = sum(vals) / n if mu == 1e500: return NotImplemented var = 0.0 for val in vals: var = var + (val - mu)**2 return (var / n)**0.5
469a6dd4735e86ac515c446043832d823b945120
121,905
import struct def parse_float(s): """Reinterprets the string 's' as an IEEE single precision float.""" return struct.unpack('<f', s)[0]
6e702fdb3312597075462c7fb499a97d55354530
121,915
def sortArray(timestamps): """ Sorts an array of tuples by timestamp \n :param timestamps: An array with tuples of timestamps and pages. \t :type timestamps: [(Time,str)] \n :returns: Sorted array with tuples. \t :rtype:: [(Time,str)] \n """ # Use a lambda function to sort by first element in tuple timestamps.sort(key=lambda tuple: tuple[0]) return timestamps
5387fbf5d2e4d3d750fd383cb25dfb22196bd9f7
121,918
def lsb (target, data): """ Embeded data to LSB of target ex: target='101010', data='111', return '101111' :param target: string <binary> :param data: string <binary> :returns: string """ s1 = str(target) s2 = str(data) # check if data can't insert in target if len(s2)>len(s1): return target # lenght of data to insert n = len(s2) # slice a target s1 = s1[:-n] return s1+s2
3f8db4f19c66f1a3b41152f134aaab80bfd319f6
121,919
from typing import Iterable from typing import Any def count(iterable: Iterable[Any]) -> int: """ Returns the number of items in the iterable by counting them. :param iterable: The iterable. :return: The number of items in the iterable. """ return sum(1 for _ in iterable)
010b504085dda7fbd151202b33deeb533cbc9afe
121,920
from datetime import datetime def decode_datetime(data, unpackb): """Decode MessagePack data into a Python 'datetime' object.""" seconds, microseconds = unpackb(data) return datetime.utcfromtimestamp(seconds).replace(microsecond=microseconds)
9a388d3d925d1136ec82dbbb5235e4f781afffc9
121,922
def binomial_coefficient(n, r): """ Find binomial coefficient using pascals triangle. >>> binomial_coefficient(10, 5) 252 """ C = [0 for i in range(r + 1)] # nc0 = 1 C[0] = 1 for i in range(1, n + 1): # to compute current row from previous row. j = min(i, r) while j > 0: C[j] += C[j - 1] j -= 1 return C[r]
6a3e88cf757535b03c59a6e482e0b432adaec0db
121,923
def heur_zero(state): """Zero Heuristic can be used to make A* search perform uniform cost search""" return 0
5555d9cadc275518b194d12aa2eb9c3823e06496
121,927
import logging def _matching_arg( fn_name, fn_args, candidate_args, canonical_arg, is_required=False): """Find single argument in `args` from `candidate_args`. Args: fn_name: Function name, only used for error string. fn_args: String argument names to `fn_name` function. candidate_args: Candidate argument names to find in `args`. canonical_arg: Canonical argument name in `candidate_args`. This is only used to log a warning if a non-canonical match is found. is_required: Whether function is required to have an arg in `candidate_args`. Returns: String argument name if found, or `None` if not found. Raises: ValueError: if 2 candidates are found, or 0 are found and `is_required` is set. """ assert canonical_arg in candidate_args # Sanity check. matching_args = candidate_args.intersection(fn_args) if len(matching_args) > 1: raise ValueError( 'Ambiguous arguments %s, must provide only one of %s.' % ( matching_args, candidate_args)) matching_arg = matching_args.pop() if matching_args else None if matching_arg: if matching_arg != canonical_arg: logging.warning( 'Canonical arg %s missing from %s(%s), using %s.', canonical_arg, fn_name, fn_args, matching_arg) elif is_required: raise ValueError( '%s missing from %s(%s).' % (candidate_args, fn_name, fn_args)) return matching_arg
121b5003011b10920bf7654cb3be738a9f57053f
121,928
import json def format_json(d, compact=False, indent=2): """Format JSON; compact or indented.""" separators = (',', ':') if compact else None return json.dumps(d, indent=indent, separators=separators)
bf20192f7c70fbb0ab17205fa74406436e2f41ba
121,930
def multiply(x, y): """ Return the product of x and y """ answer = 0 # one equal sign means assignment if x == 0: # two equal signs means compare return 0 if y == 0: return 0 while y > 0: answer += x y = y - 1 return answer
f6012dfe3934edc583cc3a99690c53d0c672f2ce
121,932
def dist2(a, b): """Squared distance between two 2D points.""" x, y = a[0] - b[0], a[1] - b[1] return x**2 + y**2
8d8e0b2db19ab7fcba3bccf5ebd044f07677bc97
121,933
def find_index_of_lbl(arg_list, label): """Find index of label in arg_list""" for i, value in enumerate(arg_list): if value["taglbl"] == label: return i else: raise Exception("Cannot find index in arg_list")
c393f42f0f2abed66c4de9b02ed1692a0f09015b
121,936
def delete_package_versions(client, domain, domainOwner, repository, format, namespace, package, list_of_versions): """Delete package versions from CodeArtifact repository""" response = client.delete_package_versions( domain=domain, domainOwner=domainOwner, repository=repository, format=format, namespace=namespace, package=package, versions=list_of_versions ) return response
96acf0d34d03e979b294a0bc8c819ac6e0b11343
121,937
def create_urls(years): """Generates urls that lead to billboard top 100 chart for provided year. :param years: List of years :type years: list :return: List of urls for provided years :rtype: list """ urls = [] for year in years: url = f"http://billboardtop100of.com/{year}-2/" urls.append(url) return urls
c16fc7b07176376ee14917e6b0c6e4dc2af4d219
121,939
def integers(sequence_of_sequences): """ Returns a new list that contains all the integers in the subsequences of the given sequence, in the order that they appear in the subsequences. For example, if the argument is: [(3, 1, 4), (10, 'hi', 10), [1, 2.5, 3, 4], 'hello', [], ['oops'], [[55], [44]], [30, -4] ] then this function returns: [3, 1, 4, 10, 10, 1, 3, 4, 30, -4] Type hints: :type sequence_of_sequences: (list|tuple) of (list|tuple|string) :rtype: list of int """ # ------------------------------------------------------------------------- # DONE: 3. Implement and test this function. # Note that you should write its TEST function first (above). # ------------------------------------------------------------------------- ########################################################################### # HINT: The # type # function can be used to determine the type of # its argument (and hence to see if it is an integer). # For example, you can write expressions like: # -- if type(34) is int: ... # -- if type(4.6) is float: ... # -- if type('three') is str: ... # -- if type([1, 2, 3]) is list: ... # Note that the returned values do NOT have quotes. # Also, the is operator tests for equality (like ==) # but is more appropriate than == in this situation. # ------------------------------------------------------------------------- ########################################################################### # ------------------------------------------------------------------------- # DIFFICULTY AND TIME RATINGS (see top of this file for explanation) # DIFFICULTY: 6 # TIME ESTIMATE: 10 minutes. # ------------------------------------------------------------------------- s = [] for k in range(len(sequence_of_sequences)): for j in range(len(sequence_of_sequences[k])): if type(sequence_of_sequences[k][j]) == int: s = s + [sequence_of_sequences[k][j]] return s
19f99d74e9a3e0e6608acca7fd3a03a94009024d
121,943
def press_Davison_1968(t_k): """From Davison Parameters ---------- t_k, K Returns ------- Vapor pressure, Pa References ---------- Davison, H.W. "Complication of Thermophysical Properties of Liquid Lithium." NASA Technical Note TN D-4650. Cleveland, Ohio: Lewis Research Center, July 1968. Notes ----- "With this equation the data shown in figure 8 are correlated with a standard deviation of 3.38 percent. The maximum deviation of -32.6 percent occurred at a vapor pressure of about 6 Pa." The plot Figure 8 shows 800 to 1800 K so we can take that as the applicable range. """ return 10**(10.015 - 8064.5 / t_k)
c7864dbdeab9f533d099a443db6dd7d05f2544ad
121,944
def get_dummy_from_bool(row, column_name): """Returns 0 if value in column_name is no, returns 1 if value in column_name is yes""" return 1 if row[column_name] == "yes" else 0
8f26a0a80af6ad6b6dcd6e77854119c1fa7e9a8c
121,948
def margins() -> dict: """ This fixture provides the margins in inches """ return { "left": 1.25, "right": 1.25, "top": 1.00, "bottom": 1.00, }
b235c1ee10df9b690b03c9f5a42da492c451c59e
121,949
def _diff(num_x: float, num_y: float) -> float: """ Returns the absolute difference between two values. Arguments: num_x: float num_y: float """ return abs(num_x - num_y)
b69cfe2f65a13138a11f713a2631e4ea6aae7fb6
121,953
def GetCols(x, *columns): """ iterable >> GetCols(*columns) Extract elements in given order from x. Also useful to change the order of or clone elements in x. >>> from nutsflow import Collect >>> [(1, 2, 3), (4, 5, 6)] >> GetCols(1) >> Collect() [(2,), (5,)] >>> [[1, 2, 3], [4, 5, 6]] >> GetCols(2, 0) >> Collect() [(3, 1), (6, 4)] >>> [[1, 2, 3], [4, 5, 6]] >> GetCols((2, 0)) >> Collect() [(3, 1), (6, 4)] >>> [(1, 2, 3), (4, 5, 6)] >> GetCols(2, 1, 0) >> Collect() [(3, 2, 1), (6, 5, 4)] >>> [(1, 2, 3), (4, 5, 6)] >> GetCols(1, 1) >> Collect() [(2, 2), (5, 5)] :param iterable iterable: Any iterable :param indexable container x: Any indexable input :param int|tuple|args columns: Indicies of elements/columns in x to extract or a tuple with these indices. :return: Extracted elements :rtype: tuple """ if len(columns) == 1 and isinstance(columns[0], tuple): columns = columns[0] return tuple(x[i] for i in columns)
46967732a4f58ed4bc5e9acde006da7cc2953e9f
121,958
def Binary_Search(nums, target, flag=0): """ - Returns the initial found index position of the target value if flag is set to 0 (Default) - Returns Starting Positon of the target value if flag is set to -1 - Returns Ending Positon of the target value if flag is set to 1 If the target is not present in the list of numbers, -1 is returned irrespective of the flag value """ pos = -1 low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: # Checking if target is at mid position pos = mid if flag == -1: high = mid - 1 elif flag == 1: low = mid + 1 else: return pos elif nums[mid] < target: # Checking if target is greater than the number at mid position low = mid + 1 else: high = mid - 1 return pos
f732e4aed93c4948cccdcce48f1ae346a045c680
121,960
def count_pairs_distinct_unordered(arr, target): """ Counts the unordered pairs of distinct integers in arr that sum to target. """ comp_count = {} # Counts the number of times each complement occurs in arr. for num in arr: comp = target - num comp_count[comp] = comp_count.get(comp, 0) + 1 count = 0 for num in comp_count: comp = target - num # Forcing num < comp ensures that we don't double count. # Since num != comp, we also ensure that they are distinct. if num < comp and comp in comp_count: count += comp_count[num] * comp_count[comp] return count
a812d2c868addb46c77e54e4f8ba838ca155d047
121,961
import torch def mask_torch_data(ten, frac=0.1, return_full_idxs=True, device='cpu', detach=True, existing_idxs=None): """Randomly masks out values from a N-dimensional Torch tensor. Creates a copy of the input tensor. Args: ten (torch.Tensor): The tensor to pull values from. frac (float, optional): The ratio of values to mask out. Defaults to 0.1. detach (bool, optional): Whether or not to allow autograd back to the input. Defaults to True. Returns: (torch.Tensor, torch.Tensor, torch.Tensor): Returns 3 values: 1. The input array with values masked out. 2. The values taken from the input array. 3. The indices (when using np.flat indexing) where the values were taken. """ n_el = torch.numel(ten) n_select = round(frac * n_el) if existing_idxs is None: remove_idxs = torch.randperm(n_el, device=device)[:n_select] else: remove_idxs = existing_idxs[:n_select] out = torch.clone(ten) if detach: out = out.detach() flat_out = out.view(-1) missing_vals = flat_out[remove_idxs] flat_out[remove_idxs] = 0 return (out, missing_vals, remove_idxs)
d433861f65dfa014bcd85ed2336a95aa6b6df2cc
121,963
import click def _check_db_name(dbname, postgres): """Looks up if a database with the name exists, prompts for using or creating a differently named one.""" create = True while create and postgres.db_exists(dbname): click.echo('database {} already exists!'.format(dbname)) if not click.confirm('Use it (make sure it is not used by another profile)?'): dbname = click.prompt('new name', type=str, default=dbname) else: create = False return dbname, create
b20eb814a75d10e55aa9911a1d2618c128083221
121,964
from typing import List def process_data(data: str) -> List[int]: """Convert each character into ASCII byte code.""" return [ord(char) for char in data.strip()]
59e45939bb00f458ad9dc1ce5ede5def9536326e
121,966
from typing import List from typing import Dict def make_other_dict(key: str, data: List) -> Dict: """Make dictionary of property data for 106 A/B :param key: The unique identifier :param data:Property data :return: Organized data for 106 A/B """ return { "key": key, "make": data[0], "model": data[1], "year": data[2], "other": data[4], "property_value": data[5], "your_property_value": data[6], }
a0d656510766ab1c03cd3ee7599fc4e01d495299
121,970
def unlist_list(listoflist): """ given a list e.g. [["James", "Jones"], ["Hackman", "Talisman", "Daboi"]] we want to unlist the list as follows: ["James", "Jones", "Hackman", "Talisman", "Daboi"] param listoflist: A list of listed items """ new_list = [] for alist in listoflist: for item in alist: new_list.append(item) return new_list
28ecc56b83268cd1c531fb57a958adae69ac7a5c
121,971
def example_gdal_path(request): """Return the pathname of a sample geotiff file Use this fixture by specifiying an argument named 'example_gdal_path' in your test method. """ return str(request.fspath.dirpath('data/sample_tile_151_-29.tif'))
324f7dcedaec5c2514a8e6e67325d2a3555c8463
121,981
def vhdl_package_header(name): """ Return a string with the header for a VHDL package. """ return "package {} is\n".format(name)
b7288808d15d8e6e1098a444a4e1e3b3601fc01b
121,995
def meanRelativeSquaredError(xs,ys,func): """Return the mean relative squared error.""" return sum([((func(x)-y)/y)**2 for x, y in zip(xs,ys)])/len(xs)
28ca788f51c9482cc7fb29532a967fb0f4123d9d
121,996
def NLR_analysis(NLR): """ Analysis NLR(Negative likelihood ratio) with interpretation table. :param NLR: negative likelihood ratio :type NLR: float :return: interpretation result as str """ try: if NLR == "None": return "None" if NLR < 0.1: return "Good" if NLR >= 0.1 and NLR < 0.2: return "Fair" if NLR >= 0.2 and NLR < 0.5: return "Poor" return "Negligible" except Exception: # pragma: no cover return "None"
facbe55d85569234d8f0ffb80aa6cc0db563377b
122,001
def intensity_perpendicular_from_anisotropy(Aniso, Fluo): """ Calculate perpendicular intensity from anisotropy and total fluorescence. """ return (1/3)*Fluo*(1-Aniso)
24762a29565dffcbf99321dfebf2bcaaee63045c
122,005
import math def calcIpn(p:int, n: int): """ 按书上公示计算I(p,n) :param p: 正例个数 :param n: 反例个数 :return: I(p, n)的结果 """ # 注意: p, n为0的特殊情况 return -(p/(p+n))*math.log2(p/(p+n))-(n/(p+n))*math.log2(n/(p+n)) if p != 0 and n != 0 else 0
661a1df162863b5e393f7827ec4f6d82640983ac
122,007
import io def buffer_bytes_io(message): """Return a string as BytesIO, in Python 2 and 3.""" return io.BytesIO(bytes(message, encoding='utf-8'))
8bb3627164870bf83101c8f6c10938589ba2785a
122,008
def duration(df): """Finds time duration of ECG strip This function subtracts the minimum time value from the maximum time value and returns the duration of the ECG strip. :param df: a dataframe of floats of ecg data :returns: a float of the duration of the ECG strip in seconds """ max_time = max(df['time']) min_time = min(df['time']) duration = max_time - min_time return duration
dab50a2aed4fb2ddc69cab75263c9c331bf1d437
122,009
def GetKeyUri(key_ref): """Returns the URI used as the default for KMS keys. This should look something like '//cloudkms.googleapis.com/v1/...' Args: key_ref: A CryptoKeyVersion Resource. Returns: The string URI. """ return key_ref.SelfLink().split(':', 1)[1]
a64137cb7c1c08817f8ab20429d161a0ec846487
122,013
import re def normalize_doc_filename(path): """ Take a path to an agency file and strip it down so that it's in the proper format as the other documents/processed documents (starts with "agency_attachments/"). """ return re.sub("^.*/?agency_attachments/", "agency_attachments/", path)
ae8ec2a751069aa4639a0e557e0503651097d304
122,015
import requests def get_token( email: str, password: str, ): """Log into AIO Impact and get a token. Parameters ---------- email : str Email address of the user account. password : str Password of the user account. Returns ------- str Bearer token. Examples -------- >>> aioconnect.get_token( >>> email="firstname.lastname@aioneers.com", password="xxx", >>> ) """ url = "https://dev-api.aioneers.tech/v1/login" url = url.rstrip("/") payload = {"email": email, "password": password} response = requests.post(url=url, data=payload) response.raise_for_status() token = response.json()["data"]["token"] return token
93d16aa518b4dc25ff5deac2cfcae552bcb97ac8
122,023
def _discover_manifests(api, root, dirs): """Returns a list with paths to all manifests we need to build. Args: api: recipes API. root: gclient solution root. dirs: list of path relative to the solution root to scan. Returns: [Path]. """ paths = [] for d in dirs: found = api.file.listdir( 'list %s' % d, root.join(d), recursive=True, test_data=['target.yaml', 'something_else.md']) paths.extend(f for f in found if api.path.splitext(f)[1] == '.yaml') return paths
550fc65919d1b0902fdc0f684f48557a0b89719f
122,025
import re def parse_user_input_tag_change(user_input): """ Tries to be as friendly to the user as possible >>> parse_user_input_tag_change('name="corrected name"') ('name', 'corrected name') >>> parse_user_input_tag_change('"name" = "corrected name"') ('name', 'corrected name') >>> parse_user_input_tag_change(' "name" = "corrected name" ') ('name', 'corrected name') >>> parse_user_input_tag_change('name=corrected') ('name', 'corrected') >>> parse_user_input_tag_change('name=corrected name') ('name', 'corrected name') >>> parse_user_input_tag_change('"name"=corrected') ('name', 'corrected') >>> parse_user_input_tag_change('"amenity"="foo"') ('amenity', 'foo') >>> parse_user_input_tag_change('"source"=""') ('source', '') >>> parse_user_input_tag_change('source=') ('source', '') >>> parse_user_input_tag_change('k="name" v="Corrected name"') ('name', 'Corrected name') >>> parse_user_input_tag_change('k="name" v="Corrected name"') ('name', 'Corrected name') >>> parse_user_input_tag_change('k="name"v="Corrected name"') ('name', 'Corrected name') >>> parse_user_input_tag_change('k=name v="Corrected name"') ('name', 'Corrected name') >>> parse_user_input_tag_change('k=name v=Corrected') ('name', 'Corrected') >>> parse_user_input_tag_change('k=name v=Corrected name') ('name', 'Corrected name') >>> parse_user_input_tag_change("k='name' v='Corrected name'") ('name', 'Corrected name') >>> parse_user_input_tag_change("k='contact:website' v='http://www.ski.kommune.no/BARNEHAGER/Vestveien/'") ('contact:website', 'http://www.ski.kommune.no/BARNEHAGER/Vestveien/') >>> parse_user_input_tag_change("'contact:website'='http://www.ski.kommune.no/BARNEHAGER/Vestveien/'") ('contact:website', 'http://www.ski.kommune.no/BARNEHAGER/Vestveien/') >>> parse_user_input_tag_change("contact:website=http://www.ski.kommune.no/BARNEHAGER/Vestveien/") ('contact:website', 'http://www.ski.kommune.no/BARNEHAGER/Vestveien/') """ user_input = user_input.replace("'", '"') # replace any single quotes with double quotes reg0 = re.search('k="?([\w:-]+)"?\s*v="?([^"]*)"?', user_input) reg1 = re.search('"?([\w:-]+)["\s]*=["\s]*([^"]*)"?', user_input) ret = None if reg0: ret = reg0.group(1), reg0.group(2) elif reg1: ret = reg1.group(1), reg1.group(2) return ret
a19a651332c1974118488817c19105bc1e50b68b
122,026
def format_binary(byte_array: bytearray): """ Formats the given byte array into a readable binary string. """ return ''.join('{:08b}_'.format(i) for i in byte_array)
9a88e935e19b7ef7df5e7d19c9c933d390c522ab
122,029
def get_atherr(dset): """Returns array with uncertainty in ash top height from VOLCAT.""" """Default units are km above sea-level""" height_err = dset.ash_cth_uncertainty height_err = height_err.where(height_err != height_err._FillValue, drop=True) return height_err
fe1c9c99391ed181ef10fbd1baec75fe4ba830f2
122,034
import string import random def generate_random_names(size:int, length: int) -> list: """Module to generate random names of a given size and length Builds up a random key of a given length using alphanumeric chars [a-z, A-Z, 0-9] Parameters ---------- size*: Represents count of total generated keys length*: Represents the length of the individual keys (we have modeled a constant length key) (* - Required parameters) Returns ------- list of string where the (list length) == size paramter. """ possibilities = string.ascii_letters + string.digits output_names = [] while len(output_names) != size: generated_name = ''.join([random.choice(possibilities) for _ in range(length)]) if generated_name not in output_names: output_names += generated_name, return output_names
f45de31a2761b5da6b65a112c27e533da9cb1047
122,040
import re def clean(s): """ Get rid of any non-alphabetic character and clean up whitespace. """ # Remove everything that isn't an alphabet character (only interested # in words, not numbers or punctuation). s = re.sub(r'[^a-zA-Z]', ' ', s) # Collapse whitespace in any amount or type (tabs, newlines, etc.) into # a single space. s = re.sub(r'\s+', ' ', s) return s
5777e63226692f2fb34f59d88fac86d757eb3e73
122,042
import json def load_json_file(file_loc:str = "ImageLabeling/LabeledImages.json"): """ Loads JSON file as a dictionary Args: file_loc: Location of JSON file Returns: Dictionary based on the provided file """ with open(file_loc, "r") as f: data = json.load(f) return data
b4f8266fb6243e0b74e1d46fe2c5552b9ea4627d
122,058
def get_value_of_card(position_of_card, deck): """Returns the value of the card that has the specific position in the deck""" # print(deck[position_of_card]) value_int = deck[position_of_card][1] return value_int
19d7085c57bccfeb7b808ac0e4da3b9b12136c45
122,060
def multiple_lines(text, line_length): """Splits text by space onto multiple lines of maximum required length :param text: The text to split on multiple lines :type text: str :param line_length: Max length allowed for each line :type line_length: int :return: Text split on multiple lines :rtype: list """ lines = [] line = "" for word in text.split(" "): if line == "": candidate = word else: candidate = line + " " + word if len(candidate) < line_length: line = candidate else: lines.append(line) line = word if len(line) > 0: lines.append(line) if len(lines) == 0: lines.append("") return lines
9e3bfd4d14126a0ac51ed46a8ce76c7dc3edd59d
122,061
def typestring(obj): """Make a string for the object's type Parameters ---------- obj : obj Python object. Returns ------- `str` String representation of the object's type. This is the type's importable namespace. Examples -------- >>> import docutils.nodes >>> para = docutils.nodes.paragraph() >>> typestring(para) 'docutils.nodes.paragraph' """ obj_type = type(obj) return ".".join((obj_type.__module__, obj_type.__name__))
f3d78088019d53debe613b5b0d9c53282d62c206
122,065
def to_pygame(coords, height): """Convert coordinates into pygame coordinates (top-left => bottom-left).""" return coords[0], height - coords[1]
056d95c80c1c546ecbb5d34cfe3c14243c3ae3ad
122,071
from typing import Optional import secrets def local_part( length: int = 8, username: Optional[str] = None, separator: str = "+" ) -> str: """Construct an email address local-part. Randomly generate a local-part using a safe subset of the allowable characters specified in RFC 5322. If a username is supplied (i.e., subaddressing is used), the random output will be used as the "detail" sub-part of the local-part. The detail sub-part will be truncated if the combined length of the username, separator, and detail sub-parts are greater than 64. Args: length (int, optional): Length of the generated local-part or detail sub-part (from 1 to 64). Defaults to 8. username (str, optional): The username sub-part of the local-part. Defaults to None. separator (str, optional): Separator between the username and detail sub-parts. Defaults to "+". Returns: str: The constructed local-part. See Also: https://tools.ietf.org/html/rfc5322#section-3.4.1 https://tools.ietf.org/html/rfc5233#section-1 https://www.jochentopf.com/email/address.html """ def _choice(length): chars = "0123456789abcdefghijklmnopqrstuvwxyz" return "".join(secrets.choice(chars) for _ in range(length)) if username: combined = len(username + separator) if combined + length >= 64: length = 64 - combined detail = _choice(length) local = f"{username}{separator}{detail}" else: local = _choice(length) return local
99983f5dd32ce72d1b1ea959cbaf70119cfb9bf1
122,072
import asyncio import typing async def stop_task(task: asyncio.Task) -> typing.Any: """ Try to cancel the task, and await it -- returns possible exceptions raised inside the task, e.g. the :class:`asyncio.CancelledError` raised by canceling the task prematurely. Args: task: task to stop, can't be the current running task Returns: result of task Raises: ValueError: if the currently running task is passed """ if task is asyncio.current_task(): raise ValueError(f"Not allowed to stop task running `stop_task`!") task.cancel() return (await asyncio.gather(task, return_exceptions=True))[0]
cc0461cd4c4983b700cee825dca58ede2351140a
122,075
def _get_basis_product_indices(basis, dimensions, W): """ Returns the indicies for the product between the weights for each interpolant for basis functions. """ BPInd = None if dimensions == 1: return None elif dimensions == 2: if basis[0][0] == 'T': return None elif len(basis) == 2: if (basis[0][0] == 'L' and basis[1][0] == 'L') or \ (basis[0][0] == 'L' and basis[1][0] == 'H') or \ (basis[0][0] == 'H' and basis[1][0] == 'L'): BPInd = [] for ind1 in range(W[1].shape[1]): for ind0 in range(W[0].shape[1]): BPInd.append([ind0, ind1]) elif basis == ['H3', 'H3']: BPInd = [[0, 0], [1, 0], [0, 1], [1, 1], [2, 0], [3, 0], [2, 1], [3, 1], [0, 2], [1, 2], [0, 3], [1, 3], [2, 2], [3, 2], [2, 3], [3, 3]] else: raise ValueError('Basis combination not supported') elif dimensions == 3: if len(basis) == 3: if (basis[0][0] == 'L' and basis[1][0] == 'L' and basis[2][0] == 'L'): BPInd = [] for ind2 in range(W[2].shape[1]): for ind1 in range(W[1].shape[1]): for ind0 in range(W[0].shape[1]): BPInd.append([ind0, ind1, ind2]) elif basis == ['H3', 'H3', 'H3']: BPInd = [ [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1], [2, 0, 0], [3, 0, 0], [2, 1, 0], [3, 1, 0], [2, 0, 1], [3, 0, 1], [2, 1, 1], [3, 1, 1], [0, 2, 0], [1, 2, 0], [0, 3, 0], [1, 3, 0], [0, 2, 1], [1, 2, 1], [0, 3, 1], [1, 3, 1], [2, 2, 0], [3, 2, 0], [2, 3, 0], [3, 3, 0], [2, 2, 1], [3, 2, 1], [2, 3, 1], [3, 3, 1], [0, 0, 2], [1, 0, 2], [0, 1, 2], [1, 1, 2], [0, 0, 3], [1, 0, 3], [0, 1, 3], [1, 1, 3], [2, 0, 2], [3, 0, 2], [2, 1, 2], [3, 1, 2], [2, 0, 3], [3, 0, 3], [2, 1, 3], [3, 1, 3], [0, 2, 2], [1, 2, 2], [0, 3, 2], [1, 3, 2], [0, 2, 3], [1, 2, 3], [0, 3, 3], [1, 3, 3], [2, 2, 2], [3, 2, 2], [2, 3, 2], [3, 3, 2], [2, 2, 3], [3, 2, 3], [2, 3, 3], [3, 3, 3]] else: raise ValueError('Basis combination not supported') else: raise ValueError('Basis combination not supported') else: raise ValueError('%d dimensions not supported' % (len(basis))) return BPInd
7cbf11faba3bc0ba9dd2099b244efbc2b81cd971
122,080
def validate_model_data(args): """ Ensures that the specified model and dataset are compatible """ implemented_models = ["cpreresnet20", "resnet18", "vgg19"] implemented_datasets = ["cifar10", "imagenet"] if args.model not in implemented_models: raise ValueError(f"{args.model} not implemented.") if args.dataset not in implemented_datasets: raise ValueError(f"{args.dataset} not implemented.") if args.dataset == "imagenet": if args.model not in ("resnet18", "vgg19"): raise ValueError( f"{args.model} does not support ImageNet. Supported models: resnet18, vgg19" ) elif args.dataset == "cifar10": if args.model not in ("cpreresnet20"): raise ValueError( f"{args.model} does not support CIFAR. Supported models: cpreresnet20" ) return args
166fe7c3b804620e6a1d5f56c1a588bcadf28862
122,084
def flatten_network(wiki_linked_pages): """ Return a list of the combine inbound and outbound links """ return wiki_linked_pages["inbound_pages"] + wiki_linked_pages["outbound_pages"]
0bcd866eea0fa2f988fb9e680137e3689c239f27
122,087