content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import json def getNodeGroups(session, url, details=False): """ Return a list of node group objects (by the index endpoint). Passing details=True will get all information for each node group. """ groups = [] page = 1 per_page = 100 done = False while not done: new_node_gr...
d865f1e99cee94410b68bee5c4384bbcd4d4a52f
657,782
import threading def synchronized(func): """synchronized decorator function This method allows the ability to add @synchronized decorator to any method. This method will wrap the decorated function around a call to threading.Lock ensuring only a single execution of the decorated method/line of co...
6ac02e42816c920ce98e35507833f24dcb2349db
657,783
def input_keywords(scf_in): """Extract all keywords from a quantum espresso input file Args: scf_in (str): path to input file Return: dict: a dictionary of inputs """ keywords = dict() with open(scf_in, 'r') as f: for line in f: if '=' in line: key, val = line.split('=') k...
f64345e07d6db4e24815b0c6fce7b1055fb58619
657,786
def strip_definition_from_video(vid_id): """Strip any sort of HD tag from the video""" hd = ['[HD]', '[FHD]', '[SD]', '(SD)', '(HD)', '(FHD)'] for item in hd: vid_id = vid_id.replace(item, '') return vid_id
996a37309e5c4de6d5bd5110a16f4dcdf6760bab
657,788
def skipHeader(infile): """ skip the lines beginning with a '!' """ ## find where the header ends counter = 0 while infile.readline().startswith("!"): counter += 1 ## reposition the file iterator infile.seek(0) for i in range(0, counter): infile.readline() return infile
5f9a785fb0f5c3b019b70d293eeec240d53ae30e
657,793
def sexpr_print_sexpr(sexpr): """Prints a python S-expression as a string S-expression.""" if isinstance(sexpr, str): return sexpr elif isinstance(sexpr, int): return str(sexpr) elif isinstance(sexpr, tuple): assert len(sexpr) > 1, sexpr parts = map(sexpr_print_sexpr, sex...
5099c127b4daccd7c6a48940bfeeaab81445a860
657,797
def find_pivot(input_list): """Find the pivot point of the sorted yet "shifted" list. A simple divide and conquer strategy to find the pivot point of the list. Time complexity O(log n) :param input_list: a sorted and pivoted list (i.e. "shifted") :type input_list: list :return: an index of th...
b790a1f0828373f036e034535e4c294d815298eb
657,798
import sympy def jacobian(expr, symbols): """ Derive a symbolic expr w.r.t. each symbol in symbols. This returns a symbolic jacobian vector. :param expr: A sympy Expr. :param symbols: The symbols w.r.t. which to derive. """ jac = [] for symbol in symbols: # Differentiate to every ...
613057e249dd79bef748f155b695344bd3abbd3a
657,801
import requests def get_track_info(url): """ Get the track info of the passed URL. """ _client_ID = "LvWovRaJZlWCHql0bISuum8Bd2KX79mb" api = "http://api.soundcloud.com/resolve.json?url={}&client_id={}" URL = api.format(url, _client_ID) r = requests.get(URL).json() title = r["title"] ...
2a12aed19b6fdffa4d32faf2f7023c58da448717
657,802
def bmi(W, H): """ Body Mass Index Calculator Calculates the BMI Algorithm: https://www.cdc.gov/healthyweight/assessing/bmi/childrens_bmi/childrens_bmi_formula.html :return: The BMI in kg/m^2 :rtype: float """ res = 703.0*W/(H*H) return res
2d158735b3ed77d5b847fac45ece22fb597faf38
657,803
def append_s(value): """ Adds the possessive s after a string. value = 'Hans' becomes Hans' and value = 'Susi' becomes Susi's """ if value.endswith('s'): return u"{0}'".format(value) else: return u"{0}'s".format(value)
a98f494a109c661eafc5ff51230d86646646339c
657,805
def _zone(index): """Chooses a GCP zone based on the index.""" if index < 6: return 'us-central1-a' elif index < 12: return 'us-east1-b' elif index < 18: return 'us-east4-c' elif index < 24: return 'us-west2-a' else: raise ValueError('Unhandled zone index')
9d5a86ce022530e59301f82e73cf3bc90cf6df87
657,809
import torch def change_box_order(boxes, order, dim=-1): """Change box order between (x_min, y_min, x_max, y_max) and (x_center, y_center, width, height). Args: boxes: (tensor) bounding boxes, sized [N, 4]. order: (str) either 'xyxy2xywh' or 'xywh2xyxy'. Returns: (tensor) converted bou...
c9e2a2b2569f365eaba6f0fc8dca3c44c8706455
657,812
def clip(text, max_len=80): """Return max_len characters clipped at space if possible""" text = text.rstrip() if len(text) <= max_len or ' ' not in text: return text end = len(text) space_at = text.rfind(' ', 0, max_len + 1) if space_at >= 0: end = space_at else: spac...
01530ebe0e25a03c4f49204b7816d0f000796a43
657,813
def gq_add_vertex_collection(coll): """Create the gremlin query that creates a Vertex for a collection in the Tree Entry table """ name = coll.entry.container.split('/')[-1] if not name: # root name = '/' query = "graph.addVertex(T.label, 'collection', " query += "'name', '{}', ...
57492e959b008804b5138dbb751f4d06854f850e
657,815
import pickle def load_clifford_table(picklefile='cliffords2.pickle'): """ Load pickled files of the tables of 1 and 2 qubit Clifford tables. Args: picklefile - pickle file name. Returns: A table of 1 and 2 qubit Clifford gates. """ with open(picklefile, "rb") as ...
25382d151456b926a317e3c820d29d650e28e31c
657,816
import ast def format_nasdaq(companies): """ Convert the parsed companies list to format that is interpretable by dash_core_components.dropdown """ companies_list = ast.literal_eval(companies) options=[] # Get the company name and symbol. for i in range(len(companies_list)): new_co...
d2f6782c0d9f37b749241ed6cd9f4cd7508f2f77
657,820
def make_coordinates(df, index_col='index'): """ Formats a geopandas.GeoDataFrame (from a shapefile that contains junction information) to a coordinate table. Parameters ---------- catchments : geopandas.GeoDataFrame Must contain a geometry field with points. index_col : str ...
a870b0e0624860f5cfcc4e130ef468559f39c329
657,822
from typing import Sequence from typing import List def lst_inc(inc: Sequence, seq: Sequence) -> List: """ Returns the intersection of two sequences. Similar to the built-in method ``set.intersection``, but duplicate (non-unique) items are not discarded. Args: inc: Sequence E...
bf8ead302c44e1d46c6d1a30c198a837f2682ec4
657,827
def _strip_or_pad_version(version, num_components): """Strips or pads a version string to the given number of components. If the version string contains fewer than the requested number of components, it will be padded with zeros. Args: version: The version string. num_components: The d...
8d8829c551fe799852098db60c2df5f1cd68a4c3
657,828
def _block_format_index(index): """ Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``. """ idx_str = ''.join('[{}]'.format(i) for i in index if i is not None) return 'arrays' + idx_str
849a345869d9080010c306751e3ea537bc583e78
657,832
def urljoin(*path): """Joins the passed string parts into a one string url""" return '/'.join((part.strip('/') for part in path))
977ee60d90977fda9041da45d9db1ea17e45f773
657,833
def euler14(lim=1000000): """Solution for problem 14.""" collatz = {1: 1} for i in range(2, lim): if i not in collatz: chain = [] while i not in collatz: chain.append(i) i = (3 * i + 1) if i % 2 else (i // 2) stop = collatz[i] + 1 ...
6a89c4b2ee996f22ea67a3d032b4259326487586
657,838
def check_rule(m, number, board, row, col): """ 如果遵循每一行,每一列,每一区域都包含1-9数字,且不重复的规则,返回真 number: 被校验的数字 board: 当前九宫格所有的元素(9x9的二维列表) row, col: 当前行数,当前列数 """ flag = True # 检查行 if number in board[row]: flag = False # 检查列 if not all([row[col] != number for row in board])...
3d192f3a0d84fe97869da1bcb08ca30874c85f44
657,841
import six def dtype(spec): """ Allow Python 2/3 compatibility with Numpy's dtype argument. Relevant issue: https://github.com/numpy/numpy/issues/2407 """ if six.PY2: return [(str(n), str(t) if type(t)==type else t) for n, t in spec] else: return spec
b3e154dc59a821b6c20d01dff2706c90f40d7372
657,844
def get_collection_keys(cleaned_zot_files): """ Gets the collection (folder) id keys for each entry in the cleaned Zotero files """ col_keys = [] if 'collections' in cleaned_zot_files['data'].keys(): if len(cleaned_zot_files['data']['collections']) > 1: for i in cleaned_zot_files...
52274c04a3c9ec0e9218914a36fdd33418e4aaa6
657,846
def find_all_stacktraces(data): """Given a data dictionary from an event this returns all relevant stacktraces in a list. If a frame contains a raw_stacktrace property it's preferred over the processed one. """ rv = [] def _probe_for_stacktrace(container): raw = container.get('raw_stac...
a8f81201cb18dcd6f54a7ab9058d02c17688a93f
657,847
def ensure_dtype(data): """ To ensure that input file and output file are comparable, data types should be the same in all files. #Input: @data: pandas DataFrame #Output: @data_trans: transformed pandas DataFrame with corrected dtype """ # dtypes taken from Hestia website data_tr...
bb99607a93cd5ef383c754e5d2dba62ed5478c06
657,851
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
2a63e85022b6b91e18ea4240437605028ee21266
657,857
def is_interval_subset(interval1, interval2): """Checks whether interval1 is subset of interval2.""" # Check the upper bound. if (interval1[1] == "inf" and interval2[1] != "inf") or \ (interval1[1] != "inf" and interval2[1] != "inf" and interval1[1] > interval2[1]): return False # C...
6f8e7baf1245fbfc0c72390913db64716239f263
657,858
def find_nested_attr(config, attr): """ Takes a config dictionary and an attribute string as input and tries to find the attribute in the dictionary. The attribute may use dots to indicate levels of depth within the dictionary. Example: find_nested_attr({'one': {'two': {'three': 3}}}, 'one.two....
3f449553d409b255989f12f1d96c945e2d076e8b
657,864
def insertion_sort(array): """ Insertion sort implementation Arguments: - array : (int[]) array of int to sort Returns: - array : (int[]) sorted numbers """ for i in range(len(array)): j = i while j > 0 and array[j] < array[j-1]: array[j], array[j-1] = a...
ad39beaffc80aa662496b9bef4e3462549cb6680
657,865
def decimal_to_binary(num): """Convert a Decimal Number to a Binary Number.""" binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 return "".join(str(e) for e in binary)
01be9bfa9c816b64b84f941920e2bdf66fc3f11f
657,868
def simple_fill(text:str, width:int=60) -> str: """ Split `text` into equal-sized chunks of length `width` This is a simplified version of `textwrap.fill`. The code is adapted from: http://stackoverflow.com/questions/11781261 Parameters ---------- text : string The text to split ...
8491ebb8ee91eb4ea6fcc3e295cf35a59eb39012
657,871
def prod(a, b): """ Example operator function. Takes in two integers, returns their product. """ return a * b
0c0f2a60cec78d3a145dc649cab72fb2a666b26c
657,872
def get_decrypted_file_path(enc_file, config): """ returns the path to the decrypted copy of the file """ result = enc_file.replace('.gpg','').replace(config.enc_mainfolder + '/', '').replace('_HOME', '$HOME') return result
6c77877cf6647d525b66a0775f8f20e2c8e6133d
657,875
def assertWrapperExceptionTypes(self, deferred, mainType, reasonTypes): """ Assert that the given L{Deferred} fails with the exception given by C{mainType} and that the exceptions wrapped by the instance of C{mainType} it fails with match the list of exception types given by C{reasonTypes}. This is...
e6a2d0781d83a7ecbceacd9ebf76cfed93de9b60
657,876
def extract_pairs(data_list, tag='mean_trajectory_return'): """Extract data from positive and negative alpha evaluations. Args: data_list: A list of dictionaries with data. Dictionary should contain 'pos' and 'neg' keys which represent going forward and backward in the parameter space. Each key sho...
5c593b9f4803e31ef14b6461e5bf62b2c2ad0c2f
657,878
import copy def calibrate_mp(pixel): """ This is a helper function in order to use multiprocessing to invoke the calibrate() method for an array of Pilatus_Pixel objects. """ pixel.calibrate() return copy.copy(pixel)
e2dd19a13d46b6fd8c7173eadb60957c72e7f539
657,881
import torch def symsqrt(matrix): """ Compute the square root of a positive definite matrix. Retrieved from https://github.com/pytorch/pytorch/issues/25481#issuecomment-544465798. """ _, s, v = matrix.svd() # truncate small components above_cutoff = s > s.max() * s.size(-1) * torch.finfo(s...
30c46f762068a85c60740b4614b1ac0794d194a2
657,882
from typing import Collection def A000120(start: int = 0, limit: int = 20) -> Collection[int]: """1's-counting sequence: number of 1's in binary expansion of n (or the binary weight of n). """ return ["{:b}".format(n).count("1") for n in range(start, start + limit)]
36bd316ad43a12ac5b5e6acd7abcf697ea8d3ec6
657,883
def _telegram_escaped_string(s): """Replaces characters in a string for Markdown V2.""" for c in "_*[]()~>#+-=|{}.!": s = s.replace(c, "\\" + c) return s
55284d0331713b30b851550672d251fcbbd2a76d
657,886
from datetime import datetime def get_anterior_datetime(offset = 300): """ Returns an anterior date given an offset time in seconds :param offset: offset interval in seconds (default: 300s) :return datetime: the anterior datetime :raises Exception: Invalid time offset """ if off...
6e122851ea6e15f0c020911e7a13fe82ebb439dd
657,889
def is_palindromic(input_string): """Return True if input string is a palindromic""" return input_string == input_string[::-1]
927d701c9d67facc85281e7c15ddb893a35decb8
657,892
def gmx_bonds_func_1(x, a, b, c): """ Gromacs potential function 1 for bonds. """ return a / 2 * (x - b) ** 2 + c
47cfdce9ff7e5e9b7daca0fe53a0e5fb7284e5a7
657,895
import math def gammanu_to_tthphi(gamma, nu): """Transfer gamma-nu to ttheta-phi. gamma is the angle in the equatorial plane nu is the angle between equatorial plane and scattering neutron [-pi/2, pi/2] return ttheta is diffraction angle phi is polar angle ...
f7ffb6c1703fcf5d7cfb0eea69cfdd49a522adaf
657,900
import struct def SetVersionBit(protocol=1): """Generate the Version bit""" return struct.pack("<B", protocol)
5ca1cb45a6adb7627e0344ece3f837d3313ffedd
657,901
def build_pathnet_graph(p_inputs, p_labels, p_task_id, pathnet, training): """Builds a PathNet graph, returns input placeholders and output tensors. Args: p_inputs: (tf.placeholder) placeholder for the input image. p_labels: (tf.placeholder) placeholder for the target labels. p_task_id: (tf.placeholder...
c283ac433ea8ec8864b61c7943af8735c9da6045
657,905
from pathlib import Path def store_secret(tmp_path: Path, name: str, secret: bytes) -> Path: """Store a secret in a temporary path. Parameters ---------- tmp_path : `pathlib.Path` The root of the temporary area. name : `str` The name of the secret to construct nice file names. ...
c8a2e27f2762bf65ef4a33fd35e548fd90d77216
657,906
import textwrap def wrap_summary(summary, initial_indent, subsequent_indent, wrap_length): """Return line-wrapped summary text.""" if wrap_length > 0: return '\n'.join( textwrap.wrap(summary, width=wrap_length, initial_indent=initial_inde...
9ad28c412b8f5086f9255a133b3037031017205d
657,907
from typing import List from typing import Union def wipe_empty_fields(card: List[Union[str, int, float, None]]) -> List[Union[str, int, float, None]]: """ Removes any trailing Nones from the card. Also converts empty strings to None. Allows floats & ints, but that's not the intended value, though...
fdbed42cde29ac965259c6e290322db0a558b910
657,911
def reuss_avg(M1, M2, f1, f2): """ Reuss average for a 2 mineral mixture Usage: M = reuss_avg(M1, M2, f1, f2) Inputs: M1 & M2 = Elastic moduli for each phase (float) f1 & f1 = Volume fraction of each phase (float) Output: M = Reuss average of elastic moduli (float)...
f78a04314d0c6e33bc6856871fa62576f323bc49
657,912
import six import re def keys_by_pattern_dict(in_dict, patterns, matchs=None): """ Recursive dictionary lookup by regex pattern. Args: in_dict (dict): Input dict. patterns (list): Lookup regex pattern list. matchs (list): Match accumulator (recursive call only). ...
2dff14f92adc6cd9ecb93f495661e9ab402e18bc
657,918
def add_cushions(table): """ Add space to start and end of each string in a list of lists Parameters ---------- table : list of lists of str A table of rows of strings. For example:: [ ['dog', 'cat', 'bicycle'], ['mouse', trumpet', ''] ...
bbe1a23ac84ac29aef7f450c9977949f4223dd15
657,923
def WmiBaseClasses(connWmi, className): """ This returns the base classes of a WMI class. """ # Adds the qualifiers of this class. klassObj = getattr( connWmi, className ) # It always work even if there is no object. return klassObj.derivation()
97eabc1c185f9471d1af11abdff564bd5c6eb18d
657,925
import re def validate_rdm_string(ops: str) -> str: """Check that a string for rdms are valid. Args: ops (str): String expression to be computed. Returns (str): Either 'element' or 'tensor'. """ qftops = ops.split() nops = len(qftops) assert (nops % 2) == 0 if any(...
0361cbe283e2a8adbcab8c6ca19cbee7338a977d
657,926
def ete_dendrogram(corpus, tree, outputfile=None, fontsize=5, save_newick=True, mode='c', show=False, color_leafs=False, save=False, return_svg=True): """ Draw a dendrogram of the texts in the corpus using ETE. Parameters ---------- corpus : `Corpus` instan...
672b08a614a6a3ee966dcfda58c272cf88eb8642
657,930
def is_loc_free(loc, tile_grid): """ Checks whether a location in the given tilegrid is free. """ if loc not in tile_grid: return True if tile_grid[loc] is None: return True return False
19237f3966341a4786079fe114d7338c018a9d91
657,936
import string def _default_devour(text): """ The default devour function (strips out whitespace). """ i = 0 while i < len(text) and text[i] in string.whitespace: i += 1 return text[i:]
a4ee9d76f934e2b7fd242e95d39d1d173eea0e36
657,937
def heading(text, level): """ Return a ReST heading at a given level. Follows the style in the Python documentation guide, see <https://devguide.python.org/documenting/#sections>. """ assert 1 <= level <= 6 chars = ("#", "*", "=", "-", "^", '"') line = chars[level] * len(text) re...
43ef5bc1fdfb6c34279e9aa74ac420c1b1110e3a
657,939
import json def _str_to_tiptap_markup(text): """Convert a plain text string into a TipTap-compatible markup structure""" return json.dumps( { 'type': 'doc', 'content': [ {'type': 'paragraph', 'content': [{'type': 'text', 'text': paragraph}]} for ...
a5edbc0b5e844b77db61ae2b5d87eee14d271fda
657,944
import re def remove_from_text(raw_text: str, symbols: list) -> str: """ Removes every symbol/character in the given symbols list from a given string, raw_text. """ return re.sub("|".join(symbols), "", raw_text)
9e3f62788de70a663005daca35443f2f2b7de742
657,949
def get_factors(x): """Returns a list of factors of given number x.""" factors = [] #iterate over range from 1 to number x for i in range(1, x+1): #check if i divide by number x evenly if (x % i == 0): factors.append(i) return factors
29b63efc435cfd54d8f384f3d5fbd18b12d3627d
657,950
def root_node_only_token_stream(request): """ Fixture that yields strings that will generate a token stream that creates a single root node. """ return request.param
0a340d78057716157677a79525c0c57707817daa
657,954
def _read_config(filename): """ Read config file into `c`. Variables in config file are formatted as `KEY=VALUE`. """ c = {} with open(filename, "r") as f: for line in f: key, val = line.split("=") key = key.strip() val = val.strip() c[key...
b4399703a09453800a2ba896b2c71324fbb2b3ad
657,961
def is_business_type(business_type_choice, on_default_path=False): """Returns a function to assert whether the wizard step should be shown based on the business type selected. The `on_default_path` allows the returned function to return a default value if the business type hasn't been filled in yet. Th...
a8b7d192af6f8620b02829adf80c9cf8a1ec77bc
657,964
import re def natural_sort_key(sort_key, _nsre=re.compile('([0-9]+)')): """ Pass to ``key`` for ``str.sort`` to achieve natural sorting. For example, ``["2", "11", "1"]`` will be sorted to ``["1", "2", "11"]`` instead of ``["1", "11", "2"]`` :param sort_key: Original key to be processed :retur...
69a2a18701fdcf72041cdac9037c19b3f2561c6c
657,965
def contains_digit(text): """Returns true if any digits exist in the text""" return any(c.isdigit() for c in text)
593bd0fa600fd6e7fae7ef77a16f32f0adaf6fe6
657,966
def many_any(lst, k): """ Returns True if at least k elements of lst are True; otherwise False. Do this in one line for extra credit. Hint: use a list comprehension. Example: >>> many_any([True, True, False, True], 3) True >>> many_any([True, True, False, False], 3) False """ re...
2e277dd5a97fb9f1f13ea8272f7b7b223312381f
657,970
import math def largest_numeric_increase_infant_mortality(data_by_country): """ Which country had the largest increase in Infant mortality for both sexes from 2005 to 2015? Parameters: data_by_country: dictionary with different data for countries. Returns: Tuple(String, String) - (Qu...
972ade7cd38b0b06b963b5762ced6a46a0a5273d
657,971
def collect_reducer_count(values): """Return the number of values >>> collect_reducer_count(['Sheep', 'Elephant', 'Wolf', 'Dog']) 4 """ return len(values)
f398326ffb9932a8a033d158140f065cff6d6453
657,975
import secrets def generate_token(length : int=32) -> str: """ Uses the secrets.token_hex() method to generate a a hexidecimal token Parameters ---------- length : int The desired length of token Returns ------- str The hexidecimal string generated by Pyth...
f2524b306910c40717f0512cb233dc34a19f2636
657,976
def B(value): """Returns 1 if value is truthy, 0 otherwise.""" return 1 if value else 0
ce788b5fa6aff71379dd3ca326e2e4e2e5da950f
657,979
def leading(value): """ Strip all leading whitespaces. :param value: The value :type value: str :return: The value with all leading whitespaces removed :rtype: str """ return value.lstrip()
f77fcf0ceb615af7d49fa6b473a9bb9ce72a2da3
657,981
def box_text(text, width, offset=0): """ Return text inside an ascii textbox """ box = " " * offset + "-" * (width + 2) + "\n" box += " " * offset + "|" + text.center(width) + "|" + "\n" box += " " * offset + "-" * (width + 2) return box
cc4bd6ba46920d02caf1ee4e2dbb769c397945f7
657,987
def add_class(form_widget, css_class): """ Adds a css class to a django form widget """ return form_widget.as_widget(attrs={'class': css_class})
9f9559698233e93ee8828a0132de9378bed7c15d
657,988
def get_thresholds(threshs_d: dict) -> tuple: """ Parameters ---------- threshs_d : dict Thresholds configs Returns ------- names : list Name for the threshold thresh_sam : int Samples threshold thresh_feat : int Features threshold """ names ...
ba9984fa94ab209f1b863175eb55bb4985a92a65
657,990
def _field_name_grib1_to_grib2(field_name_grib1): """Converts field name from grib1 to grib2. :param field_name_grib1: Field name in grib1 format. :return: field_name_grib2: Field name in grib2 format. """ return field_name_grib1.replace('gnd', 'ground').replace('sfc', 'surface')
439e7e6d101e04d3d02f2d783321812a1acda7a9
657,992
def get_descriptors(image, filtered_coords, wid=5): """ For each point return, pixel values around the point using a neighbourhood of width 2*wid+1. (Assume points are extracted with min_distance > wid). """ desc = [] for coords in filtered_coords: patch = image[coords[0]-wid:coords[0]+wid+...
e1e7b67ff88d9546e6be1e2f5bdd80287d14ffce
657,994
def write_to_file(filepath, data_to_write): """ TO DO: This function takes any <data_to_write>, converts it into a string via the str() function (if possible), and then writes it to a file located at <filepath>. Note that this function is a general writing function. It should not use the .csv mo...
a0879d88ebfea1e4308910e355ef9ff9b0088b41
657,995
def callback_ResetDropdown(window): """ Updates the dropdown after newVal is selected and applied Parameters ------------- window = GUI object Returns None ------------- """ # set values and value to empty to get rid of previously specified answers window['changeMod'].update('C...
a04075aa205fed91efc6bfd4fffc944498c26913
658,000
def dice_jaccard(y_true, y_pred, smooth=1, thr=None): """ Computes Dice and Jaccard coefficients. Args: y_true (ndarray): (H,W)-shaped groundtruth map with binary values (0, 1) y_pred (ndarray): (H,W)-shaped predicted map with values in [0, 1] smooth (int, optional): Smoothing facto...
e633fe7546809edf5445c6a5e313d705b38438ef
658,002
def _select_compcor(compcor_cols, n_compcor): """Retain a specified number of compcor components.""" # only select if not "auto", or less components are requested than there actually is if (n_compcor != "auto") and (n_compcor < len(compcor_cols)): compcor_cols = compcor_cols[0:n_compcor] return ...
f8c7936a7bb8a675d98cb2bf2ffea203f796c0b6
658,009
def generalize_version(package): """Add `.*` to package versions when it is needed.""" dep = package if ("=" in dep or (dep[-1].isdigit() and "." in dep)) and not dep[-2:] == ".*": dep += ".*" if " " in dep and not "." in dep.split()[1]: dep += ".*" return dep
b0ba536926b8fa6177ed692c21f668da5e09ff41
658,015
def ph_color_code(value): """ :param value: This is a pH value which is having its color multiplexed. Description: This takes a pH value as input and returns a color to be used in the form of a string. """ if value > 12.6: return 'navy' elif value >11.2: return 'blue' elif value >9.8: return 'dodgerb...
eac3f1dc83e2a9a75dbfc1a913a9f2d0ecb0bc67
658,017
import torch def gaussian_kl(mu, logsigma): """ Analytically compute KL divergence between the multivariate gaussian defined by the input params (assuming diagonal covariance matrix) and N(0, I). Arguments: mu (torch.Tensor): Mean. Expected size (N x num_variables) logsigma (torch.T...
0117a327f1181eaf647eba55f2e40c0886138144
658,018
def query_merge(query: dict, **kwargs: dict) -> dict: """ Merge a dictionary and key word arguments into a single dictionary. Used to merge a MongoDB query and key word arguments into a single query. :param query: The dictionary to merge. :param kwargs: The key word arguments to merge. :return...
5a53047cdc2983225815506203f9134de371c0c0
658,019
def search_to_url(search: str) -> str: """Transform user search terms into ready to use URL""" search = search.lower().replace(" ", "%20") return f"https://uk.indeed.com/jobs?q={search}&l=United%20Kingdom"
b5291f39fb7bd1722ef46c0e8a662e42f8b26f1c
658,020
def determine_format(tileSource): """ Given a tile source, return the vendor format. :param tileSource: a large_image tile source. :returns: the vendor or None if unknown. """ metadata = tileSource.getInternalMetadata() or {} if tileSource.name == 'openslide': if metadata.get('opens...
dd40ecfa44498c2237cba0729213d9abe3d9e855
658,021
def __find_number_of_repeats(seq_before, seq, seq_after): """ Finds the number of repeats before or after a mutation. :param seq_before: the genomic sequence before the mutation (str) :param seq: the genomic sequence of the mutation (str) :param seq_after: the sequence after the mutation (str) ...
63ca022ec9a529e70e3080b16c9a59a91e1c5cf6
658,026
def kelvin_to_celsius(kelvin): """ Convert kelvin temperature to celsius. """ return kelvin-273.15
91fe9431de8c08ffe7072379bdc1100d27925afc
658,033
def sec2hour_min_sec(seconds): """ Convert elapsed seconds to hours, minutes and seconds #Credits: https://codereview.stackexchange.com/questions/174796/convert-seconds-to-hours-minutes-seconds-and-pretty-print Parameters ---------- seconds : long int elapsed seconds Returns ------- str string with conve...
3e6013a625d674a1e0d0ffdd1f6306681dd28c1d
658,035
def _LLF(job, t): """ Least-Laxity-First assigns higher priority to jobs with lesser laxity (slack). The laxity (slack) of a job of a job with deadline d at time t is equal to deadline - t - (time required to complete the remaining portion of the job) """ return job.deadline - t - job.remai...
8dd5025c5ee077352c7f0cf0e23fc76bc29950c3
658,039
def calc_ttr(df_ttr): """Calculates travel time reliability. Args: df_ttr, a pandas dataframe. Returns: df_ttr, a pandas dataframe with new ttr column. """ # Working vehicle occupancy assumptions: VOCt = 1 df_ttr['VOLt'] = df_ttr['pct_truck'] * df_ttr['dir_aadt'] * 365 df_ttr['ttr'] = df...
cee9b22dd1866458dfd7ec849c9dccc20da5c92b
658,040
def trunc(s,min_pos=0,max_pos=75,ellipsis=True): """Return a nicely shortened string if over a set upper limit (default 75 characters) What is nicely shortened? Consider this line from Orwell's 1984... 0---------1---------2---------3---------4---------5---------6---------7----> When we are omn...
4622d3332e9c22c0597633ab025c0f2998f8b773
658,041
from typing import List def _check_is_list(obj): """Check whether obj is a list""" return isinstance(obj, (list, List))
2327f6641cae73e98e0820a14e05dfaf2c87dc6b
658,044
from typing import Tuple from typing import Sequence def get_involved_bits(instruction) -> Tuple[Sequence[int], Sequence[int]]: """Returns the bits involved in the instruction. :param instruction: The instruction of interest. :return: The quantum and classical bits used by the considered instruction. ...
896f1755b80e7d0e2bfd427e219eb0fb546307af
658,050
import socket import struct import random def gen_random_ip() -> str: """ Generate random ip From: https://stackoverflow.com/questions/21014618/python-randomly-generated-ip-address-of-the-string """ return socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
eda3b7494ffd36590b122ccc136f3c873feff281
658,051
def leaf_size(request): """ Fixture to specify IntervalTree leaf_size parameter; to be used with the tree fixture. """ return request.param
f28f607f631470e1541ebc9ee71735d9f66ae3f3
658,052
import math def is_equal(aabb1, aabb2, rel_tol=1e-9, abs_tol=1e-7): """ Check if two AABBs aabb1 and aabb2 are approximately equal. The two AABBs are considered equal if the min and max points of the AABBs are componentwise approximately equal. For the componentwise equality check, the standard funct...
c1758b90bc139a983748feff0850145a374ca4f4
658,059