content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def siblings_list():
"""
Shows child element iteration
"""
o = untangle.parse(
"""
<root>
<child name="child1"/>
<child name="child2"/>
<child name="child3"/>
</root>
"""
)
return ",".join([child["name"] for child in o.root.chil... | 06737cb187e18c9fa8b9dc9164720e68f5fd2c36 | 8,738 |
def combine_histogram(old_hist, arr):
""" Collect layer histogram for arr and combine it with old histogram.
"""
new_max = np.max(arr)
new_min = np.min(arr)
new_th = max(abs(new_min), abs(new_max))
(old_hist, old_hist_edges, old_min, old_max, old_th) = old_hist
if new_th <= old_th:
h... | bc6e6edc9531b07ed347dc0083f86ee921d77c11 | 8,740 |
from typing import Mapping
def unmunchify(x):
""" Recursively converts a Munch into a dictionary.
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> sorted(unmunchify(b).items())
[('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')]
unmunchify wil... | 90ee373099d46ca80cf78c4d8cca885f2258bce2 | 8,741 |
def split_data(mapping, encoded_sequence):
""" Function to split the prepared data in train and test
Args:
mapping (dict): dictionary mapping of all unique input charcters to integers
encoded_sequence (list): number encoded charachter sequences
Returns:
numpy array : train and test... | b8044b3c1686b37d4908dd28db7cbe9bff2e899a | 8,742 |
def fsp_loss(teacher_var1_name,
teacher_var2_name,
student_var1_name,
student_var2_name,
program=None):
"""Combine variables from student model and teacher model by fsp-loss.
Args:
teacher_var1_name(str): The name of teacher_var1.
teacher_var2... | b8937a64ec8f5e215128c61edee522c9b2cd83d7 | 8,743 |
def diff_numpy_array(A, B):
"""
Numpy Array A - B
return items in A that are not in B
By Divakar
https://stackoverflow.com/a/52417967/1497443
"""
return A[~np.in1d(A, B)] | 72139ba49cf71abd5ea60772143c26f384e0e171 | 8,744 |
def _find_data_between_ranges(data, ranges, top_k):
"""Finds the rows of the data that fall between each range.
Args:
data (pd.Series): The predicted probability values for the postive class.
ranges (list): The threshold ranges defining the bins. Should include 0 and 1 as the first and last val... | 323986cba953a724f9cb3bad8b2522fc711529e5 | 8,746 |
def validar_entero_n():
"""
"""
try:
n = int(input('n= ')) #si es un float también funciona el programa
except:
print ('Número no válido')
return False
else:
return n | a1238025fd2747c597fc2adf34de441ae6b8055d | 8,747 |
def Conv_Cifar10_32x64x64():
"""A 3 hidden layer convnet designed for 32x32 cifar10."""
base_model_fn = _cross_entropy_pool_loss([32, 64, 64],
jax.nn.relu,
num_classes=10)
datasets = image.cifar10_datasets(batch_size=128)
retu... | e41e2f0da80f8822187a2ee82dcfe6f70e324213 | 8,748 |
from typing import List
def rotate(angle_list: List, delta: float) -> List:
"""Rotates a list of angles (wraps around at 2 pi)
Args:
angle_list (List): list of angles in pi radians
delta (float): amount to change in pi radians
Returns:
List: new angle list in pi radians
"""
... | 560c5138486bd3e67ad956fb2439236a3e3886cc | 8,749 |
def global_average_pooling_3d(tensor: TorchTensorNCX) -> TorchTensorNCX:
"""
3D Global average pooling.
Calculate the average value per sample per channel of a tensor.
Args:
tensor: tensor with shape NCDHW
Returns:
a tensor of shape NC
"""
assert len(tensor.shape) == 5, 'm... | 27a73d29fd9dd63b461f2275ed2941bf6bd83348 | 8,750 |
def get_LAB_L_SVD_s(image):
"""Returns s (Singular values) SVD from L of LAB Image information
Args:
image: PIL Image or Numpy array
Returns:
vector of singular values
Example:
>>> from PIL import Image
>>> from ipfml.processing import transform
>>> img = Image.open('./im... | 50a4bd4e4a8b3834baa3aca1f5f1e635baa7a145 | 8,751 |
def path_inclusion_filter_fn(path, param, layer):
"""Returns whether or not layer name is contained in path."""
return layer in path | c93aa83e67c600cd83d053d50fbeaee4f7eebf94 | 8,752 |
from typing import Tuple
def _parse_feature(line: PipelineRecord) -> Tuple[str, Coordinates, Feature]:
""" Creates a Feature from a line of output from a CSVReader """
contig = line[0]
coordinates = parse_coordinates(line[1])
feature = line[2]
# Piler-cr and BLAST both use 1-based indices, but Op... | 201f9c6ed5cd618fc63ec5e07a5b99977f4ef2b0 | 8,753 |
def average_summary_df_tasks(df, avg_columns):
""" Create averages of the summary df across tasks."""
new_df = []
# Columns to have after averaging
keep_cols = ["dataset", "method_name", "trial_number"]
subsetted = df.groupby(keep_cols)
for subset_indices, subset_df in subsetted:
return... | 9c506132cc406a91979777255c092db20d786d12 | 8,754 |
def ml_variance(values, mean):
"""
Given a list of values assumed to come from a normal distribution and
their maximum likelihood estimate of the mean, compute the maximum
likelihood estimate of the distribution's variance of those values.
There are many libraries that do something like this, but th... | 440d8d2d2f0a5ed40e01e640aadafb83f16ee14b | 8,755 |
def add_landmarks(particle, d, angle):
"""
Adds a set of landmarks to the particle. Only used on first SLAM cycle
when no landmarks have been added.
:param particle: The particle to be updated
:param d: An array of distances to the landmarks
:param angle: An array of observation angles for the ... | d1d168e48f62f60d58e57a79223793108d50dac9 | 8,756 |
def walk_forward_val_multiple(model, ts_list,
history_size=HISTORY_SIZE,
target_size=TARGET_SIZE) -> float:
"""
Conduct walk-forward validation for all states, average the results.
Parameters
----------
model -- The model to be validated
... | b3f73ceeddb720fdc7c7d9470a49bccc3c21f81b | 8,757 |
def inverse_project_lambert_equal_area(pt):
"""
Inverse Lambert projections
Parameters:
pt: point, as a numpy array
"""
X = pt[0]
Y = pt[1]
f = np.sqrt(1.0-(X**2.0+Y**2.0)/4)
return tensors.Vector([f*X,f*Y,-1.0+(X**2.0+Y**2.0)/2]) | f8ab5fb44d2d271a8da13623273d8d687d38b772 | 8,759 |
import dataclasses
def _get_field_default(field: dataclasses.Field):
"""
Return a marshmallow default value given a dataclass default value
>>> _get_field_default(dataclasses.field())
<marshmallow.missing>
"""
# Remove `type: ignore` when https://github.com/python/mypy/issues/6910 is fixed
... | 0c45e55a1c14cb6b47365ef90cb68e517342dbbc | 8,760 |
from typing import List
from typing import Tuple
import select
def get_all_votes(poll_id: int) -> List[Tuple[str, int]]:
"""
Get all votes for the current poll_id that are stored in the database
Args:
poll_id (int): Telegram's `message_id` for the poll
Returns:
List[Tuple[str, int]]:... | cf0ad8ee700a0da70bf29d53d08ab71e08c941ea | 8,762 |
def getUnitConversion():
"""
Get the unit conversion from kT to kJ/mol
Returns
factor: The conversion factor (float)
"""
temp = 298.15
factor = Python_kb/1000.0 * temp * Python_Na
return factor | cb7b33231a53a68358713ce65137cbf13a397923 | 8,763 |
def find_where_and_nearest(array, value):
"""
Returns index and array[index] where value is closest to an array element.
"""
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx, array[idx] | a34ac1d59c8093989978fbca7c2409b241cedd5b | 8,764 |
import numpy
def twoexpdisk(R,phi,z,glon=False,
params=[1./3.,1./0.3,1./4.,1./0.5,logit(0.1)]):
"""
NAME:
twoexpdisk
PURPOSE:
density of a sum of two exponential disks
INPUT:
R,phi,z - Galactocentric cylindrical coordinates or (l/rad,b/rad,D/kpc)
glon= (False... | bf8c5e0afa28e715846401274941e281a8731f24 | 8,765 |
def sc(X):
"""Silhouette Coefficient"""
global best_k
score_list = [] # 用来存储每个K下模型的平局轮廓系数
silhouette_int = -1 # 初始化的平均轮廓系数阀值
for n_clusters in range(3, 10): # 遍历从2到10几个有限组
model_kmeans = KMeans(n_clusters=n_clusters, random_state=0) # 建立聚类模型对象
cluster_labels_tmp = model_kmeans.f... | c2898e115db04c1f1ac4d6a7f8c583ea0a8b238e | 8,766 |
import socket
import time
def is_tcp_port_open(host: str, tcp_port: int) -> bool:
"""Checks if the TCP host port is open."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) # 2 Second Timeout
try:
sock.connect((host, tcp_port))
sock.shutdown(socket.SHUT_RD... | cbe4d0ae58610b863c30b4e1867b47cb1dbdfc3d | 8,767 |
from typing import Callable
from typing import Any
import itertools
def recursive_apply_dict(node: dict, fn: Callable) -> Any:
"""
Applies `fn` to the node, if `fn` changes the node,
the changes should be returned. If the `fn` does not change the node,
it calls `recursive_apply` on the children of the... | c40daa68caaea02d16511fcc1cd3ee1949c73633 | 8,768 |
import six
def encode_image_array_as_jpg_str(image):
"""Encodes a numpy array into a JPEG string.
Args:
image: a numpy array with shape [height, width, 3].
Returns:
JPEG encoded image string.
"""
image_pil = Image.fromarray(np.uint8(image))
output = six.BytesIO()
image_pil.save(output, format=... | 4c2d27c15c6979678a1c9619a347b7aea5718b2c | 8,769 |
def minify_response(response):
"""Minify response to save bandwith."""
if response.mimetype == u'text/html':
data = response.get_data(as_text=True)
response.set_data(minify(data, remove_comments=True,
remove_empty_space=True,
... | 29a942d870636337eaf0d125ba6b2ca9945d1d1c | 8,770 |
def get_shorturlhash(myurl):
"""Returns a FNV1a hash of the UNquoted version of the passed URL."""
x = get_hash(unquote(myurl))
return x | f61ef1cfe14fc69a523982888a7b1082244b7bd5 | 8,771 |
def filter_privacy_level(qs, clearance_level, exact=False):
"""
Function to exclude objects from a queryset, which got a higher clearance
level than the wanted maximum clearance level.
:qs: Django queryset.
:clearance_level: Minimum clearance level.
:exact: Boolean to check for the exact cleara... | a5fd864b3a9efd86bf40e0a3b966edb047979b2a | 8,772 |
def get_configuration_store(name=None,resource_group_name=None,opts=None):
"""
Use this data source to access information about an existing App Configuration.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example = azure.appconfiguration.get_configuration_store(n... | 4c0baa2cdd089439f1a53415ff9679568a097094 | 8,773 |
def _linear(args, output_size, bias, scope=None, use_fp16=False):
"""Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
bias: boolean, whether to add a bias term or not.
bi... | d8daafaf1dfab0bc6425aef704543833bfbf731a | 8,774 |
def find_CI(method, samples, weights=None, coverage=0.683,
logpost=None, logpost_sort_idx=None,
return_point_estimate=False, return_coverage=False,
return_extras=False, options=None):
"""Compute credible intervals and point estimates from samples.
Arguments
---------
... | 6b5ab3ac47f4f4a0251862946336948fd2ff66ed | 8,775 |
def load_csv(filename, fields=None, y_column=None, sep=','):
""" Read the csv file."""
input = pd.read_csv(filename, skipinitialspace=True,
usecols=fields, sep=sep, low_memory=False)
input = input.dropna(subset=fields)
# dtype={"ss_list_price": float, "ss_wholesale_cost": float}
... | 126b96e94f4a5ab201460b427828807cf31eb6ae | 8,776 |
def Normalize(array):
"""Normalizes numpy arrays into scale 0.0 - 1.0"""
array_min, array_max = array.min(), array.max()
return ((array - array_min)/(array_max - array_min)) | a8f3bae56f8e17aed80f8e41030d049a69ac8cae | 8,777 |
def obtener_cantidad_anualmente(PaisDestino, AnioInicio, AnioFin):
"""
Obtener cantidad de vuelos entrantes anualmente dado un pais destino y un rango de años
Obtiene la cantidad total de vuelos entrantes de cada año
:param PaisDestino: Pais al que llegan los vuelos
:type PaisDestino: str
:param... | 8364a08f4b42124b70a7769dc6a9649cdd9841d7 | 8,778 |
def calculate_shap_for_test(training_data, y, pipeline, n_points_to_explain):
"""Helper function to compute the SHAP values for n_points_to_explain for a given pipeline."""
points_to_explain = training_data[:n_points_to_explain]
pipeline.fit(training_data, y)
return _compute_shap_values(pipeline, pd.Dat... | d8a88b3c9af05a8274a0cca1a0e63c3a9faaa8d0 | 8,779 |
def read_num_write(input_string):
""" read in the number of output files
"""
pattern = ('NumWrite' +
one_or_more(SPACE) + capturing(INTEGER))
block = _get_training_data_section(input_string)
keyword = first_capture(pattern, block)
assert keyword is not None
return keyword | 0ee1a9ac178eb4c49a01a36208e4c59d6b9023bc | 8,780 |
import requests
import json
def stock_zh_a_minute(symbol: str = 'sh600751', period: str = '5', adjust: str = "") -> pd.DataFrame:
"""
股票及股票指数历史行情数据-分钟数据
http://finance.sina.com.cn/realstock/company/sh600519/nc.shtml
:param symbol: sh000300
:type symbol: str
:param period: 1, 5, 15, 30, 60 分钟的数... | b54f7dce68e102ebfa6c1784de5ebd49fcb405cb | 8,781 |
import random
def randomize_case(s: str) -> str:
"""Randomize string casing.
Parameters
----------
s : str
Original string
Returns
-------
str
String with it's letters in randomized casing.
"""
result = "".join(
[c.upper() if random.randint(0, 1) == 1 else... | 5e00ce336e2886a0d3bd52bc033b02560f0fb9ae | 8,782 |
def _get_results():
"""Run speedtest with speedtest.py"""
s = speedtest.Speedtest()
print("Testing download..")
s.download()
print("Testing upload..")
s.upload()
return s.results.ping, s.results.download, s.results.upload | 7092a5aa7200ebc93e266dbd6b7885095b0433bb | 8,783 |
def findCursor(query, keyname, page_no, page_size):
"""Finds the cursor to use for fetching results from the given page.
We store a mapping of page_no->cursor in memcache. If this result is missing, we look for page_no-1, if that's
missing we look for page_no-2 and so on. Once we've found one (or we get back to ... | 9af3368ef0011d7c6c9758f57bc2c956d540f675 | 8,784 |
def _get_seq(window,variants,ref,genotypeAware):
"""
Using the variation in @variants, construct two haplotypes, one which
contains only homozygous variants, the other which contains both hom and het variants
by placing those variants into the reference base string
@param variants: A vcf_eval.ChromV... | 316c19f964c6ce29d52358070d994f0fdfbcc1b8 | 8,785 |
import scipy
def interp_logpsd(data, rate, window, noverlap, freqs, interpolation='linear'):
"""Computes linear-frequency power spectral density, then uses interpolation
(linear by default) to estimate the psd at the desired frequencies."""
stft, linfreqs, times = specgram(data, window, Fs=rate, noverlap=... | 0822f776063da9f0797aa898b0305fb295d8c0f1 | 8,786 |
def load_replica_camera_traj(traj_file_path):
"""
the format:
index
"""
camera_traj = []
traj_file_handle = open(traj_file_path, 'r')
for line in traj_file_handle:
split = line.split()
#if blank line, skip
if not len(split):
continue
camera_traj.a... | 1879c97ed5ce24834689b156ffdc971b023e67f2 | 8,787 |
def test_model(sess, graph, x_, y_):
"""
:param sess:
:param graph:
:param x_:
:param y_:
:return:
"""
data_len = len(x_)
batch_eval = batch_iter(x_, y_, 64)
total_loss = 0.0
total_acc = 0.0
input_x = graph.get_operation_by_name('input_x').outputs[0]
input_y = graph... | 7c310a7cf979004d9f14fbd1ec57228dbfc81cd2 | 8,788 |
def epanechnikov(h: np.ndarray, Xi: np.ndarray, x: np.ndarray) -> np.ndarray:
"""Epanechnikov kernel.
Parameters:
h : bandwidth.
Xi : 1-D ndarray, shape (nobs, 1). The value of the training set.
x : 1-D ndarray, shape (1, nbatch). The value at which the kernel density is being estimated... | 45902e9396661a6c0f8faf9cfc2d017125f6a427 | 8,789 |
def punctuation(chars=r',.\"!@#\$%\^&*(){}\[\]?/;\'`~:<>+=-'):
"""Finds characters in text. Useful to preprocess text. Do not forget
to escape special characters.
"""
return rf'[{chars}]' | b2fd23d8485c3b6d429723a02a95c981982559b5 | 8,790 |
import time
import logging
def log_http_request(f):
"""Decorator to enable logging on an HTTP request."""
level = get_log_level()
def new_f(*args, **kwargs):
request = args[1] # Second argument should be request.
object_type = 'Request'
object_id = time.time()
log_name = ob... | ecb62d0501307330fc0a56d8eadfbee8e729adf6 | 8,791 |
def look_at(vertices, eye, at=[0, 0, 0], up=[0, 1, 0]):
"""
"Look at" transformation of vertices.
"""
if (vertices.ndimension() != 3):
raise ValueError('vertices Tensor should have 3 dimensions')
place = vertices.place
# if list or tuple convert to numpy array
if isinstance(at, lis... | 10a6b94ecba08fecd829758f9c94765c718a5add | 8,792 |
import types
def _count(expr, pat, flags=0):
"""
Count occurrences of pattern in each string of the sequence or scalar
:param expr: sequence or scalar
:param pat: valid regular expression
:param flags: re module flags, e.g. re.IGNORECASE
:return:
"""
return _string_op(expr, Count, out... | c4c387f18ac75977a661662dae7606a066242b57 | 8,793 |
def simplex3_vertices():
"""
Returns the vertices of the standard 3-simplex. Each column is a vertex.
"""
v = np.array([
[1, 0, 0],
[-1/3, +np.sqrt(8)/3, 0],
[-1/3, -np.sqrt(2)/3, +np.sqrt(2/3)],
[-1/3, -np.sqrt(2)/3, -np.sqrt(2/3)],
])
return v.transpose() | b10c2c781d1f7ed7050e14f069efd3e0e9a80a2b | 8,794 |
def get_output_msg(status, num_logs):
""" Returnes the output message in accordance to the script status """
if status == EXECUTION_STATE_COMPLETED:
return "Retrieved successfully {} logs that triggered the alert".format(num_logs)
else:
return "Failed to retrieve logs. Please check the scrip... | caec8de737251cc7c386a85a098d73d19617e71a | 8,795 |
import re
def insert_channel_links(message: str) -> str:
"""
Takes a message and replaces all of the channel references with
links to those channels in Slack formatting.
:param message: The message to modify
:return: A modified copy of the message
"""
message_with_links = message
match... | ce56e81e8eb66dc0f2754141bcfc30f42db50c5a | 8,797 |
def check_int_uuid(uuid):
"""Check that the int uuid i pass is valid."""
try:
converted = UUID(int=uuid, version=4)
except ValueError:
return False
return converted.int == uuid | a0ba7447e6c8cc0c35b68024fb4ade25f0802239 | 8,798 |
def calc_E_E_C_hs_d_t_i(i, device, region, A_A, A_MR, A_OR, L_CS_d_t, L_CL_d_t):
"""暖冷房区画𝑖に設置された冷房設備機器の消費電力量(kWh/h)を計算する
Args:
i(int): 暖冷房区画の番号
device(dict): 暖冷房機器の仕様
region(int): 省エネルギー地域区分
A_A(float): 床面積の合計 (m2)
A_MR(float): 主たる居室の床面積 (m2)
A_OR(float): その他の居室の床面積 (m2)
... | 8dbd0119ac90f3847de1f5af05891583a9bda26b | 8,799 |
def shift_time(x, dt):
"""Shift time axis to the left by dt. Used to account for pump & lamp delay"""
x -= dt
return x | c93fdddea8e41221583139dcc7a2d81177ba7c17 | 8,800 |
from datetime import datetime
import json
def eps_xfer(request,client_slug=None,show_slug=None):
"""
Returns all the episodes for a show as json.
Used to synk public url's with the main conference site.
"""
client=get_object_or_404(Client,slug=client_slug)
show=get_object_or_404(Show,client=... | 9a6691e0ac750919b5915e45ace0c347aa83cbe3 | 8,801 |
def register(class_, option=None, get_funcs={}):
"""A decorator to register a function as the way to display an object of class_
"""
if option:
key = (class_, option)
else:
key = class_
def decorator(func):
class_function_mapping[key] = (func, get_funcs)
return func
return decorator | c060691dd9e2760905e29a2c643dfa63d4ed029c | 8,802 |
def startup(target: machine.Machine,
workload: str,
count: int = 5,
port: int = 0,
**kwargs):
"""Time the startup of some workload.
Args:
target: A machine object.
workload: The workload to run.
count: Number of containers to start.
port: The port to ... | c53b627d95270aa074f9178e1ebcd6ea49b8eeaa | 8,803 |
def log2_fold_change(df, samp_grps):
"""
calculate fold change - fixed as samp_grps.mean_names[0] over samp_grps.mean_names[1],
where the mean names are sorted alphabetically. The log has already been taken,
so the L2FC is calculated as mean0 - mean1
:param df: expanded and/or filtered dataframe
... | 07fcef6f5143095f4f8f77d0251bbd7ecd486fd9 | 8,805 |
def infer_wheel_units(pos):
"""
Given an array of wheel positions, infer the rotary encoder resolution, encoding type and units
The encoding type varies across hardware (Bpod uses X1 while FPGA usually extracted as X4), and
older data were extracted in linear cm rather than radians.
:param pos: a ... | 82d1a63c11c31d4de83ba5360def223b85194ef9 | 8,806 |
def extract_tform(landmarks, plane_name):
"""Compute the transformation that maps the reference xy-plane at origin to the GT standard plane.
Args:
landmarks: [landmark_count, 3] where landmark_count=16
plane_name: 'tv' or 'tc'
Returns:
trans_vec: translation vector [3]
quat: quaterni... | d9d4ed43c9572cdd76b34235e380f22a6eb27d03 | 8,807 |
from typing import TextIO
import csv
def load_events(fhandle: TextIO) -> annotations.Events:
"""Load an URBAN-SED sound events annotation file
Args:
fhandle (str or file-like): File-like object or path to the sound events annotation file
Raises:
IOError: if txt_path doesn't exist
Retur... | 2c2017d754fe12ebd37349b359ba6a92ec115421 | 8,808 |
def set_nan(df, chrom_bed_file):
"""This function will take in a dataframe and chromosome length bed file
and will replace 0's with np.nan according to each chromosome length.
This will fix any issues when calculating Z-scores"""
# Build dictionary of key=chromosome and value=chromosome_length
chrom... | e90008c42db5a94c8676c941da5832438301a724 | 8,810 |
def configure_smoothing(new_d,smoothing_scans):
"""
# <batchstep method="net.sf.mzmine.modules.peaklistmethods.peakpicking.smoothing.SmoothingModule">
# <parameter name="Peak lists" type="BATCH_LAST_PEAKLISTS"/>
# <parameter name="Filename suffix">smoothed</parameter>
# <parameter nam... | 031586cf5dbb9fdf1fb6762a89a988367d172942 | 8,811 |
def contact_us():
""" Contact Us Route
Route to lead to the contact page
Args:
None
Returns:
rendered template for contact_us.html
"""
return render_template('contact_us.html', title='CONP | Contact Us', user=current_user) | 2597038074e8f60e14066f10390a161b15cf7071 | 8,812 |
import pandas
def query_field(boresight, r1=None, r2=None, observatory='apo',
mag_range=None, mag_column=None, database_params=None):
"""Selects Gaia DR2 stars for a field, from the database.
Parameters
----------
boresight : tuple
A tuple with the right ascension and declinat... | c05276ecfac3b33dcc5382cf54e220b416614656 | 8,814 |
def get_throttling_equilibria(simulation_config, input_params, priority_queue=True, dev_team_factor=1.0):
"""
Returns the equilibrium profiles for throttling configuration under analysis.
:param simulation_config:
:param input_params:
:return:
"""
desc_inf003 = "THROTTLING_INF003"
proce... | 4e0f6dd8fa3b0b36b713b33ab1a5aaf8394d4942 | 8,815 |
def signature(part):
""" return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__) | 522ae88538d6dd880492292c6f2ef169f3bbd06d | 8,816 |
def clean_key(func):
"""Provides a clean, readable key from the funct name and module path.
"""
module = func.__module__.replace("formfactoryapp.", "")
return "%s.%s" % (module, func.__name__) | 946288cd231148eb39af5d1e7e0b957d9f2131e8 | 8,817 |
def rotY(M, alpha):
"""Rotates polygon M around Y axis by alpha degrees.
M needs to be a Numpy Array with shape (4,N) with N>=1"""
T = np.eye(4)
alpha_radians = np.radians(alpha)
sin = np.sin(alpha_radians)
cos = np.cos(alpha_radians)
T[0,0] = cos
T[2,2] = cos
T[0,2] = sin
T[2,0]... | 49e850ff66b3c7877e6d8b4a450baaa6707d4f15 | 8,818 |
def is_image_file(filename):
"""
:param filename:
:return:
"""
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) | 40125478c6440efc9a740d2df57ba2f7bb15a5d1 | 8,819 |
def invert_comp_specifier(comp_specifier):
""" return the opposite (logical negation) of @p comp_specifier """
inverse_map = {
Comparison.Equal: Comparison.NotEqual,
Comparison.Less: Comparison.GreaterOrEqual,
Comparison.LessOrEqual: Comparison.Greater,
Comparison.NotEqual: Compa... | 187392dd1dc7f52c744536e8e372cab752ff8c85 | 8,820 |
import utm
def latlong2utm(point):
"""
This function converts a point from lat long to utm
Input : point : (lat,long)
Output : utm point : (x,y,z, n)
"""
return utm.from_latlon(point[0],point[1]) | 3ee82f9df84b02aa35fa0f2a35ec0916edf30e42 | 8,821 |
def multiply(a,b):
"""
multiply values
Args:
a ([float/int]): any value
b ([float/int]): any value
"""
return a*b | 67a85b1675da48684e9de7e9834d3daa4357699b | 8,822 |
from typing import Tuple
from typing import Dict
from typing import List
import regex
def merge_vocab(pair: Tuple[str, str], input_vocab: Dict[str, int]) -> Tuple[Dict[str, int], List]:
"""
>>> pair = ('w', 'o')
>>> input_vocab = {'b i r d @': 3, 'w o r d @': 7, 'w o g @': 13}
>>> new_vocab, new_pairs... | 15226aa9ebd9cae73e5bd00b60cb1b3bbb5d8e07 | 8,823 |
def visualize_bbox_act(img, bboxes,labels, act_preds,
classes=None,thickness=1,
font_scale=0.4,show=False,
wait_time=0,out_file=None):
"""Show the tracks with opencv."""
assert bboxes.ndim == 2
assert labels.ndim == 1
assert bboxes.shape[0] == labels.shape[0]
... | de67d5acba2b2994ec2b66ae4e7e0c58498ecebe | 8,824 |
def calculate_similarity(subgraph_degrees):
"""
Given a list of subgraph degrees, this function calls the guidance
function and calculates the similarity of a particular node with all it's
non-connected nodes.
:param subgraph_degrees: A list of lists containing the non connected node
and degree... | cd4be7c405b2974f35db24dbd7d7db7bdf9a867e | 8,825 |
def balance_thetas(theta_sets_types, theta_sets_values):
"""Repeats theta values such that all thetas lists have the same length """
n_sets = max([len(thetas) for thetas in theta_sets_types])
for i, (types, values) in enumerate(zip(theta_sets_types, theta_sets_values)):
assert len(types) == len(va... | 3ca7316a18d57c95adbfbdfec5f5be36f33dc0ea | 8,826 |
def _format_weights(df, col, targets, regs):
"""
Reformat the edge table (target -> regulator) that's output by amusr into a pivoted table that the rest of the
inferelator workflow can handle
:param df: pd.DataFrame
An edge table (regulator -> target) with columns containing model values
:pa... | b683846d9d059a39280077a714455718bd710670 | 8,827 |
def put_thread(req_thread: ReqThreadPut):
"""Put thread for video to DynamoDB"""
try:
input = thread_input.update_item(req_thread)
res = table.update_item(**input)
return res
except ClientError as err:
err_message = err.response["Error"]["Message"]
raise HTTPExcepti... | dba9fe080451a3cb68365824faf8dbccad03b1b6 | 8,828 |
def check_method(adata):
"""Check that method output fits expected API."""
assert "labels_pred" in adata.obs
return True | 78c1a5181395f1675854333c30bf617c578cc1d4 | 8,830 |
def build_index_block(in_channels,
out_channels,
kernel_size,
stride=2,
padding=0,
groups=1,
norm_cfg=dict(type='BN'),
use_nonlinear=False,
expa... | 03e15760146ce75f06de64ffd6886fe627afcf9b | 8,831 |
def nodes(*paths, type=None):
"""Call node() on each given path and return the list of results.
nodes('foo', 'bar', ...) is equivalent to
[node('foo'), node('bar'), ...]
"""
return list(map(lambda p: node(p, type=type), paths)) | d1ae50237a275c70b9b9e85684e898494fc6c954 | 8,832 |
def parse_rule(parameter_string):
"""Parse a parameter string into its constituent name, type, and
pattern
For example:
`parse_parameter_string('<param_one:[A-z]>')` ->
('param_one', str, '[A-z]')
:param parameter_string: String to parse
:return: tuple containing
(parameter_nam... | 881e219ab59c801da078e91cf82ccb15caa7798d | 8,834 |
def plan():
"""
改进方案
:return:
"""
return render_template('plan.htm') | 135d8b003adbe8f6311f781f0d4ff7ed206a81d6 | 8,835 |
def extract_traceback(notebook):
""" Extracts information about an error from the notebook.
Parameters
----------
notebook: :class:`nbformat.notebooknode.NotebookNode`
Executed notebook to find an error traceback.
Returns
-------
bool
Whether the executed notebook has an er... | 9af26f973e6810936eaa68058efcdb7bc145803b | 8,836 |
def get_log() -> str:
"""get_log() -> str
(internal)
"""
return str() | 3e2d7bf82128afc664eded15e6c11f1ed9da45e7 | 8,837 |
def start_server(self, parameters): # pragma: no cover
"""adds the server start to celery's queue
Args:
parameters(dict): The POST JSON parameters
"""
self.update_state(state=CeleryStates.started)
session = ServerSession(parameters)
return session() | c20e2233ee7c1e6b1718b0c4bfbb2b9b5f52e0e1 | 8,838 |
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
name = properties.get('name', context.env['name'])
project_id = properties.get('project', context.env['project'])
bgp = properties.get('bgp', {'asn': properties.get('asn')})
router ... | 506c7ded703b8c00fb9a2a6d7645e9e5d0da6905 | 8,839 |
import time
def cachedmethod(timeout):
"""
Function decorator to enable caching for instance methods.
"""
def _cached(func):
if not(hasattr(func, 'expires')):
func.expires = {}
func.cache = {}
def __cached(self, *args, **kwargs):
if(timeout and func.expires.get(repr(self), 0) < time.time()):
if(r... | dd8999a60aa6d92e6b442c7c0661d88cd0e8590e | 8,840 |
def __build_pyramid(models, features):
"""Applies all submodels to each FPN level.
Args:
models (list): List of submodels to run on each pyramid level
(by default only regression, classifcation).
features (list): The FPN features.
Returns:
list: A list of tensors, one f... | 269be978f9aafbdc36b1c9d726171785a85f54a4 | 8,841 |
def get_ap_list():
"""
Method to return list of aps present in the network
"""
return jsonify_params(
CELLULAR_NETWORK.ap_list
) | da0777219025499603425f3147b2897d2bce2da6 | 8,842 |
def _merge_url_rule(rule_before, rule_after):
"""
Merges two url rule parts.
Parameters
----------
rule_before : `None` or `tuple` of `tuple` (`int`, `str`)
First url part if any to join `rule_after` to.
rule_after : `None` or `tuple` of `tuple` (`int`, `str`)
Second url part wh... | 0682734a82b227f746325363652d1c3f378f2e51 | 8,843 |
def create_graphic_model(nodes, edges, gtype):
"""
Create a graphic model given nodes and edges
Parameters
----------
nodes : dict
for each node {key, text, math}
edges : dict
for each edge {key, text, math}
gtype : str [default="text"]
"text" for a verbose version, ... | 028c740cc7fa003642815a8ec0f27154fc6e0dab | 8,845 |
def zero_cross_bounds(arr, dim, num_cross):
"""Find the values bounding an array's zero crossing."""
sign_switch = np.sign(arr).diff(dim)
switch_val = arr[dim].where(sign_switch, drop=True)[num_cross]
lower_bound = max(0.999*switch_val, np.min(arr[dim]))
upper_bound = min(1.001*switch_val, np.max(ar... | 52d3431c32f61f47223fdccf4c5a85a92589534f | 8,846 |
def remove_tseqs(t: ST_Type) -> ST_Type:
"""
Get just the sseqs and the non-nested types, removing the tseqs
"""
if type(t) == ST_SSeq or type(t) == ST_SSeq_Tuple:
inner_tseqs_removed = remove_tseqs(t.t)
return replace(t, t=inner_tseqs_removed)
elif is_nested(t):
return remov... | 323f9cd3c007c1decf11653091f641dc453d32cb | 8,847 |
def prod_cart(in_list_1: list, in_list_2: list) -> list:
"""
Compute the cartesian product of two list
:param in_list_1: the first list to be evaluated
:param in_list_2: the second list to be evaluated
:return: the prodotto cartesiano result as [[x,y],..]
"""
_list = []
for element_1 in ... | 9fdbfc558f5ec3b11c78535b9125e0a1c293035e | 8,848 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.