content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any from typing import Dict def reduce(t: Any, options: Dict) -> Any: """recursively applies itself to a nested data structure. if given a list of dicts, will reduce those down to a list of a single dict, whose values are ResultSets of the values from the dicts in the original list Ex...
43c3f4a38314830b3619692ed14f63ed00aa8f27
3,633,900
def certificate_admin_list(request): """ Displays a list of :model:`rr.Certificate` including old certificates and weak keys. Only available for super users. **Context** ``object_list`` List of :model:`rr.Certificate`. **Template:** :template:`rr/attribute_admin_list.html` ...
0d038d0df6bdae3abcad8f3b85516547a9b202cc
3,633,901
from typing import Dict from typing import Any def chaosmonkey_enabled( base_url: str, headers: Dict[str, Any] = None, timeout: float = None, verify_ssl: bool = True, configuration: Configuration = None, secrets: Secrets = None, ) -> bool: """ Enquire whether Chaos Monkey is enabled on...
a057eaaaaff8c79b93ae0e4b0e057cbd59c2c9ce
3,633,902
def compute_norm(A, scale=None): """ Compute the norm of the *A* array, which contains spin directions in Spherical or Cartesian coordinates, e.g. A = [ A_theta0 A_phi0 A_theta1 A_phi1 ... A_thetaN A_phiN] If necessary, scale the norm by the array size """ y = np.linalg.norm(A) if ...
03c180dda598e14382fc0cd8f59292db73186cec
3,633,903
def _matrixify(mat): """If `mat` is a Matrix or is matrix-like, return a Matrix or MatrixWrapper object. Otherwise `mat` is passed through without modification.""" if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False): return mat if not(getattr(mat, 'is_Matrix', True...
87065a412fce51f6a8525b42089db18dc6da786e
3,633,904
def format_value_list(value, tagname=None): """ convert osm tag value to nice html representation :param value: osm tag value as ';' separated string :return: html """ value = value.strip() if not value: return '' parts = [part.strip() for part in value.split(';')] make_bad...
bbe02729703652ae2c9f0e196c34d5b8abe4ca2b
3,633,905
def get_arg_name(node): """ Args: node: Returns: """ name = node.id if name is None: return node.arg else: return name
fecee0dfa53bbb4e1d520e13e5e2363e9035454b
3,633,906
def tf_focal_loss(y_true, y_pred, alpha=.5, gamma=2.): """ Straightforward implementation of focal loss. See https://arxiv.org/abs/1708.02002 # Arguments: y_true: actual labels {0., 1.} y_pred: predicted labels {0., 1.} alpha: see paper gamma: see paper """ assert...
43df32a74ae78fa20f6116eb8de8b3dd5d3c486c
3,633,907
def two_armed_c3d(left_model, right_model): """ C3D architecture with two arms. One of the arms will focus in Doppler videos while the other will focus in non-Doppler ones. """ left_model_input, left_model_output = left_model.layers[0].input, left_model.layers[-1].output right_model_input, righ...
58ffd61f810bc73d2537afa8b2a9d838122aa1c8
3,633,908
import torch def bbox_iou(box1, box2, x1y1x2y2=True): """ Returns the IoU of two bounding boxes """ if x1y1x2y2: # Get the coordinates of bounding boxes b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3] b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, ...
22ee7010a2cb66e31a341c78db87eeb4a7b542b9
3,633,909
def login(): """ check user credentials if next=... parameter is present redirect on success """ form = flask.request.form if flask.request.method == "POST" and form.get("login", False): password = form.get("password", None) email = form.get("email", None) ...
8284a582ad54990a897419888dd6aa3c72d2868c
3,633,910
import sys import types def load_module(url): """ Load module from url (simplest way) https://python3-cookbook.readthedocs.io/zh_CN/latest/c10/p11_load_modules_from_remote_machine_by_hooks.html """ u = request.urlopen(url) source = u.read().decode("utf-8") mod = sys.modules.setdefault(url,...
e01504ade6340dfbe290d92e66ddbc6b7de5a02f
3,633,911
def get_remove_string(packages, cuda_version): """Creates pip remove string for given cuda version and package list""" # Remove only these which version we want to change ret = for_all_pckg(packages, lambda pckg: pckg.get_uninstall_names(cuda_version)) return " ".join(ret)
885950554a716d89f37c1eb7241b068be8932f5d
3,633,912
import sys import re import os def safe_file_name(name, posix=None): """ :param str name: :param bool posix: :rtype: str """ if posix is None: posix = sys.platform != 'win32' if posix: return re.sub(r'[\x00/]', '', name) else: name = re.sub(r'[\x00-\x1f<>:"/\|?...
c9c43a00ad28107056606174c3688cf2fea4775e
3,633,913
def h_bond_basic_result_collection(monkeypatch) -> BasicResultCollection: """Create a basic collection which can be filtered.""" # Create a molecule which contains internal h-bonds. h_bond_molecule = Molecule.from_smiles(r"O\C=C/C=O") h_bond_molecule.add_conformer( np.array( [ ...
1cadd68723b747c00e09caa1dd11f387f946f3ef
3,633,914
def _try_path(basedir: P, rel: str): """ Returns content of file basedir/rel if it exists, None if file not found, or throws an exception """ if not rel: raise RuntimeError("Got invalid filename (empty string).") if rel[0] == "/": full_path = P(rel) else: full_path = base...
fd3a6c2866a2c69ed825c8e600257a899df239b5
3,633,915
def read_dataframe_legacy(dataset: zarr.Array) -> pd.DataFrame: """Reads old format of dataframes""" # NOTE: Likely that categoricals need to be removed from uns warn( f"'{dataset.name}' was written with a very old version of AnnData. " "Consider rewriting it.", OldFormatWarning, ...
c790e2266f1331423f1308634c2022c28b2028b5
3,633,916
import ast def parse_code_str(code_str) -> ast.AST: """Parses code string in a computation, which can be incomplete. Once we found something that leads to error while parsing, we should handle it here. """ if code_str.endswith(":"): code_str += "pass" try: return ast.parse(code_st...
ed0c2101dd38ca5e2fc390db3ba94b7fe13ff44d
3,633,917
def fibonacci_list(n): """ 用列表缓存中间的计算结果 :param n: n>0 :return """ lst = [0, 1, 1] while len(lst) < n + 1: ln = len(lst) lst.append(lst[ln - 1] + lst[ln - 2]) return lst[0] if n < 0 else lst[n]
02890bd5877c49d5e4d7f053a64dd9cfdeaa7d7d
3,633,918
from pathlib import Path def install(parameters): """Build capnpc-java from source.""" drydock_src = parameters['//base:drydock'] / get_relpath() if (drydock_src / 'capnpc-java').exists(): return def get_var_path(name): cmd = ['pkg-config', '--variable=%s' % name, 'capnp'] pa...
f5106f3552315ea388e8bfb895694ef57ca71a5a
3,633,919
def merge(line): """ Function that merges a single row or column in 2048. """ result = [] count = 0 newline = [] result2 = [] count2 = 0 for a in range(len(line)): result.append(0) for a in range(len(line)): result2.append(0) for num in line: if n...
5992c1bc48af124b069fd31419fec5b6edd5f3ab
3,633,920
def _perc(a, b): """ Funzione di utility: fa il rapporto tra "a" e "b", ritornandone la percentuale a due cifre """ return 'N/A' if b == 0 else round(100.0 * a / b, 2)
aa0f4c0fa09dc77b422b3779d0e9e2484b0df348
3,633,921
def shift_left_bit_length(x: int) -> int: """ Shift 1 left bit length of x :param int x: value to get bit length :returns: 1 shifted left bit length of x """ return 1 << (x - 1).bit_length()
854e79309125c60c6e5975685078809fb4c016a4
3,633,922
import datasets import tqdm def testLoadedWithoutModeRegModel(opt, model, testset,reg): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_queries1=[] all_target_captions = [] if test_queries: #...
082e42fdc9bce1c2542530eb805472c4286b70a7
3,633,923
def samPareto(a=3.0, size=None): # real signature unknown; restored from __doc__ """pareto(a, size=None) Draw samples from a Pareto II or Lomax distribution with specified shape. The Lomax or Pareto II distribution is a shifted Pareto distribution. The classical Pareto distribution can be obt...
3a931c801c0af856a339aa89014284a12ab7dc2c
3,633,924
def ripple_carry_add(A, B, cin=0): """Return symbolic logic for an N-bit ripple carry adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") ss, cs = list(), list() for i, a in enumerate(A): c = (cin if i == 0 else cs[i-1]) ss.append(a ^ B[i] ^ c) ...
730d440da2eeb8846dd86a51ef0b9ff650c71f24
3,633,925
def svn_stream_invoke_readline_fn(*args): """svn_stream_invoke_readline_fn(svn_stream_readline_fn_t _obj, void * baton, char const * eol, apr_pool_t pool) -> svn_error_t""" return _core.svn_stream_invoke_readline_fn(*args)
980c11486a8ed13289e4ba28763a6ba6978d950d
3,633,926
import argparse def cli(): """Parse and return command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( 'file', nargs='?', default='/home/sam/notes/2020-08-28_5.md', help='reading list file for reading/writing markdown notes' ) args = parse...
80a6ee8ff618aa9cfaadfddab7daccff3fe7fa1e
3,633,927
from typing import List def get_function_contents_by_name(lines: List[str], name: str): """ Extracts a function from `lines` of segmented source code with the name `name`. Args: lines (`List[str]`): Source code of a script seperated by line. name (`str`): The name ...
60239b0063e83a71641d85194f72a9cc61221177
3,633,928
import ctypes from ctypes.util import find_library import errno def create_linux_process_time(): """ Uses :mod:`ctypes` to create a :func:`time.process_time` on the :samp:`'Linux'` platform. :rtype: :obj:`function` :return: A :func:`time.process_time` equivalent. """ CLOCK_PROCESS_CPUTIM...
d1c479e059ad17c8377db0f6012a7e8ab55b1905
3,633,929
import json def get_json(obj, indent=4): """ Get formatted JSON dump string """ return json.dumps(obj, sort_keys=True, indent=indent)
be1376fcb9e820cc5012f694ca830ba0c52b5fef
3,633,930
def to_kelvin(value, initial_unit = "c"): """Convert temperature units to Kelvin. This is an internal intermediate method to convert all provided values to the same intermediate unit, which greatly simplifies exposed calculation methods. Internally, this is also mainly used to simplify ideal gas cal...
e0695e33b253c4d777f9d54b37bf593fdaacd239
3,633,931
def create_pooling_layer(pooling_type, window_size, stride_size, num_gpus, default_gpu_id): """create pooling layer""" scope = "pooling/{0}".format(pooling_type) if pooling_type == "max": pooling_laye...
f4196ed021bbda6984d95cf8385df9be778dc62c
3,633,932
def PlotConfusionMatrix(cm, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if n...
0a15a4e7b0cf8bacef2a737d8a59835fa9551fd4
3,633,933
def gen_phi(n): """ Generates a n-sized random i.i.d. sample from the uniform distribution U(-1,1). Uses inverse cdf transformation. :param n: size of the sample :return: a n-length array """ #cdf_x = np.random.rand(n) #x = 2 * cdf_x - 1 x = np.random.chisquare(2, n) return x
f7070c891fb4ae002d92cc10fa8893923d749677
3,633,934
def parse_url(url): """ Parses as RawSocket URL into it's components and returns a tuple: - ``isSecure`` is a flag which is ``True`` for ``rss`` URLs. - ``host`` is the hostname or IP from the URL. and for TCP/IP sockets: - ``tcp_port`` is the port from the URL or standard port derived fro...
2582ce00fc2aa3ee719c2ccb5d8949ef693d8d37
3,633,935
def build_operation(id, path, args, command="set", table="block"): """ Data updates sent to the submitTransaction endpoint consist of a sequence of "operations". This is a helper function that constructs one of these operations. """ if isinstance(path, str): path = path.split(".") retu...
74656a7568a6d705c9c24c091660b93d16977512
3,633,936
import string import secrets def generate_password(length=50): """Generate a password.""" alphabet = string.ascii_letters + string.digits return "".join(secrets.choice(alphabet) for i in range(length))
05b1442ef88c3a8f87c49a03f21463a61c91647b
3,633,937
def visual_estimator(possible_heights, visual_sigma, visual_height): """Computes the visual estimate. Parameters ---------- visual_sigma: ``float`` Standard deviation of the visual estimate. possible_heights: ``ndarray`` Numpy array containing all the possible heights of the...
c0338cf61f3a436b6843a10d55394e89a05018b7
3,633,938
def whiten(x, source=None): """Mean and sd normalizes x column-wise relative to summary statistics from source. Uses x itself by default""" if source is None: source = x means = np.mean(source, axis=0) stddevs = np.std(source, axis=0) return (x - means[None, :]) / stddevs[None, :]
a566c9239320b8f308be6ea96e5188061181a1a0
3,633,939
import scipy def poly_smooth(x, y, aperture, axis=0, N=3): """Smoothar *data* med hjalp av *N* te gradens polynom, langs med *axis* [=0]. Invariabler *x* x-varden for data som skall smoothas *y* y-varden for data som skall smoothas *aperture* ...
e5f1b9e71c04d92fee647d94d92e46acee121513
3,633,940
import torch def gen_img_kpts(image, human_model, pose_model, human_sort, det_dim=416, num_peroson=2): """ :param image: Input image matrix instead of image path :param human_model: The YOLOv3 model :param pose_model: The HRNet model :param human_sort: Input initialized sort tracker :param det...
a0020a584c8f0a996c6e19a747a727cb2e5dd55a
3,633,941
def deep_skipthought( dictionary, epoch = 5, batch_size = 16, embedding_size = 256, maxlen = 100, ngram = (1, 4), ): """ Train a deep skip-thought network for text similarity Parameters ---------- dictionary: dict format {'left':['right']} epoch: int, (default=5)...
4bb68193c517e76f16c3a8d067a841d287e73c32
3,633,942
def compute_min_refills(distance: int, tank: int, stops: list): """ Computes the minimum number of gas station pit stops. >>> compute_min_refills(950, 400, [200, 375, 550, 750]) 2 >>> compute_min_refills(10, 3, [1, 2, 5, 9]) -1 Example 3: >>> compute_min_refills(200, 250, [100, 150]) ...
41dff6085f3b46b191c40c3dde9b68ee3ee41e3e
3,633,943
def list_orders(): """Shows a list of orders. Requires administrator privileges. """ return render_template('order/orders.html', orders=Order.get_all())
972e20fc11a160f4b6f2ff4879e9d31f0aa288ce
3,633,944
def dkim_record_responder(query): """Provide empty DKIM key to all potential lookups.""" return TXT(query.name, "v=DKIM1; p=")
7d25172acaae8f19589e1c5d7f3b84e9b97e23a9
3,633,945
from pyrado.environments.pysim.pendulum import PendulumSim def create_default_randomizer_pend() -> DomainRandomizer: """ Create the default randomizer for the `PendulumSim`. :return: randomizer based on the nominal domain parameter values """ dp_nom = PendulumSim.get_nominal_domain_param() r...
b7519a12e94d4e68ea161fd0b106e2b9853c715d
3,633,946
def find_cursor(source): """Return (source, line, col) based on the | character, stripping the source.""" source = source.strip() i = source.index('|') assert i != -1 l = pyparsing.lineno(i, source) c = pyparsing.col(i, source) return source.replace('|', ''), l, c
88df4a8822f798a8c6c86e48e090196a04b2fcad
3,633,947
def make_provider(provider_type: str, **kwargs) -> provider.StorageProvider: """Make a StorageProvider from a provider type. Call with the arguments you would normally provide to the specific implementation's constructor. make_provider("azure", account_name="...", ...) Args: provider_type (str...
e3ad91021176ab488e62f8e919a23b71383dc025
3,633,948
def nearest(arr, val): """ Locate the element in the given array 'arr' which is closest to the specified value 'val'. """ return arr[np.abs(arr-val).argmin()]
2a4cdaab9ed866010e1da87613a03076602045f7
3,633,949
def bookmarked_posts(): """Manage a user's bookmarked posts.""" current_user = User.get_user_from_identity(get_jwt_identity()) if request.method == "GET": page = request.args.get("page", 1, type=int) per_page = request.args.get("per_page", 20, type=int) posts = current_user.bookmark...
963f653d2ca45fc69d16ff1eb2f11bf7ea430ac0
3,633,950
def get_sip_flags(target_config): """ Return the SIP platform, version and feature flags. target_config is the target configuration. """ sip_flags = [] # If we don't check for signed interpreters, we exclude the 'VendorID' # feature if target_config.py_version < 0x030000 and not target_co...
339846be395d30ee318746e6ed74830d3b62a92f
3,633,951
from PyQt6.QtWidgets import QApplication from .load_ui import loadUi def preview(ui_file): """ Preview the .ui file. Return the exit status to be passed back to the parent process. """ app = QApplication([ui_file]) ui = loadUi(ui_file) ui.show() return app.exec()
6c0fcd480e4b8db8e0c322f5cdb80516e6b2fddc
3,633,952
def analize_image(path): """Analizes a file, returning True if it contains nudity.""" image = cv2.imread(path) if image is None: return False return analize_numpy_array(image)
b15e354bbfb02997420ff1ff198567645c65874e
3,633,953
import copy def calc_pow_ref_sublhn(city, tes_cap=0.001, mod_boi=True, boi_size=50000, eta_boi=0.95, use_eh=False): """ Calculate reference electric heat generator load curve by solving thermal and electric energy balance with reduced tes size (for sublhn) ...
206a4db6362939c91b2be494024624e19fbbe736
3,633,954
def create_L(rank): """ L matrix for the calculus of the l2 norm of a column of H in the smoothness criteria (see Kimura, T., & Takahashi, N. (2017). Gauss-Seidel HALS Algorithm for Nonnegative Matrix Factorization with Sparseness and Smoothness Constraints. IEICE Transactions on Fundamentals of Electronics...
c2c6c8e6572fa510eb912c32ec87b9d2ea9a96eb
3,633,955
def _complete_sum(dnf): """ Recursive complete_sum function implementation. CS(f) = ABS([x1 | CS(0, x2, ..., xn)] & [~x1 | CS(1, x2, ..., xn)]) """ if dnf.depth <= 1: return dnf else: v = dnf.splitvar fv0, fv1 = dnf.cofactors(v) f = And(Or(v, _complete_sum(fv0)),...
c87f8f03e2106e3c79367a81d05be62ac13fccaf
3,633,956
def invert_dict(d): """Invert dict d[k]=v to be p[v]=[k1,k2,...kn]""" p = {} for k, v in d.items(): try: p[v].append(k) except KeyError: p[v] = [k] return p
1438ad5879cccf89030cb96dc5ae6c024f8e417c
3,633,957
def daten_einlesen(request): """ wird von url aufgerufen und ruft standalone-Fkt auf """ aus_alter_db_einlesen() return HttpResponseRedirect('/veranstaltungen')
e4fd282f8bfd8a6e5cc6426dfed57ff9235c0d7d
3,633,958
def _get_filtered_object_queryset(filter_params_raw, user_id=None, object_type='CITATION'): """ Parameters ---------- params : str Returns ------- :class:`.QuerySet` """ # We need a mutable QueryDict. filter_params = QueryDict(filter_params_raw, mutable=True) if object_ty...
2cae494626dbaa494003e6a65e7c20ce0b46812e
3,633,959
def _salfun(rt,dt): """Calculate salinity from conductivity and temperature variables. Calculate the salinity in the Practical Salinity Scale 1978 (PSS-78) from auxiliary variables related to conductivity and temperature. :arg float rt: Square root of the conductivity ratio, unitless. :arg...
41886e421f0c28afd1817a9db7a7636cbd9ae371
3,633,960
def Es_case_B(x, y, z, gamma): """ Eq.(9) from Ref[1] with no constant factor e*beta**2/rho**2. Note that 'x' here corresponds to 'chi = x/rho', and 'z' here corresponds to 'xi = z/2/rho' in the paper. """ if z == 0 and x == 0 and y == 0: return 0 beta2 = 1-1/gamma**2 b...
db89aab34fb147ffd4f2c245caaca0ae89bcc58c
3,633,961
def rmse(img_true, img_test): """Returns Root Mean-Squared Error score between two Numpy arrays Args: img_true: Image, numpy array of any dimension img_test: Image, numpy array of any dimension Returns: Computed RMSE score Raises: NumpyShapeComparisonException: if shap...
218f0793c56f162cbe809b231b763fc7e6e4b208
3,633,962
def enhance_color(img, r=None, severity=1): """ adjust the colour balance of an image, in a manner similar to the controls on a colour TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image. """ if r is None: severity = abs(severi...
3407c68de96413ab9569234f78bec5a1a90ecf53
3,633,963
def states(*state_names, **state_configs): """ returns a dictionary with state names as keys and state configs as values """ if not all(isinstance(s, str) for s in state_names): raise MachineError(f"all state names in 'states' should be of type 'str'") if not all(isinstance(s, dict) for s in state_c...
c895036e2a2431ed4f7ce749ac4c19f0d6b3008c
3,633,964
def find_best_matching_haplotypes(candidates, truths, ref): """Assigns genotypes to each variant to best match truths. See the module-level documentation for general information on how this algorithm works. Args: candidates: list[nucleus.protos.Variant]. A list of candidate variants, in coordinate-s...
265c474fe3749d4e6c9f1103477ff527da630cf5
3,633,965
def _documents_for(locale, topics=None, products=None): """Returns a list of articles that apply to passed in topics and products. """ # First try to get the results from the cache documents = cache.get(_documents_for_cache_key(locale, topics, products)) if documents: statsd.incr('wiki.face...
3db45743fe88bf4418ad5b7534d1c4ccae669ed0
3,633,966
def handle(pattern :str): """ Used as a descriptor. """ def wrapper(func): set_handle_func(pattern, func) return func return wrapper
65668ad31957e07b3729b06a5730b4ce7974a23c
3,633,967
import os def caterpillar_plot( hddm_model=None, ground_truth_parameter_dict=None, drop_sd=True, keep_key=None, figsize=(10, 10), columns=3, save=False, path=None, format="png", y_tick_size=10, ): """An alternative posterior predictive plot. Works for all models listed in ...
e777e854245f40e67b064b8daac7f838053fb897
3,633,968
import siteUtils from bot_eo_analyses import glob_pattern, bias_filename, tearing_task def tearing_jh_task(det_name): """JH version of single sensor execution of the tearing task.""" run = siteUtils.getRunNumber() acq_jobname = siteUtils.getProcessName('BOT_acq') flat_files = siteUtils.dependency_gl...
39025754da069cf28be50f76304726e7bb329227
3,633,969
def _ToolBar_InsertLabelTool(self, pos, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp="", clientData=None): """ Old style method to insert a tool in the toolbar. """ return self.InsertTool(pos, id, label, bitmap, bmpDisabled, kind, s...
1bb57f851ddb1c5d8ed02ef18965806bd502118d
3,633,970
def forward(request): """Forward email.""" mbox, mailid = get_mail_info(request) if request.method == "POST": url = "?action=forward&mbox=%s&mailid=%s" % (mbox, mailid) form = ForwardMailForm(request.user, request.POST) status, resp = send_mail(request, form, url) if status: ...
88758af210b05441e3f7b04bed2562f4c331224f
3,633,971
import requests def _do_delete(del_url, api_name): """Helper to do HTTP DELETE. Note: A response code of 404(NOT_FOUND) is treated as success to keep _do_delete() idempotent. """ is_success = True try: r = requests.delete(del_url, timeout=_REQUEST_TIMEOUT_SECS) if r.status_code == requests.codes....
7380bcc966ee4d0219546dd96dac40ba5bd48d7d
3,633,972
def bool2str(value): # type: (Any) -> str """ Converts :paramref:`value` to explicit ``"true"`` or ``"false"`` :class:`str` with permissive variants comparison that can represent common falsy or truthy values. """ return "true" if str(value).lower() in truthy else "false"
ec61b33d3c0d695187a80ff6cc7946adc16218e4
3,633,973
def relu(x): """Rectified linear activation function. @param x: input matrix/vector. @return: elementwise relu""" return np.maximum(x,0)
847325c8a689878cbdca5f4263a8b821ffda9a21
3,633,974
def _upper(string): """Custom upper string function. Examples: foo_bar -> FooBar """ return string.title().replace("_", "")
04ad1596657736847e909e0c4937afc407ea1f60
3,633,975
def downstream_Mn(Mn, gamma=defg._gamma): """ Args: Mn: param gamma: (Default value = defg._gamma) gamma: (Default value = defg._gamma) Returns: """ return np.sqrt((1.+.5*(gamma-1.)*Mn**2)/(gamma*Mn**2-.5*(gamma-1.)))
99643c43936ccc88ea64c643ef47fb328db77a2c
3,633,976
import re def detect_type(indicator): """Infer the type of the indicator. Args: indicator(str): The indicator whose type we want to check. Returns: str. The type of the indicator. """ if re.match(ipv4cidrRegex, indicator): return FeedIndicatorType.CIDR if re.match(ipv6...
1943bdba77c983cfd6db36a069f2304ef22598e7
3,633,977
import re def escape_sql_string(string: str) -> str: """ Escapes single quotes and backslashes with a backslash and wraps everything between single quotes. """ escaped_identifier = re.sub(r"(['\\])", r"\\\1", string) return f"'{escaped_identifier}'"
68f91b6a5c5bfcec6298f6b6f5c7dfb6b7a095f5
3,633,978
def _round_to_base(x, base=5): """Round to nearest multiple of `base`.""" return int(base * round(float(x) / base))
beccfe2951b9fcc7aafef57fd966418df1ce2cc1
3,633,979
def cards_search(): """Return a dummy cards list.""" head = {'Content-Type': 'application/json; charset=utf-8',} return (resp['cards_search'], head)
c5cd6ff642a36573f162c95b86c6c2246f6426f9
3,633,980
def mysqlpdo(editor): """Copies PHP code to connect to the active MySQL connection using PDO, to the clipboard. """ # Values depend on the active connection type if editor.connection: conn = editor.connection if conn.driver.name == "MysqlNativeSocket": params = { ...
43cb4f9965699569ae073a5b6ff31035fda0251a
3,633,981
def get_player_stats(username: str, **kwargs) -> ChessDotComResponse: """ :param username: username of the player. :returns: ``ChessDotComResponse`` object containing information about the plyers's ratings, win/loss, and other stats. """ return Resource( uri = f"/player/{user...
4127343fbf43b0de5150a98bdb266e9c9a6a4fd2
3,633,982
def perspective(image, src, dst, w, h): """ Image percpective transform function. :param image: input image :param src: original image corners points array :param dst: output image corners points array :param w: image width :param h: image height :return: result image """ M =...
a377d5eb94543f77ad267f9b9cbf223a44743952
3,633,983
def performStats(dataArray): """ Statically calculate and assign summed values of occurances to each entry """ yearArray = [[0,0] for i in range(20)] for entry in dataArray: oSum = 0 nSum = 0 for k, v in entry.old.items(): # print(k,v) oSum += v ...
444c291504783c6cf353c9dad0b4a33c0c4fa172
3,633,984
def eventize(stat, teams_regex): """ Events: End result, goal, penalties Given statistics text (ottelupöytäkirja), return a list of events """ home_team, guest_team, events, current_score = None, None, [], (0,0) for line in stat.split("\n"): line=line.strip() # end result ...
dc76dcbb1bf8f21a8c761694187030f9ca67774a
3,633,985
def QuantizeEmulate(to_quantize, quant_params, **kwargs): """Use this function to emulate quantization on NN layers during training. The function accepts a single layer or multiple layers and handles them appropriately. Arguments: to_quantize: A single keras layer, list of keras layers, or a `tf...
2ff575d96cf60b2759184eccabacb9ce585e0e15
3,633,986
from typing import Union import pkgutil import inspect def search_fhir_resource_cls( resource_type: str, cache: bool = True, fhir_release: str = None ) -> Union[str, NoneType]: # noqa: E999 """This function finds FHIR resource model class (from fhir.resources) and return dotted path string. :arg resourc...
ff0d511749c77216423d2a0fadc262cd7d4cba88
3,633,987
from typing import List from typing import Optional import logging def get_blockages_from_comments( filenames: List[Text]) -> Optional[List[List[float]]]: """Returns list of blockages if they exist in the file's comments section.""" for filename in filenames: if not filename: continue blockages ...
8ee5360d31b89d39b432e46e67ebf712f715259a
3,633,988
def get_tags(file_name): """Retreives a list of the tags for a specific file""" if File.get(File.file_name == file_name): file_tags = (Tag .select() .join(FileTag) .where(FileTag.file_id == File.get(File.file_name == file_name))) ...
d159c76146873173531e48183597df21e08a32b5
3,633,989
from typing import Any def ispointer(obj: Any) -> bool: """Check if a given obj is a pointer (is a remote object). Args: obj (Any): Object. Returns: bool: True (if pointer) or False (if not). """ if type(obj).__name__.endswith("Pointer") and hasattr(obj, "id_at_location"): ...
34bdf58b8352a11d878043ee2611d0b7c2a0dae5
3,633,990
def make_hmmer_presearchbed(nuc_fasta, hmmer_table, outbed, chrom_lens, slop=3000, windowed=False, e_cutoff=1e-2): """ Creates a bed file with regions in which to search based on HMMER output table. Filters HMMER hits by evalue then applies slop to the envelope regions of the hits. Output bedfile is...
81af6014688f9a90b91dcaae7f968fc112e1eb30
3,633,991
from googlecloudsdk.api_lib.logging import tailing def GetGCLLogTailer(): """Return a GCL LogTailer.""" try: # pylint: disable=g-import-not-at-top # pylint: enable=g-import-not-at-top except ImportError: log.out.Print(LOG_STREAM_HELP_TEXT) return None return tailing.LogTailer()
0e5aae5d1dc73e57b31167da42ceb1b3313cd493
3,633,992
def login(): """ Handles project account authentication """ if g.project is not None: return redirect(url_for('home', project_name=g.project['project_name'])) form = LoginForm(request.form) if form.validate_on_submit(): # On submit, grab name & password project_name = fo...
26a51263aa81f02caf58729c9c5d3f6f265aee97
3,633,993
def context(): """context: Overwritten by tests.""" return None
1bd0bc8ca8c9829ffcb7b141b7cf64dfcd87df45
3,633,994
import collections import calendar def updateSolarStationsCsv(station_num, tmys, config, years, merged_csv_filepath): """ Append tmy information to solar stations csv. If this is in current dir, use that one, because that allows us to process multiple stations at once. Otherwise download from data source....
8480e93defffb743cf77fc68d525409bb7ea18da
3,633,995
def postojanost_grubo_jac(x, ds, df, ip, ap, apf, l, Ct, kv, kf, ka): """ """ dfdx0 = (Ct*kv*x[0]**(kv-1.)*x[1]**kf*ap**ka+np.pi*l/1000./x[0]**2./x[1]* (ip*ds-2.*ap*(ip-1.))) dfdx1 = (Ct*kf*x[0]**kv*x[1]**(kf-1.)*ap**ka+np.pi*l/1000./x[0]/x[1]**2.* (ip*ds-2.*ap*...
754b6024eb9f342933ced512c5036742995a1975
3,633,996
def find_max_location(scoremap): """ Returns the coordinates of the given scoremap with maximum value. # Arguments scoremap: Numpy array of shape (crop_size, crop-size). # Returns keypoints2D: numpy array of shape (num_keypoints, 1). """ shape = scoremap.shape x_grid, y_grid = ...
62ba95f01611eb1a0009ad9d99275c8ffc2b14a1
3,633,997
import torch def iou_scn(x, gt, threshold=1.0): """ outputs: [K, H, W] labels: [K, H, W] """ assert x.dim() == 3 assert gt.dim() == 3 len_x = x.size(0) len_gt = gt.size(0) assert len_x == len_gt M = [] for k in range(len_x): M.append(iou_pair(x[k], gt[k])) io...
58aff4a74e4a27c336302131c47602fb29fd53f0
3,633,998
def load_word_embedding(filepath): """ given a filepath to embeddings file, return a word to vec dictionary, in other words, word_embedding E.g. {'word': array([0.1, 0.2, ...])} """ def _get_vec(word, *arr): return word, np.asarray(arr, dtype='float32') print('load word embeddings...
45fe3f2fe35d3036ff4c9b2552e1dbd8dc13bc48
3,633,999