content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mfcc_filter_banks(sampling_rate, num_fft, lowfreq=133.33, linc=200 / 3,
logsc=1.0711703, num_lin_filt=13, num_log_filt=27):
"""
Computes the triangular filterbank for MFCC computation
(used in the stFeatureExtraction function before the stMFCC function call)
This function is t... | 56,500 |
def main():
"""Read library __version__ and write to .env."""
args = _parse_args()
logging.basicConfig(
stream=sys.stderr,
level=logging.DEBUG if args.verbose > 0 else logging.INFO,
format="%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s",
)
LOGGER.info(arg... | 56,501 |
def reduce(ctx, idf, output, weather, cores, all_zones, as_version):
"""Convert EnergyPlus models to an Umi Template Library by using the model
complexity reduction algorithm.
IDF can be a file path or a directory. In case of a directory, all *.idf
files will be matched in the directory and subdirector... | 56,502 |
def train(version, n_epochs, batch_size, lr, dr, l1, l2, bn, deconvolution, n_base_filters,
depth, filter_size, activation, final_activation, n_classes, optimizer, loss_function, metrics,
n_train_patients, n_val_patients, checkpoint_model, models_dir,
train_feature_files, train_label_files... | 56,503 |
def make_BinaryQuadraticModel_from_JSON(obj: dict):
"""make BinaryQuadraticModel from JSON.
Returns:
corresponding BinaryQuadraticModel type
"""
label = obj['variable_labels'][0]
if isinstance(label, list):
#convert to tuple
label = tuple(label)
mock_linear = {label:1.... | 56,504 |
def compare_album(left_album: Album, right_album: Album):
"""Compare two album items and return True if they match."""
# do not match on year and albumtype as this info is often inaccurate on providers
if (
left_album.provider == right_album.provider
and left_album.item_id == right_album.ite... | 56,505 |
def get_elw_ticker_name(ticker: str) -> str:
"""종목 이름 조회
Args:
ticker (str): 티커
Returns:
str: 종목명
>> get_elw_ticker_name("58F194")
KODEX 200
"""
return krx.get_etx_name(ticker) | 56,506 |
def test_list_hex_binary_enumeration_4_nistxml_sv_iv_list_hex_binary_enumeration_5_3(mode, save_output, output_format):
"""
Type list/hexBinary is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/hexBinary/Schema+Instance/NISTSchema-SV-IV-list-hexBinary-enumeration-5.x... | 56,507 |
def smart_implicit_midpoint_proposal_factory(vector_field: Callable, thresh: float=1e-6, max_iters: int=1000) -> Callable:
"""This proposal distribution for Hamiltonian Monte Carlo uses the smart
implicit midpoint integrator.
Args:
vector_field: Hamiltonian vector field.
thresh: Convergence... | 56,508 |
def get_block_symbol_data(editor, block):
"""
Gets the list of ParenthesisInfo for specific text block.
:param editor: Code editor instance
:param block: block to parse
"""
def list_symbols(editor, block, character):
"""
Retuns a list of symbols found in the block text
... | 56,509 |
def calculate_info_gain(node):
"""This function calculate the information gain of attributes given a node."""
# CALCULATING EXPECTED INFORMATION OF WHOLE TRAINING DATA
expected_info_tr = 0
for c, v in node.CLASSES_DISTRIBUTIONS.items():
if v == 0:
continue
expected_i... | 56,510 |
def is_windows() -> bool:
"""Determine if the current platform is Windows or not."""
return _system() == "Windows" | 56,511 |
def jieba_clear_text(text):
"""
jieba分词,并使用自定义停用词表去除停用词以及长度为1的词
"""
text_n= "".join(re.findall(u"[\u4e00-\u9fa5]", text))
raw_result = "$".join(jieba.cut(text_n))
myword_list = []
#去除停用词
for myword in raw_result.split('$'):
if myword not in stopwords:
myword_list.app... | 56,512 |
def prepare_data(train_file_idxs, test_file_idxs, mel_list,
target_list):
"""
modified prepare_framewise_data() in classify.py of the baseline code
"""
X_train = []
y_train = []
for idx in train_file_idxs:
X_train.append(mel_list[idx])
y_train.append(target_list[idx])
train_idxs = np.random.perm... | 56,513 |
def unzip(zip_address, file_name, encoding='UTF-8'):
"""解压zip数据包
:param zip_address: 压缩包的地址
:param file_name: 压缩包里面文件的名字
:param encoding: 文件的编码
:return: 压缩包里面的数据:默认编码的UTF-8
"""
f = zipfile.ZipFile(zip_address)
fp = f.read(file_name)
lines = fp.decode(encoding)
return lines | 56,514 |
def parse() -> dict:
"""Parse command line arguments"""
parser = ArgumentParser()
parser.add_argument('-p', '--publish', action='store_true', default=False)
return vars(parser.parse_args()) | 56,515 |
def container_export(name="3bot", path=None, no_overwrite=False, skip_if_exists=False, configdir=None):
"""
export the 3bot to image file, if not specified will be /tmp/3bot.tar
:param name:
:param path:
:return:
"""
overwrite = not no_overwrite
_configure(configdir=configdir)
docker... | 56,516 |
def gen_text (lm, seed, nletters=1000):
"""Same as generate_text, except now handles keys its not seen before"""
for k in lm.keys():
order = len(k)
if len(seed) < order:
seed = ' ' * order + seed
history = seed[-order:]
out = []
for i in range(nletters):
if history not ... | 56,517 |
def parse(image, origin_anchors):
"""
:param image: input picture, shape like (H, W, 3)
:param origin_anchors: text like ["201,162,207,229",
"208,162,223,229",
"224,162,239,229"]
each line was a anch... | 56,518 |
def has_name_keywords(ustring):
"""是否含有名称的标识字符"""
if (u'店名' in ustring) or \
(u'店家' in ustring) or \
(u'名字' in ustring):
return True
return False | 56,519 |
def evaluate_df(df_true, df_subm):
"""
Score submitted dataframe wrt the true dataframe
Policy:
- If everything is perfect, 100%
- Else, we look at the F1 score. This score takes into account
whether the submitted solution contains everything it should,
while it also pen... | 56,520 |
def process_data(input_file):
"""
Parse the complete stroke trial database and retain relevant columns.
Data cleaning phase
"""
f = open(input_file, 'r')
header = f.readline().split(",")
data = []
for line in f:
data.append(map(float, line.split(",")))
return header, np.array(data) | 56,521 |
def get_error_string_for_multiple_dbs(tables: List[Table]):
"""
Get error string for tables belonging to multiple databases.
:param tables: list of table
:return: String: error string
"""
return f'Tables should belong to same db {", ".join([f"{table.table_name}: {table.conn_id}" for table in tab... | 56,522 |
def list_endpoints_formatted_text():
"""List all endpoints for the app."""
return flask.jsonify(
[
f"{entry['endpoint']:50s} {entry['methods']:25s} {entry['route']}"
for entry in sitemap_builder()
]
) | 56,523 |
def harmonic_frequencies(prog, output_str):
""" Reads the harmonic vibrational frequencies from the output string.
Returns the frequencies in cm-1.
:param prog: electronic structure program to use as a backend
:type prog: str
:param output_str: string of the program's output file
... | 56,524 |
def db_with_transactions(db_2_accounts):
"""Inserts 2 accounts of 8 transactions each."""
accounts_db = select_accounts(db_2_accounts)
for account_db in accounts_db:
transactions = make_transactions(8, account_uuid=account_db.uuid)
for transaction in transactions:
db_2_accounts.t... | 56,525 |
def integer_schedule(x, name="undefined"):
"""Deserializes an integer schedule."""
if type(x) == dict:
if x["type"] == "constant":
return lambda i: x["value"]
elif x["type"] == "geometric":
return lambda i: x["coefficient"] * (x["base"]**i)
elif x["type"] == "list... | 56,526 |
def point_set_to_vtk(pse, origin=(0.0, 0.0, 0.0)):
"""Convert the point set to a :class:`pyvista.PolyData` data object.
Args:
pse (:class:`omf.pointset.PointSetElement`): The point set to convert
Return:
:class:`pyvista.PolyData`
"""
points = np.array(pse.geometry.vertices)
out... | 56,527 |
def k8s_install_cli(client_version="1.4.5", install_location=None):
"""
Downloads the kubectl command line from Kubernetes
"""
file_url = ''
system = platform.system()
base_url = 'https://storage.googleapis.com/kubernetes-release/release/v{}/bin/{}/amd64/{}'
if system == 'Windows':
f... | 56,528 |
def add_dataset_arguments(parser: argparse.ArgumentParser):
"""Adds a subparser containing arguments for creating a dataset.
Arguments added:
- raw_data
- dataset_name
- source_type
- vocab_size
- num_comments
- num_examples
- mode
Params:
- parser (argparse.Ar... | 56,529 |
def add_components(spec):
"""Adds the service components to OpenAPI specification.
Arguments:
spec (obj): The apispec object.
"""
import copy
# Parameters
spec.components.parameter('idempotencyKey', 'header', {
"name": "X-Idempotence-Key",
"description": "A unique idem... | 56,530 |
def find_all_primes(x=22):
"""Find all the primes up to x"""
allprimes = []
for i in range(2, x + 1):
if is_prime(i):
allprimes.append(i)
print("There are %d primes between 2 and %d" % (len(allprimes), x))
return allprimes | 56,531 |
def op_number(space, bN):
"""
Todo:
Make this basis-independent
"""
assert bN.basis == "Fock"
M = op_ladder_dn(space, bN=bN)
return M.A @ M | 56,532 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the IP Webcam binary sensors."""
if discovery_info is None:
return
host = discovery_info[CONF_HOST]
name = discovery_info[CONF_NAME]
ipcam = hass.data[DATA_IP_WEBCAM][host]
async_add_entiti... | 56,533 |
def bbox_flip(bbox, width, flip_x=False):
"""
invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2
also note need to save before assignment
:param bbox: [n][x1, y1, x2, y2]
:param width: cv2 (height, width, channel)
:param flip_x: will flip x1 and x2
:return: flippe... | 56,534 |
def diff_pd(df1, df2):
"""Identify differences between two pandas DataFrames"""
assert (df1.columns == df2.columns).all(), \
"DataFrame column names are different"
if any(df1.dtypes != df2.dtypes):
"Data Types are different, trying to convert"
df2 = df2.astype(df1.dtypes)
if df1.... | 56,535 |
def toggle_lighting():
"""Toggle OpenGL lighting."""
set_lighting(not screen.lighting) | 56,536 |
def is_learned_based_on_exercise_outcomes(exercise_log):
"""
:return:
"""
if exercise_log.is_empty():
return False
return (
exercise_log.last_exercise().is_too_easy() or
len(exercise_log.most_recent_correct_dates())
>= CORRECTS_IN_DISTINCT_DAYS_FOR_... | 56,537 |
def test_recipe_str():
"""Test the recipe string representation"""
recipe = models.Recipe.objects.create(
user=sample_user(), title="pizza", time_minutes=240, price=10.0
)
assert str(recipe) == recipe.title | 56,538 |
def greeting(): # OK
"""Beschreibung:
Dient zum besonderen aussehen
:return: gibt die eingegebenen Zeichen decodiert aus
Details:
print(b'\xe2\x95\x94'.decode('utf-8')) ergibt ╔ die linke obere Ecke
print(b'\xe2\x95\x91'.decode('utf-8')) ergibt ║
somit lassen sich "Rahmen bau... | 56,539 |
def openmooc_settings(request):
"""The context processor function"""
copy_attrs = ('INSTANCE_URL',
'INSTANCE_TITLE',
'INSTANCE_NAME',
'FULL_ASKBOT_URL',
)
custom_settings = {}
for key in copy_attrs:
custom_settings[key] = g... | 56,540 |
def cbpowerspectrum( transferfile,
Omegacdm ,
Omegab ,
h ,
Omeganu = 0.0,
As = None,
ns = None ,
koverh = None ):
"""
Returns the baryon- CDM matter power spectrum using the transfer function
output, usng the cosmological parameters As, ns, h, Omegab, Omegacdm
args:
As : If As is None, a default va... | 56,541 |
def read_json_file_into_memory(json_file):
"""
Purpose:
Read properly formatted JSON file into memory.
Args:
json_file (String): Filename for JSON file to load (including path)
Returns:
json_object (Dictonary): Dictonary representation JSON Object
Examples:
>>> json_f... | 56,542 |
def load(trainFile, testFile):
"""
Builds various numpy arrays from the given .csv format training
and test tests.
Args:
trainFile: file name/path for the input training set
testFile: file name/path for the input test set
Returns:
y_train: labels in the training set as a nu... | 56,543 |
def process_arguments(args):
"""
This receives all arguments from calls to the public API functions so it
can validate and, if necessary, modify them. In particular, it can be used
to translate older style API calls into newer ones so as to maintain
backwards compatibility.
"""
args = handle... | 56,544 |
def print_trace(m,route: List[List[float]]):
"""
Save the map with route locally.
:param Location: list of latitude and longtitude of all locations on the route.
List[float] : the length is 2, while the first element is latitude
and the... | 56,545 |
def validateIP(ipaddressToValidate):
"""
Description: validates an IP address
Input: IP to be validated (string)
Return: True or False (boolean)
"""
try:
ipaddress.ip_address(ipaddressToValidate)
return True
except Exception:
return False | 56,546 |
def calc_mean_dff(data, *args):
""" Return the mean dF/F value, and the SEM of all neurons in the data matrix.
Subtracts the offset of each cell before the computation.
"""
min_vec = np.atleast_2d(np.nanmin(data, axis=1)).T
data_no_offset = data - min_vec
return np.nanmean(data_no_offset, axis=1... | 56,547 |
def tweet(auth, interval=1800, ignore=None):
"""
Decorator wrapping a string-returning function that returns
a function that tweets the results of calling the function
:param auth: Twitter auth object
:param interval: how long to wait between tweets
:param ignore: an optional list of Twitter API... | 56,548 |
def test_lighten_darken_light_file_change(input_image):
"""Tests that the file changes when using the lighten/darken method"""
input_image.lighten_darken('light')
input_image.write_file('test_light.bmp')
output_image = Bitmap.read_file('test_light.bmp')
input_image = Bitmap.read_file('bmp.bmp')
... | 56,549 |
def to_base_10(num: str, from_base: int, key="0123456789abcdefghijklmnopqrstuvwxyz", digits=100, minus_sign="-") -> int:
"""Convert a num in from_base to base 10."""
if len(key) < from_base:
raise ValueError("Must have key length > base")
if num == key[0]:
return 0
if num[0] == minus_s... | 56,550 |
def find_nearp(position, path):
""" Finds and returns the closes point in the path to the given position"""
x=path[0]
y=path[1]
z=path[2]
dx=position[0]-x
dy=position[1]-y
dz=position[2]-z
distance=np.sqrt(dx*dx+dy*dy+dz*dz) #caculate distance between position and every points in the pa... | 56,551 |
def updateCoins(coinCodes):
"""Update the H5 Repository with Coin Data
Keyword arguments:
coinList - Set of CoinCodes
"""
global apph5datafile
coinList = []
if coinCodes == '*':
print("You asked to update all tracked coins")
coinList = config.get('Active','Coins')... | 56,552 |
def unshard_env_batch(pytree):
"""Reshapes all arrays in the pytree.
`[ndev, env_s, bs, ...]` --> `[host_bs, env_s, ...]
Args:
pytree: A pytree of arrays to be sharded.
Returns:
Sharded data.
"""
def _unshard_array(array):
ndev, envs, bs = array.shape[:3]
new_shape = (envs, ndev * bs) +... | 56,553 |
def __fix_ResourceWarning__():
"""
Fix 'ResourceWarning: unclosed file' of GromacsWrapper's config.py module
"""
module_path = f"{os.path.dirname(os.path.realpath(gromacs.__file__))}/config.py"
old_str = "import sys"
new_str = "import sys ### fixed warning\n"
new_str += "import warning... | 56,554 |
def guided_filter(p, i, r, e):
"""
:param p: input image
:param i: guidance image
:param r: radius
:param e: regularization
:return: filtering output q
"""
# 1
mean_I = cv2.boxFilter(i, cv2.CV_64F, (r, r))
mean_p = cv2.boxFilter(p, cv2.CV_64F, (r, r))
corr_I = cv2.boxFilter(i... | 56,555 |
def test_evaluate_dbot_score_get_suspicious_malicious_malicious_str_confidencescore(mocker):
"""
When category suspicious, severity malicious and confidence score in string is malicious are in suspicious
category then dbot score should be 3
"""
# Configure
mocker.patch.object(demisto, 'params', ... | 56,556 |
def run_easy_twitter_deleter(username, account_key, account_secret, access_key, access_secret, datetime_older_than):
"""
Use the function 'run_easy_twitter_deleter' to find and delete tweets
"""
app = Easy_Twitter_Deleter(username, account_key, account_secret, access_key, access_secret, datetime_older_t... | 56,557 |
def _get_suffix_value_pairs(
tree_or_leaf: Any) -> List[Tuple[str, Type["Module"]]]:
"""Helper for naming pytrees of submodules."""
dict_or_leaf = serialization.to_state_dict(tree_or_leaf)
if not isinstance(dict_or_leaf, dict) or dict_or_leaf == {}:
return [('', tree_or_leaf)]
else:
flat_dict = trav... | 56,558 |
def ffmpegFormats(select = 'E'):
"""Expects ffmpeg to output something like:
File formats:
D. = Demuxing supported
.E = Muxing supported
--
D 3dostr 3DO STR
E 3g2 3GP2 (3GPP2 file format)
E 3gp 3GP (3GPP file format)
D 4xm 4X Technologies
E a64 a... | 56,559 |
def week_menu():
"""Меню расписания на неделю"""
kb = InlineKeyboardMarkup()
monday = InlBtn(text="Пн", callback_data="get_monday_schedule")
tuesday = InlBtn(text="Вт", callback_data="get_tuesday_schedule")
wednesday = InlBtn(text="Ср", callback_data="get_wednesday_schedule")
thursday = In... | 56,560 |
def sanitize_path(path):
"""Make path absolute with leading slash to prevent access to other data.
Preserve potential trailing slash.
"""
trailing_slash = "/" if path.endswith("/") else ""
path = posixpath.normpath(path)
new_path = "/"
for part in path.split("/"):
if not is_safe_pa... | 56,561 |
def hour_angle (sid_UT, loc, ra) :
"""Hour angle for sidereal_time `sid_UT`, location `loc`, and
right ascension `ra`.
`sid_UT` and `ra` must be Angle_D/Angle_R instances.
"""
### J. Meeus, p. 92
lon = loc.longitude_meuss
ha = (sid_UT - lon - ra).degrees
if abs (ha) >= 360.0 :
... | 56,562 |
def gaussian_mle_1d(x, photon_count, pixel_size, initial_position=None, initial_sigma=0.250):
"""Calculate the maximum likelihood estimate of the model parameters given measured photon count for 1D data.
Parameters
----------
x : array-like
Position data at which the function is to be evaluated... | 56,563 |
def compute_num_sim_ftrs(sim_func_names, num_doc_fields, num_user_fields, num_deep):
"""Computes the number of similarity features
:param num_doc_fields Number of document fields
:param num_user_fields Number of user fields
:param num_deep Number of deep features
:param sim_func_names Similarity fu... | 56,564 |
def brent(f, a, b, args=(), max_iteration=100, tolerance=1e-8):
"""
Calculate roots using Brent's method.
Parameters
----------
f: function
Objective function.
a: float
Lower bound for the roots.
b: float
Upper bound for the roots.
args: tuple, optional
A... | 56,565 |
def pipeRun(binaryName,
inputStream,
args):
"""Run a program, providing input as the standard input.
Parameters
----------
binaryName : string
Name of the program to run. This will be passed as-is to which()
inputStream : file
Source for the program standard ... | 56,566 |
def onboarding_message(payload):
"""Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future.
"""
event = payload.get("event", {})
# Get the id of the Slack user associated with the incoming event
user_id = event... | 56,567 |
def test_run_query():
"""
Tests that a SaltCacheError is raised when there is a problem writing to the
cache file.
"""
with patch("MySQLdb.connect", MagicMock()) as mock_connect:
expected_calls = call.cursor().execute("SELECT 1;")
mysql_cache.run_query(conn=mock_connect, query="SELEC... | 56,568 |
def square_slerp(xy, base_pts):
"""Transforms a square in [0,1]^2 to a spherical quadrilateral
defined by base_pts, using spherical linear interpolation
Args:
xy: Array, shape [..., 2]. XY coordinates on the square.
base_pts: Array, shape [4, ..., 3]. Coordinates of the square.
... | 56,569 |
def encrypted(text, key):
"""Ceasarchifferskryptering
Args:
text (_str_): Den text som ska krypteras.
key (_int_): Hur många steg ska vi skifta?
"""
encrypted = ""
# loop through the message char by char
for char in text:
# check if it's an upper case letter
... | 56,570 |
def dist(batch_reprs, eps = 1e-16, squared=False):
"""
Efficient function to compute the distance matrix for a matrix A.
Args:
batch_reprs: vector representations
eps: float, minimal distance/clampling value to ensure no zero values.
Returns:
distance_matrix, clamped to ensure no zero values are passed.
""... | 56,571 |
def check_write_entity(entity, authz):
"""Implement the cross-effects of mutable flag and the authz
system for serialisers and API."""
if authz.is_admin:
return True
collection_id = ensure_dict(entity.get("collection")).get("id")
collection_id = entity.get("collection_id", collection_id)
... | 56,572 |
def get_timed_data(wb,sheetname):
"""
Get the data from Tsys vs time data sheet
"""
sheet = wb.get_sheet_by_name(sheetname)
date_nums = date2num(array(get_column(sheet,"Date/Time")))
ras = get_column(sheet,"R.A.")
decs = get_column(sheet,"Decl.")
azs = get_column(sheet,"Az")
elevs ... | 56,573 |
def juniper_items_to_list_of_dicts(module, data):
"""Recursively convert Juniper PyEZ Table/View items to list of dicts.
"""
resources = []
# data.items() is a list of tuples
for table_key, table_fields in data.items():
# sample:
# ('fxp0', [('neighbor_interface', '1'), ('local_inter... | 56,574 |
def unquote(s):
"""Strip single quotes from the string.
:param s: string to remove quotes from
:return: string with quotes removed
"""
return s.strip("'") | 56,575 |
def construct_banded_matrix_from_band(
num_lower_diagonals: int, num_upper_diagonals: int, rect_mat: np.ndarray
) -> np.ndarray:
"""
Constructs a square banded matrix from a representation of the band.
:param num_lower_diagonals: aka ``l``
:param num_upper_diagonals: aka ``u``
:param rect_mat: ... | 56,576 |
def create_jet_model_image(width, j_length, cj_length, max_flux, imsize,
center, gauss_peak=0.001, dist_from_core=24,
gauss_bmaj=10, gauss_e=1., gauss_bpa=0.,
gauss_peak_jet=0.0, dist_from_core_jet=24,
gauss_bmaj... | 56,577 |
def choose_square(empty_squares,
row_candidates, col_candidates, square_candidates):
"""
Iterates through all the squares, and returns the most constrained squares.
Constrained factor is defined as length of intersection of that
square's row, column and encompass... | 56,578 |
def use_network_group(cli, organization: object, group: str = None, spinner: object = None):
"""
Use a network group.
:param spinner: the spinner object from parent flow is used and returned
:param organization: the netfoundry.Organization object representing the current session
:param str group: n... | 56,579 |
def normalize(text):
""" Remove all punctuation for now """
return ''.join('' if c in string.punctuation else c for c in text) | 56,580 |
def zyz_unitary(ϕ, θ, λ):
"""
Unitary decomposed as Rz, Ry, Rz rotations.
Angles are in matrix order, not in circuit order!
"""
return expm(-0.5j*ϕ*pZ)@expm(-0.5j*θ*pY)@expm(-0.5j*λ*pZ) | 56,581 |
def build_model(idkey):
"""
Default parameters:
ImageTransformer(leak=0,
norm_type='batch',
DWS=True,DWSFL=False,
outerK=3,resgroups=1,
filters=[8,16,16],
shuffle=False,
blocks=[2,2,... | 56,582 |
def check_targets(targets):
"""
Test if
1) targets has right type,
2) all columns are present
3) dtype of column peak_label is string
4) rt_min and rt_max are set
Returns a list of strings indicating identified errors.
If list is empty targets is OK.
"""
assert isinstance(targets... | 56,583 |
def p_AB(A, b, L):
"""
Numerator of function f.
"""
a11, a12, a13, a21, a22, a23, a31, a32, a33 = \
A[0, 0], A[0, 1], A[0, 2], \
A[1, 0], A[1, 1], A[1, 2], \
A[2, 0], A[2, 1], A[2, 2]
b1, b2, b3 = b[0, 0], b[1, 0], b[2, 0]
return L**4*(-a11*a22*b3**2 + a11*a23*b2*b3 + a11*a32... | 56,584 |
def disqus_num_replies(context, shortname=''):
"""
Return the HTML/js code which transforms links that end with an
#disqus_thread anchor into the threads comment count.
"""
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'con... | 56,585 |
def infer_flags(bytecode, is_async=None):
"""Infer the proper flags for a bytecode based on the instructions.
Because the bytecode does not have enough context to guess if a function
is asynchronous the algorithm tries to be conservative and will never turn
a previously async code into a sync one.
... | 56,586 |
def visualize(x, y, y_real, save_path, num_samples=10):
"""Given input image x (B,H,W,3) and output image y (B,H,W,3).
Visualize x, y side by side.
"""
fig, axs = plt.subplots(num_samples,3, figsize=(10,num_samples*5))
for i in range(num_samples):
x_temp = ((x+1)/2)[i]
... | 56,587 |
def test_arc_missing_pixelmodel(arm, res, epoch, get_or_create_tmpdir):
"""
Check for the correct behaviour/error handling if PIXELMODEL extn. missing.
"""
rawfilename = 'arc{}*{}*{}[0-9].fits'.format(epoch, res, arm)
# Copy the raw data file into here
tmpsubdir, cal_service = get_or_create_tmpd... | 56,588 |
def form_generic_id(request, id1, template_name=None, form_class=None,
request_url_post=None, request_url_get=None,
success_msg=lambda desc: _('Success'), ask_msg=lambda x: '', confirmation=_('Yes'),
request_url_both=None, ajax_success_status=0, id_key=None):
... | 56,589 |
def cli():
"""
MkDocs - Project documentation with Markdown.
""" | 56,590 |
def gromov_barycenters(N, Cs, ps, p, lambdas, loss_fun, epsilon,
max_iter=1000, tol=1e-9, verbose=False, log=False, init_C=None):
"""
Returns the gromov-wasserstein barycenters of S measured similarity matrices
(Cs)_{s=1}^{s=S}
The function solves the following optimizati... | 56,591 |
def check_elemental_balance(model, r_id, tol=1e-6):
""" Check elemental balance of a reaction in a model.
Notes:
Since some metabolites can have multiple formulas associated, it will check if at least one possible
combination of all formulas results in a balanced reaction.
Args:
mo... | 56,592 |
def BB_flux(E1, E2, T):
"""
Wrapper to compute black body flux given minimum and
maximum energies (in eV) and a black body temperature.
"""
x1 = E1 / (const.k_boltz * T) / const.eV_erg
x2 = E2 / (const.k_boltz * T) / const.eV_erg
A = 2.0 * const.k_boltz**4 * T**4 / (const.h**3 * const.c**... | 56,593 |
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
op.alter_column(
'assessments', 'status',
type_=sa.Enum(
"Not Started",
"In Progress",
"In Review",
"Verified",
"Completed",
"Deprecated",
"Rework Need... | 56,594 |
def asn1_parse(template, data):
"""Parse a data structure according to an ASN.1 template.
@param template: tuples comprising the ASN.1 template
@param data: byte string data to parse
@return: decoded structure
"""
data = bytearray(data)
r = []
i = 0
try:
for t in template:
... | 56,595 |
def open_connection(config):
"""
Use the parameters in the "account" block of the configuration file
to establish an IMAP connection, optionally using SSL.
Returns: imaplib connection object
"""
for i in [ S_HOSTNAME, S_USERNAME, S_PASSWORD ]:
if config.has_option(S_ACCOUNT, i) == False:... | 56,596 |
def muro_24():
"""muro_24"""
check50.run("python3 costear.py").stdin("V-P-V-PV-P-P---V-V-V-V-V", prompt=False).stdout("30", regex=False).exit(0) | 56,597 |
def test_client_config(reporting_server):
"""Verify that client config can be created and reports can be removed.
"""
reporting_server.xmlrpc_open("test_client-1")
# check if status of client is Active
assert reporting_server.clients.get("test_client-1", "status") == "Active"
# add xml report
... | 56,598 |
def _parse_faces(obj_faces):
"""Parse the OBJ encoding of the face attribute index buffers.
A value of -1 in the index array of the texture means the index is
undefined (i.e. no texture is mapped to this face corner).
Returns:
faces
faces_texture
faces_normals
"""
face_... | 56,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.