content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import TextIO import sys def smart_open(filename: str = None, mode: str = 'r') -> TextIO: """ File OR stdout open :param str filename: filename :param str mode: file opening mode :return: file handle object """ if filename and filename != '-': return open(filename, mode) ...
ef4adaabf69c50a9344af57b66cae3923522dca0
3,621,400
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
from typing import Tuple from typing import Sequence def compute_ocr_score(E: Text) -> float: """Compute the phrase score. FIXME: These methods effectively mutate entities, which we don't do anywhere except in the clustering code. They add the phrase/cluster scores as metadata fields. We could use memoizatio...
38d4f11e92a0db72c3243de528749769e06779ee
3,621,402
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
from typing import Dict from typing import Callable import os def plot_graph(history: Dict[str, float], loss_fn: Callable, optimizer: str) -> None: """Renders and saves an animation of the data passed in the `history` parameter. Parameters ---------- history : dict[str, float] ...
ef01bd7d26d912e15ff873924edfd5257daee835
3,621,411
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
import os def read_data(path): """Reads data file from disk.""" file = '' for file in os.listdir(path): if file.startswith('data'): break assert file.startswith('data'), "data not found" extension = os.path.splitext(file)[1].lstrip('.') info = 'file extension must be csv, parquet, or ...
283a95ec80387347dc85c6afa8ad32490b9e3656
3,621,429
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
import os import json def reader(): """ Open saved data and return the values in lists :return: list with time, list with kinect values, list with kalman values, list with robot movements, list with distance moved, list with time in each loop """ # Delete old files if not os.path.exists(os.pat...
996c5fe5f35049c5d21a94816151db3cf40b85ab
3,621,444
import functools import os def _mypy_results(session): """Get the cached mypy results for the session, or generate them.""" return _cached_json_results( results_path=( session.config._mypy_results_path if _is_master(session.config) else session.config.slaveinput['_m...
03b3161b0c42a3f36944518760fa83cbc6158c3f
3,621,445
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
import os def _get_base_docker_compose_path() -> str: """ Return the base docker compose `devops/compose/docker-compose.yml`. """ # Add the default path. dir_name = "devops/compose" # TODO(gp): Factor out the piece below. docker_compose_path = "docker-compose.yml" docker_compose_path =...
6a0293265f0fe89d6ba548159caf6b811d87d0ee
3,621,448
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 ReqTranslatorFactory(hand, trans): """\ This function will make a factory that can create handlers for the HTTP Server If this is used, the requests coming in to that handler will be formatted using the given translator. hand - a factory function that returns a handler to be used by the...
af8261377f2f2c24bb50ea9025d4867974dd96d5
3,621,451
from typing import List from typing import Any from typing import Tuple def test_memoization_nomatch(capsys: FixtureRequest) -> None: """ Test that already failed match is found in the cache on subsequent matches. """ def grammar() -> List[Any]: return [(rule1, ruleb), [rule1, rulec]] ...
b083a59b4c2c0566d9441223b9b8a1c642b3f62b
3,621,452
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
import os def batch_fastqs(fastqs,batch_size,basename="batched", out_dir=None): """ Splits reads from one or more Fastqs into batches Concatenates input Fastq files and then splits reads into smaller Fastqs using the external 'batch' utility. Arguments: fastqs (list): ...
0d85ffea790d72751304d8a7fbd44d2eadeff1d9
3,621,454
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
import os def get_urlpatterns(root_url_path: str = None)->str: """获取路由内容列表区域""" if root_url_path is None: root_url_path = SCONFIGS.UrlsPath() if not os.path.exists(root_url_path): return "" # 校验路径是否存在,不存在返回空串 urlpatterns = basetools.get_list_patt_content( retools.PATT_URLPATTERNS, ...
3e56ed0c5c3793b62b511476a3340c8dc99c384e
3,621,457
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
import json def lambda_handler(event, context): """ PayPay API(reserve)の通信結果を返す Parameters ---------- event : dict POST時に渡されたパラメータ context : dict コンテキスト内容 Returns ------- response : dict PayPay APIの通信結果 """ logger.info(event) if event['body'] is...
0a88377b41e100db43925702c708d00e487c2065
3,621,473
import tempfile import os import shutil def _get_tmp_dir(filepath): """ copy .jar to a temporary directory """ tmp_dir = tempfile.mkdtemp() if os.name == 'posix': os.chmod(tmp_dir, 0o755) LOG.info("Copying %s to a temporary directory", filepath) shutil.copyfile(filepath, os.path...
c10f2f8e64b06470ad5b0901cd36b3bb718fa711
3,621,474
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
import os def get_python_libs_root(): """ Get absolute path to scripts >>> os.path.isdir(get_python_libs_root()) True """ return os.path.join(get_cime_root(), get_python_libs_location_within_cime())
62439638b0cc49290ff1eb12df6e64f6db57d4ac
3,621,489
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
def get_sample_source(prob_label): """Return a (SampleSource, n) representing the problem""" if prob_label not in label2fname: raise ValueError('Unknown problem label. Need to be one of %s'%str(list(label2fname.keys())) ) if prob_label == 'crop48_h0': one_sample = glo.load_data_file(label2...
5b0b57a4577ded4ebedfee0e6b8ecb7f47d694ce
3,621,491
def relu_backward(output, input, layer): """RELU backward Args: output: a dictionary contains output data and shape information input: a dictionary contains input data and shape information layer: one cnn layer, defined in testLeNet.py Returns: input_od: gradients w.r.t input data """ input_...
f2a1fddbc6c538a7b18da23129740de811771b62
3,621,492
def wallace_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone): """ The reduction and final adding part of a dada tree. Useful for adding many numbers together The use of single bitwidth wires is to allow for additional flexibility :param [[Wirevector]] wire_array_2: An array of arrays of ...
b0e384fc5da3c0f4b2c0d4e0cba98a67b1a3400c
3,621,493
def _make_worker(dispatcher_address, data_transfer_protocol, shutdown_quiet_period_ms=0, port=0, worker_tags=None): """Creates a worker server.""" defaults = server_lib.WorkerConfig(dispatcher_address=dispatcher_address) config_proto = service_co...
41bd703c12f24d12199b2ff791838fffb868e108
3,621,494
import re import os def findfiles(paths, regexp, full=False, maxcount=10000): """ :param paths: :type paths: :param regexp: :type regexp: """ LOG.debug("Start find files") LOG.debug("Paths: %s", paths) LOG.debug("Regexp: '%s'", regexp) results = [] re_obj = re.compile(re...
716c236bb2d93fb06b44d0d206734fe7b83bc607
3,621,495
def calculate_precision(gts, preds, threshold = 0.5, form = 'coco', ious=None) -> float: # https://www.kaggle.com/sadmanaraf/wheat-detection-using-faster-rcnn-train """Calculates precision for GT - prediction pairs at one threshold. Args: gts: (List[List[Union[int, float]]]) Coordinates of the avai...
7cab2212d47e4404ad9e1085e13b2a7a151ea8e4
3,621,496
def _table_view(self): """ Create a new table expression that is semantically equivalent to the current one, but is considered a distinct relation for evaluation purposes (e.g. in SQL). For doing any self-referencing operations, like a self-join, you will use this operation to create a referenc...
5e1033afb8d886bd5982f1005df648199cb4d3f6
3,621,497
def formatEx(excepInst): """ _formatEx_ given a DbdException instance, generate a simple message from it """ msg = "%s:%s %s" % (excepInst.__class__.__name__, excepInst.getErrorMessage(), excepInst.getErrorCode(), ) return ...
6f2a1fda050f4ab9eaf24f5c7f6d1c019e64306e
3,621,498
from typing import Callable from typing import Any def resolutionstart(func: Callable[[Any], Any]) -> Callable[[Any], Any]: """ Mark the given function as the first frame before resolution of objects begins. Additional frames will be injected """ RESOLUTION_START.add(func.__code__) return func
2b64b5614df99bdba9a32142deb194e89e771b72
3,621,499