content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import urllib def getEntries(person): """ Fetch a Advogato member's diary and return a dictionary in the form { date : entry, ... } """ parser = DiaryParser() f = urllib.urlopen("http://www.advogato.org/person/%s/diary.xml" % urllib.quote(person)) s = f.read(8192) while s: ...
9ed0b46aa694201817fd4c341a992c81d809abf5
25,051
def sum_values(p, K): """ sum the values in ``p`` """ nv = [] for v in itervalues(p): nv = dup_add(nv, v, K) nv.reverse() return nv
c92ac3492f0aa750879f899dde145918d4a9616d
25,052
def define_permit_price_targeting_constraints(m): """Constraints used to get the absolute difference between the permit price and some target""" # Constraints to minimise difference between permit price and target m.C_PERMIT_PRICE_TARGET_CONSTRAINT_1 = pyo.Constraint( expr=m.V_DUMMY_PERMIT_PRICE_TA...
eb31f63963e0a66491e31d3f4f8f816e21c47de9
25,053
def predict4(): """Use Xception to label image""" path = 'static/Images/boxer.jpeg' img = image.load_img(path,target_size=(299,299)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) pclass = decode_predictions(preds, top=5) ...
033fcde3cb670b8a66b430451f6b341ae2e7b980
25,054
def augment_data(image, label, seg_label, perform_random_flip_and_rotate, num_channels, has_seg_labels): """ Image augmentation for training. Applies the following operations: - Horizontally flip the image with probabiliy 0.5 - Vertically flip the image with probability 0.5 ...
c243ae36a1d38cd36131bbd2f51347d2d29ca9ff
25,055
def protobuf_open_channel(channel_name, media_type): """func""" open_channel_request = pb.OpenChannelRequest() open_channel_request.channel_name = channel_name open_channel_request.content_type = media_type return open_channel_request.SerializeToString()
0d665788cbc37d8a15c276c41d2c28e5c12ee2ea
25,056
def action(update, context): """A fun command to send bot actions (typing, record audio, upload photo, etc). Action appears at top of main chat. Done using the /action command.""" bot = context.bot user_id = update.message.from_user.id username = update.message.from_user.name admin = _admin(use...
5df8260a8787293187bba86712bf07505f915f39
25,057
def borehole_vec(x, theta): """Given x and theta, return vector of values.""" (Hu, Ld_Kw, Treff, powparam) = np.split(theta, theta.shape[1], axis=1) (rw, Hl) = np.split(x[:, :-1], 2, axis=1) numer = 2 * np.pi * (Hu - Hl) denom1 = 2 * Ld_Kw / rw ** 2 denom2 = Treff f = ((numer / ((deno...
15f39f80d7ead4bb807dbb5c365acb900bbf405d
25,059
import requests import json def read_datastore(resource_id): """ Retrieves data when the resource is part of the CKAN DataStore. Parameters ---------- resource_id: str Id for resource Returns ---------- pd.DataFrame: Data records in table format """ r = reque...
80ff1b26960e7d33b0a68d286769736617353881
25,060
import hashlib import binascii def new_server_session(keys, pin): """Create SRP server session.""" context = SRPContext( "Pair-Setup", str(pin), prime=constants.PRIME_3072, generator=constants.PRIME_3072_GEN, hash_func=hashlib.sha512, bits_salt=128, bits...
5c3c20269dce31b4f7132d123845d7a46354373f
25,061
def lenzi(df): """Check if a pandas series is empty""" return len(df.index) == 0
561705e6ff0da3bfb03407a721f2aff71a4d42a1
25,062
def m_step(counts, item_classes, psuedo_count): """ Get estimates for the prior class probabilities (p_j) and the error rates (pi_jkl) using MLE with current estimates of true item classes See equations 2.3 and 2.4 in Dawid-Skene (1979) Input: counts: Array of how many times each rating was giv...
00d93803dd7f3f56af47f8fb455613d223fe0a89
25,063
from typing import Callable def make_parser(fn: Callable[[], Parser]) -> Parser: """ Make typed parser (required for mypy). """ return generate(fn)
491888a666718d84447ff9de1b215a9e9c0f8ff0
25,064
def mfcc_htk(y, sr, hop_length=2**10, window_length=22050, nmfcc=13, n_mels=26, fmax=8000, lifterexp=22): """ Get MFCCs 'the HTK way' with the help of Essentia https://github.com/MTG/essentia/blob/master/src/examples/tutorial/example_mfcc_the_htk_way.py Using all of the default parameters from there exc...
e3beb95a027e963549df6a164b0d99345137540b
25,065
def num_to_int(num): """ Checks that a numerical value (e.g. returned by robot) is an integer and not a float. Parameters ---------- num : number to check Returns ------- integer : num cast to an integer Raises ------ ValueError : if n is not an integer """ if ...
af470940eb035fe8dd0160dfe9614c2b6d060194
25,066
def shuffle_blocks(wmx_orig, pop_size=800): """ Shuffles pop_size*pop_size blocks within the martrix :param wmx_orig: original weight matrix :param pop_size: size of the blocks kept together :return: wmx_modified: modified weight matrix """ assert nPCs % pop_size == 0 np.random.seed(123...
aec38fe296b877ab79932aa675c5d04820e391af
25,067
def change(): """ Change language """ lang = request.args.get("lang", None) my_id = None if hasattr(g, 'my') and g.my: my_id = g.my['_id'] data = core.languages.change(lang=lang, my_id=my_id) return jsonify(data)
a5186669db31b533e1ca9bc146b11d577be4f845
25,068
import shutil def make_pkg(pkgname, context): """Create a new extension package. :param pkgname: Name of the package to create. :param context: Mapping with keys that match the placeholders in the templates. :return: True if package creation succeeded or a tuple with False and a...
6e2be6e991e2061a7b07e5e44a3479dbf0c2f1b1
25,069
def view_explorer_node(node_hash: str): """Build and send an induction query around the given node.""" node = manager.get_node_by_hash_or_404(node_hash) query = manager.build_query_from_node(node) return redirect_to_view_explorer_query(query)
3534d546ba540dcfc6db1110c0a4a1086515dc3d
25,070
import math def encode_into_any_base(number, base, encoded_num): """Encode number into any base 2-36. Can be fractional or whole. Parameters: number: float -- integer representation of number (in base 10) base: int -- base to convert to encoded_num: str -- representation (so far) of n...
f6dd94e173a3844dc6d858d1c6b360354624d3f1
25,071
def handle_forbidden(error: Forbidden) -> Response: """Render the base 403 error page.""" return respond(error.description, status=HTTPStatus.FORBIDDEN)
89c59dd66ce63ceef9e60cf8beea0da7895a0394
25,072
def format_timedelta(tdelta): """Return the timedelta as a 'HH:mm:ss' string.""" total_seconds = int(tdelta.total_seconds()) hours, remainder = divmod(total_seconds, 60*60) minutes, seconds = divmod(remainder, 60) return "{0:02d}:{1:02d}:{2:02d}".format(hours, minutes, seconds)
852902e7972bcd13df8b60864ebcb2d75b2b259d
25,074
def video_data_to_df(videos_entries, save_csv): """ Creating a dataframe from the video data stored as tuples :param videos_entries: (list) list of tuples containing topics, subtopics, videos and durations :param save_csv: (boolean) condition to specify if the df is saved locally as a csv file :ret...
11bb3d9293aa3689286cde76aea8bfff72594639
25,075
def create_mysql_entitySet(username, databaseName): """ Create a new entity set in the databaseName """ password = get_password(username) entitySetName = request.json['entitySetName'] attributes = request.json['attributes'] addToSchema(request.get_json(),"mysql") pks = [] sql = "CREATE TABLE...
00510e850d4c10f24defe7af070c652d3b390b5c
25,076
def m6(X, Y, Xp, Yp, alpha=1.0, prev='ident', post='ident', **kwargs): """Computes a matrix with the values of applying the kernel :math:`m_4` between each pair of elements in :math:`X` and :math:`Y`. Args: X: Numpy matrix. Y: Numpy matrix. Xp: Numpy matrix with the probabilities of...
94d1651500ec9177a14a2c8ad80abc6ca7c3948b
25,077
import time import json from unittest.mock import call def serve_communications_and_statuses(erpnext_support_user, erpnext_support_issues, bench_site): """ returns a dict of support issue communications and statuses response = { "issue_name_1": { "communications": [], "status": "status", "last_syn...
ceaeeb5a1f5cbe956aeaef681b5e37c3d4ed58d2
25,078
def answer_view(answerid): """route to view a specific answer""" return jsonify({"answer":"Your updated answer: {} ".format(user_answers[answerid])})
82c7697bfe601b54dcb1fd9c8667565886a09c34
25,079
def jwk_factory(acct_priv_key_path: str) -> _JWKBase: """generate jwk object according private key file""" with open(acct_priv_key_path, 'rb') as f: acct_priv = serialization.load_pem_private_key( data=f.read(), password=None, backend=default_backend() ) ...
fc08dd7294ddb067534c05a7e13b26e053ac3c42
25,080
from pathlib import Path def execute( scan_definition: str | Path, df: DataFrame, *, soda_server_client: SodaServerClient | None = None, ) -> ScanResult: """ Execute a scan on a data frame. Parameters ---------- scan_definition : Union[str, Path] The path to a scan file or...
7bf0bedfb8865de117565110be4225b502e2fed2
25,081
def jaccard_similarity(emb1: np.ndarray, emb2: np.ndarray) -> float: """ 计算特征向量的Jaccard系数 :param emb1: shape = [feature,] :param emb2: shape = [feature,] :return: Jaccard 系数 """ up = np.double(np.bitwise_and((emb1 != emb2), np.bitwise_or(emb1 != 0, emb2 != 0)).sum()) down = np.double(np.bit...
18e95d7f14ca093892770364fc5af75b95bebe2a
25,082
from typing import Tuple from typing import Dict from typing import List def _share_secret_int_indices(s_i: int, n: int, t: int) -> Tuple[Dict[int, int], List[PointG1]]: """ Computes n shares of a given secret such that at least t + 1 shares are required for recovery of the secret. Additionally returns t...
b822bd79337be741bbd626751f9d745b4b9e23fc
25,083
def auto_type(key, redis=None, default=None, o=True): """Returns datatype instance""" if redis is None: redis = config.redis key = compress_key(key) if redis.exists(key): datatype = redis.type(key) if datatype == 'string': test_string = RedisString(key, redis=red...
3d1751c14c4b0c04d11ab265395dce94822558d8
25,084
from pathlib import Path def get_user_data_dir(app_name=DEFAULT_APP_NAME, auto_create=True) -> Path: """ Get platform specific data folder """ return _get_user_dir( app_name=app_name, xdg_env_var='XDG_DATA_HOME', win_env_var='APPDATA', fallback='~/.local/share', win_fallback='~...
321b885983affcc5cf4d4baf0410ae9ad6b6f443
25,085
import copy import numpy def calculateDominantFrequency(signal, fs, fMin = 0, fMax = None, applyWindow = True, fftZeroPaddingFactor = 1 ): """ calculates the dominant frequency of the given signal @param signal input signal @param fs sampling frequency @param fMin the minimum frequency [Hz] that should be con...
ab5f2818d309202f57230197c87c54b67a0f849c
25,087
def check_title(file_path): """ return 'has title' if found no title, None, if not found file_path is full path with file name and extension """ #print('is text file: ', tool.is_utf8_text_file(file_path)) if tool.is_utf8_text_file(file_path): with open(file_path, 'r') as f: ...
4559772c1e50e807935c6112cfa6001a857b9dc4
25,088
from typing import Tuple import torch def permute_adjacency_twin(t1,t2) -> Tuple[torch.Tensor,torch.Tensor]: """ Makes a permutation of two adjacency matrices together. Equivalent to a renaming of the nodes. Supposes shape (n,n) """ n,_ = t1.shape perm = torch.randperm(n) return t1[perm,:]...
df3dc6507b8eae9d148ec9b2e664a427813d93a7
25,089
from collections import defaultdict,deque def rad_extract(eventfiles,center,radius_function,return_cols=['PULSE_PHASE'],cuts=None,apply_GTI=True,theta_cut=66.4,zenith_cut=105,return_indices=False): """ Extract events with a radial cut. Return specified columns and perform additional boolean cuts. ...
bb0a5f96764c0a1edec1f408f283a2473ed630bf
25,090
import re def list_to_exp(str_list, term_padding_exp=r'\b', compile=True): """ Returns a regular expression (compiled or not) that will catch any of the strings of the str_list. Each string of the str_list will be surrounded by term_padding_exp (default r'\b' forces full word matches). Note: Also orde...
f9a1d7002a36f0348179b9997c5dec672455f077
25,092
def prepare_ddp_loader(loader: DataLoader, num_processes: int, process_index: int) -> DataLoader: """ Transfers loader to distributed mode. Experimental feature. Args: loader: pytorch dataloder num_processes (:obj:`int`, `optional`, defaults to 1): The number of processes runnin...
4f57b1888fdf43fcb910d802faee8ba997ee095f
25,093
import logging def __validate_exchange(value: str) -> str: """ Check to see if passed string is in the list of possible Exchanges. :param value: Exchange name. :return: Passed value or No Return """ valid_values = EXCHANGE_VALUES if value in valid_values: return value else: ...
001472e1485da0fc410dceafa67b78fe5dfe1058
25,094
def main(content, title="", classes=[]): """Generate a 'Material for MkDocs' admonition. """ md = markdown.markdown(content) return '<div class="admonition {0}">\n'.format(" ".join(classes)) + \ ' <p class="admonition-title">{0}</p>\n'.format(title) + \ ' <p>{0}</p>\n'.format...
e29942de52b73d8652a54c64dd22c8bac6e8496c
25,095
def get_bprop_matrix_set_diag(self): """Generate bprop for MatrixSetDiag""" get_dtype = P.DType() def bprop(x, y, z, out, dout): input_shape = F.shape(x) batch_shape = input_shape[:-2] matrix_shape = input_shape[-2:] diag_shape = batch_shape + (_get_min(matrix_shape),) ...
c35f69a957b30bcefeba858e7e9bd4ee9e4591b8
25,096
from yt import load_particles def fake_sph_grid_ds(hsml_factor=1.0): """Returns an in-memory SPH dataset useful for testing This dataset should have 27 particles with the particles arranged uniformly on a 3D grid. The bottom left corner is (0.5,0.5,0.5) and the top right corner is (2.5,2.5,2.5). All ...
9f32616d325fde7941cbcea814b3133fbcc988e5
25,097
async def _async_get_image_sessions(device: Device) -> dict[str, ImageSession]: """Return image events for the device.""" events = await device.event_media_manager.async_image_sessions() return {e.event_token: e for e in events}
4406abc1ac08d39bb0127be1d02f5c664c167e04
25,098
def make_element_weight_parser(weight_column): """ Parameterize with the column - this allows us to generate data from different analysis result types. """ def parse_element_weight(csv_row): name = csv_row[0] weight = float(csv_row[weight_column]) # Assert not zero? return name, weight return parse_element...
ddc3a4f82ecd0fe4833683759b1a1c4296839a54
25,099
def jitterer(out, z): """This function jitters the x axis 1: matrix of layer activations of the form: 2. which layer number to do outputs a transposed matrix of no of neurons rows and no of data columns""" Jx=np.ones(out[z].T.shape) for i in range(out[z].T.shape[0]): 'this is the number...
65b1337e42dab802a0c91bc27d93249171569281
25,100
from typing import Tuple def deconstruct_full_path(filename: str) -> Tuple[str, str]: """ Returns a tuple with the parent folder of the file and the file's name. Parameters ---------- filename : str The path (with filename) that will be deconstructed. Returns ------- Tupl...
d33a8fc71beb39d56dc0aa9bf94264164e8bf1a9
25,101
def bbx_to_world(cords, vehicle): """ Convert bounding box coordinate at vehicle reference to world reference. Parameters ---------- cords : np.ndarray Bounding box coordinates with 8 vertices, shape (8, 4) vehicle : opencda object Opencda ObstacleVehicle. Returns -----...
3d7438beccca9635fc15b266d2e8ada6bbc053c7
25,102
def load_data(): """ Loading data and padding """ training_set, testing_set = imdb.load_data(num_words = 10000) x_train, y_train = training_set x_test, y_test = testing_set x_train_padded = sequence.pad_sequences(x_train, maxlen = 100) x_test_padded = sequence.pad_sequences(x_test, maxlen = 100)...
ca52118f7038a70386e9ca552faf24dac6be9faf
25,103
def rotate_to_calibrated_axis( data: np.ndarray, ref_val_0: complex, ref_val_1: complex ) -> np.ndarray: """ Rotates, normalizes and offsets complex valued data based on calibration points. Parameters ---------- data An array of complex valued data points. ref_val_0 The refe...
82adf83c9565ec56ae6f13e1eec15c1be90f5dc4
25,104
from typing import Optional from typing import Tuple from typing import List def filter_graph_data(df: pd.DataFrame, x_col: str, x_range: Optional[Tuple[int, int]], file_cols: List[str], file_tuple: FileTuple) -> Optional[pd.DataFrame]: """ Filter data relevant for the graph from the dat...
200e19d73ae04c4ceabae6d0d65ccd034f368e15
25,105
def get_question_summary_from_model(question_summary_model): """Returns a domain object for an Oppia question summary given a question summary model. Args: question_summary_model: QuestionSummaryModel. The QuestionSummary model object to fetch corresponding QuestionSummary domain object...
65cce3d4440ebea81f5a777dcdec80c61b06e83b
25,106
def refraction(alt_degrees, temperature_C, pressure_mbar): """Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon. """ r = 0.016667 / tan((alt_degrees + ...
d413aba8e238b81c5a8076460cc35ae56617f148
25,108
def reduce_mem_usage(df): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024**2 logger.info('Memory usage of dataframe is {:.2f} MB'.format(start_mem)) for col in df.columns: col...
d78e0de83c85bc7495141be428bd54a0b86a2564
25,109
def retry_pattern(): """Retry pattern decorator used when connecting to snowflake """ return backoff.on_exception(backoff.expo, snowflake.connector.errors.OperationalError, max_tries=5, on_backoff=log_backoff_att...
78375f5f634f2826edd9c72fa20e2bb2d760b534
25,110
def get_vrf_route_targets( device, address_family, rt_type, vrf=None, route_distinguisher=None ): """ Get route target value from a device Args: address_family ('str'): address family value rt_type ('str'): route target type ex.) rt_type = 'import' OR ...
d06b40220c8cc5c44c5ef4ab1e7a60057791dda5
25,111
def _format_field(value, parts, conv, spec, want_bytes=False): """Format a replacement field.""" for k, part, _ in parts: if k: if part.isdigit(): value = value[int(part)] else: value = value[part] else: value = getattr(value, p...
d7c7bdf86b3b09800a4147d166584e81d7300c4f
25,113
def mixed_string_list_one_valid(): """Return mixed strings.""" return _MIXED_STRING_LISTS_ONE_VALID_
c1f0ae91f761213a6d7674ec80e24befc0b959a4
25,114
def make_parser(): """Create the argument parser, derived from the general scripts parser.""" parser = get_parser( __doc__, ('A file containing a list of files/file paths to be read. These ' 'should be nxml or txt files.') ) parser.add_argument( dest='output_name', ...
4bb2320708728bbf277bd9de380bdf6b1ead5a8b
25,115
import pathlib def script_names(): """Returns the sequence of example script names.""" result = [str(pathlib.Path(s).with_suffix('.py')) for s in _stem_names()] return result
cdb4ab63718135fa98adbfbe8a1a237f6f5ad031
25,116
def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union = gts + (1 - gt_sorted).float().cumsum(0) jaccard = 1. - intersection ...
5226660a77d5753346bedaecf786644eda296b74
25,117
def expand_image(_img, block, stride, deform=True): """ Args: _img: numpy array block: size of the blocks required stride: step size Returns: array of blocks """ if deform: _img=_img.astype('float32') ims_Z=np.zeros([_img.shape[0],block[1],block[0]...
0ffbbfe2691be69980a334d1d32f4743dfd79de0
25,118
def disabled(reason='No reason given'): """Decorator that disables a command.""" # pylint:disable=missing-docstring,unused-argument def actual_decorator(func): @wraps(func) def wrapper(*args, **kwargs): raise DisabledCommandException('This command is disabled: %s' % reason) ...
32753d4d58ee11f12eb32acabdb692640b93bab7
25,119
def get_tensor_model_parallel_group(): """Get the tensor model parallel group the caller rank belongs to.""" assert _TENSOR_MODEL_PARALLEL_GROUP is not None, \ 'intra_layer_model parallel group is not initialized' return _TENSOR_MODEL_PARALLEL_GROUP
ecf9e212995f09fe9d6a5482213dba3d1071ba80
25,120
import re import string def normalize(data): """Normalizes the values of incoming data Args: data (dict): Dictionary of response data Returns: dict """ normalized_data = {} for key in data: value = str(data[key]) key = key.lower() # Strip all fields...
ed88050001e6ea65b77d8381b2fd247918ed8f37
25,121
def five_fold(data_set): """[summary] Args: data_set (List of Sample objects): The Samples to be partitioned Returns: fold: where fold is list of len n in n-fold of (train,test) where train and test are lists of Samples """ partition_index = int( len(data_set) / 5 ) s = 0 fol...
d4179c238da3e9ebe05ab3513b80bcce982c8728
25,122
import re def get_english_info(content_section): """ The english source section can have multiple publishers and volume counts. The criteria is that the publisher with the largest volume count is most likely the one we want so sort the lines in the section and grab data from the first line. """ ...
c71751d863a4407fa409b18d7cced44c6044cb10
25,124
import numpy def load_factual_vec(fname, vocab, k): """ Loads 300x1 word vecs from FACTBANK compiled word embeddings """ word_vecs = {} with open(fname, "rb") as f: header = f.readline() vocab_size, layer1_size = map(int, header.split()) binary_len = numpy.dtype('float32'...
f37e030b4b8412a96652e67a673204e13c3cb3dc
25,125
from datetime import datetime def vaccine(date): """ Auxiliary function. Download data about vaccination in Cantabria from the Ministry of Health, Consumer Affairs and Social Welfare. https://www.mscbs.gob.es Args: date(str): Date in format %Y%m%d Returns: DataFrame with vaccination d...
5e3f9ffc3106b76ab637ab23fb6e8e6f487a48f1
25,126
def cache(f): """A decorator to cache results for a given function call. Note: The caching is only done on the first argument, usually "self". """ ret = {} def _Wrapper(*args, **kwargs): self = args[0] if self not in ret: ret[self] = f(*args, **kwargs) return ret...
786218b8c248bcb7c9d519a843dd4542a9b612b0
25,127
def home(): """Return the home page.""" response = flask.render_template( 'index.html', metrics=SUPPORTED_METRICS.keys()) return response, 200
aeb98484b580ceab6f45d7f52e05dda0b97ddb2b
25,128
def data_to_segments_uniform(x, n_segments, segment_ranges=True): """ Split data into segments of equal size (number of observations).""" return split_equal_bins(x, n_segments)
d787bdad8604f4dbf327576f655a9e408b314766
25,129
from pathlib import Path def load_all_sheets(file_name): """ Load from a xls(x) file all its sheets to a pandas.DataFrame as values to sheet_names as keys in a dictionary Parameters ---------- file_name : str, Path file_name to load from Returns ------- dict dictionary...
84452af6d81c7b44c0669af637950e8b1c1dbda8
25,130
from datetime import datetime def rate_limit(limit=1000, interval=60): """Rate limit for API endpoints. If the user has exceeded the limit, then return the response 429. """ def rate_limit_decorator(func): @wraps(func) def wrapper(*args, **kwargs): key: str = f"Limit::{req...
3f609d2bfe4a90fcf822df50e6c81032ad7d0d03
25,131
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def auth_filter(filteredapp): return AuthProtocol(filteredapp, conf) return auth_filter
b4b3b64093998865cf6a1846935c1a10db37b0ea
25,132
def parse(stylesheet): """Parse a stylesheet using tinycss2 and return a StyleSheet instance. :param stylesheet: A string of an existing stylesheet. """ parsed_stylesheet = tinycss2.parse_stylesheet( stylesheet, skip_comments=True, skip_whitespace=True ) css = qstylizer.style.StyleShee...
3df3901c06e861b03746c21a056bae51bb93ebd6
25,133
import unittest def test_suite(): """Returns a test suite of all the tests in this module.""" test_classes = [TestNetCDFPointUtilsConstructor, TestNetCDFPointUtilsFunctions1, TestNetCDFPointUtilsGridFunctions ] suite_list = map(unittest.default...
ebe3b28968def1131be19aedc963263f3277a5fb
25,134
from typing import List def compute_max_cut(n: int, nodes: List[int]) -> int: """Compute (inefficiently) the max cut, exhaustively.""" max_cut = -1000 for bits in helper.bitprod(n): # Collect in/out sets. iset = [] oset = [] for idx, val in enumerate(bits): ise...
30acd71267cd213e559bf43b8296333530736624
25,135
def get_capacity_potential_from_enspreso(tech: str) -> pd.Series: """ Return capacity potential (in GW) per NUTS2 region for a given technology, based on the ENSPRESO dataset. Parameters ---------- tech : str Technology name among 'wind_onshore', 'wind_offshore', 'wind_floating', 'pv_utilit...
4daaf38ca9f54aa162b79682ed981d3ba3ab3167
25,136
import time import urllib import json def use_nearby_search(url, next_page=False, request_count=0): """Call nearby search API request. Parameters ---------- url: str URL to use to send a Nearby Search Request in Google Maps Place Search API next_page: boolean, optional(default=False) ...
f579288356c4330a3af5ec2ac94cf31242669ba8
25,137
import urllib def _GetGoogleAuthtoken(account_type, user, password, service, source): """This function authenticates the user in the specified service using the provided authentication data. Args: account_type: Type of the account to login, could be GOOGLE or any other string if the account is exte...
9852968100d116e27cf50f4b047661ef3135074d
25,138
def trim_filters(response): """Trim the leading and trailing zeros from a 1-D array or sequence, leaving one zero on each side. This is a modified version of numpy.trim_zeros. Parameters ---------- response : 1-D array or sequence Input array. Returns ------- first : int ...
2582c5821bd5c8487c0f9d2f55d2d982767d2669
25,139
def is_spanning(graph, subgraph): """ Return True or False by passing graph and subgraph through function V to check if the subgraph uses all verticies of the original graph Parameters ---------- graph = A networkx graph. subgraph = A networkx subgraph of 'graph'. ...
371388bd6657165451216c4c65c5ea43ef19fed5
25,140
from bs4 import BeautifulSoup import re def clean_text(text): """ A function to pre-process text Parameters ---------- text : string the string to be processed Returns ------- text : string a clean string """ tok = WordPunctTokenizer() pat1 = r'@[A-Za-z0-9]...
dc9d243d4c57ec1ea1af20325be57db536ec4286
25,144
def test_alias_function(): """Test 4: Generate markup based on an element using an (alias w/function) parameter to explicitly correlate data and elements""" template = get_template('contacts-alias') def alias_name(p, e, k, v): eq_(k, 'name') return 'foo' weld(template('.contact')[0], d...
69275c3e6676ac7b0473676fc7fe65d387edfecd
25,146
def baseurl(request): """ Return a BASE_URL template context for the current request. """ if request.is_secure(): scheme = 'https://' else: scheme = 'http://' return {'BASE_URL': scheme + request.get_host(), }
76f3d75008eb996d1da226dbb4a7bd6e228fbcd1
25,147
import requests def geolocate(address, bounds=None, country=None, administrative_area=None, sensor=False): """ Resolves address using Google Maps API, and performs some massaging to the output result. Provided for convenience, as Uber relies on this heavily, and the desire to give a simple 'batteries incl...
71edf37429aa10420e070d0cacf4e9ade1e6a75f
25,148
def _cmdy_hook_class(cls): """Put hooks into the original class for extending""" # store the functions with the same name # that defined by different plugins # Note that current (most recently added) is not in the stack cls._plugin_stacks = {} def _original(self, fname): """Get the orig...
5653a71aeafc184751edcb8fddecd503c4aa2ee9
25,149
def load_data( datapath=None, minstorms=3, minbmps=3, combine_nox=True, combine_WB_RP=True, remove_grabs=True, grab_ok_bmps="default", balanced_only=True, fix_PFCs=True, excluded_bmps=None, excluded_params=None, as_dataframe=False, **dc_kwargs ): """Prepare data f...
72c7e6be0eabddeba79c681c5da30e0b855b6496
25,152
def parser_IBP_Descriptor(data,i,length,end): """\ parser_IBP_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "IBP", "contents" : unparsed_descriptor_contents } (Defined in ISO 13818-1 specif...
12379af2260dd461751c59e2023b7e5e9d68b979
25,155
import logging def build_county_list(state): """ Build the and return the fips list """ state_obj = us.states.lookup(state) logging.info(f"Get fips list for state {state_obj.name}") df_whitelist = load_data.load_whitelist() df_whitelist = df_whitelist[df_whitelist["inference_ok"] == True]...
b11a0b831b7b89d04896ed1914acf993ef1d48ba
25,156
import bs4 def is_comment(obj): """Is comment.""" return isinstance(obj, bs4.Comment)
e56749b3d5f95754a031cc7286229d942333a22e
25,157
from typing import Tuple import sqlite3 def insert_user(username: str) -> Tuple[int, str]: """ Inserts a new user. If the desired username is already taken, appends integers incrementally until an open name is found. :param username: The desired username for the new user. :return A tuple contai...
9eeeb6755251183de5ad775acfceef17c9f582a3
25,158
def get_gateway(ctx, name): """Get the sdk's gateway resource. It will restore sessions if expired. It will read the client and vdc from context and make get_gateway call to VDC for gateway object. """ restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['pr...
998f1a6a600797164c3e053eed206d99d20b338c
25,159
def fn_getdatetime(fn): """Extract datetime from input filename """ dt_list = fn_getdatetime_list(fn) if dt_list: return dt_list[0] else: return None
efea54154d318e0e5ef71c6147057b461696c677
25,160
def greenplum_kill_process(process_id): """ :param process_id: int :return: None """ query = """ select pg_cancel_backend({0}); select pg_terminate_backend({0}); """.format(process_id) return greenplum_read(query)
1bcd362bf2ed3d4cb5773c5539d0e9bb43bc96ab
25,161
import base64 import re def check_app_auth(headers): """Authenticate an application from Authorization HTTP header""" try: auth_header = headers["Authorization"] except KeyError: return False # Only handle HTTP Basic authentication m = re.match("Basic (\w+==)", auth_header) i...
5378f70041294fdad591ffbb941991cb03a7fb3d
25,162
def setupConnection(): """ Create connection to database, to be shared by table classes. The file will be created if it does not exist. """ dbPath = conf.get('db', 'path') conn = builder()(dbPath) return conn
3437cf04622acf32b974b1ecc406daa594d30650
25,163
def max_pool(ip): """does a 2x2 max pool, crops off ends if not divisible by 2 ip is DxHxW op is DxH/2xW/2 """ height = ip.shape[1] - ip.shape[1]%2 width = ip.shape[2] - ip.shape[2]%2 h_max = np.maximum(ip[:,:height:2,:], ip[:,1:height:2,:]) op = np.maximum(h_max[:,:,:width:2], h_max[:,...
c270c4128842e33e69e0861f0010b0903c9728d3
25,164
import torch def get_bin_vals(global_config): """ Creates bin values for grasping widths according to bounds defined in config Arguments: global_config {dict} -- config Returns: tf.constant -- bin value tensor """ bins_bounds = np.array(global_config['DATA']['labels']['offset...
07acdcb0329c1002983ca021fbc84c60f7474758
25,165