content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def tile_images(img_nhwc): """ Tile N images into one big PxQ image. (P,Q) are chosen to be as close as possible, and if N is square, then P=Q. Parameters ---------- img_nhwc: list or array of images, ndim=4 once turned into array n = batch index, h = height, w = width, c = chann...
14bcb0629070bda20a093476c3e399cc87fa4a5d
3,621,374
from typing import List from typing import Dict def get_top_menu(user: AbstractUser, admin_site: str = "admin") -> List[Dict]: """ Produce the menu for the top nav bar """ options = get_settings() menu = make_menu(user, options.get("topmenu_links", []), options, admin_site=admin_site) children...
6a59b9f59021a473657da56601521cd6c3df8f30
3,621,375
def _calculate_share_known_cases(df): """Calculate the share of known cases from detected and undetected cases. Args: df (pandas.DataFrame): Dataframe with columns "date", "type" and "count". Each date and type is a row. Returns: share_known_cases (pandas.Series): s...
75b1a33a98a8a2fcd59905e29ee1efe4dcf91384
3,621,376
def device_get_all_by_filters(filters): """Returns Compute devices filtered by name of the field.""" return IMPL.device_get_all_by_filters(filters)
2ff170a2df5eace277ae7109ef9a97271b4b95c0
3,621,377
def fv_creator(lamp, lams, lamda_c, int_fwm, betas, M, P_p,P_s, Df_band=1): """ Cretes 7 split frequency grid set up around the waves from degenerate FWM. The central freuency of the bands is determined by the non-depleted pump approximation and is power dependent. The wideness of these bands is det...
301d9c57ab64b2e78d15400905d418304a35f3ce
3,621,378
def read_select_def(line: str): """Attempt to read SELECT definition line""" select_match = FRegex.SELECT.match(line) select_desc = None select_binding = None if select_match is None: select_type_match = FRegex.SELECT_TYPE.match(line) if select_type_match is None: select_...
5895f6e04aac2827ededc6986e27f9aaa71b967a
3,621,379
def getSubString(string, firstChar, secondChar,start=0): """ Gives the substring of string between firstChar and secondChar. Starts looking from start. If it is unable to find a substring returns an empty string. """ front = string.find(firstChar,start) back = string.find(secondChar,front+1) if ...
c845c3c31abce7ed8064cfd16e455c27f1aac806
3,621,380
def slopePythonPlane(inBlock, outBlock, inXSize, inYSize, A_mat, z_vec, winSize=3, zScale=1): """ Calculate slope using Python. Algorithm fits plane to a window of data and calculated the slope from this - slope than the standard algorithm but can deal with noisy data batter. The ...
89fcc8385f894cbb1c8387097ae5a064844cc137
3,621,381
def decTimeToDeg(sign_sym, deg, min, sec): """Convert dec sign, degrees, minutes, seconds into a signed angle in degrees. sign_sym may represent negative as either '-' or numeric -1.""" if sign_sym == -1 or sign_sym == '-': sign = -1 else: sign = 1 return dmsToDeg(sign, deg, min, ...
b2ecc2d449617560069193623a8b9aa98d1ea78c
3,621,382
def clone( model, input_tensors=None, layer_fn=to_monotonic, input_dim=-1, dc_decomp=False, convex_domain={}, mode="backward", slope_backward=V_slope.name, IBP=True, forward=True, finetune=False, ): """ :param model: Keras model :param input_tensors: List of input...
f6450b13ca26a72692b77aecbcbe310753c0a824
3,621,385
def OddCore(G): """ Subgraph of vertices and edges that participate in odd cycles. Aka, the union of nonbipartite biconnected components. """ return Graphs.union(*[C for C in BiconnectedComponents(G) if not isBipartite(C)])
94818dfce0590b900272b2926fc45b052464228f
3,621,386
def pv(td1,p1,df1): """ returns the vapour partial pressure for given dew-frost point at pressure :param td1: known dew-frost point :param p1: known total pressure :param df1: calculate over dew(1) or frost (0) :return: vapour partial pressure (Pa) """ return vp(td1, df1)*ef(td1, p1, df...
edfc31cdd7e9cbaf49e575fd408ebd7bac81296d
3,621,387
def FExist(filedisk, err): """ Test if FITS file exists returns True or False * file = File name * disk = disk number, 0->CWD * err = Python Obit Error/message stack, """ ################################################################ # Checks if err.isErr: ...
5fa0b07b17ae18eb8b43e0cb3997265eb26f0710
3,621,388
def _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar): """Estimate the diagonal covariance vectors. Parameters ---------- responsibilities : array-like of shape (n_samples, n_components) X : array-like of shape (n_samples, n_features) nk : array-like of shape (n_components,) ...
9031123eba89e79aca939290fd9d2234f9da03bb
3,621,389
def mediation_covariates(intervention, run, mediation_year, num_mediators): """Build the causal dataset.""" # Just use all of the states at the moment of treatment assignment confounders = run[intervention.time].values() mediators = run[mediation_year].values()[:num_mediators] return np.concatenate(...
eaa70942b0ebff820e5007ea47ee7d10bb802339
3,621,390
def get_azimuth(inclination: float, launchpad_latitude: float) -> float: """Gets the required Azimuth of the launch in order to satisfy the orbit inclination. The azimuth changes in function of the targeted orbit as well as the position of the launchpad. Args: inclination (float): inclination (in d...
12ccfa58da65754bdbb185e11128e11aa97844c0
3,621,392
from io import StringIO def create_wsgi_request(event_info, server_name='zappa', script_name=None, trailing_slash=True): """ Given some event_info, create and return a valid WSGI request environ. """ method = event_info['httpMethod'] params = ev...
7b95db4c0f501bfa5ffdeb21c6166b24b4bc13ed
3,621,393
def knapsack_polynomial_estimation(W, weights, costs, eps): """Полиномиальное приближение задачи о рюкзаке. W - вместимость рюкзака weights - веса предметов costs - стоимости предметов eps - точность приближения (должна быть 0 < eps < 1) """ assert W >= 0 assert weights.shape == costs.shape...
15beebcca875c61f9e077c24c0a170e383f95242
3,621,394
def extract_watermark(fileName, base=2) -> str: """ 从STL文件中提取水印 fileName: 文件名 base: 返回水印的进制,默认为二进制 """ solid = Solid(fileName) __ref = __get_ref(solid) __ord = __ord2S(__ref) # 一个参数标识提取水印 __ord = __ord[:128] # 除去后缀0 if base == 2: return __ord elif base =...
c2a8d23b37926ea4a5c007175cb19ad95c3aacae
3,621,395
def make_figure84(): """ Returns initial conditions for a 4-body system in a 8-shaped orbit. """ ps = ParticleSystem(4) ps.mass[...] = [1.0, 1.0, 1.0, 1.0] ps.rx[...] = [+1.382857, 0.0, -1.382857, 0.0] ps.ry[...] = [0.0, +0.157030, 0.0, -0.157030] ps.rz[...] = [0.0, 0.0, 0.0, 0.0] ...
7df73bbf9588df6e6599baaf9a14b535f1077c23
3,621,396
def pca(data,k=5,frac=0.99,whiten=0): """Computes a PCA and a whitening. The number of components can be specified either directly or as a fraction of the total sum of the eigenvalues. The function returns the transformed data, the mean, the eigenvalues, and the eigenvectors.""" n,d = data.sh...
fc752af6cd3c6296a607dcf801d1d273879278b8
3,621,397
import multiprocessing import threading def isatty(file): """ Returns `True` if `file` is a tty. Most built-in Python file-like objects have an `isatty` member, but some user-defined types may not, so this assumes those are not ttys. """ if (multiprocessing.current_process().name != 'Main...
07de93799f67becd927c392f65b25a335d14fc9a
3,621,398
def update_networkipv6(networkv6, user): """Updates a NetworkIPv6.""" netv6_obj = get_networkipv6_by_id(networkv6.get('id')) netv6_obj.update_v3(networkv6) return netv6_obj
57ca37be83bbee77a24b99f42c4dc7c60efaf806
3,621,399
def saveJsonConfig(fn=None): """Saves the visualization options to a JSON object or file. If fn is provided, it's saved to a file. Otherwise, it is returned. """ return scene().saveJsonConfig(fn)
9127b4af4c24d8f0a240960369921b2e376bed2b
3,621,401
import time def train_cn_image(model, train_loader, optimizer): """Train for one epoch.""" print('running train_cn_image') batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() model.train() end = time.time() ...
3949c26d79ff8571ce1dbfa3c204756cf2d35c12
3,621,403
def checksum(basenum): # type: (str) -> str """ Will compute the checksum digits for a given CNPJ base number. `basenum` needs to be a digit-string of adequate length. """ verifying_digits = str(hashdigit(basenum, 13)) verifying_digits += str(hashdigit(basenum + verifying_digits, 14)) retur...
f59a18786d1d4cd8db26dc3310bc38aaae27161d
3,621,404
def process_move(grid, move): """Returns True if the user is still alive, False otherwise.""" user_x, user_y = move.x, move.y cell = grid[user_x][user_y] if move.flag: cell.flag = not cell.flag return GameState.ALIVE cell.revealed = True if cell.is_bomb: return GameSta...
7f2bea6a328ef41d2291c47e1f1aebc6d99a431c
3,621,405
def factorial_iter(num: int) -> int: """ Return the factorial of an integer non-negative number. Parameters ---------- num : int Raises ------ TypeError if num is not integer. ValueError if num is less than zero. Returns ------- int """ if not ...
36ec433bf02bdef0770f9f9b86feff9afa995eb3
3,621,406
def update_Q(Qsa, Qsa_next, reward, alpha, gamma): """ updates the action-value function estimate using the most recent time step """ return Qsa + (alpha * (reward + (gamma * Qsa_next) - Qsa))
f5f54d8e8b9f67c1145d967fd731ea37a4aa1e57
3,621,407
import pickle def load_psnr(loss_file): """ load image psnr or optical flow psnr. :param loss_file: loss file path :return: """ with open(loss_file, 'rb') as reader: # results { # 'dataset': the name of dataset # 'psnr': the psnr of each testing videos, # } ...
a8c4b6850d3ffe15c566a732eb73a27b6d750e20
3,621,408
def check_num(prompt: str) -> float: """Function to check if users input is an integer""" while True: try: num = int(input(prompt)) return num except Exception as e: print(e)
51756a7f84f7db455ac7a53de81c6e62d20dad83
3,621,409
def _convert_to_time_range(timestamp=None): """Create a timestamp range from an HBase / HappyBase timestamp. HBase uses timestamp as an argument to specify an exclusive end deadline. Cloud Bigtable also uses exclusive end times, so the behavior matches. :type timestamp: int :param timestamp: (...
fadcef24d952138b1c5733c40d48b0565006b4dc
3,621,410
def deploy(): """ :param token: Token The token to deploy :return: bool: Whether the operation was successful """ if not CheckWitness(TOKEN_OWNER): print("Must be owner to deploy") return False if not Get(context, 'initialized'): # do deploy logic Put(co...
2236bce3e1b78e0535010211690f2d959bf4d838
3,621,412
def add_master_legend(mp, exclude_panels=None, loc='upper center', exclude_labels=[], **kwargs): """ Make a big legend! """ handles, labels = [], [] if 'bbox_to_anchor' not in kwargs: kwargs['bbox_to_anchor'] = (0.5, 1.0) if isinstance(mp, MultiPanel): for k, ax in enumer...
2c6ff08ab22513296c5da2c75baff32a688c1acd
3,621,413
def euclidean_silhouette(X, z): """ Computes the average Silhouette Coefficient with euclidean distance Args: X (array<m,n>): m x n float matrix with datapoints z (array<m>): m-length integer vector of cluster assignments Returns: A scalar float with the silhouette score ""...
07794d3f290e3cde217f2021d520c99b51a18dd2
3,621,414
def in_tcltk_website(text): """Receives the tcltk website text string and returns the range where the colors are written.""" start = text.find('<PRE>') + len('<PRE>') end = text.find('</PRE>') colors = text[start:end] return colors
decf15574f4ed00f32aa31427591cb17472ae221
3,621,415
import types def task_salt_tree() -> types.TaskDict: """Deploy the Salt tree in ISO_ROOT.""" return { 'actions': None, 'task_dep': [ '_deploy_salt_tree:*', ], }
e495bc71fd72288449797387673acd6d69d904d9
3,621,416
def get_diff(l1, l2): """ Returns the difference between two lists. """ diff = list( list(set(l1) - set(l2)) + list(set(l2) - set(l1)) ) return diff
16b2083fcd4f61cb86c563ea6773b64e6fbe6006
3,621,417
def mlurl(parser, token): """ Based on django url tag. Just adds language postfix to view name for multilinagual stuff. """ bits = token.contents.split(' ') if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" " (path to a view)" % ...
6ef6e10fc023528d3870233b4a02ddc4bea3b47b
3,621,418
from typing import List def card_list_difference(cards1: List[card.Card], cards2: List[card.Card]) -> List[card.Card]: """Returns the cards that were in one set but not in another.""" in_cards2: List[bool] = [] for card1 in cards1: remained: bool = False for card2 in cards2: if...
ab7330d2b391e6acb6cadb4fd55095920c732546
3,621,419
def get_inner_edges(bm, boundary_type): """get the edges to run maze on ignore the outer edge of selection and any edges with any verts on boundary input: bm: the bmesh for the whole mesh output: sel_geom: list of selected verts, edges, faces inner_edges: list of BMEdge """ ...
100db56bde8d9af249e107fa1a98509121ae8267
3,621,420
import struct def read_exif_from_file(filename): """Slices JPEG meta data into a list from JPEG binary data. """ f = open(filename, "rb") data = f.read(6) if data[0:2] != b"\xff\xd8": raise InvalidImageDataError("Given data isn't JPEG.") head = data[2:6] HEAD_LENGTH = 4 exif ...
5888df3d1cd4a2cd825caa27b9c39dd4b58645f6
3,621,421
def geo_to_suppl(accession, GEO): """Retrieve supplemental files associated with a GEO ID. :param accession: GEO ID :type id: str :param GEO: Type of GEO entry, either GSM or GSE :type id: str :return: a list of dictionaries with supplemental file information :rtype: list """ if ...
7db7df084d83e84925864f262d8abb3ec3324857
3,621,422
import numpy def resnet(input_, dim_in, dim, dim_out, name, use_batch_norm=True, train=True, weight_norm=True, residual_blocks=5, bottleneck=False, skip=True): """Residual convolutional network.""" with tf.variable_scope(name): res = input_ if residual_blocks != 0: ...
a80ce86902fc560e4e2d0e7a7618dfbb2a803317
3,621,423
def create_form_data(self, request, data_map, encoding = "utf-8"): """ Processes the data map, creating a single map with all the attributes described in the form data format. :type request: Request :param request: The request to be used. :type data_map: Dictionary :param data_map: The map ...
28f17ad1f1fdb5c16a7ccb849633ee50438a2630
3,621,424
def identical_prediction_lists(prev_prediction_list, curr_prediction_list): """ Check if two predictions lists are the same :param prev_prediction_list: list Last iterations predictions :param curr_prediction_list: list current iterations predictions :return: bool false = not identical, true = ident...
b74140acb3c5529fb804710d4fd3bfd64bb4f009
3,621,425
def modify_jws_and_forge_signature(raw_jws: bytes, payload_modify_function=None) -> bytes: """Take in a JWS in raw form (concatenated URL-safe base64), modify its payload using payload_modify_function, and then forge a signature with a new CA that will be attached to the cert chain. Arguments: ra...
dd7d971e917d7c5631b14ea38972ffb26c4283ca
3,621,426
from types import ModuleType from django.utils.module_loading import import_string def get_dynamic_tenant_prefixed_urlconf(urlconf, dynamic_path): """ Generates a new URLConf module with all patterns prefixed with tenant. """ class LazyURLConfModule(ModuleType): def __getattr__(self, attr): ...
c12b7ef5db488218447ecdcd457dd4e1ea24c788
3,621,427
def get_sigma(voxel_size_z=None, voxel_size_yx=100, psf_z=None, psf_yx=200): """Compute the standard deviation of the PSF of the spots. Parameters ---------- voxel_size_z : int or float or None Height of a voxel, along the z axis, in nanometer. If None, we consider a 2-d PSF. voxel_...
4eafb854a89b7861e1f2a76ffdd1785a62c22233
3,621,428
from typing import Dict from typing import Any from typing import Tuple from typing import Union from typing import List def eval_step( model: nn.Module, params_dict: Dict[str, Any], batch: Dict[str, jnp.ndarray]) -> Tuple[Union[float, List[float]], Any]: """Evaluates the given model on the batch. Args: ...
4011ef0e12fa7e39970e99161e3a551b19ab1bc5
3,621,430
def harris(img, peaking=(255, 0, 0)): """ Harris corner detection """ img, gray = rgba2rgb(img), rgba2gray(img) dest = cv.cornerHarris(src=gray, blockSize=2, ksize=5, k=0.1) dest = cv.dilate(dest, None) img[dest > 0.01 * dest.max()] = peaking return img, dest,
2d10373f892355b8aa7c0b5e785c2c3b550a0f6c
3,621,431
def _get_paragraphs(response): """Parse HTML and extract paragraphs Args: response: HTML response from Requests-HTML Returns: HTML element """ try: paragraphs = [] for paragraph in response.html.find('p'): paragraphs.append(paragraph.text) return...
3047cf726519a96c0f0bf90ff305384b5d8ecda7
3,621,432
def preprocess_box(data): """Pre-process data to take correct values.""" return [[data[2], data[0]], [data[3], data[1]]]
9955ece2ae559832a49db32dadc73c3eb3b85c82
3,621,433
def link_olac(lang): """Links to the OLAC project""" if isinstance(lang, Language) and lang.isocode: return "http://search.language-archives.org/search.html?q=%s" % lang.isocode else: return ""
eec703cbbea6b8f54d1ed634e47efb65ce520c19
3,621,434
def dense_image_warp_grad(op, grad): """ Dense image warp grad. """ image = op.inputs[0] flow = op.inputs[1] grad_image, grad_flow = gen_npu_cpu_ops.dense_image_warp_grad( grad, image, flow) return [grad_image, grad_flow]
aaaad8eac3085bb4aa0d3ad5bdb8675f0855352f
3,621,435
def _AddressTranslation(rdata, unused_origin): """Returns the address of the given rdata. Args: rdata: Rdata, The data to be translated. unused_origin: Name, The origin domain name. Returns: str, The address of the given rdata. """ return rdata.address
8be6c393f64dd852af8e8fa0a06e6ddea9d5a25f
3,621,436
def generate_sents(fsa): """ Generate all possible sentences represented by an fsa. """ # Find the starting node node_sent_dic = {} # {node: list of sentences} start_node = start_state end_node = end_state node_sent_dic[str(start_node)] = [] for nd in fsa.neighbors(start_node): ...
2c7644abfa09c6fd023cc61e76ec80ffe58eafa0
3,621,437
def spectral_roll_off(signal, fs): """Computes the spectral roll-off of the signal. The spectral roll-off corresponds to the frequency where 95% of the signal magnitude is contained below of this value. Feature computational cost: 1 Parameters ---------- signal : nd-array Signal f...
7bd447534c8c59bc3a95c7838c7452da7fc990b4
3,621,438
from typing import Tuple def sample_gaussian_data(logit_fn: LogitFn, x_generator: XGenerator, num_train: int, key: chex.PRNGKey) -> Tuple[testbed_base.Data, float]: """Generates training data for given problem.""" x_key, y_key = jax.random...
f70bcf3e40294d02a7b55c96b40e450407e0c584
3,621,439
def grab_sponsored_job_links(soup): """ Grab all sponsored job posting links from a Indeed search result page using the given soup object Parameters: soup: the soup object corresponding to a search result page e.g. https://www.indeed.com/jobs?q=data+scientist&l=Paris&start=20 R...
680a1963034ffcaa6eda174ef05916ed7a43f3df
3,621,440
def _get_start_offset(lines) -> int: """Get the start offset of the license data.""" i = len(lines) - 1 count = 0 for line in lines[::-1]: if "-" * 10 in line: count += 1 if count == 2: break i -= 1 return max(i, 0)
16fb35dad0381276a3cedd1fb5f19b165fb69b03
3,621,441
def make_n_grams(seq, n): """ return iterator """ ngrams = (tuple(seq[i:i+n]) for i in range(len(seq)-n+1)) return ngrams
f026106c2dd548c7390f2dddcdeccc5c40f3ba7b
3,621,442
def getDiaphragmaticLungNodes(cache, coordinates, generateParameters, nodes, nodetemplate, nodeFieldParameters, elementsCount1, elementsCount2, elementsCount3, nodeIds, nodeIndex, nodeIdentifier): """ :parameter: :return: nodeIndex, nodeIdentifier """ # Initialise ...
eacaf4be58a23482bd866f0858ae9ad496dcdc08
3,621,443
def main(sci_filename, size, dark_filename): """ This is a wrapper for calc_cma and shift_cma Parameters "sci_filename" is calc_cma's "filename" parameter "size" is calc_cma's "size" parameter "dark_filename" is shift_cma's "norm_filename" parameter Returns dict result ...
d3f7bd40a6bf5998e5054f2621b0bb00185598ed
3,621,446
def getrows(): """ returns the number of rows in the current map Input: - - Output: - nr of rows in the current clonemap as a scalar """ a = pcr.pcr2numpy(pcr.celllength(), np.nan).shape[0] return a
c1d4125a832e6156e3c6c4713364c14e6ed47c37
3,621,447
def gauss_mode_width_max(hist, bins, var=None, mode_guess=None, n_bins=5, cost_func='Least Squares', inflate_errors=False, gof_method='var'): """ Get the max, mode, and width of a peak based on gauss fit near the max Returns the parameters of a gaussian fit over n_bins in the vicin...
461b3828cd41f5636e72e5a32a36162798195571
3,621,449
import warnings def fetch_libsvm(dataset, replace=False, normalize=True, min_nnz=3): """ This function is deprecated, we now rely on the libsvmdata package. Parameters ---------- dataset: string Name of the dataset. replace: bool Whether to redownload the data. normalize: ...
77de81289d32fa1353c7d416a807e27db9d51e1b
3,621,450
def list_entry(): """List all the entries form entry database. Returns: html with entry data. """ entries = [] for entry in database.entry.select(): entries.append({"id": entry.id, "team_name": entry.team_name, "match_num": entry.matc...
99e5a934df2cc2cd21657d4661491b699e641ea8
3,621,453
def check_eligibility_for_deletion(status, has_been_available): """Check if a project status is eligible for deletion""" if status not in ["In Progress"]: raise DDSArgumentError("Project Status prevents files from being deleted.") if has_been_available: raise DDSArgumentError( "...
4a49f0a558c8abb3a517605d81a4e249571c73e0
3,621,455
def main(cmd): """ This is the function to create or delete the service action based on life cycle action command :param cmd: :return: """ arguments = cmd db_password = '' if 'geDbPassword' in os.environ: db_password = os.environ['geDbPassword'] try: ...
2e68c0649d5654393283fc2acca5edf7fd1b26ec
3,621,456
from typing import List from typing import Callable def expectation(samples: List[List[tf.Tensor]], fn: Callable[[List[tf.Tensor]], tf.Tensor]) -> tf.Tensor: """ tfp.monte_carlo.expectation didn't have the right functionality-- I wanted to be able to calculate multiple expectation values concu...
f3d184df411fdb56cc9389bb8d173c3024d00136
3,621,458
def rigged_lstm_model(i) -> DualLSTMModel: """ Create a fake model that is rigged to an inverted probability distribution for an ellipse token. This needs to be a fixure, because it depends on another fixture: c(). """ class FakeModel(DualLSTMModel): @property def bad_token(sel...
41c45878154f83ba513ab233ad9b9596b4bd59b6
3,621,459
from typing import Callable def train_som_classifier( train_dataset: "CaseCollection", validate_dataset: "CaseCollection", config: SOMClassifierConfig = None, class_weights = None, model_fun: "Callable" = create_model_multi_input, ) -> "SOMClassifier": """Configure the dataset based on config ...
4ba636ba3bd22e4bc3a9dbd38aeff07f859e5779
3,621,460
def depart_edit(request, nid): """ 修改部门 """ if request.method == "GET": row_object = models.Department.objects.filter(id=nid).first() return render(request, 'depart_edit.html', {"row_object": row_object}) title = request.POST.get("title") models.Department.objects.filter(id=nid).update(t...
8e6afc648cbbf5d9231c9f016ec66102d14a53d0
3,621,461
import re def get_defectdojo_date(date): """ Returns date as required by DefectDojo. :param date: :return: yyyy--mm-dd """ regex = r"([0-9]{2})\/([0-9]{2})\/([0-9]{4})" matches = re.finditer(regex, date, re.MULTILINE) match = next(enumerate(matches)) date = match[1].groups() ...
983d1ce85cbf5bf8d0f5d6a5416cc2130dd617c1
3,621,462
def get_container_colors(containers): """ Sets an ANSII color cmd to use for each container based on it's position in the list. Unit tested: test_get_container_colors :param containers: The containers found from docker ps. :type containers: list :returns: Added color cmd to each container. ...
74fdcac91c6ca5da9bee000e639b6df828d6ff1d
3,621,463
import random import string def temporary_search_template(es, template_file, template_id_in_file, size=None, with_source=False): """A context manager that manages a temporary search template.""" def random_string(length=10): """Generate a simple random string to use as a temporary template ID""" ...
2e38772ade1dd0c0d723537a6d1828ccbca696b4
3,621,464
def convert2_ratio_perim_area(width, length): """Convert width and length data into ratio of perimeter to area.""" perimeter = ( np.pi / 2 * (3 * (width + length) - np.sqrt((3 * width + length) * (3 * length + width))) ) area = np.pi / 4 * width * length return perimeter / a...
f1a915ddddaa8b1bf15a45a4dd8a14b14e02e899
3,621,465
def connect(): """Connect to the PostgreSQL database score_it. Returns a database connection and a cursor object and raises eceptions if the connection cannot be made. """ try: conn = psycopg2.connect("dbname = score_it") except psycopg2.DatabaseError: print "The program could not c...
6fe86bd073022a03d36b49651ba613fea0fe1609
3,621,466
def gift_card_verify_code(self, referenceNo: str, **kwargs): """Verify a Binance Code (USER_DATA) GET /sapi/v1/giftcard/verify This API is for verifying whether the Binance Code is valid or not by entering Binance Code or reference number. Please note that if you enter the wrong binance code 5 times ...
e5dfc37ddd0b6371008a6c1eb5b42cf735b17663
3,621,467
def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have mu...
d389f9622c8092a2c6b7d4d15910d520063e6b39
3,621,468
def calculate_m_value(methylated_noob, unmethylated_noob, offset=0): """ the log(base 2) (1+meth / 1+unmeth) intensities (with a min clip intensity of 1 to avoid divide-by-zero-errors, like sesame)""" methylated = np.clip(methylated_noob, 1, None) + offset unmethylated = np.clip(unmethylated_noob, 1, None) ...
04bb7453b16cc67cffa254e6cf73701e18a8fad0
3,621,469
import warnings def makeresources(repos, resourcedir="data/rsrc", combine=False, cssfiles=[], jsfiles=[], imgfiles=[], staticsite=False, legacyapi=False, sitename="MySite", ...
bcfd3aeddd1b4b9dd329d79365f2a2f8e0212355
3,621,470
def I_inj_t(t): """ This function returns the external current to be injected into the network at any time step from the current_input matrix. Parameters: ----------- t: float The time at which the current injection is being performed. """ # Turn indices to integer and extract from ...
14a6c934bd67180d2171d4a62ef8aa50579f15c3
3,621,471
import json def dumps(obj, **kwargs): """ convert configuration object to a json string """ obj = _encode(obj) return json.dumps(obj, **kwargs)
d435dd92bec6c1be56c58038e407254ddfbc5427
3,621,472
from bs4 import BeautifulSoup import requests def get_soup(url: str) -> BeautifulSoup: """ Get BeautifulSoup HTML document by url. Args: url (str): Request URL Returns: BeautifulSoup: HTML document """ logger.info(f"Fetching {url}") request = requests.get(url) ret...
9a29a9a3e41e0757b5c8ebda60a3f4729523f784
3,621,475
def distance(A, B, metric='riemann'): """Return the distance between two covariance matrices A and B according to the metric : :param A: First covariance matrix :param B: Second covariance matrix :param metric: the metric (Default value 'riemann'), can be : 'riemann' , 'logeuclid' , 'euclid' , 'lo...
a0c5d31799fc749ffd33ce3c781535b0196d253b
3,621,476
def is_luhn_valid(cc): """Validate a credit card number using the Luhn algorithm. @see: U{http://en.wikipedia.org/wiki/Luhn_algorithm} @type cc: str @param cc: Credit card number. @rtype: bool @return: C{True} if the credit card number appears to be valid. """ num = map(int, cc) retu...
5c502d4519aa71a6f17c576f5c98cde3917fb461
3,621,477
def _FakeService(): """ use if you need a fake service from build """ class e: execute = lambda : {'sheets':[],} class v: def get(range=None): return [] class g: def get(spreadsheetId=None, includeGridData=None, range=None): return e values = lamb...
887c14bc0669efc0511efff2ee3301bab15aafcb
3,621,478
def histDerivative(hist, bins, giveHist=False, binInput='lin'): """Takes in a histogram assuming linear/uniform bins. Returns interpolating function for derivative of the hist up to accuracy (deltabin)^2. Uses a forward difference scheme in the first bin, a central difference scheme in the 'bulk' bi...
f848a085ea4a390b58fffbdc1e17fc9142e0cfcb
3,621,479
def qs(**kwargs): """Build a URL query string.""" url = '' for k, v in kwargs.iteritems(): if k == 'username' or k == 'password': pass for value in v: url += '&%s=%s' % (quote(k), value) return url
d248c46d9c129c77c74e0a72b2f1a1bd1dfe9a24
3,621,480
from typing import Tuple def load_data(image_key: str = "x", label_key: str = "y", label_mode: str = "fine") -> Tuple[NumpyDataset, NumpyDataset]: """Load and return the CIFAR100 dataset. Please consider using the ciFAIR100 dataset instead. CIFAR100 contains duplicates between its...
0b8479c34c2acd048403231b29bfad88a9f82055
3,621,481
def profile_update_scene(request): """ Handle User Profile page, scene post submit requests. """ if request.method != "POST": return JsonResponse({}, status=status.HTTP_400_BAD_REQUEST) if not request.user.is_authenticated: return JsonResponse( {"error": "Not authenticate...
4320c76eb981c8583a1c1a215058f3613d11f575
3,621,482
from typing import Counter def syntactic_parse_features(paragraph, parse): """ Returns the count for the usage of S, SBAR units in the syntactic parse, plus statistics about the height of the trees """ KEPT_FEATURES = ['S', 'SBAR'] # Increment the count for the part-of-speech of each head of phrase counts...
4ceb35151760f42936b823288a330c1420195661
3,621,483
import random def random_user_agent(): """ This function selects a random User-Agent from the User-Agent list, which is a constant variable that can be found at `investpy.utils.constant.USER_AGENTS`. User-Agents are used in order to avoid the limitations of the requests to Investing.com. The User-Agen...
504e696ac0c7221e1d16c11af80605f4bf3bdcc0
3,621,484
def to_bel_lines(graph): """Return an iterable over the lines of the BEL graph as a canonical BEL Script (.bel). :param pybel.BELGraph graph: the BEL Graph to output as a BEL Script :return: An iterable over the lines of the representative BEL script :rtype: iter[str] """ return itt.chain( ...
080a6ccdb3de3cc2d0adab9811a4fee101c53516
3,621,485
def get_gs_energy(H, tensors): """ Returns ground-state energy and norm of the iPEPS """ E, nrm, *_ = get_obs(H, tensors, measure_obs=False) return E[0], nrm
26b7da733c8daf38eaf4dca2e2204c4f5416b380
3,621,486
def is_weekend(date): """Is the specified date (a datetime.date object) a weekend?""" return date.weekday() in [5, 6]
43e7ab6c89943f3c13b7ab7a936b79fbc985a0dd
3,621,487
def removeUser(user_id): """ Function intended to remove users """ if user_id: try: user = Users.query.get(user_id) db.session.delete(user) db.session.commit() return True except Exception as e: print(e) return Fals...
b4ed4bf0e39a3c9aeef0b359f3a7f4c000bb7bc1
3,621,488
def first_writable_file_that_preferably_exists(files): """ Returns the first file in files (sequence of path names) that preferably exists and is writable. "Preferably exists" means that two loops are done over the files -- the first loop returns the first file that exists and is writable. If no f...
0b4fa884404ed2c6769fba8ae92b5f9d79c78c0a
3,621,490