content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def weave(devicePairs):
"""
"""
routers = [x[0] for x in devicePairs if x[0][1] == "router.PNG"]
selected = []
for devicePair in devicePairs:
starterDevice = devicePair[0]
if starterDevice[1] == "router.PNG":
continue
starterPosition = maths.getCenter(t... | 6e312f2c89007e67efdb23d93c103e3f7583d48a | 1,487 |
def change_image_ani(image: _Surface,
name: _Optional[str] = None,
id_: _Optional[int] = None) -> _TextureAni:
"""
change_image_ani(image, name=None, id_None)
Type: function
Description: returns a TextureAni that simply changes the image of
an AniEleme... | ff68e741937512d70ad714e54df037940154467f | 1,488 |
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError as err:
raise ImportErro... | 06a014f531944eb0f5d428e5f2880a1e91de797c | 1,489 |
def read_u16(f):
"""Reads a two byte unsigned value from the file object f.
"""
temp = f.read(2)
if not temp:
raise EOFError("EOF")
return int.from_bytes(temp, byteorder='little', signed=False) | 03478ce0fd4076ca3a0c4ea2f687cca254ba7052 | 1,490 |
def new_figure_manager_given_figure(num, figure):
"""
Create a new figure manager instance for the given figure.
"""
canvas = FigureCanvasQTAgg(figure)
return FigureManagerQT(canvas, num) | 2862a3a2c456fcfe5461f011a28bdf5ec94971a8 | 1,491 |
def process_image(sample, settings, mode, color_jitter, rotate):
""" process_image """
mean = settings.image_mean
std = settings.image_std
crop_size = settings.crop_size
img_path = sample[0]
img = cv2.imread(img_path)
if mode == 'train':
if rotate:
img = rotate_image(i... | 230991f4078c9963731355b276a6e351f7bcbab9 | 1,492 |
def convert_pressures(a, from_units, to_units):
"""Converts values in numpy array (or a scalar) from one pressure unit to another, in situ if array.
arguments:
a (numpy float array, or float): array of pressure values to undergo unit conversion in situ, or a scalar
from_units (string): the units ... | d25ca383fe0cfaf6e756958ff99aebf2b06e13a9 | 1,494 |
def amovie(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#amovie"""
return filter(stream, amovie.__name__, *args, **kwargs) | 60daca8722bb42b34231a82dd3c9175108af8f9b | 1,495 |
import numpy
def kutta_condition(A_source, B_vortex):
"""
Builds the Kutta condition array.
Parameters
----------
A_source: 2D Numpy array of floats
Source contribution matrix for the normal velocity.
B_vortex: 2D Numpy array of floats
Vortex contribution matrix for the no... | 0009018c39c21f1bc3b98745ea7a475f0a7e6fe7 | 1,496 |
def absorption_sinogram(p, anglelist):
"""Generates the absorption sinogram for absorption by the full
elemental content of the Phantom2d object.
Parameters
----------
p : Phantom2d object
anglelist : list of float
Ordered list of sinogram projection angles in degrees.
Returns
... | 37f5048b9207221387c2410e2bb0be20bafc8dcf | 1,497 |
def trace_feature_vector_from_nodes(embeddings, traces, dimension):
"""
Computes average feature vector for each trace
Parameters
-----------------------
embeddings,
Text-based model containing the computed encodings
traces: List,
List of traces treated as sentences by the model... | 93efdf6da293bd6af61c1c77e8b19c76c6b71193 | 1,498 |
def jitter_rotate(drawing, sigma=0.2):
"""
Rotate an entire drawing about 0,0 by a random gaussian.
"""
rotation = np.random.randn(1) * sigma
matrix = create_rotation_matrix(rotation)
return [np.dot(stroke, matrix).squeeze() for stroke in drawing] | 058709f6a84e99fbd8899e3e6c4aed09b7c0ad6e | 1,499 |
def is_modified(filename: str) -> bool:
"""
Given a filename return if it has been modified
"""
global new_hashes
global old_hashes
if filename in old_hashes.keys():
if old_hashes[filename] == new_hashes[filename]:
return False
return True | f5f191a9fc714d0431d8c464630ab6b0c95f13dd | 1,500 |
def _is_url_without_path_query_or_fragment(url_parts):
"""
Determines if a URL has a blank path, query string and fragment.
:param url_parts: A URL.
:type url_parts: :class:`urlparse.ParseResult`
"""
return url_parts.path.strip('/') in ['', 'search'] and url_parts.query == '' \
and ... | 4bad1f230adfa77df019519db276a181d57682dd | 1,501 |
import math
def wgs84_distance(lat1, lon1, lat2, lon2):
"""Distance (in meters) between two points in WGS84 coord system."""
dLat = math.radians(lat2 - lat1)
dLon = math.radians(lon2 - lon1)
a = (math.sin(dLat / 2) * math.sin(dLat / 2) +
math.cos(math.radians(lat1)) * math.cos(math.radians(la... | b700c218c172843922762b741f37b25996fdc047 | 1,503 |
def optimize_acq_func(acq_func: AcquisitionFunction, bounds=None, options=None):
"""Optimizes the acquisition function"""
# optimize
candidates, _ = optimize_acqf(
acq_function=acq_func,
bounds=bounds,
q=1,
num_restarts=20,
raw_samples=512,
options=options,
... | 9aef150a89f646f8f65efe656a2987a7afe9f917 | 1,504 |
import json
def _recover_distributor(lb_id):
"""Get cached Distributor object or generate from ovs external_ids
{
'dist-lb-id': lb_id,
'dist-vip': vip,
'dist-size': size,
'dist-status': status,
'dist-mac': mac,
'dist-hash-fields': field-list,
'dist-ofpor... | a97cb4843515cf83314044af72a91b344d475a2d | 1,505 |
def setup_dispatcher(dp):
"""
Adding handlers for events from Telegram
"""
# commands
dp.add_handler(CommandHandler("start", commands.command_start))
dp.add_handler(CommandHandler("help", commands.command_help))
# admin & mod commands
dp.add_handler(CommandHandler("admin", admin.ad... | 1b37f48a8e3f9cfe451edb321b20dbde88853a84 | 1,507 |
import re
import ast
def get_version():
"""Gets the current version"""
_version_re = re.compile(r"__VERSION__\s+=\s+(.*)")
with open("leaked/__init__.py", "rb") as init_file:
version = str(ast.literal_eval(_version_re.search(
init_file.read().decode("utf-8")).group(1)))
return vers... | a6c5a94ca3cb728af38075ac98105be6d82dd3cf | 1,508 |
import re
def dir_keys(path):
"""A function to take a path, and return a list of all the numbers in the path. This is
mainly used for sorting
by the parameters they contain"""
regex = '[-+]?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?' # matching any floating point
m = re.findall(regex, path)
... | c2c32772771c9bae23a1fcc949a509eaaf36d602 | 1,509 |
def generate_data(n=5, T=1000, random_state=None, initial_data=None):
"""
Parameter
---------
n : int
number of variables
T : int
number of samples
random_state : int
seed for np.random.seed
initial_data : list of np.ndarray
dictionary of initial datas
"""... | 5e5c09de44f6db1ba28cd953d6549bb8d31aa3ec | 1,510 |
from typing import List
import re
def _get_paragraphs(paragraphs: List[str]) -> List[str]:
"""
Returns the paragraphs of an article's body, annotated with HTML tags.
Args:
paragraphs (:obj:`List[str]`):
List of strings denoting paragraphs.
Returns:
:obj:`List[str]`:
... | a4030efd2145fb15435912a1e08354cabba209e8 | 1,511 |
from scipy.stats import gaussian_kde
def calculate_kde(
ascending: bool = True,
evaluate: bool = False,
input_ts="-",
columns=None,
start_date=None,
end_date=None,
clean=False,
skiprows=None,
index_type="datetime",
source_units=None,
target_units=None,
names=None,
):
... | d654fe75030b8c99361096650c71835aad2d6b3a | 1,512 |
def EPmulk(a, da, k):
"""
C = A * k
"""
return a * k, np.absolute(da * k) | 4fb2b7ff28db1ff13fa2aa0c68f5d0c25e9ba3d9 | 1,513 |
def decrypt_location(location):
"""Decrypts the `location` field in Xiami responses to URL."""
if not location:
return None
rows, url = int(location[:1]), location[1:]
urllen = len(url)
cols_base = urllen // rows # basic column count
rows_ex = urllen % rows # count of rows that ha... | 2fc3062df2786550e2b4839fae4aee5668963cc1 | 1,515 |
def sqd_yinfast(samples):
""" compute approximate sum of squared difference
Using complex convolution (fast, cost o(n*log(n)) )"""
# yin_t(tau) = (r_t(0) + r_(t+tau)(0)) - 2r_t(tau)
B = len(samples)
W = B//2
yin = np.zeros(W)
sqdiff = np.zeros(W)
kernel = np.zeros(B)
# compute r_(t+... | c97e130960336074f6b0c30590ab8a044b8d63e5 | 1,516 |
def get_colours_extend(graph_size, start_set, end_set, source, target, reachable=None):
"""
Get colours for nodes including source and target nodes.
Blue nodes are those in the source set.
Orange nodes are those in the start set, not in the source set.
Green nodes are those reachable from the sourc... | d366ed6c4c387d0b4de4440d34d358d5a142661a | 1,517 |
def suspend_circuit():
"""
Suspends the circuits for some seconds, allowing the user to exit the house without playing the song.
"""
circuit.suspend()
return render_template("suspend.html", seconds=EXIT_HOUSE_TIMER, name=get_guest_name()) | 2336207150163ecd302dda6c56758a5405152aec | 1,518 |
def get_scalar_data_from_path(udatapath, name='pressure', x0=0, x1=None, y0=0, y1=None, z0=0, z1=None,
t0=0, t1=None, inc=1, frame=None, return_xy=False, verbose=True,
slicez=None, crop=None, mode='r',
reverse_x=False, reverse_y=False, reverse_z=Fa... | ef99d0e3dcd8a15b5c7759dac39fb3b7fbe09632 | 1,519 |
from statistics import mean
def create_transformed_df(old_df, elem_list, features_list):
"""elem_list should be in type list"""
new_dict = {}
for index, elems in zip(old_df.index, old_df[elem_list]):
for elem in elems:
if elem in new_dict.keys():
for j, feature in enume... | c5d825f446839d9b6d921bf064bb07c102b82905 | 1,520 |
def sem_id_semester_get(semester, obs_id):
"""
retrieves all the sem_id associated with an observer for the semester.
:param semester: semester id
:type semester: str
:param obs_id: observer id
:type obs_id: int
:rtype: List[str]
"""
semester_list = []
sem_ids = utils.get_prop... | d15b36ccbe1e7a6d2f2cb5016419e259df922881 | 1,521 |
def getLabels (dataMatrix, classOfInterest):
"""
Gets labels on a per class basis that will inputted to the randomForest function
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the se... | bf7bcfc4afcd16deedbfcf27c9e1eb1a5dfa603a | 1,522 |
def load_file(file_location):
"""
Opens a given file and returns its contents.
:param str file_location: The absolute path to the file
:rtype: str
:return: The contents of the file
"""
with open(file_location, 'r') as file_contents:
contents = file_contents.read()
return conte... | 61b78432cffa4c22adc9af31bbad63bf8777737b | 1,523 |
def create_bam(data, args):
"""
aligner and conversion to BAM file
"""
workdir = safe_makedir("align")
sample = data['name']
# workdir = op.join("align", sample)
data['final_bam'] = _align(data['trimmed'], sample, op.abspath(workdir),
args.index, args.is_direct... | 81e77af7317f29277d42a37e46f0e5aa719cab3c | 1,524 |
def calculateStorageLocationsDistance(D_loc: pd.DataFrame, input_loccodex: float,
input_loccodey: float, output_loccodex: float,
output_loccodey: float) -> pd.DataFrame:
"""
calculate the sum of the rectangular distances from
Input ... | 3432036119007cb1f33f69106cae8c2cf28d697b | 1,525 |
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words) | 2b6a293bc5faba31428f66f214e1991dd9878027 | 1,526 |
import codecs
def pickle(obj):
""" Creates a serialization of the provided object
Serialization is done by :mod:`pickle` module. If :mod:`cPickle` package is
available, that package will be used instead, yielding a gain in speed.
Parameters
----------
obj: :obj:`obj`
Object to be ser... | 3a36e7d3c1f0fd31a417df21701eb150e3c611a8 | 1,527 |
def calc_E_E_AP_d_t(n_p):
"""1 時間当たりの家電の消費電力量
Args:
n_p(float): 仮想居住人数 仮想居住人数
Returns:
ndarray: 1 時間当たりの家電の消費電力量
"""
schedule = load_schedule()
schedule_app = get_schedule_app(schedule)
if 1 <= n_p and n_p <= 2:
E_E_AP_1_d_t = get_E_E_AP_p_d_t(1, schedule_app)
... | 645052eaedf7cc93d4b171f710d0a29e119fe7cf | 1,528 |
from typing import List
import torch
def Squeeze_forward(op: Operation, values: List[torch.Tensor], ctx: TorchBackendContext = None, **kwargs) -> torch.Tensor:
"""
Remove single-dimensional entries from the shape of a tensor.
Takes an input axes with a list of axes to squeeze.
If axes is not provide... | f20c5565aafde993e011efc4e037d6a253a79d30 | 1,529 |
import functools
def build_dataset(instruction_dicts,
dataset_from_file_fn,
shuffle_files=False,
parallel_reads=64):
"""Constructs a `tf.data.Dataset` from TFRecord files.
Args:
instruction_dicts: `list` of {'filepath':, 'mask':, 'offset_mask':}
con... | 6918db594b74d75d5fbbebf70b0f2811366c20b5 | 1,531 |
def _SetRunOptionInRequest(run_option, run_schedule, request, messages):
"""Returns request with the run option set."""
if run_option == 'manual':
arg_utils.SetFieldInMessage(
request,
'googleCloudDatacatalogV1alpha3Crawler.config.adHocRun',
messages.GoogleCloudDatacatalogV1alpha3AdhocRu... | 9f93aaa6b9ec3ba9350c10b914439b16ec7c19a9 | 1,532 |
from unittest.mock import patch
def test_rank_closest():
"""test if phoneme-inventory is ranked correctly
according to feature vectore distance to a given phoneme"""
# set up custom class, create instance of it
class EtymMonkeyrank_closest:
def __init__(self):
self.phoneme_invento... | 6ad838f0961fb311ce68402b87f68960a1ce816f | 1,533 |
from datetime import datetime
def create_virtual_machine(module, azure):
"""
Create new virtual machine
module : AnsibleModule object
azure: authenticated azure ServiceManagementService object
Returns:
True if a new virtual machine was created, false otherwise
"""
name = module.p... | 88006dec9f8e00307f4862e2cdab203867f15558 | 1,534 |
def calcCumulOverlap(modes1, modes2, array=False):
"""Returns cumulative overlap of modes in *modes2* with those in *modes1*.
Returns a number of *modes1* contains a single :class:`.Mode` or a
:class:`.Vector` instance. If *modes1* contains multiple modes, returns an
array. Elements of the array corresp... | 6ce8c85b778ca06e1f26f9d66151656b30a4837a | 1,535 |
import multiprocessing
import tqdm
def apply_ntimes(func, n, args, verbose=True, timeout=None):
"""
Applies `n` times the function `func` on `args` (useful if, eg, `func` is partly random).
Parameters
----------
func : function
func must be pickable, see https://docs.python.org/2/library/p... | 91aca94c49b7cf74ceaf5f093f21853bbd310df1 | 1,536 |
def travel_time_without_Rebalancing(tnet, i, j, exo=0):
"""
evalute the travel time function for edge i->j
Parameters
----------
tnet: transportation network object
i: starting node of edge
j: ending node of edge
Returns
-------
float
"""
return sum(
[tnet.fcoe... | 00ae58356d1a808d34a559267134cb52fc8b0dc5 | 1,537 |
def twistless(*args):
"""
Wraps the entry point function, this function should setup and run a
twisted reactor.
A twisted task will be created to constantly schedule other stackless
tasklets as often as the timesched argument.
"""
def _twistless(func):
"""
Wrap the given fun... | 75f51549bde9e07316e9dcb31c95bdf81a3cd793 | 1,538 |
import numpy
import math
def enhance_with_function(images, labels, ratio, enhance_func):
"""
:param images:
:param labels:
:param ratio: the ratio of max input class. for example, highest sample count is 1000, ratio is 3, the result
will be around 1000 * 3 * how_many_classes
:param enhance_fun... | d16b7d3726902653bce94c11dba808da1ee88d09 | 1,539 |
async def port_create(
request: Request,
server_id: int,
port: PortCreate,
db=Depends(get_db),
user=Depends(get_current_active_admin),
):
"""
Create a new port on server
"""
db_port = create_port(db, server_id, port)
trigger_tc(db_port)
return db_port | 28e747b9af9ed04de911b1fc30653539e9e108cb | 1,540 |
def rectangle_area(base, height):
"""Returns the area of a rectangle"""
base = float(base)
height = float(height)
if (base < 0.0 or height < 0.0):
raise ValueError('Negative numbers are not allowed')
return base * height | 6dc1ea897cdeba1eb84813cefdab659abf5197ea | 1,542 |
def pipe(*args, **kwargs):
"""A processor that replaces the text of a field of an item.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'rule'.
rule (di... | 29be8fad7df2eb674633abd160b818ed4d6697b2 | 1,543 |
def adjoint(g):
"""Return the adjoint of a rigid body transformation g."""
adg = np.zeros((6, 6))
R_part, p = g[:3, :3], g[:3, 3]
pR = skew(p) @ R_part
adg[:3, :3] = R_part
adg[-3:, -3:] = R_part
adg[:3, -3:] = pR
return adg | 6ef82620aa6db984956c7a858ebf0e8715e1e9df | 1,544 |
def dmp_rr_yun0_sqf_list(f, u, K):
"""Compute square-free decomposition of ``f`` in zero-characteristic ring ``K``.
References
==========
* :cite:`LeeM2013factor`, page 8
"""
if dmp_ground_p(f, None, u):
return []
result, count = [], 1
qs = [dmp_diff_in(f, 1, i, u, K) for i i... | cf917fb0f0cfd505328c07a09fe07cafd8872d7e | 1,545 |
def angle2trig(theta):
"""Convert angle to a reportlab ready tuple.
Arguments:
- theta - Angle in degrees, counter clockwise from horizontal
Returns a representation of the passed angle in a format suitable
for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta),
cos(theta) tuple)
... | b4ad079b5b9fb889b26eec37c1d14ae97a34be50 | 1,548 |
def get_state_z0_pure_state_vector() -> np.ndarray:
"""Returns the pure state vector for :math:`|0\\rangle`.
Returns
-------
np.ndarray
the pure state vector.
"""
vec = np.array([1, 0], dtype=np.complex128)
return vec | 53a7485572ea8fed8fcb8155923692050092c881 | 1,549 |
def HSV_to_CMYKratio(hsv):
"""Converts HSV color space to CMYK (ratio representation)"""
rgb = HSV_to_RGB(hsv)
return RGB_to_CMYKratio(rgb) | c6268c86dc425d7f5b386fd9dbb56e5299d9573b | 1,550 |
def delete_single_culture(user_id, culture_id):
"""Delete a culture."""
try:
culture = Culture.query.filter_by(user_id=user_id).filter_by(culture_id=culture_id).first()
if not culture:
response_object = {
'status': 'fail',
'message': f'{culture_id} doe... | e96ab6e653b2d191e1c0977ee9dace114c6056ce | 1,551 |
def create_atomic_chunk(im, chunk_coord, aff_dtype=np.float32, verbose=True):
""" Creates single atomic chunk
:param im: IngestionManager
:param chunk_coord: np.ndarray
array of three ints
:param aff_dtype: np.dtype
np.float64 or np.float32
:param verbose: bool
:return:
"""
... | 6096e22b35a800782f394a45b6307aec23c71d57 | 1,552 |
def add_adult(request):
"""
Add a new adult record
:param request:
:return:
"""
args = dict()
app = AppUtil.get_by_user(user=request.user)
if request.method == 'POST':
form = AddAdultForm(request.POST)
if form.is_valid():
adult = form.save(commit=False)
... | 8998601a05acd875fb65008fb85bbcdac7ad418d | 1,553 |
import re
def get_layers(model, filter_regexp):
"""
Filters out the layers according to a regexp. Note that
we omit biases.
Args:
- model: a nn.Module
- filter_regexp: a regexp to filter the layers to keep
according to their name in model.named_parameters().
For in... | d34da2bd7bfcf9827846f4aafc74d8c94ceb0d31 | 1,555 |
from typing import Union
def decrypt(data: bytes,
password: Union[str, bytes]) -> bytes:
"""
decrypt data
:param data: encrypted data
:param password: password
:return: plain data
"""
__data = gzip_decompress(data[4:]) if data.startswith(b'moca') else data
iv, cipher = __da... | c6228e10c1498e734a42039071aa6d88356eef84 | 1,556 |
def stream_from_url(*args, **kwargs):
"""
Save the resource as a file on disk iteratively by first asking
for the 'content-length' header entry and downloading in chunks.
By default we will retry if an HTTP error arises.
By default we will uncompress a downloaded file if it is zipped.
"""
# ... | 2ee598ac7cb19a1f884ad7faad4cec38a5f93c32 | 1,557 |
def modulo_3(lhs, ctx):
"""Element ǒ
(num) -> a % 3
(str) -> a split into chunks of size 2
"""
return {
(NUMBER_TYPE): lambda: lhs % 3,
(str): lambda: [lhs[i : i + 2] for i in range(0, len(lhs), 2)],
}.get(vy_type(lhs), lambda: vectorise(modulo_3, lhs, ctx=ctx))() | daa2775727af48d76076e54095a2503243368dc1 | 1,558 |
def geolocalizarCiudades(lista_ciudades: list):
"""Para una lista con nombres de ciudades devuelve una fila de DataFrame.
Parámetros
----------
lista_ciudades : list
Lista de nombres de ciudades.
Devuelve
-------
df_Fila: pandas.DataFrame
Fila de un DataFrame que incluye el... | 14d26dba3a2fcef1334e7d13e60b01ff3d3f9ef5 | 1,560 |
def HandleConvPaddingModes(x, padding, kernel_shape, strides):
"""Returns an updated tensor and padding type for REFLECT and SYMMETRIC.
Args:
x: A 4D tensor with shape [batch_size, height, width, depth].
padding: Padding mode (SAME, VALID, REFLECT, or SYMMETRIC).
kernel_shape: Shape of convolution kern... | def8d35429e568096dbb5410723c1cf550890707 | 1,561 |
import uuid
def uuid1_():
"""用于生成GUID"""
return str(uuid.uuid1()) | 8b1bf00c2c76429499a4300cc7f75fd075a0bf1c | 1,562 |
def default_if_none(default):
"""Implements the rule: default if v is None else v"""
return default_if_true(lambda v: v is None, default) | 13cf841c09e14074c38a7ae2b5fac649518e783d | 1,563 |
import asyncio
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
"""Unload Unifi Protect config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for componen... | 8ef56a9029adb33853b90a9a9ba8e35e67a2d79a | 1,565 |
def auc(y, z, round=True):
"""Compute area under the ROC curve."""
if round:
y = y.round()
if len(y) == 0 or len(np.unique(y)) < 2:
return np.nan
return skm.roc_auc_score(y, z) | 895e8f37829903ee7e79012a54ecc318401ae4c6 | 1,567 |
def upperLeftOrigin( largeSize, smallSize ):
"""
The upper left coordinate (tuple) of a small rectangle in a larger rectangle (centered)
"""
origin = tuple( map( lambda x: int( ( (x[0]-x[1])/2 ) ), zip( largeSize, smallSize )) )
return origin | bda31fc5eb021f40a62b00949ced940ef171005f | 1,569 |
from re import S
import typing
import importlib
def from_ext(ext: str) -> S:
"""Get a SignedObject by file extension."""
object_types: typing.List[S] = [RpkiGhostbusters,
RpkiManifest,
RouteOriginAttestation]
entry_point_name = "rpkim... | 5edeb91022b2d97239038e99d565a6879532eeb0 | 1,571 |
def plot_audio(audio,time,ResultPath,title):
"""Plot and save an audio file amplitude over time"""
plt.figure()
plt.plot(time,audio, linewidth=0.01)
plt.ylabel("Amplitude")
plt.xlabel("Time (s)")
plt.title(title)
pathname=ResultPath + title
plt.savefig(pathname)
plt.show()
return... | faf8e6c38e65d6a1caebfdfd0335a92ed570d2b3 | 1,572 |
def dataSet():
"""
测试数据集
"""
x = [np.array([[1], [2], [3]]),
np.array([[2], [3], [4]])]
d = np.array([[1], [2]])
return x, d | 91b0dfb28ec81a4ca392aafd0c06f81319d5db38 | 1,573 |
def config():
"""
Get the OpenAPI Document configuration
:returns: OpenAPI configuration YAML dict
"""
with open(get_test_file_path('pygeoapi-test-openapi-config.yml')) as config_file: # noqa
return yaml_load(config_file) | 23519be12e1f6d9d79210de325a726df16946507 | 1,574 |
def convert_broadcast_lesser(node, **kwargs):
"""Map MXNet's broadcast_lesser operator attributes to onnx's Less operator
and return the created node.
"""
return create_basic_op_node('Less', node, kwargs) | 2ef5223ad38b24791d530c0c609859160b9a4c70 | 1,575 |
def histogram2d(x, y, bins_x, bins_y):
"""Histogram 2d between two continuous row vectors.
Parameters
----------
x : array_like
Vector array of shape (N,) and of type np.float32
y : array_like
Vector array of shape (N,) and of type np.float32
bins_x, bins_y : int64
Numbe... | 1d7f88eb0ab25092a826a8f1157895e02608aaba | 1,577 |
from typing import Any
from typing import Tuple
def xy2latlong(x: float, y: float, ds: Any) -> Tuple[float, float]:
"""Return lat long coordinate by x, y
>>> import gdal
>>> path = "../../../tests/data/raster_for_test.tif"
>>> ds = gdal.Open(path)
>>> xy2latlong(3715171, 2909857, ds)
(1.70362... | 01f3a1e2d5c8e842db6668488b0a3d9d9b432295 | 1,578 |
def relative_date(r='12m', end_date='today', date_format='%Y-%m-%d',
as_string=False, unixtimestamp=False):
"""
Relative Date function
Calculates a datetime from a given end date and a relative reference.
INPUT:
r - relative date reference as '-12d' accepts d, w, m or... | 720f24ce1fafa2b77979c924a9c20b1d6cc86c03 | 1,579 |
from re import T
def get_iexist_vdw_bond(ipt):
"""
check if a given mol pair contain any vdw bond, which exists
in the query mol. Note that input mol pairs must have cc=0.
"""
obj, mi, mj = ipt
iok = F
if np.any( [ set(b) <= set(mi.iasq+mj.iasq) for b in obj.ncbs ] ):
iok = T
r... | 81af4c03ea988412cb11be3f962e40239cfbadcf | 1,580 |
def load_data(messages_filepath, categories_filepath):
"""Loads messages and categories data and creates a merged dataframe
Args:
messages_filepath (str): Path to the messages file
categories_filepath (str): Path to the categories file
Returns:
(pd.DataFrame): A messages and catego... | 1f7308c2f51b587b3b27c35f680225c0c78c85b0 | 1,582 |
def is_square_inside(row, col, rows, cols):
"""Check if row and col is square inside grid having rows and cols."""
return row not in (0, rows - 1) and col not in (0, cols - 1) | f0cdcbc6d9bee6a41fd0cc84b16ffaf0638a522c | 1,583 |
def reshapeLabel(label):
"""
Reshape 1-D [0,1,...] to 2-D [[1,-1],[-1,1],...].
"""
n = label.size(0)
y = FloatTensor(n, 2)
y[:, 0] = 2 * (0.5 - label)
y[:, 1] = - y[:, 0]
return y.long() | 77716413deb3263b23a6ca8e684274fa67855375 | 1,584 |
import torch
def _coo_scipy2torch(adj, coalesce=True, use_cuda=False):
"""
convert a scipy sparse COO matrix to torch
"""
values = adj.data
indices = np.vstack((adj.row, adj.col))
i = torch.LongTensor(indices)
v = torch.FloatTensor(values)
ans = torch.sparse.FloatTensor(i, v, torch.Siz... | 27d9db560dc60ec31ec7f152952db201c4e6aafb | 1,585 |
def do_add_application_type(request):
"""定义
dict_class=models.CharField(u"字典类别",max_length=255)
dict_type=models.CharField(u"字典类型",max_length=255)
dict_name=models.CharField(u"字典名称",max_length=255)
dict_value=models.CharField(u"字典值",max_length=255)
dict_status=models.IntegerField(u"字典状态")
di... | 713a387215132ddb435592cd834537346cfcf024 | 1,588 |
def exponential_decay_function(distance: np.ndarray) -> np.ndarray:
"""Calculate exponential discount factor for action interaction weight matrix.
Parameters
-----------
distance: array-like, shape (len_list, )
Distance between two slots.
"""
if not isinstance(distance, np.ndarray) or ... | ac434d098274e5119418a2c18641dadcd1ca8dca | 1,589 |
def line_length(line, ellipsoid='WGS-84',shipping=True):
"""Length of a line in meters, given in geographic coordinates
Adapted from https://gis.stackexchange.com/questions/4022/looking-for-a-pythonic-way-to-calculate-the-length-of-a-wkt-linestring#answer-115285
Arguments:
line {Shapely LineString... | bb80b01729f589c0645606581f4a1fc53836e037 | 1,590 |
def corr2_coeff(x, y):
"""A magic function for computing correlation between matrices and arrays.
This code is 640x+ faster on large dataset compared to np.corrcoef().
------------------------------------------------------------------
author: Divakar (https://stackoverflow.com/users/3293881/di... | 5834294b9a67efdeecfde4546a805d1d136b8796 | 1,591 |
from typing import Optional
def get_database_url(track: str) -> Optional[URL]:
"""
Get the database URL based on the environment
How the database URL is selected:
1. If a predefined URL for the track is set, use that
2. If no predefined URL is set, generate one based on the preferred database typ... | 6a3ccd8bacff1f78bbd21728ca45dd7ae74be7d8 | 1,592 |
import unittest
def build_suite():
"""A function."""
#suite = unittest.TestSuite()
#suite.addTest(WidgetTestCase('test_default_size'))
#suite.addTest(WidgetTestCase('test_resize'))
suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
return suite | 2984f7a149d224dfc5d0a17b6c8eaed139234c6b | 1,593 |
def get_quantile(data, percentage, **kwargs):
"""
Assuming the dataset is loaded as type `np.array`, and has shape
(num_samples, num_features).
:param data: Provided dataset, assume each row is a data sample and \
each column is one feature.
:type data: `np.ndarray`
:param percentage: Quan... | ddb02aff1e441696a9a2813d772580c5fdef0ddb | 1,594 |
def clean_repository_clone_url( repository_clone_url ):
"""Return a URL that can be used to clone a tool shed repository, eliminating the protocol and user if either exists."""
if repository_clone_url.find( '@' ) > 0:
# We have an url that includes an authenticated user, something like:
# http:/... | c1d274e907d73aceaa5f1e2c52336edf1638cd8a | 1,595 |
import torch
def calculate_uncertainty_ins_seg(logits, classes):
"""
We estimate uncerainty as L1 distance between 0.0 and the logit prediction in 'logits' for the
foreground class in `classes`.
Args:
logits (Tensor): A tensor of shape (R, C, ...) or (R, 1, ...) for class-specific or
... | 794d614d63ca5df06f00ce706f6ca39ae85cfdff | 1,596 |
import torch
def euclidean_distance(x, y):
"""
Compute Euclidean distance between two Variable matrices.
---
param:
x: PyTorch Variable with shape (m, d)
y: PyTorch Variable with shape (n, d)
return:
distance: PyTorch Variable with shape (m, n)
"""
m, n = x.size(0),... | 03c32aff1d0c31b7d713851e1885d2aa492dad57 | 1,597 |
def gsettings_set(schema, path, key, value):
"""Set value of gsettings schema"""
if path is None:
gsettings = Gio.Settings.new(schema)
else:
gsettings = Gio.Settings.new_with_path(schema, path)
if isinstance(value, list):
return gsettings.set_strv(key, value)
if isinstance(va... | 29cddb07c10099bc70c1e823d3ffd1b125cf889a | 1,598 |
def initialize_parameters_deep(layer_dims):
"""
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in our network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
Wl -- weight matrix of shape (... | 374a684dfe54aa0d65ea8f25b61f72a4fc21144e | 1,599 |
def get_nblocks_ntraces(f,nblocks,ntraces,pts,nbheaders,dt,read_blockhead):
"""
Read n blocks from a Varian binary file which may have multiple traces
per block.
Parameters:
* f File object of Varian binary file to read from.
* nblocks Number of blocks to read.
* ... | b99ddcf842dbc02e1afb9067e198e7e241d1a8c0 | 1,600 |
def calcMedian(list_o_tuples):
"""Given a list of tuples (A, B), where A = category, and B = counts,
returns A that represents the median count value"""
#calc total
ct = 0
for (a, b) in list_o_tuples:
ct += float(b)
med = ct / 2
#find A
ct = 0
for (i, (a, b)) in enumerate(li... | f09a9ac4b1e7a84982bf6b33e4f43e1b2c9f64f6 | 1,601 |
def add(n1, n2):
"""Adds the 2 given numbers"""
return n1 + n2 | ca670819dab8230e355e1b236d9cc74ed0b3b868 | 1,602 |
def kwarg_any(kwarg_functions):
"""Resolve kwarg predicates with short-circuit evaluation. This optimization
technique means we do not have to evaluate every predicate if one is already
true.
"""
return any(kwarg_function() for kwarg_function in kwarg_functions) | 3303e1a871bb41920ba0f41e4928e05b6d876c1e | 1,603 |
def _behler_parrinello_cutoff_fn(dr: Array,
cutoff_distance: float=8.0) -> Array:
"""Function of pairwise distance that smoothly goes to zero at the cutoff."""
# Also returns zero if the pairwise distance is zero,
# to prevent a particle from interacting with itself.
return jnp.... | 707f3521edf1be13c6f3c830404f851a8b606613 | 1,604 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.