content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def countby(seq, key):
"""
Description
----------
Create a dictionary with keys composed of the return value of the funcion/key\n
applied to each item in the sequence. The value for each key is the number of times\n
each key was returned.
Parameters
----------
seq : (list or tuple o... | 58,900 |
def Boxplot(Metric, Names, Proof, Proof_Num, Palette):
"""
Plot the data in the form a boxplot
OUTPUT
------
It displays the boxplot of all the MD simulations and the metric
"""
if Palette == []:
# Create the color palette for the different MD simulations randomly
for i in... | 58,901 |
def datefmt_to_regex(datefmt):
"""
Convert a strftime format string to a regex.
:param datefmt: strftime format string
:type datefmt: ``str``
:returns: Equivalent regex
:rtype: ``re.compite``
"""
new_string = datefmt
for pat, reg in PATTERN_MATCHNG:
new_string = new_string.... | 58,902 |
def hsv_decomposition(image, channel='H'):
"""Decomposes the image into HSV and only returns the channel specified.
Args:
image: numpy array of shape(image_height, image_width, 3).
channel: str specifying the channel. Can be either "H", "S" or "V".
Returns:
out: numpy array of shap... | 58,903 |
def resize_images(X, y):
"""
This method resizes the images to height=66, widht=200
No. of Output Images = No. of Input Images
"""
images = []
steering_angles = []
for i in range(len(X)):
resized = cv2.resize(X[i], (200, 66))
images.append(resized)
steering_angles.app... | 58,904 |
async def async_turn_on(hass, entity_id=None):
"""Turn on specified media player or all."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, data) | 58,905 |
def spline_area(s_tuple, N=None):
"""Compute area of spline s discretized in N segments."""
# to get a good approx. take 3 x the number of knots
if N is None:
N = 3 * len(s_tuple[0])
c = splev(np.linspace(0, 1, N, endpoint=False), s_tuple)
cprm = splev(np.linspace(0, 1, N, endpoint=False),... | 58,906 |
def kgtk_date_hour(x):
"""Return the hour component of a KGTK date literal as an int.
"""
if isinstance(x, str):
m = KgtkValue.lax_date_and_times_re.match(x)
if m:
return int(m.group('hour')) | 58,907 |
def conv3d_blk(x, shape, stride, phase):
"""conv3d block with ReLu"""
W = tf.get_variable("W", shape=shape, initializer=tf.contrib.layers.xavier_initializer())
b = tf.get_variable("b", shape=shape[4], initializer=tf.constant_initializer(0.1))
return conv3d(tf.nn.relu(tf.contrib.layers.batch_norm(x, is_t... | 58,908 |
def test_numeric_plots_unit_1():
"""Unit test case 1"""
actual_obj = numeric_plots(df())
# Unit test case 1:
expected_1 = 5
actual_1 = len(actual_obj.spec._kwds['data'].columns)
assert expected_1 == actual_1, "The number of columns in the dataframe are incorrect." | 58,909 |
def check_bias(bias: TensorParams):
"""This function checks whether the bias values fit in 40 bits"""
if bias and bias.dtype == np.dtype("int64"):
valid = all(len(bin(bias_value)[2:]) <= 40 for bias_value in bias.values)
return valid
return True | 58,910 |
def build_parser():
"""Build the cli args parser."""
parser = argparse.ArgumentParser(
description=f"""Kubesplit v{__version__}
Split a set of Kubernetes descriptors to a set of files.
The yaml format of the generated files can be tuned using the same\
parameters ... | 58,911 |
def get_collection(args, mlog):
"""Get collection and print messages"""
from mtga.models.card import Card
try:
for (mtga_id, card, count) in mlog.get_collection():
if isinstance(card, MtgaUnknownCard):
print('Info: Unknown card in collection: %s (Will fetch it from Scryf... | 58,912 |
def l2normalize(v, eps=1e-12):
"""l2 normalize the input vector.
Args:
v: tensor to be normalized
eps: epsilon (Default value = 1e-12)
Returns:
A normalized tensor
"""
return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps) | 58,913 |
def check_password_by_hash(pw, hashed_pw):
"""Check a password against a salted hash"""
expected_hash = hashed_pw.encode('utf8')
return bcrypt.checkpw(pw.encode('utf8'), expected_hash) | 58,914 |
def empty_ang():
"""Return an empty angle tensor representing 1 residue-level pad character."""
dihe_padding = np.zeros(NUM_ANGLES)
dihe_padding[:] = GLOBAL_PAD_CHAR
return dihe_padding | 58,915 |
def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float:
"""Return upload total data."""
return round(status.bytes_sent * 8 / 1024 / 1024 / 1024, 1) | 58,916 |
def create_index(strings, method='fb-trie'):
"""Create a searchable index for a list of strings.
Parameters
----------
strings : iterable of str
Strings to index
method : {'fb-trie', 'trie'}
Index method to use. This affects memory usage and
query run time.
'fb-trie... | 58,917 |
def register(character_type: str, creator_fn: Callable[..., GameCharacter]) -> None:
"""Register a new game character type."""
character_creation_funcs[character_type] = creator_fn | 58,918 |
def validation_curve(model, X, y, param, rang, cv):
"""
:param model: Modelo a ser avaliado.
:param x: Variáveis independentes de treino.
:param y: Variavel dependente de treino.
:param param: Parametro do modelo a ser avaliado.
:param rang: Espaço de hipotese do parametro que esta sendo a... | 58,919 |
def calculate_factor_initial_size(n, key):
"""
Calculate different initial embedding sizes by a chosen factor.
:param n: Number of nodes in the graph
:param key: The factor- for example if key==10, the sizes will be n/10, n/100, n/100, .... the minimum is 100 nodes
in the initial embedding
:retu... | 58,920 |
def addAxes(pos, NixTopMargin=False, NixBottomMargin=False):
"""Add axes according the pos list, and return the axes handle.
# margin indices 0,1,2,3 for each panel (left, right, bottom, top)
"""
rect = pos[0]+margins[0], pos[1]+margins[2], pos[2]-margins[0]-margins[1], pos[3]-margins[2]-margins[3]
... | 58,921 |
def main(reference_rmouth_outflows_filename, data_rmouth_outflows_filename,
grid_type='HD',param_set='default',flip_data_field=False,
rotate_data_field=False,flip_ref_field=False,rotate_ref_field=False,**grid_kwargs):
"""Top level river mouth matching routine. Deals with file handling"""
refer... | 58,922 |
def test_lsb():
"""LCB property"""
# init
bf = BitField(lsb=0x5)
assert bf.lsb == 0x5
bf = BitField(lsb='0x5')
assert bf.lsb == 0x5
# set
bf.lsb = 0x3
assert bf.lsb == 0x3
bf.lsb = '0x6'
assert bf.lsb == 0x6
# set wrong
with pytest.raises(ValueError):
... | 58,923 |
def render(config_file, output_file):
"""Console script for sqldoc"""
parser_map, renderer_map = build_plugin_maps()
# load job
job = config.load(config_file)
parser_class = parser_map[job.parser.name]
parser = parser_class(job.parser.config)
renderer_class = renderer_map[job.renderer.name]... | 58,924 |
def cast(x, dtype, same_kind=True):
"""
Parameters
----------
x: scalar, array or Theano variable
The variable to cast
dtype: str
The type to which cast the variable. One of
- 'int8'
- 'int16'
- 'int32'
- 'int64'
- 'uint8'
- 'uint16'
... | 58,925 |
def verify_routing_routes(device,
addr_list,
protocol,
contains,
max_time=60,
check_interval=10):
"""Verifies address list agianst 'show route protocol {protocol}'
Args:
add... | 58,926 |
def import_csv(cursor: sqlite3.Cursor, csvfile: str, batch: int = 1000,
verbose: bool = False) -> None:
"""Import a given USDA FoodData Central CSV file.
Assumes that the schema has already been created."""
table = os.path.basename(csvfile)[:-4]
rows = []
with open(csvfile, newline=... | 58,927 |
def group(db):
"""Create group for the tests."""
group = GroupFactory()
db.session.commit()
return group | 58,928 |
def is_iterable(value):
""" Verifies the value is an is_iterable
:param value: value to identify if iterable or not.
"""
try:
iterable_obj = iter(value)
return True
except TypeError as te:
return False | 58,929 |
def remove_stop_words(tokenized_headline_list):
"""
Takes list of lists of tokens as input and removes all stop words.
"""
filtered_tokens = []
for token_list in tokenized_headline_list:
filtered_tokens.append([token for token in token_list if token not in set(stopwords.words('english'))])
return filtered_toke... | 58,930 |
def set_agent_config(sampling_interval_seconds=1, cpu_limit_percentage=DEFAULT_CPU_LIMIT_PERCENTAGE):
"""
Reporting interval needs to have a minimum value and cpu_limit_percentage is used later in tests;
the other values can be None as we are not using them here.
"""
return AgentConfiguration.set(
... | 58,931 |
def rw_normalize(A):
"""
Random walk normalization: computes D^⁼1 * A.
Parameters
----------
A: torch.Tensor
The matrix to normalize.
Returns
-------
A_norm: torch.FloatTensor
The normalized adjacency matrix.
"""
degs = A.sum(dim=1)
degs[degs == 0] = 1
r... | 58,932 |
def check_serializable(cls):
"""Throws an exception if Ray cannot serialize this class efficiently.
Args:
cls (type): The class to be serialized.
Raises:
Exception: An exception is raised if Ray cannot serialize this class
efficiently.
"""
if is_named_tuple(cls):
... | 58,933 |
def get_all_stock_fundamentals():
"""
Returns a dict mapping instrument id to stock fundamentals
"""
db = get_db()
fundamentals_by_instrument_id = dict()
all_fundamentals = list(db["fundamentals"].find())
for f in all_fundamentals:
fundamentals_by_instrument_id[f["instrument_id"]] ... | 58,934 |
def get_assets_zip_provider():
"""Opens stock TensorBoard web assets collection.
Returns:
Returns function that returns a newly opened file handle to zip file
containing static assets for stock TensorBoard, or None if webfiles.zip
could not be found. The value the callback returns must be closed. The
... | 58,935 |
def _binary_operator_expression(expression, expression_right):
"""Builds the IR for a chain of equal-precedence left-associative operations.
_binary_operator_expression transforms a right-recursive list of expression
tails into a left-associative Expression tree. For example, given the
arguments:
6, (T... | 58,936 |
def subtracao(inteiros):
"""A função `subtracao` deve receber um *array* de números inteiros, e
retornar a subtração de todos os elementos em sequência. Por exemplo,
subtracao([3,2,1]) deve retornar 0, e subtracao([10,2,3]) deve retornar 5.
Se a lista for vazia, deve retornar zero.
>>> subtracao([3... | 58,937 |
def extract_diacritics(join=True):
"""
Extracts unique diacritics from a pasted column of IPA transcriptions.
Args:
join : specifies joining of diacritics in the same transcription.
Default True.
Requires:
regex module as re
reDiac()
Returns li... | 58,938 |
def asbytes(s: Literal["v3"]):
"""
usage.scipy: 1
"""
... | 58,939 |
def announce_work(work_on_population):
"""Handle the worker counter."""
def wrapper(
analysis_id: str, t: int, redis: StrictRedis,
kill_handler: KillHandler, **kwargs):
# notify sign up as worker
n_worker = redis.incr(idfy(N_WORKER, analysis_id, t))
logger.info(
... | 58,940 |
def round(arg: ir.NumericValue, digits: int | None = None) -> ir.NumericValue:
"""Round values to an indicated number of decimal places.
Returns
-------
rounded : type depending on digits argument
digits None or 0
decimal types: decimal
other numeric types: bigint
digits non... | 58,941 |
def insert(tabela, *args):
""" Função que recebe como parâmetro obrigatório o nome da tabela a ser consultada,
e os dados para inserção como *args e os insere na tabela escolhida """
banco = Banco()
banco.connect()
banco.execute(f"INSERT INTO {tabela} VALUES (NULL{', ?' * len(args)})", ar... | 58,942 |
def load_data_sets(
atom_features: List[AtomFeature], bond_features: List[BondFeature]
) -> Tuple[MoleculeGraphDataLoader, MoleculeGraphDataLoader, int]:
"""Loads in the train and test molecules and generates labelled, featurized graph
representations.
"""
from simtk import unit
training_set_pa... | 58,943 |
def login():
"""View function to login. Uses the login form.
If the @login_required decorator is used on a view function
then the user will be redirected to this function."""
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on... | 58,944 |
def test_qr_mode_full_future_warning():
"""Check mode='full' FutureWarning.
In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
deprecated. The release date will probably be sometime in the summer
of 2013.
"""
a = np.eye(2)
assert_warns(DeprecationWarning, np.linalg.qr, a... | 58,945 |
def extract_vis_gifs(source_path, target_path):
"""
Extract gifs with visualised segmentation and saves on the target part
with a full id of a cine-MRI slice used as a unique name
Parameters
----------
source_path : Path
A path to full segmentation visualisation that contains pngs and a g... | 58,946 |
def to_isbn13(number):
"""Convert the number to ISBN-13 format."""
number = number.strip()
min_number = compact(number, convert=False)
if len(min_number) == 13:
return number # nothing to do, already ISBN-13
# put new check digit in place
number = number[:-1] + ean.calc_check_digit('978... | 58,947 |
def refine_flare_ranges(lc, sigma=3., makeplot=True, flare_ranges=None):
""" Identify the start and stop indexes of a flare event after
refining the INFF by masking out the initial flare detection indexes. """
if not flare_ranges:
flare_ranges, _ = find_flare_ranges(lc, sigma=sigma)
flare_i... | 58,948 |
def get_partial_lm_state_dict(model_state_dict, modules):
"""Create compatible ASR state_dict from model_state_dict (LM).
The keys for specified modules are modified to match ASR decoder modules keys.
Args:
model_state_dict (odict): trained model state_dict
modules (list): specified module... | 58,949 |
def test_available_phenotype_resources_missing_resource():
"""Test function response when one resource file is missing"""
# GIVEN one of the required files missing (here it's been renamed)
temp_file = ".".join([path_to_hpo_terms, "temp"])
os.rename(path_to_hpo_terms, temp_file)
# The function shou... | 58,950 |
def test__calculate_ap(od_detection_eval):
""" Test `_calculate_ap`. """
ret = _calculate_ap(od_detection_eval)
assert type(ret) == np.float64 | 58,951 |
def say(channel, attachments, text=None, ephemeral_user=None, thread=None):
"""
Sends a message (with attachments) to Slack. Use the send_* methods instead.
:param channel:
:param attachments:
:param text:
:param ephemeral_user:ID of the user who will receive the ephemeral message
:param thr... | 58,952 |
async def async_get_entry_scenes(entry: ConfigEntry, api):
"""Get the scenes within an integration."""
try:
return await api.scenes(location_id=entry.data[CONF_LOCATION_ID])
except ClientResponseError as ex:
if ex.status == HTTP_FORBIDDEN:
_LOGGER.exception(
"Unab... | 58,953 |
def set_scene_attributes():
"""! Preps Maya scene for Stingray Materials preview. """
set_camera_attributes()
mc.currentUnit(linear='meter')
mc.grid(reset=True) | 58,954 |
def _get_areas(params, feature_names):
"""Returns mapping between areas and constituent feature types."""
areas = {}
for feature_id in range(len(params)):
feature_info = params[feature_id]
feature = feature_info["ID"]
area = feature_info["Area"]
if area not in areas:
areas[area] = [feature]
... | 58,955 |
def rbf_spectrum_dc(w: np.ndarray, c: np.ndarray, d: np.ndarray) -> np.ndarray:
"""Evaluate the RBF spectrum derivative w.r.t. c.
Args:
w: The (dimensionless) frequencies at which to evaluate the power spectrum, of
shape (n, ).
c: An unconstrained parameter representing
... | 58,956 |
def render_colors(vertices, triangles, colors, width, height, channels=3, bg=None):
""" Adds color to 3D face vertices.
See https://github.com/YadiraF/face3d.
"""
if bg is None:
img = np.zeros((height, width, channels), dtype = np.float32)
else:
assert bg.shape[0] == height and b... | 58,957 |
def acceptanswer(request):
"""
采纳问题
:param request:
:return:
"""
answer_id = request.POST.get('answer_id')
answer = Answer.objects.filter(id=answer_id).first()
if request.user != answer.question.user and request.user != answer.user: # 保证采纳人一定是问题的提问者,而且不能自己采纳自己
return JsonRespons... | 58,958 |
def calc_m_sq_cos_sq_para(tensor_sigma, flag_tensor_sigma: bool = False):
"""Calculate the term P2 for paramagnetic sublattice.
For details see documentation "Integrated intensity from powder diffraction".
"""
sigma_13 = tensor_sigma[2]
sigma_23 = tensor_sigma[5]
p_2 = numpy.square(numpy.ab... | 58,959 |
def main(samples, chunksize=1, num_workers=None):
"""Main application
"""
len_samples = len(samples)
time_start = time.perf_counter()
firstPerson = FirstPersonMR(num_workers, chunksize)
freq = firstPerson.frequency(samples)
time_elapsed = (time.perf_counter() - time_start)
memBy = res... | 58,960 |
def cdf(x, loc=0, scale=1):
"""
CDF of the logistic distribution.
"""
with mpmath.extradps(5):
x = mpmath.mpf(x)
loc = mpmath.mpf(loc)
scale = mpmath.mpf(scale)
z = (x - loc) / scale
p = (1 + mpmath.tanh(z/2)) / 2
return p | 58,961 |
def visualize_seir_computation(results: pd.DataFrame,
compartments: List[Any],
show_individual_compartments=False):
"""Visualizes the SEIR computation"""
if show_individual_compartments:
w, h = plt.figaspect(2)
fig = plt.figure(figsi... | 58,962 |
def as_observer(self):
"""Hides the identity of an observer.
Returns an observer that hides the identity of the specified observer.
"""
return AnonymousObserver(self.on_next, self.on_error, self.on_completed) | 58,963 |
def main(kw=False):
"""
main method to build ast tree and call subseq functions
Top level check
license info
scan for class - class check
scan for function - function check
"""
try:
f = open(sys.argv[1])
except IOError:
print "Can't find {}".format(sys.arg... | 58,964 |
def run_retriever(n_books=17868, extractions_per_book=1, prefix_length=10):
"""Test by sequentially getting 1 prefix per book for all books."""
utils.manual_seed(42)
retriever = Retriever(
prefix_sampler_kwargs=dict(
prefix_length=prefix_length,
# Skip front and end of each ... | 58,965 |
def swarmbox(df, parameter, stat_table, hue=None):
"""
Graph boxplot of a category, with each individual point
:return: matplotlib figure
"""
fig, ax = plt.subplots()
sns.swarmplot(x='Arm', y="Difference of "+parameter, data=df, ax=ax,
palette=sns.crayon_palette(['Vivid Violet'... | 58,966 |
def get_files(asset="images", url=False):
"""Returns list of files in the uploads/images directory"""
path = f"{current_app.config['UPLOADS_DEFAULT_DEST']}/{asset}"
if not os.path.exists(path):
os.makedirs(path)
files_list = os.listdir(path)
try:
files_list.remove("data")
except ... | 58,967 |
def create_qrcode(id_list, ctime, qrtype, pay_id):
"""
:param bid:表示书籍的唯一id,用isbn号码
:param ctime: 创建时间,一分钟后过期
:param type: 二维码类型
:return:
"""
qr = qrcode.QRCode(
version =1,
error_correction = qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,... | 58,968 |
def load(file):
"""
Load an ontology from a .obo file.
"""
return OBOOntology(file) | 58,969 |
def transform_seed_objects(objects):
"""Map seed objects to state format."""
return {obj['instance_id']: {
'initial_player_number': obj['player_number'],
'initial_object_id': obj['object_id'],
'initial_class_id': obj['class_id'],
'created': 0,
'created_x': obj['x'],
... | 58,970 |
def ensure_mask_not_equal(run0, anchor0, step0, slice0, run1, anchor1, step1,
slice1):
"""
Helper function to compare two random op outputs, ensuring they are different.
See get_anchor_step for details on arguments.
"""
tensor0 = get_anchor_step(run0, anchor0, step0, slice... | 58,971 |
def mergePDFs(tempdir_name, final_PDF_name):
"""
Merge all files ending in .pdf in the given temporary directory into a single
PDF. Writes the final PDF back into the given temporary directory.
"""
merger = PdfFileMerger()
PDFs_to_be_merged = glob.glob(os.path.join(tempdir_name, "*.pdf"))
#... | 58,972 |
def _eigh_work(
H, V=None, precision=lax.Precision.HIGHEST, termination_size=128):
""" The main work loop performing the symmetric eigendecomposition of H.
Each step recursively computes a projector into the space of eigenvalues
above jnp.mean(jnp.diag(H)). The result of the projections into and out of
that... | 58,973 |
def get_cost_center(vehicle):
""" this is used to return cost center """
cost_center = frappe.get_value("Vehicle Details", vehicle, "vehicle_cost_center")
if cost_center:
return cost_center | 58,974 |
def sample_mog(prob, mean, var, rng):
"""Sample from independent mixture of gaussian (MoG) distributions
Each batch is an independent MoG distribution.
Parameters
----------
prob : numpy.ndarray
mixture probability of each gaussian. Shape --> (batch_num, center_num)
mean : numpy.ndarray
... | 58,975 |
def agc(param, clipping=1e-2, eps=1e-3):
"""
Implements the adaptive gradient clipping according to the NFNet paper: https://arxiv.org/pdf/2102.06171.pdf
"""
param_data = param.detach()
grad_data = param.grad.detach()
max_norm = unitwise_norm(param_data).clamp_(min=eps).mul_(clipping) # Clam... | 58,976 |
def get_weather(location): # location can be IP address, city, or ZIP
"""This function takes the location and outputs the current weather."""
url = f"https://api.weatherapi.com/v1/current.json?" \
f"key={weatherapi_key}&" \
f"q={location}"
stats = {"temp_f": 0, "wind_mph": 0, "wind_dir"... | 58,977 |
def progress_bar(t):
""" from https://gist.github.com/leimao/37ff6e990b3226c2c9670a2cd1e4a6f5
Wraps tqdm instance.
Don't forget to close() or __exit__() the tqdm instance once you're done
(easiest using `with` syntax).
"""
last_b = [0]
def update_to(b=1, bsize=1, tsize=None):
"""
... | 58,978 |
def remove_digits(text):
"""
Remove all digits from the text document
take string input and return a clean text without numbers.
Use regex to discard the numbers.
"""
result = ''.join(i for i in text if not i.isdigit()).lower()
return ' '.join(result.split()) | 58,979 |
def set_fe_vecs(alignment, en_emb, l2_emb, name_vecs=False):
"""Computes vectors for FE definitions and names (if ``name_vecs`` is True)
and stores it as a resource in ``alignment```.
:param alignment: The alignment object.
:type alignment: :class:`Alignment`
:param en_emb: English word embedding.
:type en_emb: ... | 58,980 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up an Mila sensor entity based on a config entry."""
entry = hass.data[DOMAIN][entry.entry_id]
conf_devices = entry[CONF_DEVICES]
coordinator = entry[DATA_COORDINATOR]
def get_entities():
"""Get the Mila sensor entities.""... | 58,981 |
def update_phone_number(PhoneNumberId=None, ProductType=None, CallingName=None):
"""
Updates phone number details, such as product type or calling name, for the specified phone number ID. You can update one phone number detail at a time. For example, you can update either the product type or the calling name in... | 58,982 |
def delivery_status_auth(sender, **extra):
"""
状态跟踪 - 审核状态
:param sender:
:param extra:
:return:
"""
print(sender, extra) | 58,983 |
def create_local_db(path_to_db=DEFAULT_PATH_TO_DB,
create_script=make_create_script()):
""" Create our SQLite database ex nihilo. """
if os.path.exists(path_to_db):
response = input("Overwrite dump at "+path_to_db+"? (y/n)\n")
if response != "y":
return False
... | 58,984 |
def _ipaddr(*args, **kwargs):
"""Fake ipaddr filter"""
return "ipaddr" | 58,985 |
def hlab_to_xyz(hlab: Vector, white: VectorLike) -> Vector:
"""Convert Hunter Lab to XYZ."""
xn, yn, zn = alg.multiply(util.xy_to_xyz(white), 100, dims=alg.D1_SC)
ka = CKA * alg.nth_root(xn / CXN, 2)
kb = CKB * alg.nth_root(zn / CZN, 2)
l, a, b = hlab
l /= 100
y = (l ** 2) * yn
x = (((a... | 58,986 |
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be ove... | 58,987 |
def draw_border_lines(windowSurface, top, bottom, left, right, lightcolour, darkcolour):
"""Draws line around rectangle for 3d effect"""
#Light colour, top and left of rectangle
pygame.draw.line(windowSurface, lightcolour, (left, top-1), (right, top-1))
pygame.draw.line(windowSurf... | 58,988 |
def get_cache_path() -> Path:
"""Returns data root folder."""
return get_data_path() / Path('cache') | 58,989 |
def create_temporary_file(
file_contents: str,
suffix: str = '.txt'
) -> NamedTemporaryFile:
"""Create a temporary file with an explicit name from a given string."""
file = NamedTemporaryFile(suffix=suffix)
file_contents_bytes = str.encode(file_contents)
file.write(file_contents_bytes)
file.... | 58,990 |
def load_CIFAR_batch(filename):
""" load single batch of cifar """
with open(filename, 'rb') as f:
datadict = pickle.load(f, encoding='latin1')
X = datadict['data']
Y = datadict['labels']
X = X.reshape(10000, 3, 32, 32).astype('float32')
Y = np.array(Y)
return X, Y | 58,991 |
def one_minus_exp(x):
"""Returns 1-exp(x). Useful for probability calculations."""
if abs(x) < log_epsilon:
return -x
else:
return 1 - exp(x) | 58,992 |
def get_diff_text(text1: List[str], text2: List[str]) -> List[Tuple[int, str]]:
"""
Take the alignment between two lists and get the difference.
"""
orig_words = '\n'.join(text1.split()) + '\n'
pred_words = '\n'.join(text2.split()) + '\n'
diff = diff_match_patch.diff_match_patch()
diff.Diff... | 58,993 |
def get_client(service_name, sandbox=False):
"""
Return a client for a given service.
The `sandbox` argument should only be necessary if a the client will be
used to make a request. If it will only be used to serialize objects, it is
irrelevant. A caller can avoid the overhead of determining the sa... | 58,994 |
def submit_project_to_runbiosimulations(name, filename_or_url,
simulator, simulator_version='latest',
cpus=1, memory=8, max_time=20, env_vars=None,
email=None, public=False,
... | 58,995 |
def encrypt(key, text):
""" Encrypt a message using the public key, for decryption with the private key """
retval = b""
i = 0
txtl = len(text)
ks = int(key.key_size / 8) - 64 # bits -> bytes, room for padding
# Process data in chunks no larger than the key, leave some room for padding.
whil... | 58,996 |
def _DecoderBlock(positions,
d_model,
d_ff,
n_heads,
dropout,
mode):
"""Returns a layer sequence representing a Transformer decoder.
(acts, pos) --> (acts', pos')
Args:
positions: random vectors for positions
d_mod... | 58,997 |
def accumulate_spectra(n_trajectories, n_states=10, suffix='flu', n_restarts=0):
"""
Create the spectra_flu.input file using the nasqm_flu_*.out files
"""
create_spectra_inputs(suffix, n_trajectories, n_restarts, n_states)
omegas_and_strengths = [open("{}_spectra/traj_{}.out".format(suffix, traj), '... | 58,998 |
def print_square(size):
"""
Print a square
"""
if type(size) != int:
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size must be >= 0')
if size == 0:
return
for i in range(size):
for j in range(size):
print("#", end="")
... | 58,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.