text string | label_name string | labels int64 |
|---|---|---|
in_out.len(),
aes_key.inner_less_safe(),
ctr,
gcm_ctx,
)
}
},
};
&mut in_out[processed..]
}
#[cfg(not(target_arch = "x86_64"))]
#[inline]
fn integrated_aes_gcm<'a>(
_: &aes::Key, _: &mut gcm::Cont... | Rust | 0 |
import pyvisa
import os
def read_settings(file_path):
settings = {}
with open(file_path, 'r') as file:
for line in file:
line = line.strip() # Remove leading and trailing whitespace
if line and not line.startswith('#'): # Ignore empty lines and comments
if '=' ... | Python | 1 |
# WELCOME TO GOOBED'S CONNECT 4 GAME
import connect4board
import Winloss
import BoardList
import random
# Function to place opponent's piece
def place_opponent_piece(choice):
ranges = {1: (1, 3), 2: (1, 3), 3: (2, 4), 4: (3, 5), 5: (4, 6), 6: (5, 7), 7: (5, 7)}
randNum = random.randint(*ranges[choice])
col... | Python | 1 |
Self::Error> {
let encoded = value.into_stream(Encoder)?;
self.push(encoded);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
self.encode()
}
}
pub struct Encoder;
impl Encoder {
#[inline]
fn encode_type<'en>(&self, dtype: &Type, value: &[u8]) -> Result<B... | Rust | 0 |
#!/usr/bin/python3
# coding:utf-8
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
data = np.loadtxt('./../../data/relocalization_distance_100.txt')
data.sort()
delt = 1.0 / len(data)
proba = np.arange... | Python | 1 |
<(), ()>) -> Result<(), ()> {
f.recurse(
&mut Context {
in_methodish: true,
is_pure: is_pure_with_inherited_val(c, &f.ctxs),
is_constructor: is_constructor(&f.name),
ignore_coeffect_local_errors: has_ignore_coeffect_local_errors_attr(
... | Rust | 0 |
#!/usr/bin/env python3
import sys
import re
course_code=sys.argv[1]
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <course code>")
sys,exit(1)
if not re.fullmatch(r"[A-Z]{4}[0-9]{4}", course_code):
print(f"Invalid course code: {course_code}")
sys.exit(1)
male_count=0
female_count=0
with open(... | Python | 1 |
pubkey)
.await
.expect("get_account")
.unwrap();
println!(
"root[0]: {:?}",
merkel_tree_account_after.data[609..641].to_vec()
);
println!(
"root[1]: {:?}",
merkel_tree_account_after.data[641..673].to_vec()
);
println!(
"root[2]: {:?}",... | Rust | 0 |
ax1.set_aspect(1.0)
# legend
lines = []
labels = []
ls = line_truth
lines.append(Line2D(
[0], [0], color=ls[1], lw=ls[2], dashes=ls[3], alpha=ls[4]))
labels.append(truth_name)
ls = line_base
lines.append(Line2D(
[0], [0], c... | Python | 1 |
int_pins();
hw.delay(400.ms());
hw.led0.off();
}
fn _debug_timer(_d_t: u32) {
#[cfg(feature = "serial")]
{
unsafe { HARDWARE.as_mut() }.map(|hw| {
let _ = hw.serial_write_num(hw.get_step() as usize);
// let _ = hw.serial_write(b" ");
// let _ = hw.serial_wri... | Rust | 0 |
ace(), Token::not_whitespace()),
1,
0,
);
let expr = expr!(
atom_loop![sub_str!(0, p1, p2), const_str!(" ")],
Atom::match_substr(0, Token::not_whitespace().into(), -1)
);
run_expr_test(
&expr,
vec![
(vec![" Oege de Moor"], "<NAME>"),
(
vec![" Kathleen Fisher... | Rust | 0 |
n_directives)
if self.get_extension_attr(ext, 'cython_cplus'):
ext.language = 'c++'
if hasattr(ext, 'no_c_in_traceback'):
c_line_in_traceback = not ext.no_c_in_traceback
else:
c_line_in_traceback = None
options = {
'use_listing_file': sel... | Python | 1 |
.begin_path();
ctx.set_stroke_style(&JsValue::from_str("#00ff00"));
ctx.rect(
self.x(),
self.y() - self.h() * 0.05,
self.w(),
self.h() + self.h() * 0.1,
);
ctx.stroke();
ctx.close_path();
}
/// Draw a button with image cont... | Rust | 0 |
defining the model...")
layers = []
for m, n in zip(dims, dims[1:]):
print('layer: {},'.format(len(layers)), 'm: {}, n: {}'.format(m, n))
layers.append(
graph_interdependence_layer(
m=m, n=n,
width=width,
... | Python | 1 |
type WeightInfo = ();
}
const DESIRED_MEMBERS: u32 = 7;
parameter_types! {
pub const CandidacyBond: Balance = 32 * XRT;
pub const VotingBond: Balance = 1 * XRT;
pub const TermDuration: BlockNumber = 7 * DAYS;
pub const DesiredMembers: u32 = DESIRED_MEMBERS;
pub const DesiredRunnersUp: u32 = 5;
... | Rust | 0 |
Copper => Some(Silver),
Silver => Some(Gold),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Atom {
pub pos: Pos,
pub atom_type: AtomType,
pub connections: [Bonds; 6],
pub is_berlo: bool,
}
impl Atom {
pub fn new(pos: Pos, atom_type... | Rust | 0 |
> {
let mut nodes = vec![];
let mut stmt = conn.prepare(
"
SELECT
node.tax_id,
node.parent_tax_id,
node.rank,
division.division,
name.name_class,
name.name,
node.comment
FROM node
INNER JOIN ... | Rust | 0 |
ontroller)
DPadLeft = 1012,
/// D-pad right Button (controller)
DPadRight = 1013,
/// D-pad up Button (controller)
DPadUp = 1014,
/// D-pad down Button (controller)
DPadDown = 1015,
/// Thumbstick 1 Button (controller)
Thumbstick1 = 1016,
/// Thumbstick 2 Button (controller)
... | Rust | 0 |
n: int = 5 # Yeh batata hai ke 'n' ek integer hai
name: str = "Harry" # Yeh batata hai ke 'name' ek string hai
# n. is se int ke sary methods milengy
def sum(a: int , b:int) -> int:
return a+b
sum(1 , 2)
| Python | 1 |
blah<PackageReference Include="Unity" Version="4.0.1">
</PackageReference>
<PackageReference Include="EntityFramework" Version="2.4.6" />
<PackageReference Include="Automapper" Version="3.1.4">
<PrivateAssets>
</PackageRef... | Rust | 0 |
let x;
let y = "hello"; // y的类型是&str,而不是上面的i64了
x = if true {
true
} else {
false
};
println!("x = {}, y = {}", x, y);
// z = 100;
// 上面的 z = 100,前面没有let,这是对变量重新赋值,和变量遮蔽不一样,重新赋值是不能改变数据类型的。
// 更重要的是rust里声明的变量默认是不可变的,所以上面的语句会报错。要声明一个变量可变,得加上mut关键字。
let mut z = 1;
println!("before:z = {}", z... | Rust | 0 |
Apply common corrections
corrections = {
"engine x": "nginx",
"instal": "install",
"restat": "restart",
"stat us": "status",
"sis tem": "system",
"up date": "update",
"pack age": "package"
}
for wrong, r... | Python | 1 |
_space::BinarySpacePartition;
/// Arguments for `BinarySpace::new(...)`.
pub type NewBinarySpaceArgs = binary_space::NewBinarySpaceArgs;
#![doc(html_root_url = "https://docs.rs/syscall-numbers/2.0.0")]
#![warn(
//missing_docs,
keyword_idents,
macro_use_extern_crate,
missing_debug_implementations,
n... | Rust | 0 |
let (a, b): (usize, usize) = mem::transmute(self);
extra.push(a as u32);
extra.push(b as u32);
invoke::<$($var,)* R> as u32
}
}
}
impl<'a, 'b, $($var,)*> IntoWasmAbi for &'a mut (FnMut($($var),*) + 'b)
w... | Rust | 0 |
a
d @ s d dl mZ ddlmZ ddlmZ ddlmZ ddlm Z m
Z
mZmZm
Z
mZmZmZ ddlmZmZ ddlmZ dd lmZmZmZmZ dd
lmZmZ dZdS )
)absolute_import )is_connection_dropped)make_headers)is_fp_closed)
SSLContextHAS_SNIIS_PYOPENS... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Python | 1 |
ile(chat.system_template.format(r'(.*?)'), re.DOTALL)
turn_pattern = re.compile(chat.turn_start.format(r'(\d+)'), re.DOTALL)
human_pattern = re.compile(chat.role_template.format(chat.role_human).strip(), re.DOTALL)
observe_pattern = re.compile(chat.role_template.format(chat.role_observation).str... | Python | 1 |
# Copyright 2021-2024 Cambridge Quantum Computing Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | Python | 1 |
; }
self.state.labels.add_global(name, value);
}
Ok(())
}
fn parse_instruction(&mut self) -> Result<(), ()>
{
self.state.check_cpudef_active(self.parser.report.clone(), &self.parser.next().span)?;
let instr_span_start = self.parser.next().span;
// Find matching rule patterns.
self.pa... | Rust | 0 |
e > residue_constants.restype_num):
raise ValueError('Invalid aatypes.')
pdb_lines.append('MODEL 1')
atom_index = 1
chain_id_ind = 0
# Add all atom sites.
for i in range(aatype.shape[0]):
if (i>0) and (residue_index[i]>=residue_index[i-1]+200):
chain_id_ind+=1
res_name_3 = restypes[a... | Python | 1 |
import logging
import requests
def register_heartbeats(
port: int,
logger: logging.Logger,
services: list[dict[str, str]],
) -> bool:
for service in services:
url = f"http://localhost:{port}/heartbeat"
r = requests.post(url=url, json=service)
if not r.ok:
logger.warn... | Python | 1 |
"Rotation value in degrees"
self.rotation
return -numpy.rad2deg(numpy.arctan2(self.rotation[1, 0], self.rotation[0, 0]))
def correct(self, points):
"Rotate the set of points to be aligned with the reference"
P = numpy.ascontiguousarray(points, dtype=numpy.float64)
if... | Python | 1 |
# 4 종류의 괄호문자들 '()', '[]', '{}', '<>' 로 이루어진 문자열이 주어진다.
# 이 문자열에 사용된 괄호들의 짝이 모두 맞는지 판별하는 프로그램을 작성한다.
# 예를 들어 아래와 같은 문자열은 유효하다고 판단할 수 있다.
# 아래와 같은 문자열은 유효하지 않은 문자열이다. 붉은색으로 표시된 괄호의 짝을 찾을 수 없기 때문이다.
# 아래 문자열은 열고 닫는 괄호의 개수는 유효하나 짝이 맞지 않는 괄호가 사용 되었기 때문에 유효하지 않다.
# [입력]
# 각 테스트 케이스의 첫 번째 줄에는 테스트케이스의 길이가 주어지며, 바로 다음 줄에 ... | Python | 1 |
_to_fit();
( *target_seq_3_letters ).shrink_to_fit();
if ( *cons_capra07_list ).len() != ( *target_seq_3_letters ).len() { error::error_bomb( "error" ); }
}use abc::{Filter, FilterResult};
use {VarContext, ex, Arg};
#[derive(Debug)]
pub struct NewlineToSpace;
impl Filter for NewlineToSpace {
#[allow(unused_v... | Rust | 0 |
::std::ffi::CStr::from_ptr(
ffi::nl_langinfo_l(codeset as ::libc::c_uint, locale.c_locale)).to_bytes())
};
if cs != "UTF-8" {
if let Ok(i) = IConv::new("UTF-8", cs) {
return Some(Arc::new(i));
}
}
... | Rust | 0 |
import os
import glob
import time
import sys
sys.path.append('./env/lib/python3.11/site-packages/rpi5_ws2812/')
from rpi5_ws2812.ws2812 import Color, WS2812SpiDriver
# Initialize temperature sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glo... | Python | 1 |
self.cdrs:
assert self.cdrs == self.cdrs_extracted # confirm that cdrs in the input file match expectation
assert self.cdrs_aligned == self.cdrs_extracted
def extract_aligned_cdrs(self):
return _extract_aligned_cdrs(self.alseq, self.cdr_columns_str)
def extract_cdrs_without_gap... | Python | 1 |
_CANCELLED`]: crate::commands::SAVE_PANEL_CANCELLED
pub fn cancel_command(mut self, cmd: Selector<()>) -> Self {
self.cancel_cmd = Some(cmd);
self
}
}
use std::io::{self, Read};
use regex::Regex;
#[derive(Copy, Clone, Debug)]
struct Item {
cost: u16,
damage: u16,
armor: u16
}
impl... | Rust | 0 |
import torch
from kan import *
from models_pytorch.utils import MyCrossEntropyLoss, JeffriesMatusitaLoss
from dataPre import datapre
from sklearn.metrics import f1_score
torch.set_default_dtype(torch.float64)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.get_default_dtype()
de... | Python | 1 |
./{}", opt.name);
let out_dir = Path::new(&out_dir_str);
// Create dir
if let Err(e) = create_dir(out_dir) {
println!("Error creating dir ({})", e);
}
// Generate C code, Though only headerfiles are needed.
// In general C files are generated when build at the user.
gen_c(&futhark_... | Rust | 0 |
}
#[cfg(not(feature = "sqlx-postres"))]
impl From<&PgRow> for ColumnQueryResult {
fn from(row: &PgRow) -> Self {
Self::default()
}
}
<reponame>nondejus/iced
/*
Copyright (C) 2018-2019 <EMAIL>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated d... | Rust | 0 |
# Polynomial.py
# This file defines a Polynomial class for representing and manipulating polynomials.
class Polynomial:
"""
Polynomial class for representing and manipulating polynomials.
Attributes:
_coeffs (list): List of coefficients of the polynomial.
_deg (int): Degree of the polynomi... | Python | 1 |
import gymnasium as gym
MYOSUITE_TASKS = [
"myo-reach",
"myo-reach-hard",
"myo-pose",
"myo-pose-hard",
"myo-obj-hold",
"myo-obj-hold-hard",
"myo-key-turn",
"myo-key-turn-hard",
"myo-pen-twirl",
"myo-pen-twirl-hard",
]
MYOSUITE_TASKS_DICT = {
"myo-reach": "myoHandReachFixed... | Python | 1 |
useful behavior.
RefineExtraArgs: "refine-extra-args",
/// `(eval-string e1 e2 ...)` takes as input zero or more expressions which are elaborated
/// as type `string`, and then evaluates them to an actual lisp string. This has the same
/// effect as the top level command `output string: e1 e2 ...;` but... | Rust | 0 |
the language
if language == 'Chinese':
prompt = (f"""
在上面提供的打乱的家族关系文本中,'{last_person}'的能够向上追溯到的最年长的亲人是谁?
例如:
例子1.如果张强的父亲是马克,除此以外提供的文本中没有更多关于亲属关系的信息,那么在提供的文本中张强能够向上追溯到的最年长的亲人就是马克。
例子2.如果李明的姥姥是张红,而张红的父亲是张强,除此以外提供的文本中没有更多关于亲属关系的信息,那么在提供的文本中李明能够向上追溯到的最年长的亲人就是张强。
例子3.如果小明是张红的曾孙女,张红的祖母是王华,王华的父亲是王刚... | Python | 1 |
art1, Pa5<PfC>, Pa6<PfC>),
);
#[cfg(feature = "atsam4s")]
uarts!(
Uart0: (UART0, Uart0, uart0, Pa9<PfA>, Pa10<PfA>),
Uart1: (UART1, Uart1, uart1, Pb2<PfA>, Pb3<PfA>),
);
pub type Serial0 = Uart0;
pub type Serial1 = Uart1;
// Copyright (c) Facebook, Inc. and its affiliates.
// Copyright (c) 2021-2022 Toposware... | Rust | 0 |
(acc_list), epoch)
if epoch % args.val_frequence == 0:
print(f'valid epoch {epoch}')
val_acc, val_f1 = val(model, dataloader_test, criterion, args=args)
if val_acc > best_acc:
best_acc = val_acc
if val_f1 > best_f1:
best_f1 = val_f1... | Python | 1 |
usage'] = per_cpu_usage
metadata['average_cpu_usage'] = average_cpu_usage
return sample.Sample(
'cpu_total_utilization',
average_cpu_usage['cpu_total_utilization'],
'',
metadata,
)
def ParseCpuUsageTags(cpu_tag):
"""Parse CPU Utilization from cpu xml tag."""
usage_percent = cpu_tag.f... | Python | 1 |
def solution(n, k, cmd):
# pyp[n]의 0번째 원소 : 인덱스, 1번째 원소 : 현재 이전 인덱스, 2번째 원소 : 현재 다음 인덱스
pyo = [[x, x - 1, x + 1] for x in range(n)]
pyo[-1][-1] = -1
answer = ['O'] * n
cache, now = [], k
for i in cmd:
command = i.split()
if command[0] == 'U':
for _ in range(... | Python | 1 |
bit_util::align(record_length, RecordDescriptor::ALIGNMENT),
);
let msg_type_id: Index = RecordDescriptor::message_type_id(header);
if RecordDescriptor::PADDING_MSG_TYPE_ID == msg_type_id {
continue;
}
messages_read += 1;
handler... | Rust | 0 |
rng().gen_range(0, (10_f64 - luminosity / SUN_LUMINOSITY) as u8) > 0
{
rand::thread_rng().gen_range(0.01_f64, 0.1_f64)
} else {
rand::thread_rng().gen_range(0.025_f64, 0.6_f64)
}
} else if luminosity < 10_f64 * SUN_LUMIN... | Rust | 0 |
raw::c_int;
}
extern "C" {
pub fn _fputs_r(arg1: *mut _reent, arg2: *const crate::esp_idf::std::os::raw::c_char, arg3: *mut FILE)
-> crate::esp_idf::std::os::raw::c_int;
}
extern "C" {
pub fn _fputs_unlocked_r(arg1: *mut _reent, arg2: *const crate::esp_idf::std::os::raw::c_char, arg3: *mut F... | Rust | 0 |
to_reserve = HashSet::new();
if primitive_types.contains(PrimitiveType::Array) {
keys_to_reserve.extend(KEYWORDS_TYPE_ARRAY.iter());
}
if primitive_types.contains(PrimitiveType::Boolean) {
keys_to_reserve.extend(KEYWORDS_TYPE_BOOLEAN.iter());
}
if primitiv... | Rust | 0 |
he purpose of generating bytecodes
#[derive(Encodable)]
pub struct Move {
frames: Vec<Frame>,
}
#[derive(Encodable)]
pub struct Frame {
texture_id: i32,
flags: HashMap<String, i32>,
}
#[derive(Encodable)]
pub struct InstFile {
moves: Vec<Move>,
// a lookup hashmap for looking up move_ids -> move_bytecode-p... | Rust | 0 |
import click
import requests
import pprint
import json
# Configuration Settings
listening_post_addr = "http://127.0.0.1:5000"
# Helper functions
def api_get_request(endpoint):
response_raw = requests.get(listening_post_addr + endpoint).text
response_json = json.loads(response_raw)
return response_json
# ... | Python | 1 |
{:?}", pub_u);
println!("Envelope: {:?}", envelope);
let mut user_record =
USER_MAP.lock().unwrap().get(username).unwrap().clone();
user_record.envelope = Some(envelope.to_vec());
user_record.pub_u = Some(*pub_u);
USER_MAP
.lock()
.unwrap()
.insert(username.to_strin... | Rust | 0 |
[
(
"/sys/fs/cgroup/memory",
(),
(
"cpu",
"test",
),
),
(
"/sys/fs/cgroup/memory/test_1",
(),
(
"cpu",
"test",
),
),
(
... | Python | 1 |
# SPDX-License-Identifier: GPL-2.0-or-later
# SPDX-FileCopyrightText: © 2022-present Gene C <arch@sapience.com>
"""
Profile
"""
# pylint: disable=too-many-branches
from utils import Msg
from utils import state_marker
from config import Opts
from .profile_base import ProfileBase
def show_list(prof: ProfileBase, opts... | Python | 1 |
# SecuML
# Copyright (C) 2016-2019 ANSSI
#
# SecuML is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# SecuML is distributed in the h... | Python | 1 |
rimary and secondary IP ranges for all
subnets in the region for the given VPC network. You can restrict which
subnet primary and secondary ranges can use NAT.
$ {command} nat1 --router=my-router
--auto-allocate-nat-external-ips
--nat-custom-subnet-ip-ranges=subnet-1,s... | Python | 1 |
and top-5 accuracies
# total_hits = np.zeros(n_top_stats)
# # For each test sample, count times where true beam is in top 1,2,3,5
# for i in range(n_test_samples):
# for j in range(n_top_stats):
# hit = np.any(pred_beams[i][:top_beams[j]] == y_test... | Python | 1 |
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | ((value as u32 & 0x... | Rust | 0 |
: UImm8::maybe_from_i64(1).unwrap(),
},
"B9F10108",
"subs r8, r9, #1",
));
insns.push((
Inst::AluRRImm8 {
alu_op: ALUOp::Rsb,
rd: writable_rreg(0),
rn: rreg(1),
imm8: UImm8::maybe_from_i64(255).unwrap(),
},
"C1F1FF00... | Rust | 0 |
# 0
def addr(a, b, regs):
return regs[a] + regs[b]
# 1
def addi(a, b, regs):
return regs[a] + b
# 2
def mulr(a, b, regs):
return regs[a] * regs[b]
# 3
def muli(a, b, regs):
return regs[a] * b
# 4
def banr(a, b, regs):
return regs[a] & regs[b]
# 5
def bani(a, b, regs):
return regs[a] & b
# ... | Python | 1 |
)
start_ix = 0
start_address = nl.addresses[:, start_ix]
with torch.no_grad():
nb = reduce_neurallambda(
nl,
N_STACK,
start_address,
total_steps,
gc_steps=GC_STEPS,
device=args.device,
)
# pretty print results... | Python | 1 |
-> Node
{
//take a lookup in ctx.symbol_table with key value
Node::VarLiteral(value)
}
}
//execute ast
pub fn exec(_ : &mut ShellContext, node: Node)
{
let mut ip = Interpreter; //::new(state);
ip.dispatch(node);
//return error list?
}
//impl the trait
<gh_stars>0
use std::ops::Index;
use std::sy... | Rust | 0 |
_main__':
run_dir = Path('baselines/session_4da05e87') # Path('baselines/session_ebdfe818')
# original session_e41c9eff, main session_4da05e87, extra session_e1b6d2dc
coords_save_pth = Path('base_coords.npz')
if coords_save_pth.is_file():
print(f'{coords_save_pth} found, loading from ... | Python | 1 |
to_micro_denom_u128(25u128),
);
// Add delegation we already have 60 so 25 + 60 = 85
let delegations = &vec![FullDelegation {
delegator: env.clone().contract.address,
validator: String::from("validator"),
amount: coin(denom_to_micro_denom_u128(85), "juno"),
... | Rust | 0 |
unwrap() + scale;
// Mean of predicted distribution: x
state.x = &XX[0] * two * scale;
for xx in XX {
state.x += xx;
}
state.x /= two * x_scale;
// Covariance of distribution: X
// Center point, premult here by 2 for efficiency
quadform_tr_x(&mut state.X, two * scale, &(&XX[0] -... | Rust | 0 |
nd_method(self.trailer_count, id))
}
fn find_trailer_ovens(&self, trailer_id: Id) -> Result<Vec<Oven>, Self::E> {
Ok(test_find_trailer_method(self.trailer_count, trailer_id))
}
// oven data methods
fn find_oven_data(&self, oven_id: Id, from: Timestamp, until: Timestamp) -> Result<Vec<OvenDa... | Rust | 0 |
_record_should_parse_an_END_record(){
let data = "END "
.as_bytes();
let result = end_record(data);
match result {
IResult::Done(_, keyword) => assert_eq!(keyword, Keyword::END),
IRe... | Rust | 0 |
"Things I'm Grateful For": SectionDefinition(
description="Express gratitude for people, events, achievements, or circumstances in your life",
aliases=["Gratitude", "Grateful", "Thankful", "Appreciation", "Blessings"],
examples=[
"grateful for family support",
... | Python | 1 |
2.0 / (1.0 + (-t * a).exp()) - 1.0
}
#[inline]
/// calculates the derivative based on the function result
pub fn bipolar_sigmoid_derivative(result: f32, a: f32) -> f32 {
0.5 * a * (1.0 - result.powi(2))
}
/// calculates the squared error of `actual`.
///
/// `E(ideal, actual) = sum((ideal - actual)^2)`
pub fn ... | Rust | 0 |
import requests
from bs4 import BeautifulSoup
import re
def get_text(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# mw-parser-output to klasa HTML uzywana na platformie MediaWiki - jest glownym kontenerem dla tresci
content = soup.find('div', class_='mw-parser-o... | Python | 1 |
.name, params);
}
}
// Get extra API Info from Config: TODO: remove
if let Some(kong) = ®.kong {
for (name, api) in kong.extra_apis.clone() {
services.insert(name, APIServiceParams {
uris: api.uris.unwrap_or("".into()),
hosts: api.hosts.join(",... | Rust | 0 |
NOP => 1,
MODE_A::ALLBANKS_PRECHARGE => 2,
MODE_A::LOAD_MODEREG => 3,
MODE_A::AUTO_REFRESH => 4,
MODE_A::EXT_LOAD_MODEREG => 5,
MODE_A::DEEP_POWERDOWN => 6,
}
}
}
#[doc = "Reader of field `MODE`"]
pub type MODE_R = crate::R<u8, MODE_A>;
impl MODE_R... | Rust | 0 |
t.insert(&k, k.clone()).unwrap();
}
for (i, (k, v)) in t.iter().map(|res| res.unwrap()).enumerate() {
let should_be = kv(i);
assert_eq!(should_be, &*k, "{:#?}", t);
assert_eq!(should_be, &*v);
}
for (i, (k, v)) in t.iter().map(|res| res.unwrap()).enumerate() {
let shou... | Rust | 0 |
r field `VLINE`"]
pub struct VLINE_W<'a> {
w: &'a mut W,
}
impl<'a> VLINE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3fff << 16)) | (((value as u32) & 0x3fff) << 16);
self.w
}... | Rust | 0 |
enerates the page"
body = template.loader.get_template(template_name)
seen = set()
def traverse(node, collect=[]):
cont = {"post": node, 'user': request.user, 'request': request}
html = body.render(cont)
collect.append(f'<div class="indent" ><div>{html}</div>')
for child ... | Python | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional
import torch
from torch import Tensor
@torch.jit.script
def script_skip_tensor_list(x: List[Tensor], mask... | Python | 1 |
from phantom import FiniteStateMachineEnv, FSMStage, Network
from phantom.metrics import NotRecorded
from phantom.utils.rllib.train import RLlibMetricLogger
from . import MockBaseEnv, MockEpisode, MockMetric
def test_fsm_logging():
env = FiniteStateMachineEnv(
num_steps=2,
network=Network(),
... | Python | 1 |
\t{:.3f}"
)
print(formatter_result.format(*results))
# %%
# Run the benchmark
# -----------------
#
# We will compare three approaches:
#
# * an initialization using `k-means++`. This method is stochastic and we will
# run the initialization 4 times;
# * a random initialization. This method is stochastic as... | Python | 1 |
[](https://crates.io/crates/schema_analysis)
[](https://docs.rs/schema_analysis/)
Ever wished you could figure out what was in that json file? Or maybe it was xml... Ehr, yaml?
It was definitely toml.
Alas, many great ... | Rust | 0 |
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from dateutil.parser import isoparse
T = TypeVar("T", bound="VerifiedAuthenticator")
@_attrs_define
class VerifiedAuthenticator:
"""
Attributes:
created_at (datetime.datetime... | Python | 1 |
数: {count} (会话ID: {session_id})"
)
return count
return 0
except Exception as e:
logger.error(f"获取 {days} 天内消息总数失败: {e}, session_id={session_id}")
return 0
async def get_active_users(
self, session_id: str, days: int = ... | Python | 1 |
actix_web=debug, info"); // Setting Environmental Variables
env_logger::init(); // Initial env_logger
HttpServer::new(move || {
App::new()
.data(rbatis.to_owned())
.wrap(Logger::default())
.service(web::scope("/api")
.configure(controller::v1::api::con... | Rust | 0 |
parse_args()
task = Task.init(project_name=args.clearml_project, task_name=args.clearml_task)
if args.lm_alpha is not None:
args.lm_alpha = float(args.lm_alpha)
if args.lm_beta is not None:
args.lm_beta = float(args.lm_beta)
evaluate_wav2vec2am(
args.model,
args.csv,
... | Python | 1 |
'sr-Latn': 'aramejski', 'sv': 'arameiska', 'sw': 'Kiaramu', 'ta': 'அராமைக்', 'te': 'అరామైక్', 'th': 'อราเมอิก', 'to': 'lea fakaʻalāmiti', 'tr': 'Aramice', 'ug': 'ئارامۇچە', 'uk': 'арамейська', 'vi': 'Tiếng Aramaic', 'yi': 'אַראַמיש', 'yrl': 'aramaiku', 'yue': '阿拉米文', 'yue-Hans': '阿拉米文', 'yue-Hant': '阿拉米文', 'zh': '阿拉米语'... | Python | 1 |
_unstable();
writer.serialize_ilint(self.value().len() as u64)?;
for key in keys {
let value = match self.value.get(key) {
Some(s) => s,
None => return Err(ErrorKind::UnableToSerialize),
};
serialize_string_tag_from_value(key, writer)?;... | Rust | 0 |
'b cpal::OutputCallbackInfo) + Send>;
pub struct AudioPlayer {
#[allow(dead_code)]
stream: Box<dyn cpal::traits::StreamTrait>,
pub volume: Arc<AtomicU16>,
}
impl AudioPlayer {
pub fn new() -> Result<(Self, Audio)> {
let host = cpal::default_host();
let device = host
.defaul... | Rust | 0 |
self.macro = macro
self.fPublished = fPublished
class GroupShape(Serialisable):
nvGrpSpPr = Typed(expected_type=NonVisualGroupShape)
nonVisualProperties = Alias("nvGrpSpPr")
grpSpPr = Typed(expected_type=GroupShapeProperties)
visualProperties = Alias("grpSpPr")
pic = Typed(expected_type... | Python | 1 |
# Generated by Django 2.2.6 on 2019-12-19 15:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("account", "0036_auto_20191209_0407")]
operations = [
migrations.AlterField(
model_name="customerevent",
name="type",
f... | Python | 1 |
ualMachineDisk.objects.filter(block_device_id__in=blockdevice_map),
process_virtualmachinedisk,
)
return dest_node_config
def _duplicate_entry_set(
queryset, process_entry: Optional[Callable] = None
) -> Dict[int, int]:
""" "Duplicate entries in the queryset, optionally further processing the... | Python | 1 |
}", counter, timer.elapsed());
}
#[allow(unused)]
#[should_panic]
#[test]
fn test_self_cartesian_product_zero() {
use std::time::Instant;
let data : &[i32] = &[1, 2, 3];
let n = 0;
let mut counter = 0;
let timer = Instant::now();
self_cartesian_prod... | Rust | 0 |
ub.val.bindings.default = {}
config_stub.val.bindings.commands = bindings
keyhint.update_keyhint(usertypes.KeyMode.normal, '<')
assert keyhint.text() == expected_text(
('<', 'yellow', 'a', 'message-info cmd-<a'),
('<', 'yellow', 'b', 'message-info cmd-<b'))
def test_color_swi... | Python | 1 |
mut value: AggregateValueEnum = struct_ty.get_undef().into();
for (i, arg) in args.into_iter().enumerate() {
value = self
.builder
.build_insert_value(value, arg, i as u32, "init")
.expect("Failed to initialize struct field.");
}
let s... | Rust | 0 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from .source import SourceSerpstat
__all__ = ["SourceSerpstat"]
| Python | 1 |
r_configs=server_configs,
)
exp_time = float('inf')
exp_list = []
for i in [2]:
configuration_to_test = [
# format num_prefixes, random_req_ratio, common_prefix_ratio, total_reqs, rps
# scale_to_gpu([60, 0.0, 0.0, 300, 1], i / 2),
# scale_to_gpu([60, 0.0, 0.0, 900, 3], i / ... | Python | 1 |
post(&self.url)
.with_header("Content-Type", "application/json")
.with_body(payload)
.send()
.is_ok()
}
}
#[allow(unused_imports)]
use agent::job_client::JobClient;
#[allow(unused_imports)]
use agent::system_info_client::SystemInfoClient;
#[allow(unused_imports)]
us... | Rust | 0 |
)
if layer == 2:
self.crnn.append(
nn.Sequential(
nn.Conv2d(
in_channels=128,
out_channels=128,
kernel_size=(3, 3),
),
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.