content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def map_to_lie_algebra(v): """Map a point in R^N to the tangent space at the identity, i.e. to the Lie Algebra Arg: v = vector in R^N, (..., 3) in our case Return: R = v converted to Lie Algebra element, (3,3) in our case""" # make sure this is a sample from R^3 assert v.size()[...
da0b9638b1eb1f6d0fbbeccdb7fdd6d68c80ffcd
671,157
def quadratic_item_score(i): """Function is similar to inverted and linear functions but weights are decreasing at non-linear rate and accelerate with the item position. Parameters ---------- i : int Item position. Returns ------- result : float Inverted square ...
462e8dc355b13da52ec959e983d03f04c34dffae
671,158
import subprocess def gzip_file(file_path): """ Returns a file-like object containing the gzipped version of the given file. """ args = ['gzip', '-c', '-n', file_path] try: proc = subprocess.Popen(args, stdout=subprocess.PIPE) return proc.stdout except subprocess.CalledProcessE...
2b0fd3dc8187f9070273284ef756ae6e05cde2c7
671,160
import json def config_reader(read_path): """ Read json file given path return: List or Dictionary Reading the json file can give us a list if we have positional args or key value args for a dictionary """ with open(read_path, 'r') as input_file: conf_file = json.load(input_file)...
b2e2ee5564cc112d3aa2bc8f9f4a75c029eee12b
671,161
def shrink_to_fit(column_sizes, terminal_width): """ If the total size of all columns exceeds the terminal width, then we need to shrink the individual column sizes to fit. In most tables, there are one or two columns that are much longer than the other columns. We therefore tailor the shrinking algorit...
04f3d999a54736b81179fd8cfc36013ad30863f1
671,162
import re def rm_spaces(text): """ Remove multiple spaces """ pattern = re.compile(r'( ){2,}') text = re.sub(pattern, r' ', text) return text
071da821bb1bd5c37c2ffa45a99cb6d946185cc8
671,163
def swap(record): """ Swap (token, (ID, URL)) to ((ID, URL), token) Args: record: a pair, (token, (ID, URL)) Returns: pair: ((ID, URL), token) """ token = record[0] keys = record[1] return (keys,token)
21d9dc45c44cc24e0c12ff85b0513321f58af558
671,164
def normalizeLanguage(lang): """ Normalizes a language-dialect string in to a standard form we can deal with. Converts any dash to underline, and makes sure that language is lowercase and dialect is upercase. """ lang=lang.replace('-','_') ld=lang.split('_') ld[0]=ld[0].lower() #Filter out meta languages suc...
96890ea57435b3b3523f313af531691478bd75d2
671,165
def least_squares_gradient(y, tx, w): """ Compute the gradient of the mean square error with respect to w, and the current error vector e. Takes as input the targeted y, the sample matrix w and the feature vector w. This function is used when solving gradient based method, such that least_squares_GD() ...
ba6e4846367c0b67a31efac1ed68d161ca3a7b2a
671,166
import csv def get_music_csv(file_name): """This is function return a list that contain song ```py get_music_csv("music.csv") ``` Args: file_name (str): Path to csv file Returns: list[dict]: List with list of music with ```title, author, link``` """ songs = [] with ...
bcf55d54ddef71e8c3600d53e5e449f3ae8c58d3
671,167
import sys import os def asset_path(relative_path: str) -> str: """Returns the path of an asset file.""" if hasattr(sys, "_MEIPASS"): # pylint: disable=E1101,W0212 return os.path.join(sys._MEIPASS, relative_path) # type: ignore return os.path.join(os.path.abspath("."), relative_path)
b22e3a3875ef345fb729524799100a66088f2ed4
671,168
def celstokelv(celsius): """ This function converts celsius to Kelvin, with celsius as parameter.""" kelvin = celsius + 273.15 return kelvin
c66ef2fa8efa5c118a0c9ba31976fca1aae4cfaf
671,169
def find_ngrams(seq, n): """ Computes the ngrams for a sequence. :type seq: a list of of strings :param seq: a sequence :return a list where ngrams are stored """ return zip(*[seq[i:] for i in range(n)])
2a8e138529eecb9dfdf3923abfe94adc284a8657
671,170
def __extract_id_from_str_list(ids_string, top_ids): """ The idea is to return first top genre that is found in the given list of track genres. :param ids_string: :param top_ids: :return: """ for id in ids_string[1:-1].replace(' ', '').split(','): if int(id) in top_ids: ...
501728ef64187c0900cf5b37047415470c2d8526
671,171
def insert_to_sql(value, safe=True): """Cleans the input data to be insertable into sql. - str: Fixes the quote problem. - None: becomes NULL - other: keep it as it is. Set safe to True to avoid safety check. """ # danger = ['create', 'alter', 'drop'] if isinstance(value, type(None)): ...
637b9d7302978f5bffc1473402f5a28edca9e715
671,172
def opcao(msg): """ Valida se um input é um número inteiro. Se digitar qualquer outro caracter que não seja inteiro a função retorna 99. Se der Ctrl+c retorna 3 :param msg: Mensagem do input. :return: retorna quando o número for inteiro (n). """ try: n = int(input(msg)) ...
4f4d4384ef674df9d559c0bfdfd0bd0871e481bb
671,173
def fib_recursive_mathy_memoized(n): """Same function as "fib_recursive_mathy", but this will be memoized.""" if n < 2: return n return fib_recursive_mathy_memoized(n - 1) + fib_recursive_mathy_memoized(n - 2)
e3d0a0280194062d09285ad159719dd27c3ad380
671,174
import re def split_parts(sep, output): """Split the output string according to the regexp sep.""" regexp = re.compile(sep) lines = output.split('\n') idx = [] num = 0 for line in lines: if regexp.search(line): idx.append(num) num = num + 1 arr = [] start = ...
350d0c052e4f9eac171659155eb554940d3498fa
671,175
def to_hexstr(str): """Convert a string to hex escape represent""" return "".join(["\\x%02x" % ord(i) for i in str])
801b4118eb2ab42992b8fdbe0d04e857ca152035
671,176
from datetime import datetime def week_end(): """ return True if time is between 19:00 on Friday and 14:00 on Sunday """ # monday is 0, sunday is 6 _weekday = datetime.today().weekday() _result = False if _weekday == 4: if datetime.today().hour >= 19: _result = True ...
ea16ca8db0becfe25871a58a235d2ba620e1349c
671,177
def _multi_bleu(hypothesis, reference_set, aligner): """ Compute a list of scores with the aligner. :param hypothesis: a single hypothesis. :param reference_set: a reference set. :param aligner: a callable to compute the semantic similarity of a hypothesis and a list of references. :return:...
0731edfb542883581e499283587a5a602b025efd
671,178
def minAddToMakeValid(self, string): """O(n) time and space""" stack = [] for char in string: if stack and char == ')' and stack[-1] == '(': stack.pop() else: stack.append(char) return len(stack)
9118934ca1a58350ac35acbde19cd69e7b9aba35
671,179
def is_number(s): """ Check if a string is a number """ try: float(s) return True except ValueError: return False
c9f5bc5010b4fb7ad6a293d3788ab4955dd1595d
671,180
def findRestaurant(list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ index1={x:i for i,x in enumerate(list1)} index2={x:i for i,x in enumerate(list2)} result=[] total=float('inf') for i in index1: if i in index2: temp=index1[i]+index2[i] if temp < total: total=...
da639bceb09db6c2122f9973657795b5af3fc1b9
671,181
import numpy def weight(E, E0, width): """Weighting function characterizing the disorder """ return numpy.exp(-numpy.sqrt(numpy.log(2.0))*((E-E0)/width)**2)
406e293ad2efc9f37a807822a37d58e880de8697
671,182
def getNumbersFromString(s): """ Splits the passed string at spaces and extracts all numeric values Parameters ---------- @param s - string to be split and have its numbers extracted Returns ---------- @param vals - list of floats """ vals = [] for v in s.replace(',',' ')...
24a69585fc9e28ae6f0f54e58ef3ce7b77b6e062
671,183
def execute(instructions): """ Execute instructions, return a tuple of accumulator and exit reason. """ index = 0 accumulator = 0 list_of_pc = set() while True: if index in list_of_pc: return (accumulator, "cycle") if index == len(instructions): return...
1576ba348f2d6381357f6f45ceec20740269d9ce
671,184
import numpy def rotation_matrix(u, theta): """Return matrix that implements the rotation around the vector :math:`u` by the angle :math:`\\theta`, cf. https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle. :param u: rotation vector :param theta: rotation angle """...
b74b84a5941605f2931c51848f976e8fe4a8749c
671,185
import sys import functools def writes_bytecode_files(fxn): """Decorator to protect sys.dont_write_bytecode from mutation and to skip tests that require it to be set to False.""" if sys.dont_write_bytecode: return lambda *args, **kwargs: None @functools.wraps(fxn) def wrapper(*args, **kwar...
943aa1ab4a015935377f57b828868a1d58a22625
671,186
from datetime import datetime def get_how_much_time_has_passed(start_time): """ Calculates time from start_time to now, and prints a message. Inputs ------ start_time (datetime) """ end_time = datetime.now() return (end_time - start_time).total_seconds()
06a8f76fe437288010be6dd17e31b94428596242
671,188
import torch def subsequent_chunk_mask( size: int, chunk_size: int, num_left_chunks: int = -1, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: """Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: siz...
e06afa21778e92725e07445048ab60a2cfa24af0
671,190
import pandas def import_assays(assay_path): """ Import assays into list Parameters: assay_path - pathlib.Path - path to assay.xlsx file Output: list: [0] - assay1 [1] - assay2 ... [x] - assayx """ data = pandas.read_excel(assay_path, engine='openpyxl') return d...
9122d356ee6b114d4e2d4e7dd0f0930c6a19f7f7
671,191
def get_col(sudoku, col): """zwraca odpowiednia kolumne z sudoku""" return [sudoku[x][col] for x in range(9)]
40100893f64918809f92070989d39070538727d6
671,192
from typing import Dict def check_label_match(frame_labels: Dict, labelset: Dict) -> bool: """ Check that the labels of the frame matches the labels of the rules. :frame_labels (Dict) The labels of the frame. :labelset (Dict) The labels of the ruleset. Return a boolean describing the status of t...
e5a22da70a89cf8201a8597cdefc71eac516107b
671,193
def _handle_ai_platform_response(uri, response): """Handle response to AI platform from both get/post calls. Args: uri: Request uri. response: Response from the request. Returns: Request results in json format. Raises: ValueError: When the request fails, the ValueError will be raised with ...
aafa4e2ee87be607595da825ca9ac57c707477ac
671,194
import numpy def select_features(X, indices): """ Selects the features marked by the indices from numpy arrays. :param X: numpy array :param indices: list :return: numpy array with feature subset """ X_subset = numpy.transpose(numpy.transpose(X)[[indices]]) if len(X_subset.shape) == 1:...
8f2ffbf06ef15dc7fdd1a290b4433fdbcd02ea4a
671,195
from typing import Any import argparse def check_positive(value: Any) -> int: """Check value is an int.""" try: ivalue = int(value) assert ivalue <= 0 except (AssertionError, ValueError): raise argparse.ArgumentTypeError(f"{value} is an invalid positive int value") return ivalu...
3f8ccccc404691604e56f92122ba8e0d240ae059
671,196
def filter_abst(abst, slots_to_abstract): """Filter abstraction instruction to only contain slots that are actually to be abstracted.""" return [a for a in abst if a.slot in slots_to_abstract]
698bb9b115810c34f77c7c9edd967f7b6a6f888a
671,197
import io import os import PIL.Image import tempfile def image_size(imgs): """ Input: - imgs : (np.ndarray) of shape (n, d). n is the number of data in this batch d is the length of the bytes as numpy int8 array. Output: - sizes : List[Tuple(int, int),...] """ num_imgs =...
1ffe3f8eeca6396041834be23c8ff05c41dc9187
671,198
import os import subprocess def detect_desktop_environment(): """Get current Desktop Environment http://stackoverflow.com /questions/2035657/what-is-my-current-desktop-environment :return: environment """ environment = {} if os.environ.get("KDE_FULL_SESSION") == "true": envir...
ede824a906f38a0acc4dd645f1ec910c76d5df50
671,200
import time def time_timestamp(time_object): """millisecond :param time_object: :return: """ timestamp = (time.mktime(time_object.timetuple()) - time.timezone) * 1000 return timestamp
5c7b024e13b1df8c3ee25a23a18c3eeeae475ae6
671,201
def lower_case_underscore_to_camel_case(text): """ Converts string or unicdoe from lower case underscore to camel case :param text: str, string to convert :return: str """ # NOTE: We use string's class to work on the string to keep its type split_string = text.split('_') class_ = text._...
2c298593b32a59865c254c78b8099d17bd0cc5fd
671,202
from typing import Any def fqualname_of(obj: Any) -> str: """Gets the fully-qualified name for the given object.""" return "{}.{}".format(obj.__class__.__module__, obj.__class__.__qualname__)
19f3e226846d3771ae8f4c15034d354aec7ba49f
671,203
def _create_py_wrapper(native_func): """Wraps a native func so that it does arg/result translation.""" def invoke(*args, **kwargs): try: exc_code, result = native_func(*args, **kwargs) except IndexError as e: # The VM raises this on an out of bounds list access, which happens # when a vari...
6087c53b867908becb00e2e399a7dd6055ec126c
671,204
def emoji_LF(row, information_extractor): """ Analyze image based on emojis""" emoji_classes = information_extractor.emoji_classification(row.emojis, 10) return dict(emoji_classes)
daf50d01edc9ae95c263c1b330b99cbf628a8bb0
671,205
import re def match_datetime(text): """ 正则表达式提取文本所有日期+时间 :param text: 待检索文本 >>> match_datetime('日期是2020-05-20 13:14:15.477062.') ['2020-05-20 13:14:15'] """ pattern = r'(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2})' pattern = re.compile(pattern) result = pattern.findall(text) ...
8b51cb40171681197fe84d9fc0a1fcc3f1047808
671,207
import re def clean_url(url): """ Removes the attributes of the URL """ MAX_URL = 2048 cleaned_url_lst = re.split(r'[?#]', url) if (len(cleaned_url_lst) == 0): exc_msg = f"Problem removing the attributes of URL:\t{url}" print(exc_msg) cleaned_url = cleaned_url_lst[0] i...
150856eeb6611f6991fbdf5a2e250d4ad9dc94d8
671,209
def error500(ex): """ internal server error """ # logger.error(ex.args[3]) return "error 500 : {0}".format(ex.args[2])
f399cfcc411b75b3c29c2e6fc4b685a7a1d49860
671,210
import re def shell_escape_filename(filename): """ Escape filename for use as shell argument. """ return re.sub(r'(\s|[\\\'"|()<>{}$&#?*`!;])', r'\\\1', filename)
4fb5d85956f4d4031d6069d67b8444b79a3cbab9
671,211
import sys def get_standard_metadata_values( file, metadata ): """ Gets metadata values from a file path :param file: The file path to search :param metadata: A list of standard metadata to retrieve [ 'sample', 'power', 'wavelength', 'time' ] :returns: A list of metadata values """ ...
e2e36896c4c27f47bf15ada5beea88ad2caf1a48
671,212
def get_attr(attr_name, data): """ Get the data from an HTML Tag. """ start_pos = data.find( attr_name ) + len(attr_name) max_pos = len(data) while start_pos < max_pos and data[start_pos] != '"': start_pos += 1 start_pos += 1 end_pos = start_pos while end_pos < max_pos a...
d6b9abfad18332e9d12125f4853d465bf52d64db
671,213
def get_webf_obj(server, session, obj_type, obj_name, subdomain=None): """ Check the existence of an object in the server. Return the object if found, False if not. A simple wrapper for the "list_XXX" API methods. """ # Get a list of objects from the API obj_list = getattr(server, "list_%ss" % o...
4fa3861462ee7db3810e4b394a4258859d7f16a2
671,214
import torch def to_device(obj, device): """ Move a tensor, tuple, list, or dict onto device. """ if torch.is_tensor(obj): return obj.to(device) if isinstance(obj, tuple): return tuple(to_device(t, device) for t in obj) if isinstance(obj, list): return [to_device(t, dev...
346c2315e8e2d71ecf274629cea3f21b76e2c4d4
671,216
from typing import List def are_supports_coordinated(orders: List[str]) -> bool: """Return False if any supports or convoys are not properly coordinated e.g. if "F BLA S A SEV - RUM", return False if "A SEV" is not ordered "A SEV - RUM" 0 1 2 3 4 5 6 """ required = {} ordered = ...
dc480381e31044b9a8733bac5db65637524eb552
671,217
def _e_f(rho, rhou, e, p): """Computes the flux of the energy equation.""" return (e + p) * rhou / rho
5eeb0b37834dbd4a49f8b8b281d63ac4c414324e
671,218
import os import fnmatch import glob def grab_files_recursive(input_directory, regex='*', return_dir=False, return_file=True, recursive=True): """ Returns all files recursively in a directory. Essentially a convenience wrapper around os.walk. Parameters ---------- input_directo...
6253274dc2b49c2c714cd79d8a92feb9ad59dcb0
671,219
import requests def get_release_info(cpan_name): """ Get release info by module or distribution name """ # Probably get info at release req_url = "http://api.metacpan.org/release/{cpan_name}".format(cpan_name=cpan_name).replace("::", "-") api_response = requests.get(req_url).json() i...
203fb1f7eb721a2f58227db3031b90f20d61db76
671,220
def retry_if_result_none(result): """Retry on result function.""" return result is None
42bccc2a2df82c2151e554b5eb544c4d4a8baa07
671,221
import os def is_user_an_admin(): """ Check user admin """ if os.name == 'nt': try: # only windows users with admin privileges can read the C:\windows\temp os.listdir(os.sep.join([os.environ.get('SystemRoot', 'C:\\windows'), 'temp'])) except Exception: retur...
9424645aa40457f03a7b47da020e364e7aef85ad
671,222
import numpy as np def steady_state_potential(xdata,HistBins=100): """ Calculates the steady state potential. Parameters ---------- xdata : ndarray Position data for a degree of freedom HistBins : int Number of bins to use for histogram of xdata. Number of position po...
daf8c0f86a170ffb34637eb863bcc02015b61d3e
671,223
import sys def prepare_str(string, encoding=None): """Encode a string to the file system encoding of our host. Does nothing if string cannot be encoded. :param str string: String to encode. :param str encoding: Override encoding to use instead of native file system encoding. :returns: En...
62cde4c144cbb0c48aaca985b8f5a7cb0a301f8d
671,224
import re def get_default_iso(molecule): """ Returns the default (most abundant on Earth) isotopologue given a molecule Parameters ---------- molecule : String DESCRIPTION. Returns ------- default_iso : String DESCRIPTION. """ if molecule == 'H2_p': # H...
4dd5d1c102eb07a9e79e52b95b557651cbdf5326
671,225
from urllib import request def getHTMLOf(url): """ @param url a valid URL string @return HTML of page at given URL """ return request.urlopen(request.Request(url)).read()
892dd83ab495a54c489a7674fc09a5386b443d09
671,226
def _extract_doc_comment_simple(content, line, column, markers): """ Extract a documentation that starts at given beginning with simple layout. The property of the simple layout is that there's no each-line marker. This applies e.g. for python docstrings. :param content: Presplitted lines of the s...
ad9cb3f201072cf4d5e922f4e4bc4ed15ae2a864
671,227
import re def get_syllables_counter(word: str) -> int: """ Counts the amount of syllables in the word :param word: word to be used for counting :return: the amount of syllables in the word """ # word = word.lower() # count = 0 # vowels = "aeiouy" # if word[0] in vowels: # c...
3a23f11bfd9876a5fe99d138ce52133a645224a8
671,228
from datetime import datetime def DatetimeFromString(date): """Parses a datetime from a serialized string.""" if date == 'None': return None if not date or isinstance(date, datetime): return date # Strip bad characters. date = date.strip('\t\n ') valid_formats = [ '%Y-%m-%d %H:%M:%S.%f %Z',...
622da29fbe312ef7063b560c15efc8b2dc740639
671,229
import re def cobrababel_parse_metanetx_equation(equation): """ Note: This function is a copy of the _parse_metanetx_equation() function in cobrababel project metanetx.py file: https://github.com/mmundy42/cobrababel https://github.com/mmundy42/cobrababel/blob/master/LICEN...
d619ed4900045cf30fb5348acb8b4b91637b3256
671,230
def anyone_certified(task, **kwargs): """ Default assignment policy, we leave the task in the awaiting processing pool. """ return task
ac8d7a74c1cd2bd3dade79ef6b9f58f9e12a8b3a
671,231
import sys import platform def get_femag(): """returns femag command""" if sys.platform.startswith('linux'): if platform.machine() == 'x86_64': return 'xfemag64' return 'xfemag' if platform.machine() == 'AMD64': return 'wfemagw64' return 'wfemag'
e2e6e221c5daf1bc821c2419fe31234849a0049d
671,232
def reindent_lines(new_leader, source): """Re-indent string lines.""" return new_leader + ('\n' + new_leader).join(source.split('\n'))
2e68bba8f49ce24b85adfb26d04cd3a1d72cbe1f
671,233
def rfnnodes(rf): """Return the total number of decision and leaf nodes in all trees of the forest.""" return sum(t.tree_.node_count for t in rf.estimators_)
f392e7d0985fa78a6123da3d4624a6b152e059a5
671,234
def pytest_runtest_makereport(item, call): """ Yield each test's outcome so we can handle it in other fixtures. """ outcome = yield report = outcome.get_result() if report.when == 'call': setattr(item, "report", report) return report
7347224cb22abc0f785a27a2e25a8d0570797605
671,235
def sum_of_squares(limit): """ Returns the sum of all squares in the range 1 up to and including limit. """ return sum([i ** 2 for i in range(limit+1)])
df2c6ebf029b54d810e730cd5790128a37786952
671,236
import os def make_custom_config_path(user_dir): """ The location of the cusstom config file. Returns ~/.sasview/config/custom_config.py """ dirname = os.path.join(user_dir, 'config') # If the directory doesn't exist, create it if not os.path.exists(dirname): os.makedirs(dirname) ...
d777cd6ba7f95c675715dece8f33382d269cac79
671,238
def fact(n): """ factorial of n :param n: int :return: int """ if type(n) != int: n = int(n) if n == 1: return 1 else: acc = 1 for x in range(1,n+1): acc = acc * x return int(acc)
ebad82edfe209501081a7739e812a6a21e81901b
671,239
def remove_qualifaction(root, namespace): """removes the specified namespace""" namespace_len = len(namespace) for elem in root.getiterator(): if elem.tag.startswith(namespace): elem.tag = elem.tag[namespace_len:] return root
fc2584d524020ab7c2308bb52aca102a347c8059
671,241
import json import sys def get_agent_list(filename): """ :param filename: Name of te file :return: Returns a dictionary containing required configuration data """ try: with open(filename, 'rb') as fh: json_data = json.loads(fh.read()) return json_data except IOError...
6fbdab75f2bbf79dc14db7ff2d00b228451e291e
671,242
import os def _ensure_trailing_slash(path, path_semantics=None): """ 'a/b/c' -> 'a/b/c/' EPICS adds the trailing slash itself if we do not, so in order for the setpoint filepath to match the readback filepath, we need to add the trailing slash ourselves. """ newpath = os.path.join(path, ...
6d0b02a1b6bb51648a2738b44f4c9e188a989eb5
671,243
import requests def __get_data(root_url="https://api.bitpanda.com/v1/", sub_url="", headers=None, bitpanda_api_key=None): """Supplementary function to get response data as json - Reads data from multiple pages""" # default header if not headers: headers = {"X-API-KEY": bitpanda_api_key} ...
24584ac827fad079f766ad0c22af1efa3894106e
671,244
def exponential_decay(lr0, s): """ Create exponential decay: reduce learning rate by s every specified iteration. Parameters ---------- lr0 : float initial learning rate s: float decay rate, e.g. 0.9 (mostly higher than in other methods) Returns ------- exponential_...
715422d1a3af457ce601cd3727dda543de612369
671,245
import re def _get_name(var) -> str: """Normalize name of Tensorflow variable""" parts = var.name.split("/") filtered = "/".join([part for part in parts if not part.startswith("part")]) return re.sub(r":\d+", "", filtered)
493d1fd2656f75e03905607c4cccb28c795e1b25
671,246
from typing import Dict from typing import Any from typing import Type from enum import Enum def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum: """ Converts an ``dict`` to a ``Enum``. """ return enum_class[d['name']]
5825e99081d52a86d80108cdc331ff4339bd5522
671,248
def get_global_pepper() -> str: """ Get the global secret pepper from secure memory. The important thing is that it is NOT stored in the database. """ return "subscribe to mcoding YSkkYFGRzdqNLCy68z0uT0kjZQgxh6-vzTH_dw7NirYPqDhcU3ykSlG0O-AAx65ivIbx1FPrukM3K4rNSFbcpg"
cd629ef5ff77e39c93b9c7df4b48f2282d77615e
671,249
def is_kwarg(argument: str) -> bool: """`True` if argument name is `**kwargs`""" return "**" in argument
016c5c0def8f78e8ef10b68f425d55aab880d4ee
671,250
def get_vocal(data): """Get vocal.""" vowels = ('A', 'E', 'I', 'O', 'U', 'Á', 'É', 'Í', 'Ó', 'Ú') result = False for x in vowels: if x == data: result = True break return result
82b97f3077c6ea641014fa29c64b6b27d9f287e6
671,251
def isabs(s): """Test whether a path is absolute""" return s.startswith('/')
41d69b168a47829f8fd4b213624fca7f8682b022
671,252
def matrix_divided(matrix, div): """divides all elements of a matrix""" if (matrix == [] or matrix == [[]] or type(matrix) is not list or not all(type(row) is list for row in matrix)): raise TypeError("matrix must be a matrix (list of lists) " ...
d1d7fecebac1e7299985500824b9d2c76ddab362
671,253
def variant_position(record): """Create position ID for each locus so can collapse variants at the same position""" POSstr = '{0:09d}'.format(record.POS) # add leading 0s return '_'.join([str(x) for x in [record.CHROM, POSstr]])
1001f918a2ed1ceb4975011c09cbc62f2742425b
671,254
def list_extremum(data: list, type=0) -> tuple: """ 找到list中的极值,并返回索引,若极值有多个,则返回多个索引 Args: data: list数据 type: 1表示执行最大值操作,0表示最小值操作 Returns: 极值,索引的列表 """ if type == 1: # 极大值 ex = max(data) elif type == 0: # 极小值 ex = min(data) else: ...
adf513af5221491b51ae7a105f5feaa96617126a
671,255
import os import shutil def td_tmpdir(request, tmpdir): """Copy test data into the temporary directory for tests. Note: 1) Test data is located by convention. Create a directory with the same name as the test file (test-file: test_mymodule.py, test-data: test_mymodule/* ) Args: r...
01ce0b165ca45b285d527f492feec7b8568f79e7
671,256
import re def normalizestring(text): """ normalizestring """ return re.sub(r'\s+', ' ', text)
59e690bec0cc615f871a36b8df07ae2ccf8ea732
671,257
def filter_data(df, condition): """ Filter data by keeping only the values that satisfy the conditions given Parameters - df: (pandas dataframe) dataframe - conditions: (string) string that contains conditions to be used to filter dataframe. Ex: if the user...
4a22f5baabfa316904b76269fcbdcb8a2e6e0b8e
671,258
def _render(env, template_str, data): """Uses the environment to render the provided template string using the provided data""" template = env.from_string(template_str) return template.render(data)
49cd566a45c3fa61bc6774ba527efdf350da9258
671,259
import os import shutil def _move_no_overwrite(src, dst): """Move a file if the destination does not exist. If successful return false.""" if not os.path.exists(dst): shutil.move(src, dst) return True return False
59f242828f5b08d2a5680dc16b30e5d22fea087c
671,260
def map_clobs(columns): """ The map_clobs function will inject the following if there are clob data types. --map-column-java col6=String,col8=String This is needed as clob columns will not come into Hadoop unless we specifically map them. """ hasclobs = False clobs = "" for c in colu...
7d9bc4cffe4ebfde0e117f59ca3c8247e423ccf7
671,261
def ExtractDependencies(input): """ Create a list of dependencies from input list of lines Each element contains the name of the object and a list of files that it depends on. Dependencies that contain "/usr/" are removed as they are system headers. """ deps = [] for line in input: headersLine = line.startswit...
8c0f87af50342221c1c73356e9c3ffdefb690e03
671,262
def Enum(field, enum, key_func=None): """ Enum is an adapter to another field: it will just change its display attribute. It uses a dictionnary to associate a value to another. key_func is an optional function with prototype "def func(key)->key" which is called to transform key. """ display...
7823a5f049a3f530840f57f55fcf6a7f380adf13
671,263
def inrange(number, range): """convenience function. is number inside range? range is tuple (low, hi), checks range inclusive of the endpoints""" return (number >= range[0] and number <= range[1])
96fe8c8bb36a012365742ddeb5e0a26790e7c9b8
671,264
import struct def _determine_file_type(file_name): """ This checks the initial bit of the header to determine file type. Parameters ---------- file_name : str Returns ------- None|str """ with open(file_name, 'rb') as fi: # read the first 12 bytes of the file ...
39bcacfac91dd0e63e2ff4e7e97453723deda665
671,265
def input_float_list(): """ Converts each element in the list to a real output :return: real number list """ a = input().split() b = [float(a[i]) for i in range(len(a))] return b
26cde7980f71e54a183c90c98f0fced7e8b784c2
671,266