content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def balanced_outward(source: str, pos: int) -> list:
"""
Returns balanced CSS model: a list of all ranges that could possibly match
given location when moving in outward direction
"""
pool = []
stack = []
result = []
prop = []
prop.append(None) # Get rid of pyLint rant
def scan_... | 1c187c3db71a756ef4e983a850af2a708f021cdf | 3,632,763 |
import struct
def float_2_bytes(f, is_little_endian=False):
"""
:param f:
:param is_little_endian:
:return:
"""
# 小端数据返回
if is_little_endian:
return struct.pack('<f', f)
# 大端数据返回
return struct.pack('>f', f) | cd13cfc7179baf28cda669b2c6fccdce58c63730 | 3,632,764 |
from typing import Union
from typing import List
from typing import Dict
def compute_balanced_class_weights(train_y: Union[np.array, pd.Series, List[any]]
) -> Dict[int, float]:
"""Computes balanced class weight dictionary from train targets.
The key is a index of sorted ... | f74a56cbc051c9eefbe3149d66969c9697a60977 | 3,632,766 |
import cv2
from numpy import zeros, nan
def get_frames_index_range(filename, start, end):
"""
returns a range of frames as numpy array. The indecies comply with scimage
We can then supplement the above table as follows:
Addendum to dimension names and orders in scikit-image
Image type: 2D color ... | 61e478272bff6c154f47f14744a5ca733ae373b1 | 3,632,767 |
import requests
def load_SMI_data_from_Helmholtz():
"""
Downloading SMI topsoil data from helmholtz website
"""
url = "https://www.ufz.de/export/data/2/237851_SMI_L02_Oberboden_monatlich_1951_2018_inv.zip" # noqa: E501
response = requests.get(url)
return response | 854f6b2f398764b7afc89cc3b9ca3b95b2d9a345 | 3,632,769 |
import io
import json
from typing import OrderedDict
def get_yaml_test_method(test_file, expected_load_file, expected_dump_file, regen=False):
"""
Build and return a test function closing on tests arguments and the function
name.
"""
def closure_test_function(self):
with io.open(test_file... | 0c58a5a9f62dd9a343ecdfe1bbdd0fbc2d847698 | 3,632,770 |
def create_mosaic_normal(out_img, maximum):
"""Create grayscale image.
Parameters
----------
out_img: numpy array
maximum: int
Returns
-------
new_img: numpy array
"""
new_img = np.array(
[np.hstack((
np.hstack((
np.flip(out_img[i, :, :], 1).T... | 8a4fa8e64f7c95f0e4c7867626f4c18e23d59250 | 3,632,773 |
def notices_for_cfr_part(title, part):
"""Retrieves all final notices for a title-part pair, orders them, and
returns them as a dict[effective_date_str] -> list(notices)"""
notices = fetch_notices(title, part, only_final=True)
modify_effective_dates(notices)
return group_by_eff_date(notices) | 8454ba063f2f31c57cc91fc5fc5eee771856a54c | 3,632,774 |
def compute_kdtree_and_dr_tractogram(tractogram, num_prototypes=None):
"""Compute the dissimilarity representation of the target tractogram and
build the kd-tree.
"""
tractogram = np.array(tractogram, dtype=np.object)
print("Computing dissimilarity matrices...")
if num_prototypes is None:
... | ff5ee28c628be38e51ac90e0519e2373b52aa739 | 3,632,776 |
def substitute(dictionary, variables, model_context, validation_result=None):
"""
Substitute fields in the specified dictionary with variable values.
:param dictionary: the dictionary in which to substitute variables
:param variables: a dictionary of variables for substitution
:param model_context: ... | 95cafec2bfb3781272f4569becec60cab835d8ca | 3,632,777 |
def batch_query_entrez_from_locus_tag(locus_tag_list):
""" convert a list of locus tags to list of entrez ids
Keyword arguments:
locus_tag_list: a list of locus tags
"""
mapping_dict = {}
id_list = list(set(locus_tag_list))
# initiate the mydisease.info python client
client = get_client(... | 626719688e3164f1b692dc68a3761928f89fcefb | 3,632,779 |
def gather_2d(params, indices):
"""Gathers from `params` with a 2D batched `indices` array.
Args:
params: [D0, D1, D2 ... Dn] Tensor
indices: [D0, D1'] integer Tensor
Returns:
result: [D0, D1', D2 ... Dn] Tensor, where
result[i, j, ...] = params[i, indices[i, j], ...]
Raises:
ValueError... | 81f09fdca8e2330352e839da2f77b7320651bfaa | 3,632,780 |
def updateUserDetails(request, user_id):
"""
Update user details view
depending on is_admin flag, admin profile is either created or deleted.
"""
user = get_object_or_404(User, pk = user_id)
user_serializer = UserSerializer(user, data = request.data)
if user_serializer.is_valid():
... | ade65f5834f0e278221a3b251fdb90567b28d78a | 3,632,781 |
def png_load(pngfile):
"""
Load a PNG file. Returns a numpy matrix with shape (y, x, 3)
png = png_load(pngfile)
pix = png[4, 5]
r, g, b = pix
:param pngfile: the path of the png file
:return: a numpy array of shape (y, x, 3)
"""
#backends = [_pil_load, _pypng_load]
backends = [... | 57670e7cb518b2f4f5c540b9bd9b0f5f227d5d6c | 3,632,782 |
def blackbody_ratio(freq_to, freq_from, temp):
""" Function to calculate the flux ratio between two frequencies for a
blackbody at a given temperature.
Parameters
----------
freq_to: float
Frequency to which to scale assuming black body SED.
freq_from: float
Frequency from which... | 33b34b9906e1ff174df375d49229229acd76a10e | 3,632,783 |
def convert_to_date(col):
"""Convert datetime to date."""
return col.date() | c6ac8febf4751e8f2c2c27fc740de286f2870cbe | 3,632,784 |
import numpy
def orthogonal_projection(all_data, training_data):
"""Projection norm of all_data over space defined by training_data
"""
o, t = subset_PCA(normalize(all_data), normalize(training_data))
norms = numpy.apply_along_axis(numpy.linalg.norm, 1, o)
return norms, o, t | 4102fdd80d61785595fbb5931aaaf5f135d2855b | 3,632,785 |
import json
import traceback
def get_iocs(prefix):
"""
Get the list of available IOCs from DatabaseServer.
Args:
prefix : The PV prefix for this instrument.
Returns:
A list of the names of available IOCs.
"""
#
try:
rawjson = dehex_and_decompress(ChannelAccess.cag... | 475a69dea9acb6f615e652fc14f0535db15ee7a3 | 3,632,786 |
import re
from typing import Counter
def perfect_match(_clipped, _seq, offset = 0, min_nt = 2):
"""
perfect match between clipped reads and breakend sequence
for whole length
min_nt : minimal nt match is better to be larger than 2,
1 nt match is 25% change by random,
2 nt match is 0.0... | 806c0b86d3f97b71c191a2c95fb77ef16bf804e2 | 3,632,787 |
def pareto_selection_diversify_ancestry(population):
"""Return a list of selected individuals from the population.
DANIEL: added comparison of lineage for each added individual. Before an inidividual is added, the lineage is
compared to the already added population. If the similarities are higher th... | 3de3c557cfe9e5a354cf92c960545f5e92bfa92a | 3,632,790 |
from typing import Optional
from textwrap import dedent
def remove_continuous_aggregation_query(viewdef: ViewDefinition) -> Optional[str]:
""" Remove a continuous aggregation policy """
if not viewdef.aggregation_policy:
return None
__query = "SELECT remove_continuous_aggregate_policy('{view_nam... | e36fdce76bc5f74992a4e25be6844be66c9b48f1 | 3,632,791 |
def stop_gradient(x):
"""
Disables gradients for the given tensor.
This may switch off the gradients for `x` itself or create a copy of `x` with disabled gradients.
Implementations:
* PyTorch: [`x.detach()`](https://pytorch.org/docs/stable/autograd.html#torch.Tensor.detach)
* TensorFlow: [`tf.... | 9103b07c78bd9e4922ab8c29c13efa77c8415095 | 3,632,792 |
def get_boundary_elevations(dataset):
"""
:param dataset: netcdf AEM line dataset
:return:
an array of layer top elevations of the same shape as layer_top_depth
"""
return np.repeat(dataset.variables['elevation'][:][:, np.newaxis],
dataset.variables['layer_top_depth'].shape... | a502a1ee923f7e5eb3f1949feb0ab6f6b8d09884 | 3,632,793 |
async def train(
background_tasks: BackgroundTasks,
current_user: User = Depends(auth.get_current_user_and_bot),
):
"""
Trains the chatbot
"""
Utility.train_model(background_tasks, current_user.get_bot(), current_user.get_user(), current_user.email, 'train')
return {"message": "Model... | e222373598c19a83903d701d1c5492c4bc655753 | 3,632,795 |
from datetime import datetime
def get_header():
"""
It returns the Header element of the pmml.
Returns
-------
header :
Returns the header of the pmml.
"""
copyryt = "Copyright (c) 2019 Software AG"
description = "Default Description"
timestamp = pml.Timestamp(datet... | 9051b906d2fc07054f2945be6c2bdaec1e1a0167 | 3,632,796 |
def Identifiers():
"""Returns a "fake" Identifiers field.
Field expects:
"<scheme1>": "<identifier1>",
...
"<schemeN>": "<identifierN>"
"""
return fields.Dict(
# scheme
keys=SanitizedUnicode(
required=True, validate=_not_blank(_('Scheme cannot be bla... | 8357b69bbf706109292db2067fa0b145a9807c81 | 3,632,797 |
def reject_sv(m, s, y):
""" Sample from N(m, s^2) times SV likelihood using rejection.
SV likelihood (in x) corresponds to y ~ N(0, exp(x)).
"""
mp = m + 0.5 * s**2 * (-1. + y**2 * np.exp(-m))
ntries = 0
while True:
ntries += 1
x = stats.norm.rvs(loc=mp, scale=s)
u = sta... | 1516ecc273a7cb1a215604c78a20fbf06e8b704a | 3,632,799 |
import requests
def get_message(message_id):
"""
Shows details for a message, by message ID.
:param message_id: Specify the message ID in the messageId parameter in the URI.
:return: message details formatted in JSON
"""
api_node = "{}messages/{}".format(SPARK_API_URL, message_id)
headers... | abd124781eb8002c2ff27f5c603e9061523ff352 | 3,632,800 |
def testsuite(*args, **kwargs):
"""
Annotate a class as being a test suite
An :py:func:`@testsuite <testsuite>`-annotated class must have one or more
:py:func:`@testcase <testcase>`-annotated methods. These methods will be
executed in their order of definition. If a ``setup(self, env)`` and
``t... | ad1885ff95a43823ee6411c50b03d0d460b5f7f1 | 3,632,801 |
def GetClusterAdjcency(clusters, facedge):
""" Creates sparse cluster adjcent matrix """
# Get boundary clusters for adjcent cluster computation
edgeclus = clusters[facedge]
bmask = edgeclus[:, 0] != edgeclus[:, 1]
bclus = edgeclus[bmask]
a = np.hstack((bclus[:, 0], bclus[:, 1]))
b... | b335d48069bda241208f81b80462097ec5fa927c | 3,632,802 |
def _strip(g, base, orbits, transversals):
"""
Attempt to decompose a permutation using a (possibly partial) BSGS
structure.
This is done by treating the sequence ``base`` as an actual base, and
the orbits ``orbits`` and transversals ``transversals`` as basic orbits and
transversals relative to... | 999f5ed33d895dae446d8aa8eabf58eb82bcb30b | 3,632,803 |
def list_physical_devices(device_type=None):
"""Return a list of physical devices visible to the runtime.
Physical devices are hardware devices locally present on the current machine.
By default all discovered CPU and GPU devices are considered visible. The
`list_physical_devices` allows querying the hardware ... | d9683db64be013df5c258aa6573456005863e74e | 3,632,804 |
def awards_grants_honors(p):
"""Make sorted awards grants and honors list.
Parameters
----------
p : dict
The person entry
"""
aghs = []
for x in p.get('funding', ()):
d = {'description': '{0} ({1}{2:,})'.format(
latex_safe(x['name']),
x.get('currency... | c1b0f2626109fe59ca71654a86f46e34a1da8a7d | 3,632,805 |
import re
from datetime import datetime
def string_to_time(course_time): # '二1-2 三3-4'
"""
:param course_time: '二1-2'
:return: 十周或若干周的上课下课时间 [{start_time, end_time},...]
"""
course_times = []
course_minutes = [0, 55, 120, 175, 250, 295, 370, 425, 480, 535, 600, 655, 710]
available_weeks... | be4722163f776d44bdf80257664d25be8da0b571 | 3,632,806 |
def get_parameters(model: str, group_id: int = 0,
t_in: int = 0, t_out: int = 0, p_th: int = 0) -> pd.DataFrame:
"""
Loads the content of the database for a specific heat pump model
and returns a pandas ``DataFrame`` containing the heat pump parameters.
Parameters
----------
... | 041d55d2ed839413a8213f3c4c8cbdb09759b933 | 3,632,807 |
def gauss(x, mu, var, a=1):
"""
Gauss distribution value at x
:param x:
:param mu: expected value
:param var: variance, (sigma^2)
:param a: coefficient in cases total area != 1
:return:
"""
return a/(np.sqrt(2*var*np.pi)) * np.exp(- (x-mu)**2/(2*var)) | 6b0843ab4372a7f3f75fd709fbdc32be826a2626 | 3,632,808 |
def create_subnet(client, cidr_blk, vpc_id):
"""
Create a subnet in the given CIDR block and VPC using client.
:param client: a valid boto3 EC2 client.
:param cidr_blk: a valid IP range in the format 'a.b.c.d/XX'
:type cidr_blk: str
:param vpc_id: the VpcID of the Databricks VPC.
:type vpc_i... | ff34f2c2ac89edcbc568a80890c90ca0b3616c09 | 3,632,810 |
import math
def get_hertz_feed(reference_timestamp, current_timestamp, period_days, phase_days, reference_asset_value, amplitude):
"""
Given the reference timestamp, the current timestamp, the period (in days), the phase (in days), the reference asset value (ie 1.00) and the amplitude (> 0 && < 1), output the curre... | 4da9ae370e4a68119a8fe64b2442275f249d5ed2 | 3,632,811 |
def find_list_in_list(reference_array, inp):
"""
---------------------------------------------------------------------------
Find occurrences of input list in a reference list and return indices
into the reference list
Inputs:
reference_array [list or numpy array] One-dimensional reference l... | 7a4db527c6f73dcaf3436afa46317ffe443bc5bc | 3,632,812 |
import torch
def accuracy(output, target):
"""Computes the accuracy over the top predictions"""
with torch.no_grad():
batch_size = target.size(0)
_, preds = torch.max(output.data, 1)
correct = (preds == target).sum().item()
return correct/batch_size | 8f4dfde0e00f12d889b403265d50a379930ba3c8 | 3,632,813 |
from bs4 import BeautifulSoup
def get_absolute_url(body_string: str):
"""Get absolute manga mangadex url"""
parser = BeautifulSoup(body_string, 'html.parser')
for link_elements in parser.find_all('link'):
# aiming for canonical link
try:
rel = link_elements.attrs['rel']
... | 35ca71dba04c243ab7c4cfa4893326ddeb480336 | 3,632,814 |
def panel_grid(hspace, wspace, ncols, num_panels):
"""Init plot."""
n_panels_x = min(ncols, num_panels)
n_panels_y = np.ceil(num_panels / n_panels_x).astype(int)
if wspace is None:
# try to set a wspace that is not too large or too small given the
# current figure size
wspace =... | 4da67af64bfcead3309f3ba3622d441301fcfbf6 | 3,632,815 |
import scipy.linalg as LA
import re
def ma_rhythm(ppath, recordings, ma_thr=20.0, min_dur = 160, band=[10,15],
state=3, win=64, pplot=True, pflipx=True, pnorm=False):
"""
calculate powerspectrum of EEG spectrogram to identify oscillations in sleep activity within different frequency bands;
o... | f5fee2d602f5f186f0aaa881938a396ab5c9d977 | 3,632,816 |
from typing import Dict
async def find_file_ids(paths: Dict[str, int]) -> Dict[str, str]:
"""Parameter 1: dict of "file path" -> file size."""
fpaths = [p for p in paths.keys() if p]
if not fpaths:
return {}
query = "select path, size, file_id from file_ids where path in ({})".format(
... | c43567330b8a4ca7430dfbb337df518831c92a6f | 3,632,817 |
def select_curve(message='Select one curve.'):
"""Select one curve in the Rhino view.
Parameters
----------
message : str, optional
Instruction for the user.
Returns
-------
System.Guid
The identifer of the selected curve.
"""
return rs.GetObject(message, preselect... | 65952f2f2ea76c196ec55db4766de0d07cfe1b5b | 3,632,818 |
def fetch_cert(url: str) -> Certificate:
"""
Fetch a certificate from a URL.
:param url: the URL to the certificate file
:return: a certificate object
"""
with fetch_file(url) as cert_file:
return ssl_serializer.deserialize_cert(cert_file.read()) | 3a18eca6e5c8e51ad3ca96860972ead48b74c029 | 3,632,819 |
def import_execute(request, extra_context={}):
"""
This is the view that actually processed the import based on the options
set by the user in import_options (above).
In addition to calling the appropriate import function (see below) this
view also prepares the status information dictionary that will be used
by... | 0850d79c1d7f23b848e2e52cf7322485122f0e98 | 3,632,820 |
def get_default_view(source_type, source_name, menu_name=None,
source_transform=None, viewer_transform=None, **kwargs):
""" Create default view metadata for a single source.
Arguments:
source_type [str] - type of the source, either "image" or "segmentation"
source_name [str... | 056eb43104acea60c51a84da06aee036a1127c46 | 3,632,821 |
def PullToBrepFace(curve, face, tolerance, multiple=False):
"""
Pull a curve to a BrepFace using closest point projection.
Args:
curve (Curve): Curve to pull.
face (BrepFace): Brep face that pulls.
tolerance (double): Tolerance to use for pulling.
Returns:
Curve[]: An a... | ac8ac6e5de10b7012c4650915fd5af1de52659f4 | 3,632,822 |
def floatX(X):
""" Change data to theano type """
return np.asarray(X, dtype=theano.config.floatX) | ee2e8863fcdc5475cef461b75c557f1e96a73457 | 3,632,823 |
def primes_sieve3(n):
""" Sieve method 3: Returns a list of primes < n
>>> primes_sieve3(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""
# begin half-sieve, n>>1 == n//2
sieve = [True] * (n>>1)
upper = int(n**0.5)+1
fo... | 629942c738eb08624672e20af1923cf78d3dcec7 | 3,632,824 |
def kl_mvg_diag(
pm: jnp.ndarray, pv: jnp.ndarray, qm: jnp.ndarray, qv: jnp.ndarray
) -> jnp.ndarray:
"""
Kullback-Leibler divergence from Gaussian pm,pv to Gaussian qm,qv.
Also computes KL divergence from a single Gaussian pm,pv to a set
of Gaussians qm,qv.
Diagonal covariances are assumed. Di... | c0f28495a2b8c18b8563d66152dc62019b3f2e60 | 3,632,826 |
from typing import Any
def isstring(var:Any, raise_error:bool=False) -> bool:
"""Check if var is a string
Args:
var (str): variable to check
raise_error (bool, optional): TypeError raised if set to `True`. Defaults to `False`.
Raises:
TypeError: raised if var is not string
R... | 897c43539099c3d0b9b38abccce88869a90b9d9e | 3,632,827 |
def run_simulation(solution, times, conditions=None,
condition_type = 'adiabatic-constant-volume',
output_species = True,
output_reactions = True,
output_directional_reactions = False,
output_rop_roc = False,
... | 352516d021b17589d60de5645076c25258df5e9c | 3,632,828 |
def first_second_person_density(doc):
"""Compute density of first|second person.
:param doc: Processed text
:type doc: Spacy Doc
:return: Density 1,2 person
:rtype: float
"""
return first_second_person_count(doc) / word_count(doc) | 29fa561361e1d3b4846accf206103fd3a99d774f | 3,632,829 |
def create_map(*columns):
"""
Creates a new map column. The input columns must be grouped as key-value pairs, e.g.
(key1, value1, key2, value2, ...). The key columns must all have the same data type, and can't
be null. The value columns must all have the same data type.
"""
return _with_expr(exp... | 40d09e0f5c16c935d741ef0c5cff2a07f62fbaa9 | 3,632,830 |
import six
import logging
def for_review_request_field(context, nodelist, review_request_details,
fieldset):
"""Loops through all fields in a fieldset.
This can take a fieldset instance or a fieldset ID.
"""
s = []
request = context.get('request')
if isinstance(... | 592092f0c6909b18fb92309c72ced4d8c0ee8d7b | 3,632,831 |
import warnings
def bayesian_optimization(f, gpr, acq_func, bounds, max_iter = None,
prop_kwargs = None, minimize = None,
verbose = False, noise=0.0):
"""
Implement Bayesian optimization to maximize or minimize a scalar function.
Arguments
-----... | 6f1eab7d21c6385532151656a9b9a80e78b78fa0 | 3,632,832 |
def to_nearest(num, tick_size):
"""
Given a number, round it to the nearest tick. Very useful for sussing float error
out of numbers: e.g. toNearest(401.46, 0.01) -> 401.46, whereas processing is
normally with floats would give you 401.46000000000004.
Use this after adding/subtracting/multiplying nu... | 662a4e0cb2956161f5b776bc65cb6c35e32aaf32 | 3,632,833 |
def placeholder(value, token):
""" Add placeholder attribute, esp. for form inputs and textareas """
value.field.widget.attrs["placeholder"] = token
return value | 16bb46a6e92c3a59972589ed28315e681a7580f3 | 3,632,835 |
def create_xml_element(connection, token, name):
"""A helper function creating an etree.Element with the necessary
attributes
:param name: The name of the element
:returns: etree.Element
"""
return etree.Element(
name,
nsmap={None: XHTML_NAMESPACE},
shop_id=connection.s... | 00427ffa2ce582674d78cf6597624c0bbe29edfc | 3,632,836 |
from typing import Optional
def generate_categorical_dataframe(
sm: nx.DiGraph,
n_samples: int,
distribution: str = "logit",
n_categories: int = 3,
noise_scale: float = 1.0,
intercept: bool = False,
seed: int = None,
kernel: Optional[Kernel] = None,
) -> pd.DataFrame:
"""
Gener... | 5cd72c10e6fdede53b2051eef2bdac82045ed7af | 3,632,837 |
def bias_cross_func(data, *args, **kwargs):
"""
生成一条年利率 4% 的模拟货币基金基准线
支持QA add_func,第二个参数 默认为 indices= 为已经计算指标
理论上这个函数只计算单一标的,不要尝试传递复杂标的,indices会尝试拆分。
"""
if (ST.VERBOSE in data.columns):
print('Phase bias_cross_func', QA_util_timestamp_to_str())
# 针对多标的,拆分 indices 数据再自动合并
code ... | 7b89c7ab3be1c6d2079dd9cbbf1f0dde8044b042 | 3,632,838 |
from typing import Optional
def login(uid: str, pwd: str) -> Optional[Admin]:
"""
登录
:return:
"""
sql = '''SELECT admins.id, admins.uid, admins.is_super FROM admins WHERE uid=%s AND pwd=%s LIMIT 1'''
connect = get_connect()
with connect.cursor() as cursor:
cursor.execute(sql, (uid... | 1c207ab29b6d793c7ac513cf901d5c9588c566d4 | 3,632,839 |
import aiohttp
async def catch_uniqueness_error(
request: aiohttp.web.Request, handler: swift_browser_ui.common.types.AiohttpHandler
) -> aiohttp.web.Response:
"""Catch excepetion arising from a non-unique primary key."""
try:
return await handler(request)
except asyncpg.exceptions.UniqueViola... | 177faf3497fa8d048b6fc1c1dc8058ed78785cf4 | 3,632,840 |
def df_canonicalize_from_smiles(df, smiles_col: str, include_stereocenters=True)->pd.Series:
"""
Canonicalize the SMILES strings with RDKit.
Args:
df: dataframe
smiles_col: column name in df
include_stereocenters: whether to keep the stereochemical information in the canonical SMILES... | 846c01b71201411ed36d5270b83f8f32d832e9f4 | 3,632,841 |
from re import T
def mse_loss(y, pred, w):
""" Regression loss function, mean squared error. """
return T.mean(w * (y - pred) ** 2) | bb6f127fd69dcbaa1e64dd811caa0b356de9f741 | 3,632,842 |
def compute_gradients(
state,
supermatrices,
supergradients,
super_oplabels,
observables,
observables_labels,
num_discretes,
):
"""
Compute the gradients of a symplectic acyclic_graph for the cost function
<psi|sum_n H_n |psi>, with H_n the element at `observables[n]`, acting on
... | 378cbc6ee3e147ca67d62edbb1929459dfb2993a | 3,632,843 |
def _cs_count_top_bottom(fragments):
"""Counting: top and bottom of the entire core sample"""
cs_top, cs_bottom = 1e10, 0
for fragment in fragments:
cs_top = min(cs_top, float(fragment['top']))
cs_bottom = max(cs_bottom, float(fragment['bottom']))
return cs_top, cs_bottom | 3b9a98993a837ff7c08980f644abbb6aad13f908 | 3,632,845 |
def get_index_from_filename(
file_name: str
) -> str:
"""
Returns the index of chart from a reproducible JSON filename.
:param file_name: `str`
The name of the file without parent path.
:returns: `str`
The index of the chart (e.g., 1) or an empty string.
"""
assembled_ind... | 2cddcbcd9bf5079d58c75f19b5d2bf5b44ded173 | 3,632,846 |
def get_box_transformation_matrix(box):
"""
Create a transformation matrix for a given box pose.
"""
# tx,ty,tz = box.center_x,box.center_y,box.center_z
tx,ty,tz = box[0], box[1], box[2]
c = np.cos(box[6])
s = np.sin(box[6])
sl, sw, sh = box[3], box[4], box[5] # 这里如果读取的是 det3d 的 det... | dae86d3260d0463d8e974c4fdba055781b520c93 | 3,632,847 |
def get_redirect_target():
"""
获取跳转目标
:return:
"""
for target in request.args.get('next'), request.referrer:
if not target:
continue
if is_safe_url(target):
return target | 2ff373be5ad9d44124304454a5f89dd7d1f7d939 | 3,632,848 |
def mixer_carrier_cancellation(SH, source, MC,
chI_par, chQ_par,
frequency: float=None,
SH_ref_level: float=-40,
init_stepsize: float=0.1,
x0=(0.0, 0.0),
... | 792f998cf2382d889ecfc2e6335c55a805d234df | 3,632,849 |
def create_single_wall_box(box_dimensions):
"""
width, depth, height, thickness,
fold_margin, wing_width
returns ShapeArray
"""
width = box_dimensions['width']
height = box_dimensions['height']
depth = box_dimensions['depth']
thickness = box_dimensions['thickness']
fold_margin ... | d7ee5700cebd083bf6800d636563d08fb1e645d3 | 3,632,850 |
from typing import Optional
def correct_start_cell_number(
start_cell_number: Optional[int], mcnp: Optional[str]
) -> int:
"""Define cell number to start with on output to accompanying excel.
Args:
start_cell_number: number from command line or configuration, optional.
mcnp: MCNP file nam... | c5fa474970be0f4f23c02ef6dead6f5028c3fc88 | 3,632,851 |
from typing import List
def convert_labels_to_one_hot(
label_list: List[List[str]], label_dict: Dictionary
) -> List[List[int]]:
"""
Convert list of labels (strings) to a one hot list.
:param label_list: list of labels
:param label_dict: label dictionary
:return: converted label list
"... | 856ae66a591ec7c32bbd5cf91e97ff87852f5b83 | 3,632,852 |
def create(container_dir, distro_config):
"""Create a container using chocolatey."""
return _fetch_choco(container_dir, distro_config) | e342101c8723b62e79b7f455e5444f2e214d9621 | 3,632,853 |
def notas(*num, sit=False):
"""
Essa função cria um dicionário que guarda várias informações sobre o boletim de um aluno
:param num: lista de notas do aluno
:param sit: situação do aluno (aprovado, reprovado, recuperação)
:return: retorna o dicionário completo
"""
boletim = {}
boletim['Q... | a154d39be15018ce764e71c7bc97d9b4b25575df | 3,632,854 |
from operator import concat
def columnize(student: 'StudentResult',
longest_user: str,
max_hwk_num: int,
max_lab_num: int,
max_wst_num: int,
highlight_partials: bool = True):
"""Build the data for each row of the information table"""
name =... | 5d4d2c20713883e6380d16b1e55ea72487b4e2d5 | 3,632,855 |
from typing import Iterable
from typing import Callable
from typing import Iterator
from typing import Tuple
def relate_one_to_many(
lhs: Iterable[Left],
rhs: Iterable[Right],
lhs_key: Callable[[Left], Key]=DEFAULT_KEY,
rhs_key: Callable[[Right], Key]=DEFAULT_KEY,
) -> Iterator[Tuple[Left, Iterator[Ri... | d49906eb86f645093b2b75f3a84f5a9f8faaba8d | 3,632,856 |
def cut(vid, bx, by):
"""Scales image without changing aspect ratio but instead growing to at least the size of box bx/by."""
ix = vid.get(cv.CAP_PROP_FRAME_WIDTH)
iy = vid.get(cv.CAP_PROP_FRAME_HEIGHT)
if bx / float(ix) > by / float(iy): # fit to width
scale_factor = bx / float(ix)
... | 7e66f170b54bc421389609efd9ce88f3b8c05b41 | 3,632,857 |
def find_region_candidates_volume(volume, peak_threshold, shifts = (0, 0)):
"""
:param volume:
:param peak_threshold:
:param shifts: (x, y)
:return:
"""
results = list()
for i in range(volume.shape[-1]):
slice = volume[..., i].copy()
cv2.GaussianBlur(slice, (3, 3), 0.4, ... | c0f61a6907bb1eb326daafc22274d90f281b5255 | 3,632,860 |
def summarize(text):
""" Summarizes some text
"""
if len(text) > 20:
summary = text[0:10] + " ... " + text[-10:]
else:
summary = text
summary = summary.replace("\n", "\\n")
return summary | 5c37f7a50e2b533bf3e05b598ce68b2c4de88fe1 | 3,632,861 |
from datetime import datetime
def create_nic(fco_api, cluster_uuid, net_type, net_uuid, vdc_uuid, name=None):
"""
Create NIC.
:param fco_api: FCO API object
:param cluster_uuid: Cluster UUID
:param net_type: Network type; currently recommended 'IP'
:param net_uuid: Network UUID
:param vdc... | 4709f215662bed8a1c76920ca0d5d49e501a50a6 | 3,632,862 |
def clean_logger(name = settings["app_name"]):
"""
Removes all handlers associated with a given logger
Parameters
----------
name : string
name of the logger
Returns
-------
logger.logger
"""
logger = lg.getLogger(name)
handlers = logger.handlers
for handler i... | fee9743c57ef054a9dbbd53bf8ab0dcd1d2801bd | 3,632,863 |
def model_from_json(json_string, custom_objects=None):
"""Parses a JSON model configuration string and returns a model instance.
Usage:
>>> model = tf.keras.Sequential([
... tf.keras.layers.Dense(5, input_shape=(3,)),
... tf.keras.layers.Softmax()])
>>> config = model.to_json()
>>> loaded_model ... | 3e929b5f2c07cb214edea5ed042fe0e49f0971ad | 3,632,864 |
def get_stock_stream(symbol, params={}):
""" gets stream of messages for given symbol
copied from api.py (found on GitHub)
"""
all_params = ST_BASE_PARAMS.copy()
return R.get_json(ST_BASE_URL + 'streams/symbol/{}.json'.format(symbol), params=all_params) | f6b5aa3601473eba52f3a736b4befa5ae1163be7 | 3,632,865 |
def get_free_swap_memory() -> int:
"""Get the free swap memory size in bytes."""
return swap_memory().free | 141313acb49baff1a25d837daec73048b9accd53 | 3,632,866 |
def get_application(application_id: str = None):
"""
Returns an application.
:param application_id: The numeric ID of the application you're interested in.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getApplication', application_id=application_id) | 53142b0ac238876f52e26e00f3af190643443671 | 3,632,867 |
def sexastr2deci(sexa_str):
"""Converts as sexagesimal string to decimal
Converts a given sexagesimal string to its decimal value
Args:
A string encoding of a sexagesimal value, with the various
components separated by colons
Returns:
A decimal value corresponding to the sexagesimal... | 46a9d8752b05b1579ecc2b85d94c28613a08ab3c | 3,632,868 |
def run_extractor_on_dataset(dataset_path):
"""Run the feature extractor pipeline on the target dataset then consolidate results.
Note: This function runs on all images within SUB DIRECTORIES of the dataset path.
Output will be a single features JSON for each frame ID. All emitted individual image
fea... | 79b816110cca7bf5ecf258f8380bbf285f0b9018 | 3,632,869 |
from typing import Callable
from typing import Mapping
def run_pipeline_func_on_cluster(
pipeline_func: Callable,
arguments: Mapping[str, str],
run_name: str = None,
experiment_name: str = None,
kfp_client: Client = None,
pipeline_conf: dsl.PipelineConf = None,
):
"""Runs pipeline on KFP-e... | c44069b016706f5cdcbab1fd9319cf96ef4f2dfa | 3,632,870 |
def reverb2mix_transcript_parse(path):
"""
Parse the file format of the MLF files that
contains the transcripts in the REVERB challenge
dataset
"""
utterances = {}
with open(path, "r") as f:
everything = f.read()
all_utt = everything.split("\n.\n")
for i, utt in enumerate... | c8a1aa0c8a4d0dec6626cf8e9d2491336ee42d5a | 3,632,872 |
def extract_qa_bits(qa_band, start_bit, end_bit):
"""Extracts the QA bitmask values for a specified bitmask (starting
and ending bit).
Parameters
----------
qa_band : numpy array
Array containing the raw QA values (base-2) for all bitmasks.
start_bit : int
First bit in the bit... | 523dc1ee149af5c5e9a494b5fe3a3c14bc3186d2 | 3,632,873 |
def is_scalar(v,value=None):
"""Returns True if v evaluates to a scalar. If value is provided, then
returns True only if v evaluates to be equal to value"""
if isinstance(v,Variable):
if not v.type.is_scalar(): return False
return value is None or v.value == value
elif isinstance(v,Cons... | 831d539c634d812b42a1c9716aab994145bf8cd2 | 3,632,874 |
def cluster_homogeneity(df:pd.DataFrame, edge_type="Edge", iteration_type="Iteration"):
"""
# Create Graph
from soothsayer_utils import get_iris_data
df_adj = get_iris_data(["X"]).iloc[:5].T.corr() + np.random.RandomState(0).normal(size=(5,5))
graph = nx.from_pandas_adjacency(df_adj)
graph.nodes... | e077ff0f3e1660ea5788880282fbc3862b5737df | 3,632,875 |
import json
def to_json_for_storage(desc: SomeRunDescriber) -> str:
"""
Serialize the given RunDescriber to JSON as a RunDescriber of the
version for storage
"""
return json.dumps(to_dict_for_storage(desc)) | cdda5322acf1da6e704bdea47cd1cee9019019ad | 3,632,876 |
def astar(graph, start, end, heuristic={}):
"""
Performs A-star search to find the shortest path from start to end
Args:
graph (gennav.utils.graph): Dictionary representing the graph where keys are the nodes
and the value is a list of all neighbouring nodes
start (gennav.utils.R... | 90c60cc7b14e7d223889316a49223450fa4806f4 | 3,632,877 |
def extractFileName(form, id, cleanup=True, allowEmptyPostfix=False):
"""Extract the filename of the widget with the given id.
Uploads from win/IE need some cleanup because the filename includes also
the path. The option ``cleanup=True`` will do this for you. The option
``allowEmptyPostfix`` allows to ... | 8aeccba3be2f4a4de781efaff88bf1835645c293 | 3,632,878 |
def find_pointing_start(asn_table_name):
"""
Parameters:
asn_table_name : string
For example, 'gs2-01-189-g102'. Targname-visit-PA-filter
Returns:
0 : if visit starts with direct image
1 : if visit starts with grism
Outputs:
"""
# Parse out the asn tab... | ee700ddc8903914956c42ec82763a2463186e38b | 3,632,879 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.