content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pathlib
def get_enabled_gems(cmake_file: pathlib.Path) -> set:
"""
Gets a list of enabled gems from the cmake file
:param cmake_file: path to the cmake file
:return: set of gem targets found
"""
cmake_file = pathlib.Path(cmake_file).resolve()
if not cmake_file.is_file():
lo... | 0b4c8c68230b075d2c27d72b1290217864fc6888 | 3,646,952 |
from operator import add
from operator import mul
def celeryAdd3(a,b):
"""This is for a specific Celery workflow
f = (a+b) * (a+b)
We'll use chord, group and chain"""
if request.method == 'GET':
# When a worker receives an expired task it will mark the task as REVOKED
res = (group(add.... | 84599389542663207ff57a07e3b58cecc9b6427b | 3,646,953 |
def create_unmerge_cells_request(sheet_id, start, end):
"""
Create v4 API request to unmerge rows and/or columns for a
given worksheet.
"""
start = get_cell_as_tuple(start)
end = get_cell_as_tuple(end)
return {
"unmergeCells": {
"range": {
"sheetId": shee... | 3fd560a82522738099bacd3f606bbea948de7226 | 3,646,954 |
def list_to_str(slist, seperator=None):
"""Convert list of any type to string seperated by seperator."""
if not seperator:
seperator = ','
if not slist:
return ""
slist = squash_int_range(slist)
return seperator.join([str(e) for e in slist]) | 64d20b744a7b465e58e50caf60e0e1aaf9b0c2e7 | 3,646,955 |
def log_web_error(msg):
"""Take a screenshot of a web browser based error
Use this function to capture a screen shot of the web browser
when using Python's `assert` keyword to perform assertions.
"""
screenshot = selene.helpers.take_screenshot(selene.browser.driver(),)
msg = '''{original_msg}
... | 8f5e9f6c586e6739d6581986c66689881d812316 | 3,646,956 |
def parent_id_name_and_quotes_for_table(sqltable):
""" Return tuple with 2 items (nameof_field_of_parent_id, Boolean)
True - if field data type id string and must be quoted), False if else """
id_name = None
quotes = False
for colname, sqlcol in sqltable.sql_columns.iteritems():
# root table... | 6f3319dc6ae0ea70af5d2c9eda90fb1a9fb9daac | 3,646,957 |
def client():
"""Returns a Flask client for the app."""
return app.test_client() | 40d3cf2c330d2f82b6ae7514e833ef5d1bcb9594 | 3,646,958 |
from enthought.mayavi import version
from .maps_3d import plot_map_3d, m2screenshot
from enthought.tvtk.api import tvtk
from enthought.mayavi import mlab
from enthought.mayavi.core.registry import registry
def plot_map(map, affine, cut_coords=None, anat=None, anat_affine=None,
figure=None, axes=No... | d7ef70bb98849532e94d7b975303cbd370fe8bbe | 3,646,960 |
def get_mode(h5,songidx=0):
"""
Get mode from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.mode[songidx] | 9a9eb7cfed2bc525a3b5d3c8cb251c7e170a589c | 3,646,961 |
import json
def read_label_schema(path):
"""
Reads json file and returns deserialized LabelSchema.
"""
with open(path, encoding="UTF-8") as read_file:
serialized_label_schema = json.load(read_file)
return LabelSchemaMapper().backward(serialized_label_schema) | 8f15a6e63864c6f737f465abb3011193ce136db6 | 3,646,962 |
def Dump(root):
"""Return a string representing the contents of an object.
This function works only if root.ValidateExports() would pass.
Args:
root: the object to dump.
Returns:
A big string containing lines of the format:
Object.SubObject.
Object.SubObject.ParameterName = %r
"""
h = ... | 7f6a9229f6b0c250a56324570fae249c0bf1d246 | 3,646,963 |
def clean_profit_data(profit_data):
"""清理权益全为0的垃圾结算日"""
for i in list(range(len(profit_data)))[::-1]:
profit = profit_data[i][1] == 0
closed = profit_data[i][2] == 0
hold = profit_data[i][3] == 0
if profit and closed and hold:
profit_data.pop(i)
return profit_dat... | d1b7fe9d747a1149f04747b1b3b1e6eba363c639 | 3,646,964 |
def convert_single_example(ex_index, example, max_word_length,max_sen_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
text_sen = example.text_sen.strip().split()
text_pos=example.text_pos.strip().split()
text_ps = example.text_ps.strip().spli... | faf13bd6db6a07a4546531cc968bad5443b95a12 | 3,646,965 |
def scrub_literal(value):
"""
Scrubs control characters from the incoming values to remove
things like form feeds (\f) and line breaks (\n) which might
cause problems with Jena.
Data with these characters was found in the Backstage data.
"""
if not value:
return None
if isinstanc... | e0e77bb0edecc810cc6fe051020936ca0ee9bf62 | 3,646,966 |
def mock_interface_settings_mismatch_protocol(mock_interface_settings, invalid_usb_device_protocol):
"""
Fixture that yields mock USB interface settings that is an unsupported device protocol.
"""
mock_interface_settings.getProtocol.return_value = invalid_usb_device_protocol
return mock_interface_se... | 61958439a2869d29532e50868efb39fe3da6c8b5 | 3,646,967 |
from typing import Mapping
from typing import Any
import shutil
def run_eval(exp_name: str) -> Mapping[str, Any]:
""" """
pred_log_dir = f"{_ROOT}/test_data/eval_tracking_dummy_logs_pred"
gt_log_dir = f"{_ROOT}/test_data/eval_tracking_dummy_logs_gt"
out_fpath = f"{_ROOT}/test_data/{exp_name}.txt"
... | 3eaead879a39a30d2524da037d82f4d9b68d17e7 | 3,646,968 |
def MakeLocalSsds(messages, ssd_configs):
"""Constructs the repeated local_ssd message objects."""
if ssd_configs is None:
return []
local_ssds = []
disk_msg = (
messages.
AllocationSpecificSKUAllocationAllocatedInstancePropertiesAllocatedDisk)
interface_msg = disk_msg.InterfaceValueValuesEnu... | 128e7a0358221fe3d93da4726924a7a783c65796 | 3,646,970 |
def valid_variant(s, is_coding=True):
"""
Returns True if s is a valid coding or noncoding variant, else False.
Parameters
----------
s : `str`
Variant string to validate.
is_coding : `bool`
Indicates if the variant string represents a coding variant.
"""
_validate_s... | 8cb6c37bed303a052a8655dfb0832bfba638f0d6 | 3,646,971 |
def is_icon_address_valid(address: str) -> bool:
"""Check whether address is in icon address format or not
:param address: (str) address string including prefix
:return: (bool)
"""
try:
if isinstance(address, str) and len(address) == 42:
prefix, body = split_icon_address(address... | 9666d22d04d568706356b7bafd0f202cb9178892 | 3,646,972 |
import base64
def _b64urldec(input: str) -> bytes:
"""
Deocde data from base64 urlsafe with stripped padding (as specified in the JWS RFC7515).
"""
# The input is stripped of padding '='. These are redundant when decoding (only relevant
# for concatenated sequences of base64 encoded data) but the ... | fb535072b560b8565916ae8ec3f32c61c41115d8 | 3,646,973 |
def get_sns_topic_arn(aws_creds, ec2_region):
"""
Retrieves the sns topic arn for the account
"""
rgt_client = ResourceGroupsTaggingClient(aws_creds, ec2_region, logger)
sns_topic_arn = rgt_client.get_sns_topic_arn(SNS_TOPIC_TAG_KEY, SNS_TOPIC_TAG_VALUE)
if not sns_topic_arn:
raise SnsTo... | 760caa77acf414eacf4bb177dd9252fe6578a505 | 3,646,974 |
import scipy
def create_bspline_basis(knots, spline_order, dt=0.02):
"""Create B-spline basis."""
# The repeated boundary knots are appended as it is required for Cox de Boor
# recursive algorithm. See https://math.stackexchange.com/questions/2817170/
# what-is-the-purpose-of-having-repeated-knots-in-a-b-spli... | 8256b282ffc5f19a9e00d59c689e57664600b2f4 | 3,646,975 |
def execute(
device,
commands,
creds=None,
incremental=None,
with_errors=False,
timeout=settings.DEFAULT_TIMEOUT,
command_interval=0,
force_cli=False
):
"""
Connect to a ``device`` and sequentially execute all the commands in the
iterab... | ead00377f7c50d8bfdb6da39a7a1fe1820d9bcc7 | 3,646,976 |
import requests
def get_proxy(usage: str):
"""
通过WEB API接口获取代理
:param usage: 目标站点,对应WEB_AVAILABLE_PROXIES的key
:return: 可用代理或None
"""
url = API_SERVER + "/proxy?usage={}".format(usage)
res = requests.get(url, timeout=5)
try:
if res.status_code == 200:
return res.jso... | 2c836f0a7a4dce2e5442080ee93a1b32d10dac3d | 3,646,978 |
def column_names_get(subject: str) -> tuple:
""" Returns column names. """
if subject == c.SUBJECT.PLANETS:
return c.HEADERS.PLANETS
elif subject == c.SUBJECT.STARSHIPS:
return c.HEADERS.STARSHIPS
elif subject == c.SUBJECT.VEHICLES:
return c.HEADERS.VEHICLES
elif subject == c... | a544574d5ac66e2ea7e045fa2bba37fe78df20f5 | 3,646,979 |
def relabel_prometheus(job_config):
"""Get some prometheus configuration labels."""
relabel = {
'path': '__metrics_path__',
'scheme': '__scheme__',
}
labels = {
relabel[key]: value
for key, value in job_config.items()
if key in relabel.keys()
}
# parse _... | eb08f617903fe66f462a5922f8149fd8861556ad | 3,646,981 |
import random
def q_geography_capital():
"""Ask what the capital of a given country is."""
question = QuestionGenerator()
question.set_type('geography')
# select country
all_countries = facts.get_geography_countries_list()
country = random.choice(all_countries)
# formulate question
q... | 63362aae1eb0e117da3ade0c9bff22edb5504689 | 3,646,982 |
from functools import reduce
def binary_stabilizer_to_pauli_stabilizer(stabilizer_tableau):
"""
Convert a stabilizer tableau to a list of PauliTerms
:param stabilizer_tableau: Stabilizer tableau to turn into pauli terms
:return: a list of PauliTerms representing the tableau
:rytpe: List of Pauli... | 78183d9ecd436267d7732ba50cb6591fea54984e | 3,646,983 |
def checkGroup(self, group, colls):
"""
Args:
group:
colls:
Returns:
"""
cut = []
for elem in group:
if elem in colls:
cut.append(elem)
if len(cut) == len(group):
return cut
else:
return [] | ca30648c536bcf26a1438d908f93a5d3dcc131c9 | 3,646,984 |
def get_node_shapes(input_graph_def, target_nodes):
"""Get shapes of target nodes from input_graph_def, shapes may be partial"""
node_shapes = []
for target in target_nodes:
for node in input_graph_def.node:
if node.name == target:
if not 'shape' in node.attr:
print("Warning: Fail to g... | 0a70a81f0be826697d47b52dc2a2e63c0c73b3b4 | 3,646,985 |
def calculate_cost(A3, Y):
"""
计算损失函数cost值
Args:
A3: 正向传播的输出,尺寸大小为(输出尺寸, 样本数量)
Y: 真实标签向量,尺寸大小和a3相同
Return:
cost: 损失函数cost值
"""
m = Y.shape[1]
logprobs = np.multiply(-np.log(A3), Y) + np.multiply(
-np.log(1 - A3), 1 - Y)
cost = 1. / m * np.nansum(logprobs)... | 0a85baae5acc6f9ceec417f2942727cd3d96a34e | 3,646,986 |
def qsammobilenetv2(**kwargs):
"""Constructs a QSAMMobileNetv2 model.
"""
model = QSAMMobileNetV2(**kwargs)
return model | 4d0b9f23a3c40ab2386d30fe45ca70a401f41b1a | 3,646,988 |
def get_frame_labels_fields(
sample_collection,
frame_labels_field=None,
frame_labels_prefix=None,
frame_labels_dict=None,
dataset_exporter=None,
required=False,
force_dict=False,
):
"""Gets the frame label field(s) of the sample collection matching the
specified arguments.
Prov... | 0bdb1346f154f125b2f39f638929ae6e5d661db7 | 3,646,989 |
def _rpc_code_to_error_code(rpc_code):
"""Maps an RPC code to a platform error code."""
return _RPC_CODE_TO_ERROR_CODE.get(rpc_code, exceptions.UNKNOWN) | 7cb6ef3d7b751c915673f99a88800bdb53e81f72 | 3,646,990 |
def peak_values(dataframe_x, dataframe_y, param):
"""Outputs x (potentials) and y (currents) values from data indices
given by peak_detection function.
Parameters
----------
DataFrame_x : pd.DataFrame
should be in the form of a pandas DataFrame column.
For ex... | 3e0d656d80ef5806abcd2d71e80be544eca585cb | 3,646,991 |
import typing
import scipy
def random_rotation_operator_tensor (operand_space_shape:typing.Tuple[int,...]) -> np.ndarray:
"""NOTE: Not a uniform distribution."""
if vorpy.tensor.dimension_of_shape(operand_space_shape) == 0:
raise Exception(f'invalid dimension for vector space having rotation')
A ... | fd4442bb6178824fe71c6050f44539f8af34c149 | 3,646,993 |
def get_early_stopping(callback_config:dict):
""" Get tf keras EarlyStopping callback.
Args:
callback_config: config info to build callback
"""
return keras.callbacks.EarlyStopping(**callback_config) | 6f9f5e26b69765ff817c89b6ebbb59a62bc76266 | 3,646,995 |
def decode(rdf, hint=[]):
"""Decode ReDIF document."""
def decode(encoding):
rslt = rdf.decode(encoding)
if rslt.lower().find("template-type") == -1:
raise RuntimeError("Decoding Error")
return rslt
encodings = hint + ["windows-1252", "utf-8", "utf-16", "latin-1"]
i... | f42eed2caaba90f4d22622643885b4d87b9df98b | 3,646,996 |
def pad_square(x):
""" Pad image to meet square dimensions """
r,c = x.shape
d = (c-r)/2
pl,pr,pt,pb = 0,0,0,0
if d>0: pt,pd = int(np.floor( d)),int(np.ceil( d))
else: pl,pr = int(np.floor(-d)),int(np.ceil(-d))
return np.pad(x, ((pt,pb),(pl,pr)), 'minimum') | 3a0b248f9403d0cb392e1aff306af435b5a43396 | 3,646,997 |
from typing import Union
from typing import Any
from typing import Tuple
def get_env_properties(
env: Union[gym.Env, VecEnv], network: Union[str, Any] = "mlp"
) -> (Tuple[int]):
"""
Finds important properties of environment
:param env: Environment that the agent is interacting with
:t... | 6a377830cb24bc215b7d1c6b09b08ed63ab383ef | 3,646,998 |
def mahalanobis(data, produce=None):
"""
Calculate mahalanobis distance on a matrix of column vectors.
Assumes that rows are observations and columns are features.
Parameters
----------
data : numpy array or pandas dataframe
The data to calculate distances on (columns are variables... | b6dff6cfe12b4c44b6a97a6bd1f51a2250b7b63f | 3,647,000 |
def text(el):
"""
Helper to get the text content of a BeautifulSoup item
"""
return el.get_text().strip() | 7b34c77c79677a73cc66532fe6305635b1bdac43 | 3,647,001 |
def get_sha512_manifest(zfile):
"""
Get MANIFEST.MF from a bar file.
:param zfile: Open (!!!) ZipFile instance.
:type zfile: zipfile.ZipFile
"""
names = zfile.namelist()
manifest = None
for name in names:
if name.endswith("MANIFEST.MF"):
manifest = name
b... | 7ef150bb3e89f8723649ee983085a413ec8a31df | 3,647,003 |
def plot_heatmap(filename, xdata, ydata, binx, biny, title = None, xlabel = None, ylabel = None, dpi = 150, figsize = (10,10), tfont = 17, lfont = 14):
"""
Present variables as a 2D heatmap
to correlate magnitude and direction.
"""
def get_bin_id(mybins, vv):
for ibin in range(len(mybins)-1)... | 3397bf2fc02932056411ef8addde264fa50b9ea5 | 3,647,004 |
def scattering_transform1d(n_classes, sequence_length):
""" Scattering transform
"""
log_eps = 1e-6
x_in = layers.Input(shape=(sequence_length))
x = Scattering1D(8, 12)(x_in)
x = layers.Lambda(lambda x: x[..., 1:, :])(x)
x = layers.Lambda(lambda x: tf.math.log(tf.abs(x) + log_eps))(x)
x = layers.GlobalAveragePo... | 53547918c5a0efa5c0e3766c770903b146eff19e | 3,647,006 |
import zlib
def addFileContent(session, filepath, source_file_name, content_hash,
encoding):
"""
Add the necessary file contents. If the file is already stored in the
database then its ID returns. If content_hash in None then this function
calculates the content hash. Or if is avail... | fdd77f23151ed9627c5d9bbfb157839810c9655a | 3,647,007 |
def model_fn_builder(num_labels, learning_rate, num_train_steps,
num_warmup_steps):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
input_ids = featur... | 570f5297fbcc57eaae1d08e9ee816207db707ffd | 3,647,008 |
def FancyAnalyzer(expression=r"\s+", stoplist=STOP_WORDS, minsize=2,
maxsize=None, gaps=True, splitwords=True, splitnums=True,
mergewords=False, mergenums=False):
"""Composes a RegexTokenizer with an IntraWordFilter, LowercaseFilter, and
StopFilter.
>>> ana = FancyAn... | 50fddbbdc22770b3a9b732bb328bf48c0407aafe | 3,647,010 |
def find_res_shift(x_min, x_max, y_min, y_max, z_min, z_max, target_id, my_sites, res_two_three_dict, my_mols, color_list, button_list):
"""Function to find the relavant residue shifts"""
print "FINDING MAX SHIFTS"
max_shift = []
# Get the delta value
delta = 5.0
# Filter residues to the ones wi... | d46a146071f5cd48ab1382d03ac4678cc2c301fd | 3,647,011 |
def lookup(*getters):
"""Find data by provided parameters and group by type respectively"""
getters = list(reversed(getters))
def wrap(struct):
while getters:
_type, getter = getters.pop()
if _type == G_TYPE_KEY:
struct = getter(struct)
contin... | 937a44e8366016cb136f0b40a91448b97c52357d | 3,647,012 |
def compute_one(t, lhs, rhs, **kwargs):
""" Join two pandas data frames on arbitrary columns
The approach taken here could probably be improved.
To join on two columns we force each column to be the index of the
dataframe, perform the join, and then reset the index back to the left
side's original... | c050fdeae2e354be3748984a32ad96b81593355b | 3,647,013 |
def simulate(mat, det, e0=20.0, dose=defaultDose, withPoisson=True, nTraj=defaultNumTraj, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams=defaultXtraParams):
"""simulate(mat,det,[e0=20.0],[withPoisson=True],[nTraj=defaultNumTraj],[dose=defaultDose],[sf=defaultCharFluor],[bf=defaultBremFluor],[xtraParams=defaul... | 5ffdf63038fa2ba4305001f1b1ec5da0c13ebf3d | 3,647,014 |
def link_match_family(link, family_name):
"""Checks whether the a link can be used in a given family.
When this function is used with built-in family names, it tests whether the link name can be
used with the given built-in family. If the family name is not known, we return True because
the user is wor... | 7d95556b5ff6537bc994d7b017263ced13d4efc0 | 3,647,015 |
def convert_AST_to_expr(ast):
"""Creates expression from the AST."""
converter = ASTToInstrBlockConverter()
instrs = converter.my_visit(ast)
return instrs[0] | b4dca77c48cd0001a2f55c71a077a6b195a181ce | 3,647,017 |
import time
def add_data_from_api(service, repo, variable_type, keys):
"""Retrieves Github API data. Utilizes the function from github_api/github.py to do so.
This function adds the retrieved variables directly to the data dictionary.
Args:
service (Service): Service object with API connection an... | 32361d85fb92efd03b79f74f8db2e02a8fcd9866 | 3,647,018 |
def part1(data):
"""
>>> part1(read_input())
0
"""
return data | 1482c41b112a3e74775e71c4aabbd588de2b6553 | 3,647,019 |
import torch
def get_rectanguloid_mask(y, fat=1):
"""Get a rectanguloid mask of the data"""
M = y.nonzero().max(0)[0].tolist()
m = y.nonzero().min(0)[0].tolist()
M = [min(M[i] + fat, y.shape[i] - 1) for i in range(3)]
m = [max(v - fat, 0) for v in m]
mask = torch.zeros_like(y)
mask[m[0] : ... | 0ff3ab25f2ab109eb533c7e4fafd724718dbb986 | 3,647,020 |
import re
def colorize_output(output):
"""Add HTML colors to the output."""
# Task status
color_output = re.sub(r'(ok: [-\w\d\[\]]+)',
r'<font color="green">\g<1></font>',
output)
color_output = re.sub(r'(changed: [-\w\d\[\]]+)',
r'<font... | 80759da16262d850b45278faede4b60b7aa4a7c6 | 3,647,021 |
def parse_user_date(usr_date: str) -> date:
"""
Parses a user's date input, prompts the user to input useful date data if user's date was
invalid
Args:
usr_date : str, user input of date info. Should be in <yyyy/mm/dd> format
Returns:
valid datetime.date() object
"""
expected_len = len("yyyy/mm/dd")
if usr... | 10becdce6ef4fdc5606ce110b09e102c186dfc04 | 3,647,023 |
def up_sampling_block(x, n_filter, kernel_size, name,
activation='relu', up_size=(2, 2)):
"""Xception block
x => sepconv block -> sepconv block -> sepconv block-> add(Act(x)) =>
"""
x = layers.UpSampling2D(size=up_size, name=name+'up')(x)
if activation:
x = layers.Activ... | 001fdb6475da138bedfdb891af6e657e5ce6160c | 3,647,024 |
def connected_components(graph):
"""
Connected components.
@attention: Indentification of connected components is meaningful only for non-directed graphs.
@type graph: graph
@param graph: Graph.
@rtype: dictionary
@return: Pairing that associates each node to its connected component.
... | 80c5bfc679c1dc274db6a3bf8f8becfa1fc99d4f | 3,647,025 |
import typing
def format_keyvals(
entries: typing.Iterable[typing.Tuple[str, typing.Union[None, str, urwid.Widget]]],
key_format: str = "key",
value_format: str = "text",
indent: int = 0
) -> typing.List[urwid.Columns]:
"""
Format a list of (key, value) tuples.
Args:
... | eb1769a3d7b47b6b4f24f02dcffd3639592c8dc6 | 3,647,026 |
def get_item_workdays(scorecard):
""" Gets the number of days in this period"""
supplier = frappe.get_doc('Supplier', scorecard.supplier)
total_item_days = frappe.db.sql("""
SELECT
SUM(DATEDIFF( %(end_date)s, po_item.schedule_date) * (po_item.qty))
FROM
`tabPurchase Order Item` po_item,
`tabPurchas... | cec620114ae784e5c272d41b6e1028175b466691 | 3,647,027 |
def time_human(x):
""" Gets time as human readable """
# Round time
x = round(x, 2)
for number, unit in [(60, "s"), (60, "min"), (24, "h"), (365, "days")]:
if abs(x) < number:
return f"{x:.2f} {unit}"
x /= number
return f"{x:.2f} years" | 3f7f51ac7454e429fc30da64eed075aaf1f10b5b | 3,647,029 |
from typing import Dict
def transaction_json_to_binary_codec_form(
dictionary: Dict[str, XRPL_VALUE_TYPE]
) -> Dict[str, XRPL_VALUE_TYPE]:
"""
Returns a new dictionary in which the keys have been formatted as CamelCase and
standardized to be serialized by the binary codec.
Args:
dictionar... | 94516b8418fc25d1966d6f5c969f9b4e411100ab | 3,647,030 |
def conv3x3(in_planes, out_planes, stride=1, groups=1):
"""3x3 convolution with padding"""
return nn.Conv1d(in_planes, out_planes, kernel_size=7, stride=stride,
padding=3, bias=False, groups=groups) | 90fa7549a2ba8722edab3712bac4d3af7fb5f2f2 | 3,647,031 |
def limit_sub_bbox(bbox, sub_bbox):
"""
>>> limit_sub_bbox((0, 1, 10, 11), (-1, -1, 9, 8))
(0, 1, 9, 8)
>>> limit_sub_bbox((0, 0, 10, 10), (5, 2, 18, 18))
(5, 2, 10, 10)
"""
minx = max(bbox[0], sub_bbox[0])
miny = max(bbox[1], sub_bbox[1])
maxx = min(bbox[2], sub_bbox[2])
maxy = ... | fa5b7763b30442fba137814ac7b0336528c4540b | 3,647,032 |
def _load_taxa_incorp_list(inFile, config):
"""Loading list of taxa that incorporate isotope.
Parameters
----------
inFile : str
File name of taxon list
config : config object
Returns
-------
{library:[taxon1, ...]}
"""
taxa = {}
with open(inFile, 'rb') as inFH:
... | d614f2be0c5ad4fa61d1d70915428324d7af97b4 | 3,647,033 |
def get_subsections(config: Config) -> t.List[t.Tuple[str, t.Dict]]:
"""Collect parameter subsections from main configuration.
If the `parameters` section contains subsections (e.g. '[parameters.1]',
'[parameters.2]'), collect the subsection key-value pairs. Otherwise,
return an empty dictionary (i.e. ... | 0cb022fb6ae192736186a519c6ffbcf9bcfdf541 | 3,647,034 |
def infer_printed_type(t):
"""Infer the types that should be printed.
The algorithm is as follows:
1. Replace all constant types with None.
2. Apply type-inference on the resulting type.
3. For the first internal type variable that appears, find a constant
whose type contains that variab... | 1ad880fc92db2e64ba6ea81f7481efa99b0bd044 | 3,647,036 |
def bias_variable(shape):
"""
返回指定形状的偏置量
:param shape:
:return:
"""
b = tf.Variable(tf.constant(0.0, shape=shape))
return b | ff2bb945414508d1dfc1db0b028cf1feeebeb6d8 | 3,647,037 |
def drag_eqn(times,g,r):
"""define scenario and integrate"""
param = np.array([ g, r])
hinit = np.array([0.0,0.0]) # initial values (position and velocity, respectively)
h = odeint(deriv, hinit, times, args = (param,))
return h[:,0], h[:,1] | d79150dd894244c11fa882d62da2f33b1173c144 | 3,647,038 |
def virtual_potential_temperature_monc(theta, thref, q_v, q_cl):
"""
Virtual potential temperature.
Derived variable name: th_v_monc
Approximate form as in MONC
Parameters
----------
theta : numpy array or xarray DataArray
Potential Temperature. (K)
thref : numpy array or xarr... | d4c3da0a5f4f2826edce53f610f8ba384845ebb2 | 3,647,039 |
def promote_user(username):
"""Give admin privileges from a normal user."""
user = annotator.credentials.find_one({'username': username})
if user:
if user['admin']:
flash("User {0} is already an administrator".format(username), 'warning')
else:
annotator.credentials.u... | 6a938c341f152991741d35dfd1c693743c07f805 | 3,647,040 |
def slide_number_from_xml_file(filename):
"""
Integer slide number from filename
Assumes /path/to/Slidefile/somekindofSlide36.something
"""
return int(filename[filename.rfind("Slide") + 5:filename.rfind(".")]) | dcfbc322b30a39041ab15b8496f097a5a5329865 | 3,647,041 |
import io
def massivescan(websites):
"""scan multiple websites / urls"""
# scan each website one by one
vulnerables = []
for website in websites:
io.stdout("scanning {}".format(website))
if scanner.scan(website):
io.stdout("SQL injection vulnerability found")
v... | b2be56bf07d00c8839813d66acd337c75b9823ef | 3,647,042 |
import re
def is_strong_pass(password):
"""
Verify the strength of 'password'
Returns a dict indicating the wrong criteria
A password is considered strong if:
8 characters length or more
1 digit or more
1 symbol or more
1 uppercase letter or more
1 lowercase let... | bfd1832951ba3059d8c542fa0b9d708a2416a4d4 | 3,647,043 |
def plot_config(config, settings=None):
"""
plot_config: obj -> obj
---------------------------------------------------------------
Sets the defaults for a custom experiment plot configuration object
from configobj.
The defaults are only set if the setting does not exist (t... | 3b17e97c68bcec31856cb0dc4d7f3db4280a748f | 3,647,044 |
def evaluate_fN(model, NHI):
""" Evaluate an f(N,X) model at a set of NHI values
Parameters
----------
NHI : array
log NHI values
Returns
-------
log_fN : array
f(NHI,X) values
"""
# Evaluate without z dependence
log_fNX = model.__call__(NHI)
return log_fNX | e952a29fdf5864b26dc534140b2ccfb0b59fe24b | 3,647,046 |
def pipe(bill_texts_df):
"""
soup = bs(text, 'html.parser')
raw_text = extractRawText(soup)
clean_text = cleanRawText(raw_text)
metadata = extract_metadata(soup)
"""
bill_texts_df['soup'] = \
bill_texts_df['html'].apply(lambda x: bs(x, 'html.parser'))
bill_texts_df[... | 73a8a850fa15f8ad33f9f823f9b2b4d6f808826b | 3,647,048 |
def _as_static(data, fs):
"""Get data into the Pyglet audio format."""
fs = int(fs)
if data.ndim not in (1, 2):
raise ValueError('Data must have one or two dimensions')
n_ch = data.shape[0] if data.ndim == 2 else 1
audio_format = AudioFormat(channels=n_ch, sample_size=16,
... | b76d4c49107f8b9679e975bd2ce114314289d181 | 3,647,049 |
def preprocess_data(cubes, time_slice: dict = None):
"""Regrid the data to the first cube and optional time-slicing."""
# Increase TEST_REVISION anytime you make changes to this function.
if time_slice:
cubes = [extract_time(cube, **time_slice) for cube in cubes]
first_cube = cubes[0]
# re... | 82e851bda39a4ab7716c7b9cd6038743961d9faf | 3,647,050 |
import base64
def password_to_str(password):
"""
加密
:param password:
:return:
"""
def add_to_16(password):
while len(password) % 16 != 0:
password += '\0'
return str.encode(password) # 返回bytes
key = 'saierwangluo' # 密钥
aes = AES.new(add_to_16(key), AES.M... | 60a6d361d6de3c41d2a27cd24312006920ad1013 | 3,647,051 |
from src.Emails.checker.mailru import checker
import re
import requests
def email_checker_mailru(request: Request, email: str):
"""
This API check email from mail.ru<br>
<pre>
:return: JSON<br>
</pre>
Example:<br>
<br>
<code>
https://server1.majhcc.xyz/api/email/checker/mailru?emai... | 2835439d3c7781efa0c244c881f42a404a8d3cad | 3,647,052 |
from typing import Callable
def guild_only() -> Callable:
"""A :func:`.check` that indicates this command must only be used in a
guild context only. Basically, no private messages are allowed when
using the command.
This check raises a special exception, :exc:`.NoPrivateMessage`
that is inherited... | 40307b2a8672180b2a3532380f11b2701bcf0dd8 | 3,647,053 |
from typing import Union
from typing import List
from typing import Callable
from typing import Any
from typing import Sequence
def make_lvis_metrics(
save_folder=None,
filename_prefix="model_output",
iou_types: Union[str, List[str]] = "bbox",
summarize_to_stdout: bool = True,
evaluator_factory: C... | cbb3df8d8e9daa7976a7be7d6c0588e943aecd5e | 3,647,054 |
def _calculate_cos_loop(graph, threebody_cutoff=4.0):
"""
Calculate the cosine theta of triplets using loops
Args:
graph: List
Returns: a list of cosine theta values
"""
pair_vector = get_pair_vector_from_graph(graph)
_, _, n_sites = tf.unique_with_counts(graph[Index.BOND_ATOM_INDICE... | 3a3283a67c743b2bb7f7a9627e6847dcfc286276 | 3,647,055 |
def load_plugin():
""" Returns plugin available in this module
"""
return HostTestPluginCopyMethod_Firefox() | 26df11d662b3d4f98a294df9c61841c1ab76e8fc | 3,647,056 |
import logging
def temp_url_page(rid):
"""
Temporary page where receipts are stored. The user, which visits it first, get the receipt.
:param rid: (str) receipt id (user is assigned to receipt with this id)
"""
if not user_handler.assign_rid_user(rid, flask.session['username']):
logging.w... | e5ebfe4602e427b4d96cdf1c0298057a5b472052 | 3,647,057 |
def extract_dependencies(content):
"""
Extract the dependencies from the CMake code.
The `find_package()` and `pkg_check_modules` calls must be on a single line
and the first argument must be a literal string for this function to be
able to extract the dependency name.
:param str content: The ... | d9f114695cb3622f4a8dbc23db3a97ed53b164ad | 3,647,058 |
def _block(x, out_channels, name, conv=conv2d, kernel=(3, 3), strides=(2, 2), dilations=(1, 1), update_collection=None,
act=tf.nn.leaky_relu, pooling='avg', padding='SAME', batch_norm=False):
"""Builds the residual blocks used in the discriminator in GAN.
Args:
x: The 4D input vector.
ou... | 21851730e1326b85023d88661da13020c37aa723 | 3,647,059 |
def createLaplaceGaussianKernel(sigma, size):
"""构建高斯拉普拉斯卷积核
Args:
sigma ([float]): 高斯函数的标准差
size ([tuple]): 高斯核的大小,奇数
Returns:
[ndarray]: 高斯拉普拉斯卷积核
"""
H, W = size
r, c = np.mgrid[0:H:1, 0:W:1]
r = r - (H - 1) / 2
c = c - (W - 1) / 2
sigma2 = pow(sigma, 2.... | aae788ba324a243691391a61b02e6a5f1b358c4e | 3,647,060 |
import warnings
def mean_bias_removal(hindcast, alignment, cross_validate=True, **metric_kwargs):
"""Calc and remove bias from py:class:`~climpred.classes.HindcastEnsemble`.
Args:
hindcast (HindcastEnsemble): hindcast.
alignment (str): which inits or verification times should be aligned?
... | 01155462155d9f718fa2a12053297903d47b6661 | 3,647,063 |
def index():
"""
vista principal
"""
return "<i>API RestFull PARCES Version 0.1</i>" | 8b8b963f75395df665bcf0283528c9641b3ea20e | 3,647,065 |
def tag(dicts, key, value):
"""Adds the key value to each dict in the sequence"""
for d in dicts:
d[key] = value
return dicts | ffcfda13845fb8b522e50211184104a11da50398 | 3,647,066 |
def openpairshelf(filename, flag='c', protocol=None, writeback=False):
"""Returns a ProteinPairDB object, with similar functionality to shelve.open()"""
return ProteinPairDB(filename, flag, protocol, writeback) | 886a474aa67f729461995fe5427d5f68b9db9fe0 | 3,647,067 |
def createUser(emailid, password, contact_no, firstname, lastname, category, address, description, company_url, image_url, con=None, cur=None, db=None):
"""
Tries to create a new user with the given data.
Returns:
- dict: dict object containing all user data, if query was successfull
- Fals... | 05dc71db991e126d43fd9ddd044f1cf65f3e97c1 | 3,647,068 |
async def discordView(cls:"PhaazebotWeb", WebRequest:ExtendedRequest) -> Response:
"""
Default url: /discord/view/{guild_id:\d+}
"""
PhaazeDiscord:"PhaazebotDiscord" = cls.BASE.Discord
if not PhaazeDiscord:
return await cls.Tree.errors.notAllowed(cls, WebRequest, msg="Discord module is not active")
guild_id:st... | 76f222bdd5164c23c95803d47fc1af48d89192e2 | 3,647,070 |
def update_max_braking_decel(vehicle, mbd):
"""
Updates the max braking decel of the vehicle
:param vehicle: vehicle
:param mbd: new max braking decel
:type vehicle: VehicleProfile
:return: Updated vehicle
"""
return vehicle.update_max_braking_decel(mbd) | dea3bf14ca14363246539fd81cf853cd2c0ad980 | 3,647,071 |
from scipy.spatial.distance import pdist, squareform
def get_outlier_removal_mask(xcoords, ycoords, nth_neighbor=10, quantile=.9):
"""
Parameters
----------
xcoords :
ycoords :
nth_neighbor :
(Default value = 10)
quantile :
(Default value = .9)
Ret... | 8d01088401405613696ced2dbbd9c03940417f10 | 3,647,072 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.