text string | label_name string | labels int64 |
|---|---|---|
ew(-1, reference.shape[-2], reference.shape[-1]), 1)
imgs = torch.zeros(5*pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3])
for i in range(pred.shape[0]):
imgs[5*i] = ms[i]
imgs[5*i+1] = torch.abs(ms[i]-pred[i])/torch.max(torch.abs(ms[i]-pred[i]))
imgs[5*i+2] = pred[i]
... | Python | 1 |
#Turtle Racing Project
import dis
import random
from turtle import Turtle, Screen
is_race_on = False
starting_y_position = 100
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
screen = Screen()
screen.bgcolor('black')
screen.setup(width=500, height=400)
while True:
user_bet = screen... | Python | 1 |
y in ("S", "s") and user_options["ui_mode"] != 1:
if sort_by[0]:
sort_by[0] = ""
else:
clear_lines_above(num_lines)
num_lines = 0
num_lines += count_and_print("(i) 请按下排序依据对应的序号:")
... | Python | 1 |
:MemLoad => ":mem-load",
OpCategory::CastBoxed => ":cast-boxed",
OpCategory::RegOp => ":reg-op",
OpCategory::Ret => ":ret",
OpCategory::Unreachable => ":unreachable",
}
}
pub fn fn_op_categories(
ehx: &mut EvalHirCtx,
b: &mut Option<Builder>,
span: Span,
arg_list_val... | Rust | 0 |
WIKITQ_EVAL = """
Here is the original question, the correct answer, and the candidate answer. Please evaluate whether the correct answer and the candidate answer are consistent.
# Examples:
-
Question: What is the capital of France?
Candidate Answer: The capital of France is Paris
Correct Answer: Paris is the capita... | Python | 1 |
v_image[y][x] > 127 and x + 1 == len(cv_image[y]))):
length_of_white_segment = x - last_black_pixel_x_position
channel_data.append([last_black_pixel_x_position, y, length_of_white_segment, 1, -1])
num_elems += 1
print "Optimizing Keyway Profile"
channel_data_classifier = 1
for i in range(0, len(channel_d... | Python | 1 |
result = index[-10:5:1]
tm.assert_index_equal(result, index)
result = index[4:-10:-1]
expected = Index(list("yxdcb"), dtype="string[pyarrow_numpy]")
tm.assert_index_equal(result, expected)
def test_slice_locs_dup(self):
index = Index(["a", "a", "b", "c", "d", "d"])
... | Python | 1 |
intln!( "Desk coords: {}/{}", x, y );
}
}
}
<filename>src/common.rs<gh_stars>0
use crate::error::GlueError;
use crate::Result;
use std::ffi::CString;
use std::path::PathBuf;
/// Convert an Into<PathBuf> into a CString.
#[inline]
pub(crate) fn into_path_to_cstr<T: Into<PathBuf>>(path: T) -> Result<CString> {
... | Rust | 0 |
diff_matrix[i, j] = prox_val - fed_val
sns.heatmap(diff_matrix, annot=True, fmt=".1f", cmap="RdBu_r", center=0,
xticklabels=all_regions, yticklabels=all_regions)
plt.... | Python | 1 |
import bpy
from bpy.props import IntProperty, FloatProperty, StringProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode
import topologic
def processItem(item):
face = item[0]
bfv1 = topologic.FaceUtility.VertexAtParameters(face,0,0)
bfv2 = topologic.FaceUtilit... | Python | 1 |
X86_INS_VPOR = 1302,
X86_INS_VPPERM = 1303,
X86_INS_VPROLD = 1304,
X86_INS_VPROLQ = 1305,
X86_INS_VPROLVD = 1306,
X86_INS_VPROLVQ = 1307,
X86_INS_VPRORD = 1308,
X86_INS_VPRORQ = 1309,
X86_INS_VPRORVD = 1310,
X86_INS_VPRORVQ = 1311,
X86_INS_VPROTB = 1312,
X86_INS_VPROTD = 1313... | Rust | 0 |
from model import InputForm
from flask import Flask, render_template, request
from compute import compute_gamma as compute
import sys, os, inspect
app = Flask(__name__)
@app.route('/vib3_ext', methods=['GET', 'POST'])
def index():
form = InputForm(request.form)
if request.method == 'POST' and form.validate():... | Python | 1 |
Any]])
| "SplitRated" >> beam.Partition(
lambda x, n_part: int(bool(x[1]["ratings"])), 2))
# Downsample non-rated.
non_rated_notes = data_lib.downsample(non_rated_notes, _N_DOWNSAMPLE.value,
_RANDOM_S... | Python | 1 |
serial: {}", e));
p.exp_regex("\\(liumos\\)").unwrap();
println!("Reached to liumOS prompt via serial");
p
}
fn connect_to_liumos_builder() -> PtySession {
let cmd = "docker exec -it liumos-builder0 /bin/bash";
let mut p = spawn(&cmd, Some(TIMEOUT_MILLISECONDS))
.unwrap_or_else(|e| panic!(... | Rust | 0 |
(rhs_simple_var_name)
elif final_rhs_var.dstr(): # RHS is complex
rhs_expr_str = final_rhs_var.dstr()
if rhs_expr_str != original_lhs_name_for_alias:
self.alias_mapping[rhs_expr_str] = original_lhs_name_for_alias
self.tracked_vars.add... | Python | 1 |
"""
В то далёкое время, когда Паша ходил в школу, ему очень не нравилась формула Герона
для вычисления площади треугольника, так как казалась слишком сложной.
В один прекрасный момент Павел решил избавить всех школьников от страданий и написать и
распространить по школам программу, вычисляющую площадь треугольника по ... | Python | 1 |
from PyQt6.QtWidgets import QWidget, QLabel, QVBoxLayout, QPushButton
from PyQt6.QtCore import Qt
class TelaAjuda(QWidget):
def __init__(self, stack):
super().__init__()
self.stack = stack
self.origem = 0
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
... | Python | 1 |
to_cipher("prince").unwrap();
let x = 0x0123456789abcedf;
assert_eq!(x, cipher.reflection_layer(cipher.reflection_layer(x)));
}
#[test]
fn encryption_test() {
let cipher = cipher::name_to_cipher("prince").unwrap();
let key = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,... | Rust | 0 |
ive,
)
.unwrap();
vg_native::Engine::run::<vg_native::runtime::Recommended, _>(move || {
match rx.try_recv() {
Ok(_) => {
if run_cargo(&opts.manifest_path, opts.build_path.clone(), "build", None) {
... | Rust | 0 |
M) -> i16 {
hiword(lp.0 as _)
}
fn get_xbutton_wparam(wp: WPARAM) -> i16 {
hiword(wp.0 as _)
}
fn get_button_states(wp: WPARAM) -> u32 {
loword(wp.0 as _) as _
}
fn lparam_to_point(lp: LPARAM) -> PhysicalPoint<i32> {
Physical(Point::new(get_x_lparam(lp) as _, get_y_lparam(lp) as _))
}
fn xbutton_to_... | Rust | 0 |
re without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this perm... | Rust | 0 |
;
use arangodb_models::model;
use arangodb_types::traits::DBCollection;
use arangodb_types::types::DBInfo;
use arangodb_types::types::DBUuid;
#[derive(Debug)]
pub struct MutexCollection {
db_info: Arc<DBInfo>,
}
impl MutexCollection {
// CONSTRUCTORS ----------------------------------------------------------... | Rust | 0 |
from django.urls import path
from . import views
from .views import NoteDeleteView,NoteDetailView
urlpatterns = [
path('', views.accueil, name='voxnote-accueil'),
path ('notes/', views.mesNotes, name='voxnote-notes'),
path('about/', views.about, name='voxnote-about'),
path('notes/<int:pk>/delete/', Not... | Python | 1 |
'''
Provide the basic vocabular instance.
'''
class Vocab(object):
def __init__(self):
self.idx2word = {}
self.word2idx = {}
def __len__(self):
return len(self.idx2word.keys())
@property
def words(self):
'''All the words in the vocab.
Returns
-... | Python | 1 |
g('pthreads')
# OSX frameworks
if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)):
if not (conf.CheckOSXFramework('CoreServices') and
conf.CheckOSXFramework('IOKit') and
conf.CheckOSXFramework('Security') and
conf.CheckOSXFramework('SystemConf... | Python | 1 |
msg_data.clone(),
},
);
}
}
<filename>src/main.rs
use std::convert::TryInto;
use std::fs;
fn main() {
let filename: &str = "input.txt";
let mut num_valid_passwords = 0;
let content = fs::read_to_string(filename)
.expect("File not found");
for line in content.lines() ... | Rust | 0 |
"], torch.tensor(0.0))
assert_equal(loss_dict["loss_rpn_box_reg"], torch.tensor(0.0))
assert_equal(loss_dict["loss_mask"], torch.tensor(0.0))
def test_forward_negative_sample_krcnn(self):
model = torchvision.models.detection.keypointrcnn_resnet50_fpn(
weights=None, weights_backb... | Python | 1 |
st]
fn ripemd128_messages() {
hash_test("", hex!("cdf26213a150dc3ecb610f18f6b38b46"));
hash_test("a", hex!("86be7afa339d0fc7cfc785e72f578d33"));
hash_test("abc", hex!("c14a12199c66e4ba84636b0f69144c77"));
hash_test("message digest", hex!("9e327b3d6e523062afc1132d7df9d1b8"));
hash_test(
"abcd... | Rust | 0 |
scheduler: KarrasDiffusionSchedulers
vae: AutoencoderKL
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
... | Python | 1 |
pub struct AcceptingFilter;
impl<K: Ord+Clone> ItemFilter<K> for AcceptingFilter {
#[inline(always)] fn accept(&mut self, k: &K) -> bool {
black_box(k);
black_box(true)
}
#[inline(always)] fn is_noop() -> bool { false }
}
}
mod ts {
use x86::bits64::t... | Rust | 0 |
h")
# Pair input
self.assertRaises(
ValueError,
tokenizer_r.batch_encode_plus,
p2,
max_length=max_length,
padding="max_length",
)
def test_encodings_from_xnli_dataset... | Python | 1 |
PathBuf,
#[structopt(long = "scale")]
scale: Option<u32>,
#[structopt(short = "q", long = "quiet")]
quiet: bool,
#[structopt(short = "v", parse(from_occurrences))]
verbose: u8,
}
fn run(opts: Options) -> Result<(), LochnesError> {
debug!("Options: {:#?}", opts);
#[cfg(feature = "ea... | Rust | 0 |
Error(
format!("transaction failed: {:?}",
treasury.get_signature_status(&transactions.last().unwrap().signatures.get(0).unwrap())
.unwrap()).to_string(),
module_path!().to_string()
)
);
assert!(false);
}
}
fn do... | Rust | 0 |
::RedBanner => RED_BANNER,
BlockType::BlackBanner => BLACK_BANNER,
BlockType::WhiteWallBanner => WHITE_WALL_BANNER,
BlockType::OrangeWallBanner => ORANGE_WALL_BANNER,
BlockType::MagentaWallBanner => MAGENTA_WALL_BANNER,
BlockType::LightBlueWallBanner => LIGHT_BLUE_WALL_BANNER,
BlockType::YellowWallBan... | Rust | 0 |
from Thesaurus"),
"geonode:handler": "thesaurus",
"properties": thesauri,
}
# We are going to hide the tkeywords property if there's no thesaurus configured
# We can't remove the property altogether, since hkeywords relies on tkeywords for positioning
if not thes... | Python | 1 |
turn super_spike_backward(grad_output, ctx.saved_tensors[0], ctx.alpha)
class SuperSpike(SurrogateFunctionBase):
def __init__(self, alpha=1.0, spiking=True):
'''
* :ref:`API in English <SuperSpike.__init__-en>`
.. _SuperSpike.__init__-cn:
`SuperSpike: Supervised learning in multi-... | Python | 1 |
from odoo import _, fields, models
class HrExpenseStripeCardBlockWizard(models.TransientModel):
_name = 'hr.expense.stripe.card.block.wizard'
_description = 'A wizard used to block a card'
card_id = fields.Many2one(comodel_name='hr.expense.stripe.card', string="Card To Block")
cancellation_reason = f... | Python | 1 |
Module = REDISMODULE_KEYTYPE_MODULE,
}
impl From<c_int> for KeyType {
fn from(v: c_int) -> Self {
KeyType::from_i32(v).unwrap()
}
}
#[derive(Primitive, Debug, PartialEq)]
pub enum ReplyType {
Unknown = REDISMODULE_REPLY_UNKNOWN,
String = REDISMODULE_REPLY_STRING,
Error = REDISMODULE_R... | Rust | 0 |
"""
:copyright: © 2019 by the Lin team.
:license: MIT, see LICENSE for more details.
"""
from lin.exception import APIException
class BookNotFound(APIException):
code = 404 # http状态码
msg = '没有找到相关图书' # 异常信息
error_code = 80010 # 约定的异常码
class RefreshException(APIException):
code = 401
... | Python | 1 |
"checksum"), hexadecimal)
yield Enum(UInt16(self, "subsystem"), self.SUBSYSTEM_NAME)
yield UInt16(self, "dll_flags")
yield filesizeHandler(UInt32(self, "size_stack_reserve"))
yield filesizeHandler(UInt32(self, "size_stack_commit"))
yield filesizeHandler(UInt32(self, "size_heap_r... | Python | 1 |
,
FieldType::NftSource => &0x21,
// Proof-of-burn fields:
FieldType::BurnUtxo => &FIELD_TYPE_BURN_UTXO,
// Prood-of-reserves fields:
FieldType::LockDescriptor => &FIELD_TYPE_LOCK_DESCRIPTOR,
FieldType::LockUtxo => &FIELD_TYPE_LOCK_UTXO,
}
... | Rust | 0 |
, Err, InitErr>);
/// Create boxed service factory
pub fn factory<T, R, C>(
factory: T,
) -> BoxServiceFactory<C, R, T::Response, T::Error, T::InitError>
where
C: 'static,
R: 'static,
T: ServiceFactory<R, C> + 'static,
T::Response: 'static,
T::Error: 'static,
T::InitError: 'static,
{
Bo... | Rust | 0 |
),
"::",
stringify!(dir)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<ma_charset_info_st>())).codepage as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(ma_charset_info_st),
"::",
... | Rust | 0 |
o.fidl: 10:21: EndOfSentence <.>
"
);
}
#[test]
fn lexer_reference_with_apostrophe() {
let mut compiler = DocCompiler::new();
let source =
Rc::new(Source::new("sdk/foo/foo.fidl".to_owned(), 10, 4, "`xyz`'s.".to_owned()));
let items = reduce_lexems(&mut compiler, ... | Rust | 0 |
from skimage import io
from skimage import transform as sktransform
import numpy as np
import json
import os
import random
from PIL import Image
from imgaug import augmenters as iaa
from .DeepFakeMask import dfl_full, facehull, components, extended
import cv2
import tqdm
def name_resolve(path):
name = os.path.spl... | Python | 1 |
t<PathBuf> {
let home_dir = dirs::home_dir().ok_or(anyhow::anyhow!("Could not find home directory"))?;
let db_dir = home_dir.join(".tinytunes");
std::fs::create_dir_all(&db_dir)?;
Ok(db_dir)
}
fn create_db_file() -> Result<String> {
let app_folder = create_app_folder()?;
let db_file = format!(
"sqlite... | Rust | 0 |
cond1 = sp_merge["next_started_at"] - sp_merge["finished_at"] <= max_time_gap # time constraint
cond2 = sp_merge["location_id"] == sp_merge["next_location_id"]
cond3 = sp_merge["index_temp"] != sp_merge["next_id"] # already merged
cond4 = sp_merge["next_type"] != "tripleg" # no tripleg... | Python | 1 |
::current_dir()?.join("src").join("resources").join("profiles");
let out_dir = env::var("OUT_DIR")?;
let dest_path = Path::new(&out_dir).join("all_profiles.rs");
let mut all_profiles = File::create(&dest_path)?;
writeln!(&mut all_profiles, r#"["#, )?;
for f in fs::read_dir(dpath)? {
let f... | Rust | 0 |
INSTALLED_APPS = [
# other apps
'api',
'rest_framework',
]
| Python | 1 |
closed_positions.append(pos)
elif pos['direction'] == -1:
if price <= pos['tp'] or price >= pos['sl'] or pos['bars_held'] >= pos['horizon']:
self.execute_trade(-1, pos['open_price'], pos['open_time'], pos['confidence'])
... | Python | 1 |
;
use nix::fcntl;
use nix::sched;
use nix::sys::stat;
use nix::unistd;
use nix::unistd::{Gid, Uid};
use crate::container::{Container, ContainerStatus};
use crate::notify_socket::NotifyListener;
use crate::process::{fork, Process};
use crate::rootfs;
use crate::spec;
use crate::stdio::FileDescriptor;
use crate::tty;
us... | Rust | 0 |
deref(&self) -> &T {
self.element.as_ref().unwrap()
}
}
impl<'a, T> Drop for Ref<'a, T> {
fn drop(&mut self) {
mem::forget(self.element.take().unwrap());
}
}
pub struct RefMut<'a, A, B, C, D, E, F, G, H> where
A: Packable3 + 'a, B: Packable3 + 'a, C: Packable3 + 'a, D: Packable3 + 'a,
... | Rust | 0 |
Vec<u8> = Vec::new();
buf.push(self.delay);
let mut s34 = self.ks_curve << 4;
let wave_bytes = self.wave.to_bytes();
if wave_bytes[0] == 1 {
s34.set_bit(0, true);
}
buf.push(s34);
buf.push(wave_bytes[1]);
let mut s42 = (self.coarse + 24) as... | Rust | 0 |
if checksum:
cached_content = index_content_cache.get(checksum)
if cached_content:
return cached_content
res = False
for ftype in FTYPES:
buf = getattr(self, '_index_%s' % ftype)(bin_data)
if buf:
res = buf.replace('\x0... | Python | 1 |
2f}" if score is not None else "N/A"
# Print the title, overview, and score (or N/A for missing score)
print(f"Title: {title}\nOverview: {overview}\nReleased Date:{release_date}\nScore: {score_display}\n{'-'*40}\n")
# Step 4: Optimized Search for Recommendations
def perform_optimized_search(query, to... | Python | 1 |
<u8, u8>;
#[doc = "Write proxy for field `HSTADDRP7`"]
pub struct HSTADDRP7_W<'a> { w: &'a mut W }
impl<'a> HSTADDRP7_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 24)) | (((value as u32)... | Rust | 0 |
.len() != 32 {
Err(E::invalid_length(v.len(), &stringify!($len)))
} else {
let mut ret = [0; 32];
ret.copy_from_slice(v);
Ok(AssetId(sha256::Midstate::from_inner(ret)))
}
... | Rust | 0 |
import sys
import glob
import os
import SimpleITK as sitk
import numpy as np
from medpy.metric import binary
import argparse
from tqdm import tqdm
def read_nii(path):
itk_img = sitk.ReadImage(path)
spacing = np.array(itk_img.GetSpacing())
return sitk.GetArrayFromImage(itk_img), spacing
def dice(pred, labe... | Python | 1 |
wrap();
println!("Sending request");
let response = client.execute("eth_getAccounts", vec![]).await;
println!("Got response");
// then
assert_eq!(response, Ok(rpc::Value::String("x".into())));
}
}
use xjbutil::boxed_slice;
use xjbutil::slice_arena::SliceArena;
use xjbutil::v... | Rust | 0 |
from typing import Any
import matplotlib.pyplot as plt
import numpy as np
import torch
def validate_numpy_array(value: Any):
r"""
Validates the input and makes sure it returns a numpy array (i.e on CPU)
Args:
value (Any): the input value
Raises:
TypeError: if the value is not a nump... | Python | 1 |
>) {
let base = msg::get_root_as_base(&control);
let is_sync = base.sync();
let inner_type = base.inner_type();
let cmd_id = base.cmd_id();
let op: Box<Op> = if inner_type == msg::Any::SetTimeout {
// SetTimeout is an exceptional op: the global timeout field is part of the
// Isolate state (not the I... | Rust | 0 |
from pydantic import BaseModel
class DefaultResponse(BaseModel):
success: bool
message: str | Python | 1 |
'e-BH (dynamic)'], 'e-BH'),
(name_map['e-BH (round, dynamic)'], 'e-BH'),
(name_map['e-BH (UMI)'], 'e-BH'),
],
height=height * .6,
font_scale=font_scale * 1.5,
gridspec_kws=gridspec_kws)
save_figure(ebh_base_fdr_diff_fg,
... | Python | 1 |
vation': ['relu'], 'NN__alpha': [1.0],
'NN__hidden_layer_sizes': [(36, 36)], 'NN__learning_rate_init': [0.016]}
}
if args.dataset1:
datasets.append(dataset1_details)
elif args.dataset2:
datasets.append(dataset2_details)
elif not args.dataset1 and not args.d... | Python | 1 |
rust<gh_stars>1-10
//! Miscellaneous helper functions
use crate::errors::{ProtocolError, Result};
use bigdecimal::BigDecimal;
use nash_mpc::rust_bigint::traits::Converter;
use nash_mpc::rust_bigint::BigInt;
use sha3::{Digest, Keccak256};
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(feature = ... | Rust | 0 |
mut sec = total_usec / 1000000;
let mut usec = (total_usec % 1000000) as i32;
if usec < 0 {
sec -= 1;
usec += 1000000;
}
(sec, usec)
}
/// Convert ticks to seconds and fractional nanoseconds.
pub fn to_sec_nsec(ticks: i64) -> (i64, i32) {
let mut sec = ticks / SECOND;
let mut r... | Rust | 0 |
-> Result<()> {
use std::{io::Write, net::TcpStream};
let (receiver, _join_handle) = source_events();
let mut source_stream = TcpStream::connect("127.0.0.1:9999")?;
write!(
&mut source_stream,
"10\n2/U/2/3\n1/B/2/9\n3/F/2/3\n4/S/2/hi\n"
)?;
asser... | Rust | 0 |
R BY cnt DESC\n"
"LIMIT 20;"
)
examples: List[Dict[str, Any]] = []
try:
for row in tp.query(examples_query):
examples.append(
{
"sliceId": getattr(row, "slice_id", None),
... | Python | 1 |
"""
filters.py - misc stuff for handling LDAP filter strings (see RFC2254)
See http://www.python-ldap.org/ for details.
\$Id: filter.py,v 1.9 2011/07/22 07:20:53 stroeder Exp $
Compability:
- Tested with Python 2.0+
"""
from ldap import __version__
def escape_filter_chars(assertion_value,escape_mode=0):
"""
R... | Python | 1 |
::from(p).map(|_| unreachable!()).or_else(|e| {
assert_eq!(e, 42);
Ok(())
})
}
#[wasm_bindgen_test(async)]
fn ok_future_is_resolved_promise() -> impl Future<Item = (), Error = JsValue> {
let f = futures::future::ok(JsValue::from(42));
let p = future_to_promise(f);
JsFuture::from(p)
... | Rust | 0 |
code('%s:%s' % (upnp_config['username'], upnp_config['password'])).strip()
UPNP_AUTH = 'Basic %s' % UPNP_AUTH
else:
UPNP_AUTH = UPNP_AUTH_NONE
return UPNP_AUTH
def get_upnp_port():
global UPNP_PORT
if UPNP_PORT:
return UPNP_PORT
UPNP_PORT = config_file.read_con... | Python | 1 |
none"
},
"interface": [
{
"name": "eth/0/0",
"enabled": false,
"@enabled": {
"yang:operation": "replace",
"yang:orig-default": false,
"yang:orig-value": "true"
}
}, {
"@": {
... | Rust | 0 |
n `Error::PortMidi(_)` if the given id is invalid.
pub fn new(id: PortMidiDeviceId) -> Result<Self> {
let dev_inf_ptr = unsafe { ffi::Pm_GetDeviceInfo(id) };
if dev_inf_ptr.is_null() {
Err(Error::PortMidi(ffi::PmError::PmInvalidDeviceId))
} else {
let name = unsafe { ... | Rust | 0 |
mode,
)));
// TODO: BSSRDF
}
}
// Retro-reflection.
bxdfs.add(arena.alloc(DisneyRetro::new(diffuse_weight * c, rough)));
// Sheen (if enabled).
if sheen_weight > 0.0 {
... | Rust | 0 |
nvalid value"));
Ok(())
}
#[test]
fn test_oem_string_invalid() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd1 = Command::cargo_bin(CLI_COMMAND)?;
cmd1.arg("--oem-string").arg("0");
cmd1.assert()
.failure()
.stderr(predicate::str::contains("string number 0"));
... | Rust | 0 |
(10.0), 1.1);
//!
//! // Set the canvas background pixel value.
//! c.set_background(100);
//!
//! // Clear the canvas and paint the light spots.
//! c.draw();
//!
//! // Access the rendered image data as a linear pixel array.
//! let image_pixbuf = c.pixels();
//!
//! // Get pixel at x = 100, y = 200.
//! let (x, y) =... | Rust | 0 |
# BIMTester - OpenBIM Auditing Tool
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of BIMTester.
#
# BIMTester is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version... | Python | 1 |
crate::Error {
location: $loc.clone(),
message: format!( $fmt, $( $arg ),+ ),
})
};
}
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::Buildable;
use crate::Filter;
use glib::objec... | Rust | 0 |
1005
# Test new voice
speaker_id = system.get_speaker_id_for_voice("new_voice")
assert speaker_id == 1006
assert system.voice_id_to_index["new_voice"] == 6
@patch('builtins.open', mock_open())
@patch('torch.load')
def test_load_voice_contexts(sel... | Python | 1 |
ps'
from nund3e94oay import lrq6hpa7kzf, sfuuajajz9t as tcugkkg9jp9, u62c32oq5dm, mo8z1f78glh as m8az7azi7ga, hdrznn65fwe, dtpvawijyc4 as ggj_n5tkej5, rbmwhfdhbbm, f1wpsajrc4s as llbg7olfca1, pegxq_otqa_ as l8hgtowho45, cvos0twvlps
st35czcrr4p
0j.wb2t8zbilhm >>= ''
raise w3lhpsr7d10
@lambda j9u3zavw2g_,... | Python | 1 |
` ツールで最新のファイル内容を確認してから `edit_file` ツールを使用してください。\n"
" - ユーザーが提示した内容が diff 形式(行頭に `+` や `-` が付く形式)の場合、`edit_file` ツールに渡すコードからは、これらの記号や差分情報を示す部分を取り除き、純粋なコードのみを指定するようにしてください。\n"
"3. 具体的な実装計画を立てる\n"
"4. コードを記述、編集する\n"
"5. コード編集後、シェルコマンド操作ツールを使用して、関連するテスト、リンター、フォーマッターを実行する\n... | Python | 1 |
from celery.result import AsyncResult
from openff.fragmenter.fragment import Fragment, FragmentationResult, PfizerFragmenter
from openff.bespokefit._tests.executor.mocking.celery import mock_celery_task
from openff.bespokefit.executor.services.fragmenter import worker
from openff.bespokefit.executor.services.fragmente... | Python | 1 |
xff], [0x0 ~> 0x7f]]
#[inline]
pub fn fiat_25519_to_bytes(out1: &mut [u8; 32], arg1: &fiat_25519_tight_field_element) -> () {
let mut x1: u64 = 0;
let mut x2: fiat_25519_u1 = 0;
fiat_25519_subborrowx_u51(&mut x1, &mut x2, 0x0, (arg1[0]), 0x7ffffffffffed);
let mut x3: u64 = 0;
let mut x4: fiat_25519_u1 = 0;
... | Rust | 0 |
email=os.getenv("EMAIL"),
base_url="https://ocr.kandianguji.com",
token=os.getenv("TOKEN")
)
for input_file in os.listdir(os.path.join(output_path, "images")):
if not input_file.endswith(".png"):
continue
request = HanApiRequest(
input_file=os.path.join(... | Python | 1 |
odel::utils::is_false;
pub use self::discriminator::{Discriminator, DiscriminatorParseError};
pub use self::flags::UserFlags;
/// The client user.
#[non_exhaustive]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ClientUser {
#[serde(flatten)]
user: User,
/// Whether the user has multi-factor a... | Rust | 0 |
impl Eq for pthread_cond_t {}
impl ::fmt::Debug for pthread_cond_t {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("pthread_cond_t")
.field("value", &self.value)
// FIXME: .field("__reserved", &self.__reserved)
... | Rust | 0 |
n1
assert box[1, 0] is button2
with pytest.raises(TypeError, match="The slice spans"):
button = box[:2, 0]
class TestLayoutProperties(TestCase):
"""test mixin with layout properties"""
class DummyTemplate(widgets.GridBox, LayoutProperties):
location = traitlets.Instance(... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import Animation
from config import map, algorithm
def K_means():
# 初始化中心圆点
num_center = map.num_agent
center_pos = np.zeros((2, num_center))
center_color = np.zeros((3, num_center))
center_color[0] = 1 #红色
# 为每个聚类赋予一个... | Python | 1 |
= 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 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `GPIO_FUNC19_IN_INV_SEL`"]
pub type GPIO_FUNC19_IN_INV_SEL_R = crate::R<bool, bo... | Rust | 0 |
= "Fail"
print(f"[{index+1}] ✅ API-Eval Done in {elapsed:.2f}s. Decision: {decision}")
return {'original_data': data_item, 'decision': decision, 'error': None}
except (json.JSONDecodeError, AttributeError):
print(f"[{index+1}] ❌ FAIL: API response is not valid J... | Python | 1 |
emp())
self.cc.has_function('abort')
def test_find_library_file(self, monkeypatch):
compiler = unix.Compiler()
compiler._library_root = lambda dir: dir
monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d)
libname = 'libabc.dylib' if sys.platform != 'cygwin' els... | Python | 1 |
f, "\\\\"),
'\n' => write!(self.buf, "\\n"),
'\r' => write!(self.buf, "\\r"),
'\t' => write!(self.buf, "\\t"),
c if c.is_control() => write!(self.buf, "\\u{:04x}", c as u32),
c => write!(self.buf, "{}", c),
}?;
}
... | Rust | 0 |
When SDL is no longer in use (the refcount in an `Rc<SdlDrop>` reaches 0), the library is quit.
#[doc(hidden)]
#[derive(Debug)]
pub struct SdlDrop;
impl Drop for SdlDrop {
#[inline]
fn drop(&mut self) {
use std::sync::atomic::Ordering;
let was_alive = IS_SDL_CONTEXT_ALIVE.swap(false, Ordering... | Rust | 0 |
filter_size=(3, 3),
init_scale=1.0,
name=None):
super(Conv2d, self).__init__(name=name)
assert len(filter_size) == 2
with self.variable_scope:
self.w = tf.get_variable(
'w',
shape=list(filter_size) + [in_dim, num_units],
init... | Python | 1 |
t W {
bits: u32,
}
impl super::STATICCONFIG {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W ... | Rust | 0 |
# 计算 均值和标准差, copied from https://zhuanlan.zhihu.com/p/104019160
import os
import numpy as np
from torch.utils.data import Dataset
from PIL import Image
def compute_mean_and_std(dataset):
import cv2
# 输入PyTorch的dataset,输出均值和标准差
mean_r = 0
mean_g = 0
mean_b = 0
for img, _ in dataset:
i... | Python | 1 |
]
const TEXT_TYPES: [(mime_guess::Mime, mime_guess::Mime); 6] = [
(mime::TEXT_PLAIN, mime::TEXT_PLAIN_UTF_8),
(mime::TEXT_HTML, mime::TEXT_HTML_UTF_8),
(mime::TEXT_CSS, mime::TEXT_CSS_UTF_8),
(mime::TEXT_CSV, mime::TEXT_CSV_UTF_8),
(
mime::TEXT_TAB_SEPARATED_VALUE... | Rust | 0 |
"""Simple function for embedding an IPython kernel
"""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import sys
from IPython.utils.frame import extract_module_locals
from .kernelapp import IPKe... | Python | 1 |
low[i]) / high[i]
medium_drop = (high[i] - medium[i]) / high[i]
average_lowdrop += low_drop
average_mediumdrop += medium_drop
print('{} droprate low: {:.2f}%, medium: {:.2f}%'.format(trackname[i], low_drop*100, medium_drop*100 ))
# logging.info('{} droprate low: {}, medium: {}'.... | Python | 1 |
struct CTRL_FFE_SRAM_DS_DM1_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_DM1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_DM1_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.