text string | label_name string | labels int64 |
|---|---|---|
from unittest.mock import MagicMock
import pytest
from rag_system.domain.conversation_manager import Message
from rag_system.use_cases.llm_client import OfflineLLMClient
from rag_system.use_cases.answer_generator import (
AnswerGenerator,
OfflineAnswerGenerator,
)
from langchain_openai import ChatOpenAI
cla... | Python | 1 |
If {
condition: Box<dyn IRNode>,
if_body: Vec<Box<dyn IRNode>>,
else_body: Option<Vec<Box<dyn IRNode>>>
}
#[ir_node]
struct LiteralExpression {
value: String,
type_: String // "number", "boolean" or "string"
}
#[ir_node]
struct NameExpression {
pub name: String
}
#[ir_node]
struct DirectExpre... | Rust | 0 |
test]
fn test_plus_operator() {
assert_eq!(CompactStr::from("a") + CompactStr::from("b"), "ab");
assert_eq!(CompactStr::from("a") + &CompactStr::from("b"), "ab");
assert_eq!(CompactStr::from("a") + "b", "ab");
assert_eq!(CompactStr::from("a") + &String::from("b"), "ab");
assert_eq!(CompactStr::from(... | Rust | 0 |
"""Tests for async interface."""
import asyncio
import os
import sys
import asynctest
import mmcv
import torch
from mmdet.apis import async_inference_detector, init_detector
if sys.version_info >= (3, 7):
from mmdet.utils.contextmanagers import concurrent
class AsyncTestCase(asynctest.TestCase):
use_defau... | Python | 1 |
_section, self.product_codes)
def get_columns(self):
return [self._make_column(product_code) for product_code in self.product_codes]
def get_values(self, item, evaluation_context=None):
case_id = self.case_id_expression(item)
domain = evaluation_context.root_doc['domain']
value... | Python | 1 |
/landingpage/IntrinsicsGuide/#text=_mm256_mask_adds_epu8&expand=204)
#[inline]
#[target_feature(enable = "avx512bw,avx512vl")]
#[cfg_attr(test, assert_instr(vpaddusb))]
pub unsafe fn _mm256_mask_adds_epu8(src: __m256i, k: __mmask32, a: __m256i, b: __m256i) -> __m256i {
transmute(vpaddusb256(a.as_u8x32(), b.as_u8x32... | Rust | 0 |
;
assert!(Expr::parse("^ a").is_err(), "Not a unary operator '^'");
assert!(Expr::parse("a + ").is_err(), "Missing second '+' operand");
assert!(Expr::parse("a - ").is_err(), "Missing second '-' operand");
assert!(Expr::parse("a * ").is_err(), "Missing second '*' operand");
assert!(Expr::parse("a / ... | Rust | 0 |
bench ... bench: [..]"));
}
// install
assert_that(p.cargo("install"),
execs().with_status(0));
assert_that(cargo_home(), has_installed_exe("foo"));
assert_that(p.cargo("uninstall").arg("foo"),
execs().with_status(0));
}
#[test]
fn dep_feature_in_cmd_line() {
l... | Rust | 0 |
,
pred_veh: Vehicle,
):
"""Plans the longitudinal trajectory"""
self.long_planner.reset(self.planning_problem.initial_state)
self.time_invariant_constraints = self._set_time_invariant_constraints()
traj_long = self.long_planner.plan(
reference_lon,
sel... | Python | 1 |
"]
pub type SENSITIVE_DMA_APBPERI_PMS_MONITOR_0 =
crate::Reg<u32, _SENSITIVE_DMA_APBPERI_PMS_MONITOR_0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SENSITIVE_DMA_APBPERI_PMS_MONITOR_0;
#[doc = "`read()` method returns [sensitive_dma_apbperi_pms_monitor_0::R](sensitive_dma_apbperi_pms_monitor_0::R) reader str... | Rust | 0 |
,
host_frame: HostPhysFrame,
readonly: bool,
) -> Result<()> {
let default_flags = EptTableFlags::READ_ACCESS
| EptTableFlags::WRITE_ACCESS
| EptTableFlags::PRIV_EXEC_ACCESS
| EptTableFlags::USERMODE_EXEC_ACCESS;
let ept_pml4e = &mut guest_ept_base[guest_addr.p4_index()];
if... | Rust | 0 |
= ReceiptParams::new(sapling.clone(), &spender_key, ¬e)
.expect("should be able to create receipt proof");
let proof = receipt
.post()
.expect("Should be able to post receipt proof");
proof
.verify_proof(&sapling)
.expect("proof should chec... | Rust | 0 |
La An instance of this class represents a loaded dll/shared
library, exporting functions using the standard C calling
convention (named 'cdecl' on Windows).
The exported functions can be accessed as attributes, or by
indexing with the function name. Examples:
<obj>.qsort -> callable object
... | Python | 1 |
import sys
import re
from pathlib import Path
import os
def main(argv):
print(os.getcwd())
module_name = "acegen_mod"
subroutine_names = ("model_size", "elastic", "residual", "jacobian", "plastic_output")
if len(argv) > 1:
name = argv[1]
else:
name = "tmp"
with open(name + ".f... | Python | 1 |
c_did_not_cal = list(zip(list(locations[0]), list(locations[1]), list(locations[2])))
for loc in loc_did_not_cal:
final_array[loc[0], loc[1], loc[2]] = \
np.min(final_array[loc[0] - 2: loc[0] + 3, loc[1] - 2: loc[1] + 3, loc[2] - 2: loc[2] + 3])
final_array[np.where(final_array > 0)] = np.lo... | Python | 1 |
raise Exception(f'Bucket {self.bucket} does not exist.')
client.list_blobs(self.bucket)
def __build_df(self, key: str) -> 'pd.DataFrame':
client = self.build_client()
df = pd.DataFrame()
bucket = client.get_bucket(self.bucket)
blob = bucket.get_blob(key)
dat... | Python | 1 |
const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeQueryChannelRange)).clone() })) as *mut c_void
}
#[no_mangle]
/// Creates a copy of the QueryChannelRange
pub extern "C" fn QueryChannelRange_clone(orig: &QueryChannelRange) -> QueryChannelRange {
orig.clone()
}
use lightning::l... | Rust | 0 |
letionOrderBackupIterator {
DeletionOrderBackupIterator {
remaining_backups : self.clone()
}
}
}
pub struct DeletionOrderBackupIterator {
remaining_backups : BackupsFolder
}
impl Iterator for DeletionOrderBackupIterator {
type Item = (Backup, BackupsFolder);
fn next(&mut ... | Rust | 0 |
pub fn read_u8(&self, offset: u8) -> u8 {
// offset 0 -> shift 0 | offset 1 -> shift 8
// offset 2 -> shift 16 | offset 3 -> shift 24
// offset 4 -> shift 0 | ...ect
let bitshift = (offset % 4) * 8;
(self.read_u32(offset) >> bitshift) as u8
}
/// Read the u32 for a giv... | Rust | 0 |
jects, num_interps, fps):
print("starting") # generate images
original = np.array([getOriginal(objects[0])])
inversion = np.array([getInversion(objects[0])])
seeds = []
labels = []
images = []
images.extend(np.repeat(original, 20, axis=0))
images.extend(np.repeat(inversion, 20, axis=0))
for object i... | Python | 1 |
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | Rust | 0 |
fer = replay_buffer
self.key_first_k = key_first_k
def __len__(self):
return len(self.indices)
def sample_sequence(self, idx):
(
buffer_start_idx,
buffer_end_idx,
sample_start_idx,
sample_end_idx,
buffer_target_key... | Python | 1 |
g, PartialEq)]
pub struct BinaryEncodedGenomeBuilder {
genome_length: usize,
}
impl BinaryEncodedGenomeBuilder {
/// Returns a new instance of the `BinaryEncodedGenomeBuilder` that builds
/// binary encoded genomes of length specified by the given `genome_length`.
pub fn new(genome_length: usize) -> Se... | Rust | 0 |
_eq!(part1("37", 513401), "5371393113");
}
#[test]
fn test_part2_ex0() {
use part2;
assert_eq!(part2("37", "51589"), 9);
}
#[test]
fn test_part2_ex1() {
use part2;
assert_eq!(part2("37", "01245"), 5);
}
#[test]
fn test_part2_ex2() {
use part... | Rust | 0 |
communication in PEM format.
"""
OTEL_METRICS_EXEMPLAR_FILTER = "OTEL_METRICS_EXEMPLAR_FILTER"
"""
.. envvar:: OTEL_METRICS_EXEMPLAR_FILTER
The :envvar:`OTEL_METRICS_EXEMPLAR_FILTER` is the filter for which measurements can become Exemplars.
"""
OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION = (
"OTEL... | Python | 1 |
import hashlib
import os
import random
import base64
def generate_random_secret(min_value=1, max_value=100):
"""Generate a random secret value within a specified range."""
return random.randint(min_value, max_value)
def hash_value(value):
"""Hash a given value using SHA-256."""
return hashlib.sha256(v... | Python | 1 |
import abc
from Decision import*
not_monument = 'cow'
class IMMDCM(Decision):
"""
Decision class for IMM decision making nodes.
"""
def logic_method(self, response_data, service_graph, dcm_node):
"""
Decision logic for IMMDCM. Decides whether the response from IMM
is a monumen... | Python | 1 |
<String>>) -> Employee {
Employee {
name: name,
id: id,
company: company,
city: city
}
}
}
mod test {
use super::Employee;
use std::rc::Rc;
#[test]
fn reference_count_test () {
let name1 = Rc::new("Venkat".to_string());
... | Rust | 0 |
not_cfgs.push(attr);
}
}
(cfgs, not_cfgs)
}
/// checks that a function signature
///
/// - has no bounds (like where clauses)
/// - is not `async`
/// - is not `const`
/// - is not `unsafe`
/// - is not generic (has no type parametrs)
/// - is not variadic
/// - uses the Rust ABI (and not e.g. "C")
fn... | Rust | 0 |
xa7u\xdc\xfbQ\xa8\x17\
t\x84\x1f\xee\xa9\xe3\x1e\xf0qY\x9cs]\xc0\x11U\
\x98\xee\x12\x03\xf5D\xec\x83\xf0]1#4\xac^F\
.\xdc\xec\xc4\xb1\xfc\xf5\xf9\x94\xf4\xf5\x15s,\x14\xd0\
I4\xacvG\x12\x17s\xd4\x14\x1cX\xf7\x1f\xce7\
~\x03\xd4SGn\x80\xfdz\x93\xe1\xfa\xa3\x5ce\xfd\
\xc5\xb2\xb5\xaf\x81-x\x92\xe78\xfe\xfb\xc1\x8b\xd5\x1... | Python | 1 |
();
if let Some(&msg) = error.downcast_ref::<&str>() {
assert_eq!(msg, "Hello, world!");
} else {
panic!("did not receive a string from panic handler");
}
}
}
<filename>src/cmu/ctrl.rs
#[doc = "Register `CTRL` reader"]
pub struct R(crate::R<CTRL_SPEC>);
impl core::ops... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os.path
import sys
import h5py
import numpy as np
import glog as log
def load(dpath):
"""
Loads data from directory.
Arguments:
dpath -- directory
Returns:
train_set_x_orig -- train set features
train_set_y... | Python | 1 |
del_path=onnx_model_path, engine_path=engine_path, MaxBatchSize=MaxBatchSize, BuildFlag='FP16')
elif model_name == 'roformer':
onnx_model_path = "general_perf/model_zoo/popular/open_roformer/roformer-frozen_end.onnx"
engine_path = "general_perf/model_zoo/popular/open_roforme... | Python | 1 |
() {
println!("Enter a word to convert in pig latin!");
let mut original_word = String::new();
io::stdin()
.read_line(&mut original_word)
.expect("Failed to read line");
let original_word: String = original_word.trim().parse().expect("Enter a word");
let pig_latin_version = conver... | Rust | 0 |
alue = resp
objects = S3Client().objects('test-pybossa')
assert objects == ['16535035993_1080p.mp4', 'BFI-demo.mp4'], objects
@patch('pybossa.s3_client.requests')
def test_objects_not_returns_folders_inside_bucket(self, requests):
resp = self.make_response(self.bucket_with_folder, 200... | Python | 1 |
ed).
size : int, optional
if set, generated lists will be of exactly this size (and
ignore the min_size/max_size params).
min_size : int, optional
set the minimum size of the generated lists (default: 0 if unset).
max_size : int, optional
set the maximum size of the generated... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import models
def _pos_restaurant_appointment_after_init(env):
table_ids = env['restaurant.table'].search([('appointment_resource_id', '=', False)])
for table_id in table_ids:
table_id.appointment... | Python | 1 |
Line Parameters*\n\n- When run without command-line parameters, Hive executes its default functionality as listed in Exhibit 2. Some of the functions include deleting itself, stopping default services shown in Exhibit 1, skipping files more than five years old, and deleting shadow copies.\n \n\n \n *Exhibit 2: Defaul... | Python | 1 |
xtension}"))
app.run(sys.argv)
# Clean up the socket file
if app.SOCKET_FILE.exists():
app.SOCKET_FILE.unlink()
else:
# If an instance is running, send the error message to the running instance
... | Python | 1 |
.get(b"all_pairs").unwrap()).unwrap();
let pair = Pair {
pair_label: pair_label.clone(),
token_0: token_0.clone(),
token_0_code_hash: token_0_code_hash.clone(),
token_1: token_1.clone(),
token_1_code_hash: token_1_code_hash.clon... | Rust | 0 |
for r in 0..len {
for c in 0..len {
if grid[r][c] > 0 {
ans += 2;
for k in 0..4 {
let nr = (r as i32 + dr[k]) as usize;
let nc = (c as i32 + dc[k]) as usize;
let mut nv = 0;
if nr < len... | Rust | 0 |
xplicit_hash_key"
.build(),
);
}
// Put records.
let mut index = 0;
let mut put_record_count = 0;
while put_record_count < records_per_second {
match kinesis_client
.put_records()
.set_records(Some(
records[index..cmp::min(inde... | Rust | 0 |
LexicalError::UnexpectedCharacter { .. } => 5,
};
id.hash(state);
}
}
impl ToDiagnostic for LexicalError {
fn to_diagnostic(&self) -> Diagnostic {
let span = self.span();
let msg = self.to_string();
match self {
LexicalError::InvalidFloat { .. } => Dia... | Rust | 0 |
1.320387891386150e+00,
-1.259108347373447e+00,
-1.210405308393228e+00,
-1.168622437549020e+00,
-1.131100128177010e+00,
-1.096330116601892e+00,
-1.063336775783950e+00,
-1.031415336713768e+00,
-1.000000000000000e+00,
... | Rust | 0 |
optimizer.zero_grad()
scheduler_obj.step()
training_steps += 1
global_step += 1
# TODO: skip eval for now
if checkpoint_path is not None and global_step % checkpoint_save_steps == 0:
full_ck_path = Path(checkpoint_path) / f"step_{glo... | Python | 1 |
([IPv4Network("10.1.55.1/32")], nodecons)
def test_055_range_proper_superset4(self):
"""Nodecon query with context range proper superset match (equal high)"""
q = NodeconQuery(self.p, range_="s5 - s5:c1.c3", range_superset=True, range_proper=True)
nodecons = sorted(n.network for n in q.res... | Python | 1 |
in prior is unrecoverable, so propigate it.
}
// Now write the buf
debug!("to write buf (blocking, len: {})", buf.remaining());
if let Err(e) = self.body.write_all(&buf) {
if e.kind() == io::ErrorKind::Interrupted {
warn!("AsyncBodySink: write interrupted");
... | Rust | 0 |
rr[0, 1] = False
expr = And(
Symbol("a"),
Constant(arr),
Symbol("b"),
Constant(np.ones((1, 3), dtype=bool)),
)
new_expr = transformer.visit(expr)
assert new_expr is not expr
assert isinstance(new_expr, And)
assert len(new_expr.expressions) == 3
assert Symbol("... | Python | 1 |
::Runtime;
// SKip order testings otherwise we will be marked as spammer
#[test]
#[ignore]
fn create_order_market() -> Result<()> {
::dotenv::dotenv().ok();
let mut rt = Runtime::new()?;
let bm = BitMEX::with_credential(&var("BITMEX_KEY")?, &var("BITMEX_SECRET")?);
let resp = rt.block_on(bm.post_order... | Rust | 0 |
usize,
/// True if we play first, false if we play second
pub on_the_play: bool,
/// The maximum number of cards we are willing to mulligan down to
pub mulligan_down_to: usize,
/// We mulligan any hand that contains a land count found in mulligan_on_lands
pub mulligan_on_lands: HashSet<usize>,
... | Rust | 0 |
ce.condensed_node_type_to_root_node_indices_map.values()
)[0]
),
2,
)
inferer = inference_blueprint.get_inferer()
tagged_outputs = [
tagged_output for tagged_output in inferer(batch_for_inference)
]
self.assertEqual(len(tagged_o... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from .base import TelegramObject
class ShippingAddress(TelegramObject):
"""
This object represents a shipping address.
Source: https://core.telegram.org/bots/api#shippingaddress
"""
country_code: str
"""Two-letter `IS... | Python | 1 |
descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;
descriptor.get(|| {
let fields = ::std::vec::Vec::new();
::protobuf::reflect::MessageDescriptor::new_pb_name::<UnknownMessage1>(
"UnknownMessage1",
... | Rust | 0 |
def Exp(r):
"""so(3) vector to SO(3) matrix
:param r: (3, ) axis-angle, torch tensor
:return: (3, 3)
"""
skew_r = vec2skew(r)
norm_r = r.norm() + 1e-15
eye = torch.eye(3, dtype=torch.float32, device=r.device)
R = eye + torch.sin(norm_r) / norm_r * skew_r + (1 - torch.cos(norm_r)
... | Python | 1 |
ptr/index.html#safety).
/// [`ReadOnlyAppSlice`] must ensure that all Rust slices with a
/// length of `0` must be constructed over a valid (but not
/// necessarily allocated) base pointer.
///
/// If the length is not `0`, the memory region of `[ptr; ptr +
/// len)` must be valid memory of the ... | Rust | 0 |
0.f; // V1.t
v[1].color = color; // V2.ABGR
v[1].position.x = topRight; // V2.X
v[1].position.y = topY; // V2.Y
v[1].texture0.x = 1.f; // V2.s
v[1].texture0... | Rust | 0 |
let args: Vec<String> = linter
.args
.iter()
.map(|arg| file_re.replace(&arg, NoExpand(file.to_str().unwrap())).to_string())
.collect();
// Get the args split by whitespace
let cmd_output = Command::new(&linter.cmd)
.args(args)
.output()?;
// Figure whe... | Rust | 0 |
mport_module("multiviewae")
tests = {
"./user_config/kld_weighting.yaml" : [[10, 10], [MODEL_MEMVAE]],
"./user_config/ll_weighting.yaml" : [[10, 10], [MODEL_MEMVAE, MODEL_MMJSD, MODEL_MOPOEVAE, MODEL_MVAE]],
"./user_config/prior_params.yaml" : [[10, 10], [MODEL_MEMVAE, MODEL_M... | Python | 1 |
(Sercom2, Pad3, IoSet3),
}
PA12 {
C: (Sercom2, Pad0, IoSet1),
D: (Sercom4, Pad1, IoSet3),
}
PA13 {
C: (Sercom2, Pad1, IoSet1),
D: (Sercom4, Pad0, IoSet3),
}
PA14 {
C: (Sercom2, Pad2, IoSet1),
D: (Sercom4, Pad2, IoSet3),
}
PA15 {
C:... | Rust | 0 |
from __future__ import unicode_literals
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.templatetags.static import static
from django.utils.translation import ugettext_lazy as _
from cmsplugin_filer_video import settings
from cmsplugin_filer_video.models import FilerVideo
... | Python | 1 |
import os
import infra.basetest
class TestIpRoute2(infra.basetest.BRTest):
config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \
"""
BR2_PACKAGE_IPROUTE2=y
BR2_TARGET_ROOTFS_CPIO=y
# BR2_TARGET_ROOTFS_TAR is not set
"""
def test_run(self):
cpio_file = os.path.joi... | Python | 1 |
}
}
// fn b(x:int) -> int { fail; }
let z = b(42);
assert(z.i == 42);
assert(z.do_stuff() == 37);
}<reponame>aschaeffer/rust-ecs-poc<gh_stars>0
use crate::api::{PropertyInstanceGetter, PropertyInstanceSetter};
use crate::behaviour::{AndGate, EntityBehaviour, DefaultConnector, ConnectorBehaviour};
use c... | Rust | 0 |
;"),
Token::Dot => write!(f, "."),
Token::Comma => write!(f, ","),
Token::LParen => write!(f, "("),
Token::RParen => write!(f, ")"),
Token::LBrace => write!(f, "{{"),
Token::RBrace => write!(f, "}}"),
// double Operators
T... | Rust | 0 |
nseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}... | Rust | 0 |
}
fn set_value(&mut self, address: u16, value: u8) {
self.timer_restart_requested = true;
MemoryMappedHardware::set_value(&mut self.value, address, value)
}
}
#[derive(Default, Serialize, Deserialize)]
struct GameBoyTimer {
counter: GameBoyRegister,
modulo: GameBoyRegister,
control... | Rust | 0 |
from typing import Sequence, Tuple
from classic.domain.core.criteria import Criteria, Xor, And, Or, Invert
from classic.domain.core import Repo, Root, translate_for
from sqlalchemy import select, Select, and_, or_, not_, delete, ColumnElement
from sqlalchemy.orm import Session
class SQLAlchemyRepo(Repo[Root]):
... | Python | 1 |
o,rǎo"),
('繟', "chǎn,chán"),
('繠', "ruǐ"),
('繡', "xiù"),
('繢', "huì,huí"),
('繣', "huà"),
('繤', "zuǎn"),
('繥', "xī"),
('繦', "qiǎng"),
('繧', "yun"),
('繨', "da"),
('繩', "shéng,yìng,mǐn,shèng"),
('繪', "huì,guì"),
('繫', "xì,jì"),
('繬', "sè"),
('繭', "jiǎn"),
('繮... | Rust | 0 |
_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
processed = feat_extract(speech_inputs, padding="longest")
input_values = processed.input_values
def _check_zero_mean_unit_variance(input_vec... | Python | 1 |
# Desenvolver um boot para automatizar mensagens no WhatssApp Web
import openpyxl
from urllib.parse import quote
import webbrowser
from time import sleep
import pyautogui
webbrowser.open('https://web.whatsapp.com/')
sleep(5)
workbook = openpyxl.load_workbook('contatos.xlsx')
pagina_contatos = workbook['Planilha1']
... | Python | 1 |
w();
for track in tracks.iter() {
let track_data = track.1.as_dictionary().expect("Malformed track data");
let artist = match track_data.get("Artist") {
Some(a) => a.as_string().expect("Malformed artist").to_string(),
None => String::new(),
};
let album = mat... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import torch
import torch.nn as nn
def get_acti_func(acti_func, params):
acti_func = acti_func.lower()
if(acti_func == 'relu'):
inplace = params.get('relu_inplace', False)
return nn.ReLU(inplace)
elif(acti_func == 'l... | Python | 1 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)[:, 1]
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
roc_auc = r... | Python | 1 |
# SPDX-FileCopyrightText: Copyright (c) 2022-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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
#... | Python | 1 |
from netmiko.broadcom.broadcom_icos_ssh import BroadcomIcosSSH
__all__ = ["BroadcomIcosSSH"]
| Python | 1 |
4) -> Result<Self>;
}
/// Indicates that the Index Entry type has additional data (of [`NtfsIndexEntryData`] datatype).
///
/// This trait and [`NtfsIndexEntryHasFileReference`] are mutually exclusive.
// TODO: Use negative trait bounds of future Rust to enforce mutual exclusion.
pub trait NtfsIndexEntryHasData: NtfsI... | Rust | 0 |
variant: CH4OCV_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The software output control forces 0 to the channel output."]
#[inline(always)]
pub fn _0(self) -> &'a mut W {
self.variant(CH4OCV_A::_0)
}
#[doc = "The software output control forces 1... | Rust | 0 |
turn false;
}
}
true
}
impl Bot {
fn new() -> Result<Bot> {
let resp = send_join_request()?;
Ok(Bot {
stage: resp.current_game_state,
static_info: resp.stage_data,
state: Default::default(),
cmd_queue: VecDeque::new(),
})
}... | Rust | 0 |
(FreeRV(t1), ObservedRV(t2)) => FreeRV(t1 * t2),
(ObservedRV(t1), FreeRV(t2)) => FreeRV(t1 * t2),
(ObservedRV(t1), ObservedRV(t2)) => FreeRV(t1 * t2),
}
}
}
<gh_stars>0
use crate::array::{Array, DictionaryArray, DictionaryKey};
pub(super) fn equal<K: DictionaryKey>(lhs: &Diction... | Rust | 0 |
self.position_in_mem = addr as usize;
}
fn ret(&mut self) {
if self.stack_pointer == 0 {
panic!("Stack underflow");
}
self.stack_pointer -= 1;
let addr = self.stack[self.stack_pointer];
self.position_in_mem = addr as usize;
}
fn add_xy(&mut self, x:... | Rust | 0 |
fn dmamuxper12(&self) -> DMAMUXPER12R {
DMAMUXPER12R::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 26:27 - Select DMA to peripheral connection for DMA peripheral 13."]
#[inline]
pub ... | Rust | 0 |
(_) => false,
Self::Semver(v) => v == other,
}
}
}
<reponame>hasenbanck/rs-nwa<filename>src/main.rs<gh_stars>1-10
extern crate byteorder;
#[macro_use]
extern crate failure;
extern crate nwa;
extern crate rayon;
extern crate structopt;
use byteorder::{LittleEndian, ReadBytesExt};
use nwa::NWAFil... | Rust | 0 |
<Vec<_>, Err>>()?,
),
crate::Align::End => crate::features::Column::align_right(
inners
.into_iter()
.map(|i| i.into_feature(ctx))
.collect::<Result<Vec<_>, Err>>()?,
... | Rust | 0 |
cert_issuance.certs.get(id);
if let Some((issuer_id, issuer_private_key)) = issuer {
// Issuer is explicitly specified, so load it and use it to sign the CSR.
let x509_req = openssl::x509::X509Req::from_pem(csr).map_err(|err| Error::invalid_parameter("csr", err))?;
let x509_req_public_key = x509_req.public... | Rust | 0 |
import argparse
import json
import logging
import os.path
import numpy as np
from constants.enums import AlgorithmsEnum, DatasetsEnum
from experiment_helper import run_test
from utilities.utils import fetch_bests_in_sweep, print_latex_line
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='... | Python | 1 |
ctionary_bytes)?;
Ok(dictionary_bytes)
}
impl<'a> Tokenize for Tokenizer<'a> {
fn tokenize(
&self,
input: &str,
mode: Mode,
enable_debug: bool,
) -> SudachiResult<Vec<Morpheme>> {
let input_bytes = input.as_bytes();
// build_lattice
let mut lattice ... | Rust | 0 |
heme_path.exists() {
let mut s = Config::new();
s.merge(File::from(theme_path.clone()))?;
s.try_into()
.map_err(|err| anyhow!("{} : {}", "Config format error", err))
} else {
Err(anyhow!(
"Unable to find theme settings file {}",
... | Rust | 0 |
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
if sys.version_info < (3, 4):
error = """
Transplant does not support Python < 3.4.
This may be due to an out of date pip.
Make sure you have pip >= 9.0.1.
"""
sys.exit(error)
setup(
name='Transplant',
version='0.8.11',
... | Python | 1 |
if location and chat_id:
lat = location.get("latitude")
lon = location.get("longitude")
if lat and lon:
user_origin_map[chat_id] = f"{lat},{lon}"
keyboard = {
"type": "reply",
... | Python | 1 |
import time
import pytest
from mock import Mock, patch
@pytest.fixture
def refresher():
from vcli.completion_refresher import CompletionRefresher
return CompletionRefresher()
def test_ctor(refresher):
"""
Refresher object should contain a few handlers
:param refresher:
:return:
"""
a... | Python | 1 |
utex<bool>>,
}
fn request<R>(
callback: Callback<Result<User, anyhow::Error>>,
pending: Arc<Mutex<bool>>,
r: http::request::Request<R>,
) -> Result<FetchTask, anyhow::Error>
where
R: std::convert::Into<std::result::Result<std::string::String, anyhow::Error>>,
{
let handler = move |response: Respons... | Rust | 0 |
rse_hex_direction(s: &str) -> Result<HexDirection, ParseHexDirectionError> {
match s {
"NW" | "nw" => Ok(HexDirection::NW),
"N" | "n" => Ok(HexDirection::N),
"NE" | "ne" => Ok(HexDirection::NE),
"SW" | "sw" => Ok(HexDirection::SW),
"S" | "s" => Ok(HexDirection::S),
"S... | Rust | 0 |
proc_spec.save(update_fields=["target_replicas", "target_status", "updated"])
def set_stop(self):
"""Set the process to "stop" state."""
proc_spec = self.spec_object
proc_spec.target_status = ProcessTargetStatus.STOP.value
# 确保停止进程 / 下架时候的副本数不会超过套餐允许的最大副本数
proc_spec.tar... | Python | 1 |
// `VDPPD xmm1, xmm2, xmm3/m128, imm8`
///
/// `VEX.128.66.0F3A.WIG 41 /r ib`
///
/// `AVX`
///
/// `16/32/64-bit`
VEX_Vdppd_xmm_xmm_xmmm128_imm8 = 3899,
/// `MPSADBW xmm1, xmm2/m128, imm8`
///
/// `66 0F 3A 42 /r ib`
///
/// `SSE4.1`
///
/// `16/32/64-bit`
Mpsadbw_xmm_xmmm128_imm8 = 3900,
/// `VMPSADBW... | Rust | 0 |
from fastapi import APIRouter, Request
from ..config import settings
from ..templates import TemplateResponse
router = APIRouter()
@router.get("/taskpane")
async def taskpane(request: Request):
return TemplateResponse(
request=request,
name="/examples/hello_world/taskpane_hello.html",
co... | Python | 1 |
urn Some(self.score(seen, *last));
}
}
None
}
fn score(&self, seen: HashSet<Num>, last: Num) -> Score {
let sum = self
.flatten()
.into_iter()
.filter(|n| !seen.contains(n))
.map(|n| n as Score)
.sum::<Score>();
... | Rust | 0 |
alt_parents.append(alt_p['name'])
ent_dict['classyfire_alternative_parents'] = str(alt_parents)
ent_dict['classyfire_substituents'] = str(ent['substituents'])
ent_df = pd.DataFrame(ent_dict, index=[result['entities'].index(ent) + (query_count ... | Python | 1 |
ray]:
"""Compute bursting frequency and size for the negative binomial regression model. The equations come from:
Anton J.M. Larsson et al. Genomic encoding of transcriptional burst kinetics, Nature volume 565, pages251–254(2019)
Args:
M_t: The first moment of the number of total mRNA. If an ar... | Python | 1 |
' be added: [' + ', '.join(not_applicable_permissions) + '] \n')
api_diabled_permissions = permissions_helper.GetApiDisabledPermissons()
iam_util.ApiDisabledPermissionsWarning(api_diabled_permissions)
testing_permissions = permissions_helper.GetTestingPermissions()
iam_util.TestingPermissionsWarning(t... | Python | 1 |
t may get errors.
skip_fusion_patterns=False,
no_constant_folding=False,
save_as_external_data=False,
verbose=False,
dtype='fp16' if quant_to_fp16 else 'fp32'
)
# transformers.optimizer
model = optimize_model(output_onnx_model,
use_gpu=False,
opt_level... | Python | 1 |
assert!(get_standard_string(NUMBER_OF_STANDARD_STRINGS as StringID - 1).is_some());
assert!(get_standard_string(NUMBER_OF_STANDARD_STRINGS as StringID).is_none());
}
}
use std::io;
fn main() {
let mut board = [' '; 9];
let mut turn = true;
for row in 1..4 {
println!("\n | |"... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.