content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_fitler_domain(http_url):
"""
domain过滤检测,仅检测二级或者三级域名
返回值:
True:过滤
False:不过滤单
"""
uri = urlparse(http_url)
domain_name = f"{uri.netloc}"
domain_list = domain_name.split(':')[0].split('.')
if len(domain_list) < 2:
return True
elif len(domain_list) > 2 and domai... | 8a768785b865260e65e79065457ddc27dec3cc1e | 68,700 |
def two_equations_system_guess(x0A, eqA, eqB, verbosity=False, niter_max=100, tolerance=1e-8):
"""
"""
iterate = True
it_counter = 0
residual0 = 0
while iterate:
it_counter += 1
xiB_guess = eqA(x0A)
xiA = eqB(xiB_guess)
residual = ((xiA - x0A)/x0A)
... | d5a4fea9250b473150a658fef46ef8fd1c16ee41 | 68,701 |
import os
def open_device(path):
"""Open a particular gbm device
* path -- integer index of devices in sorted enumeration, or
device basename (`renderD128`) or a full path-name
as returned from enumerate_devices
Will raise (at least):
* RuntimeError for invalid indic... | abec2a5e9b6c6e4d2824e45b4f419e180035a1f6 | 68,702 |
def zeropad_1501(name):
""" Arxiv IDs after yymm=1501 are padded to 5 zeros """
if not '/' in name: # new ID
yymm, num = name.split('.')
if int(yymm) > 1500 and len(num) < 5:
return yymm + ".0" + num
return name | d2a46fccf649a59194b55ff0542bd6bfbe0d8629 | 68,703 |
def performSA(
initLabels,
initRegionList,
initRegionSpatialAttr,
threshold_array,
weight,
distance_matrix,
threshold,
alpha,
tabuLength,
max_no_move,
):
"""perform the tabu list integrated simulated annealing algorithm
Parameters
----------
initLabe... | 45cb617eb2b85440d97e34c40dd7c40fdd295f06 | 68,704 |
import os
def TempDir(relative_path=''):
"""Return an absolute path to the given location in the temp directory."""
return GetAbsolutePath(os.path.join(options.temp_dir, relative_path)) | aef0b2e437a09c878cb6626205c59d6b19432936 | 68,705 |
def split_locale(locale):
"""Returns a tuple (language, TERRITORY) or just (language, )
from a a :class:`babel.core.Locale` instance or a string like `en-US` or
`en_US`.
"""
if isinstance(locale, Locale):
tloc = [locale.language.lower()]
if locale.territory:
tloc.append(l... | 6f2766818a9815d5d4c8a27597e8cd3bf894f89c | 68,706 |
def value(a):
"""
Returns a.value if a is a Variable, or just a otherwise.
"""
if isinstance(a,Variable):
return a.value
else:
return a | af45a6223ccd885fe04d51ec40cac52010f6b023 | 68,707 |
from typing import Dict
from typing import Any
import requests
def add_builds(base_url: str, body: Dict[str, Any]) -> Any:
"""
Add IIB build
Args:
base_url (str): Base URL of IIB API
body (Dict[str, Any]): Add build request payload
Returns:
Any: IIB api response
"""
s... | 272b066a5e96d65499477e9c5123af06f8b868f6 | 68,708 |
import os
def load_rel_database(db_path :str, table_name):
"""Load dataset from rel database to dataframe
Usage
------
>>> from mrec.data.dataset import load_rel_database
>>> table_name = 'mrec_table'
>>> db_path = '../../dataset/external/mrec.db'
>>> df = load_rel_database(db_path, table... | 362afa2da42c6b17d91cc16517493eb53d0ffa40 | 68,709 |
def choose_move(data: dict) -> str:
"""
data: Dictionary of all Game Board data as received from the Battlesnake Engine.
For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request
return: A String, the single move to make. One of "up", "down", "left" or "right".
... | 4ba91dc4aa509ed230924cab19608eb26a07ebd3 | 68,710 |
def seq2seq_model(input_data, target_data, keep_prob, batch_size,
source_sequence_length, target_sequence_length,
max_target_sentence_length,
source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size,
rnn_size, ... | e6ab4f68267ac19fdec0226d43b8b9620d3a3cfd | 68,711 |
def encode_categorical_classes_v2(events):
"""
velocities = 0 - velocity_bins
times = (velocity_bins + 1) - (velocity_bins + time_bins + 1); (+ velocity_bins + 1)
notes = (time_bins + velocity_bins + 2) - (prev + 87) (+ time_bins + velocity_bins - 19)
note_off = (time_bins + velocity_bins + 90) - (p... | e04a27e16622e28cd9c1075fa9a1561a0b7d9fab | 68,712 |
def get_person_applications(person_id: str = None):
"""
Returns all applications for a particular person.
:param person_id: The numeric ID of the person you're interested in.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getPersonApplications', person_id=person_... | f97dff319e27f256ac2dff10747a0bc1ff594b08 | 68,713 |
def get_bounding_box(X_masked, Y_masked):
""" Get Bounding Box.
# Arguments
X_masked: tuple of size (crop_size, 1).
Y_masked: tuple of size (crop_size, 1).
# Returns
bounding_box: List of length (4).
"""
x_min, x_max = np.min(X_masked), np.max(X_masked)
y_min, y_max = n... | bede349c5b558bd763c9a999f758e27d96242847 | 68,714 |
def __labels(known_labels, trans, labels):
"""Convert list of label names to label dictionaries with all info.
"""
return {
lbl: {
"title": trans.gettext(known_labels[lbl]['title']),
"description": trans.gettext(known_labels[lbl]['description']),
"severity": known... | 55652386496f1312ae66f64ae7673ad43d1e1879 | 68,715 |
from typing import Tuple
from typing import Optional
import json
def extract_hive_extra_setting(
connection: Connection,
) -> Tuple[Optional[str], Optional[str], Optional[int], Optional[bool]]:
"""Extract extra settings.
# Parameters:
connection (Connection): airflow connection
# Returns
... | 9ccb5d1e16b9fec1fb57f54fe8a1a7365dc7d6c4 | 68,716 |
def matrix_factory(m, n, number_generator, formula):
"""
A factory for generating matrices.
The factory takes parameters controlling the size of the matrix to be
generated, as well as the iterator to generate the number sequence and the
formula to use to compute each element of the matrix.
The... | 24f90a84b303d80e3cf89d1a588b1e151839567b | 68,717 |
def typechecker(in_=(), out_=(type(None),), msg_=None):
"""
Util function wrapper to check the type of the parameters passed to a
function.
Parameters
----------
in_ : tuple(tuple(type))
Reference of ingoing parameters' types.
out_ : tuple(tuple(type))
Reference of outgo... | 3bafe4db441b6c6a9cfb3f6322b8176f611f2f9c | 68,718 |
from typing import OrderedDict
def make_fits_objects(this_directory, fits_filenames):
""" Assemble valid, time-sorted FITS objects into (1) a list and (2) an OrderedDict by filename:
:param this_directory:
:param fits_filenames:
:return:
"""
all_fits_objects = [FITS(this_directory, '', fn) for... | 34c58cc0b94c1a420791318eb12d381d189b0159 | 68,719 |
def val_midpoint_of_line_cluster(array_line_cluster):
"""
Gets a center point of a line cluster
Hadfield and Lasenby AGACSE2018
"""
# Allocate some space for our finished matrix
accumulator_matrix = np.zeros((32, 32))
# Loop over our lines and construct the matrix
for i in range(array_l... | cdf674ababaa58e604553a80d2e3cbd8eaadcc24 | 68,720 |
def get_top_by_activity(activity: str) -> list:
"""
возвращает кол-во завершённых активностей по ТИПУ активности
:param activity: str ID в телеграма
:return: list
"""
return list(User.select(fn.COUNT(Activity.id).alias('totalcount'), User.username)
.join(Activities).join(Activity... | be86a3f134cddc4e24a7af6894c97cac6b4138ad | 68,721 |
def get_conf(splunkd_uri, session_key, owner, app_name, conf_name, stanza=None):
"""
:param splunkd_uri: splunkd uri, e.g. https://127.0.0.1:8089
:param session_key: splunkd session key
:param owner: the owner (ACL user), e.g. "-", "nobody"
:param app_name: the app"s name, e.g. "Splunk_TA_aws"
:... | 2a21a7fbb599215418d1efe863f6b2e884053e2f | 68,722 |
import binascii
def hexlify(data):
"""The binascii.hexlify function returns a bytestring in
Python3, but sometimes we want to use its output to
show a log message. This function returns an unicode
str, which is suitable for it."""
return binascii.hexlify(data).decode('ascii') | a24bf82a71a15dab12b2f683833c8a250a63097e | 68,723 |
import os
def physical_disks(release_root, config):
"""Convert a root path into a list of physical disks containing data.
Parameters
----------
release_root : :class:`str`
The "official" path to the data.
config : :class:`dict`
A dictionary containing path information.
Return... | dbba276263d4d32dfd7fd91be6d1107d67bd2ac9 | 68,724 |
import types
def stringToName(sname):
"""stringToName(string) -> CosNaming.Name
Convert a stringified name to a CosNaming.Name"""
# Try to understand this at your peril... :-)
#
# It works by splitting the input string into a list. Each item in
# the list is either a string fragment, or a single... | 76b0c1d279d100ea436ae0599bcf3c4d9278649e | 68,725 |
def pm_verify(request, state="NOP"):
"""This method can be used to verify the SUT is in a specified PM state."""
pm = Pm()
pm.verify()
return HttpResponse("Verified in %s" %state, mimetype="text/plain") | 74db962bd5d7e6940816784170ee09f6b29c5829 | 68,726 |
def create(**kwargs):
"""
Creates a new API Key.
:param kwargs:
:return:
"""
api_key = ApiKey(**kwargs)
database.create(api_key)
return api_key | 8047267a5ab8a3c4f119ba4149431d022403553e | 68,727 |
def aggAcceleration(x):
"""Aggregate acceleration inside a segment of data
Args:
x: Position values in a segment
Returns:
Aggregated velocity (single value)
"""
a = np.gradient(np.gradient(x))
# Return the highest absolute peak
return a[np.argmax(np.abs(a))... | 2c6b514ecf7fe7649f73fa2343d825df300393f0 | 68,728 |
import os
def new_suite(root_path, project, parents, suite_name):
"""Create a new empty suite."""
suite_content = ('\n'
'apps = []\n\n'
'environments = []\n\n'
'workers = 1\n\n'
'tests = []\n')
errors = []
base_path = ... | cf91bd6d698d4cc5f8cdb7534c93428e4b3debbe | 68,729 |
def _make_head_map():
"""Hardcoded Head variables mapping."""
return {"predictions/kernel:0": "dense/kernel", "predictions/bias:0": "dense/bias"} | 1fde16e3ccabc4afa7764a2240be16719d146368 | 68,730 |
def calculate_cosine_similarity_matrix(v1, v2):
"""Calculate the cosine similarity matrix between two
sentences.
"""
# Shape: (batch_size, 1, num_sentence_words1, rnn_hidden_size)
expanded_v1 = tf.expand_dims(v1, 1)
# Shape: (batch_size, num_sentence_words2, 1, rnn_hidden_size)
expanded_v2 =... | 82b33a98d5ed1384c09bceb56631643328f480d1 | 68,731 |
def site_config_processor(request):
"""Context processor to make SITE_CONFIG available to all templates."""
return {'SITE_CONFIG': SITE_CONFIG} | a948804c30ed5f1b73b69527624642f7dd39762d | 68,732 |
def not_number_message(*numbers) -> str:
"""
Формирует сообщение о неправильности чисел
:param numbers: Список чисел
:return: Отформатированное сообщение о ошибке
"""
return md.text(
md.hbold('[Ошибка]'), md.hcode(*numbers, sep=' или '), NOT_DIGIT
) | bffcb89053e81a0e62301b193ed2e46d5a3f8d56 | 68,733 |
def subclass(bases, name, suite={}, doc=None):
"""Return a class that inherits from bases
bases is the base class or classes, name is the name of the class, suite is a mapping of
attributes that the subclass should have.
Unfortunately only the metaclass of the first base class will be used at class c... | 8633b24c6b4bc9ef2eda802981a8b817d427cbb4 | 68,734 |
def call_c_function(c_function, descriptor):
"""Call a C function in a dynamic library. The descriptor is a dictionary
that contains that parameters and describes how to use them. """
# set the return type
c_function.restype = c_int
# parse the descriptor, determine the types and instantiate variab... | 4f28fd0b25b3e52d5d5a1740cf64c144dad60bbc | 68,735 |
def get_controller_in_cloud(cloud):
""" Returns a controller that is bootstrapped on the named cloud
Arguments:
cloud: cloud to check for
Returns:
available controller or None if nothing available
"""
controllers = get_controllers()['controllers'].items()
for controller_name, controlle... | 3408ef10fbb3bca8e254ebf0820454306f7193ec | 68,736 |
import time
import socket
def wait_for_dns_resolution(fqdn, timeout=30):
"""Wait for DNS to resolve a required FQDN"""
start = time.time()
end = start + timeout
while time.time() < end:
try:
socket.gethostbyname(fqdn)
return True
except socket.error:
... | ec558d8645bd202dde2510bac382e294080057dd | 68,737 |
def extract_token_argument(args):
"""Return token specified on command line.
"""
if args.token_from is None:
return args.token
return args.token_from.read().rstrip() | 63f640282cc723ea9df9b802857c4d4b68b1ddec | 68,738 |
def get_vlan(username):
"""Obtain all the different vLANs given person owns. The returned dictionary
maps the vLAN name to its tag id.
:Returns: Dictionary
:param username: The owner of the vLANs
:type username: String
"""
# Order of vlan_name, tag matters
get_sql = """SELECT vlan_name... | 0f8b4532dede2f335279cb753e47be1efd92ac1b | 68,739 |
import re
def format_condition_value(conditions):
"""
@summary:
['111', '222'] -> ['111', '222']
['111', '222\n333'] -> ['111', '222', '333']
['111', '222\\n333'] -> ['111', '222', '333']
['', '222\n', ' 333 '] -> ['', '222', '333']
[111, 222, 333] -> [111, 222, 333]
... | a62083b65a9b887ed4f1285a68cfe6ecce628613 | 68,740 |
async def generate_token(
user_gen: UserGen,
user: UserInDB = Depends(get_root_user)
):
"""Generaate user token
Note:
- In real application, once we generate a token for a user, we should
save it in a database.
- However, here we just return the token. This is the case where y... | f38ae7a3d7d67b51b478cd9ddf3642e38cc84c7e | 68,741 |
def train_example(model, image_tensor, criterion, optimizer=None,
num_chains=1, backprop=True):
""" Trains the model on a single image tensor and returns the loss """
# Require optimizer if backprobagating gradients
if backprop:
assert optimizer is not None
image_variable = Variable(im... | bc7ca744309413d982b867850b6bdce800ec7262 | 68,742 |
def report_volume( input, hdr=None, label=None, mask=None ):
"""Report (just print) the approximate volume of the input (convert to binary first).
This wrapper for get_binary_volume() allows one to call that function to report (print) the current working volume, and return the input rather than the volumes... | 6eae94ddbb51e45db1b6b7e574e4652f53975d4f | 68,743 |
from inspect import getargvalues, formatargvalues
from traceback import format_exception
from logging import getLogger
import os
import sys
def trace_logging_on(refdir=default_refdir, # reference-point directory path
negprefix=('..', '<'), # negative filtering path prefixes
... | a818f151ae7e278e94949387e6d7135c2597f0a8 | 68,744 |
import re
def non_ag_mismatches(read_seq, md, sense):
"""
Given a read sequence, MD tag, and 'sense' (look for AG if sense,
look for TC if antisense), return the number of non-AG/TC mismatches
seen in the read.
:param read_seq: string
:param md: string
:param sense: boolean
:return no... | 5c57d0b4f9f880bf1da51865b3afe43a5a02dc30 | 68,745 |
def atom_van_der_waals_radius(gra, key):
""" van der waals radius for an atom in the graph (in angstroms)
"""
symb_dct = atom_symbols(gra)
symb = symb_dct[key]
rad = ptab.van_der_waals_radius(symb) * phycon.BOHR2ANG
return rad | f7a91e769e547718846d7165655c8dad523b59cf | 68,746 |
def _get_envelopes_min_maxes(envelopes):
"""
Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note
tha the ``Quadtree.bounds`` object property serves a similar role.
Parameters
----------
envelopes : GeoSeries
The envelopes of the... | 36657377957e51ae374bf288348ce682d493a4e7 | 68,747 |
def estimate_pi(n=int(1e5), rng=1): # todo add a rng argument as in self.rand
"""Estimating pi using the rejection sampling method
Args:
n (int, optional): number of iterations for pi estimation. Defaults to int(1e5).
Returns:
float list: list of all estimations of pi (last should be the m... | 1ca0a98937f0c31354efdcc8bc7df8f9e270ed17 | 68,748 |
def new_whip(game_state):
"""
A composite component representing a Sword item.
"""
c = Composite()
set_item_components(c, game_state)
set_melee_weapon_component(c)
c.set_child(Description("Whip",
"An unusual weapon, most often used for torture."))
c.set_child(... | 0b76d89b14b14f09b46ea339d15792725d969a94 | 68,749 |
def output_add(fhandle):
"""
Set the current default output target filehandle for output routines in this module.
This sets the output destination in a stack so that the prior output can be restored
using the associated routine output_pop
Parameters:
fhandle (file): the new output destinati... | 94cc348089c03fec4ba9758fd2f5f52e96705dff | 68,750 |
def calc_ol_terms(b_xyz, j_xyz, moments_i, moments_e):
"""Compute terms of the Ohm's law.
Parameters
----------
b_xyz : xarray.DataArray
Time series of the magnetic field.
j_xyz : xarray.DataArray
Time series of the current density.
moments_i : list of xarray.DataArray
... | 48d34876e0b185e95e654f103304036c17f6ea3c | 68,751 |
def brailleify(data):
"""
>>> brailleify([0b_1000_1000, 0b_0001_0001, 0b_1111_0000, 0b_0000_1111])
'⠉⣀⡇⢸'
>>> brailleify([0b_1010_1010, 0b_0101_0101, 0b_1111_0110, 0b_0110_1111])
'⠭⣒⡷⢾'
>>> brailleify([0b_1100_1001, 0b_1001_1100, 0b_1001_0011, 0b_0011_1001])
'⢋⡙⣡⣌'
"""
return ''.join... | 4eff70272f2a28900b8b154d4c5ec183cee271e4 | 68,752 |
def y_flip_var():
"""
Label noise:
- float for global label noise
- tuple for separate label noise for every class
"""
return [0.01] | 11c0dfefa1c475794416e0559cc50e026a5244c5 | 68,753 |
def games():
"""load the select game dificulty page"""
return render_template("games.html", name=current_user.name) | 578906cca6114e689841a1e2375a3cf04cb374a9 | 68,754 |
from datetime import datetime
import os
def form_results():
"""
Forms a folder for each run and returns the path of the folders formed
:return: path of the folders created
"""
path = './Results/{}/'.format(mc.DATASET_CHOSEN)
results_folder = '{0}_{1}_{2}_{3}_{4}_{5}' \
.format(datetime... | 17769cc8416b6f1d0d07d5abb531b19b92cd83c3 | 68,755 |
def aggregateByGrid(df, field, summary, gridSize):
"""
Aggregates the specified field with chosen summary type and user
defined grid size. returns aggregated grids with summary
Parameters
----------
df : geopandas dataframe
field : string
field to be summarized.
summary : st... | 04c3c9774baa8212a68c59722858d9c83f157aba | 68,756 |
def vote_comment(_sub, _pid, cid):
""" Logs an upvote to a post. """
uid = get_jwt_identity()
value = request.json.get("upvote", None)
if type(value) is not bool:
return jsonify(msg="Upvote must be true or false"), 400
return misc.cast_vote(uid, "comment", cid, value) | 0246bf0f0f6f42439a3c50fdd574f82415c8cb4d | 68,757 |
def scalar_to_tensor(x):
"""Convert a scalar to a tensor"""
return Tensor(x) | 84f055ef07da2f704e37f08bd95f37ca4b7ab600 | 68,758 |
def getMissingCounties(counties: pd.DataFrame, drought: pd.DataFrame):
"""Checks counties that do not have a match to the drought data
These are the counties that we have, but are not in the data
Parameters:
counties: DataFrame
drought: DataFrame
Returns:
missingCounties[county_fips]: np.a... | 2f9327bd87b0963d0f1e848f80e158adf9597a6d | 68,759 |
def sum_combiner(key, value, buf, done, params):
"""
Sums the values for each key.
This is a convenience function for performing a basic sum in the combiner.
"""
if not done:
buf[key] = buf.get(key, 0) + value
else:
return buf.items() | c3cb2567efe78b4e35ffadc72ffa69a6305aa05c | 68,760 |
from datetime import datetime
import json
def hello(name: str):
"""Create a new message and send it to Rabbitmq"""
try:
json_message = {
'uid': str(uuid4()),
'creation_date': datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
'say hello to': name
}
... | b6f395ee59caad2d352ea6fffe2b68a6938287f7 | 68,761 |
from typing import Dict
def get_all_excel_sheets_as_dataframes(filepath: str) -> Dict[str, pd.DataFrame]:
"""
Takes `filepath` to an Excel file. Returns dictionary having keys = sheet names, and
values = DataFrame corresponding to respective sheet name.
"""
sheet_names = get_all_excel_sheet_names(... | ac38d506fbb9c67a6dfaca08baaabffeb87ed25f | 68,762 |
import tokenize
def build_model():
"""
Function used to create the ML pipeline and parameters to validate.
Returns: Model Object.
"""
# Model Pipeline.
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassi... | 882ca9e596feaeb539892de202f6ef3183645007 | 68,763 |
def get_mitigations_table_data(technique, reference_list, next_reference_number):
"""Given a technique a reference list, find mitigations that mitigate
technique and return list with mitigation data. Also modifies the
reference list if it finds a reference that is not on the list
"""
mitigat... | ef03d94e97bc9322c7e625f0ed00eccbd629a3a6 | 68,764 |
import math
def ppitch(y, sr=44100, n_fft=8820, win_length=1024, hop_length=2048,
num_peaks=20, num_pitches=3, min_peak=2, max_peak=743, min_fund=55.0,
max_fund=1000.0, harm_offset=0, harm_rolloff=0.75, ml_width=25,
bounce_width=0, bounce_hist=0, bounce_ratios=None, max_harm=32767,
npartial=7):
"""Pol... | 95680816341a9f1dd3d15b771371d14a46f0c8e9 | 68,765 |
def int_to_str(num):
"""takes num e.g. 123 and outputs 'one hundred and twenty three'"""
b = strip(num)
c = []
length = len(b)
count = length-1
temp = 0
while count >= 0:
if temp == 3:
temp = 0
if temp == 0:
c.append([])
c[-1].append(b[co... | ba714c527eb0368d9ab8dca24e8d28e1074879f2 | 68,766 |
def config_flask_globals(app):
"""Configure a Flask app to use all functions as template_globals."""
app = _inject_template_globals(app, _get_funcs(filters))
return app | 9c5f237a2af030b2c4391cb6e975aa01ef7096e5 | 68,767 |
import copy
def update_fits_header(
header: hint.Header, entries: dict, comments: dict = {}
) -> hint.Header:
"""This appends entries from a dictionary to an Astropy header.
This function is preferred to adding using standard methods as it performs
checks to make sure it only uses header keys reserve... | 83303aac4b44c9519d7d4e4c96504d9cfa425d19 | 68,768 |
def from_continuous_prediction(prediction, width, height):
"""Construct an instance from an instance of
:class:`ContinuousPrediction` using the grid size and offset specified
in that instance. This is more efficient as we sample each grid cell
once and then store the result.
:param prediction: An ... | 2e969b837386878cbe2ca7a632aaf8f3756d2cc3 | 68,769 |
from typing import Optional
def A_star(start: Node, end: Node, neighbours: Neighbour, heuristic: Optional[Heuristic]=None, draw=None):
"""Priority-search. Perform an A-star or Dijkstra search on the graph. If heuristic is not provided, will perform standard
Dijkstra search. If heuristic is provided, perform A... | 833cd564d7713bea4a8f9182e843cc0679468e90 | 68,770 |
from typing import Set
def get_s2_patches_with_seasonal_snow() -> Set[str]:
"""List all patches with seasonal snow from **original** BigEarthNet-S2 dataset."""
return _conv_single_col_csv_resource_to_set(Resource.patches_with_seasonal_snow) | 97a646664dc7e2b2dcc5dd30ab9ab4d71ee7e2aa | 68,771 |
def get_engine():
"""Create the default engine with the updated admin user"""
#TODO(rnirmal):Based on permissions issues being resolved we may revert
#url = URL(drivername='mysql', host='localhost',
# query={'read_default_file': '/etc/mysql/my.cnf'})
global ENGINE
... | 5de7b04848b987fb533b2b48f512e7e71874e30d | 68,772 |
def extract_atoms_from_residue_group(residue_group):
"""
Given a residue_group object, which may or may not have multiple
conformations, extract the relevant atoms for each conformer, taking into
account any atoms shared between conformers. This is implemented
separately from the main validation routine, whi... | 1c68f45c739db1fbbe1999b8a59bcfbd1d329f03 | 68,773 |
def reverse_transcribe(seq: str) -> str:
"""
transcribes DNA to RNA
then reverses the sequence
"""
t = transcribe(seq)
return(t[::-1]) | 49180931a7209eef1195b8a529437ce393dc3cb1 | 68,774 |
def normalize_user_link(url: str, user_id: int) -> str:
"""Strip off end e.g. 123/user_name"""
return f"{url.split(str(user_id))[0]}{user_id}" | d891425c3765286b2d16dc1541100d1aed69f31b | 68,775 |
def format_info_for_high_bias_fold(sess, layer_pairs, consecutive_layer_list, scaling_factor_list):
"""
Helper function that formats data from cross layer scaling and bn fold for usage by high bias fold.
:param sess: tf.compat.v1.Session type
:param layer_pairs: info obtained after batchnorm fold.
... | c64cf834c13e89ea2529cede17d39a0e5338026b | 68,776 |
import os
import pickle
def calibrate_calving_k_single_wconsensus(gdir, calving_data_fn=pygem_prms.calving_data_fullfn):
"""Calibrate calving parameter k with frontal ablation data and export to the given glacier directory
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
whe... | 43cd9410a45b8f9cbde3426e98a4a17154af9018 | 68,777 |
def train_test_split(X, y, test_size=0.25, shuffle=True, random_state=None):
"""
split features X and target y into train and test sets
inputs
------
X: a pandas dataframe with at least 3 rows
y: a pandas dataframe with at least 3 rows and only one column
test_size: a float number between 0... | 1dcf9dac7e3a9d9f62f97ef7cf8bac834576ded5 | 68,778 |
def vector_POD(inner_prod, t_train, r):
"""
Performs the vector POD, and scales the resulting modes
to lie on the unit ball. Also returns the names of the
temporal modes which will be modeled.
Parameters
----------
inner_prod: 2D numpy array of floats
(M = number of time samples, M = nu... | 5f999ad84d052754a23a38fdcb57929c1a31c5ff | 68,779 |
import functools
def etag_headers(method):
"""
A decorator that adds `ETag` and `Last-Modified` headers to `.get` method responses if not already present.
Intended to be use with Timestamped models (or any object with a modified_time field).
"""
@functools.wraps(method)
def add_etag_headers_t... | 10f50aff637804870b5268cd2ce92c4c042faa6d | 68,780 |
import re
def intcomma(value):
"""
Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
orig = force_unicode(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
if orig == new:
return new
... | 89df38e262d8b7d4d729820a8d558443b297b244 | 68,781 |
def remez_fir(data, freqmin, freqmax, df):
"""
The minimax optimal bandpass using Remez algorithm. (experimental)
.. warning:: This is experimental code. Use with caution!
:type data: numpy.ndarray
:param data: Data to filter.
:param freqmin: Low corner frequency.
:param freqmax: High corn... | 3149d7e7f5cb15c60987716f326b00337ad277c2 | 68,782 |
def get_image(driver, image_name):
"""
Return a ``NodeImage`` corresponding to a given name of size.
:param driver: The libcloud driver to query for images.
"""
try:
return [s for s in driver.list_images() if s.name == image_name][0]
except IndexError:
raise ValueError("Unknown ... | be5a246a67fafe18de368a9bdbdf3291542b0cc4 | 68,783 |
def fchr(char):
""" Print a fancy character
:param char: the shorthand character key
:type char: str
:return: a fancy character
:rtype: str
"""
return {
'PP': chr(10003),
'FF': chr(10005),
'SK': chr(10073),
'>>': chr(12299)
}.get(char, '... | d953a66546bc99cc44958d84b426d011089c8f97 | 68,784 |
import os
def test_transfer_with_ray(ray):
"""This test makes sure that the process of transferring SHConfig object to a Ray worker, working with it, and
sending it back works correctly.
"""
config = SHConfig()
config.instance_id = "x"
def _remote_ray_testing(remote_config):
"""Makes ... | 17dbe357a588bce9550c0286726d3add9f512177 | 68,785 |
import cv2
import requests
import urllib3
def download_url_img(url):
"""
下载url图像
"""
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
try:
response = requests.get(url, verify=False)
except Exception as e:
print(str(e))
return False, []
if respon... | 86c23555a55b759db2d5fac32665d0c92bcb5047 | 68,786 |
def hTest_qubitEfficient_alternative3k_circ(n, k, prep_state):
"""
Implements a qubit efficient Hadamard test for Tr(rho_A^n) using 3 registers and 1 ancilla
This implementation alternates which registers it resets.
In our noisy simulations, it actually performs worse than the other 3k circuit.
`k` is such that ... | afa2a2fc2f0e6d5c280ba468be2fadc34d000ad6 | 68,787 |
def extrinsic_euler_yzx_from_active_matrix(R, strict_check=True):
"""Compute extrinsic yzx Cardan angles from active rotation matrix.
Parameters
----------
R : array-like, shape (3, 3)
Rotation matrix
strict_check : bool, optional (default: True)
Raise a ValueError if the rotation ... | 4468adcd59116f87b42f65764f209d6947cd29fb | 68,788 |
def load_data(csv):
"""
The method reads train and test data from their dataset files.
Then, it splits train data into features and labels.
Parameters
----------
train_file: directory of the file in which train data set is located
test_file: directory of the file in which test data set is l... | 18d69855bd118c2f30f42ca64e964b21250011d7 | 68,789 |
import tqdm
def make_feat_mappings(data, feat_extractor, inv_vocab):
"""Generate the mapping dictionary for features.
Args:
data: list(tuple)
feat_extractor: feature extractor
inv_vocab: inverse vocabulary. int->str
"""
feat_mapping = dict()
for item in tqdm(data):
... | d523c7a360f4ae5b90676f1d9bd39690fc55a4aa | 68,790 |
import argparse
def bool_flag(s: str) -> bool:
"""
Parse boolean arguments from the command line.
..note::
Usage in argparse:
parser.add_argument(
"--cuda", type=bool_flag, default=True, help="Run on GPU")
"""
if s.lower() in ['off', 'false', '0']:
... | 0ce3ba6bf7c5daca42a5285e443c3afd99edc1ab | 68,791 |
def is_variable(x, exclusive=False):
"""Determines whether the input is a variable or not.
Parameters
----------
x
An ivy array.
exclusive
Whether to check if the data type is exclusively a variable, rather than an
array. For frameworks like JAX that do not have exclusive va... | 39fa0ae87d3dce411ddf278edcc32d890e6d076b | 68,792 |
import click
def get_all_triggers(config, category_id=None, active_only=False):
"""
Get all pages of triggers from Zendesk.
:param config: context config
:param category_id: only get triggers from this category
:param active: flag to only include active triggers
:return:
"""
url = f"ht... | ae576a979bc445bd9c03695be47e4e531aef755c | 68,793 |
def create_app(config_filename):
"""Configure the app w.r.t. Flask security, databases, loggers."""
config = read_config(config_filename)
app = create_app_without_blueprints(config)
register_config(app, config)
register_extensions(app, config)
register_blueprints(app, config)
register_routes... | ea3c1fc1c5d0c1ed9f71423b1fbf4c2f591ad120 | 68,794 |
def given_power(n, ef_power):
"""
Calculate and return the value of given power using given values of the params
How to Use:
Give arguments for efficiency and ef_power parameters
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERSTAND AND USE.'
Parameters:
ef... | 9b60bd43b5c53611152ab7edc17d3150670cf08e | 68,795 |
import os
def getDailyMET_livneh2013(homedir, mappingfile, subdir='livneh2013/Daily_MET_1915_2011/raw', catalog_label='dailymet_livneh2013'):
"""
Get the Livneh el al., 2013 Daily Meteorology files of interest using the reference mapping file
homedir: (dir) the home directory to be used for establish... | 439122109f9d2b3d867e8aa77b4f4e4193df9e38 | 68,796 |
def editItem(item_id):
"""Modifies the item with the given id.
Args:
item_id: the id of the item which shall be modified
"""
categories = session.query(Category).all()
item = session.query(Item).get(item_id)
if request.method == 'GET':
return render_template('edit_item.html', ... | c8f15ce6b366543ac3870e596f4586ba7b11abaa | 68,797 |
def command_eval(expr: str):
"""Evaluates a given expression."""
# Command callbacks can return values which will be passed to the caller of `dispatch()`
return eval(expr) | 0664e4c3f6f0aad320642b000e4bbf242a5b219a | 68,798 |
import torch
def augment_data(train_X, train_Y):
"""Subsample the HD signal into 10 low resolution signals"""
big_data_set = torch.Tensor(0,28,50)
big_target = torch.Tensor(0)
for i in range(10):
shifted_data = train_X[:,:,i::10]
big_data_set = torch.cat((big_data_set,shifted_data),0)
... | 93f3135811449bf5167f0b150f115db31d8b0a67 | 68,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.